pageindex: randomized invariants and the page-key guard
TestSimulationInvariants (P2-11) drives the index from 8 goroutines over three scopes with overlapping hosts and checks every hit against the clears and resets that returned before the lookup began (I1), the scope, key and inputs asked for (I3). TestStoreHoldsNoUnindexedPages checks the store holds only indexed page objects, and none after a Reset of every scope. TestOnlyPageindexBuildsPageKeys fails if code outside internal/pageindex and internal/assetcache mentions the page key prefix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/pageindex/guard_test.go+140 −0internal/pageindex/sim_test.go+557 −0
Intent
<task-notification> <task-id>a94e17e558f578c5f</task-id> <tool-use-id>toolu_016rkebBfWt8niSTEzbcWoDM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/a94e17e558f578c5f.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: pageindex core" 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. I fixed the review finding: `Pending.Abort` now retries cleanup after an earlier Abort or a failed Finish, and does nothing while a Finish is running. **Commits:** - `a44017d5` pageindex: one index owns every page publish, clear, reset and lookup - `005460f7` pageindex: Abort retries fill cleanup after Abort or a failed Finish **Tests:** the new `TestAbortRetriesCleanup` failed in both cases before the fix ("after Abort" and "after a failed Finish"; a temporary file was left behind). After the fix, the full suite passes with `go test ./internal/pageindex -count=1 -race` (33.2 s). The new test checks the store directory is empty and `Stats().Reserved` is 0 after the retry. **Concerns:** one gap. No test covers the rule that an Abort during a running Finish does nothing, because the only test hook runs after the commit, where Abort already has nothing to do. Removing that rule would not fail any test, and I did not add a hook for it. The earlier concerns still stand. **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-2-report.md (fix report appended)</result> <usage><subagent_tokens>145044</subagent_tokens><tool_uses>5</tool_uses><duration_ms>109063</duration_ms></usage> </task-notification>
<task-notification> <task-id>b6m8rc7ck</task-id> <tool-use-id>toolu_01SoVpJiqxGkcEeHGgG5rXn4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/b6m8rc7ck.output</output-file> <status>completed</status> <summary>Background command "Run scoped Astra re-review of Task 2 fix" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 23.8 g CO₂e (3,134,347 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/guard_test.go b/internal/pageindex/guard_test.go| new file mode 100644 |
| index 000000000..306d5679d |
| --- /dev/null |
| +++ b/internal/pageindex/guard_test.go |
| @@ -0,0 +1,140 @@ |
| +package pageindex |
| + |
| +import ( |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "slices" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// pageKeyOwners are the only directories whose code may build page keys. |
| +var pageKeyOwners = []string{"internal/pageindex", "internal/assetcache"} |
| + |
| +// pageKeyMarks are what code that builds page keys has to mention: the |
| +// prefix constant, or the prefix as a string literal. |
| +var pageKeyMarks = []string{"PageGenPrefix", `"page:`, "`page:"} |
| + |
| +// pageKeyMentions walks root's .go files and returns, sorted and relative |
| +// to root with forward slashes, those outside pageKeyOwners that mention a |
| +// pageKeyMark. It skips test files and the vendor, node_modules, testdata |
| +// and dot directories. |
| +func pageKeyMentions(root string) ([]string, error) { |
| + var out []string |
| + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + name := d.Name() |
| + if d.IsDir() { |
| + if path != root && (strings.HasPrefix(name, ".") || name == "vendor" || name == "node_modules" || name == "testdata") { |
| + return filepath.SkipDir |
| + } |
| + return nil |
| + } |
| + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { |
| + return nil |
| + } |
| + rel, err := filepath.Rel(root, path) |
| + if err != nil { |
| + return err |
| + } |
| + rel = filepath.ToSlash(rel) |
| + for _, owner := range pageKeyOwners { |
| + if strings.HasPrefix(rel, owner+"/") { |
| + return nil |
| + } |
| + } |
| + src, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + for _, mark := range pageKeyMarks { |
| + if strings.Contains(string(src), mark) { |
| + out = append(out, rel) |
| + break |
| + } |
| + } |
| + return nil |
| + }) |
| + slices.Sort(out) |
| + return out, err |
| +} |
| + |
| +// moduleRoot is the nearest directory above this file holding a go.mod. |
| +func moduleRoot(t *testing.T) string { |
| + t.Helper() |
| + _, file, _, ok := runtime.Caller(0) |
| + if !ok { |
| + t.Fatal("runtime.Caller found no file") |
| + } |
| + for dir := filepath.Dir(file); ; { |
| + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { |
| + return dir |
| + } |
| + up := filepath.Dir(dir) |
| + if up == dir { |
| + t.Fatalf("no go.mod above %s", file) |
| + } |
| + dir = up |
| + } |
| +} |
| + |
| +// TestOnlyPageindexBuildsPageKeys: no code outside internal/pageindex and |
| +// internal/assetcache mentions the page key prefix, so nothing else can |
| +// publish, find or delete a page behind the index's back. |
| +func TestOnlyPageindexBuildsPageKeys(t *testing.T) { |
| + root := moduleRoot(t) |
| + got, err := pageKeyMentions(root) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rel := range got { |
| + t.Errorf("%s mentions the page key prefix; only %v may build page keys", rel, pageKeyOwners) |
| + } |
| +} |
| + |
| +// TestPageKeyGuardFixtures: the guard's scan finds a mention outside the |
| +// owners, by the constant or by a literal, and leaves alone the owners, test |
| +// files, vendored code and a directory whose name only begins like an owner's. |
| +func TestPageKeyGuardFixtures(t *testing.T) { |
| + root := t.TempDir() |
| + files := map[string]string{ |
| + "go.mod": "module example.com/m\n", |
| + "internal/edge/literal.go": "package edge\n\nvar k = \"page:web-1:1:2\"\n", |
| + "internal/edge/raw.go": "package edge\n\nvar k = `page:web-1`\n", |
| + "internal/edge/constant.go": "package edge\n\nvar p = assetcache.PageGenPrefix\n", |
| + "internal/edge/clean.go": "package edge\n\nvar s = \"pages\"\n", |
| + "internal/edge/literal_test.go": "package edge\n\nvar k = \"page:web-1:1:2\"\n", |
| + "internal/pageindex/owner.go": "package pageindex\n\nvar p = assetcache.PageGenPrefix\n", |
| + "internal/assetcache/owner.go": "package assetcache\n\nconst PageGenPrefix = \"page:\"\n", |
| + "internal/pageindexer/lookalike.go": "package pageindexer\n\nvar k = \"page:x\"\n", |
| + "vendor/example.com/v/vendored.go": "package v\n\nvar k = \"page:x\"\n", |
| + "internal/edge/testdata/fixture.go": "package fixture\n\nvar k = \"page:x\"\n", |
| + ".claude/worktrees/other/x/other.go": "package x\n\nvar k = \"page:x\"\n", |
| + } |
| + for rel, src := range files { |
| + path := filepath.Join(root, filepath.FromSlash(rel)) |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + got, err := pageKeyMentions(root) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{ |
| + "internal/edge/constant.go", |
| + "internal/edge/literal.go", |
| + "internal/edge/raw.go", |
| + "internal/pageindexer/lookalike.go", |
| + } |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("pageKeyMentions = %v, want %v", got, want) |
| + } |
| +} |
diff --git a/internal/pageindex/sim_test.go b/internal/pageindex/sim_test.go| new file mode 100644 |
| index 000000000..ef0a4836d |
| --- /dev/null |
| +++ b/internal/pageindex/sim_test.go |
| @@ -0,0 +1,557 @@ |
| +package pageindex |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "math/rand" |
| + "net/http" |
| + "os" |
| + "runtime" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/assetcache" |
| +) |
| + |
| +var simSeed = flag.Int64("seed", 0, "seed for the page index simulation; 0 means the time") |
| + |
| +// simScope is one scope of the simulation and the two hosts it publishes on. |
| +type simScope struct { |
| + s Scope |
| + hosts [2]string |
| +} |
| + |
| +// The scopes differ in instance (0 and 1) and in account and app (0 and 2), |
| +// and their host names overlap, so a page is only ever told apart from |
| +// another scope's by its scope. |
| +var simScopes = [3]simScope{ |
| + {Scope{Account: "acct-1", App: "shop", Instance: "web-1"}, [2]string{"a.example.com", "b.example.com"}}, |
| + {Scope{Account: "acct-1", App: "shop", Instance: "web-2"}, [2]string{"b.example.com", "c.example.com"}}, |
| + {Scope{Account: "acct-2", App: "blog", Instance: "web-1"}, [2]string{"c.example.com", "a.example.com"}}, |
| +} |
| + |
| +var ( |
| + simHosts = []string{"a.example.com", "b.example.com", "c.example.com"} |
| + simPaths = []string{"/", "/a", "/a/b", "/b", "/c", "/docs"} |
| + simQueries = []string{"", "x=1"} |
| + simInputs = []string{"in-1", "in-2"} |
| +) |
| + |
| +// simHeader carries a copy of the body's identity in the page's metadata, |
| +// so a hit can be checked even when its body is deleted before it is read. |
| +const simHeader = "X-Sim-Page" |
| + |
| +// simBody is what every simulated page body encodes: the attempt that |
| +// rendered it and the ticket it rendered under. No two attempts share one. |
| +type simBody struct { |
| + Scope int |
| + Host, Path, Query string |
| + Inputs string |
| + Ignore bool // the page ignores the "consent" cookie |
| + Worker, Op int |
| + Epoch, Seq uint64 |
| +} |
| + |
| +// modelEntry is one Clear or Reset that has returned. |
| +type modelEntry struct { |
| + scope int |
| + epoch uint64 // the epoch the clear ran on, or the epoch the reset ended |
| + reset bool |
| + seq uint64 |
| + c Clear |
| +} |
| + |
| +// simModel is the log of returned clears and resets, in return order. |
| +type simModel struct { |
| + mu sync.Mutex |
| + log []modelEntry |
| +} |
| + |
| +func (m *simModel) add(e modelEntry) { |
| + m.mu.Lock() |
| + m.log = append(m.log, e) |
| + m.mu.Unlock() |
| +} |
| + |
| +// snapshot returns the entries logged so far. The log is append-only and |
| +// entries are never changed, so the slice may be read without the lock. |
| +func (m *simModel) snapshot() []modelEntry { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return m.log[:len(m.log):len(m.log)] |
| +} |
| + |
| +// modelMatches is the clear rule written out again, independently of |
| +// Clear.matches: nil hosts is every host, nil targets is every page. |
| +func modelMatches(c Clear, host, path, query string) bool { |
| + if c.Hosts != nil { |
| + on := false |
| + for _, h := range c.Hosts { |
| + on = on || h == host |
| + } |
| + if !on { |
| + return false |
| + } |
| + } |
| + if c.Targets == nil { |
| + return true |
| + } |
| + for _, t := range c.Targets { |
| + switch t.Kind { |
| + case TargetHost: |
| + return true |
| + case TargetPath: |
| + if t.Path == path { |
| + return true |
| + } |
| + case TargetURL: |
| + if t.Path == path && t.RawQuery == query { |
| + return true |
| + } |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// simStats counts what a simulation did, so a run can show it bit. |
| +type simStats struct { |
| + publishes, published, refused, busy, aborted atomic.Int64 |
| + lookups, hits, readGone atomic.Int64 |
| + missAbsent, missInputs, missCookies atomic.Int64 |
| + clears, ambiguous, resets, optins atomic.Int64 |
| +} |
| + |
| +func (s *simStats) String() string { |
| + return fmt.Sprintf("publishes %d (indexed %d, refused %d, busy %d, aborted %d); lookups %d (hits %d, body gone before read %d; misses absent %d, inputs %d, cookies %d); clears %d (epoch unknown %d); resets %d; opt-in changes %d", |
| + s.publishes.Load(), s.published.Load(), s.refused.Load(), s.busy.Load(), s.aborted.Load(), |
| + s.lookups.Load(), s.hits.Load(), s.readGone.Load(), s.missAbsent.Load(), s.missInputs.Load(), s.missCookies.Load(), |
| + s.clears.Load(), s.ambiguous.Load(), s.resets.Load(), s.optins.Load()) |
| +} |
| + |
| +// sim is one simulation run over a rig. |
| +type sim struct { |
| + t *testing.T |
| + r *rig |
| + model simModel |
| + stats simStats |
| + |
| + pauseMu sync.Mutex |
| + pauseRnd *rand.Rand // drives afterCommit's pauses |
| + |
| + optMu [len(simScopes)]sync.Mutex // one opt-in change and its check at a time per scope |
| +} |
| + |
| +// simulationSeed is -seed, or the time. A failing test prints it. |
| +func simulationSeed(t *testing.T) int64 { |
| + seed := *simSeed |
| + if seed == 0 { |
| + seed = time.Now().UnixNano() |
| + } |
| + t.Cleanup(func() { |
| + if t.Failed() { |
| + t.Logf("simulation seed %d (rerun with -seed %d)", seed, seed) |
| + } |
| + }) |
| + return seed |
| +} |
| + |
| +// runSim runs ops random operations over 8 goroutines against a fresh index |
| +// and returns once every goroutine is done. |
| +func runSim(t *testing.T, ops int, seed int64) *sim { |
| + t.Helper() |
| + sm := &sim{t: t, pauseRnd: rand.New(rand.NewSource(seed))} |
| + sm.r = newRig(t, 1<<30, func(c *Config) { |
| + c.LogMax = 16 // small, so tickets also fall behind the log's floor |
| + c.afterCommit = sm.pause |
| + }) |
| + const workers = 8 |
| + var wg sync.WaitGroup |
| + for w := range workers { |
| + n := ops / workers |
| + if w < ops%workers { |
| + n++ |
| + } |
| + rnd := rand.New(rand.NewSource(seed + int64(w) + 1)) |
| + wg.Go(func() { sm.worker(w, n, rnd) }) |
| + } |
| + wg.Wait() |
| + t.Logf("simulation: %v", &sm.stats) |
| + bites := sm.stats.hits.Load() > 0 && sm.stats.published.Load() > 0 && sm.stats.clears.Load() > 0 |
| + if !t.Failed() && !bites { |
| + t.Errorf("the simulation published %d, cleared %d and hit %d times; it does not bite", sm.stats.published.Load(), sm.stats.clears.Load(), sm.stats.hits.Load()) |
| + } |
| + return sm |
| +} |
| + |
| +// pause is afterCommit: nothing, a yield, or a sleep of up to 2 ms. |
| +func (sm *sim) pause() { |
| + sm.pauseMu.Lock() |
| + n := sm.pauseRnd.Intn(4) |
| + d := time.Duration(sm.pauseRnd.Int63n(int64(2*time.Millisecond) + 1)) |
| + sm.pauseMu.Unlock() |
| + switch n { |
| + case 0: |
| + case 1: |
| + runtime.Gosched() |
| + default: |
| + time.Sleep(d) |
| + } |
| +} |
| + |
| +// simPage is a page a worker published, which its later lookups favour. |
| +type simPage struct { |
| + si int |
| + k Key |
| + inputs string |
| +} |
| + |
| +func (sm *sim) worker(w, n int, rnd *rand.Rand) { |
| + var recent []simPage // the worker's last few published pages |
| + for op := range n { |
| + if sm.t.Failed() { |
| + return |
| + } |
| + si := rnd.Intn(len(simScopes)) |
| + switch p := rnd.Intn(100); { |
| + case p < 45: |
| + if pg, ok := sm.publish(w, op, si, rnd); ok { |
| + recent = append(recent, pg) |
| + if len(recent) > 8 { |
| + recent = recent[1:] |
| + } |
| + } |
| + case p < 90: |
| + // Half the lookups ask for a page this worker published, so |
| + // hits are common; the rest ask for anything. |
| + if len(recent) > 0 && rnd.Intn(2) == 0 { |
| + pg := pick(rnd, recent) |
| + sm.lookup(pg.si, pg.k, pg.inputs, rnd) |
| + break |
| + } |
| + // Mostly the scope's own hosts, where its pages are; sometimes |
| + // any host, where another scope's pages are. |
| + host := simScopes[si].hosts[rnd.Intn(2)] |
| + if rnd.Intn(4) == 0 { |
| + host = pick(rnd, simHosts) |
| + } |
| + k := Key{Host: host, Path: pick(rnd, simPaths), RawQuery: pick(rnd, simQueries)} |
| + sm.lookup(si, k, pick(rnd, simInputs), rnd) |
| + case p < 97: |
| + sm.clear(si, rnd) |
| + case p < 98: |
| + sm.reset(si) |
| + default: |
| + sm.optIn(si, rnd) |
| + } |
| + } |
| +} |
| + |
| +func pick[T any](rnd *rand.Rand, xs []T) T { return xs[rnd.Intn(len(xs))] } |
| + |
| +// publish is Begin, Reserve, Write and Finish for a page on one of the |
| +// scope's own hosts, and reports the page if it was indexed. Sometimes the |
| +// render gives up with Abort instead. |
| +func (sm *sim) publish(w, op, si int, rnd *rand.Rand) (pg simPage, indexed bool) { |
| + t, x := sm.t, sm.r.x |
| + ss := simScopes[si] |
| + sm.stats.publishes.Add(1) |
| + inputs := pick(rnd, simInputs) |
| + tk := x.Begin(ss.s, inputs) |
| + b := simBody{ |
| + Scope: si, Host: ss.hosts[rnd.Intn(2)], Path: pick(rnd, simPaths), Query: pick(rnd, simQueries), |
| + Inputs: inputs, Ignore: rnd.Intn(2) == 0, Worker: w, Op: op, Epoch: tk.Epoch, Seq: tk.Seq, |
| + } |
| + raw, err := json.Marshal(b) |
| + if err != nil { |
| + t.Errorf("encode %+v: %v", b, err) |
| + return |
| + } |
| + k := Key{Host: b.Host, Path: b.Path, RawQuery: b.Query} |
| + if rnd.Intn(2) == 0 { |
| + runtime.Gosched() |
| + } |
| + length := int64(len(raw)) |
| + if rnd.Intn(4) == 0 { |
| + length = -1 |
| + } |
| + p, err := x.Reserve(tk, k, length) |
| + if errors.Is(err, assetcache.ErrBusy) { |
| + sm.stats.busy.Add(1) |
| + return |
| + } |
| + if err != nil { |
| + t.Errorf("Reserve(%+v): %v", k, err) |
| + return |
| + } |
| + cut := rnd.Intn(len(raw) + 1) |
| + for _, part := range [][]byte{raw[:cut], raw[cut:]} { |
| + if _, err := p.Write(part); err != nil { |
| + t.Errorf("Write(%+v): %v", k, err) |
| + p.Abort() |
| + return |
| + } |
| + } |
| + if rnd.Intn(20) == 0 { |
| + p.Abort() |
| + sm.stats.aborted.Add(1) |
| + return |
| + } |
| + var ignore []string |
| + if b.Ignore { |
| + ignore = []string{"consent"} |
| + } |
| + m := assetcache.Meta{ |
| + Header: http.Header{"Content-Type": {"text/html"}, simHeader: {string(raw)}}, |
| + Lifetime: time.Hour, |
| + Expires: testNow.Add(time.Hour), |
| + } |
| + ok, err := p.Finish(m, ignore) |
| + switch { |
| + case err != nil: |
| + t.Errorf("Finish(%+v): %v", k, err) |
| + case ok: |
| + sm.stats.published.Add(1) |
| + return simPage{si: si, k: k, inputs: inputs}, true |
| + default: |
| + sm.stats.refused.Add(1) |
| + } |
| + return simPage{}, false |
| +} |
| + |
| +// lookup asks scope si for k from inputs, and checks a hit against the |
| +// clears and resets that returned before it began. |
| +func (sm *sim) lookup(si int, k Key, inputs string, rnd *rand.Rand) { |
| + t, x := sm.t, sm.r.x |
| + ss := simScopes[si] |
| + snap := sm.model.snapshot() |
| + var cookies []string |
| + if rnd.Intn(3) == 0 { |
| + cookies = []string{"consent"} |
| + } |
| + sm.stats.lookups.Add(1) |
| + e, miss := x.Lookup(ss.s, k, inputs, cookies) |
| + if miss != MissNone { |
| + if e != nil { |
| + t.Errorf("Lookup(%d, %+v) = an entry with miss %v", si, k, miss) |
| + } |
| + switch miss { |
| + case MissAbsent: |
| + sm.stats.missAbsent.Add(1) |
| + case MissInputs: |
| + sm.stats.missInputs.Add(1) |
| + case MissCookies: |
| + sm.stats.missCookies.Add(1) |
| + } |
| + return |
| + } |
| + if e == nil { |
| + t.Errorf("Lookup(%d, %+v) = no entry and no miss", si, k) |
| + return |
| + } |
| + sm.stats.hits.Add(1) |
| + |
| + raw := e.Meta.Header.Get(simHeader) |
| + var b simBody |
| + if err := json.Unmarshal([]byte(raw), &b); err != nil { |
| + t.Errorf("Lookup(%d, %+v): hit without a readable %s header %q: %v", si, k, simHeader, raw, err) |
| + return |
| + } |
| + // I3: the page is the one asked for, in the scope asked for. |
| + if b.Scope != si || b.Host != k.Host || b.Path != k.Path || b.Query != k.RawQuery { |
| + t.Errorf("I3: Lookup(%d, %+v) served %+v", si, k, b) |
| + } |
| + pk := e.Meta.Key |
| + gen := fmt.Sprintf("%s%s:%016x", assetcache.PageGenPrefix, ss.s.Instance, b.Epoch) |
| + if pk.Account != ss.s.Account || pk.App != ss.s.App || !strings.HasPrefix(pk.Gen, gen) || |
| + pk.Host != k.Host || pk.Path != k.Path || pk.RawQuery != k.RawQuery { |
| + t.Errorf("I3: Lookup(%d, %+v) served the object under key %+v", si, k, pk) |
| + } |
| + // The inputs and cookies are the ones the page may be served for. |
| + if b.Inputs != inputs { |
| + t.Errorf("Lookup(%d, %+v, %q) served a page rendered from %q: %+v", si, k, inputs, b.Inputs, b) |
| + } |
| + if len(cookies) > 0 && !b.Ignore { |
| + t.Errorf("Lookup(%d, %+v) with cookies %v served a page that ignores none: %+v", si, k, cookies, b) |
| + } |
| + // I1: nothing that returned before the lookup began removed this page. |
| + for _, me := range snap { |
| + if me.scope != b.Scope || me.epoch != b.Epoch { |
| + continue |
| + } |
| + if me.reset { |
| + t.Errorf("I1: Lookup(%d, %+v) served %+v from an epoch a returned Reset ended", si, k, b) |
| + break |
| + } |
| + if me.seq > b.Seq && modelMatches(me.c, b.Host, b.Path, b.Query) { |
| + t.Errorf("I1: Lookup(%d, %+v) served %+v (ticket seq %d), which returned clear %d %+v matches", si, k, b, b.Seq, me.seq, me.c) |
| + break |
| + } |
| + } |
| + |
| + // The bytes are the page the header names, if the body is still there. |
| + rd, err := e.Open(false) |
| + if errors.Is(err, os.ErrNotExist) { |
| + sm.stats.readGone.Add(1) |
| + return |
| + } |
| + if err != nil { |
| + t.Errorf("Lookup(%d, %+v): open body: %v", si, k, err) |
| + return |
| + } |
| + defer rd.Close() |
| + body, err := io.ReadAll(rd) |
| + if err != nil { |
| + t.Errorf("Lookup(%d, %+v): read body: %v", si, k, err) |
| + return |
| + } |
| + if string(body) != raw { |
| + t.Errorf("Lookup(%d, %+v): body %q under header %q", si, k, body, raw) |
| + } |
| +} |
| + |
| +// randomClear draws hosts (nil, or one or two of every scope's) and targets |
| +// (nil, or one or two of any kind). Most are narrow, so pages live long |
| +// enough to be hit. |
| +func randomClear(rnd *rand.Rand) Clear { |
| + var c Clear |
| + if rnd.Intn(4) != 0 { |
| + for range 1 + rnd.Intn(2) { |
| + c.Hosts = append(c.Hosts, pick(rnd, simHosts)) |
| + } |
| + } |
| + if rnd.Intn(10) != 0 { |
| + for range 1 + rnd.Intn(2) { |
| + kind := TargetPath |
| + switch n := rnd.Intn(20); { |
| + case n < 2: |
| + kind = TargetHost |
| + case n < 11: |
| + kind = TargetURL |
| + } |
| + c.Targets = append(c.Targets, Target{ |
| + Kind: kind, |
| + Path: pick(rnd, simPaths), |
| + RawQuery: pick(rnd, simQueries), |
| + }) |
| + } |
| + } |
| + return c |
| +} |
| + |
| +// clear runs a random Clear and logs it when it returns. Its epoch is read |
| +// with a Begin on each side; when a Reset ran in between, the epoch it ran |
| +// on is unknown and it is not logged, which only weakens the check. |
| +func (sm *sim) clear(si int, rnd *rand.Rand) { |
| + t, x := sm.t, sm.r.x |
| + s := simScopes[si].s |
| + c := randomClear(rnd) |
| + sm.stats.clears.Add(1) |
| + before := x.Begin(s, "") |
| + seq := x.Clear(s, c) |
| + after := x.Begin(s, "") |
| + if before.Epoch != after.Epoch { |
| + sm.stats.ambiguous.Add(1) |
| + return |
| + } |
| + if seq <= before.Seq || seq > after.Seq { |
| + t.Errorf("Clear(%d) = seq %d, outside (%d, %d] on one epoch", si, seq, before.Seq, after.Seq) |
| + } |
| + sm.model.add(modelEntry{scope: si, epoch: before.Epoch, seq: seq, c: c}) |
| +} |
| + |
| +// reset runs Reset and logs that the epoch seen before it has ended: by the |
| +// time it returns, this Reset or an earlier one has ended that epoch. |
| +func (sm *sim) reset(si int) { |
| + t, x := sm.t, sm.r.x |
| + s := simScopes[si].s |
| + sm.stats.resets.Add(1) |
| + before := x.Begin(s, "") |
| + x.Reset(s) |
| + if after := x.Begin(s, ""); after.Epoch == before.Epoch { |
| + t.Errorf("Reset(%d) left epoch %x", si, before.Epoch) |
| + } |
| + sm.model.add(modelEntry{scope: si, epoch: before.Epoch, reset: true}) |
| +} |
| + |
| +// optIn marks or clears the scope's opt-in and checks OptedIn agrees. |
| +func (sm *sim) optIn(si int, rnd *rand.Rand) { |
| + t, x := sm.t, sm.r.x |
| + s := simScopes[si].s |
| + sm.stats.optins.Add(1) |
| + 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) |
| + } |
| + return |
| + } |
| + if err := x.ClearOptIn(s); err != nil { |
| + t.Errorf("ClearOptIn(%d): %v", si, err) |
| + } else if x.OptedIn(s) { |
| + t.Errorf("OptedIn(%d) after ClearOptIn = true", si) |
| + } |
| +} |
| + |
| +// simOps is the number of operations a simulation runs. |
| +func simOps() int { |
| + if testing.Short() { |
| + return 300 |
| + } |
| + return 2000 |
| +} |
| + |
| +// TestSimulationInvariants is P2-11: 8 goroutines publish, clear, reset, |
| +// look up and opt in over three scopes at random, and every hit is checked |
| +// against I1 (no returned clear or reset removed it) and I3 (it is the page |
| +// asked for, in the scope asked for, from the inputs asked for). |
| +func TestSimulationInvariants(t *testing.T) { |
| + runSim(t, simOps(), simulationSeed(t)) |
| +} |
| + |
| +// TestStoreHoldsNoUnindexedPages: after a simulation the store holds exactly |
| +// the page objects the index names, and after a Reset of every scope none. |
| +func TestStoreHoldsNoUnindexedPages(t *testing.T) { |
| + sm := runSim(t, simOps(), simulationSeed(t)) |
| + x, store := sm.r.x, sm.r.store |
| + |
| + named := make(map[assetcache.Key]bool) |
| + for _, s := range x.Scopes() { |
| + st := x.lookupScope(s) |
| + st.mu.Lock() |
| + for _, rec := range st.records { |
| + named[rec.phys] = true |
| + } |
| + st.mu.Unlock() |
| + } |
| + held := pageKeys(store) |
| + for _, k := range held { |
| + if !named[k] { |
| + t.Errorf("store holds page object %+v that no record names", k) |
| + } |
| + } |
| + if len(held) != len(named) { |
| + t.Errorf("store holds %d page objects, index names %d", len(held), len(named)) |
| + } |
| + |
| + for _, s := range x.Scopes() { |
| + x.Reset(s) |
| + } |
| + if keys := pageKeys(store); len(keys) != 0 { |
| + t.Fatalf("store holds %d page objects after a Reset of every scope, want none: %v", len(keys), keys) |
| + } |
| + if n := recordCount(x); n != 0 { |
| + t.Fatalf("index holds %d records after a Reset of every scope, want none", n) |
| + } |
| + if st := store.Stats(); st.Reserved != 0 { |
| + t.Fatalf("store has %d bytes reserved after the simulation, want none", st.Reserved) |
| + } |
| +} |