@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
@@ -0,0 +1,1003 @@
1
+ // Real-compiler + real-DuckDB contract for the virtual-source serve transform.
2
+ // The declared serve-shape schema is trusted on faith by the compiler (it does
3
+ // NOT type-check a virtual source's columns), so the generate -> compile ->
4
+ // bind -> run path is pinned end-to-end here against a live table: a drift in
5
+ // the user-type syntax, the virtualMap contract, or the type mapping must fail
6
+ // here rather than surface as a serve-time execution error in production.
7
+ import { DuckDBConnection } from "@malloydata/db-duckdb";
8
+ import {
9
+ FixedConnectionMap,
10
+ InMemoryURLReader,
11
+ Runtime,
12
+ } from "@malloydata/malloy";
13
+ import { beforeAll, describe, expect, it } from "bun:test";
14
+ import { MaterializationEligibilityError } from "../errors";
15
+ import {
16
+ assertServesInDuckDB,
17
+ buildChainedStorageBuildModel,
18
+ buildServeShapeModel,
19
+ buildServeShapeModelForBindings,
20
+ buildVirtualMap,
21
+ deriveServeBindings,
22
+ duckdbTypeToMalloy,
23
+ extractJoins,
24
+ extractRefinements,
25
+ extractViews,
26
+ narrowSchemaToPublic,
27
+ sliceSourceRange,
28
+ type ServeBinding,
29
+ } from "./materialization_serve_transform";
30
+
31
+ describe("duckdbTypeToMalloy", () => {
32
+ it.each([
33
+ ["BIGINT", "number"],
34
+ ["INTEGER", "number"],
35
+ ["HUGEINT", "number"],
36
+ ["UBIGINT", "number"],
37
+ ["DOUBLE", "number"],
38
+ ["DECIMAL(18,2)", "number"],
39
+ ["NUMERIC", "number"],
40
+ ["VARCHAR", "string"],
41
+ ["VARCHAR(255)", "string"],
42
+ ["TEXT", "string"],
43
+ ["UUID", "string"],
44
+ ["BOOLEAN", "boolean"],
45
+ ["BOOL", "boolean"],
46
+ ["DATE", "date"],
47
+ ["TIMESTAMP", "timestamp"],
48
+ ["TIMESTAMP WITH TIME ZONE", "timestamp"],
49
+ ["TIMESTAMPTZ", "timestamp"],
50
+ ["timestamp", "timestamp"],
51
+ ["INTEGER[]", "json"],
52
+ ["STRUCT(a INTEGER)", "json"],
53
+ ["BLOB", "json"],
54
+ ])("maps %s -> %s", (duck, malloy) => {
55
+ expect(duckdbTypeToMalloy(duck)).toBe(malloy);
56
+ });
57
+ });
58
+
59
+ describe("buildServeShapeModel", () => {
60
+ it("emits the flag, a double-colon type shape, and the virtual source line", () => {
61
+ const binding: ServeBinding = {
62
+ sourceName: "mz_orders",
63
+ connectionName: "lake",
64
+ virtualHandle: "mz_orders__g1",
65
+ tablePath: "analytics.mz_orders",
66
+ schema: [
67
+ { name: "amount", type: "BIGINT" },
68
+ { name: "region", type: "VARCHAR" },
69
+ { name: "ts", type: "TIMESTAMP WITH TIME ZONE" },
70
+ ],
71
+ };
72
+ const { modelText, shapeTypeName } = buildServeShapeModel(
73
+ "mz_orders",
74
+ binding,
75
+ );
76
+ expect(shapeTypeName).toBe("mz_orders__shape");
77
+ expect(modelText).toContain("##! experimental.virtual_source");
78
+ expect(modelText).toContain("type: mz_orders__shape is {");
79
+ expect(modelText).toContain("amount::number");
80
+ expect(modelText).toContain("region::string");
81
+ expect(modelText).toContain("ts::timestamp");
82
+ expect(modelText).toContain(
83
+ "source: mz_orders is lake.virtual('mz_orders__g1')::mz_orders__shape",
84
+ );
85
+ });
86
+
87
+ it("backtick-quotes a field name that is not a bare identifier", () => {
88
+ const { modelText } = buildServeShapeModel("s", {
89
+ sourceName: "s",
90
+ connectionName: "lake",
91
+ virtualHandle: "h",
92
+ tablePath: "t",
93
+ schema: [{ name: "odd name", type: "VARCHAR" }],
94
+ });
95
+ expect(modelText).toContain("`odd name`::string");
96
+ });
97
+ });
98
+
99
+ describe("buildVirtualMap", () => {
100
+ it("groups handles by connection and quotes the table path for DuckDB", () => {
101
+ const map = buildVirtualMap([
102
+ {
103
+ sourceName: "a",
104
+ connectionName: "lake",
105
+ virtualHandle: "h1",
106
+ tablePath: "analytics.a",
107
+ schema: [],
108
+ },
109
+ {
110
+ sourceName: "b",
111
+ connectionName: "lake",
112
+ virtualHandle: "h2",
113
+ tablePath: "b",
114
+ schema: [],
115
+ },
116
+ ]);
117
+ expect(map.get("lake")?.get("h1")).toBe('"analytics"."a"');
118
+ expect(map.get("lake")?.get("h2")).toBe('"b"');
119
+ });
120
+
121
+ it("passes an already-quoted path through unchanged (no double-quoting)", () => {
122
+ // Mirrors #904's quoteManifestTablePath: an author-quoted `name=` is
123
+ // canonical SQL and must not be re-quoted into `""foo""`.
124
+ const map = buildVirtualMap([
125
+ {
126
+ sourceName: "a",
127
+ connectionName: "lake",
128
+ virtualHandle: "h",
129
+ tablePath: '"My Table"',
130
+ schema: [],
131
+ },
132
+ ]);
133
+ expect(map.get("lake")?.get("h")).toBe('"My Table"');
134
+ });
135
+ });
136
+
137
+ describe("serve transform end-to-end (generate -> compile -> bind -> run)", () => {
138
+ let connections: FixedConnectionMap;
139
+ let duckdb: DuckDBConnection;
140
+
141
+ beforeAll(async () => {
142
+ duckdb = new DuckDBConnection("duckdb", ":memory:");
143
+ await duckdb.runSQL(
144
+ "CREATE TABLE mz_physical AS " +
145
+ "SELECT 10 AS amount, 'US' AS region " +
146
+ "UNION ALL SELECT 20, 'EU' UNION ALL SELECT 30, 'US'",
147
+ );
148
+ connections = new FixedConnectionMap(
149
+ new Map([["duckdb", duckdb]]),
150
+ "duckdb",
151
+ );
152
+ });
153
+
154
+ /** DESCRIBE the physical table to build a binding from its real schema. */
155
+ async function bindingFromLiveTable(): Promise<ServeBinding> {
156
+ const described = await duckdb.runSQL("DESCRIBE mz_physical");
157
+ const rows = Array.isArray(described) ? described : described.rows;
158
+ const schema = (rows as Record<string, unknown>[]).map((r) => ({
159
+ name: String(r.column_name),
160
+ type: String(r.column_type),
161
+ }));
162
+ return {
163
+ sourceName: "mz",
164
+ connectionName: "duckdb",
165
+ virtualHandle: "mz_handle",
166
+ tablePath: "mz_physical",
167
+ schema,
168
+ };
169
+ }
170
+
171
+ it("runs a query against the virtual source bound to the live table", async () => {
172
+ const binding = await bindingFromLiveTable();
173
+ const { modelText } = buildServeShapeModel("mz", binding);
174
+ const root = "file:///e2e/";
175
+ const urlReader = new InMemoryURLReader(
176
+ new Map([[`${root}m.malloy`, modelText]]),
177
+ );
178
+ const runtime = new Runtime({ urlReader, connections });
179
+ const query = runtime
180
+ .loadModel(new URL(`${root}m.malloy`), {
181
+ importBaseURL: new URL(root),
182
+ })
183
+ .loadQuery("run: mz -> { aggregate: total is amount.sum() }");
184
+
185
+ const virtualMap = buildVirtualMap([binding]);
186
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
187
+ const result = await query.run({ virtualMap } as any);
188
+ const out = result.data.toObject() as { total: number }[];
189
+ expect(out[0].total).toBe(60);
190
+ });
191
+
192
+ it("assertServesInDuckDB passes for a well-formed captured schema", async () => {
193
+ const binding = await bindingFromLiveTable();
194
+ await expect(
195
+ assertServesInDuckDB("mz", binding, connections),
196
+ ).resolves.toBeUndefined();
197
+ });
198
+
199
+ it("assertServesInDuckDB refuses a serve shape that cannot compile", async () => {
200
+ // A field named after a reserved token with no valid mapping path: force a
201
+ // compile failure by declaring an empty shape name collision is hard, so
202
+ // use a connection name that does not resolve — the virtual source's
203
+ // connection must exist, so an unknown connection fails compilation.
204
+ const binding: ServeBinding = {
205
+ sourceName: "mz",
206
+ connectionName: "does_not_exist",
207
+ virtualHandle: "h",
208
+ tablePath: "t",
209
+ schema: [{ name: "amount", type: "BIGINT" }],
210
+ };
211
+ await expect(
212
+ assertServesInDuckDB("mz", binding, connections),
213
+ ).rejects.toThrow(MaterializationEligibilityError);
214
+ });
215
+ });
216
+
217
+ describe("join serve end-to-end (two virtual sources, join runs in DuckDB)", () => {
218
+ let connections: FixedConnectionMap;
219
+ let duckdb: DuckDBConnection;
220
+
221
+ beforeAll(async () => {
222
+ duckdb = new DuckDBConnection("duckdb", ":memory:");
223
+ await duckdb.runSQL(
224
+ "CREATE TABLE orders_phys AS " +
225
+ "SELECT 10 AS amount, 'r1' AS region_id " +
226
+ "UNION ALL SELECT 20, 'r2' UNION ALL SELECT 30, 'r1'",
227
+ );
228
+ await duckdb.runSQL(
229
+ "CREATE TABLE regions_phys AS " +
230
+ "SELECT 'r1' AS region_id, 'North' AS region_name " +
231
+ "UNION ALL SELECT 'r2', 'South'",
232
+ );
233
+ connections = new FixedConnectionMap(
234
+ new Map([["duckdb", duckdb]]),
235
+ "duckdb",
236
+ );
237
+ });
238
+
239
+ it("serves a query that traverses a join from the materialized tables", async () => {
240
+ const bindings: ServeBinding[] = [
241
+ {
242
+ sourceName: "regions",
243
+ connectionName: "duckdb",
244
+ virtualHandle: "regions_h",
245
+ tablePath: "regions_phys",
246
+ schema: [
247
+ { name: "region_id", type: "VARCHAR" },
248
+ { name: "region_name", type: "VARCHAR" },
249
+ ],
250
+ },
251
+ {
252
+ sourceName: "orders",
253
+ connectionName: "duckdb",
254
+ virtualHandle: "orders_h",
255
+ tablePath: "orders_phys",
256
+ schema: [
257
+ { name: "amount", type: "BIGINT" },
258
+ { name: "region_id", type: "VARCHAR" },
259
+ ],
260
+ refinements: [
261
+ {
262
+ kind: "join",
263
+ name: "regions",
264
+ keyword: "join_one",
265
+ text: "regions is regions on region_id = regions.region_id",
266
+ dependsOn: "regions",
267
+ },
268
+ ],
269
+ },
270
+ ];
271
+ const { modelText } = buildServeShapeModelForBindings(bindings);
272
+ const root = "file:///join-e2e/";
273
+ const runtime = new Runtime({
274
+ urlReader: new InMemoryURLReader(
275
+ new Map([[`${root}m.malloy`, modelText]]),
276
+ ),
277
+ connections,
278
+ });
279
+ const query = runtime
280
+ .loadModel(new URL(`${root}m.malloy`), {
281
+ importBaseURL: new URL(root),
282
+ })
283
+ .loadQuery(
284
+ "run: orders -> { group_by: regions.region_name; aggregate: total is amount.sum() }",
285
+ );
286
+ const virtualMap = buildVirtualMap(bindings);
287
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
288
+ const result = await query.run({ virtualMap } as any);
289
+ const out = result.data.toObject() as {
290
+ region_name: string;
291
+ total: number;
292
+ }[];
293
+ const byRegion = Object.fromEntries(
294
+ out.map((r) => [r.region_name, r.total]),
295
+ );
296
+ expect(byRegion).toEqual({ North: 40, South: 20 });
297
+ });
298
+ });
299
+
300
+ describe("deriveServeBindings", () => {
301
+ it("binds only storage entries, keying the handle on sourceEntityId", () => {
302
+ const bindings = deriveServeBindings({
303
+ se_storage: {
304
+ sourceEntityId: "se_storage",
305
+ sourceName: "mz",
306
+ physicalTableName: "mz_g003",
307
+ connectionName: "wh",
308
+ storageConnectionName: "lake",
309
+ schema: [{ name: "amount", type: "BIGINT" }],
310
+ dataAsOf: "2026-07-20T00:00:00Z",
311
+ realization: "COPY",
312
+ rowCount: null,
313
+ },
314
+ se_pathC: {
315
+ // In-warehouse (no storage): served via the manifest, not the
316
+ // transform — must NOT produce a binding.
317
+ sourceEntityId: "se_pathC",
318
+ sourceName: "orders",
319
+ physicalTableName: "orders_v1",
320
+ connectionName: "wh",
321
+ realization: "COPY",
322
+ rowCount: null,
323
+ },
324
+ se_noschema: {
325
+ // Storage but no captured schema — skipped (can't declare a shape).
326
+ sourceEntityId: "se_noschema",
327
+ sourceName: "x",
328
+ physicalTableName: "lake.x",
329
+ connectionName: "wh",
330
+ storageConnectionName: "lake",
331
+ schema: [],
332
+ realization: "COPY",
333
+ rowCount: null,
334
+ },
335
+ });
336
+ expect(bindings).toEqual([
337
+ {
338
+ sourceName: "mz",
339
+ connectionName: "lake",
340
+ virtualHandle: "se_storage",
341
+ tablePath: "lake.mz_g003",
342
+ schema: [{ name: "amount", type: "BIGINT" }],
343
+ freshAsOf: "2026-07-20T00:00:00Z",
344
+ },
345
+ ]);
346
+ // The table path is qualified with the destination catalog (attach alias)
347
+ // so the serve reads <store>.<table>, not an unqualified name.
348
+ expect(bindings[0].tablePath).toBe("lake.mz_g003");
349
+ });
350
+ });
351
+
352
+ describe("extractRefinements", () => {
353
+ it("maps derived fields to dimensions/measures and skips raw columns + joins", () => {
354
+ const fields = [
355
+ { name: "order_date", type: "date", expressionType: "scalar" }, // raw col (no code)
356
+ { name: "total_amount", type: "number", expressionType: "scalar" }, // raw col
357
+ {
358
+ name: "avg_order_value",
359
+ type: "number",
360
+ expressionType: "scalar",
361
+ code: "total_amount / order_count",
362
+ },
363
+ {
364
+ name: "grand_total",
365
+ type: "number",
366
+ expressionType: "aggregate",
367
+ code: "total_amount.sum()",
368
+ },
369
+ // analytic / window -> skipped (falls back)
370
+ {
371
+ name: "running",
372
+ type: "number",
373
+ expressionType: "analytic",
374
+ code: "sum(total_amount)",
375
+ },
376
+ // join -> no code -> skipped
377
+ { name: "region_dim", type: "join", join: "one" },
378
+ ];
379
+ expect(extractRefinements(fields)).toEqual([
380
+ {
381
+ kind: "dimension",
382
+ name: "avg_order_value",
383
+ code: "total_amount / order_count",
384
+ },
385
+ { kind: "measure", name: "grand_total", code: "total_amount.sum()" },
386
+ ]);
387
+ });
388
+
389
+ it("returns [] for undefined/empty fields", () => {
390
+ expect(extractRefinements(undefined)).toEqual([]);
391
+ expect(extractRefinements([])).toEqual([]);
392
+ });
393
+
394
+ it("skips access-restricted (private/internal) fields — never re-emit a hidden field", () => {
395
+ // The served virtual source carries no access modifiers, so re-declaring a
396
+ // private/internal field would expose over the stored table a field the
397
+ // live path refuses. It must be dropped (the query falls back to live,
398
+ // where the modifier is enforced). The compiler carries accessModifier on
399
+ // the field right beside `code`/`expressionType`.
400
+ const fields = [
401
+ {
402
+ name: "public_dim",
403
+ expressionType: "scalar",
404
+ code: "upper(region)",
405
+ },
406
+ {
407
+ name: "secret_flag",
408
+ expressionType: "scalar",
409
+ code: "amount * 2",
410
+ accessModifier: "private",
411
+ },
412
+ {
413
+ name: "internal_total",
414
+ expressionType: "aggregate",
415
+ code: "amount.sum()",
416
+ accessModifier: "internal",
417
+ },
418
+ ];
419
+ expect(extractRefinements(fields)).toEqual([
420
+ { kind: "dimension", name: "public_dim", code: "upper(region)" },
421
+ ]);
422
+ });
423
+ });
424
+
425
+ describe("buildServeShapeModelForBindings with refinements", () => {
426
+ it("re-declares dimensions/measures as an extend on the virtual base", () => {
427
+ const { modelText } = buildServeShapeModelForBindings([
428
+ {
429
+ sourceName: "daily",
430
+ connectionName: "lake",
431
+ virtualHandle: "h",
432
+ tablePath: "lake.daily",
433
+ schema: [
434
+ { name: "total_amount", type: "BIGINT" },
435
+ { name: "order_count", type: "BIGINT" },
436
+ ],
437
+ refinements: [
438
+ {
439
+ kind: "dimension",
440
+ name: "avg_order_value",
441
+ code: "total_amount / order_count",
442
+ },
443
+ ],
444
+ },
445
+ ]);
446
+ expect(modelText).toContain(
447
+ "source: daily is lake.virtual('h')::daily__shape extend {",
448
+ );
449
+ expect(modelText).toContain(
450
+ "dimension: avg_order_value is total_amount / order_count",
451
+ );
452
+ });
453
+
454
+ it("emits joins (verbatim, keyword-prefixed) before dimensions/measures", () => {
455
+ const { modelText } = buildServeShapeModelForBindings([
456
+ {
457
+ sourceName: "orders",
458
+ connectionName: "lake",
459
+ virtualHandle: "h",
460
+ tablePath: "lake.orders",
461
+ schema: [
462
+ { name: "amount", type: "BIGINT" },
463
+ { name: "region_id", type: "VARCHAR" },
464
+ ],
465
+ refinements: [
466
+ {
467
+ kind: "join",
468
+ name: "regions",
469
+ keyword: "join_one",
470
+ text: "regions is regions on region_id = regions.region_id",
471
+ dependsOn: "regions",
472
+ },
473
+ {
474
+ kind: "measure",
475
+ name: "total",
476
+ code: "amount.sum()",
477
+ },
478
+ ],
479
+ },
480
+ ]);
481
+ expect(modelText).toContain(
482
+ "join_one: regions is regions on region_id = regions.region_id",
483
+ );
484
+ expect(modelText).toContain("measure: total is amount.sum()");
485
+ // Join must precede the measure so the measure can reference joined fields.
486
+ expect(modelText.indexOf("join_one:")).toBeLessThan(
487
+ modelText.indexOf("measure: total"),
488
+ );
489
+ });
490
+
491
+ it("declares a joined source before the source that joins it (dependency order)", () => {
492
+ // `orders` (joins `regions`) is listed FIRST, but must be emitted after
493
+ // `regions` so the join reference resolves.
494
+ const { modelText } = buildServeShapeModelForBindings([
495
+ {
496
+ sourceName: "orders",
497
+ connectionName: "lake",
498
+ virtualHandle: "o",
499
+ tablePath: "lake.orders",
500
+ schema: [{ name: "region_id", type: "VARCHAR" }],
501
+ refinements: [
502
+ {
503
+ kind: "join",
504
+ name: "regions",
505
+ keyword: "join_one",
506
+ text: "regions is regions on region_id = regions.region_id",
507
+ dependsOn: "regions",
508
+ },
509
+ ],
510
+ },
511
+ {
512
+ sourceName: "regions",
513
+ connectionName: "lake",
514
+ virtualHandle: "r",
515
+ tablePath: "lake.regions",
516
+ schema: [{ name: "region_id", type: "VARCHAR" }],
517
+ },
518
+ ]);
519
+ expect(modelText.indexOf("source: regions is")).toBeLessThan(
520
+ modelText.indexOf("source: orders is"),
521
+ );
522
+ });
523
+ });
524
+
525
+ describe("sliceSourceRange", () => {
526
+ const src =
527
+ "line0\nsource: orders is x extend {\n join_one: r is regions on a = r.a\n}\n";
528
+ it("slices a single-line range (the join declaration)", () => {
529
+ // Recover `r is regions on a = r.a` from line 2.
530
+ expect(
531
+ sliceSourceRange(src, {
532
+ start: { line: 2, character: 12 },
533
+ end: { line: 2, character: 35 },
534
+ }),
535
+ ).toBe("r is regions on a = r.a");
536
+ });
537
+ it("slices a multi-line range", () => {
538
+ expect(
539
+ sliceSourceRange(src, {
540
+ start: { line: 1, character: 8 },
541
+ end: { line: 3, character: 1 },
542
+ }),
543
+ ).toBe("orders is x extend {\n join_one: r is regions on a = r.a\n}");
544
+ });
545
+ it("returns undefined for an out-of-bounds range (stale source)", () => {
546
+ expect(
547
+ sliceSourceRange("short", {
548
+ start: { line: 0, character: 0 },
549
+ end: { line: 9, character: 0 },
550
+ }),
551
+ ).toBeUndefined();
552
+ });
553
+ });
554
+
555
+ describe("narrowSchemaToPublic", () => {
556
+ const schema = [
557
+ { name: "id", type: "BIGINT" },
558
+ { name: "ssn", type: "VARCHAR" },
559
+ { name: "amount", type: "BIGINT" },
560
+ ];
561
+
562
+ it("drops a captured column the source does not publicly expose (except:)", () => {
563
+ // `ssn` is materialized into the table (getSQL projects it) and captured by
564
+ // DESCRIBE, but the source `except:`s it, so it is absent from the field
565
+ // list and must not be declared on the serve shape.
566
+ const fields = [
567
+ { name: "id" },
568
+ { name: "amount" },
569
+ { name: "amount_x2", code: "amount * 2", expressionType: "scalar" },
570
+ ];
571
+ expect(narrowSchemaToPublic(schema, fields)).toEqual([
572
+ { name: "id", type: "BIGINT" },
573
+ { name: "amount", type: "BIGINT" },
574
+ ]);
575
+ });
576
+
577
+ it("drops a captured column whose field carries a non-public access modifier", () => {
578
+ const fields = [
579
+ { name: "id" },
580
+ { name: "ssn", accessModifier: "private" },
581
+ { name: "amount" },
582
+ ];
583
+ expect(narrowSchemaToPublic(schema, fields).map((c) => c.name)).toEqual([
584
+ "id",
585
+ "amount",
586
+ ]);
587
+ });
588
+
589
+ it("keeps every column when all are public (no-op for a plain rollup)", () => {
590
+ const fields = [{ name: "id" }, { name: "ssn" }, { name: "amount" }];
591
+ expect(narrowSchemaToPublic(schema, fields)).toEqual(schema);
592
+ });
593
+
594
+ it("fails closed to an empty shape when the field list is unavailable", () => {
595
+ // Can't determine the public surface → declare nothing → queries fall back
596
+ // to live rather than risk exposing a hidden column.
597
+ expect(narrowSchemaToPublic(schema, undefined)).toEqual([]);
598
+ expect(narrowSchemaToPublic(schema, [])).toEqual([]);
599
+ });
600
+ });
601
+
602
+ describe("extractJoins", () => {
603
+ const loc = (line: number) => ({
604
+ url: "file:///m.malloy",
605
+ range: {
606
+ start: { line, character: 0 },
607
+ end: { line, character: 20 },
608
+ },
609
+ });
610
+ const ctx = (overrides?: Partial<Parameters<typeof extractJoins>[1]>) => ({
611
+ sourceNameById: new Map([
612
+ ["regions@f", "regions"],
613
+ ["inline@f", "inline_only"],
614
+ ]),
615
+ materializedSourceNames: new Set(["orders", "regions"]),
616
+ liftText: () => "r is regions on region_id = r.region_id",
617
+ ...overrides,
618
+ });
619
+
620
+ it("carries a join whose target is materialized, keyword and text set", () => {
621
+ const fields = [
622
+ {
623
+ as: "r",
624
+ name: "duckdb:regions",
625
+ join: "one",
626
+ sourceID: "regions@f",
627
+ location: loc(3),
628
+ },
629
+ ];
630
+ expect(extractJoins(fields, ctx())).toEqual([
631
+ {
632
+ kind: "join",
633
+ name: "r",
634
+ keyword: "join_one",
635
+ text: "r is regions on region_id = r.region_id",
636
+ dependsOn: "regions",
637
+ },
638
+ ]);
639
+ });
640
+
641
+ it("skips a join whose target source is not materialized (the gate)", () => {
642
+ const fields = [
643
+ { as: "u", join: "one", sourceID: "unmat@f", location: loc(3) },
644
+ ];
645
+ expect(extractJoins(fields, ctx())).toEqual([]);
646
+ });
647
+
648
+ it("skips a join to an anonymous/inline source not in the name map", () => {
649
+ const fields = [
650
+ { as: "z", join: "one", sourceID: "not_in_map@f", location: loc(3) },
651
+ ];
652
+ expect(extractJoins(fields, ctx())).toEqual([]);
653
+ });
654
+
655
+ it("skips an access-restricted (private/internal) join", () => {
656
+ const fields = [
657
+ {
658
+ as: "r",
659
+ join: "one",
660
+ sourceID: "regions@f",
661
+ location: loc(3),
662
+ accessModifier: "private",
663
+ },
664
+ ];
665
+ expect(extractJoins(fields, ctx())).toEqual([]);
666
+ });
667
+
668
+ it("skips a join whose declaration text cannot be recovered", () => {
669
+ const fields = [
670
+ { as: "r", join: "one", sourceID: "regions@f", location: loc(3) },
671
+ ];
672
+ expect(extractJoins(fields, ctx({ liftText: () => undefined }))).toEqual(
673
+ [],
674
+ );
675
+ });
676
+
677
+ it("maps join relationships to keywords and skips raw fields", () => {
678
+ const map = new Map([["regions@f", "regions"]]);
679
+ const shared = {
680
+ sourceNameById: map,
681
+ materializedSourceNames: new Set(["regions"]),
682
+ liftText: () => "x",
683
+ };
684
+ expect(
685
+ extractJoins(
686
+ [{ join: "many", sourceID: "regions@f", location: loc(1) }],
687
+ shared,
688
+ )[0].keyword,
689
+ ).toBe("join_many");
690
+ expect(
691
+ extractJoins(
692
+ [{ join: "cross", sourceID: "regions@f", location: loc(1) }],
693
+ shared,
694
+ )[0].keyword,
695
+ ).toBe("join_cross");
696
+ // A non-join field (a dimension) is ignored.
697
+ expect(
698
+ extractJoins(
699
+ [{ name: "d", expressionType: "scalar", code: "1+1" }],
700
+ shared,
701
+ ),
702
+ ).toEqual([]);
703
+ });
704
+ });
705
+
706
+ describe("extractViews", () => {
707
+ const liftText = () =>
708
+ "by_region is { group_by: region; aggregate: c is count() }";
709
+
710
+ it("carries a turtle field, lifting its declaration text", () => {
711
+ const fields = [
712
+ {
713
+ type: "turtle",
714
+ name: "by_region",
715
+ location: { url: "file:///m", range: {} },
716
+ },
717
+ ];
718
+ expect(extractViews(fields, liftText)).toEqual([
719
+ {
720
+ kind: "view",
721
+ name: "by_region",
722
+ text: "by_region is { group_by: region; aggregate: c is count() }",
723
+ },
724
+ ]);
725
+ });
726
+
727
+ it("skips an access-restricted (private/internal) view", () => {
728
+ const fields = [
729
+ {
730
+ type: "turtle",
731
+ name: "secret_view",
732
+ location: { url: "file:///m", range: {} },
733
+ accessModifier: "internal",
734
+ },
735
+ ];
736
+ expect(extractViews(fields, liftText)).toEqual([]);
737
+ });
738
+
739
+ it("skips non-turtle fields and unliftable turtles", () => {
740
+ expect(
741
+ extractViews(
742
+ [{ name: "amount", type: "number", expressionType: "scalar" }],
743
+ liftText,
744
+ ),
745
+ ).toEqual([]);
746
+ expect(
747
+ extractViews(
748
+ [
749
+ {
750
+ type: "turtle",
751
+ name: "v",
752
+ location: { url: "file:///m", range: {} },
753
+ },
754
+ ],
755
+ () => undefined,
756
+ ),
757
+ ).toEqual([]);
758
+ });
759
+
760
+ it("returns [] for undefined fields", () => {
761
+ expect(extractViews(undefined, liftText)).toEqual([]);
762
+ });
763
+ });
764
+
765
+ describe("buildServeShapeModelForBindings with a view", () => {
766
+ it("emits the view (verbatim, view: prefixed) after joins and measures", () => {
767
+ const { modelText } = buildServeShapeModelForBindings([
768
+ {
769
+ sourceName: "orders",
770
+ connectionName: "lake",
771
+ virtualHandle: "h",
772
+ tablePath: "lake.orders",
773
+ schema: [{ name: "amount", type: "BIGINT" }],
774
+ refinements: [
775
+ { kind: "measure", name: "total", code: "amount.sum()" },
776
+ {
777
+ kind: "view",
778
+ name: "by_amount",
779
+ text: "by_amount is { group_by: amount; aggregate: total }",
780
+ },
781
+ ],
782
+ },
783
+ ]);
784
+ expect(modelText).toContain(
785
+ "view: by_amount is { group_by: amount; aggregate: total }",
786
+ );
787
+ // The view must come after the measure it references.
788
+ expect(modelText.indexOf("measure: total")).toBeLessThan(
789
+ modelText.indexOf("view: by_amount"),
790
+ );
791
+ });
792
+ });
793
+
794
+ describe("view serve end-to-end (view over a join runs in DuckDB)", () => {
795
+ let connections: FixedConnectionMap;
796
+ let duckdb: DuckDBConnection;
797
+
798
+ beforeAll(async () => {
799
+ duckdb = new DuckDBConnection("duckdb", ":memory:");
800
+ await duckdb.runSQL(
801
+ "CREATE OR REPLACE TABLE v_orders AS " +
802
+ "SELECT 10 AS amount, 'r1' AS region_id " +
803
+ "UNION ALL SELECT 20, 'r2' UNION ALL SELECT 30, 'r1'",
804
+ );
805
+ await duckdb.runSQL(
806
+ "CREATE OR REPLACE TABLE v_regions AS " +
807
+ "SELECT 'r1' AS region_id, 'North' AS region_name " +
808
+ "UNION ALL SELECT 'r2', 'South'",
809
+ );
810
+ connections = new FixedConnectionMap(
811
+ new Map([["duckdb", duckdb]]),
812
+ "duckdb",
813
+ );
814
+ });
815
+
816
+ it("invokes a named view that groups by a joined field, served from storage", async () => {
817
+ const bindings: ServeBinding[] = [
818
+ {
819
+ sourceName: "regions",
820
+ connectionName: "duckdb",
821
+ virtualHandle: "vr",
822
+ tablePath: "v_regions",
823
+ schema: [
824
+ { name: "region_id", type: "VARCHAR" },
825
+ { name: "region_name", type: "VARCHAR" },
826
+ ],
827
+ },
828
+ {
829
+ sourceName: "orders",
830
+ connectionName: "duckdb",
831
+ virtualHandle: "vo",
832
+ tablePath: "v_orders",
833
+ schema: [
834
+ { name: "amount", type: "BIGINT" },
835
+ { name: "region_id", type: "VARCHAR" },
836
+ ],
837
+ refinements: [
838
+ {
839
+ kind: "join",
840
+ name: "regions",
841
+ keyword: "join_one",
842
+ text: "regions is regions on region_id = regions.region_id",
843
+ dependsOn: "regions",
844
+ },
845
+ { kind: "measure", name: "total", code: "amount.sum()" },
846
+ {
847
+ kind: "view",
848
+ name: "by_region",
849
+ text: "by_region is { group_by: regions.region_name; aggregate: total }",
850
+ },
851
+ ],
852
+ },
853
+ ];
854
+ const { modelText } = buildServeShapeModelForBindings(bindings);
855
+ const root = "file:///view-e2e/";
856
+ const runtime = new Runtime({
857
+ urlReader: new InMemoryURLReader(
858
+ new Map([[`${root}m.malloy`, modelText]]),
859
+ ),
860
+ connections,
861
+ });
862
+ const query = runtime
863
+ .loadModel(new URL(`${root}m.malloy`), {
864
+ importBaseURL: new URL(root),
865
+ })
866
+ .loadQuery("run: orders -> by_region");
867
+ const virtualMap = buildVirtualMap(bindings);
868
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
869
+ const result = await query.run({ virtualMap } as any);
870
+ const out = result.data.toObject() as {
871
+ region_name: string;
872
+ total: number;
873
+ }[];
874
+ expect(
875
+ Object.fromEntries(out.map((r) => [r.region_name, r.total])),
876
+ ).toEqual({ North: 40, South: 20 });
877
+ });
878
+ });
879
+
880
+ describe("buildChainedStorageBuildModel (stack-on-parent transient build model)", () => {
881
+ const parent: ServeBinding = {
882
+ sourceName: "daily_orders",
883
+ connectionName: "lake",
884
+ virtualHandle: "daily_h",
885
+ tablePath: "lake.daily_orders__mabc",
886
+ schema: [
887
+ { name: "order_date", type: "DATE" },
888
+ { name: "total", type: "DOUBLE" },
889
+ ],
890
+ };
891
+ const downstreamDefText =
892
+ "monthly_orders is daily_orders -> {\n" +
893
+ " group_by: order_month is order_date.month\n" +
894
+ " aggregate: monthly_total is total.sum()\n}";
895
+
896
+ it("rebinds the parent as a virtual source and re-declares the persist-annotated downstream over it", () => {
897
+ const model = buildChainedStorageBuildModel({
898
+ upstreams: [parent],
899
+ downstreamName: "monthly_orders",
900
+ downstreamDefText,
901
+ destinationName: "lake",
902
+ });
903
+ // Both experiments are enabled (persist + virtual_source).
904
+ expect(model).toContain(
905
+ "##! experimental { persistence virtual_source }",
906
+ );
907
+ // The parent is rebound to a virtual source carrying its captured schema.
908
+ expect(model).toContain("type: daily_orders__shape is {");
909
+ expect(model).toContain(
910
+ "source: daily_orders is lake.virtual('daily_h')::daily_orders__shape",
911
+ );
912
+ // The downstream is persist-annotated (so it surfaces in the transient
913
+ // build plan) and re-declared over the rebound parent with `source: `
914
+ // prepended to the lifted RHS.
915
+ expect(model).toContain("#@ persist storage=lake");
916
+ expect(model).toContain("source: monthly_orders is daily_orders ->");
917
+ });
918
+
919
+ it("compiles against DuckDB and its downstream getSQL reads the parent's mapped table", async () => {
920
+ const conn = new DuckDBConnection("lake", ":memory:");
921
+ const model = buildChainedStorageBuildModel({
922
+ upstreams: [parent],
923
+ downstreamName: "monthly_orders",
924
+ downstreamDefText,
925
+ destinationName: "lake",
926
+ });
927
+ const root = "file:///t3-assemble/";
928
+ const url = `${root}m.malloy`;
929
+ const runtime = new Runtime({
930
+ urlReader: new InMemoryURLReader(new Map([[url, model]])),
931
+ connections: new FixedConnectionMap(new Map([["lake", conn]]), "lake"),
932
+ });
933
+ const compiled = await runtime
934
+ .loadModel(new URL(url), { importBaseURL: new URL(root) })
935
+ .getModel();
936
+ const plan = compiled.getBuildPlan();
937
+ const names = Object.values(plan.sources).map((s) => s.name);
938
+ // Only the downstream is a persist source; the rebound parent is virtual.
939
+ expect(names).toEqual(["monthly_orders"]);
940
+ const downstream = Object.values(plan.sources).find(
941
+ (s) => s.name === "monthly_orders",
942
+ )!;
943
+ const virtualMap = buildVirtualMap([parent]);
944
+ const sql = downstream.getSQL({ virtualMap });
945
+ // The generated SQL reads the parent's content-addressed lake table, not
946
+ // a re-scan of raw — the whole point of stacking on the parent.
947
+ expect(sql).toContain("daily_orders__mabc");
948
+ });
949
+
950
+ it("runs the downstream over the parent's stored rows and computes the frozen roll-up", async () => {
951
+ // The end-to-end proof of the mechanism, entirely in-memory (no file, so
952
+ // it is deterministic under full-suite load): a live DuckDB holds the
953
+ // parent's STORED rows, the transient model rebinds it, and running the
954
+ // downstream over it yields Jan = 150+225 = 375, Feb = 99 — a pure
955
+ // function of the parent's rows, never a re-scan of raw.
956
+ const conn = new DuckDBConnection("lake", ":memory:");
957
+ await conn.runSQL(
958
+ 'CREATE TABLE "daily_orders__mabc" AS ' +
959
+ "SELECT CAST('2026-01-01' AS DATE) AS order_date, 150.0 AS total " +
960
+ "UNION ALL SELECT CAST('2026-01-02' AS DATE), 225.0 " +
961
+ "UNION ALL SELECT CAST('2026-02-01' AS DATE), 99.0",
962
+ );
963
+ // Bare (unqualified) table path so the virtualMap resolves against the
964
+ // in-memory connection's default catalog rather than a `lake.` catalog.
965
+ const memParent: ServeBinding = {
966
+ ...parent,
967
+ tablePath: "daily_orders__mabc",
968
+ };
969
+ const model = buildChainedStorageBuildModel({
970
+ upstreams: [memParent],
971
+ downstreamName: "monthly_orders",
972
+ downstreamDefText,
973
+ destinationName: "lake",
974
+ });
975
+ const root = "file:///t3-run/";
976
+ const url = `${root}m.malloy`;
977
+ const runtime = new Runtime({
978
+ urlReader: new InMemoryURLReader(new Map([[url, model]])),
979
+ connections: new FixedConnectionMap(new Map([["lake", conn]]), "lake"),
980
+ });
981
+ const query = runtime
982
+ .loadModel(new URL(url), { importBaseURL: new URL(root) })
983
+ .loadQuery(
984
+ "run: monthly_orders -> { select: order_month, monthly_total }",
985
+ );
986
+ const virtualMap = buildVirtualMap([memParent]);
987
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
988
+ const result = await query.run({ virtualMap } as any);
989
+ const out = result.data.toObject() as {
990
+ order_month: { toISOString(): string } | string;
991
+ monthly_total: number;
992
+ }[];
993
+ const byMonth = Object.fromEntries(
994
+ out.map((r) => [
995
+ typeof r.order_month === "string"
996
+ ? r.order_month.slice(0, 7)
997
+ : r.order_month.toISOString().slice(0, 7),
998
+ Number(r.monthly_total),
999
+ ]),
1000
+ );
1001
+ expect(byMonth).toEqual({ "2026-01": 375, "2026-02": 99 });
1002
+ });
1003
+ });