diff --git a/.github/workflows/atlas-search-worker-tests.yml b/.github/workflows/atlas-search-worker-tests.yml index f641b3445b..dec77ac332 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; +# admission.test.ts: the #13103 D1 hot-cache admission policy rules +# against the #9134 design §3/§5 oracles; # 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. @@ -49,7 +51,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/admission.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 445b7b4e9d..094015a140 100644 --- a/pkgs/atlas-search/worker/README.md +++ b/pkgs/atlas-search/worker/README.md @@ -25,6 +25,11 @@ and caches the result **indefinitely** (no TTL/eviction in v1). the pinned config fingerprint (ceiling, model revision, vector table, k). A cached entry is never served across ceilings or embedding spaces. +- `src/admission.ts` — the D1 hot-cache admission policy (#13103, + #9134 design §3/§5): heat counters, heavy-query immediate + admission, per-tenant quotas (tier weights 1:4:16, 5% floor), + entry size cap, negative-result TTL, and the LRU eviction sweep. + Pure policy, not yet wired into the read path (follow-on 4). ## Endpoints diff --git a/pkgs/atlas-search/worker/src/admission.ts b/pkgs/atlas-search/worker/src/admission.ts new file mode 100644 index 0000000000..338e363e28 --- /dev/null +++ b/pkgs/atlas-search/worker/src/admission.ts @@ -0,0 +1,256 @@ +/** + * D1 hot-cache admission policy (#13103, follow-on 3 of 6 under + * #9134): heat counters, heavy-query immediate admission, per-tenant + * quotas, and the LRU eviction sweep — design §3 and §5 + * (doc/2026-11-23T08-06-00Z_design_atlas_d1_tenant_hot_cache). + * + * This module is pure policy: it imports nothing from the store + * (follow-on 1, #13100) or the freshness evaluator (follow-on 2, + * #13101), and its entry facts mirror the design §5 schema fields, + * so the read-path integration (follow-on 4) wires it to whatever + * store lands. Every threshold is a named config value (program + * rule: everything behavioral is configuration); the defaults are + * the design's, marked there as estimates to be re-tuned from the + * first measurement round. + */ + +export interface AdmissionConfig { + /** Heat: requests inside the window that make a key eligible. Default 2 (§3). */ + heatRequests: number; + /** Heat window, milliseconds. Default 10 minutes (§3). */ + heatWindowMs: number; + /** Heavy query: source latency strictly above this (ms) admits on first request. Default 250 (§3). */ + heavyLatencyMs: number; + /** Heavy query: rows-read strictly above this admits on first request. Default 10,000 (§3). */ + heavyRowsRead: number; + /** Per-tenant quota weights by tier index. Default [1, 4, 16] across the #9083 tiers (§3). */ + tierWeights: readonly number[]; + /** Fraction of the total budget reserved per active tenant. Default 0.05 (§3). */ + tenantFloorFraction: number; + /** Entry size cap, serialized bytes; larger entries are never admitted. Default 256 KiB (§3). */ + maxEntryBytes: number; + /** Negative (empty) results are admitted with this TTL, ms. Default 30 s (§3). */ + negativeTtlMs: number; +} + +export const DEFAULT_ADMISSION_CONFIG: AdmissionConfig = { + heatRequests: 2, + heatWindowMs: 10 * 60 * 1000, + heavyLatencyMs: 250, + heavyRowsRead: 10_000, + tierWeights: [1, 4, 16], + tenantFloorFraction: 0.05, + maxEntryBytes: 256 * 1024, + negativeTtlMs: 30 * 1000, +}; + +// --------------------------------------------------------------------------- +// Heat counters (§3: eligible after `heatRequests` requests inside +// `heatWindowMs`). In-memory and per-isolate: heat is evidence, not +// state of record — losing a counter on isolate recycle costs one +// extra source fill, never correctness. All times are caller-supplied +// milliseconds, so the tracker is deterministic under test. +// --------------------------------------------------------------------------- + +export class HeatTracker { + private readonly config: AdmissionConfig; + private readonly hits = new Map(); + + constructor(config: AdmissionConfig) { + this.config = config; + } + + private slot(tenantId: string, cacheKey: string): string { + return JSON.stringify([tenantId, cacheKey]); + } + + /** Timestamps for the key that fall inside the window ending at `nowMs`. */ + private live(tenantId: string, cacheKey: string, nowMs: number): number[] { + const slot = this.slot(tenantId, cacheKey); + const kept = (this.hits.get(slot) ?? []).filter((ts) => nowMs - ts < this.config.heatWindowMs); + if (kept.length === 0) this.hits.delete(slot); + else this.hits.set(slot, kept); + return kept; + } + + /** Record one request at `nowMs`; returns the in-window count including it. */ + record(tenantId: string, cacheKey: string, nowMs: number): number { + const kept = this.live(tenantId, cacheKey, nowMs); + kept.push(nowMs); + this.hits.set(this.slot(tenantId, cacheKey), kept); + return kept.length; + } + + /** In-window request count at `nowMs`, recording nothing. */ + count(tenantId: string, cacheKey: string, nowMs: number): number { + return this.live(tenantId, cacheKey, nowMs).length; + } + + /** Whether the key has demonstrated heat at `nowMs`. */ + eligible(tenantId: string, cacheKey: string, nowMs: number): boolean { + return this.count(tenantId, cacheKey, nowMs) >= this.config.heatRequests; + } + + /** Drop all counters (tests, operator resets). */ + clear(): void { + this.hits.clear(); + } +} + +// --------------------------------------------------------------------------- +// The admission decision (§3). One fill is judged on its facts: the +// size cap is absolute (a heavy or hot oversized entry is still +// refused — it would consume a tenant's whole quota), then the +// cost-based heavy exception, then heat. +// --------------------------------------------------------------------------- + +export interface FillFacts { + /** Serialized payload size, bytes. */ + payloadBytes: number; + /** Source latency of the fill query, ms (estimate or measured). */ + sourceLatencyMs: number; + /** Rows read at the source by the fill query (estimate or measured). */ + rowsRead: number; + /** True when the result set is empty (a negative result). */ + isNegative: boolean; + /** Requests for this key inside the heat window, including the current one. */ + heatCount: number; +} + +export type AdmissionDecision = + | { admit: true; reason: "heavy" | "heat"; ttlMs: number | null } + | { admit: false; reason: "oversized" | "cold"; ttlMs: null }; + +export function decideAdmission(facts: FillFacts, config: AdmissionConfig): AdmissionDecision { + if (facts.payloadBytes > config.maxEntryBytes) { + return { admit: false, reason: "oversized", ttlMs: null }; + } + // Negative results ride the same gates (a single poll is one-hit + // traffic like any other); admission just shortens their life to + // the negative TTL so a miss expires quickly once ingestion lands. + const ttlMs = facts.isNegative ? config.negativeTtlMs : null; + if (facts.sourceLatencyMs > config.heavyLatencyMs || facts.rowsRead > config.heavyRowsRead) { + return { admit: true, reason: "heavy", ttlMs }; + } + if (facts.heatCount >= config.heatRequests) { + return { admit: true, reason: "heat", ttlMs }; + } + return { admit: false, reason: "cold", ttlMs: null }; +} + +// --------------------------------------------------------------------------- +// Per-tenant quotas (§3): each active tenant first reserves the +// floor fraction of the total budget; the remainder is split by +// tier weight. If the reservations alone would exceed the budget +// (more active tenants than the floor admits), the floor is +// impossible and the whole budget splits by weight instead — +// shares always sum to the budget and never exceed it. +// --------------------------------------------------------------------------- + +export interface TenantTier { + tenantId: string; + /** Index into `config.tierWeights`. */ + tier: number; +} + +export function quotaShares( + tenants: readonly TenantTier[], + totalBudgetBytes: number, + config: AdmissionConfig, +): Map { + const shares = new Map(); + if (tenants.length === 0 || totalBudgetBytes <= 0) return shares; + let totalWeight = 0; + for (const t of tenants) { + const w = config.tierWeights[t.tier]; + if (w === undefined) { + throw new RangeError( + `quotaShares: tenant ${t.tenantId} names tier ${t.tier}, outside config.tierWeights (0..${config.tierWeights.length - 1})`, + ); + } + totalWeight += w; + } + const floorBytes = Math.floor(config.tenantFloorFraction * totalBudgetBytes); + const reserved = floorBytes * tenants.length; + const useFloor = reserved <= totalBudgetBytes; + const distributable = useFloor ? totalBudgetBytes - reserved : totalBudgetBytes; + let assigned = 0; + for (const t of tenants) { + const base = useFloor ? floorBytes : 0; + const share = base + Math.floor((distributable * config.tierWeights[t.tier]) / totalWeight); + shares.set(t.tenantId, share); + assigned += share; + } + // Flooring leaves a remainder smaller than the tenant count; + // hand it to the first tenant so shares sum to the budget. + const remainder = totalBudgetBytes - assigned; + if (remainder > 0) { + const first = tenants[0].tenantId; + shares.set(first, (shares.get(first) ?? 0) + remainder); + } + return shares; +} + +// --------------------------------------------------------------------------- +// The eviction sweep (§5). Quota binds only under pressure: while +// the database is within its total budget, unused quota is +// borrowable and no tenant sheds anything, however far over its +// own share it sits. Under pressure, each over-share tenant sheds +// its least-recently-hit entries — Class B and C before Class A +// (A bodies are re-derivable from the content store, so they are +// evicted last) — until it is back within its share. A tenant with +// no share entry has no quota and sheds everything. +// --------------------------------------------------------------------------- + +export type EntryClass = "A" | "B" | "C"; + +/** The §5 schema facts the sweep judges on. Times are the schema's unix seconds. */ +export interface EvictionEntry { + tenantId: string; + cacheKey: string; + entryClass: EntryClass; + payloadBytes: number; + lastHitAt: number; + hitCount: number; +} + +function classRank(c: EntryClass): number { + return c === "A" ? 1 : 0; +} + +export function planEvictions( + entries: readonly EvictionEntry[], + shares: ReadonlyMap, + totalBudgetBytes: number, +): EvictionEntry[] { + let totalBytes = 0; + const byTenant = new Map(); + for (const e of entries) { + totalBytes += e.payloadBytes; + const list = byTenant.get(e.tenantId); + if (list) list.push(e); + else byTenant.set(e.tenantId, [e]); + } + if (totalBytes <= totalBudgetBytes) return []; + + const plan: EvictionEntry[] = []; + for (const tenantId of [...byTenant.keys()].sort()) { + const list = byTenant.get(tenantId) ?? []; + let tenantBytes = list.reduce((sum, e) => sum + e.payloadBytes, 0); + const share = shares.get(tenantId) ?? 0; + if (tenantBytes <= share) continue; + const victims = [...list].sort( + (a, b) => + classRank(a.entryClass) - classRank(b.entryClass) || + a.lastHitAt - b.lastHitAt || + a.hitCount - b.hitCount || + (a.cacheKey < b.cacheKey ? -1 : a.cacheKey > b.cacheKey ? 1 : 0), + ); + for (const victim of victims) { + if (tenantBytes <= share) break; + plan.push(victim); + tenantBytes -= victim.payloadBytes; + } + } + return plan; +} diff --git a/pkgs/atlas-search/worker/test/admission.test.ts b/pkgs/atlas-search/worker/test/admission.test.ts new file mode 100644 index 0000000000..8f7aa6afae --- /dev/null +++ b/pkgs/atlas-search/worker/test/admission.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_ADMISSION_CONFIG, + HeatTracker, + decideAdmission, + planEvictions, + quotaShares, + type AdmissionConfig, + type EvictionEntry, +} from "../src/admission"; + +// Oracle for every rule below: the #9134 design, §3 (admission) and +// §5 (eviction). Expected values are computed from the design text, +// not from the implementation. + +const CFG: AdmissionConfig = DEFAULT_ADMISSION_CONFIG; +const MIN = 60 * 1000; + +describe("HeatTracker (§3: eligible after 2 requests / 10 min)", () => { + it("counts the first request without making the key eligible", () => { + const heat = new HeatTracker(CFG); + expect(heat.record("t1", "k", 0)).toBe(1); + expect(heat.eligible("t1", "k", 0)).toBe(false); + }); + + it("makes the key eligible on the second request inside the window", () => { + const heat = new HeatTracker(CFG); + heat.record("t1", "k", 0); + expect(heat.record("t1", "k", 5 * MIN)).toBe(2); + expect(heat.eligible("t1", "k", 5 * MIN)).toBe(true); + }); + + it("does not combine requests across the window boundary", () => { + const heat = new HeatTracker(CFG); + heat.record("t1", "k", 0); + // Exactly one window later the first request has aged out + // (a timestamp counts iff it is younger than the window). + expect(heat.record("t1", "k", 10 * MIN)).toBe(1); + expect(heat.eligible("t1", "k", 10 * MIN)).toBe(false); + }); + + it("keeps tenants and keys separate", () => { + const heat = new HeatTracker(CFG); + heat.record("t1", "k", 0); + heat.record("t2", "k", 0); + heat.record("t1", "other", 0); + expect(heat.count("t1", "k", 0)).toBe(1); + expect(heat.eligible("t1", "k", 0)).toBe(false); + }); + + it("reads the threshold and window from config, not constants", () => { + const heat = new HeatTracker({ ...CFG, heatRequests: 3, heatWindowMs: MIN }); + heat.record("t1", "k", 0); + heat.record("t1", "k", 1000); + expect(heat.eligible("t1", "k", 1000)).toBe(false); + heat.record("t1", "k", 2000); + expect(heat.eligible("t1", "k", 2000)).toBe(true); + // The custom 1-minute window ages the t=0 hit out by t=60.5s, + // leaving the t=1s and t=2s hits inside. + expect(heat.count("t1", "k", 60_500)).toBe(2); + }); +}); + +describe("decideAdmission — heavy-query exception (§3)", () => { + const cold = { payloadBytes: 1024, sourceLatencyMs: 0, rowsRead: 0, isNegative: false, heatCount: 1 }; + + it("admits a first request whose source latency exceeds the threshold", () => { + expect(decideAdmission({ ...cold, sourceLatencyMs: 251 }, CFG)).toEqual({ + admit: true, + reason: "heavy", + ttlMs: null, + }); + }); + + it("admits a first request whose rows-read exceeds the threshold", () => { + expect(decideAdmission({ ...cold, rowsRead: 10_001 }, CFG)).toEqual({ + admit: true, + reason: "heavy", + ttlMs: null, + }); + }); + + it("treats the thresholds as strict (at-threshold is not heavy)", () => { + // Design wording is "latency > 250 ms or rows-read > 10,000". + expect(decideAdmission({ ...cold, sourceLatencyMs: 250, rowsRead: 10_000 }, CFG)).toEqual({ + admit: false, + reason: "cold", + ttlMs: null, + }); + }); + + it("reads the heavy thresholds from config", () => { + const cfg = { ...CFG, heavyLatencyMs: 100 }; + expect(decideAdmission({ ...cold, sourceLatencyMs: 150 }, cfg).admit).toBe(true); + expect(decideAdmission({ ...cold, sourceLatencyMs: 150 }, CFG).admit).toBe(false); + }); +}); + +describe("decideAdmission — heat, size cap, negatives (§3)", () => { + const base = { payloadBytes: 1024, sourceLatencyMs: 0, rowsRead: 0, isNegative: false, heatCount: 1 }; + + it("refuses a cold, light first request", () => { + expect(decideAdmission(base, CFG)).toEqual({ admit: false, reason: "cold", ttlMs: null }); + }); + + it("admits once the heat count reaches the configured threshold", () => { + expect(decideAdmission({ ...base, heatCount: 2 }, CFG)).toEqual({ + admit: true, + reason: "heat", + ttlMs: null, + }); + }); + + it("refuses an entry larger than the size cap even when heavy and hot", () => { + const big = { ...base, payloadBytes: CFG.maxEntryBytes + 1, sourceLatencyMs: 9999, heatCount: 99 }; + expect(decideAdmission(big, CFG)).toEqual({ admit: false, reason: "oversized", ttlMs: null }); + }); + + it("admits an entry exactly at the size cap (the rule is 'larger than')", () => { + expect(decideAdmission({ ...base, payloadBytes: CFG.maxEntryBytes, heatCount: 2 }, CFG).admit).toBe(true); + }); + + it("admits a negative result through the heat gate with the negative TTL", () => { + expect(decideAdmission({ ...base, isNegative: true, heatCount: 2 }, CFG)).toEqual({ + admit: true, + reason: "heat", + ttlMs: 30 * 1000, + }); + }); + + it("admits a heavy negative result with the negative TTL", () => { + expect(decideAdmission({ ...base, isNegative: true, sourceLatencyMs: 500 }, CFG)).toEqual({ + admit: true, + reason: "heavy", + ttlMs: 30 * 1000, + }); + }); + + it("does not admit a single cold negative poll (one-hit traffic)", () => { + expect(decideAdmission({ ...base, isNegative: true }, CFG)).toEqual({ + admit: false, + reason: "cold", + ttlMs: null, + }); + }); + + it("reads the negative TTL from config", () => { + const cfg = { ...CFG, negativeTtlMs: 5000 }; + expect(decideAdmission({ ...base, isNegative: true, heatCount: 2 }, cfg).ttlMs).toBe(5000); + }); +}); + +describe("quotaShares (§3: tier weights 1:4:16, 5% floor)", () => { + it("splits purely by weight when the floor is configured off", () => { + const cfg = { ...CFG, tenantFloorFraction: 0 }; + const shares = quotaShares( + [ + { tenantId: "a", tier: 0 }, + { tenantId: "b", tier: 1 }, + { tenantId: "c", tier: 2 }, + ], + 2_100_000, + cfg, + ); + expect(shares.get("a")).toBe(100_000); + expect(shares.get("b")).toBe(400_000); + expect(shares.get("c")).toBe(1_600_000); + }); + + it("reserves the floor per tenant before splitting the remainder by weight", () => { + // Budget 1,000,000; floor 5% = 50,000 each; remaining 900,000 + // split 1:16 → 52,941 / 847,058 (floored), remainder 1 to first. + const shares = quotaShares( + [ + { tenantId: "small", tier: 0 }, + { tenantId: "big", tier: 2 }, + ], + 1_000_000, + CFG, + ); + expect(shares.get("small")).toBe(50_000 + 52_941 + 1); + expect(shares.get("big")).toBe(50_000 + 847_058); + expect((shares.get("small") ?? 0) + (shares.get("big") ?? 0)).toBe(1_000_000); + }); + + it("guarantees the floor: a lone small tenant among large ones keeps 5%", () => { + const tenants = [ + { tenantId: "small", tier: 0 }, + { tenantId: "big1", tier: 2 }, + { tenantId: "big2", tier: 2 }, + ]; + const shares = quotaShares(tenants, 1_000_000, CFG); + // Pure weight would give the small tenant 1/33 ≈ 30,303 < floor. + expect(shares.get("small")).toBeGreaterThanOrEqual(50_000); + }); + + it("falls back to pure weight when floors alone would exceed the budget", () => { + // 25 active tenants × 5% floor = 125% of the budget: the floor + // is impossible, so the budget splits by weight (equal here). + const tenants = Array.from({ length: 25 }, (_, i) => ({ tenantId: `t${i}`, tier: 0 })); + const shares = quotaShares(tenants, 1_000_000, CFG); + for (const t of tenants) expect(shares.get(t.tenantId)).toBe(40_000); + }); + + it("rejects a tier outside the configured weights", () => { + expect(() => quotaShares([{ tenantId: "x", tier: 7 }], 1000, CFG)).toThrow(RangeError); + }); + + it("returns no shares for no tenants", () => { + expect(quotaShares([], 1_000_000, CFG).size).toBe(0); + }); +}); + +describe("planEvictions (§5: per-tenant under pressure, B/C before A)", () => { + const entry = (over: Partial): EvictionEntry => ({ + tenantId: "t1", + cacheKey: "k", + entryClass: "B", + payloadBytes: 100, + lastHitAt: 0, + hitCount: 0, + ...over, + }); + + it("evicts nothing while the database is within budget (quota is borrowable)", () => { + const entries = [entry({ cacheKey: "a", payloadBytes: 900 })]; + const shares = new Map([["t1", 100]]); + expect(planEvictions(entries, shares, 1000)).toEqual([]); + }); + + it("sheds only the over-share tenant, down to its share", () => { + const entries = [ + entry({ tenantId: "over", cacheKey: "o1", payloadBytes: 300, lastHitAt: 1 }), + entry({ tenantId: "over", cacheKey: "o2", payloadBytes: 300, lastHitAt: 2 }), + entry({ tenantId: "over", cacheKey: "o3", payloadBytes: 300, lastHitAt: 3 }), + entry({ tenantId: "under", cacheKey: "u1", payloadBytes: 500, lastHitAt: 1 }), + ]; + const shares = new Map([ + ["over", 600], + ["under", 600], + ]); + // Total 1400 > budget 1200 → pressure. "over" must shed 300: + // exactly its coldest entry. "under" is untouched. + const plan = planEvictions(entries, shares, 1200); + expect(plan.map((e) => e.cacheKey)).toEqual(["o1"]); + }); + + it("evicts Class B and C before Class A, LRU inside each class group", () => { + const entries = [ + entry({ cacheKey: "a-coldest", entryClass: "A", lastHitAt: 1 }), + entry({ cacheKey: "b-mid", entryClass: "B", lastHitAt: 50 }), + entry({ cacheKey: "c-old", entryClass: "C", lastHitAt: 10 }), + entry({ cacheKey: "b-new", entryClass: "B", lastHitAt: 90 }), + entry({ cacheKey: "a-recent", entryClass: "A", lastHitAt: 99 }), + ]; + const shares = new Map([["t1", 200]]); + // Total 500 > budget 400 → pressure; t1 must shed 300 of 500. + // Order: C/B by lastHitAt (c-old 10, b-mid 50, b-new 90), then A + // — the coldest A goes last despite being the coldest overall. + const plan = planEvictions(entries, shares, 400); + expect(plan.map((e) => e.cacheKey)).toEqual(["c-old", "b-mid", "b-new"]); + }); + + it("reaches into Class A only after B and C are exhausted", () => { + const entries = [ + entry({ cacheKey: "b1", entryClass: "B", lastHitAt: 5 }), + entry({ cacheKey: "a1", entryClass: "A", lastHitAt: 1 }), + entry({ cacheKey: "a2", entryClass: "A", lastHitAt: 2 }), + ]; + const shares = new Map([["t1", 0]]); + const plan = planEvictions(entries, shares, 200); + expect(plan.map((e) => e.cacheKey)).toEqual(["b1", "a1", "a2"]); + }); + + it("sheds everything for a tenant with no share entry", () => { + const entries = [ + entry({ tenantId: "ghost", cacheKey: "g1", payloadBytes: 100 }), + entry({ tenantId: "t1", cacheKey: "k1", payloadBytes: 950 }), + ]; + const shares = new Map([["t1", 1000]]); + const plan = planEvictions(entries, shares, 1000); + expect(plan.map((e) => e.cacheKey)).toEqual(["g1"]); + }); + + it("breaks lastHitAt ties by hit count, then key, deterministically", () => { + const entries = [ + entry({ cacheKey: "zz", lastHitAt: 7, hitCount: 1 }), + entry({ cacheKey: "aa", lastHitAt: 7, hitCount: 1 }), + entry({ cacheKey: "mm", lastHitAt: 7, hitCount: 5 }), + ]; + const shares = new Map([["t1", 0]]); + const plan = planEvictions(entries, shares, 100); + expect(plan.map((e) => e.cacheKey)).toEqual(["aa", "zz", "mm"]); + }); +});