aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#909 (code only)
Apply it
git checkout -b patch-3225613252cbd2bf 2ef3e06c2a7b6c7498d7550cb0de6133129ed49a curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/3225613252cbd2bf.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
909
a7895fce522934770b5e5fc90f7bfc91087bba80
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":909,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/909","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:16Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs index e20e83be..a744c447 100644 --- a/crates/aien-cli/src/main.rs +++ b/crates/aien-cli/src/main.rs @@ -1032,7 +1032,7 @@ pub async fn run_autonomous_goal(goal_id: &str) { /// the compacted one, never both the recap and the messages it replaced. /// /// `Err(CompactionUnrecorded)` means the compacted transcript is only in -/// memory. The caller stops the turn: the journal already holds the +/// memory. The caller ends the session: the journal already holds the /// pre-compaction history, and that is what resume loads. A marker cannot /// stand in for the snapshot, because the write that failed is the one that /// would have stored the compacted transcript. @@ -1273,6 +1273,118 @@ mod compaction_journal_tests { }; assert!(record_compaction(&report, &[], &mut journal).is_ok()); } + + /// Answers every chat request with one streamed assistant reply and + /// counts the requests. + fn mock_model(reply: &'static str) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) { + use std::io::{BufRead, BufReader, Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!( + "http://{}/v1/chat/completions", + listener.local_addr().unwrap() + ); + let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = calls.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { return }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut len = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + if line == "\r\n" { + break; + } + } + let mut body = vec![0u8; len]; + let _ = reader.read_exact(&mut body); + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let chunk = json!({"choices": [{"delta": {"content": reply}}]}); + let sse = format!("data: {chunk}\n\ndata: [DONE]\n\n"); + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + sse.len(), + sse + ); + } + }); + (url, calls) + } + + /// #832 item 3, end to end through `run_model_steps`: the model asks for + /// a tool, compaction applies, and its snapshot cannot be written. No + /// tool runs, no second model call is made, the loop returns the stop, + /// and resume loads the history from before the compaction. + #[tokio::test] + async fn compaction_unrecorded_ends_the_session_before_any_tool_or_model_call() { + let d = tempfile::tempdir().unwrap(); + let path = d.path().join("s.journal.jsonl"); + let mut journal = turn_journal::Journal::create(&path).unwrap(); + let compactor = ContextCompactor::new(2000, 1000, 500) + .with_store(CompactionStore::new(d.path().join("compaction"))); + let mut messages = Vec::new(); + for m in [ + json!({"role": "system", "content": "sys"}), + user("grounding"), + ] { + journal.push(&mut messages, m).unwrap(); + } + for k in 0..4 { + journal + .push(&mut messages, user(&format!("ask {k}"))) + .unwrap(); + journal + .push(&mut messages, json!({"role": "assistant", "content": format!("answer {k}: {}", "Z".repeat(4000))})) + .unwrap(); + } + journal.push(&mut messages, user("list the files")).unwrap(); + let reply = + "<tool_call>\n{\"name\": \"list_dir\", \"arguments\": {\"path\": \".\"}}\n</tool_call>"; + let (url, calls) = mock_model(reply); + let client = ChatClient::new(Some(url), Some("mock".into())); + let hooks = crate::hooks::HookRegistry::new(); + let batch = tool_batch::BatchConfig::new(32_000, None); + // The assistant reply reaches disk; the compaction snapshot does not. + journal.accept_only_n_writes_for_test(1); + + let stop = run_model_steps( + &client, + &mut messages, + &mut journal, + Some(&compactor), + &hooks, + false, + &batch, + ) + .await; + assert!( + matches!(stop, Some(turn_journal::TurnStop::CompactionUnrecorded(_))), + "{stop:?}" + ); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); + drop(journal); + + let (_j, rep) = turn_journal::Journal::resume(&path).unwrap(); + assert!(rep.in_doubt.is_empty(), "a tool request was recorded"); + assert_eq!(rep.messages.last().unwrap()["content"], reply); + assert!(!rep.messages.iter().any(|m| { + m["content"] + .as_str() + .is_some_and(|c| c.starts_with("<context_compaction_recap")) + })); + assert!(!rep.messages.iter().any(|m| { + m["content"] + .as_str() + .is_some_and(|c| c.starts_with("<tool_response")) + })); + } } #[cfg(test)] diff --git a/crates/aien-cli/src/turn_journal.rs b/crates/aien-cli/src/turn_journal.rs index 53219456..b434044a 100644 --- a/crates/aien-cli/src/turn_journal.rs +++ b/crates/aien-cli/src/turn_journal.rs @@ -334,9 +334,14 @@ pub struct Journal { file: File, last: String, next_call: u64, + /// Length of the whole records on disk. A failed append truncates back to it. + len: u64, /// `Some(0)` makes the next append fail before it writes. Test builds only. #[cfg(test)] writes_left: Option<u32>, + /// The next append writes half its line, then fails. Test builds only. + #[cfg(test)] + tear_next: bool, } impl Journal { @@ -361,8 +366,11 @@ impl Journal { file, last: GENESIS.to_string(), next_call: 0, + len: 0, #[cfg(test)] writes_left: None, + #[cfg(test)] + tear_next: false, }) } @@ -388,8 +396,11 @@ impl Journal { file, last: rep.last_digest.clone(), next_call: rep.next_call, + len: rep.valid_len as u64, #[cfg(test)] writes_left: None, + #[cfg(test)] + tear_next: false, }, rep, )) @@ -399,7 +410,9 @@ impl Journal { &self.path } - /// Appends one record and flushes it to disk before returning. + /// Appends one record and flushes it to disk before returning. A write + /// that fails part way is cut back to the last whole record, so the next + /// append does not glue its line onto a torn one (#832). pub fn append(&mut self, record: &Record) -> Result<(), JournalError> { #[cfg(test)] if self.writes_left == Some(0) { @@ -410,10 +423,15 @@ impl Journal { let line = json!({"v": 1, "prev": self.last, "digest": digest, "record": record_v}); let mut bytes = serde_json::to_vec(&line).map_err(|e| JournalError::Io(e.to_string()))?; bytes.push(b'\n'); - self.file - .write_all(&bytes) - .and_then(|_| self.file.sync_data()) - .map_err(|e| JournalError::Io(e.to_string()))?; + if let Err(e) = self.write_record(&bytes) { + // Drop whatever part of the line reached the file. If this fails + // too, `resume` still drops a torn last line. + if self.file.set_len(self.len).is_ok() { + let _ = self.file.sync_data(); + } + return Err(JournalError::Io(e.to_string())); + } + self.len += bytes.len() as u64; self.last = digest; #[cfg(test)] if let Some(left) = self.writes_left { @@ -422,6 +440,23 @@ impl Journal { Ok(()) } + fn write_record(&mut self, bytes: &[u8]) -> std::io::Result<()> { + #[cfg(test)] + if std::mem::take(&mut self.tear_next) { + self.file.write_all(&bytes[..bytes.len() / 2])?; + return Err(std::io::Error::other("journal write torn by test")); + } + self.file.write_all(bytes)?; + self.file.sync_data() + } + + /// The next append writes half of its line and then fails, as a full + /// disk or a signal part way through a write would. + #[cfg(test)] + pub fn tear_next_write_for_test(&mut self) { + self.tear_next = true; + } + /// The next `n` appends succeed. The one after that fails before it writes. /// `n == 0` fails the next append. Tests use this where a full disk would /// stop a turn ahead of a tool. @@ -796,6 +831,25 @@ mod tests { assert_eq!(rep.messages, msgs); } + #[test] + fn a_write_torn_in_process_is_cut_back_before_the_next_append() { + let (_d, p) = tmp(); + let mut j = Journal::create(&p).unwrap(); + let mut msgs = Vec::new(); + j.push(&mut msgs, user("one")).unwrap(); + let whole_len = std::fs::metadata(&p).unwrap().len(); + j.tear_next_write_for_test(); + assert!(j.push(&mut msgs, user("lost")).is_err()); + assert_eq!(msgs, vec![user("one")]); + assert_eq!(std::fs::metadata(&p).unwrap().len(), whole_len); + // The same process keeps going; its next line must not land on the torn one. + j.push(&mut msgs, user("two")).unwrap(); + drop(j); + let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); + assert!(!rep.torn_tail); + assert_eq!(rep.messages, msgs); + } + #[test] fn damage_before_the_last_line_is_refused() { let (_d, p) = tmp();