carlos / platform Public

activator tests: setKnob refuses an unowned Service; end every watch

Round 3 of #1249, Paul's "refuse up front".

setKnob(t, &v, x) replaces restoreKnob: it checks the rule, then
records the old value, then writes. A subtest may not change a package
setting while a Service it does not own runs (its parent's, or one it
built before its first setKnob); setKnob fails it before writing.
newTrackedService now takes the test, so each Service knows who built
it and when that test ends. firstOwned and ownedServices are gone.

Every restoreKnob caller and the deferred restores of package settings
(defer func() { x = old }()) now use setKnob. One subtest was refused:
TestPoolGateIndependentAdmissions/placement generation lost, whose rig
sets restoreReplica while the parent's Services run; it is now a block
of the parent. Two table tests set their settings per subtest before
building anything (TestSwapCanarySettle, TestSwapHoldCanarySettles,
and the hold-stop case of TestSwapHoldReleasesItsCallerWhileTheStop-
IsPending).

The CI failure on fb49b811: TestSwapReleaseRefusedByRootAbandons's
cleanup deletes its hand-installed entry from a.entries without
closing ownerDone, before the restores run, so endLeaseWatches could
not reach the watch. Service gains leaseWatchStop, nil in production,
which every lease watch also selects on; a test closes it to end all
of a Service's watches. Census re-sealed; activator.go's code-health
record raised by one line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 862dc78c1a9b4c51768ed5deca1bfbebf4801279 parent a1371c3
98 files changed, +526 −645
  • .amadan/code-health.tsv +2 −2
  • AGENTS.md +7 −4
  • docs/superpowers/notes/census-proposal-race-activator-1249.md +2 −2
  • internal/activator/activator.go +5 −0
  • internal/activator/activator_test.go +15 −33
  • internal/activator/backend_exec_test.go +15 −39
  • internal/activator/backend_unit_test.go +4 −6
  • internal/activator/binary_golden_test.go +2 −3
  • internal/activator/canonlink_test.go +1 −1
  • internal/activator/claimgen_test.go +2 −2
  • internal/activator/claimloop_linux_test.go +2 −4
  • internal/activator/claimrecord_linux_test.go +1 −1
  • internal/activator/cmd_test.go +1 −1
  • internal/activator/cmdunit_test.go +1 −3
  • internal/activator/containment_test.go +1 −3
  • internal/activator/demo_durability_test.go +6 −11
  • internal/activator/escrow_test.go +3 −5
  • internal/activator/exec_gate_test.go +3 −4
  • internal/activator/generations_instances_test.go +1 −1
  • internal/activator/genservice_test.go +1 −1
  • internal/activator/group_admission_test.go +4 −4
  • internal/activator/ha_pool_test.go +11 −11
  • internal/activator/haadopt_test.go +4 −4
  • internal/activator/hadrain_test.go +2 −3
  • internal/activator/haescrow_branchfix_test.go +2 −3
  • internal/activator/hafiles_test.go +4 −6
  • internal/activator/haforward_test.go +7 −13
  • internal/activator/haleaseloss_test.go +6 −10
  • internal/activator/handover_test.go +2 −3
  • internal/activator/haplacement_test.go +6 −11
  • internal/activator/harelease_test.go +3 −5
  • internal/activator/hasecrets_test.go +1 −1
  • internal/activator/hasuspect_test.go +12 −22
  • internal/activator/hatake_test.go +3 −9
  • internal/activator/hawake_test.go +3 −5
  • internal/activator/heldstream_e2e_test.go +1 −1
  • internal/activator/inputs_test.go +2 −4
  • internal/activator/instancekey_test.go +2 −4
  • internal/activator/knobrestore_test.go +195 −64
  • internal/activator/maintenance_test.go +1 −1
  • internal/activator/opset_test.go +4 −12
  • internal/activator/outcome_fence_test.go +1 −3
  • internal/activator/pendingwake_linux_test.go +3 −3
  • internal/activator/probewake_test.go +8 −12
  • internal/activator/production_backend_test.go +1 −1
  • internal/activator/pty_linux_test.go +1 −3
  • internal/activator/replica_drill1_test.go +2 −6
  • internal/activator/replica_install_wait_test.go +1 −3
  • internal/activator/replicadeploy_test.go +5 −15
  • internal/activator/replicaswitchfail_test.go +1 −3
  • internal/activator/retire_refuse_e2e_test.go +1 −1
  • internal/activator/rootfs_admission_test.go +1 −1
  • internal/activator/rootfs_cmd_lease_test.go +3 −4
  • internal/activator/rootfs_cmd_test.go +2 −4
  • internal/activator/rootfs_gate_test.go +3 −3
  • internal/activator/rootfs_invariants_test.go +6 −15
  • internal/activator/rootfs_processes_test.go +1 −1
  • internal/activator/rootfs_release_backend_test.go +2 −3
  • internal/activator/rootfs_resident_lease_test.go +2 −4
  • internal/activator/rootfs_resident_test.go +1 −3
  • internal/activator/rootfs_service.go +3 −0
  • internal/activator/rootfs_staged_test.go +4 −4
  • internal/activator/rootfs_swap_release_test.go +1 −1
  • internal/activator/rootfs_test.go +4 −12
  • internal/activator/rootfs_wake_release_test.go +1 −1
  • internal/activator/rootfsdb_test.go +2 −4
  • internal/activator/rootfsrelease_test.go +7 −8
  • internal/activator/rootfsworkers_backend_test.go +1 −3
  • internal/activator/rootfsworkers_test.go +5 −6
  • internal/activator/seedplace_linux_test.go +29 −68
  • internal/activator/settle_test.go +4 −8
  • internal/activator/shuttingdown_answer_test.go +1 −1
  • internal/activator/size_live_test.go +1 −3
  • internal/activator/startrule_test.go +5 −6
  • internal/activator/startup_test.go +7 −11
  • internal/activator/stop_returned_sidecar_test.go +1 −3
  • internal/activator/swap_admit_test.go +2 −2
  • internal/activator/swap_executed_test.go +1 −2
  • internal/activator/swap_fixture_test.go +1 −1
  • internal/activator/swap_hold_test.go +5 −9
  • internal/activator/swap_review_test.go +2 −4
  • internal/activator/swap_sim_test.go +5 −6
  • internal/activator/tunnel_refuse_test.go +2 −2
  • internal/activator/unitproc_test.go +1 −3
  • internal/activator/wakecheck_claim_linux_test.go +1 −1
  • internal/activator/wakecheck_test.go +3 −7
  • internal/activator/wakeidentity_test.go +4 −6
  • internal/activator/wakeplan_test.go +10 −18
  • internal/activator/wakerecord_refused_test.go +1 −1
  • internal/activator/wakeslots_test.go +1 −1
  • internal/activator/worker_gen_test.go +3 −9
  • internal/activator/worker_generations_test.go +2 −2
  • internal/activator/worker_identity_test.go +1 −1
  • internal/activator/worker_respawn_exec_test.go +1 −3
  • internal/activator/worker_retained_pin_test.go +1 −3
  • internal/activator/workerswap_test.go +5 −13
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-race-activator-1249.tsv +2 −2
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index 289156228..800a24b0c 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -2228,8 +2228,8 @@ 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 - 3779 # raised: one field, the lease work counter tests join before restoring settings
-file-lines internal/activator activator_test.go - 5499
+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_test.go - 5481
file-lines internal/console server.go - 4219
file-lines internal/host agent.go - 3214
file-lines internal/provision reconcile_test.go - 3094
diff --git a/AGENTS.md b/AGENTS.md
index 4973080c3..49b99818e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -302,10 +302,13 @@ anything.
in edge, activator or host that reads the standard log uses its
package's `captureLog` (a locked buffer; host also has
`captureLogBuffer`), never a plain `bytes.Buffer`, and a goroutine a
- test starts ends before the test does. An activator test that changes
- a package-level setting puts it back with `restoreKnob` and builds its
- Service with `newTrackedService`, so the restore waits for the test's
- wakes. `internal/lease` is out for now (`.amadan/README.md` says why).
+ test starts ends before the test does. An activator test changes a
+ package-level setting only with `setKnob` and builds its Service with
+ `newTrackedService`, so the restore waits for the test's wakes. A
+ subtest may not change one while a Service it does not own runs (its
+ parent's, or one it built first): `setKnob` fails it, and the setting
+ goes in the parent, before the parent builds anything.
+ `internal/lease` is out for now (`.amadan/README.md` says why).
- `20-cross@5` adds `GOOS=darwin`/`windows`/`linux-arm64` compiles, one
per shard. **The gate is not Linux-only**: `internal/host` is linked
into the CLI, which people run on Macs, so a Linux-only type assumption
diff --git a/docs/superpowers/notes/census-proposal-race-activator-1249.md b/docs/superpowers/notes/census-proposal-race-activator-1249.md
index edd677c7c..9fab9e8c2 100644
--- a/docs/superpowers/notes/census-proposal-race-activator-1249.md
+++ b/docs/superpowers/notes/census-proposal-race-activator-1249.md
@@ -4,7 +4,7 @@ Ruling `census-ruling-race-activator-1249`. The independent reviewer approves or
| unit | change | read sites | what changed |
|---|---|---|---|
-| `internal/activator/activator.go` `type Service` | body | unchanged (0) | adds the leaseWork WaitGroup field, which counts lease watches for tests; no read added and production never waits on it |
+| `internal/activator/activator.go` `type Service` | body | unchanged (0) | adds two test-only fields: leaseWork (a WaitGroup counting lease watches and the one-shot stops a short lease starts) and leaseWatchStop (a channel, nil in production, that a test closes to end every lease watch); no read added and production never waits on or closes either |
| `internal/activator/rootfs_service.go` `Service.residentLeaseShort` | body | unchanged (2) | counts each one-shot stop in leaseWork around the same call; no read added, same stops in the same order |
Envelopes re-pinned: `internal/activator`.
@@ -16,6 +16,6 @@ Recorded dispositions, which each change must still satisfy:
- `internal/activator/activator.go` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: one more in-memory field, replicaFailed (host to the permit whose successor failed here, under mu), so that step only proves what it kept; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F fix round 3 (#511 F11): two hook fields, MarkReplicaRelease and ReplicaReleaseMark (the failure book's per-host release mark on this box's disk). No read site.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): one in-memory field, heldSeen (host to the last held release attempt, error class and when it was met), under the existing wakeFailMu. Declaration only, no read.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (27d3f501) adds the background atomic.Int64 field that tests wait on; this branch keeps its replica fields. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 3: adds replicaSwitched, an in-memory map of the permit each set row switched under (host -> permit key, time, resident flag); no read added; #511 micro-fix P1b: adds replicaNoGen, an in-memory map (host -> permit key and when first seen) that is only the bound's clock for a restarted permit holder with no generation; no read added;rev3=census-ruling-stateless-replicas-4-drill1;basis=#511 drill 1 R20 bound (round 1: clock with start and last seen): one in-memory field, releaseConfigWaits (per host, a stateless release's config wait), under mu; no read;rev3=census-ruling-stateless-replicas-4-r28;basis=R28 review round 2 (#511): one field, retiringCopy, an atomic pointer to the edge's in-memory retired-copy check, handed over by edge.New (SetRetiringCopy); no read, no root decision;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent as carlos: four fields, fenceWatchers (sync.WaitGroup of running write-fence watchers) and three test seams nil in production (fenceWatchStarted, retainDB, wakeReturned). Declaration only, no read.;rev3=census-ruling-fleet-record-labels-m1;basis=fleet record labels R1/R2: actEntry gains checkpoint state (busy while CloseProven runs, unproven, named-once flag for C45), in-memory under a.mu; the worker gains fence pacing apart from crash backoff; Service gains test seams nil in production; declarations only, no read
- `internal/activator/rootfs_service.go` `Service.residentLeaseShort`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): stops every one-shot unit that may run, whatever the entry's state, off a.mu; begins a resident's graceful stop only while it is awake, as before; in memory only
-Seal: `c6d366dcf2211b714977b7a69180289555b362dfe5f36a5780af90b5ece82998` → `436925ae22e4cbbfd427c440e5a1d270a8312554a8f6778efc6b46086b8dd093`.
+Seal: `5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4` → `c2580d30b6bbfa03d65a5a7dc66dd21bd3d88f16d2672edf104c082ec140d6d7`.
Overlay: `internal/provision/testdata/plan14-root-reads-race-activator-1249.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 24f5c507d..47e511d8f 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1692,6 +1692,11 @@ type Service struct {
// starts from it. Production never waits on it: it is how a test knows that
// work has ended before it restores a timing setting the work reads.
leaseWork sync.WaitGroup
+ // leaseWatchStop, once closed, ends every lease watch of this Service,
+ // whether or not its entry is still in a.entries. It is nil in
+ // production, so the watch's case on it never fires; a test makes it
+ // before the Service starts and closes it before restoring a setting.
+ leaseWatchStop chan struct{}
// schedMu guards schedFences, each host's schedule write fence
// (schedfence.go). It is never held with a.mu or a fence's own lock.
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go
index 42e1dd3b9..5bb78d173 100644
--- a/internal/activator/activator_test.go
+++ b/internal/activator/activator_test.go
@@ -897,7 +897,7 @@ func testActivator(t *testing.T, idle time.Duration) (*Service, *fakeBackend, *f
if err != nil {
t.Fatalf("open registry: %v", err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: idle}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: idle}, b, reg)
a.now = clk.now
return a, b, clk, reg
}
@@ -2009,9 +2009,7 @@ func TestActivatorRequestDuringStopRewakes(t *testing.T) {
// (503 at the edge) rather than piling connections up behind it.
func TestActivatorWakeTimeout(t *testing.T) {
a, b, _, _ := testActivator(t, time.Minute)
- old := wakeWaitBound
- wakeWaitBound = 100 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 100*time.Millisecond)
gate := make(chan struct{})
b.startGate = gate
@@ -2835,7 +2833,7 @@ func TestActivatorDueSurvivesRestart(t *testing.T) {
// "Restart": a fresh activator, same registry.
b2 := &fakeBackend{}
- a2 := newTrackedService(Config{Bucket: "test-bucket", Idle: 10 * time.Second}, b2, reg)
+ a2 := newTrackedService(t, Config{Bucket: "test-bucket", Idle: 10 * time.Second}, b2, reg)
a2.now = clk.now
clk.advance(25 * time.Second) // past the due time
@@ -3697,9 +3695,7 @@ func noteReadyAsChild(t *testing.T, a *Service, b *fakeBackend, host, version st
// not only once the entry is awake.
func TestWorkerTokenIsLiveDuringTheSettleWindow(t *testing.T) {
a, b, _, _ := testActivator(t, time.Hour)
- old := sidecarSettle
- sidecarSettle = 5 * time.Second
- defer func() { sidecarSettle = old }()
+ setKnob(t, &sidecarSettle, 5*time.Second)
done := make(chan error, 1)
go func() { done <- a.WakeWorker(testWorkerRoute("bot.x.internal")) }()
@@ -3750,9 +3746,7 @@ func TestWorkerExitInSettleWindowFailsWakeAndReleasesLease(t *testing.T) {
// A child that survives the window is up — no probe, no readiness call needed.
func TestWorkerSurvivingSettleWindowIsAwake(t *testing.T) {
a, _, _, _ := testActivator(t, time.Hour)
- old := sidecarSettle
- sidecarSettle = 60 * time.Millisecond
- defer func() { sidecarSettle = old }()
+ setKnob(t, &sidecarSettle, 60*time.Millisecond)
start := time.Now()
if err := a.WakeWorker(testWorkerRoute("bot.x.internal")); err != nil {
@@ -3770,9 +3764,7 @@ func TestWorkerSurvivingSettleWindowIsAwake(t *testing.T) {
// not pay ten seconds of dead time on every wake.
func TestWorkerReadyEndsSettleWindowEarly(t *testing.T) {
a, b, _, _ := testActivator(t, time.Hour)
- old := sidecarSettle
- sidecarSettle = 5 * time.Second
- defer func() { sidecarSettle = old }()
+ setKnob(t, &sidecarSettle, 5*time.Second)
done := make(chan error, 1)
start := time.Now()
@@ -4611,9 +4603,7 @@ func TestSleepWorkerIgnoresAnAlwaysOnWorker(t *testing.T) {
// process down with it.
func TestWorkerTokenMintFailureFailsWakeAndReleasesLease(t *testing.T) {
a, b, _, _ := testActivator(t, time.Hour)
- old := randRead
- randRead = func([]byte) (int, error) { return 0, errors.New("entropy pool exhausted") }
- defer func() { randRead = old }()
+ setKnob(t, &randRead, func([]byte) (int, error) { return 0, errors.New("entropy pool exhausted") })
err := a.WakeWorker(testWorkerRoute("bot.x.internal"))
if err == nil {
@@ -5922,9 +5912,7 @@ func TestExecBackendRestoreErrorIsNotFresh(t *testing.T) {
// swapRestoreReplica points the replica-restore seam at a stub for one test.
func swapRestoreReplica(t *testing.T, fn func(ctx context.Context, dbPath, bucket, prefix, region string) (bool, error)) {
t.Helper()
- prev := restoreReplica
- restoreReplica = fn
- restoreKnob(t, func() { restoreReplica = prev })
+ setKnob(t, &restoreReplica, fn)
}
// The seed contract, end to end through a real exec: the app's declared argv
@@ -6071,9 +6059,8 @@ func TestExecBackendSeedIsTimeBounded(t *testing.T) {
host := "hangs.example.com"
stageSeedScript(t, b, host, "v1", "sleep 30\n")
- prevTimeout, prevGrace := seedTimeout, seedDrainGrace
- seedTimeout, seedDrainGrace = 200*time.Millisecond, 200*time.Millisecond
- restoreKnob(t, func() { seedTimeout, seedDrainGrace = prevTimeout, prevGrace })
+ setKnob(t, &seedTimeout, 200*time.Millisecond)
+ setKnob(t, &seedDrainGrace, 200*time.Millisecond)
start := time.Now()
err := b.Seed(context.Background(), registry.Route{Host: host, Kind: "instance", Seed: `["seed"]`})
@@ -6155,9 +6142,8 @@ func TestExecBackendSeedSucceedsDespiteLingeringChild(t *testing.T) {
// sleeper inherits stderr and holds the pipe open past the drain grace.
stageSeedScript(t, b, host, "v1", "printf seeded > \"$3\"\nsleep 5 &\nexit 0\n")
- prevTimeout, prevGrace := seedTimeout, seedDrainGrace
- seedTimeout, seedDrainGrace = 10*time.Second, 200*time.Millisecond
- restoreKnob(t, func() { seedTimeout, seedDrainGrace = prevTimeout, prevGrace })
+ setKnob(t, &seedTimeout, 10*time.Second)
+ setKnob(t, &seedDrainGrace, 200*time.Millisecond)
if err := b.Seed(context.Background(), registry.Route{Host: host, Kind: "instance", Seed: `["seed"]`}); err != nil {
t.Fatalf("Seed = %v, want nil — the seed exited 0; a leaked output pipe is not a failed seed", err)
@@ -6491,9 +6477,7 @@ func TestExecBackendFailedWakeDoesNotNormalizeSocketMode(t *testing.T) {
stageServingLive(t, b, host)
t.Setenv("ACTIVATOR_FAKE_APP_UNHEALTHY", "1")
- old := spawnHealthTimeout
- spawnHealthTimeout = 500 * time.Millisecond
- defer func() { spawnHealthTimeout = old }()
+ setKnob(t, &spawnHealthTimeout, 500*time.Millisecond)
rt := registry.Route{Host: host, Kind: "instance", Socket: tmpSock(t)}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -6916,9 +6900,7 @@ func TestDoWakeRefreshesTheRouteFromTheRegistry(t *testing.T) {
// compares entry identity (the *actEntry captured at launch) rather than a
// counter, and the fresh wake below still gets its own sidecar.
func TestAStopKeepsTheLeaseUntilAnInFlightSidecarStartReturns(t *testing.T) {
- prev := sidecarStartJoinWait
- sidecarStartJoinWait = 50 * time.Millisecond
- restoreKnob(t, func() { sidecarStartJoinWait = prev })
+ setKnob(t, &sidecarStartJoinWait, 50*time.Millisecond)
a, b, _, _ := testActivator(t, time.Hour)
h := &hostEmptyFake{fakeBackend: b}
a.backend = h
@@ -7013,7 +6995,7 @@ func TestDoWakeRecordsSeedPlacementAfterReplication(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
rt := testRoute("shop.example.com")
rt.SeedSource = seeds.RowSeed{ID: "sd_aaaaaaaaaaaaaaaaaaaaaaaaaa", Kind: seeds.KindReplica, State: seeds.StateReady}.Encode()
if err := reg.Upsert(rt); err != nil {
diff --git a/internal/activator/backend_exec_test.go b/internal/activator/backend_exec_test.go
index d1f31096c..c6ceab78b 100644
--- a/internal/activator/backend_exec_test.go
+++ b/internal/activator/backend_exec_test.go
@@ -283,16 +283,14 @@ func TestRestoreStagingFallback(t *testing.T) {
// passes — exactly when the fake bucket holds objects under the prefix
// it was pointed at, which is the promotion's observable effect.
var restoredFrom []string
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
objs, _ := f.List(context.Background(), bucket, prefix)
if len(objs) == 0 {
return false, nil
}
restoredFrom = append(restoredFrom, bucket+"/"+prefix)
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
// Nothing staged, nothing own: plain fresh boot (restored=false→fresh=true).
fresh, err := b.Restore(ctx, rt)
@@ -376,16 +374,14 @@ func TestRestoreIgnoresMoveReceipts(t *testing.T) {
}
var restoredFrom []string
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
objs, _ := f.List(context.Background(), bucket, prefix)
if len(objs) == 0 {
return false, nil
}
restoredFrom = append(restoredFrom, bucket+"/"+prefix)
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
// Receipts alone: a fresh boot, nothing promoted, receipts untouched.
f.put(b.Cfg.Bucket, receipts, "r1")
@@ -630,9 +626,7 @@ func (r *recordingStrict) seen() []string {
// under a deadline) and then closed. With Strict false or unset the plain
// spawn runs exactly as before and the seam is never asked.
func TestSpawnUnderAMoveIsStrictOrRefused(t *testing.T) {
- old := spawnHealthTimeout
- spawnHealthTimeout = 300 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 300*time.Millisecond)
host := "strict.example.com"
// argvPath is the recorder's first file: once it exists and the child
// has exited, the health wait the recorder never answers is over.
@@ -849,9 +843,7 @@ func (f *flakyStrict) Close() error {
// succeeds, strict spawns work again. A drain that succeeded is not
// repeated when only the close failed.
func TestStrictCleanupIsRetriedAndRefusesUntilItSucceeds(t *testing.T) {
- old := spawnHealthTimeout
- spawnHealthTimeout = 300 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 300*time.Millisecond)
host := "retry.example.com"
for name, tc := range map[string]struct {
killFails, closeFails int
@@ -861,9 +853,7 @@ func TestStrictCleanupIsRetriedAndRefusesUntilItSucceeds(t *testing.T) {
"the close fails once": {0, 1, "start,kill-and-empty,close failed,close"},
} {
t.Run(name, func(t *testing.T) {
- oldBackoff := strictCleanupBackoff
- strictCleanupBackoff = []time.Duration{400 * time.Millisecond, 400 * time.Millisecond}
- restoreKnob(t, func() { strictCleanupBackoff = oldBackoff })
+ setKnob(t, &strictCleanupBackoff, []time.Duration{400 * time.Millisecond, 400 * time.Millisecond})
b := testExecBackend(t)
b.Cgroups = delegatedManager(t)
b.strictPreflight = func() error { return nil }
@@ -941,9 +931,7 @@ func TestStrictCleanupIsRetriedAndRefusesUntilItSucceeds(t *testing.T) {
// When it runs out the handle is kept and the host's strict spawns stay
// refused: a group that never drained may still hold a process.
func TestStrictCleanupGivesUpButStaysRefused(t *testing.T) {
- oldBackoff := strictCleanupBackoff
- strictCleanupBackoff = []time.Duration{10 * time.Millisecond, 10 * time.Millisecond}
- restoreKnob(t, func() { strictCleanupBackoff = oldBackoff })
+ setKnob(t, &strictCleanupBackoff, []time.Duration{10 * time.Millisecond, 10 * time.Millisecond})
host := "stuck.example.com"
b := testExecBackend(t)
h := &flakyStrict{recordingStrict: newRecordingStrict(), killFails: 100}
@@ -1051,9 +1039,7 @@ func (d *dirStrict) Close() error {
// strict spawns work afterwards. Meanwhile any spawn of the host, an
// ordinary one included (Strict switched off), is refused and never runs.
func TestPendingStrictCleanupOwnsTheGroup(t *testing.T) {
- old := spawnHealthTimeout
- spawnHealthTimeout = 300 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 300*time.Millisecond)
host := "owned.example.com"
for name, tc := range map[string]struct {
killFails, closeFails int
@@ -1063,9 +1049,7 @@ func TestPendingStrictCleanupOwnsTheGroup(t *testing.T) {
"a transient close failure on an empty group": {0, 1, "start,kill-and-empty,close failed,close"},
} {
t.Run(name, func(t *testing.T) {
- oldBackoff := strictCleanupBackoff
- strictCleanupBackoff = []time.Duration{500 * time.Millisecond, 500 * time.Millisecond}
- restoreKnob(t, func() { strictCleanupBackoff = oldBackoff })
+ setKnob(t, &strictCleanupBackoff, []time.Duration{500 * time.Millisecond, 500 * time.Millisecond})
b := testExecBackend(t)
b.Cgroups = delegatedManager(t)
b.strictPreflight = func() error { return nil }
@@ -1201,9 +1185,7 @@ func hookAt(point string, fn func()) func(string) {
// itself; an exit that runs once any owner exists, live or pending, removes
// nothing. A strict child whose cleanup then fails keeps its directory.
func TestAnOlderExitCannotRemoveANewOwnersGroup(t *testing.T) {
- oldBackoff := strictCleanupBackoff
- strictCleanupBackoff = []time.Duration{time.Hour}
- restoreKnob(t, func() { strictCleanupBackoff = oldBackoff })
+ setKnob(t, &strictCleanupBackoff, []time.Duration{time.Hour})
host := "race.example.com"
b := testExecBackend(t)
b.Cgroups = delegatedManager(t)
@@ -1270,9 +1252,7 @@ func TestAnOlderExitCannotRemoveANewOwnersGroup(t *testing.T) {
// only ever read and written under the host gate, so -race stays quiet
// however the two interleave.
func TestAPendingTransitionRacesARefusal(t *testing.T) {
- oldBackoff := strictCleanupBackoff
- strictCleanupBackoff = []time.Duration{time.Hour}
- restoreKnob(t, func() { strictCleanupBackoff = oldBackoff })
+ setKnob(t, &strictCleanupBackoff, []time.Duration{time.Hour})
host := "transition.example.com"
b := testExecBackend(t)
b.Strict = func(string) bool { return false }
@@ -1400,9 +1380,7 @@ func TestAStalledStartBlocksOnlyItsHost(t *testing.T) {
// never taken (held by the test throughout, a spawn that wanted it would
// hang).
func TestSwitchedOffSpawnsTakeNoNewLock(t *testing.T) {
- old := spawnHealthTimeout
- spawnHealthTimeout = 300 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 300*time.Millisecond)
b := testExecBackend(t)
b.Cgroups = delegatedManager(t)
host := "off.example.com"
@@ -1452,15 +1430,13 @@ func TestRestoreDoesNotPromoteStagingUnderPhase1(t *testing.T) {
host := "moved.example.com"
rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(t.TempDir(), "i.sock")}
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
objs, _ := f.List(context.Background(), bucket, prefix)
if len(objs) == 0 {
return false, nil
}
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
// The legacy shape and the Phase 1 shape (moves/<host>/<op>/...).
f.put(b.Cfg.Bucket, "moves/"+host+"/generations/a/snapshot", "e1")
diff --git a/internal/activator/backend_unit_test.go b/internal/activator/backend_unit_test.go
index 426bc0b3f..b2176dfe9 100644
--- a/internal/activator/backend_unit_test.go
+++ b/internal/activator/backend_unit_test.go
@@ -84,7 +84,7 @@ func testUnitActivator(t *testing.T, idle time.Duration) (*Service, *fakeBackend
if err != nil {
t.Fatalf("open registry: %v", err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: idle}, &SplitBackend{Exec: eb, Unit: ub}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: idle}, &SplitBackend{Exec: eb, Unit: ub}, reg)
a.now = clk.now
return a, eb, sc, clk, reg
}
@@ -203,7 +203,7 @@ func TestUnitTenantFailedHealthStopsUnit(t *testing.T) {
if err != nil {
t.Fatalf("open registry: %v", err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Minute}, &SplitBackend{Exec: &fakeBackend{}, Unit: ub}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Minute}, &SplitBackend{Exec: &fakeBackend{}, Unit: ub}, reg)
if _, err := a.beginRequest(context.Background(), route); err == nil {
t.Fatal("wake succeeded despite the health gate failing")
@@ -391,9 +391,7 @@ func TestUnitTenantWakeServesHeldRequest(t *testing.T) {
}
}
- old := spawnHealthTimeout
- spawnHealthTimeout = 5 * time.Second
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 5*time.Second)
eb := &fakeBackend{}
ub := &UnitBackend{Systemctl: sc.run, OptDir: t.TempDir()} // nil WaitHealthy: the real prober
@@ -402,7 +400,7 @@ func TestUnitTenantWakeServesHeldRequest(t *testing.T) {
if err != nil {
t.Fatalf("open registry: %v", err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: 10 * time.Second}, &SplitBackend{Exec: eb, Unit: ub}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: 10 * time.Second}, &SplitBackend{Exec: eb, Unit: ub}, reg)
a.now = clk.now
route := registry.Route{Host: "kass.example.com", Kind: "instance", Addr: addr,
diff --git a/internal/activator/binary_golden_test.go b/internal/activator/binary_golden_test.go
index 00b5bd8bb..a0a091de8 100644
--- a/internal/activator/binary_golden_test.go
+++ b/internal/activator/binary_golden_test.go
@@ -278,9 +278,8 @@ func serveAfter(t *testing.T, sock string, delay time.Duration) {
func TestGenHealthyBoundBinary(t *testing.T) {
var out strings.Builder
fmt.Fprintf(&out, "spawnHealthTimeout %s\n", spawnHealthTimeout)
- oldBound, oldFloor := spawnHealthTimeout, firstWakeMinVerdict
- spawnHealthTimeout, firstWakeMinVerdict = time.Second, 50*time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout, firstWakeMinVerdict = oldBound, oldFloor })
+ setKnob(t, &spawnHealthTimeout, time.Second)
+ setKnob(t, &firstWakeMinVerdict, 50*time.Millisecond)
dir, err := os.MkdirTemp("", "gh")
if err != nil {
t.Fatal(err)
diff --git a/internal/activator/canonlink_test.go b/internal/activator/canonlink_test.go
index 697292f9f..310d09cea 100644
--- a/internal/activator/canonlink_test.go
+++ b/internal/activator/canonlink_test.go
@@ -99,7 +99,7 @@ func sockGenActivator(t *testing.T, on bool) (*Service, registry.Route) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &sockGenBackend{fakeBackend: &fakeBackend{}, t: t, dir: dir}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &sockGenBackend{fakeBackend: &fakeBackend{}, t: t, dir: dir}, reg)
rt := testRoute("link.example.com")
rt.Socket = filepath.Join(dir, "c.sock")
return a, rt
diff --git a/internal/activator/claimgen_test.go b/internal/activator/claimgen_test.go
index ecd57d31a..b3e639e00 100644
--- a/internal/activator/claimgen_test.go
+++ b/internal/activator/claimgen_test.go
@@ -110,7 +110,7 @@ func TestStartAdmittedRefusesAGenerationMismatch(t *testing.T) {
func TestClaimGenAt(t *testing.T) {
b := testExecBackend(t)
b.RunDirOverride = t.TempDir()
- a := newTrackedService(Config{}, b, nil)
+ a := newTrackedService(t, Config{}, b, nil)
flat := registry.Route{Host: "c.example.com", Kind: "instance", DBPath: b.DataDir + "/c.example.com.db", Socket: b.RunDirOverride + "/c.example.com.sock"}
if g := a.claimGenAt(flat, 4); g.N != 4 || g.Socket != b.flatGenSocket(flat.Host, 4) || g.Control != g.Socket+".control" {
t.Fatalf("flat: %+v", g)
@@ -121,7 +121,7 @@ func TestClaimGenAt(t *testing.T) {
}
// The split backend asks its exec half; a unit-backed row has no
// generation path of its own.
- split := newTrackedService(Config{}, &SplitBackend{Exec: b}, nil)
+ split := newTrackedService(t, Config{}, &SplitBackend{Exec: b}, nil)
if g := split.claimGenAt(flat, 6); g.N != 6 || g.Socket != b.flatGenSocket(flat.Host, 6) {
t.Fatalf("split, flat: %+v", g)
}
diff --git a/internal/activator/claimloop_linux_test.go b/internal/activator/claimloop_linux_test.go
index 84280df3b..2f6c6e8c9 100644
--- a/internal/activator/claimloop_linux_test.go
+++ b/internal/activator/claimloop_linux_test.go
@@ -51,14 +51,12 @@ func (r *loopRun) log(event string) {
// is read exactly, with no real time in it.
func recordClaimBackoff(t *testing.T, run *loopRun) {
t.Helper()
- old := claimBackoffTimer
- claimBackoffTimer = func(d time.Duration) (<-chan time.Time, func() bool) {
+ setKnob(t, &claimBackoffTimer, func(d time.Duration) (<-chan time.Time, func() bool) {
run.log("wait " + d.String())
fired := make(chan time.Time, 1)
fired <- time.Now()
return fired, func() bool { return false }
- }
- restoreKnob(t, func() { claimBackoffTimer = old })
+ })
}
func (r *loopRun) starts() []time.Time {
diff --git a/internal/activator/claimrecord_linux_test.go b/internal/activator/claimrecord_linux_test.go
index 6507243ac..3f54b4cbc 100644
--- a/internal/activator/claimrecord_linux_test.go
+++ b/internal/activator/claimrecord_linux_test.go
@@ -311,7 +311,7 @@ func claimedSidecarRestart(t *testing.T, pinned bool) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box", Bucket: "data",
+ a := newTrackedService(t, Config{Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box", Bucket: "data",
Read: func(context.Context, string) (hostclaim.Observed, error) {
mu.Lock()
defer mu.Unlock()
diff --git a/internal/activator/cmd_test.go b/internal/activator/cmd_test.go
index b5220fce6..afcae2e66 100644
--- a/internal/activator/cmd_test.go
+++ b/internal/activator/cmd_test.go
@@ -156,7 +156,7 @@ func testCmdActivator(t *testing.T, cfg Config) (*Service, *cmdFakeBackend, *fak
if cfg.Idle == 0 {
cfg.Idle = time.Second
}
- a := newTrackedService(cfg, cb, reg)
+ a := newTrackedService(t, cfg, cb, reg)
a.now = clk.now
return a, cb, clk
}
diff --git a/internal/activator/cmdunit_test.go b/internal/activator/cmdunit_test.go
index e45a2f06a..5a493b546 100644
--- a/internal/activator/cmdunit_test.go
+++ b/internal/activator/cmdunit_test.go
@@ -85,9 +85,7 @@ func startTestCmd(t *testing.T) (*ExecBackend, registry.Route, *fakeControl, *fa
// connect their streams, so every Drain waits the whole grace.
func shrinkCmdAcceptGrace(t *testing.T, d time.Duration) {
t.Helper()
- old := cmdAcceptGrace
- cmdAcceptGrace = d
- restoreKnob(t, func() { cmdAcceptGrace = old })
+ setKnob(t, &cmdAcceptGrace, d)
}
func TestStartCmdWritesTheLaunchFileAndStartsTheUnit(t *testing.T) {
diff --git a/internal/activator/containment_test.go b/internal/activator/containment_test.go
index 4af850541..dce53306f 100644
--- a/internal/activator/containment_test.go
+++ b/internal/activator/containment_test.go
@@ -641,9 +641,7 @@ func TestASeedWhoseObligationCannotBeWrittenRunsNothing(t *testing.T) {
b, _ := delegatedBackend(t, host)
runs := filepath.Join(t.TempDir(), "runs")
stageSeedScript(t, b, host, "v1", fmt.Sprintf("echo run >> %q\nprintf half > \"$3\"\nexit 0\n", runs))
- orig := writeSeedObligationFile
- restoreKnob(t, func() { writeSeedObligationFile = orig })
- writeSeedObligationFile = func(string, []byte, os.FileMode) error { return syscall.ENOSPC }
+ setKnob(t, &writeSeedObligationFile, func(string, []byte, os.FileMode) error { return syscall.ENOSPC })
err := b.Seed(context.Background(), registry.Route{Host: host, Kind: "instance", Seed: `["seed"]`})
if err == nil || errors.Is(err, ErrSeedUnproven) || !errors.Is(err, syscall.ENOSPC) {
diff --git a/internal/activator/demo_durability_test.go b/internal/activator/demo_durability_test.go
index 9a0d758cb..dfc436b97 100644
--- a/internal/activator/demo_durability_test.go
+++ b/internal/activator/demo_durability_test.go
@@ -62,12 +62,10 @@ func TestDemoDatabaseSurvivesLocalRestart(t *testing.T) {
b.FilesStore = spy
rt := demoDataRoute(t, b)
var replicaGETs atomic.Int64
- old := restoreReplica
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) {
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) {
replicaGETs.Add(1)
return false, nil
- }
- restoreKnob(t, func() { restoreReplica = old })
+ })
fresh, err := b.Restore(ctx, rt)
if err != nil || !fresh {
t.Fatalf("new instance: fresh=%v err=%v", fresh, err)
@@ -391,13 +389,11 @@ func TestDemoDatabaseServiceSleepWakeAndAdoption(t *testing.T) {
rt := demoDataRoute(t, disk)
spy := &demoDataSpy{Store: release.NewDirStore(t.TempDir())}
disk.FilesStore = spy
- old := restoreReplica
var restores atomic.Int64
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) {
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) {
restores.Add(1)
return false, nil
- }
- restoreKnob(t, func() { restoreReplica = old })
+ })
a, b, _, reg := testActivator(t, time.Hour)
t.Cleanup(func() { a.Shutdown(ctx); reg.Close() })
a.backend = &demoRestoreBackend{fakeBackend: b, disk: disk}
@@ -591,15 +587,14 @@ func TestDemoDatabaseInitializationRetry(t *testing.T) {
store := &demoInitFaultStore{Store: release.NewDirStore(t.TempDir()), fault: fault}
b.FilesStore = store
originalSync := durableSync
- restoreKnob(t, func() { durableSync = originalSync })
- durableSync = func(dir string) error {
+ setKnob(t, &durableSync, func(dir string) error {
_, dbErr := os.Stat(rt.DBPath)
_, markerErr := os.Stat(rt.DBPath + AssignedMarkerSuffix)
if dir == filepath.Dir(rt.DBPath) && (fault == "assignment-sync" && markerErr == nil || fault == "database-sync" && dbErr == nil) {
return errors.New("injected directory sync failure")
}
return originalSync(dir)
- }
+ })
if fresh, err := b.Restore(ctx, rt); err == nil || fresh {
t.Fatalf("first attempt: fresh=%v err=%v", fresh, err)
}
diff --git a/internal/activator/escrow_test.go b/internal/activator/escrow_test.go
index 4faddb85b..7f7c3c3e2 100644
--- a/internal/activator/escrow_test.go
+++ b/internal/activator/escrow_test.go
@@ -350,7 +350,7 @@ func TestNotReadyRefusesRestoreMintAndFirstLaunch(t *testing.T) {
nb := restartEscrow(t, s.b)
s.b = nb
s.wire(nb)
- s.a = newTrackedService(Config{Bucket: nb.Cfg.Bucket, Idle: time.Hour}, nb, nb.Registry)
+ s.a = newTrackedService(t, Config{Bucket: nb.Cfg.Bucket, Idle: time.Hour}, nb, nb.Registry)
t.Cleanup(s.abandon)
nb.EscrowKey = nil
if nb.escrowModeOf(s.rt) != escrowNoKey {
@@ -1150,7 +1150,7 @@ func TestABoxThatChangesKeyFailsClosed(t *testing.T) {
nb.FilesStore = cs
s.b = nb
s.wire(nb)
- s.a = newTrackedService(Config{Bucket: nb.Cfg.Bucket, Idle: time.Hour}, nb, nb.Registry)
+ s.a = newTrackedService(t, Config{Bucket: nb.Cfg.Bucket, Idle: time.Hour}, nb, nb.Registry)
sealB := sealerOf(t, nb, rt)
release := holdLease(t, nb, rt)
rep := nb.EscrowSweep(ctx, []registry.Route{rt})
@@ -1272,9 +1272,7 @@ func TestSweepRacesNoLaunchOrWorker(t *testing.T) {
// writeFailingMarker makes every conflict-marker write fail for the test.
func writeFailingMarker(t *testing.T) {
t.Helper()
- old := writeEscrowMarker
- writeEscrowMarker = func(string, string, []byte) error { return errors.New("disk full") }
- restoreKnob(t, func() { writeEscrowMarker = old })
+ setKnob(t, &writeEscrowMarker, func(string, string, []byte) error { return errors.New("disk full") })
}
// P1-1 (round 2): an escrowed instance.key is write-once. A local key that
diff --git a/internal/activator/exec_gate_test.go b/internal/activator/exec_gate_test.go
index d575ab901..366b67ac5 100644
--- a/internal/activator/exec_gate_test.go
+++ b/internal/activator/exec_gate_test.go
@@ -216,8 +216,7 @@ func TestTheExecGateIsAskedAtTheBackendsLaunchPoint(t *testing.T) {
}
})
t.Run(layout+"/planned fallback, fenced", func(t *testing.T) {
- defer func(k time.Duration) { firstWakeKillBound = k }(firstWakeKillBound)
- firstWakeKillBound = 500 * time.Millisecond
+ setKnob(t, &firstWakeKillBound, 500*time.Millisecond)
b := newLaunchBackend(t, layout, &fakeSwapBackend{fakeBackend: &fakeBackend{}})
dir := t.TempDir()
markB, markGood := filepath.Join(t.TempDir(), "v2.ran"), filepath.Join(t.TempDir(), "v1.ran")
@@ -311,7 +310,7 @@ func launchActivator(t *testing.T, b *launchBackend, plan WakePlan) (*Service, *
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.gens = true
evs := &genLog{}
a.OnGen = evs.add
@@ -424,7 +423,7 @@ func workerGateService(t *testing.T, flip func()) (*Service, *ExecBackend, regis
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &realWorkerBackend{fakeBackend: &fakeBackend{}, exec: eb}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &realWorkerBackend{fakeBackend: &fakeBackend{}, exec: eb}, reg)
a.GenerationsFile = release.GenerationsPath(t.TempDir())
t.Cleanup(func() { a.Shutdown(context.Background()) })
return a, eb, workerRoute(host), out, dir
diff --git a/internal/activator/generations_instances_test.go b/internal/activator/generations_instances_test.go
index 6eaeb35b5..1fc3cbe18 100644
--- a/internal/activator/generations_instances_test.go
+++ b/internal/activator/generations_instances_test.go
@@ -345,7 +345,7 @@ func claimedPlanActivator(t *testing.T, plan WakePlan) (*Service, *atomic.Int32,
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box",
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box",
Read: func(context.Context, string) (hostclaim.Observed, error) {
if reads.Add(1) == 1 {
return obs, nil
diff --git a/internal/activator/genservice_test.go b/internal/activator/genservice_test.go
index 6d4749b67..793c456e0 100644
--- a/internal/activator/genservice_test.go
+++ b/internal/activator/genservice_test.go
@@ -61,7 +61,7 @@ func genActivator(t *testing.T, on bool) (*Service, *genFakeBackend) {
if err != nil {
t.Fatal(err)
}
- return newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, gb, reg), gb
+ return newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, gb, reg), gb
}
// genTestRoute is testRoute with its canonical socket in the test's own
diff --git a/internal/activator/group_admission_test.go b/internal/activator/group_admission_test.go
index b1a3dcdca..af5c647ef 100644
--- a/internal/activator/group_admission_test.go
+++ b/internal/activator/group_admission_test.go
@@ -13,7 +13,7 @@ import (
func TestPreAdmissionNonHTTP(t *testing.T) {
b := &fakeBackend{}
- a := newTrackedService(Config{}, b, nil)
+ a := newTrackedService(t, Config{}, b, nil)
a.TenantStartAllowed = func() bool { return false }
a.TenantAdmittedFunc = func() bool { return false }
rt := testRoute("shop.example.com")
@@ -65,7 +65,7 @@ func TestPreAdmissionDirectAndHop(t *testing.T) {
t.Fatal(err)
}
b := &fakeBackend{}
- a := newTrackedService(Config{}, b, nil)
+ a := newTrackedService(t, Config{}, b, nil)
a.TenantAdmittedFunc = func() bool { return false }
a.TenantStartAllowed = func() bool { return false }
e, err := edge.New(reg, a)
@@ -126,7 +126,7 @@ func TestAdmissionLaunchRecheck(t *testing.T) {
func TestAdmissionClosesBeforeAcquire(t *testing.T) {
b := &fakeBackend{}
- a := newTrackedService(Config{}, b, nil)
+ a := newTrackedService(t, Config{}, b, nil)
checks := 0
a.TenantStartAllowed = func() bool { checks++; return checks == 1 }
rt := testRoute("shop.example.com")
@@ -142,7 +142,7 @@ func TestAdmissionClosesBeforeAcquire(t *testing.T) {
// job for a unit bound to the edge would queue behind the drain unit's
// stop and could cancel the edge's pending stop (W6 final review F4).
func TestTenantStartsClosedRefusesExemptRoutesToo(t *testing.T) {
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
a.TenantExempt = func(rt registry.Route) bool { return rt.Platform }
platform, tenant := registry.Route{Host: "console.example.com", Platform: true}, testRoute("shop.example.com")
if a.tenantStartRefusal(platform) != nil || a.tenantStartRefusal(tenant) != nil {
diff --git a/internal/activator/ha_pool_test.go b/internal/activator/ha_pool_test.go
index bdb11f9e2..2aed12f44 100644
--- a/internal/activator/ha_pool_test.go
+++ b/internal/activator/ha_pool_test.go
@@ -16,7 +16,7 @@ import (
func TestPoolGateCannotFallBackLocal(t *testing.T) {
for _, kind := range []string{"forward", "static", "unit", "non-hibernating", "tunnel"} {
t.Run(kind, func(t *testing.T) {
- a := newTrackedService(Config{}, poolDeniedBackend{}, nil)
+ a := newTrackedService(t, Config{}, poolDeniedBackend{}, nil)
rt := registry.Route{Host: "pass.example.com", Kind: kind, Pool: ""}
if kind == "unit" || kind == "non-hibernating" || kind == "tunnel" {
rt.Kind = "instance"
@@ -97,7 +97,7 @@ type poolDeniedBackend struct{ Backend }
func (poolDeniedBackend) poolEligible(registry.Route) bool { return false }
func TestPoolGateIndependentAdmissions(t *testing.T) {
- a := newTrackedService(Config{}, poolDeniedBackend{}, nil)
+ a := newTrackedService(t, Config{}, poolDeniedBackend{}, nil)
rt := registry.Route{Host: "known.example.com", HA: true, Pool: "ha"}
if d := a.ForwardTarget(t.Context(), rt, nil); !d.Unavailable {
t.Fatalf("no reader: %+v", d)
@@ -134,15 +134,15 @@ func TestPoolGateIndependentAdmissions(t *testing.T) {
}
delete(s.a.entries, s.rt.Host) // synthetic entries own no process or lease
}
- t.Run("placement generation lost", func(t *testing.T) {
- s := haService(t, "shop.example.com")
- s.rt.HA = true
- s.b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[]`) }
- d := s.a.ForwardTarget(t.Context(), s.rt, func() boxchoice.WakeSnapshot { s.a.holders.drop(s.rt.Host); return placementSnapshot(time.Now()) })
- if !d.Unavailable {
- t.Fatalf("lost observation fell through: %+v", d)
- }
- })
+ // A placement generation lost. Not a subtest: haService changes a package
+ // setting, which a subtest may not do while this test's Services run.
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ s.b.ServedPools = func() edgesfile.PoolEvidence { return edgesfile.PoolEvidence(`[]`) }
+ d := s.a.ForwardTarget(t.Context(), s.rt, func() boxchoice.WakeSnapshot { s.a.holders.drop(s.rt.Host); return placementSnapshot(time.Now()) })
+ if !d.Unavailable {
+ t.Fatalf("placement generation lost: the lost observation fell through: %+v", d)
+ }
}
func TestPoolGateExpiredOwnerNeedsEligibleReceiver(t *testing.T) {
diff --git a/internal/activator/haadopt_test.go b/internal/activator/haadopt_test.go
index fe5a55ede..4e23fa3bf 100644
--- a/internal/activator/haadopt_test.go
+++ b/internal/activator/haadopt_test.go
@@ -367,7 +367,7 @@ func TestHAAdoptRestartPhases(t *testing.T) {
defer reg.Close()
s.b.Registry = reg
sameBoxReady(s.b)
- fresh := newTrackedService(s.a.cfg, s.b, reg)
+ fresh := newTrackedService(t, s.a.cfg, s.b, reg)
fresh.DutyStore = reg
got, err := fresh.AdoptHost(ctx, s.rt, req)
if err != nil || (got != Adopted && got != AlreadyAdopted) {
@@ -455,7 +455,7 @@ func TestHAAdoptSequentialDepartures(t *testing.T) {
t.Fatal(err)
}
s.b.Registry = reg
- s.a = newTrackedService(s.a.cfg, s.b, reg)
+ s.a = newTrackedService(t, s.a.cfg, s.b, reg)
s.a.DutyStore = reg
req.Observed, err = lease.ReadLock(ctx, s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region)
if err != nil {
@@ -480,7 +480,7 @@ func TestHAAdoptSequentialDepartures(t *testing.T) {
return false, nil
}
s.a.now = func() time.Time { return time.Now().Add(48 * time.Hour) }
- fresh := newTrackedService(s.a.cfg, s.b, s.b.Registry)
+ fresh := newTrackedService(t, s.a.cfg, s.b, s.b.Registry)
fresh.DutyStore = s.b.Registry
fresh.now = s.a.now
s.a = fresh
@@ -761,7 +761,7 @@ func TestHAAdoptRestartAcquiringDepartedLock(t *testing.T) {
}
defer reg.Close()
s.b.Registry = reg
- fresh := newTrackedService(s.a.cfg, s.b, reg)
+ fresh := newTrackedService(t, s.a.cfg, s.b, reg)
fresh.DutyStore = reg
if got, err := fresh.AdoptHost(context.Background(), s.rt, req); err != nil || got != Adopted {
t.Fatalf("restart %v %v", got, err)
diff --git a/internal/activator/hadrain_test.go b/internal/activator/hadrain_test.go
index 9df1466ee..6bb59dbbf 100644
--- a/internal/activator/hadrain_test.go
+++ b/internal/activator/hadrain_test.go
@@ -68,11 +68,10 @@ func TestSilentDrainingHolderIsNotSuspect(t *testing.T) {
}
var reads atomic.Int32
old := readHolderLock
- readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
reads.Add(1)
return old(ctx, bucket, prefix, region)
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
s.a.NoteForward(s.rt.Host, edge.ForwardResult{Kind: edge.Holder, Outcome: edge.ForwardSilent, Ref: d.Ref, Gen: d.Gen, PeerGen: d.PeerGen})
if s.a.peers.snapshot(time.Now()).Suspect["b"] {
t.Fatal("silence from a draining box made it a placement suspect")
diff --git a/internal/activator/haescrow_branchfix_test.go b/internal/activator/haescrow_branchfix_test.go
index fc9580c89..af28a81f3 100644
--- a/internal/activator/haescrow_branchfix_test.go
+++ b/internal/activator/haescrow_branchfix_test.go
@@ -236,9 +236,8 @@ func TestHASnapshotRefreshRestagesWholeTree(t *testing.T) {
t.Fatal(err)
}
previous := syncFilesAt
- restoreKnob(t, func() { syncFilesAt = previous })
first := true
- syncFilesAt = func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) {
+ setKnob(t, &syncFilesAt, func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) {
if !first {
return previous(ctx, p, dir, skip)
}
@@ -255,7 +254,7 @@ func TestHASnapshotRefreshRestagesWholeTree(t *testing.T) {
t.Fatal(err)
}
return hostfiles.SyncStats{}, p.Stage(ctx, "b.txt", []byte("b"), 0o600, false)
- }
+ })
if err := f.publishSnapshot(ctx); err == nil || f.lastDigest != "" {
t.Fatalf("discarded app stage earned a completed snapshot: %v", err)
}
diff --git a/internal/activator/hafiles_test.go b/internal/activator/hafiles_test.go
index 1af16c775..8345fb25f 100644
--- a/internal/activator/hafiles_test.go
+++ b/internal/activator/hafiles_test.go
@@ -236,13 +236,12 @@ func TestIncompleteSnapshotRunsAgainOverAnUnchangedTree(t *testing.T) {
f.platformEvery, f.snapshotEvery = time.Hour, 100*time.Millisecond
var calls atomic.Int32
prev := syncFilesAt
- syncFilesAt = func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) {
+ setKnob(t, &syncFilesAt, func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) {
if calls.Add(1) == 1 { // a transient read failure: nothing staged, the file reported unreadable
return hostfiles.SyncStats{Unreadable: []string{"a.txt"}}, nil
}
return prev(ctx, p, dir, skip)
- }
- restoreKnob(t, func() { syncFilesAt = prev })
+ })
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go f.Run(ctx)
@@ -269,14 +268,13 @@ func TestPlatformPublishesDuringASnapshot(t *testing.T) {
blocked, unblock := make(chan struct{}), make(chan struct{})
var once sync.Once
prev := syncFilesAt
- syncFilesAt = func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) {
+ setKnob(t, &syncFilesAt, func(ctx context.Context, p *hostfiles.Publisher, dir *os.File, skip func(string, bool) bool) (hostfiles.SyncStats, error) {
if skip != nil && !skip("a.txt", false) { // the snapshot's read (the platform pass syncs no tree)
once.Do(func() { close(blocked) })
<-unblock
}
return prev(ctx, p, dir, skip)
- }
- restoreKnob(t, func() { syncFilesAt = prev })
+ })
ctx, cancel := context.WithCancel(context.Background())
ran := make(chan struct{})
go func() { defer close(ran); f.Run(ctx) }()
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go
index 0d9cc52e1..74fbfe1f5 100644
--- a/internal/activator/haforward_test.go
+++ b/internal/activator/haforward_test.go
@@ -22,9 +22,7 @@ import (
// asForwarded makes every request in the test a verified hop.
func asForwarded(t *testing.T) {
t.Helper()
- old := forwardedHop
- forwardedHop = func(*http.Request) bool { return true }
- restoreKnob(t, func() { forwardedHop = old })
+ setKnob(t, &forwardedHop, func(*http.Request) bool { return true })
}
// lockGets counts the GETs of rt's lock.json.
@@ -138,12 +136,11 @@ func TestForwardTargetSingleFlight(t *testing.T) {
gate := make(chan struct{})
var reads atomic.Int32
old := readHolderLock
- readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
reads.Add(1)
<-gate
return old(ctx, bucket, prefix, region)
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
got := s.concurrently(20)
waitFor(t, "the first read", func() bool { return reads.Load() == 1 })
time.Sleep(50 * time.Millisecond) // the other 19 queue on it
@@ -284,9 +281,7 @@ func refusal(t *testing.T, ha bool, setup func(*Service, *fakeBackend)) *httptes
func TestHoppedOtherRefusalsSayNone(t *testing.T) {
asForwarded(t)
- old := wakeWaitBound
- wakeWaitBound = 100 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 100*time.Millisecond)
cases := []struct {
name string
retry string
@@ -366,11 +361,10 @@ func TestScheduledTickNeverForwards(t *testing.T) {
s := haHeldByB(t)
var reads atomic.Int32
old := readHolderLock
- readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
reads.Add(1)
return old(ctx, bucket, prefix, region)
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
rec := httptest.NewRecorder()
s.a.ServeScheduled(rec, httptest.NewRequest("POST", "http://shop.example.com/", nil), s.rt, mustNotProxy(t))
if rec.Code != 503 || rec.Header().Get("Retry-After") == "" || rec.Header().Get("Retry-After") == "1" ||
@@ -393,7 +387,7 @@ func TestScheduledTickNeverForwards(t *testing.T) {
// unit-backed row, which cannot be born HA here, reads nothing.
func TestForwardTargetThroughSplitBackend(t *testing.T) {
s := haHeldByB(t)
- a := newTrackedService(Config{Bucket: s.b.Cfg.Bucket, Idle: time.Hour}, &SplitBackend{Exec: s.b, Unit: &UnitBackend{}}, s.b.Registry)
+ a := newTrackedService(t, Config{Bucket: s.b.Cfg.Bucket, Idle: time.Hour}, &SplitBackend{Exec: s.b, Unit: &UnitBackend{}}, s.b.Registry)
d := a.ForwardTarget(context.Background(), s.rt, nil)
if d.Ref != "b" {
t.Fatalf("ForwardTarget through the split backend = %+v, want b", d)
diff --git a/internal/activator/haleaseloss_test.go b/internal/activator/haleaseloss_test.go
index e43ae3871..2c8e6d50f 100644
--- a/internal/activator/haleaseloss_test.go
+++ b/internal/activator/haleaseloss_test.go
@@ -360,10 +360,9 @@ func TestHALostLeaseRecoversOnlyAfterFreshAcquireNewLifetime(t *testing.T) {
func TestHALostLeaseRecoveryAttemptAndShutdown(t *testing.T) {
s, e, r := lostTestEntry(t)
finishLostTestEntry(t, s, e, r)
- old := readHolderLock
entered := make(chan struct{})
finished := make(chan struct{})
- readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
defer close(finished)
deadline, ok := ctx.Deadline()
if !ok || time.Until(deadline) > 2*time.Second {
@@ -372,8 +371,7 @@ func TestHALostLeaseRecoveryAttemptAndShutdown(t *testing.T) {
close(entered)
<-ctx.Done()
return hafresh.View{}, ctx.Err()
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
s.a.retryHALostHost(s.rt)
<-entered
for i := 0; i < 20; i++ {
@@ -432,9 +430,8 @@ func TestHALostOrdinaryStopStillWaits(t *testing.T) {
func TestHALostLeaseRecoveryAcquireBudget(t *testing.T) {
s, e, r := lostTestEntry(t)
finishLostTestEntry(t, s, e, r)
- old := acquireHALease
called := false
- acquireHALease = func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*lease.Held, error) {
+ setKnob(t, &acquireHALease, func(ctx context.Context, bucket, prefix, region string, base hafresh.Marker, p hafresh.Proofs) (*lease.Held, error) {
called = true
deadline, ok := ctx.Deadline()
if !ok || time.Until(deadline) > 2*time.Second {
@@ -442,8 +439,7 @@ func TestHALostLeaseRecoveryAcquireBudget(t *testing.T) {
}
<-ctx.Done()
return nil, ctx.Err()
- }
- restoreKnob(t, func() { acquireHALease = old })
+ })
s.a.retryHALostHost(s.rt)
s.a.haLoss.joined.Wait()
if !called {
@@ -461,7 +457,7 @@ func (lostDiscoveryBackend) readHolderView(ctx context.Context, _ registry.Route
}
func TestHALostLeaseRecoveryWorkersBounded(t *testing.T) {
- a := newTrackedService(Config{}, lostDiscoveryBackend{}, nil)
+ a := newTrackedService(t, Config{}, lostDiscoveryBackend{}, nil)
a.haLoss.hosts = make(map[string]*haLeaseLoss)
a.Routes = withdrawalLookup(func(host string) (*registry.Route, error) {
return &registry.Route{Host: host, HA: true, Kind: "instance"}, nil
@@ -644,7 +640,7 @@ func (b *lostCountingBackend) readHolderView(context.Context, registry.Route) (h
func TestHALostRecoveryMassLossAndDemandExpiry(t *testing.T) {
b := &lostCountingBackend{fakeBackend: &fakeBackend{}}
- a := newTrackedService(Config{}, b, nil)
+ a := newTrackedService(t, Config{}, b, nil)
defer a.lifeStop()
clk := &fakeClock{t: time.Now()}
a.now = clk.now
diff --git a/internal/activator/handover_test.go b/internal/activator/handover_test.go
index 48826640e..7aed4374e 100644
--- a/internal/activator/handover_test.go
+++ b/internal/activator/handover_test.go
@@ -30,9 +30,8 @@ var (
func shortMoveBounds(t *testing.T, client, hop time.Duration) {
t.Helper()
- oc, oh := moveHoldClient, moveHoldHop
- moveHoldClient, moveHoldHop = client, hop
- restoreKnob(t, func() { moveHoldClient, moveHoldHop = oc, oh })
+ setKnob(t, &moveHoldClient, client)
+ setKnob(t, &moveHoldHop, hop)
}
// waitAsync runs d.Wait in the background.
diff --git a/internal/activator/haplacement_test.go b/internal/activator/haplacement_test.go
index fbb5b94fa..9b2d9bb36 100644
--- a/internal/activator/haplacement_test.go
+++ b/internal/activator/haplacement_test.go
@@ -201,11 +201,9 @@ func TestPlacementSnapshotIsLazy(t *testing.T) {
s.a.holders.unreachable(s.rt.Host, gen)
if mode == "failed revalidation" {
clk.advance(holderSuspectTTL)
- old := readHolderLock
- readHolderLock = func(context.Context, string, string, string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(context.Context, string, string, string) (hafresh.View, error) {
return hafresh.View{}, context.DeadlineExceeded
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
}
case "awake":
s.a.entries[s.rt.Host] = &actEntry{route: s.rt, state: actAwake, proc: &fakeProc{}, rep: &fakeRep{}}
@@ -235,12 +233,11 @@ func TestPlacementSingleFlight(t *testing.T) {
old := readHolderLock
gate := make(chan struct{})
var reads atomic.Int32
- readHolderLock = func(ctx context.Context, b, p, r string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, b, p, r string) (hafresh.View, error) {
reads.Add(1)
<-gate
return old(ctx, b, p, r)
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
ctx, cancel := context.WithCancel(context.Background())
first := make(chan edge.ForwardDecision, 1)
go func() { first <- s.a.ForwardTarget(ctx, s.rt, nil) }()
@@ -270,11 +267,9 @@ func TestPlacementSingleFlight(t *testing.T) {
func TestPlacementProbeFailureUsesBase(t *testing.T) {
s := haService(t, "shop.example.com")
s.rt.HA = true
- old := readHolderLock
- readHolderLock = func(context.Context, string, string, string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(context.Context, string, string, string) (hafresh.View, error) {
return hafresh.View{}, errors.New("unavailable")
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
if d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) }); d != (edge.ForwardDecision{}) {
t.Fatal(d)
}
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go
index b173501fc..a48a4055d 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -192,7 +192,7 @@ func haService(t *testing.T, host string) *haSvc {
h.mu.Unlock()
}
})
- s.a = newTrackedService(Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
+ s.a = newTrackedService(t, Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
t.Cleanup(s.abandon)
return s
}
@@ -314,7 +314,7 @@ func (s *haSvc) peer(t *testing.T) *haSvc {
t.Cleanup(func() { haFixtures.Delete(b) })
s2 := &haSvc{t: t, b: b, rt: s.rt, fx: s.fx, ctl: s.ctl, unit: s.unit, owedDir: s.owedDir}
s2.wire(b)
- s2.a = newTrackedService(Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
+ s2.a = newTrackedService(t, Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
t.Cleanup(s2.abandon)
return s2
}
@@ -758,9 +758,7 @@ func TestSweepRetriesOwedMarkers(t *testing.T) {
s := haService(t, "shop.example.com")
var calls atomic.Int32
release := make(chan struct{})
- prev := retryPendingMarkers
- retryPendingMarkers = func(context.Context) error { calls.Add(1); <-release; return nil }
- restoreKnob(t, func() { retryPendingMarkers = prev })
+ setKnob(t, &retryPendingMarkers, func(context.Context) error { calls.Add(1); <-release; return nil })
s.a.sweepOnce()
s.a.sweepOnce() // the first is still running: no second pass
waitFor(t, "the retry", func() bool { return calls.Load() == 1 })
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go
index ecd1f244e..135519f0d 100644
--- a/internal/activator/hasecrets_test.go
+++ b/internal/activator/hasecrets_test.go
@@ -296,7 +296,7 @@ func TestLegacyLaunchPublishesNothing(t *testing.T) {
// host's tick is left alone.
func TestFillScheduledToken(t *testing.T) {
b, rt := haLaunchBackend(t, "shop.example.com")
- a := newTrackedService(Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
+ a := newTrackedService(t, Config{Bucket: b.Cfg.Bucket, Idle: time.Hour}, b, b.Registry)
writeEnv(t, b, rt, "CARLOS_ADMIN_TOKEN=restored\n")
r := httptest.NewRequest(http.MethodPost, "http://shop.example.com/tick", nil)
r.Header.Set("Authorization", "Bearer ")
diff --git a/internal/activator/hasuspect_test.go b/internal/activator/hasuspect_test.go
index 7f5eba7d0..1ac413a94 100644
--- a/internal/activator/hasuspect_test.go
+++ b/internal/activator/hasuspect_test.go
@@ -153,12 +153,11 @@ func TestSuspectWindowEndReadsOnce(t *testing.T) {
gate := make(chan struct{})
var reads atomic.Int32
old := readHolderLock
- readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
reads.Add(1)
<-gate
return old(ctx, bucket, prefix, region)
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
got := s.concurrently(20)
waitFor(t, "the read", func() bool { return reads.Load() == 1 })
time.Sleep(50 * time.Millisecond) // the others queue on it
@@ -218,13 +217,11 @@ func TestSuspectRevalidationFailureRenewsTheWindow(t *testing.T) {
s, clk := suspectB(t)
clk.advance(holderSuspectTTL + time.Millisecond)
var reads atomic.Int32
- old := readHolderLock
- readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
reads.Add(1)
<-ctx.Done()
return hafresh.View{}, ctx.Err()
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
got := s.concurrently(5)
for i := range 5 {
if d := recv(t, got); !d.Refuse {
@@ -240,13 +237,11 @@ func TestSuspectRevalidationFailureRenewsTheWindow(t *testing.T) {
clk.advance(holderSuspectTTL + time.Millisecond)
gate := make(chan struct{})
var reads atomic.Int32
- old := readHolderLock
- readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
reads.Add(1)
<-gate
return hafresh.View{}, context.DeadlineExceeded
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
got := s.concurrently(1)
waitFor(t, "the read", func() bool { return reads.Load() == 1 })
s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "c", Status: 503, Holder: "c"})
@@ -266,13 +261,11 @@ func TestSuccessDuringRevalidationWins(t *testing.T) {
t.Helper()
gate := make(chan struct{})
var reads atomic.Int32
- old := readHolderLock
- readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
reads.Add(1)
<-gate
return hafresh.View{}, context.DeadlineExceeded
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
return func() bool { return reads.Load() == 1 }, func() { close(gate) }
}
t.Run("success", func(t *testing.T) {
@@ -611,13 +604,11 @@ func TestSuspectWindowRevalidationTimeout(t *testing.T) {
s := haHeldByB(t)
s.note(s.decide(), edge.ForwardResult{Outcome: edge.ForwardUnreachable})
var reads atomic.Int32
- old := readHolderLock
- readHolderLock = func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, _, _, _ string) (hafresh.View, error) {
reads.Add(1)
<-ctx.Done()
return hafresh.View{}, ctx.Err()
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
first := make(chan edge.ForwardDecision, 1)
@@ -686,7 +677,7 @@ func TestSilentHolderRevalidatesOnce(t *testing.T) {
}
old := readHolderLock
var reads atomic.Int32
- readHolderLock = func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
+ setKnob(t, &readHolderLock, func(ctx context.Context, bucket, prefix, region string) (hafresh.View, error) {
reads.Add(1)
if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > holderReadTimeout {
t.Error("unbounded suspect read")
@@ -706,8 +697,7 @@ func TestSilentHolderRevalidatesOnce(t *testing.T) {
default:
return old(ctx, bucket, prefix, region)
}
- }
- restoreKnob(t, func() { readHolderLock = old })
+ })
out := s.concurrently(50)
free := answer == "absent" || answer == "released"
for range 50 {
diff --git a/internal/activator/hatake_test.go b/internal/activator/hatake_test.go
index 008ebd4b2..181e0df30 100644
--- a/internal/activator/hatake_test.go
+++ b/internal/activator/hatake_test.go
@@ -336,9 +336,7 @@ func TestTakeRefusals(t *testing.T) {
func TestTakeWithinTheWakeBound(t *testing.T) {
s := haService(t, "shop.example.com")
putLockFor(t, s.b, s.rt, takeMarker(t, s.lifetime(), 6))
- old := wakeWaitBound
- wakeWaitBound = 200 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 200*time.Millisecond)
// The take's wake runs on, detached, after the take answers, holding
// the lease it acquired; ended, it gives the lease back (a release
// marker). It must end inside this test. Left running, it wrote that
@@ -480,13 +478,9 @@ func TestTakeBoundOnAFirstWake(t *testing.T) {
e, _ := s.b.Lifetimes.Lookup(s.rt.Host)
lifetime = e.ID
}
- old := wakeWaitBound
- wakeWaitBound = 200 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 200*time.Millisecond)
extendedCh := make(chan struct{}, 4)
- oldHook := wakeBoundExtended
- wakeBoundExtended = func() { extendedCh <- struct{}{} }
- restoreKnob(t, func() { wakeBoundExtended = oldHook })
+ setKnob(t, &wakeBoundExtended, func() { extendedCh <- struct{}{} })
// A first wake under way: never ready until the test ends it.
var e *actEntry
s.a.mu.Lock()
diff --git a/internal/activator/hawake_test.go b/internal/activator/hawake_test.go
index 080eb6a1c..434b658d9 100644
--- a/internal/activator/hawake_test.go
+++ b/internal/activator/hawake_test.go
@@ -140,8 +140,7 @@ func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Rout
}
return RecordFactsOf(rec)
}
- old := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
h.mu.Lock()
h.restores++
h.mu.Unlock()
@@ -149,8 +148,7 @@ func haBackendEmptyIndex(t *testing.T, host string) (*ExecBackend, registry.Rout
return false, err
}
return true, writeMinimalSQLite(dbPath)
- }
- restoreKnob(t, func() { restoreReplica = old })
+ })
haFixtures.Store(b, h)
t.Cleanup(func() { haFixtures.Delete(b) })
return b, rt
@@ -1157,7 +1155,7 @@ func TestWakeReplicatesAtTheRestoredClass(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Minute}, &restoredClassBackend{fakeBackend: fb, class: replicationStream}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Minute}, &restoredClassBackend{fakeBackend: fb, class: replicationStream}, reg)
rt := testRoute("shop.example.com")
rt.Replication = replicationDaily
release, err := a.beginRequest(context.Background(), rt)
diff --git a/internal/activator/heldstream_e2e_test.go b/internal/activator/heldstream_e2e_test.go
index 7cfb9e1fa..ab19c6af5 100644
--- a/internal/activator/heldstream_e2e_test.go
+++ b/internal/activator/heldstream_e2e_test.go
@@ -141,7 +141,7 @@ func newHeldE2E(t *testing.T, o heldE2EOpts) *heldE2E {
t.Fatal(err)
}
be := &heldE2EBackend{fakeSwapBackend: &fakeSwapBackend{fakeBackend: &fakeBackend{}}, exec: exec}
- h.a = newTrackedService(Config{Bucket: "test-bucket", Idle: o.idle}, be, reg)
+ h.a = newTrackedService(t, Config{Bucket: "test-bucket", Idle: o.idle}, be, reg)
h.a.gens = o.gens
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
diff --git a/internal/activator/inputs_test.go b/internal/activator/inputs_test.go
index 90d2e0aa0..b15839cd1 100644
--- a/internal/activator/inputs_test.go
+++ b/internal/activator/inputs_test.go
@@ -239,8 +239,7 @@ func TestCurrentInputsChanges(t *testing.T) {
}
func TestCurrentInputsStatCache(t *testing.T) {
- defer func(d time.Duration) { inputsStampRacy = d }(inputsStampRacy)
- inputsStampRacy = 0 // every stamp old enough to keep
+ setKnob(t, &inputsStampRacy, 0) // every stamp old enough to keep
k := newInputsKit(t)
k.deliver(t, map[string]string{"LOG_LEVEL": "debug"})
writeOwnEnv(t, k.b, k.rt, "OWN=1\n")
@@ -658,8 +657,7 @@ func TestSplitBackendPublishesInputsForExecRowsOnly(t *testing.T) {
// (RetainInputs, from the edge's reload), and its cached reads stay bounded
// by the instances on the box. A host that stays keeps its read.
func TestRetainInputsBoundsChurn(t *testing.T) {
- defer func(d time.Duration) { inputsStampRacy = d }(inputsStampRacy)
- inputsStampRacy = 0 // every stamp old enough to keep
+ setKnob(t, &inputsStampRacy, 0) // every stamp old enough to keep
k := newInputsKit(t)
writeOwnEnv(t, k.b, k.rt, "OWN=1\n")
stay := mustCurrent(t, k.b, k.rt)
diff --git a/internal/activator/instancekey_test.go b/internal/activator/instancekey_test.go
index e3604b86c..48eaee4b0 100644
--- a/internal/activator/instancekey_test.go
+++ b/internal/activator/instancekey_test.go
@@ -835,11 +835,9 @@ func TestHibernationRestoreKeepsTheInstanceKey(t *testing.T) {
if !wellFormedInstanceKey(key) {
t.Fatal("the first start minted no key")
}
- old := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, bucket, prefix, region string) (bool, error) {
return true, writeMinimalSQLite(dbPath)
- }
- restoreKnob(t, func() { restoreReplica = old })
+ })
_ = os.Remove(filepath.Join(b.DataDir, host+".db")) // hibernated: the database is gone
rt := registry.Route{Host: host, Kind: "instance", Socket: tmpSock(t)}
if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh {
diff --git a/internal/activator/knobrestore_test.go b/internal/activator/knobrestore_test.go
index 18d408d21..9eacfff81 100644
--- a/internal/activator/knobrestore_test.go
+++ b/internal/activator/knobrestore_test.go
@@ -1,6 +1,7 @@
package activator
import (
+ "fmt"
"runtime"
"slices"
"strings"
@@ -18,51 +19,101 @@ const knobJoinBound = 10 * time.Second
// knobRestores holds each running test's restores until the test ends.
var knobRestores = struct {
sync.Mutex
- byTest map[*testing.T][]func()
+ // byTest holds a test's restores, by test name, from its first setKnob.
+ byTest map[string][]func()
// abandoned names goroutines a test already reported as never ending,
// so that one leak fails one test and not every test after it.
abandoned map[string]bool
- // services are the Services built since the last top-level test ended.
- services []*Service
- // firstOwned is, for a subtest, where in services its own Services begin.
- // Those before it are its parent's, still in use.
- firstOwned map[*testing.T]int
-}{byTest: map[*testing.T][]func(){}, abandoned: map[string]bool{}, firstOwned: map[*testing.T]int{}}
-
-// newTrackedService is New for tests: the join at a test's end synchronises
-// with every Service built this way (syncWithServices).
-func newTrackedService(cfg Config, backend Backend, due DueStore) *Service {
+ // services are the Services built since a test last restored a setting.
+ services []*trackedService
+}{byTest: map[string][]func(){}, abandoned: map[string]bool{}}
+
+// trackedService is a Service built by newTrackedService.
+type trackedService struct {
+ a *Service
+ // builtBy is the name of the test that built it.
+ builtBy string
+ // afterKnob is whether builtBy had already changed a setting.
+ afterKnob bool
+ // ended is set as builtBy ends. Under knobRestores.
+ ended bool
+ // stopWatches closes a.leaseWatchStop once.
+ stopWatches sync.Once
+}
+
+// newTrackedService is New for tests. setKnob refuses a subtest while a
+// Service it does not own runs, and the join at a test's end ends every
+// tracked Service's lease watches and synchronises with it.
+func newTrackedService(t testing.TB, cfg Config, backend Backend, due DueStore) *Service {
+ t.Helper()
a := New(cfg, backend, due)
+ a.leaseWatchStop = make(chan struct{})
knobRestores.Lock()
defer knobRestores.Unlock()
- knobRestores.services = append(knobRestores.services, a)
+ s := &trackedService{a: a, builtBy: t.Name(), afterKnob: knobRestores.byTest[t.Name()] != nil}
+ knobRestores.services = append(knobRestores.services, s)
+ t.Cleanup(func() {
+ knobRestores.Lock()
+ s.ended = true
+ knobRestores.Unlock()
+ })
return a
}
-// restoreKnob puts a package-level setting back when t ends, once the
-// production goroutines t started have finished. A wake outlives the request
-// that began it, so restoring a timing knob in a plain t.Cleanup writes the
-// variable while that wake may still read it: a data race under -race, though
-// production never changes these knobs (#1249).
+// setKnob sets the package-level setting *p to v for the rest of t, and puts
+// it back when t ends, once the production goroutines t started have
+// finished. A wake outlives the request that began it, so restoring a timing
+// setting in a plain t.Cleanup writes it while that wake may still read it: a
+// data race under -race, though production never changes these settings
+// (#1249).
+//
+// The rule: a subtest changes a setting only while no Service it does not own
+// is running. It owns the Services it built after its first setKnob. Its
+// parent's Services, and any it built before, may still be running when it
+// restores the setting, and nothing its end joins would stop them reading
+// the setting then. setKnob checks the rule before it writes and fails the
+// test if it is broken: change the setting in the parent instead, before the
+// parent builds anything.
//
// Every restore of a test runs together, last first, at the point of the
-// test's first restoreKnob. Cleanups registered after that point run before
-// the join, so a rig's cleanup can release a wake the join then waits for.
-// Shrink a knob before building the rig whose cleanup ends the wake.
-func restoreKnob(t *testing.T, restore func()) {
+// test's first setKnob. Cleanups registered after that point run before the
+// join, so a rig's cleanup can release a wake the join then waits for. Set a
+// setting before building the rig whose cleanup ends the wake.
+func setKnob[T any](t testing.TB, p *T, v T) {
t.Helper()
knobRestores.Lock()
- defer knobRestores.Unlock()
- if _, ok := knobRestores.byTest[t]; !ok {
- if strings.Contains(t.Name(), "/") {
- knobRestores.firstOwned[t] = len(knobRestores.services)
- }
+ if s := unownedServiceLocked(t); s != nil {
+ knobRestores.Unlock()
+ t.Fatalf("setKnob: a subtest may not change a package setting while a Service it does not own is running "+
+ "(one built by %s before this subtest's first setKnob): that Service could read the setting as it is "+
+ "written or restored (#1249). Change the setting in the parent test, before it builds anything.", s.builtBy)
+ }
+ name := t.Name()
+ if _, ok := knobRestores.byTest[name]; !ok {
t.Cleanup(func() { runKnobRestores(t) })
}
- knobRestores.byTest[t] = append(knobRestores.byTest[t], restore)
+ old := *p
+ knobRestores.byTest[name] = append(knobRestores.byTest[name], func() { *p = old })
+ knobRestores.Unlock()
+ *p = v
}
-func runKnobRestores(t *testing.T) {
+// unownedServiceLocked returns a running Service that subtest t does not own,
+// or nil. A top-level test is not checked: its restores join every tracked
+// Service. The caller holds knobRestores.
+func unownedServiceLocked(t testing.TB) *trackedService {
+ if !strings.Contains(t.Name(), "/") {
+ return nil
+ }
+ for _, s := range knobRestores.services {
+ if !s.ended && (s.builtBy != t.Name() || !s.afterKnob) {
+ return s
+ }
+ }
+ return nil
+}
+
+func runKnobRestores(t testing.TB) {
t.Helper()
joinProductionGoroutines(t)
endLeaseWatches(t)
@@ -70,9 +121,9 @@ func runKnobRestores(t *testing.T) {
joinProductionGoroutines(t)
syncWithServices(t)
knobRestores.Lock()
- restores := knobRestores.byTest[t]
- delete(knobRestores.byTest, t)
- delete(knobRestores.firstOwned, t)
+ restores := knobRestores.byTest[t.Name()]
+ delete(knobRestores.byTest, t.Name())
+ knobRestores.services = slices.DeleteFunc(knobRestores.services, func(s *trackedService) bool { return s.ended })
knobRestores.Unlock()
for i := len(restores) - 1; i >= 0; i-- {
restores[i]()
@@ -84,7 +135,7 @@ func runKnobRestores(t *testing.T) {
// because production has no signal for "every goroutine has ended", and the
// goroutines that matter are not all counted in Service.background: the
// first-wake watch (watchFirstWake) is one that is not.
-func joinProductionGoroutines(t *testing.T) {
+func joinProductionGoroutines(t testing.TB) {
t.Helper()
live := productionGoroutines()
if len(live) == 0 {
@@ -110,12 +161,13 @@ func joinProductionGoroutines(t *testing.T) {
}
}
-// ownedServices returns the Services t may end: every one for a top-level
-// test, and for a subtest those built since its first restoreKnob.
-func ownedServices(t *testing.T) []*Service {
+// trackedServices returns the Services built since a test last restored a
+// setting. Under setKnob's rule, any of them still running as a test
+// restores is that test's own.
+func trackedServices() []*trackedService {
knobRestores.Lock()
defer knobRestores.Unlock()
- return slices.Clone(knobRestores.services[knobRestores.firstOwned[t]:])
+ return slices.Clone(knobRestores.services)
}
// lockService takes a.mu, giving up when deadline fires.
@@ -132,28 +184,21 @@ func lockService(a *Service, deadline <-chan time.Time) bool {
return true
}
-// endLeaseWatches ends the lease watches of t's Services and waits for them.
-// A parked watch reads no setting, but a lease that runs out later would wake
-// it, and the loss it then handles does. Waiting on Service.leaseWork also
+// endLeaseWatches ends the lease watches of the tracked Services and waits
+// for them. A parked watch reads no setting, but a lease that runs out later
+// would wake it, and the loss it then handles does. It closes each Service's
+// leaseWatchStop, which every watch of that Service selects on, so it reaches
+// a watch whose entry has left a.entries without closing ownerDone (a test's
+// cleanup that drops the entry does that). Waiting on Service.leaseWork also
// orders the reads of the kills a loss started before the restores.
-func endLeaseWatches(t *testing.T) {
+func endLeaseWatches(t testing.TB) {
t.Helper()
deadline := time.After(knobJoinBound)
- for _, a := range ownedServices(t) {
- if !lockService(a, deadline) {
- t.Errorf("a Service's lock was still held %s after the test ended", knobJoinBound)
- return
- }
- for _, e := range a.entries {
- if e.ownerDone != nil {
- close(e.ownerDone)
- e.ownerDone = nil
- }
- }
- a.mu.Unlock()
+ for _, s := range trackedServices() {
+ s.stopWatches.Do(func() { close(s.a.leaseWatchStop) })
ended := make(chan struct{})
go func() {
- a.leaseWork.Wait()
+ s.a.leaseWork.Wait()
close(ended)
}()
select {
@@ -172,22 +217,16 @@ func endLeaseWatches(t *testing.T) {
// last act is its Service.background decrement, and the other goroutines
// finish their knob reads before a last critical section under a.mu, so
// loading the one and taking the other is that synchronisation.
-func syncWithServices(t *testing.T) {
+func syncWithServices(t testing.TB) {
t.Helper()
- knobRestores.Lock()
- services := slices.Clone(knobRestores.services)
- if !strings.Contains(t.Name(), "/") {
- knobRestores.services = nil
- }
- knobRestores.Unlock()
deadline := time.After(knobJoinBound)
- for _, a := range services {
- a.background.Load()
- if !lockService(a, deadline) {
+ for _, s := range trackedServices() {
+ s.a.background.Load()
+ if !lockService(s.a, deadline) {
t.Errorf("a Service's lock was still held %s after the test ended", knobJoinBound)
return
}
- a.mu.Unlock()
+ s.a.mu.Unlock()
}
}
@@ -346,6 +385,34 @@ func TestEndLeaseWatchesEndsAParkedWatch(t *testing.T) {
kb.lastProc().exit()
endLeaseWatches(t)
+ requireNoLeaseWatch(t)
+}
+
+// endLeaseWatches ends a watch whose entry left a.entries without closing
+// ownerDone, as TestSwapReleaseRefusedByRootAbandons's cleanup drops its
+// hand-installed entry. Reaching watches only through a.entries left that
+// one running, and the test's end waited for it until its bound.
+func TestEndLeaseWatchesEndsAWatchWhoseEntryWasDropped(t *testing.T) {
+ host := "shop.example.com"
+ a, kb, _, _ := residentKillService(t, residentRoute(host))
+ kb.mu.Lock()
+ kb.repWrap = func(r *fakeRep) Rep { return newOwnedRep(r, time.Now().Add(time.Hour)) }
+ kb.mu.Unlock()
+ startResident(t, a, host)
+ waitFor(t, "the watch to park", func() bool { return !leaseWatchIsLive() })
+ kb.lastProc().exit()
+ a.mu.Lock()
+ delete(a.entries, host)
+ a.mu.Unlock()
+
+ endLeaseWatches(t)
+ requireNoLeaseWatch(t)
+}
+
+// requireNoLeaseWatch fails t if endLeaseWatches failed or a lease watch is
+// still running.
+func requireNoLeaseWatch(t *testing.T) {
+ t.Helper()
if t.Failed() {
t.Fatal("the lease watch did not end")
}
@@ -354,3 +421,67 @@ func TestEndLeaseWatchesEndsAParkedWatch(t *testing.T) {
t.Fatalf("a lease watch is still running:\n%s", s)
}
}
+
+// knobProbe is a setting for TestSetKnobRefusesASubtestWhileAServiceItDoesNotOwnRuns.
+// No production code reads it.
+var knobProbe int
+
+// refusingTB is a test's testing.TB whose Fatalf records the message and
+// ends only the goroutine it runs on, so a refusal does not fail the test.
+type refusingTB struct {
+ testing.TB
+ refusal string
+}
+
+func (r *refusingTB) Fatalf(format string, args ...any) {
+ r.refusal = fmt.Sprintf(format, args...)
+ runtime.Goexit()
+}
+
+// trySetKnob calls setKnob(t, &knobProbe, v) on a goroutine of its own and
+// returns the refusal, or "" if setKnob made the change.
+func trySetKnob(t testing.TB, v int) string {
+ r := &refusingTB{TB: t}
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ setKnob(r, &knobProbe, v)
+ }()
+ <-done
+ return r.refusal
+}
+
+// setKnob refuses a subtest while a Service it does not own is running: its
+// parent's, or one the subtest built before its first setKnob. It refuses
+// before it writes. A Service the subtest built after its first setKnob is
+// its own and does not stop a later one.
+func TestSetKnobRefusesASubtestWhileAServiceItDoesNotOwnRuns(t *testing.T) {
+ refused := func(t *testing.T, refusal, builtBy string) {
+ t.Helper()
+ if !strings.Contains(refusal, "a subtest may not change a package setting while a Service it does not own is running") ||
+ !strings.Contains(refusal, "built by "+builtBy+" before") {
+ t.Fatalf("setKnob's refusal = %q, want the rule, naming %s", refusal, builtBy)
+ }
+ if knobProbe != 0 {
+ t.Fatalf("knobProbe = %d after a refusal: setKnob wrote before it checked", knobProbe)
+ }
+ }
+ t.Run("its own Service, built after its first setKnob", func(t *testing.T) {
+ setKnob(t, &knobProbe, 1)
+ newTrackedService(t, Config{}, &fakeBackend{}, nil)
+ if r := trySetKnob(t, 2); r != "" || knobProbe != 2 {
+ t.Fatalf("setKnob after the subtest's own Service: refusal %q, knobProbe %d; want none and 2", r, knobProbe)
+ }
+ })
+ if knobProbe != 0 {
+ t.Fatalf("knobProbe = %d after the subtest ended, want it restored to 0", knobProbe)
+ }
+ t.Run("a Service it built first", func(t *testing.T) {
+ newTrackedService(t, Config{}, &fakeBackend{}, nil)
+ refused(t, trySetKnob(t, 3), t.Name())
+ })
+ newTrackedService(t, Config{}, &fakeBackend{}, nil)
+ t.Run("its parent's Service", func(t *testing.T) {
+ refused(t, trySetKnob(t, 4), "TestSetKnobRefusesASubtestWhileAServiceItDoesNotOwnRuns")
+ })
+}
diff --git a/internal/activator/maintenance_test.go b/internal/activator/maintenance_test.go
index 96d191565..461755b6e 100644
--- a/internal/activator/maintenance_test.go
+++ b/internal/activator/maintenance_test.go
@@ -171,7 +171,7 @@ func TestMaintenanceFenceBlocksEveryAdmissionIncludingStaleRoute(t *testing.T) {
t.Fatal("older generation accepted")
}
// A new process has no closure evidence from the old activator's lifetime.
- fresh := newTrackedService(a.cfg, a.backend, reg)
+ fresh := newTrackedService(t, a.cfg, a.backend, reg)
if proof, err := fresh.FenceAndStop(maintenanceContext(t, time.Second), host, 3); err != ErrStopUnproven || proof != nil {
t.Fatal("restart invented old evidence")
}
diff --git a/internal/activator/opset_test.go b/internal/activator/opset_test.go
index b687ca043..0c50add19 100644
--- a/internal/activator/opset_test.go
+++ b/internal/activator/opset_test.go
@@ -166,9 +166,7 @@ func TestSwapWitnessBarrierJoinsBeforeTheLease(t *testing.T) {
// finishes the member once it exits, and then the stop completes.
func TestBarrierKeepsTheLeaseWhileAGenerationIsUnproven(t *testing.T) {
x := awakeForBarrier(t, true)
- old := opJoinBound
- opJoinBound = 100 * time.Millisecond
- restoreKnob(t, func() { opJoinBound = old })
+ setKnob(t, &opJoinBound, 100*time.Millisecond)
member := &fakeProc{label: "gen:9", rec: x.b, stuck: true}
plantMember(t, x.a, x.host, roleRetiring, member, 9)
waitFor(t, "the member marked unproven", func() bool {
@@ -244,9 +242,7 @@ func (k *killGenBackend) killed() []uint64 {
// releases the lease over the surviving descendant.
func TestSwapWitnessMemberStopProvesTheGenerationChildEmpty(t *testing.T) {
x := awakeForBarrier(t, true)
- old := opJoinBound
- opJoinBound = 100 * time.Millisecond
- restoreKnob(t, func() { opJoinBound = old })
+ setKnob(t, &opJoinBound, 100*time.Millisecond)
kb := &killGenBackend{fakeBackend: x.b, err: errors.New("g9 still holds a process")}
x.a.backend = kb
member := &fakeProc{label: "gen:9", rec: x.b} // its leader exits on SIGTERM
@@ -686,9 +682,7 @@ func (g *execGenBackend) firstGen() uint64 {
// errNoGenContainment as ExecBackend's does with containment off; this
// backend has no host kill, so the lease goes back.
func TestAPlacedSpawnWithAFailedHealthWaitProvesItsChild(t *testing.T) {
- old := spawnHealthTimeout
- spawnHealthTimeout = 300 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 300*time.Millisecond)
rows := []struct {
name string
containment bool
@@ -1340,9 +1334,7 @@ var (
// the lease back.
func TestARealFlatHealthFailedWakeProvesItsHostCgroup(t *testing.T) {
requireUnixSockets(t)
- old := spawnHealthTimeout
- spawnHealthTimeout = 500 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 500*time.Millisecond)
a, b, _, _ := testActivator(t, time.Hour)
a.gens = false
exec := testExecBackend(t)
diff --git a/internal/activator/outcome_fence_test.go b/internal/activator/outcome_fence_test.go
index c48ead63a..1c4a57441 100644
--- a/internal/activator/outcome_fence_test.go
+++ b/internal/activator/outcome_fence_test.go
@@ -130,9 +130,7 @@ func TestANewWakeWaitsForAFailedFirstWakesOutcome(t *testing.T) {
// Before the fix the wake planned after the bound and could boot B again
// without its record.
func TestTheOutcomeFenceFailsClosed(t *testing.T) {
- old := outcomeFenceWait
- outcomeFenceWait = 200 * time.Millisecond
- restoreKnob(t, func() { outcomeFenceWait = old })
+ setKnob(t, &outcomeFenceWait, 200*time.Millisecond)
dir := t.TempDir()
next := stagedID(t, dir, "v2")
a, b, _ := planActivator(t, WakePlan{})
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go
index 728735058..1335f2922 100644
--- a/internal/activator/pendingwake_linux_test.go
+++ b/internal/activator/pendingwake_linux_test.go
@@ -204,7 +204,7 @@ func fleetBox(t *testing.T, name string, lock *sharedLock, bucket *fleetBucket,
}
box := &leasedBox{ruleBackend: &ruleBackend{fakeBackend: &fakeBackend{}, eb: eb, t: t},
t: t, name: name, lock: lock, bucket: bucket, dbPath: rt.DBPath}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, box, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, box, reg)
a.Routes = reg
return a, box, reg
}
@@ -979,7 +979,7 @@ func TestFenceHoldsAfterAgentRestartBeforeReconcile(t *testing.T) {
r.bucket.upload(t, newer)
moveRecord(t, store, "", "pi-2", assignB)
- restarted := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, r.box, r.reg)
+ restarted := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, r.box, r.reg)
restarted.Routes = r.reg
asFleetBox(restarted, "pi-1", store)
t.Cleanup(func() { restarted.Shutdown(context.Background()) })
@@ -1443,7 +1443,7 @@ func newCheckpointRig(t *testing.T, region string) *checkpointRig {
t.Fatal(err)
}
r := &checkpointRig{fx: fx, b: b, rt: rt, prefix: b.Cfg.hibernatePrefix(rt.Host), log: captureLog(t), kept: make(chan string, 8)}
- r.a = newTrackedService(Config{Bucket: fx.Bucket, Idle: time.Hour}, b, reg)
+ r.a = newTrackedService(t, Config{Bucket: fx.Bucket, Idle: time.Hour}, b, reg)
r.a.checkpointKept = func(host string) { r.kept <- host }
// Whatever a test leaves running stops before the fixture closes,
// unless the test shut the agent down itself.
diff --git a/internal/activator/probewake_test.go b/internal/activator/probewake_test.go
index 1706f35d1..10c04060f 100644
--- a/internal/activator/probewake_test.go
+++ b/internal/activator/probewake_test.go
@@ -113,7 +113,7 @@ func pwFlip() hostclaim.Observed {
func pwService(t *testing.T, r *pwRuntime) (*Service, *pwRoutes) {
t.Helper()
routes := &pwRoutes{rt: registry.Route{Host: pwHost, Kind: "instance", Status: "landing", HoldOp: pwOp, Socket: "/run/x.sock", DBPath: "/data/x.db"}}
- a := newTrackedService(Config{HostWrites: hostwrite.Config{Enabled: true}, Claims: r.runtime(t)}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{HostWrites: hostwrite.Config{Enabled: true}, Claims: r.runtime(t)}, &fakeBackend{}, nil)
a.Routes = routes
return a, routes
}
@@ -354,12 +354,11 @@ func TestRetireExceptKeepsAProbeInsertedBetweenTheLocks(t *testing.T) {
inserted := &actEntry{host: "two.example.com", route: held, state: actAwake, ready: make(chan struct{}), proc: &fakeProc{}, rep: &fakeRep{},
probe: &probeEntry{policy: startPolicy{Probe: true}, op: pwOp, holdOp: pwOp}}
close(inserted.ready)
- retireBetweenLocks = func() {
+ setKnob(t, &retireBetweenLocks, func() {
a.mu.Lock()
a.entries[inserted.host] = inserted
a.mu.Unlock()
- }
- restoreKnob(t, func() { retireBetweenLocks = nil })
+ })
a.RetireExcept(map[string]bool{})
retireBetweenLocks = nil
a.mu.Lock()
@@ -389,8 +388,7 @@ func TestProbeWakeCancelBeforeTheWakeStarts(t *testing.T) {
return prereq(ctx, route, o, p)
}
ctx, cancel := context.WithCancel(t.Context())
- probeWakePublished = cancel
- restoreKnob(t, func() { probeWakePublished = nil })
+ setKnob(t, &probeWakePublished, (func())(cancel))
_, err := a.ProbeWake(ctx, pwConfig())
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v", err)
@@ -548,15 +546,14 @@ func TestRetireExceptRevalidatesTheOpenUnderTheFinalLock(t *testing.T) {
t.Fatal(err)
}
e := pwHeldEntry(t, a)
- retireBeforeRegistryRead = func() {
+ setKnob(t, &retireBeforeRegistryRead, func() {
if !a.OpenProbeEntry("one.example.com", pwOp) {
t.Error("not marked")
}
if ok, err := reg.ReleaseHold("one.example.com", pwOp); err != nil || !ok {
t.Errorf("release: %v %v", ok, err)
}
- }
- restoreKnob(t, func() { retireBeforeRegistryRead = nil })
+ })
a.RetireExcept(map[string]bool{})
retireBeforeRegistryRead = nil
a.mu.Lock()
@@ -582,7 +579,7 @@ func TestRetireExceptOverlappingReloadsAcrossTheOpen(t *testing.T) {
t.Fatal(err)
}
e := pwHeldEntry(t, a)
- retireBeforeRegistryRead = func() {
+ setKnob(t, &retireBeforeRegistryRead, func() {
retireBeforeRegistryRead = nil // the newer pass runs without the pause
if !a.OpenProbeEntry("one.example.com", pwOp) {
t.Error("not marked")
@@ -592,8 +589,7 @@ func TestRetireExceptOverlappingReloadsAcrossTheOpen(t *testing.T) {
}
a.ConfirmProbeOpened("one.example.com", pwOp)
a.RetireExcept(map[string]bool{"one.example.com": true})
- }
- restoreKnob(t, func() { retireBeforeRegistryRead = nil })
+ })
a.RetireExcept(map[string]bool{})
a.mu.Lock()
state := e.state
diff --git a/internal/activator/production_backend_test.go b/internal/activator/production_backend_test.go
index e0e4e28a8..1bc5878cd 100644
--- a/internal/activator/production_backend_test.go
+++ b/internal/activator/production_backend_test.go
@@ -158,7 +158,7 @@ func TestRootfsGatesThroughTheProductionBackend(t *testing.T) {
eb, ctl := newRootfsBackend(t)
eb.RootfsOK = func(context.Context) error { return errors.New("root-image fail") }
cb := &countingSplit{SplitBackend: productionBackend(t, eb)}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, cb, nil)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, cb, nil)
a.gens = true
armRootfsForTest(a)
t.Cleanup(func() { a.Shutdown(context.Background()) })
diff --git a/internal/activator/pty_linux_test.go b/internal/activator/pty_linux_test.go
index 4b6b428e6..02d005a48 100644
--- a/internal/activator/pty_linux_test.go
+++ b/internal/activator/pty_linux_test.go
@@ -605,9 +605,7 @@ func TestTTYUnitPollsAndStopsItsOwnRole(t *testing.T) {
}
func TestTTYUnitStopAndSettleClosesTheMaster(t *testing.T) {
- old := roleEmptyBound
- roleEmptyBound = 100 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 100*time.Millisecond)
b, rt, _, unit, u := startBinaryTTY(t)
term := u.Terminal()
sock := b.logSocketNamed(rt.Host, TTYSocketName)
diff --git a/internal/activator/replica_drill1_test.go b/internal/activator/replica_drill1_test.go
index b24871682..6464451ce 100644
--- a/internal/activator/replica_drill1_test.go
+++ b/internal/activator/replica_drill1_test.go
@@ -30,9 +30,7 @@ import (
// proved on the running generation without starting anything, and
// nothing stopped.
func TestReplicaCopyKeepsServingWhenCopiesRaised(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
r := newWakeRelRig(t)
store := wireStatelessRig(r)
r.rt.Region, r.rt.Hibernate, r.rt.Stateless = "fleet/pi", false, true
@@ -601,9 +599,7 @@ func TestReplicaKeptFenceHeldUntilAck(t *testing.T) {
// the configuration's reason (SR-4-C92); the ACK halts the join and
// the box is not in Completed.
func TestJoinConfigWaitKeepsStepOpen(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
join := func(inc string) *replicas.Deploy {
return &replicas.Deploy{ID: "deploy-v2", Incarnation: inc, Target: replicaTarget, BaselineSet: true, LastGood: replicaTarget, Phase: "released", Term: "term", Revision: 5,
Swap: replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5}}
diff --git a/internal/activator/replica_install_wait_test.go b/internal/activator/replica_install_wait_test.go
index 78030c71d..edfc05b9d 100644
--- a/internal/activator/replica_install_wait_test.go
+++ b/internal/activator/replica_install_wait_test.go
@@ -47,9 +47,7 @@ func newInstallRig(t *testing.T) *installRig {
// newInstallRigIn is newInstallRig with the record's deploy in state.
func newInstallRigIn(t *testing.T, state func(string) *replicas.Deploy) *installRig {
t.Helper()
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
r := newReplicaSetRig(t, "b", state)
r.rt.Hibernate = false
r.routes.set(r.rt)
diff --git a/internal/activator/replicadeploy_test.go b/internal/activator/replicadeploy_test.go
index 9c95355f5..a56fed35e 100644
--- a/internal/activator/replicadeploy_test.go
+++ b/internal/activator/replicadeploy_test.go
@@ -313,9 +313,7 @@ func TestReplicaReturnsAfterDeploy(t *testing.T) {
// that is closed, a hold, or a box without the permit swaps nothing. An
// admission ticket left open across the swap does not hold it up (R8).
func TestReplicaSwapAcksOnlyAfterProof(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
permitted := replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5})
ctx := context.Background()
@@ -463,9 +461,7 @@ func TestReplicaReturnsAfterDeployWithStaleInstall(t *testing.T) {
// unproven stop: no answer until its stop is proven, then kept, never a
// second swap. A permit whose pointer moved on still switches.
func TestReplicaSwapProofOnlySteps(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
ctx := context.Background()
permit := replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5}
halted := permit
@@ -551,9 +547,7 @@ func TestReplicaSwapProofOnlySteps(t *testing.T) {
// resolves and the deploy halts instead of staying open. Nothing restarts
// a worker to try for a clean proof.
func TestReplicaSwapWaitsForWorkers(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
ctx := context.Background()
// A worker that never starts is judged against its start bound
// (TestReplicaSwapWorkerProofTiming, fix round 3).
@@ -621,9 +615,7 @@ func TestReplicaWakeAndAdoptLaggingPointer(t *testing.T) {
// to it finishes (its drain), while successor requests keep arriving, are
// served and are never awaited; the answer follows the stop proof.
func TestReplicaSwapRetiresAfterRoutedRequests(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
r := newReplicaSetRig(t, "b", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5}))
r.awake(t)
old, _ := r.a.Current(r.rt.Host)
@@ -680,9 +672,7 @@ func TestReplicaSwapRetiresAfterRoutedRequests(t *testing.T) {
// that never started is answered "workers failed" only after residentPoll
// + workerStartBound from its registration, which bounds the wait.
func TestReplicaSwapWorkerProofTiming(t *testing.T) {
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
ctx := context.Background()
setup := func(t *testing.T) (*replicaSetRig, *fakeWorkerBackend) {
r := newReplicaSetRig(t, "b", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5}))
diff --git a/internal/activator/replicaswitchfail_test.go b/internal/activator/replicaswitchfail_test.go
index cef477a76..ab1376b20 100644
--- a/internal/activator/replicaswitchfail_test.go
+++ b/internal/activator/replicaswitchfail_test.go
@@ -16,9 +16,7 @@ import (
// switch proof is still open (the worker wait).
func switchedRig(t *testing.T) (*replicaSetRig, func() SwapResult) {
t.Helper()
- prev := swapSettle
- swapSettle = 20 * time.Millisecond
- restoreKnob(t, func() { swapSettle = prev })
+ setKnob(t, &swapSettle, 20*time.Millisecond)
r := newReplicaSetRig(t, "b", replicaAttempt("released", replicas.Swap{Order: []string{"a", "b"}, Completed: []string{"a"}, ActiveBox: "b", Permit: 5}))
// Copies need an always-on release (appcopies.go): a resident row.
r.rt.Hibernate, r.rt.Kind = false, "instance"
diff --git a/internal/activator/retire_refuse_e2e_test.go b/internal/activator/retire_refuse_e2e_test.go
index ba0f41930..2e1c17888 100644
--- a/internal/activator/retire_refuse_e2e_test.go
+++ b/internal/activator/retire_refuse_e2e_test.go
@@ -182,7 +182,7 @@ func TestRetiringCopyRefusedInBegin(t *testing.T) {
t.Fatal(err)
}
b := &fakeBackend{}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg1)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg1)
routes := &gatedRoutes{reg: reg1, release: make(chan struct{})}
a.Routes = routes
t.Cleanup(func() {
diff --git a/internal/activator/rootfs_admission_test.go b/internal/activator/rootfs_admission_test.go
index cd48effc9..692e62da9 100644
--- a/internal/activator/rootfs_admission_test.go
+++ b/internal/activator/rootfs_admission_test.go
@@ -76,7 +76,7 @@ func harnessService(t *testing.T, h *rootfsCtlHarness) (*Service, *harnessBacken
}
t.Cleanup(func() { reg.Close() })
hb := &harnessBackend{SplitBackend: productionBackend(t, h.eb)}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: 400 * time.Millisecond}, hb, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: 400 * time.Millisecond}, hb, reg)
clk := &fakeClock{t: time.Unix(1_700_000_000, 0)}
a.now = clk.now
a.gens = true
diff --git a/internal/activator/rootfs_cmd_lease_test.go b/internal/activator/rootfs_cmd_lease_test.go
index 667f6c827..1af84ee68 100644
--- a/internal/activator/rootfs_cmd_lease_test.go
+++ b/internal/activator/rootfs_cmd_lease_test.go
@@ -189,7 +189,7 @@ func runLeaseService(t *testing.T, routes ...registry.Route) (*Service, *runLeas
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.now = clk.now
a.gens = true
armRootfsForTest(a)
@@ -858,9 +858,8 @@ func (c *hangingRootfsCtl) askedCount() int {
// backend returns, so the entry's count drops back, without any timer
// clearing it.
func TestALeaseKillIsBoundedByKillOneShotsBudgets(t *testing.T) {
- oldC, oldE := oneShotKillControlBound, roleEmptyBound
- oneShotKillControlBound, roleEmptyBound = 200*time.Millisecond, 200*time.Millisecond
- restoreKnob(t, func() { oneShotKillControlBound, roleEmptyBound = oldC, oldE })
+ setKnob(t, &oneShotKillControlBound, 200*time.Millisecond)
+ setKnob(t, &roleEmptyBound, 200*time.Millisecond)
const slack = 2 * time.Second
t.Run("the control service hangs", func(t *testing.T) {
diff --git a/internal/activator/rootfs_cmd_test.go b/internal/activator/rootfs_cmd_test.go
index 0dc1b8551..027467d08 100644
--- a/internal/activator/rootfs_cmd_test.go
+++ b/internal/activator/rootfs_cmd_test.go
@@ -365,7 +365,7 @@ func awakeHarnessRow(t *testing.T, h *rootfsCtlHarness) (*Service, *runHarnessBa
}
t.Cleanup(func() { reg.Close() })
hb := &runHarnessBackend{harnessBackend: &harnessBackend{SplitBackend: productionBackend(t, h.eb)}, rep: &heldRep{}}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, hb, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, hb, reg)
clk := &fakeClock{t: time.Unix(1_700_000_000, 0)}
a.now = clk.now
a.gens = true
@@ -397,9 +397,7 @@ func TestRootfsRunPollsAndStopsTheRootfsUnit(t *testing.T) {
if !harnessStartsImages() {
t.Skipf("the harness's root starts a rootfs image only on linux-arm64, and this box is %s", release.BoxPlatform())
}
- old := roleEmptyBound
- roleEmptyBound = 300 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 300*time.Millisecond)
h := newRootfsCtlHarness(t)
h.runProbes()
h.eb.ObservePoll = 20 * time.Millisecond
diff --git a/internal/activator/rootfs_gate_test.go b/internal/activator/rootfs_gate_test.go
index 5a1c2cf8a..6df1eee01 100644
--- a/internal/activator/rootfs_gate_test.go
+++ b/internal/activator/rootfs_gate_test.go
@@ -687,9 +687,9 @@ func TestFirstWakeBudgetIsTheRowsBound(t *testing.T) {
// answered.
func TestRootfsPlannedFirstWakeGetsTheRootfsBudget(t *testing.T) {
shrinkHealthBounds(t, 300*time.Millisecond, 2*time.Second, 100*time.Millisecond)
- ob, or, ow := firstWakeBudget, firstWakeKillReserve, wakeWaitBound
- firstWakeBudget, firstWakeKillReserve, wakeWaitBound = 600*time.Millisecond, 300*time.Millisecond, 100*time.Millisecond
- restoreKnob(t, func() { firstWakeBudget, firstWakeKillReserve, wakeWaitBound = ob, or, ow })
+ setKnob(t, &firstWakeBudget, 600*time.Millisecond)
+ setKnob(t, &firstWakeKillReserve, 300*time.Millisecond)
+ setKnob(t, &wakeWaitBound, 100*time.Millisecond)
lb, ctl := newRootfsLaunch(t, &fakeSwapBackend{fakeBackend: &fakeBackend{}})
next, good := stagedRootfsIdentity(t, lb.eb, "v2"), stagedRootfsIdentity(t, lb.eb, "v3")
ctl.setServe(serveVersions(t, lb.eb, lb.rt, 900*time.Millisecond, "v2", "v3"))
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go
index 084fcf4c6..57c4e6d39 100644
--- a/internal/activator/rootfs_invariants_test.go
+++ b/internal/activator/rootfs_invariants_test.go
@@ -650,9 +650,7 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){
r.noBinaryVerb(t)
},
"rootfs cmdUnit": func(t *testing.T, r *rootfsProofRig) {
- old := roleEmptyBound
- roleEmptyBound = 100 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 100*time.Millisecond)
r.ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdRunning}
r.ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdGone} // the binary unit's answer
u := &cmdUnit{b: r.b, rt: r.rt, role: instancectl.RoleCmd, inv: "inv-r", io: oneShotIO{out: emptyCmdStream(t), errs: emptyCmdStream(t)}}
@@ -677,9 +675,8 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){
// start, poll and stop name it, and its settle stays unproven while
// that unit's group is populated, whatever the binary unit answers.
"release cmdUnit (StartRelease)": func(t *testing.T, r *rootfsProofRig) {
- oldEmpty, oldGrace := roleEmptyBound, cmdAcceptGrace
- roleEmptyBound, cmdAcceptGrace = 100*time.Millisecond, 20*time.Millisecond
- restoreKnob(t, func() { roleEmptyBound, cmdAcceptGrace = oldEmpty, oldGrace })
+ setKnob(t, &roleEmptyBound, 100*time.Millisecond)
+ setKnob(t, &cmdAcceptGrace, 20*time.Millisecond)
id := stagedRootfsIdentity(t, r.b, "v2")
r.ctl.cmdInv = "inv-rel"
r.ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-rel", State: instancectl.CmdRunning}
@@ -719,9 +716,7 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){
// launch file stays, and root is never asked to kill a worker. Proven
// once the group empties.
"rootfs worker unitProc": func(t *testing.T, r *rootfsProofRig) {
- old := roleEmptyBound
- roleEmptyBound = 100 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 100*time.Millisecond)
unit := instancectl.WorkerUnitName(r.rt.Host, "jobs")
r.mu.Lock()
r.unit[unit] = [2]string{"active", "inv1"}
@@ -783,9 +778,7 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){
// stays open until that proof; and the lease's kill of it names the tty
// unit and stays unproven while its group is populated.
func rootfsSessionProofRow(t *testing.T, r *rootfsProofRig) {
- old := roleEmptyBound
- roleEmptyBound = 100 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 100*time.Millisecond)
unit := instancectl.RootfsUnitName(instancectl.RoleTTY, r.rt.Host)
r.mu.Lock()
r.unit[unit] = [2]string{"active", "inv-t"}
@@ -849,9 +842,7 @@ func rootfsSessionProofRow(t *testing.T, r *rootfsProofRig) {
// lease's kill of it (KillOneShot through SplitBackend) names it too and
// stays unproven while its group is populated.
func rootfsRunProofRow(t *testing.T, r *rootfsProofRig) {
- old := roleEmptyBound
- roleEmptyBound = 100 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 100*time.Millisecond)
r.ctl.cmdInv = "inv-r"
r.ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdRunning}
r.ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdGone} // the binary unit's answer
diff --git a/internal/activator/rootfs_processes_test.go b/internal/activator/rootfs_processes_test.go
index d306f62e1..18b629f1d 100644
--- a/internal/activator/rootfs_processes_test.go
+++ b/internal/activator/rootfs_processes_test.go
@@ -493,7 +493,7 @@ func TestProcessesThroughTheProductionBackend(t *testing.T) {
logs := captureLogLines(t)
eb, _ := newRootfsBackend(t)
pb := productionBackend(t, eb)
- a := newTrackedService(Config{Bucket: "test-bucket"}, pb, nil)
+ a := newTrackedService(t, Config{Bucket: "test-bucket"}, pb, nil)
t.Cleanup(func() { a.Shutdown(context.Background()) })
rt := rootfsRoute(eb)
id := stageDeclared(t, eb, "v2", declaredProcs(), nil)
diff --git a/internal/activator/rootfs_release_backend_test.go b/internal/activator/rootfs_release_backend_test.go
index 6cb75a20f..77562ef22 100644
--- a/internal/activator/rootfs_release_backend_test.go
+++ b/internal/activator/rootfs_release_backend_test.go
@@ -67,9 +67,8 @@ func needRootfsStart(t *testing.T) {
// a test that settles a cmd unit. Not parallel: both are package vars.
func shrinkCmdBounds(t *testing.T) {
t.Helper()
- oldEmpty, oldGrace := roleEmptyBound, cmdAcceptGrace
- roleEmptyBound, cmdAcceptGrace = 200*time.Millisecond, 50*time.Millisecond
- restoreKnob(t, func() { roleEmptyBound, cmdAcceptGrace = oldEmpty, oldGrace })
+ setKnob(t, &roleEmptyBound, 200*time.Millisecond)
+ setKnob(t, &cmdAcceptGrace, 50*time.Millisecond)
}
// settleAtEnd stops and proves u gone when the test ends.
diff --git a/internal/activator/rootfs_resident_lease_test.go b/internal/activator/rootfs_resident_lease_test.go
index f30648109..b8d607f3f 100644
--- a/internal/activator/rootfs_resident_lease_test.go
+++ b/internal/activator/rootfs_resident_lease_test.go
@@ -101,7 +101,7 @@ func residentKillService(t *testing.T, routes ...registry.Route) (*Service, *kil
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, kb, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, kb, reg)
a.now = clk.now
a.gens = true
armRootfsForTest(a)
@@ -115,9 +115,7 @@ func residentKillService(t *testing.T, routes ...registry.Route) (*Service, *kil
func shrinkDrainBudget(t *testing.T, d time.Duration) {
t.Helper()
- old := residentDrainBudget
- residentDrainBudget = d
- restoreKnob(t, func() { residentDrainBudget = old })
+ setKnob(t, &residentDrainBudget, d)
}
func indexWithPrefix(events []string, prefix string) int {
diff --git a/internal/activator/rootfs_resident_test.go b/internal/activator/rootfs_resident_test.go
index 953fb1088..2913067ac 100644
--- a/internal/activator/rootfs_resident_test.go
+++ b/internal/activator/rootfs_resident_test.go
@@ -103,9 +103,7 @@ func startsFromStagedIdentity(b *fakeBackend) {
// shrinkResidentPoll sets residentPoll for one test. Start reads it once.
func shrinkResidentPoll(t *testing.T, d time.Duration) {
t.Helper()
- old := residentPoll
- residentPoll = d
- restoreKnob(t, func() { residentPoll = old })
+ setKnob(t, &residentPoll, d)
}
// residentOf is a copy of host's residency state (zero when none).
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go
index 3a104c93e..563ace82d 100644
--- a/internal/activator/rootfs_service.go
+++ b/internal/activator/rootfs_service.go
@@ -946,6 +946,9 @@ func (a *Service) watchResidentLease(e *actEntry, sig residentOwnership, done <-
case <-done:
stopTimer(t)
return
+ case <-a.leaseWatchStop: // nil, never ready, outside tests
+ stopTimer(t)
+ return
case <-sig.Lost():
stopTimer(t)
select {
diff --git a/internal/activator/rootfs_staged_test.go b/internal/activator/rootfs_staged_test.go
index 447192db7..5cb84f8da 100644
--- a/internal/activator/rootfs_staged_test.go
+++ b/internal/activator/rootfs_staged_test.go
@@ -212,7 +212,7 @@ func rootfsPlanned(t *testing.T, b Backend, plan WakePlan, runtime string) (*Ser
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.gens = true
armRootfsForTest(a)
evs := &genLog{}
@@ -227,9 +227,9 @@ func rootfsPlanned(t *testing.T, b Backend, plan WakePlan, runtime string) (*Ser
func shrinkHealthBounds(t *testing.T, binary, rootfs, floor time.Duration) {
t.Helper()
- b, r, f := spawnHealthTimeout, rootfsHealthTimeout, firstWakeMinVerdict
- spawnHealthTimeout, rootfsHealthTimeout, firstWakeMinVerdict = binary, rootfs, floor
- restoreKnob(t, func() { spawnHealthTimeout, rootfsHealthTimeout, firstWakeMinVerdict = b, r, f })
+ setKnob(t, &spawnHealthTimeout, binary)
+ setKnob(t, &rootfsHealthTimeout, rootfs)
+ setKnob(t, &firstWakeMinVerdict, floor)
}
// noBinaryStart fails t if root was asked for any binary unit's start.
diff --git a/internal/activator/rootfs_swap_release_test.go b/internal/activator/rootfs_swap_release_test.go
index b522ddb7a..6f5238cfe 100644
--- a/internal/activator/rootfs_swap_release_test.go
+++ b/internal/activator/rootfs_swap_release_test.go
@@ -1007,7 +1007,7 @@ func TestReleaseRerunsAfterAnAgentRestart(t *testing.T) {
}
// The seam between the pass and swapOverlap: the agent restarts. A new
// Service over the same registry and backend wakes the incumbent.
- b := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, f.rb, f.reg)
+ b := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, f.rb, f.reg)
b.gens, b.now = true, f.clk.now
b.genHealth = func(context.Context, Gen) error { return nil }
b.Logs = f.sink
diff --git a/internal/activator/rootfs_test.go b/internal/activator/rootfs_test.go
index cf700a9f0..e9cb3579e 100644
--- a/internal/activator/rootfs_test.go
+++ b/internal/activator/rootfs_test.go
@@ -381,9 +381,7 @@ func TestRootfsStartTreatsA502AsAStartThatMayHaveRun(t *testing.T) {
// cgroup proven empty; unproven, the error says so and nothing is
// released.
func TestRootfsGenerationStartFailureStopsAndProvesTheGeneration(t *testing.T) {
- old := roleEmptyBound
- roleEmptyBound = 60 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 60*time.Millisecond)
for _, tc := range []struct {
name string
// rootUnproven: root's kill answered ErrGenUnproven (files kept);
@@ -452,9 +450,7 @@ func TestRootfsGenerationStartFailureStopsAndProvesTheGeneration(t *testing.T) {
// while the rootfs gen unit's group is populated, asks about that unit and
// never the binary one, and holds once that group is empty.
func TestTheReaperNeverProvesARootfsGenerationGoneThroughTheBinaryUnit(t *testing.T) {
- old := roleEmptyBound
- roleEmptyBound = 60 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 60*time.Millisecond)
b, ctl := newRootfsBackend(t)
b.GenContainment = true
b.Control = fakeGenControl{ctl}
@@ -758,9 +754,7 @@ func TestRootfsHealthBoundIs120Seconds(t *testing.T) {
}
// And a rootfs wake uses it: with a short override the wake fails with
// the rootfs line, and the unit is stopped through the rootfs verb.
- old := rootfsHealthTimeout
- rootfsHealthTimeout = 200 * time.Millisecond
- restoreKnob(t, func() { rootfsHealthTimeout = old })
+ setKnob(t, &rootfsHealthTimeout, 200*time.Millisecond)
b, ctl := newRootfsBackend(t)
rt := rootfsRoute(b)
began := time.Now()
@@ -892,9 +886,7 @@ func TestRootfsCmdUnitPollsStopsAndProvesTheRootfsUnit(t *testing.T) {
asked = append(asked, unit)
return true, populated[unit], nil
}
- old := roleEmptyBound
- roleEmptyBound = 50 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 50*time.Millisecond)
ctl.cmdStatusRootfs = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdRunning}
ctl.cmdStatus = instancectl.CmdStatus{InvocationID: "inv-r", State: instancectl.CmdGone} // what the BINARY unit's poll would say
u := &cmdUnit{b: b, rt: rt, role: instancectl.RoleCmd, inv: "inv-r", io: oneShotIO{out: emptyCmdStream(t), errs: emptyCmdStream(t)}}
diff --git a/internal/activator/rootfs_wake_release_test.go b/internal/activator/rootfs_wake_release_test.go
index 4a9359a8f..33daa13af 100644
--- a/internal/activator/rootfs_wake_release_test.go
+++ b/internal/activator/rootfs_wake_release_test.go
@@ -276,7 +276,7 @@ func (r *wakeRelRig) service(t *testing.T) *Service {
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, r.b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, r.b, reg)
a.now = r.clk.now
a.gens = true
armRootfsForTest(a)
diff --git a/internal/activator/rootfsdb_test.go b/internal/activator/rootfsdb_test.go
index 39ea4b81e..c207c50e8 100644
--- a/internal/activator/rootfsdb_test.go
+++ b/internal/activator/rootfsdb_test.go
@@ -244,16 +244,14 @@ func bucketServiceOn(t *testing.T, rig *bucketRig, bucket release.Store) (*Servi
eb, ctl, rt := newStagedRootfsRig(t)
eb.FilesStore = bucket
ctl.setServe(serveVersions(t, eb, rt, 0, "v1")) // serves, never opens CARLOS_DB
- old := restoreReplica
- restoreReplica = func(ctx context.Context, dbPath, _, _, _ string) (bool, error) { return rig.restore(ctx, dbPath) }
- restoreKnob(t, func() { restoreReplica = old })
+ setKnob(t, &restoreReplica, func(ctx context.Context, dbPath, _, _, _ string) (bool, error) { return rig.restore(ctx, dbPath) })
bb := &bucketBackend{ExecBackend: eb, rig: rig}
reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, bb, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, bb, reg)
a.gens = true
armRootfsForTest(a)
t.Cleanup(func() { a.Shutdown(context.Background()) })
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go
index d4b82918e..85d7f2176 100644
--- a/internal/activator/rootfsrelease_test.go
+++ b/internal/activator/rootfsrelease_test.go
@@ -612,7 +612,7 @@ func newReleaseRig(t *testing.T) *releaseRig {
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.now = clk.now
sink := &rootfsSink{}
a.Logs = sink
@@ -726,11 +726,10 @@ func pinnedNow(t *testing.T, a *Service, host, v string) bool {
// parallel: they are package vars.
func shrinkRelease(t *testing.T, lead, recheck time.Duration) {
t.Helper()
- oldLead, oldRecheck, oldPoll, oldSettle := releaseStopLead, releaseLeaseRecheck, releasePollRetry, releaseSettleRetry
- releaseStopLead, releaseLeaseRecheck, releasePollRetry, releaseSettleRetry = lead, recheck, 10*time.Millisecond, 20*time.Millisecond
- restoreKnob(t, func() {
- releaseStopLead, releaseLeaseRecheck, releasePollRetry, releaseSettleRetry = oldLead, oldRecheck, oldPoll, oldSettle
- })
+ setKnob(t, &releaseStopLead, lead)
+ setKnob(t, &releaseLeaseRecheck, recheck)
+ setKnob(t, &releasePollRetry, 10*time.Millisecond)
+ setKnob(t, &releaseSettleRetry, 20*time.Millisecond)
}
func TestReleasePassesAndEachExitIsMapped(t *testing.T) {
@@ -1467,7 +1466,7 @@ func TestEveryReleaseResultIsClassified(t *testing.T) {
// read every result the same way. Only a failure is the hold's
// SwapDown and B's recorded failure; every other result abandons the
// hold and records nothing of B, with execution as the release left it.
- a := newTrackedService(Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
boot := release.StagedIdentity{Version: "v2", StagedPath: "/opt/carlos/versions/v2/app", Digest: "bb22"}
rt := testRoute("shop.example.com")
rt.Runtime = registry.RuntimeRootfsV1
@@ -1571,7 +1570,7 @@ func newConsumerRig(t *testing.T, gens bool) *consumerRig {
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &releaseCmdFake{cmdFakeBackend: cb, rel: rel}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &releaseCmdFake{cmdFakeBackend: cb, rel: rel}, reg)
a.now = clk.now
a.gens = gens
sink := &rootfsSink{}
diff --git a/internal/activator/rootfsworkers_backend_test.go b/internal/activator/rootfsworkers_backend_test.go
index c97570b4e..67deada4c 100644
--- a/internal/activator/rootfsworkers_backend_test.go
+++ b/internal/activator/rootfsworkers_backend_test.go
@@ -453,9 +453,7 @@ func TestRootfsWorkerIdentity(t *testing.T) {
// Not parallel: it shrinks roleEmptyBound.
func TestRootfsWorkerStopAnswers(t *testing.T) {
- old := roleEmptyBound
- roleEmptyBound = 150 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 150*time.Millisecond)
b, ctl, rt, units := newWorkerBackend(t)
unit := instancectl.WorkerUnitName(rt.Host, "jobs")
units.stopEmpties = false
diff --git a/internal/activator/rootfsworkers_test.go b/internal/activator/rootfsworkers_test.go
index 76ba379e1..e7ab047c9 100644
--- a/internal/activator/rootfsworkers_test.go
+++ b/internal/activator/rootfsworkers_test.go
@@ -379,7 +379,7 @@ func newWorkerRig(t *testing.T, rt registry.Route, workers ...string) *workerRig
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, wb, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, wb, reg)
a.now = clk.now
lc := &leaseClock{t0: time.Now()}
a.leaseNow = lc.now
@@ -1556,7 +1556,7 @@ func TestRootfsWorkersReport(t *testing.T) {
func TestWorkersThroughTheProductionBackendInTheService(t *testing.T) {
b, ctl, rt, units := newWorkerBackend(t)
pb := productionBackend(t, b)
- a := newTrackedService(Config{Bucket: "test-bucket"}, pb, nil)
+ a := newTrackedService(t, Config{Bucket: "test-bucket"}, pb, nil)
armRootfsForTest(a)
t.Cleanup(func() { a.Shutdown(context.Background()) })
web, g := startWorkerWeb(t, b, ctl, rt, units, "SHOP_MODE=live\n")
@@ -1760,7 +1760,7 @@ func TestWorkerGateStrayRule(t *testing.T) {
// watch (or with a replica that has no lease signal, which the tick
// watches).
func TestRootfsWorkerInstallNeedsTheLeaseWatch(t *testing.T) {
- a := newTrackedService(Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
signal := newOwnedRep(&fakeRep{}, time.Now().Add(time.Hour))
t.Cleanup(func() { signal.timer.Stop() })
lost := &fakeRep{}
@@ -1809,9 +1809,8 @@ func TestRootfsWorkerInstallNeedsTheLeaseWatch(t *testing.T) {
// and so workerStartLead. Not parallel: they are package vars.
func shrinkWorkerBounds(t *testing.T, start, proof time.Duration) {
t.Helper()
- oldStart, oldProof := workerStartBound, workerProofBound
- workerStartBound, workerProofBound = start, proof
- restoreKnob(t, func() { workerStartBound, workerProofBound = oldStart, oldProof })
+ setKnob(t, &workerStartBound, start)
+ setKnob(t, &workerProofBound, proof)
}
// [C7; Astra W1 r1 P1, r2 P2] Every worker is stopped and proven before
diff --git a/internal/activator/seedplace_linux_test.go b/internal/activator/seedplace_linux_test.go
index bdb9ba45f..8e9fd7677 100644
--- a/internal/activator/seedplace_linux_test.go
+++ b/internal/activator/seedplace_linux_test.go
@@ -80,9 +80,7 @@ func seededRoute(t *testing.T, b *ExecBackend, rt registry.Route, state string)
func noOwnReplica(t *testing.T) {
t.Helper()
- old := hasOwnReplica
- hasOwnReplica = func(context.Context, string, string, string) (bool, error) { return false, nil }
- restoreKnob(t, func() { hasOwnReplica = old })
+ setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { return false, nil })
}
func TestSeededRestorePlacesTheSnapshot(t *testing.T) {
@@ -276,11 +274,9 @@ func TestSeededRestoreRefusesClaimAndFlat(t *testing.T) {
}
func TestSeededRestoreFailsWhenTheReplicaCannotBeListed(t *testing.T) {
- old := hasOwnReplica
- hasOwnReplica = func(context.Context, string, string, string) (bool, error) {
+ setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) {
return false, errors.New("listing failed")
- }
- defer func() { hasOwnReplica = old }()
+ })
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, _ := seededRoute(t, b, rt, seeds.StateReady)
if fresh, err := b.Restore(context.Background(), rt); err == nil || fresh || objs.opens != 0 {
@@ -289,16 +285,12 @@ func TestSeededRestoreFailsWhenTheReplicaCannotBeListed(t *testing.T) {
}
func TestSeededRestoreUsesItsOwnReplicaOnceItHasOne(t *testing.T) {
- old := hasOwnReplica
- hasOwnReplica = func(context.Context, string, string, string) (bool, error) { return true, nil }
- defer func() { hasOwnReplica = old }()
- oldRestore := restoreReplica
+ setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { return true, nil })
restored := 0
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
restored++
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, _ := seededRoute(t, b, rt, seeds.StateReady)
if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh || restored != 1 || objs.opens != 0 {
@@ -310,12 +302,8 @@ func TestSeededRestoreUsesItsOwnReplicaOnceItHasOne(t *testing.T) {
// come back fresh: fresh would boot the instance empty and run the
// manifest's seed command over a seeded row.
func TestSeededRestoreNeverReportsFreshWhenItsReplicaVanishes(t *testing.T) {
- old := hasOwnReplica
- hasOwnReplica = func(context.Context, string, string, string) (bool, error) { return true, nil }
- defer func() { hasOwnReplica = old }()
- oldRestore := restoreReplica
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) { return false, nil }
- defer func() { restoreReplica = oldRestore }()
+ setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { return true, nil })
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) { return false, nil })
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, _ := seededRoute(t, b, rt, seeds.StateReady)
if fresh, err := b.Restore(context.Background(), rt); err == nil || fresh || objs.opens != 0 {
@@ -336,9 +324,7 @@ func fmtWrap(err error) error { return errors.Join(errors.New("restore shop.exam
func countOwnReplicaLists(t *testing.T, has bool) *int {
t.Helper()
n := 0
- old := hasOwnReplica
- hasOwnReplica = func(context.Context, string, string, string) (bool, error) { n++; return has, nil }
- restoreKnob(t, func() { hasOwnReplica = old })
+ setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { n++; return has, nil })
return &n
}
@@ -353,16 +339,14 @@ func TestSeededRestoreOfAPlacedSeedPromotesAStagedReplica(t *testing.T) {
f := newFakeMirrorStore()
b.Mirror = f
f.put(b.Cfg.Bucket, MovesPrefix(rt.Host)+"generations/a/snapshot", "e1")
- oldRestore := restoreReplica
var restoredFrom []string
- restoreReplica = func(_ context.Context, dbPath, bucket, prefix, _ string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, bucket, prefix, _ string) (bool, error) {
if got, _ := f.List(context.Background(), bucket, prefix); len(got) == 0 {
return false, nil
}
restoredFrom = append(restoredFrom, prefix)
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
os.MkdirAll(filepath.Dir(rt.DBPath), 0o700) // lease.Restore's own MkdirAll
fresh, err := b.Restore(context.Background(), rt)
if err != nil || fresh || objs.opens != 0 || *lists != 0 || len(restoredFrom) != 1 {
@@ -375,12 +359,10 @@ func TestSeededRestoreOfAPlacedSeedKeepsTheWarmCopyWithoutListing(t *testing.T)
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, _ := seededRoute(t, b, rt, seeds.StatePlaced)
b.ClaimArmed = true
- oldRestore := restoreReplica
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) {
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) {
t.Fatal("a warm copy was restored over")
return false, nil
- }
- defer func() { restoreReplica = oldRestore }()
+ })
os.MkdirAll(filepath.Dir(rt.DBPath), 0o700)
if err := writeMinimalSQLite(rt.DBPath); err != nil {
t.Fatal(err)
@@ -394,9 +376,7 @@ func TestSeededRestoreOfAPlacedSeedWithNothingToRestoreFails(t *testing.T) {
countOwnReplicaLists(t, false)
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, _ := seededRoute(t, b, rt, seeds.StatePlaced)
- oldRestore := restoreReplica
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) { return false, nil }
- defer func() { restoreReplica = oldRestore }()
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) { return false, nil })
if fresh, err := b.Restore(context.Background(), rt); err == nil || fresh || objs.opens != 0 {
t.Fatalf("fresh %v err %v opens %d; want a failed wake, never fresh", fresh, err, objs.opens)
}
@@ -423,10 +403,8 @@ func TestSeededRestoreOfACommittedImportWithNothingToRestoreFails(t *testing.T)
lists := countOwnReplicaLists(t, false)
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs := committedImport(t, b, rt)
- oldRestore := restoreReplica
restored := 0
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) { restored++; return false, nil }
- defer func() { restoreReplica = oldRestore }()
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) { restored++; return false, nil })
if fresh, err := b.Restore(context.Background(), rt); err == nil || fresh || restored != 1 || objs.opens != 0 || *lists != 0 {
t.Fatalf("fresh %v err %v restored %d opens %d lists %d; want a failed wake, never fresh", fresh, err, restored, objs.opens, *lists)
}
@@ -437,11 +415,9 @@ func TestSeededRestoreOfACommittedImportRestoresItsOwnReplica(t *testing.T) {
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs := committedImport(t, b, rt)
b.ClaimArmed = true // as placed: no claim refusal for a restore of its own
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
os.MkdirAll(filepath.Dir(rt.DBPath), 0o700)
if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh || objs.opens != 0 || *lists != 0 {
t.Fatalf("fresh %v err %v opens %d lists %d; want its own replica, no fetch", fresh, err, objs.opens, *lists)
@@ -470,10 +446,8 @@ func TestSeededRestoreLeavesAnUnplaceableSeedToThePlainPath(t *testing.T) {
lists := countOwnReplicaLists(t, false)
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, _ := seededRoute(t, b, rt, state)
- oldRestore := restoreReplica
restored := 0
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) { restored++; return false, nil }
- defer func() { restoreReplica = oldRestore }()
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) { restored++; return false, nil })
fresh, err := b.Restore(context.Background(), rt)
if err != nil || !fresh || restored != 1 || objs.opens != 0 || *lists != 0 {
t.Fatalf("fresh %v err %v restored %d opens %d lists %d; want the plain path", fresh, err, restored, objs.opens, *lists)
@@ -557,7 +531,7 @@ func TestSeededRestoreRefusesASwappedTempFile(t *testing.T) {
}
old := checkSeedDB
readSwapped := false
- checkSeedDB = func(ctx context.Context, path string) error {
+ setKnob(t, &checkSeedDB, func(ctx context.Context, path string) error {
if !c.swapAfter {
swap()
// The check is handed the fetched file itself, not a
@@ -571,8 +545,7 @@ func TestSeededRestoreRefusesASwappedTempFile(t *testing.T) {
swap()
}
return err
- }
- defer func() { checkSeedDB = old }()
+ })
var spe *SeedPlacementError
_, err := b.Restore(context.Background(), rt)
if readSwapped {
@@ -721,12 +694,8 @@ func TestSeedPlacedWaitsForTheFirstUpload(t *testing.T) {
// finishes the placement; a failure there never fails the wake, and the
// wake after that asks again.
func TestSeedPlacedIsFinishedOnTheNextWake(t *testing.T) {
- old := hasOwnReplica
- hasOwnReplica = func(context.Context, string, string, string) (bool, error) { return true, nil }
- defer func() { hasOwnReplica = old }()
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) { return true, writeMinimalSQLite(dbPath) }
- defer func() { restoreReplica = oldRestore }()
+ setKnob(t, &hasOwnReplica, func(context.Context, string, string, string) (bool, error) { return true, nil })
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) { return true, writeMinimalSQLite(dbPath) })
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, objs, id := seededRoute(t, b, rt, seeds.StateReady) // the CAS was lost last wake
rt.Account, rt.App = "acct", "shop"
@@ -786,11 +755,9 @@ func TestSeededRestoreOfItsOwnReplicaWritesTheMarker(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
os.MkdirAll(filepath.Dir(rt.DBPath), 0o700)
if c.warm {
if err := writeMinimalSQLite(rt.DBPath); err != nil {
@@ -852,15 +819,13 @@ func TestPlainRestoreNeverServesAnotherSeedsDatabase(t *testing.T) {
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
rt, marker := c.seed(t, b, rt)
restored := 0
- oldRestore := restoreReplica
- restoreReplica = func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
+ setKnob(t, &restoreReplica, func(_ context.Context, dbPath, _, _, _ string) (bool, error) {
restored++
if !c.replica {
return false, nil
}
return true, writeMinimalSQLite(dbPath)
- }
- defer func() { restoreReplica = oldRestore }()
+ })
if err := os.MkdirAll(filepath.Dir(rt.DBPath), 0o700); err != nil {
t.Fatal(err)
}
@@ -913,9 +878,7 @@ func TestPlainRestoreNeverServesAnotherSeedsDatabase(t *testing.T) {
func TestPlainWakeOverAMarkerOnlyLeftoverKeepsTheReplacementsData(t *testing.T) {
countOwnReplicaLists(t, false)
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
- oldRestore := restoreReplica
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) { return false, nil }
- defer func() { restoreReplica = oldRestore }()
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) { return false, nil })
dir := filepath.Dir(rt.DBPath)
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
@@ -951,12 +914,10 @@ func TestPlainWakeOverAMarkerOnlyLeftoverKeepsTheReplacementsData(t *testing.T)
// there, and nothing is created beside it.
func TestPlainWakeFailsOnAnUnreadableMarkerAlone(t *testing.T) {
b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{})
- oldRestore := restoreReplica
- restoreReplica = func(context.Context, string, string, string, string) (bool, error) {
+ setKnob(t, &restoreReplica, func(context.Context, string, string, string, string) (bool, error) {
t.Fatal("restored beside an unreadable marker")
return false, nil
- }
- defer func() { restoreReplica = oldRestore }()
+ })
os.MkdirAll(filepath.Dir(rt.DBPath), 0o700)
a, _ := seeds.NewID()
marker := rt.DBPath + SeedMarkerSuffix
diff --git a/internal/activator/settle_test.go b/internal/activator/settle_test.go
index 92275d040..0cdddb804 100644
--- a/internal/activator/settle_test.go
+++ b/internal/activator/settle_test.go
@@ -55,11 +55,9 @@ func (p *cancelOnPoll) Exited() bool {
}
func TestSwapCanarySettle(t *testing.T) {
- old := swapSettle
- restoreKnob(t, func() { swapSettle = old })
t.Run("exit during the settle fails the build", func(t *testing.T) {
- swapSettle = 2 * time.Second
+ setKnob(t, &swapSettle, 2*time.Second)
f := newSwapFixture(t)
f.a.genHealth = func(context.Context, Gen) error {
// Alive at the settle's opening check, dead at its next poll.
@@ -78,7 +76,7 @@ func TestSwapCanarySettle(t *testing.T) {
}
})
t.Run("a canary waits out the settle", func(t *testing.T) {
- swapSettle = 100 * time.Millisecond
+ setKnob(t, &swapSettle, 100*time.Millisecond)
f := newSwapFixture(t)
at := f.attempt(ModeOverlap)
at.Canary = true
@@ -91,7 +89,7 @@ func TestSwapCanarySettle(t *testing.T) {
}
})
t.Run("a swap after the canary does not settle", func(t *testing.T) {
- swapSettle = time.Hour
+ setKnob(t, &swapSettle, time.Hour)
f := newSwapFixture(t)
done := make(chan SwapResult, 1)
go func() { done <- f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) }()
@@ -110,9 +108,7 @@ func TestSwapCanarySettle(t *testing.T) {
// observation and is not a failure (spec §6.4). The successor is stopped
// before the incumbent, through the barrier.
func TestSwapIntentionalStopDuringSettleIsNotAFailure(t *testing.T) {
- old := swapSettle
- swapSettle = 5 * time.Second
- restoreKnob(t, func() { swapSettle = old })
+ setKnob(t, &swapSettle, 5*time.Second)
for _, tc := range []struct {
name string
stop func(f *swapFixture)
diff --git a/internal/activator/shuttingdown_answer_test.go b/internal/activator/shuttingdown_answer_test.go
index 2df9fd9b3..f99322ed2 100644
--- a/internal/activator/shuttingdown_answer_test.go
+++ b/internal/activator/shuttingdown_answer_test.go
@@ -23,7 +23,7 @@ func TestShuttingDownAnswersRetryAfter(t *testing.T) {
asForwarded(t)
}
b := &fakeBackend{}
- a := newTrackedService(Config{}, b, nil)
+ a := newTrackedService(t, Config{}, b, nil)
a.mu.Lock()
a.shuttingDown = true
a.mu.Unlock()
diff --git a/internal/activator/size_live_test.go b/internal/activator/size_live_test.go
index 8000db255..b8deb30de 100644
--- a/internal/activator/size_live_test.go
+++ b/internal/activator/size_live_test.go
@@ -677,9 +677,7 @@ func (s *sizingBackend) ResizeLive(_ context.Context, _ registry.Route, size cgr
// with the lease, and neither of reapCurrentGen's proofs releases it while
// the resize runs. Not parallel: it sets opJoinBound.
func TestPendingStopKeepsTheLeaseWhileAResizeRuns(t *testing.T) {
- prev := opJoinBound
- opJoinBound = 100 * time.Millisecond
- restoreKnob(t, func() { opJoinBound = prev })
+ setKnob(t, &opJoinBound, 100*time.Millisecond)
for _, gens := range []bool{true, false} {
name := "generations off"
if gens {
diff --git a/internal/activator/startrule_test.go b/internal/activator/startrule_test.go
index 2191c718c..84db4c9d5 100644
--- a/internal/activator/startrule_test.go
+++ b/internal/activator/startrule_test.go
@@ -207,7 +207,7 @@ func wakeOn(t *testing.T, eb *ExecBackend, rt registry.Route, tweak func(*ruleBa
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, rb, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, rb, reg)
release, err := a.beginRequest(context.Background(), rt)
if err == nil {
release()
@@ -457,11 +457,11 @@ func recordDurability(t *testing.T, fail func(dir string) error) *[]string {
t.Helper()
var ops []string
prevRename, prevSync := setAsideRename, durableSync
- setAsideRename = func(sd, sn, dd, dn string) error {
+ setKnob(t, &setAsideRename, func(sd, sn, dd, dn string) error {
ops = append(ops, "rename "+filepath.Join(sd, sn)+" -> "+filepath.Join(dd, dn))
return prevRename(sd, sn, dd, dn)
- }
- durableSync = func(dir string) error {
+ })
+ setKnob(t, &durableSync, func(dir string) error {
ops = append(ops, "sync "+dir)
if fail != nil {
if err := fail(dir); err != nil {
@@ -469,8 +469,7 @@ func recordDurability(t *testing.T, fail func(dir string) error) *[]string {
}
}
return prevSync(dir)
- }
- restoreKnob(t, func() { setAsideRename, durableSync = prevRename, prevSync })
+ })
return &ops
}
diff --git a/internal/activator/startup_test.go b/internal/activator/startup_test.go
index 53fda5399..db7655141 100644
--- a/internal/activator/startup_test.go
+++ b/internal/activator/startup_test.go
@@ -12,10 +12,8 @@ import (
)
func TestStartupWaitUsesWakeTimeoutResponse(t *testing.T) {
- old := wakeWaitBound
- wakeWaitBound = 20 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ setKnob(t, &wakeWaitBound, 20*time.Millisecond)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
a.Startup = make(chan struct{})
defer a.lifeStop()
rt := registry.Route{Host: "shop.example.com", Kind: "instance", Hibernate: true}
@@ -30,10 +28,8 @@ func TestStartupWaitUsesWakeTimeoutResponse(t *testing.T) {
}
func TestStartupBlocksWorkerAndSidecarAdmission(t *testing.T) {
- old := wakeWaitBound
- wakeWaitBound = 20 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ setKnob(t, &wakeWaitBound, 20*time.Millisecond)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
a.Startup = make(chan struct{})
defer a.lifeStop()
rt := registry.Route{Host: "shop.example.com", Kind: "instance", Hibernate: true}
@@ -56,7 +52,7 @@ func TestStartupBlocksWorkerAndSidecarAdmission(t *testing.T) {
func TestStartupShutdownAnswersServiceUnavailable(t *testing.T) {
for _, ready := range []bool{false, true} {
t.Run(map[bool]string{false: "held", true: "released"}[ready], func(t *testing.T) {
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
started := make(chan struct{})
a.Startup = started
if ready {
@@ -93,7 +89,7 @@ func (s startupRoutes) Get(host string) (*registry.Route, error) {
func TestStartupHeldRequestRefusesStaleUpstream(t *testing.T) {
t.Parallel()
for _, moved := range []bool{false, true} {
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
ready := make(chan struct{})
a.Startup = ready
rt := registry.Route{Host: "shop.example.com", Kind: "instance", Hibernate: true, Socket: "/run/carlos/shop.example.com.sock"}
@@ -131,7 +127,7 @@ func TestStartupHeldRequestRefusesStaleUpstream(t *testing.T) {
// startup is still checked; one long after it is not.
func TestStartupClosedNearStartupRefusesStaleUpstream(t *testing.T) {
for _, late := range []bool{false, true} {
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
ready := make(chan struct{})
close(ready)
a.Startup = ready
diff --git a/internal/activator/stop_returned_sidecar_test.go b/internal/activator/stop_returned_sidecar_test.go
index 3d4dcec88..7f945d08c 100644
--- a/internal/activator/stop_returned_sidecar_test.go
+++ b/internal/activator/stop_returned_sidecar_test.go
@@ -41,9 +41,7 @@ func (g *stopEventGate) Event(_, _, _, _, msg string) {
// in-flight sidecar start for one test.
func shrinkSidecarJoinWait(t *testing.T) {
t.Helper()
- prev := sidecarStartJoinWait
- sidecarStartJoinWait = 50 * time.Millisecond
- restoreKnob(t, func() { sidecarStartJoinWait = prev })
+ setKnob(t, &sidecarStartJoinWait, 50*time.Millisecond)
}
// Fix wave 1, item 1 (Astra final review 1, finding 1): the missed-join
diff --git a/internal/activator/swap_admit_test.go b/internal/activator/swap_admit_test.go
index dffb3de81..c30d471df 100644
--- a/internal/activator/swap_admit_test.go
+++ b/internal/activator/swap_admit_test.go
@@ -144,7 +144,7 @@ func TestOwnershipIsCheckedApartFromSupersession(t *testing.T) {
// Claims off: hostwrite's legacy work. The check runs alone, under the
// entry lock that fn takes itself.
func TestAdmitClaimsOffRunsTheCheckAlone(t *testing.T) {
- a := newTrackedService(Config{}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{}, &fakeBackend{}, nil)
work, err := a.selectWork(context.Background(), "h.example.com")
if err != nil || !hostwrite.Legacy(work) {
t.Fatalf("claims off selected %T, %v; want the legacy work", work, err)
@@ -161,7 +161,7 @@ func TestAdmitClaimsOffRunsTheCheckAlone(t *testing.T) {
func TestAdmitClaimsOnValidatesFirstAndNeverFallsBack(t *testing.T) {
ctx := context.Background()
w := &swapWork{}
- a := newTrackedService(Config{HostWrites: hostwrite.Config{Enabled: true, Selector: &swapSelector{work: w}}}, &fakeBackend{}, nil)
+ a := newTrackedService(t, Config{HostWrites: hostwrite.Config{Enabled: true, Selector: &swapSelector{work: w}}}, &fakeBackend{}, nil)
work, err := a.selectWork(ctx, "h.example.com")
if err != nil || hostwrite.Legacy(work) {
t.Fatalf("claims on selected %T, %v", work, err)
diff --git a/internal/activator/swap_executed_test.go b/internal/activator/swap_executed_test.go
index 83a67fccb..375e410e0 100644
--- a/internal/activator/swap_executed_test.go
+++ b/internal/activator/swap_executed_test.go
@@ -285,8 +285,7 @@ func TestReplaceWorkerLearnsItsRespawnsExecutionWhenItsCallerLeaves(t *testing.T
} {
t.Run(tc.name, func(t *testing.T) {
if tc.bound > 0 {
- defer func(d time.Duration) { respawnJoinBound = d }(respawnJoinBound)
- respawnJoinBound = tc.bound
+ setKnob(t, &respawnJoinBound, tc.bound)
}
shrinkFirstWake(t, 55*time.Second, 25*time.Second, 100*time.Millisecond)
a, b, _, _, _ := stagedActivator(t)
diff --git a/internal/activator/swap_fixture_test.go b/internal/activator/swap_fixture_test.go
index a59ea52ed..493dc94fb 100644
--- a/internal/activator/swap_fixture_test.go
+++ b/internal/activator/swap_fixture_test.go
@@ -278,7 +278,7 @@ func newSwapFixtureOn(t *testing.T, wrap func(*fakeSwapBackend) Backend) *swapFi
if wrap != nil {
be = wrap(b)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, be, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, be, reg)
a.gens = true // plan 1's switch, as plan 5 sets it from CARLOS_SWAP
a.now = clk.now
a.genHealth = func(context.Context, Gen) error { return nil }
diff --git a/internal/activator/swap_hold_test.go b/internal/activator/swap_hold_test.go
index a90f87c2c..8606003ed 100644
--- a/internal/activator/swap_hold_test.go
+++ b/internal/activator/swap_hold_test.go
@@ -102,8 +102,6 @@ func (c *doneAskedCtx) Done() <-chan struct{} {
// the moment the pinned wake is ready, and a crash a second later neither
// fails the attempt nor halts the rollout.
func TestSwapHoldCanarySettles(t *testing.T) {
- old := swapSettle
- restoreKnob(t, func() { swapSettle = old })
start := func(t *testing.T, f *swapFixture) (chan SwapResult, Gen, *fakeProc) {
t.Helper()
at := f.attempt(ModeHold)
@@ -122,7 +120,7 @@ func TestSwapHoldCanarySettles(t *testing.T) {
return results, g, p
}
t.Run("an exit in the window is down, with no fallback", func(t *testing.T) {
- swapSettle = 5 * time.Second
+ setKnob(t, &swapSettle, 5*time.Second)
f := newSwapFixture(t)
results, _, p := start(t, f)
select {
@@ -140,7 +138,7 @@ func TestSwapHoldCanarySettles(t *testing.T) {
}
})
t.Run("surviving the window is done", func(t *testing.T) {
- swapSettle = 100 * time.Millisecond
+ setKnob(t, &swapSettle, 100*time.Millisecond)
f := newSwapFixture(t)
began := time.Now()
results, g, _ := start(t, f)
@@ -153,7 +151,7 @@ func TestSwapHoldCanarySettles(t *testing.T) {
}
})
t.Run("an intentional stop in the window is not a failure", func(t *testing.T) {
- swapSettle = 5 * time.Second
+ setKnob(t, &swapSettle, 5*time.Second)
f := newSwapFixture(t)
results, _, _ := start(t, f)
f.a.Bounce(f.host)
@@ -585,12 +583,10 @@ func TestSwapHoldReleasesItsCallerWhileTheStopIsPending(t *testing.T) {
}, errSwapStopped},
} {
t.Run(tc.name, func(t *testing.T) {
- old := wakeWaitBound
- restoreKnob(t, func() { wakeWaitBound = old })
- f := newSwapFixture(t)
if errors.Is(tc.want, errHoldStopSlow) {
- wakeWaitBound = 100 * time.Millisecond
+ setKnob(t, &wakeWaitBound, 100*time.Millisecond)
}
+ f := newSwapFixture(t)
gate := make(chan struct{})
incumbent := f.b.lastProc()
incumbent.setStopGate(gate)
diff --git a/internal/activator/swap_review_test.go b/internal/activator/swap_review_test.go
index 0cb847b84..c61fa7ed1 100644
--- a/internal/activator/swap_review_test.go
+++ b/internal/activator/swap_review_test.go
@@ -24,7 +24,7 @@ func TestSwapWitnessAgentRestartMidSwap(t *testing.T) {
t.Helper()
f.b.execVerFn = func() string { return "v2" } // root installed v2
gensBefore, _, _ := f.b.calls()
- a2 := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, f.b, f.reg)
+ a2 := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, f.b, f.reg)
a2.gens = true
arrangeAwake(t, a2, testRoute(f.host))
if got := f.b.startCount(); got != 2 {
@@ -194,9 +194,7 @@ func TestSwapNeverHealthyAppKeepsTheIncumbentServing(t *testing.T) {
go srv.Serve(ln) //nolint:errcheck
return func() { srv.Close() }
}
- old := spawnHealthTimeout
- spawnHealthTimeout = 600 * time.Millisecond
- restoreKnob(t, func() { spawnHealthTimeout = old })
+ setKnob(t, &spawnHealthTimeout, 600*time.Millisecond)
f := newSwapFixture(t)
f.a.genHealth = nil // the real check: GET / through the generation's handle
diff --git a/internal/activator/swap_sim_test.go b/internal/activator/swap_sim_test.go
index e3c8f4c5e..3879b63fb 100644
--- a/internal/activator/swap_sim_test.go
+++ b/internal/activator/swap_sim_test.go
@@ -65,9 +65,8 @@ func TestSwapInvariants(t *testing.T) {
}
first, last = n, n+1
}
- oldSettle, oldJoin := swapSettle, opJoinBound
- swapSettle, opJoinBound = 2*time.Millisecond, 3*time.Second
- restoreKnob(t, func() { swapSettle, opJoinBound = oldSettle, oldJoin })
+ setKnob(t, &swapSettle, 2*time.Millisecond)
+ setKnob(t, &opJoinBound, 3*time.Second)
// The Service's own log lines go into the seed's event log, so a failure
// prints them in order with the model's events, and a passing sweep
// prints nothing.
@@ -93,7 +92,7 @@ func TestSwapInvariants(t *testing.T) {
t.Logf("seeds %d..%d: seed settings and Swap results (mode/outcome: reason, normalized):\n%s", first, last-1, strings.Join(lines, "\n"))
})
for seed := first; seed < last; seed++ {
- violations, events, outcomes := simulateSwapOnce(seed, staged, sockDir, sink)
+ violations, events, outcomes := simulateSwapOnce(t, seed, staged, sockDir, sink)
for k, n := range outcomes {
tally[k] += n
}
@@ -955,7 +954,7 @@ func onOff(b bool) string {
return "off"
}
-func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, sink *simLogSink) ([]string, []string, map[string]int) {
+func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, sockDir string, sink *simLogSink) ([]string, []string, map[string]int) {
hosts := []string{"one.sim.example.com", "two.sim.example.com"}
w := &simWorld{rng: rand.New(rand.NewSource(int64(seed))), running: map[string]map[*simProc]bool{},
live: map[string]string{}, staged: map[string]string{}, seen: map[string]bool{}, outcomes: map[string]int{},
@@ -979,7 +978,7 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s
}
sb := &simBackend{w: w, dir: sockDir, reps: map[string]*simRep{}, wakes: map[string]int{}}
clk := &fakeClock{t: time.Unix(1_700_000_000, 0)}
- a := newTrackedService(Config{Bucket: "sim", Idle: time.Hour}, sb, simDue{})
+ a := newTrackedService(t, Config{Bucket: "sim", Idle: time.Hour}, sb, simDue{})
a.gens = w.gensOn
a.now = w.simHeldClock(clk.now)
// I4's record: every leg this Service registers, under a.mu.
diff --git a/internal/activator/tunnel_refuse_test.go b/internal/activator/tunnel_refuse_test.go
index 0b0743ab8..bf226bacc 100644
--- a/internal/activator/tunnel_refuse_test.go
+++ b/internal/activator/tunnel_refuse_test.go
@@ -58,7 +58,7 @@ func newRefuseBox(t *testing.T, rt registry.Route) *refuseBox {
if err != nil {
t.Fatal(err)
}
- x.a = newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, x.b, reg)
+ x.a = newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, x.b, reg)
x.a.Startup = make(chan struct{})
//lint:ignore SA1019 drives the x/net ClientConn the hub uses in production (internal/edge/tunnel.go)
conns := make(chan *http2.ClientConn, 1)
@@ -169,7 +169,7 @@ func TestServeRefusesBeforeAppRead(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.Startup = make(chan struct{})
a.lifeStop()
w := httptest.NewRecorder()
diff --git a/internal/activator/unitproc_test.go b/internal/activator/unitproc_test.go
index fdbd1305f..10ca9e09f 100644
--- a/internal/activator/unitproc_test.go
+++ b/internal/activator/unitproc_test.go
@@ -660,9 +660,7 @@ func TestSeedUnitFailureStopsBeforeCleanupAndKeepsTheDBWhenProcessesRemain(t *te
if roleEmptyBound != actStopTimeout {
t.Fatalf("roleEmptyBound = %v, want actStopTimeout (%v) outside a test", roleEmptyBound, actStopTimeout)
}
- old := roleEmptyBound
- roleEmptyBound = 300 * time.Millisecond
- restoreKnob(t, func() { roleEmptyBound = old })
+ setKnob(t, &roleEmptyBound, 300*time.Millisecond)
ctl := &fakeControl{seed: instancectl.SeedResponse{InvocationID: "s1", Result: "exit-code", Status: "3", Code: "exited"}}
unit := &fakeUnit{}
b, rt := nestedBackend(t, ctl, unit)
diff --git a/internal/activator/wakecheck_claim_linux_test.go b/internal/activator/wakecheck_claim_linux_test.go
index f961b2da0..542252893 100644
--- a/internal/activator/wakecheck_claim_linux_test.go
+++ b/internal/activator/wakecheck_claim_linux_test.go
@@ -61,7 +61,7 @@ func newHeldClaimed(t *testing.T, live, hashed string) *heldClaimed {
}
var mu sync.Mutex
reads := 0
- c.a = newTrackedService(Config{Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box", Bucket: "data",
+ c.a = newTrackedService(t, Config{Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box", Bucket: "data",
Read: func(context.Context, string) (hostclaim.Observed, error) {
mu.Lock()
defer mu.Unlock()
diff --git a/internal/activator/wakecheck_test.go b/internal/activator/wakecheck_test.go
index 50948ddbd..7501d6a5d 100644
--- a/internal/activator/wakecheck_test.go
+++ b/internal/activator/wakecheck_test.go
@@ -28,9 +28,7 @@ func heldOn(v string) func(string) HeldWake {
// bound its waiters have).
func shrinkWakeWait(t *testing.T, d time.Duration) {
t.Helper()
- old := wakeWaitBound
- wakeWaitBound = d
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, d)
}
// shrinkHeldPoll sets how often a held wake polls while it waits, for one
@@ -38,9 +36,7 @@ func shrinkWakeWait(t *testing.T, d time.Duration) {
// waits for a re-ask waits heldReask*d.
func shrinkHeldPoll(t *testing.T, d time.Duration) {
t.Helper()
- old := heldPoll
- heldPoll = d
- restoreKnob(t, func() { heldPoll = old })
+ setKnob(t, &heldPoll, d)
}
// asks records RequestStage calls as host@build.
@@ -548,7 +544,7 @@ func TestAHeldUnitRowRefusesALinkThatMovedAfterTheWait(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, split, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, split, reg)
ur := identityRoute(t, "u.example.com")
ur.Backing = registry.BackingUnit
routes := &countingRoutes{rt: ur}
diff --git a/internal/activator/wakeidentity_test.go b/internal/activator/wakeidentity_test.go
index ee8e23e49..0f9b96e33 100644
--- a/internal/activator/wakeidentity_test.go
+++ b/internal/activator/wakeidentity_test.go
@@ -603,7 +603,7 @@ func TestANestedUnversionedLinkWithNoHookWakesAsToday(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &leaselessExec{ExecBackend: eb, fb: &fakeBackend{}}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &leaselessExec{ExecBackend: eb, fb: &fakeBackend{}}, reg)
done, err := a.beginRequest(context.Background(), rt)
if err != nil {
t.Fatalf("a nested unversioned link with no hook did not wake: %v\nroot was asked:\n%s", err, ctl.joined())
@@ -674,7 +674,7 @@ func TestAUnitRouteOnASplitBackendKeepsTodaysWake(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, split, reg) // as agent.go builds it
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, split, reg) // as agent.go builds it
l := &execLog{}
a.BeforeExec = l.hook
unit.restoreFresh = true
@@ -857,7 +857,7 @@ func sidecarActivator(t *testing.T, live string) (*Service, *planGenBackend) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
b.sidecarStaged = true
if live != "" {
b.fakeBackend.setIdentity(live)
@@ -1080,9 +1080,7 @@ func TestAWorkerTokenMintFailureDropsThePendingBuild(t *testing.T) {
a, b, _, _, _ := stagedActivator(t)
b.fakeBackend.setIdentity("v1")
a.GenerationsFile = filepath.Join(t.TempDir(), "zdd", "generations.json")
- old := randRead
- randRead = func([]byte) (int, error) { return 0, errors.New("entropy pool exhausted") }
- defer func() { randRead = old }()
+ setKnob(t, &randRead, func([]byte) (int, error) { return 0, errors.New("entropy pool exhausted") })
host := "bot.x.internal"
if err := a.WakeWorker(testWorkerRoute(host)); err == nil || !strings.Contains(err.Error(), "mint worker token") {
t.Fatalf("WakeWorker = %v, want the mint failure", err)
diff --git a/internal/activator/wakeplan_test.go b/internal/activator/wakeplan_test.go
index 35e86edab..914e97bae 100644
--- a/internal/activator/wakeplan_test.go
+++ b/internal/activator/wakeplan_test.go
@@ -187,7 +187,7 @@ func planActivator(t *testing.T, plan WakePlan) (*Service, *planGenBackend, *gen
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.gens = true // plan 1's switch, as CARLOS_SWAP=overlap sets it before New
evs := &genLog{}
a.OnGen = evs.add
@@ -198,9 +198,9 @@ func planActivator(t *testing.T, plan WakePlan) (*Service, *planGenBackend, *gen
func shrinkFirstWake(t *testing.T, budget, reserve, settle time.Duration) {
t.Helper()
- b, r, s, k := firstWakeBudget, firstWakeKillReserve, firstWakeSettle, firstWakeKillBound
- firstWakeBudget, firstWakeKillReserve, firstWakeSettle = budget, reserve, settle
- restoreKnob(t, func() { firstWakeBudget, firstWakeKillReserve, firstWakeSettle, firstWakeKillBound = b, r, s, k })
+ setKnob(t, &firstWakeBudget, budget)
+ setKnob(t, &firstWakeKillReserve, reserve)
+ setKnob(t, &firstWakeSettle, settle)
}
func TestFirstWakeFallsBackToTheGoodBuildWithinTheBudget(t *testing.T) {
@@ -478,9 +478,7 @@ func TestAFirstWakeThatSurvivesSettles(t *testing.T) {
}
func TestFirstWakeWaitersGetTheLongerBudget(t *testing.T) {
- old := wakeWaitBound
- wakeWaitBound = 100 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 100*time.Millisecond)
shrinkFirstWake(t, 600*time.Millisecond, 200*time.Millisecond, time.Millisecond)
dir := t.TempDir()
good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2")
@@ -538,9 +536,7 @@ func TestAClaimedFirstWakeReportsLikeAnUnclaimedOne(t *testing.T) {
// shrinkClaimStartBackoff sets startAdmitted's backoff base for one test.
func shrinkClaimStartBackoff(t *testing.T, d time.Duration) {
t.Helper()
- old := claimStartBackoff
- claimStartBackoff = d
- restoreKnob(t, func() { claimStartBackoff = old })
+ setKnob(t, &claimStartBackoff, d)
}
// PF17: every claims-on launch refuses on this base (RoleLaunch.Start
@@ -575,7 +571,7 @@ func TestAPlannedClaimedWakeRefusesAtTheLaunchRecordingNothing(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box",
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour, HostWrites: hostwrite.Config{Enabled: true}, Claims: &ClaimRuntime{Box: "box",
Read: func(context.Context, string) (hostclaim.Observed, error) {
if reads.Add(1) == 1 {
return obs, nil
@@ -695,9 +691,7 @@ func stagedScript(t *testing.T, dir, ver, body string) release.StagedIdentity {
func TestAPlannedFirstWakeOnTheRealExecBackendFallsBackInTime(t *testing.T) {
for _, layout := range []string{"flat", "foreign"} {
t.Run(layout, func(t *testing.T) {
- oldBound := wakeWaitBound
- wakeWaitBound = time.Second
- restoreKnob(t, func() { wakeWaitBound = oldBound })
+ setKnob(t, &wakeWaitBound, time.Second)
shrinkFirstWake(t, 4*time.Second, 2*time.Second, time.Millisecond) // B's health window: 2 s
// The floor shrinks with the window, or B (2 s) would never be
// exec'd under the spec's 20 s floor.
@@ -723,7 +717,7 @@ func TestAPlannedFirstWakeOnTheRealExecBackendFallsBackInTime(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.gens = true
evs := &genLog{}
a.OnGen = evs.add
@@ -1258,9 +1252,7 @@ func TestBounceTextIsTheApprovedWording(t *testing.T) {
// in milliseconds rather than the spec's seconds.
func shrinkVerdictFloor(t *testing.T, floor time.Duration) {
t.Helper()
- old := firstWakeMinVerdict
- firstWakeMinVerdict = floor
- restoreKnob(t, func() { firstWakeMinVerdict = old })
+ setKnob(t, &firstWakeMinVerdict, floor)
}
// slowFirstCheck is a plan's selection gate whose first call, checkPlan's
diff --git a/internal/activator/wakerecord_refused_test.go b/internal/activator/wakerecord_refused_test.go
index 6d8fabd50..bb5f86d21 100644
--- a/internal/activator/wakerecord_refused_test.go
+++ b/internal/activator/wakerecord_refused_test.go
@@ -53,7 +53,7 @@ func refusedWake(t *testing.T, eb *ExecBackend, rt registry.Route) (error, []str
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &execIdentityBackend{fakeBackend: fb, eb: eb}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &execIdentityBackend{fakeBackend: fb, eb: eb}, reg)
l := &execLog{}
a.BeforeExec = l.hook
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
diff --git a/internal/activator/wakeslots_test.go b/internal/activator/wakeslots_test.go
index b137b59c8..b3f56c9ed 100644
--- a/internal/activator/wakeslots_test.go
+++ b/internal/activator/wakeslots_test.go
@@ -19,7 +19,7 @@ func testActivatorSlots(t *testing.T, slots int) (*Service, *fakeBackend) {
if err != nil {
t.Fatalf("open registry: %v", err)
}
- return newTrackedService(Config{Bucket: "test-bucket", Idle: time.Minute, WakeSlots: slots}, b, reg), b
+ return newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Minute, WakeSlots: slots}, b, reg), b
}
// A burst of first requests to different hosts (#524) wakes at most
diff --git a/internal/activator/worker_gen_test.go b/internal/activator/worker_gen_test.go
index 9a1fd1bfa..46fe4598f 100644
--- a/internal/activator/worker_gen_test.go
+++ b/internal/activator/worker_gen_test.go
@@ -16,9 +16,7 @@ func TestWorkerGenerations(t *testing.T) {
for _, on := range []bool{true, false} {
a, b, _, _ := testActivator(t, time.Hour)
a.gens = on
- old := sidecarSettle
- sidecarSettle = 20 * time.Millisecond
- restoreKnob(t, func() { sidecarSettle = old })
+ setKnob(t, &sidecarSettle, 20*time.Millisecond)
rt := testWorkerRoute("bot.example.com")
if err := a.WakeWorker(rt); err != nil {
t.Fatal(err)
@@ -152,9 +150,7 @@ func TestWorkerTerminationProvesItsHostCgroup(t *testing.T) {
}
})
t.Run("a failed worker wake keeps its lease", func(t *testing.T) {
- old := sidecarSettle
- sidecarSettle = 20 * time.Millisecond
- restoreKnob(t, func() { sidecarSettle = old })
+ setKnob(t, &sidecarSettle, 20*time.Millisecond)
a, b, _, _ := testActivator(t, time.Hour)
a.gens = true
hk := &hostKillBackend{fakeBackend: b, bad: true}
@@ -189,9 +185,7 @@ func TestWorkerTerminationProvesItsHostCgroup(t *testing.T) {
waitFor(t, "the lease given back", given)
})
t.Run("a respawn execs nothing beside the old child", func(t *testing.T) {
- old := sidecarSettle
- sidecarSettle = 20 * time.Millisecond
- restoreKnob(t, func() { sidecarSettle = old })
+ setKnob(t, &sidecarSettle, 20*time.Millisecond)
a, b, clk, _ := testActivator(t, time.Hour)
a.gens = true
hk := &hostKillBackend{fakeBackend: b}
diff --git a/internal/activator/worker_generations_test.go b/internal/activator/worker_generations_test.go
index 54dc0a86a..3649faa51 100644
--- a/internal/activator/worker_generations_test.go
+++ b/internal/activator/worker_generations_test.go
@@ -167,7 +167,7 @@ func TestWorkerCapturedBuildSurvivesARestageOfItsReusedName(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &realWorkerBackend{fakeBackend: fb, exec: eb}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &realWorkerBackend{fakeBackend: fb, exec: eb}, reg)
a.liveVer = eb.LiveVersion
a.GenerationsFile = release.GenerationsPath(dataDir)
t.Cleanup(func() { a.Shutdown(context.Background()) })
@@ -450,7 +450,7 @@ func TestWorkerFromAChainedLinkIsPublishedByPath(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, &realWorkerBackend{fakeBackend: fb, exec: eb}, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, &realWorkerBackend{fakeBackend: fb, exec: eb}, reg)
a.liveVer = eb.LiveVersion
a.GenerationsFile = release.GenerationsPath(t.TempDir())
t.Cleanup(func() { a.Shutdown(context.Background()) })
diff --git a/internal/activator/worker_identity_test.go b/internal/activator/worker_identity_test.go
index e5de224dd..b6638c948 100644
--- a/internal/activator/worker_identity_test.go
+++ b/internal/activator/worker_identity_test.go
@@ -26,7 +26,7 @@ func stagedActivator(t *testing.T) (*Service, *stagedFake, *fakeClock, *registry
if err != nil {
t.Fatalf("open registry: %v", err)
}
- a := newTrackedService(Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
+ a := newTrackedService(t, Config{Bucket: "test-bucket", Idle: time.Hour}, b, reg)
a.now = clk.now
var ver atomic.Value
ver.Store("v1")
diff --git a/internal/activator/worker_respawn_exec_test.go b/internal/activator/worker_respawn_exec_test.go
index eee82b8e2..2346865fd 100644
--- a/internal/activator/worker_respawn_exec_test.go
+++ b/internal/activator/worker_respawn_exec_test.go
@@ -134,9 +134,7 @@ func TestAShedRespawnChildIsRetainedUntilItsExitIsProven(t *testing.T) {
name := map[bool]string{false: "the shed Stop fails", true: "the shed Stop blocks past the stop's respawn wait"}[blocked]
t.Run(name, func(t *testing.T) {
if blocked {
- old := respawnJoinBound
- respawnJoinBound = 100 * time.Millisecond
- restoreKnob(t, func() { respawnJoinBound = old })
+ setKnob(t, &respawnJoinBound, 100*time.Millisecond)
}
a, b, _, _, ver := stagedActivator(t)
a.gens = false
diff --git a/internal/activator/worker_retained_pin_test.go b/internal/activator/worker_retained_pin_test.go
index 26586fac2..57adaa87c 100644
--- a/internal/activator/worker_retained_pin_test.go
+++ b/internal/activator/worker_retained_pin_test.go
@@ -67,9 +67,7 @@ func generationsHost(t *testing.T, a *Service, path, host string) []string {
// (root's pin set) until the proof holds. The process may still run those
// bytes, so root must not restage or sweep them.
func TestARetainedFailedWorkerWakeKeepsItsBuildPinned(t *testing.T) {
- old := sidecarSettle
- sidecarSettle = 20 * time.Millisecond
- restoreKnob(t, func() { sidecarSettle = old })
+ setKnob(t, &sidecarSettle, 20*time.Millisecond)
a, b, _, _, _ := stagedActivator(t)
a.gens = true
hk := &stagedHostKill{stagedFake: b, bad: true}
diff --git a/internal/activator/workerswap_test.go b/internal/activator/workerswap_test.go
index af1de16bb..b1e1c6cd2 100644
--- a/internal/activator/workerswap_test.go
+++ b/internal/activator/workerswap_test.go
@@ -229,9 +229,7 @@ func TestReplaceWorkerRunningChildIsNotACleanExit(t *testing.T) {
// "timed out" for a wake that went on to succeed. A wake that is not a
// first wake still gives up at the ordinary bound.
func TestWakeWorkerWaitsOutAFirstWakeFallback(t *testing.T) {
- old := wakeWaitBound
- wakeWaitBound = 100 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 100*time.Millisecond)
for _, tc := range []struct {
name string
firstWake bool
@@ -993,15 +991,13 @@ func TestAnExitedOneShotIsGoodOnlyAfterACleanPark(t *testing.T) {
func awaitExtensionSeam(t *testing.T, a *Service, release chan struct{}) *atomic.Int32 {
t.Helper()
var calls atomic.Int32
- old := wakeBoundExtended
- wakeBoundExtended = func() {
+ setKnob(t, &wakeBoundExtended, func() {
if calls.Add(1) != 1 {
return
}
close(release)
waitFor(t, "the failed wake to delete its entry", func() bool { return a.entryCount() == 0 })
- }
- restoreKnob(t, func() { wakeBoundExtended = old })
+ })
return &calls
}
@@ -1011,9 +1007,7 @@ func awaitExtensionSeam(t *testing.T, a *Service, release chan struct{}) *atomic
// entry, so the waiter found nothing and started a second wake, a second
// lease acquire and a second spawn (#184's shape).
func TestWakeWorkerAWakeFailingInsideTheExtensionStartsNoSecond(t *testing.T) {
- old := wakeWaitBound
- wakeWaitBound = 50 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 50*time.Millisecond)
a, b, _, _, _ := stagedActivator(t)
a.gens = true
a.backend = &plannedHostKill{stagedFake: b}
@@ -1047,9 +1041,7 @@ func TestWakeWorkerAWakeFailingInsideTheExtensionStartsNoSecond(t *testing.T) {
// The same window for a request (begin): the failed wake reports to its
// waiter, and nothing wakes the instance a second time.
func TestBeginAWakeFailingInsideTheExtensionStartsNoSecond(t *testing.T) {
- old := wakeWaitBound
- wakeWaitBound = 50 * time.Millisecond
- restoreKnob(t, func() { wakeWaitBound = old })
+ setKnob(t, &wakeWaitBound, 50*time.Millisecond)
next := stagedID(t, t.TempDir(), "v2")
a, b, _ := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true})
boom := errors.New("GET / answered 500")
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 33351eace..76466914c 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -252,3 +252,4 @@ plan14-root-reads-staticcheck-sa1012.tsv 5fcd060180e923773dad3faee7cc60ee250779a
plan14-root-reads-staticcheck-sa1019.tsv f9be26c06eb1c844b91a75f65faa51997048cb2900f3ed078be2ae28c65c0e98
plan14-root-reads-small-fixes-1246-1248.tsv c6d366dcf2211b714977b7a69180289555b362dfe5f36a5780af90b5ece82998
plan14-root-reads-edge-ppv2-idle.tsv 5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4
+plan14-root-reads-race-activator-1249.tsv c2580d30b6bbfa03d65a5a7dc66dd21bd3d88f16d2672edf104c082ec140d6d7
diff --git a/internal/provision/testdata/plan14-root-reads-race-activator-1249.tsv b/internal/provision/testdata/plan14-root-reads-race-activator-1249.tsv
index b2f1a479c..8fc23a183 100644
--- a/internal/provision/testdata/plan14-root-reads-race-activator-1249.tsv
+++ b/internal/provision/testdata/plan14-root-reads-race-activator-1249.tsv
@@ -1,6 +1,6 @@
# Census overlay race-activator-1249, written by census-propose (#369). census-ruling-race-activator-1249, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-race-activator-1249.md.
# 2 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
@legacy bc0388a6fb4e92feb0531f2634846393085e02e42b07bd05a175b2f4708586b1 internal/activator/rootfs_service.go Service.residentLeaseShort legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): stops every one-shot unit that may run, whatever the entry's state, off a.mu; begins a resident's graceful stop only while it is awake, as before; in memory only;rev3=census-ruling-race-activator-1249;basis=counts each one-shot stop in leaseWork around the same call; no read added, same stops in the same order whole:Route@188,whole:Route@377 920a67613146ad8e71423314ce799d855c0e654453582d2a03c37e19925888dd
-internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: one more in-memory field, replicaFailed (host to the permit whose successor failed here, under mu), so that step only proves what it kept; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F fix round 3 (#511 F11): two hook fields, MarkReplicaRelease and ReplicaReleaseMark (the failure book's per-host release mark on this box's disk). No read site.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): one in-memory field, heldSeen (host to the last held release attempt, error class and when it was met), under the existing wakeFailMu. Declaration only, no read.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (27d3f501) adds the background atomic.Int64 field that tests wait on; this branch keeps its replica fields. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 3: adds replicaSwitched, an in-memory map of the permit each set row switched under (host -> permit key, time, resident flag); no read added; #511 micro-fix P1b: adds replicaNoGen, an in-memory map (host -> permit key and when first seen) that is only the bound's clock for a restarted permit holder with no generation; no read added;rev3=census-ruling-stateless-replicas-4-drill1;basis=#511 drill 1 R20 bound (round 1: clock with start and last seen): one in-memory field, releaseConfigWaits (per host, a stateless release's config wait), under mu; no read;rev3=census-ruling-stateless-replicas-4-r28;basis=R28 review round 2 (#511): one field, retiringCopy, an atomic pointer to the edge's in-memory retired-copy check, handed over by edge.New (SetRetiringCopy); no read, no root decision;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent as carlos: four fields, fenceWatchers (sync.WaitGroup of running write-fence watchers) and three test seams nil in production (fenceWatchStarted, retainDB, wakeReturned). Declaration only, no read.;rev3=census-ruling-fleet-record-labels-m1;basis=fleet record labels R1/R2: actEntry gains checkpoint state (busy while CloseProven runs, unproven, named-once flag for C45), in-memory under a.mu; the worker gains fence pacing apart from crash backoff; Service gains test seams nil in production; declarations only, no read;rev3=census-ruling-race-activator-1249;basis=adds the leaseWork WaitGroup field, which counts lease watches for tests; no read added and production never waits on it 6a48976c47983eb497d81fb8c594b181e0485b8fb30e7a4bec712c12674fa8e8
+internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: one more in-memory field, replicaFailed (host to the permit whose successor failed here, under mu), so that step only proves what it kept; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F fix round 3 (#511 F11): two hook fields, MarkReplicaRelease and ReplicaReleaseMark (the failure book's per-host release mark on this box's disk). No read site.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): one in-memory field, heldSeen (host to the last held release attempt, error class and when it was met), under the existing wakeFailMu. Declaration only, no read.;rev3=census-ruling-stateless-replicas-4-merge-main;basis=Merge of main 5fac2ff1: both sides changed it. Main (27d3f501) adds the background atomic.Int64 field that tests wait on; this branch keeps its replica fields. Both kept as-is; no read added.;rev3=census-ruling-stateless-replicas-4-final;basis=#511 final wave item 3: adds replicaSwitched, an in-memory map of the permit each set row switched under (host -> permit key, time, resident flag); no read added; #511 micro-fix P1b: adds replicaNoGen, an in-memory map (host -> permit key and when first seen) that is only the bound's clock for a restarted permit holder with no generation; no read added;rev3=census-ruling-stateless-replicas-4-drill1;basis=#511 drill 1 R20 bound (round 1: clock with start and last seen): one in-memory field, releaseConfigWaits (per host, a stateless release's config wait), under mu; no read;rev3=census-ruling-stateless-replicas-4-r28;basis=R28 review round 2 (#511): one field, retiringCopy, an atomic pointer to the edge's in-memory retired-copy check, handed over by edge.New (SetRetiringCopy); no read, no root decision;rev3=census-ruling-g6-fence;basis=G6 F-C Task 3, the agent as carlos: four fields, fenceWatchers (sync.WaitGroup of running write-fence watchers) and three test seams nil in production (fenceWatchStarted, retainDB, wakeReturned). Declaration only, no read.;rev3=census-ruling-fleet-record-labels-m1;basis=fleet record labels R1/R2: actEntry gains checkpoint state (busy while CloseProven runs, unproven, named-once flag for C45), in-memory under a.mu; the worker gains fence pacing apart from crash backoff; Service gains test seams nil in production; declarations only, no read;rev3=census-ruling-race-activator-1249;basis=adds two test-only fields: leaseWork (a WaitGroup counting lease watches and the one-shot stops a short lease starts) and leaseWatchStop (a channel, nil in production, that a test closes to end every lease watch); no read added and production never waits on or closes either 675157ea15154f73e7fee1fc32d05c18655fac1d98e6e51a14e23082f780ade9
internal/activator/rootfs_service.go Service.residentLeaseShort legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): stops every one-shot unit that may run, whatever the entry's state, off a.mu; begins a resident's graceful stop only while it is awake, as before; in memory only;rev3=census-ruling-race-activator-1249;basis=counts each one-shot stop in leaseWork around the same call; no read added, same stops in the same order whole:Route@188,whole:Route@377 920a67613146ad8e71423314ce799d855c0e654453582d2a03c37e19925888dd
-@coverage internal/activator e0f6472dad54c3189d53cc507f38ed6afce6015a141992c79a213256aa2b0c01
+@coverage internal/activator 78e0076e92a3a9bbe9c94fc9e17b3625bab138ca75c4121f20eea3e35822f9d7