Skip to content

fix(blocksync,p2p,service): fix concurrency bugs behind chronic CI flakes - #1340

Merged
lklimek merged 14 commits into
v1.6-devfrom
fix/ci-flaky-tests
Jun 15, 2026
Merged

lklimek merged 14 commits into
v1.6-devfrom
fix/ci-flaky-tests

Conversation

@lklimek

@lklimek lklimek commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

Why this PR exists

  • Problem: Three recurring CI "Test" failures long treated as flakes are actually real concurrency bugs in shared primitives.
  • What breaks without it: TestReactor_SyncTime wedges ~10% (permanent sync stall at height 1); internal/consensus panics possible deadlock when sending disconnected broadcast on slow runners; TestNodeNewSeedNode fails (Wait() returns before IsRunning() flips). Net: chronically red, untrustworthy CI.

What was done?

7 commits:

  • workerpool: serialize Start/Stop/Reset/Run under one lifecycle mutex — fixes a race where a Stop interleaving Run's Reset→Start left the pool "running" with zero workers; synchronizer.runHandler exits on ErrWorkerPoolStopped.
  • blocksync: drive runHandler off the synchronizer's OWN cancelable context — fixes the goroutine start-race (handler spawned in OnStart could die at birth because BaseService.Start sets running=1 only after OnStart returns) that wedged TestReactor_SyncTime, and the stop-time producer-goroutine leak (caught-up produceJob never observed ErrWorkerPoolStopped); deterministic monitor-interval test hook for the rate assertion.
  • p2p: key the PeerManager broadcast deadlock-guard on a new ErrBroadcastDeadlock sentinel — stops panicking on benign caller-ctx expiry while actually catching the real capacity-exhaustion deadlock it previously missed.
  • service: BaseService.Stop clears running=0 before cancel() so Wait() can't return while IsRunning() is still true.
  • docs: document the workerpool Send/Receive-vs-lifecycle concurrency invariant.

How Has This Been Tested?

-race: TestReactor_SyncTime 0/50 (was 5/50), TestNodeNewSeedNode 0/200, TestReactor_NoBlockResponse 15/15, new TestStopReleasesHandlers (leaktest, red-first/green-after), full internal/p2p suite green with 0 deadlock panics; go build ./..., go vet, gofmt, golangci-lint clean. Adversarially reviewed in two rounds — the first caught a goroutine-leak regression, now fixed and locked down by the leaktest.

Breaking Changes

None — internal concurrency fixes, no API/behavior change for callers.

Notes / follow-ups (pre-existing, not introduced here)

  • Latent (now documented, not enforced): workerpool Send/Receive must not run concurrently with Reset/Run/Stop.
  • BaseService cannot truly restart (never resets quit); a second Start on a stopped instance no-ops. Pre-existing.

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

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Fixed race condition in service state management that could cause incorrect status reporting during shutdown
    • Added deadlock detection for peer communications with improved error handling
    • Enhanced block synchronization with better resource cleanup and proper context cancellation
  • Improvements

    • Improved worker pool thread-safety for concurrent operations
    • Added customizable synchronizer configuration options

lklimek and others added 7 commits June 13, 2026 01:24
…r busy-spin

Reset() and Start() toggled the `stopped` atomic as separate, unsynchronized
operations, and workers are spawned only inside Start(). A Stop() interleaving
between the Reset->Start pair in Run() could make Start() early-return (the old
`if p.stopped.Swap(false) { return }`), leaving the pool with OPEN channels but
ZERO workers: jobs enqueue but never execute, every Receive() blocks forever, and
blocksync wedges.

- Add a single lifecycleMtx that serializes Reset/Start/Stop/Run so the
  Reset->Start pair in Run is atomic with respect to Stop. The mutex (the
  go-deadlock-aliased sync.Mutex already used in this file) is held only around
  state transitions; Stop's blocking waits (worker shutdown, wg.Wait) cannot
  self-deadlock because workers acquire no pool lock. Cold path (once per sync
  session), so tracking overhead is negligible.
- Remove Start's early-return; the invariant is now: after Run/Start returns the
  pool is either stopped OR has exactly initPoolSize live workers, never zero.
- synchronizer.runHandler now EXITS on ErrWorkerPoolStopped instead of logging
  and re-looping, killing the busy-spin / log-flood once the pool is stopping.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…expiry

The deadlock guards in PeerManager.Ready and Disconnected panicked when broadcast
returned an error matching context.DeadlineExceeded. But broadcast's only
DeadlineExceeded source is the caller's ctx.Err() — a benign expiry (e.g. a slow
CI runner blowing a test's WithTimeout). The REAL deadlock path (a subscriber
failing to drain within broadcastTimeout while the PeerManager mutex is held)
returned a plain fmt.Errorf the guard never matched. So the guard both
false-positived on benign expiry AND missed the case it was meant to catch.

- Introduce the errors.Is-able sentinel ErrBroadcastDeadlock and wrap it into the
  capacity-exhaustion error.
- Both guards now panic ONLY on ErrBroadcastDeadlock; caller ctx
  cancellation/expiry is logged at debug and skipped, no panic.
- Add regression tests: benign canceled-ctx broadcast does not panic; the
  sentinel is matchable and distinct from context.DeadlineExceeded.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Stop() called bs.cancel() — which closes the quit channel that Wait() blocks on —
BEFORE atomic.StoreUint32(&bs.running, 0). A goroutine in Wait() could therefore
unblock while IsRunning() still reported true, violating the documented contract
that "Wait blocks until the service is stopped".

Swap the two statements so running is set to 0 before cancel(), guaranteeing
IsRunning() is false by the time Wait() returns. OnStop() ordering is unchanged.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…-race wedge

OnStart spawns the producer/consumer goroutines (go runHandler ...) but
BaseService.Start only sets running=1 AFTER OnStart returns. A handler goroutine
scheduled in that window read IsRunning()==false and exited at birth, freezing
s.height at 1 forever — the dominant cause of TestReactor_SyncTime flakiness
("expected node to be partially synced" never satisfied). This is the start-side
twin of the BaseService.Stop ordering bug.

Loop on ctx.Err() == nil instead of s.IsRunning(). The context is already live
when OnStart runs, so there is no dependency on the running-flag timing. The two
exits remain correct and leak-free: full-reactor cancellation ends the loop via
ctx.Err(), and a manual synchronizer.Stop() ends it via the kept
ErrWorkerPoolStopped early-return (Send/Receive observe the stopped pool).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The assertion getLastSyncRate() > 0.001 raced the sync-rate filter: with the
default monitorInterval=100 the rate is only computed once the syncing node
reaches height ~101, so a slow run could blow the 10s window before the rate
became non-zero — a separate, rarer flake from the start-race wedge.

Add a WithSynchronizerOptions reactor option that forwards OptionFuncs to the
synchronizer built in OnStart, and use it in the test to set
WithMonitorInterval(10) so the rate computes after ~10 blocks. This makes the
assertion deterministic rather than widening the Eventually window.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The previous fix looped runHandler on the EXTERNAL reactor context, but OnStop
stops the worker pool without cancelling that context. On the common
switch-to-consensus path, poolRoutine calls synchronizer.Stop() while the parent
context is still live: consumeJobResult exits (Receive -> ErrWorkerPoolStopped),
but a caught-up produceJob keeps sleeping 50ms and returning nil — it never calls
Send, never sees ErrWorkerPoolStopped, and ctx.Err() stays nil. The producer
goroutine and its timer leaked for the entire consensus phase.

- OnStart derives s.ctx, s.cancel = context.WithCancel(ctx) and runs the worker
  pool + handlers under s.ctx. It is created live before the goroutines spawn, so
  the original goroutine start-race stays fixed without consulting IsRunning().
- OnStop calls s.cancel() before workerPool.Stop(), so cancellation releases both
  handlers even when the caller's context is still live.
- produceJob's idle wait now selects on ctx.Done() so a caught-up producer
  observes cancellation promptly instead of blocking on a bare sleep.

Add TestStopReleasesHandlers (leaktest) reproducing the exact leak: Stop() with a
live parent context and a caught-up job generator must release the handlers.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…riant

Send and Receive read jobCh/resultCh/doneCh locklessly while Reset/Run/Stop
reassign or close them under lifecycleMtx. This is safe today only because
callers serialize the lifecycle against in-flight Send/Receive (service
OnStart/OnStop). Document the invariant on WorkerPool so future callers do not
introduce a data race by overlapping them.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b592aa1d-bf1e-4e79-8483-005ca0fe227e

📥 Commits

Reviewing files that changed from the base of the PR and between 6b426dc and e51b688.

📒 Files selected for processing (9)
  • internal/blocksync/reactor.go
  • internal/blocksync/reactor_test.go
  • internal/blocksync/synchronizer.go
  • internal/blocksync/synchronizer_test.go
  • internal/p2p/peermanager.go
  • internal/p2p/peermanager_test.go
  • libs/service/service.go
  • libs/workerpool/worker_pool.go
  • libs/workerpool/worker_pool_test.go

📝 Walkthrough

Walkthrough

This PR hardens concurrency and lifecycle correctness across the blocksync stack. WorkerPool gains a lifecycleMtx to serialize Start/Stop/Reset transitions and fix a Stop/Send race. BaseService.Stop clears the running flag before cancel(). PeerManager adds an ErrBroadcastDeadlock sentinel to distinguish real deadlocks from benign context expiry during broadcasts. Synchronizer gains a cancelable context for handler goroutines and fixes jobProgressCounter accounting. Reactor exposes WithSynchronizerOptions to forward custom options into the constructed Synchronizer.

Changes

Concurrency & Lifecycle Fixes

Layer / File(s) Summary
WorkerPool lifecycle serialization and Stop/Send race fix
libs/workerpool/worker_pool.go, libs/workerpool/worker_pool_test.go
lifecycleMtx added; Start, Run, and Stop delegate to locked helpers; Stop waits on the in-flight WaitGroup before closing channels; public Reset introduced; regression test stresses Stop/Send overlap under -race.
BaseService.Stop: running flag cleared before cancel
libs/service/service.go
running atomic set to 0 before bs.cancel() so IsRunning() is already false when Wait() returns.
PeerManager ErrBroadcastDeadlock sentinel and benign broadcast handling
internal/p2p/peermanager.go, internal/p2p/peermanager_test.go
Exports ErrBroadcastDeadlock; broadcast() wraps it with subscriber info on timeout; Ready()/Disconnected() panic only on real deadlock and log-skip on other context errors; tests cover no-panic path and errors.Is compatibility.
Synchronizer cancelable context, counter balance, and handler loop
internal/blocksync/synchronizer.go, internal/blocksync/synchronizer_test.go
Adds ctx/cancel to Synchronizer; OnStart derives context and wires producer/consumer through runHandler; OnStop cancels context first; produceJob and consumeJobResult balance jobProgressCounter on all failure paths; runHandler loops on ctx.Err() and exits on ErrWorkerPoolStopped; two new tests verify goroutine shutdown and counter balance.
Reactor WithSynchronizerOptions forwarding
internal/blocksync/reactor.go, internal/blocksync/reactor_test.go
Adds synchronizerOpts field and WithSynchronizerOptions option to Reactor; OnStart appends stored opts to WithLogger before calling NewSynchronizer; test uses WithMonitorInterval(10) for a deterministic sync-rate assertion.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐇 A rabbit hopped in, found races afoot,
Locked the lifecycle, cancel to boot!
The counter stays balanced, the context stays true,
No deadlock shall panic — just log and skip through.
With options now threaded from Reactor on down,
This burrow runs tight — no goroutines to drown! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the primary objective: fixing concurrency bugs in blocksync, p2p, and service that caused CI flakes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ci-flaky-tests

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 and usage tips.

@lklimek
lklimek requested a review from Copilot June 13, 2026 19:35
@lklimek
lklimek marked this pull request as ready for review June 13, 2026 19:35
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 13, 2026 19:35

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.

Pull request overview

This PR addresses long-standing CI “flake” failures by fixing concurrency/lifecycle races across the workerpool, blocksync synchronizer/reactor, PeerManager broadcast deadlock detection, and BaseService shutdown ordering.

Changes:

  • Workerpool: serialize lifecycle transitions (Start/Run/Reset/Stop) under a dedicated mutex and document concurrency invariants.
  • Blocksync: drive handler goroutines from a synchronizer-owned cancelable context; make producer/consumer handlers exit cleanly on workerpool stop; add leak test and determinism hooks for monitor interval.
  • P2P/service: add an errors.Is()-matchable broadcast-deadlock sentinel and adjust BaseService.Stop ordering so Wait()/IsRunning() become consistent.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
libs/workerpool/worker_pool.go Adds lifecycle mutex + helpers to prevent Stop/Run interleavings; documents invariants.
libs/service/service.go Ensures running=0 is stored before cancel so Wait() and IsRunning() align.
internal/p2p/peermanager.go Introduces ErrBroadcastDeadlock sentinel and wraps broadcast timeout errors.
internal/p2p/peermanager_test.go Adds coverage for benign ctx expiry vs deadlock sentinel behavior.
internal/blocksync/synchronizer.go Switches handlers to synchronizer-owned context; exits loops on pool stop; refactors handler signatures.
internal/blocksync/synchronizer_test.go Adds leaktest to lock down Stop releasing handler goroutines.
internal/blocksync/reactor.go Adds reactor option forwarding to synchronizer construction.
internal/blocksync/reactor_test.go Makes sync-rate assertion deterministic via monitor interval option.
Comments suppressed due to low confidence (1)

libs/workerpool/worker_pool.go:282

  • resetLocked assumes p.workers is already allocated and indexed up to initPoolSize. If Stop() is called before the first Start()/Run() (so workers were never initialized), stopped becomes true and a subsequent Reset()/Run() will panic with an index-out-of-range/nil slice when writing p.workers[i]. Reset should be safe regardless of whether workers were previously started.
// resetLocked re-initializes channels and workers. The caller must hold lifecycleMtx.
func (p *WorkerPool) resetLocked() {
	if !p.stopped.Swap(false) {
		return
	}
	p.doneCh = make(chan struct{})
	p.jobCh = make(chan *Job, p.initPoolSize)
	p.resultCh = make(chan Result, p.initPoolSize*2)
	for i := 0; i < p.initPoolSize; i++ {
		p.workers[i] = newWorker(i, p.jobCh, p.resultCh, p.doneCh, p.logger)
	}
}

Comment thread internal/blocksync/synchronizer.go Resolved
Comment thread internal/p2p/peermanager_test.go Resolved
Comment thread internal/blocksync/synchronizer_test.go Resolved
lklimek and others added 4 commits June 13, 2026 22:01
…re paths

produceJob bumps jobProgressCounter before Send so a worker can't make the
counter go transiently negative (run + consumeJobResult decrement may land
before Send returns). But the only decrement lived in consumeJobResult, so any
path that failed to hand the job to a worker leaked the increment forever,
permanently inflating GetStatus's in-progress count.

Decrement on each failure path (nextJob error, Send error) so the increment is
always balanced. Add TestProduceJobFailureKeepsCounterBalanced covering both
the nextJob-error and stopped-pool Send paths, asserting GetStatus returns to
its baseline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The Start doc claimed it always leaves exactly initPoolSize live workers and
never zero-workers-with-open-channels. The code does not enforce that: starting
an already-started pool (no intervening Stop) spawns a second worker set over
the same channels and can panic on send-to-closed-channel during Stop. Reword
to document the precondition (no repeated/concurrent Start or Run without an
intervening Stop) rather than guarantee an invariant the code doesn't hold. No
logic change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
broadcast classifies a stall by which select arm wins, so a genuinely wedged
subscriber that races caller-context cancellation/expiry (caller ctx deadline <
broadcastTimeout) is reported as a benign ctx error and skipped — a false
negative. Detection is reliable only when the caller ctx has no deadline
shorter than broadcastTimeout; production callers currently pass a cancel-only
ctx with no deadline. Document this on ErrBroadcastDeadlock and at the Ready /
Disconnected guard sites. Classification logic unchanged (deferred to the
maintainer).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
TestPeerManager_Broadcast_BenignCtxExpiry hard-coded the subscription buffer
capacity (3), which silently breaks if broadcastSubscriptionChannelCapacity
changes. Derive the fill count from cap(sub.Updates()) so the test tracks the
real capacity.

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

lklimek commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator Author

Review-round update (Marvin + Copilot)

Pushed fixes addressing this round's findings:

  • CRITICAL (fixed) — jobProgressCounter leaked in produceJob on all three failure paths (nextJob error, Send ErrWorkerPoolStopped, Send other error), permanently inflating GetStatus()'s in-progress count. Fixed by undoing the increment on each failure path. The +1 deliberately stays before Send (a worker can execute the job and consumeJobResult can decrement before produceJob resumes — moving the increment after Send would drive the counter transiently negative). Covered by a new red-green test TestProduceJobFailureKeepsCounterBalanced (verified to fail when the fix is reverted).
  • Docs (honesty) — softened the workerpool Start doc from a false invariant to a stated precondition; documented broadcast deadlock detection as best-effort.
  • Test nits — deferred the leaktest; derive the broadcast buffer capacity from the actual channel instead of a hard-coded literal.

🧭 Maintainer decision (MEDIUM — deliberately NOT auto-fixed)

broadcast classifies a stall by which select arm wins: ctx.Done() ⇒ benign (logged + skipped), the 60s broadcastTimeout ⇒ ErrBroadcastDeadlock ⇒ panic. A genuine subscriber stall that races caller-ctx cancellation/expiry (ctx deadline < broadcastTimeout) is then misclassified as benign and skipped — a false negative for the very condition the panic exists to surface. Today's production callers pass a cancel-only ctx (no deadline), so the realistic trigger is "shutdown racing a real stall" — narrow, and still a net improvement over the prior backwards logic. It's documented as best-effort; the timer-independent redesign (classify by what blocked, not which arm won) is left to your call.

e2e (rotate) note

The pre-fix e2e (rotate) failed twice with two different silent stalls (startup vs mid-run) and no panic/stack in the logs — the new panic-guard did not fire. That points at the documented chronic e2e (rotate) flakiness rather than a deterministic regression; the counter-leak fix may also help catch-up under validator rotation. This run will tell.

🤖 Co-authored by Claudius the Magnificent AI Agent

@thepastaclaw

thepastaclaw commented Jun 15, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit e51b688)

Coverage disclosure: Claude general and Codex general both ran. Codex produced structured no-findings output, but the ACP process exited nonzero after targeted Go tests were blocked by the local sandbox/toolchain environment (repo requires Go 1.26.4; local was 1.26.2 and toolchain download was unavailable). Verifier used the Claude finding plus supplied CodeRabbit context; CodeRabbit had 0 inline findings and no concrete comment IDs for reactions.

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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Comment thread libs/workerpool/worker_pool.go Resolved
Comment thread internal/blocksync/synchronizer.go Resolved
Comment thread internal/blocksync/synchronizer.go Resolved

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

Code Review

Verified all five fixes against the actual diff: workerpool lifecycle mutex closes the Reset/Start vs Stop race; synchronizer's own ctx/cancel created before goroutine spawn eliminates the OnStart start-race wedge and the producer leak on stop-while-caught-up; ErrBroadcastDeadlock sentinel cleanly separates real subscriber stalls from benign caller-ctx expiry; BaseService.Stop ordering makes Wait()/IsRunning() consistent; produceJob now decrements jobProgressCounter on both failure paths. Pre-existing follow-ups are explicitly documented in the PR body and out of scope here.

Coverage note: Claude general reviewer and Claude verifier completed. Codex general also completed a source/diff review and found no in-scope issues, but exited nonzero after attempted targeted go test commands could not run because the pinned Go toolchain download required permission; no Tenderdash specialist prompts are configured in ~/Projects/skills, so this run used general reviewers only.

lklimek and others added 3 commits June 15, 2026 11:45
… shutdown logs

FIX 1 (HIGH) — worker_pool.go: Stop() held no lock around wg.Wait(), so a
Send() goroutine that slipped past the stopped.Load() gate could call
wg.Add(1) while Wait was executing, triggering:
  panic: sync: WaitGroup misuse: Add called concurrently with Wait
The fix wraps wg.Wait() in Stop() under wgMtx, matching Send()'s existing
wgMtx guard around wg.Add(1). Add and Wait are now mutually exclusive.

FIX 2 (LOW) — synchronizer.go produceJob(): context.Canceled/DeadlineExceeded
errors from nextJob() and workerPool.Send() were logged at Error level during
normal shutdown. They now undo the jobProgressCounter increment and return err
silently (matching the existing ErrWorkerPoolStopped path), keeping log output
clean during OnStop.

FIX 3 (LOW) — synchronizer.go consumeJobResult(): context.Canceled/
DeadlineExceeded from workerPool.Receive() were logged at Error level during
shutdown. They now return err silently alongside ErrWorkerPoolStopped.

REGRESSION TEST — TestWorkerPool_StopSendRace in libs/workerpool/worker_pool_test.go:
races 8 concurrent Sends against Stop() across 200 iterations. Confirmed RED
(panic: "sync: WaitGroup is reused before previous Wait has returned") without
FIX 1 and GREEN (ok, no races) with FIX 1 applied.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… produceJob ctx-cancel contract

produceJob now returns the context error directly on the nextJob path
(context.Canceled / DeadlineExceeded) instead of logging-and-returning-nil.
The "nextJob error" subcase therefore receives context.Canceled, not nil, so
the old conditional ErrorIs(err, ErrWorkerPoolStopped) was both stale in its
comment and wrong in its predicate.

Each subcase now carries a wantErr field and asserts unconditionally:
- "nextJob error": expects context.Canceled (pre-cancelled ctx hits nextJob path)
- "send to stopped pool": expects workerpool.ErrWorkerPoolStopped (Send path)

The counter-balance assertion is preserved unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@lklimek
lklimek requested a review from thepastaclaw June 15, 2026 10:53

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

Code Review

Verified the PR locally: five narrowly scoped concurrency fixes (workerpool lifecycleMtx + wgMtx-guarded Wait, synchronizer cancelable ctx + jobProgressCounter rebalancing, p2p ErrBroadcastDeadlock sentinel, BaseService.Stop ordering) are each paired with a targeted regression test. No blocking issues. One valid nitpick remains about TestWorkerPool_StopSendRace discarding *testing.T while its docstring overstates what -race contributes to the failure signal.

💬 1 nitpick(s)

Comment thread libs/workerpool/worker_pool_test.go Resolved
@lklimek
lklimek merged commit a0d701b into v1.6-dev Jun 15, 2026
16 checks passed
@lklimek
lklimek deleted the fix/ci-flaky-tests branch June 15, 2026 12:55
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.

3 participants