Repository navigation
Persistence - #36
Merged
Merged
Persistence#36
Conversation
Contributor
Author
|
keeper may need to be modified; then test /r/example. |
clockworkgr
added a commit
that referenced
this pull request
Apr 17, 2026
…ness, hot-path polish A broad line-by-line follow-up review surfaced a collection of latent hazards and low-severity improvements across correctness, robustness, performance, and API ergonomics. This commit closes all of them without altering core behaviour (tree structure, hashing, versioning, proof format are untouched). Correctness - Finding #6: refinements around valueKey sentinel handling to avoid ambiguity with the all-zero ValueKey. - Finding #7: MutableTree is single-writer — all methods (including read-only Get / Has / Iterate / proof generation) mutate tree-level caches or lazy childNodes and must be serialised externally. This is now documented in README.md and on the MutableTree / ImmutableTree struct doc comments. TestConcurrent_LazyLoadFromDB exercises concurrent Has on a lazy ImmutableTree under -race. - Finding #9: proof generation over a MutableTree root reads miniTree state that Set rewrites in place. GetMembershipProof / GetNonMembershipProof and immutableForProof now carry explicit doc-comments stating callers MUST NOT mutate the tree during proof construction. - Findings #10 / #11: distinguish missing-key from missing-resolver. Iterate without a resolver returns ErrNoValueResolver instead of silently yielding 32-byte value hashes masquerading as values; Get / Iterate / GetByIndex surface ErrNoValueResolver through the resolver. ErrKeyDoesNotExist now only means the key is absent. - Findings #15 / #40: prune-reader TOCTOU is closed by pruneMu (held across the beginPruning / endPruning window). GetImmutable and immutableForProof now register the reader BEFORE loading the root so the reader-side ordering matches the prune side. - Finding #43: deleteAllNodesForVersion now loads the orphan list, deletes every value record, and deletes the orphan list itself — defensively, since today the path is unreachable under the current toVersion >= latest guard but any future relaxation would have silently leaked values. - Finding #46: markReachable and sweepOld now call a shared assertLeafChildren helper at every inner branch. It probes the first available child (in-memory or first serialised ref) once per parent and verifies (inner.height == 1) == child is *LeafNode. Violations surface as a typed ErrHeightInvariantViolated sentinel; the prune caller can roll back instead of silently corrupting the reachable set. Robustness - Finding #13: nodeDB lock discipline is now documented on the struct. mtx guards version metadata; pruneMu serialises prune with reader registration (always acquired before mtx); batch, nextNonce, and pendingEvicts are single-writer by design. - Finding #18: InnerNode.Serialize asserts child-ref length before writing (carried over from prior work). - Finding #38: Commit now documents that on write error the pending batch is lost and the caller must either reconstruct the in-flight state or roll back to a consistent checkpoint. Cache evictions queued by DeleteNode are discarded on error. - Finding #42: the unwired AsyncPruning option was removed from Options, eliminating the only code path that would have introduced a second writer goroutine against ndb.batch. - Finding #44: DeleteNode now defers cache eviction to Commit — ndb.pendingEvicts accumulates cache keys and flushes only after the batch write succeeds. Closes a theoretical race where a cache-miss reader could reload from the still-populated DB after eviction but before the batch flushes, then re-cache a node whose deletion now lives on disk. The prune-reader invariant makes this dormant today, but deferring the eviction codifies the contract. - Finding #45: ImmutableTree.Close is now guarded by sync.Once. Double or concurrent Close previously over-decremented the reader count, which would have allowed a prune to proceed while other snapshots of the same version were still live. - Finding #47: nodeKeyBytesToArr now panics with a clear diagnostic on short slices instead of silently zero-padding (which would silently miscompare against the reachable set). - Finding #52: mid-loop errors in PruneVersionsTo now discard the partial batch via discardBatch() before returning. The next Commit would otherwise flush deletes for versions that were never fully pruned, leaving disk and firstVersion bookkeeping inconsistent. Performance - Finding #16: iterator now prefetches every occupied slot's value on the first Value() call after a leaf transition and caches them on the iterator; setLeaf invalidates the cache on every transition. Amortises per-call overhead and surfaces resolver errors at the first Value() instead of arbitrarily later. - Finding #21 (remaining bullets): hot-path allocations cleaned up — Hash() slice caching, mini-merkle SiblingPath stack allocation, mini_merkle Clear() via struct copy of a package-level template, leaf/inner split stack arrays, and a merged non-membership walk. - Finding #29: InnerNode.Clone no longer re-runs Build() after the struct copy; the intermediate miniTree layer is copied by value so subsequent SetSlot calls keep their fast incremental walk-up. - Finding #49: sweepOld now checks reachable[nk] for in-memory children before descending, mirroring the serialised-ref shortcut. Avoids pointless call-frames for shared subtrees. - Finding #51: leaf-skip savings comment now derives the 32/33 ≈ 97% figure from B = 32 so a future branch factor change can re-derive the win in one step. API ergonomics and code quality - Finding #12: public methods that panicked (LoadVersionForOverwriting, DeleteVersionsFrom) now return ErrUnsupported (carried over). - Finding #19: iterateNode was removed alongside the hash-as-value fallback once Finding #11 landed; only iterateNodeResolved remains, and a comment at its declaration site documents the removal. - Finding #22: proof_spec.go MaxPrefixLength and MaxDepth are now documented inline with derivations — MaxPrefixLength = 1 is correct because ICS23 adds maxLeftChildBytes internally; MaxDepth = 60 covers 12 inner levels × 5 mini-merkle ops ≈ 32**12 entries. - Finding #24: LeafNode.Clone and InnerNode.Clone carry explicit doc comments on the slice-header aliasing invariant; redistribute / merge paths call assertCloned at entry. - Finding #27: export.go separator keys are deep-copied into a fresh sepKeys slice so a concurrent mutator on a shared root cannot tear key bytes mid-export. Importer.Close now deletes values eagerly written by Add when Commit has not succeeded and is idempotent; savedVKs is nulled on commit so post-commit Close does not try to delete values the tree now owns. - Finding #33: iterator.seekLast now decrements childIdx when end == keys[childIdx-1], avoiding one over-descent plus prevLeaf. - Finding #34: iterator Value() / Next() record resolver errors on it.err and the contract ("always Error() after Valid() == false") is documented. - Finding #35: MutableTree.Iterator now errors early when ndb == nil && memValues == nil instead of silently yielding nil values. - Finding #36: SaveVersion resets session counters only after a successful Commit; a failed Commit now triggers Rollback so the next SaveVersion does not reuse nonces from the failed attempt. - Finding #37: treeRemove root-collapse preserves the surviving child's ndb; documented in the code. - Finding #38: Commit lifecycle contract documented at the method boundary. - Finding #39: Importer resets host-tree counters on Import() so a fresh import cannot inherit session state from prior Sets. - Finding #41: PruneVersionsTo setFirstVersion is advance-only; a caller passing toVersion < getFirstVersion() - 1 no longer rewinds the bookkeeping below the true first retained version. - Finding #50: deleteSubtree now prefers inner.childNodes[i] when set, falling back to GetNode(children[i]). A caller handing in a tree with unsaved children would otherwise have leaked subtrees. Tests - TestMutableTree_COW_OldReferencesValid: update to iterateNodeResolved after the iterateNode removal. All existing tests pass under -short and -race.
8 tasks done
aeddi
pushed a commit
that referenced
this pull request
Nov 17, 2026
…oot (#36) computeHashFromAunts used nil to mean "I cannot compute a root from this proof" — five exits do so: a non-positive total, an out-of-range index, a single-leaf tree carrying sibling hashes, a multi-leaf tree carrying none, and two propagating a recursive failure. SimpleProof.Verify then fed that straight into bytes.Equal against the caller's expected root, and bytes.Equal(nil, []byte{}) is true. So a proof the code had already given up on verified against an empty or nil root, for an arbitrary leaf. tm2's own callers were never exposed: block parts, tx proofs and ABCI results all take the root from a signed header, so it is always 32 bytes. What raises the stakes is gnovm/stdlibs/crypto/merkle.VerifySimpleProof, which hands the root to a realm as an ordinary argument while index and total come from the proof under test. A realm reading the root from a message, from an uninitialised slot, or without a length check would accept any leaf. No realm uses it yet, so this is hardening rather than an incident. computeHashFromAunts and ComputeRootHash now return ([]byte, error), one distinct error per failure path. The aim is to make the failure unrepresentable rather than guarded: adding Total == 0 and Index >= Total checks to Verify would have closed the enumerated cases at the one call site we looked at, and missed the second one — SimpleValueOp.Run returned [][]byte{op.Proof.ComputeRootHash()} unchecked, and that value reaches ProofOperators.Verify's bytes.Equal(root, args[0]), the identical collision on the store/ICS23 path. A sentinel that cannot be constructed cannot be missed at a call site nobody reviewed. Verify keeps its signature and gains the two missing range checks, so a malformed proof is refused at the boundary with a message naming its actual defect — it previously reported "invalid root hash: wanted X got <empty>", sending the reader after a mismatch that never happened. The unreachable case 0 panic in computeHashFromAunts is dropped; the total <= 0 check above it always fired first. Breaking change to an exported tm2 API, with two in-repo callers, both already error-returning and both previously wrong. Verify's own signature is unchanged, so X_verifySimpleProof needs no edit and no stdlib MemPackage source bytes move — the committed multistore root is unaffected. Verified: six-case table green, and red again under a negative control that reinstates the old guards and swallows the new error; ./tm2/pkg/crypto/..., ./tm2/pkg/store/... and ./tm2/pkg/bft/types/... pass, so the tightened checks reject nothing legitimate; through the Gno stdlib all four reachable shapes now return false where every one returned true before.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Object Value and Type Persistence.
Node persistence is simulated with the preprocessing of all files upon app restart.