carlos / platform Public

Fleet public routes Task 3 fix round 1: replay, bulk batches, inventory coverage

Astra's task review (3 Important, 1 Minor):

- RetireClaimRows checks each route target's host for a forward row on
  its transaction before the saved-retirement shortcut, so a replay of a
  journal over a host a forward row now holds refuses before archive.
- SetChannels, SetEnvironments and SetChannelsAndEnvironments check every
  host of the batch before their first UPDATE.
- The inventory marks the classified SQL arguments that execute a routes
  write (writesRoutes); their functions must be reached by the writer
  table or be an exception, as resolved writes are.
- Each arm of the writer table test closes its own registry.

New tests: TestRetireClaimRowsReplayRefusesAForwardRow (with a live
replay control) and TestBulkSettersCheckEveryHostBeforeTheirFirstWrite
(an abort trigger makes any attempted UPDATE visible). Spec §7: the card
moves RetireClaimRows from body to reads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 1d7c10ea7adb532e80722d14cdd094e5cb5f1909 parent 18d0445
5 files changed, +183 −35
  • docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md +10 −2
  • internal/registry/claimrows.go +12 −6
  • internal/registry/forward_inventory_test.go +43 −23
  • internal/registry/forward_writers_test.go +94 −4
  • internal/registry/registry.go +24 −0

Intent

Human

<task-notification> <task-id>a475741402127d1ea</task-id> <tool-use-id>toolu_01EkA7MJSDuUse5sHLhi9TcP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a475741402127d1ea.output</output-file> <status>completed</status> <summary>Agent "Build worker exit and held REASON" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've applied platform-39: a failed worker start no longer gets RFS-3-C35, only a worker that ran and ended with no status does. It's one commit, not pushed. The tip is `18e556185763e5d8ce8dd42e89bd08120207bcab` on `rootfs-worker-exit`. **What changed** (`internal/activator/rootfsworkers.go`, `noteWorkerExitLocked`) - A failed start behaves as it did before C35. It gets the operator log line only, or RFS-3-C10 if it is the start that enters the crash loop. - A failed start also no longer resets the once-a-minute timer for the exit line. - A worker that ran and ended with no status still gets C35, paced like C09. **Test-first** - New test: `TestAFailedWorkerStartIsNoExitToTheMember`. It checks three cases: - a failed start gets no member event and leaves the timer alone; - a failed start entering the loop still gets C10 once; - an ended worker with no record gets C35. - It failed before the fix: the failed start told the member "worker jobs exited. starting it again in 2s" and set the timer. It passes after. - Two mutations were caught: - removing the failed-start case brings the C35 line back; - putting that case ahead of the crash-loop case loses C10. - The rolloutwords tests, the root package's copy, Plan3 and RolloutReason tests, and the activator worker, unit, exit and rootfs tests all pass, as do `go vet`, `go build` and the darwin and windows builds. **Census card: changed, so I re-proposed it** - The census failed on `noteWorkerExitLocked`, whose code changed. I re-ran `make census-propose` with the same name and the same claims file, `/home/paulca/.cache/tmp/claude-1001/rootfs-worker-exit/census-claims.tsv`. - In that file I reworded only the `noteWorkerExitLocked` claim, to say C35 is for ended workers and failed starts keep the log line alone. - Units, change classes, read sites, new dispositions and re-pinned envelopes are all the same as before. Only that claim text and the seal changed: `e59180920…` → `19fd02ddce24e25bac069e2e33441d6c62869ef3f6d7bb5142a3e93e58bcfbf0`. - The census tests pass at the tip. No reviewer has been briefed. My scratch backup is deleted; the claims file stays where it is, as asked.</result> <usage><subagent_tokens>209623</subagent_tokens><tool_uses>101</tool_uses><duration_ms>1477448</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>aa8076ab7f4edf357</task-id> <tool-use-id>toolu_01YKToic4m4TvkS3zkmhjEVZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/aa8076ab7f4edf357.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: writer guard" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE_WITH_CONCERNS. The concerns are review notes, not blockers. FPR-C01 is not written, as you ruled. **Commit:** 18d04450 on design-fleet-public-routes, one commit, not pushed. **Tests:** all the new tests failed before the change and pass after it. The writer table has 65 entries, each run once on an ordinary row and once on a forward row with a whole-database comparison. The inventory test finds 66 routes writes in 65 functions and classifies 18 SQL arguments it cannot resolve. The whole `internal/registry` package passes, as do the root CLI test, `TestPlan9B8RecordWriteCensus` and targeted runs of the `hostbox` and `host` callers. 13 mutations were each caught, including your two (`InstallLifetimeIf`'s guard removed; `SetStatus`'s literal split and dropped from the table). Build, vet, gofmt and the darwin, windows and linux/arm64 cross-builds are clean. **Two real gaps the failing tests showed before the change:** - `Upsert` given a forward-kind route created a new forward row. Only `PutForward` should do that. - `carlos add` over a forward host turned it into an instance row and printed "updated". **What the operator sees now, with no new user text:** - `carlos add`, `carlos remove` and `carlos route -tunnel` over a forward host exit 1 with "registry: the host is a forward row". The row is unchanged. - `carlos route -channel x` also exits 1 and leaves the row unchanged, but see concern 1. **Record-write census:** the new `fleetPublicRoutesWriteCensusInventory` re-pins `SwapForImport`, and `TestPlan9B8RecordWriteCensus` now uses it. `runRoute` is not re-pinned because `cli.go` has not changed yet. **Spec §7:** the census card's differences are written there in the same commit: - `importRowTx` is a changed unit the list did not name. - `forwardAt` is a new unit. - `runAdd`, `runRemove` and `runRoute` will only appear on the card once C01 lands. **Concerns:** 1. `carlos route -channel` on a forward host never reaches the registry. A forward row counts as provisioned, so an existing check in `runRoute` refuses it first, with text telling the operator to use `carlos instances set-channel`. So the test only checks exit 1 and an unchanged row for that command. I used `route -tunnel t1` to show the registry refusal coming through `runRoute`, which goes beyond the brief. When C01 is wired, its forward check has to come before the channel checks. 2. `RestoreClaimRows` and `RebindClaimRows` now create their `cold_handovers` and `recovery_rows` tables inside the transaction, after the forward check. This changes every refusal, not just forward ones: a refused restore no longer leaves an empty table behind. 3. The 26 setters that error on an unknown host, plus `Delete`, now do one extra read when nothing matched, to tell a forward row from no row. The error for a missing row is unchanged. 4. Beyond the brief, the inventory test also checks that every UPDATE, DELETE and upsert on routes contains `kind &lt;&gt; 'forward'`. INSERTs are exempt. 5. For the two entries that carry an alias, the forward-row check compares the whole database except the source row, which legitimately moves. The test asserts separately that the source did move. **Left for you once FPR-C01 is approved:** add the forward check and C01 text to `runAdd`, `runRemove` and `runRoute`. That includes the `--app` batch path, where you need to decide whether to refuse the whole batch or skip forward rows. Then add FPR-C01 to `fleetRoutesCopyBuilt`, tighten the CLI test to expect the C01 text, re-pin `runRoute` in the new census inventory, and re-run `make census-card`. The report has the exact steps. Files are in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-public-routes/`: - `internal/registry/forward_writers_test.go` - `internal/registry/forward_inventory_test.go` - `forward_cli_test.go` - `internal/provision/fleet_public_routes_census_test.go` - `.superpowers/sdd/2026-10-30-fleet-public-routes/task-3-report.md` (full report)</result> <usage><subagent_tokens>354963</subagent_tokens><tool_uses>109</tool_uses><duration_ms>1518888</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bqzhhnvgd</task-id> <tool-use-id>toolu_01Wq26PyMHpgEXAso33zLgU3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bqzhhnvgd.output</output-file> <status>completed</status> <summary>Background command "Brief, push and run Astra round 1 on rootfs-worker-exit" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bpgi07q01</task-id> <tool-use-id>toolu_01Q8mvbuMZ1nscQsWjHGYADr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bpgi07q01.output</output-file> <status>completed</status> <summary>Background command "Package Task 3 and run its Astra task review" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a475741402127d1ea</task-id> <tool-use-id>toolu_01EyBcJGVMmaHC629rNQSQM8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a475741402127d1ea.output</output-file> <status>completed</status> <summary>Agent "Build worker exit and held REASON" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I fixed Astra's P2 test-first, committed it with the findings file, and pushed. The tip is `f704ca150f84f33be9159801d65c98ef5c4cd03c` on `rootfs-worker-exit`, and `git ls-remote origin` shows the same hash. **The fix** - **Where the clean-exit policy comes from:** the `UnitMainExit` read now also asks `systemctl show` for the unit's `SuccessExitStatus`. That is the policy systemd loaded from the templates the platform ships, so there is no second hard-coded list of exit codes in Go. - Reading the template files directly wasn't possible: they are embedded in `internal/host`, which imports the activator, so the activator importing them would be a cycle. - The read returns a small struct, `MainExit`, carrying invocation, code, status and policy. - **The rule** (`cleanMainExit` in unitproc.go, copying systemd's own check): - an exit is clean at 0 or at a code the unit lists; - a death by signal is clean for HUP, INT, PIPE or TERM, which systemd itself always treats as clean, or for a signal the unit lists; - a core dump is never clean. - **The record:** a "success" record stays success only for a clean end. SIGKILL's 137 is still corrected to `exit-code`, so a normal SIGTERM stop (1/143) is no longer reported as a failure. - **The only fixed list:** systemd's four clean signals. **Tests** - `TestMainExitKeepsEachUnitsCleanExits` reads `SuccessExitStatus=` from each unit template whose exit record the activator reads: run, generation, sidecar, rootfs run, rootfs gen and rootfs worker. - For each, every listed code (129, 130, 141, 143) and each clean signal must come out success. - 137, exit 1, a SIGKILL death and a core dump must stay failures. - With no policy, 143 must fail; a signal the policy names (SIGALRM) must be clean. - In `TestAnExitRecordWithNoCodeReadsSystemd`, a worker ending 1/143 and one ending 2/TERM are success. For web, 1/143 now says "instance exited (exit 0)" at info, and 1/137 still says exit 137 at warn. - Before the fix these failed exactly as the finding describes, for example web 143 said "exit 143 (exit-code)" at warn. They pass now. - Four mutations were caught: ignoring the policy, dropping the clean signals, treating 137 as clean, and treating a core dump as clean. - The touched activator, rolloutwords and root-package tests pass, as do vet, gofmt, build and the darwin and windows builds. **Census: the card changed only in its seal** - The two new units, `systemctlUnitMainExit` and `ExecBackend.unitMainExitOf`, changed code. - I updated their claims in the same claims file and re-ran `make census-propose`. Units, change classes, read sites and dispositions are unchanged. - The seal is now `7ebc3871ee3c93ff168bfa62d23d6be5a970786c67a9b8aa813e8cc4e39b3d74`, and the census tests pass at the tip. **Not verified on a box:** I wrote the parsing from memory of how `systemctl show` prints `SuccessExitStatus`, with exit codes as numbers and signals as names like `SIGTERM`, without checking systemd's source. The tests use a fake, not real systemctl output.</result> <usage><subagent_tokens>244111</subagent_tokens><tool_uses>15</tool_uses><duration_ms>380136</duration_ms></usage> </task-notification>

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

diff --git a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
index 470779333..7669c2c4a 100644
--- a/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
+++ b/docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md
@@ -840,7 +840,7 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
Task 3's card, reconciled with this list. Every declaration named above
is on it except `SetDNSStatus` and `SetCertExpiresAt` (exceptions,
unchanged). `body` (sites unchanged): `RepointPlatformSocket`,
- `carryAliasesTx`, `AdoptClaimRoute`, `RetireClaimRows`,
+ `carryAliasesTx`, `AdoptClaimRoute`,
`CloseImportGate`, `CommitImport`, `insertRouteTx`, `ClearNextDueIf`,
`DeleteIfHold`, `DeleteIfHoldWithTimers`, `HandHold`,
`InstallLifetimeIf`, `ReleaseHold`, `ReleaseHoldSeq`, `SetAccount`,
@@ -869,7 +869,15 @@ Units, by file (N = new, R = removed, otherwise a changed body or sites):
`+registry:Route`, `+whole:Route`, `+whole:claimTransaction`, and
`-registry:sql`: their `CREATE TABLE IF NOT EXISTS cold_handovers` and
`recovery_rows` moved from `r.sql` into the claim transaction, after
- the forward check, so a refusal leaves no table behind).
+ the forward check, so a refusal leaves no table behind);
+ `RetireClaimRows` (`+registry:Host`, `+registry:Kind`,
+ `+whole:claimTransaction`: Task 3's fix round 1 checks each route
+ target's host on the transaction before the saved-retirement shortcut,
+ so a replay over a forward row refuses before `archive` too). The
+ three bulk setters (`SetChannels`, `SetEnvironments`,
+ `SetChannelsAndEnvironments`) also check every host of the batch on
+ their transaction before the first UPDATE (fix round 1); that adds no
+ read site beyond the `+registry:sql` above.
Differences from the list above, all recorded here: `importRowTx`
(`importjournal.go`, `+whole:Route`) is a changed unit the list did not
name: the import's own-row check now answers `ErrForwardRow` for a
diff --git a/internal/registry/claimrows.go b/internal/registry/claimrows.go
index 121d05fda..143c43acf 100644
--- a/internal/registry/claimrows.go
+++ b/internal/registry/claimrows.go
@@ -105,9 +105,10 @@ func (r *Registry) AdoptClaimRoute(ctx context.Context, observed Route, owner Cl
// RetireClaimRows archives the exact transaction snapshot before deletion.
// A missing or replacement row is successful only when this journal's committed
// archive proves the predecessor was already removed by an earlier attempt.
-// A route target that is a forward row is ErrForwardRow, answered before
-// archive is called and before claim_row_retirements is written (fleet
-// public routes spec §4.2); the routes DELETE never matches one either.
+// A route target whose host is a forward row is ErrForwardRow, answered
+// before archive is called and before claim_row_retirements is written,
+// replays of a saved retirement included (fleet public routes spec §4.2);
+// the routes DELETE never matches one either.
func (r *Registry) RetireClaimRows(ctx context.Context, journal string, targets []ClaimRow, archive func([]ClaimRowArchive) error) error {
if archive == nil {
return ErrClaimOwnership
@@ -140,6 +141,14 @@ func (r *Registry) RetireClaimRows(ctx context.Context, journal string, targets
return ErrClaimOwnership
}
seen[key] = true
+ // Before the saved-retirement shortcut below: a replay of this
+ // journal over a host a forward row now holds refuses too, before
+ // archive is called.
+ if t.Kind == "route" {
+ if err := forwardAt(tx, t.Host); err != nil {
+ return err
+ }
+ }
var saved []byte
err = tx.QueryRowContext(ctx, `SELECT archive FROM claim_row_retirements WHERE journal=? AND kind=? AND host=? AND name=? AND row_id=?`, journal, t.Kind, t.Host, t.Name, t.Ownership.ClaimRowID).Scan(&saved)
if err == nil {
@@ -160,9 +169,6 @@ func (r *Registry) RetireClaimRows(ctx context.Context, journal string, targets
if e != nil {
return fmt.Errorf("%w: %v", ErrClaimOwnership, e)
}
- if row.IsForward() {
- return ErrForwardRow
- }
if row.ClaimOwnership != t.Ownership {
return ErrClaimOwnership
}
diff --git a/internal/registry/forward_inventory_test.go b/internal/registry/forward_inventory_test.go
index 0a622f2e6..cb87de604 100644
--- a/internal/registry/forward_inventory_test.go
+++ b/internal/registry/forward_inventory_test.go
@@ -23,30 +23,40 @@ var forwardRowWriters = map[string]bool{
"PutForward": true, "DeleteForward": true, "SetFleetBoxIf": true, "SetDNSStatus": true, "SetCertExpiresAt": true,
}
+// unresolvedSQL classifies one SQL argument with no constant value.
+// writesRoutes marks a call that executes a routes write the scan cannot
+// read (a statement built at run time, a prepared statement's Exec, a
+// package variable): its enclosing function must be reached by the writer
+// table, or be one of the five exceptions, exactly as a resolved write's.
+type unresolvedSQL struct {
+ writesRoutes bool
+ why string
+}
+
// unresolvedRouteSQL classifies every SQL argument in internal/registry that
// has no constant value and whose constant fragments do not name a routes
// write, keyed "<file>:<enclosing function>". A new one fails the inventory
// until it is read and classified here; a key that no longer matches a call
// fails too.
-var unresolvedRouteSQL = map[string]string{
- "claimtransaction.go:ExecContext": "claimTransaction's pass-through to its connection; the SQL is its caller's, inventoried at the caller",
- "claimtransaction.go:QueryRowContext": "claimTransaction's pass-through to its connection; the SQL is its caller's, inventoried at the caller",
- "claimtransaction.go:Exec": "claimTransaction's pass-through (txer); the SQL is its caller's, inventoried at the caller",
- "claimtransaction.go:QueryRow": "claimTransaction's pass-through (queryer); the SQL is its caller's, inventoried at the caller",
- "claimrows.go:migrateClaimOwnership": "ALTER TABLE routes|timers ADD COLUMN: a schema migration, writes no row",
- "fleets.go:migrateFleets": "ALTER TABLE fleets ADD COLUMN: a schema migration of the fleets table",
- "registry.go:Get": "SELECT <readCols> FROM routes WHERE host = ?: a read",
- "registry.go:List": "SELECT <readCols> FROM routes ORDER BY host: a read",
- "claimrows.go:RetireClaimRows": "DELETE FROM routes|timers built at run time; the routes arm carries kind <> 'forward', and the forward check runs before archive",
- "registry.go:applyRegistryPragmas": "the connection pragmas (registryPragmas): busy_timeout, journal_mode, synchronous",
- "registry.go:migrate": "ALTER TABLE routes ADD COLUMN from routeAddedColumns: a schema migration, writes no row",
- "registry.go:SetChannels": "stmt.Exec(channel, host): the prepared UPDATE above it in SetChannels, which is inventoried",
- "registry.go:SetEnvironments": "stmt.Exec(env, host): the prepared UPDATE above it in SetEnvironments, which is inventoried",
- "registry.go:SetChannelsAndEnvironments": "stmt.Exec(channel, env, host): the prepared UPDATE above it, which is inventoried",
- "timers.go:queryTimers": "a SELECT over timers, built by its callers",
- "timers.go:PruneTimers": "DELETE FROM timers built at run time; timers only",
- "timers.go:DeleteTimersExcept": "DELETE FROM timers built at run time; timers only",
- "forward.go:PutForward": "putForwardSQL, the forward row's own writer (an exception), built once from ForwardForbidden",
+var unresolvedRouteSQL = map[string]unresolvedSQL{
+ "claimtransaction.go:ExecContext": {false, "claimTransaction's pass-through to its connection; the SQL is its caller's, inventoried at the caller"},
+ "claimtransaction.go:QueryRowContext": {false, "claimTransaction's pass-through to its connection; the SQL is its caller's, inventoried at the caller"},
+ "claimtransaction.go:Exec": {false, "claimTransaction's pass-through (txer); the SQL is its caller's, inventoried at the caller"},
+ "claimtransaction.go:QueryRow": {false, "claimTransaction's pass-through (queryer); the SQL is its caller's, inventoried at the caller"},
+ "claimrows.go:migrateClaimOwnership": {false, "ALTER TABLE routes|timers ADD COLUMN: a schema migration, writes no row"},
+ "fleets.go:migrateFleets": {false, "ALTER TABLE fleets ADD COLUMN: a schema migration of the fleets table"},
+ "registry.go:Get": {false, "SELECT <readCols> FROM routes WHERE host = ?: a read"},
+ "registry.go:List": {false, "SELECT <readCols> FROM routes ORDER BY host: a read"},
+ "claimrows.go:RetireClaimRows": {true, "DELETE FROM routes|timers built at run time; the routes arm carries kind <> 'forward', and the forward check runs before archive"},
+ "registry.go:applyRegistryPragmas": {false, "the connection pragmas (registryPragmas): busy_timeout, journal_mode, synchronous"},
+ "registry.go:migrate": {false, "ALTER TABLE routes ADD COLUMN from routeAddedColumns: a schema migration, writes no row"},
+ "registry.go:SetChannels": {true, "stmt.Exec(channel, host): the prepared UPDATE above it in SetChannels, which is inventoried"},
+ "registry.go:SetEnvironments": {true, "stmt.Exec(env, host): the prepared UPDATE above it in SetEnvironments, which is inventoried"},
+ "registry.go:SetChannelsAndEnvironments": {true, "stmt.Exec(channel, env, host): the prepared UPDATE above it, which is inventoried"},
+ "timers.go:queryTimers": {false, "a SELECT over timers, built by its callers"},
+ "timers.go:PruneTimers": {false, "DELETE FROM timers built at run time; timers only"},
+ "timers.go:DeleteTimersExcept": {false, "DELETE FROM timers built at run time; timers only"},
+ "forward.go:PutForward": {true, "putForwardSQL, the forward row's own writer (an exception), built once from ForwardForbidden"},
}
// sqlMethods are the database calls whose argument at the index is SQL.
@@ -171,12 +181,22 @@ func TestRouteWriterInventoryIsComplete(t *testing.T) {
reached[fn] = append(reached[fn], c.name)
}
}
- // A function whose only routes write is classified in
- // unresolvedRouteSQL (RetireClaimRows' DELETE FROM <table>, PutForward's
- // putForwardSQL) is still the writer its entry names.
+ // A routes write the scan cannot read (classified writesRoutes in
+ // unresolvedRouteSQL: RetireClaimRows' DELETE FROM <table>, PutForward's
+ // putForwardSQL, the bulk setters' prepared Exec) needs the same
+ // coverage as a resolved one: its function is reached by the writer
+ // table or is an exception.
seen := map[string]bool{}
for k := range unresolved {
- seen[k[strings.Index(k, ":")+1:]] = true
+ c, ok := unresolvedRouteSQL[k]
+ if !ok || !c.writesRoutes {
+ continue
+ }
+ fn := k[strings.Index(k, ":")+1:]
+ seen[fn] = true
+ if !forwardRowWriters[fn] && len(reached[fn]) == 0 {
+ t.Errorf("%s (%v): a routes write classified in unresolvedRouteSQL, and no entry of the writer table reaches %s (nor is it one of the five exceptions)", k, unresolved[k], fn)
+ }
}
guard := regexp.MustCompile(`(?i)\bkind\s*<>\s*'forward'`)
for _, s := range sites {
diff --git a/internal/registry/forward_writers_test.go b/internal/registry/forward_writers_test.go
index 93dc73818..cbd78ca13 100644
--- a/internal/registry/forward_writers_test.go
+++ b/internal/registry/forward_writers_test.go
@@ -509,8 +509,10 @@ func TestEveryRouteWriterRefusesAForwardRow(t *testing.T) {
for _, c := range routeWriterCases() {
t.Run(c.name, func(t *testing.T) {
// Positive arm: the fixture is live, the writer changes a row.
- r := openTestRegistry(t)
- t.Cleanup(func() { r.Close() })
+ // Each arm closes its own registry: the cleanups do not share r.
+ pos := openTestRegistry(t)
+ t.Cleanup(func() { pos.Close() })
+ r := pos
_, call := c.setup(t, r)
before := dumpDB(t, r)
changed, err := call(false)
@@ -529,8 +531,9 @@ func TestEveryRouteWriterRefusesAForwardRow(t *testing.T) {
}
// Forward arm: the same fixture, its host a forward row.
- r = openTestRegistry(t)
- t.Cleanup(func() { r.Close() })
+ fwd := openTestRegistry(t)
+ t.Cleanup(func() { fwd.Close() })
+ r = fwd
host, call := c.setup(t, r)
if c.forward != nil {
c.forward(t, r, host)
@@ -682,3 +685,90 @@ func TestRestoreWritersRefuseForwardInputsAtAbsentHosts(t *testing.T) {
})
}
}
+
+// A retirement that lost its reply is replayed with the same journal and
+// targets: the saved archive answers for the row it already removed. If a
+// forward row has since taken the host, the replay refuses before archive is
+// called, as the first attempt would (the saved-archive shortcut is no way
+// around the check). Without the forward row the replay reaches archive,
+// which shows the spy is live.
+func TestRetireClaimRowsReplayRefusesAForwardRow(t *testing.T) {
+ ctx := context.Background()
+ for _, forward := range []bool{false, true} {
+ t.Run(fmt.Sprintf("forward=%v", forward), func(t *testing.T) {
+ r := openTestRegistry(t)
+ defer r.Close()
+ rt := claimedRow(t, r)
+ targets := []ClaimRow{{Kind: "route", Host: rt.Host, Ownership: fwOwner}}
+ if err := r.RetireClaimRows(ctx, "ret", targets, func([]ClaimRowArchive) error { return nil }); err != nil {
+ t.Fatal(err)
+ }
+ if forward {
+ if err := r.PutForward(validForward(rt.Host, "home")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before := dumpDB(t, r)
+ called := false
+ err := r.RetireClaimRows(ctx, "ret", targets, func([]ClaimRowArchive) error { called = true; return nil })
+ if !forward {
+ if err != nil || !called {
+ t.Fatalf("replay without a forward row: err %v, archive called %v; want nil and true", err, called)
+ }
+ return
+ }
+ if !errors.Is(err, ErrForwardRow) {
+ t.Errorf("replay over a forward row: err = %v, want ErrForwardRow", err)
+ }
+ if called {
+ t.Errorf("replay over a forward row called archive")
+ }
+ if d := dumpDiff(before, dumpDB(t, r)); d != "" {
+ t.Errorf("replay over a forward row changed the database:\n %s", d)
+ }
+ })
+ }
+}
+
+// The three bulk setters check every host of the batch before their first
+// UPDATE: a batch holding an ordinary host and a forward one answers
+// ErrForwardRow without writing the ordinary one first (a rollback would undo
+// it, but the rule is refuse before the first write). A trigger that aborts
+// any routes UPDATE makes an attempted write visible: on an ordinary-only
+// batch it fires, which shows it is armed.
+func TestBulkSettersCheckEveryHostBeforeTheirFirstWrite(t *testing.T) {
+ const fwdHost = "fwd.example.com"
+ for _, c := range []struct {
+ name string
+ call func(r *Registry, hosts []string) error
+ }{
+ {"SetChannels", func(r *Registry, h []string) error { return r.SetChannels(h, "beta") }},
+ {"SetEnvironments", func(r *Registry, h []string) error { return r.SetEnvironments(h, "staging") }},
+ {"SetChannelsAndEnvironments", func(r *Registry, h []string) error { return r.SetChannelsAndEnvironments(h, "beta", "staging") }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := openTestRegistry(t)
+ defer r.Close()
+ plainRow(t, r, nil)
+ if err := r.PutForward(validForward(fwdHost, "home")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.sql.Exec(`CREATE TRIGGER no_route_write BEFORE UPDATE ON routes BEGIN SELECT RAISE(ABORT, 'routes write attempted'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if err := c.call(r, []string{fwHost}); err == nil || !strings.Contains(err.Error(), "routes write attempted") {
+ t.Fatalf("ordinary-only batch: err = %v; want the trigger's abort (the trigger is not armed)", err)
+ }
+ for _, hosts := range [][]string{{fwHost, fwdHost}, {fwdHost, fwHost}} {
+ before := dumpDB(t, r)
+ err := c.call(r, hosts)
+ if !errors.Is(err, ErrForwardRow) {
+ t.Errorf("batch %v: err = %v, want ErrForwardRow before any write", hosts, err)
+ }
+ if d := dumpDiff(before, dumpDB(t, r)); d != "" {
+ t.Errorf("batch %v changed the database:\n %s", hosts, d)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 3c0cdda57..e7f84787a 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -2702,6 +2702,14 @@ func (r *Registry) SetChannels(hosts []string, channel string) error {
if err != nil {
return err
}
+ // Every host is checked before the first UPDATE (fleet public routes
+ // spec §4.2): a batch naming a forward row writes nothing at all.
+ for _, h := range hosts {
+ if err := forwardAt(tx, h); err != nil {
+ tx.Rollback()
+ return err
+ }
+ }
stmt, err := tx.Prepare(`UPDATE routes SET channel = ? WHERE host = ? AND kind <> 'forward'`)
if err != nil {
tx.Rollback()
@@ -2854,6 +2862,14 @@ func (r *Registry) SetEnvironments(hosts []string, env string) error {
if err != nil {
return err
}
+ // Every host is checked before the first UPDATE (fleet public routes
+ // spec §4.2): a batch naming a forward row writes nothing at all.
+ for _, h := range hosts {
+ if err := forwardAt(tx, h); err != nil {
+ tx.Rollback()
+ return err
+ }
+ }
stmt, err := tx.Prepare(`UPDATE routes SET environment = ? WHERE host = ? AND kind <> 'forward'`)
if err != nil {
tx.Rollback()
@@ -2903,6 +2919,14 @@ func (r *Registry) SetChannelsAndEnvironments(hosts []string, channel, env strin
if err != nil {
return err
}
+ // Every host is checked before the first UPDATE (fleet public routes
+ // spec §4.2): a batch naming a forward row writes nothing at all.
+ for _, h := range hosts {
+ if err := forwardAt(tx, h); err != nil {
+ tx.Rollback()
+ return err
+ }
+ }
stmt, err := tx.Prepare(`UPDATE routes SET channel = ?, environment = ? WHERE host = ? AND kind <> 'forward'`)
if err != nil {
tx.Rollback()