Skip to content

fix(statesync): bound retained snapshot discovery resources - #1492

Merged
lklimek merged 6 commits into
v1.8-devfrom
fix/issue-1475
Sep 22, 2026
Merged

lklimek merged 6 commits into
v1.8-devfrom
fix/issue-1475

Conversation

@lklimek

@lklimek lklimek commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: Bound snapshot discovery memory and work while preserving existing legal 4 MB snapshot messages.

User story

As a node operator, I want peers advertising snapshots to use bounded resources while still giving other peers a chance to help my node synchronize.

Scenario

Peers can currently send large snapshot advertisements that remain in memory, with no global limit or requirement for an outstanding request. The node should limit what it retains, ignore excess replies, and make bounded discovery attempts without discarding the snapshot it is restoring.

Detailed discussion

Issue being fixed or feature implemented

Fixes #1475 using the approved local retention and retry policy. No smaller application metadata limit is introduced.

What was done?

  • Own exact-sized Hash/Metadata copies and enforce 64 MiB globally, 40,000,000 bytes per peer, 1,024 retained snapshot objects, and 10,240 associations. Shared payload is charged once globally and per supplying peer. Peer removal releases association charges immediately; detached active data stays globally charged. Re-admission can create a second owned copy, charged separately until the old active copy is released. Empty indexes are removed; each rejection history is capped at 1,024 entries.
  • Pin the selected payload through removal, queue cleanup and canceled-fetcher joins. Pressure admission can evict unselected candidates from better-represented peers without trusting claimed heights.
  • Apply cheap quota/blacklist checks before hashing; use cached keys for ranking and active lookups. Accept at most ten response attempts per requested peer, counting duplicates/rejections; ignore unsolicited or exhausted responses without peer penalties.
  • Request batches of up to 16 peers from a frozen sweep of at most 1,024 peers. Peer joins use available slots, and subsequent sweeps rotate through larger connected-peer lists. Failed sends revoke allowances without renewing the batch budget. Copy peer enumeration under its lock.
  • Try retained candidates before declaring discovery exhausted. Count configured retries as completed bounded sweeps; new peer arrivals cannot extend an in-progress sweep. Document the limits and discovery timing.

How Has This Been Tested?

  • Base regressions were red for unbounded aggregate payload, backing-array ownership/mutation, and unsolicited advertisements.
  • A separate fetcher-lifetime regression was red before adding cancellation joins, then green.
  • Complete state-sync package with CGO/BLS, -p 1 -tags=deadlock: passed.
  • Pool/discovery regressions with -race -p 1 -tags=deadlock -count=3: passed. Covers near-4 MB serialized messages, shared accounting/removal, active pins, global/per-peer pressure, bounded bookkeeping, duplicate/late/failed replies, peer churn, and retries=1 completing a deferred-peer sweep and terminating without responses.
  • Final detached-active object-limit and same-snapshot re-admission regressions with -race -count=10: passed.
  • Repository-configured golangci-lint v2.13.2 on state-sync/config, filtered against the development base: 0 issues. goimports and diff checks passed.
  • Four self-review passes, zero unresolved in-scope findings.

Tests use bounded component fixtures; no full-network OOM or process-RSS benchmark was run. An independent pre-existing snapshot-key field-boundary ambiguity was observed and preserved for follow-up; snapshot identity is unchanged in this PR.

Breaking Changes

No wire, application-format, individual-message-size or persisted-format change. The approved local overload/discovery behavior intentionally changes: old rejection history can expire, unselected candidates can be evicted under pressure, and retries counts completed bounded discovery sweeps. A sweep can take up to ceil(min(peers, 1024) / 16) discovery intervals, with at least one interval. Existing legal messages remain valid, but overload can defer admission or reduce available suppliers. The 64 MiB bound covers retained pool payload, not total process RSS, transport/in-flight messages, chunks or application memory. Fair admission is not a guarantee against arbitrary Sybil dominance.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Co-authored by Claudius the Magnificent AI Agent

PR Hygiene · bcc3051

  • Bots — thepastaclaw ✓
  • Self-review — posted; again after any push
  • Within your 5 open PRs
  • Build green
  • Approvals — you own every area touched; none needed

When every box is checked the PR Hygiene check passes and this can merge.

Preserve legal 4 MB advertisements while enforcing owned payload budgets,
bounded accounting and request allowances. Keep active payload charged
through fetcher cleanup and rotate finite discovery sweeps under pressure.

Co-Authored-By: GPT-6 Astra <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
Clarify association release and separate global charges when the active
snapshot has been removed and another owned copy is admitted.

Co-Authored-By: GPT-6 Astra <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository: dashpay/tenderdash/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 0e9c0f55-6302-49d7-904c-9b222aa63e14

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Sep 21, 2026 •

Copy link
Copy Markdown

⚠️ DEGRADED — Final review complete — no blockers (commit bcc3051) · triage: normal · stand-in models (primary models out of quota)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Blacklisted peers can still consume discovery batch slots, and the generated configuration template documents stale retry semantics.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 Medium severity · 1 Low severity

Open (2)
What changed in this PR

Bounds retained snapshot memory, associations, bookkeeping, and discovery response work while preserving legal snapshot message sizes.

Changes:

  • Added bounded snapshot pool accounting, ownership, eviction, and active-snapshot pinning.
  • Added directed, allowance-limited discovery batches and fetcher cleanup synchronization.
  • Documented resource limits and updated discovery configuration comments.
File Description
internal/​statesync/​snapshots.go Pool limits and discovery accounting
internal/​statesync/​syncer.go Bounded requests and lifecycle cleanup
internal/​statesync/​reactor.go Response allowance enforcement
internal/​statesync/​dispatcher.go Safe peer-list copying
internal/​statesync/​snapshot_limits_test.go Pool limit regressions
internal/​statesync/​snapshot_discovery_test.go Discovery and lifetime regressions
internal/​statesync/​snapshot_unsolicited_test.go Unsolicited response regression
docs/​nodes/​state-sync.md Resource and discovery documentation
config/​config.go Retry and sweep semantics documentation

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread internal/statesync/snapshots.go Resolved
Comment thread config/config.go Resolved
@lklimek
lklimek marked this pull request as ready for review September 21, 2026 13:11
lklimek and others added 2 commits September 21, 2026 13:11
An advertisement with an empty hash was admitted at no byte cost, ranked
first by height, and made newChunkQueue fail, which shut the node down.
Reject it in the pool before hashing. Also log (at debug) advertisements
dropped by the discovery allowance and peers skipped by a full batch,
unify the pooled-key lookup, and tidy the new tests.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The config template and docs still described retries as a retry count
after it became the number of completed discovery sweeps. Document the
per-batch cost and that restoration starts from the first batch's best
snapshot.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 21, 2026
DiscoveryBatch reserved batch slots for rejected peers whose replies are
always discarded, wasting slots and discovery intervals. Skip them and
fill the batch from the remaining frozen-sweep peers.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ DEGRADED — Final validation — Phase 1 + Phase 2

⚠️ DEGRADED review. The primary review models were unavailable (gpt-6-astra unavailable: All credentials for model gpt-6-astra are cooling down (last error: usage_limit_reached: The usage limit has been reache), so this review ran on stand-in models: gpt-5.6-luna → muse-spark-1.3-contributor, gpt-5.6-sol → muse-spark-1.3-contributor, gpt-5.6-terra → muse-spark-1.3-contributor, gpt-6-astra → muse-spark-1.3-contributor. Both review phases and the independent verifiers still ran, but on weaker models, with Phase 1 capped at high effort. Treat the verdict as provisional; a full-strength re-review will run on the next push once the primary models are back.

PR #1492 bounds snapshot-discovery retention and discovery work as described; both Codex claims were verified against head bcc3051 and do not hold. Retained-bytes accounting stays balanced across detach, re-admission, and release, and the 16-slot request budget is the intentional bound. No in-scope defects remain.

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: tenderdash-consensus-security); reviewer 3: muse-spark-1.3-contributor (standing in for gpt-6-astra) (agent: phase2-reviewer, role: general); reviewer 4: muse-spark-1.3-contributor (standing in for gpt-6-astra) (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: muse-spark-1.3-contributor (standing in for gpt-6-astra) (agent: astra-verifier, role: final-verifier)

  • Degraded mode: gpt-6-astra unavailable: All credentials for model gpt-6-astra are cooling down (last error: usage_limit_reached: The usage limit has been reache (detected by probe, since 2026-09-20T20:45:34Z); stand-ins gpt-5.6-luna → muse-spark-1.3-contributor, gpt-5.6-sol → muse-spark-1.3-contributor, gpt-5.6-terra → muse-spark-1.3-contributor, gpt-6-astra → muse-spark-1.3-contributor; Phase 1 effort capped at high
  • Triage: normal by muse-spark-1.3-contributor (standing in for gpt-6-astra) (effort low) — Large intricate state-sync retention/discovery change touches snapshots.go/reactor but preserves wire format and changes no consensus, funds, crypto, deserialization, or migration surface.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer, glm-5.3-flash — tenderdash-consensus-security (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 85% left, weekly 93% left; passed over gemini-3.8-flash-high (lane failed)
  • Fresh verifier: muse-spark-1.3-contributor (standing in for gpt-6-astra) — final-verifier; agent astra-verifier
  • Phase 2 reviewers: muse-spark-1.3-contributor (standing in for gpt-6-astra) — general (completed, effort high); agent phase2-reviewer, muse-spark-1.3-contributor (standing in for gpt-6-astra) — tenderdash-consensus-security (completed, effort high); agent phase2-reviewer

@github-actions

Copy link
Copy Markdown

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Sep 21, 2026
@lklimek

lklimek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

/self-reviewed

@lklimek
lklimek enabled auto-merge (squash) September 22, 2026 09:07
@lklimek

lklimek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

/self-reviewed

@github-actions

Copy link
Copy Markdown

Policy satisfied — this can merge.
Full checklist in the description.

@github-actions github-actions Bot removed the waiting-self-review Waiting for the author to post /self-reviewed label Sep 22, 2026
@lklimek
lklimek merged commit 5bc95cd into v1.8-dev Sep 22, 2026
24 checks passed
@lklimek
lklimek deleted the fix/issue-1475 branch September 22, 2026 09:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

statesync: bound memory used by snapshot metadata

3 participants