Skip to content

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++

Integrate validated conversation snapshot core with upstream 0.1.25

Jeremiah Ritchey991203f2a946
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 10cdc871b..9f05042a9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -50,8 +50,19 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt AND EXISTS ${CMAKE_CU
set(_strata_tests_default ON)
endif()
option(STRATA_BUILD_TESTS "Build the test suite" ${_strata_tests_default})
+option(STRATA_BUILD_CONVERSATION_TESTS "Build standalone conversation cache tests" OFF)
option(STRATA_WERROR "Treat compiler warnings as errors" OFF)
+if(STRATA_BUILD_CONVERSATION_TESTS)
+ enable_testing()
+ add_executable(conversation_cache_test src/core/conversation_cache_test.cpp)
+ target_include_directories(conversation_cache_test PRIVATE include)
+ add_test(NAME conversation_cache_test COMMAND conversation_cache_test)
+ add_executable(conversation_memory_test src/core/conversation_memory_test.cpp src/core/conversation_memory.cpp)
+ target_include_directories(conversation_memory_test PRIVATE include)
+ add_test(NAME conversation_memory_test COMMAND conversation_memory_test)
+endif()
+
if(STRATA_ENABLE_CUDA)
enable_language(CUDA)
# `enable_language(CUDA)` gives the .cu compile rules but NOT the imported targets, so `CUDA::cudart` has to
@@ -294,7 +305,8 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
# library is the honest shape of the dependency graph: core knows about devices and weights, kernels know
# about arithmetic, and this one knows the ORDER the arithmetic happens in.
add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp
- src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp)
+ src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp
+ src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp)
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")
@@ -304,6 +316,25 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
add_test(NAME file_expert_source_test COMMAND file_expert_source_test)
set_tests_properties(file_expert_source_test PROPERTIES TIMEOUT 60)
endif()
+ if(STRATA_BUILD_CONVERSATION_TESTS)
+ add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp)
+ target_link_libraries(conversation_snapshot_test PRIVATE strata_engine)
+ add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test)
+ set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120)
+ add_executable(conversation_validation_test src/core/conversation_validation_test.cpp)
+ target_link_libraries(conversation_validation_test PRIVATE strata_engine)
+ add_test(NAME conversation_validation_test COMMAND conversation_validation_test)
+ set_tests_properties(conversation_validation_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120)
+ if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
+ add_executable(conversation_transfer_test src/core/conversation_validation_test.cpp)
+ target_compile_definitions(conversation_transfer_test PRIVATE CONVERSATION_TEST_TRANSFERS)
+ target_link_options(conversation_transfer_test PRIVATE
+ -Wl,--wrap=cudaMemcpy -Wl,--wrap=cudaDeviceSynchronize -Wl,--wrap=cudaGetLastError)
+ target_link_libraries(conversation_transfer_test PRIVATE strata_engine)
+ add_test(NAME conversation_transfer_test COMMAND conversation_transfer_test)
+ set_tests_properties(conversation_transfer_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120)
+ endif()
+ endif()
# `strata generate` (P2.S6). The FIRST user-facing program: everything under it is a component, and this is
# what composes them into a token. No tokenizer - the prompt arrives as ids - because Gate C1 compares logits
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 1217072e4..d8a7765db 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -371,9 +371,35 @@ prompt when that is 2,048 tokens or more (engine 0.1.20; PR #62 + #65), so that
system prompts and tool lists. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`,
`--prompt-cache-root N` (0 = no system-prompt checkpoint), `--turn-token ID`.
-**Current limits (v1):** one request at a time, and one conversation's history in the KV cache at a time (switching
-between two chats re-reads the part where they diverge; the shared prefix, such as the system prompt, is reused); images
-only when set up with them (below); no video. **Temperature / top_p / top_k / min_p /
+**Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192
+--conversation-cache-slots 4` to the engine arguments to park up to four conversations
+in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories when
+their requests alternate; it does not execute requests concurrently. No client session
+ID is required: only exact token/image prefixes with matching steering mode are reused.
+The default budget is 0 (disabled); `--prompt-cache 0` also disables parking.
+
+Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V.
+They add host RAM, not another model or VRAM allocation. The byte budget also counts
+an incoming snapshot during a switch; oldest parked entries are evicted first.
+Oversized snapshots or host allocation failures fall back to ordinary prompt processing.
+`--conversation-cache-min-free-mib N` (default 2560) additionally requires that
+physical-RAM headroom remain available: the engine checks before allocation and
+again after capture. Unknown telemetry or insufficient RAM skips parking. Windows
+uses `GlobalMemoryStatusEx`, Linux uses `MemAvailable`; these are host-level samples,
+not a reservation or enforcement of container/job memory limits. An 8 GiB budget
+is a cap, not a recommendation for every machine.
+
+The shared snapshot core validates all layers and checkpoints before applying any
+state. Invalid entries are discarded; transfer/synchronization failure is fatal
+rather than permission to continue with partial state. Indexer spare keys and the
+moving spare row are preserved, including checkpoint rewinds. These development
+changes 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).
+
+**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats
+re-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 /
seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled result
is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the
engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out
diff --git a/docs/plans/multi-conversation-cache.md b/docs/plans/multi-conversation-cache.md
new file mode 100644
index 000000000..0a2cb070a
--- /dev/null
+++ b/docs/plans/multi-conversation-cache.md
@@ -0,0 +1,240 @@
+# 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.md
new file mode 100644
index 000000000..e692c3034
--- /dev/null
+++ b/docs/plans/shared-conversation-snapshots.md
@@ -0,0 +1,147 @@
+# Shared conversation snapshots: convergence proposal
+
+Status: proposed interface and development work for issues/PRs #41, #52 and #57.
+This is not an agreed integration-owner assignment, a merged upstream feature,
+or a claim that the disk tier already uses this core. Development starts at
+upstream `b38c183` (0.1.18); the deployed/tested 0.1.15 branch remains separate.
+
+## 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.
diff --git a/docs/plans/shared-conversation-validation.md b/docs/plans/shared-conversation-validation.md
new file mode 100644
index 000000000..0f549c231
--- /dev/null
+++ b/docs/plans/shared-conversation-validation.md
@@ -0,0 +1,135 @@
+# Shared snapshot core: validation record
+
+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/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp
new file mode 100644
index 000000000..42409d3de
--- /dev/null
+++ b/include/strata/core/conversation_cache.hpp
@@ -0,0 +1,146 @@
+// CPU-only ownership and matching policy for --serve's parked conversations.
+// Token equality, image identity, and steering mode are all required for reuse.
+#pragma once
+
+#include <algorithm>
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <deque>
+#include <utility>
+#include <vector>
+
+namespace strata::core {
+
+struct ConversationImageKey {
+ int64_t start = 0;
+ uint64_t hash = 0;
+ bool operator==(const ConversationImageKey&) const = default;
+};
+
+struct ConversationCheckpoint {
+ std::vector<int32_t> ids;
+ std::vector<ConversationImageKey> imgs;
+ std::vector<uint8_t> gdn, ple, tails, dead, block_pos;
+ uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention
+ // Ordinary layer-split checkpoints retain each device's running state.
+ // Whole-session parking is currently single-GPU and rejects these parts.
+ std::vector<ConversationCheckpoint> stage_parts;
+
+ size_t bytes() const {
+ size_t n = ids.capacity() * sizeof(int32_t) + imgs.capacity() * sizeof(ConversationImageKey) +
+ gdn.capacity() + ple.capacity() + tails.capacity() + dead.capacity() + block_pos.capacity() +
+ stage_parts.capacity() * sizeof(ConversationCheckpoint);
+ for (const auto& part : stage_parts) n += part.bytes();
+ return n;
+ }
+};
+
+// Identity-layout K/V pages and completed indexer rows. For streamed layers the
+// source is the authoritative host pool, NOT the replaceable VRAM slots.
+struct ConversationKv {
+ int format = 0;
+ int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0;
+ std::vector<uint8_t> k, v, k_scale, v_scale, pooled;
+ size_t bytes() const {
+ return k.capacity() + v.capacity() + k_scale.capacity() + v_scale.capacity() + pooled.capacity();
+ }
+};
+
+struct SavedConversation {
+ // Runtime compatibility only; NOT a model/weights identity or disk schema.
+ std::array<int64_t, 18> geometry{};
+ ConversationCheckpoint live;
+ std::vector<ConversationCheckpoint> checkpoints;
+ std::vector<ConversationKv> kv; // main layers followed by the draft layer
+ bool cvec = true;
+
+ size_t bytes() const {
+ size_t n = live.bytes() + checkpoints.capacity() * sizeof(ConversationCheckpoint) +
+ kv.capacity() * sizeof(ConversationKv);
+ for (const auto& c : checkpoints) n += c.bytes();
+ for (const auto& k : kv) n += k.bytes();
+ return n;
+ }
+};
+
+template<class Token>
+int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector<Token>& prompt,
+ const std::vector<ConversationImageKey>& images) {
+ const size_t n = c.ids.size();
+ // The last prompt token always starts the next verify window.
+ if (n == 0 || n >= prompt.size() || !std::equal(c.ids.begin(), c.ids.end(), prompt.begin())) return 0;
+ size_t j = 0;
+ for (const auto& image : images) {
+ if (image.start >= (int64_t) n) continue;
+ if (j == c.imgs.size() || !(c.imgs[j++] == image)) return 0;
+ }
+ if (j != c.imgs.size()) return 0;
+ return (int64_t) n;
+}
+
+class ConversationCache {
+public:
+ struct Match {
+ size_t index = 0;
+ int64_t tokens = 0;
+ bool live = false;
+ };
+
+ ConversationCache(size_t budget, size_t slots) : budget_(budget), slots_(slots) {}
+ bool enabled() const { return budget_ != 0 && slots_ != 0; }
+ size_t bytes() const { return bytes_; }
+ size_t size() const { return entries_.size(); }
+ size_t evictions() const { return evictions_; }
+
+ template<class Token>
+ Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images, bool cvec) const {
+ Match best;
+ // Ties prefer the most recently parked branch. The caller prefers its
+ // already-active state when that offers the same prefix length.
+ for (size_t i = entries_.size(); i-- > 0;) {
+ const auto& e = entries_[i];
+ if (e.cvec != cvec) continue;
+ auto consider = [&](const ConversationCheckpoint& c, bool live) {
+ const int64_t n = conversation_prefix(c, prompt, images);
+ if (n > best.tokens) best = {i, n, live};
+ };
+ consider(e.live, true);
+ for (const auto& c : e.checkpoints) consider(c, false);
+ }
+ return best;
+ }
+
+ SavedConversation take(size_t index) {
+ SavedConversation out = std::move(entries_.at(index));
+ bytes_ -= out.bytes();
+ entries_.erase(entries_.begin() + (std::ptrdiff_t) index);
+ return out;
+ }
+
+ // Reserve before allocating a snapshot. held is an incoming image removed
+ // with take() but still alive during the exchange; count it against RAM too.
+ bool make_room(size_t incoming, size_t held = 0) {
+ if (!enabled() || held > budget_ || incoming > budget_ - held) return false;
+ while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) {
+ bytes_ -= entries_.front().bytes();
+ entries_.pop_front();
+ ++evictions_;
+ }
+ return true;
+ }
+
+ bool put(SavedConversation&& image, size_t held = 0) {
+ const size_t n = image.bytes();
+ if (!make_room(n, held)) return false;
+ entries_.push_back(std::move(image));
+ bytes_ += n;
+ return true;
+ }
+
+private:
+ size_t budget_ = 0, slots_ = 0, bytes_ = 0, evictions_ = 0;
+ std::deque<SavedConversation> entries_; // least recently active first
+};
+
+} // namespace strata::core
diff --git a/include/strata/core/conversation_memory.hpp b/include/strata/core/conversation_memory.hpp
new file mode 100644
index 000000000..0e908b40c
--- /dev/null
+++ b/include/strata/core/conversation_memory.hpp
@@ -0,0 +1,19 @@
+#pragma once
+
+#include <cstdint>
+#include <istream>
+#include <optional>
+
+namespace strata::core {
+
+// Host physical memory, not swap/commit or a container/job memory reservation.
+// Unknown telemetry is deliberately distinct from a measured zero.
+std::optional<uint64_t> conversation_available_memory();
+std::optional<uint64_t> conversation_mem_available(std::istream& meminfo);
+
+inline bool conversation_memory_admit(std::optional<uint64_t> available,
+ uint64_t allocation, uint64_t floor) {
+ return available && *available >= floor && allocation <= *available - floor;
+}
+
+} // namespace strata::core
diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp
new file mode 100644
index 000000000..a135e3101
--- /dev/null
+++ b/include/strata/core/conversation_snapshot.hpp
@@ -0,0 +1,55 @@
+#pragma once
+
+#include "strata/core/conversation_cache.hpp"
+#include "strata/core/layer.hpp"
+#include "strata/core/session.hpp"
+
+#include <string>
+
+namespace strata::core {
+
+// Caller synchronizes the device before saving, and after restoring all layers.
+// include_index is false for the draft layer (its attention has no indexer).
+size_t conversation_kv_bytes(const QsaState& state, const ModelGeometry& g, int64_t upto, bool include_index);
+bool conversation_kv_save(ConversationKv& image, const QsaState& state, const ModelGeometry& g,
+ int64_t upto, bool include_index, std::string& error);
+// No CUDA calls or destination writes. Used for whole-session prevalidation.
+bool conversation_kv_validate(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
+ int64_t upto, bool include_index, std::string& error);
+bool conversation_kv_restore(const ConversationKv& image, const QsaState& state, const ModelGeometry& g,
+ int64_t upto, bool include_index, std::string& error);
+
+struct ConversationStateSizes {
+ size_t gdn = 0, ple = 0, tail = 0, dead = 0, block_pos = 0;
+};
+bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& sizes, std::string& error);
+bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const SessionState& session,
+ const ModelGeometry& g, std::string& error);
+bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session,
+ const ModelGeometry& g, std::string& error);
+bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session,
+ const ModelGeometry& g, std::string& error);
+
+struct ConversationView {
+ const std::vector<int32_t>& ids;
+ const std::vector<ConversationImageKey>& images;
+ const std::vector<ConversationCheckpoint>& checkpoints;
+ bool cvec;
+};
+bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session,
+ const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error);
+// Caller admits the estimate before invoking capture. Allocation failures propagate
+// to the RAM policy; the active session is never modified by capture.
+bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,
+ const SessionState& session, const ModelGeometry& g,
+ const QsaState& draft, std::string& error);
+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session,
+ const ModelGeometry& g, const QsaState& draft, std::string& error);
+enum class ConversationRestore { restored, invalid, transfer_failed };
+// Invalid images are rejected before any CUDA call/write. Transfer failure may
+// leave partial state: caller MUST NOT continue inference from that session.
+ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session,
+ const ModelGeometry& g, const QsaState& draft,
+ std::string& error);
+
+} // namespace strata::core
diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp
new file mode 100644
index 000000000..f6346d909
--- /dev/null
+++ b/src/core/conversation_cache_test.cpp
@@ -0,0 +1,92 @@
+#include "strata/core/conversation_cache.hpp"
+
+#include <cstdio>
+#include <cstdlib>
+
+using namespace strata::core;
+
+namespace {
+int checks = 0;
+void check(bool value, const char* description) {
+ ++checks;
+ if (!value) { std::fprintf(stderr, "FAIL: %s\n", description); std::exit(1); }
+}
+SavedConversation image(std::initializer_list<int32_t> ids, bool cvec = true) {
+ SavedConversation s;
+ s.live.ids = ids;
+ s.live.gdn.resize(64, 7);
+ s.cvec = cvec;
+ return s;
+}
+}
+
+int main() {
+ const std::vector<int64_t> a = {1, 2, 3, 4}, b = {9, 8, 7, 6};
+ {
+ ConversationCache cache(1024, 2);
+ check(cache.put(image({1, 2, 3})), "park A");
+ check(cache.put(image({9, 8, 7})), "park B");
+ auto match = cache.best(a, {}, true);
+ check(match.tokens == 3 && match.live, "A/B/A: recover A");
+ auto restored = cache.take(match.index);
+ check(restored.live.ids == std::vector<int32_t>({1, 2, 3}), "taking selected A preserves identity");
+ check(cache.size() == 1 && cache.best(b, {}, true).tokens == 3, "B remains parked");
+ check(cache.bytes() == image({9,8,7}).bytes(), "byte accounting after take");
+ check(cache.put(std::move(restored)), "park returned A as newest");
+ check(cache.put(image({5, 6})), "evict oldest by slot limit");
+ check(cache.best(b, {}, true).tokens == 0 && cache.best(a, {}, true).tokens == 3, "B evicted before A");
+ check(cache.evictions() == 1, "eviction counter");
+ }
+ {
+ auto s = image({1, 2, 3});
+ ConversationCheckpoint cp;
+ cp.ids = {1, 2};
+ s.checkpoints.push_back(cp);
+ ConversationCache cache(4096, 4);
+ cache.put(std::move(s));
+ auto match = cache.best(std::vector<int64_t>{1, 2, 9, 4}, {}, true);
+ check(match.tokens == 2 && !match.live, "edited suffix falls back to parked checkpoint");
+ check(cache.best(a, {}, true).tokens == 3, "live prefix beats shorter checkpoint");
+ check(cache.best(a, {}, false).tokens == 0, "steering mode is isolated");
+ check(cache.best(std::vector<int64_t>{1, 2}, {}, true).tokens == 0, "equal-length checkpoint cannot consume last token");
+ check(cache.best(std::vector<int64_t>{1}, {}, true).tokens == 0, "short prompt cannot match");
+ check(cache.best(std::vector<int64_t>{}, {}, true).tokens == 0, "empty prompt cannot match");
+ cache.put(image({1, 2, 3}));
+ check(cache.best(a, {}, true).index == 1, "ties prefer most recently parked");
+ }
+ {
+ auto s = image({1, 2, 3});
+ s.live.imgs = {{1, 123}};
+ ConversationCache cache(1024, 3);
+ cache.put(std::move(s));
+ check(cache.best(a, {{1,123}}, true).tokens == 3, "same image can resume");
+ check(cache.best(a, {{1,124}}, true).tokens == 0, "different image pixels invalidate same pad tokens");
+ check(cache.best(a, {}, true).tokens == 0, "missing image invalidates prefix");
+ check(cache.best(a, {{1,123},{2,45}}, true).tokens == 0, "additional image in cached prefix invalidates");
+ check(cache.best(a, {{1,123},{3,45}}, true).tokens == 3, "image after cached prefix does not invalidate");
+ }
+ {
+ const size_t one = image({1,2,3}).bytes();
+ ConversationCache cache(one*2, 8);
+ cache.put(image({1,2,3})); cache.put(image({9,8,7}));
+ check(cache.bytes() == one*2, "budget holds two exact-sized images");
+ auto held = cache.take(cache.best(a, {}, true).index);
+ check(cache.make_room(one, held.bytes()), "count in-flight image when reserving outgoing snapshot");
+ check(cache.size() == 0, "in-flight reservation evicts otherwise fitting B");
+ check(cache.put(image({5,6,7}), held.bytes()), "insert with in-flight accounting");
+ check(cache.bytes()+held.bytes() <= one*2, "exchange obeys byte budget");
+ check(!cache.make_room(one+1, one), "oversized exchange rejected");
+ check(cache.size() == 1, "oversized snapshot does not evict useful entries");
+ auto huge = image({1}); huge.live.gdn.resize(one*3);
+ check(!cache.put(std::move(huge)), "oversized image rejected");
+ check(cache.size() == 1, "oversized put leaves cache unchanged");
+ check(!cache.make_room(0, one*2+1), "held larger than budget cannot underflow");
+ }
+ {
+ ConversationCache disabled(0,4), no_slots(1024,0);
+ check(!disabled.enabled() && !no_slots.enabled(), "both disable switches");
+ check(!disabled.put(image({1,2,3})) && !no_slots.put(image({1,2,3})), "disabled cache stores nothing");
+ check(disabled.best(a,{},true).tokens == 0, "disabled cache has no matches");
+ }
+ std::printf("conversation_cache_test: %d checks passed\n", checks);
+}
diff --git a/src/core/conversation_checked.hpp b/src/core/conversation_checked.hpp
new file mode 100644
index 000000000..4355dc4e3
--- /dev/null
+++ b/src/core/conversation_checked.hpp
@@ -0,0 +1,24 @@
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <initializer_list>
+#include <limits>
+
+namespace strata::core::conversation_detail {
+inline bool add(size_t& total, size_t n) {
+ if (n > std::numeric_limits<size_t>::max() - total) return false;
+ total += n;
+ return true;
+}
+inline bool product(size_t& out, std::initializer_list<uint64_t> factors) {
+ size_t value = 1;
+ for (uint64_t factor : factors) {
+ if (factor > std::numeric_limits<size_t>::max() ||
+ (factor && value > std::numeric_limits<size_t>::max() / factor)) return false;
+ value *= (size_t) factor;
+ }
+ out = value;
+ return true;
+}
+} // namespace strata::core::conversation_detail
diff --git a/src/core/conversation_memory.cpp b/src/core/conversation_memory.cpp
new file mode 100644
index 000000000..bd5740f2f
--- /dev/null
+++ b/src/core/conversation_memory.cpp
@@ -0,0 +1,51 @@
+#include "strata/core/conversation_memory.hpp"
+
+#include <charconv>
+#include <fstream>
+#include <limits>
+#include <sstream>
+#include <string>
+
+#if defined(_WIN32)
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#include <windows.h>
+#endif
+
+namespace strata::core {
+
+std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {
+ std::optional<uint64_t> result;
+ std::string line;
+ while (std::getline(meminfo, line)) {
+ std::istringstream fields(line);
+ std::string key, value, unit, extra;
+ if (!(fields >> key) || key != "MemAvailable:") continue;
+ if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {};
+ uint64_t kb = 0;
+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb);
+ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() ||
+ kb > std::numeric_limits<uint64_t>::max() / 1024) return {};
+ result = kb * 1024;
+ }
+ if (meminfo.bad() || (meminfo.fail() && !meminfo.eof())) return {};
+ return result;
+}
+
+std::optional<uint64_t> conversation_available_memory() {
+#if defined(_WIN32)
+ MEMORYSTATUSEX status{};
+ status.dwLength = sizeof status;
+ if (GlobalMemoryStatusEx(&status)) return status.ullAvailPhys;
+ return {};
+#elif defined(__linux__)
+ std::ifstream meminfo("/proc/meminfo");
+ if (!meminfo) return {};
+ return conversation_mem_available(meminfo);
+#else
+ return {};
+#endif
+}
+
+} // namespace strata::core
diff --git a/src/core/conversation_memory_test.cpp b/src/core/conversation_memory_test.cpp
new file mode 100644
index 000000000..aec678f34
--- /dev/null
+++ b/src/core/conversation_memory_test.cpp
@@ -0,0 +1,49 @@
+#include "strata/core/conversation_memory.hpp"
+
+#include <cstdio>
+#include <cstdlib>
+#include <limits>
+#include <sstream>
+
+using namespace strata::core;
+namespace {
+int checks = 0;
+void check(bool ok, const char* label) {
+ ++checks;
+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
+}
+}
+
+int main() {
+ for (const char* text : {"", "MemFree: 100 kB\n", "MemAvailable: -1 kB\n",
+ "MemAvailable: +1 kB\n", "MemAvailable: 1 MB\n",
+ "MemAvailable: 1\n", "MemAvailable: 1x kB\n",
+ "MemAvailable: 18446744073709551615 kB\n",
+ "MemAvailable: 18446744073709551616 kB\n",
+ "MemAvailable: 1 kB trailing\n",
+ "MemAvailable: 1 kB\nMemAvailable: 2 kB\n"}) {
+ std::istringstream input(text);
+ check(!conversation_mem_available(input), "missing/malformed telemetry is unknown");
+ }
+ std::istringstream normal("MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n");
+ check(conversation_mem_available(normal) == 12345ULL * 1024, "only MemAvailable is counted");
+ std::istringstream zero("MemAvailable: 0 kB");
+ check(conversation_mem_available(zero) == 0, "zero available memory is known");
+ std::istringstream broken("MemAvailable: 123 kB\n");
+ broken.setstate(std::ios::badbit);
+ check(!conversation_mem_available(broken), "I/O failure declines admission");
+ check(!conversation_memory_admit({}, 0, 0), "unknown fails closed even with zero floor");
+ check(conversation_memory_admit(100, 40, 60), "exact allocation plus floor fits");
+ check(!conversation_memory_admit(99, 40, 60), "one byte below required memory rejected");
+ check(!conversation_memory_admit(59, 0, 60), "floor subtraction cannot underflow");
+ check(conversation_memory_admit(60, 0, 60), "post-capture floor check");
+ check(!conversation_memory_admit(100, std::numeric_limits<uint64_t>::max(), 1), "allocation arithmetic cannot overflow");
+ check(conversation_memory_admit(std::numeric_limits<uint64_t>::max(),
+ std::numeric_limits<uint64_t>::max(), 0), "maximal exact bound");
+ check(!conversation_memory_admit(std::numeric_limits<uint64_t>::max(),
+ std::numeric_limits<uint64_t>::max(), 1), "maximal sum overflow rejected");
+ // Test the real provider without assuming any particular amount of free RAM.
+ const auto available = conversation_available_memory();
+ check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown");
+ std::printf("conversation_memory_test: %d checks passed\n", checks);
+}
diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp
new file mode 100644
index 000000000..b085da83e
--- /dev/null
+++ b/src/core/conversation_snapshot.cpp
@@ -0,0 +1,190 @@
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/kernels/kv_q4.hpp"
+#include "conversation_checked.hpp"
+#include <cuda_runtime.h>
+
+#include <array>
+#include <limits>
+
+namespace strata::core {
+namespace {
+struct Layout {
+ int format;
+ int64_t cells, pooled_rows, page_size;
+ size_t data, scales, pooled, value_data, value_scales;
+};
+
+bool valid_extent(const QsaState& st, int64_t upto, std::string& error) {
+ const int64_t page = strata::kernels::qsa_real_shapes().page_size;
+ if (upto < 0 || upto > st.max_cells || upto > std::numeric_limits<int64_t>::max() - (page - 1)) {
+ error = "conversation snapshot: invalid K/V extent";
+ return false;
+ }
+ return true;
+}
+
+bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index, Layout& l, std::string& error) {
+ if (!valid_extent(st, upto, error)) return false;
+ if (st.kv_hybrid && (st.kv_mode != 0 || st.kv_q4 || !st.kv_int8)) {
+ error = "conversation snapshot: hybrid K8V4 requires identity-layout INT8 K";
+ return false;
+ }
+ const auto s = strata::kernels::qsa_real_shapes();
+ if (g.n_head_kv <= 0 || g.head_dim <= 0 || g.head_dim > INT32_MAX || g.idx_key_dim <= 0 ||
+ (st.kv_q4 && g.head_dim % 32) || (st.kv_int8 && !st.kv_q4 && g.head_dim % 64)) {
+ error = "conversation snapshot: invalid K/V geometry";
+ return false;
+ }
+ const int64_t cells = ((upto + s.page_size - 1) / s.page_size) * s.page_size;
+ const size_t per = st.kv_q4 ? (size_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)
+ : (size_t) g.head_dim * (st.kv_int8 ? 1 : 2);
+ // Include the moving spare row, not only completed blocks. The checkpoint
+ // restore reconstructs that row when rewinding to an earlier prefix.
+ const int64_t pooled = index && upto > 0 ? upto / s.idx_block + 1 : 0;
+ // Format 3 identifies snapshot K8V4 only; never pass it to the block movers.
+ l = {st.kv_hybrid ? 3 : qsa_kv_format(st), cells, pooled, s.page_size, 0, 0, 0, 0, 0};
+ using conversation_detail::product;
+ if (!product(l.data, {(uint64_t) cells, (uint64_t) g.n_head_kv, per}) ||
+ !product(l.scales, {(uint64_t) cells, (uint64_t) g.n_head_kv,
+ st.kv_int8 && !st.kv_q4 ? (uint64_t) (g.head_dim / 64) * 2 : 0}) ||
+ !product(l.pooled, {(uint64_t) pooled, (uint64_t) g.idx_key_dim, sizeof(float)})) {
+ error = "conversation snapshot: K/V byte count overflow";
+ return false;
+ }
+ l.value_data = l.data;
+ l.value_scales = l.scales;
+ if (st.kv_hybrid) {
+ if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv,
+ (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) {
+ error = "conversation snapshot: hybrid V byte count overflow";
+ return false;
+ }
+ l.value_scales = 0;
+ }
+ return true;
+}
+
+std::array<void*, 5> pools(const QsaState& st) {
+ const bool host = st.kv_mode != 0;
+ if (st.kv_hybrid) return {st.k_q, st.v_q4, st.k_scale, nullptr, st.idx_pooled};
+ if (st.kv_q4)
+ return {host ? st.host.k_q4 : st.k_q4, host ? st.host.v_q4 : st.v_q4, nullptr, nullptr, st.idx_pooled};
+ if (st.kv_int8)
+ return {host ? st.host.k_q : st.k_q, host ? st.host.v_q : st.v_q,
+ host ? st.host.k_scale : st.k_scale, host ? st.host.v_scale : st.v_scale, st.idx_pooled};
+ return {host ? st.host.k_pool : st.k_pool, host ? st.host.v_pool : st.v_pool, nullptr, nullptr, st.idx_pooled};
+}
+
+bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error) {
+ if (upto < 0 || upto > st.max_cells || st.n_pages < 0 || l.cells / l.page_size > st.n_pages ||
+ st.kv_mode < 0 || st.kv_mode > 2 || st.n_slots <= 0 ||
+ (st.kv_mode == 0 && st.n_slots < st.n_pages) ||
+ l.pooled_rows > st.idx_pooled_rows || (st.kv_mode != 0 && !st.host.present())) {
+ error = "conversation snapshot: invalid K/V extent or missing authoritative host pool";
+ return false;
+ }
+ if (st.kv_mode == 1) {
+ const auto& m = st.map;
+ if (m.n_blocks != st.n_pages || m.n_slots != st.n_slots || !m.page_table || !m.slot_block ||
+ !m.slot_stamp || !m.slot_ref || !m.ctl || !m.miss_block || !m.miss_slot) {
+ error = "conversation snapshot: invalid streaming map";
+ return false;
+ }
+ }
+ if (st.kv_mode == 2 && (!st.page_table ||
+ (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale
+ : !st.k_pool || !st.v_pool))) {
+ error = "conversation snapshot: invalid draft ring";
+ return false;
+ }
+ return true;
+}
+
+bool transfer(void* dst, const void* src, size_t n, std::string& error) {
+ if (!n) return true;
+ if (!src || !dst) { error = "conversation snapshot: missing state buffer"; return false; }
+ // Default handles both device allocations and device-mapped host pool aliases.
+ const cudaError_t e = cudaMemcpy(dst, src, n, cudaMemcpyDefault);
+ if (e == cudaSuccess) return true;
+ error = std::string("conversation snapshot copy: ") + cudaGetErrorString(e);
+ return false;
+}
+} // namespace
+
+size_t conversation_kv_bytes(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index) {
+ std::string error;
+ Layout l{};
+ if (!layout(st, g, upto, index, l, error) || !valid(st, l, upto, error)) return 0;
+ size_t bytes = l.pooled;
+ for (size_t n : {l.data, l.value_data, l.scales, l.value_scales})
+ if (!conversation_detail::add(bytes, n)) return 0;
+ return bytes;
+}
+
+bool conversation_kv_save(ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, std::string& error) {
+ Layout l{};
+ if (!layout(st, g, upto, index, l, error)) return false;
+ if (!valid(st, l, upto, error)) return false;
+ image.format = l.format;
+ image.cells = l.cells;
+ image.heads = g.n_head_kv;
+ image.head_dim = g.head_dim;
+ image.page_size = l.page_size;
+ image.pooled_rows = l.pooled_rows;
+ image.idx_dim = g.idx_key_dim;
+ const auto src = pools(st);
+ const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
+ const std::array<std::vector<uint8_t>*,5> dst = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ for (size_t i = 0; i < dst.size(); ++i) {
+ dst[i]->resize(sizes[i]);
+ if (!transfer(dst[i]->data(), src[i], sizes[i], error)) return false;
+ }
+ return true;
+}
+
+bool conversation_kv_validate(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, std::string& error) {
+ Layout l{};
+ if (!layout(st, g, upto, index, l, error)) return false;
+ if (!valid(st, l, upto, error)) return false;
+ const std::array<size_t,5> sizes = {l.data, l.value_data, l.scales, l.value_scales, l.pooled};
+ const std::array<const std::vector<uint8_t>*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ if (image.format != l.format || image.cells != l.cells || image.heads != g.n_head_kv ||
+ image.head_dim != g.head_dim || image.page_size != l.page_size || image.pooled_rows != l.pooled_rows ||
+ image.idx_dim != g.idx_key_dim) {
+ error = "conversation snapshot: incompatible K/V geometry";
+ return false;
+ }
+ for (size_t i = 0; i < src.size(); ++i)
+ if (src[i]->size() != sizes[i]) { error = "conversation snapshot: invalid K/V payload size"; return false; }
+ const auto dst = pools(st);
+ for (size_t i = 0; i < src.size(); ++i)
+ if (sizes[i] && !dst[i]) { error = "conversation snapshot: missing target state buffer"; return false; }
+ return true;
+}
+
+bool conversation_kv_restore(const ConversationKv& image, const QsaState& st, const ModelGeometry& g,
+ int64_t upto, bool index, std::string& error) {
+ if (!conversation_kv_validate(image, st, g, upto, index, error)) return false;
+ const std::array<const std::vector<uint8_t>*,5> src = {&image.k, &image.v, &image.k_scale, &image.v_scale, &image.pooled};
+ const auto dst = pools(st);
+ for (size_t i = 0; i < src.size(); ++i)
+ if (!transfer(dst[i], src[i]->data(), src[i]->size(), error)) return false;
+ // VRAM slots still contain the outgoing conversation. Resolve must refill
+ // them from the restored authoritative pools before any attention reads.
+ if (st.kv_mode == 1) strata::kernels::kv_stream_reset(st.map, nullptr);
+ if (st.kv_mode == 2 && upto > 0) {
+ auto shapes = strata::kernels::qsa_real_shapes();
+ shapes.n_head_kv = g.n_head_kv; shapes.head_dim = g.head_dim;
+ const int64_t end = (upto + shapes.page_size - 1) / shapes.page_size;
+ strata::kernels::kv_ring_restore(qsa_attn_pools(st), st.host, qsa_kv_format(st),
+ std::max<int64_t>(0, end - st.n_slots), end, st.n_slots, shapes, nullptr);
+ }
+ const auto status = cudaGetLastError();
+ if (status == cudaSuccess) return true;
+ error = std::string("conversation snapshot residency restore: ") + cudaGetErrorString(status);
+ return false;
+}
+
+} // namespace strata::core
diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp
new file mode 100644
index 000000000..9a8c89a72
--- /dev/null
+++ b/src/core/conversation_snapshot_test.cpp
@@ -0,0 +1,232 @@
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/kernels/kv_q4.hpp"
+#include <cuda_runtime.h>
+
+#include <array>
+#include <cstdio>
+#include <cstdlib>
+#include <limits>
+#include <vector>
+
+using namespace strata::core;
+using namespace strata::kernels;
+
+namespace {
+int checks = 0;
+void check(bool ok, const char* label) {
+ ++checks;
+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
+}
+void cuda_check(cudaError_t e) {
+ if (e != cudaSuccess) { std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e)); std::exit(1); }
+}
+struct Fixture {
+ ModelGeometry g;
+ QsaState state;
+ std::vector<void*> device, host;
+ std::array<void*,5> sources{};
+ std::array<size_t,5> sizes{};
+
+ template<class T> void alloc(T*& p, size_t n, bool pinned = false) {
+ if (!n) return;
+ void* raw = nullptr;
+ if (pinned) {
+ cuda_check(cudaHostAlloc(&raw, n, cudaHostAllocMapped));
+ host.push_back(raw);
+ void* mapped = nullptr;
+ cuda_check(cudaHostGetDevicePointer(&mapped, raw, 0));
+ p = static_cast<T*>(mapped);
+ } else {
+ cuda_check(cudaMalloc(&raw, n)); device.push_back(raw); p = static_cast<T*>(raw);
+ }
+ }
+ Fixture(int fmt, int mode) {
+ auto& st = state;
+ st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8 || fmt==3; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3;
+ st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages;
+ st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2;
+ const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*(st.kv_int8 ? 1:2);
+ const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv;
+ sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0,
+ fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4};
+ if (fmt==3) {
+ sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0,
+ (size_t)st.idx_pooled_rows*g.idx_key_dim*4};
+ alloc(st.k_q,sizes[0]); alloc(st.v_q4,sizes[1]); alloc(st.k_scale,sizes[2]);
+ sources[0]=st.k_q; sources[1]=st.v_q4; sources[2]=st.k_scale;
+ } else if (fmt==kKvQ4) {
+ alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per);
+ if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);}
+ sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4;
+ } else if (fmt==kKvInt8) {
+ alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per);
+ alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2);
+ if (mode) {
+ alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true);
+ alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true);
+ }
+ sources[0]=mode?st.host.k_q:st.k_q; sources[1]=mode?st.host.v_q:st.v_q;
+ sources[2]=mode?st.host.k_scale:st.k_scale; sources[3]=mode?st.host.v_scale:st.v_scale;
+ } else {
+ alloc(st.k_pool,slot_rows*per); alloc(st.v_pool,slot_rows*per);
+ if (mode) {alloc(st.host.k_pool,sizes[0],true); alloc(st.host.v_pool,sizes[1],true);}
+ sources[0]=mode?st.host.k_pool:st.k_pool; sources[1]=mode?st.host.v_pool:st.v_pool;
+ }
+ alloc(st.idx_pooled,sizes[4]); sources[4]=st.idx_pooled;
+ alloc(st.page_table,st.n_pages*4);
+ if (mode==1) {
+ auto& m=st.map;
+ m.page_table=st.page_table; m.n_blocks=st.n_pages; m.n_slots=st.n_slots;
+ alloc(m.slot_block,st.n_slots*4); alloc(m.slot_stamp,st.n_slots*4); alloc(m.slot_ref,st.n_slots*4);
+ alloc(m.miss_block,st.n_slots*4); alloc(m.miss_slot,st.n_slots*4); alloc(m.ctl,kKvCtlInts*4);
+ } else if (mode==2) {
+ kv_ring_table(st.page_table,st.n_pages,st.n_slots,nullptr);
+ }
+ }
+ void fill(uint8_t salt) {
+ for (size_t i=0;i<sources.size();++i) {
+ std::vector<uint8_t> data(sizes[i]);
+ for (size_t j=0;j<data.size();++j) data[j]=(uint8_t)(salt+i*31+j*7+j/257);
+ if (!data.empty()) cuda_check(cudaMemcpy(sources[i],data.data(),data.size(),cudaMemcpyDefault));
+ }
+ }
+ ~Fixture() { for (void* p:device) cudaFree(p); for (void* p:host) cudaFreeHost(p); }
+};
+bool equal(const ConversationKv& a,const ConversationKv& b) {
+ return a.k==b.k && a.v==b.v && a.k_scale==b.k_scale && a.v_scale==b.v_scale && a.pooled==b.pooled;
+}
+
+void full_session(int fmt, int mode, int experts) {
+ Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2);
+ auto& g=main.g;
+ g.n_layers=4; g.n_expert=experts;
+ g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8;
+ SessionState ss;
+ ss.max_cells=96; ss.qsa_states=&main.state;
+ std::string err;
+ ConversationStateSizes sizes;
+ check(conversation_state_sizes(g,sizes,err),"whole-session geometry sizes");
+ main.alloc(ss.gdn_state,sizes.gdn); main.alloc(ss.ple_hist,sizes.ple);
+ main.alloc(main.state.idx_tail,sizes.tail); main.alloc(main.state.idx_dead,sizes.dead);
+ main.alloc(main.state.idx_block_pos,sizes.block_pos);
+ std::vector<int32_t> ids(65);
+ for (size_t i=0;i<ids.size();++i) ids[i]=(int32_t)i+1;
+ std::vector<ConversationImageKey> images;
+ std::vector<ConversationCheckpoint> checkpoints;
+ auto fill=[&](uint8_t salt) {
+ main.fill(salt); draft.fill(salt);
+ for (const auto& [p,n] : std::vector<std::pair<void*,size_t>>{
+ {ss.gdn_state,sizes.gdn},{ss.ple_hist,sizes.ple},{main.state.idx_tail,sizes.tail},
+ {main.state.idx_dead,sizes.dead},{main.state.idx_block_pos,sizes.block_pos}})
+ cuda_check(cudaMemset(p,salt,n));
+ // A real indexer maintains its spare pooled row as a copy of idx_dead.
+ cuda_check(cudaMemcpy(main.state.idx_pooled+(ids.size()/4)*g.idx_key_dim,
+ main.state.idx_dead,sizes.dead,cudaMemcpyDeviceToDevice));
+ cuda_check(cudaDeviceSynchronize());
+ };
+ fill(13);
+ ConversationCheckpoint checkpoint;
+ checkpoint.ids.assign(ids.begin(),ids.begin()+3);
+ check(conversation_checkpoint_save(checkpoint,ss,g,err),"save complete running checkpoint");
+ checkpoint.used = 17;
+ checkpoints.push_back(std::move(checkpoint));
+ const ConversationView view{ids,images,checkpoints,true};
+ SavedConversation a,b,restored;
+ check(conversation_snapshot_save(a,view,ss,g,draft.state,err),"capture complete A");
+ check(a.checkpoints[0].used == 17,"upstream checkpoint LRU stamp survives capture");
+ fill(177);
+ check(conversation_snapshot_save(b,view,ss,g,draft.state,err),"capture complete B");
+ check(a.live.dead!=b.live.dead,"different opening-state spare keys in regression fixture");
+ auto bad=a; bad.kv.back().k.pop_back();
+ check(conversation_snapshot_restore(bad,ss,g,draft.state,err)==ConversationRestore::invalid,
+ "reject invalid late draft before any main-layer write");
+ check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture B after refused restore");
+ check(restored.live.gdn==b.live.gdn && restored.live.dead==b.live.dead &&
+ equal(restored.kv[0],b.kv[0]) && equal(restored.kv[1],b.kv[1]),"refusal preserves all tested state");
+ check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore complete A");
+ check(conversation_snapshot_save(restored,view,ss,g,draft.state,err),"capture restored A");
+ check(restored.live.gdn==a.live.gdn && restored.live.ple==a.live.ple && restored.live.tails==a.live.tails &&
+ restored.live.dead==a.live.dead && restored.live.block_pos==a.live.block_pos &&
+ equal(restored.kv[0],a.kv[0]) && equal(restored.kv[1],a.kv[1]),"whole-session A/B/A exactness including spare key");
+ check(ss.ple_prev[0]==64 && ss.ple_prev[1]==65,"PLE token window reconstructed");
+ check(conversation_checkpoint_restore(a.checkpoints[0],ss,g,err),"restore early running checkpoint");
+ std::vector<uint8_t> spare(sizes.dead);
+ cuda_check(cudaMemcpy(spare.data(),main.state.idx_pooled,sizes.dead,cudaMemcpyDeviceToHost));
+ check(spare==a.checkpoints[0].dead,"checkpoint rebuilds spare row over a later completed block");
+ check(ss.ple_prev[0]==2 && ss.ple_prev[1]==3,"checkpoint PLE token window");
+}
+}
+
+int main() {
+ int devices=0;
+ if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77;
+ for (int fmt : {kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) {
+ if (fmt==3 && mode!=0) continue;
+ Fixture f(fmt,mode);
+ if (fmt==3) {
+ std::string err;
+ ConversationKv invalid;
+ for (int unsupported : {1,2}) {
+ f.state.kv_mode=unsupported;
+ check(conversation_kv_bytes(f.state,f.g,9,true)==0,"hybrid streaming/ring rejected without block-mover abort");
+ check(!conversation_kv_save(invalid,f.state,f.g,9,true,err),"hybrid streaming/ring capture fails closed");
+ }
+ f.state.kv_mode=0;
+ }
+ {
+ std::string err;
+ ConversationKv invalid;
+ for (const int64_t bad : {-1LL, 97LL, (long long) std::numeric_limits<int64_t>::max()}) {
+ check(!conversation_kv_save(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid save extent before allocation");
+ check(!conversation_kv_restore(invalid,f.state,f.g,bad,mode!=2,err),"reject invalid restore extent before copying");
+ check(conversation_kv_bytes(f.state,f.g,bad,mode!=2)==0,"invalid extent cannot overflow byte estimate");
+ }
+ }
+ for (int64_t upto : {0,1,3,4,5,63,64,65,96}) {
+ const bool index=mode!=2;
+ std::string err;
+ f.fill(13);
+ ConversationKv a,b,restored;
+ cuda_check(cudaDeviceSynchronize());
+ check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A");
+ check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload");
+ f.fill(177);
+ check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B");
+ check(upto==0 || !equal(a,b),"fixture changes state");
+ check(conversation_kv_restore(a,f.state,f.g,upto,index,err),"restore A over B");
+ cuda_check(cudaDeviceSynchronize());
+ check(conversation_kv_save(restored,f.state,f.g,upto,index,err),"read back restored A");
+ check(equal(a,restored),"A/B/A byte-exact K/V and indexer state");
+ if (mode==1) {
+ std::vector<int32_t> table((size_t)f.state.n_pages);
+ cuda_check(cudaMemcpy(table.data(),f.state.page_table,table.size()*4,cudaMemcpyDeviceToHost));
+ check(std::all_of(table.begin(),table.end(),[](int32_t x){return x==-1;}),"stale VRAM pages invalidated");
+ }
+ if (mode==2 && upto>0) {
+ const auto s=qsa_real_shapes();
+ const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max<int64_t>(0,b1-f.state.n_slots);
+ kv_ring_restore(qsa_attn_pools(f.state),f.state.host,fmt,b0,b1,f.state.n_slots,s,nullptr);
+ cuda_check(cudaDeviceSynchronize());
+ const size_t block=kv_block_bytes(s,fmt)/2;
+ // Codes and scales are separate in INT8; check code bytes here.
+ const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block;
+ const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool;
+ std::vector<uint8_t> got(code_block);
+ for (int64_t page=b0;page<b1;++page) {
+ cuda_check(cudaMemcpy(got.data(),(const uint8_t*)slots+(page%f.state.n_slots)*code_block,code_block,cudaMemcpyDeviceToHost));
+ check(std::equal(got.begin(),got.end(),a.k.begin()+page*code_block),"draft ring contains restored pages");
+ }
+ }
+ auto bad=a; bad.head_dim++;
+ check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject incompatible geometry");
+ if (!a.k.empty()) {
+ bad=a; bad.k.pop_back();
+ check(!conversation_kv_restore(bad,f.state,f.g,upto,index,err),"reject malformed payload");
+ }
+ }
+ }
+ for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512})
+ full_session(fmt,mode,experts);
+ for (int experts : {256,512}) full_session(3,0,experts);
+ std::printf("conversation_snapshot_test: %d checks passed\n",checks);
+}
diff --git a/src/core/conversation_state.cpp b/src/core/conversation_state.cpp
new file mode 100644
index 000000000..4841d8ed8
--- /dev/null
+++ b/src/core/conversation_state.cpp
@@ -0,0 +1,250 @@
+#include "strata/core/conversation_snapshot.hpp"
+#include "conversation_checked.hpp"
+
+#include <algorithm>
+#include <array>
+#include <limits>
+
+namespace strata::core {
+namespace {
+using conversation_detail::add;
+using conversation_detail::product;
+
+std::array<int64_t, 18> geometry_key(const ModelGeometry& g) {
+ return {g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads,
+ g.ssm_v_heads, g.ssm_d_conv, g.ssm_conv_channels, g.ssm_value_dim,
+ g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim,
+ g.hc, g.hc_lr, g.n_expert, g.n_ff};
+}
+
+bool fail(std::string& error, const char* message) {
+ error = std::string("conversation snapshot: ") + message;
+ return false;
+}
+
+bool sync(std::string& error) {
+ const auto status = cudaDeviceSynchronize();
+ if (status == cudaSuccess) return true;
+ error = std::string("conversation snapshot synchronize: ") + cudaGetErrorString(status);
+ return false;
+}
+
+bool copy(void* dst, const void* src, size_t bytes, std::string& error) {
+ if (!bytes) return true;
+ if (!dst || !src) return fail(error, "missing running-state buffer");
+ const auto status = cudaMemcpy(dst, src, bytes, cudaMemcpyDefault);
+ if (status == cudaSuccess) return true;
+ error = std::string("conversation snapshot running-state copy: ") + cudaGetErrorString(status);
+ return false;
+}
+
+bool image_keys(const std::vector<ConversationImageKey>& images, size_t tokens) {
+ int64_t previous = -1;
+ for (const auto& image : images) {
+ if (image.start <= previous || image.start < 0 || (uint64_t) image.start >= tokens) return false;
+ previous = image.start;
+ }
+ return true;
+}
+
+bool checkpoint_targets(const SessionState& ss, const ModelGeometry& g, size_t tokens,
+ ConversationStateSizes& z, std::string& error) {
+ if (!conversation_state_sizes(g, z, error)) return false;
+ if (ss.max_cells < 0 || tokens > (uint64_t) ss.max_cells || (z.gdn && !ss.gdn_state) ||
+ (g.n_qsa_layers() && !ss.qsa_states)) return fail(error, "invalid session running-state targets");
+ for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
+ const auto& st = ss.qsa_states[i];
+ const auto block = strata::kernels::qsa_real_shapes().idx_block;
+ size_t pooled_bytes = 0;
+ if (!st.idx_tail || !st.idx_dead || !st.idx_block_pos || !st.idx_pooled ||
+ st.max_cells < 0 || tokens > (uint64_t) st.max_cells ||
+ (tokens && tokens / (uint64_t) block >= (uint64_t) std::max<int64_t>(0, st.idx_pooled_rows)) ||
+ !product(pooled_bytes, {tokens / (uint64_t) block + 1, (uint64_t) g.idx_key_dim, sizeof(float)}))
+ return fail(error, "invalid indexer running-state target");
+ }
+ return true;
+}
+
+bool view_validate(const ConversationView& view, const SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ ConversationStateSizes z;
+ if (!checkpoint_targets(ss, g, view.ids.size(), z, error)) return false;
+ if (view.ids.empty() || !image_keys(view.images, view.ids.size()) ||
+ std::any_of(view.ids.begin(), view.ids.end(), [](int32_t id) { return id < 0; }))
+ return fail(error, "invalid live token/image metadata");
+ for (const auto& c : view.checkpoints) {
+ if (!c.stage_parts.empty() || c.ids.empty() || c.ids.size() > view.ids.size() ||
+ !std::equal(c.ids.begin(), c.ids.end(), view.ids.begin()))
+ return fail(error, "checkpoint is not a live token prefix");
+ if (!conversation_checkpoint_validate(c, ss, g, error)) return false;
+ size_t image = 0;
+ for (const auto& key : view.images) {
+ if ((uint64_t) key.start >= c.ids.size()) break;
+ if (image >= c.imgs.size() || !(c.imgs[image++] == key))
+ return fail(error, "checkpoint image identity differs");
+ }
+ if (image != c.imgs.size()) return fail(error, "checkpoint image prefix differs");
+ }
+ return true;
+}
+
+bool metadata_bytes(const ConversationCheckpoint& c, size_t& total) {
+ size_t ids = 0, images = 0;
+ if (!product(ids, {c.ids.size(), sizeof(int32_t)}) ||
+ !product(images, {c.imgs.size(), sizeof(ConversationImageKey)})) return false;
+ for (size_t n : {ids, images, c.gdn.size(), c.ple.size(), c.tails.size(), c.dead.size(), c.block_pos.size()})
+ if (!add(total, n)) return false;
+ return true;
+}
+} // namespace
+
+bool conversation_state_sizes(const ModelGeometry& g, ConversationStateSizes& z, std::string& error) {
+ z = {};
+ const auto key = geometry_key(g);
+ for (size_t i = 0; i < key.size(); ++i)
+ if (key[i] < 0 || (i != 1 && key[i] == 0)) return fail(error, "invalid model geometry");
+ size_t recurrence = 0, convolution = 0;
+ if (!product(recurrence, {(uint64_t) g.ssm_state_size, (uint64_t) g.ssm_v_heads, (uint64_t) g.ssm_state_size}) ||
+ !product(convolution, {(uint64_t) g.ssm_conv_channels, (uint64_t) (g.ssm_d_conv - 1)}) ||
+ !add(recurrence, convolution) ||
+ !product(z.gdn, {(uint64_t) g.n_gdn_layers(), recurrence, sizeof(float)}) ||
+ !product(z.ple, {strata::kernels::NG_HIST, strata::kernels::NG_HC_DIM, sizeof(float)}) ||
+ !product(z.tail, {(uint64_t) (strata::kernels::qsa_real_shapes().idx_block - 1),
+ (uint64_t) g.idx_key_dim, sizeof(float)}) ||
+ !product(z.dead, {(uint64_t) g.idx_key_dim, sizeof(float)}))
+ return fail(error, "running-state byte count overflow");
+ z.block_pos = sizeof(int32_t);
+ size_t total = 0;
+ if (!product(total, {(uint64_t) g.n_qsa_layers(), z.tail}) ||
+ !product(total, {(uint64_t) g.n_qsa_layers(), z.dead}) ||
+ !product(total, {(uint64_t) g.n_qsa_layers(), z.block_pos}))
+ return fail(error, "indexer byte count overflow");
+ return true;
+}
+
+bool conversation_checkpoint_validate(const ConversationCheckpoint& c, const SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ ConversationStateSizes z;
+ if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false;
+ const size_t layers = (size_t) g.n_qsa_layers();
+ if (c.gdn.size() != z.gdn || c.ple.size() != (ss.ple_hist ? z.ple : 0) ||
+ c.tails.size() != layers * z.tail || c.dead.size() != layers * z.dead ||
+ c.block_pos.size() != layers * z.block_pos || !image_keys(c.imgs, c.ids.size()))
+ return fail(error, "invalid checkpoint running-state payload");
+ return true;
+}
+
+bool conversation_checkpoint_save(ConversationCheckpoint& c, const SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ ConversationStateSizes z;
+ if (!checkpoint_targets(ss, g, c.ids.size(), z, error)) return false;
+ const size_t layers = (size_t) g.n_qsa_layers();
+ c.gdn.resize(z.gdn); c.ple.resize(ss.ple_hist ? z.ple : 0);
+ c.tails.resize(layers * z.tail); c.dead.resize(layers * z.dead); c.block_pos.resize(layers * z.block_pos);
+ if (!copy(c.gdn.data(), ss.gdn_state, c.gdn.size(), error) ||
+ !copy(c.ple.data(), ss.ple_hist, c.ple.size(), error)) return false;
+ for (size_t i = 0; i < layers; ++i) {
+ const auto& st = ss.qsa_states[i];
+ if (!copy(c.tails.data() + i * z.tail, st.idx_tail, z.tail, error) ||
+ !copy(c.dead.data() + i * z.dead, st.idx_dead, z.dead, error) ||
+ !copy(c.block_pos.data() + i * z.block_pos, st.idx_block_pos, z.block_pos, error)) return false;
+ }
+ return true;
+}
+
+bool conversation_checkpoint_restore(const ConversationCheckpoint& c, SessionState& ss,
+ const ModelGeometry& g, std::string& error) {
+ if (!conversation_checkpoint_validate(c, ss, g, error)) return false;
+ ConversationStateSizes z;
+ if (!conversation_state_sizes(g, z, error)) return false;
+ if (!copy(ss.gdn_state, c.gdn.data(), c.gdn.size(), error) ||
+ !copy(ss.ple_hist, c.ple.data(), c.ple.size(), error)) return false;
+ for (size_t i = 0; i < (size_t) g.n_qsa_layers(); ++i) {
+ const auto& st = ss.qsa_states[i];
+ if (!copy(st.idx_tail, c.tails.data() + i * z.tail, z.tail, error) ||
+ !copy(st.idx_dead, c.dead.data() + i * z.dead, z.dead, error) ||
+ !copy(st.idx_block_pos, c.block_pos.data() + i * z.block_pos, z.block_pos, error)) return false;
+ if (!c.ids.empty()) {
+ const size_t row = c.ids.size() / strata::kernels::qsa_real_shapes().idx_block;
+ if (!copy(st.idx_pooled + row * g.idx_key_dim, c.dead.data() + i * z.dead, z.dead, error)) return false;
+ }
+ }
+ const size_t tokens = c.ids.size();
+ ss.ple_prev[0] = tokens >= 2 ? c.ids[tokens - 2] : -1;
+ ss.ple_prev[1] = tokens >= 1 ? c.ids[tokens - 1] : -1;
+ return sync(error);
+}
+
+bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error) {
+ bytes = 0;
+ if (!view_validate(view, ss, g, error)) return false;
+ ConversationStateSizes z;
+ if (!conversation_state_sizes(g, z, error)) return false;
+ size_t ids = 0, images = 0, checkpoints = 0, layers = 0, tails = 0, dead = 0, positions = 0;
+ const auto qsa = (uint64_t) g.n_qsa_layers();
+ if (!product(ids, {view.ids.size(), sizeof(int32_t)}) ||
+ !product(images, {view.images.size(), sizeof(ConversationImageKey)}) ||
+ !product(checkpoints, {view.checkpoints.size(), sizeof(ConversationCheckpoint)}) ||
+ !product(layers, {qsa + 1, sizeof(ConversationKv)}) ||
+ !product(tails, {qsa, z.tail}) || !product(dead, {qsa, z.dead}) ||
+ !product(positions, {qsa, z.block_pos})) return fail(error, "snapshot metadata byte count overflow");
+ for (size_t n : {ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ss.ple_hist ? z.ple : 0})
+ if (!add(bytes, n)) return fail(error, "snapshot byte count overflow");
+ for (const auto& c : view.checkpoints)
+ if (!metadata_bytes(c, bytes)) return fail(error, "checkpoint byte count overflow");
+ const int64_t upto = (int64_t) view.ids.size(); // view_validate bounds this by signed max_cells
+ for (uint64_t i = 0; i <= qsa; ++i) {
+ const auto& st = i == qsa ? draft : ss.qsa_states[i];
+ const size_t n = conversation_kv_bytes(st, g, upto, i != qsa);
+ if (!n || !add(bytes, n)) return fail(error, "invalid or overflowing K/V byte estimate");
+ }
+ return true;
+}
+
+bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view,
+ const SessionState& ss, const ModelGeometry& g,
+ const QsaState& draft, std::string& error) {
+ size_t estimate = 0;
+ if (!conversation_snapshot_bytes(view, ss, g, draft, estimate, error) || !sync(error)) return false;
+ // Build into a new object so a failure cannot publish a partial snapshot.
+ SavedConversation captured;
+ captured.geometry = geometry_key(g);
+ captured.live.ids = view.ids; captured.live.imgs = view.images;
+ captured.cvec = view.cvec; captured.checkpoints = view.checkpoints;
+ captured.kv.resize((size_t) g.n_qsa_layers() + 1);
+ if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;
+ const int64_t upto = (int64_t) view.ids.size();
+ for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
+ if (!conversation_kv_save(captured.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) return false;
+ if (!conversation_kv_save(captured.kv.back(), draft, g, upto, false, error)) return false;
+ image = std::move(captured);
+ return true;
+}
+
+bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ if (!image.live.stage_parts.empty()) return fail(error, "layer-split parking is not supported");
+ if (image.geometry != geometry_key(g)) return fail(error, "incompatible runtime geometry");
+ const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec};
+ if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false;
+ if (image.kv.size() != (size_t) g.n_qsa_layers() + 1) return fail(error, "invalid K/V layer count");
+ const int64_t upto = (int64_t) image.live.ids.size();
+ for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
+ if (!conversation_kv_validate(image.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error)) return false;
+ return conversation_kv_validate(image.kv.back(), draft, g, upto, false, error);
+}
+
+ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& ss,
+ const ModelGeometry& g, const QsaState& draft, std::string& error) {
+ if (!conversation_snapshot_validate(image, ss, g, draft, error)) return ConversationRestore::invalid;
+ if (!sync(error)) return ConversationRestore::transfer_failed;
+ const int64_t upto = (int64_t) image.live.ids.size();
+ for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
+ if (!conversation_kv_restore(image.kv[(size_t) i], ss.qsa_states[i], g, upto, true, error))
+ return ConversationRestore::transfer_failed;
+ if (!conversation_kv_restore(image.kv.back(), draft, g, upto, false, error) ||
+ !conversation_checkpoint_restore(image.live, ss, g, error)) return ConversationRestore::transfer_failed;
+ return ConversationRestore::restored;
+}
+} // namespace strata::core
diff --git a/src/core/conversation_validation_test.cpp b/src/core/conversation_validation_test.cpp
new file mode 100644
index 000000000..13d9b7c4f
--- /dev/null
+++ b/src/core/conversation_validation_test.cpp
@@ -0,0 +1,182 @@
+// Host-only validation fixtures. CUDA is linked but must never be initialized:
+// invalid restores must return before the first CUDA call or destination write.
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/kernels/kv_q4.hpp"
+
+#include <cstdio>
+#include <cstdlib>
+#include <functional>
+#include <limits>
+#include <cstring>
+
+#if defined(CONVERSATION_TEST_TRANSFERS)
+// GNU/ELF link wrapping exercises the actual restore control flow without
+// initializing CUDA or deliberately poisoning a real device context. This is
+// host-backend fault injection, not a claim of hardware-failure recovery.
+namespace {
+int copy_calls = 0, sync_calls = 0, fail_copy = 0, fail_sync = 0;
+}
+extern "C" cudaError_t __wrap_cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) {
+ if (++copy_calls == fail_copy) return cudaErrorInvalidValue;
+ std::memcpy(dst, src, n);
+ return cudaSuccess;
+}
+extern "C" cudaError_t __wrap_cudaDeviceSynchronize() {
+ return ++sync_calls == fail_sync ? cudaErrorUnknown : cudaSuccess;
+}
+extern "C" cudaError_t __wrap_cudaGetLastError() { return cudaSuccess; }
+#endif
+
+using namespace strata::core;
+namespace {
+int checks = 0;
+void check(bool ok, const char* label) {
+ ++checks;
+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
+}
+struct Pools {
+ QsaState st;
+ std::array<std::vector<uint8_t>, 8> data;
+ Pools(const ModelGeometry& g, int format) {
+ st.max_cells = 96; st.n_pages = st.n_slots = 24; st.idx_pooled_rows = 26;
+ st.kv_int8 = format == 1; st.kv_q4 = format == 2;
+ const size_t per = format == 2 ? strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)
+ : g.head_dim * (format == 1 ? 1 : 2);
+ data[0].resize(96 * g.n_head_kv * per, 0xa5); data[1] = data[0];
+ data[2].resize(format == 1 ? 96 * g.n_head_kv * (g.head_dim / 64) * 2 : 0, 0xa5); data[3] = data[2];
+ data[4].resize(26 * g.idx_key_dim * 4, 0xa5);
+ data[5].resize(3 * g.idx_key_dim * 4, 0xa5);
+ data[6].resize(g.idx_key_dim * 4, 0xa5); data[7].resize(4, 0xa5);
+ if (format == 2) { st.k_q4 = data[0].data(); st.v_q4 = data[1].data(); }
+ else if (format == 1) {
+ st.k_q = (int8_t*) data[0].data(); st.v_q = (int8_t*) data[1].data();
+ st.k_scale = (uint16_t*) data[2].data(); st.v_scale = (uint16_t*) data[3].data();
+ } else { st.k_pool = (uint16_t*) data[0].data(); st.v_pool = (uint16_t*) data[1].data(); }
+ st.idx_pooled = (float*) data[4].data(); st.idx_tail = (float*) data[5].data();
+ st.idx_dead = (float*) data[6].data(); st.idx_block_pos = (int32_t*) data[7].data();
+ }
+ ConversationKv image(const ModelGeometry& g, bool index) const {
+ ConversationKv k;
+ k.format = qsa_kv_format(st); k.cells = 12; k.page_size = 4;
+ k.heads = g.n_head_kv; k.head_dim = g.head_dim; k.idx_dim = g.idx_key_dim;
+ k.pooled_rows = index ? 3 : 0;
+ k.k.resize(data[0].size() / 8, 13); k.v = k.k;
+ k.k_scale.resize(data[2].size() / 8, 13); k.v_scale = k.k_scale;
+ k.pooled.resize(k.pooled_rows * g.idx_key_dim * 4, 13);
+ return k;
+ }
+};
+
+void fixture(int format, int experts, bool zero_qsa, bool ple) {
+ ModelGeometry g;
+ g.n_layers = zero_qsa ? 3 : 8; g.n_expert = experts;
+ g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8;
+ g.n_head_kv = 1; g.head_dim = 64; g.idx_key_dim = 8;
+ std::string error;
+ ConversationStateSizes z;
+ check(conversation_state_sizes(g, z, error), "checked canonical/pruned/zero-QSA sizing");
+ Pools first(g, format), last(g, format), draft(g, format);
+ std::array<QsaState, 2> layers{first.st, last.st};
+ std::vector<uint8_t> gdn(z.gdn, 0xa5), history(ple ? z.ple : 0, 0xa5);
+ SessionState ss;
+ ss.max_cells = 96; ss.gdn_state = (float*) gdn.data();
+ ss.ple_hist = ple ? (float*) history.data() : nullptr;
+ ss.qsa_states = zero_qsa ? nullptr : layers.data();
+ SavedConversation image;
+ image.geometry = {g.n_embd,g.n_layers,g.qsa_interval,g.ssm_state_size,g.ssm_k_heads,g.ssm_v_heads,
+ g.ssm_d_conv,g.ssm_conv_channels,g.ssm_value_dim,g.n_head,g.n_head_kv,g.head_dim,
+ g.idx_q_heads,g.idx_key_dim,g.hc,g.hc_lr,g.n_expert,g.n_ff};
+ auto checkpoint = [&](size_t tokens) {
+ ConversationCheckpoint c;
+ c.ids.resize(tokens);
+ for (size_t i = 0; i < tokens; ++i) c.ids[i] = (int32_t) i + 1;
+ c.imgs = {{1, 44}};
+ c.gdn.resize(z.gdn, 13); c.ple.resize(ple ? z.ple : 0, 13);
+ c.tails.resize(g.n_qsa_layers() * z.tail, 13); c.dead.resize(g.n_qsa_layers() * z.dead, 13);
+ c.block_pos.resize(g.n_qsa_layers() * z.block_pos, 13);
+ return c;
+ };
+ image.live = checkpoint(9); image.checkpoints.push_back(checkpoint(5));
+ image.kv.reserve((size_t) g.n_qsa_layers() + 1);
+ if (!zero_qsa) { image.kv.push_back(first.image(g, true)); image.kv.push_back(last.image(g, true)); }
+ image.kv.push_back(draft.image(g, false));
+ check(conversation_snapshot_validate(image, ss, g, draft.st, error), "complete image validates without CUDA");
+ size_t estimate = 0;
+ check(conversation_snapshot_bytes({image.live.ids,image.live.imgs,image.checkpoints,true},ss,g,draft.st,estimate,error),
+ "capture estimate works without CUDA");
+ check(estimate == image.bytes(), "estimate covers checkpoint/indexer/spare payloads");
+ auto unchanged = [&] {
+ auto pristine = [](const auto& bytes) { return std::all_of(bytes.begin(),bytes.end(),[](uint8_t b){return b==0xa5;}); };
+ if (!pristine(gdn) || !pristine(history) || ss.ple_prev[0] != -1 || ss.ple_prev[1] != -1) return false;
+ for (const auto* p : {&first,&last,&draft}) for (const auto& bytes : p->data) if (!pristine(bytes)) return false;
+ return true;
+ };
+ auto reject = [&](const std::function<void(SavedConversation&)>& mutate, const char* label) {
+ auto bad = image; mutate(bad);
+ check(conversation_snapshot_restore(bad,ss,g,draft.st,error) == ConversationRestore::invalid,label);
+ check(unchanged(), "invalid restore did not touch any layer or running-state buffer");
+ };
+ reject([](auto& s){s.kv.back().k.pop_back();}, "late draft corruption rejected before first layer write");
+ reject([](auto& s){s.geometry[16] = 128;}, "different expert geometry rejected");
+ reject([](auto& s){s.live.stage_parts.emplace_back();}, "layer-split live state rejected before writes");
+ reject([](auto& s){s.checkpoints[0].stage_parts.emplace_back();}, "layer-split checkpoint rejected before writes");
+ reject([](auto& s){s.kv.pop_back();}, "missing KV layer rejected");
+ reject([](auto& s){s.live.gdn.pop_back();}, "bad live recurrence rejected");
+ reject([](auto& s){s.checkpoints.back().gdn.pop_back();}, "bad retained checkpoint rejected");
+ reject([](auto& s){s.checkpoints.back().ids[0] = 99;}, "foreign checkpoint prefix rejected");
+ reject([](auto& s){s.checkpoints.back().imgs[0].hash++;}, "foreign checkpoint image rejected");
+ reject([](auto& s){s.live.imgs[0].start = -1;}, "negative image position rejected");
+ reject([](auto& s){s.live.ids[0] = -1;}, "negative live token rejected");
+ reject([](auto& s){s.live.ple.push_back(0);}, "PLE size/enabled mismatch rejected");
+ reject([](auto& s){s.live.tails.push_back(0);}, "tail size/zero-QSA mismatch rejected");
+ if (!zero_qsa) {
+ reject([](auto& s){s.kv[1].pooled.pop_back();}, "late indexer spare row corruption rejected");
+ reject([](auto& s){s.live.dead.pop_back();}, "missing indexer spare key rejected");
+ reject([](auto& s){s.live.block_pos.pop_back();}, "missing indexer metadata rejected");
+ ss.qsa_states = nullptr;
+ check(!conversation_snapshot_validate(image,ss,g,draft.st,error), "missing QSA targets rejected");
+ ss.qsa_states = layers.data();
+ }
+ auto bad_geometry = g; bad_geometry.ssm_state_size = std::numeric_limits<int64_t>::max();
+ check(!conversation_state_sizes(bad_geometry,z,error), "running-state arithmetic overflow rejected");
+ bad_geometry = g; bad_geometry.qsa_interval = 0;
+ check(!conversation_state_sizes(bad_geometry,z,error), "zero layer interval rejected before division");
+ bad_geometry = g; bad_geometry.n_head_kv = std::numeric_limits<int64_t>::max();
+ check(conversation_kv_bytes(draft.st,bad_geometry,9,false)==0, "KV byte overflow rejected");
+#if defined(CONVERSATION_TEST_TRANSFERS)
+ auto reset = [&] {
+ for (auto* p : {&first,&last,&draft}) for (auto& bytes : p->data) std::fill(bytes.begin(),bytes.end(),0xa5);
+ std::fill(gdn.begin(),gdn.end(),0xa5); std::fill(history.begin(),history.end(),0xa5);
+ ss.ple_prev[0] = ss.ple_prev[1] = -1;
+ copy_calls = sync_calls = fail_copy = fail_sync = 0;
+ };
+ reset(); fail_sync = 1;
+ check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
+ "pre-transfer CUDA synchronization failure is fatal");
+ check(copy_calls==0 && unchanged(), "pre-sync failure did not mutate state");
+ reset(); fail_copy = 1;
+ check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
+ "first CUDA transfer failure is fatal");
+ check(unchanged(), "first-copy failure did not mutate state");
+ reset(); fail_copy = 2;
+ check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
+ "partial CUDA transfer failure is fatal, not an invalid-image fallback");
+ check(!unchanged(), "fault fixture genuinely produced partial state");
+ reset(); fail_sync = 2;
+ check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::transfer_failed,
+ "post-transfer CUDA synchronization failure is fatal");
+ check(copy_calls>0 && !unchanged(), "post-sync failure occurred after state writes");
+ reset();
+ check(conversation_snapshot_restore(image,ss,g,draft.st,error)==ConversationRestore::restored,
+ "injected host transfer backend completes a valid restore");
+ check(gdn==image.live.gdn && history==image.live.ple && ss.ple_prev[0]==8 && ss.ple_prev[1]==9,
+ "successful restore publishes correct running state and PLE window");
+#endif
+}
+}
+
+int main() {
+ for (int format : {0,1,2}) for (int experts : {256,512})
+ for (bool zero_qsa : {false,true}) for (bool ple : {false,true}) fixture(format,experts,zero_qsa,ple);
+ std::printf("conversation_validation_test: %d host-only checks passed\n", checks);
+}
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 607008706..a2bb0d139 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -15,6 +15,8 @@
// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump.
#include "strata/core/expert_cache.hpp"
+#include "strata/core/conversation_snapshot.hpp"
+#include "strata/core/conversation_memory.hpp"
#include "strata/core/expert_source.hpp"
#include "strata/core/remote_experts.hpp"
#include "strata/core/on_device.hpp"
@@ -75,6 +77,8 @@
#include <deque>
#include <map>
#include <mutex>
+#include <optional>
+#include <new>
#include <charconv>
#include <cmath>
#include <limits>
@@ -282,6 +286,9 @@ struct Options {
/// prompt again, the v0.1.2 behaviour). One is the GDN recurrence of the 36 layers, the QSA indexer tails and
/// the PLE history (~118 MB of host RAM); the KV cache itself is positional and stays where it is.
int prompt_cache = 6;
+ int64_t conversation_cache_mib = 0; // opt-in host RAM for independent conversations
+ int conversation_cache_slots = 4;
+ int64_t conversation_cache_min_free_mib = 2560;
/// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary)
int64_t prompt_cache_every = 16384;
/// --serve: a prompt read from token 0 is also checkpointed at its first turn boundary - the end of the system
@@ -375,6 +382,9 @@ void usage() {
" --vision --serve takes images too (GENI requests; embeddings from strata-vision)\n"
" --prompt-cache N --serve: keep N conversation checkpoints between requests (default 6, ~118 MB\n"
" of RAM each; 0 = read every prompt from the start)\n"
+ " --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n"
+ " --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n"
+ " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n"
" --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n"
" --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n"
" --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n"
@@ -708,19 +718,8 @@ int argmax(const std::vector<float>& v) {
// back rejected drafts.
// A checkpoint is only valid while the positional cells below it still hold ITS tokens, so the serve loop keeps
// just the checkpoints that are prefixes of the tokens the session holds now.
-struct ImgKey {
- int64_t start = 0; ///< the image's first <|image_pad|> position
- uint64_t hash = 0; ///< its embeddings and grid: the pad tokens alone are the same for every picture
- bool operator==(const ImgKey& o) const { return start == o.start && hash == o.hash; }
-};
-
-struct ConvCheckpoint {
- std::vector<int32_t> ids; ///< the tokens this state has consumed
- std::vector<ImgKey> imgs; ///< the images among them
- std::vector<uint8_t> gdn, ple, tails;
- uint64_t used = 0; ///< last-use stamp for the retention policy (conv_cache.hpp)
- std::vector<ConvCheckpoint> stage_parts; ///< a layer split's later stages: their sessions' running state
-};
+using ImgKey = strata::core::ConversationImageKey;
+using ConvCheckpoint = strata::core::ConversationCheckpoint;
uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) {
const uint8_t* p = (const uint8_t*) data;
@@ -728,52 +727,25 @@ uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull)
return h;
}
-struct ConvStateSizes {
- size_t gdn = 0, ple = 0, tail = 0;
-};
+using ConvStateSizes = strata::core::ConversationStateSizes;
ConvStateSizes conv_state_sizes(const strata::core::ModelGeometry& g) {
ConvStateSizes z;
- z.gdn = (size_t) g.n_gdn_layers() *
- ((size_t) g.ssm_state_size * (size_t) g.ssm_v_heads * (size_t) g.ssm_state_size +
- (size_t) g.ssm_conv_channels * (size_t) (g.ssm_d_conv - 1)) * sizeof(float);
- z.ple = (size_t) strata::kernels::NG_HIST * (size_t) strata::kernels::NG_HC_DIM * sizeof(float);
- z.tail = (size_t) (strata::kernels::qsa_real_shapes().idx_block - 1) * (size_t) g.idx_key_dim * sizeof(float);
+ std::string error;
+ strata::core::conversation_state_sizes(g, z, error); // geometry has already passed engine validation
return z;
}
/// Copies the running state out. The caller has synchronized the device.
bool checkpoint_save(ConvCheckpoint& c, const strata::core::SessionState& ss, const strata::core::ModelGeometry& g) {
- const ConvStateSizes z = conv_state_sizes(g);
- c.gdn.resize(z.gdn);
- c.ple.resize(ss.ple_hist != nullptr ? z.ple : 0);
- c.tails.resize(z.tail * (size_t) g.n_qsa_layers());
- if (cudaMemcpy(c.gdn.data(), ss.gdn_state, z.gdn, cudaMemcpyDeviceToHost) != cudaSuccess) return false;
- if (!c.ple.empty() && cudaMemcpy(c.ple.data(), ss.ple_hist, z.ple, cudaMemcpyDeviceToHost) != cudaSuccess)
- return false;
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
- if (cudaMemcpy(c.tails.data() + (size_t) i * z.tail, ss.qsa_states[i].idx_tail, z.tail, cudaMemcpyDeviceToHost) !=
- cudaSuccess)
- return false;
- return true;
+ std::string error;
+ return strata::core::conversation_checkpoint_save(c, ss, g, error);
}
/// Puts a checkpoint's running state back; the positional cells below it are the caller's to guarantee.
bool checkpoint_restore(const ConvCheckpoint& c, strata::core::SessionState& ss, const strata::core::ModelGeometry& g) {
- const ConvStateSizes z = conv_state_sizes(g);
- if (c.gdn.size() != z.gdn || c.tails.size() != z.tail * (size_t) g.n_qsa_layers()) return false;
- if (cudaMemcpy(ss.gdn_state, c.gdn.data(), z.gdn, cudaMemcpyHostToDevice) != cudaSuccess) return false;
- if (!c.ple.empty() && cudaMemcpy(ss.ple_hist, c.ple.data(), z.ple, cudaMemcpyHostToDevice) != cudaSuccess)
- return false;
- for (int64_t i = 0; i < g.n_qsa_layers(); ++i)
- if (cudaMemcpy(ss.qsa_states[i].idx_tail, c.tails.data() + (size_t) i * z.tail, z.tail, cudaMemcpyHostToDevice) !=
- cudaSuccess)
- return false;
- // the PLE's token window is the last two tokens, OLDEST FIRST, -1 where there is none (as session_zero leaves it)
- const size_t L = c.ids.size();
- ss.ple_prev[0] = L >= 2 ? c.ids[L - 2] : -1;
- ss.ple_prev[1] = L >= 1 ? c.ids[L - 1] : -1;
- return cudaDeviceSynchronize() == cudaSuccess;
+ std::string error;
+ return strata::core::conversation_checkpoint_restore(c, ss, g, error);
}
// --control-vector-scaled: llama.cpp's `common_control_vector_load` (every file's `direction.<l>` times its scale,
@@ -1020,6 +992,20 @@ int main(int argc, char** argv) {
else if (a == "--serve") o.serve = true;
else if (a == "--vision") o.vision = true;
else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));
+ else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||
+ a == "--conversation-cache-min-free-mib") {
+ const std::string value = next(a.c_str());
+ int64_t parsed = 0;
+ const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);
+ const int64_t limit = a == "--conversation-cache-slots" ? INT32_MAX : INT64_MAX / (1024 * 1024);
+ if (result.ec != std::errc{} || result.ptr != value.data() + value.size() || parsed < 0 || parsed > limit) {
+ std::fprintf(stderr, "%s needs a nonnegative integer within range\n", a.c_str());
+ return 2;
+ }
+ if (a == "--conversation-cache-mib") o.conversation_cache_mib = parsed;
+ else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = parsed;
+ else o.conversation_cache_slots = (int) parsed;
+ }
else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every")));
else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root")));
else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token"));
@@ -1089,6 +1075,13 @@ int main(int argc, char** argv) {
return 2;
}
}
+ if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))
+ std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",
+ o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");
+ if (o.conversation_cache_mib > 0 && o.conversation_cache_slots > 0 && o.prompt_cache > 0 && !o.layer_split.empty()) {
+ std::fprintf(stderr, "strata serve: conversation parking does not yet support --layer-split; disable parking with --conversation-cache-mib 0\n");
+ return 2;
+ }
// Layer split (multi-GPU): the later stages run layers [K_i, K_i+1) on their own GPUs (--split-device, default
// the next visible ones); "auto" places the K from each GPU's free VRAM once the weights are in (below). Across
// GPUs, not yet: KV streaming, images, control vectors, the helper caches (--expert-cache-remote), and lending
@@ -3263,6 +3256,50 @@ int main(int argc, char** argv) {
std::vector<ConvCheckpoint> checks;
uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it
bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with
+ strata::core::ConversationCache conversations(
+ o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0,
+ (size_t) o.conversation_cache_slots);
+ // Save only on a switch/rewind, not on each continuing request. No graph
+ // addresses change: all parked images live in ordinary host vectors.
+ auto park_current = [&](size_t held) -> bool {
+ if (!conversations.enabled() || !live_ok || live.empty()) return true;
+ const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached};
+ size_t estimate = 0;
+ if (!strata::core::conversation_snapshot_bytes(view, ss, g, mtp.kv_state(), estimate, err)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (%s)\n", err.c_str());
+ return true;
+ }
+ if (!conversations.make_room(estimate, held)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (snapshot %zu MiB exceeds available budget)\n",
+ estimate >> 20);
+ return true;
+ }
+ const auto t0 = Clock::now();
+ try {
+ const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;
+ if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), estimate, floor)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n",
+ estimate >> 20, (long long) o.conversation_cache_min_free_mib);
+ return true;
+ }
+ strata::core::SavedConversation image;
+ if (!strata::core::conversation_snapshot_save(image, view, ss, g, mtp.kv_state(), err)) return false;
+ if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {
+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");
+ return true;
+ }
+ const bool stored = conversations.put(std::move(image), held);
+ std::fprintf(stderr, "strata serve: conversation cache: %s %zu tokens in %.1f ms; parked=%zu bytes=%zu evictions=%zu\n",
+ stored ? "parked" : "skipped", live.size(),
+ std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),
+ conversations.size(), conversations.bytes(), conversations.evictions());
+ } catch (const std::bad_alloc&) {
+ // The active state has not been touched. Continue with normal
+ // prompt processing rather than killing a serving process.
+ std::fprintf(stderr, "strata serve: conversation cache: allocation failed; skip parking\n");
+ }
+ return true;
+ };
int64_t pp_total = 0, pp_from = 0, pp_next_check = 0;
Clock::time_point pp_t0 = Clock::now();
auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
@@ -3291,12 +3328,15 @@ int main(int argc, char** argv) {
c.gdn = std::move((*parts)[0].gdn);
c.ple = std::move((*parts)[0].ple);
c.tails = std::move((*parts)[0].tails);
+ c.dead = std::move((*parts)[0].dead);
+ c.block_pos = std::move((*parts)[0].block_pos);
for (size_t i = 1; i < parts->size(); ++i) c.stage_parts.push_back(std::move((*parts)[i]));
} else {
if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(c, ss, g)) return false;
for (auto& st : stages) { // a layer split's later stages: their sessions' part
const strata::core::OnDevice on(st->dev);
ConvCheckpoint part;
+ part.ids = c.ids;
if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(part, st->ss, g)) return false;
c.stage_parts.push_back(std::move(part));
}
@@ -3358,6 +3398,7 @@ int main(int argc, char** argv) {
if (o.prompt_cache <= 0 || o.prompt_cache_every <= 0 || done < part_next[i]) return true;
part_next[i] = done + o.prompt_cache_every;
ConvCheckpoint part; // this stage's state at `done` (its stream is synchronized)
+ part.ids.assign(cur.begin(), cur.begin() + done);
if (!checkpoint_save(part, stage_ss, g)) { e = "saving a checkpoint part failed"; return false; }
std::lock_guard<std::mutex> lk(part_mu);
auto& v = part_at[done];
@@ -3542,14 +3583,16 @@ int main(int argc, char** argv) {
cudaMemGetInfo(&free_b, &total_b);
std::printf("INFO context=%lld kv=%s kv_resident=%lld expert_slots=%lld expert_cache_mib=%lld spec=%d "
"mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f "
- "spec_min_p=%.2f engine=" STRATA_VERSION "\n",
+ "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d "
+ "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n",
(long long) o.max_context, o.kv.c_str(),
(long long) (g.n_qsa_layers() > 0 && ss.qsa_states[0].kv_mode == 1
? ss.qsa_states[0].n_slots * 4 : 0),
(long long) xcache.slots(), (long long) (xcache.bytes() >> 20), o.spec, o.mtp_max_t,
o.suffix_draft, (long long) (free_b >> 20), cvec_summary.c_str(),
(long long) (strata::kernels::cpu::expert_layout().total >> 20), pool.workers(), o.pcie_frac,
- o.spec_min_p);
+ o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots,
+ (long long) o.conversation_cache_min_free_mib);
}
// issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on
// a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the
@@ -3784,20 +3827,10 @@ int main(int argc, char** argv) {
if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false;
return imgs_below(req_imgs, L) == pre_imgs;
};
- // the control vector for this request. The live session and the checkpoints were read one way, so a
- // switch reads the prompt again from the start
- if (strata::kernels::cvec().loaded()) {
- const bool want = req_cvec != 0;
- if (want != cvec_cached) {
- live_ok = false;
- checks.clear();
- cvec_cached = want;
- }
- strata::kernels::cvec_set_enabled(want);
- }
+ const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true;
int64_t resume = 0;
bool from_live = false;
- if (o.prompt_cache > 0) {
+ if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; }
for (const ConvCheckpoint& c : checks)
if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) {
@@ -3805,6 +3838,48 @@ int main(int argc, char** argv) {
from_live = false;
}
}
+ const auto parked = conversations.best(ids, req_imgs, want_cvec);
+ std::optional<strata::core::SavedConversation> incoming;
+ if (parked.tokens > resume) incoming.emplace(conversations.take(parked.index));
+ // Reject the entire image before parking/overwriting the outgoing
+ // state. Invalid entries can safely fall back to its existing prefix.
+ if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, mtp.kv_state(), err)) {
+ std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str());
+ incoming.reset();
+ }
+ // Preserve the outgoing branch before any checkpoint rewind, reset,
+ // or incoming restore overwrites the positional state it requires.
+ if ((!from_live || incoming) && !park_current(incoming ? incoming->bytes() : 0)) {
+ std::printf("ERR %s\n", err.c_str());
+ return 1;
+ }
+ if (incoming) {
+ const auto t0 = Clock::now();
+ if (strata::core::conversation_snapshot_restore(*incoming, ss, g, mtp.kv_state(), err) !=
+ strata::core::ConversationRestore::restored) {
+ // Already prevalidated above: a failure here is fatal, never
+ // permission to decode from a partially restored session.
+ std::printf("ERR restoring parked conversation: %s\n", err.c_str());
+ return 1;
+ }
+ live = std::move(incoming->live.ids);
+ live_imgs = std::move(incoming->live.imgs);
+ checks = std::move(incoming->checkpoints);
+ cvec_cached = incoming->cvec;
+ resume = parked.tokens;
+ from_live = parked.live;
+ incoming.reset(); // release the transfer image before prompt processing
+ std::fprintf(stderr, "strata serve: conversation cache: restored %lld tokens (%s) in %.1f ms; parked=%zu bytes=%zu\n",
+ (long long) resume, from_live ? "live" : "checkpoint",
+ std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),
+ conversations.size(), conversations.bytes());
+ }
+ if (want_cvec != cvec_cached) {
+ live_ok = false;
+ checks.clear();
+ cvec_cached = want_cvec;
+ }
+ if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec);
// this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's
// path) no longer has its cells; the ones kept are prefixes of both the old tokens and the new
checks.erase(std::remove_if(checks.begin(), checks.end(), [&](const ConvCheckpoint& c) {
@@ -4257,7 +4332,7 @@ int main(int argc, char** argv) {
};
const ConvStateSizes z = conv_state_sizes(g);
uint64_t h_gdn = hash_dev(ss.gdn_state, z.gdn, 1469598103934665603ull);
- if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // per GDN layer: which one differs first
+ if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr && g.n_gdn_layers() > 0) { // per GDN layer: which one differs first
const size_t per = z.gdn / (size_t) g.n_gdn_layers();
std::string s;
char b[8];
@@ -4267,8 +4342,9 @@ int main(int argc, char** argv) {
}
std::fprintf(stderr, "strata serve: STATE_HASH_GDN %s\n", s.c_str());
}
- uint64_t h_ple = hash_dev(ss.ple_hist, z.ple, 1469598103934665603ull);
+ uint64_t h_ple = hash_dev(ss.ple_hist, ss.ple_hist ? z.ple : 0, 1469598103934665603ull);
uint64_t h_tail = 1469598103934665603ull, h_pool = h_tail, h_kv = h_tail, h_stale = h_tail;
+ uint64_t h_dead = h_tail;
const int64_t kvb = qs.head_dim, scb = (qs.head_dim / 64) * 2;
// a state's K/V arrays and their bytes per (cell, head) row: the host copy when it has one
auto kv_arrays = [&](const strata::core::QsaState& st) {
@@ -4281,18 +4357,22 @@ int main(int argc, char** argv) {
const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim);
a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b},
{h ? st.host.k_scale : st.k_scale, scb}};
- } else {
+ } else if (st.kv_int8) {
a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb},
{h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}};
+ } else {
+ a = {{h ? st.host.k_pool : st.k_pool, qs.head_dim * 2},
+ {h ? st.host.v_pool : st.v_pool, qs.head_dim * 2}};
}
return a;
};
const int64_t end_cell = std::min<int64_t>(((L + qs.page_size - 1) / qs.page_size) * qs.page_size,
- ss.qsa_states[0].max_cells);
+ ss.max_cells);
for (int64_t i = 0; i < g.n_qsa_layers(); ++i) {
const strata::core::QsaState& st = ss.qsa_states[i];
h_tail = hash_dev(st.idx_tail, z.tail, h_tail);
- h_pool = hash_dev(st.idx_pooled, (size_t) (L / qs.idx_block) * qs.idx_dim * 4, h_pool);
+ h_dead = hash_dev(st.idx_dead, z.dead, h_dead);
+ h_pool = hash_dev(st.idx_pooled, (size_t) (L > 0 ? L / qs.idx_block + 1 : 0) * qs.idx_dim * 4, h_pool);
// KV streaming: the host copy is the identity layout and holds every cell
for (const auto& [pool, w] : kv_arrays(st)) {
h_kv = hash_cells(pool, w, 0, L, h_kv);
@@ -4305,10 +4385,10 @@ int main(int argc, char** argv) {
for (const auto& [pool, w] : kv_arrays(ms))
if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp);
std::fprintf(stderr, "strata serve: STATE_HASH L=%lld gdn=%016llx ple=%016llx tail=%016llx pooled=%016llx "
- "kv=%016llx mtp=%016llx stale=%016llx ple_prev=%d,%d\n", (long long) L,
+ "kv=%016llx mtp=%016llx stale=%016llx dead=%016llx ple_prev=%d,%d\n", (long long) L,
(unsigned long long) h_gdn, (unsigned long long) h_ple, (unsigned long long) h_tail,
(unsigned long long) h_pool, (unsigned long long) h_kv, (unsigned long long) h_mtp,
- (unsigned long long) h_stale, ss.ple_prev[0], ss.ple_prev[1]);
+ (unsigned long long) h_stale, (unsigned long long) h_dead, ss.ple_prev[0], ss.ple_prev[1]);
}
const int64_t req_hits = drive.d.cache_hits - decode_hits0;
const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;
diff --git a/tools/conversation_cache_http_smoke.py b/tools/conversation_cache_http_smoke.py
new file mode 100644
index 000000000..bd1df98cc
--- /dev/null
+++ b/tools/conversation_cache_http_smoke.py
@@ -0,0 +1,137 @@
+"""Destructive-to-cache HTTP smoke test for an EXCLUSIVE, idle Strata test server.
+
+Sends synthetic conversations, deliberately evicts cached conversations, and
+disconnects a streaming response. Never run while other clients are using it.
+Dry-run by default; --run explicitly enables network traffic. Does not restart
+or reconfigure the server. Use the private-engine parity gate for state hashes.
+"""
+import argparse
+import json
+from pathlib import Path
+import time
+import urllib.request
+import uuid
+
+
+def require(condition, message):
+ if not condition:
+ raise RuntimeError(message)
+
+
+class Client:
+ def __init__(self, url):
+ self.url = url.rstrip('/')
+
+ def metrics(self):
+ with urllib.request.urlopen(self.url + '/metrics', timeout=10) as response:
+ return json.load(response)
+
+ def request(self, model, content, stream=False, count=8):
+ body = {'model': model, 'messages': [{'role': 'user', 'content': content}],
+ 'max_tokens': count, 'temperature': 0, 'stream': stream,
+ 'chat_template_kwargs': {'enable_thinking': False}}
+ request = urllib.request.Request(self.url + '/v1/chat/completions',
+ data=json.dumps(body).encode(),
+ headers={'Content-Type': 'application/json'})
+ return urllib.request.urlopen(request, timeout=120)
+
+
+def run(client):
+ initial = client.metrics()
+ require(initial['live']['state'] == 'idle' and initial['live']['queued'] == 0, 'server is busy')
+ info = initial['engine']
+ slots = info.get('conversation_cache_slots', 0)
+ require(info.get('conversation_cache_mib', 0) > 0 and 1 <= slots <= 16,
+ 'requires an enabled cache with 1–16 slots')
+ require(not info.get('api_key'), 'use an unauthenticated private test endpoint')
+ marker = 'cache-smoke-' + uuid.uuid4().hex
+ records = []
+
+ def before():
+ metrics = client.metrics()
+ require(metrics['live']['state'] == 'idle' and metrics['live']['queued'] == 0,
+ 'concurrent client detected')
+ return max((r['time'] for r in metrics['requests']), default=0)
+
+ def after(stamp, label):
+ for _ in range(50):
+ metrics = client.metrics()
+ if metrics['live']['state'] == 'idle':
+ break
+ time.sleep(.2)
+ require(metrics['live']['state'] == 'idle', 'request did not drain')
+ fresh = [r for r in metrics['requests'] if r['time'] > stamp]
+ require(len(fresh) == 1 and metrics['live']['queued'] == 0,
+ 'missing request evidence or concurrent traffic')
+ record = {'name': label, **fresh[0]}
+ records.append(record)
+ return record
+
+ def prompt(label):
+ return marker + ' ' + label + '\n' + '\n'.join(
+ f'Record {i}: blue square, green triangle, red circle.' for i in range(128)
+ ) + '\nName one color. Answer with one word.'
+
+ def ask(label, content):
+ stamp = before()
+ with client.request(info['model'], content) as response:
+ result = json.load(response)
+ require(bool(result.get('choices')), 'missing completion')
+ record = after(stamp, label)
+ require(record['finish'] in ('length', 'stop'), 'request did not finish normally')
+ return result['choices'][0]['message'], record
+
+ a, _ = ask('A', prompt('A'))
+ ask('B', prompt('B'))
+ restored, record = ask('A-restored', prompt('A'))
+ require(record['reused'] > 0 and a == restored, 'A/B/A reuse or output mismatch')
+ for i in range(slots + 1):
+ ask(f'evict-{i}', prompt(f'evict-{i}'))
+ _, record = ask('A-evicted', prompt('A'))
+ require(record['reused'] == 0, 'old A survived slot eviction')
+
+ text = marker + ' cancel: ' + 'blue green red. ' * 256
+ text += '\nCount from 1 to 1000, one number per line. Do not summarize.'
+ stamp = before()
+ with client.request(info['model'], text, stream=True, count=4096) as response:
+ for line in response:
+ if not line.startswith(b'data: ') or line.strip() == b'data: [DONE]':
+ continue
+ choices = json.loads(line[6:]).get('choices', [])
+ if choices and choices[0].get('delta', {}).get('content'):
+ break
+ else:
+ raise RuntimeError('no streamed content to cancel')
+ record = after(stamp, 'cancelled')
+ require(record['finish'] in ('disconnect', 'cancel') and 0 < record['output_tokens'] < 4096,
+ 'stream cancellation not observed')
+ ask('after-cancel-B', marker + ' Unrelated B: say hello.')
+ _, record = ask('cancelled-A-restored', text)
+ require(record['reused'] > 0, 'cancelled conversation was not restored')
+ return {'engine_info': info, 'records': records}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--url', default='http://127.0.0.1:11434')
+ parser.add_argument('--output', type=Path, required=True, help='new results file; existing paths refused')
+ parser.add_argument('--run', action='store_true')
+ args = parser.parse_args()
+ if not args.run:
+ print('Dry run: HTTP A/B/A, slot eviction, cancellation and recovery. No network traffic.')
+ return
+ # Refuse accidental overwrites before generating traffic.
+ with args.output.open('x', encoding='utf-8') as output:
+ try:
+ result = run(Client(args.url))
+ except Exception as error:
+ json.dump({'passed': False, 'error': str(error)}, output, indent=2)
+ output.write('\n')
+ raise
+ json.dump({'passed': True, **result}, output, indent=2)
+ output.write('\n')
+ print(f'PASS: HTTP reuse, slot eviction, cancellation/recovery. Results: {args.output}')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/conversation_cache_isolation.py b/tools/conversation_cache_isolation.py
new file mode 100644
index 000000000..8cfa54796
--- /dev/null
+++ b/tools/conversation_cache_isolation.py
@@ -0,0 +1,156 @@
+"""Private-engine image/steering cache isolation gate; dry-run unless --run.
+
+Synthetic image embeddings exercise GENI, image identity and M-RoPE without an
+image encoder. Synthetic nonzero control vectors exercise actual add/project
+kernels. This validates cache correctness, not vision or steering quality.
+"""
+import argparse
+import json
+from pathlib import Path
+import re
+import struct
+import sys
+import threading
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path[:0] = [str(ROOT), str(ROOT / 'tools')]
+from conversation_cache_parity import STATE_KEYS, engine_args, require
+from gguf_reader import GGUFFile
+from gguf_writer import GGUFWriter
+from serve.server import StrataEngine, child_env
+from serve.frontend import ChatTemplate
+import strata_tokenizer as ST
+import numpy as np
+
+
+def fixtures(output, width):
+ vector = np.sin(np.arange(width, dtype=np.float32) * .17)
+ vector *= .25 / np.linalg.norm(vector)
+ writer = GGUFWriter()
+ writer.add('general.architecture', 'controlvector')
+ writer.add('controlvector.model_hint', 'qwen4exp')
+ writer.add_f32('direction.1', vector)
+ writer.add_f32('direction.20', vector)
+ writer.write(output / 'control.gguf')
+ rows = np.sin(np.arange(4 * width, dtype=np.float32) * .013).reshape(4, width) * .2
+ for name, nx, ny, values in [('image-a', 2, 2, rows), ('image-b', 2, 2, -rows),
+ ('image-grid', 1, 4, rows)]:
+ with (output / (name + '.sve')).open('xb') as f:
+ f.write(struct.pack('<5i', 0x31455653, 4, nx, ny, width))
+ f.write(values.astype('<f4').tobytes())
+
+
+def verify(results, scenario):
+ baseline, candidate = results['baseline'], results['candidate']
+ expected = (['image-A', 'text-B', 'image-A-return', 'image-B', 'image-A-again',
+ 'grid-changed', 'image-A-final'] if scenario == 'image' else
+ ['off', 'on', 'text-B', 'off-return', 'on-return', 'off-again'])
+ for records in (baseline, candidate):
+ require([r['name'] for r in records] == expected, 'incomplete isolation sequence')
+ for before, after in zip(baseline, candidate):
+ require(len(before['ids']) == len(after['ids']) == 1, 'missing isolation output')
+ require(before['finish'] in ('length', 'stop') and after['finish'] in ('length', 'stop'),
+ 'isolation request did not finish normally')
+ require(before['ids'] == after['ids'], 'isolation output differs')
+ require(set(STATE_KEYS) <= before['state'].keys() and set(STATE_KEYS) <= after['state'].keys(),
+ 'incomplete isolation state')
+ require(before['state'] == after['state'], 'isolation main-model state differs')
+ for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'):
+ require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key],
+ f'isolation engine setting differs: {key}')
+ misses, hits = (([0, 1, 3, 5], [2, 4, 6]) if scenario == 'image' else ([0, 1, 2], [3, 4, 5]))
+ require(all(candidate[i]['reused'] == 0 for i in misses), 'incompatible identity reused state')
+ require(all(candidate[i]['reused'] > 0 for i in hits), 'compatible parked state was not restored')
+ changed = 3 if scenario == 'image' else 1
+ require(baseline[0]['state'] != baseline[changed]['state'], 'fixture did not change actual model state')
+ if scenario == 'image':
+ require(baseline[0]['state'] != baseline[5]['state'], 'grid fixture did not change M-RoPE state')
+ else:
+ require(results['engine_info']['candidate']['cvec'] != 0, 'control vector not loaded')
+
+
+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('--output', type=Path, required=True)
+ ap.add_argument('--scenario', choices=('image', 'add', 'project'), required=True)
+ ap.add_argument('--run', action='store_true')
+ args = ap.parse_args()
+ if not args.run:
+ print(f'Dry run: {args.scenario} isolation; no model loaded or files created.')
+ return
+ cfg = json.loads(args.config.read_text())
+ native = cfg['args'][cfg['args'].index('--native') + 1]
+ geometry = GGUFFile(native).metadata
+ 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()))
+ tpl = ChatTemplate(p / 'chat_template.jinja')
+ def encode(text):
+ return tok.encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False), parse_special=True)
+ image_tokens = '<|vision_start|>' + '<|image_pad|>' * 4 + '<|vision_end|>'
+ tail = '\n'.join(f'Record {i}: blue square and green triangle.' for i in range(64))
+ A = encode('Conversation A: ' + (image_tokens if args.scenario == 'image' else '') + '\n' + tail)
+ B = encode('Unrelated conversation B: name a color.\n' + tail)
+ args.output.mkdir(mode=0o700, parents=False, exist_ok=False)
+ fixtures(args.output, width)
+ env = child_env(cfg)
+ env['STRATA_STATE_HASH'] = '1'
+ results = {'engine_info': {}}
+ for label, budget in [('baseline', 0), ('candidate', 8192)]:
+ log = args.output / (label + '.log')
+ command = engine_args(cfg, budget, 1)
+ if args.scenario == 'image':
+ command += ['--vision']
+ else:
+ command += ['--control-vector', str(args.output / 'control.gguf'), '--cvec-mode', args.scenario]
+ engine = StrataEngine(str(args.engine.resolve()), command, cwd=cfg.get('cwd'), log=str(log), env=env)
+ records = []
+ results['engine_info'][label] = dict(engine.info)
+ def generate(name, ids, image=None, steering=True):
+ embeddings = str(args.output / (image + '.sve')) if image else None
+ out = [t for t in engine.generate(ids, 1, {'experimental_speed_projection': steering},
+ threading.Event(), embeddings=embeddings) if t is not None]
+ records.append({'name': name, 'ids': out, **engine.last})
+ try:
+ if args.scenario == 'image':
+ generate('image-A', A, 'image-a')
+ generate('text-B', B)
+ generate('image-A-return', A, 'image-a')
+ generate('image-B', A, 'image-b')
+ generate('image-A-again', A, 'image-a')
+ generate('grid-changed', A, 'image-grid')
+ generate('image-A-final', A, 'image-a')
+ else:
+ generate('off', A, steering=False)
+ generate('on', A)
+ generate('text-B', B)
+ generate('off-return', A, steering=False)
+ generate('on-return', A)
+ 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})
+ require(len(hashes) == len(records), 'missing isolation state hashes')
+ for record, state in zip(records, hashes):
+ record['state'] = state
+ results[label] = records
+ (args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
+ verify(results, args.scenario)
+ print(f'PASS: {args.scenario} identity isolation, output and main-model state parity')
+ print(f'Results: {args.output / "results.json"}')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/conversation_cache_parity.py b/tools/conversation_cache_parity.py
new file mode 100644
index 000000000..710baee8d
--- /dev/null
+++ b/tools/conversation_cache_parity.py
@@ -0,0 +1,219 @@
+"""Full-model A/B/A parity gate. Loads private engines sequentially, never uses an existing server.
+
+Dry-run by default. --run requires an available GPU/model-loading window.
+"""
+import argparse
+import json
+from pathlib import Path
+import re
+import sys
+import threading
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path[:0] = [str(ROOT), str(ROOT / 'tools')]
+from serve.server import StrataEngine, child_env
+from serve.frontend import ChatTemplate
+import strata_tokenizer as ST
+
+STATE_KEYS = ('L', 'gdn', 'ple', 'tail', 'dead', 'pooled', 'kv', 'ple_prev')
+
+def require(condition, message):
+ if not condition:
+ raise AssertionError(message)
+
+
+def engine_args(cfg, budget, spec):
+ # Native IQ packs require verifier capacity >= 2, even for one-token decode.
+ return list(cfg['args']) + [
+ '--conversation-cache-mib', str(budget), '--conversation-cache-slots', '4',
+ '--prompt-cache', '6', '--adapt-swaps', '0', '--spec', str(max(2, spec)),
+ '--mtp-max-t', str(spec), '--suffix-draft', '0', '--spec-min-p', '0']
+
+
+def verify_pressure(results, budget_mib, oversized=False):
+ """Require actual byte-pressure evidence, not just correct output on misses."""
+ baseline, candidate = results['baseline'], results['candidate']
+ names = ['A', 'B', 'C', 'A-again']
+ for records in (baseline, candidate):
+ require([r['name'] for r in records] == names, 'incomplete pressure sequence')
+ for before, after in zip(baseline, candidate):
+ require(len(before['ids']) == len(after['ids']) == 1, 'missing pressure output')
+ require(before['finish'] in ('length', 'stop') and after['finish'] in ('length', 'stop'),
+ 'pressure request did not finish normally')
+ require(before['reused'] == after['reused'] == 0, 'pressure did not force a cache miss')
+ require(before['ids'] == after['ids'], 'pressure output differs')
+ keys = set(STATE_KEYS)
+ require(keys <= before['state'].keys() and keys <= after['state'].keys(), 'missing pressure state')
+ require(before['state'] == after['state'], 'pressure state differs')
+ for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'):
+ require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key],
+ f'pressure engine setting differs: {key}')
+ info = results['engine_info']['candidate']
+ require(info['conversation_cache_mib'] == budget_mib and info['conversation_cache_slots'] == 4,
+ 'pressure cache configuration differs')
+ evidence = results['pressure']
+ parks = evidence['parks']
+ require(all(p['bytes'] <= budget_mib * 1024 * 1024 for p in parks), 'byte budget exceeded')
+ if oversized:
+ require(evidence['skips'] == 3 and not parks, 'oversized snapshots were not all skipped')
+ else:
+ require(evidence['skips'] == 0 and len(parks) == 3, 'snapshots must fit individually')
+ require(all(0 < p['parked'] < 4 for p in parks), 'slot pressure confounds byte-pressure test')
+ require(parks[-1]['evictions'] > 0, 'no byte-pressure eviction observed; reduce --cache-mib')
+
+
+def verify_results(results, prompt_tokens, spec):
+ """Fail closed on incomplete evidence, even under python -O."""
+ baseline, candidate = results['baseline'], results['candidate']
+ require([r['name'] for r in baseline] == ['A', 'A+'], 'incomplete baseline')
+ require([r['name'] for r in candidate] == ['A', 'B', 'A+', 'B-again', 'A+-checkpoint'], 'incomplete candidate')
+ state_keys = set(STATE_KEYS)
+ for record in baseline + candidate:
+ require(bool(record['ids']), 'missing generated tokens')
+ require(record['finish'] in ('length', 'stop'), 'request did not finish normally')
+ require(state_keys <= record['state'].keys(), 'incomplete state fingerprint')
+ require(len(baseline[0]['ids']) == len(candidate[0]['ids']) == 1, 'invalid initial A output length')
+ require(baseline[0]['ids'] == candidate[0]['ids'], 'initial A output differs')
+ require(candidate[2]['reused'] >= prompt_tokens, 'A was not restored after B')
+ require(candidate[4]['reused'] > 0, 'parked checkpoint was not restored')
+ for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'):
+ require(results['engine_info']['baseline'][key] == results['engine_info']['candidate'][key],
+ f'baseline/candidate engine setting differs: {key}')
+ for record in (candidate[2], candidate[4]):
+ require(record['ids'] == baseline[1]['ids'], 'restored continuation output differs')
+ if spec == 1:
+ require(record['state'] == baseline[1]['state'], 'restored main-model state differs')
+
+
+def verify_exchange(results, prompt_tokens, spec, budget_mib):
+ verify_results(results, prompt_tokens, spec)
+ require(results['engine_info']['candidate']['conversation_cache_mib'] == budget_mib,
+ 'exchange cache budget differs')
+ evidence = results['pressure']
+ require(evidence['skips'] == 2 and len(evidence['parks']) == 2,
+ 'expected two parks and two outgoing skips while an incoming snapshot is held')
+ require(all(p['parked'] == 1 and 0 < p['bytes'] <= budget_mib * 1024 * 1024
+ for p in evidence['parks']), 'invalid exchange snapshot budget')
+
+
+def verify_admission(results, budget_mib, floor_mib):
+ evidence = results['pressure']
+ require(evidence['memory_skips'] == 3 and evidence['skips'] == 0 and not evidence['parks'],
+ 'expected physical-memory denial, not oversized-budget fallback')
+ require(results['engine_info']['candidate']['conversation_cache_min_free_mib'] == floor_mib,
+ 'physical RAM floor differs')
+ # The same four cold requests must preserve output and complete state. Reuse
+ # the oversized gate's no-parking assertions after checking the actual cause.
+ equivalent = {**results, 'pressure': {**evidence, 'skips': evidence['memory_skips']}}
+ verify_pressure(equivalent, budget_mib, oversized=True)
+
+
+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('--output', type=Path, required=True, help='new private directory; existing paths refused')
+ ap.add_argument('--cache-mib', type=int, default=8192)
+ ap.add_argument('--paragraphs', type=int, default=128)
+ ap.add_argument('--scenario', choices=('reuse', 'pressure', 'oversized', 'exchange', 'admission'), default='reuse',
+ help='pressure requires snapshots fitting individually but not together; oversized requires none to fit')
+ ap.add_argument('--min-free-mib', type=int, default=2560,
+ help='physical RAM floor; for admission denial choose a value above available system RAM')
+ ap.add_argument('--spec', type=int, default=1, choices=range(1, 9),
+ help='decode window cap; 1 uses engine --spec 2 --mtp-max-t 1 for native IQ packs')
+ ap.add_argument('--run', action='store_true')
+ a = ap.parse_args()
+ if a.cache_mib <= 0 or a.paragraphs < 1 or not 0 <= a.min_free_mib <= (2**63 - 1) // (1024 * 1024):
+ ap.error('cache-mib/paragraphs must be positive and min-free-mib must fit the engine range')
+ if not a.run:
+ print(f'Dry run: {a.scenario}; paired baseline/candidate; fixed residency, greedy output.')
+ print('No model loaded. Use --run only with a separately available GPU/test window.')
+ return
+ cfg = 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()))
+ tpl = ChatTemplate(p / 'chat_template.jinja')
+ def encode(text):
+ return tok.encode(text, parse_special=True)
+ def prompt(label):
+ text = label + ': remember this list.\n' + '\n'.join(
+ f'Record {i}: blue square, green triangle, red circle.' for i in range(a.paragraphs))
+ return encode(tpl.render([{'role': 'user', 'content': text}], enable_thinking=False))
+ A, B, C = prompt('Conversation A'), prompt('Unrelated conversation B'), prompt('Distinct conversation C')
+ suffix = encode('<|im_end|>\n<|im_start|>user\nName a color from the list.<|im_end|>\n'
+ '<|im_start|>assistant\n<think>\n\n</think>\n\n')
+ a.output.mkdir(mode=0o700, parents=False, exist_ok=False)
+ env = child_env(cfg)
+ env['STRATA_STATE_HASH'] = '1'
+ results = {'engine_info': {}}
+ for label, budget in [('baseline', 0), ('candidate', a.cache_mib)]:
+ log = a.output / f'{label}.log'
+ args = engine_args(cfg, budget, a.spec)
+ args += ['--conversation-cache-min-free-mib', str(a.min_free_mib)]
+ engine = StrataEngine(str(a.engine.resolve()), args, cwd=cfg.get('cwd'), log=str(log), env=env)
+ results['engine_info'][label] = dict(engine.info)
+ records = []
+ def generate(ids, count, name):
+ out = [t for t in engine.generate(ids, count, {'temperature': 0}, threading.Event()) if t is not None]
+ records.append({'name': name, 'ids': out, **engine.last})
+ return out
+ try:
+ # One output token leaves exactly A's prompt as the live prefix,
+ # avoiding the pre-existing accepted-draft output-cap overshoot.
+ if a.scenario in ('pressure', 'oversized', 'admission'):
+ generate(A, 1, 'A')
+ generate(B, 1, 'B')
+ generate(C, 1, 'C')
+ generate(A, 1, 'A-again')
+ else:
+ head = generate(A, 1, 'A')
+ continuation = A + head + suffix
+ if budget:
+ generate(B, 1, 'B')
+ generate(continuation, 8, 'A+')
+ if budget:
+ generate(B, 1, 'B-again')
+ 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})
+ require(len(hashes) == len(records), 'missing state hashes')
+ for record, fingerprint in zip(records, hashes):
+ record['state'] = fingerprint
+ results[label] = records
+ if label == 'candidate' and a.scenario != 'reuse':
+ log_text = log.read_text()
+ parks = re.findall(r'conversation cache: parked \d+ tokens .*?parked=(\d+) bytes=(\d+) evictions=(\d+)', log_text)
+ results['pressure'] = {
+ 'parks': [dict(zip(('parked', 'bytes', 'evictions'), map(int, p))) for p in parks],
+ 'skips': log_text.count('conversation cache: skip parking (snapshot '),
+ 'memory_skips': log_text.count('conversation cache: skip parking (physical RAM admission;')}
+ (a.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
+ if a.scenario == 'admission':
+ verify_admission(results, a.cache_mib, a.min_free_mib)
+ print('PASS: physical-memory admission denial, output and byte-exact main-model state')
+ elif a.scenario == 'exchange':
+ verify_exchange(results, len(A), a.spec, a.cache_mib)
+ print('PASS: bounded incoming/outgoing exchange, A/B/A output and checkpoint reuse')
+ elif a.scenario == 'reuse':
+ verify_results(results, len(A), a.spec)
+ print('PASS: A/B/A output and checkpoint reuse' + (', byte-exact main-model state' if a.spec == 1 else ''))
+ else:
+ verify_pressure(results, a.cache_mib, a.scenario == 'oversized')
+ print(f'PASS: {a.scenario} fallback, output and byte-exact main-model state')
+ print(f'Results: {a.output / "results.json"}')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/conversation_cache_soak.py b/tools/conversation_cache_soak.py
new file mode 100644
index 000000000..ae910c00b
--- /dev/null
+++ b/tools/conversation_cache_soak.py
@@ -0,0 +1,176 @@
+"""Private-engine known-answer A/B/A soak; dry-run by default.
+
+Loads paired engines sequentially. Requires an exclusive model/GPU window, not
+an existing HTTP server. This is a synthetic cache gate, not a real-agent benchmark.
+"""
+import argparse
+import json
+from pathlib import Path
+import re
+import sys
+import threading
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path[:0] = [str(ROOT), str(ROOT / 'tools')]
+from conversation_cache_parity import STATE_KEYS, engine_args, require
+from serve.server import StrataEngine, child_env
+from serve.frontend import ChatTemplate
+import strata_tokenizer as ST
+
+
+def answer_text(text):
+ return text.replace('<|im_end|>', '').replace('<|endoftext|>', '').strip().casefold()
+
+
+def verify(results):
+ contexts, cycles = results['contexts'], results['cycles']
+ count = results['requested_cycles']
+ require(count >= 30 and len(cycles) == count, 'incomplete 30-cycle soak')
+ require(len(contexts) >= 3, 'need at least three context lengths')
+ require(len({c['prompt_tokens'] for c in contexts}) == len(contexts), 'context lengths are not distinct')
+ baseline, candidate = results['engine_info']['baseline'], results['engine_info']['candidate']
+ for key in ('expert_slots', 'kv', 'kv_resident', 'context', 'spec', 'mtp_max', 'lookup', 'cvec'):
+ require(baseline[key] == candidate[key], f'engine setting differs: {key}')
+ require(baseline['conversation_cache_mib'] == 0 and candidate['conversation_cache_mib'] > 0,
+ 'invalid baseline/candidate cache configuration')
+ lengths = [c['prompt_tokens'] for c in contexts]
+ require(candidate['kv_resident'] > 0 and max(lengths) > candidate['kv_resident'], 'no streamed-KV coverage')
+ require(max(lengths) >= .9 * candidate['context'], 'longest prompt is not near the context limit')
+ budget = candidate['conversation_cache_mib'] * 1024 * 1024
+ for c in contexts:
+ require(c['baseline']['ids'] and set(STATE_KEYS) <= c['baseline']['state'].keys(), 'incomplete baseline')
+ require(c['baseline']['finish'] in ('length', 'stop'), 'baseline did not finish normally')
+ require(answer_text(c['baseline']['text']) == c['expected'].casefold(), 'baseline known answer is wrong')
+ for i, record in enumerate(cycles):
+ require(record['cycle'] == i and record['context'] == i % len(contexts), 'missing or reordered cycle')
+ c = contexts[record['context']]
+ require(record['finish'] in ('length', 'stop') and record['ids'], 'soak request failed')
+ require(answer_text(record['text']) == c['expected'].casefold(), 'restored known answer is wrong')
+ require(record['ids'] == c['baseline']['ids'], 'continuation token parity failed')
+ require(record['reused'] >= c['prompt_tokens'], 'return did not restore the long prefix')
+ require(set(STATE_KEYS) <= record['state'].keys() and record['state'] == c['baseline']['state'],
+ 'restored main-model state differs')
+ require(0 <= record['cache_bytes'] <= budget, 'parked byte budget exceeded')
+ # Compare steady-state retained snapshot payload, not allocator RSS or VRAM.
+ # Sampled RSS is diagnostic: allocator high-water marks need not shrink,
+ # and request-end samples do not establish a transient peak bound.
+ for index in range(len(contexts)):
+ tail = [r['cache_bytes'] for r in cycles if r['context'] == index][-3:]
+ require(len(tail) == 3 and len(set(tail)) == 1, 'retained payload did not reach a stable plateau')
+
+
+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('--output', type=Path, required=True, help='new directory; existing paths refused')
+ ap.add_argument('--prompt-tokens', default='2048,40000,120000', help='three increasing approximate prompt lengths')
+ ap.add_argument('--cycles', type=int, default=30)
+ ap.add_argument('--cache-mib', type=int, default=8192)
+ ap.add_argument('--run', action='store_true')
+ args = ap.parse_args()
+ try:
+ lengths = [int(n) for n in args.prompt_tokens.split(',')]
+ except ValueError:
+ ap.error('prompt-tokens must contain three integers')
+ if len(lengths) != 3 or lengths != sorted(set(lengths)) or min(lengths) < 256 or args.cycles < 30 or args.cache_mib <= 0:
+ ap.error('need three distinct increasing lengths >= 256, cycles >= 30 and cache-mib > 0')
+ if not args.run:
+ print(f'Dry run: {args.cycles} known-answer A/B/A cycles; approximate lengths {lengths}.')
+ print('No model loaded or files created. Use --run only in an exclusive GPU test window.')
+ return
+ cfg = 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()))
+ template = ChatTemplate(path / 'chat_template.jinja')
+ def encode(text):
+ return tok.encode(text, parse_special=True)
+ def prompt(text):
+ return encode(template.render([{'role': 'user', 'content': text}], enable_thinking=False))
+ def long_prompt(target, secret, index):
+ paragraphs = max(1, target // 17)
+ for _ in range(6):
+ lines = [f'Record {i}: blue square, green triangle, red circle.' for i in range(paragraphs)]
+ lines[paragraphs // 3] = f'The secret access code for conversation {index} is {secret}.'
+ ids = prompt(f'Conversation {index}. Remember its secret access code for my next question.\n' + '\n'.join(lines))
+ delta = target - len(ids)
+ if abs(delta) < 64:
+ return ids
+ paragraphs = max(1, paragraphs + delta // 17)
+ return ids
+ secrets = ['MANGO', 'CEDAR', 'RAVEN']
+ prompts = [long_prompt(n, secret, i) for i, (n, secret) in enumerate(zip(lengths, secrets))]
+ suffix = encode('<|im_end|>\n<|im_start|>user\nWhat is this conversation\'s secret access code? '
+ 'Reply with only that one word, no punctuation.<|im_end|>\n'
+ '<|im_start|>assistant\n<think>\n\n</think>\n\n')
+ other = prompt('Unrelated worker conversation. Reply with HELLO and nothing else.')
+ args.output.mkdir(mode=0o700, parents=False, exist_ok=False)
+ env = child_env(cfg)
+ env['STRATA_STATE_HASH'] = '1'
+ results = {'requested_cycles': args.cycles, 'engine_info': {}, 'contexts': [], 'cycles': []}
+ heads, continuations = [], []
+ for label, budget in [('baseline', 0), ('candidate', args.cache_mib)]:
+ log = args.output / f'{label}.log'
+ engine = StrataEngine(str(args.engine.resolve()), engine_args(cfg, budget, 1),
+ cwd=cfg.get('cwd'), log=str(log), env=env)
+ results['engine_info'][label] = dict(engine.info)
+ hash_count = 0
+ def generate(ids, count):
+ nonlocal hash_count
+ output = [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]
+ 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}
+ occupancy = re.findall(r'parked=\d+ bytes=(\d+)', text)
+ rss = None
+ try:
+ match = re.search(r'^VmRSS:\s+(\d+) kB', Path(f'/proc/{engine.proc.pid}/status').read_text(), re.M)
+ if match:
+ rss = int(match[1]) * 1024
+ except OSError:
+ pass
+ return {'ids': output, 'text': tok.decode(output), **engine.last, 'state': state,
+ 'cache_bytes': int(occupancy[-1]) if occupancy else 0, 'sampled_rss_bytes': rss}
+ try:
+ require(max(map(len, prompts)) + len(suffix) + 64 < engine.max_context, 'test prompt exceeds context')
+ if label == 'baseline':
+ for i, ids in enumerate(prompts):
+ head = generate(ids, 1)
+ require(len(head['ids']) == 1, 'baseline initial output is missing')
+ heads.append(head['ids'])
+ continuations.append(ids + head['ids'] + suffix)
+ answer = generate(continuations[-1], 16)
+ results['contexts'].append({'expected': secrets[i], 'prompt_tokens': len(ids), 'baseline': answer})
+ require(answer_text(answer['text']) == secrets[i].casefold(), 'baseline known answer is wrong')
+ print(f'baseline length={len(ids)} answer={answer_text(answer["text"])}', flush=True)
+ else:
+ primed = set()
+ for cycle in range(args.cycles):
+ index = cycle % len(prompts)
+ if index not in primed:
+ head = generate(prompts[index], 1)
+ require(head['ids'] == heads[index], 'initial candidate output differs')
+ primed.add(index)
+ generate(other, 1)
+ answer = generate(continuations[index], 16)
+ results['cycles'].append({'cycle': cycle, 'context': index, **answer})
+ print(f'cycle={cycle + 1}/{args.cycles} length={len(prompts[index])} '
+ f'reused={answer["reused"]} answer={answer_text(answer["text"])}', flush=True)
+ finally:
+ engine.close()
+ # Keep partial evidence on failure; verify rejects incomplete runs.
+ (args.output / 'results.json').write_text(json.dumps(results, indent=2) + '\n')
+ verify(results)
+ print('PASS: 30+ known-answer A/B/A cycles, streamed/near-limit KV, exact state/output, stable retained payload')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/test_conversation_cache_http_smoke.py b/tools/test_conversation_cache_http_smoke.py
new file mode 100644
index 000000000..fd0a79d2d
--- /dev/null
+++ b/tools/test_conversation_cache_http_smoke.py
@@ -0,0 +1,71 @@
+"""Offline tests of HTTP smoke-test orchestration and safety defaults."""
+from collections import OrderedDict
+import io
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import Mock
+
+from tools.conversation_cache_http_smoke import run
+
+
+class FakeClient:
+ def __init__(self):
+ self.history = []
+ self.cache = OrderedDict()
+
+ def metrics(self):
+ return {'live': {'state': 'idle', 'queued': 0},
+ 'engine': {'model': 'fake', 'conversation_cache_slots': 4, 'conversation_cache_mib': 8192},
+ 'requests': self.history[::-1]}
+
+ def request(self, model, content, stream=False, count=8):
+ reused = 100 if content in self.cache else 0
+ self.cache.pop(content, None)
+ self.cache[content] = True
+ while len(self.cache) > 5: # active plus four parked entries
+ self.cache.popitem(last=False)
+ self.history.append({'time': len(self.history) + 1, 'reused': reused, 'output_tokens': 5,
+ 'finish': 'disconnect' if stream else 'stop'})
+ data = {'choices': [{'delta': {'content': '1'}}]} if stream else {
+ 'choices': [{'message': {'role': 'assistant', 'content': 'blue'}}]}
+ return io.BytesIO((('data: ' if stream else '') + json.dumps(data) + '\n').encode())
+
+
+class HttpSmoke(unittest.TestCase):
+ def test_orchestration_offline(self):
+ result = run(FakeClient())
+ self.assertEqual(len(result['records']), 12)
+ self.assertEqual(result['records'][-1]['name'], 'cancelled-A-restored')
+ self.assertGreater(result['records'][-1]['reused'], 0)
+
+ def test_busy_server_receives_no_requests(self):
+ client = Mock()
+ client.metrics.return_value = {'live': {'state': 'generating', 'queued': 0}}
+ with self.assertRaisesRegex(RuntimeError, 'busy'):
+ run(client)
+ client.request.assert_not_called()
+
+ def test_disabled_cache_receives_no_requests(self):
+ client = Mock()
+ client.metrics.return_value = {'live': {'state': 'idle', 'queued': 0}, 'engine': {}}
+ with self.assertRaisesRegex(RuntimeError, 'enabled cache'):
+ run(client)
+ client.request.assert_not_called()
+
+ def test_dry_run_does_not_connect_or_create_output(self):
+ with tempfile.TemporaryDirectory(prefix='strata-http-dry-') as directory:
+ output = Path(directory) / 'not-created.json'
+ result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_http_smoke.py')),
+ '--url', 'invalid://not-a-server', '--output', str(output)],
+ capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('No network traffic', result.stdout)
+ self.assertFalse(output.exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/test_conversation_cache_isolation.py b/tools/test_conversation_cache_isolation.py
new file mode 100644
index 000000000..7205d4d4d
--- /dev/null
+++ b/tools/test_conversation_cache_isolation.py
@@ -0,0 +1,82 @@
+"""Offline checks for image/steering isolation evidence and generated fixtures."""
+import copy
+from pathlib import Path
+import struct
+import subprocess
+import sys
+import tempfile
+import unittest
+
+from tools.conversation_cache_isolation import STATE_KEYS, fixtures, verify
+from tools.gguf_reader import GGUFFile
+
+
+def evidence(scenario):
+ image = scenario == 'image'
+ names = (['image-A', 'text-B', 'image-A-return', 'image-B', 'image-A-again', 'grid-changed', 'image-A-final']
+ if image else ['off', 'on', 'text-B', 'off-return', 'on-return', 'off-again'])
+ hits = [2, 4, 6] if image else [3, 4, 5]
+ records = [{'name': name, 'ids': [123], 'finish': 'length', 'reused': 0,
+ 'state': {k: str(i) for k in STATE_KEYS}} for i, name in enumerate(names)]
+ candidate = copy.deepcopy(records)
+ for i in hits:
+ candidate[i]['reused'] = 100
+ info = dict(expert_slots=8000, kv='int8', kv_resident=32768, context=262144,
+ spec=2, mtp_max=1, lookup=0, cvec=0 if image else 'add:1-47')
+ return {'baseline': records, 'candidate': candidate,
+ 'engine_info': {'baseline': dict(info), 'candidate': dict(info)}}
+
+
+class IsolationGate(unittest.TestCase):
+ def test_complete_evidence(self):
+ for scenario in ('image', 'add', 'project'):
+ verify(evidence(scenario), scenario)
+
+ def test_incomplete_or_wrong_evidence_rejected(self):
+ for scenario in ('image', 'add'):
+ cases = {
+ 'incompatible reuse': lambda d: d['candidate'][1].update(reused=5),
+ 'no parked hit': lambda d: d['candidate'][-1].update(reused=0),
+ 'state mismatch': lambda d: d['candidate'][-1]['state'].update(gdn='ffff'),
+ 'missing state': lambda d: d['candidate'][-1]['state'].clear(),
+ 'empty output': lambda d: d['candidate'][-1]['ids'].clear(),
+ 'missing request': lambda d: d['candidate'].pop(),
+ 'different residency': lambda d: d['engine_info']['candidate'].update(expert_slots=1),
+ }
+ for name, mutate in cases.items():
+ with self.subTest(scenario=scenario, case=name):
+ data = evidence(scenario)
+ mutate(data)
+ with self.assertRaises(AssertionError):
+ verify(data, scenario)
+
+ def test_generated_fixtures(self):
+ with tempfile.TemporaryDirectory(prefix='strata-isolation-') as directory:
+ p = Path(directory)
+ fixtures(p, 2560)
+ cv = GGUFFile(p / 'control.gguf')
+ self.assertEqual(cv.metadata['general.architecture'], 'controlvector')
+ self.assertEqual([t.name for t in cv.tensors], ['direction.1', 'direction.20'])
+ self.assertTrue(all(t.elements == 2560 for t in cv.tensors))
+ a, b, grid = [(p / (name + '.sve')).read_bytes() for name in ('image-a', 'image-b', 'image-grid')]
+ self.assertEqual(struct.unpack('<5i', a[:20]), (0x31455653, 4, 2, 2, 2560))
+ self.assertEqual(len(a), 20 + 4 * 2560 * 4)
+ self.assertEqual(a[:20], b[:20])
+ self.assertNotEqual(a[20:], b[20:])
+ self.assertNotEqual(a[:20], grid[:20])
+ self.assertEqual(a[20:], grid[20:])
+
+ def test_dry_run_does_not_read_missing_config(self):
+ with tempfile.TemporaryDirectory(prefix='strata-isolation-dry-') as directory:
+ p = Path(directory)
+ result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_isolation.py')),
+ '--config', str(p / 'missing.json'), '--engine', str(p / 'missing'),
+ '--output', str(p / 'not-created'), '--scenario', 'image'],
+ capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('no model loaded', result.stdout)
+ self.assertFalse((p / 'not-created').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/test_conversation_cache_parity.py b/tools/test_conversation_cache_parity.py
new file mode 100644
index 000000000..15c9cc409
--- /dev/null
+++ b/tools/test_conversation_cache_parity.py
@@ -0,0 +1,154 @@
+"""CPU-only checks that the model-level gate cannot pass with incomplete evidence."""
+import copy
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+from tools.conversation_cache_parity import STATE_KEYS, engine_args, verify_admission, verify_exchange, verify_pressure, verify_results
+
+
+def fixture():
+ state = {k: '1234' for k in STATE_KEYS}
+ def record(name):
+ return {'name': name, 'ids': [123], 'finish': 'length', 'state': dict(state), 'reused': 100}
+ info = {'expert_slots': 100, 'kv': 'int8', 'kv_resident': 32768, 'context': 65536,
+ 'spec': 1, 'mtp_max': 0, 'lookup': 0, 'cvec': '0'}
+ return {'baseline': [record('A'), record('A+')],
+ 'candidate': [record(n) for n in ('A', 'B', 'A+', 'B-again', 'A+-checkpoint')],
+ 'engine_info': {'baseline': dict(info), 'candidate': dict(info)}}
+
+
+class ParityGate(unittest.TestCase):
+ def test_native_iq_single_token_arguments(self):
+ cfg = {'args': ['--spec', '4', '--mtp-max-t', '4']}
+ args = engine_args(cfg, 400, 1)
+ values = {args[i]: args[i + 1] for i in range(0, len(args), 2)}
+ self.assertEqual(values['--spec'], '2')
+ self.assertEqual(values['--mtp-max-t'], '1')
+ self.assertEqual(values['--suffix-draft'], '0')
+ self.assertEqual(values['--adapt-swaps'], '0')
+ self.assertEqual(values['--conversation-cache-mib'], '400')
+ self.assertEqual(cfg['args'], ['--spec', '4', '--mtp-max-t', '4'])
+
+ def test_complete_evidence(self):
+ verify_results(fixture(), 100, 1)
+
+ def test_incomplete_or_different_evidence_fails(self):
+ cases = {
+ 'missing state': lambda d: d['candidate'][2]['state'].clear(),
+ 'missing spare key': lambda d: d['candidate'][2]['state'].pop('dead'),
+ 'empty output': lambda d: d['candidate'][2]['ids'].clear(),
+ 'missing request': lambda d: d['candidate'].pop(),
+ 'state differs': lambda d: d['candidate'][2]['state'].update(gdn='ffff'),
+ 'output differs': lambda d: d['candidate'][2].update(ids=[456]),
+ 'live not restored': lambda d: d['candidate'][2].update(reused=0),
+ 'checkpoint not restored': lambda d: d['candidate'][4].update(reused=0),
+ 'different residency': lambda d: d['engine_info']['candidate'].update(expert_slots=99),
+ 'cancellation': lambda d: d['candidate'][2].update(finish='cancel'),
+ 'initial output differs': lambda d: d['candidate'][0].update(ids=[789]),
+ }
+ for name, mutate in cases.items():
+ with self.subTest(name=name):
+ data = copy.deepcopy(fixture())
+ mutate(data)
+ with self.assertRaises(AssertionError):
+ verify_results(data, 100, 1)
+
+ def test_speculative_gate_still_requires_output_parity(self):
+ data = fixture()
+ data['candidate'][2]['state']['gdn'] = 'ffff'
+ verify_results(data, 100, 4)
+ data['candidate'][2]['ids'] = [456]
+ with self.assertRaises(AssertionError):
+ verify_results(data, 100, 4)
+
+ def test_dry_run_does_not_read_config_or_start_engine(self):
+ with tempfile.TemporaryDirectory(prefix='strata-parity-dry-') as directory:
+ output = Path(directory) / 'not-created'
+ result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_parity.py')),
+ '--config', str(Path(directory) / 'missing.json'),
+ '--engine', str(Path(directory) / 'missing-engine'), '--output', str(output)],
+ capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('No model loaded', result.stdout)
+ self.assertFalse(output.exists())
+
+
+def pressure_fixture():
+ data = fixture()
+ record = data['baseline'][0]
+ for key in ('baseline', 'candidate'):
+ data[key] = [{**copy.deepcopy(record), 'name': name, 'reused': 0}
+ for name in ('A', 'B', 'C', 'A-again')]
+ data['engine_info']['candidate'].update(conversation_cache_mib=400, conversation_cache_slots=4)
+ data['pressure'] = {'skips': 0, 'parks': [
+ {'parked': 1, 'bytes': 266000000, 'evictions': n} for n in range(3)]}
+ return data
+
+
+class PressureGate(unittest.TestCase):
+ def test_physical_memory_admission_evidence(self):
+ data = pressure_fixture()
+ data['pressure'] = {'memory_skips': 3, 'skips': 0, 'parks': []}
+ data['engine_info']['candidate']['conversation_cache_min_free_mib'] = 999999
+ verify_admission(data, 400, 999999)
+ for mutate in (
+ lambda d: d['pressure'].update(memory_skips=0, skips=3),
+ lambda d: d['pressure'].update(memory_skips=2),
+ lambda d: d['engine_info']['candidate'].update(conversation_cache_min_free_mib=2560),
+ lambda d: d['candidate'][3].update(reused=10),
+ ):
+ broken = copy.deepcopy(data)
+ mutate(broken)
+ with self.assertRaises(AssertionError):
+ verify_admission(broken, 400, 999999)
+
+ def test_incoming_exchange_evidence(self):
+ data = fixture()
+ data['engine_info']['candidate']['conversation_cache_mib'] = 400
+ data['pressure'] = {'skips': 2, 'parks': [
+ {'parked': 1, 'bytes': 266000000, 'evictions': 0},
+ {'parked': 1, 'bytes': 384000000, 'evictions': 0}]}
+ verify_exchange(data, 100, 1, 400)
+ for skips in (0, 1, 3):
+ data['pressure']['skips'] = skips
+ with self.assertRaises(AssertionError):
+ verify_exchange(data, 100, 1, 400)
+
+ def test_byte_eviction_evidence(self):
+ verify_pressure(pressure_fixture(), 400)
+
+ def test_oversized_evidence(self):
+ data = pressure_fixture()
+ data['engine_info']['candidate']['conversation_cache_mib'] = 1
+ data['pressure'] = {'skips': 3, 'parks': []}
+ verify_pressure(data, 1, oversized=True)
+ data['pressure']['skips'] = 2
+ with self.assertRaises(AssertionError):
+ verify_pressure(data, 1, oversized=True)
+
+ def test_insufficient_pressure_evidence_rejected(self):
+ cases = {
+ 'slot pressure': lambda d: d['pressure']['parks'][1].update(parked=4),
+ 'no eviction': lambda d: d['pressure']['parks'][-1].update(evictions=0),
+ 'too large individually': lambda d: d['pressure'].update(skips=1),
+ 'missing snapshots': lambda d: d['pressure']['parks'].pop(),
+ 'over budget': lambda d: d['pressure']['parks'][0].update(bytes=500 * 1024 * 1024),
+ 'cache hit': lambda d: d['candidate'][-1].update(reused=100),
+ 'state mismatch': lambda d: d['candidate'][-1]['state'].update(gdn='ffff'),
+ 'empty state': lambda d: d['candidate'][-1]['state'].clear(),
+ 'wrong output': lambda d: d['candidate'][-1].update(ids=[456]),
+ 'wrong budget': lambda d: d['engine_info']['candidate'].update(conversation_cache_mib=8192),
+ }
+ for name, mutate in cases.items():
+ with self.subTest(name=name):
+ data = pressure_fixture()
+ mutate(data)
+ with self.assertRaises(AssertionError):
+ verify_pressure(data, 400)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tools/test_conversation_cache_soak.py b/tools/test_conversation_cache_soak.py
new file mode 100644
index 000000000..7d815890b
--- /dev/null
+++ b/tools/test_conversation_cache_soak.py
@@ -0,0 +1,73 @@
+"""Offline checks for the synthetic known-answer soak acceptance gate."""
+import copy
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+from tools.conversation_cache_soak import STATE_KEYS, answer_text, verify
+
+
+def evidence():
+ lengths = [2048, 40000, 120000]
+ def record(index):
+ return {'ids': [100 + index], 'text': ['MANGO', 'CEDAR', 'RAVEN'][index],
+ 'finish': 'stop', 'reused': lengths[index], 'cache_bytes': 100000,
+ 'state': {key: str(index) for key in STATE_KEYS}}
+ info = dict(expert_slots=8000, kv='int8', kv_resident=32768, context=131072,
+ spec=2, mtp_max=1, lookup=0, cvec=0, conversation_cache_mib=8192)
+ return {'requested_cycles': 30, 'engine_info': {'baseline': {**info, 'conversation_cache_mib': 0}, 'candidate': info},
+ 'contexts': [{'expected': record(i)['text'], 'prompt_tokens': lengths[i], 'baseline': record(i)} for i in range(3)],
+ 'cycles': [{'cycle': i, 'context': i % 3, **record(i % 3)} for i in range(30)]}
+
+
+class SoakGate(unittest.TestCase):
+ def test_complete_evidence(self):
+ verify(evidence())
+
+ def test_bad_or_incomplete_evidence(self):
+ cases = {
+ 'missing cycle': lambda r: r['cycles'].pop(),
+ 'too few requested': lambda r: r.update(requested_cycles=29),
+ 'missing context': lambda r: r['contexts'].pop(),
+ 'duplicate lengths': lambda r: r['contexts'][0].update(prompt_tokens=40000),
+ 'reordered cycle': lambda r: r['cycles'][2].update(context=0),
+ 'no streaming': lambda r: r['engine_info']['candidate'].update(kv_resident=0),
+ 'not near context limit': lambda r: (r['engine_info']['baseline'].update(context=262144),
+ r['engine_info']['candidate'].update(context=262144)),
+ 'different GPU residency': lambda r: r['engine_info']['candidate'].update(expert_slots=7999),
+ 'no restore': lambda r: r['cycles'][9].update(reused=0),
+ 'wrong answer despite parity': lambda r: (r['contexts'][0]['baseline'].update(text='WRONG'),
+ r['cycles'][0].update(text='WRONG')),
+ 'wrong token output': lambda r: r['cycles'][5].update(ids=[999]),
+ 'missing spare fingerprint': lambda r: r['cycles'][4]['state'].pop('dead'),
+ 'different state': lambda r: r['cycles'][4]['state'].update(gdn='bad'),
+ 'cancelled': lambda r: r['cycles'][3].update(finish='cancel'),
+ 'over budget': lambda r: r['cycles'][3].update(cache_bytes=2**40),
+ 'retained allocation grows': lambda r: r['cycles'][-1].update(cache_bytes=200000),
+ }
+ for name, mutate in cases.items():
+ with self.subTest(name=name):
+ results = copy.deepcopy(evidence())
+ mutate(results)
+ with self.assertRaises(AssertionError):
+ verify(results)
+
+ def test_answer_normalization_does_not_hide_extra_text(self):
+ self.assertEqual(answer_text(' MANGO<|im_end|>\n'), 'mango')
+ self.assertNotEqual(answer_text('The code is MANGO.'), 'mango')
+
+ def test_dry_run_never_reads_config_or_starts_model(self):
+ with tempfile.TemporaryDirectory(prefix='strata-soak-dry-') as directory:
+ root = Path(directory)
+ result = subprocess.run([sys.executable, str(Path(__file__).with_name('conversation_cache_soak.py')),
+ '--config', str(root / 'missing.json'), '--engine', str(root / 'missing'),
+ '--output', str(root / 'output')], capture_output=True, text=True, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('No model loaded', result.stdout)
+ self.assertFalse((root / 'output').exists())
+
+
+if __name__ == '__main__':
+ unittest.main()