interplane.Get Omega
Read in your language

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#305 (code only)

closed derived ab0e65b203914267 #305

Imported from GitHub aien-dev/aien-sovereign-core-mv#305 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 12c1a5ff18b70e748b678280c4210788f820c712 · Head 7834d3074726bbe8ed08042ca2405f339f434de3

Apply it

git checkout -b patch-ab0e65b203914267 12c1a5ff18b70e748b678280c4210788f820c712
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/ab0e65b203914267.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
305
7834d3074726bbe8ed08042ca2405f339f434de3
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":305,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/305","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:45Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs
index 230574b8..6fae04b1 100644
--- a/crates/aien-runtime/src/control.rs
+++ b/crates/aien-runtime/src/control.rs
@@ -219,19 +219,88 @@ pub enum ControlResponse {
 
 /// Actor managing operator sessions and enforcing idempotent command execution.
 /// Processed operation IDs persist to disk so idempotency survives restarts.
+///
+/// The state file path is fixed when the controller is built (#275): a later
+/// change of `AIEN_RUNTIME_STATE_DIR` never redirects its writes. Every save
+/// is a read-merge-write under an exclusive `flock` on `<file>.lock`, through
+/// a temp file unique to that write, fsynced, then renamed (#299). Two
+/// controllers sharing one file (threads or processes) therefore never tear
+/// it and never drop each other's ids.
 pub struct RuntimeController {
     processed_operations: HashSet<u128>,
+    state_path: std::path::PathBuf,
 }
 
+/// The state file: `$AIEN_RUNTIME_STATE_DIR/processed_operations.json`, else
+/// the machine-wide `/tmp/aien-runtime-processed-ops.json`. Unit tests of this
+/// crate fall back to a per-process directory instead, so no lib test reads
+/// state another program wrote.
 fn operations_state_path() -> std::path::PathBuf {
     if let Ok(dir) = std::env::var("AIEN_RUNTIME_STATE_DIR") {
         if !dir.trim().is_empty() {
             return std::path::PathBuf::from(dir.trim()).join("processed_operations.json");
         }
     }
+    #[cfg(test)]
+    {
+        let dir = std::env::temp_dir().join(format!("aien-runtime-unit-{}", std::process::id()));
+        let _ = std::fs::create_dir_all(&dir);
+        dir.join("processed_operations.json")
+    }
+    #[cfg(not(test))]
     std::path::PathBuf::from("/tmp/aien-runtime-processed-ops.json")
 }
 
+/// Reads the ids in `path`. Absent = empty; unreadable or unparsable = error.
+fn read_operations(path: &std::path::Path) -> Result<Vec<u128>, String> {
+    match std::fs::read(path) {
+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
+        Err(e) => Err(format!("idempotency state {}: {e}", path.display())),
+        Ok(bytes) => serde_json::from_slice::<Vec<u128>>(&bytes).map_err(|e| {
+            format!(
+                "idempotency state {} is damaged ({e}); refusing to start rather than forget processed operations",
+                path.display()
+            )
+        }),
+    }
+}
+
+/// Exclusive advisory lock on `<state file>.lock`, released on drop.
+struct StateLock(std::fs::File);
+
+impl StateLock {
+    fn acquire(path: &std::path::Path) -> Result<Self, String> {
+        use std::os::fd::AsRawFd;
+        let lock_path = path.with_extension("json.lock");
+        let file = std::fs::OpenOptions::new()
+            .create(true)
+            .truncate(false)
+            .write(true)
+            .open(&lock_path)
+            .map_err(|e| format!("idempotency lock {}: {e}", lock_path.display()))?;
+        loop {
+            // SAFETY: flock on a file descriptor this function owns.
+            if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 {
+                return Ok(Self(file));
+            }
+            let e = std::io::Error::last_os_error();
+            if e.kind() != std::io::ErrorKind::Interrupted {
+                return Err(format!("idempotency lock {}: {e}", lock_path.display()));
+            }
+        }
+    }
+}
+
+impl Drop for StateLock {
+    fn drop(&mut self) {
+        use std::os::fd::AsRawFd;
+        // SAFETY: unlock the descriptor locked in acquire (close would too).
+        unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) };
+    }
+}
+
+static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
 impl Default for RuntimeController {
     fn default() -> Self {
         Self::new()
@@ -245,42 +314,66 @@ impl RuntimeController {
         Self::load().unwrap_or_else(|e| panic!("{e}"))
     }
 
-    /// Loads the persisted operation ids. An absent file is an empty set; a
-    /// file that cannot be read or parsed is an error (NEXT-PHASE-2,
-    /// ACCEPTANCE-v2 2.8): idempotency state is never reset silently.
+    /// Loads the persisted operation ids from the default state file. An
+    /// absent file is an empty set; a file that cannot be read or parsed is
+    /// an error (NEXT-PHASE-2, ACCEPTANCE-v2 2.8): idempotency state is never
+    /// reset silently.
     pub fn load() -> Result<Self, String> {
-        let path = operations_state_path();
-        let ids = match std::fs::read(&path) {
-            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
-            Err(e) => return Err(format!("idempotency state {}: {e}", path.display())),
-            Ok(bytes) => serde_json::from_slice::<Vec<u128>>(&bytes).map_err(|e| {
-                format!(
-                    "idempotency state {} is damaged ({e}); refusing to start rather than forget processed operations",
-                    path.display()
-                )
-            })?,
-        };
+        Self::load_from(operations_state_path())
+    }
+
+    /// [`Self::load`] for an explicit state file, independent of the
+    /// environment.
+    pub fn load_from(state_path: std::path::PathBuf) -> Result<Self, String> {
+        let ids = read_operations(&state_path)?;
         Ok(Self {
             processed_operations: ids.into_iter().collect(),
+            state_path,
         })
     }
 
+    /// The file this controller reads and writes.
+    pub fn state_path(&self) -> &std::path::Path {
+        &self.state_path
+    }
+
     pub fn is_operation_processed(&self, op_id: u128) -> bool {
         self.processed_operations.contains(&op_id)
     }
 
-    pub fn mark_operation_processed(&mut self, op_id: u128) {
+    /// Records `op_id` in memory and on disk. The id stays recorded in memory
+    /// even when the disk write fails; the error says the record is not
+    /// durable (a restart would forget it). A damaged file on disk is an
+    /// error and is never overwritten.
+    pub fn mark_operation_processed(&mut self, op_id: u128) -> Result<(), String> {
         self.processed_operations.insert(op_id);
+        let _lock = StateLock::acquire(&self.state_path)?;
+        // Merge with what other controllers on this file recorded meanwhile.
+        let on_disk = read_operations(&self.state_path)?;
+        self.processed_operations.extend(on_disk);
         let ids: Vec<u128> = self.processed_operations.iter().copied().collect();
-        if let Ok(bytes) = serde_json::to_vec(&ids) {
-            // Write then rename: a crash mid-write must not leave a truncated
-            // file, which new() would silently discard, losing idempotency.
-            let path = operations_state_path();
-            let tmp = path.with_extension(format!("json.tmp.{}", std::process::id()));
-            if std::fs::write(&tmp, bytes).is_ok() && std::fs::rename(&tmp, &path).is_err() {
-                let _ = std::fs::remove_file(&tmp);
-            }
-        }
+        let bytes = serde_json::to_vec(&ids).map_err(|e| format!("idempotency state: {e}"))?;
+        // Write a temp file unique to this write, sync, then rename: a crash
+        // or a concurrent writer never leaves a truncated state file.
+        let tmp = self.state_path.with_extension(format!(
+            "json.tmp.{}.{}",
+            std::process::id(),
+            TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+        ));
+        let write = || -> std::io::Result<()> {
+            use std::io::Write;
+            let mut f = std::fs::File::create(&tmp)?;
+            f.write_all(&bytes)?;
+            f.sync_all()?;
+            std::fs::rename(&tmp, &self.state_path)
+        };
+        write().map_err(|e| {
+            let _ = std::fs::remove_file(&tmp);
+            format!(
+                "idempotency state {}: write failed ({e}); operation {op_id:#x} is not durable",
+                self.state_path.display()
+            )
+        })
     }
 }
 
@@ -288,23 +381,28 @@ impl RuntimeController {
 mod tests {
     use super::*;
 
+    fn state_file(dir: &tempfile::TempDir) -> std::path::PathBuf {
+        dir.path().join("processed_operations.json")
+    }
+
     #[test]
     fn idempotency_survives_restart() {
-        let dir = std::env::temp_dir().join(format!("aien-ops-test-{}", std::process::id()));
-        let _ = std::fs::create_dir_all(&dir);
-        std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir);
+        // Explicit path: this test never sets the process-wide
+        // AIEN_RUNTIME_STATE_DIR other tests in this binary read (#275).
+        let dir = tempfile::tempdir().unwrap();
+        let path = state_file(&dir);
         let op_id = 0xC0FFEEu128;
 
         {
-            let mut first = RuntimeController::new();
+            let mut first = RuntimeController::load_from(path.clone()).unwrap();
             assert!(!first.is_operation_processed(op_id));
-            first.mark_operation_processed(op_id);
+            first.mark_operation_processed(op_id).unwrap();
             assert!(first.is_operation_processed(op_id));
         }
 
         // Simulate a process restart: a fresh controller reloads from disk.
         {
-            let second = RuntimeController::new();
+            let second = RuntimeController::load_from(path.clone()).unwrap();
             assert!(
                 second.is_operation_processed(op_id),
                 "replayed operation ID must be rejected after restart"
@@ -312,15 +410,99 @@ mod tests {
         }
 
         // NEXT-PHASE-2: a damaged state file is refused, never reset.
-        std::fs::write(dir.join("processed_operations.json"), b"{").unwrap();
-        let err = RuntimeController::load()
+        std::fs::write(&path, b"{").unwrap();
+        let err = RuntimeController::load_from(path.clone())
             .err()
             .expect("damaged state must be refused");
         assert!(err.contains("is damaged"), "{err}");
-        std::fs::write(dir.join("processed_operations.json"), b"[1, 2").unwrap();
-        assert!(RuntimeController::load().is_err());
+        std::fs::write(&path, b"[1, 2").unwrap();
+        assert!(RuntimeController::load_from(path.clone()).is_err());
+        // An empty file (what the #299 race left behind) is damaged too.
+        std::fs::write(&path, b"").unwrap();
+        assert!(RuntimeController::load_from(path).is_err());
+    }
+
+    #[test]
+    fn a_save_never_overwrites_damaged_state() {
+        let dir = tempfile::tempdir().unwrap();
+        let path = state_file(&dir);
+        let mut c = RuntimeController::load_from(path.clone()).unwrap();
+        std::fs::write(&path, b"[1, 2").unwrap();
+        let err = c.mark_operation_processed(7).unwrap_err();
+        assert!(err.contains("is damaged"), "{err}");
+        assert_eq!(
+            std::fs::read(&path).unwrap(),
+            b"[1, 2",
+            "damaged file kept as found"
+        );
+        assert!(c.is_operation_processed(7), "still recorded in memory");
+    }
 
-        let _ = std::fs::remove_dir_all(&dir);
+    #[test]
+    fn concurrent_saves_never_damage_or_drop_state() {
+        // #299 root cause: every save used the temp name `json.tmp.<pid>`, so
+        // two controllers in one process truncated each other's temp file and
+        // renamed an empty file into place. Red on 12c1a5f: "is damaged (EOF
+        // while parsing a value at line 1 column 0)".
+        let dir = tempfile::tempdir().unwrap();
+        let path = state_file(&dir);
+        let threads: Vec<_> = (0..8u128)
+            .map(|t| {
+                let path = path.clone();
+                std::thread::spawn(move || {
+                    let mut c = RuntimeController::load_from(path).unwrap();
+                    for i in 0..200u128 {
+                        c.mark_operation_processed(t * 1000 + i).unwrap();
+                    }
+                })
+            })
+            .collect();
+        for t in threads {
+            t.join().unwrap();
+        }
+        let after = RuntimeController::load_from(path).expect("state loads after concurrent saves");
+        for t in 0..8u128 {
+            for i in 0..200u128 {
+                assert!(
+                    after.is_operation_processed(t * 1000 + i),
+                    "id {t}/{i} forgotten"
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn interrupted_save_leaves_the_last_good_state() {
+        // A process killed mid-save leaves its temp file (and the lock file)
+        // behind; the state file itself is the last complete write.
+        let dir = tempfile::tempdir().unwrap();
+        let path = state_file(&dir);
+        let mut c = RuntimeController::load_from(path.clone()).unwrap();
+        c.mark_operation_processed(1).unwrap();
+        std::fs::write(path.with_extension("json.tmp.999999.0"), b"[1, 2, 3").unwrap();
+        let mut restarted = RuntimeController::load_from(path.clone()).unwrap();
+        assert!(restarted.is_operation_processed(1));
+        assert!(
+            !restarted.is_operation_processed(3),
+            "half-written temp file is never read"
+        );
+        restarted.mark_operation_processed(2).unwrap();
+        let again = RuntimeController::load_from(path).unwrap();
+        assert!(again.is_operation_processed(1) && again.is_operation_processed(2));
+    }
+
+    #[test]
+    fn path_is_fixed_at_construction() {
+        // #275: a controller keeps writing where it loaded from, whatever a
+        // parallel test does to AIEN_RUNTIME_STATE_DIR afterwards.
+        let dir = tempfile::tempdir().unwrap();
+        let path = state_file(&dir);
+        let mut c = RuntimeController::load_from(path.clone()).unwrap();
+        assert_eq!(c.state_path(), path.as_path());
+        c.mark_operation_processed(5).unwrap();
+        assert!(RuntimeController::load_from(path)
+            .unwrap()
+            .is_operation_processed(5));
     }
 
     #[test]
diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs
index 69663a8d..ba38a2dc 100644
--- a/crates/aien-runtime/src/spine.rs
+++ b/crates/aien-runtime/src/spine.rs
@@ -362,8 +362,7 @@ impl AienRuntimeSpine {
                 };
                 match self.launch_swarm(config, &req.prompt_tokens) {
                     Ok(swarm_id) => {
-                        self.controller
-                            .mark_operation_processed(envelope.operation_id);
+                        record_processed(&mut self.controller, envelope.operation_id);
                         ControlResponse::SwarmAccepted {
                             swarm_id,
                             operation_id: envelope.operation_id,
@@ -393,8 +392,7 @@ impl AienRuntimeSpine {
                             }
                         }
                         self.pending_backend_releases.extend(released);
-                        self.controller
-                            .mark_operation_processed(envelope.operation_id);
+                        record_processed(&mut self.controller, envelope.operation_id);
                         ControlResponse::SwarmCancelled { swarm_id }
                     }
                     Err(e) => ControlResponse::Error(e),
@@ -422,8 +420,7 @@ impl AienRuntimeSpine {
                     .into(),
             ),
             ControlCommand::Shutdown => {
-                self.controller
-                    .mark_operation_processed(envelope.operation_id);
+                record_processed(&mut self.controller, envelope.operation_id);
                 ControlResponse::ShutdownAck
             }
         };
@@ -2639,6 +2636,15 @@ mod verify_callback_integration_tests {
     }
 }
 
+/// Records a processed operation id. The operation has already run, so a
+/// failed save does not change the reply; it is reported on stderr so the
+/// loss of durability is never silent (#299).
+fn record_processed(controller: &mut RuntimeController, operation_id: u128) {
+    if let Err(e) = controller.mark_operation_processed(operation_id) {
+        eprintln!("aien-runtime: {e}");
+    }
+}
+
 #[cfg(test)]
 mod destination_enforcement_tests {
     use super::*;
diff --git a/crates/aien-runtime/tests/warm_up_before_serving_test.rs b/crates/aien-runtime/tests/warm_up_before_serving_test.rs
index 30141ddd..305e8f44 100644
--- a/crates/aien-runtime/tests/warm_up_before_serving_test.rs
+++ b/crates/aien-runtime/tests/warm_up_before_serving_test.rs
@@ -82,7 +82,19 @@ impl AienInferenceBackend for RecordingBackend {
     }
 }
 
+/// This binary's own runtime state dir (#299): never the machine-wide
+/// `/tmp/aien-runtime-processed-ops.json` other daemons and tests write.
+fn private_state_dir() {
+    static ONCE: std::sync::Once = std::sync::Once::new();
+    ONCE.call_once(|| {
+        let dir = std::env::temp_dir().join(format!("aien-warm-up-test-{}", std::process::id()));
+        std::fs::create_dir_all(&dir).unwrap();
+        std::env::set_var("AIEN_RUNTIME_STATE_DIR", &dir);
+    });
+}
+
 fn spine() -> AienRuntimeSpine {
+    private_state_dir();
     // Small prefill chunks: the warm-up prompt spans several steps, so a
     // request accepted during the warm-up would interleave with its chunks.
     let cfg = SchedulerConfig {