[PR #4226] [Engine] add persistent disk conversation caching with compact snapshots #4961

Open
opened 2026-11-07 16:31:37 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/4226
Author: @G0-0000
Created: 10/26/2026
Status: 🔄 Open

Base: main ← Head: feat/conversation-disk-cache-20261026


📝 Commits (10+)

  • 31653e6 [Engine] add persistent disk conversation caching
  • bf0b658 [Engine] add independent conversation cache read threshold
  • ab2e38e [Engine] make disk delta compaction configurable
  • 48d2a6c [Engine] add state references to prefix disk snapshots
  • f985d12 [Engine] add RHT+INT16 codec for GDN disk snapshots
  • 8a80bc7 [Engine] add background state writes for disk-only saves
  • aba5873 [Engine] fix two extraction leftovers so the disk cache branch builds
  • eefd149 [Engine] 新增磁盘缓存重算门控(opt-in)
  • d461e36 [Engine] route the spill cache's file access through a ConversationStore
  • f59547a [Engine] bound the spill name search so a refusing store cannot loop forever

📊 Changes

33 files changed (+14895 additions, -317 deletions)

View changed files

📝 CMakeLists.txt (+26 -1)
📝 docs/DETAILS.md (+80 -1)
📝 include/strata/core/conversation_cache.hpp (+185 -24)
📝 include/strata/core/conversation_file.hpp (+225 -11)
📝 include/strata/core/conversation_snapshot.hpp (+60 -3)
➕ include/strata/core/conversation_spill.hpp (+340 -0)
➕ include/strata/core/conversation_store.hpp (+71 -0)
➕ include/strata/core/rht_state_codec.hpp (+314 -0)
➕ include/strata/program/startup_info.hpp (+62 -0)
📝 metal/CMakeLists.txt (+1 -0)
📝 metal/src/engine/missing.cpp (+2 -0)
📝 serve/server.py (+56 -2)
📝 serve/test_monitor.py (+44 -0)
📝 serve/web/app.js (+28 -1)
📝 serve/web/index.html (+4 -0)
➕ src/core/conversation_accept_config_test.cpp (+167 -0)
📝 src/core/conversation_cache_test.cpp (+43 -0)
➕ src/core/conversation_digest_test.cpp (+278 -0)
📝 src/core/conversation_file.cpp (+2030 -150)
📝 src/core/conversation_file_test.cpp (+2543 -3)

...and 13 more files

📄 Description

Problem and result

Parked conversations currently depend on a RAM budget. An eviction or an engine restart can make a later request read a long prompt again, and a machine that spends most of its RAM on the model may not be able to park the conversations that would benefit most.

This pull request proposes one self-contained, opt-in disk conversation-cache design. It does not wait for another disk-cache PR: the prerequisite work of #1271, #1269 and #1480 is integrated here, so the branch builds and runs on its own (see Provenance). It adds persistence across restarts, a disk-only mode that does not park a whole conversation in RAM, incremental writes, smaller state representations, and an optional background state-write path that shortens the time a session switch is blocked.

The main pieces are:

  • Disk tier and streaming restore. --conversation-cache-spill-dir DIR keeps RAM-cache evictions as ordinary session files with bounded metadata sidecars. A two-pass restore validates the file and moves K/V through bounded blocks instead of materializing the whole file in RAM.
  • Disk-only conversations and prefixes. --conversation-cache-disk-only saves outgoing conversations directly from their pools and restores them without using the RAM conversation-cache budget. Persistent prefix entries reuse shared openings across conversations and restarts. The monitor reports disk-only saves, restores, usage, and refusals.
  • Read/write token thresholds. --conversation-cache-min-tokens WRITE[,READ] keeps short side requests from writing or looking up cached conversations. A single value retains the existing WRITE-only meaning; READ defaults to zero.
  • Delta records and bounded chains. --conversation-cache-disk-delta appends changed K/V and running state instead of rewriting every base file. --conversation-cache-disk-delta-percent N controls compaction. Manifest, sidecar, ledger, and LRU updates preserve the committed chain on write failure or interruption.
  • Lossless prefix references. --conversation-cache-disk-state-ref avoids storing a second copy when all five running-state arrays in a prefix checkpoint are byte-identical to the live state. REF is local to the same file and is lossless; it does not alias the restored RAM copies.
  • Optional RHT+INT16 for ordinary base/delta state. --conversation-cache-disk-state-codec-rht encodes recurrent GDN rows with a normalized Hadamard transform, per-row INT16 values, and FP32 scales. Runtime state and convolution state remain FP32; convolution is stored RAW. Prefix snapshots and non-finite/unsupported states do not use RHT.
  • Background state writes. --conversation-cache-disk-background-state uses a v3 K/V-first layout for ordinary disk-only base/delta saves. Once the K/V sources have been consumed, the running session can continue while one owned background task encodes state and writes the file through two bounded 16 MiB buffers. Publication happens later at a safe cache boundary.
  • Recompute gate for cross-configuration reuse (opt-in). A spill directory may hold files saved under an older engine configuration (an upgrade, a settings change). With --conversation-cache-disk-recompute-gate, the cache reads a per-directory ledger and indexes a same-model file saved under another configuration only when both its batch record and its entry record passed an independent recomputation check. Approved entries are restored read-only under their original identity; no delta is appended to them. strata-session-digest and the offline tools/cache_verify.py produce and verify the ledger. With the gate off, nothing is read and foreign files stay unindexed.

Recompute gate for cross-configuration reuse

A spill directory keeps a session file written under another engine configuration (an upgrade, a settings change) but never indexes it, because the engine version and the resolved model/configuration are part of the cache identity. Until now the only recovery was to clear the directory. The eighth commit adds an opt-in gate that lets such a file be reused when it has been shown to reproduce the same state under the current build.

What the engine does with the gate on (--conversation-cache-disk-recompute-gate, default off):

  • On open() it also reads <dir>/.strata-cache-gate. A batch is a source (model + config) to target (model + config + engine build) approval; an entry row names one file (stem, base bytes, live token count) and the engine rechecks all three.
  • A file is indexed only when its own row and its batch both pass for exactly this identity and this engine build. A foreign model is never approved. A missing, unreadable, truncated, edited or checksum-mismatched ledger approves nothing, and the same-identity cache keeps working as before.
  • A gate-approved entry is read-only: reserve_delta and spill_delta refuse it, so no delta record is ever appended to a file whose base came from another configuration.
  • A hit that rewrites the .meta keeps the file's original identity.

The offline verifier (tools/cache_verify.py):

  • Scans <stem>.sess + <stem>.meta pairs and groups the files of the target model by source identity.
  • Picks the smallest eligible base of each group (no images, no delta chain, decodable token ids) and recomputes exactly its prompt with the current engine: <engine> [config args] --tokens-file IDS --max-new 1 --greedy --session-out FRESH.
  • Compares format-independent digests from strata-session-digest: K/V always; the token digest (and the state digest) only when the old sidecar holds no checkpoint, because a fresh export is live-only; an RHT-coded state is lossy and is never compared.
  • On a pass writes one batch line plus an entry row for every eligible file of that source; on a fail writes the batch and no rows. It only ever reads cache files, and writes the ledger atomically (temporary beside it, fsync, rename). A malformed ledger starts empty (fail closed).
  • It starts a second engine against the same GPU, so it is offline only: stop the server first. There is no online mode.

New command-line surface:

  • strata-session-digest --file PATH --model FP --config FP prints version= tokens= kv= state= state_exact= state_ref= state_rht= for one base session file, with no model and no GPU.
  • generate ... --session-out PATH (requires --max-new 1) exports a session whose contents are exactly the prompt, which is what the verifier recomputes.

#3891 asks for an automatic disk-backed conversation cache with a size cap and auto-eviction, configured in the run config, for subagent workloads on low-RAM machines. #3485 records measurements for a disk tier and is where the roadmap scope was raised. This pull request implements that request as one self-contained design.

The maintainers have not agreed the scope of this integration yet. The draft is here to ask for that agreement and for the backend and hardware coverage listed under Validation.

#1937 is a separate disk-tier design by xrip (--conversation-disk-*). It shares no code with this branch and neither depends on the other; #1090 lists the designs to choose from, and this one is offered for that choice.

Approach and compatibility

All disk-cache modes and codecs are opt-in. The existing RAM cache, slot SAVE/RESTORE, and default v1 file layout remain in place. The streaming restore uses the existing session format. REF/RHT use versioned descriptors in v2 files; background state writes use v3 only when explicitly enabled. The reader accepts v1, v2, and v3, including mixed-version delta chains. Existing golden tests cover the default formats; the final PR-head validation section below records the checks actually rerun on this branch.

Only ordinary disk-only base/delta saves use the background path. Prefix saves, slot SAVE/RESTORE, RAM-history parking, and RAM-eviction spills keep their previous formats and behavior. There is no whole-K/V RAM copy or K/V copy-on-write scheme. At most one background save is unfinished; cache lookups, destructive operations, prefix/slot operations, and shutdown first join and publish it.

A delta failure after source release does not reread the now-active K/V to fabricate a base snapshot: the old committed chain is kept and a later save can retry. A v3 apply pass fully decodes during the read pass, then consumes the later state section hash-only while applying K/V. The trailing hash and end marker protect that section just as they protect K/V. Corruption found after K/V has been applied follows the existing fail-stop path rather than continuing from partial state.

Cache identity still includes the engine version and resolved model/configuration. An upgrade can therefore leave old files on disk but not indexed or counted in the disk budget. Older binaries do not understand the newer file versions; rollback compatibility is limited. REF/RHT feature switches themselves are not part of the identity.

The disk-only paths retain the existing limits: single GPU, without --batch, --peer-device, or layer split.

This is a rebased and cleaned integration, with the original work attributed in the commits:

  • #1271, Aníbal Muñoz Calero: spill directory, head 4af468f6b.
  • #1269, pspranger-throw: streaming restore, head d258f1892.
  • #1480, Jim Routh: disk-only mode and persistent prefixes, head 3d5b97b84.
  • Delta records and sidecar LRU work by Emanon: 09d83375d and 1bac6f24c, originally on top of the #1480 branch.
  • The READ/WRITE threshold work also incorporates the approach from #3615, so the cache policy is self-contained here.
  • The REF and RHT+INT16 codecs were first proposed in #4086; it is closed in favour of this branch, where both are carried.
  • The RHT+INT16 approach is based on jundot/omlx, specifically omlx/cache/boundary_snapshot_store.py. The implementation here is independent; the transform sign and normalization conventions are documented in the codec.

These references record provenance; none is a merge prerequisite for this branch. The ported authors have not reviewed this integration.

Measurements from the local implementation

The following are measurements from the identified local builds, which carry the same cache implementation. The rebased head was compiled and its host tests were run separately; the GPU runs below were not repeated on the head (see Validation). Unless stated otherwise, the environment was Linux, CUDA 12.9 / sm_70, a Tesla V100-SXM2-32GB, Qwen3.8-Flash-Next UD-Q4_K_XL with INT8 K/V, and NVMe storage. The model runs used single, sequential requests.

Disk space and state fidelity

Case Observed result Scope
REF prefix file, local build 0.1.48.1.14 Measured v2 file: 160,160,728 B. The equivalent v1 size is 278,223,720 B by exact format arithmetic, a saving of 118,062,992 B (112.59 MiB). The v2 file was measured; the v1 baseline is derived from the validated layout, not a second measured file. A same-version restart restored 2,443 prefix tokens and read 51 new tokens.
RHT GDN state, local build 0.1.48.1.15 One complete GDN state copy, including RAW convolution: 117,669,888 B logical -> 61,931,520 B stored, a 47.37% reduction. This is a state-copy saving, not a whole-cache-file percentage. The observed base .sess was 218,849,020 B and the delta .dlog was 125,250,924 B. A same-version restart restored the base+delta chain (6,191 cached tokens plus 7 new tokens).
Offline RHT comparison on real cache state Across five recurrent-state copies / 141,557,760 FP32 values, relative L2 error was 1.91295e-5 for RHT+INT16 versus 2.05572e-4 for FP16. State-fidelity evidence only, not a generation-quality A/B. The codec-size arithmetic is 566,231,040 B FP32 -> 287,539,200 B INT16 + FP32 scales (49.21875%), excluding metadata, alignment, and convolution.

REF and RHT apply to different state/cache cases; their percentages must not be added into a single whole-cache saving claim.

Save blocking and restore time

Two interleaved OFF/ON rounds on local build 0.1.51.18 compared the same binary with background state writes disabled/enabled:

  • Four base-save pairs gave a mean synchronous blocking time of 932.6 ms OFF versus 261.2 ms ON until the K/V sources were released, a 72.0% reduction in request-blocking time.
  • The mean complete ON save still took 1,437.4 ms. This moves work out of the request-blocking section; it does not eliminate the work or prove a lower total save time.
  • That build also had a v3 restore regression: the OFF/v2 restore mean was 1,306.1 ms, versus 2,992.2 ms for the initial ON/v3 path. This was investigated and fixed before the .19 measurements below; it is not presented as a benefit of the initial implementation.

Local build 0.1.51.19 removed the duplicate v3 state decoding in the apply pass:

Restore case Result
Initial v3, clean single-file samples around 222 MiB 2,405.9–2,719.4 ms
v2 reference, median of four samples 1,311.8 ms
.19, two base-only 222 MiB restores 958.0–959.4 ms
.19, clean 342 MiB base+delta restore 3,406.1 ms (1,913.9 ms read pass; about 1.49 s of delta replay/non-read-pass work)
.19, after that chain compacted to one 223 MiB file 995.8 ms

The .19 targeted run also observed K/V-source release at 230.0/257.6 ms for delta saves and 298.5 ms for a base save. The save path itself was not changed by the restore fix.

These are small samples from the named local builds, not universal performance claims. In particular, a delta chain still has replay cost; the single-file result must not be substituted for the clean base+delta result. The .19 run recorded API-side prompt_ms, but did not rerun a matched interleaved end-to-end TTFT and generation-throughput comparison. No final throughput or whole-process RSS improvement is claimed.

Validation

The rebased head eefd1499 (8 commits on 46c152a13, v0.2.7.1) was compiled and its host tests were run for this pull request; the GPU runs were made on the fork builds named in each line, which carry the same cache implementation. Exact commands, revisions and results follow, with the three lists kept apart.

Passed:

  • Rebased head eefd1499, Linux, CUDA 12.9, sm_70, Release, Ninja. Configured with -DSTRATA_ENABLE_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON -DSTRATA_BUILD_TESTS=ON -DSTRATA_GGML_DIR=<llama.cpp checkout>: 313/313 targets linked, exit 0.

  • Rebased head, conversation test build (-DSTRATA_BUILD_CONVERSATION_TESTS=ON), ctest: 10/10 passed, including conversation_file_test, conversation_spill_test, conversation_digest_test, conversation_accept_config_test and rht_state_codec_test.

  • Rebased head, full ctest: 188/207 passed. The 19 failures are not this change: 15 CUDA tests could not take the device (the production server holds the only GPU), 3 fail on the clean 46c152a13 baseline too (pool_tasks_test, pool_cores_test, isa_guard_check, reproduced there), and ple_parity lacks its model fixture.

  • Rebased head, python3 -m unittest tests/terminal/test_cache_verify.py: 51/51 OK (the venv has no pytest).

  • Recompute gate, Tesla V100-SXM2-32GB, 2026-10-28. A real old prefix file written by engine 0.1.51.19 was rejected as kv_mismatch against 0.1.52.20, a true semantic difference the gate isolates; two recomputations of the same configuration gave identical tokens, K/V and state; a file that differed only in max_context (131072 to 65536) passed tools/cache_verify.py and was indexed, and the engine logged 1 batches, 1 approved entries before READY.

  • 0.1.51.18 (71fd72fa), 12 host CTest, 41.64 s. ctest --test-dir build-test -R '^(conversation_cache_test|conversation_file_test|conversation_spill_test|conversation_memory_test|conversation_snapshot_test|conversation_validation_test|conversation_split_failure_test|session_save_reclaim_test|rht_state_codec_test|startup_info_test|vma_alloc_test|numa_pool_test)$': 100% tests passed, 0 tests failed out of 12 (conversation_file_test 38.80 s; every other test 1.40 s or less).

  • 0.1.51.18, real model on one Tesla V100-SXM2-32GB, Qwen3.8-Flash-Next UD-Q4_K_XL, INT8 K/V, NVMe, single sequential requests. The engine ran from serve/server.py --engine strata --config <test config> --host 127.0.0.1 --port 8090:

    • OFF round: a v2 base save and restore and a delta append; continuing a 7,139-token prompt reported 7,086 cached tokens.
    • ON round: ten requests, all HTTP 200; v3 base saves of 7,125 / 7,123 / 14,123 tokens (222 / 222 / 324 MiB); delta saves of 7,143 / 14,143 / 7,179 tokens (119 MiB); the configured delta threshold compacted a chain into a new file; restores of 2,964.2, 3,019.0, 7,682.2, 7,676.3, 3,231.2, 2,995.9 and 3,002.6 ms; an orderly shutdown completed the pending delta save.
    • Restart and mixed chains: one v2 base followed by a v3 delta restored across a restart (7,122 cached tokens); the A/B/C chain restored after a restart (A 7,140, C 14,104 cached tokens).
    • Failure paths: with the spill directory read-only, all 8 committed files stayed byte-identical (sha256) and the chain restored later (7,158 tokens); SIGKILL during a compaction save left no temporary file and the committed chain restored (14,122 tokens in 12,180.2 ms).
    • Regression round without the disk tier: RAM-history restore (7,122 tokens in 35.9 ms), slot SAVE (7,179 tokens, 345,780,740 bytes) and RESTORE (7,179 tokens, 2,164.2 ms), and v1 session headers for the parked conversations.
  • 0.1.51.19 (2eda9f01). Full CUDA build (518 steps) and ctest 5/5 (conversation_file_test, conversation_spill_test, conversation_cache_test, conversation_snapshot_test, session_save_reclaim_test). Same-version restores of 958.0 / 959.4 ms for a 222 MiB base-only file and 995.8 ms for the compacted 223 MiB file, against a 1,311.8 ms v2 median and 2,405.9-2,719.4 ms for the pre-fix v3 path.

  • Deployment. 0.1.51.19 was installed on a production box after those runs; the new background-state flag stays off in that configuration.

Failed:

  • 0.1.51.19, clean 342 MiB base+delta restore: 3,406.1 ms, above the 2.3 s threshold of that test (read pass 1,913.9 ms; about 1.49 s is delta replay and other non-read-pass work). Kept as a failure: the 995.8 ms figure is the same chain after compaction and does not replace it.
  • 0.1.51.19 did not index files written by 0.1.51.18 (3 spill file(s) ... belong to another model/config identity). The engine version is part of the cache identity, so this is the existing policy and not a regression; no cross-version compatibility is claimed.
  • Regression round, fourth sub-item: no prefix-saved line appeared, recorded as not observed (that configuration did not set --conversation-cache-disk-state-ref).
  • ON-side internal replay: one request that should have matched returned cached=0 with no disk hit; the cause was not established. The response, engine log and server log were kept.

Not run:

  • HIP, SYCL, Metal, Windows and macOS builds. Only Linux CUDA 12.9 / sm_70 was built and tested.
  • Real-model execution on the rebased head itself: the GPU runs above were made on the fork builds. No GPU was used for the head build.
  • A matched interleaved end-to-end TTFT and generation-throughput run, and a controlled whole-process RSS comparison.
  • A generation-quality A/B for RHT.
  • serve/test_monitor.py and the GPU runs were not rerun on the new head; the only GPU is held by the production server.

The two failing checks on this pull request are outside this change. metal-link fails in metal/src/mtl_rt.mm (MTLGPUFamilyMetal4 and mathMode are not in the Xcode 15.4 SDK), and the Minimal serving runtime job fails in serve/test_lifeline.py (the watcher case, #3590). Both reproduce on main and on unrelated pull requests, and neither file is touched here.

Limits

  • Compilation and hardware execution are separate checks. No SYCL integration or cross-backend support is claimed from the shared host-side file code.
  • No generation-quality A/B has established that RHT preserves output quality. RHT is lossy and remains a separate opt-in switch.
  • No matched .19 interleaved end-to-end TTFT/generation benchmark or controlled whole-process RSS comparison has been run. Background work can overlap the next request, so state-buffer arithmetic is not an RSS guarantee.
  • A separate cross-build byte-for-byte comparison of every default-off path has not been run. Existing format golden tests do not by themselves prove that broader claim.
  • The recompute gate is an offline verifier. There is no online asynchronous dual-engine check; one GPU and one RAM budget do not allow it. Its ledger is a cache, not an authority: if it is damaged or missing the gate closes and foreign files stay unindexed. RHT state is lossy, so a gated comparison covers K/V and tokens only (a file with checkpoints compares K/V only).

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/4226 **Author:** [@G0-0000](https://github.com/G0-0000) **Created:** 10/26/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `feat/conversation-disk-cache-20261026` --- ### 📝 Commits (10+) - [`31653e6`](https://github.com/Niko1221/Strata/commit/31653e6059f282bb8cc02923da181022fccb74c5) [Engine] add persistent disk conversation caching - [`bf0b658`](https://github.com/Niko1221/Strata/commit/bf0b658521e1f64436249a5a2664837db3a44108) [Engine] add independent conversation cache read threshold - [`ab2e38e`](https://github.com/Niko1221/Strata/commit/ab2e38e36b32e98ea7bb91b718219667cacc69e5) [Engine] make disk delta compaction configurable - [`48d2a6c`](https://github.com/Niko1221/Strata/commit/48d2a6ca1153faf1390e01fa735f5eb37b17a750) [Engine] add state references to prefix disk snapshots - [`f985d12`](https://github.com/Niko1221/Strata/commit/f985d120a182002aa18a711b053ce85b35b40a4f) [Engine] add RHT+INT16 codec for GDN disk snapshots - [`8a80bc7`](https://github.com/Niko1221/Strata/commit/8a80bc700682c85c7b1d468a05af9db52d234d57) [Engine] add background state writes for disk-only saves - [`aba5873`](https://github.com/Niko1221/Strata/commit/aba58730acd59dcb1dac626fe6ed4d9e9b67f37a) [Engine] fix two extraction leftovers so the disk cache branch builds - [`eefd149`](https://github.com/Niko1221/Strata/commit/eefd149981ebf2bf5c0640e1e45c9ff574bc4ce7) [Engine] 新增磁盘缓存重算门控(opt-in) - [`d461e36`](https://github.com/Niko1221/Strata/commit/d461e3647a3e89c9e0ba9e18e9df9e4a30ac3dc7) [Engine] route the spill cache's file access through a ConversationStore - [`f59547a`](https://github.com/Niko1221/Strata/commit/f59547a0ce64858e8843edf30157535a5712f6c0) [Engine] bound the spill name search so a refusing store cannot loop forever ### 📊 Changes **33 files changed** (+14895 additions, -317 deletions) <details> <summary>View changed files</summary> 📝 `CMakeLists.txt` (+26 -1) 📝 `docs/DETAILS.md` (+80 -1) 📝 `include/strata/core/conversation_cache.hpp` (+185 -24) 📝 `include/strata/core/conversation_file.hpp` (+225 -11) 📝 `include/strata/core/conversation_snapshot.hpp` (+60 -3) ➕ `include/strata/core/conversation_spill.hpp` (+340 -0) ➕ `include/strata/core/conversation_store.hpp` (+71 -0) ➕ `include/strata/core/rht_state_codec.hpp` (+314 -0) ➕ `include/strata/program/startup_info.hpp` (+62 -0) 📝 `metal/CMakeLists.txt` (+1 -0) 📝 `metal/src/engine/missing.cpp` (+2 -0) 📝 `serve/server.py` (+56 -2) 📝 `serve/test_monitor.py` (+44 -0) 📝 `serve/web/app.js` (+28 -1) 📝 `serve/web/index.html` (+4 -0) ➕ `src/core/conversation_accept_config_test.cpp` (+167 -0) 📝 `src/core/conversation_cache_test.cpp` (+43 -0) ➕ `src/core/conversation_digest_test.cpp` (+278 -0) 📝 `src/core/conversation_file.cpp` (+2030 -150) 📝 `src/core/conversation_file_test.cpp` (+2543 -3) _...and 13 more files_ </details> ### 📄 Description ## Problem and result Parked conversations currently depend on a RAM budget. An eviction or an engine restart can make a later request read a long prompt again, and a machine that spends most of its RAM on the model may not be able to park the conversations that would benefit most. This pull request proposes one self-contained, opt-in disk conversation-cache design. It does not wait for another disk-cache PR: the prerequisite work of #1271, #1269 and #1480 is integrated here, so the branch builds and runs on its own (see Provenance). It adds persistence across restarts, a disk-only mode that does not park a whole conversation in RAM, incremental writes, smaller state representations, and an optional background state-write path that shortens the time a session switch is blocked. The main pieces are: - **Disk tier and streaming restore.** `--conversation-cache-spill-dir DIR` keeps RAM-cache evictions as ordinary session files with bounded metadata sidecars. A two-pass restore validates the file and moves K/V through bounded blocks instead of materializing the whole file in RAM. - **Disk-only conversations and prefixes.** `--conversation-cache-disk-only` saves outgoing conversations directly from their pools and restores them without using the RAM conversation-cache budget. Persistent prefix entries reuse shared openings across conversations and restarts. The monitor reports disk-only saves, restores, usage, and refusals. - **Read/write token thresholds.** `--conversation-cache-min-tokens WRITE[,READ]` keeps short side requests from writing or looking up cached conversations. A single value retains the existing WRITE-only meaning; READ defaults to zero. - **Delta records and bounded chains.** `--conversation-cache-disk-delta` appends changed K/V and running state instead of rewriting every base file. `--conversation-cache-disk-delta-percent N` controls compaction. Manifest, sidecar, ledger, and LRU updates preserve the committed chain on write failure or interruption. - **Lossless prefix references.** `--conversation-cache-disk-state-ref` avoids storing a second copy when all five running-state arrays in a prefix checkpoint are byte-identical to the live state. REF is local to the same file and is lossless; it does not alias the restored RAM copies. - **Optional RHT+INT16 for ordinary base/delta state.** `--conversation-cache-disk-state-codec-rht` encodes recurrent GDN rows with a normalized Hadamard transform, per-row INT16 values, and FP32 scales. Runtime state and convolution state remain FP32; convolution is stored RAW. Prefix snapshots and non-finite/unsupported states do not use RHT. - **Background state writes.** `--conversation-cache-disk-background-state` uses a v3 K/V-first layout for ordinary disk-only base/delta saves. Once the K/V sources have been consumed, the running session can continue while one owned background task encodes state and writes the file through two bounded 16 MiB buffers. Publication happens later at a safe cache boundary. - **Recompute gate for cross-configuration reuse (opt-in).** A spill directory may hold files saved under an older engine configuration (an upgrade, a settings change). With `--conversation-cache-disk-recompute-gate`, the cache reads a per-directory ledger and indexes a same-model file saved under another configuration only when both its batch record and its entry record passed an independent recomputation check. Approved entries are restored read-only under their original identity; no delta is appended to them. `strata-session-digest` and the offline `tools/cache_verify.py` produce and verify the ledger. With the gate off, nothing is read and foreign files stay unindexed. ## Recompute gate for cross-configuration reuse A spill directory keeps a session file written under another engine configuration (an upgrade, a settings change) but never indexes it, because the engine version and the resolved model/configuration are part of the cache identity. Until now the only recovery was to clear the directory. The eighth commit adds an opt-in gate that lets such a file be reused when it has been shown to reproduce the same state under the current build. **What the engine does with the gate on** (`--conversation-cache-disk-recompute-gate`, default off): - On `open()` it also reads `<dir>/.strata-cache-gate`. A batch is a source (model + config) to target (model + config + engine build) approval; an entry row names one file (stem, base bytes, live token count) and the engine rechecks all three. - A file is indexed only when its own row and its batch both pass for exactly this identity and this engine build. A foreign model is never approved. A missing, unreadable, truncated, edited or checksum-mismatched ledger approves nothing, and the same-identity cache keeps working as before. - A gate-approved entry is read-only: `reserve_delta` and `spill_delta` refuse it, so no delta record is ever appended to a file whose base came from another configuration. - A hit that rewrites the `.meta` keeps the file's original identity. **The offline verifier** (`tools/cache_verify.py`): - Scans `<stem>.sess` + `<stem>.meta` pairs and groups the files of the target model by source identity. - Picks the smallest eligible base of each group (no images, no delta chain, decodable token ids) and recomputes exactly its prompt with the current engine: `<engine> [config args] --tokens-file IDS --max-new 1 --greedy --session-out FRESH`. - Compares format-independent digests from `strata-session-digest`: K/V always; the token digest (and the state digest) only when the old sidecar holds no checkpoint, because a fresh export is live-only; an RHT-coded state is lossy and is never compared. - On a pass writes one batch line plus an entry row for every eligible file of that source; on a fail writes the batch and no rows. It only ever reads cache files, and writes the ledger atomically (temporary beside it, fsync, rename). A malformed ledger starts empty (fail closed). - It starts a second engine against the same GPU, so it is offline only: stop the server first. There is no online mode. **New command-line surface:** - `strata-session-digest --file PATH --model FP --config FP` prints `version= tokens= kv= state= state_exact= state_ref= state_rht=` for one base session file, with no model and no GPU. - `generate ... --session-out PATH` (requires `--max-new 1`) exports a session whose contents are exactly the prompt, which is what the verifier recomputes. ## Related discussion #3891 asks for an automatic disk-backed conversation cache with a size cap and auto-eviction, configured in the run config, for subagent workloads on low-RAM machines. #3485 records measurements for a disk tier and is where the roadmap scope was raised. This pull request implements that request as one self-contained design. The maintainers have not agreed the scope of this integration yet. The draft is here to ask for that agreement and for the backend and hardware coverage listed under Validation. [#1937](https://github.com/Niko1221/Strata/pull/1937) is a separate disk-tier design by xrip (`--conversation-disk-*`). It shares no code with this branch and neither depends on the other; #1090 lists the designs to choose from, and this one is offered for that choice. ## Approach and compatibility All disk-cache modes and codecs are opt-in. The existing RAM cache, slot SAVE/RESTORE, and default v1 file layout remain in place. The streaming restore uses the existing session format. REF/RHT use versioned descriptors in v2 files; background state writes use v3 only when explicitly enabled. The reader accepts v1, v2, and v3, including mixed-version delta chains. Existing golden tests cover the default formats; the final PR-head validation section below records the checks actually rerun on this branch. Only ordinary disk-only base/delta saves use the background path. Prefix saves, slot SAVE/RESTORE, RAM-history parking, and RAM-eviction spills keep their previous formats and behavior. There is no whole-K/V RAM copy or K/V copy-on-write scheme. At most one background save is unfinished; cache lookups, destructive operations, prefix/slot operations, and shutdown first join and publish it. A delta failure after source release does not reread the now-active K/V to fabricate a base snapshot: the old committed chain is kept and a later save can retry. A v3 apply pass fully decodes during the read pass, then consumes the later state section hash-only while applying K/V. The trailing hash and end marker protect that section just as they protect K/V. Corruption found after K/V has been applied follows the existing fail-stop path rather than continuing from partial state. Cache identity still includes the engine version and resolved model/configuration. An upgrade can therefore leave old files on disk but not indexed or counted in the disk budget. Older binaries do not understand the newer file versions; rollback compatibility is limited. REF/RHT feature switches themselves are not part of the identity. The disk-only paths retain the existing limits: single GPU, without `--batch`, `--peer-device`, or layer split. ## Provenance and related work This is a rebased and cleaned integration, with the original work attributed in the commits: - [#1271](https://github.com/Niko1221/Strata/pull/1271), Aníbal Muñoz Calero: spill directory, head `4af468f6b`. - [#1269](https://github.com/Niko1221/Strata/pull/1269), pspranger-throw: streaming restore, head `d258f1892`. - [#1480](https://github.com/Niko1221/Strata/pull/1480), Jim Routh: disk-only mode and persistent prefixes, head `3d5b97b84`. - Delta records and sidecar LRU work by Emanon: `09d83375d` and `1bac6f24c`, originally on top of the #1480 branch. - The READ/WRITE threshold work also incorporates the approach from [#3615](https://github.com/Niko1221/Strata/pull/3615), so the cache policy is self-contained here. - The REF and RHT+INT16 codecs were first proposed in [#4086](https://github.com/Niko1221/Strata/pull/4086); it is closed in favour of this branch, where both are carried. - The RHT+INT16 approach is based on [jundot/omlx](https://github.com/jundot/omlx), specifically `omlx/cache/boundary_snapshot_store.py`. The implementation here is independent; the transform sign and normalization conventions are documented in the codec. These references record provenance; none is a merge prerequisite for this branch. The ported authors have not reviewed this integration. ## Measurements from the local implementation The following are measurements from the identified local builds, which carry the same cache implementation. The rebased head was compiled and its host tests were run separately; the GPU runs below were not repeated on the head (see Validation). Unless stated otherwise, the environment was Linux, CUDA 12.9 / `sm_70`, a Tesla V100-SXM2-32GB, Qwen3.8-Flash-Next UD-Q4_K_XL with INT8 K/V, and NVMe storage. The model runs used single, sequential requests. ### Disk space and state fidelity | Case | Observed result | Scope | |---|---|---| | REF prefix file, local build `0.1.48.1.14` | Measured v2 file: **160,160,728 B**. The equivalent v1 size is **278,223,720 B** by exact format arithmetic, a saving of **118,062,992 B (112.59 MiB)**. | The v2 file was measured; the v1 baseline is derived from the validated layout, not a second measured file. A same-version restart restored 2,443 prefix tokens and read 51 new tokens. | | RHT GDN state, local build `0.1.48.1.15` | One complete GDN state copy, including RAW convolution: **117,669,888 B logical -> 61,931,520 B stored**, a **47.37%** reduction. | This is a state-copy saving, not a whole-cache-file percentage. The observed base `.sess` was 218,849,020 B and the delta `.dlog` was 125,250,924 B. A same-version restart restored the base+delta chain (6,191 cached tokens plus 7 new tokens). | | Offline RHT comparison on real cache state | Across five recurrent-state copies / 141,557,760 FP32 values, relative L2 error was **1.91295e-5** for RHT+INT16 versus **2.05572e-4** for FP16. | State-fidelity evidence only, not a generation-quality A/B. The codec-size arithmetic is 566,231,040 B FP32 -> 287,539,200 B INT16 + FP32 scales (**49.21875%**), excluding metadata, alignment, and convolution. | REF and RHT apply to different state/cache cases; their percentages must not be added into a single whole-cache saving claim. ### Save blocking and restore time Two interleaved OFF/ON rounds on local build `0.1.51.18` compared the same binary with background state writes disabled/enabled: - Four base-save pairs gave a mean synchronous blocking time of **932.6 ms OFF** versus **261.2 ms ON** until the K/V sources were released, a **72.0%** reduction in request-blocking time. - The mean complete ON save still took **1,437.4 ms**. This moves work out of the request-blocking section; it does not eliminate the work or prove a lower total save time. - That build also had a v3 restore regression: the OFF/v2 restore mean was **1,306.1 ms**, versus **2,992.2 ms** for the initial ON/v3 path. This was investigated and fixed before the `.19` measurements below; it is not presented as a benefit of the initial implementation. Local build `0.1.51.19` removed the duplicate v3 state decoding in the apply pass: | Restore case | Result | |---|---:| | Initial v3, clean single-file samples around 222 MiB | 2,405.9–2,719.4 ms | | v2 reference, median of four samples | 1,311.8 ms | | `.19`, two base-only 222 MiB restores | **958.0–959.4 ms** | | `.19`, clean 342 MiB base+delta restore | **3,406.1 ms** (1,913.9 ms read pass; about 1.49 s of delta replay/non-read-pass work) | | `.19`, after that chain compacted to one 223 MiB file | **995.8 ms** | The `.19` targeted run also observed K/V-source release at 230.0/257.6 ms for delta saves and 298.5 ms for a base save. The save path itself was not changed by the restore fix. These are small samples from the named local builds, not universal performance claims. In particular, a delta chain still has replay cost; the single-file result must not be substituted for the clean base+delta result. The `.19` run recorded API-side `prompt_ms`, but did not rerun a matched interleaved end-to-end TTFT and generation-throughput comparison. No final throughput or whole-process RSS improvement is claimed. ## Validation The rebased head `eefd1499` (8 commits on `46c152a13`, v0.2.7.1) was compiled and its host tests were run for this pull request; the GPU runs were made on the fork builds named in each line, which carry the same cache implementation. Exact commands, revisions and results follow, with the three lists kept apart. **Passed:** - **Rebased head `eefd1499`, Linux, CUDA 12.9, `sm_70`, Release, Ninja.** Configured with `-DSTRATA_ENABLE_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=70 -DSTRATA_EXPERIMENTAL_SM60=ON -DSTRATA_BUILD_TESTS=ON -DSTRATA_GGML_DIR=<llama.cpp checkout>`: 313/313 targets linked, exit 0. - **Rebased head, conversation test build (`-DSTRATA_BUILD_CONVERSATION_TESTS=ON`), `ctest`:** 10/10 passed, including `conversation_file_test`, `conversation_spill_test`, `conversation_digest_test`, `conversation_accept_config_test` and `rht_state_codec_test`. - **Rebased head, full `ctest`:** 188/207 passed. The 19 failures are not this change: 15 CUDA tests could not take the device (the production server holds the only GPU), 3 fail on the clean `46c152a13` baseline too (`pool_tasks_test`, `pool_cores_test`, `isa_guard_check`, reproduced there), and `ple_parity` lacks its model fixture. - **Rebased head, `python3 -m unittest tests/terminal/test_cache_verify.py`:** 51/51 OK (the venv has no pytest). - **Recompute gate, Tesla V100-SXM2-32GB, 2026-10-28.** A real old prefix file written by engine 0.1.51.19 was rejected as `kv_mismatch` against 0.1.52.20, a true semantic difference the gate isolates; two recomputations of the same configuration gave identical tokens, K/V and state; a file that differed only in `max_context` (131072 to 65536) passed `tools/cache_verify.py` and was indexed, and the engine logged `1 batches, 1 approved entries` before READY. - **`0.1.51.18` (`71fd72fa`), 12 host CTest, 41.64 s.** `ctest --test-dir build-test -R '^(conversation_cache_test|conversation_file_test|conversation_spill_test|conversation_memory_test|conversation_snapshot_test|conversation_validation_test|conversation_split_failure_test|session_save_reclaim_test|rht_state_codec_test|startup_info_test|vma_alloc_test|numa_pool_test)$'`: `100% tests passed, 0 tests failed out of 12` (`conversation_file_test` 38.80 s; every other test 1.40 s or less). - **`0.1.51.18`, real model on one Tesla V100-SXM2-32GB, Qwen3.8-Flash-Next UD-Q4_K_XL, INT8 K/V, NVMe, single sequential requests.** The engine ran from `serve/server.py --engine strata --config <test config> --host 127.0.0.1 --port 8090`: - OFF round: a v2 base save and restore and a delta append; continuing a 7,139-token prompt reported 7,086 cached tokens. - ON round: ten requests, all HTTP 200; v3 base saves of 7,125 / 7,123 / 14,123 tokens (222 / 222 / 324 MiB); delta saves of 7,143 / 14,143 / 7,179 tokens (119 MiB); the configured delta threshold compacted a chain into a new file; restores of 2,964.2, 3,019.0, 7,682.2, 7,676.3, 3,231.2, 2,995.9 and 3,002.6 ms; an orderly shutdown completed the pending delta save. - Restart and mixed chains: one v2 base followed by a v3 delta restored across a restart (7,122 cached tokens); the A/B/C chain restored after a restart (A 7,140, C 14,104 cached tokens). - Failure paths: with the spill directory read-only, all 8 committed files stayed byte-identical (sha256) and the chain restored later (7,158 tokens); `SIGKILL` during a compaction save left no temporary file and the committed chain restored (14,122 tokens in 12,180.2 ms). - Regression round without the disk tier: RAM-history restore (7,122 tokens in 35.9 ms), slot SAVE (7,179 tokens, 345,780,740 bytes) and RESTORE (7,179 tokens, 2,164.2 ms), and v1 session headers for the parked conversations. - **`0.1.51.19` (`2eda9f01`).** Full CUDA build (518 steps) and `ctest` 5/5 (`conversation_file_test`, `conversation_spill_test`, `conversation_cache_test`, `conversation_snapshot_test`, `session_save_reclaim_test`). Same-version restores of 958.0 / 959.4 ms for a 222 MiB base-only file and 995.8 ms for the compacted 223 MiB file, against a 1,311.8 ms v2 median and 2,405.9-2,719.4 ms for the pre-fix v3 path. - **Deployment.** `0.1.51.19` was installed on a production box after those runs; the new background-state flag stays off in that configuration. **Failed:** - **`0.1.51.19`, clean 342 MiB base+delta restore: 3,406.1 ms**, above the 2.3 s threshold of that test (read pass 1,913.9 ms; about 1.49 s is delta replay and other non-read-pass work). Kept as a failure: the 995.8 ms figure is the same chain after compaction and does not replace it. - **`0.1.51.19` did not index files written by `0.1.51.18`** (`3 spill file(s) ... belong to another model/config identity`). The engine version is part of the cache identity, so this is the existing policy and not a regression; no cross-version compatibility is claimed. - **Regression round, fourth sub-item:** no `prefix-saved` line appeared, recorded as not observed (that configuration did not set `--conversation-cache-disk-state-ref`). - **ON-side internal replay:** one request that should have matched returned `cached=0` with no disk hit; the cause was not established. The response, engine log and server log were kept. **Not run:** - HIP, SYCL, Metal, Windows and macOS builds. Only Linux CUDA 12.9 / `sm_70` was built and tested. - Real-model execution on the rebased head itself: the GPU runs above were made on the fork builds. No GPU was used for the head build. - A matched interleaved end-to-end TTFT and generation-throughput run, and a controlled whole-process RSS comparison. - A generation-quality A/B for RHT. - `serve/test_monitor.py` and the GPU runs were not rerun on the new head; the only GPU is held by the production server. The two failing checks on this pull request are outside this change. `metal-link` fails in `metal/src/mtl_rt.mm` (`MTLGPUFamilyMetal4` and `mathMode` are not in the Xcode 15.4 SDK), and the Minimal serving runtime job fails in `serve/test_lifeline.py` (the watcher case, #3590). Both reproduce on `main` and on unrelated pull requests, and neither file is touched here. ## Limits - Compilation and hardware execution are separate checks. No SYCL integration or cross-backend support is claimed from the shared host-side file code. - No generation-quality A/B has established that RHT preserves output quality. RHT is lossy and remains a separate opt-in switch. - No matched `.19` interleaved end-to-end TTFT/generation benchmark or controlled whole-process RSS comparison has been run. Background work can overlap the next request, so state-buffer arithmetic is not an RSS guarantee. - A separate cross-build byte-for-byte comparison of every default-off path has not been run. Existing format golden tests do not by themselves prove that broader claim. - The recompute gate is an offline verifier. There is no online asynchronous dual-engine check; one GPU and one RAM budget do not allow it. Its ledger is a cache, not an authority: if it is damaged or missing the gate closes and foreign files stay unindexed. RHT state is lossy, so a gated comparison covers K/V and tokens only (a file with checkpoints compares K/V only). --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#4961
No description provided.