diff --git a/crates/aien-serve-http/src/kv_persist.rs b/crates/aien-serve-http/src/kv_persist.rs index e87812f2..8a759678 100644 --- a/crates/aien-serve-http/src/kv_persist.rs +++ b/crates/aien-serve-http/src/kv_persist.rs @@ -63,6 +63,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}; @@ -526,6 +527,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, + strip: impl FnOnce(&str), +) -> Option> { + let s = settings_from_lookup(get); + strip(aien_kv_store::seal::KEY_ENV); + s +} + /// Hash exactly the bounded regular file accepted by the checkpoint loader. fn sha256_file(p: &Path) -> Result<[u8; 32], String> { aien_inference_abi::checkpoint_sha256(p).map_err(|e| e.to_string()) @@ -595,6 +609,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). @@ -725,6 +741,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(); @@ -788,6 +810,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, @@ -942,7 +965,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 { if self.worker.capacity().state == StoreState::Recovering { self.miss("store-recovering"); @@ -1011,12 +1035,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 => { @@ -1034,7 +1065,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); @@ -1053,7 +1083,7 @@ impl KvPersistence { break; } drop(g); - if t0.elapsed() >= LOAD_TIMEOUT { + if t_fetch.elapsed() >= LOAD_TIMEOUT { fail = Some("timeout".into()); break; } @@ -1098,6 +1128,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 { @@ -1171,14 +1207,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) { - 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. @@ -1188,6 +1225,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. @@ -1206,14 +1244,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; } } @@ -1275,6 +1314,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 35144c3d..525219c1 100644 --- a/crates/aien-serve-http/src/main.rs +++ b/crates/aien-serve-http/src/main.rs @@ -277,6 +277,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) => {} @@ -425,11 +429,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 3cfaa429..ac6cf051 100644 --- a/crates/aien-serve-http/src/omega_engine.rs +++ b/crates/aien-serve-http/src/omega_engine.rs @@ -466,8 +466,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 2f2a72b6..c3e727a6 100644 --- a/crates/aien-serve-http/tests/kv_persist.rs +++ b/crates/aien-serve-http/tests/kv_persist.rs @@ -32,7 +32,7 @@ use aien_inference_abi::qwen3_moe_omega::{host_test_engine, OmegaEngine, WeightF 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}; @@ -134,7 +134,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 = s.store_vars.iter().cloned().collect(); let settings = kv_persist::settings_from_lookup(|n| vars.get(n).cloned()).expect("store dir is set"); @@ -468,6 +478,7 @@ fn health_reports_the_persistence_counters_when_on() { for k in [ "parked_chunks", "park_bytes", + "park_dropped", "restores", "restored_tokens", "restore_bytes", @@ -912,3 +923,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::::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/own30b-pkv-bench.sh b/scripts/own30b-pkv-bench.sh index ffd3fcc5..3f09fce9 100755 --- a/scripts/own30b-pkv-bench.sh +++ b/scripts/own30b-pkv-bench.sh @@ -99,7 +99,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 3cab59b8..e477bb53 100644 --- a/scripts/own30b-pkv-lib.sh +++ b/scripts/own30b-pkv-lib.sh @@ -113,7 +113,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') @@ -130,14 +130,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 @@ -235,11 +241,13 @@ chat() { # : 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 7edd38c9..73441508 100755 --- a/scripts/own30b-pkv-two-process.sh +++ b/scripts/own30b-pkv-two-process.sh @@ -63,7 +63,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" <"$T/bin/ss" <"$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; }