Skip to content

Add rhinostake address - #43

Closed
ericjohncarlson wants to merge 1 commit into
gnolang:masterfrom
RhinoStake:rhinostake-address
Closed

ericjohncarlson wants to merge 1 commit into
gnolang:masterfrom
RhinoStake:rhinostake-address

Conversation

@ericjohncarlson

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
zivkovicmilos pushed a commit that referenced this pull request May 30, 2025
Bumps [anchore/sbom-action](https://github.com/anchore/sbom-action) from 0.17.1 to 0.17.2.
- [Release notes](https://github.com/anchore/sbom-action/releases)
- [Commits](anchore/sbom-action@v0.17.1...v0.17.2)

---
updated-dependencies:
- dependency-name: anchore/sbom-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
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.
aeddi pushed a commit that referenced this pull request Nov 17, 2026
)

* fix(gnovm): visit the operand stack (m.Values) during GC

GarbageCollect() visited m.Blocks, m.Frames, m.Package, the staging
package, and m.Exception, but never m.Values (the operand stack).
Objects reachable only from the operand stack — intermediate expression
results, call arguments before OpCall pops them into a block, and
composite-literal elements before doOpArrayLit/doOpSliceLit/doOpStructLit
construct the object — were invisible to GC, with two compounding effects:

  1. Gas undercharge: visitCount never included operand-stack objects, so
     gcVisitGas(visitCount) charged far less than the real GC work.
  2. Memory undercount: after Alloc.Reset(), Recount only re-added visited
     objects, so alloc.bytes collapsed to the blocks/frames/package
     residue. That handed the program free headroom equal to everything
     parked on the stack, letting the Go heap grow without bound past
     maxAllocTx (500MB) / maxAllocQuery (1.5GB) → OOM, a fatal Go runtime
     error recover() cannot catch (validators crash → consensus halt).

An attacker could exploit this via a large composite literal in
MsgAddPackage (elements pile onto m.Values until doOpArrayLit) or via the
unauthenticated qeval query path, building hundreds of MB the cap should
have refused.

Fix: GarbageCollect() now walks m.Values before blocks/frames/package,
recounting each slot as a TypedValue (as Frame.Visit does for the receiver
and defer args) and visiting its V for deep traversal. Operand-stack
objects are now both counted in visitCount (correct GC gas) and recounted
in alloc.bytes (cap enforced, no free headroom).

Refresh the now-stale comments at store.go and keeper.go that cited the
m.Values blind spot as the reason the preprocess allocator keeps
collect=nil; that hard cap is by design (static-eval scratch), not a GC
gap. Update expected bytes in 10 alloc filetests (+80/GC cycle from the
recounted operand-stack slots) and gas in gas/nested_alloc (+2987 from the
now-charged operand-stack visits). Add a unit test
(TestGarbageCollect_VisitsOperandStack), a filetest
(alloc_13_operand_stack), and an integration txtar (alloc_operand_stack)
that reproduces the 560MB-literal attack and asserts it is now refused with
'allocation limit exceeded' before the storage-deposit step.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm,vm): clarify preprocess-allocator hard-cap rationale

The comments on the per-tx preprocess allocator (keeper.go, store.go)
cited "GC doesn't visit m.Values" as the reason collect=nil (hard cap,
no GC retry). That blind spot is fixed in this branch, so the stated
rationale was stale. State the standing reason instead: preprocess is
bounded static evaluation (const-fold, evalStaticType) that should fail
fast at the cap, and preprocess sub-Machines install no GC fn
(isPreprocessing skips SetGCFn). Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm): note the operand-stack slot-accounting known gap in GC

The per-slot Recount(allocTypedValue) added for m.Values counts a 40B
TypedValue wrapper that runtime never charges (PushValue is a bare
append), so GC counts slightly more than runtime for these operand-stack
slots — matching the pre-existing Frame.Visit / Exception.Visit recounts.
The gap is bounded (stack depth <= source size) and non-amplifiable, so
it is not a DoS; the deep vis(v) is what closes the OOM. Reconciling the
slot accounting is left to a follow-up (tracked in PR discussion).

Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm): drop dangling PR-discussion reference in GC known-gap note

Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm): address review on operand-stack GC comments; fix slice_alloc threshold

- garbage_collector.go: state what the m.Values walk covers and what it
  does not (pop-then-allocate windows), and the two known over-counts:
  the 40B slot wrapper (bounded by metered work, cannot amplify) and
  string aliases charged once per slot (fail-safe, present at every
  root; fixed root-independently by per-backing dedup, #4885,
  not by a stack-slot special case). Slot count is runtime stack depth,
  not source size.
- store.go / keeper.go: collect stays nil for preprocessAlloc because it
  is shared across every preprocess sub-Machine in the tx.
- gas/slice_alloc.gno: n was 3 slots (120B) past the ceiling on this
  branch in isolation; drop to 12499840 (verified max) and re-pin Gas.

* docs(gnovm): simplify operand-stack GC gap notes

* docs(gnovm): plain wording for the slot-wrapper over-count note

* docs(gnovm): ADR for visiting the operand stack during GC

* docs(gnovm): name the ADR after the PR number

* docs(gnovm): keep the operand-stack slot recount; follow-up charges cap growth at runtime

* test(gnovm): pin GC counting of nil-V operand-stack slots

* test(gnovm): assert GC visit gas on the real path

The gas assertion in TestGarbageCollect_VisitsOperandStack was a tautology:
gcVisitCount re-implemented the root walk with its own visitor, so the only
difference between the two calls was whether the *helper's* m.Values loop
ran. Verified: with the m.Values loop deleted from GarbageCollect, the
assertion still passed on its own, leaving the consensus-visible GC-gas axis
(+2987 in gas/nested_alloc) with no regression coverage.

Read the gas GarbageCollect itself consumes instead, on two machines that
differ only in whether the array is parked on the operand stack. Recount
charges no gas and the array is allocated before the meter is read, so the
delta is the GC visit charge alone. With the loop removed both machines
report 58 gas and the assertion fails; with it, 87 vs 58.

Also drops gcVisitCount, a second copy of the root walk already out of sync
with the original (no blockPool, staging package or Exception chain).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm): correct the two gap claims this PR does not close, and pin them

"Transient and bounded" was wrong for the pop-then-allocate window, and
Block.Blank did not belong in the "not amplification vectors" bucket. Both
verified as filetests under a 1 MB cap:

- []Big{a, a, ...}, 100 aliased 300 KB elements: builds 30 MB, scaling with
  the element count. Two compounding causes: the elements all alias one
  operand-stack value, so the walk charges one element (vis dedups Objects),
  and doOpSliceLit fills a Go-local backing array, so the copies it has
  already written are recounted past. doOpStructLit and popCopyArgs' variadic
  list have the same shape. The array form is refused (doOpArrayLit allocates
  up front), which is why alloc_operand_stack.txtar passes without
  generalising; a slice literal of distinct fresh elements is refused too, so
  aliasing is what defeats the walk.
- _ = make([]byte, 300_000) per recursion level: 200 levels hold 60 MB,
  because Block.VisitAssociated walks only b.Values and b.Parent. Binding the
  same expression to a name is correctly refused.

Both are pinned as filetests (alloc_15_slicelit_alias_gap, alloc_16_blank_gap)
that must flip to "// Error: allocation limit exceeded" when their root is
closed, so neither reads as fixed. Neither root is fixed here: the first needs
the destination anchored before the fill across three ops, the second is a
different root with serialization and realm-publicity paths to check.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm,vm): finish the preprocess-allocator comment substitution

preprocess_alloc_test.go carried a third copy of the old rationale ("GC
during preprocess would undercount because GarbageCollect doesn't visit
m.Values"), and it sits on the test that pins preAlloc.collect == nil, so it
was the first thing anyone would read before touching that invariant. Give
it the same substitution store.go and keeper.go already got: preAlloc is
shared by every preprocess sub-Machine in the tx, so a collect bound to one
machine would walk only that machine's roots.

Also replace the preprocess.go line numbers in those comments with the
function names they point at (evalStaticTypeMachine, evalStaticTypeOfRaw,
tryEvalStatic, evalConst) so they do not go stale.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(gnovm): count the two remaining roots that retain memory

A root GarbageCollect cannot reach is not a leak, it is a cap bypass:
Reset()+Recount() drops it, Allocate is told there is headroom that does not
exist, and the retried allocation succeeds. Repeat per element and the
program grows without bound while alloc.bytes stays flat. Visiting m.Values
closed one such root; two more were open, both reachable from MsgAddPackage
and from the unauthenticated qeval path.

Buffers under construction. Ops allocate a destination buffer as a Go local
and fill it one entry at a time, allocating as they go: doOpSliceLit,
doOpSliceLit2 (keyed copies plus the default fill, which is sized by the
index range), both doOpStructLit branches, popCopyArgs (args and the
variadic list), and the default fills themselves in defaultArrayValue and
defaultStructFields. Nothing references the buffer until the op finishes.
The m.Values walk does not compensate: in []T{a, a, ...} every slot holds
the same *ArrayValue and vis dedups Objects, so the walk charges one element
however many fresh copies get written. Measured under a 1 MB cap with
Big = [300000]byte and one package-level var a Big: []Big{a x 100} built
30 MB (scaling with the element count), and S{a x 10}, S{F0: a, ...},
g(a x 10), f(a...) and []Big{0: a, ...} each built 3 MB.

Add Allocator.anchors, a root set for exactly these buffers. PushAnchor
marks one live before the first write, PopAnchor releases it once its owner
is reachable from another root; GarbageCollect walks them with the machine's
roots. The caller rule — no allocation between the pop and the moment the
owner is rooted — is easy to hold because GC only runs from Allocate. The
list lives on the Allocator, not the Machine, so defaultArrayValue and
defaultStructFields can protect their fills for every caller. runOnce
truncates to its entry depth on any caught panic, so an op that dies
mid-fill cannot leave a buffer anchored and a recovered panic in a loop
cannot grow the list; under -tags debugAssert an unbalanced anchor on the
normal path panics, and the full filetest suite is clean.

Block.Blank. `_ = expr` assigns through GetBlankRef, so the block pins expr
for its whole life, but Block.VisitAssociated walked only Values and Parent.
One blank assignment per recursion level held 200 x 300 KB = 60 MB under a
1 MB cap, while the same expression bound to a name was correctly refused.
Visit it. Removing the retention instead would be wrong today: Assign2 calls
rlm.DidUpdate with the block as base, which is truthful precisely because
the block holds the value.

Seven filetests, one per shape: each passes on the merge base and is refused
here. Plus TestGarbageCollect_VisitsAnchoredBuffer and
TestAllocatorAnchors_Unwind. No existing golden moves — anchors only matter
when a GC lands inside a fill, which no existing fixture does — and
BenchmarkOpCall_10Params_0Captures / BenchmarkOpCallWarm show no regression
above noise with alloc-gas unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm): rewrite the ADR for all three roots

The ADR described one root and filed the other two as follow-ups, one of
them ("pop-then-allocate windows") as "transient and bounded" and the other
(Block.Blank) under "not amplification vectors". Both were wrong, and both
are now closed, so rewrite rather than patch: context for each root with its
measurement, the anchor design and why the list sits on the Allocator, why
Block.Blank is counted rather than dropped, the alternatives that do not
cover the default fills, and what is left (all of it fail-safe now).

Also correct the txtar's scope note: it covers the array-literal form, and
the sibling shapes are covered as filetests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm): the pop-then-copy gap is not bounded; closed by the stacked PR

* docs(gnovm): drop forward references to the stacked PR

* docs(gnovm): reflow the gap note; ADR drops the ordering note and names VM-owned stack growth

* test(gnovm): measure operand-stack GC gas on the real path; ADR names Block.Blank retention as a vector

* fix(gnovm): charge GC's linear slot walks per slot

GarbageCollect's walks over m.Values and Allocator.anchors inspect every
slot but only bump visitCount for slots carrying a .V, so a stack of
primitives is scanned for free: O(len) work that gcVisitGas never sees,
with len(m.Values) bounded only by gas (alloc_14 parks ~8192 slots from
~600 bytes of source at depth 128). Measured flat at 58 gas from 1K to
4M slots while wall time rises 4.8us -> 7.8ms.

Charge gcStackScanSlopeGas (4) per slot scanned, priced separately from
gcVisitGasTable: a slot scan is a sequential pass over a contiguous
[]TypedValue (~1.3-3.3 ns/slot per BenchmarkGCStackScan) rather than a
29-700ns pointer-chasing object visit, so folding it into the visit
table would overcharge by two orders of magnitude. The slope is a rough
developer-machine figure, not reference hardware; it sits just above the
measured maximum and matches OpCPUSlopeCopyPrimitive, the existing slope
for a comparable linear pass.

Goldens: gas/nested_alloc +424, gas/compute_map_key_big_bytes +4,
gas/compute_map_key_big_struct +36. Programs with shallow operand stacks
pay almost nothing; the charge tracks the depth actually scanned.

ADR: correct the Consequences figures. The +2987 quoted for
gas/nested_alloc was the stack-walk delta alone, not the series total,
and "+80 B per GC cycle" is not uniform (alloc_defer_gc moves +120, for
three live slots). Also record that visitCount does not cover nil-V
slots, which is why the scan needs its own charge.

* test(gno.land): update gc.txtar gas for the per-slot GC scan charge

The per-slot charge added in b2267dd60 moves this integration golden by
+36 (nine slots x gcStackScanSlopeGas), the same delta as
gas/compute_map_key_big_struct. It was missed because the gnovm filetests
and gno.land/pkg/sdk/vm were re-run but gno.land/pkg/integration was not.

Merging develop in first was necessary, not incidental: develop had already
moved this golden to 151131786 while this branch sat 57 commits behind, so
the value depends on develop's tree. Setting it from the branch alone would
have changed the same line develop changed and conflicted in the PR merge
tree GitHub actually tests. After the merge the local run reproduces CI
exactly (151131822).

Verified: gno.land/pkg/integration TestTestdata fully green,
gno.land/pkg/sdk/vm green, gnovm filetests unchanged (same 10 pre-existing
Go 1.26 type-check wording failures).

* fix(gnovm): anchor the map literal; locate the deferred func by NumArgs

Two gaps found by reviewing #96 against this branch.

doOpMapLit was the one composite-literal op the anchors did not cover.
It pops its operands and then copies each entry into a MapValue that is
still a Go local, so with the values all aliasing one package-level var
({0: a, 1: a, ...}) the popped sources are a single object while the
copies are N fresh allocations GC cannot see: 10 entries of a 300KB var
built 3MB under a 1MB cap, and 100 entries built 30MB, scaling linearly.
Same shape as the 560MB literal this series set out to refuse.

PushAnchor could not express it — a MapValue's entries are a linked list,
not a []TypedValue — so anchors now hold either a buffer or a whole
object (PushAnchorValue), and GC visits an object anchor through the
ordinary visitor. The map is anchored after the operands are popped on
purpose: pushing it onto the operand stack instead would overwrite
kvs[0], which PopValues leaves in place below the new top.

doOpDefer located the deferred func with m.PeekValue(len(Call.Args)+1),
but an embedded multi-value call leaves len(Args[0].Results) operands on
the stack (nodes.go: "len(Args) or len(Args[0].Results)"). So
`defer f(g())` bound the defer to one of g's results instead of f: with a
func-typed first result it silently deferred that closure, and with
scalar results it panicked "defer called a nil function". Use
ds.Call.NumArgs, which is what the preprocessor computed for exactly
this.

Tests: alloc_22_maplit.gno (fails without the map anchor, and the 100-entry
30MB variant is likewise refused) and defer_multivalue_call.gno, which
covers both the func-typed and scalar multi-result forms.

ADR: record the object anchor, and two gaps this series does not close —
doOpAssign destinations derived from popped LHS operands (IndexExpr /
SelectorExpr / StarExpr / CompositeLitExpr), where the miss is N and not
one in-flight copy; and doOpArrayLit's anchor being defence in depth
rather than a closed vector, since defaultArrayValue pre-charges the
destination at full size and no fixture covers its removal.

Verified: gnovm/pkg/gnolang -short, gno.land/pkg/integration TestTestdata
and gno.land/pkg/sdk/vm all green apart from the 10 pre-existing Go 1.26
type-check wording failures. No golden moved: no existing fixture GCs
inside a map fill.

---------

Co-authored-by: ltzmaxwell <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Morgan Bazalgette <[email protected]>
aeddi pushed a commit that referenced this pull request Nov 17, 2026
…l args are copied (stacked on #43) (#96)

* fix(gnovm): visit the operand stack (m.Values) during GC

GarbageCollect() visited m.Blocks, m.Frames, m.Package, the staging
package, and m.Exception, but never m.Values (the operand stack).
Objects reachable only from the operand stack — intermediate expression
results, call arguments before OpCall pops them into a block, and
composite-literal elements before doOpArrayLit/doOpSliceLit/doOpStructLit
construct the object — were invisible to GC, with two compounding effects:

  1. Gas undercharge: visitCount never included operand-stack objects, so
     gcVisitGas(visitCount) charged far less than the real GC work.
  2. Memory undercount: after Alloc.Reset(), Recount only re-added visited
     objects, so alloc.bytes collapsed to the blocks/frames/package
     residue. That handed the program free headroom equal to everything
     parked on the stack, letting the Go heap grow without bound past
     maxAllocTx (500MB) / maxAllocQuery (1.5GB) → OOM, a fatal Go runtime
     error recover() cannot catch (validators crash → consensus halt).

An attacker could exploit this via a large composite literal in
MsgAddPackage (elements pile onto m.Values until doOpArrayLit) or via the
unauthenticated qeval query path, building hundreds of MB the cap should
have refused.

Fix: GarbageCollect() now walks m.Values before blocks/frames/package,
recounting each slot as a TypedValue (as Frame.Visit does for the receiver
and defer args) and visiting its V for deep traversal. Operand-stack
objects are now both counted in visitCount (correct GC gas) and recounted
in alloc.bytes (cap enforced, no free headroom).

Refresh the now-stale comments at store.go and keeper.go that cited the
m.Values blind spot as the reason the preprocess allocator keeps
collect=nil; that hard cap is by design (static-eval scratch), not a GC
gap. Update expected bytes in 10 alloc filetests (+80/GC cycle from the
recounted operand-stack slots) and gas in gas/nested_alloc (+2987 from the
now-charged operand-stack visits). Add a unit test
(TestGarbageCollect_VisitsOperandStack), a filetest
(alloc_13_operand_stack), and an integration txtar (alloc_operand_stack)
that reproduces the 560MB-literal attack and asserts it is now refused with
'allocation limit exceeded' before the storage-deposit step.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm,vm): clarify preprocess-allocator hard-cap rationale

The comments on the per-tx preprocess allocator (keeper.go, store.go)
cited "GC doesn't visit m.Values" as the reason collect=nil (hard cap,
no GC retry). That blind spot is fixed in this branch, so the stated
rationale was stale. State the standing reason instead: preprocess is
bounded static evaluation (const-fold, evalStaticType) that should fail
fast at the cap, and preprocess sub-Machines install no GC fn
(isPreprocessing skips SetGCFn). Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm): note the operand-stack slot-accounting known gap in GC

The per-slot Recount(allocTypedValue) added for m.Values counts a 40B
TypedValue wrapper that runtime never charges (PushValue is a bare
append), so GC counts slightly more than runtime for these operand-stack
slots — matching the pre-existing Frame.Visit / Exception.Visit recounts.
The gap is bounded (stack depth <= source size) and non-amplifiable, so
it is not a DoS; the deep vis(v) is what closes the OOM. Reconciling the
slot accounting is left to a follow-up (tracked in PR discussion).

Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm): drop dangling PR-discussion reference in GC known-gap note

Comment-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(gnovm): address review on operand-stack GC comments; fix slice_alloc threshold

- garbage_collector.go: state what the m.Values walk covers and what it
  does not (pop-then-allocate windows), and the two known over-counts:
  the 40B slot wrapper (bounded by metered work, cannot amplify) and
  string aliases charged once per slot (fail-safe, present at every
  root; fixed root-independently by per-backing dedup, #4885,
  not by a stack-slot special case). Slot count is runtime stack depth,
  not source size.
- store.go / keeper.go: collect stays nil for preprocessAlloc because it
  is shared across every preprocess sub-Machine in the tx.
- gas/slice_alloc.gno: n was 3 slots (120B) past the ceiling on this
  branch in isolation; drop to 12499840 (verified max) and re-pin Gas.

* docs(gnovm): simplify operand-stack GC gap notes

* docs(gnovm): plain wording for the slot-wrapper over-count note

* docs(gnovm): ADR for visiting the operand stack during GC

* docs(gnovm): name the ADR after the PR number

* docs(gnovm): keep the operand-stack slot recount; follow-up charges cap growth at runtime

* test(gnovm): pin GC counting of nil-V operand-stack slots

* test(gnovm): assert GC visit gas on the real path

The gas assertion in TestGarbageCollect_VisitsOperandStack was a tautology:
gcVisitCount re-implemented the root walk with its own visitor, so the only
difference between the two calls was whether the *helper's* m.Values loop
ran. Verified: with the m.Values loop deleted from GarbageCollect, the
assertion still passed on its own, leaving the consensus-visible GC-gas axis
(+2987 in gas/nested_alloc) with no regression coverage.

Read the gas GarbageCollect itself consumes instead, on two machines that
differ only in whether the array is parked on the operand stack. Recount
charges no gas and the array is allocated before the meter is read, so the
delta is the GC visit charge alone. With the loop removed both machines
report 58 gas and the assertion fails; with it, 87 vs 58.

Also drops gcVisitCount, a second copy of the root walk already out of sync
with the original (no blockPool, staging package or Exception chain).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm): correct the two gap claims this PR does not close, and pin them

"Transient and bounded" was wrong for the pop-then-allocate window, and
Block.Blank did not belong in the "not amplification vectors" bucket. Both
verified as filetests under a 1 MB cap:

- []Big{a, a, ...}, 100 aliased 300 KB elements: builds 30 MB, scaling with
  the element count. Two compounding causes: the elements all alias one
  operand-stack value, so the walk charges one element (vis dedups Objects),
  and doOpSliceLit fills a Go-local backing array, so the copies it has
  already written are recounted past. doOpStructLit and popCopyArgs' variadic
  list have the same shape. The array form is refused (doOpArrayLit allocates
  up front), which is why alloc_operand_stack.txtar passes without
  generalising; a slice literal of distinct fresh elements is refused too, so
  aliasing is what defeats the walk.
- _ = make([]byte, 300_000) per recursion level: 200 levels hold 60 MB,
  because Block.VisitAssociated walks only b.Values and b.Parent. Binding the
  same expression to a name is correctly refused.

Both are pinned as filetests (alloc_15_slicelit_alias_gap, alloc_16_blank_gap)
that must flip to "// Error: allocation limit exceeded" when their root is
closed, so neither reads as fixed. Neither root is fixed here: the first needs
the destination anchored before the fill across three ops, the second is a
different root with serialization and realm-publicity paths to check.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm,vm): finish the preprocess-allocator comment substitution

preprocess_alloc_test.go carried a third copy of the old rationale ("GC
during preprocess would undercount because GarbageCollect doesn't visit
m.Values"), and it sits on the test that pins preAlloc.collect == nil, so it
was the first thing anyone would read before touching that invariant. Give
it the same substitution store.go and keeper.go already got: preAlloc is
shared by every preprocess sub-Machine in the tx, so a collect bound to one
machine would walk only that machine's roots.

Also replace the preprocess.go line numbers in those comments with the
function names they point at (evalStaticTypeMachine, evalStaticTypeOfRaw,
tryEvalStatic, evalConst) so they do not go stale.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(gnovm): count the two remaining roots that retain memory

A root GarbageCollect cannot reach is not a leak, it is a cap bypass:
Reset()+Recount() drops it, Allocate is told there is headroom that does not
exist, and the retried allocation succeeds. Repeat per element and the
program grows without bound while alloc.bytes stays flat. Visiting m.Values
closed one such root; two more were open, both reachable from MsgAddPackage
and from the unauthenticated qeval path.

Buffers under construction. Ops allocate a destination buffer as a Go local
and fill it one entry at a time, allocating as they go: doOpSliceLit,
doOpSliceLit2 (keyed copies plus the default fill, which is sized by the
index range), both doOpStructLit branches, popCopyArgs (args and the
variadic list), and the default fills themselves in defaultArrayValue and
defaultStructFields. Nothing references the buffer until the op finishes.
The m.Values walk does not compensate: in []T{a, a, ...} every slot holds
the same *ArrayValue and vis dedups Objects, so the walk charges one element
however many fresh copies get written. Measured under a 1 MB cap with
Big = [300000]byte and one package-level var a Big: []Big{a x 100} built
30 MB (scaling with the element count), and S{a x 10}, S{F0: a, ...},
g(a x 10), f(a...) and []Big{0: a, ...} each built 3 MB.

Add Allocator.anchors, a root set for exactly these buffers. PushAnchor
marks one live before the first write, PopAnchor releases it once its owner
is reachable from another root; GarbageCollect walks them with the machine's
roots. The caller rule — no allocation between the pop and the moment the
owner is rooted — is easy to hold because GC only runs from Allocate. The
list lives on the Allocator, not the Machine, so defaultArrayValue and
defaultStructFields can protect their fills for every caller. runOnce
truncates to its entry depth on any caught panic, so an op that dies
mid-fill cannot leave a buffer anchored and a recovered panic in a loop
cannot grow the list; under -tags debugAssert an unbalanced anchor on the
normal path panics, and the full filetest suite is clean.

Block.Blank. `_ = expr` assigns through GetBlankRef, so the block pins expr
for its whole life, but Block.VisitAssociated walked only Values and Parent.
One blank assignment per recursion level held 200 x 300 KB = 60 MB under a
1 MB cap, while the same expression bound to a name was correctly refused.
Visit it. Removing the retention instead would be wrong today: Assign2 calls
rlm.DidUpdate with the block as base, which is truthful precisely because
the block holds the value.

Seven filetests, one per shape: each passes on the merge base and is refused
here. Plus TestGarbageCollect_VisitsAnchoredBuffer and
TestAllocatorAnchors_Unwind. No existing golden moves — anchors only matter
when a GC lands inside a fill, which no existing fixture does — and
BenchmarkOpCall_10Params_0Captures / BenchmarkOpCallWarm show no regression
above noise with alloc-gas unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm): rewrite the ADR for all three roots

The ADR described one root and filed the other two as follow-ups, one of
them ("pop-then-allocate windows") as "transient and bounded" and the other
(Block.Blank) under "not amplification vectors". Both were wrong, and both
are now closed, so rewrite rather than patch: context for each root with its
measurement, the anchor design and why the list sits on the Allocator, why
Block.Blank is counted rather than dropped, the alternatives that do not
cover the default fills, and what is left (all of it fail-safe now).

Also correct the txtar's scope note: it covers the array-literal form, and
the sibling shapes are covered as filetests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(gnovm): the pop-then-copy gap is not bounded; closed by the stacked PR

* fix(gnovm): keep operands GC-visible while composite literals and call args are copied

doOpSliceLit and friends popped their operands and then Copy'd each into a
Go-local destination, so a GC triggered by one of those copies saw neither
the operands nor the copies already made. With elements aliasing one value,
the stack held one object (counted once) while the heap grew N x its size
unseen: a 70-element slice literal built 595 MB under the 500 MiB tx cap.

Composite literals now push the new value as an anchor and read the
operands in place (pushAnchorPeek/popAnchored); call and defer args are
copied straight into the pushed block or a Defer already on the frame
(popCopyArgsInto). PopCopyValues, the shared pop-then-copy helper every
amplifiable site used, is removed.

Tests: alloc_15*_alias.gno pin each op; alloc_operand_stack.txtar gains the
aliased slice form. gas/nested_alloc moves +2987: same 54 GC cycles, the 26
that fire mid-literal now visit the anchored array.

* docs(gnovm): drop forward references to the stacked PR

* docs(gnovm): reflow the gap note; ADR drops the ordering note and names VM-owned stack growth

* test(gnovm): measure operand-stack GC gas on the real path; ADR names Block.Blank retention as a vector

* fix(gnovm): charge GC's linear slot walks per slot

GarbageCollect's walks over m.Values and Allocator.anchors inspect every
slot but only bump visitCount for slots carrying a .V, so a stack of
primitives is scanned for free: O(len) work that gcVisitGas never sees,
with len(m.Values) bounded only by gas (alloc_14 parks ~8192 slots from
~600 bytes of source at depth 128). Measured flat at 58 gas from 1K to
4M slots while wall time rises 4.8us -> 7.8ms.

Charge gcStackScanSlopeGas (4) per slot scanned, priced separately from
gcVisitGasTable: a slot scan is a sequential pass over a contiguous
[]TypedValue (~1.3-3.3 ns/slot per BenchmarkGCStackScan) rather than a
29-700ns pointer-chasing object visit, so folding it into the visit
table would overcharge by two orders of magnitude. The slope is a rough
developer-machine figure, not reference hardware; it sits just above the
measured maximum and matches OpCPUSlopeCopyPrimitive, the existing slope
for a comparable linear pass.

Goldens: gas/nested_alloc +424, gas/compute_map_key_big_bytes +4,
gas/compute_map_key_big_struct +36. Programs with shallow operand stacks
pay almost nothing; the charge tracks the depth actually scanned.

ADR: correct the Consequences figures. The +2987 quoted for
gas/nested_alloc was the stack-walk delta alone, not the series total,
and "+80 B per GC cycle" is not uniform (alloc_defer_gc moves +120, for
three live slots). Also record that visitCount does not cover nil-V
slots, which is why the scan needs its own charge.

* test(gno.land): update gc.txtar gas for the per-slot GC scan charge

The per-slot charge added in b2267dd60 moves this integration golden by
+36 (nine slots x gcStackScanSlopeGas), the same delta as
gas/compute_map_key_big_struct. It was missed because the gnovm filetests
and gno.land/pkg/sdk/vm were re-run but gno.land/pkg/integration was not.

Merging develop in first was necessary, not incidental: develop had already
moved this golden to 151131786 while this branch sat 57 commits behind, so
the value depends on develop's tree. Setting it from the branch alone would
have changed the same line develop changed and conflicted in the PR merge
tree GitHub actually tests. After the merge the local run reproduces CI
exactly (151131822).

Verified: gno.land/pkg/integration TestTestdata fully green,
gno.land/pkg/sdk/vm green, gnovm filetests unchanged (same 10 pre-existing
Go 1.26 type-check wording failures).

* fix(gnovm): anchor the map literal; locate the deferred func by NumArgs

Two gaps found by reviewing #96 against this branch.

doOpMapLit was the one composite-literal op the anchors did not cover.
It pops its operands and then copies each entry into a MapValue that is
still a Go local, so with the values all aliasing one package-level var
({0: a, 1: a, ...}) the popped sources are a single object while the
copies are N fresh allocations GC cannot see: 10 entries of a 300KB var
built 3MB under a 1MB cap, and 100 entries built 30MB, scaling linearly.
Same shape as the 560MB literal this series set out to refuse.

PushAnchor could not express it — a MapValue's entries are a linked list,
not a []TypedValue — so anchors now hold either a buffer or a whole
object (PushAnchorValue), and GC visits an object anchor through the
ordinary visitor. The map is anchored after the operands are popped on
purpose: pushing it onto the operand stack instead would overwrite
kvs[0], which PopValues leaves in place below the new top.

doOpDefer located the deferred func with m.PeekValue(len(Call.Args)+1),
but an embedded multi-value call leaves len(Args[0].Results) operands on
the stack (nodes.go: "len(Args) or len(Args[0].Results)"). So
`defer f(g())` bound the defer to one of g's results instead of f: with a
func-typed first result it silently deferred that closure, and with
scalar results it panicked "defer called a nil function". Use
ds.Call.NumArgs, which is what the preprocessor computed for exactly
this.

Tests: alloc_22_maplit.gno (fails without the map anchor, and the 100-entry
30MB variant is likewise refused) and defer_multivalue_call.gno, which
covers both the func-typed and scalar multi-result forms.

ADR: record the object anchor, and two gaps this series does not close —
doOpAssign destinations derived from popped LHS operands (IndexExpr /
SelectorExpr / StarExpr / CompositeLitExpr), where the miss is N and not
one in-flight copy; and doOpArrayLit's anchor being defence in depth
rather than a closed vector, since defaultArrayValue pre-charges the
destination at full size and no fixture covers its removal.

Verified: gnovm/pkg/gnolang -short, gno.land/pkg/integration TestTestdata
and gno.land/pkg/sdk/vm all green apart from the 10 pre-existing Go 1.26
type-check wording failures. No golden moved: no existing fixture GCs
inside a map fill.

* test(gnovm): correct alloc_15h's claim about doOpArrayLit's anchor

The file said "Regression: doOpArrayLit variant of alloc_15_slicelit_alias",
but it passes with that anchor removed: defaultArrayValue allocates
[10]Big at full size before the copy loop, so the 1MB cap trips at
construction and the anchored window is never reached. Say what it
actually covers, and record why no discriminating shape is known.

---------

Co-authored-by: ltzmaxwell <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Morgan Bazalgette <[email protected]>
aeddi pushed a commit that referenced this pull request Nov 17, 2026
Reconciles the master merge with the five PRs that landed on the fork's
develop in the meantime (#43, #96, #97, #31, #61). Master already carries all
five, so every conflict was the same shape: the fork's copy points at a
prxxxx_/pr43_ ADR that upstream stripped when it landed the code. Resolved to
master's wording in all four (alloc.go, machine.go, alloc_operand_stack.txtar,
alloc_15h_arraylit_alias.gno), keeping the tree byte-identical to master
outside .github/ and the ADRs themselves.

Verified: go build ./..., go vet ./gnovm/pkg/gnolang/, and the two conflicted
tests (TestTestdata/alloc_operand_stack, TestFiles/alloc_15h_arraylit_alias).
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