region HA DR-5: finish departures when nobody serves the pool
A departure whose host locks name the departed box no longer waits for an adopter that cannot exist: when the lock is released or past expiry, this box could adopt it but for the pool, and no live box in the complete departure view serves (or may serve) that pool, the host is recorded unserved. No import, no lock write, no page (spec §7.5). Timing: a step scans every due departure (up to 8), an inventory request inside the 60 s spacing is deferred instead of dropped, and the rescan is due at once. The N6 reproduction finishes in 1m02s-2m02s (bound 3 min); reverting the timing gives 3m02s-3m32s, and without the rule member A never finishes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md+6 −1docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md+2 −0internal/edge/hadepartures.go+2 −0internal/hadeparture/pools_test.go+25 −0internal/hadeparture/types.go+25 −0internal/host/changeindex.go+49 −7internal/host/changeindex_nudger_dr5_test.go+68 −0internal/host/hadepartures.go+21 −2internal/host/hadepartures_dr5_test.go+514 −0internal/host/hadepartures_g3_test.go+18 −9internal/host/hadepartures_scan.go+92 −4
CI failed — run details
Intent
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="4d2c35b0-a724-4a31-a7c5-2d844bc21aca"> Agent manager 8a3d302: DR-5 §7.5 + plan APPROVED, build it. Four conditions appended to ~/.cache/region-ha-dr5/REPORT.md (fixed-box prerequisite list for adi; no new periodic S3 polling; timer follow-up filed as G5 on #421; production-wired N6 test with expiry and missing-served_pools variants). </paseo-system>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="f91f1480-6309-4ee4-8cdb-fdb5272a0ff9"> Agent manager 8a3d302: note appended to ~/.cache/region-ha-dr5/REPORT.md about the stuck dev g-428c05c1 (no UK HA box left to scan it). Answer there; don't touch dev. </paseo-system>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="ea924d0b-4c5f-4cb7-846e-cc421001c4a5"> Agent manager 8a3d302: runbook section goes on a separate docs branch after the code merges, with copy review by Paul then. Answer in REPORT.md. Carry on with the N6 test. </paseo-system>
Attributed to this commit: 181 g CO₂e (19,408,791 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fix/region-ha-dr5, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md b/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md| index 8f7d5621a..1607ebf23 100644 |
| --- a/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md |
| +++ b/docs/superpowers/plans/2026-11-08-region-ha-dr5-unserved-departures.md |
| @@ -37,6 +37,10 @@ Negative cases in the same file: |
| - `inventoryNudger.request`: a request inside the 60 s spacing records `pending` and arms one timer for the end of the spacing; `begin` is unchanged, so the spacing and the three-round limit hold. Unit tests on the nudger with a fake clock. |
| - `ScanPass`: when a clean adoption pass sets `Rescan`, the next attempt is now, not +30 s. |
| +### S3 requests (8a3d302 condition 2) |
| + |
| +No new periodic S3 request. The unserved rule reads only the in-memory departure view and the local journal. The step loop scans only departures already due. Per departure, as before: one lock LIST per walk (one page per 1,000 locks) plus one GET per in-scope lock, for the adoption walk and the rescan (two walks); then at finalize one edges GET, one conditional DELETE, one index write, one status GET and one DELETE. The rescan now starts at once rather than 30 s later; its requests are the same. The deferred inventory round replaces a dropped one: rounds stay at most one per 60 s and three per piece of evidence, so a departure costs at most three early rounds, as before. |
| + |
| ## Task 4: gates |
| - Targeted tests: `go test ./internal/host/ -run 'Departure|HADeparture|Nudger' -count=1`, `./internal/edge/ -run Departure`, `./internal/hadeparture/`. |
| @@ -48,5 +52,6 @@ Negative cases in the same file: |
| ## Out of scope |
| -- A new pool server scanning for unserved hosts (follow-up on #421). |
| +- A new pool server scanning for unserved hosts: G5 item on #421 (8a3d302 condition 3). |
| +- Retiring leftovers in a region with no HA box left (dev g-428c05c1): hand step and switch-off card rule, runbook on a separate docs branch after this merges (8a3d302). |
| - Any page or operator text: the new line is a diagnostic. |
diff --git a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md| index 478be3ae4..31e0ac505 100644 |
| --- a/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md |
| @@ -350,6 +350,8 @@ An unserved host gets no import, and its lock is not touched. The departure then |
| **Who finalizes.** Every HA box that enrolled the departure, as today; no new role. The departure controller already runs on every HA box, holds the termination proof and does the scan. Finalizing is idempotent: the deletes are conditional, and a box that finds the edges file gone moves on. The deployment housekeeper was considered and rejected. It is one elected fixed box and would add a dependency to every departure for a case the scan rule covers. A fixed-box-only rule was rejected too: a surviving member that does not serve the pool is in the same position as dennis. |
| +**Prerequisite: a fixed box that finishes departures.** The rule runs only on a box whose termination recovery is running. A fixed box needs, in `host.env`: `CARLOS_REGION_HA=1`; `CARLOS_TERMINATION_QUEUE_URL` (the region's terminations queue, same account and region as the box); `CARLOS_DEPLOYMENT_BUCKET`; `CARLOS_HIBERNATE_BUCKET` and `CARLOS_HIBERNATE_REGION` (the region's data bucket, in the box's own AWS region); a parseable `CARLOS_SECRETS_KEY` (its fingerprint is the scope); `CARLOS_REGION` as the members have it (empty in the home region); and `CARLOS_HA_FIXED_BOX_IDENTITIES` naming every other fixed box of the region. Its role needs the region-host grants: receive and delete on the queue, `ec2:DescribeInstances`, read and list under the hibernate prefix, put and get on `control/terminations/`, and delete on `control/edges/*` and `status/boxes/*`. The journal line "Termination recovery is running." confirms it. A fixed box without these (dennis after U1) finishes nothing, and DR-5 cannot help it. |
| + |
| **What this does not change.** |
| - **Takeover.** No box acquires, renews or rewrites the lease of an unserved host. A later server of the pool acquires it as §9.4 says: a release marker is open to any box, and an expired lock needs the persisted termination proof (N-HA16). "Takeover only after proof and expiry" stands. |
| - **Serving.** Nothing here makes a box serve a pool it does not serve. Requests for the host keep failing until a box serving its pool exists, as they did the moment the pool's last server left. |
diff --git a/internal/edge/hadepartures.go b/internal/edge/hadepartures.go| index df0420809..a95dc8206 100644 |
| --- a/internal/edge/hadepartures.go |
| +++ b/internal/edge/hadepartures.go |
| @@ -28,6 +28,8 @@ func (m *homeMap) departureView() DepartureView { |
| _ = json.Unmarshal(f.Generation, &gen) |
| at, _ := time.Parse(time.RFC3339Nano, gen) |
| o := hadeparture.BoxObservation{Box: hadeparture.Box{Ref: f.Box, Scope: hadeparture.Scope{CloudRegion: f.Region, Placement: f.Placement, DataBucket: f.DataBucket, SecretsKeyFP: f.SecretsKeyFP}}, Known: true, PlacementNull: f.placementNull, EdgesKey: key, EdgesETag: f.etag, Generation: gen, PublishedAt: at} |
| + pools, known := f.ServedPools.Pools() |
| + o.ServedPools, o.PoolsKnown = hadeparture.EncodePools(pools), known |
| if f.Box == m.self { |
| v.Self = o |
| } else { |
diff --git a/internal/hadeparture/pools_test.go b/internal/hadeparture/pools_test.go| new file mode 100644 |
| index 000000000..30c7d2df8 |
| --- /dev/null |
| +++ b/internal/hadeparture/pools_test.go |
| @@ -0,0 +1,25 @@ |
| +package hadeparture |
| + |
| +import "testing" |
| + |
| +func TestServesEncodedPools(t *testing.T) { |
| + for _, tc := range []struct { |
| + pools []string |
| + known bool |
| + pool string |
| + want bool |
| + }{ |
| + {[]string{""}, true, "", true}, |
| + {[]string{""}, true, "ha", false}, |
| + {[]string{}, true, "", false}, |
| + {[]string{"ha"}, true, "", false}, |
| + {[]string{"", "ha"}, true, "ha", true}, |
| + {[]string{"hapair"}, true, "ha", false}, |
| + {[]string{"ha"}, false, "ha", false}, |
| + } { |
| + o := BoxObservation{ServedPools: EncodePools(tc.pools), PoolsKnown: tc.known} |
| + if got := o.Serves(tc.pool); got != tc.want { |
| + t.Errorf("%q known=%v serves %q = %v", tc.pools, tc.known, tc.pool, got) |
| + } |
| + } |
| +} |
diff --git a/internal/hadeparture/types.go b/internal/hadeparture/types.go| index bcc23e4a5..184936472 100644 |
| --- a/internal/hadeparture/types.go |
| +++ b/internal/hadeparture/types.go |
| @@ -2,6 +2,7 @@ package hadeparture |
| import ( |
| "context" |
| + "strings" |
| "time" |
| ) |
| @@ -24,7 +25,31 @@ type BoxObservation struct { |
| PlacementNull bool |
| EdgesKey, EdgesETag, Generation string |
| PublishedAt time.Time |
| + // ServedPools is the box's published served_pools, encoded by |
| + // EncodePools so the observation stays comparable. PoolsKnown is false |
| + // when the field is missing or malformed (DR-5: a possible server). |
| + ServedPools string |
| + PoolsKnown bool |
| } |
| + |
| +// EncodePools writes each pool as "|"+name, so the shared pool "" and an |
| +// empty list stay distinct. Pool names never contain "|". |
| +func EncodePools(pools []string) string { |
| + var b strings.Builder |
| + for _, p := range pools { |
| + b.WriteString("|") |
| + b.WriteString(p) |
| + } |
| + return b.String() |
| +} |
| + |
| +// Serves reports whether the observed box publishes pool among known |
| +// served pools. Unknown evidence serves nothing here; callers treat |
| +// !PoolsKnown as a possible server themselves. |
| +func (o BoxObservation) Serves(pool string) bool { |
| + return o.PoolsKnown && strings.Contains(o.ServedPools+"|", "|"+pool+"|") |
| +} |
| + |
| type Departure struct { |
| ID string |
| Box Box |
diff --git a/internal/host/changeindex.go b/internal/host/changeindex.go| index 954994fd3..120d66033 100644 |
| --- a/internal/host/changeindex.go |
| +++ b/internal/host/changeindex.go |
| @@ -193,16 +193,21 @@ func recordViewBackstop(ctx context.Context, v *provision.RecordView, due *atomi |
| // Three start times cover every departure observed before those rounds began. |
| // Keeping only those times bounds memory even when another path abandons or |
| // acknowledges a departure. A new controller does not reset the process budget. |
| +// A request inside the 60 s spacing is kept and started when the spacing ends |
| +// (DR-5), so departure evidence arriving just after a round still gets one; |
| +// the spacing and the three-round limit are unchanged. |
| type inventoryNudger struct { |
| mu sync.Mutex |
| wake chan struct{} |
| now func() time.Time |
| + after func(time.Duration, func()) |
| starts [3]time.Time |
| pending time.Time |
| + armed bool |
| } |
| func newInventoryNudger(now func() time.Time) *inventoryNudger { |
| - return &inventoryNudger{wake: make(chan struct{}, 1), now: now} |
| + return &inventoryNudger{wake: make(chan struct{}, 1), now: now, after: func(d time.Duration, f func()) { time.AfterFunc(d, f) }} |
| } |
| var departureInventoryNudges = newInventoryNudger(time.Now) |
| @@ -211,19 +216,48 @@ func (n *inventoryNudger) eligible(observed, now time.Time) bool { |
| return now.After(observed) && !n.starts[0].After(observed) && (n.starts[2].IsZero() || now.Sub(n.starts[2]) >= time.Minute) |
| } |
| +// spaced reports a request refused only by the 60 s spacing. |
| +func (n *inventoryNudger) spaced(observed, now time.Time) bool { |
| + return now.After(observed) && !n.starts[0].After(observed) && !n.starts[2].IsZero() && now.Sub(n.starts[2]) < time.Minute |
| +} |
| + |
| +func (n *inventoryNudger) signal() { |
| + select { |
| + case n.wake <- struct{}{}: |
| + default: |
| + } |
| +} |
| + |
| +// deferLocked arms one timer for the end of the spacing. Callers hold mu. |
| +func (n *inventoryNudger) deferLocked(now time.Time) { |
| + if n.armed { |
| + return |
| + } |
| + n.armed = true |
| + n.after(n.starts[2].Add(time.Minute).Sub(now), func() { |
| + n.mu.Lock() |
| + n.armed = false |
| + n.mu.Unlock() |
| + n.signal() |
| + }) |
| +} |
| + |
| func (n *inventoryNudger) request(observed time.Time) { |
| n.mu.Lock() |
| defer n.mu.Unlock() |
| - if !n.eligible(observed, n.now()) { |
| + now := n.now() |
| + eligible := n.eligible(observed, now) |
| + if !eligible && !n.spaced(observed, now) { |
| return |
| } |
| if observed.After(n.pending) { |
| n.pending = observed |
| } |
| - select { |
| - case n.wake <- struct{}{}: |
| - default: |
| + if eligible { |
| + n.signal() |
| + return |
| } |
| + n.deferLocked(now) |
| } |
| func (n *inventoryNudger) begin() bool { |
| @@ -231,10 +265,18 @@ func (n *inventoryNudger) begin() bool { |
| defer n.mu.Unlock() |
| now := n.now() |
| observed := n.pending |
| - n.pending = time.Time{} |
| - if observed.IsZero() || !n.eligible(observed, now) { |
| + if observed.IsZero() { |
| return false |
| } |
| + if !n.eligible(observed, now) { |
| + if n.spaced(observed, now) { |
| + n.deferLocked(now) |
| + return false |
| + } |
| + n.pending = time.Time{} |
| + return false |
| + } |
| + n.pending = time.Time{} |
| n.starts[0], n.starts[1], n.starts[2] = n.starts[1], n.starts[2], now |
| return true |
| } |
diff --git a/internal/host/changeindex_nudger_dr5_test.go b/internal/host/changeindex_nudger_dr5_test.go| new file mode 100644 |
| index 000000000..8a18c4423 |
| --- /dev/null |
| +++ b/internal/host/changeindex_nudger_dr5_test.go |
| @@ -0,0 +1,68 @@ |
| +package host |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +// DR-5: a request inside the 60 s spacing is deferred, not dropped; the |
| +// spacing and the three-round limit still hold. |
| +func TestInventoryNudgerDefersSpacedRequest(t *testing.T) { |
| + now := time.Unix(1_000_000, 0) |
| + n := newInventoryNudger(func() time.Time { return now }) |
| + var due time.Time |
| + var fire func() |
| + n.after = func(d time.Duration, f func()) { due, fire = now.Add(d), f } |
| + drain := func() bool { |
| + select { |
| + case <-n.wake: |
| + return true |
| + default: |
| + return false |
| + } |
| + } |
| + obs1 := now.Add(-time.Second) |
| + n.request(obs1) |
| + if !drain() || !n.begin() { |
| + t.Fatal("first request did not start a round") |
| + } |
| + round1 := now |
| + now = now.Add(30 * time.Second) |
| + obs2 := now.Add(-time.Millisecond) |
| + n.request(obs2) |
| + if drain() { |
| + t.Fatal("spacing ignored") |
| + } |
| + if fire == nil || !due.Equal(round1.Add(time.Minute)) { |
| + t.Fatalf("not deferred to the end of the spacing: due=%v", due) |
| + } |
| + now = now.Add(10 * time.Second) |
| + n.signal() // an early wake inside the spacing keeps the request |
| + if !drain() || n.begin() { |
| + t.Fatal("round started inside the spacing") |
| + } |
| + now = due |
| + f := fire |
| + fire = nil |
| + f() |
| + if !drain() || !n.begin() { |
| + t.Fatal("deferred request did not start a round at the end of the spacing") |
| + } |
| + if !n.starts[2].Equal(due) { |
| + t.Fatalf("round start %v, want %v", n.starts[2], due) |
| + } |
| + // Three rounds have started after obs2: a later request for it is dropped. |
| + for range 2 { |
| + now = now.Add(time.Minute) |
| + n.request(now.Add(-time.Millisecond)) |
| + if !drain() || !n.begin() { |
| + t.Fatal("eligible request refused") |
| + } |
| + } |
| + now = now.Add(10 * time.Second) |
| + fire = nil |
| + n.request(obs2) |
| + if drain() || fire != nil { |
| + t.Fatal("evidence past three rounds requested again") |
| + } |
| +} |
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go| index 61f539664..7e0540566 100644 |
| --- a/internal/host/hadepartures.go |
| +++ b/internal/host/hadepartures.go |
| @@ -24,6 +24,9 @@ import ( |
| var errDepartureScope = errors.New("ha_departure_scope_invalid") |
| +// departuresPerStep bounds the scan passes one step runs (DR-5). |
| +const departuresPerStep = 8 |
| + |
| type LocalPolicy struct { |
| Scope hadeparture.Scope |
| Pools []string |
| @@ -474,8 +477,24 @@ func (c *Controller) step(ctx context.Context) error { |
| } |
| } |
| if c.cfg.NewReader != nil { |
| - _, err := c.ScanPass(ctx) |
| - return err |
| + // DR-5: scan every due departure in this step (at most |
| + // departuresPerStep), so departures never take turns across steps. |
| + // Each pass reserves its departure first, so the loop advances. |
| + // One departure's error does not hold the others. |
| + var errs error |
| + for range departuresPerStep { |
| + due, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1) |
| + if err != nil || len(due) == 0 || ctx.Err() != nil { |
| + return errors.Join(errs, err) |
| + } |
| + worked, err := c.ScanPass(ctx) |
| + errs = errors.Join(errs, err) |
| + if !worked && err == nil { |
| + // Not admitted, or nothing reserved: stop rather than spin. |
| + break |
| + } |
| + } |
| + return errs |
| } |
| pending, err := c.cfg.Registry.PendingDepartures(ctx, c.now(), 1) |
| if err != nil { |
diff --git a/internal/host/hadepartures_dr5_test.go b/internal/host/hadepartures_dr5_test.go| new file mode 100644 |
| index 000000000..908bfde55 |
| --- /dev/null |
| +++ b/internal/host/hadepartures_dr5_test.go |
| @@ -0,0 +1,514 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/route53" |
| + r53types "github.com/aws/aws-sdk-go-v2/service/route53/types" |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/steering" |
| +) |
| + |
| +// dr5Rig is dev rehearsal N6 (2026-11-08) on the production wiring of |
| +// newG3Departure: the whole group (members A and B) is terminated and both |
| +// departures are enrolled at T. Self is a fixed box with no named pools. |
| +// A was the last releaser of the pool "ha" hosts; B released the one |
| +// shared-pool host. Inventory rounds run only when the scan requests them, |
| +// through the real inventoryNudger on the fake clock, and each walk takes |
| +// 20 s. Steps run every 30 s, and a record is rewritten every 30 s. |
| +type dr5Rig struct { |
| + *g3Departure |
| + b hadeparture.Box |
| + bID string |
| + bEdgesKey string |
| + haHosts []string |
| + locks map[string][]byte |
| + nudger *inventoryNudger |
| + deferredAt time.Time |
| + deferredFn func() |
| + walkFrom time.Time |
| + walkDone time.Time |
| + unserved int |
| + logs []string |
| +} |
| + |
| +const ( |
| + dr5Walk = 20 * time.Second |
| + dr5Bound = 3 * time.Minute |
| +) |
| + |
| +type dr5Options struct { |
| + heldUntil time.Duration // >0: the first "ha" lock is held by A until T+heldUntil |
| + livePeer string // "": none; "serves": served_pools ["ha"]; "unknown": served_pools missing |
| + incompleteView bool |
| + otherPlacement bool // A also released a pool "ha" host placed in another region |
| +} |
| + |
| +func newDR5Rig(t *testing.T, o dr5Options) *dr5Rig { |
| + t.Helper() |
| + x := &dr5Rig{g3Departure: newG3Departure(t, 1), locks: map[string][]byte{}} |
| + a := &x.a |
| + ctx := t.Context() |
| + x.c.cfg.Logf = func(f string, args ...any) { |
| + line := fmt.Sprintf(f, args...) |
| + x.logs = append(x.logs, line) |
| + if strings.HasPrefix(line, "ha_departure_unserved ") { |
| + x.unserved++ |
| + } |
| + } |
| + // Member B: identity, member-shaped edges file, status snapshot. |
| + x.b = hadeparture.Box{Account: a.Self.Account, InstanceID: "i-4123456789abcdef0", Scope: a.Self.Scope} |
| + x.b.Ref = groupReferenceOf(x.b.Account, x.b.InstanceID) |
| + _, raw := x.signer.Record(t, x.b.Ref, x.b.Account, x.b.Scope.CloudRegion, x.b.InstanceID) |
| + if _, err := x.store.Put(ctx, boxid.Key(x.b.Ref), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.bEdgesKey = "control/edges/" + x.b.Ref + ".json" |
| + bTag, err := x.store.Put(ctx, x.bEdgesKey, dr5MemberEdges(x.b), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, ref := range []string{x.dead.Ref, x.b.Ref} { |
| + if _, err = x.store.Put(ctx, "status/boxes/"+ref+".json", []byte(`{"v":1}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // Republish A's edges file in member shape (pool "ha" only, not the |
| + // shared pool), as members publish it. The scan rebinds the new ETag. |
| + if x.edgesTag, err = x.store.Put(ctx, x.edgesKey, dr5MemberEdges(x.dead), x.edgesTag); err != nil { |
| + t.Fatal(err) |
| + } |
| + obs, err := x.c.cfg.Identities.Observe(ctx, hadeparture.BoxObservation{Known: true, Box: x.b, EdgesKey: x.bEdgesKey, EdgesETag: bTag}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + x.b = obs.Box |
| + if err = x.c.Enqueue(ctx, obs); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.bID = departureID(x.c.cfg.DeploymentBucket, obs.Box) |
| + // The shared-pool host (record 0) was released by B: self adopts it. |
| + x.putMarker(t, x.records[0].Host, x.b, 3) |
| + // Pool "ha" hosts released by A, as N6 found them. |
| + n := 2 |
| + if o.otherPlacement { |
| + n = 3 |
| + } |
| + for i := range n { |
| + rec := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: fmt.Sprintf("dr5-ha-%d.example.com", i), Channel: "stable", Pool: "ha", HA: true, CreatedAt: x.start.Add(-time.Hour)} |
| + if i == 2 { |
| + rec.Region = "elsewhere" |
| + } |
| + if err = provision.CreateRecord(ctx, x.store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.records = append(x.records, rec) |
| + x.haHosts = append(x.haHosts, rec.Host) |
| + if i == 0 && o.heldUntil > 0 { |
| + x.putHeld(t, rec.Host, x.dead, 6, x.start.Add(o.heldUntil)) |
| + continue |
| + } |
| + x.putMarker(t, rec.Host, x.dead, int64(4+i)) |
| + } |
| + // A churn target outside this placement, written every 30 s. |
| + churn := provision.Record{Schema: 1, Account: "bab", App: "shop", Host: "dr5-churn.example.com", Channel: "stable", Region: "elsewhere", CreatedAt: x.start.Add(-time.Hour)} |
| + if err = provision.CreateRecord(ctx, x.store, churn); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.records = append(x.records, churn) |
| + x.reconcile(t) |
| + // The departure view the edge folds from the edges files. |
| + view := hadeparture.DepartureView{Complete: !o.incompleteView, Self: hadeparture.BoxObservation{Known: true, Box: a.Self, EdgesKey: "control/edges/" + a.Self.Ref + ".json", ServedPools: hadeparture.EncodePools([]string{""}), PoolsKnown: true}} |
| + for _, m := range []hadeparture.Box{x.dead, x.b} { |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: m.Ref, Scope: m.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + } |
| + switch o.livePeer { |
| + case "serves": |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: x.peer.Ref, Scope: x.peer.Scope}, ServedPools: hadeparture.EncodePools([]string{"ha"}), PoolsKnown: true}) |
| + case "unknown": |
| + view.Peers = append(view.Peers, hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: x.peer.Ref, Scope: x.peer.Scope}}) |
| + } |
| + if err = x.c.Tick(ctx, view); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Inventory rounds only on request, through the production nudger. The |
| + // nudger's clock runs 1 ms ahead: in production the request follows the |
| + // observation it carries by the pass's own I/O. |
| + x.nudger = newInventoryNudger(func() time.Time { return x.now.Add(time.Millisecond) }) |
| + x.nudger.after = func(d time.Duration, f func()) { x.deferredAt, x.deferredFn = x.now.Add(d), f } |
| + x.c.cfg.RequestInventory = func(_ context.Context, observed time.Time) { x.nudger.request(observed) } |
| + for _, h := range x.haHosts { |
| + x.locks[h] = x.lockBody(t, h) |
| + } |
| + return x |
| +} |
| + |
| +func dr5MemberEdges(b hadeparture.Box) []byte { |
| + raw, _ := json.Marshal(edgesFile{V: 1, Box: b.Ref, BoxID: b.Ref, Region: b.Scope.CloudRegion, Placement: b.Scope.Placement, DataBucket: b.Scope.DataBucket, SecretsKeyFP: b.Scope.SecretsKeyFP, EIP: "192.0.2.9", ServesSharedPool: false, NamedPools: []string{"ha"}, ServedPools: edgesfile.PoolEvidence(`["ha"]`)}) |
| + return raw |
| +} |
| + |
| +func (x *dr5Rig) putMarker(t *testing.T, host string, b hadeparture.Box, gen int64) { |
| + t.Helper() |
| + rec := x.record(t, host) |
| + entry, _ := provision.LifetimeEntryOf(rec) |
| + raw, _ := hafresh.MarkerBody(gen, hafresh.Marker{V: 1, Box: b.Ref, IID: b.InstanceID, Lifetime: entry.ID}) |
| + x.fx.PutLock(activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, host), raw) |
| +} |
| + |
| +func (x *dr5Rig) putHeld(t *testing.T, host string, b hadeparture.Box, gen int64, expiry time.Time) { |
| + t.Helper() |
| + raw, _ := json.Marshal(hafresh.Lock{Generation: gen, Owner: hafresh.OwnerFor(hafresh.Self{Ref: b.Ref, IID: b.InstanceID}, 1, true), ExpiresAt: expiry}) |
| + x.fx.PutLock(activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, host), raw) |
| +} |
| + |
| +func (x *dr5Rig) record(t *testing.T, host string) provision.Record { |
| + t.Helper() |
| + for _, r := range x.records { |
| + if r.Host == host { |
| + return r |
| + } |
| + } |
| + rec, _, err := provision.FindRecordByHost(t.Context(), x.store, host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return *rec |
| +} |
| + |
| +func (x *dr5Rig) lockBody(t *testing.T, host string) []byte { |
| + t.Helper() |
| + r, err := defaultDepartureReaderFor(t, x) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + v, err := r.ReadLock(t.Context(), x.a.Self.Scope.DataBucket, activator.HibernatePrefix(x.a.Backend.Cfg.Prefix, host)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(v.Lock) |
| + return append(raw, []byte(v.ETag)...) |
| +} |
| + |
| +func defaultDepartureReaderFor(t *testing.T, x *dr5Rig) (DepartureLockReader, error) { |
| + return x.c.cfg.NewReader(t.Context(), x.a.Self.Scope.CloudRegion) |
| +} |
| + |
| +// round is one inventory round whose walk began at from. |
| +func (x *dr5Rig) round(t *testing.T, from time.Time) { |
| + t.Helper() |
| + cfg := provision.ReconcileConfig{DataDir: x.a.Backend.DataDir, Departures: x.a.Inventory.Begin(from.String(), from, from, true), Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }} |
| + if err := provision.Reconcile(t.Context(), x.store, x.a.Registry, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.ReconcileSidecars(t.Context(), x.store, x.a.Registry, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (x *dr5Rig) churn(t *testing.T, n int) { |
| + t.Helper() |
| + rec := &x.records[len(x.records)-1] |
| + rec.Channel = fmt.Sprintf("churn-%d", n) |
| + key := provision.RecordKey(rec.Account, rec.App, rec.Host) |
| + _, tag, err := x.store.Get(t.Context(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(rec) |
| + if _, err = x.store.Put(t.Context(), key, raw, tag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (x *dr5Rig) phase(t *testing.T, id string) string { |
| + t.Helper() |
| + d, err := x.a.Registry.Departure(t.Context(), id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return d.Phase |
| +} |
| + |
| +// run drives the box for limit after T and returns each departure's |
| +// completion offset (0 = not complete). |
| +func (x *dr5Rig) run(t *testing.T, limit time.Duration, each func(at time.Duration)) (time.Duration, time.Duration) { |
| + t.Helper() |
| + var doneA, doneB time.Duration |
| + churns := 0 |
| + for x.now = x.start; !x.now.After(x.start.Add(limit)); x.now = x.now.Add(time.Second) { |
| + at := x.now.Sub(x.start) |
| + if x.deferredFn != nil && !x.now.Before(x.deferredAt) { |
| + f := x.deferredFn |
| + x.deferredFn = nil |
| + f() |
| + } |
| + select { |
| + case <-x.nudger.wake: |
| + if x.walkDone.IsZero() && x.nudger.begin() { |
| + x.walkFrom, x.walkDone = x.now, x.now.Add(dr5Walk) |
| + } |
| + default: |
| + } |
| + if !x.walkDone.IsZero() && !x.now.Before(x.walkDone) { |
| + x.round(t, x.walkFrom) |
| + x.walkDone = time.Time{} |
| + } |
| + if at%(30*time.Second) == 15*time.Second { |
| + churns++ |
| + x.churn(t, churns) |
| + } |
| + // Steps start just after T, the first one after enrollment. |
| + if at%(30*time.Second) == 2*time.Second { |
| + if err := x.c.step(t.Context()); err != nil && !errors.Is(err, errDeparturePending) { |
| + t.Fatalf("step at T+%s: %v", at, err) |
| + } |
| + if doneA == 0 && x.phase(t, x.id) == "complete" { |
| + doneA = at |
| + } |
| + if doneB == 0 && x.phase(t, x.bID) == "complete" { |
| + doneB = at |
| + } |
| + } |
| + if each != nil { |
| + each(at) |
| + } |
| + } |
| + return doneA, doneB |
| +} |
| + |
| +func (x *dr5Rig) gone(t *testing.T, key string) bool { |
| + t.Helper() |
| + _, _, err := x.store.Get(t.Context(), key) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return errors.Is(err, os.ErrNotExist) |
| +} |
| + |
| +func (x *dr5Rig) assertUntouched(t *testing.T) { |
| + t.Helper() |
| + for _, h := range x.haHosts[:min(2, len(x.haHosts))] { |
| + if got := x.lockBody(t, h); !bytes.Equal(got, x.locks[h]) { |
| + t.Fatalf("lock of %s changed:\n%s\n%s", h, x.locks[h], got) |
| + } |
| + rec := x.record(t, h) |
| + entry, _ := provision.LifetimeEntryOf(rec) |
| + for _, id := range []string{x.id, x.bID} { |
| + if _, adopted, err := x.a.Registry.HAAdoption(t.Context(), h, entry.ID, id); err != nil || adopted { |
| + t.Fatalf("pool ha host %s imported (departure %s): %v", h, id, err) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestDepartureDR5WholeGroupGone(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + o dr5Options |
| + }{ |
| + {"n6", dr5Options{}}, |
| + {"held_lock_expiry", dr5Options{heldUntil: 100 * time.Second}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + x := newDR5Rig(t, tc.o) |
| + // Steering as the housekeeper sees it before the departures. |
| + before := x.edgesBodies(t) |
| + r53 := &dr5Route53{} |
| + routes := []registry.Route{{Host: "shop.apps.example.com", Steering: "latency"}} |
| + if err := steering.ConvergeDeployment(t.Context(), r53, "Z1", routes, before, "apps.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + zone := r53.snapshot() |
| + doneA, doneB := x.run(t, 5*time.Minute, func(at time.Duration) { |
| + if tc.o.heldUntil > 0 && at < tc.o.heldUntil && x.phase(t, x.id) == "complete" { |
| + t.Fatalf("A finished at T+%s before its held lock expired at T+%s", at, tc.o.heldUntil) |
| + } |
| + }) |
| + t.Logf("A complete at T+%s, B complete at T+%s, unserved lines %d", doneA, doneB, x.unserved) |
| + if doneA == 0 || doneA > dr5Bound || doneB == 0 || doneB > dr5Bound { |
| + t.Fatalf("departures not finished within %s of proof: A=%s B=%s logs=%q", dr5Bound, doneA, doneB, x.logs) |
| + } |
| + for _, key := range []string{x.edgesKey, x.bEdgesKey, "status/boxes/" + x.dead.Ref + ".json", "status/boxes/" + x.b.Ref + ".json"} { |
| + if !x.gone(t, key) { |
| + t.Fatalf("%s left behind", key) |
| + } |
| + } |
| + if x.pages != 0 { |
| + t.Fatalf("paged %d times", x.pages) |
| + } |
| + if x.unserved < 2 { |
| + t.Fatalf("unserved hosts not logged: %d", x.unserved) |
| + } |
| + x.assertUntouched(t) |
| + // The shared-pool host B released was imported here. |
| + entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| + if _, adopted, err := x.a.Registry.HAAdoption(t.Context(), x.records[0].Host, entry.ID, x.bID); err != nil || !adopted { |
| + t.Fatalf("shared-pool host not adopted: %v", err) |
| + } |
| + // Route 53 steering is unchanged once both members are gone. |
| + r53.changes = 0 |
| + if err := steering.ConvergeDeployment(t.Context(), r53, "Z1", routes, x.edgesBodies(t), "apps.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r53.changes != 0 || r53.snapshot() != zone { |
| + t.Fatalf("steering changed: %d change batches\nbefore %s\nafter %s", r53.changes, zone, r53.snapshot()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDepartureDR5StaysBlocked(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + o dr5Options |
| + }{ |
| + {"live_peer_serves_pool", dr5Options{livePeer: "serves"}}, |
| + {"peer_served_pools_missing", dr5Options{livePeer: "unknown"}}, |
| + {"incomplete_view", dr5Options{incompleteView: true}}, |
| + {"other_placement", dr5Options{otherPlacement: true}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + x := newDR5Rig(t, tc.o) |
| + doneA, doneB := x.run(t, 5*time.Minute, nil) |
| + if doneA != 0 { |
| + t.Fatalf("A finished at T+%s with a possible adopter", doneA) |
| + } |
| + if doneB == 0 { |
| + t.Fatal("B (nothing unserved) did not finish") |
| + } |
| + if x.gone(t, x.edgesKey) || x.gone(t, "status/boxes/"+x.dead.Ref+".json") { |
| + t.Fatal("A's files retired while blocked") |
| + } |
| + if x.pages == 0 { |
| + t.Fatal("blocked departure did not page") |
| + } |
| + x.assertUntouched(t) |
| + }) |
| + } |
| +} |
| + |
| +// edgesBodies lists the edges files as the housekeeper loads them, plus |
| +// self's own (armed: shared pool, an EIP, an AWS region). |
| +func (x *dr5Rig) edgesBodies(t *testing.T) [][]byte { |
| + t.Helper() |
| + self, _ := json.Marshal(map[string]any{"v": 1, "box": x.a.Self.Ref, "eip": "192.0.2.1", "region": x.a.Self.Scope.CloudRegion, "serves_shared_pool": true}) |
| + out := [][]byte{self} |
| + for _, key := range []string{x.edgesKey, x.bEdgesKey} { |
| + raw, _, err := x.store.Get(t.Context(), key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, raw) |
| + } |
| + return out |
| +} |
| + |
| +// dr5Route53 is a minimal zone: record sets keyed by name and set id, and |
| +// health checks with tags. |
| +type dr5Route53 struct { |
| + records map[string]r53types.ResourceRecordSet |
| + checks []r53types.HealthCheck |
| + tags map[string][]r53types.Tag |
| + changes int |
| +} |
| + |
| +func (f *dr5Route53) snapshot() string { |
| + keys := make([]string, 0, len(f.records)) |
| + for k, rr := range f.records { |
| + raw, _ := json.Marshal(rr) |
| + keys = append(keys, k+"="+string(raw)) |
| + } |
| + slices.Sort(keys) |
| + return strings.Join(keys, "\n") |
| +} |
| + |
| +func (f *dr5Route53) ListResourceRecordSets(context.Context, *route53.ListResourceRecordSetsInput, ...func(*route53.Options)) (*route53.ListResourceRecordSetsOutput, error) { |
| + out := &route53.ListResourceRecordSetsOutput{} |
| + keys := make([]string, 0, len(f.records)) |
| + for k := range f.records { |
| + keys = append(keys, k) |
| + } |
| + slices.Sort(keys) |
| + for _, k := range keys { |
| + out.ResourceRecordSets = append(out.ResourceRecordSets, f.records[k]) |
| + } |
| + return out, nil |
| +} |
| + |
| +func (f *dr5Route53) ChangeResourceRecordSets(_ context.Context, in *route53.ChangeResourceRecordSetsInput, _ ...func(*route53.Options)) (*route53.ChangeResourceRecordSetsOutput, error) { |
| + f.changes++ |
| + if f.records == nil { |
| + f.records = map[string]r53types.ResourceRecordSet{} |
| + } |
| + for _, c := range in.ChangeBatch.Changes { |
| + rr := *c.ResourceRecordSet |
| + key := aws.ToString(rr.Name) + "|" + string(rr.Type) + "|" + aws.ToString(rr.SetIdentifier) |
| + switch c.Action { |
| + case r53types.ChangeActionDelete: |
| + delete(f.records, key) |
| + default: |
| + f.records[key] = rr |
| + } |
| + } |
| + return &route53.ChangeResourceRecordSetsOutput{}, nil |
| +} |
| + |
| +func (f *dr5Route53) ListHealthChecks(context.Context, *route53.ListHealthChecksInput, ...func(*route53.Options)) (*route53.ListHealthChecksOutput, error) { |
| + return &route53.ListHealthChecksOutput{HealthChecks: f.checks}, nil |
| +} |
| + |
| +func (f *dr5Route53) ListTagsForResources(_ context.Context, in *route53.ListTagsForResourcesInput, _ ...func(*route53.Options)) (*route53.ListTagsForResourcesOutput, error) { |
| + out := &route53.ListTagsForResourcesOutput{} |
| + for _, id := range in.ResourceIds { |
| + out.ResourceTagSets = append(out.ResourceTagSets, r53types.ResourceTagSet{ResourceId: aws.String(id), ResourceType: in.ResourceType, Tags: f.tags[id]}) |
| + } |
| + return out, nil |
| +} |
| + |
| +func (f *dr5Route53) CreateHealthCheck(_ context.Context, in *route53.CreateHealthCheckInput, _ ...func(*route53.Options)) (*route53.CreateHealthCheckOutput, error) { |
| + f.changes++ |
| + hc := r53types.HealthCheck{Id: aws.String(fmt.Sprintf("hc-%d", len(f.checks)+1)), CallerReference: in.CallerReference, HealthCheckConfig: in.HealthCheckConfig} |
| + f.checks = append(f.checks, hc) |
| + return &route53.CreateHealthCheckOutput{HealthCheck: &hc}, nil |
| +} |
| + |
| +func (f *dr5Route53) DeleteHealthCheck(_ context.Context, in *route53.DeleteHealthCheckInput, _ ...func(*route53.Options)) (*route53.DeleteHealthCheckOutput, error) { |
| + f.changes++ |
| + for i, hc := range f.checks { |
| + if aws.ToString(hc.Id) == aws.ToString(in.HealthCheckId) { |
| + f.checks = append(f.checks[:i], f.checks[i+1:]...) |
| + break |
| + } |
| + } |
| + return &route53.DeleteHealthCheckOutput{}, nil |
| +} |
| + |
| +func (f *dr5Route53) ChangeTagsForResource(_ context.Context, in *route53.ChangeTagsForResourceInput, _ ...func(*route53.Options)) (*route53.ChangeTagsForResourceOutput, error) { |
| + f.changes++ |
| + if f.tags == nil { |
| + f.tags = map[string][]r53types.Tag{} |
| + } |
| + f.tags[aws.ToString(in.ResourceId)] = append(f.tags[aws.ToString(in.ResourceId)], in.AddTags...) |
| + return &route53.ChangeTagsForResourceOutput{}, nil |
| +} |
diff --git a/internal/host/hadepartures_g3_test.go b/internal/host/hadepartures_g3_test.go| index 25f9ec272..e77d11a71 100644 |
| --- a/internal/host/hadepartures_g3_test.go |
| +++ b/internal/host/hadepartures_g3_test.go |
| @@ -621,14 +621,24 @@ func TestDepartureG3EdgesRebindRefusals(t *testing.T) { |
| t.Fatal(e) |
| } |
| x.now = x.expiry.Add(30 * time.Second) |
| - if e = x.c.step(t.Context()); e != nil { |
| - t.Fatal(e) |
| - } |
| - x.now = x.now.Add(30 * time.Second) |
| + // DR-5: the adoption pass, the rescan and the finalize run in one |
| + // step. step itself needs identities, so the unbound case drives |
| + // the same passes through ScanPass. |
| if mode == "unbound" { |
| + // step needs identities; drive the same passes through |
| + // ScanPass, with the confirmer's hook (which resolves |
| + // identities) detached. |
| x.c.cfg.Identities = nil |
| + x.a.Confirmer.OnConfirmed = nil |
| + for range 3 { |
| + if _, e = x.c.ScanPass(t.Context()); e != nil { |
| + break |
| + } |
| + } |
| + } else { |
| + e = x.c.step(t.Context()) |
| } |
| - if _, e = x.c.ScanPass(t.Context()); !errors.Is(e, errDepartureIdentity) { |
| + if !errors.Is(e, errDepartureIdentity) { |
| t.Fatalf("unsafe rebind: %v", e) |
| } |
| if _, current, e := x.store.Get(t.Context(), x.edgesKey); e != nil || current != tag { |
| @@ -655,10 +665,9 @@ func TestDepartureG3LateEdges(t *testing.T) { |
| entry, _ := provision.LifetimeEntryOf(x.records[0]) |
| raw, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: x.dead.Ref, IID: x.dead.InstanceID, Lifetime: entry.ID}) |
| x.fx.PutLock("instances/"+x.records[0].Host, raw) |
| - if e = x.c.step(t.Context()); e != nil { |
| - t.Fatal(e) |
| - } |
| - x.now = x.now.Add(30 * time.Second) |
| + // DR-5: a released host finishes in the first step, so the late |
| + // publication lands after enrollment and before that step. |
| + x.now = x.now.Add(time.Millisecond) |
| x.writeEdges(t) |
| if e = x.c.step(t.Context()); e != nil { |
| t.Fatal("late publication stuck", e) |
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go| index b9302e3ab..2c8d3b9d6 100644 |
| --- a/internal/host/hadepartures_scan.go |
| +++ b/internal/host/hadepartures_scan.go |
| @@ -168,6 +168,7 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| limit = 128 |
| } |
| blockers := []provision.DepartureHost{} |
| + departed := map[string]bool{} |
| count := 0 |
| for _, h := range inv.Records { |
| digest := scanDigest(h) |
| @@ -291,10 +292,15 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| old.Result = "pending" |
| old.NotBefore = time.Time{} |
| s.Hosts[h.Host] = old |
| + unserved := false |
| if !CanAdopt(h, c.cfg.Policy()) || !h.HA { |
| - block() |
| - blockers = append(blockers, h) |
| - continue |
| + // DR-5 (spec §7.5): a host no surviving box could adopt does not |
| + // hold the departure. It is neither imported nor touched. |
| + if unserved = c.unserved(ctx, d, h, departed); !unserved { |
| + block() |
| + blockers = append(blockers, h) |
| + continue |
| + } |
| } |
| if v.Lock.Release == nil && !readStarted.After(v.Lock.ExpiresAt) { |
| old.NotBefore = v.Lock.ExpiresAt |
| @@ -302,6 +308,12 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| wait(old.NotBefore) |
| continue |
| } |
| + if unserved { |
| + old.Result = departureUnserved |
| + s.Hosts[h.Host] = old |
| + c.logf("ha_departure_unserved departure=%s box=%s host=%s pool=%q generation=%d", d.ID, d.Box.Ref, h.Host, h.Pool, v.Lock.Generation) |
| + continue |
| + } |
| if s.Rescan { |
| block() |
| continue |
| @@ -351,6 +363,10 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| } |
| // A clean adoption pass is followed by an independent full lock walk. |
| s.Rescan = s.Unresolved == 0 && s.Waiting == 0 |
| + if s.Rescan { |
| + // DR-5: the independent rescan is due at once, not a step later. |
| + next = c.now() |
| + } |
| s.Cursor = 0 |
| s.Unresolved = 0 |
| s.Waiting = 0 |
| @@ -369,6 +385,72 @@ func (c *Controller) ScanPass(ctx context.Context) (bool, error) { |
| return true, c.retryScanAt(ctx, d, blockers, "scan", blocked, next) |
| } |
| +// departureUnserved marks a host discharged under spec §7.5: no box that |
| +// could adopt it remains, so the departure finishes without an import. |
| +const departureUnserved = "unserved" |
| + |
| +// unserved applies spec §7.5 rules 2 and 3 (rule 1, the release marker or |
| +// the passed expiry, is the scan's own wait). It reads only this box's |
| +// departure view and local journal: no S3 request. departed memoizes the |
| +// proven-departure answer per reference for one pass. |
| +func (c *Controller) unserved(ctx context.Context, d registry.HADeparture, h provision.DepartureHost, departed map[string]bool) bool { |
| + p := c.cfg.Policy() |
| + if !h.HA || p.Denied { |
| + return false |
| + } |
| + // Rule 2: this box would adopt the host if it served the host's pool. |
| + p.Pools = []string{h.Pool} |
| + if !CanAdopt(h, p) { |
| + return false |
| + } |
| + c.mu.Lock() |
| + v := c.view |
| + c.mu.Unlock() |
| + if !v.Complete || !v.Self.Known || v.Self.Box.Ref != c.cfg.Self.Ref { |
| + return false |
| + } |
| + // Rule 3: every other box in scope is a known non-server or proven gone. |
| + for _, o := range v.Peers { |
| + if o.Box.Ref == c.cfg.Self.Ref { |
| + continue |
| + } |
| + if !o.Known || o.PlacementNull { |
| + return false |
| + } |
| + if o.Box.Scope != c.cfg.Self.Scope { |
| + continue |
| + } |
| + if o.PoolsKnown && !o.Serves(h.Pool) { |
| + continue |
| + } |
| + if !c.provenDeparted(ctx, d, o.Box.Ref, departed) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// provenDeparted reports a departure enrolled in this box's journal for the |
| +// current incarnation of ref. Enrollment requires termination proof. |
| +func (c *Controller) provenDeparted(ctx context.Context, d registry.HADeparture, ref string, memo map[string]bool) bool { |
| + if ref == d.Box.Ref { |
| + return true |
| + } |
| + if known, ok := memo[ref]; ok { |
| + return known |
| + } |
| + memo[ref] = false |
| + o, ok, err := c.cfg.Identities.Resolve(ctx, ref, "") |
| + if err != nil || !ok || !o.Known || o.PlacementNull { |
| + return false |
| + } |
| + if _, err = c.cfg.Registry.Departure(ctx, departureID(c.cfg.DeploymentBucket, o.Box)); err != nil { |
| + return false |
| + } |
| + memo[ref] = true |
| + return true |
| +} |
| + |
| type departureLockListing struct { |
| root string |
| prefixes map[string]bool |
| @@ -676,7 +758,13 @@ func (c *Controller) complete(ctx context.Context, id string) (result error) { |
| c.telemetry.mu.Lock() |
| c.telemetry.sample.Completions++ |
| c.telemetry.mu.Unlock() |
| - c.logf("Recovered duties for %d instances from box %s.", len(s.Hosts), d.Box.Ref) |
| + recovered := 0 |
| + for _, h := range s.Hosts { |
| + if h.Result != departureUnserved { |
| + recovered++ |
| + } |
| + } |
| + c.logf("Recovered duties for %d instances from box %s.", recovered, d.Box.Ref) |
| return c.ackDeparture(ctx, d) |
| } |