@malloy-publisher/server 0.0.230 → 0.0.232

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.
Files changed (79) hide show
  1. package/README.docker.md +4 -0
  2. package/dist/app/api-doc.yaml +74 -3
  3. package/dist/app/assets/{EnvironmentPage-wa_EPkwK.js → EnvironmentPage-DXEaZIPx.js} +1 -1
  4. package/dist/app/assets/{HomePage-jnCrupQp.js → HomePage-kofsqpZt.js} +1 -1
  5. package/dist/app/assets/{LightMode-DYbwNULZ.js → LightMode-CNhIlIlJ.js} +1 -1
  6. package/dist/app/assets/{MainPage-CuJLrPNI.js → MainPage-Bgqo8jCy.js} +1 -1
  7. package/dist/app/assets/{MaterializationsPage-D_67x2ee.js → MaterializationsPage-CgBlgGz2.js} +1 -1
  8. package/dist/app/assets/{ModelPage-D5JtAWqR.js → ModelPage-B0TjoDtf.js} +1 -1
  9. package/dist/app/assets/{PackagePage-BRwtqUSG.js → PackagePage-BL8vnFj1.js} +1 -1
  10. package/dist/app/assets/{RouteError-CBNNrnSD.js → RouteError-BzPby0X2.js} +1 -1
  11. package/dist/app/assets/{ThemeEditorPage-CTCeBneA.js → ThemeEditorPage-CTEP_9r3.js} +1 -1
  12. package/dist/app/assets/{WorkbookPage-SN6f1RBm.js → WorkbookPage-BwM3BmKw.js} +1 -1
  13. package/dist/app/assets/{core-Dp3q5Ieu.es-CD5FvM2s.js → core-CK68iv6w.es-CpRxXBt7.js} +1 -1
  14. package/dist/app/assets/{index-C_tJstcx.js → index-B33zGctF.js} +15 -15
  15. package/dist/app/assets/{index-DU4r7GdU.js → index-BabP-V-S.js} +346 -321
  16. package/dist/app/assets/{index-B3Nn8Vm2.js → index-BkiWKaAF.js} +266 -265
  17. package/dist/app/assets/{index-BLCx1EdC.js → index-CmkW1MiE.js} +1 -1
  18. package/dist/app/assets/{index-CfmBVB6M.js → index-tXJXwdyj.js} +1 -1
  19. package/dist/app/index.html +1 -1
  20. package/dist/instrumentation.mjs +2 -0
  21. package/dist/package_load_worker.mjs +11 -1
  22. package/dist/server.mjs +3186 -433
  23. package/package.json +12 -12
  24. package/scripts/bake-duckdb-extensions.js +4 -1
  25. package/src/config.spec.ts +39 -0
  26. package/src/config.ts +135 -0
  27. package/src/controller/materialization.controller.spec.ts +62 -0
  28. package/src/controller/materialization.controller.ts +15 -0
  29. package/src/controller/package.controller.spec.ts +6 -0
  30. package/src/controller/package.controller.ts +7 -2
  31. package/src/errors.ts +19 -0
  32. package/src/logger.spec.ts +18 -1
  33. package/src/logger.ts +3 -1
  34. package/src/materialization_metrics.spec.ts +89 -4
  35. package/src/materialization_metrics.ts +155 -5
  36. package/src/mcp/skills/skills_bundle.json +1 -1
  37. package/src/mcp/tools/embedding_index.spec.ts +1236 -0
  38. package/src/mcp/tools/embedding_index.ts +808 -0
  39. package/src/mcp/tools/get_context_eval.ts +194 -45
  40. package/src/mcp/tools/get_context_tool.spec.ts +295 -2
  41. package/src/mcp/tools/get_context_tool.ts +159 -10
  42. package/src/pg_helpers.spec.ts +201 -0
  43. package/src/pg_helpers.ts +44 -5
  44. package/src/server.ts +24 -0
  45. package/src/service/build_plan.spec.ts +128 -2
  46. package/src/service/build_plan.ts +239 -17
  47. package/src/service/connection.ts +263 -7
  48. package/src/service/connection_config.spec.ts +48 -0
  49. package/src/service/connection_config.ts +21 -8
  50. package/src/service/connection_federation.spec.ts +184 -0
  51. package/src/service/embedding_provider.spec.ts +329 -0
  52. package/src/service/embedding_provider.ts +236 -0
  53. package/src/service/environment.ts +274 -12
  54. package/src/service/environment_store.spec.ts +678 -3
  55. package/src/service/environment_store.ts +449 -33
  56. package/src/service/environment_store_clone.spec.ts +350 -0
  57. package/src/service/manifest_loader.spec.ts +68 -13
  58. package/src/service/manifest_loader.ts +67 -19
  59. package/src/service/materialization_build_session.spec.ts +435 -0
  60. package/src/service/materialization_build_session.ts +681 -0
  61. package/src/service/materialization_eligibility.spec.ts +158 -0
  62. package/src/service/materialization_eligibility.ts +305 -0
  63. package/src/service/materialization_serve_transform.spec.ts +1003 -0
  64. package/src/service/materialization_serve_transform.ts +779 -0
  65. package/src/service/materialization_service.spec.ts +774 -7
  66. package/src/service/materialization_service.ts +1107 -42
  67. package/src/service/materialization_test_fixtures.ts +7 -0
  68. package/src/service/model.spec.ts +207 -0
  69. package/src/service/model.ts +540 -52
  70. package/src/service/model_storage_serve.spec.ts +193 -0
  71. package/src/service/model_storage_serve_joins.spec.ts +193 -0
  72. package/src/service/package.spec.ts +196 -0
  73. package/src/service/package.ts +385 -17
  74. package/src/service/persistence_policy.spec.ts +109 -0
  75. package/src/storage/duckdb/schema.ts +37 -0
  76. package/tests/fixtures/xlsx/database.xlsx +0 -0
  77. package/tests/integration/first_boot/readiness_line.integration.spec.ts +177 -0
  78. package/tests/integration/materialization/manifest_binding.integration.spec.ts +104 -0
  79. package/tests/integration/mcp/mcp_get_context_semantic.integration.spec.ts +235 -0
@@ -1,22 +1,34 @@
1
1
  /**
2
- * Lexical-baseline eval for malloy_getContext.
2
+ * Retrieval eval for malloy_getContext: lexical baseline vs the optional
3
+ * embedding-backed semantic mode.
3
4
  *
4
5
  * Runs a labeled set of plain-English queries against the live MCP endpoint
5
- * and reports recall@K: whether the expected entity appears in the top-K results.
6
- * This establishes the lexical (lunr/BM25) baseline so retrieval quality is
7
- * measurable; an embeddings comparison is deferred to if/when an embedding
8
- * provider is added (see the EPC eval risk).
6
+ * and reports recall@K: whether the expected entity appears in the top-K
7
+ * results. Each case is labeled with the retrieval mode the server reported
8
+ * (`semantic` / `lexical`; servers without an embedding provider report no
9
+ * mode and run the lexical baseline).
10
+ *
11
+ * A/B: run once against a server started WITHOUT `EMBEDDING_API_KEY`
12
+ * (lexical baseline), then once against a server started with it, and
13
+ * compare the two summaries. The cases marked `gap` share no tokens with
14
+ * their target entity's name or docs, so the lexical run is expected to
15
+ * miss them and the semantic run to hit them.
9
16
  *
10
17
  * bun run packages/server/src/mcp/tools/get_context_eval.ts [K]
11
18
  *
12
- * Targets MCP_URL (default http://localhost:4040/mcp) over the demo
13
- * environment (EVAL_ENV, default "samples"); start the server first.
19
+ * Targets MCP_URL (default http://localhost:4040/mcp); start the server
20
+ * first. Cases cover the bundled `examples` environment (storefront), so
21
+ * the default config works out of the box, plus the classic ecommerce/faa
22
+ * cases for a malloy-samples config (`samples` environment); cases whose
23
+ * environment is not served are skipped, not counted as misses.
14
24
  */
15
25
 
16
26
  interface EvalCase {
27
+ env: string;
17
28
  pkg: string;
18
29
  query: string;
19
30
  expect: string; // substring expected in a top-K result name (case-insensitive)
31
+ gap?: boolean; // true = no token overlap; lexical is expected to miss
20
32
  }
21
33
 
22
34
  interface ResultEntity {
@@ -25,34 +37,108 @@ interface ResultEntity {
25
37
  source?: string | null;
26
38
  }
27
39
 
28
- // Ground truth verified against the demo packages (ecommerce, faa).
40
+ interface GetContextPayload {
41
+ retrieval?: string;
42
+ results?: ResultEntity[];
43
+ error?: string;
44
+ }
45
+
46
+ // Ground truth verified against the bundled examples (storefront) and the
47
+ // malloy-samples demo packages (ecommerce, faa).
29
48
  const CASES: EvalCase[] = [
49
+ // examples/storefront: served by the default config, works out of the box.
50
+ {
51
+ env: "examples",
52
+ pkg: "storefront",
53
+ query: "revenue by product category",
54
+ expect: "category",
55
+ },
56
+ {
57
+ env: "examples",
58
+ pkg: "storefront",
59
+ query: "top selling products",
60
+ expect: "top_products",
61
+ },
62
+ {
63
+ env: "examples",
64
+ pkg: "storefront",
65
+ query: "monthly sales trend",
66
+ expect: "sales_by_month",
67
+ },
68
+ // Token-gap cases: no word here appears in the entity's name or #(doc)
69
+ // text, so a token-based index misses them; embeddings should not.
70
+ {
71
+ env: "examples",
72
+ pkg: "storefront",
73
+ query: "how much money did we make",
74
+ expect: "total_sales",
75
+ gap: true,
76
+ },
30
77
  {
78
+ env: "examples",
79
+ pkg: "storefront",
80
+ query: "refund percentage",
81
+ expect: "return_rate",
82
+ gap: true,
83
+ },
84
+ // malloy-samples (needs a config serving them as environment "samples").
85
+ {
86
+ env: "samples",
31
87
  pkg: "ecommerce",
32
88
  query: "revenue by product category",
33
89
  expect: "category",
34
90
  },
35
- { pkg: "ecommerce", query: "total sales revenue", expect: "total_sales" },
36
- { pkg: "ecommerce", query: "customer state location", expect: "state" },
37
- { pkg: "ecommerce", query: "order count", expect: "order_count" },
38
- { pkg: "ecommerce", query: "product brand", expect: "brand" },
39
- { pkg: "faa", query: "flights by carrier", expect: "carrier" },
40
- { pkg: "faa", query: "airport", expect: "airport" },
41
- { pkg: "faa", query: "aircraft model", expect: "aircraft" },
42
- // Known lexical gap: the field is "dep_delay", which does not share tokens with
43
- // "departure delay", so a token-based index misses it. Kept to surface the gap.
44
- { pkg: "faa", query: "departure delay", expect: "delay" },
91
+ {
92
+ env: "samples",
93
+ pkg: "ecommerce",
94
+ query: "total sales revenue",
95
+ expect: "total_sales",
96
+ },
97
+ {
98
+ env: "samples",
99
+ pkg: "ecommerce",
100
+ query: "customer state location",
101
+ expect: "state",
102
+ },
103
+ {
104
+ env: "samples",
105
+ pkg: "ecommerce",
106
+ query: "order count",
107
+ expect: "order_count",
108
+ },
109
+ {
110
+ env: "samples",
111
+ pkg: "ecommerce",
112
+ query: "product brand",
113
+ expect: "brand",
114
+ },
115
+ {
116
+ env: "samples",
117
+ pkg: "faa",
118
+ query: "flights by carrier",
119
+ expect: "carrier",
120
+ },
121
+ { env: "samples", pkg: "faa", query: "airport", expect: "airport" },
122
+ { env: "samples", pkg: "faa", query: "aircraft model", expect: "aircraft" },
123
+ // The original lexical-gap case: the field is "dep_delay", which shares
124
+ // no tokens with "departure delay".
125
+ {
126
+ env: "samples",
127
+ pkg: "faa",
128
+ query: "departure delay",
129
+ expect: "delay",
130
+ gap: true,
131
+ },
45
132
  ];
46
133
 
47
134
  const ENDPOINT = process.env.MCP_URL || "http://localhost:4040/mcp";
48
- const EVAL_ENV = process.env.EVAL_ENV || "samples";
49
135
  const K = Number(process.argv[2] || 5);
136
+ const WARMUP_ATTEMPTS = 15;
137
+ const WARMUP_DELAY_MS = 2_000;
50
138
 
51
- async function getContext(
52
- pkg: string,
53
- query: string,
54
- limit: number,
55
- ): Promise<ResultEntity[]> {
139
+ async function callGetContext(
140
+ args: Record<string, unknown>,
141
+ ): Promise<GetContextPayload> {
56
142
  const res = await fetch(ENDPOINT, {
57
143
  method: "POST",
58
144
  headers: {
@@ -63,36 +149,91 @@ async function getContext(
63
149
  jsonrpc: "2.0",
64
150
  id: 1,
65
151
  method: "tools/call",
66
- params: {
67
- name: "malloy_getContext",
68
- arguments: {
69
- environmentName: EVAL_ENV,
70
- packageName: pkg,
71
- query,
72
- limit,
73
- },
74
- },
152
+ params: { name: "malloy_getContext", arguments: args },
75
153
  }),
76
154
  });
77
155
  const text = await res.text();
78
156
  const dataLine = text.split("\n").find((l) => l.startsWith("data: "));
79
- if (!dataLine) return [];
157
+ if (!dataLine) return { results: [] };
80
158
  const msg = JSON.parse(dataLine.slice(6)) as {
81
159
  result?: { content?: { resource?: { text?: string } }[] };
82
160
  };
83
161
  const payloadText = msg.result?.content?.[0]?.resource?.text;
84
- if (!payloadText) return [];
85
- const payload = JSON.parse(payloadText) as { results?: ResultEntity[] };
86
- return payload.results ?? [];
162
+ if (!payloadText) return { results: [] };
163
+ return JSON.parse(payloadText) as GetContextPayload;
164
+ }
165
+
166
+ /** True when the environment exists on the server (tier-2 listing works). */
167
+ async function environmentServed(env: string): Promise<boolean> {
168
+ const payload = await callGetContext({ environmentName: env });
169
+ return payload.error === undefined;
170
+ }
171
+
172
+ /**
173
+ * On a semantic-capable server the first query against a package kicks off
174
+ * the embedding sync and answers lexically; poll until the mode flips (or
175
+ * give up and report whatever mode the server settles on).
176
+ */
177
+ async function warmUp(env: string, pkg: string): Promise<string | undefined> {
178
+ let mode: string | undefined;
179
+ for (let attempt = 0; attempt < WARMUP_ATTEMPTS; attempt++) {
180
+ const payload = await callGetContext({
181
+ environmentName: env,
182
+ packageName: pkg,
183
+ query: "warm up",
184
+ limit: 1,
185
+ });
186
+ mode = payload.retrieval;
187
+ // No marker: the server has no embedding provider configured, so
188
+ // there is nothing to warm up.
189
+ if (mode === undefined || mode === "semantic") return mode;
190
+ await new Promise((resolve) => setTimeout(resolve, WARMUP_DELAY_MS));
191
+ }
192
+ return mode;
87
193
  }
88
194
 
89
195
  async function main(): Promise<void> {
90
196
  console.log(
91
- `get_context lexical baseline, recall@${K} (endpoint ${ENDPOINT})\n`,
197
+ `get_context retrieval eval, recall@${K} (endpoint ${ENDPOINT})\n`,
92
198
  );
199
+
200
+ const servedEnvs = new Map<string, boolean>();
201
+ for (const env of new Set(CASES.map((c) => c.env))) {
202
+ servedEnvs.set(env, await environmentServed(env));
203
+ }
204
+ for (const [env, served] of servedEnvs) {
205
+ if (!served) {
206
+ console.log(
207
+ ` [SKIP] environment "${env}" is not served; skipping its cases`,
208
+ );
209
+ }
210
+ }
211
+
212
+ const warmed = new Set<string>();
93
213
  let hits = 0;
214
+ let scored = 0;
215
+ const modesSeen = new Set<string>();
216
+
94
217
  for (const c of CASES) {
95
- const results = await getContext(c.pkg, c.query, K);
218
+ if (!servedEnvs.get(c.env)) continue;
219
+
220
+ const pkgKey = `${c.env}/${c.pkg}`;
221
+ if (!warmed.has(pkgKey)) {
222
+ warmed.add(pkgKey);
223
+ await warmUp(c.env, c.pkg);
224
+ }
225
+
226
+ const payload = await callGetContext({
227
+ environmentName: c.env,
228
+ packageName: c.pkg,
229
+ query: c.query,
230
+ limit: K,
231
+ });
232
+ const results = payload.results ?? [];
233
+ const mode = payload.retrieval ?? "lexical (no provider)";
234
+ modesSeen.add(mode);
235
+
236
+ scored++;
96
237
  const rank = results.findIndex((r) =>
97
238
  r.name.toLowerCase().includes(c.expect.toLowerCase()),
98
239
  );
@@ -104,20 +245,28 @@ async function main(): Promise<void> {
104
245
  .map((r) => `${r.kind}:${r.name}`)
105
246
  .join(", ") || "(none)";
106
247
  const tag = hit ? `HIT@${rank + 1}` : "MISS ";
107
- console.log(` [${tag}] ${c.pkg} / "${c.query}" (want ~${c.expect})`);
248
+ const gap = c.gap ? " [gap]" : "";
249
+ console.log(
250
+ ` [${tag}] [${mode}] ${c.env}/${c.pkg} / "${c.query}" (want ~${c.expect})${gap}`,
251
+ );
108
252
  console.log(` top: ${top}`);
109
253
  }
110
- const pct = ((hits / CASES.length) * 100).toFixed(0);
111
- console.log(`\nrecall@${K}: ${hits}/${CASES.length} (${pct}%)`);
254
+
255
+ if (scored === 0) {
256
+ console.log("\nNo cases ran: no listed environment is served.");
257
+ process.exit(1);
258
+ }
259
+ const pct = ((hits / scored) * 100).toFixed(0);
112
260
  console.log(
113
- "Misses occur where the field name does not share tokens with the query",
261
+ `\nrecall@${K}: ${hits}/${scored} (${pct}%) mode(s): ${[...modesSeen].join(", ")}`,
114
262
  );
115
263
  console.log(
116
- "(e.g. 'departure delay' vs a 'dep_delay' field). Closing that gap is the",
264
+ "The [gap] cases share no tokens with their target entity, so a lexical",
117
265
  );
118
266
  console.log(
119
- "motivation for an optional embeddings provider; lexical ships as the v1 baseline.",
267
+ "run misses them by construction; a semantic run (EMBEDDING_API_KEY set)",
120
268
  );
269
+ console.log("is expected to close them. Compare the two summaries.");
121
270
  }
122
271
 
123
272
  main().catch((err) => {
@@ -1,6 +1,42 @@
1
- import { describe, expect, it } from "bun:test";
2
- import { docText, sanitize, registerGetContextTool } from "./get_context_tool";
1
+ import {
2
+ afterAll,
3
+ afterEach,
4
+ beforeAll,
5
+ beforeEach,
6
+ describe,
7
+ expect,
8
+ it,
9
+ } from "bun:test";
10
+ import * as fs from "fs";
11
+ import * as os from "os";
12
+ import * as path from "path";
13
+ import {
14
+ docOnlyText,
15
+ docText,
16
+ sanitize,
17
+ registerGetContextTool,
18
+ } from "./get_context_tool";
19
+ import { embeddingText } from "./embedding_index";
3
20
  import type { EnvironmentStore } from "../../service/environment_store";
21
+ import { DuckDBConnection } from "../../storage/duckdb/DuckDBConnection";
22
+ import { createEntityEmbeddingsTable } from "../../storage/duckdb/schema";
23
+ import {
24
+ EmbeddingProvider,
25
+ _clearEmbeddingProviderForTests,
26
+ _setEmbeddingProviderForTests,
27
+ } from "../../service/embedding_provider";
28
+ import { _resetEmbeddingIndexStateForTests } from "./embedding_index";
29
+
30
+ // Pin the baseline: every test in this file runs unconfigured (lexical)
31
+ // unless it sets a provider itself, regardless of ambient EMBEDDING_* env
32
+ // vars in the developer's shell.
33
+ beforeEach(() => {
34
+ _setEmbeddingProviderForTests(null);
35
+ _resetEmbeddingIndexStateForTests();
36
+ });
37
+ afterAll(() => {
38
+ _clearEmbeddingProviderForTests();
39
+ });
4
40
 
5
41
  describe("get_context docText", () => {
6
42
  it("extracts #(doc) text from annotation lines", () => {
@@ -31,6 +67,56 @@ describe("get_context docText", () => {
31
67
  });
32
68
  });
33
69
 
70
+ describe("get_context docOnlyText (embedding-input safety)", () => {
71
+ it("extracts #(doc) text like docText", () => {
72
+ expect(docOnlyText(["#(doc) Total revenue."])).toBe("Total revenue.");
73
+ expect(docOnlyText([{ value: "#(doc) Customer state." }])).toBe(
74
+ "Customer state.",
75
+ );
76
+ });
77
+
78
+ it("does NOT fall back to raw lines: no #(doc) yields empty", () => {
79
+ // The security-critical difference from docText: predicate-bearing
80
+ // annotations must never become embedding input.
81
+ expect(docOnlyText(["# bar_chart"])).toBe("");
82
+ expect(
83
+ docOnlyText([
84
+ "#(authorize) \"$ROLE = 'admin'\"",
85
+ "#(malloy) drillable",
86
+ ]),
87
+ ).toBe("");
88
+ });
89
+
90
+ it("keeps only the #(doc) line when mixed with predicate annotations", () => {
91
+ expect(
92
+ docOnlyText([
93
+ "#(authorize) \"$TENANT = 'acme'\"",
94
+ "#(doc) Secured orders.",
95
+ ]),
96
+ ).toBe("Secured orders.");
97
+ });
98
+
99
+ it("an #(authorize)-only entity produces no embedding text beyond its name", () => {
100
+ // End-to-end: what embeddingText actually sends for a governed,
101
+ // undocumented entity is the humanized name only, never the predicate.
102
+ const embedDoc = docOnlyText([
103
+ "#(authorize) \"$ROLE = 'admin'\"",
104
+ "#(authorize) \"$TENANT = 'acme' or $TENANT = 'globex'\"",
105
+ ]);
106
+ const text = embeddingText({
107
+ kind: "source",
108
+ name: "orders_secured",
109
+ source: "orders_secured",
110
+ modelPath: "m.malloy",
111
+ embedDoc,
112
+ });
113
+ expect(text).toBe("orders secured");
114
+ expect(text).not.toContain("authorize");
115
+ expect(text).not.toContain("ROLE");
116
+ expect(text).not.toContain("acme");
117
+ });
118
+ });
119
+
34
120
  describe("get_context sanitize", () => {
35
121
  it("strips lunr operator characters so a plain-English query never throws", () => {
36
122
  const cleaned = sanitize('revenue: +top ~10 "exact" -minus ^boost *wild');
@@ -236,4 +322,211 @@ describe("get_context discovery tiers", () => {
236
322
  );
237
323
  expect(results).toHaveLength(5);
238
324
  });
325
+
326
+ it("tier 4: without a provider the payload has no retrieval marker or scores", async () => {
327
+ const handler = captureHandler({
328
+ getEnvironment: async () =>
329
+ ({ getPackage: async () => mockPackage }) as never,
330
+ });
331
+ const payload = parse(
332
+ await handler({
333
+ environmentName: "malloy-samples",
334
+ packageName: "ecommerce",
335
+ query: "state",
336
+ }),
337
+ );
338
+ expect(payload.retrieval).toBeUndefined();
339
+ expect(Object.keys(payload)).toEqual(["results"]);
340
+ for (const r of payload.results) {
341
+ expect(r.score).toBeUndefined();
342
+ }
343
+ });
344
+ });
345
+
346
+ describe("get_context semantic retrieval", () => {
347
+ let tempDir: string;
348
+ let db: DuckDBConnection;
349
+
350
+ beforeAll(async () => {
351
+ tempDir = fs.mkdtempSync(
352
+ path.join(os.tmpdir(), "get-context-semantic-spec-"),
353
+ );
354
+ db = new DuckDBConnection(path.join(tempDir, "test.db"));
355
+ await db.initialize();
356
+ await createEntityEmbeddingsTable(db);
357
+ });
358
+
359
+ afterAll(async () => {
360
+ // Close before removing: Windows refuses to delete a directory
361
+ // holding DuckDB's open file handle.
362
+ await db.close();
363
+ fs.rmSync(tempDir, { recursive: true, force: true });
364
+ });
365
+
366
+ afterEach(() => {
367
+ _setEmbeddingProviderForTests(null);
368
+ });
369
+
370
+ // Entity texts are humanize(name) [+ doc]: "order items" and "state".
371
+ const VECTORS: Record<string, number[]> = {
372
+ "order items": [0, 1],
373
+ state: [1, 0],
374
+ "where do customers live": [1, 0],
375
+ };
376
+
377
+ function stubProvider(options: { fail?: boolean } = {}): EmbeddingProvider {
378
+ const fetchStub = (async (
379
+ _url: RequestInfo | URL,
380
+ init?: RequestInit,
381
+ ) => {
382
+ if (options.fail) return new Response("down", { status: 500 });
383
+ const body = JSON.parse(String(init?.body)) as { input: string[] };
384
+ const data = body.input.map((text, index) => {
385
+ const embedding = VECTORS[text];
386
+ if (!embedding) throw new Error(`no stub vector for "${text}"`);
387
+ return { index, embedding };
388
+ });
389
+ return new Response(JSON.stringify({ data }), { status: 200 });
390
+ }) as typeof fetch;
391
+ return new EmbeddingProvider(
392
+ {
393
+ apiKey: "test",
394
+ model: "stub-model",
395
+ baseUrl: "https://stub.example.com/v1",
396
+ },
397
+ fetchStub,
398
+ );
399
+ }
400
+
401
+ /** A store whose package is a fresh instance, backed by the temp DB. */
402
+ function semanticStore(): Partial<EnvironmentStore> {
403
+ const pkg = {
404
+ listModels: async () => [{ path: "ecommerce.malloy" }],
405
+ getModel: () => mockModel,
406
+ };
407
+ return {
408
+ getEnvironment: async () => ({ getPackage: async () => pkg }) as never,
409
+ storageManager: {
410
+ getDuckDbConnection: () => db,
411
+ } as never,
412
+ };
413
+ }
414
+
415
+ async function callUntilSemantic(
416
+ handler: Handler,
417
+ params: Record<string, unknown>,
418
+ ) {
419
+ for (let i = 0; i < 200; i++) {
420
+ const payload = parse(await handler(params));
421
+ if (payload.retrieval === "semantic") return payload;
422
+ await new Promise((resolve) => setTimeout(resolve, 5));
423
+ }
424
+ throw new Error("retrieval never became semantic");
425
+ }
426
+
427
+ it("ranks semantically once the index syncs, with scores and a marker", async () => {
428
+ _setEmbeddingProviderForTests(stubProvider());
429
+ const handler = captureHandler(semanticStore());
430
+ const params = {
431
+ environmentName: "specs",
432
+ packageName: "semantic-pkg",
433
+ query: "where do customers live",
434
+ };
435
+
436
+ // Cold start: the sync kicks off in the background and this call
437
+ // answers lexically, marked as such.
438
+ const first = parse(await handler(params));
439
+ expect(first.retrieval).toBe("lexical");
440
+
441
+ const payload = await callUntilSemantic(handler, params);
442
+ expect(payload.results[0].name).toBe("state");
443
+ expect(payload.results[0].kind).toBe("dimension");
444
+ expect(payload.results[0].score).toBeCloseTo(1.0, 3);
445
+ // "order items" is orthogonal to the query: below the similarity
446
+ // floor, so it must not pad the results.
447
+ expect(
448
+ payload.results.some(
449
+ (r: { name: string }) => r.name === "order_items",
450
+ ),
451
+ ).toBe(false);
452
+ });
453
+
454
+ it("falls back to lexical, marked, when the provider goes down after indexing", async () => {
455
+ // Index healthily first, so this pins the query-embed failure
456
+ // path, not just the cold start (which answers lexically anyway).
457
+ _setEmbeddingProviderForTests(stubProvider());
458
+ const handler = captureHandler(semanticStore());
459
+ const params = {
460
+ environmentName: "specs",
461
+ packageName: "failing-pkg",
462
+ query: "where do customers live",
463
+ };
464
+ await callUntilSemantic(handler, params);
465
+
466
+ // Same model and config, but the endpoint now returns 500s: the
467
+ // per-call query embed fails and the call degrades to marked
468
+ // lexical with no scores.
469
+ _setEmbeddingProviderForTests(stubProvider({ fail: true }));
470
+ const payload = parse(await handler({ ...params, query: "state" }));
471
+ expect(payload.retrieval).toBe("lexical");
472
+ expect(
473
+ payload.results.some((r: { name: string }) => r.name === "state"),
474
+ ).toBe(true);
475
+ for (const r of payload.results) {
476
+ expect(r.score).toBeUndefined();
477
+ }
478
+ });
479
+
480
+ it("degrades to lexical when the storage handle is unavailable", async () => {
481
+ _setEmbeddingProviderForTests(stubProvider());
482
+ const store = semanticStore();
483
+ delete (store as { storageManager?: unknown }).storageManager;
484
+ const handler = captureHandler(store);
485
+ const payload = parse(
486
+ await handler({
487
+ environmentName: "specs",
488
+ packageName: "no-storage-pkg",
489
+ query: "state",
490
+ }),
491
+ );
492
+ expect(payload.retrieval).toBe("lexical");
493
+ expect(
494
+ payload.results.some((r: { name: string }) => r.name === "state"),
495
+ ).toBe(true);
496
+ });
497
+
498
+ it("degrades to lexical (never throws) when the real config is malformed", async () => {
499
+ // Exercises the tool-path catch with REAL env parsing, not the
500
+ // _setEmbeddingProviderForTests override: a malformed base makes
501
+ // getEmbeddingProvider() throw, and tier 4 must swallow it and
502
+ // answer marked lexical (embeddingConfigured() is still true).
503
+ const saved = {
504
+ key: process.env.EMBEDDING_API_KEY,
505
+ base: process.env.EMBEDDING_API_BASE,
506
+ };
507
+ process.env.EMBEDDING_API_KEY = "k";
508
+ process.env.EMBEDDING_API_BASE = "not a url";
509
+ _clearEmbeddingProviderForTests();
510
+ try {
511
+ const handler = captureHandler(semanticStore());
512
+ const payload = parse(
513
+ await handler({
514
+ environmentName: "specs",
515
+ packageName: "malformed-cfg-pkg",
516
+ query: "state",
517
+ }),
518
+ );
519
+ expect(payload.retrieval).toBe("lexical");
520
+ expect(
521
+ payload.results.some((r: { name: string }) => r.name === "state"),
522
+ ).toBe(true);
523
+ } finally {
524
+ if (saved.key === undefined) delete process.env.EMBEDDING_API_KEY;
525
+ else process.env.EMBEDDING_API_KEY = saved.key;
526
+ if (saved.base === undefined) delete process.env.EMBEDDING_API_BASE;
527
+ else process.env.EMBEDDING_API_BASE = saved.base;
528
+ _clearEmbeddingProviderForTests();
529
+ _setEmbeddingProviderForTests(null);
530
+ }
531
+ });
239
532
  });