Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(host-core): preserve transcript durability in PR #1202
vastsa6f56edf6ad3e
diff --cc crates/host-core/src/db/migrations.rsindex f48c2ae3b,357e1221e..db92ea4a3--- a/crates/host-core/src/db/migrations.rs+++ b/crates/host-core/src/db/migrations.rs@@@ -10,13 -10,45 +10,52 @@@ impl Database"CREATE INDEX IF NOT EXISTS idx_turns_ended_at ON turns(ended_at DESC)",[],);+ // Session summaries and session search both ask whether a run owns a+ // session, so the probe wants an index of the sessions that have one.+ let _ = self.conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_task_runs_session ON task_runs(session_id)+ WHERE session_id IS NOT NULL",+ [],+ );+ // Search ranks every result set by `created_at` and cuts it with a+ // LIMIT, so the planner needs that column ordered; this is the same+ // idempotent-addition pattern as `idx_turns_ended_at` above. Both+ // statements only add an index, so no existing row is rewritten and a+ // schema-version bump with a migration backup is unnecessary.+ let _ = self.conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_messages_created ON messages(created_at DESC)",+ [],+ );+ let _ = self.conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_messages_session_created+ ON messages(session_id, created_at DESC, seq DESC, id ASC)",+ [],+ );++ // The write path asks one question about a message over and over: does+ // the last copy of this id still sit in the transcript as a provisional,+ // streaming assistant row? The index row already mirrors that copy — it+ // is inserted with the row and re-stamped whenever the transcript line+ // is replaced — so the answer belongs in a column instead of in a+ // backwards walk over every message line of a session that can hold+ // gigabytes, 64 lines at a time, twice per turn.+ //+ // NULL means "written before this column existed". The read falls back to+ // the transcript there, so an existing database answers exactly as it did+ // before until a row is rewritten by an append. That is what makes the+ // column safe to add without a schema-version bump: it carries no default+ // and carries no index, so no row is rewritten and no migration backup is+ // needed — the same idempotent-addition pattern as the indexes above.+ let has_streaming: bool = self.conn.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('messages') WHERE name = 'streaming')",+ [],+ |row| row.get(0),+ )?;+ if !has_streaming {+ let _ = self+ .conn+ .execute_batch("ALTER TABLE messages ADD COLUMN streaming INTEGER");+ }let tx = self.conn.unchecked_transaction()?;tx.execute("UPDATE turnsdiff --cc crates/host-core/src/rpc/mod.rsindex 5fb41e6f0,5daf0ccee..8d94653aa--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@@ -419,25 -419,19 +419,18 @@@ pub async fn serve(state: Arc<Mutex<Apprequest_tasks.spawn(async move {let _permit = permit;let budget = request_budget_ms(&method, ¶ms);- let out = match with_request_budget(- budget,- handle_request(state, &method, params, tx.clone()),- // The transcript writes this request made are committed to- // the device here: after the handler released the state- // lock, and before the response leaves. That is the same- // acknowledgement the inline flush gave, without holding up- // every other request for the length of a device commit.++ // Deferred checkpoint writes are committed after the++ // handler releases the state lock and before the response++ // leaves. Transcript appends are synced inside their write++ // path before derived SQLite rows are committed.+ let (handled, committed) = transcripts::commit_writes_of(+ with_request_budget(+ budget,+ handle_request(state, &method, params, tx.clone()),+ ),)- .await- {- Ok(result) => JsonRpcResponse {- jsonrpc: "2.0",- id,- result: Some(result),- error: None,- },- Err(err) => JsonRpcResponse {- jsonrpc: "2.0",- id,- result: None,- error: Some(err),- },- };+ .await;+ let out = response_for(id, handled, committed);if let Ok(raw) = serde_json::to_string(&out) {let _ = tx.send(format!("{raw}\n"));}@@@ -582,6 -576,47 +575,45 @@@ fn rpc_err(code: i64, message: impl Int}}+ /// The response for one handled request, given the handler's own outcome and-/// the outcome of committing the transcript writes it made.++/// the outcome of committing deferred checkpoint writes.+ ///-/// A transcript append is acknowledged only once its bytes are on the device-/// (`transcripts::commit_writes_of`), so a device failure has to reach the-/// client as this request's failure — same code, same error shape the append-/// itself produced when the flush was still inline. A handler that failed-/// anyway keeps its own error and the device error goes to the log, because a-/// response carries one error and it must never be success.++/// Transcript append failures reach the client directly from the handler,++/// before the SQLite index update. A deferred checkpoint failure is returned++/// here. If the handler already failed, its error remains the response and the++/// checkpoint failure is logged because a response carries one error.+ fn response_for(+ id: Value,+ handled: Result<Value, JsonRpcError>,+ committed: anyhow::Result<()>,+ ) -> JsonRpcResponse {+ let error = match (handled, committed) {+ (Ok(result), Ok(())) => {+ return JsonRpcResponse {+ jsonrpc: "2.0",+ id,+ result: Some(result),+ error: None,+ }+ }+ (Ok(_), Err(device)) => rpc_err(1000, device.to_string(), "INTERNAL"),+ (Err(error), Ok(())) => error,+ (Err(error), Err(device)) => {+ tracing::error!(+ error = %device,+ "transcript device flush failed behind a request that failed anyway"+ );+ error+ }+ };+ JsonRpcResponse {+ jsonrpc: "2.0",+ id,+ result: None,+ error: Some(error),+ }+ }+fn config_sync_rpc_err(error: impl ToString) -> JsonRpcError {let message = error.to_string();let error_code = messagediff --cc crates/host-core/src/rpc/scheduled_rpc.rsindex 57fd4fb42,ce248bc61..7e043f47a--- a/crates/host-core/src/rpc/scheduled_rpc.rs+++ b/crates/host-core/src/rpc/scheduled_rpc.rs@@@ -326,157 -288,6 +326,157 @@@ fn validate_execution_input(params: &Vamod tests {use super::*;+ /// A run's transcript reports its automation ownership, the reader the+ /// Scheduled page uses sees the same flag, search carries it through the+ /// query that builds its own column list, and deleting the task releases the+ /// transcript back into the ordinary lists (issue #1291).+ #[tokio::test]+ async fn automation_sessions_are_marked_and_released_with_their_task() {+ let dir = tempfile::tempdir().unwrap();+ let mut st = AppState::open(dir.path()).unwrap();+ st.handshook = true;+ let id = handle(+ &st,+ "scheduled.create",+ json!({"title":"Nightly","prompt":"Summarize the dependencies",+ "cadence":"manual","schedule":null}),+ )+ .unwrap()["task"]["id"]+ .as_str()+ .unwrap()+ .to_string();+ let run = handle(&st, "scheduled.run", json!({"id":id})).unwrap();+ let run_session = run["sessionId"].as_str().unwrap().to_string();+ let ordinary = sessions::create_session(+ &st.db,+ Some("Hand written".into()),+ Some("agent".into()),+ None,+ None,+ None,+ )+ .unwrap();++ let flag = |session_id: &str| {+ sessions::list_sessions(&st.db)+ .unwrap()+ .into_iter()+ .find(|session| session.id == session_id)+ .map(|session| session.scheduled_run)+ };+ assert_eq!(+ flag(&run_session),+ Some(true),+ "a run's transcript is marked as automation output"+ );+ assert_eq!(+ flag(&ordinary.id),+ Some(false),+ "an ordinary conversation is never marked"+ );+ let detail = sessions::get_session(&st.db, &run_session)+ .unwrap()+ .expect("the run's session exists");+ assert!(detail.summary.scheduled_run);+- let page = crate::session_search::search(&st.db, "Nightly", 0).unwrap();++ let page = crate::session_search::search(&st.db, "Nightly", 0, 30).unwrap();+ let hit = page+ .hits+ .iter()+ .find(|hit| hit.session.id == run_session)+ .expect("search finds the run's transcript");+ assert!(+ hit.session.scheduled_run,+ "search reports the same ownership as the list"+ );++ // A task with a run still in flight cannot be deleted yet.+ let settled = handle(+ &st,+ "scheduled.finishRun",+ json!({"runId": run["runId"].as_str().unwrap(), "status": "completed"}),+ )+ .unwrap();+ assert_eq!(settled["ok"], json!(true));+ handle(&st, "scheduled.delete", json!({"id":id})).unwrap();+ assert_eq!(+ flag(&run_session),+ Some(false),+ "deleting the task releases its transcripts"+ );+ assert!(+ flag(&ordinary.id).is_some(),+ "the conversation itself survives the task deletion"+ );+ }++ /// A `reuse` task keeps one conversation; the default keeps one per run.+ #[tokio::test]+ async fn reuse_tasks_continue_one_conversation_and_per_run_tasks_do_not() {+ let dir = tempfile::tempdir().unwrap();+ let mut st = AppState::open(dir.path()).unwrap();+ st.handshook = true;+ let create = |mode: Option<&str>| {+ let mut params =+ json!({"title":"Nightly","prompt":"Summarize","cadence":"manual","schedule":null});+ if let Some(mode) = mode {+ params["sessionMode"] = json!(mode);+ }+ handle(&st, "scheduled.create", params).unwrap()["task"].clone()+ };+ let dispatch = |id: &str| handle(&st, "scheduled.run", json!({"id":id})).unwrap();+ let settle = |launch: &Value| {+ handle(+ &st,+ "scheduled.finishRun",+ json!({"runId":launch["runId"].as_str().unwrap(),"status":"completed"}),+ )+ .unwrap();+ };++ let per_run = create(None);+ assert_eq!(+ per_run["sessionMode"],+ json!("perRun"),+ "a task without the setting keeps the historical shape"+ );+ let per_run_id = per_run["id"].as_str().unwrap();+ let first = dispatch(per_run_id);+ settle(&first);+ let second = dispatch(per_run_id);+ settle(&second);+ assert_ne!(+ first["sessionId"], second["sessionId"],+ "a per-run task opens a conversation per run"+ );++ let reuse = create(Some("reuse"));+ assert_eq!(reuse["sessionMode"], json!("reuse"));+ let reuse_id = reuse["id"].as_str().unwrap();+ let first = dispatch(reuse_id);+ settle(&first);+ let second = dispatch(reuse_id);+ settle(&second);+ assert_eq!(+ first["sessionId"], second["sessionId"],+ "a reuse task continues the conversation its previous run used"+ );++ // Deleting that conversation starts a fresh one instead of failing.+ sessions::delete_session(&st.db, first["sessionId"].as_str().unwrap()).unwrap();+ let third = dispatch(reuse_id);+ settle(&third);+ assert_ne!(third["sessionId"], first["sessionId"]);++ let invalid = handle(+ &st,+ "scheduled.create",+ json!({"title":"Bad","prompt":"Summarize","cadence":"manual",+ "schedule":null,"sessionMode":"sometimes"}),+ );+ assert!(invalid.is_err(), "an unknown conversation mode is refused");+ }+#[tokio::test]async fn review_deleted_project_is_not_recreated_by_automatic_task() {use std::sync::Arc;diff --cc crates/host-core/src/sessions.rsindex 8cc084a6a,164be0a71..65ce3b94e--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@@ -4014,6 -4049,6 +4116,63 @@@ mod tests}}++ /// A failed transcript device flush must not leave an index row that makes++ /// replay of the same append a no-op.++ #[cfg(unix)]++ #[tokio::test]++ async fn a_failed_transcript_flush_can_be_retried_without_a_phantom_index() {++ use std::os::unix::fs::symlink;++++ let db = test_db();++ let session = create_session(&db, None, None, None, None, None).unwrap();++ let transcript_path = transcripts::transcript_path(db.data_dir(), &session.id).unwrap();++ if transcript_path.exists() {++ std::fs::remove_file(&transcript_path).unwrap();++ }++ std::fs::create_dir_all(transcript_path.parent().unwrap()).unwrap();++ symlink("/dev/null", &transcript_path).unwrap();++++ let message = user_msg("retry-after-flush-failure", "body", "2025-05-01T00:00:00Z");++ let (written, committed) = transcripts::commit_writes_of(async {++ append_message(&db, &session.id, &message, None)++ })++ .await;++ assert!(++ written.is_err() || committed.is_err(),++ "the append must report the device flush failure"++ );++++ std::fs::remove_file(&transcript_path).unwrap();++ let (retried, committed) = transcripts::commit_writes_of(async {++ append_message(&db, &session.id, &message, None)++ })++ .await;++ retried.expect("retry should append after the device recovers");++ committed.expect("retry should commit its durable transcript line");++++ let records = transcripts::read_transcript(db.data_dir(), &session.id).unwrap();++ let index_count: i64 = db++ .conn()++ .query_row(++ "SELECT COUNT(*) FROM messages WHERE session_id = ?1 AND id = ?2",++ params![session.id, message.id],++ |row| row.get(0),++ )++ .unwrap();++ assert_eq!(++ records++ .iter()++ .filter(|record| record.id == message.id)++ .count(),++ 1,++ "the canonical transcript should hold the retried message once"++ );++ assert_eq!(++ index_count, 1,++ "the index should hold the retried message once"++ );++ }++fn checkpoint(first: &str, through: &str) -> CompactionRecord {CompactionRecord {id: Uuid::new_v4().to_string(),diff --cc crates/host-core/src/transcripts.rsindex d0f3bf297,7b33883f2..733d0179c--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@@ -591,6 -843,211 +843,163 @@@ pub fn list_transcript_sessions(data_diOk(ids)}-/// The transcript durability contract, and where its device waits happen.++/// Request-scoped durability for in-flight checkpoints.+ ///-/// A write is acknowledged only once its bytes are on the device, and a failed-/// device flush fails the request that made the write. Both stay exactly as they-/// were when the `sync_data` sat inside the writing function.++/// Transcript and revision lines are synced by `append_line` before returning,++/// so callers can commit derived SQLite state only after the file is durable.++/// Checkpoints have no corresponding index transaction; their writes can run++/// after the request releases the state lock, before the response is sent.+ ///-/// What moves is *where* the caller waits. Making 321 new bytes durable costs-/// 3.57 ms on the ext4 volume the app data directory lives on (median of 40-/// appends, two runs; a commit with nothing new to write is 96 µs), and both-/// transcript appends and in-flight checkpoints ran inside the single-/// `Mutex<AppState>` that serializes the RPC surface — so one write held every-/// unrelated request for the length of a device commit.-///-/// Measured against the running host, with concurrent agent turns and an-/// unrelated session read probed every 5 ms, that lock — not the CPU — is the-/// wall. Four turns: 140 appends/s, read median 11.6 ms, host CPU 25%. Eight-/// turns: 148/s, 23.6 ms, 24%. With the wait of both writers moved out of the-/// lock: 339/s at 1.5 ms and 420/s at 4.1 ms, CPU 43-48%, and 8 sessions x 250-/// turns land every row exactly once with no torn content.-///-/// So a write records what it owes and the request that made it commits the debt-/// in order, once it has released the state lock and before its response goes-/// out. A caller that is not serving a request — startup recovery, a unit test —-/// has nowhere to record it and keeps the original inline work.-///-/// Two things the state lock used to order have to be kept explicitly:-///-/// * Checkpoints for one file keep the order of the *decisions* that produced-/// them, which is the order the state lock gave them. A checkpoint whose-/// decision is older than one already written is dropped, so a request that-/// reaches its commit late cannot put an older reply back.-/// * A checkpoint that lands after a terminal append removed it is discarded on-/// recovery: `recover_inflight_message` drops a checkpoint whose message id is-/// already indexed as a final row, so a stale snapshot cannot resurrect a-/// settled reply.++/// Checkpoints for one file keep the order of the decisions that produced them.++/// A checkpoint whose decision is older than one already written is dropped,++/// so a late request cannot put an older reply back. A checkpoint that lands++/// after a terminal append removed it is discarded on recovery because the++/// final row is already indexed.+ mod durability {+ use super::*;+ use std::cell::RefCell;+ use std::future::Future;+ use std::sync::atomic::{AtomicU64, Ordering};++ /// What one request owes the device before it may answer.+ enum Owed {- /// Bytes already in the page cache; only the flush is left.- Flush(PathBuf, File),+ /// A checkpoint still to write, flush and swap into place. `decided` is+ /// its place in the process-wide order of checkpoint decisions.+ Checkpoint {+ path: PathBuf,+ payload: String,+ decided: u64,+ },+ }++ tokio::task_local! {- /// What the request being served owes the device, in the order it was- /// recorded. Transcript bytes are in the page cache by the time they are- /// recorded; a checkpoint is not written at all yet.++ /// Checkpoint writes the request being served owes the device, in the++ /// order they were recorded.+ static PENDING: RefCell<Vec<Owed>>;+ }+- /// Record the device debt of `file`, or flush it here when no request will.- pub(super) fn owe(path: &Path, file: File) -> Result<()> {- if PENDING.try_with(|_| ()).is_err() {- return file- .sync_data()- .with_context(|| format!("flush {}", path.display()));- }- PENDING.with(|pending| {- let mut pending = pending.borrow_mut();- // The kernel buffer, not the descriptor, holds the bytes, so a newer- // handle for the same file supersedes an older one.- pending.retain(|owed| !matches!(owed, Owed::Flush(known, _) if known == path));- pending.push(Owed::Flush(path.to_path_buf(), file));- });- Ok(())- }-+ /// Record a checkpoint the request owes, or write it here when no request+ /// will. The record is serialized now, so the commit only touches the file.+ pub(super) fn owe_checkpoint(path: &Path, record: &InflightRecord) -> Result<()> {+ let decided = decision_order();+ let payload = serde_json::to_string(record)?;+ if PENDING.try_with(|_| ()).is_err() {+ return write_checkpoint(path, &payload, decided);+ }+ PENDING.with(|pending| {+ pending.borrow_mut().push(Owed::Checkpoint {+ path: path.to_path_buf(),+ payload,+ decided,+ });+ });+ Ok(())+ }+- /// Serve one request: commit every write it made, in order, before it- /// answers. The request's own outcome comes back untouched.++ /// Serve one request: commit every checkpoint it made before it answers.++ /// The request's own outcome comes back untouched.+ pub async fn serving<F, T>(future: F) -> (T, Result<()>)+ where+ F: Future<Output = T>,+ {+ PENDING+ .scope(RefCell::new(Vec::new()), async move {+ let output = future.await;+ let pending = PENDING.with(|pending| std::mem::take(&mut *pending.borrow_mut()));+ // The work blocks, so it runs off the async worker.+ let committed = tokio::task::spawn_blocking(move || commit(pending))+ .await+ .unwrap_or_else(|error| Err(anyhow!("transcript commit did not run: {error}")));+ (output, committed)+ })+ .await+ }+- /// Commit each owed item in order, stopping at the first failure: work that- /// could not reach the device is reported, never quietly dropped.++ /// Commit each checkpoint in order, stopping at the first device failure.+ fn commit(pending: Vec<Owed>) -> Result<()> {+ for owed in pending {+ match owed {- Owed::Flush(path, file) => file- .sync_data()- .with_context(|| format!("flush {}", path.display()))?,+ Owed::Checkpoint {+ path,+ payload,+ decided,+ } => write_checkpoint(&path, &payload, decided)?,+ }+ }+ Ok(())+ }++ /// Write one checkpoint: into a temporary file, to the device, and only then+ /// over the checkpoint it replaces.+ ///+ /// A checkpoint whose decision is older than one already written is dropped:+ /// the state lock that used to hold the decision and the write together is+ /// released before this runs, and the file keeps the later decision.+ fn write_checkpoint(path: &Path, payload: &str, decided: u64) -> Result<()> {+ let state = writer_state(path);+ let _per_file = state+ .lock+ .lock()+ .unwrap_or_else(|poison| poison.into_inner());+ if state.written.load(Ordering::SeqCst) >= decided {+ return Ok(());+ }+ let tmp = path.with_extension("json.tmp");+ {+ let mut file = File::create(&tmp)?;+ file.write_all(payload.as_bytes())?;+ file.write_all(b"\n")?;+ file.flush()?;+ file.sync_data()+ .with_context(|| format!("flush {}", tmp.display()))?;+ }+ swap_into_place(&tmp, path)?;+ state.written.store(decided, Ordering::SeqCst);+ Ok(())+ }++ /// Where a checkpoint decision sits in the process-wide decision order. The+ /// state lock used to be that order; it is released before the write now.+ fn decision_order() -> u64 {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ NEXT.fetch_add(1, Ordering::SeqCst) + 1+ }++ /// One checkpoint file's writer state: the lock that makes a decision and its+ /// swap atomic against another writer of the same file, and the decision that+ /// last landed there.+ ///+ /// One entry per checkpoint path ever written is kept for the life of the+ /// process. Evicting could hand two concurrent writers different state for one+ /// file, which is the interleaving this exists to prevent; sessions are+ /// long-lived and few, so the table stays small.+ struct WriterState {+ lock: std::sync::Mutex<()>,+ written: AtomicU64,+ }++ fn writer_state(path: &Path) -> &'static WriterState {+ type Registry = std::sync::Mutex<std::collections::HashMap<PathBuf, &'static WriterState>>;+ static WRITERS: std::sync::OnceLock<Registry> = std::sync::OnceLock::new();+ let registry =+ WRITERS.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));+ let mut guard = registry.lock().unwrap_or_else(|poison| poison.into_inner());+ let state: &'static WriterState = guard.entry(path.to_path_buf()).or_insert_with(|| {+ Box::leak(Box::new(WriterState {+ lock: std::sync::Mutex::new(()),+ written: AtomicU64::new(0),+ }))+ });+ state+ }+ }+-/// Serve one RPC, committing the transcript writes it made before it answers.++/// Serve one RPC, committing the checkpoints it made before it answers.+ ///-/// Returns the request's own outcome together with the device outcome, so the-/// caller decides which of the two a response carries — and so a device failure-/// cannot be answered with success.++/// Transcript lines are synced inline before their derived index transaction;++/// this returns the checkpoint outcome so the caller can report its failures.+ pub use durability::serving as commit_writes_of;+/// Durable single-line append shared by transcript and revision writers./// `header` is written first when the file does not exist yet.fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()> {@@@ -616,9 -1073,10 +1025,8 @@@buf.push('\n');file.write_all(buf.as_bytes())?;file.flush()?;- // Message durability matches the DB's WAL synchronous=NORMAL guarantees.- file.sync_data()?;- Ok(())- // The bytes are in the kernel. Whether they reach the device before this- // caller is answered belongs to the request that made the write (see- // `commit_writes_of`); a caller outside one flushes them here.- durability::owe(path, file)++ file.sync_data()++ .with_context(|| format!("flush {}", path.display()))}/// Whether a non-empty file ends in a newline; an empty file counts as@@@ -1979,4 -2560,248 +2510,246 @@@ mod testsassert!(!revisions_path(dir.path(), "s1").unwrap().exists());remove_session_files(dir.path(), "s1");}++ /// A tool row whose block array names a provider call id.+ fn tool_record(id: &str, call_id: &str) -> MessageRecord {+ MessageRecord {+ id: id.into(),+ role: "tool".into(),+ tool_name: Some("bash".into()),+ is_error: false,+ blocks: json!([{ "type": "tool_result", "callId": call_id, "text": "x" }]),+ meta: None,+ created_at: "2026-07-26T00:00:00.000Z".into(),+ }+ }++ /// Byte offset of every line start, which is all `read_tool_call` needs.+ fn line_offsets(dir: &Path, session_id: &str) -> TranscriptLayout {+ let raw = fs::read(transcript_path(dir, session_id).unwrap()).unwrap();+ let mut message_offsets = Vec::new();+ let mut at = 0usize;+ for line in raw.split_inclusive(|byte| *byte == b'\n') {+ message_offsets.push(at as u64);+ at += line.len();+ }+ TranscriptLayout {+ message_offsets,+ compaction_offsets: Vec::new(),+ file_len: raw.len() as u64,+ }+ }++ /// Presence is answered from the id field, and the byte pre-filter must not+ /// hide an id that JSON writes in escaped form.+ #[test]+ fn transcript_contains_id_answers_from_the_id_field_alone() {+ let dir = tempdir().unwrap();+ let escaped = "quote\"and\\slash";+ for id in ["m1", "middle", escaped] {+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record(id, "x")).unwrap();+ }+ for id in ["m1", "middle", escaped] {+ assert!(+ transcript_contains_id(dir.path(), "s1", id).unwrap(),+ "{id:?} should be present"+ );+ }+ assert!(!transcript_contains_id(dir.path(), "s1", "absent").unwrap());+ // A prefix of a stored id is not a stored id.+ assert!(!transcript_contains_id(dir.path(), "s1", "mid").unwrap());+ // A session with no transcript answers false rather than failing.+ assert!(!transcript_contains_id(dir.path(), "other", "m1").unwrap());+ }++ /// The byte pre-filter in `read_tool_call` must not hide a call id that JSON+ /// writes in escaped form.+ #[test]+ fn read_tool_call_finds_ids_that_json_escapes() {+ let dir = tempdir().unwrap();+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x")).unwrap();+ let call_ids = ["call-1", "quote\"and\\slash"];+ for (index, call_id) in call_ids.iter().enumerate() {+ append_message(+ dir.path(),+ "s1",+ "2026-07-26T00:00:00Z",+ &tool_record(&format!("tool-{index}"), call_id),+ )+ .unwrap();+ }+ let layout = line_offsets(dir.path(), "s1");+ for call_id in call_ids {+ assert!(+ read_tool_call(dir.path(), "s1", &layout, call_id)+ .unwrap()+ .is_some(),+ "{call_id:?} should be found"+ );+ }+ assert!(read_tool_call(dir.path(), "s1", &layout, "absent")+ .unwrap()+ .is_none());+ }++ /// Concurrent appends from several sessions must not cost a line, fuse two+ /// lines, or leak across files: writes are ordered by the state lock and+ /// each append flushes its own file. Guards the append shape the durability+ /// contract rests on.+ #[test]+ fn concurrent_appends_keep_every_line_intact_and_in_its_own_session() {+ const SESSIONS: usize = 8;+ const PER_SESSION: usize = 25;+ let dir = tempdir().unwrap();+ let mut handles = Vec::new();+ for session in 0..SESSIONS {+ let root = dir.path().to_path_buf();+ handles.push(std::thread::spawn(move || {+ let id = format!("sess-{session}");+ for index in 0..PER_SESSION {+ let record = record(&format!("msg-{:06}", session * PER_SESSION + index), "x");+ append_message(&root, &id, "2026-07-26T00:00:00Z", &record).unwrap();+ }+ }));+ }+ for handle in handles {+ handle.join().unwrap();+ }+ for session in 0..SESSIONS {+ let id = format!("sess-{session}");+ let expected: Vec<String> = (session * PER_SESSION..(session + 1) * PER_SESSION)+ .map(|index| format!("msg-{index:06}"))+ .collect();+ let ids: Vec<String> = read_transcript(dir.path(), &id)+ .unwrap()+ .iter()+ .map(|record| record.id.clone())+ .collect();+ assert_eq!(+ ids, expected,+ "every line survives, in order, in its own session"+ );+ }+ }++ /// Point one session's transcript at a file that takes writes and refuses+ /// the device flush. `/dev/null` accepts the bytes and fails `fdatasync`+ /// with EINVAL, which is how a broken device behaves, on any machine.+ #[cfg(unix)]+ fn transcript_that_cannot_be_flushed(dir: &Path) -> PathBuf {+ let path = transcript_path(dir, "s1").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::os::unix::fs::symlink("/dev/null", &path).unwrap();+ path+ }++ /// A caller that is not serving a request has nowhere to defer to, so it+ /// must not report an append whose bytes never reached the device as a+ /// success.+ #[cfg(unix)]+ #[test]+ fn an_append_outside_a_request_reports_a_failed_device_flush() {+ let dir = tempdir().unwrap();+ transcript_that_cannot_be_flushed(dir.path());+ let error = append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x"))+ .expect_err("a failed device flush is not a successful append");+ assert!(format!("{error:#}").contains("flush"), "{error:#}");+ }+- /// The request that owns the write owns the device wait: it commits the- /// lines it wrote before it answers, and a failed flush comes back to it- /// instead of being logged and forgotten.++ /// Transcript appends sync inline; a failed flush is returned by the append++ /// before a caller can update the derived index.+ #[cfg(unix)]+ #[tokio::test]- async fn a_request_only_answers_after_its_lines_reached_the_device() {++ async fn an_append_in_a_request_reports_a_failed_device_flush() {+ let dir = tempdir().unwrap();+ transcript_that_cannot_be_flushed(dir.path());+ let (written, committed) = commit_writes_of(async {+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x"))+ })+ .await;- assert!(written.is_ok(), "the write itself succeeds: {written:?}");- let error =- committed.expect_err("the flush failed, so the request must not answer success");++ let error = written.expect_err("a failed device flush must fail the append");+ assert!(format!("{error:#}").contains("flush"), "{error:#}");++ committed.expect("an append flush is not deferred");+ }+- /// The same scope on a healthy file commits the write and reports nothing.++ /// A healthy inline append succeeds inside the request durability scope.+ #[tokio::test]- async fn a_request_commits_the_transcript_lines_it_wrote() {++ async fn an_append_in_a_request_succeeds_after_flushing_its_line() {+ let dir = tempdir().unwrap();+ let (written, committed) = commit_writes_of(async {+ append_message(dir.path(), "s1", "2026-07-26T00:00:00Z", &record("m1", "x"))+ })+ .await;+ written.unwrap();+ committed.expect("a synced write commits");+ let ids: Vec<String> = read_transcript(dir.path(), "s1")+ .unwrap()+ .iter()+ .map(|record| record.id.clone())+ .collect();+ assert_eq!(ids, vec!["m1".to_string()]);+ }++ /// An in-flight checkpoint for `message_id`, stamped `created_at`.+ fn inflight(session_id: &str, message_id: &str, created_at: &str) -> InflightRecord {+ let mut message = record(message_id, "partial");+ message.created_at = created_at.into();+ InflightRecord {+ schema: INFLIGHT_SCHEMA,+ session_id: session_id.into(),+ turn_id: Some("turn-1".into()),+ saved_at: created_at.into(),+ message,+ }+ }++ /// A checkpoint is part of what a request owes the device, so one that cannot+ /// reach it fails the request instead of answering success.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_request_whose_checkpoint_cannot_be_flushed_fails() {+ let dir = tempdir().unwrap();+ let path = inflight_path(dir.path(), "s1").unwrap();+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ // The temporary the writer creates, flushes and renames into place.+ std::os::unix::fs::symlink("/dev/null", path.with_extension("json.tmp")).unwrap();+ let record = inflight("s1", "m1", "2026-07-26T00:00:01.000Z");+ let (written, committed) =+ commit_writes_of(async { write_inflight(dir.path(), "s1", &record) }).await;+ assert!(written.is_ok(), "the write itself succeeds: {written:?}");+ let error = committed.expect_err("an unflushed checkpoint is not a saved checkpoint");+ assert!(format!("{error:#}").contains("flush"), "{error:#}");+ }++ /// Checkpoints of one file keep the order of the decisions that produced+ /// them, including when the earlier decision reaches its commit last: the+ /// state lock used to give that order and the commit no longer holds it.+ #[tokio::test]+ async fn a_checkpoint_decided_later_always_wins() {+ let dir = tempdir().unwrap();+ let root = dir.path().to_path_buf();+ let first = inflight("s1", "m1", "2026-07-26T00:00:01.000Z");+ let second = inflight("s1", "m1", "2026-07-26T00:00:02.000Z");+ let (written, committed) = commit_writes_of(async {+ // Decided first, and it reaches its commit only after the second+ // decision has already replaced the file.+ write_inflight(&root, "s1", &first).unwrap();+ let later = {+ let (root, second) = (root.clone(), second.clone());+ // No request scope on this thread, so this one is written inline,+ // exactly as every checkpoint was before the wait moved.+ tokio::task::spawn_blocking(move || write_inflight(&root, "s1", &second))+ };+ later.await.unwrap().unwrap();+ Ok::<(), anyhow::Error>(())+ })+ .await;+ written.unwrap();+ committed.unwrap();+ let stored = read_inflight(&root, "s1").unwrap().unwrap();+ assert_eq!(+ stored.message.created_at, second.message.created_at,+ "a checkpoint decided earlier must not land on top of a later one"+ );+ }}