Skip to content

fix(statesync): unblock chunk delivery during sync teardown - #1489

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

lklimek merged 4 commits into
v1.8-devfrom
fix/issue-1429

Conversation

@lklimek

@lklimek lklimek commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: State sync can stop or retry when incoming snapshot data has filled its delivery buffer.

User story

As a node operator, I want state sync to stop cleanly or retry a snapshot without leaving my node stuck.

Scenario

A peer delivers snapshot data faster than the application consumes it. If synchronization is canceled or the application rejects or retries the snapshot, cleanup currently waits indefinitely for the blocked delivery. Closing the queue concurrently can also panic. The change lets those deliveries finish and allows cleanup or retry to proceed.

Detailed discussion

Issue being fixed or feature implemented

Fixes #1429.

What was done?

Each sync attempt owns a cancellation context for chunk deliveries. Teardown cancels deliveries before acquiring the write lock that waits for them to finish. A separate queue-closed signal wakes blocked producers and consumers without closing a channel that can still have senders. Consumers verify queue lifetime under the file-access mutex. Snapshot retry drains buffered IDs from the completed attempt before resetting their status, preventing stale IDs from producing nil chunks.

How Has This Been Tested?

  • Confirmed the original cancellation regression and full-buffer application abort, rejection, and retry tests fail on the original implementation.
  • Verified the buffered retry defect separately against unchanged base code.
  • State-sync package tests with CGO/BLS, -p 1 -tags=deadlock: passed.
  • New teardown, repeated retry, Close/Add, blocked Next, and buffered Next/Close regressions with -race -p 1 -tags=deadlock -count=100: passed.
  • Repository-configured golangci-lint v2.13.2 on the state-sync package, filtered against the development base: 0 issues. goimports and diff whitespace checks passed.
  • Three self-review passes; zero unresolved in-scope findings.

These are component-level tests using mocked application calls and real queue/concurrency paths; no whole-process SIGTERM test was run.

Breaking Changes

None. No wire, public API, configuration, persisted format, or accepted application-data changes. Backpressure stays bounded, and snapshot retry keeps its existing re-request behavior.

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

Documentation change is the internal retry lifecycle comment; no user-facing configuration or API documentation changes are needed.

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 · 630a8a2

  • 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.

Cancel attempt deliveries before waiting on the syncer write lock, signal
queue closure without closing the channel used by concurrent senders, and
discard buffered IDs before resetting a snapshot retry.

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: 55d3e59e-0914-40f8-827a-380c82e48168

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.

@lklimek
lklimek marked this pull request as ready for review September 21, 2026 09:47
@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

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

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 21, 2026
@thepastaclaw

thepastaclaw commented Sep 21, 2026 •

Copy link
Copy Markdown

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

@lklimek lklimek left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

LGTM

@lklimek
lklimek enabled auto-merge (squash) September 21, 2026 10:04

@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.

Teardown fix is correct on its main path: per-attempt chunk context cancelled before the write lock, separate closed signal instead of closing applyCh, Next rechecks lifetime under lock, and RetryAll drains stale IDs. Two in-scope suggestions remain: a narrow post-drain race can still re-enqueue a stale ID and return (nil, nil) from Next, and cancelled deliveries log as errors on clean teardown.

🟡 2 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🟡 Suggestion: Context-cancelled deliveries surface as errors on clean teardown
internal/statesync/syncer.go:111-118

The new queue.add select returns ctx.Err() when chunkCtx is cancelled during teardown. AddChunk swallows only errNilSnapshot and propagates the context error to handleChunkMessage (reactor.go:1099-1106), which logs it at Error level. A delivery racing Sync cancellation is expected shutdown, not a failure, so it adds error noise and makes the new return path look like a fault.

	added, err := s.chunkQueue.add(s.chunkCtx, chunk)
	if err != nil {
		if errors.Is(err, errNilSnapshot) {
			s.logger.Error("Can't add a chunk because of a snapshot is nil", keyVals...)
			return false, nil
		}
		if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
			s.logger.Debug("Ignoring chunk delivered during sync teardown", keyVals...)
			return false, nil
		}
		return false, err
	}

source: muse-spark-1.3-contributor (phase1-reviewer: general)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (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) — Concurrency and teardown fix in statesync chunk queue is ordinary logic requiring review but does not change consensus rules, funds, crypto, network deserialization, or migrations.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort high); agent phase1-reviewer, muse-spark-1.3-contributor — tenderdash-consensus-security (completed, effort high); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (lane failed), glm-5.3-flash (zai below 15% reserve: 5h 100% left, weekly 13% left)
  • 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
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `internal/statesync/chunks.go`:
- [SUGGESTION] internal/statesync/chunks.go:330-340: Residual race: cancelled producer can still enqueue a stale ID after RetryAll drain, yielding nil chunk panic
  chunkQueue.add (lines 212-218) selects on send vs ctx.Done() vs closed with uniform random choice when multiple cases are ready. Sync cancels chunkCtx before SyncAny calls RetryAll, which drains applyCh and resets received/done items to init. A producer blocked on a full buffer that is not scheduled between cancel and drain sees both send (buffer now has space) and ctx.Done() (closed) ready, and the send can win. That ID then refers to an initStatus item, so load() returns (nil, nil) and Next() returns (nil, nil) with done marked; applyChunks in syncer.go dereferences chunk.ID with err==nil and panics. Narrow window and availability-only (statesync node is not yet a consensus participant), but it directly undercuts this PR's stated stale-ID fix and is newly reachable via the cancellable send.

In `internal/statesync/syncer.go`:
- [SUGGESTION] internal/statesync/syncer.go:111-118: Context-cancelled deliveries surface as errors on clean teardown
  The new queue.add select returns ctx.Err() when chunkCtx is cancelled during teardown. AddChunk swallows only errNilSnapshot and propagates the context error to handleChunkMessage (reactor.go:1099-1106), which logs it at Error level. A delivery racing Sync cancellation is expected shutdown, not a failure, so it adds error noise and makes the new return path look like a fault.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Pre-existing deterministic nil-chunk panic via per-chunk Discard/Retry of a still-buffered ID — Independent of the new race: applyChunks honors app-driven RefetchChunks/RETRY via Discard()/Retry(), which reset an item to discarded/initStatus while its ID may still sit buffered in applyCh. A later Next() pops that ID, load() returns (nil, nil) for non-received status, and Next() returns (nil, nil), panicking applyChunks on chunk.ID. A malicious ABCI app can trigger this deterministically. Predates this PR (RetryAll drain fixes only the retry-all variant).
    • Follow-up: Create a separate issue/PR to make Next() skip stale buffered IDs (loop until a loadable chunk or closed/timeout) and/or generation-guard Discard/Retry against IDs already queued in applyCh.

Comment thread internal/statesync/chunks.go Resolved
Treat canceled and expired sync contexts as expected delivery termination.
Cover both errors and retry immediately after Sync returns to verify the
producer barrier without an extra test-side join.

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

@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 — Re-review — 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.

Teardown fix verified at head: cancelled deliveries return false/nil with Debug log, and the alleged post-drain stale-ID race is excluded by the syncer RLock/Lock barrier so RetryAll cannot overtake an in-flight producer. No in-scope defects remain.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

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); reviewer 5: muse-spark-1.3-contributor (standing in for gpt-6-astra) (agent: phase2-reviewer, role: general); reviewer 6: 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) — Concurrency/teardown fix for chunk delivery buffering is an ordinary logic change that does not itself alter consensus rules, funds, crypto, network deserialization, or migrations.
  • 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 99% left, weekly 99% left; passed over gemini-3.8-flash-high (lane failed)
  • Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • 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, 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
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

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

🔵 Needs a closer look

Two moderate unresolved issues remain in internal/statesync/chunks.go.

Review effort: Lite
Findings: None

What changed in this PR

Fixes state-sync teardown and retry hangs by making chunk delivery cancellable and queue shutdown safe.

Changes:

  • Adds per-attempt cancellation for chunk producers.
  • Signals queue closure without closing active channels.
  • Drains stale retry IDs and adds concurrency regression tests.
File Summary Findings
internal/​statesync/​syncer.go Coordinates chunk-delivery cancellation during teardown. None
internal/​statesync/​shutdown_test.go Adds teardown, retry, close, and cancellation regression tests. None
internal/​statesync/​chunks.go Makes queue delivery teardown-safe and drains retry state. Two moderate issues remain involving producer completion during retry and Add racing with Close.

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

@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
Use the queue passed to fetchChunks instead of the lock-guarded syncer field
when re-enqueueing chunks, so fetchers cannot race with releaseChunkQueue.
Correct AddChunk, errDone, closed and chunkCtx documentation, simplify the
RetryAll drain loop, and assert the closed-queue error type in the tests.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Sep 21, 2026
@lklimek

lklimek commented Sep 21, 2026

Copy link
Copy Markdown
Collaborator Author

/self-reviewed

@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 — Re-review — 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.

Teardown fix is sound at this head: per-attempt cancellable deliveries plus a separate closed signal remove the full-buffer hang and send-on-closed panic, with lock ordering that forces in-flight producers to settle before RetryAll drains. No in-scope defects remain; one residual ABCI-triggered nil-chunk path is tracked separately as pre-existing hardening.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

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); reviewer 5: muse-spark-1.3-contributor (standing in for gpt-6-astra) (agent: phase2-reviewer, role: general); reviewer 6: 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) — Concurrency teardown fix in statesync queue/syncer logic is an ordinary logic change that does not itself alter consensus rules, funds, crypto, network deserialization, or migrations.
  • 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 87% left, weekly 98% left; passed over gemini-3.8-flash-high (lane failed)
  • Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • 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, 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
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Next() can return (nil, nil) for a buffered ID discarded before consumption, panicking applyChunks — Outside this PR's teardown scope and pre-existing: chunkQueue.Discard() resets status and removes the file but cannot remove an ID already buffered in applyCh. A later Next() load() yields (nil, nil) for that non-received ID, yet Next() marks it done and returns (nil, nil) with nil error, and applyChunks then dereferences chunk.ID. Only trigger is an ABCI ResponseApplySnapshotChunk listing a still-buffered ID in RefetchChunks, so statesync-only availability, not remote BFT safety.
    • Follow-up: File a separate issue for a fail-closed guard in Next()/applyChunks on nil loaded chunk plus a regression covering Discard of a buffered ID.

@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

@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 7f3d3af into v1.8-dev Sep 22, 2026
21 checks passed
@lklimek
lklimek deleted the fix/issue-1429 branch September 22, 2026 06:17
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: chunkQueue.Add can deadlock graceful shutdown while holding syncer.mtx

3 participants