Repository navigation
feat: per-engine lifecycle and bounded concurrent tick - #59
Merged
Merged
Conversation
Add a per-managed-engine lifecycle wrapper (managedEngine) that closes a stale-checkpoint-write race that would arise when parallelising Tick(), and introduce bounded cross-engine concurrency via SHUNT_MAX_CONCURRENT_RECONCILES (default 1 — exact serial behaviour preserved). ## The race Refresh() replaces *Engine instances when a repo's .shunt.yml changes or when a topic search no longer discovers a repo. Previously the replacement happened by immediate map assignment with no drain, safe only because Refresh and Tick ran sequentially in the same goroutine. With concurrent goroutines inside Tick() a stale goroutine could call saveCheckpoint() after the new engine had already loaded its checkpoint under the same (owner, repo, base) key. ## The fix Each managedEngine now carries: - lifetimeCtx / stop: Refresh cancels this context before replacing or removing the engine, prompting any in-flight Reconcile to exit at its next ctx.Err() check. - mu (sync.Mutex): held for the duration of each Reconcile call. Tick uses TryLock (at-most-one invariant, logs a warning on failure). Refresh uses Lock+Unlock to drain — blocking until any in-flight Reconcile returns before touching the map. drain() = stop() + mu.Lock()/mu.Unlock() provides the cancel-then-wait guarantee. ## Context propagation Each Reconcile call derives its context from both the caller's (process shutdown) context and the engine's lifetimeCtx via context.WithCancel + context.AfterFunc. Either a SIGTERM or an engine replacement cancels in-flight work promptly. ## Bounded concurrency Tick() now uses golang.org/x/sync/errgroup (already an indirect dep). SetLimit(maxConcurrent) serialises goroutines when maxConcurrent == 1 — each eg.Go() blocks until the previous goroutine finishes, preserving the exact serial schedule of the old for loop. eg.Wait() ensures Tick() always blocks until all goroutines have returned, so Refresh() on the next cycle is always safe. New env var: SHUNT_MAX_CONCURRENT_RECONCILES (default 1). ## Tests Five new tests in internal/manager/manager_test.go using a fakeReconciler (blocking on channel gates): - TestTickAtMostOneConcurrentReconcilePerEngine: TryLock skips second Tick. - TestRefreshDrainsBeforeReplacement: drain() blocks until Reconcile returns. - TestTickConcurrentDifferentEngines: N engines start concurrently with SetLimit(N), verified by all N sending to a buffered channel before any returns. - TestTickShutdownCancelsInFlightReconciles: ctx cancellation unblocks Tick. - TestTickEngineReplacementCancelsReconcile: drain() cancels via lifetimeCtx. go test -race ./internal/manager/... ./internal/engine/...: clean. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this changes
Adds a per-managed-engine lifecycle wrapper (
managedEngine) that closes a stale-checkpoint-write race, and introduces bounded cross-engine concurrency viaSHUNT_MAX_CONCURRENT_RECONCILES(default1— exact serial behaviour preserved).The race this closes
Refresh()replaces*Engineinstances when a repo's.shunt.ymlchanges or when a topic search no longer discovers a repo. Previously the replacement happened by immediate map assignment — safe only becauseRefreshandTickran sequentially in the same goroutine. The momentTick()spawns goroutines that outlive the loop itself, a stale goroutine could callsaveCheckpoint()after the new engine has already loaded its checkpoint under the same(owner, repo, base)key — silent state corruption.Mechanism
Each
managedEnginenow carries:lifetimeCtx/stop:Refreshcallsstop()before replacing or removing the engine, prompting any in-flightReconcileto exit at its nextctx.Err()check (viacontext.AfterFuncpropagation).mu sync.Mutex: held for the duration of eachReconcilecall.TickusesTryLock(at-most-one-per-engine invariant, logs a warning on failure).RefreshusesLock+Unlockto drain — blocking until any in-flight call returns before touching the map.drain()=stop()+mu.Lock()/mu.Unlock()provides the cancel-then-wait guarantee.Default behaviour is provably unchanged
Ticknow usesgolang.org/x/sync/errgroup(already an indirect dep) withSetLimit(maxConcurrent). WhenmaxConcurrent == 1(the default):eg.Go()call blocks until the previous goroutine finishes — serial.eg.Wait()blocks until the final goroutine returns —Tickalways completes before returning, soRefreshon the next cycle is always safe.Σ(reconcile_i), identical to the oldforloop.Context propagation
Each
Reconcilecall derives its context from both the caller's (process shutdown) context and the engine's ownlifetimeCtxviacontext.WithCancel+context.AfterFunc. Either a SIGTERM or an engine replacement cancels in-flight work promptly.Test evidence
Five new tests in
internal/manager/manager_test.gousing afakeReconciler(blocking on channel gates):TestTickAtMostOneConcurrentReconcilePerEngineTryLockcauses secondTickto skip, not double-callTestRefreshDrainsBeforeReplacementdrain()blocks untilReconcilereturns (no stale write after replacement)TestTickConcurrentDifferentEnginesSetLimit(N)and N engines, all N start before any returns (wall-clock parallel)TestTickShutdownCancelsInFlightReconcilesctxunblocks all in-flight reconciles andTickreturns promptlyTestTickEngineReplacementCancelsReconciledrain()cancels vialifetimeCtxeven with a live process contextRace detector:
go test -race ./internal/manager/... ./internal/engine/...— clean.