Skip to content

feat: per-engine lifecycle and bounded concurrent tick - #59

Merged
rbtr merged 1 commit into
mainfrom
feat/reconcile-fairness
Jul 22, 2026
Merged

rbtr merged 1 commit into
mainfrom
feat/reconcile-fairness

Conversation

@rbtr

@rbtr rbtr commented Jul 22, 2026

Copy link
Copy Markdown
Owner

What this changes

Adds a per-managed-engine lifecycle wrapper (managedEngine) that closes a stale-checkpoint-write race, and introduces bounded cross-engine concurrency via SHUNT_MAX_CONCURRENT_RECONCILES (default 1 — exact serial behaviour preserved).

The race this closes

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 — safe only because Refresh and Tick ran sequentially in the same goroutine. The moment Tick() spawns goroutines that outlive the loop itself, a stale goroutine could call saveCheckpoint() after the new engine has already loaded its checkpoint under the same (owner, repo, base) key — silent state corruption.

Mechanism

Each managedEngine now carries:

  • lifetimeCtx / stop: Refresh calls stop() before replacing or removing the engine, prompting any in-flight Reconcile to exit at its next ctx.Err() check (via context.AfterFunc propagation).
  • mu sync.Mutex: held for the duration of each Reconcile call. Tick uses TryLock (at-most-one-per-engine invariant, logs a warning on failure). Refresh uses Lock+Unlock to 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

Tick now uses golang.org/x/sync/errgroup (already an indirect dep) with SetLimit(maxConcurrent). When maxConcurrent == 1 (the default):

  • Each eg.Go() call blocks until the previous goroutine finishes — serial.
  • eg.Wait() blocks until the final goroutine returns — Tick always completes before returning, so Refresh on the next cycle is always safe.
  • The total execution time is Σ(reconcile_i), identical to the old for loop.

Context propagation

Each Reconcile call derives its context from both the caller's (process shutdown) context and the engine's own lifetimeCtx via context.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.go using a fakeReconciler (blocking on channel gates):

Test Verifies
TestTickAtMostOneConcurrentReconcilePerEngine TryLock causes second Tick to skip, not double-call
TestRefreshDrainsBeforeReplacement drain() blocks until Reconcile returns (no stale write after replacement)
TestTickConcurrentDifferentEngines With SetLimit(N) and N engines, all N start before any returns (wall-clock parallel)
TestTickShutdownCancelsInFlightReconciles Cancelling caller's ctx unblocks all in-flight reconciles and Tick returns promptly
TestTickEngineReplacementCancelsReconcile drain() cancels via lifetimeCtx even with a live process context

Race detector: go test -race ./internal/manager/... ./internal/engine/... — clean.

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>
@rbtr
rbtr merged commit cad481d into main Jul 22, 2026
4 checks passed
@rbtr
rbtr deleted the feat/reconcile-fairness branch July 22, 2026 17:06
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.

1 participant