carlos / platform Public

edge: held-stream dispatch review fixes (#432)

Human

Prompt

Task 6 review round 1 (five P2s, Ruling T6-a): login
re-resolution, door-scope redirect, reload vs late registration, HA lock
reads for marked requests, asset bypass witnesses.

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

classification is classifyHold, run again on a login POST's
settled upstream (marker stripped only then). A marked request failing
door scope gets the plain 404, never the fallback redirect. serveHeld
registers, then checks the published map (holdsHost) and closes an
unmanaged stream with an empty event stream before any leg; Reload
already publishes before its sweep. frontForwardHA routes a marked
request to a hibernating HA route from memory only
(HAForwarderFromMemory; the activator's ForwardTargetFromMemory peeks the
holder cache); a miss gets the retry event, a non-stream marked request
is left to the 400. Witnesses for each fix and each asset guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev edba0ba197ba91fee4887263bf612788a210e356 parent e8cc112
7 files changed, +519 −29
  • internal/activator/hacache.go +20 −0
  • internal/activator/haforward.go +40 −5
  • internal/activator/haforward_test.go +23 −0
  • internal/edge/edge.go +94 −22
  • internal/edge/forwardha.go +35 −2
  • internal/edge/heldstream.go +16 −0
  • internal/edge/heldstream_dispatch_test.go +291 −0
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go
index d950bda4d..23426cb13 100644
--- a/internal/activator/hacache.go
+++ b/internal/activator/hacache.go
@@ -234,6 +234,26 @@ type holderResolution struct {
View *hafresh.View
}
+// peek is host's live entry as resolve would answer it, without reading
+// or joining a read: hit false when there is none (or only an expired
+// one, which is left for resolve to handle).
+func (c *holderCache) peek(host string) (_ holderResolution, hit bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ el := c.holders[host]
+ if el == nil {
+ return holderResolution{}, false
+ }
+ e := el.Value.(*holderEntry)
+ if !c.clock().Before(e.expires) {
+ return holderResolution{}, false
+ }
+ if e.suspect {
+ return holderResolution{Refuse: true}, true
+ }
+ return holderResolution{Ref: e.ref, Gen: e.gen, View: e.view}, true
+}
+
func (c *holderCache) resolve(ctx context.Context, host string, read func() holderRead) holderResolution {
deadline := time.Now().Add(2 * holderReadTimeout)
for time.Now().Before(deadline) {
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go
index d79c0a0f8..56d244027 100644
--- a/internal/activator/haforward.go
+++ b/internal/activator/haforward.go
@@ -107,20 +107,51 @@ var holderReadErrLogged atomic.Int64
// together, and an unexpired HA lease of another box sets the entry,
// anything else the negative one. A read that fails caches nothing.
func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot) edge.ForwardDecision {
+ d, _ := a.forwardTarget(ctx, rt, snapshot, false)
+ return d
+}
+
+// ForwardTargetFromMemory is ForwardTarget without the lock read, for a
+// request on the edge-held streams path (spec 2026-10-28 §2, §4): ok is
+// false when the answer would need a read (no live holder-cache entry),
+// and nothing is read or waited on.
+func (a *Service) ForwardTargetFromMemory(rt registry.Route, snapshot func() boxchoice.WakeSnapshot) (edge.ForwardDecision, bool) {
+ return a.forwardTarget(context.Background(), rt, snapshot, true)
+}
+
+var _ edge.HAForwarderFromMemory = (*Service)(nil)
+
+// forwardTarget is ForwardTarget; with memoryOnly, a holder-cache miss
+// answers ok false instead of reading the lock.
+func (a *Service) forwardTarget(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot, memoryOnly bool) (edge.ForwardDecision, bool) {
if !rt.HA {
- return edge.ForwardDecision{}
+ return edge.ForwardDecision{}, true
}
r := holderReaderFor(a.backend, rt)
if r == nil {
- return edge.ForwardDecision{}
+ return edge.ForwardDecision{}, true
}
a.mu.Lock()
here := a.entries[rt.Host] != nil
a.mu.Unlock()
if here {
- return edge.ForwardDecision{}
+ return edge.ForwardDecision{}, true
}
- resolved := a.holders.resolve(ctx, rt.Host, func() holderRead {
+ var resolved holderResolution
+ if memoryOnly {
+ var hit bool
+ if resolved, hit = a.holders.peek(rt.Host); !hit {
+ return edge.ForwardDecision{}, false
+ }
+ } else {
+ resolved = a.holders.resolve(ctx, rt.Host, a.holderReadFor(ctx, rt, r))
+ }
+ return a.decideForward(rt, r, resolved, snapshot), true
+}
+
+// holderReadFor is resolve's read of rt's lock through r.
+func (a *Service) holderReadFor(ctx context.Context, rt registry.Route, r holderLockReader) func() holderRead {
+ return func() holderRead {
// The read is every queued caller's, not only this one's: detached
// from this request's cancellation, so one visitor hanging up does
// not fail the rest, and bounded on its own.
@@ -135,7 +166,11 @@ func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route, snapshot
return holderRead{Err: err}
}
return holderRead{Ref: otherHolder(v, r.self(), a.holders.clock()), View: &v}
- })
+ }
+}
+
+// decideForward turns a holder resolution into the edge's decision.
+func (a *Service) decideForward(rt registry.Route, r holderLockReader, resolved holderResolution, snapshot func() boxchoice.WakeSnapshot) edge.ForwardDecision {
if resolved.Refuse {
return edge.ForwardDecision{Refuse: true}
}
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go
index 08e68de67..96334bb6f 100644
--- a/internal/activator/haforward_test.go
+++ b/internal/activator/haforward_test.go
@@ -509,3 +509,26 @@ func TestForwardTargetStalledReadIsBounded(t *testing.T) {
t.Fatalf("the lookup after the stall: %q with %d reads, want b and 1", ref, lockGets(s.b, s.rt))
}
}
+
+// ForwardTargetFromMemory (edge-held streams, T6 review finding 4) never
+// reads the lock: a holder-cache miss answers ok false with no read, and
+// once the cache knows the holder it answers as ForwardTarget does.
+func TestForwardTargetFromMemoryNeverReadsTheLock(t *testing.T) {
+ s := haHeldByB(t)
+ if d, ok := s.a.ForwardTargetFromMemory(s.rt, nil); ok {
+ t.Fatalf("ForwardTargetFromMemory on a miss = %+v, ok; want not ok", d)
+ }
+ if n := lockGets(s.b, s.rt); n != 0 {
+ t.Fatalf("%d lock reads on a memory-only miss, want 0", n)
+ }
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "b" {
+ t.Fatalf("ForwardTarget = %q, want b", got)
+ }
+ d, ok := s.a.ForwardTargetFromMemory(s.rt, nil)
+ if !ok || d.Ref != "b" {
+ t.Fatalf("ForwardTargetFromMemory on a hit = %+v, %v; want b", d, ok)
+ }
+ if n := lockGets(s.b, s.rt); n != 1 {
+ t.Fatalf("%d lock reads, want only ForwardTarget's 1", n)
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index a6b494e5a..c7dcb98e8 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2053,32 +2053,22 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 2), on the upstream this box will serve, before the login POST
// handling, the gate or anything else can answer the request. After the
// HA forward above, which only proxies to the lease holder: that box
- // classifies, as a tunnel's box does. A marked request to a hibernating
- // route is either a held-stream request, flagged for the hold branch
- // after the gate, or answered 400 here; to a route served over a tunnel
- // or fleet channel it goes on untouched, for the receiving edge to
- // classify; to any other route the marker is stripped and the request
- // served as an ordinary one. up only changes after this through the
- // login POST's re-resolution, and a login POST is always answered by
- // the gate or passed down a tunnel, never handed to the activator.
+ // classifies, as a tunnel's box does (frontForwardHA decides a marked
+ // request's forward from memory alone). See classifyHold.
+ //
+ // A login POST re-resolves its upstream by `next` below, so it is
+ // classified again once that settles (T6 review finding 1): a marked
+ // login POST whose `next` lands on a hibernating route is answered 400
+ // there rather than given the gate's redirect. Its marker is stripped
+ // only on that second pass, so a login passed down a tunnel keeps it.
//
// up.hibernating is false on every viaTunnel entry and whenever this
// edge has no activator (Reload), so the hold branch is unreachable on
// `carlos edge`.
- held := false
- if markedRequest(r) {
- switch {
- case up.hibernating && up.route.Hibernate:
- if !isHeldStreamRequest(r) {
- w.Header().Set("Cache-Control", "no-store")
- http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
- return
- }
- held = true
- case up.viaTunnel:
- default:
- r = withoutHoldMarker(r)
- }
+ isLogin := r.Method == http.MethodPost && r.URL.Path == gate.LoginPath
+ r, held, answered := classifyHold(w, r, up, !isLogin)
+ if answered {
+ return
}
// A login POST re-resolves its upstream by the path in `next`, not by
@@ -2199,7 +2189,21 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// prefix is refused before the gate judges its password, and before the
// meter, the gate, the cache and the dispatch below, which all use this
// same up.
+ // The second classification of a login POST, on the upstream its
+ // `next` settled on (see the first, above).
+ if isLogin {
+ if r, held, answered = classifyHold(w, r, up, true); answered {
+ return
+ }
+ }
if isDoor && !doorOwnsRoute(door, up.route) {
+ // A marked request gets the plain unknown-host 404, never the
+ // fallback redirect, which a client would follow unmarked (T6
+ // review finding 2).
+ if markedRequest(r) {
+ http.Error(w, "unknown host", http.StatusNotFound)
+ return
+ }
e.unknownHost(w, r)
return
}
@@ -2618,6 +2622,38 @@ func isHeldStreamRequest(r *http.Request) bool {
return false
}
+// classifyHold is the edge-held streams classification (spec 2026-10-28
+// §3.1) of r against up, the upstream this box will serve it from. An
+// unmarked request passes unchanged. A marked request to a hibernating
+// route (up.hibernating && up.route.Hibernate) is either a held-stream
+// request (held true, query untouched: serveHeld strips it per leg) or
+// answered 400 here (answered true). To a route served over a tunnel or
+// fleet channel it passes untouched, for the receiving edge to classify. To
+// any other route its marker is stripped, when strip is set, and it is
+// served as an ordinary request. It reads the mark ServeHTTP recorded
+// (markedRequest), never the query, so it can run again after the query
+// has been cleaned.
+func classifyHold(w http.ResponseWriter, r *http.Request, up upstream, strip bool) (_ *http.Request, held, answered bool) {
+ if !markedRequest(r) {
+ return r, false, false
+ }
+ switch {
+ case up.hibernating && up.route.Hibernate:
+ if !isHeldStreamRequest(r) {
+ w.Header().Set("Cache-Control", "no-store")
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return r, false, true
+ }
+ return r, true, false
+ case up.viaTunnel:
+ return r, false, false
+ }
+ if strip {
+ r = withoutHoldMarker(r)
+ }
+ return r, false, false
+}
+
// withoutHoldMarker returns a shallow copy of r whose query has every
// carlos_hold=1 pair removed and the rest kept byte for byte. r and its URL
// are left as they were.
@@ -2633,6 +2669,42 @@ func withoutHoldMarker(r *http.Request) *http.Request {
return r2
}
+// answerHeldRetry writes the held-stream over-cap answer (one retry event,
+// spec §3.6) with this edge's write deadline.
+func (e *Edge) answerHeldRetry(w http.ResponseWriter) {
+ d := DefaultHeldConfig.WriteDeadline
+ if e.held != nil {
+ d = e.held.cfg.WriteDeadline
+ }
+ writeHeldRetry(w, d)
+}
+
+// writeHeldClosed answers a held-stream request this edge stopped holding
+// before its stream began: an empty event stream, which the browser's
+// EventSource reconnects from as it does from a held stream closed by a
+// reload (§3.4), and the new map routes the reconnect.
+func writeHeldClosed(w http.ResponseWriter, deadline time.Duration) {
+ rc := http.NewResponseController(w)
+ _ = rc.SetWriteDeadline(time.Now().Add(deadline))
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(http.StatusOK)
+ _ = rc.Flush()
+ _ = rc.SetWriteDeadline(time.Time{})
+}
+
+// holdsHost reports whether the upstream map now published names host as a
+// hibernating route this edge holds streams for. An edge that has published
+// no map yet (a bare Edge in a unit test) does not judge: true.
+func (e *Edge) holdsHost(host string) bool {
+ m := e.upstreams.Load()
+ if m == nil {
+ return true
+ }
+ u, ok := (*m)[host]
+ return ok && u.hibernating && u.route.Hibernate
+}
+
// HeldWake tells this edge's held streams for host that it may have become
// admissible (the activator's held wake hook, SetHeldWakeHook). It never
// blocks.
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
index 6414a13b6..7273c7cc5 100644
--- a/internal/edge/forwardha.go
+++ b/internal/edge/forwardha.go
@@ -43,6 +43,15 @@ type HAForwarder interface {
NoteForward(host string, res ForwardResult)
}
+// HAForwarderFromMemory is the in-memory half of HAForwarder, for a request
+// on the edge-held streams path (spec 2026-10-28 §2, §4: no bucket read on
+// the hold path). ForwardTargetFromMemory answers as ForwardTarget would
+// when that answer needs no read of the host's lock; ok is false when it
+// would (a holder-cache miss), and nothing is read.
+type HAForwarderFromMemory interface {
+ ForwardTargetFromMemory(rt registry.Route, snapshot func() boxchoice.WakeSnapshot) (d ForwardDecision, ok bool)
+}
+
// ForwardKind distinguishes lease holders from short-lived routing advice.
type ForwardKind uint8
@@ -172,13 +181,37 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin
if !ok {
return false
}
- d := fw.ForwardTarget(r.Context(), up.route, func() boxchoice.WakeSnapshot {
+ snapshot := func() boxchoice.WakeSnapshot {
m := e.homes.Load()
if m == nil {
return boxchoice.WakeSnapshot{}
}
return m.wakeSnapshot(up.route, time.Now())
- })
+ }
+ var d ForwardDecision
+ if markedRequest(r) && up.route.Hibernate {
+ // A marked request to a hibernating HA route (edge-held streams
+ // T6 review finding 4) is routed from memory only: the hold path
+ // reads no bucket. One that is not a held-stream request is left to
+ // this box's classification, which answers it 400 as the holder
+ // would. A held-stream request whose holder is not known without a
+ // lock read gets the over-cap answer, one retry event, and the
+ // browser comes back once the cache has learned the holder from
+ // other traffic.
+ if !isHeldStreamRequest(r) {
+ return false
+ }
+ mem, ok := fw.(HAForwarderFromMemory)
+ if ok {
+ d, ok = mem.ForwardTargetFromMemory(up.route, snapshot)
+ }
+ if !ok {
+ e.answerHeldRetry(w)
+ return true
+ }
+ } else {
+ d = fw.ForwardTarget(r.Context(), up.route, snapshot)
+ }
if d.Unavailable {
w.Header().Set("Retry-After", "10")
MarkAnswered(r)
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go
index e0a2535dd..05ce566ca 100644
--- a/internal/edge/heldstream.go
+++ b/internal/edge/heldstream.go
@@ -84,6 +84,9 @@ type heldSet struct {
// onFinish is a test seam, nil in production: called after a stream
// has left the set.
onFinish func(host string, r heldCloseReason)
+ // beforeRegister is a test seam, nil in production: called by
+ // serveHeld just before it registers a stream.
+ beforeRegister func()
}
// heldStream is one held stream's entry in the set: the signals other
@@ -222,6 +225,9 @@ func (e *Edge) serveHeld(w http.ResponseWriter, r *http.Request, rt registry.Rou
s := e.held
var st *heldStream
if s != nil && e.act != nil {
+ if s.beforeRegister != nil {
+ s.beforeRegister()
+ }
st = s.register(rt.Host)
}
if st == nil {
@@ -232,6 +238,16 @@ func (e *Edge) serveHeld(w http.ResponseWriter, r *http.Request, rt registry.Rou
writeHeldRetry(w, d)
return
}
+ // Registered first, then judged against the map published now (T6
+ // review finding 3). Reload publishes its map before it sweeps the
+ // held set, so a stream registered after the sweep sees the new map
+ // here and one registered before it is swept. One this edge no longer
+ // holds is closed before any leg is admitted.
+ if !e.holdsHost(rt.Host) {
+ s.finish(st, heldCloseUnmanaged)
+ writeHeldClosed(w, s.cfg.WriteDeadline)
+ return
+ }
t := &heldTask{
e: e, cfg: s.cfg, st: st, host: rt.Host, rt: rt, proxy: proxy,
w: w, rc: http.NewResponseController(w), r: r,
diff --git a/internal/edge/heldstream_dispatch_test.go b/internal/edge/heldstream_dispatch_test.go
index 3d616b114..78ef8ef13 100644
--- a/internal/edge/heldstream_dispatch_test.go
+++ b/internal/edge/heldstream_dispatch_test.go
@@ -7,6 +7,7 @@ package edge
// Every request goes through Edge.ServeHTTP on a real listener.
import (
+ "context"
"io"
"net"
"net/http"
@@ -18,6 +19,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/gate"
"github.com/carlosframework/platform/internal/registry"
)
@@ -301,3 +303,292 @@ func TestReloadClosesHeldStreamsForUnmanagedHost(t *testing.T) {
t.Fatal("held stream still open 3s after a reload made the host always-on")
}
}
+
+// ---- fix round 1 (T6 review) --------------------------------------------
+
+// A marked login POST on an always-on front whose `next` resolves to a
+// gated hibernating prefix target is classified again on that target and
+// answered 400, not given the gate's redirect (finding 1).
+func TestMarkedLoginPostToHibernatingPrefixIs400(t *testing.T) {
+ front, frontSeen := hostEchoBackend(t, "the front app")
+ target := newDispatchUpstream(t, okUpstream)
+ h, err := gate.Hash("correct horse")
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "front.example.com", Kind: "service",
+ Addr: front.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(registry.Route{Host: "gated.example.com", Kind: "instance",
+ Addr: target.addr(), Status: "ready", Hibernate: true, Gate: h}); err != nil {
+ t.Fatal(err)
+ }
+ upsertPath(t, reg, "front.example.com", "paulca", "gated.example.com")
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ e, err := New(reg, act)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.SetHeldConfig(heldTestConfig())
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+
+ login := func(target string) *http.Response {
+ form := url.Values{"password": {"correct horse"}, "next": {"/paulca/live"}}
+ return dispatchDo(t, srv, http.MethodPost, "front.example.com", target,
+ map[string]string{"Content-Type": "application/x-www-form-urlencoded"}, strings.NewReader(form.Encode()))
+ }
+ // Control: unmarked, the target's gate answers 303.
+ if resp := login(gate.LoginPath); resp.StatusCode != http.StatusSeeOther {
+ t.Fatalf("control: unmarked login POST = %d, want 303", resp.StatusCode)
+ }
+ resp := login(gate.LoginPath + "?carlos_hold=1")
+ if resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("marked login POST to a hibernating prefix = %d (Location %q), want 400", resp.StatusCode, resp.Header.Get("Location"))
+ }
+ if gateCookie(resp) != "" {
+ t.Fatal("a marked login POST was given a gate cookie")
+ }
+ if *frontSeen != "" || target.hits.Load() != 0 || act.served.Load() != 0 {
+ t.Fatalf("reached: front %q, target %d, activator %d", *frontSeen, target.hits.Load(), act.served.Load())
+ }
+}
+
+// A marked request that fails the door's scope gets the plain unknown-host
+// 404, never the fallback redirect (finding 2).
+func TestMarkedDoorScopeRefusalDoesNotRedirect(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ act := &scriptActivator{}
+ act.asleep.Store(true)
+ rt := heldRoute(up.addr())
+ rt.Account, rt.App = "abc", "web"
+ e, _, _ := newDispatchEdge(t, act, heldTestConfig(), rt)
+ e.fallbackURL = "https://fallback.example.org/"
+ serve := func(target string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodGet, "http://"+heldTestHost+target, nil)
+ req.Header.Set("Accept", "text/event-stream")
+ req = req.WithContext(context.WithValue(req.Context(), doorCallerKey{}, doorCaller{Account: "other", App: "app"}))
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+ return rec
+ }
+ if rec := serve("/live"); rec.Code != http.StatusFound {
+ t.Fatalf("control: unmarked out-of-scope door call = %d, want the fallback 302", rec.Code)
+ }
+ rec := serve("/live?carlos_hold=1")
+ if rec.Code != http.StatusNotFound || rec.Header().Get("Location") != "" {
+ t.Fatalf("marked out-of-scope door call = %d Location %q, want 404 and no redirect", rec.Code, rec.Header().Get("Location"))
+ }
+ if act.served.Load() != 0 || up.hits.Load() != 0 {
+ t.Fatalf("activator %d, upstream %d, want 0", act.served.Load(), up.hits.Load())
+ }
+}
+
+// A held stream that registers after a reload stopped this edge holding its
+// host is closed before any leg is admitted (finding 3). The request is
+// paused just before registration while the reload completes.
+func TestHeldStreamRegisteredAfterReloadIsClosed(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ act := &scriptActivator{} // awake: an unchecked stream would admit a leg
+ cfg := heldTestConfig()
+ cfg.MaxHold = 30 * time.Second
+ rt := heldRoute(up.addr())
+ e, reg, front := newDispatchEdge(t, act, cfg, rt)
+ reached, resume := make(chan struct{}), make(chan struct{})
+ var once sync.Once
+ e.held.beforeRegister = func() {
+ once.Do(func() {
+ close(reached)
+ <-resume
+ })
+ }
+ ends := make(chan heldCloseReason, 4)
+ e.held.onFinish = func(_ string, r heldCloseReason) { ends <- r }
+
+ type result struct {
+ resp *http.Response
+ body string
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ req, _ := http.NewRequest(http.MethodGet, front.URL+"/live?carlos_hold=1", nil)
+ req.Host = heldTestHost
+ req.Header.Set("Accept", "text/event-stream")
+ resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
+ if err != nil {
+ done <- result{err: err}
+ return
+ }
+ b, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ done <- result{resp: resp, body: string(b), err: err}
+ }()
+ select {
+ case <-reached:
+ case <-time.After(5 * time.Second):
+ close(resume)
+ t.Fatal("the request never reached registration")
+ }
+ rt.Hibernate = false
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ close(resume)
+ select {
+ case res := <-done:
+ if res.err != nil {
+ t.Fatalf("held request: %v", res.err)
+ }
+ if res.resp.StatusCode != http.StatusOK || res.resp.Header.Get("Content-Type") != "text/event-stream" || res.body != "" {
+ t.Fatalf("got %d %q %q, want an empty event stream", res.resp.StatusCode, res.resp.Header.Get("Content-Type"), res.body)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("the stream registered after the reload is still open")
+ }
+ if r := <-ends; r != heldCloseUnmanaged {
+ t.Fatalf("close reason %v, want unmanaged", r)
+ }
+ if n := act.admits.Load(); n != 0 {
+ t.Fatalf("%d legs admitted for a host this edge no longer holds", n)
+ }
+ if n := up.hits.Load(); n != 0 {
+ t.Fatalf("upstream hits = %d, want 0", n)
+ }
+}
+
+// haHoldActivator is a sleeping instance that is born HA: ForwardTarget
+// counts the decisions that would read the lock; ForwardTargetFromMemory
+// answers mem/memOK.
+type haHoldActivator struct {
+ *scriptActivator
+ reads atomic.Int64
+ mem ForwardDecision
+ memOK bool
+}
+
+var _ HAForwarderFromMemory = (*haHoldActivator)(nil)
+
+func (a *haHoldActivator) ForwardTarget(context.Context, registry.Route, func() boxchoice.WakeSnapshot) ForwardDecision {
+ a.reads.Add(1)
+ return ForwardDecision{}
+}
+func (a *haHoldActivator) NoteForward(string, ForwardResult) {}
+func (a *haHoldActivator) ForwardTargetFromMemory(registry.Route, func() boxchoice.WakeSnapshot) (ForwardDecision, bool) {
+ return a.mem, a.memOK
+}
+
+// A marked request to a hibernating HA route is routed from memory only: on
+// a holder-cache miss a held-stream request gets the retry answer, and
+// nothing calls the lock-reading ForwardTarget (finding 4).
+func TestMarkedHARequestNeverReadsTheLock(t *testing.T) {
+ up := newDispatchUpstream(t, okUpstream)
+ act := &haHoldActivator{scriptActivator: &scriptActivator{}}
+ act.asleep.Store(true)
+ rt := heldRoute(up.addr())
+ rt.HA = true
+ _, _, front := newDispatchEdge(t, act, heldTestConfig(), rt)
+
+ // Holder-cache miss: one retry event.
+ resp := dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?carlos_hold=1", sseAccept, nil)
+ b, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "text/event-stream" ||
+ resp.Header.Get("Cache-Control") != "no-store" || string(b) != "retry: 30000\n\n" {
+ t.Fatalf("miss: %d %q %q %q, want the retry answer", resp.StatusCode, resp.Header.Get("Content-Type"), resp.Header.Get("Cache-Control"), b)
+ }
+ // A marked request that is not a held-stream request: 400 here.
+ if resp := dispatchDo(t, front, http.MethodPost, heldTestHost, "/live?carlos_hold=1", sseAccept, nil); resp.StatusCode != http.StatusBadRequest {
+ t.Fatalf("marked POST = %d, want 400", resp.StatusCode)
+ }
+ // A hit that says "serve here": held on this edge.
+ act.memOK = true
+ resp = dispatchDo(t, front, http.MethodGet, heldTestHost, "/live?carlos_hold=1", sseAccept, nil)
+ if got, _ := readFor(resp.Body, 300*time.Millisecond); resp.StatusCode != http.StatusOK || !strings.Contains(got, ": ping\n") {
+ t.Fatalf("hit, serve here: %d %q, want a held stream", resp.StatusCode, got)
+ }
+ if n := act.reads.Load(); n != 0 {
+ t.Fatalf("ForwardTarget (the lock-reading decision) called %d times for marked requests, want 0", n)
+ }
+ if n := act.served.Load(); n != 0 {
+ t.Fatalf("activator ServeHTTP called %d times, want 0", n)
+ }
+ // Control: an unmarked request still takes the full decision.
+ dispatchDo(t, front, http.MethodGet, heldTestHost, "/page", nil, nil)
+ if n := act.reads.Load(); n != 1 {
+ t.Fatalf("control: ForwardTarget called %d times for an unmarked request, want 1", n)
+ }
+}
+
+// ---- asset catch witnesses (finding 5) ----------------------------------
+
+// The local catch neither answers a marked request from its store nor
+// fills for one; the app answers it.
+func TestMarkedRequestBypassesLocalAssetCatch(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ wantCache(t, s.get(t, "/assets/app.js"), "miss")
+ rec := s.get(t, "/assets/app.js?carlos_hold=1")
+ if got := rec.Header().Get("Carlos-Cache"); got != "" || rec.Code != 200 || rec.Body.String() != laBody {
+ t.Fatalf("marked request on a stored asset: Carlos-Cache %q, %d %q; want the app's answer", got, rec.Code, rec.Body.String())
+ }
+ if n := s.b.n.Load(); n != 2 {
+ t.Fatalf("the backend saw %d requests, want 2", n)
+ }
+ rec = s.get(t, "/assets/other.js?carlos_hold=1")
+ if got := rec.Header().Get("Carlos-Cache"); got != "" {
+ t.Fatalf("marked request on an unstored asset: Carlos-Cache %q", got)
+ }
+ for _, q := range []string{"", "carlos_hold=1"} {
+ if _, ok := s.store.Get(s.key("/assets/other.js", q)); ok {
+ t.Fatalf("the catch stored a marked request (query %q)", q)
+ }
+ }
+}
+
+// The far catch neither answers nor fills a marked request: it is
+// backhauled to the home as an ordinary request, marker and all.
+func TestMarkedRequestBypassesFarAssetCatch(t *testing.T) {
+ s := newFarScene(t, assetOK(laBody))
+ rec := s.get(t, "/assets/app.js?carlos_hold=1")
+ if got := rec.Header().Get("Carlos-Cache"); got != "" || rec.Code != 200 || rec.Body.String() != laBody {
+ t.Fatalf("marked far request: Carlos-Cache %q, %d %q; want the home's answer", got, rec.Code, rec.Body.String())
+ }
+ seen := s.rec.get()
+ if seen.n != 1 || seen.fill != "" {
+ t.Fatalf("the home saw %d request(s), fill assertion %q; want one ordinary hop", seen.n, seen.fill)
+ }
+ if st := s.store.Stats(); st.Entries != 0 {
+ t.Fatalf("the far edge stored %+v for a marked request", st)
+ }
+}
+
+// The home side of a far fill does not fill or acknowledge a marked
+// request, even with a valid assertion on a verified hop.
+func TestMarkedRequestBypassesHopAssetFill(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody))
+ key := s.armMesh(t)
+ // Control: the same fill unmarked is acknowledged.
+ if resp := s.hop(t, key, laHost, "/assets/app.js", laClaims("/assets/app.js")); resp.Header().Get(assetAckHeader) == "" {
+ t.Fatalf("control: an unmarked fill was not acknowledged: %v", resp.Header())
+ }
+ for _, claimed := range []string{"/assets/b.js", "/assets/b.js?carlos_hold=1"} {
+ resp := s.hop(t, key, laHost, "/assets/b.js?carlos_hold=1", laClaims(claimed))
+ if resp.Header().Get(assetAckHeader) != "" || resp.Header().Get(assetExpiresHeader) != "" {
+ t.Fatalf("a marked fill (claimed %q) was acknowledged: %v", claimed, resp.Header())
+ }
+ if got := resp.Header().Get("Carlos-Cache"); got != "" {
+ t.Fatalf("a marked fill (claimed %q) was answered by the catch: Carlos-Cache %q", claimed, got)
+ }
+ }
+ for _, q := range []string{"", "carlos_hold=1"} {
+ if _, ok := s.store.Get(s.key("/assets/b.js", q)); ok {
+ t.Fatalf("the home stored a marked fill (query %q)", q)
+ }
+ }
+}