mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #4226] [Engine] add persistent disk conversation caching with compact snapshots #4961
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4961
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 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 cachingbf0b658[Engine] add independent conversation cache read thresholdab2e38e[Engine] make disk delta compaction configurable48d2a6c[Engine] add state references to prefix disk snapshotsf985d12[Engine] add RHT+INT16 codec for GDN disk snapshots8a80bc7[Engine] add background state writes for disk-only savesaba5873[Engine] fix two extraction leftovers so the disk cache branch buildseefd149[Engine] 新增磁盘缓存重算门控(opt-in)d461e36[Engine] route the spill cache's file access through a ConversationStoref59547a[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:
--conversation-cache-spill-dir DIRkeeps 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.--conversation-cache-disk-onlysaves 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.--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.--conversation-cache-disk-deltaappends changed K/V and running state instead of rewriting every base file.--conversation-cache-disk-delta-percent Ncontrols compaction. Manifest, sidecar, ledger, and LRU updates preserve the committed chain on write failure or interruption.--conversation-cache-disk-state-refavoids 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.--conversation-cache-disk-state-codec-rhtencodes 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.--conversation-cache-disk-background-stateuses 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.--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-digestand the offlinetools/cache_verify.pyproduce 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):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.reserve_deltaandspill_deltarefuse it, so no delta record is ever appended to a file whose base came from another configuration..metakeeps the file's original identity.The offline verifier (
tools/cache_verify.py):<stem>.sess+<stem>.metapairs and groups the files of the target model by source identity.<engine> [config args] --tokens-file IDS --max-new 1 --greedy --session-out FRESH.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.New command-line surface:
strata-session-digest --file PATH --model FP --config FPprintsversion= 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 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:
4af468f6b.d258f1892.3d5b97b84.09d83375dand1bac6f24c, originally on top of the #1480 branch.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
0.1.48.1.140.1.48.1.15.sesswas 218,849,020 B and the delta.dlogwas 125,250,924 B. A same-version restart restored the base+delta chain (6,191 cached tokens plus 7 new tokens).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.18compared the same binary with background state writes disabled/enabled:.19measurements below; it is not presented as a benefit of the initial implementation.Local build
0.1.51.19removed the duplicate v3 state decoding in the apply pass:.19, two base-only 222 MiB restores.19, clean 342 MiB base+delta restore.19, after that chain compacted to one 223 MiB fileThe
.19targeted 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
.19run recorded API-sideprompt_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 on46c152a13, 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, includingconversation_file_test,conversation_spill_test,conversation_digest_test,conversation_accept_config_testandrht_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 clean46c152a13baseline too (pool_tasks_test,pool_cores_test,isa_guard_check, reproduced there), andple_paritylacks 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_mismatchagainst 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 inmax_context(131072 to 65536) passedtools/cache_verify.pyand was indexed, and the engine logged1 batches, 1 approved entriesbefore 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_test38.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 fromserve/server.py --engine strata --config <test config> --host 127.0.0.1 --port 8090:SIGKILLduring a compaction save left no temporary file and the committed chain restored (14,122 tokens in 12,180.2 ms).0.1.51.19(2eda9f01). Full CUDA build (518 steps) andctest5/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.19was 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.19did not index files written by0.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.prefix-savedline appeared, recorded as not observed (that configuration did not set--conversation-cache-disk-state-ref).cached=0with no disk hit; the cause was not established. The response, engine log and server log were kept.Not run:
sm_70was built and tested.serve/test_monitor.pyand 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-linkfails inmetal/src/mtl_rt.mm(MTLGPUFamilyMetal4andmathModeare not in the Xcode 15.4 SDK), and the Minimal serving runtime job fails inserve/test_lifeline.py(the watcher case, #3590). Both reproduce onmainand on unrelated pull requests, and neither file is touched here.Limits
.19interleaved 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.🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.
--family swift#4676