carlos / platform Public

console: coalesce copies kicks per fleet; bound the lock wait (#1061 r1)

Astra round 1 on Task 3. P2: every copies write started a goroutine
that waited on the fleet lock without limit, so a burst behind a slow
pass or drain could pile them up. Kicks now coalesce per fleet: at most
one run in flight, and a kick during it only marks the fleet dirty. The
run clears the mark when it takes the lock and reads its view, and goes
round once more only for kicks after that. The fleet lock is taken by
TryLock, retried until the run's two-minute deadline; a run that gives
up logs once and leaves the work to the next pass. The app's placement
row is now read before the run starts, so the coalescing key is the
fleet.

P3: the kick test released the fleet lock only on the happy path; it
now releases it once, deferred to cleanup as well. A new test holds the
lock across four copies writes and sees one run start and exactly one
reconcile after release.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ba04880192b1a6f58686daca2488bb7d1f5eff89 parent c4ae218
3 files changed, +172 −30
  • internal/console/replicakick_test.go +56 −2
  • internal/console/replicaplacement.go +106 −25
  • internal/console/server.go +10 −3

Intent

Human

<task-notification> <task-id>a17b099a61041ff5d</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2b517942-2259-467d-a8d0-994fd28c9e84/tasks/a17b099a61041ff5d.output</output-file> <status>completed</status> <summary>Agent "Implement #1061 Task 3" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE Commit: c4ae2184 console: place raised copies now, not at the next relabel pass (#1061) Tests: the new test failed first (no assignment written), then passed. The targeted set `Replica|Copies|Placement|FleetRelabel` passes (232 s), and so does `TestClaimConsoleMutationInvariant` (382 s). I did not run the full console package; CI covers it. Lowering: `reconcileReplicaFleet` already retires extra copies, so the kick runs after every successful copies write. No removal logic was added. Concerns: - **Kick is off in most copies tests.** `copiesWorld` turns it off with a test-only switch, `replicaKickOff`, because 8 existing tests run placement passes themselves and failed with it on. Only the new test and other fixtures run with the kick on. - **The census test needed an entry.** I added the new `AppPlacement` caller to `placement_census_test.go`; without it that test fails. - **The function signature differs from the brief.** It is `kickReplicaPlacement(account, app)` rather than `(fleet)`, so it finds the app's fleet in the background goroutine, not while the request is still running. - **The fleet lock wait is not time-limited.** It ignores the 2-minute deadline, as in the 5-minute pass. If the app is locked when the kick runs, it is skipped until the next pass. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/sr-followups/.superpowers/sdd/plan-1061/task-3-report.md</result> <usage><subagent_tokens>115735</subagent_tokens><tool_uses>46</tool_uses><duration_ms>1882178</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bud4hsckd</task-id> <tool-use-id>toolu_019LdpNR6ext6LxaGviowHPf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2b517942-2259-467d-a8d0-994fd28c9e84/tasks/bud4hsckd.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.paseo/zerosub/homes/claude-37fe90ef3f56/plugins/cache/claude-plugins-official/superpowers/7.0.2/skills/subagent-driven-development; bash $S/scripts/review-package $PWD/.superpowers/sdd/2026-11-14-sr-followups/plan-1061.md d84c1ac3 HEAD &amp;&amp; P=.superpowers/sdd/plan-1061 &amp;&amp; cat &gt; $P/task-3-astra-brief.md &lt;&lt;'EOF' You are reviewing one task of a Go change in the CARLOS platform, read-only. Do not modify files, the index or branch state. Read: 1. Task brief: .superp ... [1684 characters truncated] ... ndings P1/P2/P3 with file:line, scenario, fix. Concise. EOF timeout 1800 codex exec -m gpt-6-astra -c model_reasoning_effort=high -s read-only "Read .superpowers/sdd/plan-1061/task-3-astra-brief.md and do what it says." &lt;/dev/null &gt; $P/task-3-astra-review.txt 2&gt;&amp;1; echo done" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 10.2 g CO₂e (1,253,764 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on sr-followups, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/replicakick_test.go b/internal/console/replicakick_test.go
index 4f0b2b552..5ac1555cf 100644
--- a/internal/console/replicakick_test.go
+++ b/internal/console/replicakick_test.go
@@ -2,9 +2,21 @@ package console
import (
"slices"
+ "sync"
+ "sync/atomic"
"testing"
)
+// holdFleet holds fleet's lock as a running pass would, released by the
+// returned func or, at the latest, when the test ends: a failure never
+// leaves the lock held for the fixture's wait on the kick.
+func holdFleet(t *testing.T, fx *consoleFixture, fleet string) func() {
+ t.Helper()
+ release := sync.OnceFunc(fx.srv.lockFleet(fleet))
+ t.Cleanup(release)
+ return release
+}
+
// #1061: raising copies places the new copy at once. The copies door kicks
// placement for the app's fleet after it answers; no FleetRelabel pass runs.
// The fleet lock is held across the request, as a running pass would hold
@@ -13,12 +25,12 @@ func TestCopiesRaisePlacesWithoutRelabelPass(t *testing.T) {
fx, token := copiesWorld(t)
fx.srv.replicaKickOff = false
before := serialNow(t, fx)
- unlock := fx.srv.lockFleet("pi")
+ release := holdFleet(t, fx, "pi")
code, out := copiesPut(t, fx, token, `{"copies":2}`)
if a := shopRec(t, fx, "a.example.com").ReplicaAssignment; a != nil {
t.Fatalf("placed under a held fleet lock: %+v", a)
}
- unlock()
+ release()
if code != 200 {
t.Fatalf("copies: %d %s", code, out)
}
@@ -45,3 +57,45 @@ func TestCopiesRaisePlacesWithoutRelabelPass(t *testing.T) {
}
}
}
+
+// A burst of copies writes behind a held fleet lock starts one kick run
+// for the fleet, not one per write, and that run reconciles once after
+// the lock is free: every kick came before it read its view.
+func TestCopiesKicksCoalescePerFleet(t *testing.T) {
+ fx, token := copiesWorld(t)
+ fx.srv.replicaKickOff = false
+ var starts, reconciles atomic.Int32
+ fx.srv.replicaKickHook = func(fleet, stage string) {
+ if fleet != "pi" {
+ t.Errorf("kick for fleet %q", fleet)
+ }
+ switch stage {
+ case "start":
+ starts.Add(1)
+ case "reconcile":
+ reconciles.Add(1)
+ }
+ }
+ release := holdFleet(t, fx, "pi")
+ for i, body := range []string{`{"copies":2}`, `{"copies":1}`, `{"copies":2}`, `{"copies":2}`} {
+ if code, out := copiesPut(t, fx, token, body); code != 200 {
+ t.Fatalf("write %d: %d %s", i, code, out)
+ }
+ }
+ if n := starts.Load(); n != 1 {
+ t.Fatalf("%d kick runs started behind the held lock; want 1", n)
+ }
+ if n := reconciles.Load(); n != 0 {
+ t.Fatalf("%d reconciles under the held lock; want 0", n)
+ }
+ release()
+ fx.srv.replicaKicks.Wait()
+ if s, r := starts.Load(), reconciles.Load(); s != 1 || r != 1 {
+ t.Fatalf("starts %d reconciles %d after release; want 1 and 1", s, r)
+ }
+ for _, host := range []string{"a.example.com", "b.example.com"} {
+ if a := shopRec(t, fx, host).ReplicaAssignment; a == nil || a.Desired != 2 || len(a.Boxes) != 2 {
+ t.Fatalf("%s: assignment %+v; want the last count, 2, placed", host, a)
+ }
+ }
+}
diff --git a/internal/console/replicaplacement.go b/internal/console/replicaplacement.go
index ca997370b..767f1b451 100644
--- a/internal/console/replicaplacement.go
+++ b/internal/console/replicaplacement.go
@@ -9,6 +9,7 @@ import (
"os"
"slices"
"sort"
+ "sync"
"time"
"github.com/carlosframework/platform/internal/appconfig"
@@ -431,60 +432,140 @@ func (s *Server) reconcileReplicaFleet(ctx context.Context, fleet string, v flee
return errors.Join(errs...)
}
-// replicaKickTimeout bounds one copies-door placement kick: the fleet
-// lock wait, the fleet view read and the assignment writes.
+// replicaKickTimeout bounds one copies-door placement kick run: the fleet
+// lock wait, the fleet view read and the assignment writes. A run that
+// cannot take the fleet lock in time gives up; the next pass places.
const replicaKickTimeout = 2 * time.Minute
+// replicaKickRetry is how often a kick run retries a busy fleet lock.
+const replicaKickRetry = 100 * time.Millisecond
+
+// replicaKickState is one fleet's kick: at most one run in flight, and at
+// most one rerun owed by kicks that arrived after the run read its view.
+type replicaKickState struct {
+ running, dirty bool
+}
+
// kickReplicaPlacement places app's copies now rather than at the next
// FleetRelabel pass, up to fleetRelabelInterval away (#1061). The copies
// door calls it after it has answered and released the app lock:
// reconcileReplicaApp only tryLocks the app, so a kick under the door's
-// lock would do nothing. It runs in the background, does only what the
-// worker's pass does for one fleet (fleetRelabelPass: off on a host-claim
-// console, one admitted unit of record work, the fleet lock, a fresh view,
-// reconcileReplicaFleet and its serial bump), and logs its errors; a kick
-// that fails or finds the app busy leaves the work to the next pass.
-// Lowering the count goes through the same reconcile, which retires the
-// extra copies. replicaKicks lets a test wait for it.
+// lock would do nothing. It reads the app's placement column (one store
+// row) and hands the fleet's work to one background run, coalesced per
+// fleet: a kick while that fleet's run is in flight only marks it dirty,
+// and the run goes round once more if a kick came after it read its view.
+// So a burst of writes behind a slow pass or drain holds at most one
+// goroutine per fleet. Each run does only what the worker's pass does for
+// one fleet (fleetRelabelPass: off on a host-claim console, one admitted
+// unit of record work, the fleet lock, a fresh view, reconcileReplicaFleet
+// and its serial bump), waits for the fleet lock no longer than
+// replicaKickTimeout, and logs its errors; a run that fails, gives up or
+// finds the app busy leaves the work to the next pass. Lowering the count
+// goes through the same reconcile, which retires the extra copies.
+// replicaKicks lets a test wait for the runs.
func (s *Server) kickReplicaPlacement(account int64, app string) {
if s.replicaKickOff || s.cfg.HostClaim || s.cfg.Releases == nil || s.cfg.Registry == "" {
return
}
+ placed, err := s.store.AppPlacement(account, app)
+ if err != nil {
+ log.Printf("console: replica placement kick %s: placement: %v (the relabel worker places it)", app, err)
+ return
+ }
+ fleet, ok := registry.FleetPlacement(placed)
+ if !ok {
+ return
+ }
+ s.replicaKickMu.Lock()
+ if s.replicaKickFleets == nil {
+ s.replicaKickFleets = map[string]*replicaKickState{}
+ }
+ st := s.replicaKickFleets[fleet]
+ if st != nil {
+ st.dirty = true
+ s.replicaKickMu.Unlock()
+ return
+ }
+ st = &replicaKickState{running: true}
+ s.replicaKickFleets[fleet] = st
s.replicaKicks.Add(1)
+ s.replicaKickMu.Unlock()
+ if s.replicaKickHook != nil {
+ s.replicaKickHook(fleet, "start")
+ }
go func() {
defer s.replicaKicks.Done()
- ctx, cancel := context.WithTimeout(context.Background(), replicaKickTimeout)
- defer cancel()
- placed, err := s.store.AppPlacement(account, app)
- if err != nil {
- log.Printf("console: replica placement kick %s: placement: %v (the relabel worker places it)", app, err)
- return
- }
- fleet, ok := registry.FleetPlacement(placed)
- if !ok {
+ for {
+ ran := s.replicaKickRun(fleet, st)
+ s.replicaKickMu.Lock()
+ if ran && st.dirty {
+ st.dirty = false
+ s.replicaKickMu.Unlock()
+ continue
+ }
+ delete(s.replicaKickFleets, fleet)
+ s.replicaKickMu.Unlock()
return
}
- s.lifetimesIteration(ctx, "replica placement kick", true, false, func(ctx context.Context) {
- s.replicaPlacementKick(ctx, fleet)
- })
}()
}
+// replicaKickRun is one kick run for fleet; false when it could not take
+// the fleet lock in time (the next pass places, and owed reruns drop).
+func (s *Server) replicaKickRun(fleet string, st *replicaKickState) bool {
+ ctx, cancel := context.WithTimeout(context.Background(), replicaKickTimeout)
+ defer cancel()
+ ran := true
+ s.lifetimesIteration(ctx, "replica placement kick", true, false, func(ctx context.Context) {
+ ran = s.replicaPlacementKick(ctx, fleet, st)
+ })
+ return ran
+}
+
// replicaPlacementKick is fleetRelabelPass's placement step for one fleet,
-// as of the moment it holds the fleet lock.
-func (s *Server) replicaPlacementKick(ctx context.Context, fleet string) {
+// as of the moment it holds the fleet lock. Kicks before that moment are
+// covered by the view it reads, so it clears the fleet's dirty mark there.
+func (s *Server) replicaPlacementKick(ctx context.Context, fleet string, st *replicaKickState) bool {
ctx = withWriteMemo(ctx)
- unlock := s.lockFleet(fleet)
+ unlock, ok := s.tryLockFleetUntil(ctx, fleet)
+ if !ok {
+ log.Printf("console: replica placement kick %s: fleet busy past %s (the relabel worker places it)", fleet, replicaKickTimeout)
+ return false
+ }
defer unlock()
+ s.replicaKickMu.Lock()
+ st.dirty = false
+ s.replicaKickMu.Unlock()
now := time.Now()
v, err := s.loadFleetViewAt(ctx, fleet, now)
if err != nil {
log.Printf("console: replica placement kick %s: view: %v (the relabel worker places it)", fleet, err)
- return
+ return true
}
if err := s.reconcileReplicaFleet(ctx, fleet, v, now); err != nil {
log.Printf("console: replica placement kick %s: %v (the relabel worker retries)", fleet, err)
}
+ if s.replicaKickHook != nil {
+ s.replicaKickHook(fleet, "reconcile")
+ }
+ return true
+}
+
+// tryLockFleetUntil takes lockFleet's mutex, retrying a busy one every
+// replicaKickRetry until ctx ends.
+func (s *Server) tryLockFleetUntil(ctx context.Context, fleet string) (func(), bool) {
+ m, _ := s.fleetLocks.LoadOrStore(fleet, &sync.Mutex{})
+ mu := m.(*sync.Mutex)
+ t := time.NewTicker(replicaKickRetry)
+ defer t.Stop()
+ for !mu.TryLock() {
+ select {
+ case <-ctx.Done():
+ return nil, false
+ case <-t.C:
+ }
+ }
+ return mu.Unlock, true
}
func (s *Server) reconcileReplicaApp(ctx context.Context, fleet string, app AppRef, v fleetView, cache *replicaPlacementCache, now time.Time) (bool, error) {
diff --git a/internal/console/server.go b/internal/console/server.go
index e6d21ecdc..35c2c4e98 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1452,9 +1452,16 @@ type Server struct {
// linkFirstSyncs counts the poll's background first syncs
// (firstLinkSync), so a test can wait for them.
linkFirstSyncs sync.WaitGroup
- // replicaKicks counts the copies door's background placement kicks
- // (kickReplicaPlacement), so a test can wait for them.
- replicaKicks sync.WaitGroup
+ // replicaKicks counts the copies door's background placement kick
+ // runs (kickReplicaPlacement), so a test can wait for them.
+ // replicaKickFleets, under replicaKickMu, is each fleet's run in
+ // flight and whether it owes a rerun.
+ replicaKicks sync.WaitGroup
+ replicaKickMu sync.Mutex
+ replicaKickFleets map[string]*replicaKickState
+ // replicaKickHook, when non-nil, is called when a fleet's kick run
+ // starts ("start") and when it has reconciled ("reconcile"). Tests only.
+ replicaKickHook func(fleet, stage string)
// replicaKickOff, when set, stops the copies door's placement kick.
// Tests only: worlds that drive placement passes themselves.
replicaKickOff bool