Skip to content
Open
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: 8 additions & 7 deletions pkgs/atlas-search/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@ and caches the result **indefinitely** (no TTL/eviction in v1).
- `src/service.ts` — calls to `fleet serve search`
(`POST /v1/embed`, `POST /v1/search`) via the
`atlas-search.security.cab` tunnel hostname + Cloudflare
Access service token. The service enforces this client's
`personal` tier ceiling; the Worker holds no Turso credentials
and keeps no shard list (new `atlas-core-*` databases join the
fan-out through the service's manifest discovery).
Access service token. Search requests explicitly state the
`hosted-per-user` disclosure context and this client's `personal`
tier ceiling; the Worker holds no Turso credentials and keeps no
shard list (new `atlas-core-*` databases join the fan-out through
the service's manifest discovery).
- `src/key.ts` — DO key = sha256 over the normalized query plus
the pinned config fingerprint (ceiling, model revision, vector
table, k). A cached entry is never served across ceilings or
embedding spaces.
the disclosure context and pinned config fingerprint (ceiling,
model revision, vector table, k). A cached entry is never served
across contexts, ceilings or embedding spaces.

## Endpoints

Expand Down
10 changes: 5 additions & 5 deletions pkgs/atlas-search/worker/src/cache_do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* forever.
*/
import { embedQuery, searchService, type ServiceEnv } from "./service";
import { EMBED_DIMS, EMBED_MODEL } from "./space";
import { EMBED_DIMS, EMBED_MODEL, type DisclosureContext } from "./space";

interface EntryRow {
[key: string]: SqlStorageValue;
Expand Down Expand Up @@ -79,8 +79,8 @@ export class QueryCache {
const url = new URL(req.url);
try {
if (req.method === "POST" && url.pathname === "/query") {
const body = (await req.json()) as { query: string; k: number };
return Response.json(await this.query(body.query, body.k));
const body = (await req.json()) as { query: string; k: number; context: DisclosureContext };
return Response.json(await this.query(body.query, body.k, body.context));
}
if (req.method === "GET" && url.pathname === "/inspect") {
return Response.json(this.inspect());
Expand All @@ -97,7 +97,7 @@ export class QueryCache {
}
}

private async query(query: string, k: number): Promise<QueryOutcome> {
private async query(query: string, k: number, context: DisclosureContext): Promise<QueryOutcome> {
let row = this.row();
if (row?.result_json) {
const stored = row.result_json;
Expand Down Expand Up @@ -129,7 +129,7 @@ export class QueryCache {
row = this.row()!;
}

const { result, ms } = await searchService(this.env, query, k);
const { result, ms } = await searchService(this.env, query, k, context);
const searchedAt = new Date().toISOString();
this.state.storage.sql.exec(
"UPDATE entry SET result_json = ?, searched_at = ?, search_ms = ? WHERE id = 1",
Expand Down
9 changes: 5 additions & 4 deletions pkgs/atlas-search/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import { readTextUpTo } from "./body";
import { QueryCache } from "./cache_do";
import { normalizeQuery, queryKey } from "./key";
import { DISCLOSURE_CONTEXT } from "./space";

export { QueryCache };

Expand Down Expand Up @@ -96,12 +97,12 @@ export default {
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 key = await queryKey({ q: query, k, context: DISCLOSURE_CONTEXT });
const stub = env.QUERY_CACHE.get(env.QUERY_CACHE.idFromName(key));
const resp = await stub.fetch("https://do/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query, k }),
body: JSON.stringify({ query, k, context: DISCLOSURE_CONTEXT }),
});
const payload = (await resp.json()) as Record<string, unknown>;
if (!resp.ok) return Response.json(payload, { status: resp.status });
Expand All @@ -121,7 +122,7 @@ export default {
// keyed or reach a Durable Object.
if (!query) return errorJson(400, "bad_request", "query must not be empty");
const k = clampK(Number(url.searchParams.get("k") ?? DEFAULT_K));
const key = await queryKey({ q: query, k });
const key = await queryKey({ q: query, k, context: DISCLOSURE_CONTEXT });
const stub = env.QUERY_CACHE.get(env.QUERY_CACHE.idFromName(key));
const resp = await stub.fetch("https://do/inspect");
const meta = (await resp.json()) as Record<string, unknown>;
Expand Down Expand Up @@ -151,7 +152,7 @@ export default {
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 key = await queryKey({ q: query, k, context: DISCLOSURE_CONTEXT });
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 };
Expand Down
6 changes: 4 additions & 2 deletions pkgs/atlas-search/worker/src/key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
* different ceiling or space (the same rule the search service
* applies to its job dedupe).
*/
import { CEILING, MODEL_REV, VEC_TABLE } from "./space";
import { CEILING, MODEL_REV, VEC_TABLE, type DisclosureContext } from "./space";

export const KEY_SCHEMA = 1;
export const KEY_SCHEMA = 2;

/** Trim, NFC, and collapse every whitespace run to one space. */
export function normalizeQuery(q: string): string {
Expand All @@ -20,13 +20,15 @@ export function normalizeQuery(q: string): string {
export interface KeyParts {
q: string;
k: number;
context: DisclosureContext;
}

/** The canonical key material (field order is part of the key). */
export function keyMaterial(parts: KeyParts): string {
return JSON.stringify({
v: KEY_SCHEMA,
q: parts.q,
context: parts.context,
ceiling: CEILING,
model_rev: MODEL_REV,
vec_table: VEC_TABLE,
Expand Down
4 changes: 3 additions & 1 deletion pkgs/atlas-search/worker/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* service token (the two `CF-Access-*` headers); the service's own
* client bearer token rides `Authorization`.
*/
import { CEILING, validateEmbed, type EmbedResponse } from "./space";
import { CEILING, validateEmbed, type DisclosureContext, type EmbedResponse } from "./space";

export interface ServiceEnv {
SERVICE_BASE: string;
Expand Down Expand Up @@ -81,12 +81,14 @@ export async function searchService(
env: ServiceEnv,
query: string,
k: number,
context: DisclosureContext,
): Promise<{ result: Record<string, unknown>; ms: number }> {
const t0 = Date.now();
const raw: unknown = await postJson(env, "/v1/search", {
query,
ceiling: CEILING,
k,
context,
});
// The response is untrusted until validated, exactly like the embed
// door (validateEmbed in space.ts): a JSON null 200 cannot even be
Expand Down
4 changes: 4 additions & 0 deletions pkgs/atlas-search/worker/src/space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export const VEC_TABLE = "vec_snowflake_m_v2_768_f32";
/** The one ceiling this surface may ever search under. */
export const CEILING = "personal";

/** This hosted per-user surface always searches in its explicit disclosure context. */
export const DISCLOSURE_CONTEXT = "hosted-per-user" as const;
export type DisclosureContext = "fleet-internal" | "hosted-per-user" | "public-surface" | "local-owner";

export interface EmbedResponse {
model: string;
dims: number;
Expand Down
54 changes: 47 additions & 7 deletions pkgs/atlas-search/worker/test/key.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,59 @@ describe("queryKey", () => {
// field by field — a drift in key.ts's field order, names, or
// pinned constants fails this test.
const canonical =
`{"v":1,"q":"alpha beta","ceiling":"${CEILING}",` +
`{"v":2,"q":"alpha beta","context":"hosted-per-user","ceiling":"${CEILING}",` +
`"model_rev":"${MODEL_REV}","vec_table":"${VEC_TABLE}","k":10}`;
expect(keyMaterial({ q: "alpha beta", k: 10 })).toBe(canonical);
expect(keyMaterial({ q: "alpha beta", k: 10, context: "hosted-per-user" })).toBe(canonical);
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
const expected = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
expect(await queryKey({ q: "alpha beta", k: 10 })).toBe(expected);
expect(await queryKey({ q: "alpha beta", k: 10, context: "hosted-per-user" })).toBe(expected);
});

it("differs across query and across k (no cross-config serving)", async () => {
const a = await queryKey({ q: "alpha", k: 10 });
const b = await queryKey({ q: "beta", k: 10 });
const c = await queryKey({ q: "alpha", k: 5 });
const a = await queryKey({ q: "alpha", k: 10, context: "hosted-per-user" });
const b = await queryKey({ q: "beta", k: 10, context: "hosted-per-user" });
const c = await queryKey({ q: "alpha", k: 5, context: "hosted-per-user" });
expect(a).not.toBe(b);
expect(a).not.toBe(c);
});
});

it("never shares a result key across disclosure contexts", async () => {
const keyForContext = (context: "hosted-per-user" | "public-surface") =>
queryKey({ q: "same query", k: 10, context });
expect(await keyForContext("hosted-per-user")).not.toBe(await keyForContext("public-surface"));
Comment thread
dezren39 marked this conversation as resolved.
Resolved
});

it("never shares a result key across disclosure contexts for generated queries and depths", async () => {
// Generated context-isolation coverage: for each generated (query, k),
// all four disclosure contexts must produce distinct cache keys, so a
// cached entry can never be served across a disclosure boundary.
// Oracle: the key digest itself — the context is part of the key
// material, so distinct contexts must yield distinct digests.
// Deterministic mulberry32 generator (fixed seed); no new dependency.
const contexts = ["fleet-internal", "hosted-per-user", "public-surface", "local-owner"] as const;
let seed = 0x21057;
const next = () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
const words = ["alpha", "beta", "fleet", "queue", "café", "naïve", "x", "deep", "search", "42", "MUSE"];
const spaces = [" ", " ", "\t", "\n", " \t "];
const pick = <T,>(xs: readonly T[]): T => xs[Math.floor(next() * xs.length)];
for (let i = 0; i < 64; i++) {
const wordCount = 1 + Math.floor(next() * 4);
let q = "";
for (let w = 0; w < wordCount; w++) {
if (w > 0) q += pick(spaces);
const word = pick(words);
q += next() < 0.25 ? word.toUpperCase() : word;
}
if (next() < 0.5) q = pick(spaces) + q;
if (next() < 0.5) q = q + pick(spaces);
const k = 1 + Math.floor(next() * 50);
const keys = await Promise.all(contexts.map((context) => queryKey({ q, k, context })));
expect(new Set(keys).size).toBe(contexts.length);
}
});
});
13 changes: 12 additions & 1 deletion pkgs/atlas-search/worker/test/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { EMBED_DIMS, EMBED_MODEL } from "../src/space";

const GATE = { Authorization: "Bearer test-gate" };
const counts = { embed: 0, search: 0 };
const forwardedSearchBodies: Record<string, unknown>[] = [];

function embedReply(space: "good" | "bad") {
return () => {
Expand All @@ -30,8 +31,9 @@ function embedReply(space: "good" | "bad") {
};
}

function searchReply() {
function searchReply({ body }: { body: string }) {
counts.search++;
forwardedSearchBodies.push(JSON.parse(body) as Record<string, unknown>);
return {
statusCode: 200,
data: JSON.stringify({
Expand Down Expand Up @@ -102,6 +104,15 @@ describe("atlas-search worker", () => {
expect(counts.embed).toBe(embedBefore);
});

it("states the hosted-per-user disclosure context on the forwarded search request", async () => {
const before = forwardedSearchBodies.length;
const resp = await search({ query: "disclosure context request" });
expect(resp.status).toBe(200);
expect(forwardedSearchBodies.slice(before)).toEqual([
{ query: "disclosure context request", ceiling: "personal", k: 10, context: "hosted-per-user" },
]);
});

it("miss embeds + fans out once; the repeat is a DO hit, byte-identical", async () => {
// Cache-hit identity oracle: the upstream call counters. The
// second request (same normalized query, messier whitespace)
Expand Down