← Back to Pull requests

fix(store): disable zero-copy for historical queries so results outlive the DB cache #110

Closed
unknown closed this pull request without merging on Aug 07, 2026 14:37 UTC
View on GitHub
unknown unknown commented on Aug 06, 2026 17:15 UTC
Author

What

loadAtVersion in store/rootmulti now forces ZeroCopy = false on the historical memiavl DB it opens, so historical query results are cloned instead of aliasing the snapshot mmap. Also clones the leaf key/value in memiavl/createExistenceProof under the tree's own zeroCopy flag, and memoizes Iterator.Key()/Value() clones per position so the added copying is paid once per element instead of once per call.

Issue

loadAtVersion inherited ZeroCopy from the operator's rs.opts. With zero-copy on, Store.Query returned a ResponseQuery whose Value pointed 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: close only fires at refs == 0 && evicted, and Query holds the borrow across its whole body. The defect is purely results escaping past the release.

Separately, PersistedNode.Key()/Value() alias the mmap unconditionally — unlike Tree.Get/GetByIndex/Iterator, they have no zero-copy gate of their own. So createExistenceProof handed back mmap-backed slices even on a tree built with zeroCopy = false, violating that tree's contract.

Scope of the live bug. ZeroCopy defaults to false, so only operators who set memiavl.zero-copy = true were exposed. Within Store.Query the one field that genuinely escapes is res.Value on the /key path (a bare tree.Get). /subspace and the proof ops are already safe, because pairs.Marshal() and CommitmentOp.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 the ZeroCopy = false line removed:

| Query | Before | After | Delta |
| --- | --- | --- | --- |
| /key | 125 ns, 212 B, 4 allocs | 134 ns, 260 B, 5 allocs | +7% |
| /key with Prove | 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

  • loadAtVersion sets opts.ZeroCopy = false unconditionally, next to the existing ReadOnly = true.

  • createExistenceProof clones node.Key()/node.Value() when !t.zeroCopy. convertInnerOps needed no change — it builds prefix/suffix with append into fresh slices, so aliased Hash() bytes are copied in transit, and nonexist.Key is the caller's own key.

  • Iterator caches its key/value clone per position and resets it in Next(), rather than cloning on every Key()/Value() call. Callers must treat the result as read-only (CONTRACT: key readonly []byte on dbm.Iterator), and resetting on Next means a retained slice is never overwritten. On the repeated-access pattern the cachekv merge iterator produces (3x Key() + 1x Value() per position), this is 153 → 103 allocs/op, 1952 → 1600 B/op, ~30% faster. It does not change /subspace: KVStorePrefixIterator is a bare kvs.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.toml template notes that zero-copy no longer applies to historical queries, so operators do not expect it from archive reads.

  • createExistenceProof now returns immediately on a pathToLeaf error, instead of falling through to build an existence proof that would be discarded anyway.

  • Tree.Get no longer clones the cached value a second time; GetWithIndex already clones it under !zeroCopy.
  • Note the first two changes are independent. The rootmulti path is in fact already saved from the proof aliasing by CommitmentOp.ProofOp(), which protobuf-marshals the proof into a fresh buffer while the borrow is still held. The proof.go change fixes the memiavl API contract for any other caller of GetMembershipProof.

    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. Compares uintptr(unsafe.Pointer(unsafe.SliceData(...))) rather than the slices, because require.NotEqual uses reflect.DeepEqual, which follows pointers and would compare pointee content instead of addresses.

  • TestHistoricalQueryResultSurvivesCacheEviction (store/rootmulti) — sets ZeroCopy: true to simulate the operator setting, queries an old version with Prove: true, then queries defaultHistoricalDBCacheSize more versions to force eviction. Asserts eviction actually happened by locking historicalDBCache.mu and scanning entries, then re-reads the response value and proof ops. Without the fix this faults rather than failing, so the final reads are guarded with debug.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 with zeroCopy = false so the membership proof has a real inner-node path and the non-membership proof has both Left/Right branches, takes both proofs, closes the tree, then reads the proof key/value. Mirrors the existing TestZeroCopy idiom (debug.SetPanicOnFault).

  • TestIteratorZeroCopyDisabledClonesPerPosition (memiavl) — asserts repeated Key()/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) and BenchmarkHistoricalLoad in store/rootmulti, BenchmarkIteratorRepeatedKeyAccess in memiavl.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: thomas-nguy Review duration: 1281m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%