carlos / platform Public

pageindex: one index owns every page publish, clear, reset and lookup

New package internal/pageindex, the spec's page index (6.1). Per-scope
lock over Clear, Reset, Lookup and Finish's indexing step; a unique
physical store key per publish attempt (P1-1); epoch, sequence and a
bounded clear log fence renders a matching clear raced; Sweep drops
records whose store object was evicted (R2-8); durable opt-in marks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a44017d5e75eaa405c3881760ddbc5326cff58af parent e8043ac
4 files changed, +1,234 −0
  • internal/pageindex/index.go +428 −0
  • internal/pageindex/index_test.go +512 −0
  • internal/pageindex/optin.go +155 −0
  • internal/pageindex/pending.go +139 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>a75f085d30159ee68</task-id> <tool-use-id>toolu_015oFxGUQuh2NQ3tdCZQHreS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/a75f085d30159ee68.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: assetcache Delete" 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>I didn't touch `copy-review/`, and it's outside my task. A concurrent copy-review session probably changed it, so I'm leaving it alone. **Status:** DONE_WITH_CONCERNS **Commit:** e8043ac6 assetcache: Delete and page keys the asset sweep leaves alone **Tests:** - RED came first for both packages: `s.Delete undefined` in `internal/assetcache`, and "sweep dropped 2 entries, want only the asset key" in `internal/edge`. - GREEN: `go test -race ./internal/assetcache -run 'TestDelete|TestKey'` passes. - GREEN: `go test ./internal/edge -run TestSweep` passes. - `TestSweepAssetsKeepsPageKeys` also passes under `-race`. - Edge tests ran outside the sandbox with a short `TMPDIR`, as the house rules require. **Concerns:** - The worktree now shows `copy-review/result.json` deleted and `copy-review/strings.json` modified. Both are unstaged and not in my commit. - I used the commit trailer from the house rules (Claude Opus 5.5). That differs from the attribution line in the session reminder (Claude Sonnet 5.5). - `TestSweepAssetsKeepsPageKeys` commits entries directly with `Expires` set to now plus an hour. The existing `serveEntry` helper stamps a fixed past expiry, so `Get` missed. **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-1-report.md</result> <usage><subagent_tokens>56166</subagent_tokens><tool_uses>15</tool_uses><duration_ms>218334</duration_ms></usage> </task-notification>

Human

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

Attributed to this commit: 26.4 g CO₂e (3,472,601 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/pageindex/index.go b/internal/pageindex/index.go
new file mode 100644
index 000000000..38056b13b
--- /dev/null
+++ b/internal/pageindex/index.go
@@ -0,0 +1,428 @@
+// Package pageindex is the edge's page index: the only code that makes a
+// cached page servable, removes one, or answers a lookup for one.
+//
+// Page bytes live in an assetcache.Store. Each attempt to publish a page
+// writes its own physical store object, whose key's Gen begins
+// assetcache.PageGenPrefix and carries the scope's epoch and a random
+// attempt id, so no two attempts ever share an object. The index maps each
+// logical page (host, path, query) of a scope to the one physical object it
+// published.
+//
+// Every scope (one app instance) has its own lock. Clear, Reset, Lookup and
+// the indexing step of Finish run under it, so they are totally ordered
+// within the scope. A render takes a Ticket when it begins; its Finish is
+// indexed only if no clear since that ticket could have matched it. Store
+// calls that may delete files are made after the scope lock is released.
+package pageindex
+
+import (
+ "crypto/rand"
+ "encoding/binary"
+ "errors"
+ "slices"
+ "sort"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+)
+
+// Scope is one app instance's pages.
+type Scope struct{ Account, App, Instance string }
+
+// Key is one logical page within a scope.
+type Key struct{ Host, Path, RawQuery string }
+
+// TargetKind says what a Target matches.
+type TargetKind int
+
+const (
+ // TargetHost matches every key on the clear's hosts.
+ TargetHost TargetKind = iota
+ // TargetPath matches the path with any query.
+ TargetPath
+ // TargetURL matches the exact path and raw query.
+ TargetURL
+)
+
+// Target is one thing a Clear removes.
+type Target struct {
+ Kind TargetKind
+ Path, RawQuery string
+}
+
+// Clear names the pages of a scope to remove.
+type Clear struct {
+ Hosts []string // nil = every host of the scope
+ Targets []Target // nil = everything on Hosts
+}
+
+// Ticket is what a render takes when it begins: the scope's epoch and
+// sequence at that moment, and the inputs it renders from.
+type Ticket struct {
+ Scope Scope
+ Epoch, Seq uint64
+ Inputs string
+}
+
+// Info is what the index keeps beside each published page.
+type Info struct {
+ ValidAt uint64 // the scope's sequence when the page was indexed
+ Ignore []string // cookie names a request may carry and still be served
+ Inputs string // the inputs the page was rendered from
+}
+
+// Miss says why Lookup found nothing to serve.
+type Miss int
+
+const (
+ // MissNone is a hit.
+ MissNone Miss = iota
+ // MissAbsent means no page is indexed, or the store no longer has it.
+ MissAbsent
+ // MissCookies means the request carries a cookie the page does not ignore.
+ MissCookies
+ // MissInputs means the page was rendered from other inputs.
+ MissInputs
+)
+
+// Config configures an Index.
+type Config struct {
+ Store *assetcache.Store
+ MarkDir string // where opt-in marks are kept; created 0700
+ Now func() time.Time
+ LogMax int // 0 means 256
+ LogAge time.Duration // 0 means 10 * time.Minute
+ afterCommit func() // test seam: runs between Commit and the scope lock
+}
+
+// MaxBody is the largest page body the index stores.
+const MaxBody = 8 << 20
+
+const (
+ defaultLogMax = 256
+ defaultLogAge = 10 * time.Minute
+)
+
+// Index is the page index over one store.
+type Index struct {
+ cfg Config
+
+ mu sync.Mutex // guards scopes only
+ scopes map[Scope]*scopeState
+}
+
+// scopeState is one scope's state. Every field but the mark fields is
+// guarded by mu.
+type scopeState struct {
+ mu sync.Mutex
+ epoch uint64
+ seq uint64 // the sequence of the last clear on this epoch
+ floor uint64 // log holds every clear with a sequence in (floor, seq]
+ log []logEntry // oldest first
+ records map[Key]record
+
+ markMu sync.Mutex // serializes this scope's mark file changes
+ marked atomic.Bool // the mark file is durably present
+}
+
+// record is one published page: its physical store key and its Info.
+type record struct {
+ phys assetcache.Key
+ info Info
+}
+
+// logEntry is one clear in a scope's log.
+type logEntry struct {
+ seq uint64
+ at time.Time
+ c Clear
+}
+
+// Open makes an index over cfg.Store. It deletes every page object the
+// store holds, because the epochs they were published under belong to an
+// earlier process, and loads the opt-in marks from cfg.MarkDir. A store has
+// one Index: a second Open would delete the first one's pages.
+func Open(cfg Config) (*Index, error) {
+ if cfg.Store == nil {
+ return nil, errors.New("pageindex: no store")
+ }
+ if cfg.MarkDir == "" {
+ return nil, errors.New("pageindex: no mark directory")
+ }
+ if cfg.Now == nil {
+ cfg.Now = time.Now
+ }
+ if cfg.LogMax <= 0 {
+ cfg.LogMax = defaultLogMax
+ }
+ if cfg.LogAge <= 0 {
+ cfg.LogAge = defaultLogAge
+ }
+ x := &Index{cfg: cfg, scopes: make(map[Scope]*scopeState)}
+ cfg.Store.Retain(func(k assetcache.Key) bool { return !assetcache.IsPageKey(k) })
+ if err := x.loadMarks(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+// random64 draws a random 64-bit value. crypto/rand.Read does not fail.
+func random64() uint64 {
+ var b [8]byte
+ rand.Read(b[:])
+ return binary.BigEndian.Uint64(b[:])
+}
+
+// scope returns s's state, making it with a fresh epoch the first time s is
+// touched in this process.
+func (x *Index) scope(s Scope) *scopeState {
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ st := x.scopes[s]
+ if st == nil {
+ st = &scopeState{epoch: random64(), records: make(map[Key]record)}
+ x.scopes[s] = st
+ }
+ return st
+}
+
+// lookupScope returns s's state, or nil when s has never been touched.
+func (x *Index) lookupScope(s Scope) *scopeState {
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ return x.scopes[s]
+}
+
+// Begin starts a render for s from inputs.
+func (x *Index) Begin(s Scope, inputs string) Ticket {
+ st := x.scope(s)
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ return Ticket{Scope: s, Epoch: st.epoch, Seq: st.seq, Inputs: inputs}
+}
+
+// Clear removes the pages of s that c matches, fences every render begun
+// before it whose page c matches, and returns the clear's sequence. The
+// matching pages' store objects are deleted before it returns.
+func (x *Index) Clear(s Scope, c Clear) (seq uint64) {
+ c = cloneClear(c)
+ st := x.scope(s)
+ now := x.cfg.Now()
+ st.mu.Lock()
+ st.seq++
+ seq = st.seq
+ st.log = append(st.log, logEntry{seq: seq, at: now, c: c})
+ st.trimLocked(now, x.cfg.LogMax, x.cfg.LogAge)
+ var gone []assetcache.Key
+ for k, rec := range st.records {
+ if c.matches(k) {
+ gone = append(gone, rec.phys)
+ delete(st.records, k)
+ }
+ }
+ st.mu.Unlock()
+ x.deleteAll(gone)
+ return seq
+}
+
+// trimLocked drops the oldest clears while the log is longer than max or
+// older than age, raising floor past each. The caller holds st.mu.
+func (st *scopeState) trimLocked(now time.Time, logMax int, age time.Duration) {
+ n := 0
+ for n < len(st.log) && (len(st.log)-n > logMax || now.Sub(st.log[n].at) > age) {
+ st.floor = st.log[n].seq
+ n++
+ }
+ if n > 0 {
+ st.log = slices.Delete(st.log, 0, n)
+ }
+}
+
+// Reset drops every page of s, empties its clear log and draws a new epoch,
+// so no render begun before it can publish. The pages' store objects are
+// deleted before it returns.
+func (x *Index) Reset(s Scope) {
+ st := x.lookupScope(s)
+ if st == nil {
+ return
+ }
+ st.mu.Lock()
+ old := st.epoch
+ for st.epoch == old {
+ st.epoch = random64()
+ }
+ st.seq, st.floor, st.log = 0, 0, nil
+ gone := make([]assetcache.Key, 0, len(st.records))
+ for _, rec := range st.records {
+ gone = append(gone, rec.phys)
+ }
+ st.records = make(map[Key]record)
+ st.mu.Unlock()
+ x.deleteAll(gone)
+}
+
+// Lookup returns the page indexed for k in s, if the request may have it:
+// the page was rendered from inputs, and every cookie the request carries is
+// on the page's ignore list. A page whose store object is gone (evicted or
+// expired) is dropped from the index and reported MissAbsent.
+func (x *Index) Lookup(s Scope, k Key, inputs string, cookieNames []string) (*assetcache.Entry, Miss) {
+ st := x.lookupScope(s)
+ if st == nil {
+ return nil, MissAbsent
+ }
+ st.mu.Lock()
+ rec, ok := st.records[k]
+ if !ok {
+ st.mu.Unlock()
+ return nil, MissAbsent
+ }
+ if rec.info.Inputs != inputs {
+ st.mu.Unlock()
+ return nil, MissInputs
+ }
+ for _, name := range cookieNames {
+ if !slices.Contains(rec.info.Ignore, name) {
+ st.mu.Unlock()
+ return nil, MissCookies
+ }
+ }
+ st.mu.Unlock()
+
+ // Get may delete an expired object, so it runs without the scope lock.
+ // A clear or reset that removes the record meanwhile also deletes the
+ // object before it returns, so a Lookup that begins after it cannot
+ // reach this point with the record.
+ e, ok := x.cfg.Store.Get(rec.phys)
+ if !ok {
+ st.dropIfCurrent(k, rec.phys)
+ return nil, MissAbsent
+ }
+ return e, MissNone
+}
+
+// dropIfCurrent removes k's record if it still names phys, so a page
+// published meanwhile is not dropped for its predecessor's absence.
+func (st *scopeState) dropIfCurrent(k Key, phys assetcache.Key) bool {
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ if rec, ok := st.records[k]; ok && rec.phys == phys {
+ delete(st.records, k)
+ return true
+ }
+ return false
+}
+
+// Sweep drops the records whose physical object the store no longer has,
+// and returns how many it dropped. It reads the store's keys through Retain,
+// keeping every entry, so it neither deletes anything nor changes any
+// entry's recency.
+func (x *Index) Sweep() int {
+ type held struct {
+ st *scopeState
+ k Key
+ phys assetcache.Key
+ }
+ // The records first: each was indexed after its object was committed,
+ // so an object missing from the store's later listing is truly gone.
+ var all []held
+ for _, st := range x.allScopes() {
+ st.mu.Lock()
+ for k, rec := range st.records {
+ all = append(all, held{st, k, rec.phys})
+ }
+ st.mu.Unlock()
+ }
+ present := make(map[assetcache.Key]bool)
+ x.cfg.Store.Retain(func(k assetcache.Key) bool {
+ if assetcache.IsPageKey(k) {
+ present[k] = true
+ }
+ return true
+ })
+ n := 0
+ for _, h := range all {
+ if !present[h.phys] && h.st.dropIfCurrent(h.k, h.phys) {
+ n++
+ }
+ }
+ return n
+}
+
+// allScopes returns every scope state the index holds.
+func (x *Index) allScopes() []*scopeState {
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ out := make([]*scopeState, 0, len(x.scopes))
+ for _, st := range x.scopes {
+ out = append(out, st)
+ }
+ return out
+}
+
+// Scopes lists every scope the index holds state for: those touched in this
+// process and those with an opt-in mark. They are sorted.
+func (x *Index) Scopes() []Scope {
+ x.mu.Lock()
+ out := make([]Scope, 0, len(x.scopes))
+ for s := range x.scopes {
+ out = append(out, s)
+ }
+ x.mu.Unlock()
+ sort.Slice(out, func(i, j int) bool {
+ a, b := out[i], out[j]
+ if a.Account != b.Account {
+ return a.Account < b.Account
+ }
+ if a.App != b.App {
+ return a.App < b.App
+ }
+ return a.Instance < b.Instance
+ })
+ return out
+}
+
+// deleteAll deletes store objects. It is called without any scope lock.
+func (x *Index) deleteAll(keys []assetcache.Key) {
+ for _, k := range keys {
+ x.cfg.Store.Delete(k)
+ }
+}
+
+// matches reports whether c removes k.
+func (c Clear) matches(k Key) bool {
+ if c.Hosts != nil && !slices.Contains(c.Hosts, k.Host) {
+ return false
+ }
+ if c.Targets == nil {
+ return true
+ }
+ for _, t := range c.Targets {
+ switch t.Kind {
+ case TargetPath:
+ if t.Path == k.Path {
+ return true
+ }
+ case TargetURL:
+ if t.Path == k.Path && t.RawQuery == k.RawQuery {
+ return true
+ }
+ default: // TargetHost, and any kind not known here, errs towards clearing
+ return true
+ }
+ }
+ return false
+}
+
+// cloneClear copies c's slices, keeping nil as nil, so a caller reusing
+// them cannot change the log.
+func cloneClear(c Clear) Clear {
+ if c.Hosts != nil {
+ c.Hosts = append(make([]string, 0, len(c.Hosts)), c.Hosts...)
+ }
+ if c.Targets != nil {
+ c.Targets = append(make([]Target, 0, len(c.Targets)), c.Targets...)
+ }
+ return c
+}
diff --git a/internal/pageindex/index_test.go b/internal/pageindex/index_test.go
new file mode 100644
index 000000000..d7b1737fd
--- /dev/null
+++ b/internal/pageindex/index_test.go
@@ -0,0 +1,512 @@
+package pageindex
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "io"
+ "math/rand"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+)
+
+// roomyFS reports a large, empty filesystem, so only the budget limits fills.
+type roomyFS struct{}
+
+func (roomyFS) Space(string) (uint64, uint64, error) { return 64 << 30, 64 << 30, nil }
+
+var testNow = time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
+
+var shop = Scope{Account: "acct-1", App: "shop", Instance: "shop-1"}
+
+const testHost = "shop.example.com"
+
+func pageKey(path, rawQuery string) Key {
+ return Key{Host: testHost, Path: path, RawQuery: rawQuery}
+}
+
+// rig is a page index over a store in a temporary directory.
+type rig struct {
+ t *testing.T
+ dir string
+ markDir string
+ store *assetcache.Store
+ x *Index
+}
+
+func newRig(t *testing.T, budget int64, mod func(*Config)) *rig {
+ t.Helper()
+ r := &rig{t: t, dir: t.TempDir(), markDir: t.TempDir()}
+ s, err := assetcache.Open(assetcache.Config{Dir: r.dir, Budget: budget, FS: roomyFS{}, Now: func() time.Time { return testNow }})
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.store = s
+ r.x = r.open(mod)
+ return r
+}
+
+// open opens a new index over the rig's store and mark directory.
+func (r *rig) open(mod func(*Config)) *Index {
+ r.t.Helper()
+ cfg := Config{Store: r.store, MarkDir: r.markDir, Now: func() time.Time { return testNow }}
+ if mod != nil {
+ mod(&cfg)
+ }
+ x, err := Open(cfg)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ return x
+}
+
+func pageMeta() assetcache.Meta {
+ return assetcache.Meta{
+ Header: http.Header{"Content-Type": {"text/html"}},
+ Lifetime: time.Hour,
+ Expires: testNow.Add(time.Hour),
+ }
+}
+
+// reserveWrite reserves k for ticket tk and writes body into it.
+func reserveWrite(t *testing.T, x *Index, tk Ticket, k Key, body string) *Pending {
+ t.Helper()
+ p, err := x.Reserve(tk, k, int64(len(body)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.Write([]byte(body)); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+// finish runs Finish and fails the test on an error.
+func finish(t *testing.T, p *Pending, ignore []string) bool {
+ t.Helper()
+ ok, err := p.Finish(pageMeta(), ignore)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ok
+}
+
+// publish renders body for k from start to finish and requires it be indexed.
+func publish(t *testing.T, x *Index, s Scope, k Key, inputs, body string, ignore []string) {
+ t.Helper()
+ p := reserveWrite(t, x, x.Begin(s, inputs), k, body)
+ if !finish(t, p, ignore) {
+ t.Fatalf("Finish for %+v = false, want true", k)
+ }
+}
+
+func readEntry(t *testing.T, e *assetcache.Entry) string {
+ t.Helper()
+ rd, err := e.Open(false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rd.Close()
+ b, err := io.ReadAll(rd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+// lookupBody is Lookup that reads the body of a hit.
+func lookupBody(t *testing.T, x *Index, s Scope, k Key, inputs string, cookies []string) (string, Miss) {
+ t.Helper()
+ e, miss := x.Lookup(s, k, inputs, cookies)
+ if miss != MissNone {
+ if e != nil {
+ t.Fatalf("Lookup(%+v) = entry with miss %v", k, miss)
+ }
+ return "", miss
+ }
+ if e == nil {
+ t.Fatalf("Lookup(%+v) = no entry and no miss", k)
+ }
+ return readEntry(t, e), miss
+}
+
+func wantHit(t *testing.T, x *Index, k Key, inputs, body string) {
+ t.Helper()
+ got, miss := lookupBody(t, x, shop, k, inputs, nil)
+ if miss != MissNone || got != body {
+ t.Fatalf("Lookup(%+v) = %q, %v; want %q, a hit", k, got, miss, body)
+ }
+}
+
+func wantMiss(t *testing.T, x *Index, k Key, inputs string, want Miss) {
+ t.Helper()
+ got, miss := lookupBody(t, x, shop, k, inputs, nil)
+ if miss != want {
+ t.Fatalf("Lookup(%+v) = %q, %v; want miss %v", k, got, miss, want)
+ }
+}
+
+// pageKeys lists the page keys the store holds, without touching recency.
+func pageKeys(s *assetcache.Store) []assetcache.Key {
+ var out []assetcache.Key
+ s.Retain(func(k assetcache.Key) bool {
+ if assetcache.IsPageKey(k) {
+ out = append(out, k)
+ }
+ return true
+ })
+ return out
+}
+
+// recordCount is the number of records the index holds over every scope.
+func recordCount(x *Index) int {
+ n := 0
+ for _, s := range x.Scopes() {
+ st := x.lookupScope(s)
+ st.mu.Lock()
+ n += len(st.records)
+ st.mu.Unlock()
+ }
+ return n
+}
+
+func TestPublishThenLookup(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/", "")
+ publish(t, r.x, shop, k, "b1", "<p>home</p>", nil)
+ wantHit(t, r.x, k, "b1", "<p>home</p>")
+}
+
+func TestLookupNeedsInputs(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/", "")
+ publish(t, r.x, shop, k, "b1", "home", nil)
+ wantMiss(t, r.x, k, "b2", MissInputs)
+ wantHit(t, r.x, k, "b1", "home")
+}
+
+func TestClearRemovesMatching(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ a, ax, b := pageKey("/a", ""), pageKey("/a", "x=1"), pageKey("/b", "")
+ publishAll := func() {
+ publish(t, r.x, shop, a, "b1", "a", nil)
+ publish(t, r.x, shop, ax, "b1", "ax", nil)
+ publish(t, r.x, shop, b, "b1", "b", nil)
+ }
+
+ publishAll()
+ r.x.Clear(shop, Clear{Targets: []Target{{Kind: TargetPath, Path: "/a"}}})
+ wantMiss(t, r.x, a, "b1", MissAbsent)
+ wantMiss(t, r.x, ax, "b1", MissAbsent)
+ wantHit(t, r.x, b, "b1", "b")
+ if n := len(pageKeys(r.store)); n != 1 {
+ t.Fatalf("store holds %d page objects after the path clear, want 1", n)
+ }
+
+ publishAll()
+ r.x.Clear(shop, Clear{Targets: []Target{{Kind: TargetURL, Path: "/a", RawQuery: "x=1"}}})
+ wantHit(t, r.x, a, "b1", "a")
+ wantMiss(t, r.x, ax, "b1", MissAbsent)
+ wantHit(t, r.x, b, "b1", "b")
+
+ // A clear on another host leaves this one alone; one with no targets on
+ // this host takes everything on it.
+ r.x.Clear(shop, Clear{Hosts: []string{"other.example.com"}})
+ wantHit(t, r.x, a, "b1", "a")
+ r.x.Clear(shop, Clear{Hosts: []string{testHost}})
+ wantMiss(t, r.x, a, "b1", MissAbsent)
+ wantMiss(t, r.x, b, "b1", MissAbsent)
+ if n := len(pageKeys(r.store)); n != 0 {
+ t.Fatalf("store holds %d page objects after the host clear, want 0", n)
+ }
+}
+
+func TestClearBetweenBeginAndFinishFences(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ p := reserveWrite(t, r.x, r.x.Begin(shop, "b1"), k, "stale")
+ r.x.Clear(shop, Clear{Targets: []Target{{Kind: TargetPath, Path: "/a"}}})
+ if finish(t, p, nil) {
+ t.Fatal("Finish after a matching clear = true, want false")
+ }
+ wantMiss(t, r.x, k, "b1", MissAbsent)
+ if keys := pageKeys(r.store); len(keys) != 0 {
+ t.Fatalf("store holds page objects %v after a refused Finish, want none", keys)
+ }
+}
+
+func TestUnrelatedClearDoesNotFence(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ p := reserveWrite(t, r.x, r.x.Begin(shop, "b1"), k, "fresh")
+ r.x.Clear(shop, Clear{Targets: []Target{{Kind: TargetPath, Path: "/other"}}})
+ if !finish(t, p, nil) {
+ t.Fatal("Finish after an unrelated clear = false, want true")
+ }
+ wantHit(t, r.x, k, "b1", "fresh")
+}
+
+func TestLogGapRefuses(t *testing.T) {
+ r := newRig(t, 64<<20, func(c *Config) { c.LogMax = 2 })
+ k := pageKey("/a", "")
+ p := reserveWrite(t, r.x, r.x.Begin(shop, "b1"), k, "unknown")
+ for range 3 {
+ r.x.Clear(shop, Clear{Targets: []Target{{Kind: TargetPath, Path: "/other"}}})
+ }
+ if finish(t, p, nil) {
+ t.Fatal("Finish across a gap in the clear log = true, want false")
+ }
+ wantMiss(t, r.x, k, "b1", MissAbsent)
+ if keys := pageKeys(r.store); len(keys) != 0 {
+ t.Fatalf("store holds page objects %v after a refused Finish, want none", keys)
+ }
+}
+
+// TestStaleCommitCannotReplaceFreshPage is P1-1: a render fenced by a clear
+// commits after a fresh render has published. Its bytes must never be served
+// and its refusal must not delete the fresh page.
+func TestStaleCommitCannotReplaceFreshPage(t *testing.T) {
+ var armed atomic.Bool
+ entered, release := make(chan struct{}), make(chan struct{})
+ r := newRig(t, 64<<20, func(c *Config) {
+ c.afterCommit = func() {
+ if armed.CompareAndSwap(true, false) {
+ close(entered)
+ <-release
+ }
+ }
+ })
+ k := pageKey("/a", "")
+
+ pa := reserveWrite(t, r.x, r.x.Begin(shop, "b1"), k, "A")
+ r.x.Clear(shop, Clear{Targets: []Target{{Kind: TargetURL, Path: "/a"}}})
+ publish(t, r.x, shop, k, "b1", "B", nil)
+ eb, miss := r.x.Lookup(shop, k, "b1", nil)
+ if miss != MissNone {
+ t.Fatalf("Lookup after B = %v, want a hit", miss)
+ }
+ physB := eb.Meta.Key
+
+ armed.Store(true)
+ type result struct {
+ ok bool
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ ok, err := pa.Finish(pageMeta(), nil)
+ done <- result{ok, err}
+ }()
+ <-entered
+ wantHit(t, r.x, k, "b1", "B")
+ close(release)
+ res := <-done
+ if res.err != nil || res.ok {
+ t.Fatalf("A's Finish = %v, %v; want false, nil", res.ok, res.err)
+ }
+ wantHit(t, r.x, k, "b1", "B")
+ if _, ok := r.store.Get(physB); !ok {
+ t.Fatal("B's physical object is gone after A's refusal")
+ }
+ if keys := pageKeys(r.store); len(keys) != 1 || keys[0] != physB {
+ t.Fatalf("store page objects = %v, want only B's %v", keys, physB)
+ }
+}
+
+func TestRepublishDeletesPreviousObject(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ publish(t, r.x, shop, k, "b1", "one", nil)
+ publish(t, r.x, shop, k, "b1", "two", nil)
+ wantHit(t, r.x, k, "b1", "two")
+ if keys := pageKeys(r.store); len(keys) != 1 {
+ t.Fatalf("store holds page objects %v after two publishes, want exactly one", keys)
+ }
+}
+
+func TestResetDropsAndChangesEpoch(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ publish(t, r.x, shop, k, "b1", "old", nil)
+ before := r.x.Begin(shop, "b1")
+ p := reserveWrite(t, r.x, before, k, "in flight")
+
+ r.x.Reset(shop)
+ wantMiss(t, r.x, k, "b1", MissAbsent)
+ if after := r.x.Begin(shop, "b1"); after.Epoch == before.Epoch {
+ t.Fatalf("epoch after Reset = %x, unchanged", after.Epoch)
+ }
+ if finish(t, p, nil) {
+ t.Fatal("Finish of a ticket from before Reset = true, want false")
+ }
+ wantMiss(t, r.x, k, "b1", MissAbsent)
+ if keys := pageKeys(r.store); len(keys) != 0 {
+ t.Fatalf("store holds page objects %v after Reset, want none", keys)
+ }
+}
+
+func TestIgnoreCookies(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ publish(t, r.x, shop, k, "b1", "page", []string{"consent"})
+ if got, miss := lookupBody(t, r.x, shop, k, "b1", []string{"consent"}); miss != MissNone || got != "page" {
+ t.Fatalf("Lookup with an ignored cookie = %q, %v; want a hit", got, miss)
+ }
+ if _, miss := lookupBody(t, r.x, shop, k, "b1", []string{"consent", "sid"}); miss != MissCookies {
+ t.Fatalf("Lookup with an unlisted cookie = %v, want MissCookies", miss)
+ }
+}
+
+func TestEvictedObjectIsMissAbsent(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ publish(t, r.x, shop, k, "b1", "page", nil)
+ e, miss := r.x.Lookup(shop, k, "b1", nil)
+ if miss != MissNone {
+ t.Fatalf("Lookup = %v, want a hit", miss)
+ }
+ if !r.store.Delete(e.Meta.Key) {
+ t.Fatal("Store.Delete found no object for the hit")
+ }
+ wantMiss(t, r.x, k, "b1", MissAbsent)
+ if n := recordCount(r.x); n != 0 {
+ t.Fatalf("index holds %d records after the miss, want 0", n)
+ }
+}
+
+func TestOpenDropsEarlierPages(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/a", "")
+ publish(t, r.x, shop, k, "b1", "page", nil)
+
+ // An asset entry beside the page, which the new index must leave alone.
+ asset := assetcache.Key{Account: shop.Account, App: shop.App, Gen: "build-1", Host: testHost, Path: "/app.css"}
+ f, err := r.store.Reserve(asset, 4)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.Write([]byte("a{} ")); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.Commit(pageMeta(), false); err != nil {
+ t.Fatal(err)
+ }
+
+ x2 := r.open(nil)
+ wantMiss(t, x2, k, "b1", MissAbsent)
+ if keys := pageKeys(r.store); len(keys) != 0 {
+ t.Fatalf("store holds page objects %v after Open, want none", keys)
+ }
+ if _, ok := r.store.Get(asset); !ok {
+ t.Fatal("Open dropped an asset entry")
+ }
+}
+
+// TestSweepBoundsRecords is R2-8: records whose objects the store evicted
+// are dropped by Sweep, with no Reset.
+func TestSweepBoundsRecords(t *testing.T) {
+ const bodySize = 8 << 10
+ // One fill's reservation (identity, gzip copy and meta), plus room for
+ // about ten committed entries.
+ budget := int64(2*bodySize+64<<10) + 10*(bodySize+1<<10)
+ r := newRig(t, budget, nil)
+ rnd := rand.New(rand.NewSource(1))
+ body := make([]byte, bodySize)
+ // Each publish fsyncs several times; -short keeps the run quick and still
+ // publishes several times what the store can hold.
+ pages := 500
+ if testing.Short() {
+ pages = 60
+ }
+ for i := range pages {
+ rnd.Read(body) // incompressible, so no gzip copy
+ k := pageKey("/list", "page="+strconv.Itoa(i))
+ publish(t, r.x, shop, k, "b1", string(body), nil)
+ }
+ stored := len(pageKeys(r.store))
+ if stored == 0 || stored > 20 {
+ t.Fatalf("store holds %d page objects, want about 10", stored)
+ }
+ if n := recordCount(r.x); n <= stored {
+ t.Fatalf("index holds %d records before Sweep, want more than the %d stored (the test does not bite)", n, stored)
+ }
+ dropped := r.x.Sweep()
+ if n := recordCount(r.x); n > len(pageKeys(r.store)) {
+ t.Fatalf("index holds %d records after Sweep, more than the %d page objects stored", n, len(pageKeys(r.store)))
+ }
+ if dropped < pages-stored {
+ t.Fatalf("Sweep = %d, want at least %d", dropped, pages-stored)
+ }
+}
+
+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")
+ }
+ if err := r.x.MarkOptIn(shop); err != nil {
+ t.Fatal(err)
+ }
+ if !r.x.OptedIn(shop) {
+ t.Fatal("OptedIn after MarkOptIn = 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 {
+ t.Fatalf("mark file: %v", err)
+ }
+
+ x2 := r.open(nil)
+ if !x2.OptedIn(shop) {
+ t.Fatal("OptedIn after re-Open = false, want true")
+ }
+ if x2.OptedIn(other) {
+ t.Fatal("another instance is opted in after re-Open")
+ }
+ if err := x2.ClearOptIn(shop); err != nil {
+ t.Fatal(err)
+ }
+ if x2.OptedIn(shop) {
+ t.Fatal("OptedIn after ClearOptIn = true")
+ }
+ if x3 := r.open(nil); x3.OptedIn(shop) {
+ t.Fatal("OptedIn after ClearOptIn and re-Open = true, want false")
+ }
+}
+
+func TestTooLargeAborts(t *testing.T) {
+ r := newRig(t, 64<<20, nil)
+ k := pageKey("/big", "")
+ tk := r.x.Begin(shop, "b1")
+ if _, err := r.x.Reserve(tk, k, MaxBody+1); err == nil {
+ t.Fatal("Reserve with a length past MaxBody succeeded")
+ }
+ p, err := r.x.Reserve(tk, k, -1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.Write(make([]byte, MaxBody)); err != nil {
+ t.Fatalf("writing MaxBody: %v", err)
+ }
+ if _, err := p.Write([]byte{0}); err == nil {
+ t.Fatal("writing past MaxBody succeeded")
+ }
+ p.Abort()
+ ents, err := os.ReadDir(r.dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(ents) != 0 {
+ t.Fatalf("store directory holds %d files after Abort, want none", len(ents))
+ }
+ if st := r.store.Stats(); st.Reserved != 0 || st.Entries != 0 {
+ t.Fatalf("store stats after Abort = %+v, want nothing reserved or held", st)
+ }
+ wantMiss(t, r.x, k, "b1", MissAbsent)
+}
diff --git a/internal/pageindex/optin.go b/internal/pageindex/optin.go
new file mode 100644
index 000000000..1f02357a2
--- /dev/null
+++ b/internal/pageindex/optin.go
@@ -0,0 +1,155 @@
+package pageindex
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+)
+
+// An opt-in mark records, durably, that an instance has published a page.
+// From then on its responses never go through the asset LRU, across
+// restarts, until the mark is cleared. Each mark is one file in MarkDir,
+// named by markName and holding the scope as JSON.
+
+// markName is the file name of s's mark: the hex sha256 of its fields
+// joined by NUL bytes.
+func markName(s Scope) string {
+ sum := sha256.Sum256([]byte(s.Account + "\x00" + s.App + "\x00" + s.Instance))
+ 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)
+ if st.marked.Load() {
+ return nil
+ }
+ st.markMu.Lock()
+ defer st.markMu.Unlock()
+ if st.marked.Load() {
+ return nil
+ }
+ raw, err := json.Marshal(s)
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ dir := x.cfg.MarkDir
+ name := filepath.Join(dir, markName(s))
+ tmp := fmt.Sprintf("%s.tmp-%016x", name, random64())
+ if err := writeSynced(tmp, raw); err != nil {
+ os.Remove(tmp)
+ return err
+ }
+ if err := os.Rename(tmp, name); err != nil {
+ os.Remove(tmp)
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ if err := syncDir(dir); err != nil {
+ return err
+ }
+ st.marked.Store(true)
+ return nil
+}
+
+// ClearOptIn removes s's mark and fsyncs the directory. OptedIn reports
+// false once the file is gone, even if the directory sync then fails.
+func (x *Index) ClearOptIn(s Scope) error {
+ st := x.scope(s)
+ st.markMu.Lock()
+ defer st.markMu.Unlock()
+ 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)
+ }
+ st.marked.Store(false)
+ return syncDir(dir)
+}
+
+// OptedIn reports whether s holds a durable mark.
+func (x *Index) OptedIn(s Scope) bool {
+ st := x.lookupScope(s)
+ return st != nil && st.marked.Load()
+}
+
+// loadMarks creates MarkDir if needed, removes the temporaries a crash can
+// leave in it, and marks every scope whose mark file it finds. A file that
+// is not a mark it can read is left alone.
+func (x *Index) loadMarks() error {
+ dir := x.cfg.MarkDir
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ ents, err := os.ReadDir(dir)
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ for _, de := range ents {
+ name := de.Name()
+ if !de.Type().IsRegular() {
+ continue
+ }
+ if strings.Contains(name, ".tmp-") {
+ if err := os.Remove(filepath.Join(dir, name)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ continue
+ }
+ raw, err := os.ReadFile(filepath.Join(dir, name))
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ var s Scope
+ if json.Unmarshal(raw, &s) != nil || markName(s) != name {
+ continue
+ }
+ x.scope(s).marked.Store(true)
+ }
+ return nil
+}
+
+// writeSynced writes data to a new file at path and fsyncs it.
+func writeSynced(path string, data []byte) error {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ _, err = f.Write(data)
+ if err == nil {
+ err = f.Sync()
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ return nil
+}
+
+// syncDir fsyncs dir, so the renames and removals in it are durable.
+// Windows cannot sync a directory handle; the edge does not run there.
+func syncDir(dir string) error {
+ if runtime.GOOS == "windows" {
+ return nil
+ }
+ d, err := os.Open(dir)
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ err = d.Sync()
+ if cerr := d.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return fmt.Errorf("pageindex: %w", err)
+ }
+ return nil
+}
diff --git a/internal/pageindex/pending.go b/internal/pageindex/pending.go
new file mode 100644
index 000000000..9d19c42d0
--- /dev/null
+++ b/internal/pageindex/pending.go
@@ -0,0 +1,139 @@
+package pageindex
+
+import (
+ "fmt"
+ "os"
+ "slices"
+ "sync"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+)
+
+// Pending is one attempt to publish a page: a store fill under a physical
+// key no other attempt shares. Write the body into it, then Finish or Abort.
+type Pending struct {
+ x *Index
+ t Ticket
+ key Key
+ phys assetcache.Key
+ fill *assetcache.Fill
+
+ mu sync.Mutex
+ done bool // finished or aborted
+}
+
+// Reserve starts an attempt to publish k for the render that took t.
+// contentLength is the length the app announced; negative means unknown,
+// and the reservation is then MaxBody. A length past MaxBody is refused with
+// assetcache.ErrTooLarge, as is any write that takes the body past it.
+func (x *Index) Reserve(t Ticket, k Key, contentLength int64) (*Pending, error) {
+ if contentLength > MaxBody {
+ return nil, assetcache.ErrTooLarge
+ }
+ n := contentLength
+ if n < 0 {
+ n = MaxBody
+ }
+ phys := assetcache.Key{
+ Account: t.Scope.Account,
+ App: t.Scope.App,
+ Gen: fmt.Sprintf("%s%s:%016x:%016x", assetcache.PageGenPrefix, t.Scope.Instance, t.Epoch, random64()),
+ Host: k.Host,
+ Path: k.Path,
+ RawQuery: k.RawQuery,
+ }
+ f, err := x.cfg.Store.Reserve(phys, n)
+ if err != nil {
+ return nil, err
+ }
+ return &Pending{x: x, t: t, key: k, phys: phys, fill: f}, nil
+}
+
+// Write appends to the page body.
+func (p *Pending) Write(b []byte) (int, error) {
+ return p.fill.Write(b)
+}
+
+// Abort gives up the attempt and removes what it wrote. It does nothing
+// after Finish, and is safe to call twice.
+func (p *Pending) Abort() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.done {
+ return
+ }
+ p.done = true
+ p.fill.Abort()
+}
+
+// Finish commits the body and, if no clear or reset since the ticket could
+// have matched the page, indexes it, replacing the page the key had. It
+// sets m.Key itself; the caller supplies Header, Lifetime and Expires.
+// ignore lists the cookie names a request may carry and still be served.
+//
+// The commit happens first, without the scope lock. Under the lock the page
+// is indexed only if the ticket's epoch is the scope's, its sequence is no
+// later than the scope's, the clear log covers every sequence after it, and
+// no clear among those matches the key. Otherwise Finish deletes its own
+// object, and only that, and returns false. Finish after Finish or Abort
+// returns os.ErrClosed.
+func (p *Pending) Finish(m assetcache.Meta, ignore []string) (published bool, err error) {
+ p.mu.Lock()
+ if p.done {
+ p.mu.Unlock()
+ return false, os.ErrClosed
+ }
+ p.done = true
+ p.mu.Unlock()
+
+ x := p.x
+ m.Key = p.phys
+ if err := p.fill.Commit(m, true); err != nil {
+ // Commit undoes itself on most failures, but one after its meta
+ // rename leaves the object stored. The key is this attempt's own.
+ x.cfg.Store.Delete(p.phys)
+ return false, err
+ }
+ if x.cfg.afterCommit != nil {
+ x.cfg.afterCommit()
+ }
+
+ st := x.scope(p.t.Scope)
+ st.mu.Lock()
+ admit := st.admitsLocked(p.t, p.key)
+ var prev record
+ var hadPrev bool
+ if admit {
+ prev, hadPrev = st.records[p.key]
+ st.records[p.key] = record{
+ phys: p.phys,
+ info: Info{ValidAt: st.seq, Ignore: slices.Clone(ignore), Inputs: p.t.Inputs},
+ }
+ }
+ st.mu.Unlock()
+
+ if !admit {
+ x.cfg.Store.Delete(p.phys)
+ return false, nil
+ }
+ if hadPrev && prev.phys != p.phys {
+ x.cfg.Store.Delete(prev.phys)
+ }
+ return true, nil
+}
+
+// admitsLocked reports whether a page for k rendered under t may be indexed
+// now: t is on the current epoch, no later than the current sequence, the
+// log still holds every clear after t, and none of those matches k. The
+// caller holds st.mu.
+func (st *scopeState) admitsLocked(t Ticket, k Key) bool {
+ if t.Epoch != st.epoch || t.Seq > st.seq || t.Seq < st.floor {
+ return false
+ }
+ for _, e := range st.log {
+ if e.seq > t.Seq && e.c.matches(k) {
+ return false
+ }
+ }
+ return true
+}