carlos / platform Public

edge: page diagnostics on held and upgrade answers; serving app's decls

Review fixes for the home-box page cache:

- The hold and upgrade branches proxy before the LRU point, so their
  answers missed Carlos-Cache. Both now write through the diagnostic
  writer (pageDiagnostics); it forwards Hijack, so an upgrade stays an
  http.Hijacker, and a real 101 gets no header. A held stream's first
  leg hands its page mark to the browser request's holder when its head
  becomes the browser's.
- DeclaresPrefix takes the serving route's account and app from the
  edge instead of the policy snapshot's owner, so a snapshot that lags
  an owner change never answers with the previous app's manifest. The
  snapshot's owners map is gone.
- TestDeclaresPrefixBeforeBindIsUnknown asserts unknown only for calls
  made wholly before the bind; calls across the bind may answer either.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e231c7fd31f5392355c2d9089149740d7fa5094a parent 871bb18
8 files changed, +383 −120
  • internal/edge/assettypes.go +6 −5
  • internal/edge/edge.go +6 −0
  • internal/edge/heldstream.go +21 −9
  • internal/edge/pagecache.go +28 −11
  • internal/edge/pagecache_test.go +187 −13
  • internal/edge/pagerecord.go +15 −2
  • internal/host/assetpolicy.go +21 −35
  • internal/host/assetpolicy_test.go +99 −45

CI failed — run details

Intent

Human

<task-notification> <task-id>a7287ac9275b31cdc</task-id> <tool-use-id>toolu_01K1pJMf1YqAQXGK6XyPQPkU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/a7287ac9275b31cdc.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7: home-box page serving" 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. Home-box page serving and storing is in place at the LRU gate, and the host answers `DeclaresPrefix` without reading the bucket on a request. Commits: - `bf3bd261` edge: home-box page cache at the LRU point - `d7bbea5d` edge: a short page body is never published - `871bb18c` edge: the ineligible-routes table refuses a dispatch to a real route Tests: all 26 brief tests pass, plus 3 I added (short body, a host retry and queue-bound test, a randomized leak test) and Task 5's mark tests; `-race` is clean on both packages and the edge/host neighbours pass. The brief's three mutations and 24 of my own each make a test fail; one first survived and I strengthened its test. Concerns, details in the report: 1. I set `Carlos-Cache: miss` only when a page was actually reserved, as the asset cache does. Under the plan's wording ("the response was considered"), every storable request would show `miss`. Please confirm which you want. 2. The host finds a route's account and app in the asset policy's settled snapshot, so pages bypass until its first settled pass, and new routes until the next one. This fails safe. 3. Four rules stricter than the brief: tunnel-served routes are refused; backhauled door calls are not readable; the end-of-response check reruns all of eligibility on a fresh route lookup; a failed write to the client abandons the recording. 4. Inside the sandbox the Go build cache is read-only, so all go commands ran outside it with the default cache. Report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-page-cache-1/.superpowers/sdd/2026-11-08-edge-page-cache-plan-1-home/task-7-report.md`</result> <usage><subagent_tokens>337166</subagent_tokens><tool_uses>114</tool_uses><duration_ms>2882464</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>b6nxaj3ag</task-id> <tool-use-id>toolu_018soa7g4e8dmVUCJb6eg161</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/b6nxaj3ag.output</output-file> <status>completed</status> <summary>Background command "Run Astra review of Task 7" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 26.9 g CO₂e (3,478,128 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on edge-page-cache-1, 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/edge/assettypes.go b/internal/edge/assettypes.go
index f0bc56e74..8ad12c5bf 100644
--- a/internal/edge/assettypes.go
+++ b/internal/edge/assettypes.go
@@ -43,12 +43,13 @@ type LocalAssets interface {
}
// assetDeclarations is an optional LocalAssets method for the page cache
-// (edge page cache plan 1 Task 7, P2-9 and R2-5): whether build, run by the
-// route host, declares an asset prefix of path, whatever the route's
-// AssetsOff says. known is false when the answer is not held yet; the page
-// cache then bypasses. It never reads storage on the caller's goroutine.
+// (edge page cache plan 1 Task 7, P2-9 and R2-5): whether build of
+// account/app (the serving route's owner and build, as the edge's route
+// snapshot holds them) declares an asset prefix of path, whatever the
+// route's AssetsOff says. known is false when the answer is not held yet;
+// the page cache then bypasses. It never reads storage on the caller's goroutine.
// internal/host's policy implements it; a LocalAssets that does not leaves
// every declaration unknown, and so no page eligible.
type assetDeclarations interface {
- DeclaresPrefix(host, build, path string) (declared, known bool)
+ DeclaresPrefix(account, app, build, path string) (declared, known bool)
}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index d8a861a47..fd067f75f 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2562,6 +2562,8 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer release()
w = &slotWriter{ResponseWriter: w, release: release}
}
+ // The page diagnostics (pagerecord.go), as at the LRU point.
+ w = e.pageDiagnostics(r, host, up).wrap(w)
e.serveHeld(w, r, up.route, up.proxy)
return
}
@@ -2599,6 +2601,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer release()
w = &slotWriter{ResponseWriter: w, release: release}
}
+ // The page diagnostics (pagerecord.go) for an upgrade answered with a
+ // final status; a 101 passes untouched, and the hijack reaches the
+ // writers beneath through Unwrap.
+ w = e.pageDiagnostics(r, host, up).wrap(w)
// The admission (#471 spec §4.4): a tunnel arm's upgrade carries
// what this branch admitted it under, and the hub's transport sends
// an upgrade down a channel only with it, re-checked against the map
diff --git a/internal/edge/heldstream.go b/internal/edge/heldstream.go
index f94d106b6..9dc9e70fe 100644
--- a/internal/edge/heldstream.go
+++ b/internal/edge/heldstream.go
@@ -401,8 +401,8 @@ const (
heldLegEnd
)
-// heldLegMsg is what a leg's reader hands the task. attr is set on the
-// head.
+// heldLegMsg is what a leg's reader hands the task. attr and mark are set
+// on the head.
type heldLegMsg struct {
run *heldLegRun
kind heldLegMsgKind
@@ -410,6 +410,7 @@ type heldLegMsg struct {
header http.Header
sse bool
attr heldLegAttr
+ mark pageMark // what the leg's own holder said of its head
block sseBlock
chunk []byte
err error
@@ -606,7 +607,7 @@ func (t *heldTask) openLeg(leg HeldLeg, exempt bool) {
t.leg, t.lastLegStart = run, run.start
req, out := t.legRequest(ctx)
pr, pw := io.Pipe()
- lw := &heldLegWriter{hdr: make(http.Header), headC: make(chan heldLegHeadMsg, 1), pw: pw, out: out}
+ lw := &heldLegWriter{hdr: make(http.Header), headC: make(chan heldLegHeadMsg, 1), pw: pw, out: out, mark: pageMarkOf(req)}
proxy := t.proxy
go func() {
defer lw.finish()
@@ -694,7 +695,7 @@ func (t *heldTask) onLeg(m heldLegMsg) (heldCloseReason, bool) {
}
switch {
case m.sse:
- if err := t.writeFirstHead(http.StatusOK, m.header, true); err != nil {
+ if err := t.writeFirstHead(http.StatusOK, m.header, true, m.mark); err != nil {
return heldCloseWriteFailed, true
}
case m.status >= 300 && m.status < 400:
@@ -710,7 +711,7 @@ func (t *heldTask) onLeg(m heldLegMsg) (heldCloseReason, bool) {
}
return heldCloseBadGateway, true
default:
- if err := t.writeFirstHead(m.status, m.header, false); err != nil {
+ if err := t.writeFirstHead(m.status, m.header, false, m.mark); err != nil {
return heldCloseWriteFailed, true
}
t.passThrough = true
@@ -807,8 +808,13 @@ func (t *heldTask) commit() error {
// writeFirstHead writes the first leg's status and headers as the
// browser's. For an event stream the framing headers go and Cache-Control
-// is no-store (§3.3 step 3).
-func (t *heldTask) writeFirstHead(status int, src http.Header, sse bool) error {
+// is no-store (§3.3 step 3). The leg's page mark becomes the browser
+// request's (pagemark.go): this head is the response the browser gets, so
+// the page diagnostics see the app's marker on it.
+func (t *heldTask) writeFirstHead(status int, src http.Header, sse bool, mark pageMark) error {
+ if m := pageMarkOf(t.r); m != nil {
+ *m = mark
+ }
h := src.Clone()
removeHeldHopHeaders(h)
// No first-leg answer redirects the browser (§3.3 step 3).
@@ -911,6 +917,7 @@ type heldLegHeadMsg struct {
status int
header http.Header
attr heldLegAttr
+ mark pageMark
}
// heldLegWriter is the response writer a leg's proxy run writes into: it
@@ -923,6 +930,7 @@ type heldLegWriter struct {
headC chan heldLegHeadMsg
pw *io.PipeWriter
out *outcome
+ mark *pageMark // the leg request's holder; nil off an instance route
}
// attr reads the leg's outcome, on the proxy goroutine that writes it.
@@ -940,7 +948,11 @@ func (lw *heldLegWriter) WriteHeader(code int) {
return // informational answers are not the leg's head
}
lw.sent = true
- lw.headC <- heldLegHeadMsg{status: code, header: lw.hdr.Clone(), attr: lw.attr()}
+ var mark pageMark
+ if lw.mark != nil {
+ mark = *lw.mark
+ }
+ lw.headC <- heldLegHeadMsg{status: code, header: lw.hdr.Clone(), attr: lw.attr(), mark: mark}
}
func (lw *heldLegWriter) Write(b []byte) (int, error) {
@@ -990,7 +1002,7 @@ func readHeldLeg(run *heldLegRun, pr *io.PipeReader, headC <-chan heldLegHeadMsg
return
}
sse := isHeldSSE(hd.status, hd.header)
- if !send(heldLegMsg{kind: heldLegHead, status: hd.status, header: hd.header, sse: sse, attr: hd.attr}) {
+ if !send(heldLegMsg{kind: heldLegHead, status: hd.status, header: hd.header, sse: sse, attr: hd.attr, mark: hd.mark}) {
return
}
if sse {
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go
index c730a5615..b0fc00852 100644
--- a/internal/edge/pagecache.go
+++ b/internal/edge/pagecache.go
@@ -62,8 +62,10 @@ func (e *Edge) pagesOptedIn(up upstream) bool {
// says, whether or not this request was let through (R3-9);
// - neither host's own entry nor the route's primary has path rows, and
// the request was not dispatched by path to another route (P1-6);
-// - the serving build's asset declarations are known and path is not
-// under one of them (P2-9): those paths are the asset cache's;
+// - the serving app's build's asset declarations are known and path is
+// not under one of them (P2-9): those paths are the asset cache's. The
+// app is the route's own account and app (pageScopeOf), so a policy
+// snapshot that lags an owner change is never asked about the old one;
// - the route's current inputs are known.
func (e *Edge) pageRouteEligible(host, path string, up upstream) (inputs string, ok bool) {
if e.pages.Load() == nil {
@@ -95,7 +97,8 @@ func (e *Edge) pageRouteEligible(host, path string, up upstream) (inputs string,
if !ok {
return "", false
}
- if declared, known := d.DeclaresPrefix(rt.Host, rt.Version, path); !known || declared {
+ s := pageScopeOf(up)
+ if declared, known := d.DeclaresPrefix(s.Account, s.App, rt.Version, path); !known || declared {
return "", false
}
in, ok := e.cache.CurrentInputs(rt)
@@ -260,16 +263,11 @@ type pageServe struct {
// when the request is storable and the process that will answer it was
// started from the current inputs.
func (e *Edge) servePage(w http.ResponseWriter, r *http.Request, host string, up upstream) (ps *pageServe, served bool) {
- if up.route.Kind != "instance" {
- return nil, false
- }
- ps = &pageServe{e: e, r: r, host: host, up: up}
- x := e.pages.Load()
- if x == nil {
+ ps = e.pageDiagnostics(r, host, up)
+ if ps == nil || ps.x == nil {
return ps, false
}
- ps.x, ps.scope = x, pageScopeOf(up)
- ps.optedIn = x.OptedIn(ps.scope)
+ x := ps.x
inputs, ok := e.pageRouteEligible(host, r.URL.Path, up)
if !ok {
return ps, false
@@ -294,6 +292,25 @@ func (e *Edge) servePage(w http.ResponseWriter, r *http.Request, host string, up
return ps, false
}
+// pageDiagnostics is the page state of a request to up that records nothing:
+// whether the instance is opted in, and the request's mark holder, which is
+// all the diagnostic writer (wrap) needs. ServeHTTP wraps the branches that
+// proxy before the LRU point with it (the hold branch and the upgrade
+// branch), so their responses carry Carlos-Cache by the same rule, whatever
+// the request's eligibility. servePage starts from it too. Nil for a route
+// that is not an instance.
+func (e *Edge) pageDiagnostics(r *http.Request, host string, up upstream) *pageServe {
+ if up.route.Kind != "instance" {
+ return nil
+ }
+ ps := &pageServe{e: e, r: r, host: host, up: up}
+ if x := e.pages.Load(); x != nil {
+ ps.x, ps.scope = x, pageScopeOf(up)
+ ps.optedIn = x.OptedIn(ps.scope)
+ }
+ return ps
+}
+
// pageClock is the clock pages are aged and expired by: the asset store's.
func (e *Edge) pageClock() time.Time {
if st := e.assets.Load(); st != nil {
diff --git a/internal/edge/pagecache_test.go b/internal/edge/pagecache_test.go
index b7051f528..d411b22c2 100644
--- a/internal/edge/pagecache_test.go
+++ b/internal/edge/pagecache_test.go
@@ -1,11 +1,13 @@
package edge
import (
+ "bufio"
"bytes"
"compress/gzip"
"context"
"errors"
"io"
+ "net"
"net/http"
"net/http/httptest"
"os"
@@ -44,7 +46,7 @@ const (
type pcDecl struct {
fakeLocalAssets
dmu sync.Mutex
- decls map[string][]string // build -> declared prefixes; absent: not read
+ decls map[string][]string // account/app/build -> declared prefixes; absent: not read
wants []string
reads atomic.Int64
}
@@ -53,28 +55,34 @@ func newPCDecl() *pcDecl {
return &pcDecl{fakeLocalAssets: fakeLocalAssets{hosts: map[string]HostAssets{}, builds: map[string]bool{}}, decls: map[string][]string{}}
}
-func (d *pcDecl) DeclaresPrefix(host, build, path string) (declared, known bool) {
+func pcDeclKey(account, app, build string) string { return account + "/" + app + "/" + build }
+
+func (d *pcDecl) DeclaresPrefix(account, app, build, path string) (declared, known bool) {
d.dmu.Lock()
defer d.dmu.Unlock()
- p, ok := d.decls[build]
+ k := pcDeclKey(account, app, build)
+ p, ok := d.decls[k]
if !ok {
- d.wants = append(d.wants, host+" "+build)
+ d.wants = append(d.wants, k)
return false, false
}
return assetPrefixMatch(p, path), true
}
-func (d *pcDecl) load(build string, prefixes ...string) {
+// load and forget name a build of the scene's own app (abc/blog).
+func (d *pcDecl) load(build string, prefixes ...string) { d.loadFor("abc", "blog", build, prefixes...) }
+
+func (d *pcDecl) loadFor(account, app, build string, prefixes ...string) {
d.reads.Add(1)
d.dmu.Lock()
defer d.dmu.Unlock()
- d.decls[build] = prefixes
+ d.decls[pcDeclKey(account, app, build)] = prefixes
}
func (d *pcDecl) forget(build string) {
d.dmu.Lock()
defer d.dmu.Unlock()
- delete(d.decls, build)
+ delete(d.decls, pcDeclKey("abc", "blog", build))
}
func (d *pcDecl) wanted() []string {
@@ -89,6 +97,7 @@ func (d *pcDecl) wanted() []string {
type pcActivator struct {
served atomic.Int64
onWake func(rt registry.Route)
+ admit atomic.Bool // admit held legs (else they are refused: asleep)
}
func (a *pcActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
@@ -101,10 +110,14 @@ func (a *pcActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt regis
}
func (a *pcActivator) RetireExcept(map[string]bool) {}
-func (a *pcActivator) AdmitHeldLeg(context.Context, registry.Route) (HeldLeg, error) {
- return nil, errors.New("asleep")
+func (a *pcActivator) AdmitHeldLeg(ctx context.Context, _ registry.Route) (HeldLeg, error) {
+ if !a.admit.Load() {
+ return nil, errors.New("asleep")
+ }
+ c, cancel := context.WithCancel(ctx)
+ return &scriptLeg{ctx: c, cancel: cancel}, nil
}
-func (a *pcActivator) HeldAdmissible(string) bool { return false }
+func (a *pcActivator) HeldAdmissible(string) bool { return a.admit.Load() }
func (a *pcActivator) SetHeldWakeHook(func(string)) {}
type pcScene struct {
@@ -153,8 +166,8 @@ func newPCScene(t *testing.T, h http.HandlerFunc, mods ...func(*registry.Route))
c.SetCurrentInputs(s.currentInputs)
s.act.onWake = func(rt registry.Route) { s.publishFor(rt) }
s.publish()
- s.decl.decls[pcBuild] = []string{"/assets/"}
- s.decl.decls["v2"] = []string{"/assets/"}
+ s.decl.decls[pcDeclKey("abc", "blog", pcBuild)] = []string{"/assets/"}
+ s.decl.decls[pcDeclKey("abc", "blog", "v2")] = []string{"/assets/"}
s.store = openLAStore(t)
e.assets.Store(&assetState{store: s.store, local: s.decl, now: time.Now})
idx, err := pageindex.Open(pageindex.Config{Store: s.store, MarkDir: filepath.Join(t.TempDir(), "marks")})
@@ -871,7 +884,7 @@ func TestPageDeclarationsLoadInBackground(t *testing.T) {
if n := s.decl.reads.Load(); n != 0 {
t.Fatalf("%d declaration reads happened on the request path", n)
}
- if w := s.decl.wanted(); !slices.Contains(w, pcHost+" "+pcBuild) {
+ if w := s.decl.wanted(); !slices.Contains(w, pcDeclKey("abc", "blog", pcBuild)) {
t.Fatalf("the request queued no background read (wanted %q)", w)
}
s.decl.load(pcBuild, "/assets/") // the background read
@@ -888,6 +901,23 @@ func TestPageDeclarationsLoadInBackground(t *testing.T) {
}
}
+// The declarations asked about are the serving route's own app's: another
+// app's build of the same name, declaring the page's path, changes nothing,
+// and the route's own declaration of it does.
+func TestPageDeclarationsAreTheServingApps(t *testing.T) {
+ s := newPCScene(t, pageOK(pcBody), func(r *registry.Route) { r.AssetsOff = true })
+ s.decl.loadFor("abc", "shop", pcBuild, "/p")
+ s.decl.loadFor("other", "blog", pcBuild, "/p")
+ wantCache(t, s.get("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+ s.decl.load(pcBuild, "/q")
+ wantCache(t, s.get("/q"), "bypass")
+ wantCache(t, s.get("/q"), "bypass")
+ if n := s.pages(); n != 1 {
+ t.Fatalf("%d pages stored, want only /p", n)
+ }
+}
+
// ---- diagnostics (P2-10, R2-6, R3-7) ---------------------------------------
func TestPageDiagnostics(t *testing.T) {
@@ -974,6 +1004,149 @@ func TestPageDiagnostics(t *testing.T) {
}
}
+// The branches that proxy before the LRU point carry the same diagnostics
+// (P2-10, R2-6): an upgrade request the app answers with a final status, and
+// a held stream, whether its head is the app's first leg or the edge's own.
+// A real 101 carries none.
+func TestPageDiagnosticsBeforeTheLRU(t *testing.T) {
+ // /p is a marked page; /plain an unmarked one; /sse an event stream,
+ // marked when asked with ?mark=1; an upgrade to /ws switches protocols.
+ app := func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/p":
+ pageOK(pcBody)(w, r)
+ case "/sse":
+ if r.URL.Query().Get("mark") == "1" {
+ w.Header().Set(pageCacheHeader, "on")
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.WriteHeader(http.StatusOK)
+ w.(http.Flusher).Flush()
+ <-r.Context().Done()
+ case "/ws":
+ conn, buf, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + pageCacheHeader + ": on\r\n\r\n")
+ buf.Flush()
+ io.Copy(io.Discard, conn)
+ default:
+ w.Header().Set("Content-Type", "text/html")
+ io.WriteString(w, "plain")
+ }
+ }
+ upgrade := []string{"Connection", "Upgrade", "Upgrade", "websocket"}
+
+ t.Run("upgrade answered 200", func(t *testing.T) {
+ for _, c := range []struct {
+ name, path string
+ optIn bool
+ unarmed bool
+ want string
+ }{
+ {"marked, not opted in", "/p", false, false, "bypass"},
+ {"marked, unarmed", "/p", false, true, "bypass"},
+ {"unmarked, opted in", "/plain", true, false, "bypass"},
+ {"unmarked, not opted in", "/plain", false, false, ""},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s := newPCScene(t, app)
+ if c.optIn {
+ wantCache(t, s.get("/p"), "miss")
+ }
+ if c.unarmed {
+ s.e.EnablePageCache(nil)
+ }
+ rec := s.get(c.path, upgrade...)
+ if rec.Code != 200 {
+ t.Fatalf("status %d", rec.Code)
+ }
+ if got, ok := rec.Header()[assetCacheHeader]; c.want == "" && ok {
+ t.Fatalf("Carlos-Cache = %q, want none", got)
+ }
+ if c.want != "" {
+ wantCache(t, rec, c.want)
+ }
+ })
+ }
+ })
+
+ t.Run("a real 101 carries none", func(t *testing.T) {
+ s := newPCScene(t, app)
+ wantCache(t, s.get("/p"), "miss") // opted in
+ srv := httptest.NewServer(s.e)
+ t.Cleanup(srv.Close)
+ conn, err := net.Dial("tcp", srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ io.WriteString(conn, "GET /ws HTTP/1.1\r\nHost: "+pcHost+"\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n")
+ conn.SetReadDeadline(time.Now().Add(5 * time.Second))
+ resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("status %d, want 101", resp.StatusCode)
+ }
+ if v, ok := resp.Header[assetCacheHeader]; ok {
+ t.Fatalf("a 101 carries Carlos-Cache %q", v)
+ }
+ wantNoPageMark(t, "the 101", resp.Header)
+ })
+
+ held := func(t *testing.T, s *pcScene, path string) http.Header {
+ t.Helper()
+ srv := httptest.NewServer(s.e)
+ t.Cleanup(srv.Close)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = pcHost
+ req.Header.Set("Accept", "text/event-stream")
+ resp, err := srv.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != 200 || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
+ t.Fatalf("held answer = %d %q", resp.StatusCode, resp.Header.Get("Content-Type"))
+ }
+ wantNoPageMark(t, "a held answer", resp.Header)
+ return resp.Header
+ }
+ t.Run("held, opted in, the edge's own head", func(t *testing.T) {
+ s := newPCScene(t, app, func(r *registry.Route) { r.Hibernate = true })
+ wantCache(t, s.get("/p"), "miss") // opted in
+ if got := held(t, s, "/sse?carlos_hold=1").Get(assetCacheHeader); got != "bypass" {
+ t.Fatalf("Carlos-Cache = %q, want bypass", got)
+ }
+ })
+ t.Run("held, a marked first leg", func(t *testing.T) {
+ s := newPCScene(t, app, func(r *registry.Route) { r.Hibernate = true })
+ s.act.admit.Store(true)
+ if got := held(t, s, "/sse?mark=1&carlos_hold=1").Get(assetCacheHeader); got != "bypass" {
+ t.Fatalf("Carlos-Cache = %q, want bypass", got)
+ }
+ if s.idx.OptedIn(s.scope()) {
+ t.Fatal("a held stream opted the instance in")
+ }
+ })
+ t.Run("held, an unmarked first leg", func(t *testing.T) {
+ s := newPCScene(t, app, func(r *registry.Route) { r.Hibernate = true })
+ s.act.admit.Store(true)
+ if v, ok := held(t, s, "/sse?carlos_hold=1")[assetCacheHeader]; ok {
+ t.Fatalf("Carlos-Cache = %q, want none", v)
+ }
+ })
+}
+
// ---- the account throttle (R3-9) -------------------------------------------
func TestPageThrottledAccountBypasses(t *testing.T) {
@@ -1008,6 +1181,7 @@ func TestPageIneligibleRoutes(t *testing.T) {
if err := s.e.Reload(); err != nil {
t.Fatal(err)
}
+ s.decl.loadFor("abc", "other", pcBuild, "/assets/")
other, ok := s.e.current()["other.example.com"]
if !ok {
t.Fatal("no upstream for the second route")
diff --git a/internal/edge/pagerecord.go b/internal/edge/pagerecord.go
index bdf407e08..d09a1881e 100644
--- a/internal/edge/pagerecord.go
+++ b/internal/edge/pagerecord.go
@@ -1,7 +1,9 @@
package edge
import (
+ "bufio"
"fmt"
+ "net"
"net/http"
"strconv"
"strings"
@@ -11,8 +13,11 @@ import (
"github.com/carlosframework/platform/internal/pageindex"
)
-// pageRecorder wraps every proxied response of an instance route at the LRU
-// point (pageServe.wrap), on every box, armed or not.
+// pageRecorder wraps every proxied response of an instance route
+// (pageServe.wrap), on every box, armed or not: at the LRU point, and around
+// the hold and upgrade branches before it (pageDiagnostics), where it only
+// diagnoses. A 101 is informational here and gets no header; an upgrade
+// request answered with a final status does.
//
// As the diagnostic writer it sets Carlos-Cache at the first final status
// when the instance is opted in or the response is marked (P2-10, R2-6,
@@ -116,6 +121,14 @@ func (p *pageRecorder) Flush() {
func (p *pageRecorder) Unwrap() http.ResponseWriter { return p.ResponseWriter }
+// Hijack forwards to the writers beneath, so an upgrade wrapped by the page
+// diagnostics is still an http.Hijacker for the activator and the proxy
+// (the upgrade branch's contract). A hijacked response writes nothing more
+// here.
+func (p *pageRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ return http.NewResponseController(p.ResponseWriter).Hijack()
+}
+
// abort abandons the recording, if one runs.
func (p *pageRecorder) abort() {
if p.pend != nil {
diff --git a/internal/host/assetpolicy.go b/internal/host/assetpolicy.go
index 4b612591d..9f56a235a 100644
--- a/internal/host/assetpolicy.go
+++ b/internal/host/assetpolicy.go
@@ -455,35 +455,32 @@ const assetDeclarationsReadTimeout = 30 * time.Second
type wantedBuild struct{ acct, app, build string }
var _ interface {
- DeclaresPrefix(host, build, path string) (declared, known bool)
+ DeclaresPrefix(account, app, build, path string) (declared, known bool)
} = (*assetPolicy)(nil)
-// DeclaresPrefix reports whether build, run by the route host, declares an
-// asset prefix of path (the page cache's rule, edge page cache plan 1 Task 7,
-// P2-9 and R2-5): declared prefixes belong to the asset cache, so a page
-// under one is never stored. known is false when the answer is not held: the
-// manifest cache is not bound yet (R3-6), the settled snapshot does not name
-// host's owner, build is empty, or the build's manifest has not been read.
-// In the last case it queues a background read (WantDeclarations), so a
-// later request knows. It reads only the manifest cache and the snapshot,
-// never the bucket, and AssetsOff does not change its answer. Safe for
-// concurrent calls.
-func (p *assetPolicy) DeclaresPrefix(host, build, path string) (declared, known bool) {
- if p == nil || build == "" {
+// DeclaresPrefix reports whether build of account/app, the serving route's
+// own owner and build as the edge holds them, declares an asset prefix of
+// path (the page cache's rule, edge page cache plan 1 Task 7, P2-9 and
+// R2-5): declared prefixes belong to the asset cache, so a page under one is
+// never stored. The owner comes from the caller, never from a snapshot, so
+// the answer is always the serving app's manifest, even just after a route
+// changed owner. known is false when the answer is not held: the manifest
+// cache is not bound yet (R3-6), an argument is empty, or the build's
+// manifest has not been read. In the last case it queues a background read
+// (WantDeclarations), so a later request knows. It reads only the manifest
+// cache, never the bucket, and AssetsOff does not change its answer. Safe
+// for concurrent calls.
+func (p *assetPolicy) DeclaresPrefix(account, app, build, path string) (declared, known bool) {
+ if p == nil || account == "" || app == "" || build == "" {
return false, false
}
c := p.manifests.Load()
- s := p.current()
- if c == nil || s == nil {
- return false, false
- }
- o, ok := s.owners[host]
- if !ok {
+ if c == nil {
return false, false
}
- paths, ok := c.cached(o.account, o.app, build)
+ paths, ok := c.cached(account, app, build)
if !ok {
- p.WantDeclarations(o.account, o.app, build)
+ p.WantDeclarations(account, app, build)
return false, false
}
return slices.ContainsFunc(paths, func(prefix string) bool { return prefix != "" && strings.HasPrefix(path, prefix) }), true
@@ -495,7 +492,7 @@ func (p *assetPolicy) DeclaresPrefix(host, build, path string) (declared, known
// assetDeclarationsRetry is not queued again, and the queue holds at most
// assetDeclarationsQueueMax builds.
func (p *assetPolicy) WantDeclarations(acct, app, build string) {
- if p == nil || build == "" {
+ if p == nil || acct == "" || app == "" || build == "" {
return
}
c := p.manifests.Load()
@@ -575,18 +572,12 @@ func (p *assetPolicy) loadDeclarations(c *assetManifestCache) {
// assetSnapshot is one settled decision for every hostname this box could
// catch for itself: For's answers (pooled routes included, aliases whatever
// their DNS) and the declared paths of every build the manifest cache held.
-// owners is every ready, non-sidecar route host's owner, whether or not it
-// catches assets: DeclaresPrefix names a build's manifest by it. It is
-// immutable once published.
+// It is immutable once published.
type assetSnapshot struct {
hosts map[string]edge.HostAssets
builds map[string][]string
- owners map[string]assetOwner
}
-// assetOwner is the account and app a route's manifests are read under.
-type assetOwner struct{ account, app string }
-
// current is the snapshot For and Declared answer from: the writer's last
// settled decision. Nil until the edges file writer has stored its first one,
// and until then the home catches nothing (design §4.2, "after a restart";
@@ -603,12 +594,7 @@ func (p *assetPolicy) current() *assetSnapshot {
// writer's schedule. The caller has checked that in was read settled against
// clocks.
func (p *assetPolicy) buildSnapshot(ctx context.Context, in assetInputs, clocks assetClocks) *assetSnapshot {
- s := &assetSnapshot{hosts: map[string]edge.HostAssets{}, owners: map[string]assetOwner{}}
- for host, r := range in.byHost {
- if r.Status == "ready" && !r.IsSidecar() {
- s.owners[host] = assetOwner{account: release.RouteAccount(r), app: r.App}
- }
- }
+ s := &assetSnapshot{hosts: map[string]edge.HostAssets{}}
consider := func(host string) {
if _, done := s.hosts[host]; done {
return
diff --git a/internal/host/assetpolicy_test.go b/internal/host/assetpolicy_test.go
index 0b5219fc8..e31293db8 100644
--- a/internal/host/assetpolicy_test.go
+++ b/internal/host/assetpolicy_test.go
@@ -45,33 +45,33 @@ func (g *gatedGetStore) open() { g.once.Do(func() { close(g.gate) }) }
// declaresWithin calls DeclaresPrefix on another goroutine and fails if it
// does not return within a second: a request-time bucket read would block on
// the gated store.
-func declaresWithin(t *testing.T, p *assetPolicy, host, build, path string) (declared, known bool) {
+func declaresWithin(t *testing.T, p *assetPolicy, acct, app, build, path string) (declared, known bool) {
t.Helper()
type answer struct{ declared, known bool }
ch := make(chan answer, 1)
go func() {
- d, k := p.DeclaresPrefix(host, build, path)
+ d, k := p.DeclaresPrefix(acct, app, build, path)
ch <- answer{d, k}
}()
select {
case a := <-ch:
return a.declared, a.known
case <-time.After(time.Second):
- t.Fatalf("DeclaresPrefix(%s, %s, %s) blocked: it read the bucket on the request", host, build, path)
+ t.Fatalf("DeclaresPrefix(%s, %s, %s, %s) blocked: it read the bucket on the request", acct, app, build, path)
return false, false
}
}
// waitDeclared polls DeclaresPrefix until it knows the answer.
-func waitDeclared(t *testing.T, p *assetPolicy, host, build, path string) (declared bool) {
+func waitDeclared(t *testing.T, p *assetPolicy, acct, app, build, path string) (declared bool) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for {
- if d, k := p.DeclaresPrefix(host, build, path); k {
+ if d, k := p.DeclaresPrefix(acct, app, build, path); k {
return d
}
if time.Now().After(deadline) {
- t.Fatalf("DeclaresPrefix(%s, %s, %s) never became known", host, build, path)
+ t.Fatalf("DeclaresPrefix(%s, %s, %s, %s) never became known", acct, app, build, path)
}
time.Sleep(5 * time.Millisecond)
}
@@ -103,7 +103,7 @@ func TestDeclaresPrefixIgnoresAssetsOff(t *testing.T) {
}
w.pass()
if !assetsOff {
- if got := waitDeclared(t, w.policy, "shop.example.com", "v1", "/assets/app.js"); !got {
+ if got := waitDeclared(t, w.policy, "abc", "shop", "v1", "/assets/app.js"); !got {
t.Fatal("an asset-catching build's prefix is not declared")
}
return
@@ -112,35 +112,38 @@ func TestDeclaresPrefixIgnoresAssetsOff(t *testing.T) {
t.Fatalf("the writer read %d objects for an assets-off build; the test assumes it reads none", n)
}
for i := 0; i < 10; i++ {
- if _, known := declaresWithin(t, w.policy, "shop.example.com", "v1", "/assets/app.js"); known {
+ if _, known := declaresWithin(t, w.policy, "abc", "shop", "v1", "/assets/app.js"); known {
t.Fatal("an unread build's declaration was known")
}
}
gated.open()
- if !waitDeclared(t, w.policy, "shop.example.com", "v1", "/assets/app.js") {
+ if !waitDeclared(t, w.policy, "abc", "shop", "v1", "/assets/app.js") {
t.Fatal("an assets-off build's declared prefix is not declared")
}
- if d, k := w.policy.DeclaresPrefix("shop.example.com", "v1", "/p"); !k || d {
+ if d, k := w.policy.DeclaresPrefix("abc", "shop", "v1", "/p"); !k || d {
t.Fatalf("an undeclared path = (%v, %v), want (false, true)", d, k)
}
if n := gated.gets.Load(); n != 1 {
t.Fatalf("the manifest was read %d times, want once", n)
}
- // An unknown host and an empty build stay unknown, and queue
- // nothing that reads.
- if _, k := w.policy.DeclaresPrefix("other.example.com", "v1", "/p"); k {
- t.Fatal("a host the snapshot does not hold was known")
+ // An empty owner or build stays unknown, and queues nothing.
+ for _, a := range [][3]string{{"", "shop", "v1"}, {"abc", "", "v1"}, {"abc", "shop", ""}} {
+ if _, k := w.policy.DeclaresPrefix(a[0], a[1], a[2], "/p"); k {
+ t.Fatalf("DeclaresPrefix(%q) was known", a)
+ }
}
- if _, k := w.policy.DeclaresPrefix("shop.example.com", "", "/p"); k {
- t.Fatal("an empty build was known")
+ if n := gated.gets.Load(); n != 1 {
+ t.Fatalf("an empty argument read the bucket (%d reads)", n)
}
})
}
}
-// Requests ask DeclaresPrefix while the edges file loop binds the manifest
-// cache late (R3-6). Before the bind every answer is unknown, nothing
-// panics, and the race detector sees the publication as ordered.
+// Requests ask DeclaresPrefix before, and while, the edges file loop binds
+// the manifest cache late (R3-6). Every answer given entirely before the
+// bind is unknown. Calls that run concurrently with the bind may answer
+// either way; they must not panic, and the race detector must see the
+// publication as ordered. After the bind the declaration becomes known.
func TestDeclaresPrefixBeforeBindIsUnknown(t *testing.T) {
w := newAssetWorld(t)
w.policy = armAssetPolicy(armedAssetEnv, w.reg, w.auth, nil, w.servingBuild)
@@ -150,38 +153,54 @@ func TestDeclaresPrefixBeforeBindIsUnknown(t *testing.T) {
w.confirm()
w.pass() // a pass with no manifest cache publishes its snapshot all the same
- var bound atomic.Bool
- stop := make(chan struct{})
- var wg sync.WaitGroup
- var knownBeforeBind atomic.Int64
- for i := 0; i < 8; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for {
- select {
- case <-stop:
- return
- default:
- }
- wasBound := bound.Load()
- if _, k := w.policy.DeclaresPrefix("shop.example.com", "v1", "/assets/app.js"); k && !wasBound {
- knownBeforeBind.Add(1)
+ ask := func() bool {
+ _, k := w.policy.DeclaresPrefix("abc", "shop", "v1", "/assets/app.js")
+ return k
+ }
+ // run calls ask from n goroutines until stop closes, and counts the
+ // known answers.
+ run := func(n int, stop <-chan struct{}) (wait func() int64) {
+ var known atomic.Int64
+ var wg sync.WaitGroup
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ if ask() {
+ known.Add(1)
+ }
}
- }
- }()
+ }()
+ }
+ return func() int64 { wg.Wait(); return known.Load() }
}
+
+ // Before the bind: every call starts and ends before it.
+ stop := make(chan struct{})
+ wait := run(8, stop)
time.Sleep(20 * time.Millisecond)
+ close(stop)
+ if n := wait(); n != 0 {
+ t.Fatalf("%d answers before the bind were known", n)
+ }
+
+ // Across the bind: answers may be either; none panics.
+ stop = make(chan struct{})
+ wait = run(8, stop)
+ time.Sleep(5 * time.Millisecond)
w.policy.bindManifests(newAssetManifestCache(w.store))
- bound.Store(true)
- if !waitDeclared(t, w.policy, "shop.example.com", "v1", "/assets/app.js") {
+ if !waitDeclared(t, w.policy, "abc", "shop", "v1", "/assets/app.js") {
t.Fatal("after the bind the declared prefix is not declared")
}
close(stop)
- wg.Wait()
- if n := knownBeforeBind.Load(); n != 0 {
- t.Fatalf("%d answers before the bind were known", n)
- }
+ wait()
+
// A second bind changes nothing: the first cache stays.
first := w.policy.manifests.Load()
w.policy.bindManifests(newAssetManifestCache(w.store))
@@ -190,6 +209,41 @@ func TestDeclaresPrefixBeforeBindIsUnknown(t *testing.T) {
}
}
+// The answer is the serving app's manifest, named by the caller: a route
+// whose owner changed (here, its app) before the settled snapshot caught
+// up gets the new app's declaration, never the old app's cached one for the
+// same build name.
+func TestDeclaresPrefixUsesTheServingAppsManifest(t *testing.T) {
+ w := newAssetWorld(t)
+ w.ship("v1", "/assets/")
+ m := release.Manifest{App: "blog", Version: "v1", Kind: "binary",
+ Artifacts: map[string]release.Artifact{"linux-arm64": {}}, Assets: &release.Assets{Paths: []string{"/static/"}}}
+ if err := release.Ship(context.Background(), w.store.Store, "abc", m, map[string][]byte{"linux-arm64": []byte("blog v1")}); err != nil {
+ t.Fatal(err)
+ }
+ w.instance("shop.example.com", assetGen1, "v1")
+ w.confirm()
+ w.pass() // shop's v1 is read and cached: /assets/
+ if !waitDeclared(t, w.policy, "abc", "shop", "v1", "/assets/app.js") {
+ t.Fatal("shop's v1 does not declare /assets/")
+ }
+ // The row moves to app blog; no writer pass runs, so the snapshot still
+ // says shop.
+ w.instance("shop.example.com", assetGen1, "v1", func(r *registry.Route) { r.App = "blog" })
+ if _, k := w.policy.DeclaresPrefix("abc", "blog", "v1", "/static/x"); k {
+ t.Fatal("blog's unread v1 was answered, from shop's manifest")
+ }
+ if !waitDeclared(t, w.policy, "abc", "blog", "v1", "/static/x") {
+ t.Fatal("blog's v1 does not declare /static/")
+ }
+ if d, _ := w.policy.DeclaresPrefix("abc", "blog", "v1", "/assets/app.js"); d {
+ t.Fatal("blog's v1 was answered with shop's /assets/ prefix")
+ }
+ if d, _ := w.policy.DeclaresPrefix("abc", "shop", "v1", "/static/x"); d {
+ t.Fatal("shop's v1 was answered with blog's /static/ prefix")
+ }
+}
+
// A build whose manifest cannot be read is not asked for again on every
// request: the loader waits before retrying it, and the queue is bounded.
func TestDeclaresPrefixFailedReadIsNotRetriedAtOnce(t *testing.T) {
@@ -198,7 +252,7 @@ func TestDeclaresPrefixFailedReadIsNotRetriedAtOnce(t *testing.T) {
w.confirm()
w.pass() // v9 was never shipped: its manifest read fails
for i := 0; i < 50; i++ {
- if _, k := w.policy.DeclaresPrefix("shop.example.com", "v9", "/p"); k {
+ if _, k := w.policy.DeclaresPrefix("abc", "shop", "v9", "/p"); k {
t.Fatal("an unreadable build was known")
}
time.Sleep(time.Millisecond)