host: ingress drain fix round 1: step times, cap from request, exit lock
Each step's time in the report is its own value, written under the lock. The cap counts from the request; no settle starts on an answer read at or after it; building the reader and every read are bounded even if the callee ignores its context. The 3-minute exit decides and exits under the lock the shutdown takes, so one never overlaps the other. Test helper renamed to ingressRouteAsk (Task 6 declares ingressAsk).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/host/ingressdrain.go+65 −27internal/host/ingressdrain_test.go+195 −15
Intent
<task-notification> <task-id>a6ad6f58e17960e42</task-id> <tool-use-id>toolu_01G7xXGxKcGsuBs5Tf18UXTQ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a373aecd-faa9-4b83-8736-ff726fb2d3af/tasks/a6ad6f58e17960e42.output</output-file> <status>completed</status> <summary>Agent "Implement W6 Tasks 4+5 (driver)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE The driver and its socket routes are written and the new tests pass. I did not run the full `internal/host` package, as you said. Commits: `b7f428a4` host: ingress drain driver and its socket routes on fixed boxes. Git printed a `packed-refs.lock` warning during the commit (probably another git process), but the commit is on `w6-ingress-drain` and the working tree is clean. The report file is not in the commit because `.superpowers/` is excluded from git. Tests: the new driver, route and real-socket tests pass, also under `-race`. Existing tests also pass: the drain, socket and fence tests, `TestRootNeverDialsTheDrainSocket`, and every test in the ten files that read `agent.go`. `go vet ./internal/host/` and the darwin and windows cross-builds are clean. `GOOS=darwin go vet` fails on existing test files (`claimsOffEnv` is defined only in a linux test file). I didn't touch them. Concerns: 1. The agent's own shutdown cancels the 3-minute exit. The spec doesn't say this. Without it, a slow stop could hit `os.Exit(1)` mid-shutdown and skip the HA clean marker. 2. When the target group's retention settings are wrong, or the box is not healthy at start, the verdict is unverified but the drain still waits for withdrawal (or the cap). If the spec meant "skip the wait", that is a one-line change. 3. A fixed box serves the socket when region HA is on and `CARLOS_INGRESS_TARGET_GROUPS` is set. The ARNs and the box's identity (from `lease.CurrentSelf()`) are checked each time a drain is asked for, and a bad key answers `not_armed` with the reason. The spec says "served whenever armed", so this serves slightly more widely. 4. A settle that starts before the 90 s cap may finish after it (by 100 s at most). 5. Every served answer is 200 JSON with a `result` field: running, done, refused, not_armed or group_member. Task 6 should print `result`, `verdict` and `reasons`. Task 9 can swap the package var `newIngressReader` for its fake adapter. 6. There was no compile-fail step before the code: I wrote the driver first and showed the tests catch bugs by deliberately breaking the settle logic (7 tests failed). Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/w6-build/.superpowers/sdd/2026-11-10-fixed-edge-ingress-drain/task-4-5-report.md</result> <usage><subagent_tokens>170264</subagent_tokens><tool_uses>49</tool_uses><duration_ms>1114869</duration_ms></usage> </task-notification>
Attributed to this commit: 10.0 g CO₂e (1,248,897 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on w6-ingress-drain, 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/internal/host/ingressdrain.go b/internal/host/ingressdrain.go| index f1a5d73d0..9f20c84f2 100644 |
| --- a/internal/host/ingressdrain.go |
| +++ b/internal/host/ingressdrain.go |
| @@ -304,7 +304,7 @@ func (d *ingressDrain) start() (<-chan struct{}, *ingressReport) { |
| d.armed = arm |
| d.report = &ingressReport{V: 1, Incarnation: agentIncarnation, Result: "running", StartedAt: &now, TargetGroups: slices.Clone(arm.Groups)} |
| d.done = make(chan struct{}) |
| - go d.run(d.edge, arm, d.report, d.done) |
| + go d.run(d.edge, arm, d.report, now, d.done) |
| return d.done, nil |
| } |
| @@ -332,37 +332,40 @@ func (d *ingressDrain) note(f func()) { |
| f() |
| } |
| -func (d *ingressDrain) stamp(at **time.Time) { |
| +// at is the time now, in a variable of its own: each step's time in the |
| +// report points at its own value, never rewritten. |
| +func (d *ingressDrain) at() *time.Time { |
| t := d.clock.now() |
| - d.note(func() { *at = &t }) |
| + return &t |
| } |
| -func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport, done chan struct{}) { |
| +func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport, started time.Time, done chan struct{}) { |
| defer close(done) |
| // Step 1: Connection: close on every response, then the health check |
| // fails. Nothing is refused. The edge refuses while a region HA |
| // connection drain is on, and then nothing changes. |
| if err := e.BeginIngressDrain(); err != nil { |
| - t := d.clock.now() |
| - d.note(func() { rep.Result, rep.Reason, rep.FinishedAt = "refused", err.Error(), &t }) |
| + t := d.at() |
| + d.note(func() { rep.Result, rep.Reason, rep.FinishedAt = "refused", err.Error(), t }) |
| log.Printf("agent: ingress drain refused: %v", err) |
| return |
| } |
| d.health.SetIngressDrain(true) |
| - d.stamp(&rep.HealthFailedAt) |
| + failed := d.at() |
| + d.note(func() { rep.HealthFailedAt = failed }) |
| log.Printf("agent: ingress drain: health check failing; waiting for %d target group(s) to withdraw the box", len(arm.Groups)) |
| // Step 2. |
| - verdict, reasons := d.wait(arm, rep) |
| - t := d.clock.now() |
| - d.note(func() { rep.Verdict, rep.Reasons, rep.WaitEndedAt = verdict, reasons, &t }) |
| + verdict, reasons := d.wait(arm, rep, started) |
| + waited := d.at() |
| + d.note(func() { rep.Verdict, rep.Reasons, rep.WaitEndedAt = verdict, slices.Clone(reasons), waited }) |
| // Step 3. From here the box serves nothing on its public ports, so |
| // the agent ends itself if the stop does not come. |
| out, err := e.CloseIngress(context.Background(), ingressConnWait) |
| - t = d.clock.now() |
| + closed := d.at() |
| d.note(func() { |
| - rep.ListenersClosedAt = &t |
| + rep.ListenersClosedAt = closed |
| rep.HeldClosed, rep.Finished, rep.Closed = out.HeldClosed, out.Finished, out.Closed |
| if err != nil { |
| rep.CloseError = err.Error() |
| @@ -375,8 +378,8 @@ func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport, |
| d.mu.Unlock() |
| // Step 4. |
| - t = d.clock.now() |
| - d.note(func() { rep.Result, rep.FinishedAt = "done", &t }) |
| + finished := d.at() |
| + d.note(func() { rep.Result, rep.FinishedAt = "done", finished }) |
| why := "" |
| if len(reasons) > 0 { |
| why = ": " + strings.Join(reasons, "; ") |
| @@ -390,11 +393,14 @@ func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport, |
| // exitWithoutStop is the 3-minute exit (spec §4.2): the drain closed the |
| // listeners and no stop followed, so the agent exits and systemd restarts |
| // it through admission and two passing health checks. |
| +// |
| +// The decision and the exit hold the lock shutdownStarted takes: once the |
| +// shutdown has begun the exit never runs, and once the exit has been |
| +// decided the shutdown waits for it (os.Exit does not return). |
| func (d *ingressDrain) exitWithoutStop() { |
| d.mu.Lock() |
| - stopping := d.stopping |
| - d.mu.Unlock() |
| - if stopping { |
| + defer d.mu.Unlock() |
| + if d.stopping { |
| return |
| } |
| log.Printf("agent: ingress drain ended without a stop; exiting") |
| @@ -405,19 +411,24 @@ func (d *ingressDrain) exitWithoutStop() { |
| // withdrawn with another target healthy, and that holds through the |
| // settle; or until the cap. It never refuses: the stop is coming either |
| // way, so it answers a verdict and the drain goes on. |
| -func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport) (string, []string) { |
| - start := d.clock.now() |
| - capAt := start.Add(ingressCap) |
| +// |
| +// The cap counts from the request (started), so building the reader and |
| +// the retention read spend it too. A settle starts only on an answer read |
| +// before the cap; one begun before it may end up to the settle after it. |
| +func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport, started time.Time) (string, []string) { |
| + capAt := started.Add(ingressCap) |
| var reasons []string |
| - rd, buildErr := d.reader(context.Background(), arm.Region, arm.Groups) |
| + rd, buildErr := boundedCall(ingressReadBound, func(ctx context.Context) (ingresshealth.Reader, error) { |
| + return d.reader(ctx, arm.Region, arm.Groups) |
| + }) |
| read := func() (ingresshealth.Verdict, error) { |
| if buildErr != nil { |
| return ingresshealth.Verdict{}, fmt.Errorf("target health reader: %w", buildErr) |
| } |
| - ctx, cancel := context.WithTimeout(context.Background(), ingressReadBound) |
| - defer cancel() |
| - return rd.Withdrawn(ctx, arm.Self) |
| + return boundedCall(ingressReadBound, func(ctx context.Context) (ingresshealth.Verdict, error) { |
| + return rd.Withdrawn(ctx, arm.Self) |
| + }) |
| } |
| // Retention, once, before the first poll (spec §8): with connections |
| @@ -426,9 +437,7 @@ func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport) (string, []st |
| if buildErr != nil { |
| reasons = append(reasons, fmt.Sprintf("target group retention: target health reader: %v", buildErr)) |
| } else { |
| - ctx, cancel := context.WithTimeout(context.Background(), ingressReadBound) |
| - rets, err := rd.Retention(ctx) |
| - cancel() |
| + rets, err := boundedCall(ingressReadBound, rd.Retention) |
| if err != nil { |
| reasons = append(reasons, fmt.Sprintf("target group retention: %v", err)) |
| } |
| @@ -457,6 +466,11 @@ func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport) (string, []st |
| } |
| if err == nil && v.Withdrawn() && v.OthersHealthy() { |
| if settleFrom.IsZero() { |
| + if !now.Before(capAt) { |
| + // Withdrawn, but first seen at or after the cap: no |
| + // settle starts now. |
| + return ingressUnverified, append(reasons, "the target groups withdrew the box only after the cap") |
| + } |
| settleFrom = now |
| } |
| if now.Sub(settleFrom) >= ingressSettle { |
| @@ -477,6 +491,30 @@ func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport) (string, []st |
| } |
| } |
| +// boundedCall runs f with a context that ends after bound, and answers |
| +// within bound whether or not f heeds it: a hung call cannot hold the |
| +// drain. A call left running finishes on its own; its answer is dropped. |
| +func boundedCall[T any](bound time.Duration, f func(context.Context) (T, error)) (T, error) { |
| + ctx, cancel := context.WithTimeout(context.Background(), bound) |
| + defer cancel() |
| + type result struct { |
| + v T |
| + err error |
| + } |
| + ch := make(chan result, 1) |
| + go func() { |
| + v, err := f(ctx) |
| + ch <- result{v, err} |
| + }() |
| + select { |
| + case r := <-ch: |
| + return r.v, r.err |
| + case <-ctx.Done(): |
| + var zero T |
| + return zero, fmt.Errorf("no answer within %s", bound) |
| + } |
| +} |
| + |
| // capReasons names what held the drain at the cap: the read error, each |
| // target group that has not withdrawn the box with its state, and each |
| // with no other healthy target (the load balancer fails open, spec §8). |
diff --git a/internal/host/ingressdrain_test.go b/internal/host/ingressdrain_test.go| index c952c6f01..987444ed2 100644 |
| --- a/internal/host/ingressdrain_test.go |
| +++ b/internal/host/ingressdrain_test.go |
| @@ -56,6 +56,12 @@ func (c *fakeIngressClock) clock() ingressClock { |
| } |
| } |
| +func (c *fakeIngressClock) advance(d time.Duration) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.t = c.t.Add(d) |
| +} |
| + |
| func (c *fakeIngressClock) afters() []fakeAfter { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| @@ -72,6 +78,9 @@ type fakeTargetHealth struct { |
| retErr error |
| // gate, when set, holds the first read until it is closed. |
| gate chan struct{} |
| + // delay, when set, is how long a read starting at at takes on the |
| + // drain's clock. |
| + delay func(at time.Duration) time.Duration |
| mu sync.Mutex |
| reads int |
| @@ -91,6 +100,12 @@ func (f *fakeTargetHealth) Withdrawn(_ context.Context, self ingresshealth.Self) |
| f.clock.mu.Lock() |
| at := f.clock.t.Sub(f.start) |
| f.clock.mu.Unlock() |
| + if f.delay != nil { |
| + if d := f.delay(at); d > 0 { |
| + f.clock.advance(d) |
| + at += d |
| + } |
| + } |
| return f.script(at) |
| } |
| @@ -118,6 +133,8 @@ type fakeIngressEdge struct { |
| closeErr error |
| waits []time.Duration |
| health *fakeIngressHealth |
| + // during, when set, runs inside CloseIngress (the connection wait). |
| + during func() |
| // healthAtClose is whether the health check was failing when step 3 |
| // began. |
| healthAtClose bool |
| @@ -136,6 +153,9 @@ func (e *fakeIngressEdge) CloseIngress(_ context.Context, wait time.Duration) (e |
| e.calls = append(e.calls, "close") |
| e.waits = append(e.waits, wait) |
| e.healthAtClose = e.health.on() |
| + if e.during != nil { |
| + e.during() |
| + } |
| return e.out, e.closeErr |
| } |
| @@ -640,7 +660,7 @@ func TestIngressDrainNotArmedAnswers(t *testing.T) { |
| } |
| } |
| -func ingressAsk(t *testing.T, h http.Handler, ctx context.Context, method, path string) (*httptest.ResponseRecorder, map[string]any) { |
| +func ingressRouteAsk(t *testing.T, h http.Handler, ctx context.Context, method, path string) (*httptest.ResponseRecorder, map[string]any) { |
| t.Helper() |
| req := httptest.NewRequest(method, "http://agent"+path, nil).WithContext(ctx) |
| rec := httptest.NewRecorder() |
| @@ -661,7 +681,7 @@ func TestIngressDrainRoutes(t *testing.T) { |
| h := (&haDrainSocket{ingress: f.d}).handler() |
| ctx := context.Background() |
| - rec, st := ingressAsk(t, h, ctx, http.MethodGet, "/v1/ingress/status") |
| + rec, st := ingressRouteAsk(t, h, ctx, http.MethodGet, "/v1/ingress/status") |
| if rec.Code != http.StatusOK || st["armed"] != ingressArmed || st["report"] != nil || st["incarnation"] != agentIncarnation || |
| rec.Header().Get("Cache-Control") != "no-store" { |
| t.Fatalf("status before: %d %v", rec.Code, st) |
| @@ -672,7 +692,7 @@ func TestIngressDrainRoutes(t *testing.T) { |
| {http.MethodPost, "/v1/ingress/drain?x=1"}, |
| {http.MethodPost, "/v1/ingress/other"}, |
| } { |
| - if rec, _ := ingressAsk(t, h, ctx, p.method, p.path); rec.Code != http.StatusNotFound { |
| + if rec, _ := ingressRouteAsk(t, h, ctx, p.method, p.path); rec.Code != http.StatusNotFound { |
| t.Fatalf("%s %s answered %d", p.method, p.path, rec.Code) |
| } |
| } |
| @@ -680,16 +700,16 @@ func TestIngressDrainRoutes(t *testing.T) { |
| t.Fatal("a refused ask started a drain") |
| } |
| - rec, rep := ingressAsk(t, h, ctx, http.MethodPost, "/v1/ingress/drain") |
| + rec, rep := ingressRouteAsk(t, h, ctx, http.MethodPost, "/v1/ingress/drain") |
| if rec.Code != http.StatusOK || rep["result"] != "done" || rep["verdict"] != ingressWithdrawn { |
| t.Fatalf("drain: %d %v", rec.Code, rep) |
| } |
| - _, st = ingressAsk(t, h, ctx, http.MethodGet, "/v1/ingress/status") |
| + _, st = ingressRouteAsk(t, h, ctx, http.MethodGet, "/v1/ingress/status") |
| if r, _ := st["report"].(map[string]any); st["armed"] != ingressArmed || r["result"] != "done" { |
| t.Fatalf("status after: %v", st) |
| } |
| // A repeat joins and gets the same report. |
| - _, again := ingressAsk(t, h, ctx, http.MethodPost, "/v1/ingress/drain") |
| + _, again := ingressRouteAsk(t, h, ctx, http.MethodPost, "/v1/ingress/drain") |
| if again["finished_at"] != rep["finished_at"] || again["reads"] != rep["reads"] { |
| t.Fatalf("repeat: %v, first %v", again, rep) |
| } |
| @@ -702,11 +722,11 @@ func TestIngressDrainRouteNotArmed(t *testing.T) { |
| return ingressArming{Answer: ingressNotArmed, Reason: "region HA is off (CARLOS_REGION_HA)"} |
| } |
| h := f.d.handler() |
| - _, ans := ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| + _, ans := ingressRouteAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| if ans["result"] != ingressNotArmed || ans["reason"] != "region HA is off (CARLOS_REGION_HA)" { |
| t.Fatalf("answer %v", ans) |
| } |
| - _, st := ingressAsk(t, h, context.Background(), http.MethodGet, "/v1/ingress/status") |
| + _, st := ingressRouteAsk(t, h, context.Background(), http.MethodGet, "/v1/ingress/status") |
| if st["armed"] != ingressNotArmed || st["reason"] != "region HA is off (CARLOS_REGION_HA)" { |
| t.Fatalf("status %v", st) |
| } |
| @@ -739,7 +759,7 @@ func TestIngressDrainCallerGoesAway(t *testing.T) { |
| t.Fatalf("edge calls %v before the wait ended", got) |
| } |
| close(f.tg.gate) |
| - _, rep := ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| + _, rep := ingressRouteAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| if rep["result"] != "done" || rep["verdict"] != ingressWithdrawn || !slices.Equal(f.edge.called(), []string{"begin", "close"}) { |
| t.Fatalf("report %v, edge %v", rep, f.edge.called()) |
| } |
| @@ -754,13 +774,13 @@ func TestIngressDrainRouteBound(t *testing.T) { |
| f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| f.tg.gate = make(chan struct{}) |
| h := f.d.handler() |
| - _, rep := ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| + _, rep := ingressRouteAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| if rep["result"] != "running" || rep["health_failed_at"] == nil { |
| t.Fatalf("bounded answer %v", rep) |
| } |
| close(f.tg.gate) |
| ingressCallBound = old |
| - _, rep = ingressAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| + _, rep = ingressRouteAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain") |
| if rep["result"] != "done" { |
| t.Fatalf("report %v", rep) |
| } |
| @@ -778,11 +798,11 @@ func TestDrainSocketRoutesByBox(t *testing.T) { |
| {http.MethodPost, "/v1/drain/move"}, |
| {http.MethodPost, "/v1/drain/cancel"}, |
| } { |
| - if rec, _ := ingressAsk(t, fixed, context.Background(), p.method, p.path); rec.Code != http.StatusNotFound { |
| + if rec, _ := ingressRouteAsk(t, fixed, context.Background(), p.method, p.path); rec.Code != http.StatusNotFound { |
| t.Fatalf("fixed box: %s %s answered %d", p.method, p.path, rec.Code) |
| } |
| } |
| - if rec, _ := ingressAsk(t, fixed, context.Background(), http.MethodGet, "/v1/ingress/status"); rec.Code != http.StatusOK { |
| + if rec, _ := ingressRouteAsk(t, fixed, context.Background(), http.MethodGet, "/v1/ingress/status"); rec.Code != http.StatusOK { |
| t.Fatalf("fixed box: ingress status %d", rec.Code) |
| } |
| @@ -791,10 +811,170 @@ func TestDrainSocketRoutesByBox(t *testing.T) { |
| }, &fakeIngressHealth{}) |
| g := newDrainDriver(&fakeDrainAct{}, &fakeDrainEdge{}, &fakeMarks{}, func() fenceState { return fenceState{} }) |
| both := (&haDrainSocket{group: g, ingress: member}).handler() |
| - if rec, st := ingressAsk(t, both, context.Background(), http.MethodGet, "/v1/drain/status"); rec.Code != http.StatusOK || st["result"] != "none" { |
| + if rec, st := ingressRouteAsk(t, both, context.Background(), http.MethodGet, "/v1/drain/status"); rec.Code != http.StatusOK || st["result"] != "none" { |
| t.Fatalf("member: drain status %d %v", rec.Code, st) |
| } |
| - if _, ans := ingressAsk(t, both, context.Background(), http.MethodPost, "/v1/ingress/drain"); ans["result"] != ingressGroupMember { |
| + if _, ans := ingressRouteAsk(t, both, context.Background(), http.MethodPost, "/v1/ingress/drain"); ans["result"] != ingressGroupMember { |
| t.Fatalf("member: ingress drain %v", ans) |
| } |
| } |
| + |
| +// Each step's time is its own: time spent in step 3 moves the listeners' |
| +// and the finish times only, and status read throughout (encoded as JSON, |
| +// as the route does) never races the driver's writes. |
| +func TestIngressDrainStepTimesAreTheirOwn(t *testing.T) { |
| + f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + f.edge.during = func() { f.clock.advance(7 * time.Second) } |
| + stop := make(chan struct{}) |
| + var wg sync.WaitGroup |
| + for i := 0; i < 4; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + for { |
| + select { |
| + case <-stop: |
| + return |
| + default: |
| + } |
| + if _, err := json.Marshal(f.d.status()); err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + } |
| + }() |
| + } |
| + rep := f.drain(t) |
| + close(stop) |
| + wg.Wait() |
| + if elapsed(rep, rep.HealthFailedAt) != 0 || elapsed(rep, rep.WaitEndedAt) != 16*time.Second || |
| + elapsed(rep, rep.ListenersClosedAt) != 23*time.Second || elapsed(rep, rep.FinishedAt) != 23*time.Second { |
| + t.Fatalf("times: failed %s, waited %s, closed %s, finished %s", elapsed(rep, rep.HealthFailedAt), |
| + elapsed(rep, rep.WaitEndedAt), elapsed(rep, rep.ListenersClosedAt), elapsed(rep, rep.FinishedAt)) |
| + } |
| + if rep.WaitEndedAt == rep.ListenersClosedAt || rep.ListenersClosedAt == rep.FinishedAt || rep.HealthFailedAt == rep.WaitEndedAt { |
| + t.Fatal("two steps share one time value") |
| + } |
| +} |
| + |
| +// A withdrawn answer that arrives after the cap starts no settle, even |
| +// when the read began before it. |
| +func TestIngressDrainNoSettleStartsAfterTheCap(t *testing.T) { |
| + f := newIngressFixture(t, healthyUntil(90*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + f.tg.delay = func(at time.Duration) time.Duration { |
| + if at == 80*time.Second { |
| + return 12 * time.Second |
| + } |
| + return 0 |
| + } |
| + rep := f.drain(t) |
| + if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 92*time.Second || |
| + !slices.Equal(rep.Reasons, []string{"the target groups withdrew the box only after the cap"}) { |
| + t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt)) |
| + } |
| + |
| + // A settle begun before the cap still finishes after it, past a slow |
| + // read. |
| + f = newIngressFixture(t, healthyUntil(88*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + f.tg.delay = func(at time.Duration) time.Duration { |
| + if at == 90*time.Second { |
| + return 3 * time.Second |
| + } |
| + return 0 |
| + } |
| + rep = f.drain(t) |
| + if rep.Verdict != ingressWithdrawn || elapsed(rep, rep.WaitEndedAt) != 99*time.Second { |
| + t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt)) |
| + } |
| +} |
| + |
| +// The cap counts from the request: a reader slow to build spends it. |
| +func TestIngressDrainCapCountsFromTheRequest(t *testing.T) { |
| + f := newIngressFixture(t, healthyUntil(120*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + build := f.d.reader |
| + f.d.reader = func(ctx context.Context, region string, groups []string) (ingresshealth.Reader, error) { |
| + f.clock.advance(85 * time.Second) |
| + return build(ctx, region, groups) |
| + } |
| + rep := f.drain(t) |
| + if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) != 91*time.Second || rep.Reads != 4 { |
| + t.Fatalf("verdict %s %q at %s after %d reads", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt), rep.Reads) |
| + } |
| +} |
| + |
| +// Building the reader and each read are bounded: a call that never |
| +// answers is an error after the bound, and the drain goes on. |
| +func TestIngressDrainBoundsHungCalls(t *testing.T) { |
| + old := ingressReadBound |
| + ingressReadBound = 20 * time.Millisecond |
| + t.Cleanup(func() { ingressReadBound = old }) |
| + never := make(chan struct{}) |
| + t.Cleanup(func() { close(never) }) |
| + |
| + f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + f.d.reader = func(context.Context, string, []string) (ingresshealth.Reader, error) { |
| + <-never |
| + return nil, errors.New("late") |
| + } |
| + rep := f.drain(t) |
| + if rep.Verdict != ingressUnverified || len(rep.Reasons) != 2 || !strings.Contains(rep.Reasons[0], "no answer within 20ms") || |
| + !slices.Equal(f.edge.called(), []string{"begin", "close"}) { |
| + t.Fatalf("hung construction: %s %q, edge %v", rep.Verdict, rep.Reasons, f.edge.called()) |
| + } |
| + |
| + f = newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + f.tg.gate = never // the first read never answers |
| + rep = f.drain(t) |
| + if rep.Verdict != ingressWithdrawn || rep.Polls[0].Error != "no answer within 20ms" || elapsed(rep, rep.WaitEndedAt) != 16*time.Second { |
| + t.Fatalf("hung read: %s %q at %s, polls %+v", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt), rep.Polls) |
| + } |
| +} |
| + |
| +// The exit and the shutdown are one decision: a shutdown that starts while |
| +// the exit is running waits for it (os.Exit never returns), and an exit |
| +// timer that fires while the shutdown is starting does nothing after it. |
| +func TestIngressDrainExitAndShutdownInterleave(t *testing.T) { |
| + f := newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + f.d.exit = func(code int) { |
| + close(entered) |
| + <-release |
| + *f.exits = append(*f.exits, code) |
| + } |
| + f.drain(t) |
| + timer := f.clock.afters()[0].f |
| + go timer() |
| + <-entered |
| + shut := make(chan struct{}) |
| + go func() { f.d.shutdownStarted(); close(shut) }() |
| + select { |
| + case <-shut: |
| + t.Fatal("the shutdown began while the exit was running") |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + close(release) |
| + <-shut |
| + if !slices.Equal(*f.exits, []int{1}) { |
| + t.Fatalf("exits %v", *f.exits) |
| + } |
| + |
| + // The shutdown holds the decision: a timer fired while shutdownStarted |
| + // is inside its critical section exits nothing. |
| + f = newIngressFixture(t, healthyUntil(0, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy)) |
| + f.drain(t) |
| + timer = f.clock.afters()[0].f |
| + f.d.mu.Lock() // the shutdown, mid-transition |
| + fired := make(chan struct{}) |
| + go func() { timer(); close(fired) }() |
| + select { |
| + case <-fired: |
| + t.Fatal("the exit decided without the shutdown's lock") |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + f.d.stopping = true |
| + f.d.mu.Unlock() |
| + <-fired |
| + if len(*f.exits) != 0 { |
| + t.Fatalf("exited during the shutdown: %v", *f.exits) |
| + } |
| +} |