Skip to content

kingnodes address - #40

Closed
nullmames wants to merge 1 commit into
gnolang:masterfrom
nullmames:master
Closed

nullmames wants to merge 1 commit into
gnolang:masterfrom
nullmames:master

Conversation

@nullmames

Copy link
Copy Markdown

No description provided.

@jaekwon

jaekwon commented Jan 13, 2022

Copy link
Copy Markdown
Contributor

adding manually

@jaekwon jaekwon closed this Jan 13, 2022
@moul moul added this to the 🏗1️⃣ test1.gno.land milestone Oct 20, 2022
clockworkgr added a commit that referenced this pull request Apr 17, 2026
Every issue below was a latent bug that could corrupt persisted state or
silently drop data. All fixes ship together because several interact
(#15 ↔ #40, #1 ↔ #9 ↔ #30).

Findings closed
===============

#1  Iterator does not register a version reader
    An open iterator at version V did not increment versionReaders[V], so a
    concurrent PruneVersionsTo(V) could delete nodes the iterator still
    needed to traverse via getChild. Iterators now register on construction
    and decrement exactly once on (idempotent) Close. See iterator.go and
    TestIterator_BlocksPruneUntilClose.

#2  Empty-tree branch mishandled orphan value records
    When a version committed with an empty root, its orphan value records
    were left in the DB forever. Pruning logic now handles the empty-root
    case correctly; verified by TestMarkSweepPrune_EmptyOldVersion.

#3  Positional-descent prune algorithm mis-identified subtrees
    The previous prune walked the new version's tree by position and could
    mistakenly delete nodes that were still reachable from retained
    versions, triggering cascading "failed to load child node" panics
    under sustained random-insert + prune workloads. Replaced with a
    mark-and-sweep implementation that is content-addressed via NodeKey
    and therefore immune to positional-routing fragility. Regression
    coverage: TestMarkSweepPrune_SustainedInsertPrune (seeded long-run),
    FuzzPruneConsistency, FuzzPruneDeepTree, plus the height-3 stress
    tests in prune_test.go.

#6  ValueKey nonce starting at 0 collided with the all-zero sentinel
    Fresh stores used nonce = 0 on the first value write, which collides
    with the legacy empty/zero-value sentinel used elsewhere in the
    store layer. Nonces now start at 1; a migration test in
    valuekey_nonce_test.go confirms pre-existing stores continue to load.

#8  Iterate dropped resolver errors on both trees
    Value-resolution errors during iteration were swallowed, yielding
    silent empty values to the caller. Errors now propagate through
    Iterate on both the ImmutableTree and MutableTree paths; see
    iterate_error_test.go.

#15 PruneVersionsTo had a check-vs-delete TOCTOU against reader registration
    beginPruning now holds pruneMu across the reader-count check AND the
    actual DB deletions. incrVersionReaders takes the same lock, so a
    reader registration is either serialised before the check (rejecting
    prune with ErrActiveReaders) or after the deletes have completed
    (observing a consistent post-prune DB). Lock ordering: pruneMu BEFORE
    mtx on every path. Regression tests:
    TestPrune_BeginPruningBlocksReaderRegistration,
    TestPrune_TOCTOU_ReaderRaceIsClosed,
    TestPrune_BlocksConcurrentReaderRegistration.

#26 SaveVersion idempotent-save false mismatch vs legacy empty-tree blob
    SaveVersion compared the new empty-tree root record against the legacy
    on-disk representation byte-for-byte, which produced a spurious
    mismatch and rejected the idempotent save. Comparison now accepts
    both the legacy zero-length and hash-only empty-root encodings;
    coverage in idempotent_save_test.go.

#30 GetImmutable / immutableForProof did not register version readers
    A caller holding an ImmutableTree or generating a proof was not
    reflected in versionReaders[V], so a concurrent PruneVersionsTo(V)
    could tear the snapshot out from under the caller. Both paths now
    register and the ImmutableTree.Close() releases (idempotently).
    Tests: TestGetImmutable_BlocksPruneUntilClose,
    TestGetImmutable_EmptyVersionRegistersReader,
    TestImmutableTree_CloseIsIdempotent,
    TestProof_ReleasesReaderAfterReturn.

#40 GetImmutable / immutableForProof registered the reader AFTER loading
    Registration happened at the end of GetImmutable, so a prune that had
    already passed beginPruning could delete the root record between our
    GetRoot call and our incrVersionReaders call; the subsequent
    loadNode would then hit a partially-pruned DB. Fix: register FIRST,
    then read the root, with decrVersionReaders on every error path.
    Same reordering applied to immutableForProof. Regression tests:
    TestGetImmutable_BlocksOnInFlightPrune,
    TestGetImmutable_ReleasesReaderOnMissingVersion.

Architecture changes
====================

- prune.go: positional-descent implementation removed; mark-and-sweep is
  now the sole pruning strategy. Leaf-skip optimisation at inner.height == 1
  avoids loading children when marking/deleting them by NodeKey bytes.
- nodedb.go: pruneMu introduced. Lock order invariant documented
  (pruneMu BEFORE mtx on every path that touches both).
- immutable_tree.go: Close() is idempotent; subsequent calls are no-ops
  rather than double-decrementing versionReaders.
- mutable_tree.go, proof.go, iterator.go: reader registration reordered
  to precede any DB reads on versioned snapshots.

Tests added
===========

- version_readers_test.go     — reader-registration invariants for
                                GetImmutable, iterators, proofs, and
                                the Finding #40 TOCTOU regressions.
- prune_toctou_test.go        — Finding #15 blocking invariants and
                                reader/prune race closures.
- prune_marksweep_test.go     — basic, reload-after-prune, sustained
                                insert+prune, node-count-decreases,
                                shared-subtree preservation,
                                empty-old-version scenarios.
- idempotent_save_test.go     — Finding #26 legacy-encoding acceptance.
- iterate_error_test.go       — Finding #8 resolver-error propagation.
- valuekey_nonce_test.go      — Finding #6 nonce-from-1 + migration.
- prune_test.go               — expanded height-3 churn / cascading
                                multi-version prune / height oscillation.
- fuzz_prune_test.go          — native FuzzPruneConsistency +
                                FuzzPruneDeepTree + TestPrune_FuzzLongRun.

Verification
============

  go test -short -count=1 ./tm2/pkg/bptree/... ./tm2/pkg/store/bptree/...   PASS
  go test -race -short -run 'TestGetImmutable|TestImmutableTree_|
      TestIterator_|TestProof_|TestPrune_BeginPruningBlocksReaderRegistration|
      TestPrune_TOCTOU_ReaderRaceIsClosed|
      TestPrune_BlocksConcurrentReaderRegistration|TestMarkSweepPrune_'      PASS
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.
clockworkgr added a commit that referenced this pull request Apr 22, 2026
A line-by-line critical pass over the PR (six parallel reviewers,
results cross-verified) surfaced five actual bugs in the work
landed on this branch. All five are closed here without changing
tree semantics or the PR's headline correctness/perf story.

BUG-1 (HIGH) — Store.GetImmutable leaked version readers
  Files: tm2/pkg/store/bptree/{store.go,tree.go,store_test.go,
         coverage_test.go}

  The store wrapper's Store.GetImmutable returned a *Store with no
  Close path. Each call permanently incremented versionReaders[v]
  with no decrement. Since the store wrapper is the production
  interface (tm2/pkg/store/rootmulti and the IAVL-compat layer),
  this defeated the very contract Findings #1/#15/#30/#40 added to
  PruneVersionsTo — pruning would block on stranded reader counts
  as soon as any consumer used GetImmutable.

  Fix: added CloseSnapshot() error to the Tree interface (no-op on
  the mutable adapter; calls bp.ImmutableTree.Close on the
  immutable adapter) and Store.Close() that propagates. Updated
  the four GetImmutable test sites that previously leaked.

BUG-2 (MEDIUM) — SaveVersion idempotent path leaked session state
  File: tm2/pkg/bptree/mutable_tree.go

  When SaveVersion(N) found N already persisted with the matching
  hash, the early return skipped clearing sessionValues,
  versionOrphans, and resetting nextValueNonce. A subsequent
  Rollback would DeleteValueDirect VKs that t.lastSaved still
  references; the next SaveVersion would carry stale orphans and
  non-zero nonces forward into the wrong namespace.

  Fix: clear all three before the idempotent return so the
  post-condition matches a normal successful save.

BUG-3 (MEDIUM) — LoadVersion partial failure poisoned nextValueNonce
  File: tm2/pkg/bptree/mutable_tree.go

  In LoadVersion, if maxValueNonceForVersion succeeded but loadNode
  then failed, t.nextValueNonce was set for the *failed-load*'s
  working-version namespace. The tree's t.version was unchanged
  (still the prior version). The next Set against the OLD t.version
  would allocate VKs in the wrong namespace, re-introducing the
  value-overwrite hazard maxValueNonceForVersion was added in this
  PR to prevent.

  Fix: snapshot the prior nonce; restore on loadNode failure.

BUG-4 (LOW) — Panic in nodeKeyBytesToArr bypassed batch discard
  File: tm2/pkg/bptree/prune.go

  nodeKeyBytesToArr panicked on short slices (a corruption
  diagnostic per Finding #47). The panic propagated out of
  markReachable / sweepOld past the explicit discardBatch calls in
  PruneVersionsTo's loop, leaving ndb.batch with partial deletes
  that the next Commit would flush — corrupting the prune
  bookkeeping further (firstVersion not advanced, but partial node
  deletes flushed on the next save).

  Fix: returned a typed ErrShortNodeKeyRef; updated both call sites
  in markReachable and sweepOld to propagate the error so
  PruneVersionsTo's discardBatch path runs cleanly.

BUG-5 (LOW) — merge skipped copyKey for absorbed right-keys
  File: tm2/pkg/bptree/remove.go

  The leaf and inner cases in merge appended right's keys into left
  without copyKey(), breaking Finding #20's "all separator
  boundaries use copyKey" uniform discipline. Safe today under the
  immutable-key-bytes invariant, but inconsistent — a future
  in-place key mutation elsewhere in the codebase would silently
  corrupt prior snapshots that share these slice headers via the
  merged-left.

  Fix: added copyKey() at both sites with comments referencing
  Finding #20.

Verification:

  go test -count=1 ./tm2/pkg/bptree/... ./tm2/pkg/store/bptree/...
    PASS (full suite)

  go test -race -count=1 -run='TestPrune|TestSaveVersion|
    TestLoadVersion|TestStore|TestImmutable|TestGetImmutable|
    TestIdempotent' ./tm2/pkg/bptree/ ./tm2/pkg/store/bptree/
    PASS

Six remaining concerns from the same review (not blocking) are
documented in the PR description as C-1 through C-6.
aeddi pushed a commit that referenced this pull request Nov 17, 2026
* fix(gnoweb): bound URL path len before regex validation in gnoweb

* fix(gnoweb): address oversized URL review feedback

* Update gno.land/pkg/gnoweb/handler_http_test.go

Co-authored-by: Guilhem Fanton <[email protected]>

* fix(gnoweb): bound invalid path log output

Assisted-by: Codex

* fix(gnoweb): bound only the path segment, not webargs, by maxPathLength

The maxPathLength limit was applied to the whole EscapedPath, which
includes $help webargs and :args. Legitimate argument values (e.g. a
CreateThread body submitted through the $help form) share that string,
so the 4096 bound rejected real content past ~two paragraphs of English.

Only the path segment reaches reURLPath/reGnolandPath, so bound it there
and leave args/webargs out of the limit.

---------

Co-authored-by: Guilhem Fanton <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects
Archived in project

Development

Successfully merging this pull request may close these issues.

3 participants