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
13 changes: 13 additions & 0 deletions pkgs/atlas-search/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ query, result, meta}`.
- `GET /v1/cache/inspect?query=..&k=..` — gated; DO metadata
readback (embedding presence/dims/validity, result presence,
hit count, timings). The proof/audit surface.
- `POST /v1/cache/purge` `{query, k?}` — gated with the same
`GATE_TOKEN`; removes exactly that normalized query/config cache
entry. The query key is a SHA-256 digest, so per-prefix purge
cannot enumerate matching entries without a separate index and is
intentionally not provided.

## Deferred cache policy triggers (#6805)

- Add corpus generation to the cache key at the first same-space
re-ingest that changes more than 5% of chunks, or on a user-visible
stale-result complaint.
- Add an LRU sweeper when there are 10,000 cached queries or 1 GB of
aggregate cache storage. Until then, entries have no TTL.

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

Expand Down
5 changes: 5 additions & 0 deletions pkgs/atlas-search/worker/src/cache_do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ export class QueryCache {
if (req.method === "GET" && url.pathname === "/inspect") {
return Response.json(this.inspect());
}
if (req.method === "POST" && url.pathname === "/purge") {
const existed = this.row() !== undefined;
this.state.storage.sql.exec("DELETE FROM entry WHERE id = 1");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize purge with in-flight cache fills

If a purge arrives while a same-key cache miss is awaiting embedQuery() or searchService(), this deletion removes the row that the suspended fill still expects. Those outbound-fetch awaits allow other Durable Object requests to execute; when the fill resumes, its UPDATE affects no rows and meta(this.row()!) throws, returning a 500 to the active search. If a post-purge search recreates the row first, the older fill can instead write its pre-purge result into the new entry, defeating invalidation indefinitely. Serialize purge with fills or use a generation identifier to prevent pre-purge operations from updating post-purge state.

Useful? React with 👍 / 👎.

return Response.json({ purged: existed });
}
return Response.json({ error: { code: "not_found", message: "no route" } }, { status: 404 });
} catch (e) {
const status = (e as { status?: number }).status ?? 500;
Expand Down
31 changes: 31 additions & 0 deletions pkgs/atlas-search/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* GET /health (open; liveness only)
* POST /v1/search {query, k?} (gated) -> miss or hit envelope
* GET /v1/cache/inspect?query=&k= (gated) -> DO metadata readback
* POST /v1/cache/purge {query, k?} (gated) -> delete one cached query
*/
import { readTextUpTo } from "./body";
import { QueryCache } from "./cache_do";
Expand Down Expand Up @@ -127,6 +128,36 @@ export default {
return Response.json({ key, query, ...meta });
}

if (req.method === "POST" && url.pathname === "/v1/cache/purge") {
if (!(await gateOk(env, req))) {
return errorJson(401, "unauthorized", "missing or invalid gate token");
}
const raw = await readTextUpTo(req);
if (raw === null) {
return errorJson(413, "payload_too_large", "body is larger than the 64 KiB limit");
}
let body: { query?: unknown; k?: unknown };
try {
body = JSON.parse(raw) as typeof body;
} catch {
return errorJson(400, "bad_request", "body must be JSON");
}
if (typeof body !== "object" || body === null) {
return errorJson(400, "bad_request", "body must be a JSON object");
}
if (typeof body.query !== "string") {
return errorJson(400, "bad_request", "query must be a string");
}
const query = normalizeQuery(body.query);
if (!query) return errorJson(400, "bad_request", "query must not be empty");
const k = clampK(body.k);
const key = await queryKey({ q: query, k });
const stub = env.QUERY_CACHE.get(env.QUERY_CACHE.idFromName(key));
const resp = await stub.fetch("https://do/purge", { method: "POST" });
const result = (await resp.json()) as { purged: boolean };
return Response.json({ key, query, ...result });
}

return errorJson(404, "not_found", "no route");
},
};
38 changes: 38 additions & 0 deletions pkgs/atlas-search/worker/test/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,44 @@ describe("atlas-search worker", () => {
expect(meta.hit_count).toBe(1);
});

it("gated per-key purge makes the next search re-run embedding and fan-out", async () => {
const query = "purge target alpha";
const e0 = counts.embed;
const s0 = counts.search;
const first = await search({ query });
expect(first.status).toBe(200);
expect(counts.embed).toBe(e0 + 1);
expect(counts.search).toBe(s0 + 1);

const denied = await SELF.fetch("https://worker.test/v1/cache/purge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query }),
});
expect(denied.status).toBe(401);
expect(counts.embed).toBe(e0 + 1);
expect(counts.search).toBe(s0 + 1);

const purged = await SELF.fetch("https://worker.test/v1/cache/purge", {
method: "POST",
headers: { ...GATE, "Content-Type": "application/json" },
body: JSON.stringify({ query }),
});
expect(purged.status).toBe(200);
expect(await purged.json()).toMatchObject({ purged: true, query });
const inspect = await SELF.fetch(
`https://worker.test/v1/cache/inspect?query=${encodeURIComponent(query)}`,
{ headers: GATE },
);
expect(await inspect.json()).toMatchObject({ exists: false });

const second = await search({ query });
expect(second.status).toBe(200);
expect(((await second.json()) as { cache: string }).cache).toBe("miss");
expect(counts.embed).toBe(e0 + 2);
expect(counts.search).toBe(s0 + 2);
});

it("rejects a whitespace-only query on both routes (#6937)", async () => {
const e0 = counts.embed;
const s0 = counts.search;
Expand Down