code health: context calls in the pin; step 2c in its own file
CI's ratchet: Protection.pin now uses QueryRowContext and BeginTx (the pinned transaction on a context that does not end), bounded by a 30 s pinTimeout. doWakeOnce's step 2c is one call to protectBeforeStart in replicatebeforestart.go, and its two activator tests moved to their own file. Raised with reasons: doWakeOnce 570, activator.go 3783 (the one call) and runAgent 688 (the continuity directory). (#1290)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+128
−90
.amadan/code-health.tsv+3 −3internal/activator/activator.go+4 −22internal/activator/activator_test.go+0 −62internal/activator/replicatebeforestart.go+37 −0internal/activator/replicatebeforestart_test.go+73 −0internal/lease/continuity.go+11 −3
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 9c0a1494b..ab104589a 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -2186,7 +2186,7 @@ func-lines . TestFleetAppServesThroughTheHub - 408 |
| func-lines . runDeploy - 329 |
| func-lines . runRoute - 519 |
| func-lines cmd/console serve - 370 |
| -func-lines internal/activator (*Service).doWakeOnce - 567 |
| +func-lines internal/activator (*Service).doWakeOnce - 570 # raised: #1290 step 2c, the one call that protects the database before the seed, release commands and the process start (body in replicatebeforestart.go) |
| func-lines internal/analytics Prune - 343 |
| func-lines internal/appconfig SyncExecWithCallbacks - 320 |
| func-lines internal/console (*Server).handleAPIInstanceCreate - 769 |
| @@ -2215,7 +2215,7 @@ func-lines internal/host plan14RequiredArtifactsRootRunner - 374 |
| func-lines internal/host plan14TimerIntention - 315 |
| func-lines internal/host plan14TimerIntention.func1 - 311 |
| func-lines internal/host rootFilesSeedIsolatedWitness - 308 |
| -func-lines internal/host runAgent - 685 |
| +func-lines internal/host runAgent - 688 # raised: #1290 sets the agent continuity directory beside the HA obligation store, where every exec-backend store is configured |
| func-lines internal/host runFilesSeedPreparationWithLive - 390 |
| func-lines internal/host runServingParkPeerNamespace - 538 |
| func-lines internal/host testRootMigrationBootstrap - 364 |
| @@ -2230,7 +2230,7 @@ func-lines internal/release adoptHost - 494 |
| func-lines internal/team TestFixture - 421 |
| file-lines . apimode.go - 4199 |
| file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals |
| -file-lines internal/activator activator.go - 3780 # raised: two test-only fields, the lease work counter and the lease watch stop, that tests use to end lease watches before restoring settings |
| +file-lines internal/activator activator.go - 3783 # raised: #1290 step 2c, the call to protectBeforeStart (its body and interface live in replicatebeforestart.go) |
| file-lines internal/activator activator_test.go - 5481 |
| file-lines internal/console server.go - 4219 |
| file-lines internal/host agent.go - 3214 |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 0d3f63da6..7b330bf4b 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -382,15 +382,6 @@ func leaseLost(l Lease) error { |
| return nil |
| } |
| -// startProtector is a lease that protects its database before anything |
| -// that can write it starts (lease.ProtectStart; spec |
| -// 2026-11-19-replicate-before-start.md). A lease without it (a unit |
| -// tenant's, replicated by the box-wide unit; a demo's local lease) starts |
| -// as before. |
| -type startProtector interface { |
| - ProtectStart(dbPath string) error |
| -} |
| - |
| // Lease is a held-but-not-yet-replicating lease (wake in progress; Eleven's |
| // actLease). |
| type Lease interface { |
| @@ -3209,19 +3200,10 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance, |
| ctx = withStorageMode(ctx, rt, id, false, digest) |
| } |
| - // 2c. Replicate before start (spec 2026-11-19-replicate-before-start.md, |
| - // discussion #1290): nothing that can write the database (the seed, a |
| - // release command, the process) starts before it is protected. A |
| - // database exactly as its last clean close left it is pinned, so every |
| - // frame the start writes stays in the WAL until Replicate's litestream |
| - // reads it; any other is snapshotted by Replicate before the wake |
| - // serves. A lease that cannot protect refuses the start. |
| - if p, ok := lease.(startProtector); ok { |
| - if err := p.ProtectStart(rt.DBPath); err != nil { |
| - w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| - return w, fmt.Errorf("protect %s: %w", host, err) |
| - } |
| - w.steps.mark(a.now(), "protect") |
| + // 2c. Replicate before start (#1290): nothing that can write the |
| + // database starts before it is protected (protectBeforeStart). |
| + if err := a.protectBeforeStart(ctx, rt, lease, w); err != nil { |
| + return w, err |
| } |
| // 3. First-boot seed, strictly between the restore and the spawn — so it |
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go| index aff3f39da..c7cfa56a1 100644 |
| --- a/internal/activator/activator_test.go |
| +++ b/internal/activator/activator_test.go |
| @@ -266,24 +266,9 @@ type fakeLease struct { |
| owed bool |
| } |
| -// ProtectStart is startProtector: it records "protect" in the order log |
| -// and answers b.protectErr. |
| -func (l *fakeLease) ProtectStart(string) error { |
| - if l.b == nil { |
| - return nil |
| - } |
| - l.b.mu.Lock() |
| - defer l.b.mu.Unlock() |
| - l.b.order = append(l.b.order, "protect") |
| - return l.b.protectErr |
| -} |
| - |
| func (l *fakeLease) Replicate(_ context.Context, _ string, syncInterval time.Duration) (Rep, error) { |
| if l.b != nil { |
| l.b.mu.Lock() |
| - if l.b.logReplicate { |
| - l.b.order = append(l.b.order, "replicate") |
| - } |
| l.b.syncIntervals = append(l.b.syncIntervals, syncInterval) |
| wrap := l.b.repWrap |
| l.b.mu.Unlock() |
| @@ -399,11 +384,6 @@ type fakeBackend struct { |
| // "a restored instance is never seeded" case. |
| restoreFresh bool |
| restoreErr error |
| - // protectErr is what the lease's ProtectStart answers (replicate |
| - // before start, #1290); logReplicate puts each Replicate in the order |
| - // log too. |
| - protectErr error |
| - logReplicate bool |
| seedErr error |
| seedRoutes []registry.Route |
| startErr error |
| @@ -7342,45 +7322,3 @@ func TestAPendingFlagOffStopProvesTheHostCgroupBeforeTheLeaseGoes(t *testing.T) |
| } |
| func (b *fakeBackend) poolEligible(registry.Route) bool { return true } |
| - |
| -// --- replicate before start (#1290) ------------------------------------------ |
| -// |
| -// Nothing that can write the database starts before the lease protects it |
| -// (spec 2026-11-19-replicate-before-start.md): protect comes after the |
| -// restore and before the seed and the process. |
| - |
| -func TestWakeProtectsTheDatabaseBeforeAnythingStarts(t *testing.T) { |
| - a, b, _, _ := testActivator(t, time.Minute) |
| - b.restoreFresh = true |
| - b.logReplicate = true |
| - rt := testRoute("protect.example.com") |
| - rt.Seed = `["seed"]` |
| - release, err := a.beginRequest(context.Background(), rt) |
| - if err != nil { |
| - t.Fatalf("beginRequest: %v", err) |
| - } |
| - release() |
| - ev := b.events() |
| - r, p, s, st, rep := indexOf(ev, "restore"), indexOf(ev, "protect"), indexOf(ev, "seed"), indexOf(ev, "start:instance"), indexOf(ev, "replicate") |
| - if r == -1 || p == -1 || s == -1 || st == -1 || rep == -1 || !(r < p && p < s && s < st && st < rep) { |
| - t.Fatalf("order %v, want restore < protect < seed < start:instance < replicate", ev) |
| - } |
| -} |
| - |
| -func TestWakeThatCannotProtectStartsNothing(t *testing.T) { |
| - a, b, _, _ := testActivator(t, time.Minute) |
| - b.protectErr = errors.New("pin refused") |
| - rt := testRoute("unprotected.example.com") |
| - if _, err := a.beginRequest(context.Background(), rt); err == nil || !strings.Contains(err.Error(), "pin refused") { |
| - t.Fatalf("beginRequest: %v, want the protection's refusal", err) |
| - } |
| - b.mu.Lock() |
| - starts, releases := b.starts, b.releases |
| - b.mu.Unlock() |
| - if starts != 0 { |
| - t.Fatalf("%d starts after a refused protection, want 0", starts) |
| - } |
| - if releases != 1 { |
| - t.Fatalf("%d lease releases, want 1", releases) |
| - } |
| -} |
diff --git a/internal/activator/replicatebeforestart.go b/internal/activator/replicatebeforestart.go| new file mode 100644 |
| index 000000000..177dfc7e3 |
| --- /dev/null |
| +++ b/internal/activator/replicatebeforestart.go |
| @@ -0,0 +1,37 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// startProtector is a lease that protects its database before anything |
| +// that can write it starts (lease.ProtectStart; spec |
| +// 2026-11-19-replicate-before-start.md). A lease without it (a unit |
| +// tenant's, replicated by the box-wide unit; a demo's local lease) starts |
| +// as before. |
| +type startProtector interface { |
| + ProtectStart(dbPath string) error |
| +} |
| + |
| +// protectBeforeStart is doWakeOnce's step 2c (discussion #1290): nothing |
| +// that can write the database (the seed, a release command, the process) |
| +// starts before it is protected. A database exactly as its last clean |
| +// close left it is pinned, so every frame the start writes stays in the |
| +// WAL until Replicate's litestream reads it; any other is given a full |
| +// image by Replicate before the wake serves. A lease that cannot protect |
| +// refuses the start: the lease goes back and nothing runs. |
| +func (a *Service) protectBeforeStart(ctx context.Context, rt registry.Route, lease Lease, w *wokenInstance) error { |
| + p, ok := lease.(startProtector) |
| + if !ok { |
| + return nil |
| + } |
| + if err := p.ProtectStart(rt.DBPath); err != nil { |
| + w.stopOutcome.leaseReleased = a.giveBack(ctx, rt.Host, lease) |
| + return fmt.Errorf("protect %s: %w", rt.Host, err) |
| + } |
| + w.steps.mark(a.now(), "protect") |
| + return nil |
| +} |
diff --git a/internal/activator/replicatebeforestart_test.go b/internal/activator/replicatebeforestart_test.go| new file mode 100644 |
| index 000000000..04c117a9e |
| --- /dev/null |
| +++ b/internal/activator/replicatebeforestart_test.go |
| @@ -0,0 +1,73 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// --- replicate before start (#1290) ------------------------------------------ |
| +// |
| +// Nothing that can write the database starts before the lease protects it |
| +// (spec 2026-11-19-replicate-before-start.md): protect comes after the |
| +// restore and before the seed and the process. |
| + |
| +// fakeProtectErrs is what each backend's leases answer to ProtectStart. |
| +var fakeProtectErrs sync.Map // *fakeBackend -> error |
| + |
| +// ProtectStart is startProtector: it records "protect" in the order log |
| +// and answers the backend's fakeProtectErrs entry. |
| +func (l *fakeLease) ProtectStart(string) error { |
| + if l.b == nil { |
| + return nil |
| + } |
| + l.b.record("protect") |
| + if err, ok := fakeProtectErrs.Load(l.b); ok { |
| + return err.(error) |
| + } |
| + return nil |
| +} |
| + |
| +func TestWakeProtectsTheDatabaseBeforeAnythingStarts(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + b.restoreFresh = true |
| + // Each Replicate goes into the order log too. |
| + b.repWrap = func(r *fakeRep) Rep { |
| + b.record("replicate") |
| + return r |
| + } |
| + rt := testRoute("protect.example.com") |
| + rt.Seed = `["seed"]` |
| + release, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Fatalf("beginRequest: %v", err) |
| + } |
| + release() |
| + ev := b.events() |
| + r, p, s, st, rep := indexOf(ev, "restore"), indexOf(ev, "protect"), indexOf(ev, "seed"), indexOf(ev, "start:instance"), indexOf(ev, "replicate") |
| + if r == -1 || p == -1 || s == -1 || st == -1 || rep == -1 || !(r < p && p < s && s < st && st < rep) { |
| + t.Fatalf("order %v, want restore < protect < seed < start:instance < replicate", ev) |
| + } |
| +} |
| + |
| +func TestWakeThatCannotProtectStartsNothing(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + fakeProtectErrs.Store(b, errors.New("pin refused")) |
| + t.Cleanup(func() { fakeProtectErrs.Delete(b) }) |
| + rt := testRoute("unprotected.example.com") |
| + if _, err := a.beginRequest(context.Background(), rt); err == nil || !strings.Contains(err.Error(), "pin refused") { |
| + t.Fatalf("beginRequest: %v, want the protection's refusal", err) |
| + } |
| + b.mu.Lock() |
| + starts, releases := b.starts, b.releases |
| + b.mu.Unlock() |
| + if starts != 0 { |
| + t.Fatalf("%d starts after a refused protection, want 0", starts) |
| + } |
| + if releases != 1 { |
| + t.Fatalf("%d lease releases, want 1", releases) |
| + } |
| +} |
diff --git a/internal/lease/continuity.go b/internal/lease/continuity.go| index 53a608ff1..270140b24 100644 |
| --- a/internal/lease/continuity.go |
| +++ b/internal/lease/continuity.go |
| @@ -311,13 +311,15 @@ func (p *Protection) pin() (bool, error) { |
| return false, nil |
| } |
| } |
| + ctx, cancel := context.WithTimeout(context.Background(), pinTimeout) |
| + defer cancel() |
| db, err := sql.Open("sqlite", "file:"+p.path+"?_pragma=busy_timeout(5000)") |
| if err != nil { |
| return false, err |
| } |
| db.SetMaxOpenConns(1) |
| var mode string |
| - if err := db.QueryRow(`PRAGMA journal_mode`).Scan(&mode); err != nil { |
| + if err := db.QueryRowContext(ctx, `PRAGMA journal_mode`).Scan(&mode); err != nil { |
| db.Close() |
| return false, err |
| } |
| @@ -325,13 +327,15 @@ func (p *Protection) pin() (bool, error) { |
| db.Close() |
| return false, nil |
| } |
| - tx, err := db.Begin() |
| + // The transaction outlives ctx: it is held until Release, so it is |
| + // begun on a context that does not end. |
| + tx, err := db.BeginTx(context.WithoutCancel(ctx), nil) |
| if err != nil { |
| db.Close() |
| return false, err |
| } |
| var n int |
| - if err := tx.QueryRow(`SELECT count(*) FROM sqlite_master`).Scan(&n); err != nil { |
| + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_master`).Scan(&n); err != nil { |
| _ = tx.Rollback() |
| db.Close() |
| return false, err |
| @@ -340,6 +344,10 @@ func (p *Protection) pin() (bool, error) { |
| return true, nil |
| } |
| +// pinTimeout bounds opening the pin: a database it cannot read within it |
| +// is an error, and the start does not happen. |
| +const pinTimeout = 30 * time.Second |
| + |
| // beginContinuity is where Replicate and Checkpoint decide: the pin a |
| // ProtectStart left, or, with none, a pin taken now (protect), held by the |
| // caller through its first sync. A database that cannot be pinned is not |