diff --git a/pkgs/atlas-search/worker/README.md b/pkgs/atlas-search/worker/README.md index 445b7b4e9d..db5fe563a5 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/freshness.ts` — the D1 hot-cache freshness evaluator + (#13101; design #9134 §1): pure per-class watermark/TTL rules + with fail-safe degradation, plus the tenant watermark read seam. + Not wired into a read path yet — the D1 store is #13100 and + read-path integration is follow-on 4 under #9134. ## Endpoints diff --git a/pkgs/atlas-search/worker/src/freshness.ts b/pkgs/atlas-search/worker/src/freshness.ts new file mode 100644 index 0000000000..967cf48648 --- /dev/null +++ b/pkgs/atlas-search/worker/src/freshness.ts @@ -0,0 +1,262 @@ +/** + * D1 hot-cache freshness evaluator (#13101; design #9134 §1, merged + * via PR #13098). Follow-on 2 of 6 under #9134: the per-class + * freshness rules, the tenant watermark read, and fail-safe + * degradation. The cache store itself is follow-on 1 (#13100) and + * read-path integration is follow-on 4; this module is the pure + * decision core both call. + * + * A cached entry may be served only inside its freshness bound; + * outside the bound the read revalidates against Turso. There is no + * serve-stale mode. Freshness is per data class (§1): + * + * A — content-addressed payloads. The content hash is the version: + * a body whose hash matches the request cannot be stale. No + * TTL, no watermark check; the watermark state is irrelevant. + * B — query result sets. Fresh iff the entry's source_watermark + * still equals the tenant's current watermark AND age ≤ TTL_B + * (default 60 s) — whichever fails first ends freshness, so a + * watermark advance makes an entry stale even inside the TTL. + * C — tenant aggregates. Fresh iff age ≤ TTL_C (default 15 min) + * AND no invalidation event for the tenant post-dates the + * entry. + * + * Fail-safe degradation (§1): when the tenant's current watermark + * cannot be read, unavailability of the truth source narrows the + * bound and never widens it — Class B degrades to TTL-only with + * TTL_B divided by the degraded divisor (default 2 → 30 s), Class C + * stops being served, Class A is unaffected. A serve that violates + * these rules is a defect, not a mode: §7's stale_serves counter + * counts watermark-mismatch serves and its expected value is zero. + * + * Purity: evaluateFreshness does no I/O and reads no clock — the + * caller supplies `now` and the watermark read result. The read + * itself is the thin seam readTenantWatermark, which maps every + * failure of the source (throw, null) to `unavailable` so a broken + * truth source can only ever narrow the bound. + */ + +/** The three data classes of design #9134 §1. */ +export type DataClass = "A" | "B" | "C"; + +/** + * Freshness bounds, named config values per design #9134 §1 (all + * bounds are configuration, program §7). Defaults: TTL_B 60 s, + * TTL_C 15 min, degraded divisor 2. + */ +export interface FreshnessConfig { + /** Class B TTL in seconds. */ + ttlBSeconds: number; + /** Class C TTL in seconds. */ + ttlCSeconds: number; + /** Divisor applied to TTL_B when the watermark source is unreachable. */ + degradedDivisor: number; +} + +export const DEFAULT_FRESHNESS_CONFIG: FreshnessConfig = { + ttlBSeconds: 60, + ttlCSeconds: 15 * 60, + degradedDivisor: 2, +}; + +function positiveFiniteOr(value: number | undefined, fallback: number): number { + return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback; +} + +/** + * Resolve a partial override against the defaults. An override is + * honored only when it is a positive finite number, and the degraded + * divisor is clamped to ≥ 1: a bad config value must never widen a + * bound past its default or turn degradation into an extension. + */ +export function resolveFreshnessConfig(overrides?: Partial): FreshnessConfig { + const divisor = positiveFiniteOr(overrides?.degradedDivisor, DEFAULT_FRESHNESS_CONFIG.degradedDivisor); + return { + ttlBSeconds: positiveFiniteOr(overrides?.ttlBSeconds, DEFAULT_FRESHNESS_CONFIG.ttlBSeconds), + ttlCSeconds: positiveFiniteOr(overrides?.ttlCSeconds, DEFAULT_FRESHNESS_CONFIG.ttlCSeconds), + degradedDivisor: Math.max(1, divisor), + }; +} + +/** The fill-time facts every cached entry carries (design §1, §5). */ +export interface CacheEntryFacts { + dataClass: DataClass; + /** The tenant's corpus watermark at the Turso source when the entry was filled. */ + sourceWatermark: string; + /** Wall-clock fill time, unix seconds (the §5 schema's filled_at). */ + filledAt: number; + /** Class A only: the content hash the stored body is addressed by. */ + contentHash?: string; +} + +/** + * The result of reading the tenant's current watermark: either the + * watermark verbatim, or `unavailable` when the source cannot be + * read. There is deliberately no third state — unknown is + * unavailable, and unavailable only ever narrows the bound. + */ +export type WatermarkRead = + | { status: "ok"; currentWatermark: string } + | { status: "unavailable" }; + +/** Everything the evaluator needs about the moment of the read. */ +export interface FreshnessContext { + /** Current wall-clock time, unix seconds (same clock domain as filledAt). */ + now: number; + watermark: WatermarkRead; + /** + * Class A only: the content hash the request names. When supplied, + * the entry is fresh iff its hash equals it. When omitted, the + * entry is addressed by its hash by construction (the §5 key) and + * is fresh. + */ + requestedContentHash?: string; + /** + * The latest invalidation event time for the tenant (unix + * seconds), or null when no event is known. Class C only: an + * event that post-dates the entry makes it stale (§4 mechanism 2). + */ + lastInvalidationAt?: number | null; +} + +/** Why the evaluator reached its verdict — the §2 skip log's reason surface. */ +export type FreshnessReason = + /** A: the stored body's hash is the requested version. */ + | "content-hash-match" + /** A: the stored body is not the requested version — never served. */ + | "content-hash-mismatch" + /** B: watermark still current and inside TTL_B. */ + | "watermark-current" + /** B: the tenant watermark advanced past the entry's fill watermark. */ + | "watermark-advanced" + /** B (degraded): inside the halved TTL-only bound. */ + | "degraded-ttl" + /** B/C: age exceeds the applicable TTL bound. */ + | "ttl-expired" + /** C: inside TTL_C with no later invalidation event. */ + | "within-ttl" + /** C: an invalidation event post-dates the entry. */ + | "invalidated" + /** C: the watermark source is unreachable — aggregates are not served. */ + | "watermark-unavailable" + /** B/C: filledAt is in the future — the age comparison cannot be trusted. */ + | "clock-skew"; + +export interface FreshnessVerdict { + /** True only when the entry may be served without revalidation. */ + fresh: boolean; + reason: FreshnessReason; + /** Entry age at evaluation time, seconds (negative under clock skew). */ + ageSeconds: number; + /** The TTL bound that applied, seconds; null for Class A (no TTL). */ + boundSeconds: number | null; + /** True when the watermark source was unreachable for this evaluation. */ + degraded: boolean; +} + +/** + * The pure freshness decision of design §1. Never serves outside + * the bound: every uncertainty (unreachable watermark, future fill + * time, unprovable hash) resolves to not fresh or to a narrower + * bound, never to a wider one. + */ +export function evaluateFreshness( + entry: CacheEntryFacts, + context: FreshnessContext, + config: FreshnessConfig = DEFAULT_FRESHNESS_CONFIG, +): FreshnessVerdict { + const ageSeconds = context.now - entry.filledAt; + const degraded = context.watermark.status === "unavailable"; + + if (entry.dataClass === "A") { + // The hash is the version: no TTL, no watermark check, and the + // watermark state (including its unavailability) is irrelevant. + if (context.requestedContentHash !== undefined && entry.contentHash !== context.requestedContentHash) { + return { fresh: false, reason: "content-hash-mismatch", ageSeconds, boundSeconds: null, degraded }; + } + return { fresh: true, reason: "content-hash-match", ageSeconds, boundSeconds: null, degraded }; + } + + // Classes B and C compare ages against a TTL; a fill time in the + // future makes that comparison meaningless, so fail safe. + if (ageSeconds < 0) { + return { + fresh: false, + reason: "clock-skew", + ageSeconds, + boundSeconds: entry.dataClass === "B" ? config.ttlBSeconds : config.ttlCSeconds, + degraded, + }; + } + + if (entry.dataClass === "B") { + if (context.watermark.status === "unavailable") { + // Degraded: TTL-only, halved (floored — rounding may only + // narrow the bound), never extended. + const boundSeconds = Math.floor(config.ttlBSeconds / Math.max(1, config.degradedDivisor)); + return ageSeconds <= boundSeconds + ? { fresh: true, reason: "degraded-ttl", ageSeconds, boundSeconds, degraded } + : { fresh: false, reason: "ttl-expired", ageSeconds, boundSeconds, degraded }; + } + if (entry.sourceWatermark !== context.watermark.currentWatermark) { + // A watermark advance makes the entry stale by rule, even + // inside the TTL — the watermark is the primary, clock-free + // guard (§6), so it is reported ahead of the TTL check. + return { fresh: false, reason: "watermark-advanced", ageSeconds, boundSeconds: config.ttlBSeconds, degraded }; + } + return ageSeconds <= config.ttlBSeconds + ? { fresh: true, reason: "watermark-current", ageSeconds, boundSeconds: config.ttlBSeconds, degraded } + : { fresh: false, reason: "ttl-expired", ageSeconds, boundSeconds: config.ttlBSeconds, degraded }; + } + + // Class C — tenant aggregates. + if (context.watermark.status === "unavailable") { + // Aggregates are the class most likely to be quoted as exact: + // not served at all while the truth source is unreachable. + return { fresh: false, reason: "watermark-unavailable", ageSeconds, boundSeconds: config.ttlCSeconds, degraded }; + } + if (context.lastInvalidationAt != null && context.lastInvalidationAt > entry.filledAt) { + return { fresh: false, reason: "invalidated", ageSeconds, boundSeconds: config.ttlCSeconds, degraded }; + } + return ageSeconds <= config.ttlCSeconds + ? { fresh: true, reason: "within-ttl", ageSeconds, boundSeconds: config.ttlCSeconds, degraded } + : { fresh: false, reason: "ttl-expired", ageSeconds, boundSeconds: config.ttlCSeconds, degraded }; +} + +/** + * A tenant watermark source: resolves the tenant's current corpus + * watermark at the Turso source of truth, or null when it has none + * on record. Implementations do the I/O; this seam is the only + * impure part of the freshness path. + */ +export type WatermarkSource = (tenantId: string) => Promise; + +/** + * The tenant watermark read (§8 item 2). Every failure of the + * source — a throw, a rejection, a null — maps to `unavailable`, so + * the evaluator degrades the bound instead of guessing. + */ +export async function readTenantWatermark(source: WatermarkSource, tenantId: string): Promise { + try { + const currentWatermark = await source(tenantId); + return currentWatermark === null ? { status: "unavailable" } : { status: "ok", currentWatermark }; + } catch { + return { status: "unavailable" }; + } +} + +/** + * Convenience composition for the read path: read the tenant's + * watermark through the source, then evaluate purely. Equivalent to + * evaluateFreshness with the read's result as the context watermark. + */ +export async function evaluateWithWatermarkRead( + entry: CacheEntryFacts, + tenantId: string, + source: WatermarkSource, + context: Omit, + config: FreshnessConfig = DEFAULT_FRESHNESS_CONFIG, +): Promise { + const watermark = await readTenantWatermark(source, tenantId); + return evaluateFreshness(entry, { ...context, watermark }, config); +} diff --git a/pkgs/atlas-search/worker/test/freshness.test.ts b/pkgs/atlas-search/worker/test/freshness.test.ts new file mode 100644 index 0000000000..a1a5fa0683 --- /dev/null +++ b/pkgs/atlas-search/worker/test/freshness.test.ts @@ -0,0 +1,309 @@ +import { describe, expect, it } from "vitest"; +import { + DEFAULT_FRESHNESS_CONFIG, + evaluateFreshness, + evaluateWithWatermarkRead, + readTenantWatermark, + resolveFreshnessConfig, + type CacheEntryFacts, + type DataClass, + type FreshnessConfig, + type FreshnessContext, +} from "../src/freshness"; + +// Oracle for every test in this file: design #9134 §1 (merged via +// PR #13098). A cached entry may be served only inside its freshness +// bound; the stale-serves counter's expected value is zero. + +const T0 = 1_700_000_000; +const OK_W0: FreshnessContext["watermark"] = { status: "ok", currentWatermark: "w0" }; +const DOWN: FreshnessContext["watermark"] = { status: "unavailable" }; + +function entry(dataClass: DataClass, over: Partial = {}): CacheEntryFacts { + return { dataClass, sourceWatermark: "w0", filledAt: T0, ...over }; +} + +describe("Class A — the hash is the version", () => { + it("serves a hash match at any age, watermark state irrelevant", () => { + const e = entry("A", { contentHash: "h1" }); + const v = evaluateFreshness(e, { now: T0 + 10_000_000, watermark: DOWN, requestedContentHash: "h1" }); + expect(v.fresh).toBe(true); + expect(v.reason).toBe("content-hash-match"); + expect(v.boundSeconds).toBeNull(); + }); + + it("never serves a hash mismatch", () => { + const e = entry("A", { contentHash: "h1" }); + const v = evaluateFreshness(e, { now: T0, watermark: OK_W0, requestedContentHash: "h2" }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("content-hash-mismatch"); + }); + + it("cannot prove identity when the entry carries no hash", () => { + const v = evaluateFreshness(entry("A"), { now: T0, watermark: OK_W0, requestedContentHash: "h1" }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("content-hash-mismatch"); + }); + + it("serves without a requested hash (the §5 key is the hash)", () => { + const v = evaluateFreshness(entry("A", { contentHash: "h1" }), { now: T0 + 999, watermark: DOWN }); + expect(v.fresh).toBe(true); + }); +}); + +describe("Class B — watermark equality or TTL_B, whichever fails first", () => { + it("serves inside the TTL while the watermark is current", () => { + const v = evaluateFreshness(entry("B"), { now: T0 + 60, watermark: OK_W0 }); + expect(v.fresh).toBe(true); + expect(v.reason).toBe("watermark-current"); + expect(v.boundSeconds).toBe(60); + }); + + it("a watermark advance makes the entry stale even inside the TTL", () => { + const v = evaluateFreshness(entry("B"), { + now: T0 + 5, + watermark: { status: "ok", currentWatermark: "w1" }, + }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("watermark-advanced"); + }); + + it("expires on TTL even while the watermark is current", () => { + const v = evaluateFreshness(entry("B"), { now: T0 + 61, watermark: OK_W0 }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("ttl-expired"); + }); + + it("degrades to TTL-only halved when the watermark source is unreachable", () => { + const inside = evaluateFreshness(entry("B"), { now: T0 + 30, watermark: DOWN }); + expect(inside.fresh).toBe(true); + expect(inside.reason).toBe("degraded-ttl"); + expect(inside.boundSeconds).toBe(30); + expect(inside.degraded).toBe(true); + const outside = evaluateFreshness(entry("B"), { now: T0 + 31, watermark: DOWN }); + expect(outside.fresh).toBe(false); + expect(outside.reason).toBe("ttl-expired"); + }); + + it("degradation never extends: 45 s is stale degraded though inside the normal TTL", () => { + const v = evaluateFreshness(entry("B"), { now: T0 + 45, watermark: DOWN }); + expect(v.fresh).toBe(false); + }); +}); + +describe("Class C — TTL_C and no later invalidation event", () => { + it("serves inside TTL_C with no invalidation event", () => { + const v = evaluateFreshness(entry("C"), { now: T0 + 900, watermark: OK_W0, lastInvalidationAt: null }); + expect(v.fresh).toBe(true); + expect(v.reason).toBe("within-ttl"); + expect(v.boundSeconds).toBe(900); + }); + + it("expires past TTL_C", () => { + const v = evaluateFreshness(entry("C"), { now: T0 + 901, watermark: OK_W0 }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("ttl-expired"); + }); + + it("an invalidation event that post-dates the entry makes it stale", () => { + const v = evaluateFreshness(entry("C"), { now: T0 + 10, watermark: OK_W0, lastInvalidationAt: T0 + 1 }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("invalidated"); + }); + + it("an event at or before fill time does not invalidate", () => { + const at = evaluateFreshness(entry("C"), { now: T0 + 10, watermark: OK_W0, lastInvalidationAt: T0 }); + expect(at.fresh).toBe(true); + const before = evaluateFreshness(entry("C"), { now: T0 + 10, watermark: OK_W0, lastInvalidationAt: T0 - 5 }); + expect(before.fresh).toBe(true); + }); + + it("stops being served entirely while the watermark source is unreachable", () => { + const v = evaluateFreshness(entry("C"), { now: T0, watermark: DOWN }); + expect(v.fresh).toBe(false); + expect(v.reason).toBe("watermark-unavailable"); + }); +}); + +describe("fail-safe edges", () => { + it("a fill time in the future is never fresh for the TTL classes", () => { + const b = evaluateFreshness(entry("B", { filledAt: T0 + 100 }), { now: T0, watermark: OK_W0 }); + expect(b.fresh).toBe(false); + expect(b.reason).toBe("clock-skew"); + const c = evaluateFreshness(entry("C", { filledAt: T0 + 100 }), { now: T0, watermark: OK_W0 }); + expect(c.fresh).toBe(false); + expect(c.reason).toBe("clock-skew"); + }); +}); + +describe("config resolution — a bad value never widens a bound", () => { + it("defaults are the design's: TTL_B 60 s, TTL_C 15 min, divisor 2", () => { + expect(DEFAULT_FRESHNESS_CONFIG).toEqual({ ttlBSeconds: 60, ttlCSeconds: 900, degradedDivisor: 2 }); + expect(resolveFreshnessConfig()).toEqual(DEFAULT_FRESHNESS_CONFIG); + }); + + it("honors valid overrides", () => { + const cfg = resolveFreshnessConfig({ ttlBSeconds: 10, ttlCSeconds: 60, degradedDivisor: 4 }); + expect(cfg).toEqual({ ttlBSeconds: 10, ttlCSeconds: 60, degradedDivisor: 4 }); + const v = evaluateFreshness(entry("B"), { now: T0 + 11, watermark: OK_W0 }, cfg); + expect(v.fresh).toBe(false); + }); + + it("falls back to defaults for non-positive or non-finite overrides", () => { + const cfg = resolveFreshnessConfig({ ttlBSeconds: -5, ttlCSeconds: Number.NaN, degradedDivisor: 0 }); + expect(cfg).toEqual(DEFAULT_FRESHNESS_CONFIG); + }); + + it("clamps a sub-1 divisor so degradation can never extend TTL_B", () => { + const cfg = resolveFreshnessConfig({ degradedDivisor: 0.5 }); + const v = evaluateFreshness(entry("B"), { now: T0 + 45, watermark: DOWN }, cfg); + expect(v.boundSeconds).not.toBeNull(); + expect(v.boundSeconds as number).toBeLessThanOrEqual(cfg.ttlBSeconds); + expect(v.fresh).toBe(true); // bound is TTL_B itself, not beyond it + const beyond = evaluateFreshness(entry("B"), { now: T0 + 61, watermark: DOWN }, cfg); + expect(beyond.fresh).toBe(false); + }); +}); + +describe("the tenant watermark read", () => { + it("returns the watermark verbatim", async () => { + expect(await readTenantWatermark(async () => "w7", "tenant-1")).toEqual({ + status: "ok", + currentWatermark: "w7", + }); + }); + + it("maps null and throws to unavailable — never to a guessed watermark", async () => { + expect(await readTenantWatermark(async () => null, "tenant-1")).toEqual({ status: "unavailable" }); + expect( + await readTenantWatermark(async () => { + throw new Error("turso unreachable"); + }, "tenant-1"), + ).toEqual({ status: "unavailable" }); + }); + + it("evaluateWithWatermarkRead composes the read and the pure rules", async () => { + const advanced = await evaluateWithWatermarkRead(entry("B"), "tenant-1", async () => "w9", { now: T0 + 5 }); + expect(advanced.fresh).toBe(false); + expect(advanced.reason).toBe("watermark-advanced"); + const degraded = await evaluateWithWatermarkRead( + entry("B"), + "tenant-1", + async () => { + throw new Error("down"); + }, + { now: T0 + 30 }, + ); + expect(degraded.fresh).toBe(true); + expect(degraded.reason).toBe("degraded-ttl"); + }); +}); + +/** + * The §1 model, transcribed directly from the design table as an + * independent predicate: true iff a serve at this moment is inside + * the bound. The property oracle below holds the evaluator to exact + * agreement with this transcription over generated sequences. + */ +function withinBoundModel(e: CacheEntryFacts, ctx: FreshnessContext, cfg: FreshnessConfig): boolean { + const age = ctx.now - e.filledAt; + switch (e.dataClass) { + case "A": + return ctx.requestedContentHash === undefined || e.contentHash === ctx.requestedContentHash; + case "B": { + if (age < 0) return false; + if (ctx.watermark.status === "unavailable") { + return age <= Math.floor(cfg.ttlBSeconds / Math.max(1, cfg.degradedDivisor)); + } + return e.sourceWatermark === ctx.watermark.currentWatermark && age <= cfg.ttlBSeconds; + } + case "C": { + if (age < 0) return false; + if (ctx.watermark.status === "unavailable") return false; + if (ctx.lastInvalidationAt != null && ctx.lastInvalidationAt > e.filledAt) return false; + return age <= cfg.ttlCSeconds; + } + } +} + +/** Deterministic PRNG (mulberry32) — generated cases must reproduce. */ +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +describe("property oracle — no serve happens outside the bound", () => { + it("evaluator agrees with the §1 model over generated (watermark, age, class, event) sequences; stale-serves counter is zero", () => { + const configs: FreshnessConfig[] = [ + DEFAULT_FRESHNESS_CONFIG, + resolveFreshnessConfig({ ttlBSeconds: 10, ttlCSeconds: 120, degradedDivisor: 4 }), + resolveFreshnessConfig({ ttlBSeconds: 300, ttlCSeconds: 60, degradedDivisor: 1 }), + ]; + const classes: DataClass[] = ["A", "B", "C"]; + let staleServes = 0; // evaluator served outside the bound — §7's counter, expected zero + let missedServes = 0; // evaluator refused inside the bound — over-narrowing is also a defect + let evaluations = 0; + + for (let seq = 0; seq < 200; seq++) { + const rand = mulberry32(0x9134 + seq); + const cfg = configs[seq % configs.length]; + const dataClass = classes[Math.floor(rand() * classes.length)]; + const watermarks = ["w0", "w1", "w2", "w3"]; + const hashes = ["h0", "h1", "h2"]; + let watermarkIdx = Math.floor(rand() * 2); // entry fills at w0 or w1 + const e: CacheEntryFacts = { + dataClass, + sourceWatermark: watermarks[watermarkIdx], + filledAt: T0, + contentHash: hashes[Math.floor(rand() * hashes.length)], + }; + let now = T0; + let sourceDown = false; + let lastInvalidationAt: number | null = null; + let requestedContentHash: string | undefined = + dataClass === "A" && rand() < 0.7 ? e.contentHash : undefined; + + const steps = 1 + Math.floor(rand() * 12); + for (let step = 0; step < steps; step++) { + // One generated event per step. + const event = rand(); + if (event < 0.35) { + now += Math.floor(rand() * 1200); // time passes + } else if (event < 0.55) { + watermarkIdx = Math.min(watermarks.length - 1, watermarkIdx + 1); // corpus write advances the watermark + } else if (event < 0.7) { + lastInvalidationAt = now; // tenant invalidation event fires + } else if (event < 0.85) { + sourceDown = !sourceDown; // watermark source flaps + } else if (dataClass === "A") { + requestedContentHash = hashes[Math.floor(rand() * hashes.length)]; // a different body is requested + } else { + now += Math.floor(rand() * 90); + } + + const ctx: FreshnessContext = { + now, + watermark: sourceDown ? DOWN : { status: "ok", currentWatermark: watermarks[watermarkIdx] }, + requestedContentHash, + lastInvalidationAt, + }; + const verdict = evaluateFreshness(e, ctx, cfg); + const model = withinBoundModel(e, ctx, cfg); + evaluations++; + if (verdict.fresh && !model) staleServes++; + if (!verdict.fresh && model) missedServes++; + expect(verdict.fresh).toBe(model); + } + } + + expect(evaluations).toBeGreaterThan(1000); + expect(staleServes).toBe(0); + expect(missedServes).toBe(0); + }); +});