carlos / platform Public

pageindex: fence the opt-in mark by the render's epoch; departure is one step

Task 9 review, Important 1: a reload that reset a scope and cleared its
mark after a recording passed stillCurrent let the recorder's MarkOptIn
write the mark back. The page was refused by the epoch, but the mark
stayed, and a later reload that restored eligibility kept it.

MarkOptInFor(Ticket) replaces MarkOptIn: it checks the ticket's epoch
under the scope lock and writes nothing (false) once a Reset has ended
it. ResetAndClearOptIn holds the scope's mark lock across Reset and the
mark removal, so a departure either follows the mark write and clears
it or precedes the epoch check. The recorder uses MarkOptInFor and
aborts on false; the reload hook uses ResetAndClearOptIn for departure
and PagesOff.

Important 2: the edge simulation picked a disturbance from an empty
list when all five were active; it now undoes one instead.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4598f3e39d8cbf0edee58b10718a3f3034c84ac1 parent 858caf1
7 files changed, +272 −37
  • internal/edge/pagecache.go +6 −6
  • internal/edge/pagecache_reload_test.go +74 −6
  • internal/edge/pagerecord.go +18 −2
  • internal/pageindex/index.go +3 −1
  • internal/pageindex/index_test.go +104 −4
  • internal/pageindex/optin.go +61 −14
  • internal/pageindex/sim_test.go +6 −4

CI cancelled — superseded by a newer push — run details

Intent

Human

<task-notification> <task-id>ad2816afb902f3f83</task-id> <tool-use-id>toolu_016BKNKBgGpzde4qR6v1XsT3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/ad2816afb902f3f83.output</output-file> <status>completed</status> <summary>Agent "Implement Task 9: reload hook and I2 sim" 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 reload hook now resets an instance's page scope when its route changes, and clears the opt-in mark only on departure or `PagesOff`. Commit: `858caf1d edge: route changes reset pages; only departure and switch-off clear the mark`. The brief's subject was 90 characters, so I shortened it; the commit body says so. Tests: all 8 Task 9 tests pass, including `TestEdgeSimulationNoPersonalLeak` (1000 steps, 200 under `-short`), along with a wider targeted edge run and the pageindex tests. Dropping the opted-in LRU gate makes the simulation fail on 8 of 8 seeds, and the other 7 mutations are each caught. Concerns: 1. Arming now calls `Reload()`, because a guard test allows `reloadMu` only inside `Reload`. Whoever wires `EnablePageCache` in must not call it from inside a reload hook. 2. A narrow race (`stillCurrent` passes, the reload clears the mark, then `MarkOptIn` writes it back) can leave a stale mark on a departed instance. It errs on the safe side (the LRU stays off) and the next reload clears it; a full fix needs an epoch check in pageindex. 3. Departed scopes stay in `Scopes()` forever, at a small in-memory cost per reload. 4. `Upsert` can't clear a gate, the page switch or HA, so the tests write rows with the narrow setters and clear HA by hand in SQL (production never clears it). Task 7's `setRoute` uses plain `Upsert` and can't clear those fields either. 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-9-report.md</result> <usage><subagent_tokens>163020</subagent_tokens><tool_uses>52</tool_uses><duration_ms>1208953</duration_ms></usage> </task-notification>

Human

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

Attributed to this commit: 36.6 g CO₂e (4,747,810 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/pagecache.go b/internal/edge/pagecache.go
index 6e1d00591..e29ff3455 100644
--- a/internal/edge/pagecache.go
+++ b/internal/edge/pagecache.go
@@ -70,7 +70,9 @@ func (e *Edge) EnablePageCache(x *pageindex.Index) {
//
// 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
+// only while the index still holds it. A departure's reset and mark clear
+// are one step (ResetAndClearOptIn), so a recording that passed
+// stillCurrent before the reload cannot write the mark back after 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()
@@ -89,11 +91,9 @@ func (e *Edge) applyPageRoutes() {
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 {
+ // One step against an in-flight recording's mark
+ // (MarkOptInFor), and no I/O once the mark is gone.
+ if err := x.ResetAndClearOptIn(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))
}
diff --git a/internal/edge/pagecache_reload_test.go b/internal/edge/pagecache_reload_test.go
index d95b2edf0..3df1efa3c 100644
--- a/internal/edge/pagecache_reload_test.go
+++ b/internal/edge/pagecache_reload_test.go
@@ -296,11 +296,11 @@ func TestArmingClearsDepartedMarks(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err := first.MarkOptIn(gone); err != nil {
- t.Fatal(err)
+ if ok, err := first.MarkOptInFor(first.Begin(gone, "")); err != nil || !ok {
+ t.Fatalf("mark: %v %v", ok, err)
}
- if err := first.MarkOptIn(s.scope()); err != nil {
- t.Fatal(err)
+ if ok, err := first.MarkOptInFor(first.Begin(s.scope(), "")); err != nil || !ok {
+ t.Fatalf("mark: %v %v", ok, err)
}
idx, err := pageindex.Open(pageindex.Config{Store: s.store, MarkDir: marks})
if err != nil {
@@ -559,9 +559,9 @@ func TestEdgeSimulationNoPersonalLeak(t *testing.T) {
}
op := "none"
switch {
- case len(on) > 0 && rng.Intn(4) != 0:
+ case len(on) > 0 && (len(off) == 0 || rng.Intn(4) != 0):
op = on[rng.Intn(len(on))]
- case len(on) > 0 || rng.Intn(3) == 0:
+ case len(off) > 0 && (len(on) > 0 || rng.Intn(3) == 0):
op = off[rng.Intn(len(off))]
}
reloads[op]++
@@ -609,3 +609,71 @@ func TestEdgeSimulationNoPersonalLeak(t *testing.T) {
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)
}
+
+// A departure or the switch that lands after a recording has passed
+// stillCurrent, and before it writes the opt-in mark, still leaves the
+// instance unmarked: the recording's mark is fenced by its ticket's epoch,
+// which the reload ended. Its page is not stored, and when the route comes
+// back eligible the LRU is today's.
+func TestPageMarkFencedAgainstInFlightRecording(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ change, restore func(s *pcScene)
+ }{
+ {"departure",
+ func(s *pcScene) {
+ if err := s.reg.Delete(pcHost); err != nil {
+ t.Error(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Error(err)
+ }
+ },
+ func(s *pcScene) { s.rewrite(func(*registry.Route) {}) }},
+ {"pages off",
+ func(s *pcScene) {
+ s.mu.Lock()
+ s.rt.PagesOff = true
+ rt := s.rt
+ s.mu.Unlock()
+ if err := s.reg.SetPages(rt.Host, true); err != nil {
+ t.Error(err)
+ }
+ if err := s.e.Reload(); err != nil {
+ t.Error(err)
+ }
+ },
+ func(s *pcScene) { s.rewrite(func(r *registry.Route) { r.PagesOff = false }) }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s := newPCScene(t, reloadApp)
+ var ran atomic.Bool
+ pageBeforeMark = func() {
+ if !ran.CompareAndSwap(false, true) {
+ return
+ }
+ // The reload runs on its own goroutine, as Watch's does,
+ // and the recording waits for it to finish.
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ c.change(s)
+ }()
+ <-done
+ }
+ t.Cleanup(func() { pageBeforeMark = nil })
+ s.get("/p")
+ if !ran.Load() {
+ t.Fatal("the recording never reached the mark")
+ }
+ pageBeforeMark = nil
+ s.wantMarked(false, "after the in-flight recording")
+ if n := s.pages(); n != 0 {
+ t.Fatalf("the in-flight recording stored %d pages", n)
+ }
+ c.restore(s)
+ s.wantMarked(false, "once the route is eligible again")
+ s.wantLRUIsTodays("/q")
+ })
+ }
+}
diff --git a/internal/edge/pagerecord.go b/internal/edge/pagerecord.go
index d09a1881e..ec4adf27a 100644
--- a/internal/edge/pagerecord.go
+++ b/internal/edge/pagerecord.go
@@ -137,6 +137,11 @@ func (p *pageRecorder) abort() {
}
}
+// pageBeforeMark, when set, runs in finish after stillCurrent has passed and
+// before the opt-in mark is written. Tests only: it lets a reload land in
+// that window.
+var pageBeforeMark func()
+
// finish publishes the recorded page once the proxy has returned, or
// abandons it: on a body shorter than its Content-Length or a failed client
// write, on a Set-Cookie trailer (announced or not), and when the route, its
@@ -157,18 +162,29 @@ func (p *pageRecorder) finish() {
pend.Abort()
return
}
- if err := ps.x.MarkOptIn(ps.scope); err != nil {
+ if pageBeforeMark != nil {
+ pageBeforeMark()
+ }
+ // The mark is written only while the recording's epoch is current: a
+ // departure or the switch that reset the scope since stillCurrent ended
+ // it, and the page could not be published either (MarkOptInFor).
+ marked, err := ps.x.MarkOptInFor(ps.ticket)
+ if err != nil {
pend.Abort()
ps.e.logThrottled("page-mark "+ps.up.route.Host, fmt.Sprintf(
"page cache: could not record the opt-in of %s, so its page was not stored: %v", ps.up.route.Host, err))
return
}
+ if !marked {
+ pend.Abort()
+ return
+ }
var ignore []string
if m := pageMarkOf(ps.r); m != nil {
ignore = m.Ignore
}
now := ps.e.pageClock()
- _, err := pend.Finish(assetcache.Meta{Header: assetStoredHeader(p.snap), Lifetime: p.lifetime, Expires: now.Add(p.lifetime)}, ignore)
+ _, err = pend.Finish(assetcache.Meta{Header: assetStoredHeader(p.snap), Lifetime: p.lifetime, Expires: now.Add(p.lifetime)}, ignore)
if err != nil {
pend.Abort()
ps.e.logThrottled("page-commit "+ps.up.route.Host, fmt.Sprintf(
diff --git a/internal/pageindex/index.go b/internal/pageindex/index.go
index 38056b13b..cc2a809c4 100644
--- a/internal/pageindex/index.go
+++ b/internal/pageindex/index.go
@@ -95,6 +95,8 @@ type Config struct {
LogMax int // 0 means 256
LogAge time.Duration // 0 means 10 * time.Minute
afterCommit func() // test seam: runs between Commit and the scope lock
+ // test seam: runs in MarkOptInFor after the epoch check, before the write
+ beforeMarkWrite func()
}
// MaxBody is the largest page body the index stores.
@@ -123,7 +125,7 @@ type scopeState struct {
log []logEntry // oldest first
records map[Key]record
- markMu sync.Mutex // serializes this scope's mark file changes
+ markMu sync.Mutex // serializes this scope's mark file changes; taken before mu
marked atomic.Bool // the mark file is durably present
}
diff --git a/internal/pageindex/index_test.go b/internal/pageindex/index_test.go
index 5dfc85f10..fc1a2976d 100644
--- a/internal/pageindex/index_test.go
+++ b/internal/pageindex/index_test.go
@@ -449,13 +449,13 @@ func TestOptInMarkSurvivesOpen(t *testing.T) {
r := newRig(t, 64<<20, nil)
other := Scope{Account: shop.Account, App: shop.App, Instance: "shop-2"}
if r.x.OptedIn(shop) {
- t.Fatal("OptedIn before MarkOptIn = true")
+ t.Fatal("OptedIn before MarkOptInFor = true")
}
- if err := r.x.MarkOptIn(shop); err != nil {
- t.Fatal(err)
+ if ok, err := r.x.MarkOptInFor(r.x.Begin(shop, "b1")); err != nil || !ok {
+ t.Fatalf("MarkOptInFor = %v, %v", ok, err)
}
if !r.x.OptedIn(shop) {
- t.Fatal("OptedIn after MarkOptIn = false")
+ t.Fatal("OptedIn after MarkOptInFor = false")
}
sum := sha256.Sum256([]byte(shop.Account + "\x00" + shop.App + "\x00" + shop.Instance))
if _, err := os.Stat(filepath.Join(r.markDir, hex.EncodeToString(sum[:]))); err != nil {
@@ -480,6 +480,106 @@ func TestOptInMarkSurvivesOpen(t *testing.T) {
}
}
+// A render's mark is fenced by its ticket's epoch: once a Reset has ended
+// it, MarkOptInFor writes nothing, whether the Reset cleared the mark or
+// not, and a later ticket marks as before.
+func TestMarkOptInForFencedByReset(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ reset func(x *Index)
+ }{
+ {"ResetAndClearOptIn", func(x *Index) {
+ if err := x.ResetAndClearOptIn(shop); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {"Reset", func(x *Index) { x.Reset(shop) }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ old := r.x.Begin(shop, "b1")
+ c.reset(r.x)
+ if ok, err := r.x.MarkOptInFor(old); err != nil || ok {
+ t.Fatalf("MarkOptInFor(a ticket from before the reset) = %v, %v; want false, nil", ok, err)
+ }
+ if r.x.OptedIn(shop) {
+ t.Fatal("a ticket from before the reset marked the scope")
+ }
+ if ents, _ := os.ReadDir(r.markDir); len(ents) != 0 {
+ t.Fatalf("the mark directory holds %d files", len(ents))
+ }
+ if ok, err := r.x.MarkOptInFor(r.x.Begin(shop, "b1")); err != nil || !ok {
+ t.Fatalf("MarkOptInFor(a fresh ticket) = %v, %v", ok, err)
+ }
+ if !r.x.OptedIn(shop) {
+ t.Fatal("a fresh ticket did not mark the scope")
+ }
+ })
+ }
+ t.Run("marked already", func(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ if ok, err := r.x.MarkOptInFor(r.x.Begin(shop, "b1")); err != nil || !ok {
+ t.Fatalf("MarkOptInFor = %v, %v", ok, err)
+ }
+ old := r.x.Begin(shop, "b1")
+ r.x.Reset(shop)
+ if ok, _ := r.x.MarkOptInFor(old); ok {
+ t.Fatal("MarkOptInFor of an ended epoch = true on a marked scope")
+ }
+ if !r.x.OptedIn(shop) {
+ t.Fatal("a plain Reset cleared the mark")
+ }
+ })
+}
+
+// A departure that starts while a mark is being written waits for it and
+// then clears it: the mark is never left behind. The write is held in the
+// window after the epoch check; ResetAndClearOptIn must not finish while it
+// is held, and the scope ends unmarked.
+func TestResetAndClearOptInWaitsForMarkWrite(t *testing.T) {
+ var armed atomic.Bool
+ entered, release := make(chan struct{}), make(chan struct{})
+ r := newRig(t, 64<<20, func(c *Config) {
+ c.beforeMarkWrite = func() {
+ if armed.CompareAndSwap(true, false) {
+ close(entered)
+ <-release
+ }
+ }
+ })
+ tk := r.x.Begin(shop, "b1")
+ armed.Store(true)
+ marked := make(chan error, 1)
+ go func() {
+ _, err := r.x.MarkOptInFor(tk)
+ marked <- err
+ }()
+ <-entered
+ departed := make(chan error, 1)
+ go func() { departed <- r.x.ResetAndClearOptIn(shop) }()
+ select {
+ case err := <-departed:
+ t.Fatalf("ResetAndClearOptIn finished (%v) while a mark write was held", err)
+ case <-time.After(100 * time.Millisecond):
+ }
+ close(release)
+ if err := <-marked; err != nil {
+ t.Fatal(err)
+ }
+ if err := <-departed; err != nil {
+ t.Fatal(err)
+ }
+ if r.x.OptedIn(shop) {
+ t.Fatal("the scope is still marked after the departure")
+ }
+ if ents, _ := os.ReadDir(r.markDir); len(ents) != 0 {
+ t.Fatalf("the mark directory holds %d files", len(ents))
+ }
+ if x2 := r.open(nil); x2.OptedIn(shop) {
+ t.Fatal("the mark came back on re-Open")
+ }
+}
+
func TestTooLargeAborts(t *testing.T) {
r := newRig(t, 64<<20, nil)
k := pageKey("/big", "")
diff --git a/internal/pageindex/optin.go b/internal/pageindex/optin.go
index 1f02357a2..b177089f0 100644
--- a/internal/pageindex/optin.go
+++ b/internal/pageindex/optin.go
@@ -24,39 +24,81 @@ func markName(s Scope) string {
return hex.EncodeToString(sum[:])
}
-// MarkOptIn makes s's mark durable: written to a temporary, fsynced,
-// renamed into place, and the directory fsynced. OptedIn reports true only
-// once all of that has succeeded.
-func (x *Index) MarkOptIn(s Scope) error {
- st := x.scope(s)
+// MarkOptInFor makes the mark of t's scope durable for the render t began,
+// unless a Reset has ended t's epoch since: then it writes nothing and
+// returns false, since that render's page cannot be published either. The
+// mark is written to a temporary, fsynced, renamed into place, and the
+// directory fsynced; OptedIn reports true only once all of that has
+// succeeded.
+//
+// The epoch is checked under the scope's lock, and the check and the write
+// are serialized with ResetAndClearOptIn by the scope's mark lock. So a
+// departure either comes after the mark and clears it, or comes before the
+// check and the mark is never written: a render begun before a departure
+// cannot bring the mark back.
+func (x *Index) MarkOptInFor(t Ticket) (bool, error) {
+ st := x.scope(t.Scope)
if st.marked.Load() {
- return nil
+ // Already durable: nothing is written, so no lock is needed.
+ return st.epochIs(t.Epoch), nil
}
st.markMu.Lock()
defer st.markMu.Unlock()
+ if !st.epochIs(t.Epoch) {
+ return false, nil
+ }
if st.marked.Load() {
- return nil
+ return true, nil
+ }
+ if x.cfg.beforeMarkWrite != nil {
+ x.cfg.beforeMarkWrite()
}
- raw, err := json.Marshal(s)
+ raw, err := json.Marshal(t.Scope)
if err != nil {
- return fmt.Errorf("pageindex: %w", err)
+ return false, fmt.Errorf("pageindex: %w", err)
}
dir := x.cfg.MarkDir
- name := filepath.Join(dir, markName(s))
+ name := filepath.Join(dir, markName(t.Scope))
tmp := fmt.Sprintf("%s.tmp-%016x", name, random64())
if err := writeSynced(tmp, raw); err != nil {
os.Remove(tmp)
- return err
+ return false, err
}
if err := os.Rename(tmp, name); err != nil {
os.Remove(tmp)
- return fmt.Errorf("pageindex: %w", err)
+ return false, fmt.Errorf("pageindex: %w", err)
}
if err := syncDir(dir); err != nil {
- return err
+ return false, err
}
st.marked.Store(true)
- return nil
+ return true, nil
+}
+
+// epochIs reports whether st's epoch is still epoch.
+func (st *scopeState) epochIs(epoch uint64) bool {
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ return st.epoch == epoch
+}
+
+// ResetAndClearOptIn is Reset and then ClearOptIn as one step against
+// MarkOptInFor: it holds the scope's mark lock across both, so no render
+// begun before it can write the mark after it. It is the step for an
+// instance that has left the box or switched pages off. When s holds no
+// mark it does no I/O.
+func (x *Index) ResetAndClearOptIn(s Scope) error {
+ st := x.lookupScope(s)
+ if st == nil {
+ return nil
+ }
+ st.markMu.Lock()
+ defer st.markMu.Unlock()
+ x.Reset(s)
+ if !st.marked.Load() {
+ return nil
+ }
+ return x.clearMarkLocked(s, st)
}
// ClearOptIn removes s's mark and fsyncs the directory. OptedIn reports
@@ -65,6 +107,11 @@ func (x *Index) ClearOptIn(s Scope) error {
st := x.scope(s)
st.markMu.Lock()
defer st.markMu.Unlock()
+ return x.clearMarkLocked(s, st)
+}
+
+// clearMarkLocked is ClearOptIn under st.markMu.
+func (x *Index) clearMarkLocked(s Scope, st *scopeState) error {
dir := x.cfg.MarkDir
if err := os.Remove(filepath.Join(dir, markName(s))); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("pageindex: %w", err)
diff --git a/internal/pageindex/sim_test.go b/internal/pageindex/sim_test.go
index 6a6290425..9b342c06b 100644
--- a/internal/pageindex/sim_test.go
+++ b/internal/pageindex/sim_test.go
@@ -496,10 +496,12 @@ func (sm *sim) optIn(si int, rnd *rand.Rand) {
sm.optMu[si].Lock()
defer sm.optMu[si].Unlock()
if rnd.Intn(2) == 0 {
- if err := x.MarkOptIn(s); err != nil {
- t.Errorf("MarkOptIn(%d): %v", si, err)
- } else if !x.OptedIn(s) {
- t.Errorf("OptedIn(%d) after MarkOptIn = false", si)
+ // A Reset between Begin and the mark ends the ticket's epoch,
+ // and then nothing is written (false).
+ if ok, err := x.MarkOptInFor(x.Begin(s, "")); err != nil {
+ t.Errorf("MarkOptInFor(%d): %v", si, err)
+ } else if ok && !x.OptedIn(s) {
+ t.Errorf("OptedIn(%d) after MarkOptInFor = false", si)
}
return
}