Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Focus shared-core patch on runtime, regression tests and current documentation
Jeremiah Ritchey4ac028522e40
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 5e97ffeee..0d043b752 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -402,7 +402,7 @@ moving spare row are preserved, including checkpoint rewinds. These developmentchanges and the optional disk-tier boundary are described in the[shared-core proposal](plans/shared-conversation-snapshots.md).The engine log reports parking, restoration, bytes and evictions. Snapshots are not-persisted across restarts. See [the design and validation gates](plans/multi-conversation-cache.md).+persisted across restarts. See [the design and validation gates](plans/shared-conversation-snapshots.md).**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chatsre-reads the other one unless the opt-in cache above is enabled); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p /diff --git a/docs/plans/agent-cache-benchmark.md b/docs/plans/agent-cache-benchmark.mddeleted file mode 100644index 747891364..000000000--- a/docs/plans/agent-cache-benchmark.md+++ /dev/null@@ -1,50 +0,0 @@-# Controlled local Pi cache comparison--`tools/agent_cache_benchmark.py` runs a bounded real coding task through the Pi-SDK with parking disabled and enabled. It defaults to a dry run and never uses-an existing server. `--run` requires an exclusive GPU window, the configured-model assets, Node.js, and an installed `@earendil-works/pi-coding-agent` package.--Both runs start from identical files and use the same working-directory path,-prompts, model configuration and tool limits. Each loads a fresh private server.-The workflow is controller A implementing a CSV-report library, worker B adding-its CLI, then A returning to verify/fix the integration. This exercises real file-edits and shell checks rather than replaying prerecorded model responses. The-input corpus is generated public test data, not a user conversation.--The task uses the Python standard library. Ten independent checks cover UTC-date grouping, decimal sums, sorting, invalid input, last-valid duplicate IDs,-quoted commas, file/stdin CLI behavior and missing-file status. These validators-run outside the agent workspace after the workflow finishes. A model's assertion-that the task succeeded is not accepted as validation.--Each phase allows 24 executed tools, 32 model turns and 240 seconds. Bash calls-are limited to 15 seconds and returned text to 16,000 characters per tool result.-Requests use greedy sampling, disabled thinking, and at most 2,048 output tokens.-No compaction, skills, discovered extensions, inherited context files or remote-model catalogs are loaded. Generated event logs remain local; review them before-publishing any benchmark artifact.--Example (paths to the local model configuration and Pi installation are supplied-by the operator):--```sh-python tools/agent_cache_benchmark.py \- --config /path/to/engine-config.json --engine build-validation/strata \- --pi-package /path/to/node_modules/@earendil-works/pi-coding-agent \- --output /path/to/new-results --run-```--Use a fixed expert allocation small enough that neither engine trims it for-VRAM headroom. The harness rejects mismatched engine settings. `--order on,off`-supports a reverse-order repetition; changing the order is not a substitute for-reporting repeat variability.--Results include task wall time (excluding model startup), per-phase/tool times,-prompt/decode times, token reuse and generation volume, engine configuration,-independent success status, generated files, and the engine's Linux kernel-high-water RSS. RSS includes startup and model mappings; it is not a system-wide-or GPU peak-memory measurement. Normal speculative inference can produce-different tool paths, so report output/task differences and do not infer a-general speedup from a single pair. This local workload does not reproduce the-earlier remote Windows game-building workflow.diff --git a/docs/plans/multi-conversation-cache.md b/docs/plans/multi-conversation-cache.mddeleted file mode 100644index 0a2cb070a..000000000--- a/docs/plans/multi-conversation-cache.md+++ /dev/null@@ -1,240 +0,0 @@-# Multi-conversation caching--## Objective and evidence--Keep Pi controller and worker conversations warm when their requests interleave,-without requiring a Pi-specific session ID or changing the generated prompt.-The existing server caches one conversation. Observed controller requests reread-46,856, 46,974, and 47,644 tokens after worker requests, spending 143 seconds in-prompt processing. A subsequent packet capture verified 21 continuing turns with-unchanged history and reasoning: do not modify Pi's reasoning serialization.--This feature does not shorten tool results or fix the separate, unproven cause of-one historical within-conversation 12,038-token replay.--## Design--- Opt-in engine flags: `--conversation-cache-mib N` (default 0/off) and- `--conversation-cache-slots N` (default 4 parked conversations).-- Keep existing single-conversation behavior and fast-path cost when disabled.-- Search the active state and parked states for the longest exact token prefix.- Images and control-vector mode must also match. Prefer active state on ties.-- Before overwriting an eligible active state, snapshot its running state,- checkpoints, main-layer K/V, completed indexer rows, and draft-layer K/V.-- Park in ordinary host RAM, not additional VRAM. Preserve graph-bound addresses- by copying back into existing allocations. Streamed K/V snapshots use the- authoritative host pools; restore invalidates main-layer residency maps and- refills the draft ring before reuse.-- Save only used pages, not the full maximum context allocation. Full pages- preserve the page/head/cell layout, including partially filled final pages.-- Evict least-recently-active parked entries to satisfy slot and byte limits.- Count an incoming restore image against the byte budget during an exchange.- An oversized snapshot or allocation failure skips parking, not inference.-- Cache misses retain normal prompt processing; image or steering changes cannot- reuse incompatible state. No persistence to disk and no raw conversation logs.-- Keep checkpoint fallback available inside each parked conversation.--The budget covers snapshot payload allocations, including retained checkpoint-buffers. It is additional to the active engine's normal state/checkpoint memory;-allocator bookkeeping and small container overhead are not exact RSS accounting.--## Correctness gates--1. CPU policy tests: A/B/A reuse, checkpoint fallback, image identity, steering- isolation, longest prefix and ties, byte/slot eviction, oversized entries,- disabled cache, short/equal prompts, and in-flight restore accounting.-2. Snapshot tests: byte-exact save/restore across FP16, INT8 and Q4 K/V, resident- and streamed layouts, draft rings, partial pages, and indexer boundaries.-3. Full engine builds; disabled option retains existing behavior.-4. Controlled A/B/A serving parity versus an uninterrupted A baseline, including- returning through a checkpoint, with fixed expert residency and deterministic- sampling. Verify restore tokens and compare running/KV state hashes.-5. Measure long-context switching time and memory bounds; test budget eviction- and cancellation. Do not claim end-to-end speedups from component tests.--## Operational constraints--Full-model tests load private engines and require an available GPU. Run them in-a maintenance window or on separate hardware; do not load a second model beside-a production engine unless there is sufficient GPU and host memory.--## Status--This document's historical results describe the original prototype and its-0.1.15 integration. The separate 0.1.18 development branch now has a-[shared-core proposal and acceptance checklist](shared-conversation-snapshots.md).-Its audit found that the original snapshots/fingerprints omitted `idx_dead` and-the moving indexer spare row; the new core preserves these and the new harnesses-require the expanded fingerprint. Earlier parity results remain valid only for-the fields and fixtures actually measured, not those previously omitted fields.--Feature implemented; all five correctness gates above have passing evidence for-the original feature revision `9d154ed`, before the upstream integration below.-Verified on 2026-09-28:--- Full CUDA 13.4 / SM89 portable-AVX2 engine build and help smoke test pass.-- CPU policy: 35 checks pass, also under AddressSanitizer/UBSan.-- GPU snapshots: 891 checks pass across FP16/INT8/Q4, resident/streamed/ring- storage, zero/full/partial pages, indexer boundaries, malformed payloads, and- incompatible geometry, and invalid/overflowing extents. GPU fixtures are small- and do not load a model.-- All 17 existing Python server tests pass using mock engines.-- 12 CLI parsing checks pass; new C++ modules pass `-Wall -Wextra -Werror`.-- Seventeen harness unit tests pass normally and under Python `-O`, including- rejection of incomplete evidence, native-IQ window configuration, byte-pressure- evidence validation, offline HTTP orchestration, and no-traffic dry-run checks.--Full-model IQ3_S gates passed in an isolated test window, using a 262144-token-context, INT8 K/V with 32768-resident cells, and the same 8000 expert slots in each paired run:--- Single-token decoding: A/B/A and parked-checkpoint recovery reproduce both- output tokens and byte-exact main-model state fingerprints.-- Speculative decoding (`--spec 4`, suffix drafting off, fixed expert residency):- the same checks pass with 49909-token A and 49911-token B. Main-model state- fingerprints also match, although this gate only requires output parity.-- Initial A prompt read: 48.809 seconds. Returning to A after B: 49909 tokens- reused, 22 new tokens read, 1.961 seconds of prompt processing including- parking/restoring. This is a synthetic switching result, not a general decode- speedup or a matched uncached A/B/A replay benchmark.-- Returning through A's checkpoint: 49924 tokens reused, 7 read, 1.101 seconds.- Parking A used 1352930652 bytes; parking the continued A used 1471553864 bytes.- Restoring a parked state took 182–201 ms in this long-context run.-- HTTP checks on the candidate with normal production speculative/adaptive- settings: A/B/A returns the same text, reusing 1957 of 1964 prompt tokens.- Five intervening distinct conversations evict A; requesting it again reads- from zero. Logs show four parked slots and increasing eviction counts.-- HTTP streaming disconnect after five output tokens: the engine stays alive,- serves an unrelated B, then restores 1054 of the cancelled A's 1061 tokens.- The frontend and engine remained running without a restart throughout these checks.-- Byte pressure: a 400 MiB cache holds each ~254 MiB snapshot individually, but- not two. A/B/C/A produced two byte-driven evictions with only one parked slot- occupied. Output and main-model state match the cache-disabled sequence.-- Oversized snapshots: with a 1 MiB budget, all three attempted parks are skipped;- ordinary inference continues with output and state matching the baseline.-- In-flight budget: A/B/A and checkpoint recovery also pass at 400 MiB. Two- outgoing parks are skipped while the incoming snapshot is held, preserving the- restore and keeping allocated parked/transfer payload within the budget.-- Image isolation: real `GENI` requests with synthetic embeddings reject reuse- when embedding values or image-grid geometry change. Returning to the original- image restores 773 of 780 tokens with exact output/main-model state parity.-- Steering isolation: nonzero synthetic control vectors in both add and project- modes change actual model state. Switching on/off never reuses incompatible- state; returning to each mode restores 766 of 773 tokens with exact output and- main-model state parity. These are cache tests, not steering-quality tests.-- The packaged HTTP smoke test also passes against the restored service:- A/B/A, four-slot eviction, disconnect cancellation and cached recovery. Engine- and frontend remained running without a restart throughout that test.--Raw synthetic test evidence is retained locally in the ignored-`logs/conversation-validation-2026-09-28/`: `spec1-supported`, `spec4-long`,-`pressure`, `oversized`, `exchange`, `image`, `steering-add`, and `steering-project`-(each contains engine logs and `results.json`), plus `http-smoke.json` for the-packaged HTTP check.-The original `spec1` attempt failed at startup because native IQ packs require-engine `--spec >= 2`; the harness now uses the supported configuration below.--`tools/conversation_cache_parity.py` prepares the controlled runtime gate. It-defaults to a dry run and requires `--run` to launch private model processes.-Provide `--config`, `--engine`, and a new `--output` directory. Run first with-`--spec 1` for byte-exact main-model state, then `--spec 4` for speculative output-parity. The single-token gate configures engine `--spec 2 --mtp-max-t 1` because-native IQ packs require a speculative-capable engine even with one-token decode-windows. It compares an uninterrupted A/A+ baseline against A/B/A+, then exercises-a parked checkpoint by switching away and repeating A+. It never connects to an-existing HTTP server. Use only in a separately authorized GPU test window.--The image tests exercise the serving engine's embedding-input and M-RoPE paths,-not a vision encoder or image-recognition quality. The live Pi configuration-remains text-only with no control vector loaded.--### Reproducible checks--The parity script now accepts `--scenario pressure` and `--scenario oversized`.-Both run A/B/C/A with one output token per request, compare against the same-cache-disabled sequence, and require output and main-model state parity. For-this IQ3_S model at the default 128 paragraphs, use `--cache-mib 400` for byte-pressure (one snapshot fits, two do not) and `--cache-mib 1` for oversized skips.-The byte-pressure gate rejects slot-limit eviction as insufficient evidence;-the oversized gate requires all three attempted parks to be skipped. Both gates-passed in the full-model test window.--`--scenario exchange --cache-mib 400` instead runs the A/B/A continuation and-checkpoint sequence while requiring two outgoing parks to be skipped because an-incoming snapshot is still held. This specifically tests the temporary byte-budget during restoration, in addition to ordinary byte-driven eviction. This-gate also passed.--`tools/conversation_cache_isolation.py` takes the same `--config`, `--engine`,-`--output`, and explicit `--run` arguments. Run `--scenario image`, `--scenario add`,-and `--scenario project` in separate new output directories. All three gates-passed. They generate small deterministic embedding/control-vector fixtures and-load baseline/candidate engines sequentially. Do not run any model gate beside-the production engine unless sufficient GPU capacity is separately available.--For standalone component tests, configure with-`-DSTRATA_BUILD_CONVERSATION_TESTS=ON`; build `conversation_cache_test` and, with-CUDA enabled, `conversation_snapshot_test`. Run:--```sh-ctest --test-dir build-conversations -R '^conversation_(cache|snapshot)_test$' --output-on-failure-python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_http_smoke-```--`tools/conversation_cache_http_smoke.py --output NEW_RESULTS.json` defaults to-no traffic. Adding `--run` targets `http://127.0.0.1:11434` (override with `--url`)-and exercises A/B/A, slot eviction, streaming cancellation, and recovery. Use-only with an exclusive idle test endpoint: it intentionally displaces cached-conversations. An idle check cannot lock out new clients, so pause other clients-first. Both the one-off sequence and the packaged script have passed against the-real cache-enabled HTTP server.--### Upstream integration (2026-09-28)--Merged upstream `main` at `d551edf` (engine 0.1.15). The serving INFO-line-conflict was resolved by retaining both engine-version reporting and the-conversation-cache settings. Upstream prefill/MMQ and AVX2 changes are retained.--The merged tree passes a separate CUDA 13.4 / SM89 portable-AVX2 engine build,-35 CPU cache-policy checks, 891 GPU snapshot checks, 12 CLI parsing/help checks,-and 35 Python tests (17 cache-harness tests and 18 server tests).--The merge itself did not restart or reconfigure the running engine. In a-subsequently authorized maintenance window, all eight full-model gates passed-on merged revision `eb6a392`: single-token reuse/checkpoint state parity, long-speculative reuse/checkpoint parity, byte-pressure eviction, oversized snapshots,-incoming/outgoing exchange budgeting, image identity, and control-vector-isolation in add/project modes. The 12-request HTTP smoke test also passed on-an exclusive localhost endpoint with normal adaptive settings, including slot-eviction, streaming cancellation, and cached recovery without a process restart.--The merged long-context test used 51133-token A and 51135-token B, fixed 8700-expert slots, INT8 KV with 32768 resident cells, spec 4, and suffix drafting off.-Initial A read took 46.558 seconds. Returning after B reused 51133 tokens and-read 22 in 1.363 seconds including parking/restoring; checkpoint recovery reused-51148 tokens and read 7 in 0.580 seconds. Both restored outputs and main-model-state fingerprints match the uninterrupted baseline. This synthetic switch test-is not a matched performance comparison against the original feature binary.--Evidence is retained locally under the ignored-`logs/upstream-merge-validation-20260928-F1emt1/` directory, including paired-engine logs/results and `http-smoke.json`. The earlier measurements above remain-specific to the original feature revision.--## Deployment and rollback--The original Pi trial used an 8192 MiB host-RAM budget and four parked slots, with-the existing text-only model configuration otherwise unchanged. HTTP health-and generation checks pass; image/steering tests ran in separate private engines.--After the upstream-integration gates passed, the merged engine was deployed-with the same 8192 MiB/four-slot cache settings. The normal launch configuration-selects the merged binary; the prior binary and configuration are preserved for-rollback. Final HTTP generation and idle/empty-queue health checks passed.--To try this feature, preserve the original binary and configuration, then add-the two opt-in flags to the engine arguments and restart in a maintenance window.-To disable parking, remove the flags or set `--conversation-cache-mib 0` and-restart. To roll back the binary, gracefully stop the candidate, verify its engine-exited, then start the original binary with the original configuration. Never-start both model processes on the same GPU without sufficient free memory.diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.mdindex 0b4699e36..f7cfc4d0b 100644--- a/docs/plans/shared-conversation-snapshots.md+++ b/docs/plans/shared-conversation-snapshots.md@@ -1,159 +1,73 @@-# Shared conversation snapshots: convergence proposal--Status: shared-core development for issues/PRs #41, #52 and #57. In the issue's-September 28 follow-up the maintainer asked @jeremiahritchey to own the unified-PR, @midhatn to review Windows admission/acceptance, and @maedoc to layer optional-NVMe persistence on the core. The September 29 follow-up permits the single-GPU-core to land first. This is not a merged upstream feature or acceptance of the-separate disk implementation.--The original evidence targets upstream `b38c183` (0.1.18). Current integration-is based on `8fc40dd` (0.1.25), fetched September 29 after main advanced beyond-the requested 0.1.22. The earlier branches and their evidence remain separate.-Parking rejects `--layer-split` while ordinary upstream multi-device checkpoint-handling is retained. Checkpoint LRU stamps and system-prompt/root retention are-preserved. K8V4 snapshots store separate INT8 K/scales and Q4 V payloads; hybrid-streaming/ring layouts are rejected before calling upstream's block movers.-See the [current integration and validation record](shared-conversation-upstream-validation.md)-for revision-specific evidence and platform limits.--## Boundaries--1. **Snapshot core:** own the in-memory representation, checked sizing,- capture, complete non-mutating validation, and restore into existing session- allocations. Validate all layers, running state and checkpoints before the- first destination write. No cache policy, filesystem I/O or client markers.-2. **RAM policy:** longest compatible exact prefix, active wins ties, bounded- payload bytes and slots, LRU eviction. Incoming/outgoing exchange payloads- count together. Off by default. A failed admission is a normal cache miss.-3. **Disk adapter (separate contribution):** use the same state representation,- but do not serialize C++ structs, pointers or native vector layouts. Define a- versioned envelope and bounded streaming/staging explicitly before integration.--The serve loop selects a resume point and publishes new token/image/checkpoint-metadata only after successful restore. It must not infer that a failed transfer-left the old session usable.--## State checklist--| State | Representation or reconstruction |-|---|---|-| Token/image identity and steering | Exact IDs, image identity/grid hashes, immutable engine steering configuration plus per-request enabled state |-| GDN | Recurrences and convolution history, in live state and every retained checkpoint |-| PLE | Normalized history; previous token window reconstructed from the checkpoint IDs |-| QSA KV | Used, page-rounded identity-layout cells, all codes/scales for FP16/INT8/Q4; authoritative host pools for streamed layers |-| Indexer | Completed pooled rows, raw tail, per-sequence spare key (`idx_dead`), and block-position metadata; rebuild the spare pooled row at the selected resume point |-| MTP | Used authoritative draft KV; refill its resident ring at the selected resume point |-| Residency | Invalidate replaceable streamed maps; keep graph-bound addresses stable; do not treat outgoing VRAM slots as authoritative |-| Compatibility | Runtime geometry, layout and buffer extents; persistent identity additionally binds exact weights/tokenizer/steering/schema |--The first #57 implementation omitted `idx_dead` and block-position metadata;-fixtures with identical opening tokens can mask the spare-key omission. Include-distinct spare keys in the component regression and different opening prefixes-in future model gates. Do not describe earlier state hashes as coverage of these-previously unmeasured fields. Scratch recomputed before use (attention scores,-step/position uploads, graph intermediates) is not part of the persisted state.--## Failure contract--- Invalid snapshot: reject before CUDA synchronization/copies or destination- writes; discard that entry and retain a valid active prefix or perform normal- clean prefill. Do not discard the outgoing state before validating the incoming- candidate.-- Allocation/admission failure: skip parking, preserving active inference.-- Transfer/synchronization failure: return a distinct fatal outcome. The caller- reports an error and exits so the server can restart on the next request. A- future clean-reset recovery needs its own proof that the CUDA context remains- usable; validation does **not** make GPU failures transactional.-- Resume metadata is committed only after successful state application.--## Memory admission--Keep logical byte/slot capacity separate from physical-memory headroom. Proposed-flag: `--conversation-cache-min-free-mib` (default 2560, matching #41's starting-floor). Before allocating, require known available physical memory sufficient-for the estimated new payload plus that floor. Check again after capture; if the-floor is no longer met, discard the temporary image. Telemetry already includes-incoming images and parked allocations: do not subtract them a second time.--Use `GlobalMemoryStatusEx` on Windows and `MemAvailable` on Linux. Unknown or-malformed telemetry declines parking. These are instantaneous admission samples,-not a reservation against other processes. Host telemetry alone does not enforce-cgroup/job limits; container-aware limits and Windows runtime verification need-review. Disabled caching must not sample telemetry or allocate snapshots.--## Disk interface questions for review--- A spill consumes an evicted immutable snapshot. If persistence fails, should- eviction still drop it, or may policy retain it within the existing bound?-- A promoted snapshot must reserve its staging bytes before reading. Either use- an explicitly bounded whole-image reservation or a validated streaming format;- a digest pass alone is not safe if the file can change before the apply pass.-- Bind model/weights, tokenizer, all geometry/KV layout, control vectors and- scales, image identity, and schema. The current RAM-only steering boolean is- not a persistent model identity.-- Use atomic publication and reject truncated/corrupt/foreign snapshots. Specify- local permissions, retention/deletion and privacy: disk contains conversation- tokens and model state, unlike the current RAM-only feature.-- Eviction-only spilling does not promise that the latest active turn survives- a crash. Decide whether shutdown/periodic persistence is a separate opt-in.--## Acceptance and remaining work--Use #57's existing component/parity harnesses as a starting point, not a complete-acceptance contract. Add CPU tests for unknown/low memory, arithmetic boundaries,-late-layer and checkpoint rejection before mutation, PLE mismatch, zero-QSA and-256/512-expert geometries; GPU round trips with distinct indexer spare keys;-transfer-failure tests; and a dry-run-by-default known-answer 30-cycle soak.--Full-model testing must cover histories beyond resident KV at several lengths,-including near the configured limit, and compare exact answers plus the restored-state. Add real-encoder image smoke separately from synthetic embeddings.-Persistence/restart/corruption/staging tests belong with the disk adapter.-A controlled real Pi/Hermes task comparison still needs reproducible task inputs,-independent success validation, timings and peak memory. No existing synthetic-benchmark substitutes for that evidence.--No unified PR should claim the whole contract until these gates and the-collaborators' interface/ownership review are complete.--## Development checks--Revision-specific results and coverage limits are in the-[validation record](shared-conversation-validation.md).--The first development pass implements the RAM-side shared core and host-memory-admission; it does not connect the NVMe tier or define a stable disk ABI. Configure-with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON` and build/run these targets:--```sh-cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test-ctest --test-dir build -R '^conversation_(cache|memory|snapshot|validation)_test$' --output-on-failure-python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_http_smoke tools.test_conversation_cache_soak-```--`conversation_validation_test` links CUDA but runs with devices hidden and checks-invalid-image rejection without CUDA initialization. On GNU/Clang ELF platforms,-also build `conversation_transfer_test`: link-wrapped host copies/synchronization-inject first-copy, partial-copy and final-sync failures into the real restore-control flow. This demonstrates fail-closed outcomes, not hardware-context recovery.-Run that target with `ctest --test-dir build -R '^conversation_transfer_test$' --output-on-failure`.-`conversation_snapshot_test` uses small real-GPU fixtures, including distinct spare-keys, early checkpoint rewinds and both expert-count metadata variants. Geometry-fixtures are not a full-model Coder run.--The private parity script's `--scenario admission --min-free-mib N` gate requires-three physical-memory admission skips, no budget-related skips, and unchanged-output/state. Choose an `N` above the machine's available physical RAM to test-denial without actually exhausting memory.--`tools/conversation_cache_soak.py` defaults to no I/O or model loading. With-`--config CONFIG --engine ENGINE --output NEW_DIRECTORY --run`, it runs at least-30 A/B/A cycles across three approximate lengths (`--prompt-tokens 2048,40000,120000`).-Select lengths for the test configuration: the largest must cross resident KV and-reach at least 90% of maximum context, while leaving room for the continuation.-It checks known secret-code answers, token/state parity against uninterrupted-baselines, cache reuse and a steady-state retained-payload plateau. Request-end RSS-samples are diagnostics, not a transient peak-memory bound. This is a synthetic-soak, not the requested real Pi/Hermes task benchmark. Run all model gates only in-an exclusive GPU window; no existing HTTP service is contacted by these scripts.+# Conversation snapshots and RAM cache++[Issue #57](https://github.com/Niko1221/Strata/issues/57) preserves reusable state+when independent agent conversations alternate on one server. Requests remain+serial, require no client session markers, and restore into existing allocations.+The shared core and RAM policy land first; the optional NVMe tier is a dependent+integration, following the [maintainer's requested order](https://github.com/Niko1221/Strata/pull/52#issuecomment-5898176448).++## Ownership and matching++- `conversation_snapshot.hpp`, `conversation_snapshot.cpp`, and+ `conversation_state.cpp` define complete capture, validation and restoration.+ They contain no retention policy or filesystem operations.+- `ConversationCache` owns inactive snapshots, selects the longest exact token+ prefix with matching image/grid identity and steering state, and evicts the+ least recently active entries. Active state wins ties.+- The serve loop parks before a switch or checkpoint rewind overwrites state.+ A continuing request does not trigger a snapshot. Checkpoint root/LRU behavior+ from upstream is retained inside each conversation.++Snapshots include live and checkpoint GDN/PLE state, page-rounded used main KV,+indexer pooled rows/tail/spare key/block position, and used draft KV. They exclude+scratch recomputed before use. Restoring an early checkpoint reconstructs the+spare pooled row and PLE token history. Streamed KV uses authoritative host pools;+restore invalidates replaceable VRAM maps and refills the draft ring. Device+addresses remain stable for captured graphs.++FP16, INT8, Q4 and identity-layout K8V4 are represented explicitly. K8V4 stores+INT8 K/scales separately from Q4 V; it does not use the block movers' format enum.+Hybrid streaming/ring layouts and whole-conversation layer-split parking are+rejected. Ordinary upstream layer-split checkpoints remain available.++## Capacity and failure handling++`--conversation-cache-mib` defaults to zero (disabled),+`--conversation-cache-slots` to four, and `--conversation-cache-min-free-mib` to+2560. `--prompt-cache 0` disables parking and produces a warning when requested.++The byte budget counts vector capacity, retained checkpoints, and incoming+snapshots held during an exchange; it is additional to the active session and+is not an exact RSS limit. Estimate before allocation, then check physical RAM+using Linux `MemAvailable` or Windows `GlobalMemoryStatusEx`. Unknown telemetry+rejects admission. Check the free-RAM floor again after capture. These samples+are not reservations or cgroup/job-limit enforcement.++Oversized entries and allocation/admission failures skip parking. Validate the+entire incoming image before modifying the outgoing session; invalid images+are discarded and ordinary prefix selection/prefill remains available. Transfer+or synchronization failures may leave partial GPU state, so the engine reports+an error and exits rather than continuing inference. Publish resume metadata+only after successful restore. Validation is not a transactional GPU rollback.++## NVMe integration contract++The disk adapter must consume this representation and restore through this core,+without another state-copy implementation. Spill immutable snapshots on RAM+eviction; disabled persistence performs no filesystem operations. A disk hit+competes with active/RAM prefixes and must reserve an explicit bounded staging+allocation plus physical RAM headroom before reading.++Persist a versioned portable envelope, not native C++ objects. Bind exact weights,+tokenizer, steering configuration, geometry, KV format (including K8V4) and state+schema. Read, integrity-check and validate the same staged bytes before applying+them. Atomic publication must reject interrupted, truncated, corrupt and foreign+entries. A failed spill may drop the already-evicted entry; it must not exceed+RAM limits or stop inference. Eviction-only persistence does not promise that+the latest active turn survives a crash. Files contain conversation content.++The adapter is being integrated from @maedoc's #52; disk restart/corruption,+staging-budget, compatibility and eviction/promotion tests remain required.+Windows admission coverage includes @midhatn's contribution, preserved with its+original authorship. See the [validation record](shared-conversation-upstream-validation.md)+for results, commands, and hardware limits.diff --git a/docs/plans/shared-conversation-upstream-validation.md b/docs/plans/shared-conversation-upstream-validation.mdindex 0910f9f09..5aa0ac794 100644--- a/docs/plans/shared-conversation-upstream-validation.md+++ b/docs/plans/shared-conversation-upstream-validation.md@@ -1,171 +1,74 @@-# Shared-core integration onto upstream 0.1.25--Integration base: upstream `8fc40dd`, fetched 2026-09-29. Implementation starts-at `cabd50c`; Windows test contribution is preserved as `b319d43` (original-`32cf918`, by @midhatn). The earlier 0.1.18 validation record describes a different-revision and remains historical evidence.--Issue #57 references: [unified PR ownership](https://github.com/Niko1221/Strata/issues/57#issuecomment-5875083621),-[current upstream/single-GPU scope](https://github.com/Niko1221/Strata/issues/57#issuecomment-5887959836),-and the [Windows test contribution](https://github.com/jeremiahritchey/Strata/pull/1).-Upstream had advanced from the requested 0.1.22 to 0.1.25 when fetched; this-record pins the exact revision rather than referring to a moving main branch.--## Integration decisions--- Preserve upstream's root-pinned/LRU checkpoint policy and retain last-use- stamps when parking a conversation.-- Preserve the existing layer-split checkpoint representation. Whole-session- parking with `--layer-split` is explicitly rejected before loading the model;- multi-GPU parking is deferred as permitted in issue #57.-- Retain chunked indexer processing and restore the per-sequence spare key,- block-position metadata and spare pooled row at checkpoint resume.-- Add K8V4 snapshot layout support: independently size/copy INT8 K, K scales and- Q4 V; the draft ring remains plain INT8. Reject hybrid streaming/ring layouts.-- Use the selected CUDA/HIP runtime target in CMake; CUDA linker-wrap fault- tests are not registered for HIP. No HIP runtime validation is claimed.--## Windows review--The contributed change modifies only `conversation_memory_test.cpp`. Under-Windows it checks that `GlobalMemoryStatusEx` succeeds and that the helper's-sample is known and no larger than total physical RAM. Comparing against total-RAM avoids a race between two available-memory samples. It neither allocates-pressure memory nor changes admission behavior. No review defect was found.--This machine cannot run Windows/MSVC tests. The contributor reported 25 passing-MSVC checks in their PR; those are their results, not locally reproduced results.-Local Linux compilation runs the existing 23 admission checks. Full Windows-restore, memory-pressure and agent acceptance remain outstanding.--## Local environment and evidence--Linux, EPYC 7532, RTX 4090; GCC 15.2, CUDA 13.4, Release build, SM89, portable-AVX2. IQ3_S model; INT8 KV, 131,072 context and 32,768 GPU-resident KV cells for-the primary full-model gates. Engines run sequentially on the exclusive GPU.--The private evidence directory is `logs/upstream-20260929/`. For paired model-tests, `--expert-cache 6000` yields 7,846 variable-sized expert slots; the PCIe-share is fixed to 0.55. Both engines must report matching residency and other-inference settings. The first attempt requested 8,700 uniform slots, was trimmed-to different residency by VRAM availability, and failed the comparison guard.-That attempt is retained under `spec1/` and excluded from accepted evidence.--The entire optional upstream test build cannot configure because-`bench/micro/native_mmvq_multi.cpp` and `bench/micro/hit_cpu_order_parity.cu` are-absent at this revision. Focused conversation, checkpoint-retention and sampler-targets are built instead. Do not report this as a full upstream test-suite pass.--The controlled local Pi task is documented in [agent-cache-benchmark.md](agent-cache-benchmark.md).-Results below must remain tied to the actual tested executable/configuration;-synthetic reuse timings are not version-to-version performance comparisons.--## Results--Completed checks:--- Seven focused CTest targets: RAM policy, admission, GPU snapshot round trips,- whole-image validation, injected transfer failures, upstream root/LRU retention,- and sampler parity. K8V4 and checkpoint-stamp fixtures are included.-- 65 server Python tests (three skipped) and 47 tool tests passed; the 22 cache- harness tests also passed with Python assertions disabled (`-O`).-- ASan/UBSan: 35 RAM-policy checks, 23 admission checks, and 1,116 host validation/- transfer-failure checks passed. The latter compiles snapshot/state code with- sanitizers and uses wrapped copies/synchronization, not CUDA hardware failures.-- Ten CLI checks: malformed/negative/overflowing options rejected and enabled- layer-split parking refused before loading a model.-- Nine full-model paired gates passed: single-token and long speculative A/B/A,- checkpoint recovery, byte pressure, oversized entries, incoming/outgoing- exchange budget, deliberate RAM-admission denial, synthetic image identity,- and add/project steering isolation.--In the long speculative run, returning to the 55,009-token A reused all 55,009-and processed 22 new tokens in 1.2559 seconds including snapshot work. Checkpoint-return reused 55,024 tokens and processed seven in 0.5746 seconds. Both output-and main-model fingerprints matched the uninterrupted baseline. This is an-intra-revision cache test, not a comparison against 0.1.18.--The 30-cycle soak passed at approximately 2k, 40k and 120k tokens. Every output-and main-model fingerprint matched its uninterrupted baseline. Cache payload-plateaued for each repeated context rather than growing each cycle.--The nine INT8 gates and soak above used executable SHA-256+# Conversation cache validation++The core review branch is being brought onto upstream 0.1.26 (`4c68013`). Results+below belong to the earlier 0.1.25 implementation (`cabd50c` through `1d9e4e7`),+not the new base. The Windows admission test is @midhatn's `32cf918`, retained as+`b319d43`. Historical records and the general Pi benchmark remain on local branch+`feat/conversation-cache-upstream` at `cb8d90c`; they are outside the core patch.++## Recorded Linux evidence (2026-09-29)++EPYC 7532, RTX 4090, GCC 15.2, CUDA 13.4, SM89, portable AVX2, IQ3_S. Paired+engines used 131,072 context, INT8 KV, 32,768 resident cells, 7,846 expert slots,+and PCIe share 0.55. Evidence remains in that worktree's `logs/upstream-20260929/`.++| Gate | Result and scope |+| --- | --- |+| Components | Seven CTest targets passed: cache policy, admission, GPU round trips, host validation, injected transfers, checkpoint retention, sampler parity |+| Python | 65 server tests (three skipped), 47 tool tests, 22 harness tests under `-O` |+| ASan/UBSan | 35 policy, 23 admission, 1,116 host validation/transfer checks passed |+| CLI | Ten malformed/range/layer-split checks passed |+| Full model | Nine paired gates: reuse/checkpoints, long speculation, pressure, oversize, exchange, admission denial, synthetic image/grid and add/project steering isolation |+| Soak | 30 known-answer returns at 2,026 / 39,985 / 119,987 tokens; exact outputs/main-state fingerprints and stable retained payload |+| HTTP | Twelve requests passed reuse, eviction, disconnect and recovery without an engine restart |++The nine INT8 gates and soak used executable SHA-256`0d8cbca38ce27153cea516cf6454df4653196ae875e0224fd3dd3c51e1d27ea0`.-A subsequent full-model K8V4 gate exposed a format-flag mismatch: upstream uses-`kv_hybrid=true` with `kv_int8=false`, while the initial fixture incorrectly set-both. Parking was skipped; the gate failed its reuse assertion. The layout and-fixture now reflect upstream's distinct flags. The failed attempt is retained-in `k8v4/`; final checks use `k8v4-fixed/` and executable SHA-256-`4e174e8a4b602f1f8efe846cf19570478fcc7d2b50f3c48373c799d39b3610c7`.--On the corrected executable, K8V4 and INT8 full-model A/B/A plus checkpoint-parity both passed (including byte-exact main-model fingerprints). The three-snapshot/validation/transfer CTest targets and 1,116 ASan/UBSan transfer checks-were rerun successfully. The twelve-request HTTP smoke passed reuse, slot-eviction, disconnect cancellation and recovery with the same engine process.--The initial Pi pair (`pi-off-on/`) used a 12-tool/16-turn cap. Cache-off hit the-tool cap while correcting its own sample-data test expectations and did not-reach the CLI phase; cache-on completed all ten independent checks in 108.7 s.-This incomplete pair does not support a speedup claim. Both modes were repeated-with the same revised allowance of 24 tools/32 turns per phase; the 240-second-phase timeout, fixed task inputs and independent validators remain unchanged.--Both revised pairs passed all ten independent checks in all four runs:--| Order | Parking | Task seconds | Requests | Output tokens | Prompt seconds | Decode seconds | Engine peak RSS GiB |-| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |-| off → on | off | 91.59 | 20 | 6,319 | 23.259 | 64.865 | 49.734 |-| off → on | on | 108.37 | 28 | 7,361 | 25.750 | 78.780 | 53.433 |-| on → off | on | 104.57 | 23 | 7,274 | 22.823 | 78.350 | 53.433 |-| on → off | off | 111.39 | 26 | 7,525 | 27.948 | 79.471 | 51.979 |--The controller's first return request took 4.334 s with parking off (15,431-prompt tokens, zero reused), versus 1.503 s with parking on (16,333 prompt-tokens, 15,810 reused). Total task time increased in this pair while the-agent followed a different tool path and generated more output. This is not-evidence of an end-to-end speedup. RSS is Linux VmHWM for the engine, including-startup and model mappings, not cache payload or GPU memory.--In reverse order, the return request took 5.777 s with parking off (17,113-prompt tokens, zero reused), versus 1.522 s with parking on (16,165 prompt-tokens, 15,620 reused). Whole-task timing favored cache-on in this repetition-(104.57 vs 111.39 s), reversing the first pair. With different generated output-and tool paths, two pairs do not establish an overall speedup or regression.-The consistent finding is reduced return-prefill work: approximately 2.9–3.8×-faster for these observed requests, with higher engine peak RSS. Prompt lengths-are similar but not identical, so this is a workload observation, not a matched-microbenchmark ratio.--Task wall time excludes server/model startup. All runs used 7,846 expert slots,-INT8 KV, 131,072 context, 32,768 resident cells and the same speculative settings.-The runner verified matching engine settings within each pair. It records-executable/task-script hashes and identical initial-file hashes for each mode;-per-run tool execution totaled 0.96–1.15 s. Private detail is retained in-`pi-bounded-off-on/`, `pi-bounded-on-off/`, and `pi-comparison.json`.--## Scope and remaining validation--These results cover this Linux/RTX 4090 host and the local IQ3_S model. Windows-runtime acceptance, HIP execution, multi-GPU parking, real vision-encoder-integration, and the larger Coder model remain untested here. Synthetic image-identity and model-geometry fixtures do not replace those runtime checks.-The NVMe backend remains a separate integration; this work validates the RAM-backend and shared snapshot representation. No upstream PR or issue comment-was posted as part of this local validation.--This benchmark compares conversation parking on/off within the integrated-0.1.25 executable. It cannot establish whether 0.1.25 is faster or slower than-the earlier 0.1.15/0.1.18 branches, nor reproduce the previous Windows workload.--## Local deployment--The tested executable is running from `Strata-conversation-cache-upstream`,-branch `feat/conversation-cache-upstream`, in tmux pane `%15` on port 11434.-The runtime configuration is `logs/runtime-20260929-191116/engine-config.json`.-It preserves the user's automatic expert allocation, 131,072 context, INT8 KV,-32,768 resident cells, 8 GiB conversation budget, four slots and 2,560 MiB RAM-floor. Automatic allocation selected 8,814 expert slots; this differs from the-fixed 7,846-slot benchmark allocation and is not included in its timing claims.-Health and a non-streaming generation request passed (`OK`), with the server-idle and zero queued requests afterward. Earlier worktrees remain intact.+K8V4 then exposed incorrect hybrid-format flags. After correction, executable+`4e174e8a4b602f1f8efe846cf19570478fcc7d2b50f3c48373c799d39b3610c7`+passed K8V4/INT8 model parity, the three affected CTest targets, the 1,116 sanitizer+checks, and HTTP recovery. The full nine-gate suite was not repeated on that fix.+An initial unequal-expert-residency comparison was rejected, not counted as a pass.++Four bounded Pi coding runs passed ten independent checks each. Return prompt+processing took 4.33–5.78 s with parking off and 1.50–1.52 s with it on, with+similar but unequal prompts. Whole-task timing favored opposite modes in the two+pairs, so there is no demonstrated overall speedup/regression. The benchmark+harness, detailed results and failed preliminary tool-budget trial are separate+from the core patch. These are not version-to-version or Windows measurements.++## Reproduction++Configure the engine normally with `-DSTRATA_BUILD_CONVERSATION_TESTS=ON`, then:++```sh+cmake --build build --target conversation_cache_test conversation_memory_test conversation_snapshot_test conversation_validation_test conv_cache_test sampler_parity+ctest --test-dir build -R '^(conversation_.*|conv_cache_test|sampler_parity)$' --output-on-failure+python -m unittest tools.test_conversation_cache_parity tools.test_conversation_cache_isolation tools.test_conversation_cache_soak tools.test_conversation_cache_http_smoke+```++On GNU/Clang ELF CUDA builds also build `conversation_transfer_test`; it wraps+copies and synchronization for host fault injection. It does not simulate recovery+of a broken CUDA context. GPU fixtures cover partial pages, distinct indexer spare+keys, early checkpoints, zero-QSA and 256/512-expert metadata.++Model tools default to a dry run. With `--config CONFIG --engine ENGINE --output+NEW_DIRECTORY --run`, run parity at `--spec 1` and `--spec 4`, then scenarios+`pressure`, `oversized`, `exchange` and `admission`. Select byte budgets that+actually force the named condition; use a RAM floor above available memory for+denial. Isolation scenarios are `image`, `add`, and `project`. The soak requires+at least 30 cycles and three lengths crossing resident KV and approaching the+configured context limit. HTTP smoke requires an exclusive idle test endpoint.+Run model/GPU gates only in an exclusive test window.++## Outstanding evidence++- Repeat affected build/model gates on 0.1.26, including batched draft prompt KV+ and its fingerprint. Previous main-model hashes excluded draft scratch/state.+- NVMe restart, corruption, foreign identity, eviction/promotion and explicit+ staging bounds; no disk acceptance is claimed yet.+- Windows runtime: only contributor-reported 25 MSVC admission checks, not locally+ reproduced. HIP execution, multi-GPU parking, real vision encoder and full+ Coder-model runs are untested; synthetic fixtures do not substitute for them.+- Full optional upstream test configuration was blocked on 0.1.25 by missing+ `native_mmvq_multi.cpp` and `hit_cpu_order_parity.cu`; focused tests were used.diff --git a/docs/plans/shared-conversation-validation.md b/docs/plans/shared-conversation-validation.mddeleted file mode 100644index 18f27c75c..000000000--- a/docs/plans/shared-conversation-validation.md+++ /dev/null@@ -1,138 +0,0 @@-# Shared snapshot core: validation record--Historical 0.1.18 evidence. The later integration is documented separately in-[the upstream 0.1.25 validation record](shared-conversation-upstream-validation.md).--Date: 2026-09-28. Engine source: `3657b8f`, based on upstream `b38c183`-(0.1.18). This is development-branch evidence for the RAM tier/shared core,-not acceptance of a combined RAM/NVMe implementation or a deployment report.--## Configuration and provenance--- Linux, AMD EPYC 7532, approximately 247 GiB physical RAM, NVIDIA RTX 4090.-- GCC 15.2, CUDA 13.4, SM 89, portable/AVX2 CPU kernels.-- Qwen3.8-Flash-Next-GSQ-RCO IQ3_S; INT8 KV, 131,072-token maximum context,- 32,768 resident KV cells, automatic prefill sizing, 8,817 expert slots.-- Paired engines run sequentially with fixed expert residency. Baseline has- conversation caching disabled; candidate normally has an 8,192 MiB budget,- four parked slots and a 2,560 MiB physical-memory floor. Pressure/oversize/- exchange/admission gates explicitly change the relevant limit.-- Tested executable SHA-256:- `f31d1fe2eecf7d27f440ea1ddfdb39133a16f471c70c1869491582614a16c2f9`.--Do not infer a speedup over the earlier 0.1.15 results: maximum context,-expert residency and prefill configuration differ. These tests compare cache-behavior within this revision, not engine versions.--## Component and offline checks--| Gate | Result |-|---|---|-| CPU RAM ownership/prefix/budget policy | 35 checks passed |-| Available-memory parsing/admission boundaries | 23 checks passed |-| Real-GPU KV and complete-session fixtures | 1,071 checks passed |-| Whole-image rejection before mutation, devices hidden | 780 checks passed |-| Wrapped transfer/synchronization failure control flow | 1,020 checks passed (includes the 780 validation checks) |-| CPU policy/memory and host validation/transfer tests under ASan/UBSan | Passed |-| Python server tests plus cache-harness tests | 45 tests passed |-| Cache-harness tests under Python `-O` | 22 tests passed |-| CLI parsing, help, disabled-feature warnings | 20 checks passed |--GPU fixtures cover FP16/INT8/Q4 KV, resident/streamed layouts, distinct indexer-spare keys, checkpoint rewind, and 256/512-expert geometry metadata. Host fixtures-also cover zero-QSA and PLE-present/absent layouts. Small geometry fixtures do not-constitute a full Coder/pruned-model run. Link-wrapped host failures exercise the-real restore control flow, not actual CUDA hardware-context recovery.--## Full-model private-engine gates--All nine gates below passed with this executable:--1. Single-token A/B/A and checkpoint output/main-model state parity.-2. Long speculative A/B/A and checkpoint recovery beyond resident KV.-3. Byte-pressure eviction and correct cold fallback.-4. Oversized-entry rejection without disrupting inference.-5. Incoming/outgoing exchange-budget enforcement.-6. Image-content/grid identity isolation using synthetic embeddings.-7. Add-mode control-vector identity isolation.-8. Project-mode control-vector identity isolation.-9. Physical-memory admission denied by a 1 TiB floor: three admission skips,- no budget skips or parked entries, and output/state parity for A/B/C/A.--State comparisons include GDN, PLE, indexer tail, `idx_dead`, pooled rows-including the spare row, main KV, previous PLE tokens and consumed length.-Unused draft cells are not part of the main-model fingerprint; draft snapshot-copies are covered by the component fixtures. Earlier prototype fingerprints-did not include `idx_dead` and must not be treated as equivalent coverage.--In the long speculative gate (`spec=4`, `mtp_max=4`, lookup disabled):--| Candidate request | Prompt tokens | Reused | Prompt-path time |-|---|---:|---:|---:|-| Initial A | 51,133 | 0 | 23.3721 s |-| Initial B | 51,135 | 0 | 22.3445 s |-| A continuation after B | 51,155 | 51,133 | 1.2371 s |-| A checkpoint continuation | 51,155 | 51,148 | 0.5659 s |--Return-path times include parking/restoration and the remaining new prompt-tokens, but not decoding. Both A continuations matched uninterrupted baseline-outputs and the complete main-model fingerprints listed above. These synthetic-requests are not a controlled real-agent task benchmark.--## Known-answer soak--`tools/conversation_cache_soak.py --prompt-tokens 2048,40000,120000 --cycles 30`-passed against the same executable. Actual prompt lengths were 2,026, 39,985 and-119,987 tokens (the largest is 91.5% of maximum context). Single-token decode-was enforced with `spec=2`, `mtp_max=1` and lookup disabled.--Each conversation contains a distinct secret word inside its history. After an-unrelated worker request, all 30 returns produced the expected word and exactly-matched uninterrupted baseline output tokens and main-model state fingerprints.-Each size was restored ten times; the final three retained-payload samples per-size were identical:--| Active conversation length | Parked payload after its answer |-|---|---:|-| 2,026 tokens | 4,099,851,588 bytes |-| 39,985 tokens | 3,283,651,392 bytes |-| 119,987 tokens | 1,824,199,544 bytes |--Occupancy differs because the active conversation is not parked; these figures-are not the snapshot sizes of the active conversations. Maximum logged parked-payload was 4,249,016,776 bytes, below the 8 GiB budget. The policy also accounts-for an incoming image held during exchange; the logged parked count alone does-not measure that transient total. Request-end RSS was sampled as a diagnostic,-not as a peak-memory bound or a proof against every allocator leak. Thirty cycles-establish this finite regression gate, not indefinite stability.--## Private HTTP smoke--All 12 requests in `tools/conversation_cache_http_smoke.py` passed on a separate-localhost-only endpoint using the same executable and normal adaptive settings-(reported `spec=6`, `mtp_max=4`, lookup 3, 8,816 expert slots). This was not the-fixed-residency/single-token configuration used for deterministic state parity.--- A/B/A preserved the answer and reused 1,987 of 1,994 prompt tokens.-- Exceeding the four-slot limit evicted A; its next request correctly reused zero.-- A streaming disconnect cancelled after five output tokens; an unrelated- request then succeeded, and returning to the cancelled conversation reused- 1,085 of 1,092 prompt tokens.-- Frontend and engine process identities remained unchanged throughout the- smoke. The private test instance was then stopped; no production endpoint or- configuration was replaced.--## Remaining acceptance work--- Real vision encoder/image-recognition smoke (current image gate uses synthetic- embeddings); full-model 256-expert/Coder coverage.-- Windows runtime/memory-pressure review, including constrained-memory hardware;- Linux container/job-limit-aware admission is not implemented.-- Controlled real Pi/Hermes task with fixed initial files, tool limits,- independent success checks, wall-time breakdown and peak memory.-- Agreed ownership/interface for the unified PR, NVMe adapter, bounded staging,- persistent compatibility identity, corruption/restart/durability tests.--No private conversations, raw request captures, local configuration files or-machine-specific paths are needed to reproduce these synthetic fixtures.-See [the design and test commands](shared-conversation-snapshots.md).diff --git a/tools/agent_cache_benchmark.py b/tools/agent_cache_benchmark.pydeleted file mode 100644index a36dc8fab..000000000--- a/tools/agent_cache_benchmark.py+++ /dev/null@@ -1,192 +0,0 @@-"""Controlled local Pi coding task with cache off/on; private server, dry-run by default.--Requires an installed Pi SDK (--pi-package). Never contacts an existing server.-Only --run creates files or loads a model. Retains generated code, private agent-events, exact inputs, timings, engine metrics and independent validator results.-"""-import argparse-import hashlib-import json-import os-from pathlib import Path-import shutil-import signal-import subprocess-import sys-import time-import urllib.request--ROOT = Path(__file__).resolve().parents[1]-SPEC = '''Implement a Python 3 standard-library expense report.-report.py exports summarize(text: str) -> list[dict]. Input is CSV with headers-id,timestamp,team,amount. Strip surrounding whitespace in values. A valid row has-a nonempty id and team, an ISO timestamp WITH timezone (Z or explicit offset),-and a finite decimal amount with at most two fractional digits. Ignore invalid-rows. Among valid rows with the same id, the last valid row wins (a later invalid-row must not erase a valid row). Normalize timestamps to UTC and group by UTC-date and team. Return groups sorted by (day, team), each with exactly the keys-day (YYYY-MM-DD), team, count (int), total (decimal string with two places).-Negative amounts and zero are valid. Use decimal arithmetic, not binary floats.-Empty input and header-only input return []. Correctly parse quoted commas.-cli.py accepts exactly one argument, a CSV filename or - for stdin. Print the-JSON list and exit 0. An unreadable filename prints a concise message to stderr-and exits 2 without a traceback. Do not add third-party dependencies.-'''-VALIDATOR = r'''-import importlib.util, json, subprocess, sys-from pathlib import Path-root=Path(sys.argv[1]); spec=importlib.util.spec_from_file_location('report',root/'report.py')-m=importlib.util.module_from_spec(spec); spec.loader.exec_module(m)-header='id,timestamp,team,amount\n'-cases=[('',[]),(header,[]),- (header+'a,2026-01-02T00:30:00+02:00,"Blue, East",0.10\nb,2026-01-01T12:00:00Z,"Blue, East",0.20\n',- [{'day':'2026-01-01','team':'Blue, East','count':2,'total':'0.30'}]),- (header+'a,2026-01-01T00:00:00Z,X,1.00\na,2026-01-02T00:00:00Z,Y,2.00\na,bad,X,9.00\n',- [{'day':'2026-01-02','team':'Y','count':1,'total':'2.00'}]),- (header+' a ,2026-01-01T00:00:00Z, X ,-2.10\nb,2026-01-01T00:00:00Z,X,0\n',- [{'day':'2026-01-01','team':'X','count':2,'total':'-2.10'}]),- (header+'a,2026-01-01T00:00:00,X,1\nb,2026-01-01T00:00:00Z,X,NaN\nc,2026-01-01T00:00:00Z,X,1.001\n,2026-01-01T00:00:00Z,X,2\nd,2026-01-01T00:00:00Z,,2\n',[]),- (header+'a,2026-01-02T00:00:00Z,B,1\nb,2026-01-01T00:00:00Z,Z,2\nc,2026-01-02T00:00:00Z,A,3\n',- [{'day':'2026-01-01','team':'Z','count':1,'total':'2.00'},- {'day':'2026-01-02','team':'A','count':1,'total':'3.00'},- {'day':'2026-01-02','team':'B','count':1,'total':'1.00'}])]-checks=[]-for i,(text,want) in enumerate(cases):- got=m.summarize(text); assert got==want,(i,got,want); checks.append('library-'+str(i))-text,want=cases[2]-p=subprocess.run([sys.executable,str(root/'cli.py'),'-'],input=text,text=True,capture_output=True,timeout=10)-assert p.returncode==0 and json.loads(p.stdout)==want,p; checks.append('stdin')-f=root/'validator-input.csv';f.write_text(text)-p=subprocess.run([sys.executable,str(root/'cli.py'),str(f)],text=True,capture_output=True,timeout=10)-assert p.returncode==0 and json.loads(p.stdout)==want,p;checks.append('file');f.unlink()-p=subprocess.run([sys.executable,str(root/'cli.py'),str(root/'does-not-exist.csv')],text=True,capture_output=True,timeout=10)-assert p.returncode==2 and p.stderr and 'Traceback' not in p.stderr,p;checks.append('missing-file')-print(json.dumps({'passed':checks}))-'''---def get_json(url):- with urllib.request.urlopen(url, timeout=5) as response:- return json.load(response)---def main():- ap = argparse.ArgumentParser(description=__doc__)- ap.add_argument('--config', type=Path, required=True)- ap.add_argument('--engine', type=Path, required=True)- ap.add_argument('--pi-package', type=Path, required=True)- ap.add_argument('--output', type=Path, required=True)- ap.add_argument('--port', type=int, default=11436)- ap.add_argument('--order', default='off,on', choices=('off,on', 'on,off'))- ap.add_argument('--run', action='store_true')- args = ap.parse_args()- if not args.run:- print('Dry run: private server, identical Pi A/B/A coding tasks, cache off/on, independent validators.')- return- args.output = args.output.resolve()- args.output.mkdir(parents=False, exist_ok=False)- cfg = json.loads(args.config.read_text())- cfg.update(exe=str(args.engine.resolve()), cwd=str(ROOT), host='127.0.0.1', port=args.port)- work = args.output / 'workspace'- agent = args.output / 'agent'- agent.mkdir()- model = cfg['model_name']- if model != 'qwen3.8-flash-next-iq3_s':- raise ValueError('This task is currently validated for qwen3.8-flash-next-iq3_s')- (agent/'models.json').write_text(json.dumps({'providers': {'strata-benchmark': {- 'baseUrl': f'http://127.0.0.1:{args.port}/v1', 'api': 'openai-completions', 'apiKey': 'local',- 'models': [{'id': model, 'reasoning': False, 'input': ['text'], 'contextWindow': 131072,- 'maxTokens': 2048, 'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0}}],- 'compat': {'supportsStore': False, 'supportsDeveloperRole': False, 'supportsReasoningEffort': False}- }}}))- corpus = 'id,timestamp,team,amount\n' + ''.join(- f'r{i},2026-01-{i%28+1:02d}T12:00:00Z,Team{i%7},{i%100}.{i%97:02d}\n' for i in range(280))- initial = {'SPEC.md': SPEC, 'sample.csv': corpus,- 'report.py': 'def summarize(text):\n raise NotImplementedError\n', 'cli.py': ''}- manifest = {name: hashlib.sha256(text.encode()).hexdigest() for name, text in initial.items()}- (args.output/'inputs.json').write_text(json.dumps(initial, indent=2))- validator = args.output/'validate.py'- validator.write_text(VALIDATOR)- results = []- for label in args.order.split(','):- run = args.output/label- run.mkdir()- if work.exists():- shutil.rmtree(work) # only this harness's new, disposable task workspace- work.mkdir()- for name, text in initial.items():- (work/name).write_text(text)- run_cfg = dict(cfg, args=list(cfg['args']), log=str(run/'engine.log'))- run_cfg['args'] += ['--conversation-cache-mib', '8192' if label=='on' else '0']- config = run/'config.json'- config.write_text(json.dumps(run_cfg, indent=2))- config.with_name('config.shared-settings.json').write_text(json.dumps({- 'reasoning_effort': 'none', 'temperature': 0, 'max_tokens': 2048}))- record = {'mode': label, 'inputs_sha256': manifest,- 'task_script_sha256': hashlib.sha256((ROOT/'tools/agent_cache_task.mjs').read_bytes()).hexdigest(),- 'engine_sha256': hashlib.sha256(args.engine.read_bytes()).hexdigest()}- with (run/'server.log').open('w') as log:- server = subprocess.Popen([sys.executable, '-m', 'serve.server', '--engine', 'strata',- '--config', str(config), '--host', '127.0.0.1', '--port', str(args.port)],- cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)- try:- base = f'http://127.0.0.1:{args.port}'- for _ in range(180):- if server.poll() is not None:- raise RuntimeError('Private server exited; inspect server.log')- try:- get_json(base+'/health')- break- except OSError:- time.sleep(1)- else:- raise TimeoutError('Private server did not become ready')- started = time.monotonic()- with (run/'agent.log').open('w') as agent_log:- task = subprocess.run(['node', str(ROOT/'tools/agent_cache_task.mjs'),- str(args.pi_package.resolve()), str(work), str(agent), str(run/'task.json')],- cwd=work, stdout=agent_log, stderr=subprocess.STDOUT, timeout=750,- env={**os.environ, 'PI_OFFLINE': '1'})- record.update(wall_s=time.monotonic()-started, agent_exit=task.returncode)- check = subprocess.run([sys.executable, str(validator), str(work)],- text=True, capture_output=True, timeout=30)- (run/'validation.txt').write_text(check.stdout+check.stderr)- record.update(validator_exit=check.returncode, success=task.returncode==check.returncode==0)- metrics = get_json(base+'/metrics?requests=all')- (run/'metrics.json').write_text(json.dumps(metrics, indent=2))- record.update(totals=metrics['totals'], engine=metrics['engine'])- # Kernel high-water RSS for the engine, unlike periodic request-end samples.- children = Path(f'/proc/{server.pid}/task/{server.pid}/children').read_text().split()- record['child_memory_kib'] = {}- for pid in children:- try:- if Path(f'/proc/{pid}/comm').read_text().strip() != 'strata':- continue- status = Path(f'/proc/{pid}/status').read_text().splitlines()- except FileNotFoundError:- continue- record['child_memory_kib'][pid] = {s.split(':')[0]: int(s.split()[1])- for s in status if s.startswith(('VmHWM:', 'VmRSS:'))}- if not record['child_memory_kib']:- raise RuntimeError('Missing engine high-water memory sample')- shutil.copytree(work, run/'artifacts')- finally:- if server.poll() is None:- os.killpg(server.pid, signal.SIGINT)- try:- server.wait(timeout=30)- except subprocess.TimeoutExpired:- os.killpg(server.pid, signal.SIGTERM)- server.wait(timeout=10)- results.append(record)- (args.output/'results.json').write_text(json.dumps(results, indent=2)+'\n')- print(json.dumps(record), flush=True)- for key in ('expert_slots', 'context', 'kv', 'kv_resident', 'spec', 'mtp_max', 'lookup', 'pool_workers', 'pcie_frac'):- if results[0]['engine'][key] != results[1]['engine'][key]:- raise AssertionError(f'Unmatched engine configuration: {key}')- if not all(r['success'] for r in results):- raise SystemExit('Agent task or independent validation failed; no successful-task speedup claim')---if __name__ == '__main__':- main()diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjsdeleted file mode 100644index 93a6df3ed..000000000--- a/tools/agent_cache_task.mjs+++ /dev/null@@ -1,114 +0,0 @@-// Bounded real Pi A -> B -> A coding workflow, used by agent_cache_benchmark.py.-import fs from 'node:fs';-import path from 'node:path';-import {pathToFileURL} from 'node:url';--const [packageDir, cwd, agentDir, output] = process.argv.slice(2);-const {createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager} =- await import(pathToFileURL(path.join(packageDir, 'dist/index.js')));-const runtime = await ModelRuntime.create({authPath: path.join(agentDir, 'auth.json'),- modelsPath: path.join(agentDir, 'models.json'), allowModelNetwork: false});-const model = runtime.getModel('strata-benchmark', 'qwen3.8-flash-next-iq3_s');-if (!model) throw new Error('Benchmark model unavailable');-const events = fs.createWriteStream(output + '.events.jsonl');-const sessions = [];-const phases = [];-const budgets = new WeakMap();-const system = 'You are implementing a small Python standard-library project. Work only in the current directory. '- + 'Do not access the network, install dependencies, or read parent directories. Use at most 24 tool calls per task. '- + 'Keep tool outputs below 16000 characters and shell commands below 15 seconds. Implement the requested files, '- + 'run focused checks, then give a short result. Do not build unrelated features.';-async function makeSession() {- const budget = {calls: 0, limited: false};- const settingsManager = SettingsManager.inMemory({compaction: {enabled: false}, retry: {enabled: false}});- const loader = new DefaultResourceLoader({cwd, agentDir, settingsManager, noExtensions: true,- noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,- extensionFactories: [pi => {- pi.on('before_provider_request', event => {- const payload = {...event.payload, temperature: 0, max_tokens: 2048,- chat_template_kwargs: {enable_thinking: false}};- delete payload.max_completion_tokens;- return payload;- });- pi.on('tool_call', event => {- if (++budget.calls > 24) {- budget.limited = true;- return {block: true, terminate: true, reason: 'Benchmark tool-call limit'};- }- if (event.toolName === 'bash') event.input.timeout = Math.min(event.input.timeout || 15, 15);- });- pi.on('tool_result', event => {- let left = 16000;- return {content: event.content.map(part => {- if (part.type !== 'text') return part;- const marker = '\n[benchmark output limit]';- const text = part.text.length <= left ? part.text- : left >= marker.length ? part.text.slice(0, left - marker.length) + marker : '';- left -= text.length;- return {...part, text};- })};- });- }],- systemPromptOverride: () => system});- await loader.reload();- const {session} = await createAgentSession({cwd, agentDir, model, modelRuntime: runtime,- thinkingLevel: 'off', tools: ['read', 'write', 'edit', 'bash'], resourceLoader: loader,- sessionManager: SessionManager.inMemory(), settingsManager});- sessions.push(session);- budgets.set(session, budget);- return session;-}-async function phase(session, name, prompt) {- const budget = budgets.get(session);- budget.calls = 0; budget.limited = false;- const record = {name, tool_calls: 0, tool_ms: 0, turns: 0, limited: false};- const activeTools = new Map();- const started = performance.now();- const unsubscribe = session.subscribe(event => {- events.write(JSON.stringify({phase: name, elapsed_ms: performance.now() - started, event}) + '\n');- if (event.type === 'turn_start') record.turns++;- if (event.type === 'tool_execution_start') {- record.tool_calls++;- activeTools.set(event.toolCallId, performance.now());- }- if (event.type === 'tool_execution_end') {- record.tool_ms += performance.now() - (activeTools.get(event.toolCallId) ?? performance.now());- }- if (record.tool_calls > 24 || record.turns > 32) {- record.limited = true;- void session.abort();- }- });- const timeout = setTimeout(() => { record.limited = true; void session.abort(); }, 240000);- try {- await session.prompt(prompt);- const last = session.messages.filter(m => m.role === 'assistant').at(-1);- if (record.limited || budget.limited || !last || ['error', 'aborted'].includes(last.stopReason)) {- throw new Error(`Phase ${name} failed: ${last?.errorMessage ?? last?.stopReason ?? 'limit'}`);- }- record.answer = last.content;- } finally {- clearTimeout(timeout); unsubscribe(); record.wall_ms = performance.now() - started;- phases.push(record);- fs.writeFileSync(output, JSON.stringify({phases}, null, 2) + '\n');- }-}-try {- const controller = await makeSession();- const worker = await makeSession();- await phase(controller, 'controller-implement',- 'Implement report.py summarize(text) using SPEC.md. Read the complete sample.csv (a realistic input corpus) '- + 'before implementing. Implement only the library for now; another developer will implement cli.py. '- + 'You may add small tests. Summarize what you implemented.');- await phase(worker, 'worker-cli',- 'You are responsible for cli.py. Read SPEC.md and report.py, implement the specified CLI, and verify both '- + 'file and stdin inputs. Do not modify report.py. Keep your answer brief.');- await phase(controller, 'controller-integrate',- 'The CLI developer has finished. Read cli.py and verify the integrated project against SPEC.md, especially '- + 'quoted commas, timezone-to-UTC day conversion, last-valid duplicate IDs, invalid rows, empty input, '- + 'Decimal totals, stdin, and missing-file exit status. Fix any problems in report.py or cli.py. '- + 'Run focused checks and report the result.');-} finally {- for (const session of sessions) session.dispose();- events.end();-}diff --git a/tools/conversation_cache_isolation.py b/tools/conversation_cache_isolation.pyindex 8cfa54796..5c201300a 100644--- a/tools/conversation_cache_isolation.py+++ b/tools/conversation_cache_isolation.py@@ -7,19 +7,17 @@ kernels. This validates cache correctness, not vision or steering quality.import argparseimport jsonfrom pathlib import Path-import reimport structimport sysimport threadingROOT = Path(__file__).resolve().parents[1]sys.path[:0] = [str(ROOT), str(ROOT / 'tools')]-from conversation_cache_parity import STATE_KEYS, engine_args, require+from conversation_cache_parity import STATE_KEYS, engine_args, load_tokenizer, require, state_hashesfrom gguf_reader import GGUFFilefrom gguf_writer import GGUFWriterfrom serve.server import StrataEngine, child_envfrom serve.frontend import ChatTemplate-import strata_tokenizer as STimport numpy as np@@ -86,12 +84,7 @@ def main():width = geometry['qwen4exp.embedding_length']require(geometry['qwen4exp.block_count'] > 20, 'fixture requires layers 1 and 20')p = Path(cfg['tokenizer'])- vocab = json.loads((p / 'vocab.json').read_text())- tokens = [None] * len(vocab)- for token, i in vocab.items():- tokens[i] = token- tok = ST.Tokenizer(tokens, (p / 'merges.txt').read_text().split('\n'),- json.loads((p / 'token_type.json').read_text()))+ tok = load_tokenizer(p)tpl = ChatTemplate(p / 'chat_template.jinja')def encode(text):return tok.encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False), parse_special=True)@@ -137,11 +130,7 @@ def main():generate('off-again', A, steering=False)finally:engine.close()- hashes = []- for line in log.read_text().splitlines():- if 'STATE_HASH L=' in line:- fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line))- hashes.append({k: fields[k] for k in STATE_KEYS})+ hashes = state_hashes(log.read_text())require(len(hashes) == len(records), 'missing isolation state hashes')for record, state in zip(records, hashes):record['state'] = statediff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.pyindex 710baee8d..80c467d21 100644--- a/tools/conversation_cache_parity.py+++ b/tools/conversation_cache_parity.py@@ -22,6 +22,25 @@ def require(condition, message):raise AssertionError(message)+def load_tokenizer(path):+ vocab = json.loads((path / 'vocab.json').read_text())+ tokens = [None] * len(vocab)+ for token, index in vocab.items():+ tokens[index] = token+ return ST.Tokenizer(tokens, (path / 'merges.txt').read_text().split('\n'),+ json.loads((path / 'token_type.json').read_text()))+++def state_hashes(text):+ # Padding and the drafter's final uncomputed cell aren't main-model state.+ hashes = []+ for line in text.splitlines():+ if 'STATE_HASH L=' in line:+ fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line))+ hashes.append({key: fields[key] for key in STATE_KEYS})+ return hashes++def engine_args(cfg, budget, spec):# Native IQ packs require verifier capacity >= 2, even for one-token decode.return list(cfg['args']) + [@@ -131,12 +150,7 @@ def main():returncfg = json.loads(a.config.read_text())p = Path(cfg['tokenizer'])- vocab = json.loads((p / 'vocab.json').read_text())- tokens = [None] * len(vocab)- for text, i in vocab.items():- tokens[i] = text- tok = ST.Tokenizer(tokens, (p / 'merges.txt').read_text().split('\n'),- json.loads((p / 'token_type.json').read_text()))+ tok = load_tokenizer(p)tpl = ChatTemplate(p / 'chat_template.jinja')def encode(text):return tok.encode(text, parse_special=True)@@ -181,13 +195,7 @@ def main():generate(continuation, 8, 'A+-checkpoint')finally:engine.close()- hashes = []- for line in log.read_text().splitlines():- if 'STATE_HASH L=' in line:- fields = dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line))- # Padding and the drafter's final uncomputed cell aren't used- # main-model state; do not gate on their diagnostic hashes.- hashes.append({k: fields[k] for k in STATE_KEYS})+ hashes = state_hashes(log.read_text())require(len(hashes) == len(records), 'missing state hashes')for record, fingerprint in zip(records, hashes):record['state'] = fingerprintdiff --git a/tools/conversation_cache_soak.py b/tools/conversation_cache_soak.pyindex ae910c00b..a7c95fddb 100644--- a/tools/conversation_cache_soak.py+++ b/tools/conversation_cache_soak.py@@ -12,10 +12,9 @@ import threadingROOT = Path(__file__).resolve().parents[1]sys.path[:0] = [str(ROOT), str(ROOT / 'tools')]-from conversation_cache_parity import STATE_KEYS, engine_args, require+from conversation_cache_parity import STATE_KEYS, engine_args, load_tokenizer, require, state_hashesfrom serve.server import StrataEngine, child_envfrom serve.frontend import ChatTemplate-import strata_tokenizer as STdef answer_text(text):@@ -81,12 +80,7 @@ def main():returncfg = json.loads(args.config.read_text())path = Path(cfg['tokenizer'])- vocab = json.loads((path / 'vocab.json').read_text())- tokens = [None] * len(vocab)- for token, index in vocab.items():- tokens[index] = token- tok = ST.Tokenizer(tokens, (path / 'merges.txt').read_text().split('\n'),- json.loads((path / 'token_type.json').read_text()))+ tok = load_tokenizer(path)template = ChatTemplate(path / 'chat_template.jinja')def encode(text):return tok.encode(text, parse_special=True)@@ -124,11 +118,10 @@ def main():nonlocal hash_countoutput = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None]text = log.read_text()- hashes = [dict(re.findall(r'(\w+)=([0-9a-f,-]+)', line))- for line in text.splitlines() if 'STATE_HASH L=' in line]+ hashes = state_hashes(text)require(len(hashes) == hash_count + 1 and int(hashes[-1]['L']) >= len(ids), 'missing current state fingerprint')hash_count += 1- state = {k: hashes[-1][k] for k in STATE_KEYS}+ state = hashes[-1]occupancy = re.findall(r'parked=\d+ bytes=(\d+)', text)rss = Nonetry: