Skip to content

Make the rule-result cache and template fan-out compose #296

Description

@nc9

#295 made the per-page rule-result cache and template fan-out (#279) mutually exclusive: a run with a cache does not build a fan-out at all. This is the design that would let both run.

Why they do not compose today

A fanned verdict belongs to the page's CLUSTER, so no per-page key can capture what it depends on.

Cache two pages of one cluster, then change the FIRST one — the cluster's representative. It is fresh and records its new verdict; the second page replays the verdict it inherited from the representative's PREVIOUS run, and every fully-replayed audit after that repeats the stale value. A fresh audit gives it the new one. Nothing about the second page changed, so nothing about its key can notice.

Two narrower fixes were tried and rejected. Letting a replayed page abstain from the fan-out changes which page is elected representative. Letting it record instead, keyed on its stored page_features.template_fp, closes that direction and leaves this one.

The shape of a fix

Cache the CLUSTER's verdict, not just the page's, against the identity of the page that produced it:

  • a cluster entry keyed on (cluster key, run context, representative's page key)
  • on a warm run, a cluster whose representative's page key is unchanged replays its verdicts into the fan-out without any page running them
  • a representative whose key moved is fresh by definition, so it runs, records, and members take the new verdict — which is exactly what a fresh audit does

The hard part is that "the representative" is the first page of the cluster in crawl order, a whole-crawl property the streamed loop resolves as it goes, while the cache decides what to replay per batch. Cluster keys ARE available before parsing on a warm run (they are in the cached page_features), so the election can be resolved ahead of the loop.

What it is worth

Measured at 2,500 pages on the synthetic estate: enabling the cache costs the cold rules phase 6.9% (116 s to 124 s), which is fan-out's share plus the cache's writes. Cold wall time was unchanged. So this is worth roughly the fan-out half of that on first audits only; re-audits already replay everything and gain nothing from fan-out.

Related: #275 (the chrome-only cluster key can pair pages that differ in a declared rule's inputs). Turning fan-out off is currently the more accurate of the two answers, because every rule really runs on every page.

Acceptance Criteria

  • A run with a rule cache can also fan out template-scoped rules
  • A fully-replayed audit produces a byte-identical report to a fresh audit of the same content, including when the changed page is the one whose verdict others inherited
  • The cold rules phase with the cache on is no slower than with fan-out on and the cache off
  • The regression is covered by a test that fails when the composition is removed

Part of #637.

Activity

  1. added
    enhancement
    P3
    size: L
    on Sep 23, 2026
  2. added theissue type on Oct 28, 2026
  3. added
    engine
    on Nov 13, 2026
  4. nc9 commented on Nov 15, 2026

    @nc9
    ContributorAuthor

    AC3 measurement: cold rules phase, cache on vs fan-out on + cache off

    Result: FAIL on the agreed bar. Median CPU, cache cold (B) 15.31 s vs cache off (A) 14.51 s: +5.5%, bar is +3% (B limit 14.95 s). Wall +7.1%. AC3 not met on this measurement.

    • Commit: public main d41e1fb9da398ac5761ae63a9c0c5a9164e283b3 (contains 4279bfd / feat: batch 1113b: third-party docs, ci report address and MCP docs, seed verification, rule cache and fan-out #1805)
    • Corpus: wollongongservicecompany-com-au project.db, crawl 0b526b6d, 189 pages, all with stored HTML; 2 template clusters, 187 pages inherit a verdict (4,301 rule runs removed by fan-out in BOTH arms). Largest real local crawl that still has its HTML (larger ones such as gymshark 4,000 pages had theirs evicted from the content store).
    • Method: template-fanout-bench.ts --child, streamed page-rule pass only, one child process per run, fan-out ON in both arms. Interleaved ABAB, 9 runs per arm after one untimed warm-up. Scratch copy of the project.db and a scratch content store holding only this crawl's HTML. Every run under sandbox-exec with outbound network denied (curl verified failing under it), serialized through heavy.sh. Load average 2.4 to 3.5 throughout (8-core box).
    • Arm A: BENCH_RULE_CACHE unset (cache off). Arm B: BENCH_RULE_CACHE=cold: the CLI's own project.db store (createProjectRuleCacheStore + bindRuleCache, run-context hash computed inside the timer), with page_rule_cache wiped before EVERY run, so every B run is a full miss: 189 fresh, 0 replayed, 189 rows written each time.

    Local toggle (uncommitted, measurement only)

    diff --git i/apps/cli/scripts/template-fanout-bench.ts w/apps/cli/scripts/template-fanout-bench.ts
    index b11a5c5c9..84e90d106 100644
    --- i/apps/cli/scripts/template-fanout-bench.ts
    +++ w/apps/cli/scripts/template-fanout-bench.ts
    @@ -61,6 +61,9 @@ import { tmpdir } from "node:os";
     import { join } from "node:path";
     
     import { getGlobalContentStore } from "@/crawler/storage/content-store";
    +import { bindRuleCache, computeRunContextHash, type StreamRuleCache } from "@squirrelscan/audit-engine";
    +import { createProjectRuleCacheStore } from "@/audit/rule-cache-store";
    +import { RULES_VERSION } from "@/audit/rules-version";
     
     function run<A>(eff: Effect.Effect<A, unknown, never>): Promise<A> {
       return Effect.runPromise(eff as Effect.Effect<A, never, never>);
    @@ -158,14 +161,39 @@ if (flag("child")) {
       // The parent hands the child the disposable COPY as --db, so the child never
       // opens the corpus it was pointed at.
       const { storage, crawlId, siteData } = await openCrawl(DB);
    +  // LOCAL BENCH TOGGLE (pub#296 AC3, uncommitted): BENCH_RULE_CACHE=cold runs the
    +  // pass with the CLI's project.db-backed rule cache, wiped before the timer.
    +  const benchCache = process.env.BENCH_RULE_CACHE === "cold";
    +  const db = (storage as unknown as { db: import("bun:sqlite").Database }).db;
    +  db.run("DELETE FROM page_rule_cache");
    +  const runner = createRunner(CONFIG);
       const started = performance.now();
       const cpuStart = process.cpuUsage();
    +  let ruleCache: StreamRuleCache | undefined;
    +  let store: ReturnType<typeof createProjectRuleCacheStore> | undefined;
    +  if (benchCache) {
    +    store = createProjectRuleCacheStore(storage, crawlId);
    +    const ctx = await computeRunContextHash({
    +      engineVersion: "bench",
    +      rulesVersion: RULES_VERSION,
    +      pageRules: runner.pageRuleSignature(),
    +      siteData,
    +      ignoreApplicability: false,
    +      utcYear: new Date().getUTCFullYear(),
    +      utcMonth: new Date().getUTCMonth(),
    +      timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    +    });
    +    if (!("hash" in ctx)) throw new Error(`cache disabled: ${ctx.disabled}`);
    +    ruleCache = bindRuleCache(store, ctx.hash);
    +  }
       const result = await run(
    -    streamPageRules(storage, crawlId, createRunner(CONFIG), siteData, {
    +    streamPageRules(storage, crawlId, runner, siteData, {
           batchSize: BATCH,
           templateFanout: fanout,
    +      ...(ruleCache ? { ruleCache } : {}),
         })
       );
    +  const cacheRows = (db.query("SELECT count(*) AS n FROM page_rule_cache").get() as { n: number }).n;
       // Wall time on a box running other work is mostly a measurement of the other
       // work: five repeats of the SAME arm swung 66 to 101 s here while the load
       // average moved between 3.7 and 8. CPU time for the same work does not, so both
    @@ -182,6 +210,9 @@ if (flag("child")) {
           clusters: result.templateFanout.clusters,
           fannedPages: result.templateFanout.fannedPages,
           fannedRuleRuns: result.templateFanout.fannedRuleRuns,
    +      cache: benchCache,
    +      cacheStats: result.ruleCache,
    +      cacheRows,
         })}`
       );
       process.exit(0);

    Per run

    arm run load 1/5/15 CPU s wall s cache rows written
    A 1 2.40 2.74 2.72 15.66 13.93 0
    B 1 3.42 2.96 2.80 15.66 13.85 189
    A 2 3.18 2.93 2.79 15.86 13.87 0
    B 2 2.98 2.90 2.79 15.72 13.87 189
    A 3 3.45 3.00 2.82 14.51 12.60 0
    B 3 3.07 2.94 2.80 14.83 13.21 189
    A 4 2.76 2.87 2.78 13.94 11.88 0
    B 4 2.72 2.86 2.78 14.26 12.50 189
    A 5 2.96 2.90 2.79 14.09 12.12 0
    B 5 3.21 2.95 2.81 13.98 12.37 189
    A 6 2.87 2.89 2.79 14.39 12.12 0
    B 6 2.67 2.84 2.78 14.46 12.66 189
    A 7 2.57 2.82 2.77 14.31 12.27 0
    B 7 2.71 2.84 2.78 15.72 14.29 189
    A 8 3.23 2.94 2.81 15.44 13.38 0
    B 8 3.04 2.91 2.80 16.69 15.27 189
    A 9 2.95 2.90 2.80 16.01 14.08 0
    B 9 2.86 2.89 2.80 15.31 13.50 189
    arm n CPU median CPU min CPU max wall median wall min wall max
    A 9 14.51 13.94 16.01 12.60 11.88 14.08
    B 9 15.31 13.98 16.69 13.50 12.37 15.27

    Reading

    • Agreed metric (median CPU): B/A = 1.055, over the 1.03 bar. FAIL.
    • Noise is large relative to the effect on a 13 s pass: same-arm CPU spans 13.9 to 16.0 s (A) and 14.0 to 16.7 s (B). Paired per-pair deltas (B vs the A run just before it): -4.4, -0.9, -0.8, 0.0, +0.5, +2.2, +2.2, +8.1, +9.9% (median +0.5%); minimum vs minimum +0.3%. So the true cost of the cold cache (key hashing, entry encode + gzip, one INSERT batch) is likely small, but this run does not show it under 3% on the agreed statistic, and the two worst B samples (pairs 7 and 8) are the whole gap.
    • Caveat: 189 pages / 2 clusters is small; no larger real crawl with HTML is on this box. A rerun on a 1,000+ page real crawl with more repeats would settle it.
  5. nc9 commented on Nov 15, 2026

    @nc9
    ContributorAuthor

    AC3 stays open. The rerun with a permanent bench arm, a 1,000+ page corpus of our own sites and a paired-difference bar is tracked in #1971.

  6. nc9 commented on Nov 20, 2026

    @nc9
    ContributorAuthor

    AC1, AC2 and AC4 are met on main by 4279bfd. I've ticked them. AC3 stays open until #1971 runs.

    • Evidence: bun test packages/audit-engine/tests/rule-cache-replay-golden.test.ts, re-run today on main at f25906f: 13 pass, 0 fail.
    • AC1: "a run with a cache fans out template-scoped rules". It works through the cluster-aware fanReplayable in packages/audit-engine/src/streaming.ts.
    • AC2: "a fully-replayed audit matches a fresh one across a template cluster" and "changing a cluster's representative re-runs members that inherited its verdict".
    • AC4, checked by mutation: I replaced fanReplayable with return true, so it no longer looks at clusters. Two tests then failed: "changing a cluster's representative re-runs members that inherited its verdict" and "an entry written without fan-out does not replay into a fan-out run". With the change reverted, all 13 pass.
    • AC3: the cold rules phase with the cache on is not yet shown to be no slower than fan-out with the cache off. The 11-15 numbers in this thread: median CPU +5.5% against a +3% bar, paired median +0.5%, noisy on a 189-page corpus. The rerun with a permanent bench arm and a 1,000+ page corpus is tracked in Bench: permanent rule-cache arm and a 1,000+ page rerun to settle #296 AC3 #1971. This stays open until that reports.

    nik

  7. added
    blocked
    on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3blockedengineenhancementsize: L

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions