edge: held-stream review fixes (#432)
Human
Prompt
Task 5 fix round 1 (Astra round 1, four P2s and a P3).
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
no heartbeat inside a passed-through first-leg answer; a leg lasting ShortLeg resets the short-leg count however it ends (hold, swap, exempt); Location is stripped from every first-leg header copy; the simulation no longer excuses H2 by checker oversleep. An observation is conclusive only over a window with no oversleep past 20 ms, a seed runs until it has one (up to 10 s), and it fails as inconclusive otherwise. Encoded marker cases are pinned (carlos%5Fhold=1 and carlos_hold=%31 are marked). Unit tests use a 1 s write deadline except the two deadline tests, which keep 30 ms.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+163
−42
internal/edge/heldstream.go+10 −2internal/edge/heldstream_sim_test.go+42 −37internal/edge/heldstream_test.go+111 −3
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go| index ababa1a38..e0a2535dd 100644 |
| --- a/internal/edge/heldstream.go |
| +++ b/internal/edge/heldstream.go |
| @@ -388,7 +388,9 @@ func (t *heldTask) run() heldCloseReason { |
| t.scheduleReopen(true, 0) |
| } |
| case now := <-tickT.C: |
| - if t.committed && now.Sub(t.lastWrite) >= t.cfg.Tick { |
| + // No heartbeat inside a passed-through answer: its body goes to |
| + // the browser byte for byte. |
| + if t.committed && !t.passThrough && now.Sub(t.lastWrite) >= t.cfg.Tick { |
| if err := t.write([]byte(": ping\n")); err != nil { |
| return heldCloseWriteFailed |
| } |
| @@ -598,6 +600,11 @@ func (t *heldTask) legEnded() (heldCloseReason, bool) { |
| byActivator := run.leg.Context().Err() != nil && t.ctx.Err() == nil |
| lasted := time.Since(run.start) |
| t.retireLeg() |
| + // A leg that lasted ShortLeg or more resets the count however it ended |
| + // (§3.6), before the hold and exemption branches below. |
| + if lasted >= t.cfg.ShortLeg { |
| + t.shortLegs = 0 |
| + } |
| if !t.e.act.HeldAdmissible(t.host) { |
| if err := t.hold(); err != nil { |
| return heldCloseWriteFailed, true |
| @@ -615,7 +622,6 @@ func (t *heldTask) legEnded() (heldCloseReason, bool) { |
| } |
| t.scheduleReopen(false, t.backoff()) |
| default: |
| - t.shortLegs = 0 |
| t.scheduleReopen(false, 0) |
| } |
| return 0, false |
| @@ -649,6 +655,8 @@ func (t *heldTask) commit() error { |
| func (t *heldTask) writeFirstHead(status int, src http.Header, sse bool) error { |
| h := src.Clone() |
| removeHeldHopHeaders(h) |
| + // No first-leg answer redirects the browser (§3.3 step 3). |
| + h.Del("Location") |
| if sse { |
| h.Del("Content-Length") |
| h.Del("Content-Encoding") |
diff --git a/internal/edge/heldstream_sim_test.go b/internal/edge/heldstream_sim_test.go| index 4a9e68fcf..0c87e212c 100644 |
| --- a/internal/edge/heldstream_sim_test.go |
| +++ b/internal/edge/heldstream_sim_test.go |
| @@ -32,7 +32,12 @@ import ( |
| // H2: a stream not closed has an open leg once the host has been |
| // admissible, the stream has been running, and its last leg has been |
| // done for longer than Tick + ReopenSpacing + BackoffCap (spec G4: |
| -// outside a bounded reopen delay, no silent stream past one tick); |
| +// outside a bounded reopen delay, no silent stream past one tick). |
| +// An observation is conclusive only when the checker overslept by no |
| +// more than starveLimit anywhere in its window; others are skipped, |
| +// never excused by widening the bound. Each seed runs until it has at |
| +// least one conclusive H2 observation past the bound (up to maxRun) |
| +// and fails as inconclusive without one; |
| // H3: a stream never has two legs open at once. |
| // At the end of each seed every admitted leg must have been Done. |
| @@ -245,16 +250,18 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| t.Skip("simulation") |
| } |
| const ( |
| - seeds = 300 |
| - runFor = 600 * time.Millisecond |
| - slack = 25 * time.Millisecond // scheduler jitter under nice -n 19 |
| - checkEv = 5 * time.Millisecond |
| + seeds = 300 |
| + runFor = 600 * time.Millisecond |
| + maxRun = 10 * time.Second |
| + slack = 25 * time.Millisecond // fixed scheduler jitter allowance |
| + checkEv = 5 * time.Millisecond |
| + starveLimit = 20 * time.Millisecond |
| ) |
| cfg := heldTestConfig() |
| cfg.MaxHold = time.Minute |
| cfg.LegHeader = time.Second |
| bound := cfg.Tick + cfg.ReopenSpacing + cfg.BackoffCap + slack |
| - var totalAdmitted, totalClosedShort, excused int |
| + var totalAdmitted, totalClosedShort, conclusiveTotal, skipped int |
| var maxLag time.Duration |
| for seed := int64(1); seed <= seeds; seed++ { |
| m := newSimModel(seed) |
| @@ -330,33 +337,21 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| } |
| }() |
| - // Check the invariants. The checker measures its own oversleep: on |
| - // a loaded box under nice -n 19 every goroutine here can lose tens |
| - // of milliseconds, and H2 is a bound on the task's logic, not on the |
| - // scheduler. An H2 window is excused only by the time the checker |
| - // itself was starved inside it. |
| - var starved []struct { |
| - at time.Time |
| - lag time.Duration |
| - } |
| - starvedIn := func(from time.Time) time.Duration { |
| - var sum time.Duration |
| - for _, s := range starved { |
| - if s.at.After(from) { |
| - sum += s.lag |
| - } |
| - } |
| - return sum |
| - } |
| - for time.Since(start) < runFor { |
| + // Check the invariants. The checker measures its own oversleep; an H2 |
| + // window it was starved in for more than starveLimit says nothing |
| + // about the stream task, so that observation is skipped. A fresh |
| + // window starts when the oversleep ends: the bound is never widened, |
| + // it is only measured over a window with no oversleep in it. |
| + var lastStarve time.Time |
| + starves := 0 |
| + conclusive := 0 |
| + for time.Since(start) < runFor || (conclusive == 0 && time.Since(start) < maxRun) { |
| before := time.Now() |
| time.Sleep(checkEv) |
| now := time.Now() |
| - if lag := now.Sub(before) - checkEv; lag > time.Millisecond { |
| - starved = append(starved, struct { |
| - at time.Time |
| - lag time.Duration |
| - }{now, lag}) |
| + if lag := now.Sub(before) - checkEv; lag > starveLimit { |
| + lastStarve = now |
| + starves++ |
| maxLag = max(maxLag, lag) |
| } |
| if m.served.Load() != 0 { |
| @@ -376,11 +371,14 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| if le := m.lastLegEnd[i]; le.After(quiet) { |
| quiet = le |
| } |
| - if q := now.Sub(quiet); q > bound && m.open[i] == 0 { |
| - if ex := starvedIn(quiet); q <= bound+ex { |
| - excused++ |
| - } else { |
| - m.violate("H2: stream %d has no leg %v into an admissible window (bound %v, checker starved %v)", i, q, bound, ex) |
| + if q := now.Sub(quiet); q > bound { |
| + if now.Sub(lastStarve) <= bound { |
| + skipped++ // no unstarved window past the bound yet |
| + continue |
| + } |
| + conclusive++ |
| + if m.open[i] == 0 { |
| + m.violate("H2: stream %d has no leg %v into an admissible window (bound %v)", i, q, bound) |
| } |
| } |
| } |
| @@ -399,6 +397,13 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| } |
| } |
| + if conclusive == 0 { |
| + close(stopDrive) |
| + cancel() |
| + t.Fatalf("seed %d: inconclusive: no H2 observation past the bound in an unstarved window within %v (%d checker oversleeps over %v)", seed, maxRun, starves, starveLimit) |
| + } |
| + conclusiveTotal += conclusive |
| + |
| close(stopDrive) |
| <-driveDone |
| cancel() |
| @@ -420,8 +425,8 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| } |
| totalClosedShort += int(closedShort.Load()) |
| } |
| - t.Logf("%d seeds: %d legs admitted, %d streams closed by short legs; H2 checks excused by checker starvation: %d (worst checker oversleep %v)", |
| - seeds, totalAdmitted, totalClosedShort, excused, maxLag) |
| + t.Logf("%d seeds: %d legs admitted, %d streams closed by short legs; H2 observations past the bound: %d conclusive, %d skipped as starved (worst checker oversleep over %v: %v)", |
| + seeds, totalAdmitted, totalClosedShort, conclusiveTotal, skipped, starveLimit, maxLag) |
| if totalAdmitted == 0 { |
| t.Fatal("no leg was ever admitted") |
| } |
diff --git a/internal/edge/heldstream_test.go b/internal/edge/heldstream_test.go| index cac07ce50..c8a757de2 100644 |
| --- a/internal/edge/heldstream_test.go |
| +++ b/internal/edge/heldstream_test.go |
| @@ -25,7 +25,10 @@ func heldTestConfig() HeldConfig { |
| return HeldConfig{ |
| PerHost: 64, PerBox: 4096, |
| MaxHold: 2 * time.Second, Commit: 20 * time.Millisecond, LegHeader: time.Second, |
| - WriteDeadline: 30 * time.Millisecond, Tick: 50 * time.Millisecond, |
| + // The brief's 30 ms write deadline is set only by the tests about |
| + // deadlines; elsewhere a starved test process must not turn a slow |
| + // first write into a closed connection. |
| + WriteDeadline: time.Second, Tick: 50 * time.Millisecond, |
| ReopenSpacing: 10 * time.Millisecond, ShortLeg: 200 * time.Millisecond, BackoffCap: 100 * time.Millisecond, |
| ShortLegsToClose: 5, |
| } |
| @@ -158,7 +161,12 @@ func (h *heldHarness) get(t *testing.T, path string, hdr map[string]string) *htt |
| } |
| resp, err := h.srv.Client().Do(req) |
| if err != nil { |
| - t.Fatalf("get: %v", err) |
| + select { |
| + case r := <-h.ends: |
| + t.Fatalf("get: %v (stream closed: %v)", err, r) |
| + case <-time.After(100 * time.Millisecond): |
| + t.Fatalf("get: %v", err) |
| + } |
| } |
| t.Cleanup(func() { resp.Body.Close() }) |
| return resp |
| @@ -498,7 +506,9 @@ func TestHeldHTTP2IdleSurvivesWriteDeadline(t *testing.T) { |
| if resp.ProtoMajor != 2 { |
| t.Fatalf("proto %s", resp.Proto) |
| } |
| - body, err := readFor(resp.Body, 550*time.Millisecond) |
| + // About nine heartbeats are due in a second; four leaves room for a |
| + // loaded box. The point is that the stream is never reset. |
| + body, err := readFor(resp.Body, time.Second) |
| if err != nil { |
| t.Fatalf("stream ended: %v (body %q)", err, body) |
| } |
| @@ -509,6 +519,7 @@ func TestHeldHTTP2IdleSurvivesWriteDeadline(t *testing.T) { |
| func TestHeldBlockedWriteEnds(t *testing.T) { |
| cfg := heldTestConfig() |
| + cfg.WriteDeadline = 30 * time.Millisecond |
| cfg.MaxHold = time.Minute |
| big := "data: " + strings.Repeat("x", 16<<10) + "\n\n" |
| // lastSent is when the proxy's last write was taken off the pipe; the |
| @@ -573,6 +584,11 @@ func TestStripHoldMarker(t *testing.T) { |
| {"b=%2f&a=x+y&&carlos_hold=1&c", "b=%2f&a=x+y&&c", true}, |
| {"carlos_hold=1&z=%E2%9C%93", "z=%E2%9C%93", true}, |
| {"carlos_hold", "carlos_hold", false}, |
| + // The marker is the decoded parameter: an encoded key or value that |
| + // decodes to carlos_hold=1 is marked and stripped. |
| + {"carlos%5Fhold=1&a=1", "a=1", true}, |
| + {"a=1&carlos_hold=%31", "a=1", true}, |
| + {"carlos_hold=%32", "carlos_hold=%32", false}, |
| } { |
| out, marked := stripHoldMarker(c.in) |
| if out != c.out || marked != c.marked { |
| @@ -580,3 +596,95 @@ func TestStripHoldMarker(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// Fix round 1, P2-1: a pass-through body arrives byte for byte; no heartbeat |
| +// is written into it however long it pauses. |
| +func TestHeldPassThroughDelayedBodyNoPings(t *testing.T) { |
| + for _, fixed := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("content-length=%v", fixed), func(t *testing.T) { |
| + h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/plain") |
| + if fixed { |
| + w.Header().Set("Content-Length", "10") |
| + } |
| + w.WriteHeader(http.StatusUnauthorized) |
| + _, _ = io.WriteString(w, "sign ") |
| + w.(http.Flusher).Flush() |
| + time.Sleep(4 * heldTestConfig().Tick) |
| + _, _ = io.WriteString(w, "in ok") |
| + }) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + body, err := io.ReadAll(resp.Body) |
| + if resp.StatusCode != http.StatusUnauthorized || string(body) != "sign in ok" || err != nil { |
| + t.Fatalf("status %d body %q err %v", resp.StatusCode, body, err) |
| + } |
| + if fixed && resp.ContentLength != 10 { |
| + t.Fatalf("Content-Length %d", resp.ContentLength) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Fix round 1, P2-2: a leg lasting ShortLeg or more resets the short-leg |
| +// count however it ends, across a sleep or a swap. |
| +func TestHeldLongLegResetsShortCount(t *testing.T) { |
| + for _, via := range []string{"sleep", "swap"} { |
| + t.Run(via, func(t *testing.T) { |
| + cfg := heldTestConfig() |
| + // Legs 0-3 short, leg 4 long and ended by the activator, legs 5-6 |
| + // short, leg 7 stays open. Without the reset, leg 6 (sleep: leg 5 |
| + // is the exempt leg after the hold) or leg 5 (swap) would be the |
| + // fifth short leg in a row and close the stream. |
| + h := newHeldHarness(t, cfg, func(n int, w http.ResponseWriter, r *http.Request) { |
| + sseHead(w) |
| + sseSend(w, fmt.Sprintf("id: %d\ndata: x\n\n", n)) |
| + if n == 4 || n >= 7 { |
| + <-r.Context().Done() |
| + } |
| + }) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + go func() { _, _ = io.Copy(io.Discard, resp.Body) }() |
| + waitFor(t, 3*time.Second, "leg 4", func() bool { return len(h.proxy.legs()) == 5 }) |
| + time.Sleep(cfg.ShortLeg + 50*time.Millisecond) |
| + if via == "sleep" { |
| + h.act.asleep.Store(true) |
| + h.act.lastLeg().cancel() |
| + time.Sleep(20 * time.Millisecond) |
| + h.act.asleep.Store(false) |
| + h.e.held.wake(heldTestHost) |
| + } else { |
| + h.act.lastLeg().cancel() |
| + } |
| + waitFor(t, 3*time.Second, "leg 7", func() bool { return len(h.proxy.legs()) == 8 }) |
| + select { |
| + case r := <-h.ends: |
| + t.Fatalf("stream closed: %v", r) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Fix round 1, P2-4: no Location reaches the browser from a first leg. |
| +func TestHeldFirstLegStripsLocation(t *testing.T) { |
| + for _, status := range []int{http.StatusOK, http.StatusUnauthorized} { |
| + t.Run(fmt.Sprint(status), func(t *testing.T) { |
| + h := newHeldHarness(t, heldTestConfig(), func(_ int, w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Location", "/login") |
| + if status == http.StatusOK { |
| + sseHead(w) |
| + <-r.Context().Done() |
| + return |
| + } |
| + w.WriteHeader(status) |
| + }) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + if resp.StatusCode != status || resp.Header.Get("Location") != "" { |
| + t.Fatalf("status %d headers %v", resp.StatusCode, resp.Header) |
| + } |
| + }) |
| + } |
| +} |