fix(store): disable zero-copy for historical queries so results outlive the DB cache #110
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #110"
general
weight: 0.35
thomas-nguy
What
loadAtVersioninstore/rootmultinow forcesZeroCopy = falseon the historical memiavl DB it opens, so historical query results are cloned instead of aliasing the snapshot mmap. Also clones the leaf key/value inmemiavl/createExistenceProofunder the tree's ownzeroCopyflag, and memoizesIterator.Key()/Value()clones per position so the added copying is paid once per element instead of once per call.Issue
loadAtVersioninheritedZeroCopyfrom the operator'srs.opts. With zero-copy on,Store.Queryreturned aResponseQuerywhoseValuepointed into the snapshot mmap. The historical DB cache is an LRU of size 4: once the borrower releases the entry and the LRU evicts it,db.Close()unmaps the snapshot — and the already-returned response is left pointing at unmapped memory. Reading it faults (SIGSEGV) or returns garbage.The refcounting itself is fine:
closeonly fires atrefs == 0 && evicted, andQueryholds the borrow across its whole body. The defect is purely results escaping past the release.Separately,
PersistedNode.Key()/Value()alias the mmap unconditionally — unlikeTree.Get/GetByIndex/Iterator, they have no zero-copy gate of their own. SocreateExistenceProofhanded back mmap-backed slices even on a tree built withzeroCopy = false, violating that tree's contract.Scope of the live bug.
ZeroCopydefaults to false, so only operators who setmemiavl.zero-copy = truewere exposed. WithinStore.Querythe one field that genuinely escapes isres.Valueon the/keypath (a baretree.Get)./subspaceand the proof ops are already safe, becausepairs.Marshal()andCommitmentOp.ProofOp()copy into fresh buffers while the borrow is still held.Tradeoff. Historical queries now allocate a copy per value. Measured on darwin/arm64 (M4 Max), medians of
-count 5, warm LRU, 1000 keys of 34-byte values, comparing against the same benchmarks with theZeroCopy = falseline removed:| Query | Before | After | Delta |
| --- | --- | --- | --- |
|
/key| 125 ns, 212 B, 4 allocs | 134 ns, 260 B, 5 allocs | +7% ||
/keywithProve| 2693 ns, 6320 B, 99 allocs | 2629 ns, 6432 B, 102 allocs | within noise, +112 B ||
/subspace, 1000 keys | 83.8 µs, 212 KB, 2022 allocs | 107.2 µs, 276 KB, 4022 allocs | +28% || cold
loadAtVersion| 260 µs | 260 µs | unchanged |For scale: one cold historical DB load is ~260 µs, so the +9 ns on a point query and the +23 µs on a full 1000-key scan are both small next to the load the LRU exists to amortise. Copy overhead on a scan is +23 ns and +64 B per element — exactly one key clone plus one value clone. Live (non-historical) queries are untouched; they still honor the operator's setting.
Solution
loadAtVersionsetsopts.ZeroCopy = falseunconditionally, next to the existingReadOnly = true.createExistenceProofclonesnode.Key()/node.Value()when!t.zeroCopy.convertInnerOpsneeded no change — it builds prefix/suffix withappendinto fresh slices, so aliasedHash()bytes are copied in transit, andnonexist.Keyis the caller's own key.Iteratorcaches its key/value clone per position and resets it inNext(), rather than cloning on everyKey()/Value()call. Callers must treat the result as read-only (CONTRACT: key readonly []byteondbm.Iterator), and resetting onNextmeans a retained slice is never overwritten. On the repeated-access pattern the cachekv merge iterator produces (3xKey()+ 1xValue()per position), this is 153 → 103 allocs/op, 1952 → 1600 B/op, ~30% faster. It does not change/subspace:KVStorePrefixIteratoris a barekvs.Iterator, so it already called each accessor once per element. The win is on the cachekv-wrapped execution path, where zero-copy is off by default.app.tomltemplate notes thatzero-copyno longer applies to historical queries, so operators do not expect it from archive reads.createExistenceProofnow returns immediately on apathToLeaferror, instead of falling through to build an existence proof that would be discarded anyway.Tree.Getno longer clones the cached value a second time;GetWithIndexalready clones it under!zeroCopy.Note the first two changes are independent. The
rootmultipath is in fact already saved from the proof aliasing byCommitmentOp.ProofOp(), which protobuf-marshals the proof into a fresh buffer while the borrow is still held. Theproof.gochange fixes the memiavl API contract for any other caller ofGetMembershipProof.Test
Four new tests, each verified to fail without its fix:
TestLoadAtVersionDisablesZeroCopy(store/rootmulti) — commits two versions, reads the same key from two separately-loaded historical DBs, and asserts the backing pointers differ. Comparesuintptr(unsafe.Pointer(unsafe.SliceData(...)))rather than the slices, becauserequire.NotEqualusesreflect.DeepEqual, which follows pointers and would compare pointee content instead of addresses.TestHistoricalQueryResultSurvivesCacheEviction(store/rootmulti) — setsZeroCopy: trueto simulate the operator setting, queries an old version withProve: true, then queriesdefaultHistoricalDBCacheSizemore versions to force eviction. Asserts eviction actually happened by lockinghistoricalDBCache.muand scanningentries, then re-reads the response value and proof ops. Without the fix this faults rather than failing, so the final reads are guarded withdebug.SetPanicOnFault— otherwise a regression takes down the whole package's test binary with a SIGSEGV and is easy to misattribute.TestProofOutlivesSnapshotWhenZeroCopyDisabled(memiavl) — builds a multi-version, multi-leaf snapshot-backed tree withzeroCopy = falseso the membership proof has a real inner-node path and the non-membership proof has bothLeft/Rightbranches, takes both proofs, closes the tree, then reads the proof key/value. Mirrors the existingTestZeroCopyidiom (debug.SetPanicOnFault).TestIteratorZeroCopyDisabledClonesPerPosition(memiavl) — asserts repeatedKey()/Value()calls at one position return the same backing array, that advancing hands out a fresh one so a retained slice is not overwritten, and that retained pairs still read correctly after the snapshot is unmapped.Benchmarks added so the numbers above are reproducible:
BenchmarkHistoricalQuery(point, proof, subspace) andBenchmarkHistoricalLoadinstore/rootmulti,BenchmarkIteratorRepeatedKeyAccessinmemiavl.