Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pkgs/atlas-search/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ query, result, meta}`.
- Add an LRU sweeper when there are 10,000 cached queries or 1 GB of
aggregate cache storage. Until then, entries have no TTL.

## D1 tenant hot cache (#9134, flag off)

The `HOT_CACHE` D1 binding and the store module in
`src/hot_cache.ts` implement §8 item 1 of the D1 tenant hot cache
design (`doc/2026-11-23T08-06-00Z_design_atlas_d1_tenant_hot_cache/`):
the §5 `hot_cache` schema (migration `migrations/0001_hot_cache.sql`)
plus get/put/touch/evict primitives. The tier is gated by
`HOT_CACHE_ENABLED` (default `"false"`); with the flag off nothing
reads or writes the cache 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
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`.

## Secrets (names only; set with `wrangler secret put`)

`GATE_TOKEN`, `SERVICE_TOKEN` (the service's `cf-worker` client
Expand Down
5 changes: 5 additions & 0 deletions pkgs/atlas-search/worker/cloudflare.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export default defineConfig({
env: {
QUERY_CACHE: bindings.durableObject({ worker: "atlas-search", exportName: "QueryCache" }),
SERVICE_BASE: bindings.text("https://atlas-search.security.cab"),
// D1 tenant hot cache (#9134 §5, #13100): mirrors the
// wrangler.toml binding; placeholder id until the database
// is created at deploy time. Flag default off.
HOT_CACHE: bindings.d1({ name: "atlas-hot-cache", id: "00000000-0000-0000-0000-000000000001" }),
HOT_CACHE_ENABLED: bindings.text("false"),
},
},
});
17 changes: 17 additions & 0 deletions pkgs/atlas-search/worker/migrations/0001_hot_cache.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- Atlas D1 tenant hot cache (#9134 design §5; implementation #13100).
-- One shared D1 database; the tenant is carried in the key, never in
-- a per-tenant database. Applied with `wrangler d1 migrations apply`
-- (or the cf equivalent) against the HOT_CACHE binding's database.
CREATE TABLE hot_cache (
tenant_id TEXT NOT NULL,
cache_key TEXT NOT NULL,
class TEXT NOT NULL, -- 'A' | 'B' | 'C'
payload BLOB NOT NULL,
payload_bytes INTEGER NOT NULL,
source_watermark TEXT NOT NULL,
filled_at INTEGER NOT NULL, -- unix seconds
last_hit_at INTEGER NOT NULL,
hit_count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (tenant_id, cache_key)
);
CREATE INDEX hot_cache_eviction ON hot_cache (tenant_id, last_hit_at);
130 changes: 130 additions & 0 deletions pkgs/atlas-search/worker/src/hot_cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* D1 tenant hot cache store (#9134 design §5; implementation #13100).
*
* Primitives over the single shared `hot_cache` table (schema in
* migrations/0001_hot_cache.sql): get / put / touch / evict for one
* (tenant, key) row. The tenant is carried in the key, never in a
* per-tenant database (design §5).
*
* This module is deliberately only the storage layer. Freshness
* evaluation (design §1) is follow-on #13101, admission and the
* eviction sweep (§3/§5) are #13103, and read-path integration is
* #13105. Nothing reads through this store until those land, and the
* whole tier sits behind the HOT_CACHE_ENABLED flag (default off):
* with the flag off, `hotCacheStore` returns undefined and callers
* keep the pre-cache path exactly — zero behavior change.
*/

export type HotCacheClass = "A" | "B" | "C";

export interface HotCachePut {
tenantId: string;
cacheKey: string;
entryClass: HotCacheClass;
payload: Uint8Array;
sourceWatermark: string;
/** Unix seconds; the fill time recorded by the filler. */
filledAt: number;
}

export interface HotCacheEntry extends HotCachePut {
payloadBytes: number;
lastHitAt: number;
hitCount: number;
}

interface HotCacheRow {
tenant_id: string;
cache_key: string;
class: string;
payload: ArrayBuffer;
payload_bytes: number;
source_watermark: string;
filled_at: number;
last_hit_at: number;
hit_count: number;
}

export class HotCacheStore {
constructor(private readonly db: D1Database) {}

/** Read one entry; undefined when the (tenant, key) pair is absent. */
async get(tenantId: string, cacheKey: string): Promise<HotCacheEntry | undefined> {
const row = await this.db
.prepare(
"SELECT tenant_id, cache_key, class, payload, payload_bytes, source_watermark, filled_at, last_hit_at, hit_count FROM hot_cache WHERE tenant_id = ? AND cache_key = ?",
)
.bind(tenantId, cacheKey)
.first<HotCacheRow>();
if (!row) return undefined;
return {
tenantId: row.tenant_id,
cacheKey: row.cache_key,
entryClass: row.class as HotCacheClass,
payload: new Uint8Array(row.payload),
payloadBytes: row.payload_bytes,
sourceWatermark: row.source_watermark,
filledAt: row.filled_at,
lastHitAt: row.last_hit_at,
hitCount: row.hit_count,
};
}

/**
* Insert or replace one entry. A fresh fill starts its hit
* bookkeeping over: last_hit_at is the fill time, hit_count is 0.
*/
async put(entry: HotCachePut): Promise<void> {
await this.db
.prepare(
"INSERT OR REPLACE INTO hot_cache (tenant_id, cache_key, class, payload, payload_bytes, source_watermark, filled_at, last_hit_at, hit_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)",
)
.bind(
entry.tenantId,
entry.cacheKey,
entry.entryClass,
entry.payload,
entry.payload.byteLength,
entry.sourceWatermark,
entry.filledAt,
entry.filledAt,
)
.run();
}

/** Record a served hit; drives the §5 least-recently-hit eviction order. */
async touch(tenantId: string, cacheKey: string, atSeconds: number): Promise<void> {
await this.db
.prepare(
"UPDATE hot_cache SET last_hit_at = ?, hit_count = hit_count + 1 WHERE tenant_id = ? AND cache_key = ?",
)
.bind(atSeconds, tenantId, cacheKey)
.run();
}

/** Delete one entry; true when a row was actually removed. */
async evict(tenantId: string, cacheKey: string): Promise<boolean> {
const result = await this.db
.prepare("DELETE FROM hot_cache WHERE tenant_id = ? AND cache_key = ?")
.bind(tenantId, cacheKey)
.run();
return result.meta.changes > 0;
}
}

/** The config flag (design §8 item 1): only the literal "true" enables the tier. */
export function hotCacheEnabled(env: { HOT_CACHE_ENABLED?: string }): boolean {
return env.HOT_CACHE_ENABLED === "true";
}

/**
* The store for a request environment, or undefined when the tier is
* disabled or unbound — the caller's signal to use the pre-cache path.
*/
export function hotCacheStore(env: {
HOT_CACHE?: D1Database;
HOT_CACHE_ENABLED?: string;
}): HotCacheStore | undefined {
if (!hotCacheEnabled(env) || !env.HOT_CACHE) return undefined;
return new HotCacheStore(env.HOT_CACHE);
}
6 changes: 6 additions & 0 deletions pkgs/atlas-search/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ export { QueryCache };

export interface Env {
QUERY_CACHE: DurableObjectNamespace;
/** D1 tenant hot cache binding (#9134 §5, #13100); optional so a
* deploy without the database provisioned still typechecks and
* runs the pre-cache path. */
HOT_CACHE?: D1Database;
/** Hot-cache master flag; only the literal "true" enables it. */
HOT_CACHE_ENABLED?: string;
GATE_TOKEN: string;
SERVICE_BASE: string;
SERVICE_TOKEN: string;
Expand Down
121 changes: 121 additions & 0 deletions pkgs/atlas-search/worker/test/hot_cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { env } from "cloudflare:test";
import { beforeAll, describe, expect, it } from "vitest";
import {
HotCacheStore,
hotCacheEnabled,
hotCacheStore,
type HotCacheClass,
} from "../src/hot_cache";
import schemaSql from "../migrations/0001_hot_cache.sql?raw";

const db = (env as unknown as { HOT_CACHE: D1Database }).HOT_CACHE;
const store = new HotCacheStore(db);

beforeAll(async () => {
// D1's exec is line-oriented and cannot run the migration's
// multi-line statements; apply it statement by statement instead.
const statements = schemaSql
.split("\n")
.filter((line) => !line.trim().startsWith("--"))
.join("\n")
.split(";")
.map((s) => s.trim())
.filter((s) => s.length > 0);
for (const stmt of statements) {
await db.prepare(stmt).run();
}
});

const CLASSES: HotCacheClass[] = ["A", "B", "C"];

describe("hot cache store round-trip", () => {
it.each(CLASSES)("round-trips a class %s entry byte-for-byte", async (entryClass) => {
const payload = new TextEncoder().encode(`payload-for-${entryClass}`);
await store.put({
tenantId: "tenant-1",
cacheKey: `key-${entryClass}`,
entryClass,
payload,
sourceWatermark: "wm-42",
filledAt: 1_700_000_000,
});
const got = await store.get("tenant-1", `key-${entryClass}`);
expect(got).toBeDefined();
expect(got!.entryClass).toBe(entryClass);
expect(got!.payload).toEqual(payload);
expect(got!.payloadBytes).toBe(payload.byteLength);
expect(got!.sourceWatermark).toBe("wm-42");
expect(got!.filledAt).toBe(1_700_000_000);
expect(got!.lastHitAt).toBe(1_700_000_000);
expect(got!.hitCount).toBe(0);
});

it("returns undefined for a missing entry", async () => {
expect(await store.get("tenant-1", "no-such-key")).toBeUndefined();
});

it("keeps tenants apart under the same key", async () => {
const payload = new TextEncoder().encode("tenant-2-bytes");
await store.put({
tenantId: "tenant-2",
cacheKey: "key-A",
entryClass: "A",
payload,
sourceWatermark: "wm-7",
filledAt: 1_700_000_100,
});
const t1 = await store.get("tenant-1", "key-A");
const t2 = await store.get("tenant-2", "key-A");
expect(t1!.sourceWatermark).toBe("wm-42");
expect(t2!.payload).toEqual(payload);
});

it("put replaces the payload and resets hit bookkeeping", async () => {
await store.touch("tenant-1", "key-B", 1_700_000_500);
const refill = new TextEncoder().encode("refilled");
await store.put({
tenantId: "tenant-1",
cacheKey: "key-B",
entryClass: "B",
payload: refill,
sourceWatermark: "wm-43",
filledAt: 1_700_000_600,
});
const got = await store.get("tenant-1", "key-B");
expect(got!.payload).toEqual(refill);
expect(got!.sourceWatermark).toBe("wm-43");
expect(got!.hitCount).toBe(0);
expect(got!.lastHitAt).toBe(1_700_000_600);
});

it("touch records hits for the eviction order", async () => {
await store.touch("tenant-1", "key-C", 1_700_001_000);
await store.touch("tenant-1", "key-C", 1_700_001_100);
const got = await store.get("tenant-1", "key-C");
expect(got!.hitCount).toBe(2);
expect(got!.lastHitAt).toBe(1_700_001_100);
});

it("evict removes exactly the named tenant's entry", async () => {
expect(await store.evict("tenant-2", "key-A")).toBe(true);
expect(await store.get("tenant-2", "key-A")).toBeUndefined();
expect(await store.get("tenant-1", "key-A")).toBeDefined();
expect(await store.evict("tenant-2", "key-A")).toBe(false);
});
});

describe("hot cache flag gating", () => {
it("is off unless the flag is the literal true", () => {
expect(hotCacheEnabled({})).toBe(false);
expect(hotCacheEnabled({ HOT_CACHE_ENABLED: "false" })).toBe(false);
expect(hotCacheEnabled({ HOT_CACHE_ENABLED: "true" })).toBe(true);
});

it("yields no store when off or unbound, a store when on and bound", () => {
expect(hotCacheStore({ HOT_CACHE: db })).toBeUndefined();
expect(hotCacheStore({ HOT_CACHE_ENABLED: "true" })).toBeUndefined();
expect(hotCacheStore({ HOT_CACHE: db, HOT_CACHE_ENABLED: "true" })).toBeInstanceOf(
HotCacheStore,
);
});
});
4 changes: 4 additions & 0 deletions pkgs/atlas-search/worker/test/sql-raw.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module "*.sql?raw" {
const sql: string;
export default sql;
}
15 changes: 15 additions & 0 deletions pkgs/atlas-search/worker/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,25 @@ workers_dev = true

[vars]
SERVICE_BASE = "https://atlas-search.security.cab"
# D1 tenant hot cache master flag (#9134 §8 item 1, #13100).
# Default off: with the flag off the Worker keeps the pre-cache
# read path exactly; src/hot_cache.ts is the only consumer.
HOT_CACHE_ENABLED = "false"

[durable_objects]
bindings = [{ name = "QUERY_CACHE", class_name = "QueryCache" }]

[[migrations]]
tag = "v1"
new_sqlite_classes = ["QueryCache"]

# D1 tenant hot cache (#9134 design §5; store in src/hot_cache.ts,
# schema in migrations/). The database is created at deploy time;
# the id below is the local placeholder (miniflare and wrangler
# --local ignore it), replaced with the real id when the database
# is created -- same convention as pkgs/id/worker-poc/d1-journal-poc.
[[d1_databases]]
binding = "HOT_CACHE"
database_name = "atlas-hot-cache"
database_id = "00000000-0000-0000-0000-000000000001"
migrations_dir = "migrations"