diff --git a/.github/workflows/atlas-search-worker-tests.yml b/.github/workflows/atlas-search-worker-tests.yml index 4fe1cb9c28..6f25e4bb01 100644 --- a/.github/workflows/atlas-search-worker-tests.yml +++ b/.github/workflows/atlas-search-worker-tests.yml @@ -7,6 +7,8 @@ name: atlas-search worker tests # The atlas-search cache Worker's vitest suite — pkgs/atlas-search/ # worker/test/ (key.test.ts: query canonicalisation + the DO cache-key # digest oracle; space.test.ts: validateEmbed embedding-space pins; +# measurement.test.ts: the #13107 D1 hot-cache §7 counters + report +# renderer against the #9134 design §7 oracle; # worker.test.ts: auth gate, DO cache hit, the #6937 whitespace-query # and #6982 null-search-response regressions) — was run by no # workflow, flake check, or justfile recipe, only by hand via npm test. @@ -50,7 +52,7 @@ jobs: - name: Run the atlas-search worker vitest suite working-directory: pkgs/atlas-search/worker run: | - for f in test/key.test.ts test/space.test.ts test/worker.test.ts package.json package-lock.json; do + for f in test/key.test.ts test/space.test.ts test/measurement.test.ts test/worker.test.ts package.json package-lock.json; do if [ ! -f "$f" ]; then echo "::error::pkgs/atlas-search/worker/$f is missing — the worker suite was not run." exit 1 diff --git a/pkgs/atlas-search/worker/README.md b/pkgs/atlas-search/worker/README.md index 423fb85f3c..f4182b885d 100644 --- a/pkgs/atlas-search/worker/README.md +++ b/pkgs/atlas-search/worker/README.md @@ -34,6 +34,12 @@ and caches the result **indefinitely** (no TTL/eviction in v1). revision, vector table, and k. A cached entry is never served across ceilings, disclosure contexts, or embedding spaces; entries keyed under schema v1 are orphaned, never served. +- `src/measurement.ts` — the D1 hot-cache measurement report + (#13107; design #9134 §7): the §7 counters (hits, skips, + revalidations per class and tenant; stale_serves, expected + zero; estimated Turso cost avoided; D1 bytes per tenant vs + quota) rendered as a report for #9098's economics prototype. + Pure accumulator + renderer, fed by the read path (follow-on 4). ## Endpoints @@ -82,8 +88,8 @@ wired into the request path at all: nothing in the Worker calls it outside tests, so the flag alone does not activate the cache — with the flag on and the binding present, the Worker still never touches D1 and the read path is unchanged. Freshness -(#13101), admission/eviction (#13103), and read-path integration -(#13105) are separate follow-ons. The committed `database_id` is a +(#13101), admission/eviction (#13103), measurement (#13107), +and read-path integration (#13105) are separate follow-ons. The committed `database_id` is a local placeholder: the real `atlas-hot-cache` database is created at deploy time and its id replaces the placeholder in both `wrangler.toml` and `cloudflare.config.ts`. diff --git a/pkgs/atlas-search/worker/src/measurement.ts b/pkgs/atlas-search/worker/src/measurement.ts new file mode 100644 index 0000000000..89f67f763f --- /dev/null +++ b/pkgs/atlas-search/worker/src/measurement.ts @@ -0,0 +1,489 @@ +/** + * D1 hot-cache measurement (#13107; design #9134 §7, merged via + * PR #13098). Follow-on 6 of 6 under #9134: the §7 counters surfaced + * as a report the #9098 embed-storage economics prototype consumes. + * + * The design's value is a measured number, not an assertion: hits, + * skips, revalidations per class and tenant; stale_serves (expected + * zero — any non-zero value is a bug report, not a tuning signal, + * §1); estimated Turso cost avoided as skips x the entry's recorded + * fill cost, labelled an estimate with its method; D1 writes and + * storage bytes per tenant vs quota. + * + * This module is the pure measurement core: an in-memory accumulator + * the read path feeds (follow-on 4, #13105, owns the live recording; + * §2's skip log is the feed) plus a pure report renderer over a + * snapshot of the counters. It does no I/O, reads no clock, and + * touches no D1 binding — the durable counters live wherever the + * read path records them, and the report renders from whatever the + * accumulator was told. + * + * Event semantics (the caller drives them; the module only counts): + * + * hit — a cache lookup found an entry for (tenant, key), + * whether fresh or stale. Every skip and every + * revalidation was a hit first, so in a coherent + * sequence hits = skips + revalidations. + * skip — a Turso hop was skipped: the entry was fresh + * under §1 and served from the cache (§2). + * revalidation — a found entry was stale and the read went to + * Turso to revalidate. + * staleServe — a serve that violated the §1 freshness bound. + * A defect, counted separately (§1, §7). + * fill — an entry was (re)filled into D1: one D1 write, + * payloadBytes written, and the fill-time source + * cost recorded against the key for later skips. + * evict — an entry left D1: one eviction, bytes freed, and + * the key's recorded fill cost forgotten (an + * evicted entry cannot be skipped). + * + * The estimated Turso cost avoided is the sum, over skips, of the + * skipped entry's fill-time source cost (latency ms, rows read). + * A skip whose entry has no recorded fill cost — filled before the + * accumulator started, in another isolate, or before a restart — + * contributes 0 and is counted as unknown, never invented. The + * accumulator is per-isolate in-memory state, so the estimate is + * partial by construction; the report says so in its method. + */ + +import type { HotCacheClass } from "./hot_cache"; + +/** Source cost of one query, captured at fill time (§7). */ +export interface FillCost { + /** Source latency in milliseconds for the single query at fill time. */ + latencyMs: number; + /** Rows read from the source for the single query at fill time. */ + rowsRead: number; +} + +/** + * The §7 counters for one (class) or one (tenant) slice. All fields + * are cumulative counts since the accumulator was created, except + * the cost-avoided fields, which are sums over skips. + */ +export interface ClassCounters { + hits: number; + skips: number; + revalidations: number; + staleServes: number; + fills: number; + /** Skips whose entry had no recorded fill cost (contributed 0). */ + skipsWithUnknownFillCost: number; + /** Estimated Turso latency avoided by this slice's skips (ms). */ + costAvoidedLatencyMs: number; + /** Estimated Turso rows-read avoided by this slice's skips. */ + costAvoidedRowsRead: number; + /** Skips that contributed a known fill cost to the estimate. */ + costAvoidedSkips: number; + /** D1 writes (fills) performed for this slice. */ + d1Writes: number; + /** D1 bytes written by this slice's fills. */ + d1BytesWritten: number; + /** D1 bytes freed by this slice's evictions. */ + d1BytesEvicted: number; +} + +function zeroCounters(): ClassCounters { + return { + hits: 0, + skips: 0, + revalidations: 0, + staleServes: 0, + fills: 0, + skipsWithUnknownFillCost: 0, + costAvoidedLatencyMs: 0, + costAvoidedRowsRead: 0, + costAvoidedSkips: 0, + d1Writes: 0, + d1BytesWritten: 0, + d1BytesEvicted: 0, + }; +} + +function addInto(into: ClassCounters, from: ClassCounters): void { + into.hits += from.hits; + into.skips += from.skips; + into.revalidations += from.revalidations; + into.staleServes += from.staleServes; + into.fills += from.fills; + into.skipsWithUnknownFillCost += from.skipsWithUnknownFillCost; + into.costAvoidedLatencyMs += from.costAvoidedLatencyMs; + into.costAvoidedRowsRead += from.costAvoidedRowsRead; + into.costAvoidedSkips += from.costAvoidedSkips; + into.d1Writes += from.d1Writes; + into.d1BytesWritten += from.d1BytesWritten; + into.d1BytesEvicted += from.d1BytesEvicted; +} + +/** Plain-data snapshot of the accumulator, for the #9098 prototype. */ +export interface MeasurementSnapshot { + /** Counters per class, summed over all tenants. */ + byClass: Record; + /** Counters per tenant, summed over all classes. */ + byTenant: Record; + /** The full matrix: counters per (tenant, class). */ + byTenantClass: Record>; + /** D1 storage bytes currently held per tenant (fills minus evictions). */ + storedBytesByTenant: Record; + /** Estimated Turso cost avoided across all skips (see the method). */ + tursoCostAvoided: FillCost & { skips: number }; +} + +interface RecordedEntry { + entryClass: HotCacheClass; + fillCost: FillCost; + payloadBytes: number; +} + +const CLASSES: HotCacheClass[] = ["A", "B", "C"]; + +function clampNonNegative(value: number): number { + return Number.isFinite(value) && value > 0 ? value : 0; +} + +function clampCost(cost: FillCost): FillCost { + return { latencyMs: clampNonNegative(cost.latencyMs), rowsRead: clampNonNegative(cost.rowsRead) }; +} + +/** + * The §7 counters. One instance per Worker isolate: fills recorded + * here are the only fill costs later skips can draw on, so a skip in + * an isolate that never saw the fill contributes 0 (counted as + * unknown, never invented). + */ +export class HotCacheMeasurement { + private readonly byTenantClass = new Map>(); + private readonly entries = new Map(); + + private cell(tenantId: string, entryClass: HotCacheClass): ClassCounters { + let byClass = this.byTenantClass.get(tenantId); + if (!byClass) { + byClass = new Map(); + this.byTenantClass.set(tenantId, byClass); + } + let cell = byClass.get(entryClass); + if (!cell) { + cell = zeroCounters(); + byClass.set(entryClass, cell); + } + return cell; + } + + private static entryKey(tenantId: string, cacheKey: string): string { + return `${tenantId}\n${cacheKey}`; + } + + /** A cache lookup found an entry for (tenant, key). */ + recordHit(tenantId: string, entryClass: HotCacheClass): void { + this.cell(tenantId, entryClass).hits += 1; + } + + /** + * A Turso hop was skipped: the entry was fresh and served from the + * cache (§2). Adds the entry's recorded fill cost to the estimated + * cost avoided; an unrecorded entry contributes 0 and counts as + * unknown. + */ + recordSkip(tenantId: string, entryClass: HotCacheClass, cacheKey: string): void { + const cell = this.cell(tenantId, entryClass); + cell.skips += 1; + const recorded = this.entries.get(HotCacheMeasurement.entryKey(tenantId, cacheKey)); + if (!recorded) { + cell.skipsWithUnknownFillCost += 1; + return; + } + cell.costAvoidedLatencyMs += recorded.fillCost.latencyMs; + cell.costAvoidedRowsRead += recorded.fillCost.rowsRead; + cell.costAvoidedSkips += 1; + } + + /** A found entry was stale and the read revalidated against Turso. */ + recordRevalidation(tenantId: string, entryClass: HotCacheClass): void { + this.cell(tenantId, entryClass).revalidations += 1; + } + + /** + * A serve violated the §1 freshness bound. Expected value zero; + * any non-zero reading is a bug report (§1), flagged by the report. + */ + recordStaleServe(tenantId: string, entryClass: HotCacheClass): void { + this.cell(tenantId, entryClass).staleServes += 1; + } + + /** + * An entry was (re)filled into D1: one D1 write, payloadBytes + * written, and the fill-time source cost recorded against the key. + * A refill replaces the previous record: stored bytes move by the + * size delta and later skips draw on the new fill cost. + */ + recordFill( + tenantId: string, + entryClass: HotCacheClass, + cacheKey: string, + payloadBytes: number, + fillCost: FillCost, + ): void { + const bytes = clampNonNegative(payloadBytes); + const cost = clampCost(fillCost); + const cell = this.cell(tenantId, entryClass); + cell.fills += 1; + cell.d1Writes += 1; + cell.d1BytesWritten += bytes; + this.entries.set(HotCacheMeasurement.entryKey(tenantId, cacheKey), { + entryClass, + fillCost: cost, + payloadBytes: bytes, + }); + } + + /** + * An entry left D1: one eviction, bytes freed, and the key's + * recorded fill cost forgotten. Evicting an unknown key still + * counts the eviction but cannot free bytes the accumulator never + * saw — stored bytes never go negative. + */ + recordEvict(tenantId: string, entryClass: HotCacheClass, cacheKey: string, payloadBytes: number): void { + const bytes = clampNonNegative(payloadBytes); + const cell = this.cell(tenantId, entryClass); + cell.d1BytesEvicted += bytes; + this.entries.delete(HotCacheMeasurement.entryKey(tenantId, cacheKey)); + } + + /** A deep copy of the counters; later records do not rewrite it. */ + snapshot(): MeasurementSnapshot { + const byClass: Record = { + A: zeroCounters(), + B: zeroCounters(), + C: zeroCounters(), + }; + const byTenant: Record = {}; + const byTenantClass: Record> = {}; + const storedBytesByTenant: Record = {}; + let avoidedLatencyMs = 0; + let avoidedRowsRead = 0; + let avoidedSkips = 0; + + for (const [tenantId, classes] of this.byTenantClass) { + const tenantTotals = zeroCounters(); + const tenantCells: Record = { + A: zeroCounters(), + B: zeroCounters(), + C: zeroCounters(), + }; + for (const entryClass of CLASSES) { + const cell = classes.get(entryClass); + if (!cell) continue; + tenantCells[entryClass] = { ...cell }; + addInto(byClass[entryClass], cell); + addInto(tenantTotals, cell); + } + byTenant[tenantId] = tenantTotals; + byTenantClass[tenantId] = tenantCells; + } + + for (const [key, entry] of this.entries) { + const tenantId = key.slice(0, key.indexOf("\n")); + storedBytesByTenant[tenantId] = (storedBytesByTenant[tenantId] ?? 0) + entry.payloadBytes; + } + // Tenants with counters but no live entries still report storage. + for (const tenantId of Object.keys(byTenant)) { + storedBytesByTenant[tenantId] ??= 0; + avoidedLatencyMs += byTenant[tenantId].costAvoidedLatencyMs; + avoidedRowsRead += byTenant[tenantId].costAvoidedRowsRead; + avoidedSkips += byTenant[tenantId].costAvoidedSkips; + } + + return { + byClass, + byTenant, + byTenantClass, + storedBytesByTenant, + tursoCostAvoided: { latencyMs: avoidedLatencyMs, rowsRead: avoidedRowsRead, skips: avoidedSkips }, + }; + } +} + +/** + * The method behind the estimated Turso cost avoided, carried + * verbatim into the report (§7: reported as an estimate with its + * method, never as an exact figure). + */ +export const TURSO_COST_AVOIDED_METHOD = + "sum over Turso-hop skips of the skipped entry's fill-time source cost (latency ms, rows read); " + + "a fill-time cost is not the cost the hop would have paid now, and skips whose entry has no " + + "recorded fill cost contribute 0, so this is an estimate, never an exact figure."; + +export interface MeasurementReportOptions { + /** + * D1 storage quota in bytes per tenant — the §3 quota shares from + * admission (#13103), supplied by the caller so this module stays + * independent of the unmerged admission slice. A tenant with no + * quota reports null and is never over-quota. + */ + quotaBytesByTenant?: Record; + /** + * Active config values at report time (TTL_B, heavy-query + * threshold, tier weights, ...), echoed so the first tuning round + * has its before-values on the record. + */ + config?: Record; +} + +/** One slice of the report: counters plus the tuning ratios. */ +export interface ClassReport extends ClassCounters { + /** skips / hits; 0 when no hits were recorded. */ + skipRatio: number; + /** skips / (skips + revalidations); 0 when neither was recorded. */ + serveRatio: number; +} + +/** One tenant's slice: counters, ratios, and storage vs quota. */ +export interface TenantReport extends ClassReport { + storedBytes: number; + quotaBytes: number | null; + overQuota: boolean; +} + +export interface StorageLine { + tenantId: string; + storedBytes: number; + quotaBytes: number | null; + overQuota: boolean; +} + +/** The §7 report, as plain data for the #9098 prototype. */ +export interface MeasurementReport { + byClass: Record; + byTenant: Record; + totals: ClassReport; + /** stale_serves: expected zero; a non-zero total is a defect (§1). */ + staleServes: { total: number; expectedZero: true; defect: boolean }; + /** Estimated Turso cost avoided, labelled an estimate (§7). */ + tursoCostAvoided: { + kind: "estimate"; + method: string; + latencyMs: number; + rowsRead: number; + skips: number; + skipsWithUnknownFillCost: number; + }; + /** D1 storage bytes per tenant vs quota, sorted by tenant. */ + storage: StorageLine[]; + config?: Record; +} + +function toClassReport(counters: ClassCounters): ClassReport { + return { + ...counters, + skipRatio: counters.hits > 0 ? counters.skips / counters.hits : 0, + serveRatio: + counters.skips + counters.revalidations > 0 + ? counters.skips / (counters.skips + counters.revalidations) + : 0, + }; +} + +/** + * Render the §7 report from a snapshot of live counters. Pure: the + * same snapshot always renders the same report. + */ +export function renderMeasurementReport( + snapshot: MeasurementSnapshot, + options?: MeasurementReportOptions, +): MeasurementReport { + const byClass: Record = { + A: toClassReport(snapshot.byClass.A), + B: toClassReport(snapshot.byClass.B), + C: toClassReport(snapshot.byClass.C), + }; + const totalsCounters = zeroCounters(); + for (const entryClass of CLASSES) addInto(totalsCounters, snapshot.byClass[entryClass]); + const totals = toClassReport(totalsCounters); + + const quotas = options?.quotaBytesByTenant ?? {}; + const byTenant: Record = {}; + const storage: StorageLine[] = []; + for (const tenantId of Object.keys(snapshot.byTenant).sort()) { + const storedBytes = snapshot.storedBytesByTenant[tenantId] ?? 0; + // Indexing the record yields number under this tsconfig, so widen + // explicitly: a missing quota is undefined, not a TS2367 comparison. + const quota: number | undefined = quotas[tenantId]; + const quotaBytes = quota !== undefined && Number.isFinite(quota) && quota >= 0 ? quota : null; + const overQuota = quotaBytes !== null && storedBytes > quotaBytes; + byTenant[tenantId] = { + ...toClassReport(snapshot.byTenant[tenantId]), + storedBytes, + quotaBytes, + overQuota, + }; + storage.push({ tenantId, storedBytes, quotaBytes, overQuota }); + } + + let unknownSkips = 0; + for (const entryClass of CLASSES) unknownSkips += snapshot.byClass[entryClass].skipsWithUnknownFillCost; + + return { + byClass, + byTenant, + totals, + staleServes: { + total: totals.staleServes, + expectedZero: true as const, + defect: totals.staleServes > 0, + }, + tursoCostAvoided: { + kind: "estimate", + method: TURSO_COST_AVOIDED_METHOD, + latencyMs: snapshot.tursoCostAvoided.latencyMs, + rowsRead: snapshot.tursoCostAvoided.rowsRead, + skips: snapshot.tursoCostAvoided.skips, + skipsWithUnknownFillCost: unknownSkips, + }, + storage, + ...(options?.config ? { config: { ...options.config } } : {}), + }; +} + +/** The human-readable rendering of a report, for the issue record. */ +export function formatMeasurementReport(report: MeasurementReport): string { + const lines: string[] = ["D1 hot-cache measurement report (#13107; design #9134 §7)", ""]; + const t = report.totals; + lines.push( + `totals: hits=${t.hits} skips=${t.skips} revalidations=${t.revalidations} ` + + `stale_serves=${t.staleServes} fills=${t.fills} ` + + `skip_ratio=${t.skipRatio.toFixed(3)} serve_ratio=${t.serveRatio.toFixed(3)}`, + ); + for (const entryClass of CLASSES) { + const c = report.byClass[entryClass]; + lines.push( + `class ${entryClass}: hits=${c.hits} skips=${c.skips} revalidations=${c.revalidations} ` + + `stale_serves=${c.staleServes} fills=${c.fills} ` + + `skip_ratio=${c.skipRatio.toFixed(3)} serve_ratio=${c.serveRatio.toFixed(3)}`, + ); + } + lines.push( + report.staleServes.defect + ? `stale_serves: ${report.staleServes.total} (expected 0 — DEFECT: any non-zero value files a defect, §1)` + : `stale_serves: ${report.staleServes.total} (expected 0 — OK)`, + ); + const avoided = report.tursoCostAvoided; + lines.push( + `estimated Turso cost avoided: ${avoided.latencyMs} ms latency, ${avoided.rowsRead} rows read ` + + `over ${avoided.skips} skips (${avoided.skipsWithUnknownFillCost} skips with unknown fill cost contributed 0)`, + ); + lines.push(`estimate method: ${avoided.method}`); + if (report.storage.length > 0) { + lines.push("D1 storage by tenant:"); + for (const line of report.storage) { + const quota = line.quotaBytes === null ? "no quota supplied" : `quota ${line.quotaBytes} bytes`; + lines.push( + ` ${line.tenantId}: ${line.storedBytes} bytes stored, ${quota}` + + (line.overQuota ? " — over quota" : ""), + ); + } + } + if (report.config) { + lines.push(`config at report time: ${JSON.stringify(report.config)}`); + } + return lines.join("\n"); +} diff --git a/pkgs/atlas-search/worker/test/measurement.test.ts b/pkgs/atlas-search/worker/test/measurement.test.ts new file mode 100644 index 0000000000..0104f42b31 --- /dev/null +++ b/pkgs/atlas-search/worker/test/measurement.test.ts @@ -0,0 +1,259 @@ +import { describe, expect, it } from "vitest"; +import { + HotCacheMeasurement, + TURSO_COST_AVOIDED_METHOD, + formatMeasurementReport, + renderMeasurementReport, + type FillCost, +} from "../src/measurement"; + +// Oracle for every test in this file: design #9134 §7 (merged via +// PR #13098). The measurement report surfaces hits, skips, +// revalidations per class and tenant, stale_serves (expected zero), +// estimated Turso cost avoided (skips x recorded fill cost, labelled +// an estimate with its method), and D1 write/storage bytes per tenant +// vs quota — for #9098's embed-storage economics prototype. +// +// The counters are the measurement surface §2's skip log and §7 feed +// into; the read-path integration that records live events is +// follow-on 4 (#13105). This slice is the accumulator + the report +// renderer, driven here through its public record API. + +const COST_A: FillCost = { latencyMs: 300, rowsRead: 12_000 }; +const COST_B: FillCost = { latencyMs: 100, rowsRead: 2_000 }; + +function filled(tenantId = "tenant-1"): HotCacheMeasurement { + const m = new HotCacheMeasurement(); + m.recordFill(tenantId, "B", "key-b", 1_024, COST_A); + m.recordFill(tenantId, "A", "key-a", 512, COST_B); + return m; +} + +describe("counters accumulate per class and per tenant", () => { + it("records hits, skips, revalidations and stale serves in the right cells", () => { + const m = filled(); + m.recordHit("tenant-1", "B"); + m.recordSkip("tenant-1", "B", "key-b"); + m.recordHit("tenant-1", "B"); + m.recordRevalidation("tenant-1", "B"); + m.recordHit("tenant-2", "C"); + m.recordStaleServe("tenant-2", "C"); + + const s = m.snapshot(); + expect(s.byClass.B.hits).toBe(2); + expect(s.byClass.B.skips).toBe(1); + expect(s.byClass.B.revalidations).toBe(1); + expect(s.byClass.C.hits).toBe(1); + expect(s.byClass.C.staleServes).toBe(1); + expect(s.byTenant["tenant-1"].hits).toBe(2); + expect(s.byTenant["tenant-2"].staleServes).toBe(1); + expect(s.byTenantClass["tenant-1"].B.skips).toBe(1); + expect(s.byTenantClass["tenant-2"].C.staleServes).toBe(1); + }); + + it("a coherent read sequence keeps hits = skips + revalidations", () => { + const m = filled(); + // Every found entry is either served (skip) or revalidated: the + // read path records the hit first, then the outcome. + m.recordHit("tenant-1", "B"); + m.recordSkip("tenant-1", "B", "key-b"); + m.recordHit("tenant-1", "B"); + m.recordRevalidation("tenant-1", "B"); + const s = m.snapshot(); + expect(s.byClass.B.hits).toBe(s.byClass.B.skips + s.byClass.B.revalidations); + }); + + it("snapshots are frozen: later records do not rewrite an earlier snapshot", () => { + const m = filled(); + m.recordHit("tenant-1", "B"); + const before = m.snapshot(); + m.recordHit("tenant-1", "B"); + expect(before.byClass.B.hits).toBe(1); + expect(m.snapshot().byClass.B.hits).toBe(2); + }); +}); + +describe("estimated Turso cost avoided (§7)", () => { + it("is skips x the skipped entry's recorded fill cost", () => { + const m = filled(); + m.recordSkip("tenant-1", "B", "key-b"); + m.recordSkip("tenant-1", "B", "key-b"); + m.recordSkip("tenant-1", "A", "key-a"); + const s = m.snapshot(); + expect(s.tursoCostAvoided.skips).toBe(3); + expect(s.tursoCostAvoided.latencyMs).toBe(300 + 300 + 100); + expect(s.tursoCostAvoided.rowsRead).toBe(12_000 + 12_000 + 2_000); + expect(s.byClass.B.costAvoidedLatencyMs).toBe(600); + expect(s.byClass.A.costAvoidedLatencyMs).toBe(100); + }); + + it("a skip with no recorded fill cost contributes 0 and is counted, not invented", () => { + const m = new HotCacheMeasurement(); + m.recordSkip("tenant-1", "B", "never-filled"); + const s = m.snapshot(); + expect(s.tursoCostAvoided.latencyMs).toBe(0); + expect(s.tursoCostAvoided.rowsRead).toBe(0); + expect(s.tursoCostAvoided.skips).toBe(0); + expect(s.byClass.B.skipsWithUnknownFillCost).toBe(1); + expect(s.byClass.B.skips).toBe(1); + }); + + it("a refill replaces the recorded fill cost for later skips", () => { + const m = filled(); + m.recordFill("tenant-1", "B", "key-b", 1_024, { latencyMs: 50, rowsRead: 500 }); + m.recordSkip("tenant-1", "B", "key-b"); + expect(m.snapshot().tursoCostAvoided.latencyMs).toBe(50); + expect(m.snapshot().tursoCostAvoided.rowsRead).toBe(500); + }); + + it("an evicted entry no longer contributes its fill cost to later skips", () => { + const m = filled(); + m.recordEvict("tenant-1", "B", "key-b", 1_024); + m.recordSkip("tenant-1", "B", "key-b"); + const s = m.snapshot(); + expect(s.tursoCostAvoided.latencyMs).toBe(0); + expect(s.byClass.B.skipsWithUnknownFillCost).toBe(1); + }); +}); + +describe("report renders from live counters (§7 acceptance)", () => { + it("renders per-class and per-tenant totals with hit/skip ratios", () => { + const m = filled(); + m.recordHit("tenant-1", "B"); + m.recordSkip("tenant-1", "B", "key-b"); + m.recordHit("tenant-1", "B"); + m.recordRevalidation("tenant-1", "B"); + const r = renderMeasurementReport(m.snapshot()); + + expect(r.totals.hits).toBe(2); + expect(r.totals.skips).toBe(1); + expect(r.totals.revalidations).toBe(1); + expect(r.byClass.B.skipRatio).toBe(0.5); + expect(r.byClass.B.serveRatio).toBe(0.5); + expect(r.byTenant["tenant-1"].hits).toBe(2); + expect(r.byTenant["tenant-1"].skipRatio).toBe(0.5); + }); + + it("empty counters render a valid zero report, never NaN", () => { + const r = renderMeasurementReport(new HotCacheMeasurement().snapshot()); + expect(r.totals.hits).toBe(0); + expect(r.totals.skipRatio).toBe(0); + expect(r.totals.serveRatio).toBe(0); + expect(r.byClass.A.skipRatio).toBe(0); + expect(r.staleServes.total).toBe(0); + expect(r.staleServes.defect).toBe(false); + expect(r.tursoCostAvoided.latencyMs).toBe(0); + expect(r.storage).toEqual([]); + expect(Number.isNaN(r.totals.skipRatio)).toBe(false); + }); + + it("stale_serves is flagged as a defect when non-zero (expected value zero, §1)", () => { + const m = new HotCacheMeasurement(); + m.recordStaleServe("tenant-1", "B"); + const r = renderMeasurementReport(m.snapshot()); + expect(r.staleServes.total).toBe(1); + expect(r.staleServes.expectedZero).toBe(true); + expect(r.staleServes.defect).toBe(true); + expect(r.byClass.B.staleServes).toBe(1); + }); + + it("labels the Turso cost avoided an estimate and states its method", () => { + const m = filled(); + m.recordSkip("tenant-1", "B", "key-b"); + const r = renderMeasurementReport(m.snapshot()); + expect(r.tursoCostAvoided.kind).toBe("estimate"); + expect(r.tursoCostAvoided.method).toBe(TURSO_COST_AVOIDED_METHOD); + expect(r.tursoCostAvoided.latencyMs).toBe(300); + expect(r.tursoCostAvoided.rowsRead).toBe(12_000); + expect(r.tursoCostAvoided.skips).toBe(1); + }); + + it("reports D1 storage bytes per tenant against the supplied quota", () => { + const m = filled(); + const r = renderMeasurementReport(m.snapshot(), { + quotaBytesByTenant: { "tenant-1": 1_000 }, + }); + expect(r.storage).toEqual([ + { tenantId: "tenant-1", storedBytes: 1_536, quotaBytes: 1_000, overQuota: true }, + ]); + const ok = renderMeasurementReport(m.snapshot(), { + quotaBytesByTenant: { "tenant-1": 2_000 }, + }); + expect(ok.storage[0].overQuota).toBe(false); + }); + + it("a tenant with no supplied quota reports a null quota, never over-quota", () => { + const m = filled(); + const r = renderMeasurementReport(m.snapshot()); + expect(r.storage).toEqual([ + { tenantId: "tenant-1", storedBytes: 1_536, quotaBytes: null, overQuota: false }, + ]); + }); + + it("echoes the active config so the tuning round has its before-values", () => { + const m = filled(); + const r = renderMeasurementReport(m.snapshot(), { + config: { ttlBSeconds: 60, heavyQueryLatencyMs: 250, tierWeights: "1:4:16" }, + }); + expect(r.config).toEqual({ ttlBSeconds: 60, heavyQueryLatencyMs: 250, tierWeights: "1:4:16" }); + }); + + it("formats as readable text carrying the numbers, the verdict and the method", () => { + const m = filled(); + m.recordHit("tenant-1", "B"); + m.recordSkip("tenant-1", "B", "key-b"); + m.recordStaleServe("tenant-2", "C"); + const text = formatMeasurementReport( + renderMeasurementReport(m.snapshot(), { quotaBytesByTenant: { "tenant-1": 1_000 } }), + ); + expect(text).toContain("D1 hot-cache measurement report"); + expect(text).toContain("stale_serves: 1 (expected 0 — DEFECT"); + expect(text).toContain("estimate"); + expect(text).toContain(TURSO_COST_AVOIDED_METHOD); + expect(text).toContain("tenant-1"); + expect(text).toContain("over quota"); + }); + + it("formats a clean zero report without a defect verdict", () => { + const text = formatMeasurementReport(renderMeasurementReport(new HotCacheMeasurement().snapshot())); + expect(text).toContain("stale_serves: 0 (expected 0 — OK)"); + expect(text).not.toContain("DEFECT"); + }); +}); + +describe("D1 write and storage accounting (§7 fill cost)", () => { + it("recordFill counts D1 writes and bytes; recordEvict counts evictions and frees storage", () => { + const m = filled(); + m.recordEvict("tenant-1", "B", "key-b", 1_024); + const s = m.snapshot(); + expect(s.byClass.B.fills).toBe(1); + expect(s.byClass.B.d1Writes).toBe(1); + expect(s.byClass.B.d1BytesWritten).toBe(1_024); + expect(s.byClass.B.d1BytesEvicted).toBe(1_024); + expect(s.storedBytesByTenant["tenant-1"]).toBe(512); + }); + + it("a refill adjusts stored bytes by the size delta, not by double counting", () => { + const m = filled(); + m.recordFill("tenant-1", "B", "key-b", 2_048, COST_A); + expect(m.snapshot().storedBytesByTenant["tenant-1"]).toBe(2_048 + 512); + expect(m.snapshot().byClass.B.d1BytesWritten).toBe(1_024 + 2_048); + }); + + it("evicting an unknown key never drives stored bytes negative", () => { + const m = new HotCacheMeasurement(); + m.recordEvict("tenant-1", "B", "ghost", 1_024); + expect(m.snapshot().storedBytesByTenant["tenant-1"]).toBe(0); + }); + + it("negative sizes and costs clamp to zero instead of corrupting the totals", () => { + const m = new HotCacheMeasurement(); + m.recordFill("tenant-1", "B", "key-b", -5, { latencyMs: -10, rowsRead: -1 }); + const s = m.snapshot(); + expect(s.storedBytesByTenant["tenant-1"]).toBe(0); + expect(s.byClass.B.d1BytesWritten).toBe(0); + m.recordSkip("tenant-1", "B", "key-b"); + expect(m.snapshot().tursoCostAvoided.latencyMs).toBe(0); + expect(m.snapshot().tursoCostAvoided.skips).toBe(1); + }); +});