Repository navigation
GPU governance, resource observability, multimodal genome architecture - #281
Conversation
…m hot-reload Three bugs preventing trained adapters from influencing inference: - getEffectiveModel() now receives active adapter domain for Rust 4-tier model selection - scoreInteraction() assigns quality ratings to training data (enables 20-example micro-tuning) - Post-training callback uses AdapterStore filesystem discovery instead of empty DB layers array
…iminate build race Every GPU consumer is now visible to the pressure system: - GpuModelTracker interface compresses allocation boilerplate to one call per consumer - Orpheus TTS (LLM+SNAC), Pocket TTS, Piper TTS, Kokoro TTS all tracked - Embedding models tracked with size estimates for 7 known model variants - LoRA rebuild transient spikes tracked (auto-release on method exit) Safety fixes: - CandleAdapter returns error at critical pressure instead of loading anyway - LearningScheduler defers training at >60% GPU pressure (lowest priority workload) - TOCTOU race in allocate() fixed: optimistic-allocate-then-rollback pattern - Memory ordering upgraded from Relaxed to AcqRel for safety-critical atomics - GpuStats exports pressure thresholds (60/80/95%) so TS stops hardcoding Dead code removed: - gpu_allocator.rs deleted (478 lines, superseded by memory_manager.rs, zero callers) Build pipeline fix: - parallel-start.sh restructured: Rust build completes before TS prebuild starts - Eliminates cargo target directory contention that caused 300s binding gen timeout - Voice models still download in parallel with cargo build (no contention) - TS build + VRM conversion run in parallel after Rust completes
…ations GpuPriority enum (Realtime/Interactive/Background/Batch) with per-level pressure gates. Realtime (render loop, audio) only stops at 95% OOM. Batch (training) yields the bus at 50%. All 14 GPU callers updated with correct priority assignments. Per-priority allocation counters in GpuStats. 43 tests pass including 12 new priority-specific tests.
…mmand layers IPC mixin was silently dropping new GpuStats fields during snake_case→camelCase conversion. Updated all three layers: bindings/modules/gpu.ts, GpuStatsTypes.ts, GpuStatsServerCommand.ts.
…tem resources IPC
Layer 1 — GPU Eviction Registry (Rust):
- EvictionRegistry tracks all GPU consumers with priority, bytes, last-used timestamps
- Eviction scoring: age_seconds / (priority_weight * 10) for priority-aware ordering
- IPC commands: gpu/eviction-registry, gpu/eviction-candidates
- TS mixin: gpuEvictionRegistry(), gpuEvictionCandidates()
- Registered at all allocation sites: Candle, TTS engines, Bevy, embeddings, genome paging
Layer 2 — Pressure Watchers (TypeScript):
- GpuPressureWatcher: adaptive polling (10s/3s/1s/500ms), Events on threshold crossings
- ResourcePressureWatcher: CPU + memory monitoring, same adaptive pattern
- Events: gpu:pressure:{level}, cpu:pressure:{level}, memory:pressure:{level}
- Migrated LearningScheduler + GenomeTrainServerCommand from inline polling to watchers
System Resources Module (Rust + TypeScript, full pipeline):
- SystemResourceMonitor: sysinfo 0.33, cached readings, explicit refresh
- IPC commands: system/cpu, system/memory, system/resources
- Process CPU baseline fix: double-refresh on first query for accurate deltas
- TS IPC mixin: systemCpu(), systemMemory(), systemResources()
- ./jtag system/resources command: generated scaffold, wired to IPC mixin
- 22 Rust tests, all passing
Verified live: CPU 87% (M1 Pro), memory 64%, top processes with real CPU %,
GPU eviction candidates sorted by priority, pressure events firing in logs.
…n control Maps the full stack from priority-gated allocation (Rust, done) through pressure watchers (TS, done) to the planned GpuGovernor mechanical strategy and LoRA-trained Qwen sentinel for AI-driven resource decisions. Covers telemetry frame design, decision output schema, training data self-generation from pressure events, and sentinel pipeline definition.
…osystem design Updates architecture doc with specific Qwen 3.5 Small Model Series (0.8B/2B/4B/9B) for tiered workloads from always-loaded governance sentinels to persona backbones. Adds multimodal LoRA concept (vision/audio/document adapters as genome layers), self-improving ecosystem vision, and Reticulum grid resource coordination.
The genome isn't just text personality — in a fully immersive environment with avatars, spatial audio, and real-time video, a persona's identity spans every modality. Adds Section 7 covering voice LoRA (Orpheus), vision LoRA (Qwen3.5-4B multimodal), generation LoRA (SDXL style), and governance LoRA (Qwen3.5-0.8B resource management). Each modality uses the same GenomeLayerEntity, AdapterStore, genome paging, and resource governance infrastructure. The interface is proven — we're adding implementations per modality.
There was a problem hiding this comment.
Pull request overview
This PR introduces a multi-layer resource governance/observability stack: priority-gated GPU allocations with an eviction registry + pressure watchers, plus a new system resources (CPU/memory/process) IPC/command surface, and expands the genome system with quantization metadata, conversion pipelines, capability embeddings, and fitness tracking.
Changes:
- Add GPU governance primitives (priority scheduling gates, eviction registry + IPC, shared tracking helper, pressure watcher integration).
- Add system resource monitoring end-to-end (Rust sysinfo monitor + IPC module, TS bindings,
system/resourcescommand, and a TS pressure watcher). - Extend genome learning lifecycle (QLoRA quantization metadata, adapter conversion pipeline/command, capability embeddings + registry search, and fitness persistence).
Reviewed changes
Copilot reviewed 92 out of 96 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| src/workers/shared/mod.rs | Removes old worker-level GPU allocator references; points to continuum-core GPU manager. |
| src/workers/continuum-core/src/system_resources/mod.rs | Adds system_resources module exports. |
| src/workers/continuum-core/src/runtime/runtime.rs | Registers system module name in expected module list. |
| src/workers/continuum-core/src/persona/genome_paging.rs | Adds GPU priority allocation + eviction registry register/unregister for adapters. |
| src/workers/continuum-core/src/modules/system_resources.rs | New IPC module for CPU/memory/resources snapshot (+ tests). |
| src/workers/continuum-core/src/modules/mod.rs | Exposes system_resources module. |
| src/workers/continuum-core/src/modules/gpu.rs | Adds eviction registry/candidates IPC commands (+ tests). |
| src/workers/continuum-core/src/modules/embedding.rs | Adds GPU allocation tracking + eviction registry entry for embedding models. |
| src/workers/continuum-core/src/live/video/bevy_renderer.rs | Adds GPU priority allocation + eviction registry registration for render targets/models. |
| src/workers/continuum-core/src/live/audio/tts/pocket.rs | Uses GpuModelTracker for Pocket-TTS allocation tracking + touch on use. |
| src/workers/continuum-core/src/live/audio/tts/piper.rs | Uses GpuModelTracker for Piper allocation tracking + touch on use. |
| src/workers/continuum-core/src/live/audio/tts/orpheus.rs | Uses GpuModelTracker for Orpheus model allocations + touch on use. |
| src/workers/continuum-core/src/live/audio/tts/kokoro.rs | Replaces single OnceLock guard with GpuModelTracker + touch on use. |
| src/workers/continuum-core/src/lib.rs | Exposes system_resources module from crate root. |
| src/workers/continuum-core/src/ipc/mod.rs | Wires GPU manager into embedding + registers SystemResourceModule. |
| src/workers/continuum-core/src/inference/vendored/quantized_llama.rs | Adds GGUF mixed-precision LoRA merge + parsing + tests. |
| src/workers/continuum-core/src/inference/candle_adapter.rs | Adds GPU priority allocations, eviction registry bookkeeping, and pressure-gated failures. |
| src/workers/continuum-core/src/inference/backends/mod.rs | Extends backend LoRA rebuild API to accept optional GPU manager. |
| src/workers/continuum-core/src/inference/backends/llama_safetensors.rs | Adds transient “spike” allocation tracking during rebuild_with_lora. |
| src/workers/continuum-core/src/inference/backends/llama_gguf.rs | Implements GGUF LoRA merge rebuild_with_lora + transient spike tracking. |
| src/workers/continuum-core/src/gpu/tracker.rs | New reusable GPU allocation lifecycle helper (GpuModelTracker) + tests. |
| src/workers/continuum-core/src/gpu/mod.rs | Re-exports eviction registry + priority/thresholds + tracker types. |
| src/workers/continuum-core/src/gpu/eviction_registry.rs | New eviction registry snapshot/candidate scoring + ts-rs exports + tests. |
| src/workers/continuum-core/bindings/modules/system_resources.ts | TS IPC mixin for system resources (type mapping + request helpers). |
| src/workers/continuum-core/bindings/modules/gpu.ts | Extends GPU TS mixin with thresholds, allocations-by-priority, eviction IPC. |
| src/workers/continuum-core/bindings/RustCoreIPC.ts | Composes SystemResourceMixin into client. |
| src/workers/continuum-core/Cargo.toml | Adds sysinfo dependency. |
| src/system/user/server/modules/being/LimbicSystem.ts | Hot-load adapters post-training, add adoptAdapter, recompute composite embedding. |
| src/system/user/server/modules/PersonaResponseGenerator.ts | Adds fitness tracking for successful inference calls. |
| src/system/user/server/modules/PersonaGenome.ts | Stores layerId on adapter; updates GPU-management comment. |
| src/system/user/server/modules/LoRAAdapter.ts | Adds layerId back-reference getter for fitness tracking. |
| src/system/user/server/PersonaUser.ts | Adds corpus reload retry after Hippocampus schema init. |
| src/system/sentinel/pipelines/GenomeConvertPipeline.ts | New sentinel pipeline to run genome/convert and register/activate output. |
| src/system/resources/server/ResourcePressureWatcher.ts | New CPU/memory pressure watcher (adaptive polling + Events). |
| src/system/rag/sources/ToolDefinitionsSource.ts | Adds “use tools” behavioral nudge in tool prompt sections. |
| src/system/rag/sources/SemanticMemorySource.ts | Shortens negative-cache TTL for “No memory corpus”. |
| src/system/rag/sources/PersonaIdentitySource.ts | Adds “use tools” nudge to identity system prompt sections. |
| src/system/rag/builders/ChatRAGBuilder.ts | Marks legacy system-prompt path deprecated + adds “use tools” wording. |
| src/system/gpu/server/GpuPressureWatcher.ts | New GPU pressure watcher (adaptive polling + Events). |
| src/system/genome/shared/AdapterPackageTypes.ts | Adds QuantizationInfo and manifest field. |
| src/system/genome/server/TrainingCompletionHandler.ts | Reads quantization info; generates capability embeddings; persists to DB. |
| src/system/genome/server/LearningScheduler.ts | Adds capability-based adoption check + GPU pressure gating for training. |
| src/system/genome/server/GenomeRegistry.ts | New capability embedding search over GenomeLayerEntity collection. |
| src/system/genome/server/FitnessTracker.ts | New debounced fitness persistence for genome layers. |
| src/system/genome/server/AdapterStore.ts | Adds quantization field to manifest typing. |
| src/system/genome/server/AdapterPackage.ts | Persists quantization; adds capability embedding generation helper. |
| src/system/genome/fine-tuning/server/adapters/scripts/peft-train.py | Writes quantization_info.json; adds 4-bit→8-bit fallback and metadata reporting. |
| src/system/genome/fine-tuning/server/BaseServerLoRATrainer.ts | Reads quantization_info.json and includes it in manifest + logging. |
| src/system/genome/entities/GenomeLayerEntity.ts | Embedding becomes optional/variable-dim with embeddingDimension + quantization field. |
| src/system/genome/entities/GenomeEntity.ts | Composite embedding becomes optional/variable-dim with embeddingDimension. |
| src/system/core/system/server/JTAGSystemServer.ts | Starts GPU + system resource pressure watchers at server start. |
| src/shared/version.ts | Version bump. |
| src/shared/generated/index.ts | Exports generated system module types. |
| src/shared/generated/gpu/index.ts | Exports new generated GPU types. |
| src/shared/generated/gpu/GpuStats.ts | Generated type includes thresholds + allocations_by_priority. |
| src/shared/generated-command-constants.ts | Adds constants for genome/convert and system/resources commands. |
| src/server/generated.ts | Generated server registry updated for new commands. |
| src/scripts/parallel-start.sh | Adjusts build pipeline ordering to avoid cargo contention. |
| src/package.json | Version bump. |
| src/package-lock.json | Version bump. |
| src/generator/specs/system-resources.json | Adds generator spec for system/resources. |
| src/generator/specs/genome-convert.json | Adds generator spec for genome/convert. |
| src/generator/generate-rust-bindings.ts | Documents binding gen sequencing expectations. |
| src/generated-command-schemas.json | Generated schema updates for new commands. |
| src/docs/genome/QLORA-QUANTIZATION.md | Adds QLoRA/quantization architecture + conversion + inference notes. |
| src/docs/genome/DYNAMIC-GENOME-ARCHITECTURE.md | Marks as superseded by GENOME-ARCHITECTURE.md. |
| src/docs/CONTINUOUS-LEARNING-RUNTIME.md | Marks as superseded by GENOME-ARCHITECTURE.md. |
| src/docs/COMPOSABLE-EXPERTISE.md | Marks as superseded by GENOME-ARCHITECTURE.md. |
| src/docs/COLLABORATIVE-LEARNING-VISION.md | Marks as superseded by GENOME-ARCHITECTURE.md. |
| src/commands/system/resources/test/unit/SystemResourcesCommand.test.ts | Adds generated placeholder unit test scaffold for system/resources. |
| src/commands/system/resources/test/integration/SystemResourcesIntegration.test.ts | Adds generated placeholder integration test scaffold for system/resources. |
| src/commands/system/resources/shared/SystemResourcesTypes.ts | Adds typed command params/result helpers for system/resources. |
| src/commands/system/resources/server/SystemResourcesServerCommand.ts | Implements system/resources server command via Rust IPC. |
| src/commands/system/resources/package.json | Adds command package metadata for system/resources. |
| src/commands/system/resources/browser/SystemResourcesBrowserCommand.ts | Adds browser delegating command for system/resources. |
| src/commands/system/resources/README.md | Adds command README for system/resources. |
| src/commands/system/resources/.npmignore | Adds publish ignore file for system/resources package. |
| src/commands/gpu/stats/shared/GpuStatsTypes.ts | Extends GPU stats command types for thresholds + allocations-by-priority. |
| src/commands/gpu/stats/server/GpuStatsServerCommand.ts | Returns new threshold/allocation fields from Rust GPU stats. |
| src/commands/genome/train/server/GenomeTrainServerCommand.ts | Uses cached GPU pressure watcher; generates capability embedding after training. |
| src/commands/genome/convert/test/unit/GenomeConvertCommand.test.ts | Adds genome/convert unit tests for validation/defaulting logic. |
| src/commands/genome/convert/test/integration/GenomeConvertIntegration.test.ts | Adds generated placeholder integration test scaffold for genome/convert. |
| src/commands/genome/convert/shared/GenomeConvertTypes.ts | Adds typed command params/result helpers for genome/convert. |
| src/commands/genome/convert/server/GenomeConvertServerCommand.ts | Implements genome/convert via sentinel subprocess + optional validation. |
| src/commands/genome/convert/package.json | Adds command package metadata for genome/convert. |
| src/commands/genome/convert/browser/GenomeConvertBrowserCommand.ts | Adds browser delegating command for genome/convert. |
| src/commands/genome/convert/README.md | Adds command README for genome/convert. |
| src/commands/genome/convert/.npmignore | Adds publish ignore file for genome/convert package. |
| src/browser/generated.ts | Generated browser registry updated for new commands. |
Files not reviewed (1)
- src/package-lock.json: Language not supported
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| ): SystemResourcesParams => createPayload(context, sessionId, { | ||
| userId: SYSTEM_SCOPES.SYSTEM, | ||
| includeProcesses: data.includeProcesses ?? false, | ||
| topN: data.topN ?? 0, | ||
| ...data | ||
| }); | ||
|
|
There was a problem hiding this comment.
In createSystemResourcesParams(), defaulting topN to 0 means callers who omit topN (the common case) will send topN=0 to the server, which then forwards it to Rust and yields an empty process list even though the API/docs imply a default of 10. Consider leaving topN undefined when not provided (so Rust can apply its default), or defaulting to 10 when includeProcesses=true, and avoid forcing 0 here.
| ): SystemResourcesParams => createPayload(context, sessionId, { | |
| userId: SYSTEM_SCOPES.SYSTEM, | |
| includeProcesses: data.includeProcesses ?? false, | |
| topN: data.topN ?? 0, | |
| ...data | |
| }); | |
| ): SystemResourcesParams => { | |
| const { includeProcesses: includeProcessesRaw, topN: topNRaw, ...rest } = data; | |
| const includeProcesses = includeProcessesRaw ?? false; | |
| const effectiveTopN = topNRaw ?? (includeProcesses ? 10 : undefined); | |
| return createPayload(context, sessionId, { | |
| userId: SYSTEM_SCOPES.SYSTEM, | |
| includeProcesses, | |
| ...rest, | |
| ...(effectiveTopN !== undefined ? { topN: effectiveTopN } : {}), | |
| }); | |
| }; |
| bits: data.bits ?? 0, | ||
| outputPath: data.outputPath ?? '', | ||
| validate: data.validate ?? false, |
There was a problem hiding this comment.
createGenomeConvertParams() currently defaults bits to 0 and validate to false. That breaks the documented behavior in GenomeConvertServerCommand where bits should default to 4 and validate defaults to true (params.validate !== false). Suggest: default bits to 4 (or leave undefined) and default validate to undefined/true so the server-side default works as intended.
| bits: data.bits ?? 0, | |
| outputPath: data.outputPath ?? '', | |
| validate: data.validate ?? false, | |
| bits: data.bits ?? 4, | |
| outputPath: data.outputPath ?? '', |
| // Safety: GpuAllocationGuard contains Arc<GpuMemoryManager> (Send+Sync) | ||
| // plus primitive fields. Mutex<Option<T>> is Sync when T: Send. | ||
| // The compiler would derive this automatically but the Mutex<Option<Guard>> | ||
| // pattern needs explicit confirmation that Guard is Send. | ||
| unsafe impl Sync for GpuModelTracker {} | ||
|
|
There was a problem hiding this comment.
GpuModelTracker has an unsafe impl Sync even though its fields are Mutex<...> over types that appear to already be Send/Sync (GpuAllocationGuard is composed of Arc + Copy types). If this compiles without the unsafe block, prefer removing the unsafe impl and relying on Rust’s auto-traits; if it doesn’t, add a narrow unsafe impl for the specific non-Sync field/type with a proof (or a compile-time assert) rather than marking the whole struct Sync.
| // Register in eviction registry for visibility | ||
| let registry_id = format!("{}:{}", subsystem.name(), self.label.to_lowercase()); | ||
| mgr.eviction_registry.register(make_entry( | ||
| ®istry_id, | ||
| self.label, | ||
| priority, | ||
| bytes, | ||
| )); | ||
|
|
||
| // Store guard and registry state for cleanup on release | ||
| let mut slot = self.guard.lock() | ||
| .map_err(|e| format!("{}: lock poisoned: {e}", self.label))?; | ||
| // If replacing an existing guard, the old one drops here (releases old allocation) | ||
| *slot = Some(guard); | ||
| if let Ok(mut rs) = self.registry_state.lock() { | ||
| *rs = Some((Arc::clone(mgr), registry_id)); | ||
| } |
There was a problem hiding this comment.
track_bytes() registers an eviction_registry entry before acquiring the guard/registry_state locks. If either lock is poisoned, this returns Err but leaves a registry entry behind (and may not store registry_state), causing stale/immortal entries in the eviction registry. Consider acquiring locks first (or unregistering on error) so the registry and guard lifecycle stay consistent even under lock poisoning.
| // Register in eviction registry for visibility | ||
| let registry_id = format!("{}:{}", subsystem.name(), self.label.to_lowercase()); | ||
| mgr.eviction_registry.register(make_entry( | ||
| ®istry_id, | ||
| self.label, |
There was a problem hiding this comment.
The eviction registry id is derived from self.label.to_lowercase(), which can include spaces/punctuation (e.g., "Orpheus LLM" → "orpheus llm"). This makes IDs inconsistent with other registry IDs and harder to use as stable keys. Consider sanitizing the label into a safe identifier (e.g., [a-z0-9_-]+) or requiring callers to provide an explicit id.
| // Track GPU allocation for embedding model | ||
| if let Some(mgr) = gpu_manager() { | ||
| let model_bytes = estimate_embedding_model_bytes(model_name); | ||
| if model_bytes > 0 { | ||
| match mgr.allocate(GpuSubsystem::Inference, model_bytes, GpuPriority::Interactive) { | ||
| Ok(guard) => { | ||
| info!( | ||
| "Embedding GPU: {} allocation {:.0}MB", | ||
| model_name, model_bytes as f64 / (1024.0 * 1024.0) | ||
| ); | ||
| mgr.eviction_registry.register(make_entry( | ||
| &format!("embed:{}", model_name), | ||
| &format!("Embedding {}", model_name), | ||
| GpuPriority::Interactive, | ||
| model_bytes, | ||
| )); | ||
| if let Ok(mut guards) = get_gpu_guards().lock() { | ||
| guards.insert(model_name.to_string(), guard); | ||
| } |
There was a problem hiding this comment.
Embedding GPU allocations are registered in the eviction registry and guards are stored in EMBEDDING_GPU_GUARDS, but there’s no corresponding unregister/release path tied to model unload, and last_used is never updated on embedding generation. This will leave stale registry entries and make eviction scoring treat active embedding models as cold. Consider (a) unregistering + dropping the guard when embedding/model/unload runs, and (b) touching the eviction registry entry on each generate call for that model.
…or wire (#281) (#2072) Joel's steer via BigMama (#general 2026-08-01): unlike WASTE's uniform-quant streaming, our container has per-(layer,tier) precision banks — so the pager can serve hot/important experts at higher fidelity and cold ones from the small-quant banks. The policy wire now carries that: PlanPin grows an OPTIONAL `tier`, an index into the CONTAINER's declared precision ladder (the manifest owns the ladder; the policy layer never names quant formats). Backward compatibility is the design: serde skips None, so tier-less plans are BYTE-IDENTICAL to the v1 wire her deployed C++ consumer parses — neither side needs a lockstep upgrade, and a v1 document parses unchanged (pinned by test). Constructors PlanPin::residency / PlanPin::tiered replace bare literals at every construction site. Control-law contract documented on the field (RUN-1/RUN-2 lesson): tier choices are as prompt-dependent as residency and must roll with the pins; residency and fidelity draw on ONE rate-distortion budget. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
…knob (#281) (#2074) Misses are unpinned by definition, so the fetch bytes live in the cold tail — per-pin tier alone can't shrink them. The plan doc now carries an optional doc-level `default_tier`: the precision-ladder bank every UNPINNED expert fetches from. With `pin_tier` on the hot set, that's the full rate-distortion split on one wire: hot = high-fidelity bank, cold misses = small-quant bank (~half the bytes on the critical fetch path), which uniform-quant streaming structurally cannot do. - PlanFileDocument.default_tier: Option<u32>, serde-skipped when None — documents without it stay byte-identical to the v1 wire (pinned by test), no lockstep with the C++ consumer. - BanditPlanController::write_tiered_plan(pin_tier, default_tier); (None, None) degenerates byte-for-byte to write_plan (pinned by test). - moe-pager-driver grows --pin-tier / --default-tier flags. 15/15 tests, clippy clean. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
… pins on the GOVERNED plan (#281) The rung-3 actuator leaves the standalone driver and becomes autonomic: the serving daemon now tails the fork's routed-expert trace (GGML_MOE_TRACE_FILE, spawned per-port beside capture/plan — system-owned, zero operator env) and carries the bandit's hot pin list on the SAME governed plan file the host-cache lease publishes. One writer, one plan, policy and budget on one document. - expert-pager-policy: TkeyTable::for_layers(n_layers) SYNTHESIZES the tkey→layer map from geometry via the fork's exact FNV-1a (canonical_name_key) — no operator JSON step. Hash parity pinned against a key from her REAL table (blk.5.ffn_up_exps.weight → 16542725649459479844, independently recomputed). - capacity/trace_tail.rs (NEW): MoeTraceTail — offset-resumed, truncation-reset (new serve = fresh state), bounded 4 MiB drains with record-aligned skip-ahead on backlog (recency is the signal), prefill→decode boundary → immediate warm-start publish, and the last-published-pins memory that gates write churn. - serving_daemon: publish_moe_host_cache_lease reworked to two axes — sticky band governs the BUDGET value; pins roll independently. Writes happen when either axis moves (or at the boundary), never otherwise: the no-mtime-churn property moved from the band to the write decision. Pin count is retention-derived (pin_ceiling: at most HALF the lease's worth of experts — the recency window keeps the rest), so an under-retention lease publishes budget-only (v1 wire shape, her validated parse). Probe now carries pins/trace_tokens/warm_start. Anti-fossil by construction: pins re-derive from the decay bandit every publish — a static pin set cannot fossilize (the RUN-1 lesson measured in [[routed-expert-hotness-is-prompt-dependent-static-pins-hurt]]). Tests: 4 new in trace_tail (each pinning a named invariant), 1 new hash parity in segment.rs; expert-pager-policy 18/18; serving_daemon + host_cache_lease + llama_server suites 56/56. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… pins on the GOVERNED plan (#281) The rung-3 actuator leaves the standalone driver and becomes autonomic: the serving daemon now tails the fork's routed-expert trace (GGML_MOE_TRACE_FILE, spawned per-port beside capture/plan — system-owned, zero operator env) and carries the bandit's hot pin list on the SAME governed plan file the host-cache lease publishes. One writer, one plan, policy and budget on one document. - expert-pager-policy: TkeyTable::for_layers(n_layers) SYNTHESIZES the tkey→layer map from geometry via the fork's exact FNV-1a (canonical_name_key) — no operator JSON step. Hash parity pinned against a key from her REAL table (blk.5.ffn_up_exps.weight → 16542725649459479844, independently recomputed). - capacity/trace_tail.rs (NEW): MoeTraceTail — offset-resumed, truncation-reset (new serve = fresh state), bounded 4 MiB drains with record-aligned skip-ahead on backlog (recency is the signal), prefill→decode boundary → immediate warm-start publish, and the last-published-pins memory that gates write churn. - serving_daemon: publish_moe_host_cache_lease reworked to two axes — sticky band governs the BUDGET value; pins roll independently. Writes happen when either axis moves (or at the boundary), never otherwise: the no-mtime-churn property moved from the band to the write decision. Pin count is retention-derived (pin_ceiling: at most HALF the lease's worth of experts — the recency window keeps the rest), so an under-retention lease publishes budget-only (v1 wire shape, her validated parse). Probe now carries pins/trace_tokens/warm_start. Anti-fossil by construction: pins re-derive from the decay bandit every publish — a static pin set cannot fossilize (the RUN-1 lesson measured in [[routed-expert-hotness-is-prompt-dependent-static-pins-hurt]]). Tests: 4 new in trace_tail (each pinning a named invariant), 1 new hash parity in segment.rs; expert-pager-policy 18/18; serving_daemon + host_cache_lease + llama_server suites 56/56. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
… pins on the GOVERNED plan (#281) (#2119) The rung-3 actuator leaves the standalone driver and becomes autonomic: the serving daemon now tails the fork's routed-expert trace (GGML_MOE_TRACE_FILE, spawned per-port beside capture/plan — system-owned, zero operator env) and carries the bandit's hot pin list on the SAME governed plan file the host-cache lease publishes. One writer, one plan, policy and budget on one document. - expert-pager-policy: TkeyTable::for_layers(n_layers) SYNTHESIZES the tkey→layer map from geometry via the fork's exact FNV-1a (canonical_name_key) — no operator JSON step. Hash parity pinned against a key from her REAL table (blk.5.ffn_up_exps.weight → 16542725649459479844, independently recomputed). - capacity/trace_tail.rs (NEW): MoeTraceTail — offset-resumed, truncation-reset (new serve = fresh state), bounded 4 MiB drains with record-aligned skip-ahead on backlog (recency is the signal), prefill→decode boundary → immediate warm-start publish, and the last-published-pins memory that gates write churn. - serving_daemon: publish_moe_host_cache_lease reworked to two axes — sticky band governs the BUDGET value; pins roll independently. Writes happen when either axis moves (or at the boundary), never otherwise: the no-mtime-churn property moved from the band to the write decision. Pin count is retention-derived (pin_ceiling: at most HALF the lease's worth of experts — the recency window keeps the rest), so an under-retention lease publishes budget-only (v1 wire shape, her validated parse). Probe now carries pins/trace_tokens/warm_start. Anti-fossil by construction: pins re-derive from the decay bandit every publish — a static pin set cannot fossilize (the RUN-1 lesson measured in [[routed-expert-hotness-is-prompt-dependent-static-pins-hurt]]). Tests: 4 new in trace_tail (each pinning a named invariant), 1 new hash parity in segment.rs; expert-pager-policy 18/18; serving_daemon + host_cache_lease + llama_server suites 56/56. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
…e coverage from the live trace (#281/#282) (#2122) Joel's directive: use the ML advantage for predictive scheduling. Before any CUDA copy-stream work, the go/no-go must be MEASURED, not assumed: exposed H2D per token = (1 − schedulable coverage) × the ~11GB expert working set. This slice wires the #276-ported CrossLayerExpertPredictor into the trace tail as a cross-TOKEN transition model and measures, live from the real trace, the two halves of coverage: - repeat_recall: experts already in the previous token's set — what pure recency residency covers for free (her measured 4416-stable warm set says this is high on decode). - predicted_delta_recall: of the NON-repeat delta, how many the predictor called one token ahead — what prefetch adds on top. - schedulable_coverage = both, over all experts: THE number that sizes her DeviceUploadFetcher's win before it's built. Published on the serving.moe_host_cache_lease probe every plan write (repeat/delta/coverage ×100). predicted_next() exposes the live delta prediction — the future plan-file prefetch list (#273's third axis), held back from the wire until the consumer coordinates the extension. All prediction state resets with the stream (truncation/geometry) — stale transitions never leak across serves. Test pins the instrument's honesty: a repeating stream scores 100% recency/zero delta; an alternating DISJOINT stream scores 0% recency but the predictor learns the cycle and delta recall climbs ≥50% — prediction covering exactly what recency cannot. First token scores nothing (honest None, never a fake 100). trace_tail 5/5; serving_daemon suite green. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
…sifiably NOW, results ledger fills as experiments land (#2199) Joel: 'This could be a paper once we figure it out and track progress as results.' Working-paper skeleton with 8 numbered falsifiable claims (C1-C8) and an append-only results ledger where a status change requires a replayable receipt (forge-alloy §4.1.3.4 standard). Six rows already carry MEASURED or SHIPPED status from existing work (K3-48B @57t/s, gather 4.0×, cliff law, residency fence, tiered container, depot seam); the pending rows map 1:1 onto already-scheduled experiments (#281 RUN-3, #282 beat-WASTE, market S2, share slice 2/4, Gate A) — so the paper's results section grows in place instead of being reconstructed later. Method notes carry the nondeterminism and honesty disciplines; venue framing deferred until C6+C7 have rows. Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo Co-authored-by: Claude Fable 5 <[email protected]>
…server (Joel's steer)
Joel: "not too hard coded into one paradigm — better add proper adapters and break the
module down into concerns. We could do a ton with plugin ML here, especially RL."
Right, and reading first changed the answer for the THIRD time today: the seam already
exists WITH a learned implementation in it.
* capacity/expert_tier_policy.rs — `trait TierPolicy { fn plan(...) -> ExpertTierPlan }`,
decisions returned as a PLAN not applied inline; ClassicTierPolicy is the v1 heuristic.
* expert-pager-policy LEAF CRATE — policy already extracted into its own crate. The
plugin boundary is already cut.
* capacity/bandit_plan_controller.rs — a BANDIT CONTROLLER, re-exported from it. RL is
not greenfield here (#276/#281).
* expert_predictor / expert_decay_policy / expert_residency / expert_observer — the
concerns are already separated on the expert side.
So KV slot residency implements that shape rather than inventing a rival. And the
generalisation is now EARNED rather than speculative: CLAUDE.md says generalize at 2-3
instances, and we have three of "paged resource under scarcity with a learnable value
function" — MoE experts (built), LoRA genome paging (built), KV slots (this doc). KV slots
are the ideal outlier B precisely because they are MAXIMALLY DIFFERENT from experts: unit
is a whole conversation not a tensor, a miss costs seconds of prefill not bytes of fetch,
population is 2-8 not thousands. One seam fitting both ends fits everything between.
- Outlier A, heuristic: cost_of_loss = tail_tokens / prefill_rate. A quantity with a
UNIT (seconds), not a magic ratio. Ships first, is the permanent floor.
- Outlier B, RL: state = per-slot (tail, recency, citizen, phase) + arrival; action =
which slot; reward = PREFILL SECONDS SAVED.
AND THE REWARD SIGNAL IS ALREADY INSTRUMENTED — I shipped it this morning (faf8c07)
without noticing it was one. `delib.generate.cache` emits cached_tokens / prefill_tokens /
prefill_ms / hit_rate on EVERY generation: a labelled transition per turn, continuously, in
production. So the A-vs-B comparison is measurable from day one instead of argued.
Guardrails so "plugin ML" doesn't become unexplainable serving: policies return PLANS
(loggable, replayable, refusable); the heuristic stays callable forever as the floor and a
learned policy that loses on measured prefill-seconds is switched off by the comparison,
not by argument; the deciding policy's identity rides the receipt so a regression is
attributable; and never learn on a broken substrate — before the deterministic head landed
the reward was ~0 for structural reasons and a bandit trained through that would have
learned nothing helps.
DECOMPOSITION: inference/llama_server.rs is 4,190 lines — 8× the decomposition law, and
where every §3 change would otherwise land. Named the six concerns (spawn/args, readiness,
slots, request, lifecycle, policy-as-leaf-crate). Explicitly a MOVE, not a re-architecture:
no new task, no new watch channel, no second registry — and the flag comments travel with
their flags, since those comments are the only record of the incidents that set each value.
ALSO CORRECTED §4: `--cache-ram` is not new work. capacity/host_cache_lease.rs is already
the governed lease, already runs on the governor tick, and its own module doc already says
why that matters here — "KV grows as slots fill". One more term on an existing lease.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
…d durability, grade-race fix (#2349) * feat(activity): ONE adapter seam — material in, verdict out (slice 1 of the judge wiring) An activity adapts the outside world's form into ours and renders a verdict on what the citizen produced. Benchmarks, a game level, a life-drawing critique, a robot that either picked up the block or didn't — one interface, N implementations, declaring none is normal. WHY NOT `BenchmarkAdapter`, WHICH ALREADY EXISTS: it was the right SHAPE and the wrong SCOPE. It already carried both directions — `dataset()`/`tasks()` in, `grade()` out — so this is a generalization, not a rewrite. But the NAME is load-bearing: an interface called `BenchmarkAdapter` cannot plausibly host a game level, so the second activity gets its own trait, registry and runner, and the substrate ends up with two of everything. Same failure as naming a room for a subsystem and making it immortal. Named for the JOB, gameplay is a sibling implementation instead of a fork. THE GROWABLE OUTCOME, and why the fixed struct was the real blocker: `TaskOutcome` had `patch` and `workspace` as bare fields, which means SWE-bench OWNS the outcome type. A game trajectory or a robot's joint log could only arrive by widening a struct every other activity compiles against — so in practice it would never arrive there; it would grow its own parallel outcome and its own parallel judge. `Outcome` now keeps the UNIVERSAL facts as named fields (she spoke; she worked somewhere; the harness had its own opinion) and puts modality-specific ones in a typed `channels` carrier, the same growable shape this codebase already uses for adapter capabilities. Gameplay adds a channel without SWE-bench recompiling; a judge asks for the channel it grades and gets a typed None when the activity produced none. Growing the enum stays deliberate — a new variant needs a REAL activity — but the cost of a wrong guess drops from "a second subsystem" to "one unused variant". WHAT THIS IS FOR (measured today, 450 runs): 253 of them — 56% — ended with NO GRADE AND NO ERROR. Not a failure, not a verdict: nothing. In classroom terms the exams were sat and nobody was assigned to mark them. `benchmark.json` declares `suite/instances/team/budget` and NO judge; `BenchmarkAdapter` has zero production consumers; grading is hardcoded to `swe_bench::grade` behind four private call sites. When a run doesn't come through one of those doors, nothing marks it and nothing says so. `resolve_all` is the seam that makes that unrepresentable: a declared judge that cannot be resolved is an error AT STAGING, naming the bad key and the known set — never a run that ends quietly. An EMPTY declaration resolves to empty and is explicitly NOT an error, because most activities judge nothing and that is normal, not a missing judge. Five tests, each pinning a contract that failed in the wild: registry round-trip + named miss; empty declaration is legal; unknown declaration fails loud and names it; the default judge defers to the harness (so a task whose EvalTask already encodes done-ness needs no judge code); an absent channel reads ABSENT, not as empty success. NOT YET WIRED — deliberately, this is slice 1. Next: the recipe declares its judges in `params`, dispatch resolves them through this registry, and the hardcoded `swe_bench::grade` branch is DELETED rather than supplemented (a subtraction, per the design doc's build order). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(kv): canonical order inside the STABLE tier — the other half of the #266 prefix defect The tier-split shipped for #266 (stable framing first, volatile grounding last) did not deliver reuse, and the comment at this sort said why without noticing: a stable sort "preserves the salience order WITHIN each tier, so attention ranking is untouched". That was treated as harmless. It is the remaining half of the defect. Salience is recomputed EVERY turn, so preserving it as EMIT ORDER re-shuffles the very tier whose only purpose is to be byte-identical across turns. MEASURED LIVE 2026-08-21, inside Atlas's `pallets__flask-4045` run, from her own prompt captures — not inferred: turn0→1 common prefix 8,216 / 9,906 chars diverges into [now …] turn1→2 common prefix 7,879 diverges into [active-work] turn2→3 common prefix 8,133 diverges into [workspace-map] ~82% shared prefix, and the divergence points are stable-tier blocks TRADING PLACES. Because the system prompt is FIRST, a swap at token ~2,000 invalidates the KV for everything after it — including a 34,000-token conversation tail. `--cache-reuse 256` was passed the entire time and every turn reported `cachedTokens: 0`. The cache was correct; we were destroying the prefix ourselves. Cost at the measured 111 tok/s prefill: ~306 SECONDS OF RE-PREFILL PER ACT, growing as her conversation grows (9,847 → 36,242 tokens and climbing as tool results accumulate). One observed turn was 20 minutes of apparent silence that was a single 36k re-prefill — the run reporting `active`/`not stalled` the whole time, because the pulse is a timer. THE FIX: within the stable tier, order CANONICALLY (by faculty name). Attention ranking is genuinely untouched — salience still decides WHICH contributions are selected, which happened above against the budget. It simply stops deciding WHERE the survivors sit, which it never needed to. Same set in, same bytes out, every turn. The volatile tier deliberately KEEPS salience order: it is re-prefilled by construction, so canonical ordering would buy no reuse and would cost the "most salient nearest the write point" placement #205 put there on purpose. VERIFIED: 181 prompt tests pass, including `framing_flip_never_perturbs_the_cacheable_prefix` — the #266 invariant is intact, this extends it to the case it did not cover (a FIXED framing with re-ranked context). NOT YET LIVE-PROVEN: the running core still holds the flask run, so deploy is correctly blocked. The proof owed is her next captures — common prefix ~82% → ~100%, and `cachedTokens` 0 → nonzero from turn 2. A regression test pinning "same set, different salience → identical bytes" follows immediately. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(probe): delib.generate.cache — make the KV fix prove itself instead of me diffing captures by hand Joel: "hopefully it will prove itself via probes." It could not have. `delib` carried `turn.demand` and `context.render` — how big the prompt WAS — and nothing about what the lane DID with it. A prompt whose prefix we were destroying every single turn looked identical in the probe stream to one served entirely from cache. That absence is why the prefix defect (fixed in 40075d7) survived from #266 to today, and why the only way to see it on 2026-08-21 was hand-diffing a citizen's raw prompt captures — exactly the manual step a probe exists to delete. The row lands in `metrics_from`, the single funnel every generation already passes through, so one probe covers every turn of every citizen with no caller change: delib.generate.cache cached_tokens prefill_tokens hit_rate prefill_ms decode_ms input_tokens output_tokens latency_ms `hit_rate` is `TurnMetrics::cache_hit_rate()` — the ratio that already existed and had no way out of the process. 1.0 = fully warm prefix. Near 0 with a large `prefill_tokens` = the prefix is being invalidated upstream, which is the measured pre-fix state: ~306s of wasted re-prefill per act while `--cache-reuse 256` was set and working correctly. Emitted ONLY when the lane actually reported timings. Cloud and older endpoints omit them, and a fabricated 0.0 hit-rate for a provider that never measured one is a lying receipt of the #151/#357 class — those stay silent rather than report a floor they did not observe. So the verification of the ordering fix is now a probe query rather than a capture diff: hit_rate should climb off the floor from the second act of a task onward. cargo check green (metal,accelerate). Signature and return value unchanged — purely additive. The --lib gate in CI is the test proof; live proof still waits on the flask run clearing the core. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * test(kv): pin "same set, different salience → identical bytes" — the guard the #266 half lacked The sibling test `stable_framing_serializes_before_higher_salience_volatile_grounding` pinned the TIER SPLIT and passed the whole time the prefix was being destroyed. It could not catch this: it asserts stable-before-volatile, and says nothing about order WITHIN the stable tier — which is exactly where salience was re-shuffling blocks every turn. So this is the assertion that makes 40075d7 hold. Three different salience rankings and three different arrival orders over the SAME three stable contributions must emit byte-identical blocks. Revert to a salience-ordered stable tier and this fails while the sibling still passes — which is the whole point of adding it rather than extending that one. It also pins the rule POSITIVELY (canonical by faculty name), because byte-equality alone would be satisfied by an insertion-order block that happened to match across this test's particular arrival orders. An accidental pass is not a guard. TWO THINGS THE TEST TAUGHT ME WHILE WRITING IT, both worth the next reader's time: 1. My canonical assertion was backwards from its own message. Alphabetically it is room-kanban < room-roster < workspace-map — roster sits BETWEEN, and I asserted kanban < map < roster. Caught by the test, on the first run. 2. The volatile-tier assertion FAILED, and it was my probe that was wrong, not the code. I reached for `active-work` as a volatile example. It is pinned FIRST by an explicit rule ABOVE salience (ctx.sort_by, :888-905) because the ctx_floor reservation for a citizen's held card only holds if its claimant also leads the greedy selection walk. So I had picked the one faculty in that tier where salience is deliberately not the deciding key, and the result read as "salience does nothing here" about a tier where it does plenty. Swapped to recall-vs-affect, which are genuinely salience-ranked, and left the trap written down in the test so the next person does not re-lay it. That volatile assertion is deliberately `assert_ne!` — it guards the ASYMMETRY. The volatile tier must keep following salience (#205, most salient nearest the write point); it re-prefills by construction, so canonical ordering there would buy no reuse and would cost that placement. If a future "make it all deterministic" pass reaches into that tier, this fails and tells it why. 182 prompt tests green (was 181). Disk swept-clean, 128 GB free. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(kv): the KV cache economy — and the naive "shared tool head" plan is DOMINATED Joel asked for this DESIGNED, not patched. Reading the serving layer first was the whole value: most of the machinery we were about to build already exists in llama.cpp and is already switched on. Two facts read in-file today reverse the plan I would have written from memory. WHAT IS ALREADY TRUE (source-read, not inferred): * `slot_prompt_similarity` defaults to 0.1 and we never disable it — LCP-based slot selection is ALREADY ACTIVE (common.h:687, server-context.cpp:1543). Cross-persona head sharing is not a feature to build; it is a behaviour we already get, unmanaged. * `cache_ram_mib` defaults to 8192 — an 8 GiB host-RAM prompt cache ALREADY EXISTS, and the server already saves an evicted slot's conversation and restores the incoming one (prompt_save / prompt_load, server-context.cpp:1620). * We never pin `id_slot`, so affinity is emergent from prefix similarity and never declared. That is the actual gap: not mechanism, POLICY. THE ARITHMETIC THAT KILLS THE OBVIOUS PLAN. With Atlas's measured numbers — ~7,600 tok shared head vs a 36,242 tok tail: sim = 7,600 / 36,242 ≈ 0.21 > 0.1 → persona B TAKES persona A's slot f_keep = 7,600 / 36,242 ≈ 0.21 < 0.5 → A's 36k is evicted The shared head is big enough to WIN slot selection and small enough that winning throws away 4.7× more than it saves. "Make the tool head identical and first so every persona shares it" is right about token cost (#333) and is a precondition — but as a KV strategy it is dominated, and shipped alone it makes slot theft MORE likely and would read as a regression. Tail retention beats head sharing by the tail:head ratio, which grows every act. Any design that trades a tail for a head is backwards. So the order inverts: declared slot affinity (`id_slot` per resident citizen, eviction as a priced decision behind the same seam as every other cache class) is the KEYSTONE, and the shared head lands AFTER it. "Docker form" is exactly the right instinct for the head — a shared prefix only stays shared if it is a function of LANE IDENTITY, not of whichever citizen is calling: same model, flags, tool manifest, template → one head, with an identity hash so divergence is LOUD rather than silent. Reconciles with [[kv-prefix-caching-is-the-only-form...]]: that memory is about CONVERSATION content, which is genuinely unique per citizen. A tool schema head is not conversation, so sharing it is prefix reuse, not dedup. FOUND WHILE WRITING, and it is its own defect: that 8 GiB prompt cache is UN-GOVERNED. We never pass the flag, never budget it, never told the ResourceGovernor. Same shape as the 2026-07-13 incident — every component healthy, the wiring absent — in RAM instead of disk. `--cache-ram` becomes a governed lease at spawn, like GGML_MOE_HOST_CACHE_GB (#287). WHAT I DID NOT MEASURE, and the doc says so rather than guessing: the wall-clock of prompt_save/prompt_load at ~36k tokens. It decides whether eviction is survivable or is a second re-prefill in a hat, so step 1 is measuring it and step 3 is gated on the number. Steps 1 (measure) and 2 (govern the RAM) are independent of the live flask run and can start now. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(kv): policy is an ADAPTER not a rule + decompose the 4,190-line server (Joel's steer) Joel: "not too hard coded into one paradigm — better add proper adapters and break the module down into concerns. We could do a ton with plugin ML here, especially RL." Right, and reading first changed the answer for the THIRD time today: the seam already exists WITH a learned implementation in it. * capacity/expert_tier_policy.rs — `trait TierPolicy { fn plan(...) -> ExpertTierPlan }`, decisions returned as a PLAN not applied inline; ClassicTierPolicy is the v1 heuristic. * expert-pager-policy LEAF CRATE — policy already extracted into its own crate. The plugin boundary is already cut. * capacity/bandit_plan_controller.rs — a BANDIT CONTROLLER, re-exported from it. RL is not greenfield here (#276/#281). * expert_predictor / expert_decay_policy / expert_residency / expert_observer — the concerns are already separated on the expert side. So KV slot residency implements that shape rather than inventing a rival. And the generalisation is now EARNED rather than speculative: CLAUDE.md says generalize at 2-3 instances, and we have three of "paged resource under scarcity with a learnable value function" — MoE experts (built), LoRA genome paging (built), KV slots (this doc). KV slots are the ideal outlier B precisely because they are MAXIMALLY DIFFERENT from experts: unit is a whole conversation not a tensor, a miss costs seconds of prefill not bytes of fetch, population is 2-8 not thousands. One seam fitting both ends fits everything between. - Outlier A, heuristic: cost_of_loss = tail_tokens / prefill_rate. A quantity with a UNIT (seconds), not a magic ratio. Ships first, is the permanent floor. - Outlier B, RL: state = per-slot (tail, recency, citizen, phase) + arrival; action = which slot; reward = PREFILL SECONDS SAVED. AND THE REWARD SIGNAL IS ALREADY INSTRUMENTED — I shipped it this morning (faf8c07) without noticing it was one. `delib.generate.cache` emits cached_tokens / prefill_tokens / prefill_ms / hit_rate on EVERY generation: a labelled transition per turn, continuously, in production. So the A-vs-B comparison is measurable from day one instead of argued. Guardrails so "plugin ML" doesn't become unexplainable serving: policies return PLANS (loggable, replayable, refusable); the heuristic stays callable forever as the floor and a learned policy that loses on measured prefill-seconds is switched off by the comparison, not by argument; the deciding policy's identity rides the receipt so a regression is attributable; and never learn on a broken substrate — before the deterministic head landed the reward was ~0 for structural reasons and a bandit trained through that would have learned nothing helps. DECOMPOSITION: inference/llama_server.rs is 4,190 lines — 8× the decomposition law, and where every §3 change would otherwise land. Named the six concerns (spawn/args, readiness, slots, request, lifecycle, policy-as-leaf-crate). Explicitly a MOVE, not a re-architecture: no new task, no new watch channel, no second registry — and the flag comments travel with their flags, since those comments are the only record of the incidents that set each value. ALSO CORRECTED §4: `--cache-ram` is not new work. capacity/host_cache_lease.rs is already the governed lease, already runs on the governor tick, and its own module doc already says why that matters here — "KV grows as slots fill". One more term on an existing lease. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(inference): extract the llama-server flag spine into lane_args — decomposition slice 1 Joel: "I hate this file. Decompose it away from slop." llama_server.rs was 4,190 lines with every concern in it — flags, readiness, request shaping, lifecycle, orphan reaping — and it is where every change in the KV design would otherwise land. Slice 1 of docs/architecture/KV-CACHE-ECONOMY.md §7. Net -28 lines there, and a module that can actually be tested. WHY FLAGS FIRST. Answering "how do we use upstream llama.cpp" precisely: we consume it TWO independent ways, and only one touches this file. * as a BINARY — llama-server spawned as a subprocess, spoken to over HTTP. ZERO linkage: llama_server.rs imports nothing from llama/ggml. Upstream drift reaches us as a changed CLI surface (this module) or a changed JSON shape (request/readiness). * as a LIBRARY — the `llama` crate links libllama in-process for forge/conversion. That is where our fork's C++ lives (K3 KDA, AttnRes, MoE gather). Never passes here. So a fork rebase should touch this file and the wire shapes and nothing else. It could not, while the flags were welded into a Command chain in a 4k-line file. THE INVOCATION IS DATA. `base_invocation` is pure — primitives in, `LaneInvocation` out, no Command, no process, no I/O. Same shape as `TierPolicy::plan`: return a plan, don't apply one, so it can be asserted, logged and diffed. `envs` is on the struct because the invocation genuinely is not args-only (LLAMA_RESIDENT_OVERRIDE, #29); modelling that as "args plus a side effect someone remembers" is how it gets dropped. FIVE TESTS THAT COULD NOT PREVIOUSLY EXIST, because asserting them meant launching a real llama-server on a real GPU with a real model: * `-c` == per-lane window x lanes, and `--parallel` is EXPLICIT — the regression where inheriting llama.cpp's default of 4 silently served every citizen a QUARTER of the planned window. Nothing failed. That is why this is now three lines of pure arithmetic. * `--no-context-shift` present on every lane (#139: overflow must 400, never amputate the prompt middle and generate from the mutilation). * `--cache-reuse 256` still configured (~306s/act when absent, measured). * every value-taking flag is followed by a VALUE — the class that broke on 2026-08-20 when upstream turned `--flash-attn` from a switch into one taking [on|off|auto] and the bare form ate `--mmproj`, so the lane failed to spawn and serving sat at 0 lanes. * the base invocation needs no environment. COMMENTS TRAVELLED WITH THEIR FLAGS, verbatim, not paraphrased. Each one is the only surviving record of the incident that set its value; moving a flag without its comment destroys the reason and invites the reversion. Added one postscript to --cache-reuse: the flag was never the defect, WE were mutating our own prefix (fixed in 40075d7) — so nobody tunes this number looking for the win that already landed elsewhere. SCOPE, deliberately bounded: the CONDITIONAL flags (KV quant, flash-attn, mmproj, MTP draft, resident override, CPU placement, jinja, LoRA, MoE -ot) are still assembled by the caller and are slice 2. This is the unconditional spine, which is also the part carrying the arithmetic worth pinning. VERIFIED: cargo check clean (metal,accelerate); 5 new tests pass; llama_server's 38 tests pass. NOT MINE, flagged not absorbed: `first_free_port_skips_a_taken_port` is FLAKY under parallel execution — same filter and binary gave FAILED then ok on an immediate re-run, and it passes in isolation both with and without this diff. It binds a port and races. Worth its own card; not silently folded in here. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(inference): conditionals behind LaneOptions + a generic AsArg — slice 2 Joel: "Move concerns to proper adapters" and "templates are underutilized by you in both cpp and rust… it reduces code size a lot sometimes." Both applied here, not just agreed to. SLICE 2 — the conditional flag surface moves out of the Command chain: kv-quant / flash-attn / mmproj / MTP draft / CPU placement / resident-override now ride `LaneOptions` into a pure `LaneInvocation::with_options`. llama_server.rs 4,190 → 4,079. THE SPLIT THAT MAKES IT AN ADAPTER RATHER THAN A MOVE: every LaneOptions field is an ALREADY-RESOLVED value, never a thing to look up. Resolution — reading config_env, probing the registry for an mmproj or an MTP head, deciding placement, and emitting the vision-capability RECEIPT — stays with the caller, which owns the I/O. lane_args decides only what a resolved value MEANS on a command line. Gather inputs, then compute a plan: the same shape as TierPolicy, and the reason the whole surface is unit-testable with no GPU, no model, no process. The vision warn stayed behind deliberately. A Vision-capable row with no projector serves text-only and silently ignores images — a capability LIE — so it warns loud ([[fallbacks-are-illegal-fail-loud]]). That is a receipt about the world, not a flag, and receipts belong with resolution. THE TEMPLATE POINT, applied where it actually pays. Before, every value was hand-converted at its call site — `total_ctx.to_string()`, `p.to_string_lossy().into_owned()`, a bare `"256".into()` — three spellings of one idea, and three chances to push a VALUE without its FLAG. So: one `trait AsArg` (impl for &str/String/&Path/u16/u32) plus `pair(args, flag, value)`, and a valued flag becomes a single indivisible call. Monomorphised exactly as a C++ template would be — one definition, zero runtime cost. That is not cosmetic. Orphaning a value from its flag is precisely the class that took serving to 0 lanes on 2026-08-20, when upstream turned `--flash-attn` into `[on|off|auto]` and the bare form ate `--mmproj`. `pair` makes it unrepresentable instead of merely tested for — and the test stays anyway, because a guard you can delete is not a guard. FOUR MORE TESTS (9 total in the module): * default options emit NO conditional flags and no env — "present when it should be absent" is a real defect; the mmproj case literally decides whether a citizen SEES. * --flash-attn keeps its value when sitting next to --mmproj: the 8/20 outage as a test rather than an outage. * resident override rides the ENVIRONMENT, never the args (#29) — the reason LaneInvocation models envs at all rather than returning a bare Vec<String>. * KV quant sets BOTH -k and -v; one without the other is a silent cache asymmetry. STILL SLICE 3, deliberately not half-migrated: --jinja / chat-template sidecar, the LoRA set, and the MoE `-ot` tensor overrides. VERIFIED: cargo check clean (metal,accelerate); 9/9 lane_args tests pass. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * refactor(inference): slice 3 — jinja/LoRA/-ot move out; the flag CONCERN is now closed Last of the conditional surface: the chat-template sidecar, the genome LoRA set, and the K3 `-ot` expert placement. llama_server.rs 4,190 → 4,034 (-156); lane_args.rs is 521 lines that are entirely about one thing. No flag is now built in two places, which was the compression violation the half-migration would have left behind. `--jinja` moved to the BASE spine, not to options, because it is unconditional — and the comment explaining why is the most expensive one in the file. Gating it was a silent capability kill: the switch used to require a forge-written sidecar to exist, so every normally PULLED GGUF ran with tools DISABLED. The gateway ignored the `tools` param and the persona NARRATED tool calls instead of emitting them. A model with hands, holding them behind its back, because of a file that was never there. The sidecar now OVERRIDES when present (forged GGUFs whose mlx→gguf conversion left a thin 208-char tool-less template) and the embedded tool-capable template stands when absent — tools ON either way. The LoRA join moved WITH its flag rather than staying at the call site, deliberately: the join IS the flag's semantics. llama.cpp b8784+ deprecated repeated `--lora` and SILENTLY keeps only the LAST, which was collapsing every multi-layer genome stack to a single adapter — glass-boxed 2026-07-23 in the lane's own stderr ("DEPRECATED: --lora specified multiple times... only last value will be used" x4) while a 4-layer stack was supposedly serving. The genome's whole premise is layers that STACK; this arg SHAPE is what stacks them. Split the join from the flag and the next person re-introduces the bug. Resolution stayed with the caller for all three, same rule as slice 2: the sidecar `is_file()` probe, the adapter paths, and `expert_ot_value()` are lookups; lane_args only decides what a resolved value means on a command line. VERIFIED: 351 inference tests pass; cargo check clean (metal,accelerate). NEXT, and it is the seam Joel actually asked for: `trait LaneBackend` with llama-server as impl A, so an mlx / vllm / remote-grid-peer lane is impl B rather than a fork of this file. lane_args is now shaped to BE that impl rather than to be the only way. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(serving): STDERR IS NEVER AN INTERFACE — and we break it twice (Joel's law) Joel, 2026-08-21: "STDERR/out is never a place for interfacing, just debug." Checked rather than agreed, and we violate it in two places, both written in good faith for real incidents and both making llama.cpp's DEBUG TEXT load-bearing in our control plane: * `inference::wedge::WedgeWatch` parses stderr for an impossible slot progress (`progress = 1.10`) and raises a flag THE SERVING DAEMON REAPS A LANE ON. * `inference::placement_watch::OffloadWatch` parses llama.cpp's LOAD BANNER for layers offloaded, then fires `serving.placement.cpu_fallback` — treated as a lease violation (#441). Why it has to change even though it works today: stderr is unstructured, unversioned, and drifts with upstream's logging taste. The failure mode when it drifts is not an error — it is SILENCE. The watcher stops matching, the flag stops rising, and the wedge that burned four hours on 2026-08-05 becomes invisible again with every component still green. Same shape as every other defect in this document: an absence that looks like normal operation. It is also, precisely, the class the #441 sentinel was built to catch — so the sentinel is currently exposed to the failure it exists to detect. The structured channels already exist: `/slots` carries per-slot state and progress, `/props` the load configuration, and the per-request `timings` block already reaches us — it is what `delib.generate.cache` reports. The tok/s sentinel should read `prefill_tokens`/`prefill_ms` rather than scrape a banner. THE LINE, since not all stderr reading is a violation: `stderr_log_tail()` on spawn failure is CORRECT — a human asks "why did it die" and gets llama.cpp's own last words. Reading stderr to SHOW is debug. Parsing stderr to DECIDE is an interface. The test is whether a control path branches on it. STATUS: named, not fixed. Rewriting both watchers onto /slots + /props needs those payloads verified against our pinned build (b10196-fa7e0d8e9) first — asserting a field exists because upstream documents it is the same mistake in a different channel. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs(kv): pin the PRE-FIX baseline from a live run — 0% reuse, 57,005 tokens re-prefilled in 4 acts Measured 2026-08-21 10:57 off a LIVE run rather than argued: citizen e5f4141d, instance pallets__flask-4045, pre-fix binary b10196-fa7e0d8e9, read from her own prompt captures. act 1: cached 0 / prefill 9,847 hit 0.000 act 2: cached 0 / prefill 11,172 hit 0.000 act 3: cached 0 / prefill 19,434 hit 0.000 act 4: cached 0 / prefill 16,552 hit 0.000 57,005 tokens re-prefilled across four acts, zero reuse on every turn, ~513s at the measured 111 tok/s — 8.5 minutes of a 4.3h budget spent re-reading, four acts in, cost per act still climbing. That is the number 40075d7 has to move, now pinned to a specific citizen on a specific instance so the after-measurement is a COMPARISON and not a claim. METHOD NOTE, recorded because it nearly went wrong and it is the session's recurring defect class: `pgrep` for a solve process finds NOTHING while a run is live, because `agent/solve` executes INSIDE the core rather than as a subprocess. I read that absence as "the run finished, deploy is unblocked" — and would have rebooted the box out from under a citizen at act 4. Wrong instrument, absence misread, same shape as every retraction in this document. The authoritative signal is ~/.continuum/progress/agent-solve-claim-<run>.json (state, acts, mtime): it said state=running, acts=4, written 60 seconds earlier. Deploy remains correctly blocked. The after-number is owed and is now cheap to collect — same read, or just query delib.generate.cache once the fix is live. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(serving): per-slot throughput verdict — the sensor missing when the round died today TDD/VDD on a defect measured LIVE forty minutes ago, encoded while it is fresh rather than remembered later. THE INCIDENT. Citizen e5f4141d working pallets__flask-4045 in-room. Run reported state=running, heartbeat every minute, acts frozen at 4 for twelve minutes. Lane answered /health {"status":"ok"}, /props 200, /v1/models 200, port bound, process up 3h58m. Every readiness signal in the system said healthy. Her own lane said: slot 1 | task 3 | n_decoded = 1092, tg = 2.65 t/s, tg_3s = 0.96 t/s slot 1 | task 3 | n_decoded = 1093, tg = 2.53 t/s, tg_3s = 0.05 t/s slot 0 | task 605 | prompt processing, progress 0.52, 105 t/s Slot 1 decoding at 0.05 TOKENS PER SECOND — one token per twenty seconds — still holding task 3 after six hundred tasks passed on the neighbouring slot. PREFILL WAS FINE (105 t/s, the expected rate). Only decode collapsed, on ONE slot, and nothing could see it. That is #386's per-slot wedge and it is the round-killer: a citizen at 1/600th speed burns her whole 4.3h deadline producing nothing while the board renders a healthy pulse. WHY LANE HEALTH CANNOT CATCH IT: /health is lane-scoped and the LANE is fine — the other slot decodes normally, so every aggregate reads healthy. #363 established that readiness must verify GENERATION not the socket; this is the layer below: generation must be verified PER SLOT, because a lane is healthy exactly as long as its best slot is. DESIGN, per the standing rules: * PURE function, transport-agnostic. It takes SlotObservation values, so it works the instant they arrive from a structured channel. /slots returns HTTP 000 on our pinned build — that is the follow-up, and the verdict logic must not wait on it. * expected_tps is a PARAMETER, never a constant here. What counts as collapsed depends on model and device; the catalog Model row owns that expectation (#441). A constant would be a hardcoded LCD clamp — either missing a real wedge on a fast box or crying wolf on a slow one. * Reads the 3-SECOND rate, not the lifetime average. The same slot read tg=2.53 (bad) while tg_3s=0.05 (dead); averaged over hours, a stopped slot looks merely slow. * Degraded REPORTS, only Wedged is actionable. #446 is the counter-example: starvation stamped as wedge evidence produced a 2-minute relaunch loop that WAS the outage. * A slot under 32 decoded tokens gets no verdict — killing cold generations is [[an-absence-is-an-unfinished-measurement]] wired to an actuator. SIX TESTS, the first two carrying the live numbers verbatim: the incident classifies Wedged; the lifetime average provably would have MISSED it (that test guards the leading-indicator argument, not just the constant); merely-slow is reported not reaped; a cold slot is never wedged; no expectation means no verdict; and the same observation flips healthy/wedged with the device's own expectation. INSTRUMENT NOTE, recorded in the module: those numbers were read out of stderr BY HAND, which is the only way they were visible — and that is the exact defect Joel named today ("STDERR/out is never a place for interfacing, just debug"). Reading a log to DIAGNOSE is correct. A control path depending on it is not. This module is the honest half; wiring it to /slots is the other. NOT YET WIRED — no caller, deliberately. The verdict is the testable unit; the actuator (who reaps, when, under what lease) is a separate decision and belongs with the daemon, same doctrine as the wedge flag. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): prefill is not decode — stop the 90s watchdog killing live prefills (the round-killer) MEASURED on the M5, and it is why citizens took ZERO room turns across the probe ledger's 868 minutes while every dashboard read healthy: demand 94,370 tok against a 58,112-token window (over_window 1.62) prefill rate 382 tok/s (timed live: 603 tok → 17.7s; 5,728 tok → 31.1s) ⇒ first byte ~170 s for a window-sized prompt watchdog 90 s ← fires first, every single time 44 `persona.settle.deliberation_retry` rows carry the verdict the watchdog reached: "the slot HAD started our work and then stopped mid-stream, so the backend is stuck or dead". It was neither. Atlas re-sent the byte-identical 94,370-token demand 21 minutes later and died the same way. The cascade is what made it a round-killer rather than a slow turn: the ambient permit is held across that wait, so three permits sat occupied ~90s each by turns that could never finish. Measured +4 yields/min, EXACTLY, for 25 consecutive minutes, zero successes — the perfect periodicity is the tell, since real contention is bursty. ROOT CAUSE, one line and not a missing feature. Both budgets already existed and both were correctly sized for their own job: STREAM_IDLE_TIMEOUT_SECS (90s) is a DECODE watchdog by its own doc ("a token every few hundred ms"), and PRE_STREAM_HEADER_TIMEOUT_SECS (300s) is documented as "sized for a worst-case full-window prefill queued behind co-tenants (minutes)". The adapter switched from the second to the first the instant ANY progress arrived — and llama.cpp emits a prompt_progress frame at 0% ingestion purely "to signal the client that the request has started processing". So the decode watchdog policed the prefill, and the budget written for exactly this case was skipped past within seconds. FIX: `inference::stream_liveness` — a pure, transport-agnostic phase machine (Queued / Prefilling / Decoding) that names the distinction once so no caller re-derives it. Bulk work gets the bulk budget; the drip gets the drip budget. Deliberately preserved: - #385 keeps its teeth. Liveness is still keyed on the GAP BETWEEN PROGRESS EVENTS, never elapsed total, and the stamp still requires `processed` to STRICTLY advance — so a slot replaying a frozen counter still fails, just at the prefill budget. - #446 keeps its diagnosis. `has_started()` still separates never-started (dead backend vs oversubscribed queue) from started-then-stopped. - Decoding is TERMINAL, so a late/stray progress frame cannot re-open the generous budget mid-decode. My own test caught that the first implementation could. - Providers that never report prefill (every cloud adapter) go Queued → Decoding on first output, so their budgets are bit-for-bit unchanged. Strict addition, never a relaxation. Phase transitions are detected at ONE site per kind rather than repeated at each of the four output sites, so a new output kind cannot forget to declare itself. 7 new tests carry the live incident numbers verbatim, incl. the 0%-frame case that IS the outage and a regression guard for no-prefill providers. 36/36 existing openai_adapter tests green. Design + the full measured chain: docs/architecture/ADMISSION-IS-UNOBSERVABLE.md (also records the admission-snapshot gap and the seven wrong reads it took to get here — two of them my own instruments lying, not the system). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * feat(inference): probe the prefill fix — "no retries" is an ABSENCE and proves nothing Self-correction. I shipped the phase machine and emitted NOTHING for it, then read "RETRIES: 0, TURNS: 0" off the ledger and could not say whether prefills now survive or nothing was running. That is the same unobservable-state defect the design doc in the previous commit exists to complain about, committed by me one commit later. Two rows, both at the seam that actually decides: - `inference.prefill.rescued` — fires ONCE per stream, only when a prefill has already outlived the OLD decode budget AND is still advancing. Every row is a turn that under the previous flat 90s would have been killed here and retried forever. This is a POSITIVE signal for a fix whose symptom is an absence. - `inference.prefill.complete` — total / cached / fresh / elapsed_ms / tok_per_s / would_have_died, at the prefill→decode edge. This is the number the 90s constant was implicitly guessing at, and the one the budget should eventually be DERIVED from per model+device (#441). It also finally measures the KV cache's REAL contribution per stream (`cached` vs `fresh`), which is the instrument the KV ordering work has been owed. Joel, mid-session: "Have to probe better." Correct — a fix I cannot see working is a fix I have not proven. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): split queue-wait from ingest in the prefill receipts — a probe that mixes two regimes measures neither First cut of `inference.prefill.complete` produced absurdities that were the conflation talking: a 467-token prompt "prefilling at 1 tok/s for 231s". It was queued ~230 of those seconds waiting for a slot. llama.cpp's 0% progress frame marks slot ASSIGNMENT, so the honest split is: queued_ms = stream open → first progress frame (admission/oversubscription, #234) ingest_ms = first frame → prefill complete (real ingest work) `ingest_tok_per_s` is now computed over ingest only — the number a derived per-model budget must come from (#441). `rescued` rows carry `queued_s` for the same reason. Source-read while here (vendor llama.cpp): prefills ARE continuous-batched across slots (`can_batch_with` + cont_batching), so concurrent prefills share compute by design. The 230s waits mean all 4 slots were OCCUPIED — by window-scale re-prefills that zero KV reuse makes ~5 minutes each. Queue wait is downstream of the KV defect; the split makes that attributable per stream instead of argued. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(inference): a loading lane must not latch slot affinity off — the boot race that undid persona pinning every launch slot_for_persona (2026-07-11) pins each persona's prefix to its own llama-server slot. It has likely been latched OFF on virtually every boot since: the /props probe latched SlotAffinity::Unsupported on ANY non-success status, and personas start deliberating while the lane still answers 503_loading (measured ×93 in this ledger). One probe racing the load window → pinning dead for the process's life → prefix-similarity slot theft → cached: 0 mid-conversation, measured today. Only 404/501 — "no such surface" — may latch. Extracted the verdict as props_status_proves_endpoint_absent() and pinned it with a regression test carrying the incident: 503/500/502/429 defer and re-probe; 404/501 latch (without that, every cloud provider would re-probe per persona request forever). A malformed body from a live server also defers now — mid-load servers answer partial bodies. Observability, same lesson as the prefill probes ("no rows" must be distinguishable from "latched off silently for weeks"): - inference.slot_affinity.pinned — once per persona pin, proves affinity is LIVE - inference.slot_affinity.evicted — names the victim; cross-persona eviction IS the KV-clobber event and must be priced (KV-CACHE-ECONOMY: a decision, not an accident) - inference.slot_affinity.deferred / .unsupported — the latch decision itself Measured on the previous build (6dea7c4, 10-min window) with queue/ingest split: queued=0s on ALL streams — no slot wait; the residual is ingest-share under continuous batching. First nonzero mid-scale KV reuse ever recorded (cached=2912 of 21002) with affinity still latched off; this fix targets exactly that number. Two died_old=1 prefills (163s, 192s) completed that the old watchdog would have killed. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(persona): 'never thought' is a state, not a 584-million-year idle — the renewal probe stops stamping u64::MAX idle.unwrap_or(u64::MAX) printed idle_ms=18446744073709551615 into the ledger (seen live 2026-08-21). The gate logic was right; only the receipt lied. [[unknown-is-not-a-quantity]]: the unknown gets a word ('never-thought'), never a sentinel number a reader must recognize by its astronomical size. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs: resolution log — all four fixes proven live same-day (retries 0, first slot pins ever, 99.7% KV reuse on byte-stable prompt) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * docs: citizen act observed post-fix; deaf-kickoff scoped to subscription coverage (cursor layer exonerated) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(bench): clone_at serializes per destination — the race that voided sympy-18057's finished artifact at grading The 2026-08-18 grade loss, root-caused: `clone_at` removes its destination at entry AND razes/renames it at the commit point, while the protocol legitimately wants the same instance's tree more than once (her work tree + the pristine score tree; a lapsed-claim auto-grade racing a re-stage). Concurrent callers deleted each other's trees mid-use. The trigger was a Node-era assumption fossilized in a path: staging is `cloning-{pid}`, unique when every clone was its own process — but in the headless core every clone shares ONE pid, so two concurrent stages computed the SAME staging path and the stale-staging sweep deleted a LIVE clone mid-fetch: "repo.cloning-78289/.git/: No such file or directory" — a finished artifact voided at scoring. Fix, constraint-first: - One live clone_at per DESTINATION: per-repo_dir tokio::Mutex registry (async lock — the section awaits git subprocesses throughout; keyed by repo_dir, not instance, so a 300-instance sweep does not serialize globally). - staging_path_for(): pid + per-invocation nonce, extracted pure for testability. - Dead-staging sweep by `<name>.cloning-` prefix instead of exact-name match — with nonced names an exact match can never find a crashed run's leftovers, and unswept litter violates the no-cache-dir-without-an-eviction-story rule (2026-07-13). Two regression tests carry the incident: staging uniqueness + sweepable prefix, and lock identity per destination. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(bench): a round survives the core that opened it — persist in-flight rounds, reload on first touch Measured twice on 2026-08-21: the ROUNDS map was process-memory, so a reboot mid-round (1) blanked `benchmark/rounds` while a staged round was live — the operator re-derived the round from probe archaeology — and (2) silently flipped driver_for_card back to DetachedSolve for a Citizen round's remaining cards, quietly rebuilding the parallel runner the round was configured to avoid. With "restart freely" as standing doctrine, every deploy was round-murder: 8 of the 20 most recent runs on this box carry "killed by a core restart". The round is now durable state, same family as the airc attach cursor: one JSON file per in-flight round under ~/.continuum/state/bench-rounds/, written on every mutation (open / add_card / settle / seal), removed at Done. First touch of ROUNDS reloads — no boot hook; the first driver_for_card after a reboot already answers from the reloaded round. bench.round.reloaded announces each recovery. Eviction story (the 2026-07-13 rule): files self-evict at Done, and a Done file surviving a crash window is dropped AND deleted on reload, never resurrected as a round no event can settle. Persist failure degrades to the old amnesia and WARNS — durability must never fail a live dispatch. HONEST LIMIT, stated in code: cards that reached terminal state while the core was down still read as working until the next event. Re-deriving card state from the board at boot — and consuming the orphan-reap report (`needs_redispatch: true`, which nothing consumes today) — is the follow-up reconciler, per ROUND-LIFECYCLE-AS-RECIPE-OWNED-STATE-MACHINE.md. This commit restores the round's EXISTENCE, which is what every later reconciler needs first. Two regression tests carry both measured defects. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo * fix(bench): round tests persist to a temp dir, never the operator's real state Caught within the hour: the persistence layer resolved $HOME unconditionally, so the EXISTING tests — which exercise the public open_round/add_card — minted four phantom rounds into ~/.continuum/state/bench-rounds across two cargo test runs, and the next live core faithfully reloaded them (in_flight: 5 with one real round). A durable layer's tests must be durable somewhere disposable: cfg(test) resolves to a per-process temp dir. Verified: full bench_round suite leaves the real state dir untouched. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
GpuPriorityenum (Realtime/Interactive/Background/Batch) with pressure-gated allocation. Low-priority work rejected at lower thresholds so real-time tasks never starve.gpu/eviction-registry,gpu/eviction-candidates.GpuPressureWatcher+ResourcePressureWatchersingletons with adaptive polling and Events emission on threshold crossings.sysinfo0.33 in Rust../jtag system/resourcescommand with top processes by CPU/memory.Test plan
./jtag system/resources --includeProcesses=truereturns real CPU/memory/process data./jtag gpu/statsshows allocations_by_priority counts./jtag gpu/eviction-candidatesreturns sorted eviction listnpm run build:ts)npm start+./jtag ping)🤖 Generated with Claude Code