@skyphusion/create-prism 1.2.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -4
- package/index.js +2 -2
- package/package.json +1 -1
- package/template/MIGRATIONS.md +30 -0
- package/template/README.md +29 -36
- package/template/docs/legal/INSTANCE-PRIVACY.md +11 -10
- package/template/public/app.js +2 -2
- package/template/public/url-safety.js +6 -6
- package/template/src/env.ts +27 -10
- package/template/src/routes/chat.ts +13 -6
- package/template/src/routes/projects.ts +5 -4
- package/template/src/routes/rag.ts +146 -65
- package/template/src/routes/shared.ts +5 -2
- package/template/src/skyphusion-search.ts +108 -0
- package/template/src/vector-id.ts +27 -0
- package/template/src/version.ts +1 -1
- package/template/tests/log-identity-guard.test.ts +88 -0
- package/template/tests/rag-retrieval-diagnostic.test.ts +89 -80
- package/template/tests/rag-vector-id.test.ts +154 -0
- package/template/tests/skyphusion-search.test.ts +144 -0
- package/template/tests/vectorize-rekey-vector-ids.test.ts +141 -0
- package/template/wrangler.example.toml +14 -9
- package/template/src/searxng.ts +0 -75
- package/template/tests/searxng.test.ts +0 -51
|
@@ -1,18 +1,14 @@
|
|
|
1
|
-
// The zero-join retrieval diagnostic (skyphusion-labs/fleet-chezmoi#1608).
|
|
1
|
+
// The zero-join retrieval diagnostic (skyphusion-labs/fleet-chezmoi#1608, prism#233).
|
|
2
2
|
//
|
|
3
|
-
// retrieveContext queries Vectorize globally
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// Vectorize result legitimately contains vector ids belonging to other tenants,
|
|
7
|
-
// and vector ids are minted as `${userEmail}:${docId}:${chunkIndex}`.
|
|
3
|
+
// With VEC_METADATA_FILTER off, retrieveContext queries Vectorize globally and scopes by user in the
|
|
4
|
+
// D1 join. So the raw Vectorize result can hold vector ids belonging to other users, and
|
|
5
|
+
// pre-prism#232 ids embed an email. The zero-join branch is where those ids sit next to two outputs:
|
|
8
6
|
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
// nothing derived from the shared index.
|
|
7
|
+
// - the string returned to the caller (fleet-chezmoi#1608): nothing derived from the shared index.
|
|
8
|
+
// - the operator log (prism#233): counts and opaque row ids only. No caller identity, no foreign
|
|
9
|
+
// identity, no vector id.
|
|
13
10
|
//
|
|
14
|
-
// Only env.AI / env.VEC / env.DB are stubbed
|
|
15
|
-
// Everything between them is the real shipped retrieveContext.
|
|
11
|
+
// Only env.AI / env.VEC / env.DB are stubbed. Everything between them is the shipped retrieveContext.
|
|
16
12
|
|
|
17
13
|
import { describe, it, expect, vi, afterEach } from "vitest";
|
|
18
14
|
import { retrieveContext } from "../src/routes/rag";
|
|
@@ -25,33 +21,41 @@ const FOREIGN_IDS = [
|
|
|
25
21
|
"bob@example.com:99:2",
|
|
26
22
|
];
|
|
27
23
|
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
// still fires if only the identity survives some future re-formatting.
|
|
24
|
+
// Neither output may contain any of these. Kept as the identity half of each id as well as the whole
|
|
25
|
+
// id, so the assertion still fires if only the identity survives some future re-formatting.
|
|
31
26
|
const FOREIGN_IDENTITIES = ["victim@example.com", "usr_0123456789abcdef01234567", "bob@example.com"];
|
|
27
|
+
const FORBIDDEN_IN_LOG = [CALLER, ...FOREIGN_IDS, ...FOREIGN_IDENTITIES];
|
|
32
28
|
|
|
33
|
-
|
|
34
|
-
|
|
29
|
+
type Census = { held: number; own: number } | "throw" | null;
|
|
30
|
+
|
|
31
|
+
function fakeEnv(census: Census = { held: 2, own: 0 }) {
|
|
32
|
+
const vecReturned: string[] = [];
|
|
33
|
+
const env = {
|
|
35
34
|
AI: {
|
|
36
35
|
run: async () => ({ shape: [1, 3], data: [[0.1, 0.2, 0.3]] }),
|
|
37
36
|
},
|
|
38
37
|
VEC: {
|
|
39
|
-
query: async () =>
|
|
40
|
-
|
|
41
|
-
|
|
38
|
+
query: async () => {
|
|
39
|
+
vecReturned.push(...FOREIGN_IDS);
|
|
40
|
+
return { matches: FOREIGN_IDS.map((id, i) => ({ id, score: 0.9 - i * 0.01 })) };
|
|
41
|
+
},
|
|
42
42
|
},
|
|
43
43
|
DB: {
|
|
44
44
|
prepare(sql: string) {
|
|
45
45
|
const isPrefs = sql.includes("user_prefs");
|
|
46
|
+
const isCensus = sql.includes("COUNT(*) AS held");
|
|
46
47
|
return {
|
|
47
48
|
bind() {
|
|
48
49
|
return {
|
|
49
|
-
// loadUserPrefs -> gateway credentials, so embedBatch proceeds.
|
|
50
50
|
async first() {
|
|
51
|
-
|
|
51
|
+
if (isPrefs) return { prefs_json: JSON.stringify({ gateway_id: "alice-gw" }) };
|
|
52
|
+
if (isCensus) {
|
|
53
|
+
if (census === "throw") throw new Error(`D1 down for ${CALLER}`);
|
|
54
|
+
return census;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
52
57
|
},
|
|
53
|
-
// The tenant-scoped join finds none of the
|
|
54
|
-
// which is the branch under test.
|
|
58
|
+
// The tenant-scoped join finds none of the matched vectors: the branch under test.
|
|
55
59
|
async all() {
|
|
56
60
|
return { results: [] };
|
|
57
61
|
},
|
|
@@ -61,82 +65,87 @@ function fakeEnv(): Env {
|
|
|
61
65
|
},
|
|
62
66
|
},
|
|
63
67
|
} as unknown as Env;
|
|
68
|
+
return { env, vecReturned };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function logged(warn: ReturnType<typeof vi.spyOn>): string {
|
|
72
|
+
return warn.mock.calls.map((c) => c.join(" ")).join("\n");
|
|
64
73
|
}
|
|
65
74
|
|
|
66
75
|
afterEach(() => {
|
|
67
76
|
vi.restoreAllMocks();
|
|
68
77
|
});
|
|
69
78
|
|
|
70
|
-
describe("retrieveContext zero-join
|
|
71
|
-
it("
|
|
72
|
-
|
|
73
|
-
const {
|
|
74
|
-
|
|
79
|
+
describe("retrieveContext zero-join: the caller-visible message", () => {
|
|
80
|
+
it("carries no foreign identity", async () => {
|
|
81
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
82
|
+
const { env } = fakeEnv();
|
|
83
|
+
const { chunks, error } = await retrieveContext(env, CALLER, "quarterly revenue");
|
|
75
84
|
expect(chunks).toEqual([]);
|
|
76
|
-
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
// The disclosure assertion runs FIRST so that it is the assertion that
|
|
80
|
-
// fires when the defect is present. With the pin first, driving the
|
|
81
|
-
// pre-fix code (888e6bb reversed) reddened this test on the pin's
|
|
82
|
-
// `toBe` line and short-circuited, so the loop below never executed:
|
|
83
|
-
// the suite detected the defect, but the assertion that names it had
|
|
84
|
-
// never been shown capable of failing.
|
|
85
|
-
for (const identity of FOREIGN_IDENTITIES) {
|
|
86
|
-
expect(error).not.toContain(identity);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// Pin the exact branch SECOND. This is the anti-vacuity control: on any
|
|
90
|
-
// earlier failure path ("embed failed: ...", "vectorize query failed:
|
|
91
|
-
// ...") the loop above passes for free, because those strings are also
|
|
92
|
-
// free of foreign identities and are not the case under test. Running it
|
|
93
|
-
// after preserves that guarantee while leaving the loop reachable.
|
|
85
|
+
// Disclosure assertion first, so it is the one that fires under the defect; the branch pin
|
|
86
|
+
// second, as the anti-vacuity control (earlier failure paths are also identity-free).
|
|
87
|
+
for (const identity of FOREIGN_IDENTITIES) expect(error).not.toContain(identity);
|
|
94
88
|
expect(error).toBe("No indexed documents matched the query.");
|
|
89
|
+
});
|
|
95
90
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
const
|
|
100
|
-
for (const identity of FOREIGN_IDENTITIES)
|
|
101
|
-
|
|
102
|
-
}
|
|
91
|
+
it("is scoped the same way with a project", async () => {
|
|
92
|
+
vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
93
|
+
const { env } = fakeEnv();
|
|
94
|
+
const { error } = await retrieveContext(env, CALLER, "quarterly revenue", 5, 42);
|
|
95
|
+
for (const identity of FOREIGN_IDENTITIES) expect(error).not.toContain(identity);
|
|
96
|
+
expect(error).toBe("No indexed documents in this project matched the query.");
|
|
103
97
|
});
|
|
98
|
+
});
|
|
104
99
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
// debuggable. The fix is a split, not a removal, and this is what would
|
|
108
|
-
// fail if a later cleanup "simplified" the console.warn away.
|
|
100
|
+
describe("retrieveContext zero-join: the operator log (prism#233)", () => {
|
|
101
|
+
it("carries no caller identity, no foreign identity and no vector id", async () => {
|
|
109
102
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
110
|
-
|
|
103
|
+
const { env, vecReturned } = fakeEnv();
|
|
104
|
+
await retrieveContext(env, CALLER, "quarterly revenue");
|
|
105
|
+
const log = logged(warn);
|
|
106
|
+
// Disclosure assertion first (see above).
|
|
107
|
+
for (const s of FORBIDDEN_IN_LOG) expect(log, s).not.toContain(s);
|
|
108
|
+
expect(log).not.toMatch(/@/);
|
|
109
|
+
// Anti-vacuity: the log was written, on this branch, after the identities were really fed in.
|
|
110
|
+
expect(log).toContain("zero-join matches=3");
|
|
111
|
+
expect(vecReturned).toEqual(FOREIGN_IDS);
|
|
112
|
+
});
|
|
111
113
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
114
|
+
it("keeps the diagnostic: counts say the vectors were written under another identity", async () => {
|
|
115
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
116
|
+
const { env } = fakeEnv({ held: 2, own: 0 });
|
|
117
|
+
await retrieveContext(env, CALLER, "quarterly revenue");
|
|
118
|
+
expect(logged(warn)).toContain("matches=3 held_by_caller=0 held_by_other_users=2 not_in_d1=1");
|
|
116
119
|
});
|
|
117
120
|
|
|
118
|
-
it("
|
|
121
|
+
it("with a project: opaque project id and the caller-owned count, still no identity", async () => {
|
|
119
122
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
120
|
-
const {
|
|
123
|
+
const { env } = fakeEnv({ held: 3, own: 3 });
|
|
124
|
+
await retrieveContext(env, CALLER, "quarterly revenue", 5, 42);
|
|
125
|
+
const log = logged(warn);
|
|
126
|
+
for (const s of FORBIDDEN_IN_LOG) expect(log, s).not.toContain(s);
|
|
127
|
+
expect(log).toContain("matches=3 project_id=42 held_by_caller=3 held_by_other_users=0 not_in_d1=0");
|
|
128
|
+
});
|
|
121
129
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
expect(
|
|
129
|
-
|
|
130
|
+
it("a failed census logs census=unavailable, and its error text (which names the caller) is not logged", async () => {
|
|
131
|
+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
132
|
+
const { env } = fakeEnv("throw");
|
|
133
|
+
await retrieveContext(env, CALLER, "quarterly revenue");
|
|
134
|
+
const log = logged(warn);
|
|
135
|
+
for (const s of FORBIDDEN_IN_LOG) expect(log, s).not.toContain(s);
|
|
136
|
+
expect(log).toContain("zero-join matches=3 census=unavailable");
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe("NEGATIVE CONTROL", () => {
|
|
141
|
+
it("the log check goes red on a line shaped like the pre-prism#233 diagnostic", () => {
|
|
142
|
+
const old = `Vectorize returned 3 matches but D1 join returned 0. user_email='${CALLER}', sample vector_ids=[${FOREIGN_IDS.join(", ")}].`;
|
|
143
|
+
expect(FORBIDDEN_IN_LOG.some((s) => old.includes(s))).toBe(true);
|
|
130
144
|
});
|
|
131
145
|
|
|
132
|
-
it("
|
|
133
|
-
// If FOREIGN_IDS were ever emptied, every not-toContain assertion above
|
|
134
|
-
// would pass while testing nothing.
|
|
146
|
+
it("the fixture really does supply foreign ids", () => {
|
|
135
147
|
expect(FOREIGN_IDS.length).toBeGreaterThan(0);
|
|
136
148
|
expect(FOREIGN_IDENTITIES.length).toBe(FOREIGN_IDS.length);
|
|
137
|
-
for (const id of FOREIGN_IDS)
|
|
138
|
-
expect(id).toContain(":");
|
|
139
|
-
expect(id.split(":")[0]).not.toBe(CALLER);
|
|
140
|
-
}
|
|
149
|
+
for (const id of FOREIGN_IDS) expect(id.split(":")[0]).not.toBe(CALLER);
|
|
141
150
|
});
|
|
142
151
|
});
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// prism#232: RAG vector ids must not carry the owner's identity.
|
|
2
|
+
//
|
|
3
|
+
// Both mint sites are driven through the shipped functions: ingestDocument (upload and ZIP import)
|
|
4
|
+
// and handleDiscordImport (project Discord import). Only env.AI / env.VEC / env.DB / env.R2 are
|
|
5
|
+
// stubbed, plus the request identity. The caller is an access-mode identity (a raw email), which is
|
|
6
|
+
// the case the issue is about.
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi } from "vitest";
|
|
9
|
+
|
|
10
|
+
const EMAIL = "alice.example@example.org";
|
|
11
|
+
|
|
12
|
+
vi.mock("../src/routes/shared", async (orig) => {
|
|
13
|
+
const real = await orig<typeof import("../src/routes/shared")>();
|
|
14
|
+
return { ...real, getUserEmail: async () => EMAIL };
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
import { ingestDocument } from "../src/routes/rag";
|
|
18
|
+
import { handleDiscordImport } from "../src/routes/projects";
|
|
19
|
+
import { mintVectorId, isOpaqueVectorId } from "../src/vector-id";
|
|
20
|
+
import { mintVectorId as scriptMint } from "../scripts/vectorize-rekey-vector-ids.mjs";
|
|
21
|
+
import type { Env } from "../src/env";
|
|
22
|
+
|
|
23
|
+
interface Upserted {
|
|
24
|
+
id: string;
|
|
25
|
+
metadata?: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Fake bindings: records every Vectorize upsert and every D1 statement with its bound args. */
|
|
29
|
+
function fakeEnv() {
|
|
30
|
+
const upserts: Upserted[] = [];
|
|
31
|
+
const statements: { sql: string; args: unknown[] }[] = [];
|
|
32
|
+
const stmt = (sql: string, args: unknown[] = []) => ({
|
|
33
|
+
sql,
|
|
34
|
+
args,
|
|
35
|
+
bind: (...a: unknown[]) => stmt(sql, a),
|
|
36
|
+
async first() {
|
|
37
|
+
statements.push({ sql, args });
|
|
38
|
+
if (sql.includes("user_prefs")) return { prefs_json: JSON.stringify({ gateway_id: "gw" }) };
|
|
39
|
+
if (sql.includes("RETURNING id")) return { id: 7, created_at: "2026-11-12 00:00:00" };
|
|
40
|
+
if (sql.includes("FROM projects")) return { id: 3 };
|
|
41
|
+
return null;
|
|
42
|
+
},
|
|
43
|
+
async run() {
|
|
44
|
+
statements.push({ sql, args });
|
|
45
|
+
return { meta: { changes: 1 } };
|
|
46
|
+
},
|
|
47
|
+
async all() {
|
|
48
|
+
statements.push({ sql, args });
|
|
49
|
+
return { results: [] };
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
const env = {
|
|
53
|
+
AI: {
|
|
54
|
+
run: async (_m: string, input: { text: string[] }) => ({
|
|
55
|
+
shape: [input.text.length, 3],
|
|
56
|
+
data: input.text.map(() => [0.1, 0.2, 0.3]),
|
|
57
|
+
}),
|
|
58
|
+
},
|
|
59
|
+
VEC: {
|
|
60
|
+
upsert: async (vs: Upserted[]) => {
|
|
61
|
+
upserts.push(...vs);
|
|
62
|
+
return { mutationId: "m" };
|
|
63
|
+
},
|
|
64
|
+
deleteByIds: async () => ({ mutationId: "m" }),
|
|
65
|
+
},
|
|
66
|
+
R2: { put: async () => ({}), delete: async () => {} },
|
|
67
|
+
DB: {
|
|
68
|
+
prepare: (sql: string) => stmt(sql),
|
|
69
|
+
batch: async (ss: { sql: string; args: unknown[] }[]) => {
|
|
70
|
+
for (const s of ss) statements.push({ sql: s.sql, args: s.args });
|
|
71
|
+
return ss.map(() => ({ meta: { changes: 1 } }));
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
} as unknown as Env;
|
|
75
|
+
const chunkRowVectorIds = () =>
|
|
76
|
+
statements.filter((s) => s.sql.includes("INSERT INTO chunks")).map((s) => String(s.args[4]));
|
|
77
|
+
return { env, upserts, chunkRowVectorIds };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The check under test. It must be able to go red: see the negative control below. */
|
|
81
|
+
function carriesIdentity(id: string, identity: string): boolean {
|
|
82
|
+
return id.includes(identity) || id.includes("@");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
describe("mintVectorId", () => {
|
|
86
|
+
it("is c_ plus 32 hex digits, unique per call, and carries no @", () => {
|
|
87
|
+
const ids = new Set(Array.from({ length: 200 }, () => mintVectorId()));
|
|
88
|
+
expect(ids.size).toBe(200);
|
|
89
|
+
for (const id of ids) {
|
|
90
|
+
expect(isOpaqueVectorId(id), id).toBe(true);
|
|
91
|
+
expect(id.length).toBe(34);
|
|
92
|
+
expect(id).not.toContain("@");
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("the re-key script mints the same format as the worker", () => {
|
|
97
|
+
expect(isOpaqueVectorId(scriptMint())).toBe(true);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
describe("NEGATIVE CONTROL: the identity check can go red", () => {
|
|
102
|
+
it("flags the pre-prism#232 id shape", () => {
|
|
103
|
+
expect(carriesIdentity(`${EMAIL}:7:0`, EMAIL)).toBe(true);
|
|
104
|
+
expect(isOpaqueVectorId(`${EMAIL}:7:0`)).toBe(false);
|
|
105
|
+
expect(carriesIdentity(mintVectorId(), EMAIL)).toBe(false);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe("ingestDocument (upload, ZIP import)", () => {
|
|
110
|
+
it("writes vector ids with no identity, the same id to D1, and keeps ownership in metadata", async () => {
|
|
111
|
+
const { env, upserts, chunkRowVectorIds } = fakeEnv();
|
|
112
|
+
const text = "Paragraph one about the shaft.\n\n".repeat(60);
|
|
113
|
+
const r = await ingestDocument(env, EMAIL, "notes.txt", "text/plain", new TextEncoder().encode(text));
|
|
114
|
+
expect(r.ok).toBe(true);
|
|
115
|
+
expect(upserts.length).toBeGreaterThan(1);
|
|
116
|
+
for (const v of upserts) {
|
|
117
|
+
expect(carriesIdentity(v.id, EMAIL), v.id).toBe(false);
|
|
118
|
+
expect(isOpaqueVectorId(v.id), v.id).toBe(true);
|
|
119
|
+
expect(v.metadata?.user_email).toBe(EMAIL);
|
|
120
|
+
}
|
|
121
|
+
expect(chunkRowVectorIds()).toEqual(upserts.map((v) => v.id));
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe("handleDiscordImport (project Discord import)", () => {
|
|
126
|
+
it("writes vector ids with no identity, the same id to D1, and keeps ownership in metadata", async () => {
|
|
127
|
+
const { env, upserts, chunkRowVectorIds } = fakeEnv();
|
|
128
|
+
const exportJson = {
|
|
129
|
+
guild: { id: "1", name: "G" },
|
|
130
|
+
channel: { id: "10", type: "GuildTextChat", category: "c", name: "general", topic: null },
|
|
131
|
+
messages: Array.from({ length: 6 }, (_, i) => ({
|
|
132
|
+
id: String(100 + i),
|
|
133
|
+
type: "Default",
|
|
134
|
+
timestamp: new Date(Date.UTC(2024, 0, 15, 12, i * 30)).toISOString(),
|
|
135
|
+
content: `message ${i} about the transit hub`,
|
|
136
|
+
author: { id: "a", name: "alice", discriminator: "0", nickname: null, isBot: false },
|
|
137
|
+
})),
|
|
138
|
+
};
|
|
139
|
+
const data = Buffer.from(JSON.stringify(exportJson)).toString("base64");
|
|
140
|
+
const req = new Request("https://x/api/projects/3/discord", {
|
|
141
|
+
method: "POST",
|
|
142
|
+
body: JSON.stringify({ filename: "export.json", data }),
|
|
143
|
+
});
|
|
144
|
+
const res = await handleDiscordImport(req, env, 3);
|
|
145
|
+
expect(res.status).toBeLessThan(300);
|
|
146
|
+
expect(upserts.length).toBeGreaterThan(0);
|
|
147
|
+
for (const v of upserts) {
|
|
148
|
+
expect(carriesIdentity(v.id, EMAIL), v.id).toBe(false);
|
|
149
|
+
expect(isOpaqueVectorId(v.id), v.id).toBe(true);
|
|
150
|
+
expect(v.metadata?.user_email).toBe(EMAIL);
|
|
151
|
+
}
|
|
152
|
+
expect(chunkRowVectorIds()).toEqual(upserts.map((v) => v.id));
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import type { Env } from "../src/env";
|
|
3
|
+
import { searchWeb } from "../src/routes/rag";
|
|
4
|
+
import { mapSearchChunks } from "../src/skyphusion-search";
|
|
5
|
+
|
|
6
|
+
const RPC_ERRORS = [
|
|
7
|
+
"empty_question",
|
|
8
|
+
"question_too_long",
|
|
9
|
+
"rate_limited",
|
|
10
|
+
"search_unavailable",
|
|
11
|
+
] as const;
|
|
12
|
+
|
|
13
|
+
const WIKI_HIT = {
|
|
14
|
+
query: {
|
|
15
|
+
search: [{ title: "Ada Lovelace", snippet: "Mathematician", pageid: 42 }],
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const CHUNK = {
|
|
20
|
+
text: " prism workers ",
|
|
21
|
+
score: 0.42,
|
|
22
|
+
item: {
|
|
23
|
+
key: "prism/README.md.txt",
|
|
24
|
+
metadata: { repo: "prism", path: "README.md" },
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function wikiResponse(): Response {
|
|
29
|
+
return new Response(JSON.stringify(WIKI_HIT), {
|
|
30
|
+
status: 200,
|
|
31
|
+
headers: { "content-type": "application/json" },
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function installWikipediaFetch() {
|
|
36
|
+
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
|
37
|
+
const url = typeof input === "string"
|
|
38
|
+
? input
|
|
39
|
+
: input instanceof URL
|
|
40
|
+
? input.toString()
|
|
41
|
+
: input.url;
|
|
42
|
+
if (!url.includes("https://en.wikipedia.org/w/api.php")) {
|
|
43
|
+
throw new Error(`unexpected global fetch: ${url}`);
|
|
44
|
+
}
|
|
45
|
+
return wikiResponse();
|
|
46
|
+
});
|
|
47
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
48
|
+
return fetchMock;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function binding(search: (question: string) => Promise<{ chunks: unknown[] }>): Env {
|
|
52
|
+
return { SEARCH: { search } } as unknown as Env;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
afterEach(() => {
|
|
56
|
+
vi.unstubAllGlobals();
|
|
57
|
+
vi.restoreAllMocks();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe("mapSearchChunks", () => {
|
|
61
|
+
it("maps a chunk to a github blob link", () => {
|
|
62
|
+
expect(mapSearchChunks([CHUNK], 5)).toEqual([{
|
|
63
|
+
title: "prism/README.md",
|
|
64
|
+
url: "https://github.com/skyphusion-labs/prism/blob/main/README.md",
|
|
65
|
+
snippet: "prism workers",
|
|
66
|
+
score: 0.42,
|
|
67
|
+
}]);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("drops a chunk whose path is not a safe corpus path", () => {
|
|
71
|
+
expect(mapSearchChunks([{
|
|
72
|
+
text: "nope",
|
|
73
|
+
item: { key: "prism/../etc/passwd", metadata: { repo: "prism", path: "../etc/passwd" } },
|
|
74
|
+
}], 5)).toEqual([]);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("searchWeb sources", () => {
|
|
79
|
+
it("binding returns hits", async () => {
|
|
80
|
+
const wiki = installWikipediaFetch();
|
|
81
|
+
const search = vi.fn(async (_question: string) => ({ chunks: [CHUNK] }));
|
|
82
|
+
const out = await searchWeb(binding(search), "prism workers");
|
|
83
|
+
expect(search).toHaveBeenCalledTimes(1);
|
|
84
|
+
expect(search.mock.calls[0]).toEqual(["prism workers"]);
|
|
85
|
+
expect(out.error).toBeNull();
|
|
86
|
+
expect(out.sources.web).toEqual({ status: "ok", count: 1 });
|
|
87
|
+
expect(out.sources.wikipedia.status).toBe("ok");
|
|
88
|
+
expect(out.sources.wikipedia.count).toBe(1);
|
|
89
|
+
expect(out.results.map((r) => r.source)).toEqual(["skyphusion-search", "wikipedia"]);
|
|
90
|
+
expect(out.results[0]).toMatchObject({
|
|
91
|
+
title: "prism/README.md",
|
|
92
|
+
url: "https://github.com/skyphusion-labs/prism/blob/main/README.md",
|
|
93
|
+
snippet: "prism workers",
|
|
94
|
+
});
|
|
95
|
+
expect(out.results[1]).toMatchObject({
|
|
96
|
+
title: "Ada Lovelace",
|
|
97
|
+
url: "https://en.wikipedia.org/?curid=42",
|
|
98
|
+
});
|
|
99
|
+
expect(wiki).toHaveBeenCalled();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it.each(RPC_ERRORS)("%s: web source failed, Wikipedia still answers", async (code) => {
|
|
103
|
+
const wiki = installWikipediaFetch();
|
|
104
|
+
const search = vi.fn(async () => {
|
|
105
|
+
throw new Error(code);
|
|
106
|
+
});
|
|
107
|
+
const out = await searchWeb(binding(search), "prism workers");
|
|
108
|
+
expect(search).toHaveBeenCalledTimes(1);
|
|
109
|
+
expect(out.sources.web).toEqual({ status: "failed", count: 0, error: code });
|
|
110
|
+
expect(out.error).toBe(code);
|
|
111
|
+
expect(out.sources.wikipedia).toEqual({ status: "ok", count: 1 });
|
|
112
|
+
expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
|
|
113
|
+
expect(wiki).toHaveBeenCalled();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("a thrown binding is failed and does not clear Wikipedia", async () => {
|
|
117
|
+
installWikipediaFetch();
|
|
118
|
+
const env = binding(async () => {
|
|
119
|
+
throw new Error("binding down");
|
|
120
|
+
});
|
|
121
|
+
const out = await searchWeb(env, "prism workers");
|
|
122
|
+
expect(out.sources.web).toEqual({ status: "failed", count: 0, error: "binding down" });
|
|
123
|
+
expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("binding absent is not a failure and not zero hits", async () => {
|
|
127
|
+
const wiki = installWikipediaFetch();
|
|
128
|
+
const out = await searchWeb({} as Env, "prism workers");
|
|
129
|
+
expect(out.sources.web).toEqual({ status: "absent", count: 0 });
|
|
130
|
+
expect(out.error).toBeNull();
|
|
131
|
+
expect(out.sources.wikipedia).toEqual({ status: "ok", count: 1 });
|
|
132
|
+
expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
|
|
133
|
+
expect(wiki).toHaveBeenCalled();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("an empty chunks array is zero hits, not a failure", async () => {
|
|
137
|
+
installWikipediaFetch();
|
|
138
|
+
const env = binding(async () => ({ chunks: [] }));
|
|
139
|
+
const out = await searchWeb(env, "prism workers");
|
|
140
|
+
expect(out.sources.web).toEqual({ status: "ok", count: 0 });
|
|
141
|
+
expect(out.error).toBeNull();
|
|
142
|
+
expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// scripts/vectorize-rekey-vector-ids.mjs (prism#232): which ids move, the add-before-remove order,
|
|
2
|
+
// gaps and conflicts, dry run, refusals, and that no id reaches the printed result.
|
|
3
|
+
|
|
4
|
+
import { describe, it, expect } from "vitest";
|
|
5
|
+
import {
|
|
6
|
+
client,
|
|
7
|
+
isEmailBearingId,
|
|
8
|
+
parseArgs,
|
|
9
|
+
rekey,
|
|
10
|
+
type LegacyRow,
|
|
11
|
+
type RekeyApi,
|
|
12
|
+
type Vec,
|
|
13
|
+
} from "../scripts/vectorize-rekey-vector-ids.mjs";
|
|
14
|
+
|
|
15
|
+
const OLD_A = "alice@example.org:1:0";
|
|
16
|
+
const OLD_B = "alice@example.org:1:1";
|
|
17
|
+
const PUBLIC_ID = "usr_0123456789abcdef01234567:2:0";
|
|
18
|
+
|
|
19
|
+
function fakeApi(opts: { rows?: LegacyRow[]; stored?: Vec[]; changes?: (rowId: number) => number; census?: () => Promise<{ total: number; legacy: number }> } = {}) {
|
|
20
|
+
const rows = opts.rows ?? [];
|
|
21
|
+
const stored = new Map((opts.stored ?? []).map((v) => [v.id, v]));
|
|
22
|
+
const log: string[] = [];
|
|
23
|
+
const d1 = new Map(rows.map((r) => [r.rowId, r.vectorId]));
|
|
24
|
+
const api: RekeyApi = {
|
|
25
|
+
census: opts.census ?? (async () => ({ total: rows.length + 1, legacy: rows.length })),
|
|
26
|
+
legacyRows: async () => rows,
|
|
27
|
+
repoint: async (_d, rowId, oldId, newId) => {
|
|
28
|
+
log.push(`repoint ${rowId}`);
|
|
29
|
+
const n = opts.changes ? opts.changes(rowId) : d1.get(rowId) === oldId ? 1 : 0;
|
|
30
|
+
if (n === 1) d1.set(rowId, newId);
|
|
31
|
+
return n;
|
|
32
|
+
},
|
|
33
|
+
getByIds: async (_i, ids) => ids.map((id) => stored.get(id)).filter((v): v is Vec => !!v),
|
|
34
|
+
upsert: async (_i, vs) => {
|
|
35
|
+
log.push(`upsert ${vs.length}`);
|
|
36
|
+
for (const v of vs) stored.set(v.id, v);
|
|
37
|
+
},
|
|
38
|
+
deleteByIds: async (_i, ids) => {
|
|
39
|
+
log.push(`delete ${ids.length}`);
|
|
40
|
+
for (const id of ids) stored.delete(id);
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
return { api, log, stored, d1 };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const vec = (id: string): Vec => ({ id, values: [0.1, 0.2], metadata: { user_email: "alice@example.org", document_id: 1 } });
|
|
47
|
+
const opts = { index: "ix", d1: "db", dryRun: false, batch: 20 };
|
|
48
|
+
|
|
49
|
+
describe("isEmailBearingId", () => {
|
|
50
|
+
it("selects the access-mode email form only", () => {
|
|
51
|
+
expect(isEmailBearingId(OLD_A)).toBe(true);
|
|
52
|
+
expect(isEmailBearingId(PUBLIC_ID)).toBe(false);
|
|
53
|
+
expect(isEmailBearingId("c_0123456789abcdef0123456789abcdef")).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("rekey", () => {
|
|
58
|
+
it("moves every email-bearing vector: same values and metadata, new opaque id, D1 repointed, old deleted", async () => {
|
|
59
|
+
const rows = [{ rowId: 1, vectorId: OLD_A }, { rowId: 2, vectorId: OLD_B }];
|
|
60
|
+
const { api, log, stored, d1 } = fakeApi({ rows, stored: [vec(OLD_A), vec(OLD_B)] });
|
|
61
|
+
const r = await rekey(api, opts);
|
|
62
|
+
expect(r.code).toBe(0);
|
|
63
|
+
expect(r.counts).toMatchObject({ legacy: 2, fetched: 2, rekeyed: 2, old_deleted: 2, gaps: 0, conflicts: 0 });
|
|
64
|
+
// Add before remove: the new vectors exist before D1 moves, and D1 moves before the old go.
|
|
65
|
+
expect(log).toEqual(["upsert 2", "repoint 1", "repoint 2", "delete 2"]);
|
|
66
|
+
expect([...stored.keys()].some((id) => id.includes("@"))).toBe(false);
|
|
67
|
+
for (const id of d1.values()) {
|
|
68
|
+
expect(id).toMatch(/^c_[0-9a-f]{32}$/);
|
|
69
|
+
expect(stored.get(id)?.values).toEqual([0.1, 0.2]);
|
|
70
|
+
expect(stored.get(id)?.metadata).toEqual({ user_email: "alice@example.org", document_id: 1 });
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("NEGATIVE CONTROL: a non-email id handed back by D1 is never touched", async () => {
|
|
75
|
+
const { api, log, stored } = fakeApi({ rows: [{ rowId: 9, vectorId: PUBLIC_ID }], stored: [vec(PUBLIC_ID)] });
|
|
76
|
+
const r = await rekey(api, opts);
|
|
77
|
+
expect(r.code).toBe(0);
|
|
78
|
+
expect(r.counts.legacy).toBe(0);
|
|
79
|
+
expect(log).toEqual([]);
|
|
80
|
+
expect(stored.has(PUBLIC_ID)).toBe(true);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("a D1 id with no vector is a GAP (exit 1), not a silent skip", async () => {
|
|
84
|
+
const { api } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }, { rowId: 2, vectorId: OLD_B }], stored: [vec(OLD_A)] });
|
|
85
|
+
const r = await rekey(api, opts);
|
|
86
|
+
expect(r.code).toBe(1);
|
|
87
|
+
expect(r.counts).toMatchObject({ gaps: 1, rekeyed: 1 });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("a row that changed under us is a CONFLICT: its new vector is deleted and the old one kept", async () => {
|
|
91
|
+
const { api, stored } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], stored: [vec(OLD_A)], changes: () => 0 });
|
|
92
|
+
const r = await rekey(api, opts);
|
|
93
|
+
expect(r.code).toBe(1);
|
|
94
|
+
expect(r.counts).toMatchObject({ conflicts: 1, rekeyed: 0, old_deleted: 0 });
|
|
95
|
+
expect([...stored.keys()]).toEqual([OLD_A]);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("dry run writes nothing but still counts", async () => {
|
|
99
|
+
const { api, log } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], stored: [vec(OLD_A)] });
|
|
100
|
+
const r = await rekey(api, { ...opts, dryRun: true });
|
|
101
|
+
expect(r.code).toBe(0);
|
|
102
|
+
expect(r.counts).toMatchObject({ legacy: 1, fetched: 1, rekeyed: 0 });
|
|
103
|
+
expect(log).toEqual([]);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("refuses (2) and writes nothing when D1 cannot be counted", async () => {
|
|
107
|
+
const { api, log } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], census: async () => { throw new Error("boom"); } });
|
|
108
|
+
const r = await rekey(api, opts);
|
|
109
|
+
expect(r.code).toBe(2);
|
|
110
|
+
expect(log).toEqual([]);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("the result carries counts only, never an id", async () => {
|
|
114
|
+
const { api } = fakeApi({ rows: [{ rowId: 1, vectorId: OLD_A }], stored: [vec(OLD_A)] });
|
|
115
|
+
const r = await rekey(api, opts);
|
|
116
|
+
expect(JSON.stringify(r)).not.toMatch(/@|c_[0-9a-f]{32}/);
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
describe("client", () => {
|
|
121
|
+
it("sends the repoint as a parameterized UPDATE guarded on the old id", async () => {
|
|
122
|
+
const seen: { url: string; body: unknown }[] = [];
|
|
123
|
+
const fetchImpl = (async (url: string, init: RequestInit) => {
|
|
124
|
+
seen.push({ url, body: JSON.parse(String(init.body)) });
|
|
125
|
+
return new Response(JSON.stringify({ success: true, result: [{ results: [], meta: { changes: 1 } }] }));
|
|
126
|
+
}) as unknown as typeof fetch;
|
|
127
|
+
const n = await client({ token: "t", accountId: "acc", fetchImpl }).repoint("db", 5, OLD_A, "c_new");
|
|
128
|
+
expect(n).toBe(1);
|
|
129
|
+
expect(seen[0].url).toBe("https://api.cloudflare.com/client/v4/accounts/acc/d1/database/db/query");
|
|
130
|
+
expect(seen[0].body).toEqual({ sql: "UPDATE chunks SET vector_id = ? WHERE id = ? AND vector_id = ?", params: ["c_new", 5, OLD_A] });
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
describe("parseArgs", () => {
|
|
135
|
+
it("requires --index and --d1 and bounds --batch", () => {
|
|
136
|
+
expect(() => parseArgs(["--d1", "x"])).toThrow(/--index/);
|
|
137
|
+
expect(() => parseArgs(["--index", "x"])).toThrow(/--d1/);
|
|
138
|
+
expect(() => parseArgs(["--index", "x", "--d1", "y", "--batch", "0"])).toThrow(/--batch/);
|
|
139
|
+
expect(parseArgs(["--index", "x", "--d1", "y", "--dry-run"])).toMatchObject({ dryRun: true, batch: 20 });
|
|
140
|
+
});
|
|
141
|
+
});
|