carlos / platform Public

console: drain requests and join workers on SIGTERM

From the Go audit (#1123), batch 2. SIGTERM used to release the policy
writer lease and os.Exit(0) with requests in flight, so every console
roll dropped them. Now cmd/console/stop.go:
- shuts the HTTP server down with a 20 s drain (WebSockets closed at
  once), logs and cuts what is left with 2 s grace;
- closes worker admission, cancels the worker context and joins every
  background loop for up to 10 s, naming any that stay (the relay
  writer, verify reader and GeoIP loops are now joined workers);
- releases the policy lease only after the capacity observer joins;
- a second signal, at any point, exits 1 without starting a release.
Worst case 37 s, inside systemd's default 90 s stop timeout.

Reviewed by Astra (round 1, READY AFTER FIXES; P2s fixed in a2e41dfe),
scoped termination check passed (test fix a7488581). Outside the census.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from audit-console-shutdown into main.
claude agent, operated by paul@keymail.dev 7412166852aad021ed18fafda3198b8e35048b0c parent b530ec0
16 files changed, +1,553 −100
  • cmd/console/claim_sweep_test.go +1 −1
  • cmd/console/claimworkers_started_test.go +10 −1
  • cmd/console/hacapacity_test.go +30 −6
  • cmd/console/main.go +115 −77
  • cmd/console/plansponsor_test.go +1 −1
  • cmd/console/region_test.go +3 −3
  • cmd/console/stop.go +509 −0
  • cmd/console/stop_test.go +588 −0
  • docs/superpowers/reviews/CHECK-BRIEF-audit-console-shutdown-R1-fix.md +30 −0
  • docs/superpowers/reviews/CHECK-audit-console-shutdown-R1-fix.md +41 −0
  • docs/superpowers/reviews/FINDINGS-audit-console-shutdown-R1.md +52 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-console-shutdown.md +50 −0
  • internal/console/geoipfollower.go +12 −5
  • internal/console/relayops.go +11 −2
  • internal/console/verifyreader.go +11 −4
  • internal/console/workerjoin_test.go +89 −0

CI passed — run details

diff --git a/cmd/console/claim_sweep_test.go b/cmd/console/claim_sweep_test.go
index 42c574a20..aaf2a719d 100644
--- a/cmd/console/claim_sweep_test.go
+++ b/cmd/console/claim_sweep_test.go
@@ -38,7 +38,7 @@ func TestClaimLegacySweepRefusesEnabled(t *testing.T) {
old := log.Writer()
log.SetOutput(&logs)
defer log.SetOutput(old)
- sweepLegacyMail(enabled, s, st)
+ sweepLegacyMail(ctx, enabled, s, st)
_, _, err = s.Get(ctx, key)
if enabled {
if err != nil {
diff --git a/cmd/console/claimworkers_started_test.go b/cmd/console/claimworkers_started_test.go
index 8ca9f24eb..b0b4e8964 100644
--- a/cmd/console/claimworkers_started_test.go
+++ b/cmd/console/claimworkers_started_test.go
@@ -23,10 +23,19 @@ func TestEveryRegisteredClaimWorkerIsStarted(t *testing.T) {
if len(registered) < 10 {
t.Fatalf("found only %d registered workers; the pattern no longer matches claim_workers.go", len(registered))
}
+ // Each is started through startClaimWorker, which runs it on the stop's
+ // worker context (stop.go), never on a background one a stop cannot
+ // cancel or wait for.
started := map[string]bool{}
- for _, m := range regexp.MustCompile(`RunClaimWorker\(context\.Background\(\), "([A-Za-z]+)"\)`).FindAllSubmatch(main, -1) {
+ for _, m := range regexp.MustCompile(`(?m)^\tstartClaimWorker\("([A-Za-z]+)"\)$`).FindAllSubmatch(main, -1) {
started[string(m[1])] = true
}
+ if !regexp.MustCompile(`startClaimWorker := func\(name string\) \{\s+work\.Go\(name, func\(ctx context\.Context\) \{ srv\.RunClaimWorker\(ctx, name\) \}\)`).Match(main) {
+ t.Error("startClaimWorker no longer runs RunClaimWorker on work's context")
+ }
+ if regexp.MustCompile(`RunClaimWorker\(context\.Background\(\)`).Match(main) {
+ t.Error("a claim worker is started on context.Background(), which a stop cannot cancel or wait for")
+ }
names := map[string]bool{}
for _, m := range registered {
name := string(m[1])
diff --git a/cmd/console/hacapacity_test.go b/cmd/console/hacapacity_test.go
index 9de008463..3108ab8e6 100644
--- a/cmd/console/hacapacity_test.go
+++ b/cmd/console/hacapacity_test.go
@@ -59,9 +59,36 @@ func TestHACapacityServeWiring(t *testing.T) {
if serve == nil {
t.Fatal("serve missing")
}
- var starts, stops, waits int
+ var starts, stops, handed int
fields := map[string]string{}
ast.Inspect(serve.Body, func(n ast.Node) bool {
+ // The stop (stop.go) is handed the observer's cancel and its join;
+ // TestConsoleStopOrder proves it cancels and joins it before the
+ // lease release.
+ if lit, ok := n.(*ast.CompositeLit); ok {
+ if u, ok := lit.Type.(*ast.Ident); ok && u.Name == "consoleStop" {
+ for _, e := range lit.Elts {
+ if kv, ok := e.(*ast.KeyValueExpr); ok {
+ switch {
+ case isIdent(kv.Key, "stopCapacity") && isIdent(kv.Value, "stopCapacity"),
+ isIdent(kv.Key, "capacityDone") && isIdent(kv.Value, "capacityDone"):
+ handed++
+ }
+ }
+ }
+ }
+ }
+ // The observer's context is the workers' context's child: a stop
+ // cancels it with them.
+ if as, ok := n.(*ast.AssignStmt); ok && len(as.Lhs) == 2 && isIdent(as.Lhs[0], "capacityCtx") && len(as.Rhs) == 1 {
+ call, ok := as.Rhs[0].(*ast.CallExpr)
+ sel, ok2 := call.Fun.(*ast.SelectorExpr)
+ if !ok || !ok2 || sel.Sel.Name != "WithCancel" || len(call.Args) != 1 {
+ t.Error("capacityCtx is not a WithCancel context")
+ } else if arg, ok := call.Args[0].(*ast.SelectorExpr); !ok || !isIdent(arg.X, "work") || arg.Sel.Name != "ctx" {
+ t.Error("capacityCtx does not derive from work.ctx")
+ }
+ }
if kv, ok := n.(*ast.KeyValueExpr); ok {
if k, ok := kv.Key.(*ast.Ident); ok {
if call, ok := kv.Value.(*ast.CallExpr); ok && len(call.Args) == 1 {
@@ -86,13 +113,10 @@ func TestHACapacityServeWiring(t *testing.T) {
}
}
}
- if u, ok := n.(*ast.UnaryExpr); ok && u.Op == token.ARROW && isIdent(u.X, "capacityDone") {
- waits++
- }
return true
})
- if starts != 1 || stops != 2 || waits != 1 {
- t.Fatalf("start=%d cancel=%d shutdown wait=%d", starts, stops, waits)
+ if starts != 1 || stops != 1 || handed != 2 {
+ t.Fatalf("start=%d deferred cancel=%d handed to the stop=%d", starts, stops, handed)
}
if fields["HACapacityConfig"] != `"CONSOLE_HA_CAPACITY_CONFIG"` || fields["HACapacityDirectory"] != `"CARLOS_DEPLOYMENT_DIR"` {
t.Fatalf("configuration wiring: %v", fields)
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 2790394ab..1237af9b7 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -489,7 +489,11 @@ func serve() {
}
// Before the server exists: every door that seals reads this switch.
appconfig.SetBoundSealing(secretsEnvelopeV2())
- geoReader := consoleGeoReader(strings.TrimSpace(os.Getenv("CONSOLE_GEOIP_DB")))
+ // Every background loop the console runs, from the GeoIP reader's on,
+ // runs on work's context, so a stop cancels them together and waits for
+ // them (stop.go).
+ work := newWorkers(context.Background(), time.Now)
+ geoReader := consoleGeoReader(strings.TrimSpace(os.Getenv("CONSOLE_GEOIP_DB")), work)
regionalIngress, err := regionIngress(os.Getenv)
if err != nil {
log.Fatal(err)
@@ -692,22 +696,39 @@ func serve() {
defer cancel()
srv.LoadHostsMode(ctx)
}()
- capacityCtx, stopCapacity := context.WithCancel(context.Background())
+ capacityCtx, stopCapacity := context.WithCancel(work.ctx)
defer stopCapacity()
capacityDone := startHACapacity(capacityCtx, srv, cfg)
- // A graceful stop releases the app policy writer lease, so a rolled
- // console's successor need not wait out its TTL (the housekeeper's
- // "graceful stand-down must be reachable"). Cancel and join the capacity
- // observer before releasing the lease and exiting.
- go func() {
- sig := make(chan os.Signal, 1)
- signal.Notify(sig, syscall.SIGTERM, os.Interrupt)
- <-sig
- stopCapacity()
- <-capacityDone
- srv.ReleasePolicyWriter(context.Background())
- os.Exit(0)
- }()
+ // The graceful stop (stop.go): drain the requests, cancel and join the
+ // workers and the capacity observer, then release the app policy writer
+ // lease, so a rolled console's successor need not wait out its TTL (the
+ // housekeeper's "graceful stand-down must be reachable"). The capacity
+ // observer is joined before the lease is released. Armed here, before
+ // the first worker starts; until serving begins a signal stops with no
+ // requests to drain.
+ sigs := make(chan os.Signal, 2)
+ signal.Notify(sigs, syscall.SIGTERM, os.Interrupt)
+ stop := &consoleStop{
+ work: work,
+ stopCapacity: stopCapacity,
+ capacityDone: capacityDone,
+ release: srv.ReleasePolicyWriter,
+ drain: stopDrainBound,
+ cutGrace: stopCutGrace,
+ workerWait: stopWorkerBound,
+ logf: log.Printf,
+ now: time.Now,
+ }
+ handOff := stop.untilServing(sigs, os.Exit)
+ // The startup steps below run on work's context, which an early stop
+ // cancels. A step that then fails is the stop's doing, not a fault: it
+ // waits for the stop to exit instead of exiting 1 under it.
+ fatalUnlessStopping := func(format string, a ...any) {
+ if work.ctx.Err() != nil {
+ handOff() // a stop has begun: blocks until it exits
+ }
+ log.Fatalf(format, a...)
+ }
// The console mailer's identity ensure (consoleMailer above) — makes or
// re-reads the sending domain's SES/DKIM identity. Started here, not in
// NewServer, same reasoning as the alert watcher below: constructing a
@@ -715,18 +736,18 @@ func serve() {
// no overall timeout, and an ensure that never returns would hold the
// mailer for good (a send gives up at its own deadline, but every one
// would).
- go func() {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ work.Go("ensureConsoleMail", func(ctx context.Context) {
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
ensureConsoleMail(ctx)
- }()
+ })
// The senders migration's tail (tenant-email senders design §5): once a
// release has passed with every console writing senders/app.json, an
// operator sets CARLOS_MAIL_LEGACY_SWEEP=1 and the next start deletes the
// email.json objects that have already been replaced. Off by default, and
// it never touches an app that has not been migrated.
if os.Getenv("CARLOS_MAIL_LEGACY_SWEEP") == "1" {
- go sweepLegacyMail(cfg.HostClaim, rel, st)
+ work.Go("sweepLegacyMail", func(ctx context.Context) { sweepLegacyMail(ctx, cfg.HostClaim, rel, st) })
}
// The mail user boundary backfill (CARLOS_MAIL_USER_BOUNDARY): an
// operator sets CARLOS_MAIL_BOUNDARY_SWEEP=1 and the next start puts the
@@ -737,7 +758,9 @@ func serve() {
// the legacy sweep is: it would act on IAM users outside the claim mail
// gate and the apps' permits.
if os.Getenv("CARLOS_MAIL_BOUNDARY_SWEEP") == "1" {
- go sweepMailBoundaries(context.Background(), cfg.HostClaim, mailProvisioner, log.Printf)
+ work.Go("sweepMailBoundaries", func(ctx context.Context) {
+ sweepMailBoundaries(ctx, cfg.HostClaim, mailProvisioner, log.Printf)
+ })
}
// The S3 change index's reader (CARLOS_CHANGE_INDEX=read, change-index
// design §4.6): the run and seed sweeps read their records through a
@@ -751,33 +774,36 @@ func serve() {
demoView = v
edgesWatch = w
}
- if err := srv.SetManagedConfigWatch(context.Background(), edgesWatch); err != nil {
+ if err := srv.SetManagedConfigWatch(work.ctx, edgesWatch); err != nil {
log.Printf("console: managed configuration: %v", err)
}
- recoveryCtx, recoveryCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ recoveryCtx, recoveryCancel := context.WithTimeout(work.ctx, 10*time.Second)
recoveryErr := srv.ReconcileDemoJobs(recoveryCtx, true)
recoveryCancel()
if recoveryErr != nil {
- log.Fatalf("console: demo job recovery: %v", recoveryErr)
+ fatalUnlessStopping("console: demo job recovery: %v", recoveryErr)
}
if demoView != nil || cfg.Demo.Enabled || cfg.Demo.BoxMode() {
- go recordViewBackstopLoop(context.Background(), demoView, srv)
+ work.Go("recordViewBackstopLoop", func(ctx context.Context) { recordViewBackstopLoop(ctx, demoView, srv) })
}
- go srv.RunDemoJobs(context.Background(), edgesWatch)
+ work.Go("RunDemoJobs", func(ctx context.Context) { srv.RunDemoJobs(ctx, edgesWatch) })
// The region labels' name map (region labels spec §3.2): one edges read
// at start, then at most every 10 minutes on a generation change, else
// every 30 (±10%).
- go srv.RunRegionNames(context.Background(), edgesWatch)
+ work.Go("RunRegionNames", func(ctx context.Context) { srv.RunRegionNames(ctx, edgesWatch) })
// The restore-test reader (member backups slice 2b): every box's
// control/verify/<ref>.json, read at start, then per moved scope while
// the change index vouches, with a relist at most every 6 hours. Stored
- // synchronously, before the server listens; it runs its own goroutine.
- srv.StartVerifyReader(context.Background(), edgesWatch)
+ // synchronously, before the server listens; its tick runs in its own
+ // goroutine, which the stop waits for like any worker.
+ work.Spawn("StartVerifyReader", func(ctx context.Context) <-chan struct{} {
+ return srv.StartVerifyReader(ctx, edgesWatch)
+ })
// The move pass's pages (moves Plan 5 Task 7): the console's alert sinks,
// armed before the claim runtime binds the pass, so no pass runs unarmed.
- armMovesPaging(context.Background(), cfg, os.Getenv)
- if err := srv.ConfigureClaimRuntime(context.Background()); err != nil {
- log.Fatalf("console: claim recovery: %v", err)
+ armMovesPaging(work.ctx, cfg, os.Getenv)
+ if err := srv.ConfigureClaimRuntime(work.ctx); err != nil {
+ fatalUnlessStopping("console: claim recovery: %v", err)
}
// The fleet owner record backfill (rootfs apps Plan 4 D7): once per
// start, every fleet's accounts/<acct>/fleets/<fleet>.json, create-only,
@@ -790,121 +816,125 @@ func serve() {
// the placement column from routes, for apps placed before the column
// existed. Not before the first seal: sealKeyFor reads the same routes
// until it lands.
- go func() {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ work.Go("fleetBackfills", func(ctx context.Context) {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
srv.RunFleetOwnerBackfill(ctx)
srv.RunAppPlacementBackfill(ctx)
- }()
+ })
+ // Each claim worker runs on work's context under its own name.
+ startClaimWorker := func(name string) {
+ work.Go(name, func(ctx context.Context) { srv.RunClaimWorker(ctx, name) })
+ }
// The alert engine reads the alert signals every minute, steps the
// incidents and sends what they owe (internal/console/alertwatch.go).
// It refuses on a host-claim console and says so in its job status.
// Started here rather than in NewServer so constructing a Server —
// which every console test does — never starts a goroutine or sends
// anything.
- go srv.RunClaimWorker(context.Background(), "StartHostReports")
- go srv.RunClaimWorker(context.Background(), "StartAlertEngine")
+ startClaimWorker("StartHostReports")
+ startClaimWorker("StartAlertEngine")
// The geoip orphan sweep and D1 expiry, at startup and daily.
- go srv.RunClaimWorker(context.Background(), "StartGeoipJobs")
+ startClaimWorker("StartGeoipJobs")
// The moves console record (moves Task 13): with the switch on or a
// secrets key, best-effort, logged by the method itself.
- go srv.RunClaimWorker(context.Background(), "PublishMovesConsole")
+ startClaimWorker("PublishMovesConsole")
// The economics pass writes the daily usage/census/storage/statement
// objects and pulls the AWS bill (internal/console/economicspass.go).
// Same placement rule as the alert engine: started here, never in
// NewServer, so constructing a Server stays goroutine-free.
- go srv.RunClaimWorker(context.Background(), "StartClaimRecoveryPass")
- go srv.RunClaimWorker(context.Background(), "StartEconomicsPass")
+ startClaimWorker("StartClaimRecoveryPass")
+ startClaimWorker("StartEconomicsPass")
// The infrastructure inventory pass writes infra/inventory.json for
// /fleet/architecture (internal/console/infrapass.go). Same placement
// rule as the economics pass: started here, never in NewServer.
- go srv.RunClaimWorker(context.Background(), "StartInfraPass")
+ startClaimWorker("StartInfraPass")
// The object-storage scan pass advances each opted-in store's coverage
// (internal/console/scanpass.go). Same placement rule again: started
// here, never in NewServer. It returns immediately when no engine is
// configured, which is every deployment that has not opted in.
- go srv.RunClaimWorker(context.Background(), "StartScanPass")
+ startClaimWorker("StartScanPass")
// The on-demand drain, on its own clock (spec §7.2). Separate goroutine
// from the sweep above and not a phase inside it: a queue phase behind a
// sequential per-app budget would starve for as long as the sweep takes.
- go srv.RunClaimWorker(context.Background(), "StartScanDrain")
+ startClaimWorker("StartScanDrain")
// The temporary-app expiry pass (internal/console/expirypass.go). Same
// placement rule as every pass above: started here, never in NewServer.
- go srv.RunClaimWorker(context.Background(), "StartExpiryPass")
+ startClaimWorker("StartExpiryPass")
// The plan limits pass (internal/console/planlimits.go): publishes each
// account's limits record. A no-op with CARLOS_PLAN_CATALOG unset.
- go srv.RunClaimWorker(context.Background(), "StartPlanLimitsPass")
- go srv.RunClaimWorker(context.Background(), "StartPlanGracePass")
+ startClaimWorker("StartPlanLimitsPass")
+ startClaimWorker("StartPlanGracePass")
// The billing sync (internal/console/billingpass.go, plans 6a): returns
// at once with CARLOS_BILLING off.
- go srv.RunClaimWorker(context.Background(), "StartBillingSyncPass")
- go srv.RunClaimWorker(context.Background(), "StartDomainPurchasePass")
+ startClaimWorker("StartBillingSyncPass")
+ startClaimWorker("StartDomainPurchasePass")
// The plans deployment marker (internal/console/plansmarker.go): once per
// start. Writes nothing on a deployment that never set a catalog.
- go srv.RunClaimWorker(context.Background(), "PublishPlansMarker")
+ startClaimWorker("PublishPlansMarker")
// The run sweep (internal/console/runsweep.go): expires queued runs,
// ends lost ones, deletes a day-old run's objects. Same placement rule.
- go srv.RunClaimWorker(context.Background(), "StartRunSweep")
+ startClaimWorker("StartRunSweep")
// The seeds sweep (internal/console/seedsweep.go, seeded-instances spec
// §3.1, §5.6): abandons stale reservations and imports, finishes
// rolled-back seeds, deletes snapshots no live seed needs. Same
// placement rule as every pass above.
- go srv.RunClaimWorker(context.Background(), "StartSeedsPass")
+ startClaimWorker("StartSeedsPass")
// The lifetimes cutover watch (internal/console/lifetimes_cutover.go):
// reads control/lifetimes-cutover.json every 10 seconds, turns instance
// lifetimes on once the work admitted before it has drained, and runs the
// claims-off app materialisation as its first admitted iteration. Off on
// a host-claim console.
- go srv.RunClaimWorker(context.Background(), "StartLifetimesCutoverWatch")
+ startClaimWorker("StartLifetimesCutoverWatch")
// The lifetime recovery pass (internal/console/lifetimes_recovery.go):
// every 60 seconds, finishes or ends each create and orphan retirement
// a crash or a failed write left pending. It does work only once
// lifetimes are on, and is off on a host-claim console.
- go srv.RunClaimWorker(context.Background(), "StartLifetimeRecoveryPass")
+ startClaimWorker("StartLifetimeRecoveryPass")
// The incarnation migration pass (internal/console/lifetimes_migrate.go):
// every 60 seconds, moves up to 50 fieldless instance records into
// slot-governed lifetimes, oldest first. Off unless
// CARLOS_LIFETIMES_MIGRATE=1, it does work only once lifetimes are on,
// and is off on a host-claim console.
- go srv.RunClaimWorker(context.Background(), "StartIncarnationMigrationPass")
+ startClaimWorker("StartIncarnationMigrationPass")
// The relay's writer lease and its converging reconcile
// (internal/console/relayops.go). Same placement rule as every pass
// above, and it returns immediately when CARLOS_RELAY_REGIONS is empty —
// which is every deployment that has not armed a relay.
- go srv.RunClaimWorker(context.Background(), "StartRelay")
+ startClaimWorker("StartRelay")
// The email-events push (internal/console/mailpush.go): delivers the
// SES outcomes an app asked to be told about. Same placement rule as
// every pass above; with nothing queued, a pass is two indexed queries.
- go srv.RunClaimWorker(context.Background(), "StartMailEventPush")
+ startClaimWorker("StartMailEventPush")
// Door keys (#175 P7): re-sign every app's record before its 72-hour
// expiry, once at startup and then every 12 hours. Inert without a
// signing key or a deployment bucket.
- go srv.RunClaimWorker(context.Background(), "StartDoorKeyResign")
+ startClaimWorker("StartDoorKeyResign")
// The fleet-address report (internal/console/egressfleet.go, #328):
// re-checks every live egress allow against the boxes' published
// addresses on an edges change and the 30-minute backstop, and alerts.
// Read-only, on every console; idle with no allow.
- go srv.RunClaimWorker(context.Background(), "StartEgressReport")
+ startClaimWorker("StartEgressReport")
// Once, at boot: log any route already sitting at another app's platform
// apex (internal/console/apex.go). Reports; repairs nothing.
- go srv.RunClaimWorker(context.Background(), "ReportApexSquats")
+ startClaimWorker("ReportApexSquats")
// Spec §5.7: after any roll, list possible placement discrepancies for
// operator review. Read-only; never blocks startup.
- go srv.RunClaimWorker(context.Background(), "LogPlacementDiscrepancies")
+ startClaimWorker("LogPlacementDiscrepancies")
// Managed fleets 1b (rules 2, 4, 5, 8): every 5 minutes, label existing
// fleet records to the box their binding names, move records off lost
// and draining boxes, and pause with an alert while a fleet box is below
// the label floor. Off on a host-claim console.
- go srv.RunClaimWorker(context.Background(), "FleetRelabel")
- go srv.RunClaimWorker(context.Background(), "ManagedFleets")
+ startClaimWorker("FleetRelabel")
+ startClaimWorker("ManagedFleets")
// The link sync (internal/console/links_sync.go): every 10 seconds,
// and once at start, writes the hub registry's channel for each linked
// deployment whose last write failed. Reads only the console database.
- go srv.RunClaimWorker(context.Background(), "LinkSync")
+ startClaimWorker("LinkSync")
addr := envOr("CONSOLE_ADDR", "127.0.0.1:8090")
ln, err := net.Listen("tcp", addr)
if err != nil {
- log.Fatalf("console: listen %s: %v", addr, err)
+ fatalUnlessStopping("console: listen %s: %v", addr, err)
}
log.Printf("console: %s listening on %s", origin, addr)
// ReadHeaderTimeout guards against Slowloris-style slow-header connection
@@ -931,10 +961,12 @@ func serve() {
// line fails its restart — and the adopt pass rolls the symlink back and
// starts the previous version, instead of stamping a build that never
// served (internal/release/adopt.go).
+ stop.attach(httpSrv)
+ handOff()
if err := NotifyReady(); err != nil {
log.Printf("console: notifying systemd of readiness: %v", err)
}
- log.Fatal(httpSrv.Serve(ln))
+ os.Exit(stop.serve(ln, sigs))
}
// openServeDB is openConsoleDB for the serving console. With
@@ -1795,14 +1827,14 @@ func haRegionsList(v string) []string {
// The mapping sits behind a geo.Swappable so D1 can close it (geoip spec §0
// D1, §11.3, codex R10-1): a GeoLite2 override already past its 30 days is
// refused here, and one that expires while the console runs is closed by
-// watchGeoIPExpiry. The file is the operator's; the platform never deletes
-// it, and the log says to replace it.
-func openGeoIP(path string) geo.Locator {
+// watchGeoIPExpiry, run as one of work's workers. The file is the
+// operator's; the platform never deletes it, and the log says to replace it.
+func openGeoIP(path string, work *workers) geo.Locator {
sw := openGeoIPAt(path, time.Now())
if sw == nil {
return nil
}
- go watchGeoIPExpiry(sw, path, time.Minute, time.Now)
+ work.Go("watchGeoIPExpiry", func(ctx context.Context) { watchGeoIPExpiry(ctx, sw, path, time.Minute, time.Now) })
return sw
}
@@ -1836,10 +1868,15 @@ func openGeoIPAt(path string, now time.Time) *geo.Swappable {
// watchGeoIPExpiry closes the override once D1 says so. It returns when it
// has closed it (nothing left to watch).
-func watchGeoIPExpiry(sw *geo.Swappable, path string, every time.Duration, now func() time.Time) {
+func watchGeoIPExpiry(ctx context.Context, sw *geo.Swappable, path string, every time.Duration, now func() time.Time) {
t := time.NewTicker(every)
defer t.Stop()
- for range t.C {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
if geoIPExpiryTick(sw, path, now()) {
return
}
@@ -2057,17 +2094,18 @@ func consoleBoxLabel() string {
// consoleGeoReader is the console's one GeoIP reader. With CONSOLE_GEOIP_DB
// set it is that override (opened once, D1-checked, closed at expiry);
// otherwise it follows the generation this box's edge mirrors, under
-// CARLOS_DATA_DIR (default /data) as carlos/geoip, once a minute.
-func consoleGeoReader(override string) *geo.Swappable {
+// CARLOS_DATA_DIR (default /data) as carlos/geoip, once a minute. Either
+// loop runs as one of work's workers.
+func consoleGeoReader(override string, work *workers) *geo.Swappable {
if override != "" {
- if loc, ok := openGeoIP(override).(*geo.Swappable); ok {
+ if loc, ok := openGeoIP(override, work).(*geo.Swappable); ok {
return loc
}
return nil
}
sw := geo.NewSwappable()
f := console.NewGeoipFollower(filepath.Join(envOr("CARLOS_DATA_DIR", "/data"), "carlos", "geoip"), sw)
- go f.Run()
+ work.Go("geoipFollower", f.Run)
return sw
}
@@ -2081,12 +2119,12 @@ func geoLocator(sw *geo.Swappable) geo.Locator {
return sw
}
-func sweepLegacyMail(claims bool, rel release.Store, st *console.Store) {
+func sweepLegacyMail(ctx context.Context, claims bool, rel release.Store, st *console.Store) {
if claims {
log.Printf("console: mail legacy sweep: %v", mail.ErrClaimMailPending)
return
}
- n, err := mail.SweepLegacyRecords(context.Background(), rel, true)
+ n, err := mail.SweepLegacyRecords(ctx, rel, true)
if err != nil {
log.Printf("console: mail legacy sweep: %v", err)
return
diff --git a/cmd/console/plansponsor_test.go b/cmd/console/plansponsor_test.go
index e7f58abf8..5b400a734 100644
--- a/cmd/console/plansponsor_test.go
+++ b/cmd/console/plansponsor_test.go
@@ -163,7 +163,7 @@ func TestServeSettlesTheSponsorshipBeforeItServes(t *testing.T) {
if p, ok := first["planCatalog"]; !ok || p > at {
t.Error("sponsorAtStart runs before planCatalog loads the catalog")
}
- for _, later := range []string{"billingConfigFor", "console.NewServer", "srv.RunClaimWorker", "net.Listen", "httpSrv.Serve", "NotifyReady"} {
+ for _, later := range []string{"billingConfigFor", "console.NewServer", "srv.RunClaimWorker", "net.Listen", "stop.serve", "NotifyReady"} {
p, ok := first[later]
if !ok {
t.Errorf("serve() no longer calls %s; update this test", later)
diff --git a/cmd/console/region_test.go b/cmd/console/region_test.go
index 59efe142f..b83600cf7 100644
--- a/cmd/console/region_test.go
+++ b/cmd/console/region_test.go
@@ -13,10 +13,10 @@ import (
)
func TestOpenGeoIPIsOptionalAndNeverFatal(t *testing.T) {
- if openGeoIP("") != nil {
+ if openGeoIP("", testWorkers(t)) != nil {
t.Fatal("unset CONSOLE_GEOIP_DB must mean no locator")
}
- if openGeoIP(filepath.Join(t.TempDir(), "missing.mmdb")) != nil {
+ if openGeoIP(filepath.Join(t.TempDir(), "missing.mmdb"), testWorkers(t)) != nil {
t.Fatal("an unopenable file must mean no locator, not a crash")
}
}
@@ -96,7 +96,7 @@ func TestGeoIPOverrideIsClosedAtExpiryAndRefusedWhenExpired(t *testing.T) {
}
func TestConsoleGeoReaderNeverYieldsATypedNil(t *testing.T) {
- sw := consoleGeoReader(filepath.Join(t.TempDir(), "missing.mmdb"))
+ sw := consoleGeoReader(filepath.Join(t.TempDir(), "missing.mmdb"), testWorkers(t))
if sw != nil {
t.Fatal("an unusable override must give no reader")
}
diff --git a/cmd/console/stop.go b/cmd/console/stop.go
new file mode 100644
index 000000000..f9afb3cc8
--- /dev/null
+++ b/cmd/console/stop.go
@@ -0,0 +1,509 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+// How long each step of a graceful stop may take. console.service names no
+// TimeoutStopSec (the unit is written on each console box and is in no
+// repo), so systemd's DefaultTimeoutStopSec applies: SIGTERM, then SIGKILL
+// 90 s later. The adopt pass's `systemctl try-restart` waits for that stop
+// before its settle window starts. The worst case here is drain 20 s + cut
+// grace 2 s + workers 10 s + the policy lease release's own 5 s budget
+// (policyLeaseReleaseBudget) = 37 s, well inside the 90.
+//
+// The drain is the one a roll feels: the listener closes as the stop
+// starts, so for as long as a request is still running the edge in front
+// gets refused connections. An ordinary page or API call finishes in well
+// under a second; 20 s also covers a policy write's signing attempt
+// (policyAttemptWindow, 10 s). A longer upload or stream is cut.
+const (
+ stopDrainBound = 20 * time.Second
+ stopCutGrace = 2 * time.Second
+ stopWorkerBound = 10 * time.Second
+)
+
+// consoleStop is the console's graceful stop (SIGTERM or SIGINT), in order:
+//
+// 1. Stop accepting and drain: http.Server.Shutdown closes the listener at
+// once (a new connection is refused) and waits for the requests in
+// flight, for up to drain. Upgraded connections (the WebSocket doors:
+// interactive sessions, run and demo box legs), which Shutdown does not
+// track, are closed as it starts, so their handlers wind down inside the
+// same bound. At the bound, whatever still runs is named in the log and
+// cut: request contexts cancelled, connections closed, and cutGrace for
+// the handlers to return.
+// 2. Close worker admission (a worker started from here on never runs),
+// cancel the background workers' context and the HA capacity observer's,
+// and wait for both for up to workerWait, naming any worker that did not
+// return.
+// 3. Release the app policy writer lease, so a successor need not wait out
+// its TTL, and only once the capacity observer has been joined (the
+// order the stand-down has always kept). An observer still running
+// leaves the lease to expire instead.
+//
+// A second signal stops waiting: what is running is named and cut, and the
+// process exits 1. Taken before the release decision, it also leaves the
+// lease to expire. Taken while a release is under way, the stop exits
+// without waiting for it, but a release request already sent to the store
+// cannot be called back, so the lease may be released anyway.
+type consoleStop struct {
+ srv *http.Server // nil until serving: a stop before it has no requests to drain
+ reqs *requests
+ cancelRequests context.CancelFunc
+
+ work *workers
+ stopCapacity func()
+ capacityDone <-chan struct{}
+ release func(context.Context)
+
+ drain, cutGrace, workerWait time.Duration
+ logf func(string, ...any)
+ now func() time.Time
+}
+
+// attach makes h the server a stop drains: request contexts derive from one
+// the cut cancels, each handler is counted while it runs, and upgraded
+// connections are tracked so the stop can close them.
+func (p *consoleStop) attach(h *http.Server) {
+ reqCtx, cancel := context.WithCancel(context.Background())
+ p.reqs = newRequests(p.now)
+ p.cancelRequests = cancel
+ h.BaseContext = func(net.Listener) context.Context { return reqCtx }
+ connCtx := h.ConnContext
+ h.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
+ if connCtx != nil {
+ ctx = connCtx(ctx, c)
+ }
+ return context.WithValue(ctx, connKey{}, c)
+ }
+ connState := h.ConnState
+ h.ConnState = func(c net.Conn, st http.ConnState) {
+ if connState != nil {
+ connState(c, st)
+ }
+ if st == http.StateHijacked {
+ p.reqs.hijacked(c)
+ }
+ }
+ h.Handler = p.reqs.wrap(h.Handler)
+ h.RegisterOnShutdown(func() {
+ if n := p.reqs.closeHijacked(); n > 0 {
+ p.logf("console: stop: closed %d upgraded connection(s) (WebSocket sessions and box legs)", n)
+ }
+ })
+ p.srv = h
+}
+
+// untilServing handles a signal that arrives while serve is still starting
+// (workers running, nothing listening yet): the same stop with no requests
+// to drain, then exit. The returned handOff is called just before serving;
+// it returns once the early handler has stood down, or never if a signal
+// already started a stop (exit ends the process).
+func (p *consoleStop) untilServing(sigs <-chan os.Signal, exit func(int)) (handOff func()) {
+ early := *p // no server yet; main may set p.srv while this goroutine waits
+ taken := make(chan struct{})
+ go func() {
+ select {
+ case sig := <-sigs:
+ early.logf("console: %v before serving: stopping", sig)
+ code := 0
+ if early.stop(sigs) {
+ code = 1
+ }
+ exit(code)
+ case taken <- struct{}{}:
+ }
+ }()
+ return func() { <-taken }
+}
+
+// serve serves ln until a signal (or a failed Serve), then stops, and
+// returns the exit status: 0 after a requested stop, even one whose bound
+// cut something (the log names it); 1 after a second signal or when Serve
+// itself failed.
+func (p *consoleStop) serve(ln net.Listener, sigs <-chan os.Signal) int {
+ served := make(chan error, 1)
+ go func() { served <- p.srv.Serve(ln) }()
+ code := 0
+ select {
+ case sig := <-sigs:
+ p.logf("console: %v: stopping", sig)
+ case err := <-served:
+ p.logf("console: serving failed: %v; stopping", err)
+ code = 1
+ }
+ if p.stop(sigs) {
+ code = 1
+ }
+ return code
+}
+
+// stopRun is one stop in progress. Its goroutine is the only reader of sigs
+// from the first signal on, and it reads them only inside await and
+// pending, so whether a second signal has been taken (forced) is decided in
+// one place, in order with the waits, the release decision and the exit
+// status: no other goroutine can hold a signal it has taken but not yet
+// acted on.
+type stopRun struct {
+ *consoleStop
+ sigs <-chan os.Signal
+ force context.Context // cancelled by a second signal
+ cancel context.CancelFunc
+ forced bool
+}
+
+// hurry acts on a second signal: every wait derived from force ends.
+func (r *stopRun) hurry(sig os.Signal) {
+ if r.forced {
+ return
+ }
+ r.forced = true
+ r.logf("console: %v again: stopping now", sig)
+ r.cancel()
+}
+
+// pending takes a second signal already queued, without waiting.
+func (r *stopRun) pending() {
+ select {
+ case sig := <-r.sigs:
+ r.hurry(sig)
+ default:
+ }
+}
+
+// await waits for done until ctx (derived from force) ends, taking a second
+// signal if one comes, and reports whether done was closed. A done already
+// closed wins over a ctx already ended.
+func (r *stopRun) await(ctx context.Context, done <-chan struct{}) bool {
+ for {
+ select {
+ case <-done:
+ return true
+ default:
+ }
+ select {
+ case <-done:
+ return true
+ case <-ctx.Done():
+ return closed(done)
+ case sig := <-r.sigs:
+ r.hurry(sig)
+ }
+ }
+}
+
+func closed(ch <-chan struct{}) bool {
+ select {
+ case <-ch:
+ return true
+ default:
+ return false
+ }
+}
+
+// stop runs the three steps and reports whether a second signal cut it short.
+func (p *consoleStop) stop(sigs <-chan os.Signal) (forced bool) {
+ force, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r := &stopRun{consoleStop: p, sigs: sigs, force: force, cancel: cancel}
+ if p.srv != nil {
+ r.drainRequests()
+ }
+ capacityJoined := r.stopWorkers()
+ // The release decision. A second signal queued by now counts.
+ r.pending()
+ switch {
+ case r.forced:
+ p.logf("console: stop: the policy writer lease was not released (second signal); a successor waits out its TTL")
+ return true
+ case !capacityJoined:
+ p.logf("console: stop: the HA capacity observer did not stop within %s; the policy writer lease was not released and expires on its own", p.workerWait)
+ return false
+ }
+ // From here a release is issued. A second signal stops the wait for it,
+ // and the exit status is 1, but cannot undo a release request already
+ // sent: the lease may be released anyway.
+ released := make(chan struct{})
+ go func() {
+ defer close(released)
+ p.release(force)
+ }()
+ if !r.await(force, released) || r.forced {
+ p.logf("console: stop: exiting during the policy writer lease release (second signal); a release already sent may still land, otherwise a successor waits out its TTL")
+ return true
+ }
+ r.pending()
+ if r.forced {
+ return true
+ }
+ p.logf("console: stopped")
+ return false
+}
+
+// why names what ended a wait early: the second signal, or else the bound.
+func (r *stopRun) why(bound string) string {
+ if r.forced {
+ return "at the second signal"
+ }
+ return bound
+}
+
+func (r *stopRun) drainRequests() {
+ p := r.consoleStop
+ p.logf("console: stop: not accepting connections; draining requests for up to %s", p.drain)
+ ctx, cancel := context.WithTimeout(r.force, p.drain)
+ defer cancel()
+ shut := make(chan struct{})
+ var shutErr error
+ go func() {
+ defer close(shut)
+ shutErr = p.srv.Shutdown(ctx)
+ }()
+ // Shutdown does not wait for upgraded connections' handlers; they were
+ // closed as it started and wind down in the second wait.
+ if r.await(ctx, shut) && shutErr == nil && r.await(ctx, p.reqs.run.done()) {
+ return
+ }
+ left := p.reqs.run.labels()
+ p.logf("console: stop: cut %d request(s) still running %s: %s", len(left), r.why(fmt.Sprintf("after %s", p.drain)), strings.Join(left, ", "))
+ p.cancelRequests()
+ p.srv.Close()
+ p.reqs.closeHijacked()
+ if r.forced {
+ return
+ }
+ gctx, gcancel := context.WithTimeout(r.force, p.cutGrace)
+ defer gcancel()
+ if !r.await(gctx, p.reqs.run.done()) {
+ left := p.reqs.run.labels()
+ p.logf("console: stop: %d handler(s) still running %s after the cut, left to the exit: %s", len(left), p.cutGrace, strings.Join(left, ", "))
+ }
+}
+
+// stopWorkers closes admission, cancels the workers and the capacity
+// observer and waits for both; it reports whether the observer was joined.
+func (r *stopRun) stopWorkers() bool {
+ p := r.consoleStop
+ p.work.run.closeAdmission()
+ p.work.cancel()
+ p.stopCapacity()
+ ctx, cancel := context.WithTimeout(r.force, p.workerWait)
+ defer cancel()
+ if !r.await(ctx, p.work.run.done()) {
+ left := p.work.run.labels()
+ p.logf("console: stop: %d background worker(s) did not stop %s, cut: %s", len(left), r.why(fmt.Sprintf("within %s", p.workerWait)), strings.Join(left, ", "))
+ }
+ return r.await(ctx, p.capacityDone)
+}
+
+// workers runs the console's background loops on one context, so a stop
+// cancels them together and can wait for them with a bound.
+type workers struct {
+ ctx context.Context
+ cancel context.CancelFunc
+ run *running
+}
+
+func newWorkers(parent context.Context, now func() time.Time) *workers {
+ ctx, cancel := context.WithCancel(parent)
+ return &workers{ctx: ctx, cancel: cancel, run: newRunning(now)}
+}
+
+// Go runs f(ctx) in its own goroutine, named so a stop that outlasts its
+// bound can say which worker it cut. Once a stop has closed admission, f
+// never runs and Go reports false.
+func (w *workers) Go(name string, f func(context.Context)) bool {
+ e := w.run.start(name)
+ if e == nil {
+ return false
+ }
+ go func() {
+ defer w.run.end(e)
+ f(w.ctx)
+ }()
+ return true
+}
+
+// Spawn is Go for an entry point that does its setup synchronously, starts
+// its own goroutine and returns a channel closed when that goroutine ends
+// (StartVerifyReader): start runs in the caller, and the worker counts as
+// running until the channel closes. Once admission is closed, start is
+// never called.
+func (w *workers) Spawn(name string, start func(context.Context) <-chan struct{}) bool {
+ e := w.run.start(name)
+ if e == nil {
+ return false
+ }
+ done := start(w.ctx)
+ go func() {
+ defer w.run.end(e)
+ <-done
+ }()
+ return true
+}
+
+// requests counts the handlers running and the connections they upgraded.
+type requests struct {
+ run *running
+
+ mu sync.Mutex
+ conns map[net.Conn]struct{}
+ closing bool
+}
+
+type connKey struct{}
+
+func newRequests(now func() time.Time) *requests {
+ return &requests{run: newRunning(now), conns: map[net.Conn]struct{}{}}
+}
+
+// wrap counts h's handlers. The writer and request pass through unchanged.
+// Only the path is logged at a cut, never the query string.
+func (q *requests) wrap(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ e := q.run.start(r.Method + " " + r.URL.Path)
+ defer q.run.end(e)
+ if c, ok := r.Context().Value(connKey{}).(net.Conn); ok {
+ defer q.forget(c)
+ }
+ h.ServeHTTP(w, r)
+ })
+}
+
+// hijacked records a connection a handler took over; once the stop has
+// started it is closed at once instead.
+func (q *requests) hijacked(c net.Conn) {
+ q.mu.Lock()
+ if q.closing {
+ q.mu.Unlock()
+ c.Close()
+ return
+ }
+ q.conns[c] = struct{}{}
+ q.mu.Unlock()
+}
+
+// forget drops c when the handler that may have upgraded it returns.
+func (q *requests) forget(c net.Conn) {
+ q.mu.Lock()
+ delete(q.conns, c)
+ q.mu.Unlock()
+}
+
+// closeHijacked closes every upgraded connection and every one upgraded
+// from now on, and returns how many it closed now.
+func (q *requests) closeHijacked() int {
+ q.mu.Lock()
+ q.closing = true
+ conns := make([]net.Conn, 0, len(q.conns))
+ for c := range q.conns {
+ conns = append(conns, c)
+ }
+ clear(q.conns)
+ q.mu.Unlock()
+ for _, c := range conns {
+ c.Close()
+ }
+ return len(conns)
+}
+
+// running is a set of labelled things in progress, waited on with a bound.
+// Not a sync.WaitGroup: an add after a wait has begun (a request read just
+// as the server closes) is legal here, unless admission has been closed.
+type running struct {
+ now func() time.Time
+
+ mu sync.Mutex
+ set map[*runEntry]struct{}
+ empty chan struct{} // made by the first done; closed once the set is empty
+ emptied bool
+ refusing bool // admission closed: start returns nil
+}
+
+type runEntry struct {
+ label string
+ since time.Time
+}
+
+func newRunning(now func() time.Time) *running {
+ return &running{now: now, set: map[*runEntry]struct{}{}}
+}
+
+// start adds label, or returns nil once admission is closed.
+func (r *running) start(label string) *runEntry {
+ e := &runEntry{label: label, since: r.now()}
+ r.mu.Lock()
+ if r.refusing {
+ r.mu.Unlock()
+ return nil
+ }
+ if r.emptied {
+ // A wait already saw the set empty and returned; the next one
+ // waits afresh.
+ r.empty, r.emptied = nil, false
+ }
+ r.set[e] = struct{}{}
+ r.mu.Unlock()
+ return e
+}
+
+func (r *running) end(e *runEntry) {
+ r.mu.Lock()
+ delete(r.set, e)
+ r.signalLocked()
+ r.mu.Unlock()
+}
+
+func (r *running) signalLocked() {
+ if r.empty != nil && !r.emptied && len(r.set) == 0 {
+ r.emptied = true
+ close(r.empty)
+ }
+}
+
+// closeAdmission makes every later start return nil, so the set can only
+// shrink and a done that closes stays true.
+func (r *running) closeAdmission() {
+ r.mu.Lock()
+ r.refusing = true
+ r.mu.Unlock()
+}
+
+// done returns a channel closed once nothing is running. Before admission is
+// closed, a later start makes the next done a fresh channel.
+func (r *running) done() <-chan struct{} {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.empty == nil {
+ r.empty = make(chan struct{})
+ r.signalLocked()
+ }
+ return r.empty
+}
+
+// labels names what is still running, oldest first, with how long each has
+// run.
+func (r *running) labels() []string {
+ r.mu.Lock()
+ entries := make([]*runEntry, 0, len(r.set))
+ for e := range r.set {
+ entries = append(entries, e)
+ }
+ r.mu.Unlock()
+ sort.Slice(entries, func(i, j int) bool { return entries[i].since.Before(entries[j].since) })
+ now := r.now()
+ out := make([]string, len(entries))
+ for i, e := range entries {
+ out[i] = fmt.Sprintf("%s (%s)", e.label, now.Sub(e.since).Round(time.Second))
+ }
+ return out
+}
diff --git a/cmd/console/stop_test.go b/cmd/console/stop_test.go
new file mode 100644
index 000000000..a36964cd3
--- /dev/null
+++ b/cmd/console/stop_test.go
@@ -0,0 +1,588 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "runtime"
+ "slices"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+)
+
+// stopRig is a consoleStop wired to fakes that record what happened in
+// which order: one worker that returns when its context ends, a capacity
+// observer that is joined when cancelled, and a lease release.
+type stopRig struct {
+ t *testing.T
+ stop *consoleStop
+ sigs chan os.Signal
+ mu sync.Mutex
+ events []string
+ logs []string
+}
+
+func newStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration) *stopRig {
+ return buildStopRig(t, drain, cutGrace, workerWait, false)
+}
+
+// newBareStopRig has no worker and an observer already joined, for the
+// tests about one worker or one signal, so nothing else races their bound.
+func newBareStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration) *stopRig {
+ return buildStopRig(t, drain, cutGrace, workerWait, true)
+}
+
+func buildStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration, bare bool) *stopRig {
+ t.Helper()
+ r := &stopRig{t: t, sigs: make(chan os.Signal, 2)}
+ work := newWorkers(context.Background(), time.Now)
+ capacityCtx, stopCapacity := context.WithCancel(work.ctx)
+ capacityDone := make(chan struct{})
+ if bare {
+ close(capacityDone)
+ } else {
+ go func() {
+ <-capacityCtx.Done()
+ r.event("capacity joined")
+ close(capacityDone)
+ }()
+ work.Go("loop", func(ctx context.Context) {
+ <-ctx.Done()
+ r.event("worker joined")
+ })
+ }
+ // Registered first, so it runs after each test's own cleanups (which
+ // free what the test held stuck): cancel and join the fixture's
+ // goroutines.
+ t.Cleanup(func() {
+ work.cancel()
+ stopCapacity()
+ <-capacityDone
+ <-work.run.done()
+ })
+ r.stop = &consoleStop{
+ work: work,
+ stopCapacity: stopCapacity,
+ capacityDone: capacityDone,
+ release: func(context.Context) { r.event("lease released") },
+ drain: drain,
+ cutGrace: cutGrace,
+ workerWait: workerWait,
+ logf: func(format string, a ...any) {
+ r.mu.Lock()
+ r.logs = append(r.logs, fmt.Sprintf(format, a...))
+ r.mu.Unlock()
+ },
+ now: time.Now,
+ }
+ return r
+}
+
+func (r *stopRig) event(e string) {
+ r.mu.Lock()
+ r.events = append(r.events, e)
+ r.mu.Unlock()
+}
+
+func (r *stopRig) eventList() []string {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return slices.Clone(r.events)
+}
+
+func (r *stopRig) log() string {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return strings.Join(r.logs, "\n")
+}
+
+// serve attaches h through the production constructor and serves it on a
+// loopback listener. It returns the address, a channel closed once Shutdown
+// has closed the listener, and the serve result.
+func (r *stopRig) serve(h http.Handler) (addr string, shutdownStarted <-chan struct{}, result <-chan int) {
+ r.t.Helper()
+ srv := console.NewHTTPServer(h)
+ r.stop.attach(srv)
+ started := make(chan struct{})
+ // Shutdown runs its hooks after it has closed the listeners.
+ srv.RegisterOnShutdown(func() { close(started) })
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ res := make(chan int, 1)
+ go func() { res <- r.stop.serve(ln, r.sigs) }()
+ return ln.Addr().String(), started, res
+}
+
+// guard fails the test rather than hang it when ch never delivers.
+func guard[T any](t *testing.T, ch <-chan T, what string) T {
+ t.Helper()
+ select {
+ case v := <-ch:
+ return v
+ case <-time.After(30 * time.Second):
+ t.Fatalf("%s: nothing after 30s", what)
+ panic("unreachable")
+ }
+}
+
+func indexOf(t *testing.T, events []string, e string) int {
+ t.Helper()
+ i := slices.Index(events, e)
+ if i < 0 {
+ t.Fatalf("no %q in %v", e, events)
+ }
+ return i
+}
+
+// A request in flight at SIGTERM completes; a new connection after the
+// signal is refused; the workers and the capacity observer are joined after
+// the drain, and the lease is released last.
+func TestConsoleStopDrainsInFlightRequest(t *testing.T) {
+ r := newStopRig(t, time.Minute, time.Minute, time.Minute)
+ entered, proceed := make(chan struct{}), make(chan struct{})
+ addr, shutdownStarted, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ close(entered)
+ <-proceed
+ io.WriteString(w, "done")
+ r.event("handler returned")
+ }))
+ type reply struct {
+ status int
+ body string
+ err error
+ }
+ got := make(chan reply, 1)
+ go func() {
+ resp, err := http.Get("http://" + addr + "/slow")
+ if err != nil {
+ got <- reply{err: err}
+ return
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ got <- reply{resp.StatusCode, string(b), err}
+ }()
+ guard(t, entered, "request entering the handler")
+ r.sigs <- syscall.SIGTERM
+ guard(t, shutdownStarted, "Shutdown starting")
+
+ if c, err := net.Dial("tcp", addr); err == nil {
+ c.Close()
+ t.Fatal("a new connection was accepted after the signal")
+ }
+ select {
+ case code := <-result:
+ t.Fatalf("serve returned %d with a request still in flight", code)
+ default:
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Fatal("the lease was released while a request was in flight")
+ }
+
+ close(proceed)
+ rep := guard(t, got, "the in-flight reply")
+ if rep.err != nil || rep.status != http.StatusOK || rep.body != "done" {
+ t.Fatalf("in-flight request: status %d body %q err %v; want 200 \"done\"", rep.status, rep.body, rep.err)
+ }
+ if code := guard(t, result, "serve returning"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ ev := r.eventList()
+ handler, worker, capacity, release := indexOf(t, ev, "handler returned"), indexOf(t, ev, "worker joined"), indexOf(t, ev, "capacity joined"), indexOf(t, ev, "lease released")
+ if handler > worker || handler > capacity {
+ t.Errorf("workers stopped before the drain finished: %v", ev)
+ }
+ if release < worker || release < capacity {
+ t.Errorf("lease released before the workers and capacity observer were joined: %v", ev)
+ }
+ if strings.Contains(r.log(), "cut") {
+ t.Errorf("a clean drain logged a cut:\n%s", r.log())
+ }
+}
+
+// A handler that ignores its context and never returns is cut at the
+// drain bound: the stop names it, the client's connection is closed, the
+// lease is still released, and serve returns.
+func TestConsoleStopCutsStuckHandlerAtBound(t *testing.T) {
+ r := newStopRig(t, 50*time.Millisecond, 50*time.Millisecond, time.Minute)
+ entered, unstick := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ addr, _, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ close(entered)
+ <-unstick
+ }))
+ clientErr := make(chan error, 1)
+ go func() {
+ resp, err := http.Get("http://" + addr + "/stuck?token=secret")
+ if err == nil {
+ resp.Body.Close()
+ }
+ clientErr <- err
+ }()
+ guard(t, entered, "request entering the handler")
+ r.sigs <- syscall.SIGTERM
+ if code := guard(t, result, "serve returning"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ if err := guard(t, clientErr, "the client"); err == nil {
+ t.Error("the cut request's client got a response")
+ }
+ log := r.log()
+ if !strings.Contains(log, "cut 1 request(s) still running after 50ms: GET /stuck (") {
+ t.Errorf("the cut is not named:\n%s", log)
+ }
+ if strings.Contains(log, "secret") {
+ t.Errorf("a query string reached the log:\n%s", log)
+ }
+ if !strings.Contains(log, "1 handler(s) still running 50ms after the cut") {
+ t.Errorf("the handler left running is not named:\n%s", log)
+ }
+ ev := r.eventList()
+ if indexOf(t, ev, "lease released") < indexOf(t, ev, "capacity joined") {
+ t.Errorf("lease released before the capacity observer was joined: %v", ev)
+ }
+}
+
+// Upgraded connections (the WebSocket doors), which Shutdown does not wait
+// for, are closed as the stop starts, so a session cannot hold the drain to
+// its bound.
+func TestConsoleStopClosesUpgradedConnections(t *testing.T) {
+ r := newStopRig(t, time.Hour, time.Hour, time.Minute)
+ upgraded := make(chan struct{})
+ addr, _, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ c, buf, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer c.Close()
+ buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n")
+ buf.Flush()
+ close(upgraded)
+ _, _ = io.Copy(io.Discard, c) // until the connection is closed
+ r.event("session returned")
+ }))
+ c, err := net.Dial("tcp", addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ fmt.Fprintf(c, "GET /session HTTP/1.1\r\nHost: console\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n")
+ if line, err := bufio.NewReader(c).ReadString('\n'); err != nil || !strings.Contains(line, "101") {
+ t.Fatalf("upgrade: %q %v", line, err)
+ }
+ guard(t, upgraded, "the upgrade")
+ r.sigs <- syscall.SIGTERM
+ if code := guard(t, result, "serve returning"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ ev := r.eventList()
+ if indexOf(t, ev, "session returned") > indexOf(t, ev, "lease released") {
+ t.Errorf("the session handler returned after the lease release: %v", ev)
+ }
+ if !strings.Contains(r.log(), "closed 1 upgraded connection(s)") {
+ t.Errorf("the closed session is not logged:\n%s", r.log())
+ }
+ if strings.Contains(r.log(), "cut") {
+ t.Errorf("the session was cut at the bound, not closed at the start:\n%s", r.log())
+ }
+}
+
+// A second signal stops waiting: the stuck request is named and cut, the
+// lease is left to expire, and the exit status is 1.
+func TestConsoleStopSecondSignal(t *testing.T) {
+ r := newStopRig(t, time.Hour, time.Hour, time.Hour)
+ entered, unstick := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ addr, shutdownStarted, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ close(entered)
+ <-unstick
+ }))
+ go func() {
+ if resp, err := http.Get("http://" + addr + "/stuck"); err == nil {
+ resp.Body.Close()
+ }
+ }()
+ guard(t, entered, "request entering the handler")
+ r.sigs <- syscall.SIGTERM
+ guard(t, shutdownStarted, "Shutdown starting")
+ r.sigs <- os.Interrupt
+ if code := guard(t, result, "serve returning"); code != 1 {
+ t.Fatalf("exit status %d, want 1", code)
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was released after a second signal")
+ }
+ log := r.log()
+ for _, want := range []string{"interrupt again: stopping now", "cut 1 request(s) still running at the second signal: GET /stuck (", "not released (second signal)"} {
+ if !strings.Contains(log, want) {
+ t.Errorf("log lacks %q:\n%s", want, log)
+ }
+ }
+}
+
+// A worker that ignores its context is named at the worker bound and the
+// lease is still released, since the capacity observer was joined. An
+// observer that is not joined keeps the lease from being released.
+func TestConsoleStopWorkerBound(t *testing.T) {
+ t.Run("stuck worker", func(t *testing.T) {
+ r := newBareStopRig(t, time.Minute, time.Minute, 50*time.Millisecond)
+ unstick := make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ r.stop.work.Go("StartStuckPass", func(context.Context) { <-unstick })
+ if r.stop.stop(r.sigs) {
+ t.Fatal("reported a second signal")
+ }
+ if !strings.Contains(r.log(), "1 background worker(s) did not stop within 50ms, cut: StartStuckPass (") {
+ t.Errorf("the stuck worker is not named:\n%s", r.log())
+ }
+ if !slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was not released")
+ }
+ })
+ t.Run("capacity observer not joined", func(t *testing.T) {
+ r := newBareStopRig(t, time.Minute, time.Minute, 50*time.Millisecond)
+ r.stop.capacityDone = make(chan struct{}) // never closed
+ if r.stop.stop(r.sigs) {
+ t.Fatal("reported a second signal")
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was released before the capacity observer was joined")
+ }
+ if !strings.Contains(r.log(), "HA capacity observer did not stop") {
+ t.Errorf("the skipped release is not logged:\n%s", r.log())
+ }
+ })
+}
+
+// A signal before serving begins stops the workers, releases the lease and
+// exits 0; with no signal, handOff stands the early handler down so the
+// next signal reaches serve.
+func TestConsoleStopBeforeServing(t *testing.T) {
+ t.Run("signal", func(t *testing.T) {
+ r := newStopRig(t, time.Minute, time.Minute, time.Minute)
+ exited := make(chan int, 1)
+ r.stop.untilServing(r.sigs, func(code int) { exited <- code })
+ r.sigs <- syscall.SIGTERM
+ if code := guard(t, exited, "the early stop exiting"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ ev := r.eventList()
+ if indexOf(t, ev, "lease released") < indexOf(t, ev, "capacity joined") || indexOf(t, ev, "lease released") < indexOf(t, ev, "worker joined") {
+ t.Errorf("lease released before the joins: %v", ev)
+ }
+ })
+ t.Run("hand off", func(t *testing.T) {
+ r := newStopRig(t, time.Minute, time.Minute, time.Minute)
+ handOff := r.stop.untilServing(r.sigs, func(code int) { t.Errorf("early stop exited %d", code) })
+ handOff()
+ r.sigs <- syscall.SIGTERM
+ if len(r.sigs) != 1 {
+ t.Fatal("the early handler took a signal after the hand-off")
+ }
+ })
+}
+
+// running.done is closed at once when nothing runs, a start after a done
+// that saw it empty is waited for by the next done, and once admission is
+// closed a start is refused.
+func TestRunningDoneRearms(t *testing.T) {
+ r := newRunning(time.Now)
+ if !closed(r.done()) {
+ t.Fatal("empty: done not closed")
+ }
+ e := r.start("late")
+ if closed(r.done()) {
+ t.Fatal("done closed with one running")
+ }
+ r.end(e)
+ if !closed(r.done()) {
+ t.Fatal("after end: done not closed")
+ }
+ r.closeAdmission()
+ if r.start("later") != nil {
+ t.Fatal("a start was admitted after admission closed")
+ }
+ if !closed(r.done()) {
+ t.Fatal("a refused start reopened done")
+ }
+}
+
+// testWorkers is a workers whose goroutines the test's cleanup cancels and
+// joins.
+func testWorkers(t *testing.T) *workers {
+ t.Helper()
+ w := newWorkers(context.Background(), time.Now)
+ t.Cleanup(func() {
+ w.cancel()
+ <-w.run.done()
+ })
+ return w
+}
+
+// A second signal already queued when the waits have all finished is taken
+// at the release decision: no release, exit status 1. The new stop takes it
+// there whatever the scheduling. GOMAXPROCS(1) only makes it likely, not
+// certain (the scheduler can still preempt), that the old asynchronous
+// watcher had not run by then, which is how this test caught the old race.
+func TestConsoleStopQueuedSecondSignalBeforeRelease(t *testing.T) {
+ defer runtimeGOMAXPROCS(1)()
+ r := newBareStopRig(t, time.Minute, time.Minute, time.Minute)
+ r.sigs <- os.Interrupt
+ if !r.stop.stop(r.sigs) {
+ t.Fatal("a queued second signal did not make the stop forced")
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Fatal("the lease was released with a second signal queued")
+ }
+}
+
+// A second signal while a worker is still running ends the worker wait,
+// names the worker, and leaves the lease unreleased.
+func TestConsoleStopSecondSignalDuringWorkerWait(t *testing.T) {
+ r := newBareStopRig(t, time.Minute, time.Minute, time.Hour)
+ cancelled, unstick := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ r.stop.work.Go("StartStuckPass", func(ctx context.Context) {
+ <-ctx.Done()
+ close(cancelled)
+ <-unstick
+ })
+ forced := make(chan bool, 1)
+ go func() { forced <- r.stop.stop(r.sigs) }()
+ guard(t, cancelled, "the worker's cancellation")
+ r.sigs <- os.Interrupt
+ if !guard(t, forced, "the stop returning") {
+ t.Fatal("not reported as forced")
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was released after a second signal")
+ }
+ if !strings.Contains(r.log(), "1 background worker(s) did not stop at the second signal, cut: StartStuckPass (") {
+ t.Errorf("the cut worker is not named:\n%s", r.log())
+ }
+}
+
+// A second signal during the lease release returns at once with status 1,
+// without waiting for a release that does not return.
+func TestConsoleStopSecondSignalDuringRelease(t *testing.T) {
+ r := newBareStopRig(t, time.Minute, time.Minute, time.Minute)
+ started, unstick := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ r.stop.release = func(context.Context) {
+ close(started)
+ <-unstick // a release that ignores its context
+ }
+ forced := make(chan bool, 1)
+ go func() { forced <- r.stop.stop(r.sigs) }()
+ guard(t, started, "the release starting")
+ r.sigs <- os.Interrupt
+ if !guard(t, forced, "the stop returning") {
+ t.Fatal("not reported as forced")
+ }
+ if !strings.Contains(r.log(), "exiting during the policy writer lease release") {
+ t.Errorf("the abandoned release is not logged:\n%s", r.log())
+ }
+}
+
+// Once the stop has begun joining the workers, a worker start is refused
+// and never runs, and the join does not end with it running.
+func TestConsoleStopRefusesWorkersAfterJoinBegins(t *testing.T) {
+ r := newBareStopRig(t, time.Minute, time.Minute, time.Hour)
+ cancelled, unstick := make(chan struct{}), make(chan struct{})
+ r.stop.work.Go("StartSlowPass", func(ctx context.Context) {
+ <-ctx.Done()
+ close(cancelled)
+ <-unstick
+ })
+ result := make(chan bool, 1)
+ go func() { result <- r.stop.stop(r.sigs) }()
+ guard(t, cancelled, "the worker's cancellation")
+ ran := make(chan struct{})
+ never := make(chan struct{})
+ t.Cleanup(func() { close(never) })
+ if r.stop.work.Go("late", func(context.Context) { close(ran); <-never }) {
+ t.Error("Go admitted a worker after the join began")
+ }
+ if r.stop.work.Spawn("lateSpawn", func(context.Context) <-chan struct{} { close(ran); return never }) {
+ t.Error("Spawn admitted a worker after the join began")
+ }
+ close(unstick)
+ if guard(t, result, "the stop returning") {
+ t.Fatal("reported as forced")
+ }
+ if closed(ran) {
+ t.Fatal("a worker started after the join began ran")
+ }
+ if left := r.stop.work.run.labels(); len(left) != 0 {
+ t.Fatalf("still running after the join: %v", left)
+ }
+ if !slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was not released")
+ }
+}
+
+// A worker whose own goroutine runs past its entry point (Spawn, as the
+// verify reader is started) is waited for until that goroutine ends, and
+// named when it outlasts the bound.
+func TestConsoleStopNamesASpawnedWorker(t *testing.T) {
+ r := newBareStopRig(t, time.Minute, time.Minute, 50*time.Millisecond)
+ unstick := make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ if !r.stop.work.Spawn("StartVerifyReader", func(ctx context.Context) <-chan struct{} {
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ <-unstick // a tick that ignores ctx
+ }()
+ return done
+ }) {
+ t.Fatal("Spawn refused before any stop")
+ }
+ if r.stop.stop(r.sigs) {
+ t.Fatal("reported as forced")
+ }
+ if !strings.Contains(r.log(), "1 background worker(s) did not stop within 50ms, cut: StartVerifyReader (") {
+ t.Errorf("the spawned worker is not named:\n%s", r.log())
+ }
+}
+
+// The GeoIP follower runs as a worker and ends with work's context; the
+// override's expiry watcher ends when its context does.
+func TestConsoleGeoReaderRunsAsAWorker(t *testing.T) {
+ t.Setenv("CARLOS_DATA_DIR", t.TempDir())
+ w := newWorkers(context.Background(), time.Now)
+ if consoleGeoReader("", w) == nil {
+ t.Fatal("no follower reader")
+ }
+ if left := w.run.labels(); len(left) != 1 || !strings.HasPrefix(left[0], "geoipFollower (") {
+ t.Fatalf("workers running: %v, want the follower", left)
+ }
+ w.cancel()
+ guard(t, w.run.done(), "the follower ending")
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ ended := make(chan struct{})
+ go func() {
+ defer close(ended)
+ watchGeoIPExpiry(ctx, nil, "override.mmdb", time.Hour, time.Now)
+ }()
+ guard(t, ended, "the expiry watcher ending")
+}
+
+func runtimeGOMAXPROCS(n int) (restore func()) {
+ old := runtime.GOMAXPROCS(n)
+ return func() { runtime.GOMAXPROCS(old) }
+}
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-audit-console-shutdown-R1-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-audit-console-shutdown-R1-fix.md
new file mode 100644
index 000000000..7ed541611
--- /dev/null
+++ b/docs/superpowers/reviews/CHECK-BRIEF-audit-console-shutdown-R1-fix.md
@@ -0,0 +1,30 @@
+# Scoped check: audit-console-shutdown, after round 1 (not a review round)
+
+Repo carlos/platform, branch `audit-console-shutdown` (tip in the prompt).
+
+Round 1 (`docs/superpowers/reviews/FINDINGS-audit-console-shutdown-R1.md`)
+ended READY AFTER FIXES with four P2s and one P3. The fix is commit
+a2e41dfe. AGENTS.md "Stopping rules" rule 1: the review does not reopen,
+but newly changed termination behaviour is checked. This is that check.
+
+Scope: `git show a2e41dfe` only.
+
+Check:
+1. Each round-1 finding: resolved, partly, not (one line each).
+2. Does the fix introduce a path where the process never exits, exits 0
+ after a second signal, releases the policy lease while the capacity
+ observer runs, or releases it twice?
+3. Worker admission closes before cancel and join; startup steps on the
+ worker context; a failing startup step during an early stop waits for
+ the stop. Any deadlock between those?
+4. StartRelay now joins its writer-lease loop before returning; the
+ verify reader and the GeoIP loops are joined workers. Could any of
+ these now block startup or shutdown forever (a join on a loop that
+ never sees cancellation)?
+5. New tests: deterministic enough for a loaded runner (one waits 200 ms;
+ one pins GOMAXPROCS=1)?
+
+Answer each item: OK, or a finding with file:line, failure scenario and
+fix, marked P1 (unsafe or broken) or P2. End with exactly one line:
+CHECK PASSED, or CHECK FAILED with the P1s. Do not edit files, do not
+spawn reviewers or agents, do not run full test suites.
diff --git a/docs/superpowers/reviews/CHECK-audit-console-shutdown-R1-fix.md b/docs/superpowers/reviews/CHECK-audit-console-shutdown-R1-fix.md
new file mode 100644
index 000000000..4d6250178
--- /dev/null
+++ b/docs/superpowers/reviews/CHECK-audit-console-shutdown-R1-fix.md
@@ -0,0 +1,41 @@
+Scoped check of `a2e41dfed54263c4d553ebc056761f1b8774e9b3` at checkout `a60c26f6b827f109860626f9fb6776e104cb0651`. This does not reopen round 1. No P1 findings.
+
+1. **Round-1 findings — OK.**
+
+ - **P2-1 resolved:** signal handling, release decisions and forced-exit status now run in one sequence.
+ - **P2-2 resolved:** relay joins its writer loop; verify-reader completion and both GeoIP loops are registered workers.
+ - **P2-3 resolved:** admission closes before cancellation and joining; subsequent worker starts are refused.
+ - **P2-4 resolved:** timeout-specific tests use an empty worker registry and an already-completed observer.
+ - **P3 resolved:** fixture cleanup cancels and joins the handoff test’s worker and observer.
+
+2. **Termination and policy lease — OK.**
+
+ In [stop.go:214](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:214), queued signals are checked before release and after its completion. Signals consumed during waits force status 1. Release runs only after actual capacity-observer completion, and the coordinator invokes it once.
+
+ I found no newly introduced indefinite wait. Ordinary release still depends on the existing release implementation honoring its five-second context; a second signal now lets the coordinator stop waiting even if release ignores cancellation. The comments correctly acknowledge that an already-issued remote release cannot be recalled.
+
+3. **Admission and early startup — OK.**
+
+ [stop.go:294](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:294) closes admission under the same mutex used to register workers, before cancellation and joining. A racing start is either registered or refused.
+
+ The changed startup calls use `work.ctx`. In [main.go:726](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/main.go:726), a startup failure after cancellation waits for the early-stop goroutine’s process exit. That goroutine does not depend on startup reaching handoff, so I found no circular wait.
+
+4. **Nested-loop joins — OK.**
+
+ Relay’s writer loop observes the same cancellation context as its parent. The verify reader closes its completion channel when its loop returns. Both GeoIP loops check cancellation between ticks.
+
+ A stuck store call or local-file operation can leave its worker running, but the console’s worker join remains bounded and names that worker. These additions do not make startup or process shutdown wait indefinitely for those loops.
+
+5. **New tests — P2: the relay regression test can falsely pass under scheduler delay.**
+
+ **Location:** [workerjoin_test.go:45](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/internal/console/workerjoin_test.go:45).
+
+ **Scenario:** Without `defer writer.Wait()`, a loaded runner can delay the relay’s main goroutine for the entire 200 ms observation window. The test then unblocks the writer before the main goroutine resumes, allowing the broken implementation to pass.
+
+ **Fix:** Use `testing/synctest` with the held-store channels created inside its test scope. After cancellation, call `synctest.Wait()` and assert that `returned` remains open; then unblock the writer and verify completion. This tests the join without requiring scheduling within 200 ms.
+
+ The queued-signal test is otherwise sound: its signal is buffered before `stop` runs. `GOMAXPROCS(1)` does not prevent preemption, despite the comment, but the corrected implementation’s assertions do not depend on that claim.
+
+The targeted tests could not start: the read-only sandbox prevented Go from creating its build directory. No tests executed, no full suites ran, no files changed, and no agents were spawned.
+
+CHECK PASSED
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-audit-console-shutdown-R1.md b/docs/superpowers/reviews/FINDINGS-audit-console-shutdown-R1.md
new file mode 100644
index 000000000..3fdec05a1
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-console-shutdown-R1.md
@@ -0,0 +1,52 @@
+Reviewed `c4b44c34..b0f70f0c311a61e46e29ac3c3688930ef3023baf`, round 1 of 3. The requested tip adds only the brief to the implementation commit named there.
+
+No P1 findings.
+
+1. **P2 — A queued second signal can lose to lease release and a successful exit.**
+ **Location:** [stop.go:152](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:152), [stop.go:171](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:171).
+ **Invariant:** A second signal forces exit status 1 and prevents initiation of graceful lease release.
+ The second-signal goroutine sets `hurried` asynchronously. If a second signal is already buffered but that goroutine has not run, completed request and worker waits can lead directly to `p.release(force)` and return `false`. Deferred cancellation can then make the watcher exit without consuming the signal. The existing test avoids this race by keeping shutdown blocked on a handler until the watcher cancels it.
+
+ **Fix:** Serialize second-signal handling, the release decision and the final exit status. Add coverage with a queued second signal and already-completed workers, plus signals during worker waiting and release. Define the release boundary accurately: cancellation cannot undo a remote release already issued.
+
+2. **P2 — The worker join omits live background loops.**
+ **Location:** [main.go:789](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/main.go:789), [stop.go:227](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:227).
+ **Invariant:** Background workers receive cancellation and are joined or named when the shutdown budget expires.
+ `StartVerifyReader` receives `work.ctx`, but its internal goroutine is never registered or joined. `StartRelay` starts `relayWriterLoop` in another goroutine and returns without joining it. The GeoIP follower and override-expiry watcher started through `consoleGeoReader` still run outside the worker context altogether.
+
+ Consequently, shutdown can report completion while these loops remain active; a stuck nested relay renewal is absent from the worker timeout report.
+
+ **Fix:** Give these loops completion signals or blocking entry points and include them in the bounded join. Make `StartRelay` join its child before returning. Add coverage that holds a nested worker open and checks that shutdown waits or names it.
+
+3. **P2 — Early shutdown does not close worker admission.**
+ **Location:** [stop.go:108](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:108), [stop.go:269](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop.go:269).
+ **Invariant:** Once shutdown starts joining workers, startup cannot introduce work outside that join.
+ `untilServing` runs shutdown concurrently with the remainder of `serve`. Startup continues calling `work.Go`, which accepts work even after cancellation. If the registry becomes empty, `wait` can return; a subsequent `Go` rearms the registry, but shutdown does not wait again. The new worker can execute its initial pass while lease release proceeds. Receiving an already-cancelled context does not prevent that function from running.
+
+ **Fix:** Close worker admission atomically before cancellation and joining, and reject subsequent starts. Pass the startup cancellation context through remaining startup operations. Test a worker start attempted after the shutdown join has begun.
+
+4. **P2 — The stuck-worker test depends on cooperative goroutines running within 50 ms.**
+ **Location:** [stop_test.go:316](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop_test.go:316).
+ **Invariant:** Tests distinguish shutdown defects from runner scheduling delays.
+ The test requires both the ordinary worker and capacity observer to finish within 50 ms. On a loaded runner, either may miss that window. Correct production behavior then logs another outstanding worker or retains the lease, failing the exact-count or release assertion.
+
+ **Fix:** Pre-complete the unrelated worker and observer in this timeout-specific test, or control deadline advancement explicitly. Keep cancellation-and-join ordering covered separately by the channel-coordinated drain test.
+
+5. **P3 — The handoff test leaves its fixture goroutines running.**
+ **Location:** [stop_test.go:363](/home/paulca/amadan.net/carlos/platform-audit-console-shutdown/cmd/console/stop_test.go:363).
+ **Invariant:** Test fixtures clean up goroutines they start.
+ The handoff subtest never cancels the worker context, leaving the ordinary worker and capacity observer blocked after the test returns.
+
+ **Fix:** Register fixture cleanup that cancels and joins both. Track this as follow-up work.
+
+The normal serving shutdown order is sound: HTTP shutdown starts first, upgraded connections close through the shutdown hook, outstanding handlers receive the shared drain budget and cut grace, then workers are cancelled. The policy release is gated on actual capacity-observer completion. I found no duplicate release path in the new coordinator.
+
+The nominal budgets total 37 seconds, assuming the release implementation honors its cancellation and timeout. Twenty seconds is a reasonable bounded drain for ordinary requests, but cannot complete every supported operation: rootfs uploads allow an hour, and import checking continues asynchronously after HTTP 202. Interrupted uploads surface as CLI errors, generally transport errors rather than an explanation that the console restarted. Detached import checking remains outside this shutdown lifecycle; its existing restart-and-sweep recovery still applies.
+
+In the cancellation paths inspected, I found no newly introduced durable state requiring operator repair solely because these worker contexts now cancel. Mail deliveries may remain due and be retried; scan callbacks are best effort; seed, lifetime and purchase work retains recovery state.
+
+The four changed source-reading tests retain their principal checks. The new functional shutdown tests distinguish draining, forced cuts, upgraded connections and observer-before-release ordering from the old behavior. Their second-signal and startup coverage needs the additions above.
+
+The targeted test command could not start because the read-only sandbox prevented Go from creating its build directory. No tests executed, no full suites ran, and no files were changed.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-console-shutdown.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-console-shutdown.md
new file mode 100644
index 000000000..e47ee78c9
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-console-shutdown.md
@@ -0,0 +1,50 @@
+# Review brief: branch audit-console-shutdown, round 1 of 3
+
+Repo carlos/platform, branch `audit-console-shutdown`, commit b4e7a657072895e7ff63c5d4028d92b2a310453e.
+Under review: the diff `origin/main...b4e7a657072895e7ff63c5d4028d92b2a310453e` (base c4b44c34).
+Authorities: AGENTS.md on main ("Stopping rules"). Context: amadan #1123,
+batch 2. Outside the root census (cmd/console only).
+
+You are the independent reviewer. This changes the console's
+**termination** behaviour, which runs on every console roll on dev,
+flagship and Tito.
+
+## What to check
+
+1. Order on SIGTERM (cmd/console/stop.go): Shutdown with a 20 s drain,
+ WebSockets closed at once, stuck handlers logged and cut with 2 s
+ grace, worker context cancelled and workers given 10 s, policy writer
+ lease released only after the HA capacity observer has joined (the old
+ ordering guarantee). Any path where the lease is released while the
+ observer still runs, or released twice, or where the process never
+ exits?
+2. A second signal exits 1 without releasing the lease; a signal before
+ serving starts. Correct and race-free?
+3. Every background loop in main.go now runs on the worker context
+ (work.Go / startClaimWorker). Did any worker change behaviour when its
+ context is cancelled (half-written jobs, leases, outbox rows)? Name any
+ that now stop mid-step in a way that leaves state an operator must fix.
+4. The worst case is 37 s against systemd's default TimeoutStopSec of 90 s
+ (the console unit is hand-written on each box and not in git). Is 20 s
+ a good drain for what the console serves (db door, forwarded reads,
+ PDF, ship and import uploads)? Would a long upload in progress be cut
+ in a way the CLI reports clearly?
+5. The source-reading tests changed (claimworkers_started_test.go,
+ hacapacity_test.go, plansponsor_test.go, claim_sweep_test.go): do they
+ still enforce what they enforced?
+6. New tests in stop_test.go: would each fail on the old behaviour; any
+ timing that could flake on a loaded runner?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review (the
+ termination check still applies to the fix).
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix, and
+the invariant each breaks. End with exactly one verdict: READY, READY
+AFTER FIXES, or NOT READY. Do not edit files, spawn reviewers or run full
+suites.
diff --git a/internal/console/geoipfollower.go b/internal/console/geoipfollower.go
index eb6f75762..e1bb548e2 100644
--- a/internal/console/geoipfollower.go
+++ b/internal/console/geoipfollower.go
@@ -6,6 +6,7 @@ package console
// database without a second download or a restart.
import (
+ "context"
"errors"
"log"
"os"
@@ -98,11 +99,17 @@ func (f *geoipFollower) logHourly(msg string) {
}
}
-// Run ticks once a minute, forever (process lifetime, like the console's
-// other loops started from cmd/console).
-func (f *geoipFollower) Run() {
- f.Tick()
- for range time.Tick(time.Minute) {
+// Run ticks at once and then once a minute until ctx ends (cmd/console
+// runs it as one of the workers its stop cancels and waits for).
+func (f *geoipFollower) Run(ctx context.Context) {
+ t := time.NewTicker(time.Minute)
+ defer t.Stop()
+ for {
f.Tick()
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
}
}
diff --git a/internal/console/relayops.go b/internal/console/relayops.go
index 1fdc144fa..1bf07a801 100644
--- a/internal/console/relayops.go
+++ b/internal/console/relayops.go
@@ -268,7 +268,10 @@ func (s *Server) relayWriterLoop(ctx context.Context) {
// StartRelay runs the relay's two background loops: the writer lease, and the
// converging reconcile every five minutes and once at start. Started from
// cmd/console beside the other passes — never from NewServer, which stays
-// goroutine-free so constructing a Server in a test starts nothing.
+// goroutine-free so constructing a Server in a test starts nothing. It
+// returns only once both loops have, so the console's stop, which waits for
+// its workers, waits for the lease loop too and names this worker if that
+// loop is stuck.
//
// Gated on a configured region list rather than on holding the lease: a
// deployment with no relay has nothing to converge and should not be reading
@@ -277,7 +280,13 @@ func (s *Server) StartRelay(ctx context.Context) {
if s.cfg.Releases == nil || len(s.relayRegions()) == 0 {
return
}
- go s.relayWriterLoop(ctx)
+ var writer sync.WaitGroup
+ writer.Add(1)
+ go func() {
+ defer writer.Done()
+ s.relayWriterLoop(ctx)
+ }()
+ defer writer.Wait()
// The first reconcile is the one that finishes whatever the previous
// holder abandoned, so it is worth a short wait for the lease rather
// than five minutes of drift.
diff --git a/internal/console/verifyreader.go b/internal/console/verifyreader.go
index 80049a344..a5373b30c 100644
--- a/internal/console/verifyreader.go
+++ b/internal/console/verifyreader.go
@@ -612,16 +612,22 @@ func verifyRefOfScope(scope string) (string, bool) {
// ctx ends. Not on a console without a deployment store, nor on a
// host-claim console. watch is the record view's change watch, nil when the
// index is not armed (start and relists only). Call it once, before the
-// server listens; a second call is a no-op.
-func (s *Server) StartVerifyReader(ctx context.Context, watch *release.ChangeWatch) {
+// server listens; a second call is a no-op. The returned channel closes
+// when the tick has stopped (at once when none was started), so the
+// console's stop can wait for it.
+func (s *Server) StartVerifyReader(ctx context.Context, watch *release.ChangeWatch) <-chan struct{} {
+ done := make(chan struct{})
if s.cfg.Releases == nil || s.cfg.HostClaim {
- return
+ close(done)
+ return done
}
r := newVerifyReader(s.cfg.Releases, watch, time.Now)
if !s.verify.CompareAndSwap(nil, r) {
- return
+ close(done)
+ return done
}
go func() {
+ defer close(done)
for {
tctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout)
r.tick(tctx, r.now())
@@ -633,4 +639,5 @@ func (s *Server) StartVerifyReader(ctx context.Context, watch *release.ChangeWat
}
}
}()
+ return done
}
diff --git a/internal/console/workerjoin_test.go b/internal/console/workerjoin_test.go
new file mode 100644
index 000000000..f0421036f
--- /dev/null
+++ b/internal/console/workerjoin_test.go
@@ -0,0 +1,89 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// heldGetStore holds every Get until unblock closes, ignoring ctx, the way
+// a stuck store call holds the relay's lease loop.
+type heldGetStore struct {
+ release.Store
+ once sync.Once
+ entered chan struct{}
+ unblock chan struct{}
+}
+
+func (h *heldGetStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ h.once.Do(func() { close(h.entered) })
+ <-h.unblock
+ return nil, "", errors.New("held store")
+}
+
+// StartRelay returns only after its writer-lease loop has: cmd/console's
+// stop waits for StartRelay, so a lease loop it left behind would run on
+// past the stop's join and never be named. In a synctest bubble (the held
+// store's channels are made inside it), synctest.Wait returns once every
+// goroutine is durably blocked, so after the cancel StartRelay has either
+// returned or is parked waiting for the writer, whatever the scheduling.
+func TestStartRelayJoinsItsWriterLoop(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ st := &heldGetStore{Store: release.NewDirStore(t.TempDir()), entered: make(chan struct{}), unblock: make(chan struct{})}
+ s := &Server{cfg: Config{Releases: st, RelayRegions: []string{"eu-west-1"}}}
+ ctx, cancel := context.WithCancel(context.Background())
+ returned := make(chan struct{})
+ go func() {
+ defer close(returned)
+ s.StartRelay(ctx)
+ }()
+ synctest.Wait()
+ select {
+ case <-st.entered:
+ default:
+ t.Fatal("the writer loop never read the lease")
+ }
+ cancel()
+ synctest.Wait()
+ select {
+ case <-returned:
+ close(st.unblock)
+ t.Fatal("StartRelay returned while its writer loop was still in a store call")
+ default:
+ }
+ close(st.unblock)
+ <-returned // a StartRelay that never returns is a bubble deadlock, which fails the test
+ })
+}
+
+// StartVerifyReader's channel closes when its tick goroutine ends, and at
+// once when it starts none.
+func TestStartVerifyReaderReportsItsEnd(t *testing.T) {
+ srv, err := NewServer(Config{Releases: release.NewDirStore(t.TempDir())}, openTestStore(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := srv.StartVerifyReader(ctx, nil)
+ select {
+ case <-done:
+ t.Fatal("closed while the tick runs")
+ default:
+ }
+ select {
+ case <-srv.StartVerifyReader(ctx, nil):
+ default:
+ t.Fatal("a second call, which starts nothing, did not close at once")
+ }
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(30 * time.Second):
+ t.Fatal("the tick did not end with its context")
+ }
+}