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

closed derived b9706ef55873d806 #652

Imported from GitHub aien-dev/aien-sovereign-core-mv#652 (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 e6852de85dfe503347d37ed2438d1ce6f1ac8c3a · Head a116d2e6dd08b96acb3eaa0669c70dfa3315dca7

Fetch it

A git bundle of the pull request's head, 19147 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/b9706ef55873d806.bundle -o b9706ef55873d806.bundle
git fetch b9706ef55873d806.bundle refs/pull/652/head

Raw bundle · 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
652
a116d2e6dd08b96acb3eaa0669c70dfa3315dca7
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":652,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/652","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:46Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index f5e6e78e..fc96098b 100644
--- a/.crumb
+++ b/.crumb
@@ -100,8 +100,8 @@
           "purpose": ""
         },
         {
-          "digest": "34b010337138a65931ca4d0177631d839f71af021c5092583f52afd69ddd1b72",
-          "last_commit": "fe3677c3",
+          "digest": "005ba1131a8d3ce09088141a822c4ca3bf395706a18f0d976cd788e894a3dfee",
+          "last_commit": "dbc7674f",
           "name": "scripts",
           "purpose": ""
         },
@@ -118,15 +118,15 @@
           "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health "
         }
       ],
-      "children_root": "sha256:b85c8810abe85be616a42d2802e5637c38014f05e3c06d23705fef6ea5a766f2",
-      "compiled_at": "2026-10-18T15:37:23Z",
+      "children_root": "sha256:4e9c36c27aa6ad2252b2fcdd936c7c813939689959d5c34e459e3967939ff68b",
+      "compiled_at": "2026-10-18T16:57:59Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:2dbc3bfc48f62db17b27a04f0fd028ee3ad19f77af8d9cac6f93d3e77d147f7b",
+      "digest": "sha256:190837c399e68b8daca9ccc36668881dc2a408be768689e3d1454188f2e63566",
       "evidence_files": 1578,
       "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160",
-      "files": 5891,
-      "generated_at_commit": "6b58967d3b40455d5180fa7f22237f0b46912b98",
-      "source_tree": "sha256:1769c5da9a48ba6c23bc738850153c93581c418175c8ef5ac9e31926c116dfb0"
+      "files": 5893,
+      "generated_at_commit": "5b1ffc9fcb4de6fc20e06f838c1e24945b01dae6",
+      "source_tree": "sha256:c7180aba34fd638a54dd1783a1389777ce2add02f91659e409cef56ed5a57a4f"
     }
   },
   "history": [],
diff --git a/crates/aien-serve-http/src/kv_persist.rs b/crates/aien-serve-http/src/kv_persist.rs
index 11129180..197628dc 100644
--- a/crates/aien-serve-http/src/kv_persist.rs
+++ b/crates/aien-serve-http/src/kv_persist.rs
@@ -49,6 +49,7 @@ use aien_kv_store::{
     chunk_chain, chunk_key, BackendFormat, ChunkHeader, ChunkKey, ComputeConfig, EngineConfig,
     EngineIdentity, HiddenAct, HolderGuard, Incarnation, JobId, KvDtype, KvStore, LayoutStrides,
     NamespaceFields, NamespaceId, PinnedDest, PinnedSource, RecoveryProgress, StoreState, Terminal,
+    HEADER_REGION_LEN,
 };
 use aien_runtime::shared_kv::{KvPersistSettings, KV_STORE_DIR_ENV};
 use sha2::{Digest, Sha256};
@@ -512,6 +513,19 @@ pub fn settings_from_lookup(
     }))
 }
 
+/// The startup read of the server: the persistence settings ([`settings_from_lookup`]), then the
+/// store key stripped from the environment through `strip` so the key lives on only in the
+/// settings and no child process inherits it. The key is stripped whether or not
+/// `AIEN_KV_STORE_DIR` is set (sc#523); the server calls this before it loads the engine.
+pub fn take_settings(
+    get: impl Fn(&str) -> Option<String>,
+    strip: impl FnOnce(&str),
+) -> Option<Result<KvPersistSettings, String>> {
+    let s = settings_from_lookup(get);
+    strip(aien_kv_store::seal::KEY_ENV);
+    s
+}
+
 /// sha256 of a file, streamed.
 fn sha256_file(p: &Path) -> Result<[u8; 32], String> {
     let mut f = std::fs::File::open(p).map_err(|e| format!("{}: {e}", p.display()))?;
@@ -593,6 +607,8 @@ pub struct PersistCounters {
     pub park_dedup: u64,
     /// Chunks the store refused at submit (quota, queue, state).
     pub park_refused: u64,
+    /// Chunks after a refused one, never submitted: a chain with a hole cannot be restored past it.
+    pub park_dropped: u64,
     /// Chunks whose export or write failed.
     pub park_failed: u64,
     /// Generations not parked because the store was not open (recovering, degraded, failed).
@@ -723,6 +739,12 @@ impl KvPersistence {
         self.identity.geometry.block_stride()
     }
 
+    /// `QueueFull` with nothing in flight before and after the submit: no credit will come back,
+    /// so waiting cannot help (sc#523: a chunk larger than the budget; [`open`] refuses those).
+    fn credit_never_frees(&self, idle_before: bool) -> bool {
+        idle_before && self.worker.capacity().inflight_bytes == 0
+    }
+
     /// The store finished recovery (or failed) within `timeout`.
     pub fn wait_ready(&self, timeout: Duration) -> bool {
         let t0 = Instant::now();
@@ -786,6 +808,7 @@ impl KvPersistence {
             "park_bytes": c.park_bytes,
             "park_dedup": c.park_dedup,
             "park_refused": c.park_refused,
+            "park_dropped": c.park_dropped,
             "park_failed": c.park_failed,
             "park_skipped": c.park_skipped,
             "restores": c.restores,
@@ -940,7 +963,8 @@ impl KvPersistence {
     }
 
     /// Looks up and loads the longest stored prefix of `prompt` when it beats `in_ram`. Runs
-    /// without the GPU lock. `None` = plain prefill (the reason is counted).
+    /// without the GPU lock. `None` = plain prefill (the reason is counted). One deadline,
+    /// [`LOAD_TIMEOUT`] from the start, covers submitting the loads and waiting for them (sc#523).
     pub fn fetch(&self, prompt: &[u32], in_ram: usize) -> Option<Fetched> {
         if self.worker.capacity().state == StoreState::Recovering {
             self.miss("store-recovering");
@@ -1009,12 +1033,19 @@ impl KvPersistence {
                 };
                 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
                 self.pump(&mut g);
+                let idle = self.worker.capacity().inflight_bytes == 0;
                 match self.worker.submit_load(key, &header, dst, self.inc()) {
                     Ok(job) => {
                         g.loads.insert(job, None);
                         jobs.push((job, buf));
                         break;
                     }
+                    Err(aien_platform::PlatformError::QueueFull)
+                        if self.credit_never_frees(idle) =>
+                    {
+                        fail = Some("over-budget".into());
+                        break;
+                    }
                     Err(aien_platform::PlatformError::QueueFull)
                         if t_fetch.elapsed() < LOAD_TIMEOUT =>
                     {
@@ -1032,7 +1063,6 @@ impl KvPersistence {
             }
         }
         if fail.is_none() {
-            let t0 = Instant::now();
             loop {
                 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
                 self.pump(&mut g);
@@ -1051,7 +1081,7 @@ impl KvPersistence {
                     break;
                 }
                 drop(g);
-                if t0.elapsed() >= LOAD_TIMEOUT {
+                if t_fetch.elapsed() >= LOAD_TIMEOUT {
                     fail = Some("timeout".into());
                     break;
                 }
@@ -1096,6 +1126,12 @@ impl KvPersistence {
         self.miss("import");
     }
 
+    /// Counts a fetched prefix never imported because the GPU lock stayed busy (the request was
+    /// answered busy; sc#523).
+    pub fn note_lock_busy(&self) {
+        self.miss("gpu-lock-busy");
+    }
+
     /// Under the GPU lock, after a generation: exports the chunks of the engine's history that
     /// the store does not hold. Submitting them is [`Self::submit`], after the lock is released.
     pub fn snapshot(&self, e: &mut Qwen3MoeOmegaEngine) -> Vec<ParkItem> {
@@ -1169,14 +1205,15 @@ impl KvPersistence {
     }
 
     /// Hands exported chunks to the storage worker (no GPU lock held). Stops at the first
-    /// refusal: a chain with a hole cannot be restored past it.
+    /// refusal: a chain with a hole cannot be restored past it (the rest counts in `park_dropped`).
     ///
     /// A chain longer than the worker's park budget is normal on the real model (one 256-token
     /// chunk of the 30B is 25 MB, the default budget 64 MB): on `QueueFull` the chunk waits, up to
     /// [`PARK_CREDIT_WAIT`], for the earlier chunks to publish and free their credit, then retries.
     /// Runs after the GPU lock is released; the inner lock is not held while waiting.
     pub fn submit(&self, items: Vec<ParkItem>) {
-        for it in items {
+        let n = items.len();
+        for (i, it) in items.into_iter().enumerate() {
             let nb = it.tokens.div_ceil(KV_BLOCK_SIZE);
             let tail_valid = (it.tokens - (nb - 1) * KV_BLOCK_SIZE) as u32;
             // Shared so a refused submit (which drops its guard) leaves the bytes for the retry.
@@ -1186,6 +1223,7 @@ impl KvPersistence {
             loop {
                 let mut g = self.inner.lock().unwrap_or_else(|p| p.into_inner());
                 self.pump(&mut g);
+                let idle = self.worker.capacity().inflight_bytes == 0;
                 let keep = bytes.clone();
                 // SAFETY: the guard owns a reference to the bytes, so they live and stay unwritten
                 // (nothing writes through an `Arc<[u8]>`) until the store releases the holder.
@@ -1204,14 +1242,15 @@ impl KvPersistence {
                         break;
                     }
                     Err(aien_platform::PlatformError::QueueFull)
-                        if t0.elapsed() < PARK_CREDIT_WAIT =>
+                        if t0.elapsed() < PARK_CREDIT_WAIT && !self.credit_never_frees(idle) =>
                     {
                         drop(g);
                         std::thread::sleep(Duration::from_micros(500));
                     }
                     Err(_) => {
                         g.counters.park_refused += 1;
-                        // A chain with a hole cannot be restored past it.
+                        // A chain with a hole cannot be restored past it: the rest is dropped.
+                        g.counters.park_dropped += (n - i - 1) as u64;
                         return;
                     }
                 }
@@ -1273,6 +1312,25 @@ fn open_inner(
         .checked_mul(KV_BLOCK_SIZE)
         .filter(|&t| u32::try_from(t).is_ok())
         .ok_or("AIEN_KV_CHUNK_BLOCKS: chunk size overflows")?;
+    // One chunk must fit the worker's park budget (a quarter of the in-flight bytes) and its
+    // restore budget (the rest), the split of `aien_kv_store::worker` (sc#523): a chunk that
+    // never fits is `QueueFull` forever, and every turn would wait out the credit wait first.
+    let charge = (identity.geometry.payload_len(chunk_tokens) + HEADER_REGION_LEN) as u64;
+    let max = settings.worker.max_inflight_bytes;
+    let (park_budget, restore_budget) = (max / 4, max - max / 4);
+    for (on, what, budget, share) in [
+        (settings.park, "park", park_budget, "a quarter"),
+        (
+            settings.restore,
+            "restore",
+            restore_budget,
+            "three quarters",
+        ),
+    ] {
+        if on && charge > budget {
+            return Err(format!("one chunk of {chunk_tokens} tokens takes {charge} bytes in flight, more than the storage worker's {what} budget of {budget} bytes ({share} of AIEN_KV_STORE_MAX_INFLIGHT_BYTES={max}); raise it or lower AIEN_KV_CHUNK_BLOCKS"));
+        }
+    }
     let (ns, mut cfg) = {
         let fields = identity.fields(chunk_tokens as u32, &settings.namespace);
         let ns = fields
diff --git a/crates/aien-serve-http/src/main.rs b/crates/aien-serve-http/src/main.rs
index 1f32b2e5..1dd1d3b0 100644
--- a/crates/aien-serve-http/src/main.rs
+++ b/crates/aien-serve-http/src/main.rs
@@ -177,6 +177,10 @@ fn main() -> ExitCode {
         }
     };
     apply_generation_defaults(&mut args.cfg, &args.model_dir);
+    // Persistent KV (sc#505): settings only when AIEN_KV_STORE_DIR is set; the store key leaves
+    // the environment now, before any engine loads, set dir or not (sc#523): no child inherits it.
+    let persist_settings =
+        kv_persist::take_settings(|n| std::env::var(n).ok(), |k| std::env::remove_var(k));
     // OWN-8B stage S negative controls: read once, refused outright without debug assertions.
     match aien_serve_http::sampling::install_mutant_from_env() {
         Ok(None) => {}
@@ -250,11 +254,8 @@ fn main() -> ExitCode {
             args.prefill,
         ) {
             Ok(mut door) => {
-                // Persistent KV (sc#505): only when AIEN_KV_STORE_DIR is set; otherwise nothing else is read.
-                if let Some(settings) = kv_persist::settings_from_lookup(|n| std::env::var(n).ok())
-                {
-                    // The key lives on only in the settings; no child inherits it.
-                    std::env::remove_var(aien_kv_store::seal::KEY_ENV);
+                // Persistent KV (sc#505): only when AIEN_KV_STORE_DIR was set at startup.
+                if let Some(settings) = persist_settings {
                     let line = enable_persistence(&mut door, settings, &args);
                     eprintln!("aien-serve-http: {line}");
                 }
diff --git a/crates/aien-serve-http/src/omega_engine.rs b/crates/aien-serve-http/src/omega_engine.rs
index 4b699fe8..856a8afc 100644
--- a/crates/aien-serve-http/src/omega_engine.rs
+++ b/crates/aien-serve-http/src/omega_engine.rs
@@ -362,8 +362,16 @@ impl Engine for OmegaDoor {
             pk.fetch(prompt, in_ram)
         });
         let t_lock = Instant::now();
-        let lock =
-            GpuLock::acquire_at(&self.lock_path, self.lock_wait).map_err(EngineError::Busy)?;
+        let lock = match GpuLock::acquire_at(&self.lock_path, self.lock_wait) {
+            Ok(l) => l,
+            Err(e) => {
+                // A prefix loaded but never imported is a restore miss, not lost from the counters.
+                if let (Some(pk), Some(_)) = (persist, fetched.as_ref()) {
+                    pk.note_lock_busy();
+                }
+                return Err(EngineError::Busy(e));
+            }
+        };
         let lock_wait_ms = t_lock.elapsed().as_millis();
         if let (Some(pk), Some(f)) = (persist, fetched.as_ref()) {
             // All or nothing: on error the engine is reset and the prompt is prefilled.
diff --git a/crates/aien-serve-http/tests/kv_persist.rs b/crates/aien-serve-http/tests/kv_persist.rs
index 45a10f9f..2120ff3f 100644
--- a/crates/aien-serve-http/tests/kv_persist.rs
+++ b/crates/aien-serve-http/tests/kv_persist.rs
@@ -11,13 +11,13 @@ use std::net::TcpStream;
 use std::path::{Path, PathBuf};
 use std::sync::atomic::{AtomicUsize, Ordering};
 use std::sync::{Arc, Mutex};
-use std::time::Duration;
+use std::time::{Duration, Instant};
 
 use aien_inference_abi::qwen3_moe_omega::{host_test_engine, OmegaEngine, WeightFormat};
 use aien_serve_http::codec::ByteCodec;
 use aien_serve_http::engine::{Engine, GenerateParams};
 use aien_serve_http::kv_persist::{self, OmegaBuild, PersistState};
-use aien_serve_http::omega_engine::OmegaDoor;
+use aien_serve_http::omega_engine::{GpuLock, OmegaDoor};
 use aien_serve_http::sampling::sample_next;
 use aien_serve_http::server::{serve, serve_until, ServerConfig};
 
@@ -119,7 +119,17 @@ fn door(scratch: &Scratch, s: &Setup) -> (OmegaDoor, String) {
 
 /// [`door`] with the store's test-only stall (`AIEN_KV_TEST_FAULT`, sc#507).
 fn door_with_fault(scratch: &Scratch, s: &Setup, fault: Option<&str>) -> (OmegaDoor, String) {
-    let mut d = OmegaDoor::from_parts(engine(s.weights), scratch.lock(), Duration::from_secs(5));
+    door_at(scratch, s, fault, Duration::from_secs(5))
+}
+
+/// [`door_with_fault`] whose generations wait `lock_wait` for the GPU lock.
+fn door_at(
+    scratch: &Scratch,
+    s: &Setup,
+    fault: Option<&str>,
+    lock_wait: Duration,
+) -> (OmegaDoor, String) {
+    let mut d = OmegaDoor::from_parts(engine(s.weights), scratch.lock(), lock_wait);
     let vars: HashMap<String, String> = s.store_vars.iter().cloned().collect();
     let settings =
         kv_persist::settings_from_lookup(|n| vars.get(n).cloned()).expect("store dir is set");
@@ -451,6 +461,7 @@ fn health_reports_the_persistence_counters_when_on() {
     for k in [
         "parked_chunks",
         "park_bytes",
+        "park_dropped",
         "restores",
         "restored_tokens",
         "restore_bytes",
@@ -873,3 +884,178 @@ fn a_turn_larger_than_the_park_and_restore_budgets_is_parked_and_restored_in_ful
         "restored continuation differs from the uninterrupted run"
     );
 }
+
+/// What the storage worker charges for one chunk of these tests: its payload (one block at
+/// `AIEN_KV_CHUNK_BLOCKS=1`, the same for every chunk) plus the header region. Probed by parking a
+/// turn on a door with the default budgets.
+fn chunk_charge() -> u64 {
+    let probe = Scratch::new("charge-probe");
+    let (a, line) = door(&probe, &Setup::new(&probe.store(), &gen_key()));
+    assert!(line.contains("persistent KV: on"), "{line}");
+    let _ = turn(&a, &prompt1());
+    assert!(pk_of(&a).wait_idle(WAIT));
+    let c = counters(&a);
+    assert!(c.parked_chunks > 0 && c.park_refused == 0, "{c:?}");
+    c.park_bytes / c.parked_chunks + aien_kv_store::record::HEADER_REGION_LEN as u64
+}
+
+/// sc#523 item 2: a chunk that can never fit the worker's park budget (a quarter of
+/// `AIEN_KV_STORE_MAX_INFLIGHT_BYTES`) or restore budget (the rest) is refused at open, not
+/// spun on at every turn until the credit wait runs out.
+#[test]
+fn a_chunk_larger_than_the_park_or_restore_budget_refuses_at_open() {
+    let c = chunk_charge();
+    let scratch = Scratch::new("oversize");
+    let s = Setup::new(&scratch.store(), &gen_key());
+    // Park budget one byte short of a chunk, restore budget three chunks: parking can never run.
+    let short_park = s
+        .clone()
+        .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &(4 * c - 4).to_string());
+    let (d, line) = door(&scratch, &short_park);
+    assert!(
+        line.contains("REFUSED") && line.contains("park budget"),
+        "{line}"
+    );
+    assert!(matches!(d.persistence(), PersistState::Refused(_)));
+    let t0 = Instant::now();
+    assert_eq!(
+        turn(&d, &prompt1()),
+        turn(&plain_door(&scratch), &prompt1())
+    );
+    assert!(t0.elapsed() < Duration::from_secs(5), "{:?}", t0.elapsed());
+    drop(d);
+    // The same budgets with parking off: restore alone fits, so persistence is on.
+    let (d, line) = door(&scratch, &short_park.clone().with_var("AIEN_KV_PARK", "0"));
+    assert!(line.contains("persistent KV: on"), "{line}");
+    drop(d);
+    // Restore budget (three quarters of one chunk) short of a chunk: restoring can never run.
+    let short_restore = s
+        .with_var("AIEN_KV_PARK", "0")
+        .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &c.to_string());
+    let (d, line) = door(&scratch, &short_restore);
+    assert!(
+        line.contains("REFUSED") && line.contains("restore budget"),
+        "{line}"
+    );
+    assert!(matches!(d.persistence(), PersistState::Refused(_)));
+}
+
+/// sc#523 item 3: one fetch holds the request for at most [`kv_persist::LOAD_TIMEOUT`] in all,
+/// submit phase and wait phase together. The restore budget holds one chunk, so each of the three
+/// loads of turn 2 waits for the one before; each load stalls 4 s, so the last is submitted at
+/// about 8 s and lands at about 12 s.
+#[test]
+fn one_fetch_waits_at_most_the_load_timeout_over_submit_and_wait() {
+    let c = chunk_charge();
+    let scratch = Scratch::new("onedeadline");
+    let s = Setup::new(&scratch.store(), &gen_key());
+    let (_, h1) = park_turn1(&scratch, &s);
+    let narrow = s
+        .clone()
+        .with_var("AIEN_KV_PARK", "0")
+        .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &(2 * c).to_string());
+    let (b, line) = door_with_fault(&scratch, &narrow, Some("load:4000:3"));
+    assert!(line.contains("persistent KV: on"), "{line}");
+    let t0 = Instant::now();
+    let r2 = turn(&b, &prompt2(&h1));
+    let took = t0.elapsed();
+    let c = counters(&b);
+    assert_eq!(
+        (c.restores, c.restore_misses.get("timeout").copied()),
+        (0, Some(1)),
+        "turn 2 took {took:?}: {c:?}"
+    );
+    assert!(
+        took < kv_persist::LOAD_TIMEOUT + Duration::from_secs(2),
+        "one fetch held the request {took:?}"
+    );
+    assert_eq!(r2, plain_turn2(&scratch, &h1));
+}
+
+/// sc#523 item 4: a refused park drops the rest of its chain (a chain with a hole cannot be
+/// restored past it); the dropped chunks are counted. The park budget holds one chunk and the
+/// first park stalls past [`kv_persist::PARK_CREDIT_WAIT`], so chunk 2 is refused and the rest
+/// is dropped.
+#[test]
+fn a_refused_park_counts_the_chunks_it_drops() {
+    let c = chunk_charge();
+    let scratch = Scratch::new("parkdrop");
+    let s = Setup::new(&scratch.store(), &gen_key())
+        .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &(4 * c).to_string());
+    let stall = kv_persist::PARK_CREDIT_WAIT + Duration::from_secs(2);
+    let (a, line) = door_with_fault(&scratch, &s, Some(&format!("p3:{}:1", stall.as_millis())));
+    assert!(line.contains("persistent KV: on"), "{line}");
+    let _ = turn(&a, &prompt1());
+    let chunks = a.history().len().div_ceil(16) as u64;
+    assert!(chunks >= 3, "{chunks}");
+    assert!(pk_of(&a).wait_idle(WAIT));
+    let v = pk_of(&a).status_json();
+    assert_eq!(v["chunk_tokens"], 16, "{v}");
+    assert_eq!(
+        (
+            v["parked_chunks"].as_u64(),
+            v["park_refused"].as_u64(),
+            v["park_dropped"].as_u64()
+        ),
+        (Some(1), Some(1), Some(chunks - 2)),
+        "every chunk of the turn is accounted for: {v}"
+    );
+}
+
+/// sc#523 item 5: a prefix loaded from the store but never imported because the GPU lock stayed
+/// busy is counted as a restore miss (`gpu-lock-busy`), not lost from the counters.
+#[test]
+fn a_fetched_prefix_left_unused_by_a_busy_gpu_lock_is_a_miss() {
+    let scratch = Scratch::new("lockbusy");
+    let s = Setup::new(&scratch.store(), &gen_key());
+    let (_, h1) = park_turn1(&scratch, &s);
+    let (b, _) = door_at(&scratch, &s, None, Duration::from_millis(200));
+    let held = GpuLock::acquire_at(&scratch.lock(), Duration::from_secs(1)).unwrap();
+    let r = b.generate(&prompt2(&h1), &greedy(6), &mut |_| true);
+    assert!(
+        r.is_err(),
+        "the door must answer busy while the lock is held"
+    );
+    let c = counters(&b);
+    assert_eq!(
+        (c.restores, c.restore_misses.get("gpu-lock-busy").copied()),
+        (0, Some(1)),
+        "{c:?}"
+    );
+    drop(held);
+    assert_eq!(turn(&b, &prompt2(&h1)), plain_turn2(&scratch, &h1));
+    assert_eq!(counters(&b).restores, 1, "the store still serves");
+}
+
+/// sc#523 item 10: the startup read strips the store key from the environment whether or not
+/// `AIEN_KV_STORE_DIR` is set (a key exported for nothing must not reach a child either).
+#[test]
+fn the_startup_read_strips_the_store_key_with_or_without_the_store_dir() {
+    let key = gen_key();
+    for dir in [None, Some(""), Some("/nonexistent/pkv523")] {
+        let stripped = Mutex::new(Vec::<String>::new());
+        let got = kv_persist::take_settings(
+            |n| match n {
+                "AIEN_KV_STORE_DIR" => dir.map(String::from),
+                "AIEN_KV_STORE_KEY" => Some(key.clone()),
+                _ => None,
+            },
+            |k| stripped.lock().unwrap().push(k.to_string()),
+        );
+        assert_eq!(
+            *stripped.lock().unwrap(),
+            vec!["AIEN_KV_STORE_KEY".to_string()],
+            "dir {dir:?}"
+        );
+        match dir {
+            Some(d) if !d.is_empty() => {
+                let s = got.expect("dir set").expect("settings parse");
+                assert!(
+                    matches!(s.store_key, Some(Ok(_))),
+                    "the key is in the settings"
+                );
+            }
+            _ => assert!(got.is_none(), "dir {dir:?}"),
+        }
+    }
+}
diff --git a/scripts/.crumb b/scripts/.crumb
index 8ab3769d..445939f0 100644
--- a/scripts/.crumb
+++ b/scripts/.crumb
@@ -4,14 +4,14 @@
     "generated": {
       "children": [],
       "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "compiled_at": "2026-10-17T11:27:44Z",
+      "compiled_at": "2026-10-18T11:32:26Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:34b010337138a65931ca4d0177631d839f71af021c5092583f52afd69ddd1b72",
+      "digest": "sha256:005ba1131a8d3ce09088141a822c4ca3bf395706a18f0d976cd788e894a3dfee",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 53,
-      "generated_at_commit": "fe3677c38c6cd8219db0959d954c8d83e1c8a52c",
-      "source_tree": "sha256:09dbafbfb7f2503e6def8005c3bee8fe9dbc7d4e2b1f9831ff76d40d02f02097"
+      "files": 54,
+      "generated_at_commit": "6acac4755ac490718eec7b3afc011feabab02f63",
+      "source_tree": "sha256:2ac7bc64c3f3e5e8e13b84e6a81403d9d9be24b8eb2c4bac07cf52fb096229f9"
     }
   },
   "parent": {
diff --git a/scripts/own30b-pkv-bench.sh b/scripts/own30b-pkv-bench.sh
index f0859f75..dc231ccb 100755
--- a/scripts/own30b-pkv-bench.sh
+++ b/scripts/own30b-pkv-bench.sh
@@ -84,7 +84,7 @@ stop_samplers() {
 	if [ -n "$SAMPLER" ]; then kill "$SAMPLER" 2>/dev/null || true; fi
 	SAMPLER=
 }
-trap 'stop_samplers; [ -n "$IOSTAT" ] && kill "$IOSTAT" 2>/dev/null; stop_server; rm -rf "$work"' EXIT
+trap 'stop_samplers; [ -n "$IOSTAT" ] && kill "$IOSTAT" 2>/dev/null; stop_server || PKV_LEAK=1; rm -rf "$work"; pkv_trap_status' EXIT
 
 if command -v iostat >/dev/null; then
 	iostat -dxk -t 5 >"$dir/iostat.txt" 2>&1 &
diff --git a/scripts/own30b-pkv-lib.sh b/scripts/own30b-pkv-lib.sh
index efbcc23c..06f6a6b4 100644
--- a/scripts/own30b-pkv-lib.sh
+++ b/scripts/own30b-pkv-lib.sh
@@ -97,7 +97,7 @@ pkv_begin() {
 	work=$(mktemp -d /tmp/pkv-chip.XXXXXX)
 	chmod 700 "$work"
 	PIDF="$work/server.pid"
-	trap 'stop_server; rm -rf "$work"' EXIT
+	trap 'stop_server || PKV_LEAK=1; rm -rf "$work"; pkv_trap_status' EXIT
 	KEY=
 	if [ "${PKV_CHECK_EPHEMERAL_KEY:-0}" = 1 ]; then
 		KEY=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
@@ -114,14 +114,20 @@ SERVED_MODEL=${PKV_SERVED_MODEL:-qwen3-30b-a3b-instruct-2507}
 
 server_pid() { [ -f "$PIDF" ] && cat "$PIDF"; }
 
-# Exits the run if anything still owns our port after a stop: never start the next server
-# beside a leftover one (two 30 GB loads on the chip).
+# Fails (returns 1) if anything still owns our port after a stop: never start the next server
+# beside a leftover one (two 30 GB loads on the chip). Mid-run the callers' set -e stops the run;
+# the EXIT trap records it and carries on with its cleanup (an exit inside the trap would end the
+# trap there and leave the other server and the work dir behind, sc#523).
 port_released() {
 	for _ in $(seq 1 50); do ss -Hltn "sport = :$PORT" | grep -q . || return 0; sleep 0.2; done
 	echo "something still listens on :$PORT after the stop; stopping the run" >&2
-	exit 1
+	return 1
 }
 
+# The last step of every EXIT trap: a stop that left the port held (PKV_LEAK=1) fails the run,
+# after every other cleanup step has run.
+pkv_trap_status() { [ -z "${PKV_LEAK:-}" ] || exit 1; }
+
 # Stops our server: SIGTERM (graceful drain, #509), SIGKILL after PKV_STOP_WAIT_S (default 120).
 stop_server() {
 	[ -n "${PIDF:-}" ] && [ -f "$PIDF" ] || return 0
@@ -219,11 +225,13 @@ chat() { # <out-name> <messages-json>: prints the content
 	printf '%s\n' "$c"
 }
 
-wait_parks() { # until parked_chunks > 0 and unchanged for 3 s
+wait_parks() { # until parked_chunks is a number > 0 and unchanged for 3 s
 	local last=-1 now
 	for _ in $(seq 1 60); do
-		now=$(curl -s -m 5 "$base/health" | jq -r '.persistent_kv.parked_chunks')
-		[ "$now" != 0 ] && [ "$now" = "$last" ] && return 0
+		now=$(curl -s -m 5 "$base/health" | jq -r '.persistent_kv.parked_chunks' 2>/dev/null || true)
+		# A failed request, null or a missing counter is not a count (sc#523): never settled.
+		case $now in '' | *[!0-9]*) now=-1 ;; esac
+		[ "$now" -gt 0 ] && [ "$now" = "$last" ] && return 0
 		last=$now
 		sleep 3
 	done
diff --git a/scripts/own30b-pkv-two-process.sh b/scripts/own30b-pkv-two-process.sh
index 1741bc4a..69a57439 100755
--- a/scripts/own30b-pkv-two-process.sh
+++ b/scripts/own30b-pkv-two-process.sh
@@ -48,7 +48,7 @@ PORT=$PORT1 base="http://127.0.0.1:$PORT1"
 pkv_begin
 
 use() { PORT=$1 base="http://127.0.0.1:$1" PIDF="$work/server-$1.pid"; }
-trap 'use $PORT2; stop_server; use $PORT1; stop_server; rm -rf "$work"' EXIT
+trap 'use $PORT2; stop_server || PKV_LEAK=1; use $PORT1; stop_server || PKV_LEAK=1; rm -rf "$work"; pkv_trap_status' EXIT
 memavail() { awk '/^MemAvailable:/ {printf "%.1f", $2/1048576}' /proc/meminfo; }
 
 use "$PORT1"
diff --git a/scripts/test-pkv-lib.sh b/scripts/test-pkv-lib.sh
new file mode 100755
index 00000000..1338279f
--- /dev/null
+++ b/scripts/test-pkv-lib.sh
@@ -0,0 +1,74 @@
+#!/usr/bin/env bash
+# test-pkv-lib.sh: host-only self-test of scripts/own30b-pkv-lib.sh (sc#523 items 7 and 8) with
+# stub curl, ss and sleep on PATH: no server, no chip, no network, no real port. Proves:
+# wait_parks settles only on a number (a null or empty parked_chunks never counts as settled),
+# and a port still held at exit makes the EXIT trap fail the run without skipping its cleanup.
+set -euo pipefail
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+LIB="$ROOT/scripts/own30b-pkv-lib.sh"
+T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
+fail=0
+chk() { if eval "$1"; then echo "  ok   $2"; else echo "  FAIL $2"; fail=1; fi; }
+
+mkdir "$T/bin"
+# curl: the live port never answers; any other URL answers with $T/health when it exists.
+cat >"$T/bin/curl" <<EOF
+#!/bin/sh
+case "\$*" in *:18091*) exit 7 ;; esac
+[ -f "$T/health" ] || exit 7
+cat "$T/health"
+EOF
+# ss: a listener on the port while $T/listening exists.
+cat >"$T/bin/ss" <<EOF
+#!/bin/sh
+[ -f "$T/listening" ] && echo "LISTEN 0 128 127.0.0.1:18098 0.0.0.0:*"
+exit 0
+EOF
+printf '#!/bin/sh\nexit 0\n' >"$T/bin/sleep"
+chmod +x "$T/bin/curl" "$T/bin/ss" "$T/bin/sleep"
+
+# wait_parks against a /health body; prints its exit status.
+parks() {
+	printf '%s\n' "$1" >"$T/health"
+	(PATH="$T/bin:$PATH"; set -euo pipefail; . "$LIB"; wait_parks) >/dev/null 2>&1 && echo 0 || echo $?
+}
+echo "test-pkv-lib: wait_parks (item 7)"
+chk '[ "$(parks "{\"persistent_kv\":{\"parked_chunks\":3}}")" = 0 ]' "a steady number settles"
+chk '[ "$(parks "{\"persistent_kv\":{\"parked_chunks\":0}}")" != 0 ]' "zero never settles"
+chk '[ "$(parks "{\"persistent_kv\":{\"parked_chunks\":null}}")" != 0 ]' "null never settles"
+chk '[ "$(parks "{\"persistent_kv\":{}}")" != 0 ]' "a missing counter never settles"
+chk '[ "$(parks "{\"status\":\"ok\"}")" != 0 ]' "persistence absent never settles"
+chk '[ "$(parks "")" != 0 ]' "an empty reply never settles"
+rm -f "$T/health"
+
+echo "test-pkv-lib: the EXIT trap with the port still held (item 8)"
+# pkv_begin with a free port, then something keeps listening after our server is gone.
+rc=0
+(
+	PATH="$T/bin:$PATH"
+	set -euo pipefail
+	. "$LIB"
+	dir="$T/ev" BIN=/bin/true
+	pkv_begin
+	echo "$work" >"$T/work"
+	echo 999999 >"$PIDF" # not an aien-serve-http: stop_server sends no signal
+	touch "$T/listening"
+) >"$T/trap.out" 2>&1 || rc=$?
+chk '[ "$rc" != 0 ]' "the run fails (exit $rc)"
+chk 'grep -q "still listens" "$T/trap.out"' "the leftover listener is reported"
+chk '[ -s "$T/work" ] && [ ! -e "$(cat "$T/work")" ]' "the trap still removed the private work dir"
+
+rm -f "$T/listening"
+rc=0
+(
+	PATH="$T/bin:$PATH"
+	set -euo pipefail
+	. "$LIB"
+	dir="$T/ev2" BIN=/bin/true
+	pkv_begin
+	echo "$work" >"$T/work2"
+) >/dev/null 2>&1 || rc=$?
+chk '[ "$rc" = 0 ]' "a clean stop exits 0 (control)"
+chk '[ ! -e "$(cat "$T/work2")" ]' "and removes the work dir"
+
+[ "$fail" = 0 ] && echo "test-pkv-lib: PASS" || { echo "test-pkv-lib: FAIL"; exit 1; }
diff --git a/tests/gates/run.sh b/tests/gates/run.sh
index 3514e894..86368571 100755
--- a/tests/gates/run.sh
+++ b/tests/gates/run.sh
@@ -67,6 +67,7 @@ case "$step" in
     ;;
   aien-verify-tests)   sh tools/aien-verify/tests/run.sh ;;
   pins-selftest)       bash scripts/test-pins.sh ;;
+  pkv-lib)             bash scripts/test-pkv-lib.sh ;;
   native-identity)     bash scripts/test-native-identity.sh ;;
   install-test)        bash scripts/test-install.sh ;;
   scoring-v5)          bash docs/campaigns/scoring/test-scoring-v5.sh ;;
diff --git a/tests/gates/sc-pkv-lib.gate b/tests/gates/sc-pkv-lib.gate
new file mode 100644
index 00000000..a177c19a
--- /dev/null
+++ b/tests/gates/sc-pkv-lib.gate
@@ -0,0 +1,22 @@
+# tests/gates/sc-pkv-lib.gate
+# No hosted mirror: host-only self-test of the persistent KV chip-script helpers (stub curl, ss, sleep;
+# no server, chip, network or real port). Kept out of ci.yml so the judge decides pkv heads without an
+# operator run (#613).
+gate: SC-PKV-LIB
+manifest_version: 2
+owner: aien-sovereign-core
+requires:
+  - host
+inputs:
+  - scripts/own30b-pkv-lib.sh
+  - scripts/test-pkv-lib.sh
+  - tests/gates/
+run:
+  exec: tests/gates/run.sh
+  args: ["pkv-lib"]
+expects:
+  exit: 0
+  verdict: PASS
+timeout: 10m
+exactness: EXACT
+cache_scope: machine