persona: an identity diff is written to her trace before the put, posted under a stable request id after it, and owed posts are retried next wake

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-01 00:01:32 +01:00
commit 4ef517b881
2 changed files with 170 additions and 26 deletions

View file

@ -26,6 +26,7 @@
//! her rooms (`render_tail`) and the turn records' store (`FileTrace`). Items no start calls yet carry an
//! `allow(dead_code)` that the first caller removes.
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::PathBuf;
@ -323,6 +324,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
Ok(records) => records,
Err(fault) => return failed("her trace was not read", fault),
};
owed_identity(start, instance, &state, &trace);
let mut deliveries: Vec<&ChatDelivery> = pending.deliveries.iter().collect();
deliveries.sort_by_key(|delivery| delivery.seq);
// Her rooms and her addressee, as the heartbeat reads them: the rooms named for the repos she stewards, and the heartbeat's table
@ -528,16 +530,43 @@ fn interpreted<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, waked:
let request = format!("{stem}-i{began_ms}");
let receipt = match interpret(start.model.as_ref(), &model, &request, state, &heard, narration, prose) {
Err(failed) => json!({ "kind": "interpreter", "status": "error", "put": "none", "error": failed.reason, "usage": failed.usage, "put_refused": true }),
Ok((deltas, usage)) => match put_applied(&*start.persona, state, &Taken { deltas: &deltas, heard: &heard, instance }, stem, now, &*start.clock) {
Ok(landed) => {
if let Some(say) = identity_post(start, instance, &landed.applied, stem)
&& let Err(fault) = start.trace.record(&format!("{stem}-s"), &row(2, say))
{
eprintln!("mind-persona: the record of the identity post was not appended: {fault:#}");
Ok((deltas, usage)) => {
// The diff is written to her trace before each put, so a change is never put that nothing recorded to show: the record
// the last attempt wrote, or void when a later attempt had no identity change.
let diff_key = format!("{stem}-d");
let written: RefCell<Option<Value>> = RefCell::new(None);
let ahead = |applied: &Applied| -> std::result::Result<(), String> {
let record = identity_record(config, instance, applied, &diff_key).map(|record| row(2, record));
let record = match (record, written.borrow().clone()) {
(Some(record), _) => record,
(None, Some(mut earlier)) => {
earlier["status"] = json!("void");
earlier
}
(None, None) => return Ok(()),
};
start.trace.record(&diff_key, &record).map_err(|fault| format!("the identity change was not recorded first, so nothing was put: {fault:#}"))?;
*written.borrow_mut() = Some(record);
Ok(())
};
match put_applied(&*start.persona, state, &Taken { deltas: &deltas, heard: &heard, instance }, stem, now, &*start.clock, &ahead) {
Ok(landed) => {
if let Some(record) = written.borrow().clone().filter(|record| record["status"] == "pending") {
post_identity(start, instance, record);
}
json!({ "kind": "interpreter", "status": "ok", "put": landed.put, "applied": landed.applied.changes, "refused": landed.applied.refused, "pruned": landed.applied.pruned, "usage": usage })
}
Err(missed) => {
if let Some(mut record) = written.borrow().clone().filter(|record| record["status"] == "pending") {
record["status"] = json!("void");
if let Err(fault) = start.trace.record(&diff_key, &record) {
eprintln!("mind-persona: the identity record {diff_key} was not voided: {fault:#}");
}
}
json!({ "kind": "interpreter", "status": "error", "put": "refused", "error": missed.why, "applied": missed.applied.changes, "refused": missed.applied.refused, "usage": usage, "put_refused": true })
}
json!({ "kind": "interpreter", "status": "ok", "put": landed.put, "applied": landed.applied.changes, "refused": landed.applied.refused, "pruned": landed.applied.pruned, "usage": usage })
}
Err(missed) => json!({ "kind": "interpreter", "status": "error", "put": "refused", "error": missed.why, "applied": missed.applied.changes, "refused": missed.applied.refused, "usage": usage, "put_refused": true }),
}
},
};
if let Err(fault) = start.trace.record(&format!("{stem}-i"), &row(1, receipt)) {
@ -545,16 +574,70 @@ fn interpreted<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, waked:
}
}
/// The identity changes a landed put made, posted to the review room as one code-written line with each field's value before and
/// after (`identity-write-all-visible`), and the `say` row that records the post. None when nothing changed or no room is named.
fn identity_post<C: Chat>(start: &Start<C>, instance: &Slug, applied: &Applied, stem: &str) -> Option<Value> {
let room = start.config.review_room.as_deref().filter(|_| !applied.identity.is_empty())?;
/// The identity changes a put is about to make, written to her trace before the put (`identity-write-all-visible`): the code-written
/// line for the review room with each field's value before and after, and a request id derived from the diff, so the same change posts
/// under the same id wherever it is retried and a repeat inside the mouth's dedupe window is deduped. None when nothing changes or no
/// room is named. The record's `status` is `pending` until the put's outcome is known: `landed` once it landed and the post is owed,
/// `posted` once the mouth took it, `void` when the put did not land.
fn identity_record(config: &Config, instance: &Slug, applied: &Applied, key: &str) -> Option<Value> {
let room = config.review_room.as_deref().filter(|_| !applied.identity.is_empty())?;
let text = format!("{}'s identity changed.\n{}", instance.0, applied.identity.iter().map(|diff| format!("{}: {} -> {}", diff.field, diff.before, diff.after)).collect::<Vec<_>>().join("\n"));
let request = ChatSendRequest { request_id: format!("{stem}-id"), persona: instance.0.clone(), room_alias: room.to_owned(), text: text.clone(), basis: None, resend: false };
Some(match start.chat.send(&request) {
Ok(receipt) => json!({ "kind": "say", "say": { "room": room, "text": text, "event": receipt.event_id, "refusal": receipt.refusal.map(|refusal| format!("{refusal:?}")) } }),
Err(fault) => json!({ "kind": "say", "say": { "room": room, "text": text, "event": null, "refusal": format!("{fault:#}") } }),
})
let mut digest = sha2::Sha256::new();
sha2::Digest::update(&mut digest, instance.0.as_bytes());
for diff in &applied.identity {
sha2::Digest::update(&mut digest, format!("\0{}\0{}", diff.field, diff.after).as_bytes());
}
let id: String = sha2::Digest::finalize(digest).iter().take(8).map(|byte| format!("{byte:02x}")).collect();
Some(json!({ "kind": "identity_diff", "key": key, "status": "pending", "request_id": format!("identity-{id}"), "room": room, "text": text, "diffs": applied.identity, "event": null }))
}
/// Whether her state holds the change a diff made.
fn holds(state: &Value, diff: &Value) -> bool {
let (field, after) = (diff["field"].as_str().unwrap_or_default(), &diff["after"]);
match field {
"presentation" => after.as_object().is_some_and(|parts| parts.iter().all(|(part, value)| state["presentation"][part] == *value)),
"values" => state["values"].as_array().is_some_and(|values| values.contains(after)),
_ => state[field] == *after,
}
}
/// An identity record whose put landed, posted through the mouth under its own request id and marked `posted`. A post the mouth
/// refuses or cannot take leaves it `landed`, and the next wake posts it again under the same id (`owed_identity`).
fn post_identity<C: Chat>(start: &Start<C>, instance: &Slug, mut record: Value) {
let key = record["key"].as_str().unwrap_or_default().to_owned();
let mut mark = |record: &mut Value, status: &str| {
record["status"] = json!(status);
if let Err(fault) = start.trace.record(&key, &*record) {
eprintln!("mind-persona: the identity record {key} was not updated to {status}: {fault:#}");
}
};
mark(&mut record, "landed");
let request = ChatSendRequest { request_id: record["request_id"].as_str().unwrap_or_default().to_owned(), persona: instance.0.clone(), room_alias: record["room"].as_str().unwrap_or_default().to_owned(), text: record["text"].as_str().unwrap_or_default().to_owned(), basis: None, resend: false };
match start.chat.send(&request) {
Ok(receipt) if receipt.refusal.is_none() => {
record["event"] = json!(receipt.event_id);
mark(&mut record, "posted");
}
Ok(receipt) => eprintln!("mind-persona: the identity post {} was refused: {:?}", request.request_id, receipt.refusal),
Err(fault) => eprintln!("mind-persona: the identity post {} was not sent: {fault:#}", request.request_id),
}
}
/// What an earlier wake left owed: an identity record that landed and was never posted is posted now; one still `pending` is
/// `landed` when her state holds its change, and `void` when it does not.
fn owed_identity<C: Chat>(start: &Start<C>, instance: &Slug, state: &Value, records: &[Value]) {
for record in records.iter().filter(|record| record["kind"] == "identity_diff" && matches!(record["status"].as_str(), Some("pending" | "landed"))) {
let landed = record["status"] == "landed" || record["diffs"].as_array().is_some_and(|diffs| !diffs.is_empty() && diffs.iter().all(|diff| holds(state, diff)));
if landed {
post_identity(start, instance, record.clone());
} else {
let mut void = record.clone();
void["status"] = json!("void");
if let Err(fault) = start.trace.record(record["key"].as_str().unwrap_or_default(), &void) {
eprintln!("mind-persona: an identity record was not voided: {fault:#}");
}
}
}
}
/// Her put through the persona door, the one writer of her state a start has.
@ -609,7 +692,7 @@ pub(crate) struct Missed {
/// from). Each attempt applies, stamps (P5), validates the whole document against the schema and only then puts: a state the
/// schema refuses is never put. A stale put reads her again and applies the same deltas to the state as it stands, so what Self
/// or Life put in between survives, and puts once more.
fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime<Utc>, clock: &dyn Fn() -> DateTime<Utc>) -> std::result::Result<Landed, Missed> {
fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime<Utc>, clock: &dyn Fn() -> DateTime<Utc>, ahead: &dyn Fn(&Applied) -> std::result::Result<(), String>) -> std::result::Result<Landed, Missed> {
let attempt = |from: &Value| -> (std::result::Result<Value, String>, Applied) {
let (mut next, applied) = apply_commit(from, turn.deltas, turn.heard, key, now);
next["updatedAt"] = json!(stamp_after(clock(), from.get("updatedAt").and_then(Value::as_str)));
@ -620,6 +703,7 @@ fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str,
};
let (next, applied) = attempt(read);
let next = next.map_err(|why| Missed { applied: applied.clone(), why })?;
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why })?;
match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) {
Ok(Put::Committed) => return Ok(Landed { applied, put: "committed" }),
Ok(Put::Stale) => {}
@ -629,6 +713,7 @@ fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str,
let (fresh, _) = store.persona().map_err(|fault| Missed { applied: applied.clone(), why: format!("her state was not read again: {fault:#}") })?;
let (next, applied) = attempt(&fresh);
let next = next.map_err(|why| Missed { applied: applied.clone(), why })?;
ahead(&applied).map_err(|why| Missed { applied: applied.clone(), why })?;
match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) {
Ok(Put::Committed) => Ok(Landed { applied, put: "stale_reapplied" }),
Ok(Put::Stale) => Err(Missed { applied, why: "stale again".to_owned() }),

View file

@ -57,6 +57,8 @@ struct FakeMouth {
sent: RefCell<Vec<ChatSendRequest>>,
acks: RefCell<Vec<u64>>,
ack_fails: Cell<bool>,
/// The mouth cannot take a send.
send_fails: Cell<bool>,
}
impl Chat for Rc<FakeMouth> {
@ -64,6 +66,9 @@ impl Chat for Rc<FakeMouth> {
Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().iter().filter(|delivery| delivery.seq > after).cloned().collect(), tail: Some(vec![]), tail_gaps: vec![] })
}
fn send(&self, request: &ChatSendRequest) -> Result<ChatSendReceipt> {
if self.send_fails.get() {
bail!("the mouth is unreachable");
}
self.sent.borrow_mut().push(request.clone());
Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some("$sent".into()), refusal: None, newer: vec![] })
}
@ -127,11 +132,13 @@ struct MemTrace {
rows: RefCell<Vec<(String, Value)>>,
/// The trace cannot be written (the state directory is full).
fail: Cell<bool>,
/// A record whose key ends so cannot be written.
fail_suffix: RefCell<String>,
}
impl Trace for Rc<MemTrace> {
fn record(&self, key: &str, record: &Value) -> Result<()> {
if self.fail.get() {
if self.fail.get() || (!self.fail_suffix.borrow().is_empty() && key.ends_with(self.fail_suffix.borrow().as_str())) {
bail!("no space left on device");
}
let mut rows = self.rows.borrow_mut();
@ -214,8 +221,8 @@ impl Rig {
let dir = TempDir::new().unwrap();
ControlWriter::open(dir.path().join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
SwarmWriter::open(dir.path().join("swarm.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), ack_fails: Cell::new(false) });
let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false) });
let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), ack_fails: Cell::new(false), send_fails: Cell::new(false) });
let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false), fail_suffix: RefCell::default() });
Self { mouth, trace, store: Rc::new(FakeStore::new(control())), dir, ticks: Rc::default(), review: RefCell::default() }
}
@ -248,7 +255,7 @@ impl Rig {
/// Her wake records alone.
fn records(&self) -> Vec<Value> {
self.all_records().into_iter().filter(|record| !matches!(record["kind"].as_str(), Some("interpreter" | "say"))).collect()
self.all_records().into_iter().filter(|record| !matches!(record["kind"].as_str(), Some("interpreter" | "say" | "identity_diff"))).collect()
}
fn acks(&self) -> Vec<u64> {
@ -533,7 +540,7 @@ fn t_p2_a_failed_call_puts_nothing_and_the_wake_still_decides_its_lines() {
assert_eq!(history(&records).last_outcome.unwrap()["untold"], json!([{ "kind": "not_kept" }]), "her next wake is told her state was not kept");
}
/// T-P2: a publicName change is put, and the drain posts the diff to the review room with its own say row; with no review room none is made.
/// T-P2: a publicName change is put, and the drain posts the diff to the review room, recorded first as an identity_diff row; with no review room none is made.
#[test]
fn t_p2_identity_diff_is_posted_to_the_review_room() {
const RENAME: &str = r#"{"self":{"identity":{"publicName":"Tobiah of the River"}}}"#;
@ -546,14 +553,66 @@ fn t_p2_identity_diff_is_posted_to_the_review_room() {
assert_eq!(sent[0].room_alias, "#review:gamecult.org");
assert!(sent[0].text.contains("publicName") && sent[0].text.contains("Tobiah Fenn") && sent[0].text.contains("Tobiah of the River"), "{}", sent[0].text);
let records = rig.all_records();
let say = rows(&records, "say");
assert_eq!((say.len(), say[0]["say"]["event"].as_str()), (1, Some("$sent")));
let diff = rows(&records, "identity_diff");
assert_eq!((diff.len(), diff[0]["status"].as_str(), diff[0]["event"].as_str(), diff[0]["request_id"].as_str()), (1, Some("posted"), Some("$sent"), Some(sent[0].request_id.as_str())));
// No room named: the change is refused, nothing is put for it and nothing is posted.
let rig = three_rooms();
rig.run(Interprets(RENAME));
assert!(rig.mouth.sent.borrow().is_empty());
assert_eq!(rig.store.puts.borrow()[0]["publicName"], "Tobiah Fenn");
assert_eq!(rows(&rig.all_records(), "interpreter")[0]["refused"][0]["reason"], "no_review_room");
assert!(rows(&rig.all_records(), "identity_diff").is_empty());
}
/// An identity change whose record cannot be written first is never put.
#[test]
fn t_p2_identity_is_never_put_unrecorded() {
const RENAME: &str = r#"{"self":{"identity":{"publicName":"Tobiah of the River"}}}"#;
let rig = three_rooms();
*rig.review.borrow_mut() = Some("#review:gamecult.org".into());
*rig.trace.fail_suffix.borrow_mut() = "-d".into();
rig.run(Interprets(RENAME));
assert!(rig.store.puts.borrow().is_empty(), "no diff on record, no put");
assert!(rig.mouth.sent.borrow().is_empty());
}
/// A put that landed whose post failed is posted by the next wake under the same request id, and once.
#[test]
fn t_p2_identity_post_is_retried_next_wake() {
const RENAME: &str = r#"{"self":{"identity":{"publicName":"Tobiah of the River"}}}"#;
let rig = three_rooms();
*rig.review.borrow_mut() = Some("#review:gamecult.org".into());
rig.mouth.send_fails.set(true);
rig.run(Interprets(RENAME));
assert_eq!(rig.store.puts.borrow()[0]["publicName"], "Tobiah of the River", "the put landed");
assert!(rig.mouth.sent.borrow().is_empty());
let records = rig.all_records();
let (status, id) = (rows(&records, "identity_diff")[0]["status"].clone(), rows(&records, "identity_diff")[0]["request_id"].clone());
assert_eq!(status, "landed");
rig.mouth.send_fails.set(false);
rig.run(Interprets(RENAME));
let sent = rig.mouth.sent.borrow();
assert_eq!((sent.len(), json!(sent[0].request_id)), (1, id), "posted by the next wake under the stable id");
assert_eq!(rows(&rig.all_records(), "identity_diff")[0]["status"], "posted");
drop(sent);
rig.run(Interprets(RENAME));
assert_eq!(rig.mouth.sent.borrow().len(), 1, "a posted record is never posted again");
}
/// A crash between the write-ahead and the put's outcome: the next wake posts what her state holds and voids what it does not.
#[test]
fn t_p2_a_pending_identity_record_is_settled_by_her_state() {
let diff = |after: &str| json!({ "kind": "identity_diff", "key": format!("n0-d-{after}"), "seq": 9, "status": "pending", "request_id": format!("identity-{}", after.len()), "room": "#review:gamecult.org", "text": "changed", "diffs": [{ "field": "publicName", "before": "Tobiah Fenn", "after": after }], "event": null });
let rig = three_rooms();
*rig.review.borrow_mut() = Some("#review:gamecult.org".into());
rig.trace.record("n0-d-a", &diff("Tobiah Fenn")).unwrap();
rig.trace.record("n0-d-b", &diff("Never Put")).unwrap();
rig.run(Tally::default());
let records = rig.all_records();
let status = |key: &str| rig.trace.rows.borrow().iter().find(|(held, _)| held == key).unwrap().1["status"].clone();
assert_eq!((status("n0-d-a"), status("n0-d-b")), (json!("posted"), json!("void")));
assert_eq!(rig.mouth.sent.borrow().len(), 1);
assert!(rows(&records, "identity_diff").len() == 2);
}
/// T-P2: Self's put between her read and her put survives, and her deltas are applied on top of it.
@ -582,7 +641,7 @@ fn t_p2_schema_refusal_no_put() {
let deltas = Default::default();
let slug = Slug("eureka".into());
let taken = Taken { deltas: &deltas, heard: &heard, instance: &slug };
let missed = put_applied(&store, &read, &taken, "w1", at(0), &|| at(1)).err().expect("the schema refuses it");
let missed = put_applied(&store, &read, &taken, "w1", at(0), &|| at(1), &|_| Ok(())).err().expect("the schema refuses it");
assert!(missed.why.contains("schema"), "{}", missed.why);
assert!(store.puts.borrow().is_empty());
}