carlos / platform Public

edge: route changes reset pages; only departure and switch-off clear the mark

Plan 1 Task 9 (P1-5, R3-3). A reload hook, registered by
EnablePageCache, compares the page index's scopes with every row the
last Reload read, before it filtered out sidecars and rows that are not
ready. A route gone from the box (no row for the host, or another
account or app) and PagesOff reset the scope's pages and clear its
opt-in mark. Any other ineligibility (HA, a gate, an import gate, a
status that is not ready, a sidecar, a forward row) resets the pages
and keeps the mark, so the LRU stays off. A mark that cannot be
removed is logged and retried at the next reload. Arming reloads once,
so marks loaded for instances that left while the edge was down are
cleared at once.

TestEdgeSimulationNoPersonalLeak (I2; R2-7, R3-8) drives requests,
gate, HA, status, switch and departure reloads and clears through the
real registry and Reload, and fails when the opted-in LRU gate is
dropped.

The brief's subject ran to 90 characters; this one is shortened.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 858caf1da3578aec7ca3a47133d780640de90eab parent e3a9990
3 files changed, +699 −2
  • internal/edge/edge.go +11 −0
  • internal/edge/pagecache.go +77 −2
  • internal/edge/pagecache_reload_test.go +611 −0

Intent

Human

<task-notification> <task-id>ac22e61fd10fe7542</task-id> <tool-use-id>toolu_01Mnhy81PAFhnXnX9hMKmzGB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/ac22e61fd10fe7542.output</output-file> <status>completed</status> <summary>Agent "Implement Task 8: clears reach the index" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE. The control socket now acts for the route it was built for, never for whatever the edge's route table holds. Commits: - 6ca0baba edge: Carlos-Purge and the control socket clear pages; add the all target - f6ada519 edge: purges act for the authorized instance; all reaches wildcard hosts - e3a99901 edge: the control socket acts for the route it was built for What changed: `ListenControl` and `ListenPurge` take a `registry.Route` instead of a hostname. Every socket purge's page clears and `all` expansion act for that route. I removed the owner pinning from the table and `ownerOf`. The two activator start sites (`backend_exec.go` and `prepare.go`) pass `rt`, and I updated the 14 test call sites; the repo has no other callers. Tests: - The new `TestControlSocketActsForTheSpawningRoute` builds B's listener while the table still holds A. All 3 subtests (`all`, `*`, `/p`) fail when the owner comes from the table, and pass now. - All 10 Task 8 tests pass, including under `-race`. - The wider edge purge/page/alias/cache/socket runs and the activator purge/inputs/control/childproc/drain runs pass. - `go build ./...` passes, and so do the windows and darwin builds. Concerns: - A caller that passes only `registry.Route{Host: h}` gets a page scope with no app, so its socket purges clear no real instance's pages. That's fine for the LRU-only tests that do this; the activator passes the full route. - The windows `go vet` failure (`readerConn` undefined) is unchanged and also fails on base e231c7fd, so it predates this task. Report (round-2 section appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-page-cache-1/.superpowers/sdd/2026-11-08-edge-page-cache-plan-1-home/task-8-report.md</result> <usage><subagent_tokens>231217</subagent_tokens><tool_uses>11</tool_uses><duration_ms>374257</duration_ms></usage> </task-notification>

Human

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

Attributed to this commit: 23.9 g CO₂e (3,122,649 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/edge.go b/internal/edge/edge.go
index dac09aebe..0f9fbabeb 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -316,6 +316,16 @@ type Edge struct {
// stored by EnablePageCache. Nil serves no page and stores none; the
// page diagnostics still run.
pages atomic.Pointer[pageindex.Index]
+ // pageRoutes is every row the last successful Reload read from the
+ // registry, before it left out sidecars, rows that are not ready and
+ // every other row it does not serve; pageRoutesRead says one has. The
+ // page cache's reload hook (applyPageRoutes) judges a departure from it,
+ // never from the live table. Both are guarded by reloadMu.
+ pageRoutes []registry.Route
+ pageRoutesRead bool
+ // pageHookOnce registers applyPageRoutes with OnReload once, however
+ // often EnablePageCache runs.
+ pageHookOnce sync.Once
// gzipOn is the CARLOS_EDGE_GZIP kill switch, read once in New. When
// false, ServeHTTP never constructs a gzipWriter and the writer stack is
// byte-for-byte what it was before compression existed (compress.go).
@@ -1480,6 +1490,7 @@ func (e *Edge) Reload() error {
}
}
}
+ e.pageRoutes, e.pageRoutesRead = routes, true
e.runReloadHooks()
return nil
}
diff --git a/internal/edge/pagecache.go b/internal/edge/pagecache.go
index 9e5f5dbfe..6e1d00591 100644
--- a/internal/edge/pagecache.go
+++ b/internal/edge/pagecache.go
@@ -1,6 +1,7 @@
package edge
import (
+ "fmt"
"net/http"
"slices"
"strings"
@@ -33,8 +34,73 @@ import (
// Pages are eligible only while the asset cache is armed too: its policy
// answers which paths the serving build declares as assets. nil disarms:
// no page is served or stored, and the diagnostics still run.
+//
+// Arming registers applyPageRoutes to run after every Reload, and reloads
+// once, as EnableStatic does, so a mark x loaded for an instance that left
+// the box while the edge was down is cleared now rather than at the next
+// route change (which might be that instance's return). A failed reload is
+// logged; the next one applies the rule. Reload takes reloadMu, so never
+// call this from a reload hook.
func (e *Edge) EnablePageCache(x *pageindex.Index) {
e.pages.Store(x)
+ e.pageHookOnce.Do(func() { e.OnReload(e.applyPageRoutes) })
+ if x == nil {
+ return
+ }
+ if err := e.Reload(); err != nil {
+ e.logThrottled("page-arm", fmt.Sprintf("page cache: the reload on arming failed, the next reload applies the routes: %v", err))
+ }
+}
+
+// applyPageRoutes brings every scope the page index holds into line with
+// the rows the last Reload read (pageRoutes, before any filtering), under
+// reloadMu (design P1-5, R3-3):
+// - the instance has left the box: no row has its host, or the row now
+// names another account or app. Its pages are reset and its opt-in mark
+// cleared;
+// - the page switch is off (PagesOff): the same;
+// - the row is there but is not one the page cache serves, for any other
+// reason (HA, a forward row, a gate, an import gate, a sidecar, a status
+// that is not ready): its pages are reset and the mark stays, so the LRU
+// stays off for the instance. Absence from the live table alone is this
+// case, never a departure.
+//
+// A release or a config change is not handled here: a page is served and
+// stored only from the route's current inputs (servePage, stillCurrent).
+//
+// When nothing changed it does no I/O: an eligible row is left alone, a
+// reset of a scope with no pages touches only memory, and a mark is cleared
+// only while the index still holds it. A mark that cannot be removed is
+// logged and stays, so the next reload tries again; the reload goes on.
+func (e *Edge) applyPageRoutes() {
+ x := e.pages.Load()
+ if x == nil || !e.pageRoutesRead {
+ return
+ }
+ scopes := x.Scopes()
+ if len(scopes) == 0 {
+ return
+ }
+ rows := make(map[string]registry.Route, len(e.pageRoutes))
+ for _, rt := range e.pageRoutes {
+ rows[rt.Host] = rt
+ }
+ for _, s := range scopes {
+ rt, ok := rows[s.Instance]
+ switch {
+ case !ok || routeScope(rt) != s || rt.PagesOff:
+ x.Reset(s)
+ if !x.OptedIn(s) {
+ continue
+ }
+ if err := x.ClearOptIn(s); err != nil {
+ e.logThrottled("page-unmark "+s.Instance, fmt.Sprintf(
+ "page cache: could not clear the opt-in of %s (account %s, app %s), retrying at the next reload: %v", s.Instance, s.Account, s.App, err))
+ }
+ case !pageRowEligible(rt):
+ x.Reset(s)
+ }
+ }
}
// pageScopeOf is the scope up's pages live in: the route's account (as the
@@ -144,8 +210,7 @@ func (e *Edge) pageRouteEligible(host, path string, up upstream) (inputs string,
return "", false
}
rt := up.route
- if rt.Kind != "instance" || rt.IsForward() || rt.HA || rt.IsSidecar() || rt.Backing == registry.BackingUnit ||
- rt.Status != "ready" || rt.Gate != "" || rt.ImportGate != "" || rt.PagesOff || up.viaTunnel {
+ if !pageRowEligible(rt) || up.viaTunnel {
return "", false
}
if f := e.planThrottle.Load(); f != nil {
@@ -180,6 +245,16 @@ func (e *Edge) pageRouteEligible(host, path string, up upstream) (inputs string,
return in, true
}
+// pageRowEligible is the row half of pageRouteEligible's second rule: a
+// ready instance this box runs, not a forward row, not HA, not a sidecar,
+// not unit-backed, with no password gate, no import gate and the page
+// switch on. The reload hook (applyPageRoutes) asks it of the registry's
+// rows; pageRouteEligible adds the live entry's own test (a tunnel).
+func pageRowEligible(rt registry.Route) bool {
+ return rt.Kind == "instance" && !rt.IsForward() && !rt.HA && !rt.IsSidecar() && rt.Backing != registry.BackingUnit &&
+ rt.Status == "ready" && rt.Gate == "" && rt.ImportGate == "" && !rt.PagesOff
+}
+
// pageReadable is the request half of the rule for reading the page cache:
// GET or HEAD, no Range, not an upgrade, not a door call (here or
// backhauled), not a held-stream request, no Authorization, a canonical
diff --git a/internal/edge/pagecache_reload_test.go b/internal/edge/pagecache_reload_test.go
new file mode 100644
index 000000000..d95b2edf0
--- /dev/null
+++ b/internal/edge/pagecache_reload_test.go
@@ -0,0 +1,611 @@
+package edge
+
+import (
+ "database/sql"
+ "fmt"
+ "io"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/pageindex"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// Route changes and the page cache (edge page cache plan 1, Task 9). A
+// reload resets an instance's pages whenever its route stops being one the
+// page cache serves. Only two things clear the durable opt-in mark as well:
+// the route leaving this box (no row for its host, or a row for another
+// account or app), and the page switch. Every other change keeps the mark,
+// so the LRU stays off for the instance.
+
+// reloadApp answers /p as a marked page, and every other path as a plain
+// LRU-cacheable response naming the request's provenance.
+func reloadApp(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/p" {
+ pageOK(pcBody)(w, r)
+ return
+ }
+ _, cookie := r.Header["Cookie"]
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Cache-Control", "public, max-age=600")
+ fmt.Fprintf(w, "plain %s cookie=%v", r.URL.Path, cookie)
+}
+
+// seedPersonalLRU stores a personal answer to path in the LRU, before the
+// instance opts in, and checks the LRU serves it.
+func (s *pcScene) seedPersonalLRU(path string) {
+ s.t.Helper()
+ if s.idx.OptedIn(s.scope()) {
+ s.t.Fatal("seeding the LRU after the opt-in")
+ }
+ s.get(path, "Cookie", "session=seeded")
+ before := s.b.n.Load()
+ rec := s.get(path)
+ if s.b.n.Load() != before || rec.Body.String() != "plain "+path+" cookie=true" {
+ s.t.Fatalf("the LRU did not serve the seeded %s: %q", path, rec.Body.String())
+ }
+}
+
+// optIn publishes /p, which opts the instance in, and checks it hits.
+func (s *pcScene) optIn() {
+ s.t.Helper()
+ wantCache(s.t, s.get("/p"), "miss")
+ wantCache(s.t, s.get("/p"), "hit")
+ if !s.idx.OptedIn(s.scope()) {
+ s.t.Fatal("publishing /p did not opt the instance in")
+ }
+}
+
+// wantFromApp asks for path and fails unless the app answered it.
+func (s *pcScene) wantFromApp(path string, hdr ...string) *httptest.ResponseRecorder {
+ s.t.Helper()
+ before := s.b.n.Load()
+ rec := s.get(path, hdr...)
+ if rec.Code != http.StatusOK || s.b.n.Load() != before+1 {
+ s.t.Fatalf("%s was not answered by the app: %d %q", path, rec.Code, rec.Body.String())
+ }
+ return rec
+}
+
+func (s *pcScene) wantMarked(want bool, why string) {
+ s.t.Helper()
+ if got := s.idx.OptedIn(s.scope()); got != want {
+ s.t.Fatalf("%s: opted in = %v, want %v", why, got, want)
+ }
+}
+
+func (s *pcScene) reload() {
+ s.t.Helper()
+ if err := s.e.Reload(); err != nil {
+ s.t.Fatalf("reload: %v", err)
+ }
+}
+
+// wantLRUIsTodays checks the LRU stores and serves path again: the instance
+// holds no mark.
+func (s *pcScene) wantLRUIsTodays(path string) {
+ s.t.Helper()
+ s.get(path)
+ before := s.b.n.Load()
+ s.get(path)
+ if s.b.n.Load() != before {
+ s.t.Fatalf("the LRU did not serve %s: the instance still behaves as opted in", path)
+ }
+}
+
+// putRow writes rt to reg in full. Upsert keeps a stored gate, page switch
+// and HA mark, so those go through their narrow setters, and HA, which
+// nothing clears in production, is cleared by hand as other edge tests edit
+// a row.
+func putRow(t *testing.T, reg *registry.Registry, rt registry.Route) {
+ t.Helper()
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ if err := reg.SetGate(rt.Host, rt.Gate); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetPages(rt.Host, rt.PagesOff); err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", reg.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if _, err := db.Exec(`UPDATE routes SET ha = ? WHERE host = ?`, b2i(rt.HA), rt.Host); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func b2i(b bool) int {
+ if b {
+ return 1
+ }
+ return 0
+}
+
+// rewrite changes the scene's route row in full (putRow) and reloads.
+func (s *pcScene) rewrite(mod func(*registry.Route)) {
+ s.t.Helper()
+ s.mu.Lock()
+ mod(&s.rt)
+ rt := s.rt
+ s.mu.Unlock()
+ putRow(s.t, s.reg, rt)
+ s.reload()
+}
+
+func TestRouteDepartureResetsAndClearsMark(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ depart func(s *pcScene)
+ }{
+ {"row deleted", func(s *pcScene) {
+ if err := s.reg.Delete(pcHost); err != nil {
+ t.Fatal(err)
+ }
+ s.reload()
+ }},
+ {"another app", func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.App = "other" }) }},
+ {"another account", func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.Account = "ghi" }) }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s := newPCScene(t, reloadApp)
+ s.optIn()
+ c.depart(s)
+ s.wantMarked(false, "after the departure")
+ if n := s.pages(); n != 0 {
+ t.Fatalf("%d pages survived the departure", n)
+ }
+ // The instance comes back: it starts unmarked, so the LRU is
+ // today's, and its old page is gone.
+ s.mu.Lock()
+ s.rt.App, s.rt.Account = "blog", "abc"
+ s.mu.Unlock()
+ s.rewrite(func(*registry.Route) {})
+ s.wantMarked(false, "after the return")
+ s.wantLRUIsTodays("/q")
+ wantCache(t, s.get("/p"), "miss")
+ })
+ }
+}
+
+func TestPagesOffResetsAndClearsMark(t *testing.T) {
+ s := newPCScene(t, reloadApp)
+ s.optIn()
+ s.rewrite(func(r *registry.Route) { r.PagesOff = true })
+ s.wantMarked(false, "after the switch")
+ if n := s.pages(); n != 0 {
+ t.Fatalf("%d pages survived the switch", n)
+ }
+ s.wantLRUIsTodays("/q")
+ s.rewrite(func(r *registry.Route) { r.PagesOff = false })
+ s.wantMarked(false, "after the switch back")
+ s.optIn()
+}
+
+// keepsMark seeds a personal LRU entry, opts in, and runs change (which
+// reloads into an ineligible route and asks for paths with hdr) then
+// restore. The mark survives both, the seeded URL reaches the app each
+// time, and the page misses once the route is back.
+func keepsMark(t *testing.T, change, restore func(s *pcScene), hdr ...string) {
+ s := newPCScene(t, reloadApp)
+ s.seedPersonalLRU("/q")
+ s.optIn()
+ change(s)
+ s.wantMarked(true, "after the change")
+ if n := s.pages(); n != 0 {
+ t.Fatalf("%d pages survived the change", n)
+ }
+ if hdr != nil {
+ rec := s.wantFromApp("/q", hdr...)
+ wantBody(t, rec, 200, "plain /q cookie=false")
+ s.wantFromApp("/p", hdr...)
+ }
+ restore(s)
+ s.wantMarked(true, "after the restore")
+ wantBody(t, s.wantFromApp("/q"), 200, "plain /q cookie=false")
+ wantCache(t, s.wantFromApp("/p"), "miss")
+ wantCache(t, s.get("/p"), "hit")
+}
+
+func TestGateKeepsMarkAndLRUStaysOff(t *testing.T) {
+ h, err := gate.Hash("correct horse")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cookie := gate.CookieName + "=" + gate.Mint(pcHost, h, time.Now().Add(time.Hour))
+ keepsMark(t,
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.Gate = h }) },
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.Gate = "" }) },
+ "Cookie", cookie)
+}
+
+func TestHAFlipKeepsMark(t *testing.T) {
+ keepsMark(t,
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.HA = true }) },
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.HA = false }) },
+ "Accept", "text/html")
+}
+
+// TestNotReadyAndBackKeepsMark (R3-3): a route that is not ready is absent
+// from the live table, but its row is still in the registry: it has not
+// left the box.
+func TestNotReadyAndBackKeepsMark(t *testing.T) {
+ keepsMark(t,
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.Status = "stopped" }) },
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.Status = "ready" }) })
+}
+
+// A mark that cannot be removed stays (the LRU stays off), the reload goes
+// on, and the next reload removes it.
+func TestPageMarkClearRetriedOnNextReload(t *testing.T) {
+ if runtime.GOOS == "windows" || os.Geteuid() == 0 {
+ t.Skip("directory permissions do not stop a removal here")
+ }
+ s := newPCScene(t, reloadApp)
+ marks := filepath.Join(t.TempDir(), "marks")
+ idx, err := pageindex.Open(pageindex.Config{Store: s.store, MarkDir: marks})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.idx = idx
+ s.e.EnablePageCache(idx)
+ s.optIn()
+ if err := os.Chmod(marks, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(marks, 0o700) })
+ if err := s.reg.Delete(pcHost); err != nil {
+ t.Fatal(err)
+ }
+ s.reload()
+ s.wantMarked(true, "with the mark directory read-only")
+ if n := s.pages(); n != 0 {
+ t.Fatalf("%d pages survived the departure", n)
+ }
+ if err := os.Chmod(marks, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ s.reload()
+ s.wantMarked(false, "on the next reload")
+ if ents, _ := os.ReadDir(marks); len(ents) != 0 {
+ t.Fatalf("the mark directory still holds %d files", len(ents))
+ }
+}
+
+// Arming the page cache applies the rule to the marks it loaded, over the
+// last reload's rows: a mark left by an instance that left the box while
+// the edge was down is cleared at once.
+func TestArmingClearsDepartedMarks(t *testing.T) {
+ s := newPCScene(t, reloadApp)
+ marks := filepath.Join(t.TempDir(), "marks")
+ gone := pageindex.Scope{Account: "abc", App: "gone", Instance: "gone.example.com"}
+ first, err := pageindex.Open(pageindex.Config{Store: s.store, MarkDir: marks})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := first.MarkOptIn(gone); err != nil {
+ t.Fatal(err)
+ }
+ if err := first.MarkOptIn(s.scope()); err != nil {
+ t.Fatal(err)
+ }
+ idx, err := pageindex.Open(pageindex.Config{Store: s.store, MarkDir: marks})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.idx = idx
+ s.e.EnablePageCache(idx)
+ if idx.OptedIn(gone) {
+ t.Fatal("arming kept the mark of an instance that is not on the box")
+ }
+ s.wantMarked(true, "the instance on the box")
+}
+
+// TestEdgeSimulationNoPersonalLeak (I2; R2-7, R3-8) drives random requests,
+// reloads and clears through one armed box serving two instances, and
+// checks that no personal page ever leaks from either cache. Unlike Task
+// 7's simulation (TestPageSimulationNoPersonalLeak) it changes the routes
+// under the requests: password gates, HA, a status that is not ready, the
+// page switch and departures, each written to the real registry and applied
+// by Reload.
+//
+// The app's every body names the request it answered (an id, its host and
+// path, and whether it carried a cookie or Authorization). Paths under /m
+// are marked pages, which opt the instance in; the others are s-maxage
+// responses today's LRU stores, including from personal requests before the
+// mark (the adversarial fixtures, seeded at the start and again whenever a
+// mark is cleared). The oracle tracks each instance's row, its opt-in state
+// and the pages stored since its last reset, and asserts:
+// - every page-cache hit carries an anonymous body for the same host and
+// path, was asked for by a request with no Authorization and only
+// ignorable cookies, while the route was eligible, for a page stored
+// since the last reset or clear;
+// - only an anonymous request is ever recorded as a page;
+// - while an instance is opted in, no response comes from the LRU;
+// - a host the box does not serve gets nothing from either cache;
+// - the index's mark is the oracle's after every step: it survives gates,
+// HA and status flips, and is cleared by departure and the switch;
+// - before opt-in the LRU is today's, and is not judged.
+//
+// CARLOS_EDGE_SIM_SEED replays a seed; the seed is printed on failure.
+func TestEdgeSimulationNoPersonalLeak(t *testing.T) {
+ seed := time.Now().UnixNano()
+ if v := os.Getenv("CARLOS_EDGE_SIM_SEED"); v != "" {
+ n, err := strconv.ParseInt(v, 10, 64)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seed = n
+ }
+ steps := 1000
+ if testing.Short() {
+ steps = 200
+ }
+ rng := rand.New(rand.NewSource(seed))
+ defer func() {
+ if t.Failed() {
+ t.Logf("seed %d (replay with CARLOS_EDGE_SIM_SEED=%d)", seed, seed)
+ }
+ }()
+ gateHash, err := gate.Hash("correct horse")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ const two = "two.example.com"
+ app := func(w http.ResponseWriter, r *http.Request) {
+ _, cookie := r.Header["Cookie"]
+ _, auth := r.Header["Authorization"]
+ body := fmt.Sprintf("id=%s host=%s path=%s cookie=%v auth=%v", r.Header.Get("X-Sim-Id"), r.Host, r.URL.RequestURI(), cookie, auth)
+ h := w.Header()
+ h.Set("Content-Type", "text/html")
+ h.Set("Cache-Control", "public, s-maxage=600")
+ if strings.HasPrefix(r.URL.Path, "/m") {
+ h.Set(pageCacheHeader, `on; ignore-cookies="consent"`)
+ }
+ io.WriteString(w, body)
+ }
+ s := newPCScene(t, app)
+ s.decl.loadFor("def", "shop", pcBuild, "/assets/")
+
+ type instance struct {
+ row registry.Route
+ present bool
+ optedIn bool
+ stored map[string]bool // pages stored since the last reset or clear
+ }
+ model := map[string]*instance{
+ pcHost: {row: s.rt, present: true, stored: map[string]bool{}},
+ two: {row: registry.Route{Host: two, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(),
+ Status: "ready", Account: "def", App: "shop", Version: pcBuild}, present: true, stored: map[string]bool{}},
+ }
+ disturbed := func(m *instance, field string) bool {
+ switch field {
+ case "gate":
+ return m.row.Gate != ""
+ case "ha":
+ return m.row.HA
+ case "status":
+ return m.row.Status != "ready"
+ case "pages-off":
+ return m.row.PagesOff
+ }
+ return !m.present
+ }
+ served := func(m *instance) bool { return m.present && m.row.Status == "ready" }
+ eligible := func(m *instance) bool {
+ return served(m) && m.row.Gate == "" && !m.row.HA && !m.row.PagesOff
+ }
+ hosts := []string{pcHost, two}
+ paths := []string{"/m1", "/m2?x=1", "/u1", "/u2"}
+ kinds := []string{"anon", "consent", "session", "consent+session", "auth"}
+ var ids atomic.Int64
+ var pageHits, lruBefore, notServed, optedInAnswers, optIns, markClears, resets int
+ reloads := map[string]int{}
+
+ // apply writes m's row to the registry (or deletes it), reloads, and
+ // moves the oracle: departure and the switch clear the mark, and a
+ // route that is not eligible after the reload has had its pages reset.
+ apply := func(m *instance) {
+ t.Helper()
+ if m.present {
+ putRow(t, s.reg, m.row)
+ } else if err := s.reg.Delete(m.row.Host); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ if m.present {
+ s.publishFor(m.row)
+ }
+ if (!m.present || m.row.PagesOff) && m.optedIn {
+ m.optedIn = false
+ markClears++
+ }
+ if !eligible(m) {
+ if len(m.stored) > 0 {
+ resets++
+ }
+ m.stored = map[string]bool{}
+ }
+ }
+ apply(model[two])
+
+ // request sends one request and judges its answer.
+ request := func(step int, host, path, kind string) {
+ t.Helper()
+ m := model[host]
+ id := strconv.FormatInt(ids.Add(1), 10)
+ req := httptest.NewRequest(http.MethodGet, "http://"+host+path, nil)
+ req.Header.Set("X-Sim-Id", id)
+ var cookies []string
+ if m.row.Gate != "" {
+ cookies = append(cookies, gate.CookieName+"="+gate.Mint(host, gateHash, time.Now().Add(time.Hour)))
+ }
+ switch kind {
+ case "consent":
+ cookies = append(cookies, "consent=yes")
+ case "session":
+ cookies = append(cookies, "session=s-"+id)
+ case "consent+session":
+ cookies = append(cookies, "consent=yes", "session=s-"+id)
+ case "auth":
+ req.Header.Set("Authorization", "Bearer t-"+id)
+ }
+ if cookies != nil {
+ req.Header.Set("Cookie", strings.Join(cookies, "; "))
+ }
+ optedIn := m.optedIn
+ rec := httptest.NewRecorder()
+ s.e.ServeHTTP(rec, req)
+ body := rec.Body.String()
+ verdict := rec.Header().Get(assetCacheHeader)
+ where := fmt.Sprintf("step %d: a %s request to %s%s", step, kind, host, path)
+ if !served(m) {
+ notServed++
+ if verdict == "hit" || strings.Contains(body, "id=") {
+ t.Fatalf("%s, which the box does not serve, was answered from a cache: %d %q", where, rec.Code, body)
+ }
+ return
+ }
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s = %d %q", where, rec.Code, body)
+ }
+ fromApp := strings.HasPrefix(body, "id="+id+" ")
+ if optedIn {
+ optedInAnswers++
+ }
+ switch {
+ case verdict == "hit":
+ pageHits++
+ if kind != "anon" && kind != "consent" {
+ t.Fatalf("%s was answered from the page cache: %q", where, body)
+ }
+ if !strings.HasSuffix(body, "cookie=false auth=false") {
+ t.Fatalf("%s got a personal page: %q", where, body)
+ }
+ if !strings.Contains(body, " host="+host+" path="+path+" ") {
+ t.Fatalf("%s got another page: %q", where, body)
+ }
+ if !eligible(m) {
+ t.Fatalf("%s got a page while the route %+v is not eligible", where, m.row)
+ }
+ if !m.stored[path] {
+ t.Fatalf("%s got a page stored before the last reset or clear: %q", where, body)
+ }
+ case !fromApp:
+ if optedIn {
+ t.Fatalf("%s was answered from the LRU while the instance is opted in: %q", where, body)
+ }
+ lruBefore++
+ case verdict == "miss":
+ if kind != "anon" {
+ t.Fatalf("%s was recorded as a page", where)
+ }
+ if !m.optedIn {
+ optIns++
+ }
+ m.stored[path], m.optedIn = true, true
+ }
+ }
+
+ // The adversarial fixtures: before either instance opts in, today's LRU
+ // stores personal answers to its unmarked paths.
+ seedLRU := func(host string) {
+ for _, path := range paths[2:] {
+ request(-1, host, path, "session")
+ }
+ }
+ for _, host := range hosts {
+ seedLRU(host)
+ }
+ if s.lruLen() == 0 {
+ t.Fatal("no personal LRU entries were seeded")
+ }
+
+ for step := 0; step < steps; step++ {
+ host := hosts[rng.Intn(len(hosts))]
+ m := model[host]
+ switch r := rng.Intn(100); {
+ case r < 3:
+ s.idx.Clear(pageindex.Scope{Account: m.row.Account, App: m.row.App, Instance: host}, pageindex.Clear{})
+ m.stored = map[string]bool{}
+ reloads["clear"]++
+ case r < 15:
+ // A reload of this instance's row: mostly a disturbance put
+ // right, sometimes a new one (stacked on another or not), and
+ // sometimes nothing at all, which must change nothing.
+ var on, off []string
+ for _, f := range []string{"gate", "ha", "status", "pages-off", "presence"} {
+ if disturbed(m, f) {
+ on = append(on, f)
+ } else {
+ off = append(off, f)
+ }
+ }
+ op := "none"
+ switch {
+ case len(on) > 0 && rng.Intn(4) != 0:
+ op = on[rng.Intn(len(on))]
+ case len(on) > 0 || rng.Intn(3) == 0:
+ op = off[rng.Intn(len(off))]
+ }
+ reloads[op]++
+ switch op {
+ case "gate":
+ if m.row.Gate == "" {
+ m.row.Gate = gateHash
+ } else {
+ m.row.Gate = ""
+ }
+ case "ha":
+ m.row.HA = !m.row.HA
+ case "status":
+ if m.row.Status == "ready" {
+ m.row.Status = "stopped"
+ } else {
+ m.row.Status = "ready"
+ }
+ case "pages-off":
+ m.row.PagesOff = !m.row.PagesOff
+ case "presence":
+ m.present = !m.present
+ }
+ wasOptedIn := m.optedIn
+ apply(m)
+ if wasOptedIn && !m.optedIn && served(m) {
+ // The mark is gone, so the LRU is today's again: seed it
+ // with personal answers for the next opt-in to ignore.
+ seedLRU(host)
+ }
+ default:
+ request(step, host, paths[rng.Intn(len(paths))], kinds[rng.Intn(len(kinds))])
+ }
+ for _, h := range hosts {
+ mh := model[h]
+ sc := pageindex.Scope{Account: mh.row.Account, App: mh.row.App, Instance: h}
+ if got := s.idx.OptedIn(sc); got != mh.optedIn {
+ t.Fatalf("step %d: %s opted in = %v, the oracle says %v (row %+v, present %v)", step, h, got, mh.optedIn, mh.row, mh.present)
+ }
+ }
+ }
+ if pageHits == 0 {
+ t.Fatalf("the run produced no page hits (seed %d): the oracle judged nothing", seed)
+ }
+ t.Logf("seed %d: %d steps, %d page hits, %d answers while opted in, %d LRU answers before opt-in, %d unserved, %d opt-ins, %d mark clears, %d resets, ops %v",
+ seed, steps, pageHits, optedInAnswers, lruBefore, notServed, optIns, markClears, resets, reloads)
+}