Skip to content

update to go 1.17 - #35

Closed
faddat wants to merge 2 commits into
gnolang:masterfrom
notional-labs:117
Closed

faddat wants to merge 2 commits into
gnolang:masterfrom
notional-labs:117

Conversation

@faddat

@faddat faddat commented Oct 24, 2021

Copy link
Copy Markdown
Contributor

Hi, I noticed in the commit log that you were hunting some Facebook dependencies.

@jaekwon could you please let me know if you'd like me to dig through and figure out how to get those gone?

Go 1.17 makes it much easier to identify & get rid of indirect imports by putting them directly in go.mod so that you don't need to hunt through go.sum for them!

:)

-Jake

@faddat

faddat commented Jan 10, 2022

Copy link
Copy Markdown
Contributor Author

Seems this is complete.

@faddat faddat closed this Jan 10, 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
…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(gnoweb): block entity-encoded dangerous URL scheme in rendered links

* update ADR

* update test case

* fix(gnoweb): resolve link destinations before classifying and validating

The dangerous-scheme check was not the only consumer of a raw markdown
destination. Two others read the unresolved bytes and reached the wrong
conclusion, because goldmark resolves entity references on the way out:

  - The link classifier parsed the raw destination, so
    `[x](&#x68;ttps://evil.example/p)` was typed as a relative path and
    rendered without rel="noopener nofollow ugc" and without the
    external-link icon, while the href still resolved to a working
    foreign URL. A reader lost the only signal that the link leaves
    gno.land.
  - The image validator saw the raw bytes too, so
    `![i](&#x64;ata:image/png;base64,...)` passed the allowSvgDataImage
    policy that exists to reject every data: URI but image/svg+xml.

Route all three consumers through one resolveDestination helper so none
of them can decide from bytes the renderer will later rewrite. A
destination whose resolved form net/url refuses to parse (an
entity-encoded C0 control) is now typed invalid and dropped rather than
emitted as a broken relative href.

Also cover the octal numeric-reference spelling: goldmark decodes
`&#152;` to 'j' because it parses the reference with
strconv.ParseUint base 0, which makes a leading zero octal.

* fix(gnoweb): stop the alert parser pinning the markdown reader

`>>>>>` followed by a TAB — six bytes — made gnoweb's markdown renderer
allocate until it was OOM-killed. Upstream goldmark renders the same input
in microseconds; loading ExtAlerts alone was enough to trigger it, and any
realm can return those bytes from Render.

alertParser.process ended with `reader.SetPadding(2)` when the `>` marker
was followed by a tab. Two things are wrong with that.

process is called from Open before the `[!KIND]` regex decides whether the
line is an alert at all, so when the regex fails and Open returns
NoChildren, the padding stays set for whichever parser handles the line
next. A block parser that declines to open must leave the reader as it
found it.

And the padding is wrong in kind. goldmark's blockquoteParser consumes the
tab and sets padding to the remainder of the tab stop; setting a fixed
padding without consuming the tab leaves the reader on the same byte, and
Advance spends padding units before it touches pos.Start. The blockquote
parser's advance is absorbed, its Open succeeds on the byte it already
handled, HasChildren sends parser.openBlocks back to `retry`, and the loop
appends an ast.Blockquote per pass forever. Traced, the reader sits at
segStart=4, peek=">\t" indefinitely.

This was not only a DoS. Because alerts are always loaded in production, a
plain `>` + TAB blockquote rendered as a literal code block containing the
marker, where goldmark alone gives `<blockquote><p>body</p></blockquote>`.
Tab-indented alert bodies were mangled the same way. No golden covered a
tab after `>`, which is presumably why it went unnoticed.

Make process pure and move marker consumption into consumeMarker, called
from Continue, mirroring blockquoteParser.process byte for byte — the two
parsers share the `>` trigger and alternate on nested lines, so they have
to agree on how far a marker advances the reader.

No existing golden changed.

* fix(gnoweb): advance alert titles by byte position, not indent width

Review follow-up on the reader-pin fix. Two things.

alertHeaderParser.Open advanced past the gap between `]` and the title with
`w, _ := util.IndentWidth(...)` / `reader.Advance(w)`. IndentWidth returns a
width in COLUMNS and a position in BYTES; a tab there is one byte but three or
four columns, so advancing by the width ate title bytes. `> [!NOTE]\ttitle`
rendered as `tle`, and `> [!WARNING]\t` — tab as the last byte on the line —
advanced past the newline and pulled the following line up into the summary.
Advance by the byte position instead. New golden fixture
ext_alerts/valid_tab_title.md.txtar pins all three cases; no existing golden
changed.

This predates the reader pin, but it is the same class of mistake in the same
tab arithmetic, so it is fixed here rather than filed separately.

The two unit guards also gained a starting offset. The padding that pinned the
reader was only set when the byte AFTER a `>` was a tab, so on `>>>>>\t` it
fired at the innermost marker — the `>>>>>\t` case named after the payload
started at offset 0, never reached that branch, and passed with the bug
reintroduced. Only `>\tnot an alert\n` was load-bearing. With `at: 4` and a
`>\t[!NOTE]` case, three subcases now fail on regression instead of one.

* fix(gnoweb): measure the alert marker offset from the line start

Review follow-up on the tab arithmetic. Two more offset bugs of the same shape
as the title one, both predating it.

`process` computed its advance relative to `pos`, the indent position, but
returned it as though it were relative to the start of the line, and `Open`
sliced `line[advanceBy:]` with it. Any leading indent stayed in the slice, the
`[!KIND]` regex missed, and the alert silently degraded to a plain blockquote:
`  > [!NOTE] x` was not an alert. CommonMark allows a block start to be
indented up to three columns, and `consumeMarker` accepts exactly that on every
continuation line, so the two halves of the same parser disagreed about what a
marker looks like. The same slice bug hid alerts behind a tab-padded outer
blockquote (`>\t> [!NOTE] x`), where the padding arrives as leading spaces from
`PeekLine`. Return the offset from the line start instead; it is also the right
argument for `reader.Advance`, which spends reader padding before it touches
real bytes, so indented and padding-prefixed markers both work out. Four
columns is still an indented code block, not an alert.

`alertHeaderParser.Open` trimmed the line terminator by testing only for `\n`,
which leaves a lone `\r` behind on CRLF input. A `\r` is not empty, so it
counted as a title and suppressed the default kind label: `> [!NOTE]\r\n`
rendered a `<summary>` with no text where `> [!NOTE]\n` renders `Note`. Nothing
between a realm's `Render` output and goldmark normalizes line endings, so this
is reachable from chain data; plain goldmark strips the `\r` itself, which is
why only the alert summary showed it. Trim with `bytes.TrimRight` and subtract
the bytes removed, so any reader padding stays accounted for.

Also drop a dead `segment` assignment that was overwritten before being read,
and locate the `]` inside the subline the regex matched rather than scanning
the whole line, which drops a `string(line)` conversion.

New golden `ext_alerts/valid_indented_marker.md.txtar` pins one, two and three
columns of indent, the tab-padded nested marker, an indented continuation line,
and four columns staying a code block. `TestAlertProcessOffsetIncludesIndent`
pins the offset itself, and `TestAlertTitleTerminatorTrimmed` covers CRLF as a
unit test rather than a golden because txtar round-tripping and git checkout
normalization both eat lone `\r` bytes. Verified both new guards and the new
golden fail when either fix is reverted. No existing golden changed.

Widening what opens an alert widens the surface the reader pin lived on, so the
earlier sweeps were re-run against this: ~598k inputs differentially against
plain goldmark and ~814k token-level inputs through the full production
extension stack, checked for non-termination and output blowup. Clean on both.
Full `gno.land/pkg/gnoweb/...` green.

* chore(gnoweb): regenerate main.css after the alert parser change

`make -C gno.land/pkg/gnoweb generate` is part of CI's contract, and the
generated bundle depends on Go sources: purgecss (frontend/postcss.config.cjs)
scans `../**/*.go` with an extractor that matches any word-shaped token,
comments included.

`ext_alert_test.go` documents that consumeMarker "must make forward progress",
and `progress` is now the only occurrence of that token anywhere under
gno.land/pkg/gnoweb. Purgecss therefore keeps the `progress` normalize rule
alive where it previously stripped it, and public/main.css grows by one rule
(33 bytes). Regenerate so the committed artifact matches its sources again.

---------

Co-authored-by: Lee ByeongJun <[email protected]>
alexiscolin added a commit to alexiscolin/gno that referenced this pull request Nov 27, 2026
A line starting with an entity code such as gnolang#35; or #quot; was dropped
as a comment, and its continuation lines went to the period before it.
Only a # that starts no entity code begins a comment line.
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.

2 participants