carlos / platform Public

host: ingress drain deadlines are absolute from the request

Step 2 ends by the cap plus the settle (100 s): each read is bounded by
what is left, a read out at 100 s is abandoned, and no sleep runs past it.
Step 3 runs under a context that ends 140 s after the request, so the
connection wait and the edge's join both fit. The route waits 150 s, the
helper 155 s, and the drain unit's TimeoutStopSec is 170. A combined
worst-case test (settle begun at 89.9 s, slow reads, slow Shutdown and
join) shows the report final at 140 s (W6 final review F1).

An edge with no public listener to close makes the verdict unverified
with the edge's reason (F7).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c152583e5aafbaa491cf8dc5ab8d365509d56f24 parent f25e10c
5 files changed, +194 −18
  • internal/host/hadrain_call.go +2 −2
  • internal/host/ingressdrain.go +49 −11
  • internal/host/ingressdrain_test.go +138 −2
  • internal/host/units/carlos-edge-drain.service +4 −2
  • internal/host/units_ingress_drain_test.go +1 −1
diff --git a/internal/host/hadrain_call.go b/internal/host/hadrain_call.go
index 7093c144d..1540f5bcc 100644
--- a/internal/host/hadrain_call.go
+++ b/internal/host/hadrain_call.go
@@ -278,8 +278,8 @@ func (c *cappedBuffer) Write(p []byte) (int, error) {
}
// ingressAskBound bounds one ask for the ingress drain, by the drain unit
-// and by the verbs' child: the agent answers within its own 140 s
-// (ingressCallBound), and the unit's TimeoutStopSec=150 outlasts this.
+// and by the verbs' child: the agent answers within its own 150 s
+// (ingressCallBound), and the unit's TimeoutStopSec=170 outlasts this.
var ingressAskBound = ingressCallBound + 5*time.Second
// ingressDrainEntry is __ingress-drain's body (the drain unit's ExecStop,
diff --git a/internal/host/ingressdrain.go b/internal/host/ingressdrain.go
index 9f20c84f2..e85970bf6 100644
--- a/internal/host/ingressdrain.go
+++ b/internal/host/ingressdrain.go
@@ -15,6 +15,7 @@ package host
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"log"
"net/http"
@@ -30,10 +31,18 @@ import (
"github.com/carlosframework/platform/internal/ingresshealth/awstg"
)
-// The drain's timings (spec §4.2). The cap is from the request; the
-// settle runs after the target groups first report the box withdrawn and
-// may end past the cap (the drain unit's 150 s stop timeout allows the
-// cap, the settle, the connection wait and slack).
+// The drain's timings (spec §4.2), every deadline counted from the
+// request on the drain's own clock, so slow reads, a slow Shutdown or a
+// slow join cannot push the report past the route's bound:
+//
+// - step 2 ends by the cap plus the settle (100 s). No settle starts at
+// or after the cap, a read is bounded by what is left of the 100 s, and
+// a read still out at 100 s is abandoned;
+// - step 3 ends by ingressCloseBy (140 s): the 30 s connection wait, then
+// the edge's join of what it cut (10 s), within one context;
+// - the report is final then, before the route answers at 150 s.
+//
+// The drain unit's TimeoutStopSec=170 outlasts the helper's 155 s.
var (
ingressPollEvery = 2 * time.Second
ingressSettle = 10 * time.Second
@@ -43,9 +52,11 @@ var (
// ingressReadBound bounds one read of the target groups, so a hung
// call cannot hold the drain past its cap by more than this.
ingressReadBound = 5 * time.Second
+ // ingressCloseBy is when step 3 must have ended, from the request.
+ ingressCloseBy = 140 * time.Second
// ingressCallBound is how long POST /v1/ingress/drain waits for the
// report before answering the drain as it stands.
- ingressCallBound = 140 * time.Second
+ ingressCallBound = 150 * time.Second
)
// ingressPorts are the ports the box is registered on in its target
@@ -361,8 +372,12 @@ func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport,
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)
+ // the agent ends itself if the stop does not come. Its deadline is
+ // absolute, from the request: the connection wait and the edge's join
+ // both end inside it.
+ ctx, cancel := context.WithTimeout(context.Background(), started.Add(ingressCloseBy).Sub(d.clock.now()))
+ out, err := e.CloseIngress(ctx, ingressConnWait)
+ cancel()
closed := d.at()
d.note(func() {
rep.ListenersClosedAt = closed
@@ -370,6 +385,12 @@ func (d *ingressDrain) run(e ingressEdge, arm ingressArming, rep *ingressReport,
if err != nil {
rep.CloseError = err.Error()
}
+ if errors.Is(err, edge.ErrNoPublicListeners) {
+ // Nothing was closed (dev mode's plain HTTP): the box still
+ // serves on its port, so the drain cannot say it withdrew.
+ reasons = append(reasons, err.Error())
+ verdict, rep.Verdict, rep.Reasons = ingressUnverified, ingressUnverified, slices.Clone(reasons)
+ }
})
d.mu.Lock()
if !d.stopping {
@@ -414,9 +435,14 @@ func (d *ingressDrain) exitWithoutStop() {
//
// 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.
+// before the cap; one begun before it may end up to the settle after it,
+// and no later: step 2 ends by the cap plus the settle (waitEnd). Each
+// read is bounded by what is left of that, and a read whose answer comes
+// at or after it is abandoned, as one cut by its bound would be.
func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport, started time.Time) (string, []string) {
capAt := started.Add(ingressCap)
+ waitEnd := capAt.Add(ingressSettle)
+ late := fmt.Errorf("no answer within %s of the request", ingressCap+ingressSettle)
var reasons []string
rd, buildErr := boundedCall(ingressReadBound, func(ctx context.Context) (ingresshealth.Reader, error) {
@@ -426,7 +452,11 @@ func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport, started time.
if buildErr != nil {
return ingresshealth.Verdict{}, fmt.Errorf("target health reader: %w", buildErr)
}
- return boundedCall(ingressReadBound, func(ctx context.Context) (ingresshealth.Verdict, error) {
+ bound := min(ingressReadBound, waitEnd.Sub(d.clock.now()))
+ if bound <= 0 {
+ return ingresshealth.Verdict{}, late
+ }
+ return boundedCall(bound, func(ctx context.Context) (ingresshealth.Verdict, error) {
return rd.Withdrawn(ctx, arm.Self)
})
}
@@ -453,6 +483,10 @@ func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport, started time.
for {
v, err := read()
now := d.clock.now()
+ if !now.Before(waitEnd) {
+ // Out at the wait's end: whatever it says comes too late.
+ v, err = ingresshealth.Verdict{}, late
+ }
d.record(rep, now, v, err)
if err == nil && !checkedStart {
// The first answer: a box already not healthy has been so for
@@ -482,12 +516,16 @@ func (d *ingressDrain) wait(arm ingressArming, rep *ingressReport, started time.
} else {
// Not withdrawn, or it did not hold: the settle starts again
// from the next withdrawn answer, if one comes before the cap.
+ if !settleFrom.IsZero() && !now.Before(waitEnd) {
+ return ingressUnverified, append(reasons, fmt.Sprintf("the settle did not end within %s of the request", ingressCap+ingressSettle))
+ }
settleFrom = time.Time{}
if !now.Before(capAt) {
return ingressUnverified, append(reasons, capReasons(v, err)...)
}
}
- d.clock.sleep(ingressPollEvery)
+ // Never past the wait's end: a read there answers late at once.
+ d.clock.sleep(max(0, min(ingressPollEvery, waitEnd.Sub(d.clock.now()))))
}
}
@@ -565,7 +603,7 @@ func (d *ingressDrain) record(rep *ingressReport, at time.Time, v ingresshealth.
// handler serves the drain's routes on the drain socket:
//
// POST /v1/ingress/drain start or join; answers the report when the
-// drain ends, or as it stands after 140 s
+// drain ends, or as it stands after 150 s
// GET /v1/ingress/status arming and the report so far
//
// Both answer 200 with JSON. A box with no drain answers the drain with
diff --git a/internal/host/ingressdrain_test.go b/internal/host/ingressdrain_test.go
index 532d71c25..87f3fc993 100644
--- a/internal/host/ingressdrain_test.go
+++ b/internal/host/ingressdrain_test.go
@@ -83,6 +83,10 @@ type fakeTargetHealth 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
+ // honorBound, when set, makes a delayed read heed its context as the
+ // AWS client does: a read that would outlast the bound the drain gave
+ // it ends at that bound, with no answer.
+ honorBound bool
mu sync.Mutex
reads int
@@ -90,7 +94,7 @@ type fakeTargetHealth struct {
selves []ingresshealth.Self
}
-func (f *fakeTargetHealth) Withdrawn(_ context.Context, self ingresshealth.Self) (ingresshealth.Verdict, error) {
+func (f *fakeTargetHealth) Withdrawn(ctx context.Context, self ingresshealth.Self) (ingresshealth.Verdict, error) {
f.mu.Lock()
f.reads++
first := f.reads == 1
@@ -107,6 +111,10 @@ func (f *fakeTargetHealth) Withdrawn(_ context.Context, self ingresshealth.Self)
f.clock.mu.Unlock()
if f.delay != nil {
if d := f.delay(at); d > 0 {
+ if b, ok := fakeBound(ctx); ok && f.honorBound && d >= b {
+ f.clock.advance(b)
+ return ingresshealth.Verdict{}, context.DeadlineExceeded
+ }
f.clock.advance(d)
at += d
}
@@ -114,6 +122,17 @@ func (f *fakeTargetHealth) Withdrawn(_ context.Context, self ingresshealth.Self)
return f.script(at)
}
+// fakeBound is the bound the drain gave a call, read off its context's
+// deadline: the drain sets it from its own clock an instant before, so it
+// is rounded to the tenth of a second the tests' times are written in.
+func fakeBound(ctx context.Context) (time.Duration, bool) {
+ dl, ok := ctx.Deadline()
+ if !ok {
+ return 0, false
+ }
+ return time.Until(dl).Round(100 * time.Millisecond), true
+}
+
func (f *fakeTargetHealth) Retention(context.Context) ([]ingresshealth.Retention, error) {
f.mu.Lock()
defer f.mu.Unlock()
@@ -140,6 +159,9 @@ type fakeIngressEdge struct {
health *fakeIngressHealth
// during, when set, runs inside CloseIngress (the connection wait).
during func()
+ // closing, when set, is CloseIngress's answer, given its context and
+ // wait.
+ closing func(ctx context.Context, wait time.Duration) (edge.IngressClose, error)
// healthAtClose is whether the health check was failing when step 3
// began.
healthAtClose bool
@@ -152,7 +174,7 @@ func (e *fakeIngressEdge) BeginIngressDrain() error {
return e.beginErr
}
-func (e *fakeIngressEdge) CloseIngress(_ context.Context, wait time.Duration) (edge.IngressClose, error) {
+func (e *fakeIngressEdge) CloseIngress(ctx context.Context, wait time.Duration) (edge.IngressClose, error) {
e.mu.Lock()
defer e.mu.Unlock()
e.calls = append(e.calls, "close")
@@ -161,6 +183,9 @@ func (e *fakeIngressEdge) CloseIngress(_ context.Context, wait time.Duration) (e
if e.during != nil {
e.during()
}
+ if e.closing != nil {
+ return e.closing(ctx, wait)
+ }
return e.out, e.closeErr
}
@@ -982,3 +1007,114 @@ func TestIngressDrainExitAndShutdownInterleave(t *testing.T) {
t.Fatalf("exited during the shutdown: %v", *f.exits)
}
}
+
+// The whole drain fits the socket's bound in the worst case (W6 final
+// review F1): a settle begun at 89.9 s with slow reads, a Shutdown that
+// takes its whole wait and a join that would outlast what is left. Step 2
+// ends by 100 s (cap plus settle; the read still out then is abandoned),
+// step 3 by 140 s, and the report is final before the route's 150 s.
+func TestIngressDrainWorstCaseEndsInsideTheSocketBound(t *testing.T) {
+ ms := func(n int) time.Duration { return time.Duration(n) * time.Millisecond }
+ f := newIngressFixture(t, healthyUntil(ms(89_900), ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.honorBound = true
+ f.tg.delay = func(at time.Duration) time.Duration {
+ switch {
+ case at == 88*time.Second:
+ return ms(1_900) // withdrawn first seen at 89.9 s: the settle begins
+ case at > 88*time.Second:
+ return ms(4_900) // every read after it is slow
+ }
+ return 0
+ }
+ var wait, budget time.Duration
+ f.edge.closing = func(ctx context.Context, w time.Duration) (edge.IngressClose, error) {
+ b, ok := fakeBound(ctx)
+ if !ok {
+ t.Error("step 3 was given no deadline")
+ b = time.Hour
+ }
+ wait, budget = w, b
+ // Shutdown takes its whole wait; the join then runs until ctx ends
+ // (the edge's half, TestCloseIngressJoinEndsWithTheContext).
+ f.clock.advance(w)
+ f.clock.advance(b - w)
+ return edge.IngressClose{Finished: 3, Closed: 2}, edge.ErrDrainNotIdle
+ }
+ h := f.d.handler()
+ _, ans := ingressRouteAsk(t, h, context.Background(), http.MethodPost, "/v1/ingress/drain")
+ rep := f.d.snapshot()
+ if rep.Result != "done" || rep.Verdict != ingressUnverified || ans["result"] != "done" || ans["finished_at"] == nil {
+ t.Fatalf("report %+v, answered %v", rep, ans)
+ }
+ if got := elapsed(rep, rep.WaitEndedAt); got != 100*time.Second {
+ t.Fatalf("step 2 ended at %s, want 1m40s", got)
+ }
+ if !slices.Contains(rep.Reasons, "the settle did not end within 1m40s of the request") {
+ t.Fatalf("reasons %q", rep.Reasons)
+ }
+ if last := rep.Polls[len(rep.Polls)-1]; last.Error != "no answer within 1m40s of the request" {
+ t.Fatalf("the read out at 100 s was not abandoned: %+v", last)
+ }
+ if wait != 30*time.Second || budget != 40*time.Second {
+ t.Fatalf("step 3 given wait %s, deadline %s after step 2; want 30s and 40s", wait, budget)
+ }
+ if got := elapsed(rep, rep.FinishedAt); got != 140*time.Second || got >= ingressCallBound {
+ t.Fatalf("the report was final at %s; the route answers at %s", got, ingressCallBound)
+ }
+ if rep.Finished != 3 || rep.Closed != 2 || rep.CloseError != edge.ErrDrainNotIdle.Error() {
+ t.Fatalf("step 3's counts %+v", rep)
+ }
+}
+
+// The budget's parts add up: the wait's end (cap and settle), the
+// connection wait and the edge's join fit inside step 3's deadline, that
+// inside the route's bound, the route inside the helper's, and the
+// helper inside the drain unit's stop timeout.
+func TestIngressDrainBudgetAddsUp(t *testing.T) {
+ if ingressCap+ingressSettle+ingressConnWait+10*time.Second > ingressCloseBy {
+ t.Fatalf("cap %s + settle %s + wait %s + join 10s > step 3's deadline %s", ingressCap, ingressSettle, ingressConnWait, ingressCloseBy)
+ }
+ if ingressCloseBy+5*time.Second > ingressCallBound || ingressCallBound != 150*time.Second {
+ t.Fatalf("step 3 by %s, route bound %s; want the route at 150s with slack", ingressCloseBy, ingressCallBound)
+ }
+ stop := strings.Join(unitValues(readUnit(t, ingressDrainUnit), "[Service]TimeoutStopSec"), "")
+ if stop != "170" || ingressAskBound >= 170*time.Second {
+ t.Fatalf("drain unit TimeoutStopSec=%s, helper bound %s", stop, ingressAskBound)
+ }
+}
+
+// A read that would answer after the wait's end is abandoned there, even
+// when its answer would have finished the settle; and step 2 never sleeps
+// past that end.
+func TestIngressDrainAbandonsTheReadOutAtTheWaitsEnd(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(89*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.tg.delay = func(at time.Duration) time.Duration {
+ if at == 88*time.Second {
+ return time.Second // withdrawn first seen at 89 s
+ }
+ if at >= 97*time.Second {
+ return 4 * time.Second // would answer withdrawn at 101 s or later
+ }
+ return 0
+ }
+ rep := f.drain(t)
+ if rep.Verdict != ingressUnverified || elapsed(rep, rep.WaitEndedAt) > 101*time.Second {
+ t.Fatalf("verdict %s %q at %s", rep.Verdict, rep.Reasons, elapsed(rep, rep.WaitEndedAt))
+ }
+ if !slices.Contains(rep.Reasons, "the settle did not end within 1m40s of the request") {
+ t.Fatalf("reasons %q", rep.Reasons)
+ }
+}
+
+// An edge with no public listener to close (dev mode's plain HTTP) makes
+// the drain unverified, with the edge's reason, never withdrawn with the
+// listeners reported closed (W6 final review F7).
+func TestIngressDrainWithNoPublicListenersIsUnverified(t *testing.T) {
+ f := newIngressFixture(t, healthyUntil(6*time.Second, ingresshealth.StateUnhealthy, ingresshealth.StateUnhealthy))
+ f.edge.closeErr = edge.ErrNoPublicListeners
+ rep := f.drain(t)
+ if rep.Result != "done" || rep.Verdict != ingressUnverified || !slices.Equal(rep.Reasons, []string{edge.ErrNoPublicListeners.Error()}) ||
+ rep.CloseError != edge.ErrNoPublicListeners.Error() {
+ t.Fatalf("report %+v", rep)
+ }
+}
diff --git a/internal/host/units/carlos-edge-drain.service b/internal/host/units/carlos-edge-drain.service
index d0dc27532..b3b3e5abb 100644
--- a/internal/host/units/carlos-edge-drain.service
+++ b/internal/host/units/carlos-edge-drain.service
@@ -20,9 +20,11 @@ ExecStart=/bin/true
# case, and at once when the agent's socket does not answer (the edge has
# crashed, or a binary from before W6 is on disk during a rollback).
ExecStop=-/opt/carlos/carlos __ingress-drain
-# The 90 s cap, the 10 s settle, the 30 s connection wait, and slack. The
+# The agent's report is final 140 s after the ask (the 90 s cap, the 10 s
+# settle, the 30 s connection wait and the 10 s join), its route answers by
+# 150 s and the helper gives up at 155 s; this outlasts all of them. The
# edge's own TimeoutStopSec=120 is separate.
-TimeoutStopSec=150
+TimeoutStopSec=170
# --- the edge's hardening (carlos-edge.service), with no capabilities ---
# It runs as the agent's user: the drain socket serves only that user.
diff --git a/internal/host/units_ingress_drain_test.go b/internal/host/units_ingress_drain_test.go
index e988d1e00..bdb2fe363 100644
--- a/internal/host/units_ingress_drain_test.go
+++ b/internal/host/units_ingress_drain_test.go
@@ -82,7 +82,7 @@ func TestIngressDrainUnitShape(t *testing.T) {
"[Service]RemainAfterExit": "yes",
"[Service]ExecStart": "/bin/true",
"[Service]ExecStop": "-/opt/carlos/carlos __ingress-drain",
- "[Service]TimeoutStopSec": "150",
+ "[Service]TimeoutStopSec": "170",
"[Service]User": "carlos",
"[Service]Group": "carlos",
// Only the drain socket is dialled.