@malloy-publisher/server 0.0.234 → 0.0.236

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 (318) hide show
  1. package/dist/app/api-doc.yaml +47 -17
  2. package/dist/app/assets/{EnvironmentPage-DTZQ4Gxc.js → EnvironmentPage-BsAnavYN.js} +1 -1
  3. package/dist/app/assets/{HomePage-C5mlDPXK.js → HomePage-CADE138j.js} +1 -1
  4. package/dist/app/assets/{LightMode-DGNmhG0u.js → LightMode-Cfh7KzN8.js} +1 -1
  5. package/dist/app/assets/{MainPage-CVL_wmP4.js → MainPage-CO3pRlnV.js} +1 -1
  6. package/dist/app/assets/{MaterializationsPage-DmzMBCpy.js → MaterializationsPage-p9YjkRXZ.js} +1 -1
  7. package/dist/app/assets/{ModelPage-Dbvf4QbB.js → ModelPage-C1OSTv-x.js} +1 -1
  8. package/dist/app/assets/{PackagePage-DxdHc2Qs.js → PackagePage-e4kN75YR.js} +1 -1
  9. package/dist/app/assets/{RouteError-OJdT4tCd.js → RouteError-CzbfOkng.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-Bk7s0KXY.js → ThemeEditorPage-CciagFTq.js} +1 -1
  11. package/dist/app/assets/{WorkbookPage-j_vCWdN3.js → WorkbookPage-DNWmkCXa.js} +1 -1
  12. package/dist/app/assets/{core-Rj_4rRnA.es-DoIfLxDJ.js → core-Rj_4rRnA.es-BZyvITuO.js} +1 -1
  13. package/dist/app/assets/{index-B_jKMR35.js → index-CH2AcDzc.js} +4 -4
  14. package/dist/app/assets/{index-hw-xn0X7.js → index-DQa463gC.js} +2 -2
  15. package/dist/app/assets/{index-DWIe_hK0.js → index-DQpV7MyA.js} +1 -1
  16. package/dist/app/assets/{index-BabP-V-S.js → index-DzaYbhnD.js} +1 -1
  17. package/dist/app/assets/{index-D-rDyK11.js → index-VBbcc8s6.js} +1 -1
  18. package/dist/app/index.html +1 -1
  19. package/dist/package_load_worker.mjs +8 -1
  20. package/dist/server.mjs +471 -54
  21. package/package.json +16 -13
  22. package/.eslintrc.json +0 -44
  23. package/.prettierignore +0 -1
  24. package/.prettierrc +0 -4
  25. package/build.ts +0 -97
  26. package/eslint.config.mjs +0 -76
  27. package/k6-tests/README.md +0 -144
  28. package/k6-tests/bun.lock +0 -797
  29. package/k6-tests/load-test/load-test-crud-connections.ts +0 -263
  30. package/k6-tests/load-test/load-test-crud-packages.ts +0 -461
  31. package/k6-tests/load-test/load-test-crud-projects.ts +0 -160
  32. package/k6-tests/load-test/load-test-crud.ts +0 -142
  33. package/k6-tests/load-test/load-test.ts +0 -784
  34. package/k6-tests/package.json +0 -27
  35. package/k6-tests/scripts/run-with-otel.sh +0 -50
  36. package/k6-tests/smoke-test/smoke-test.ts +0 -158
  37. package/k6-tests/tsconfig.json +0 -29
  38. package/k6-tests/utils/client_factory.ts +0 -128
  39. package/k6-tests/utils/common.ts +0 -489
  40. package/k6-tests/utils/logger.ts +0 -62
  41. package/k6-tests/utils/types.d.ts +0 -35
  42. package/malloy_mcp.dxt +0 -0
  43. package/publisher.config.example.bigquery.json +0 -33
  44. package/publisher.config.example.duckdb.json +0 -23
  45. package/publisher.config.json +0 -23
  46. package/scripts/bake-duckdb-extensions.js +0 -110
  47. package/src/config.spec.ts +0 -1535
  48. package/src/config.theme.spec.ts +0 -178
  49. package/src/config.ts +0 -1142
  50. package/src/constants.ts +0 -105
  51. package/src/controller/compile.controller.ts +0 -40
  52. package/src/controller/connection.controller.spec.ts +0 -849
  53. package/src/controller/connection.controller.ts +0 -901
  54. package/src/controller/database.controller.ts +0 -24
  55. package/src/controller/materialization.controller.spec.ts +0 -293
  56. package/src/controller/materialization.controller.ts +0 -319
  57. package/src/controller/model.controller.ts +0 -164
  58. package/src/controller/package.controller.spec.ts +0 -273
  59. package/src/controller/package.controller.ts +0 -306
  60. package/src/controller/query.controller.ts +0 -152
  61. package/src/controller/theme.controller.ts +0 -83
  62. package/src/controller/watch-mode.controller.ts +0 -243
  63. package/src/data_styles.ts +0 -71
  64. package/src/default-publisher.config.json +0 -23
  65. package/src/ducklake_version.spec.ts +0 -163
  66. package/src/ducklake_version.ts +0 -153
  67. package/src/errors.spec.ts +0 -119
  68. package/src/errors.ts +0 -237
  69. package/src/filter_deprecation.spec.ts +0 -64
  70. package/src/filter_deprecation.ts +0 -42
  71. package/src/health.spec.ts +0 -123
  72. package/src/health.ts +0 -233
  73. package/src/heap_check.spec.ts +0 -144
  74. package/src/heap_check.ts +0 -144
  75. package/src/instrumentation.ts +0 -214
  76. package/src/json_utils.spec.ts +0 -51
  77. package/src/json_utils.ts +0 -33
  78. package/src/logger.spec.ts +0 -210
  79. package/src/logger.ts +0 -251
  80. package/src/malloy_pin_prereqs.spec.ts +0 -25
  81. package/src/materialization_metrics.spec.ts +0 -169
  82. package/src/materialization_metrics.ts +0 -346
  83. package/src/mcp/error_messages.spec.ts +0 -35
  84. package/src/mcp/error_messages.ts +0 -183
  85. package/src/mcp/handler_utils.spec.ts +0 -108
  86. package/src/mcp/handler_utils.ts +0 -251
  87. package/src/mcp/mcp_constants.ts +0 -6
  88. package/src/mcp/query_envelope.spec.ts +0 -229
  89. package/src/mcp/query_envelope.ts +0 -240
  90. package/src/mcp/server.protocol.spec.ts +0 -250
  91. package/src/mcp/server.ts +0 -87
  92. package/src/mcp/skills/build_skills_bundle.spec.ts +0 -51
  93. package/src/mcp/skills/build_skills_bundle.ts +0 -176
  94. package/src/mcp/skills/skills_bundle.json +0 -1
  95. package/src/mcp/skills/skills_bundle.spec.ts +0 -171
  96. package/src/mcp/tool_response.spec.ts +0 -108
  97. package/src/mcp/tool_response.ts +0 -138
  98. package/src/mcp/tools/compile_tool.spec.ts +0 -315
  99. package/src/mcp/tools/compile_tool.ts +0 -208
  100. package/src/mcp/tools/docs_search/build_docs_index.ts +0 -132
  101. package/src/mcp/tools/docs_search/malloy_docs_index.json +0 -1
  102. package/src/mcp/tools/docs_search_tool.spec.ts +0 -32
  103. package/src/mcp/tools/docs_search_tool.ts +0 -128
  104. package/src/mcp/tools/embedding_index.spec.ts +0 -1236
  105. package/src/mcp/tools/embedding_index.ts +0 -808
  106. package/src/mcp/tools/execute_query_tool.spec.ts +0 -294
  107. package/src/mcp/tools/execute_query_tool.ts +0 -316
  108. package/src/mcp/tools/get_context_eval.ts +0 -275
  109. package/src/mcp/tools/get_context_tool.spec.ts +0 -592
  110. package/src/mcp/tools/get_context_tool.ts +0 -585
  111. package/src/mcp/tools/reload_package_tool.spec.ts +0 -232
  112. package/src/mcp/tools/reload_package_tool.ts +0 -132
  113. package/src/mcp_config.spec.ts +0 -919
  114. package/src/mcp_config.ts +0 -425
  115. package/src/oom_guards.integration.spec.ts +0 -269
  116. package/src/package_load/package_load_pool.spec.ts +0 -252
  117. package/src/package_load/package_load_pool.ts +0 -931
  118. package/src/package_load/package_load_worker.ts +0 -1034
  119. package/src/package_load/protocol.ts +0 -364
  120. package/src/package_load/rpc_wait_accountant.spec.ts +0 -109
  121. package/src/package_load/rpc_wait_accountant.ts +0 -76
  122. package/src/package_load_metrics.spec.ts +0 -114
  123. package/src/package_load_metrics.ts +0 -127
  124. package/src/path_safety.spec.ts +0 -158
  125. package/src/path_safety.ts +0 -146
  126. package/src/pg_helpers.spec.ts +0 -223
  127. package/src/pg_helpers.ts +0 -52
  128. package/src/query_cap_metrics.spec.ts +0 -89
  129. package/src/query_cap_metrics.ts +0 -116
  130. package/src/query_concurrency.spec.ts +0 -247
  131. package/src/query_concurrency.ts +0 -237
  132. package/src/query_metadata_metrics.ts +0 -49
  133. package/src/query_param_utils.ts +0 -29
  134. package/src/query_timeout.spec.ts +0 -224
  135. package/src/query_timeout.ts +0 -179
  136. package/src/runtime/publisher.js +0 -328
  137. package/src/server-old.ts +0 -988
  138. package/src/server.ts +0 -2059
  139. package/src/service/annotations.spec.ts +0 -118
  140. package/src/service/annotations.ts +0 -91
  141. package/src/service/authorize.spec.ts +0 -154
  142. package/src/service/authorize.ts +0 -498
  143. package/src/service/authorize_integration.spec.ts +0 -2041
  144. package/src/service/build_plan.spec.ts +0 -685
  145. package/src/service/build_plan.ts +0 -797
  146. package/src/service/compile_authorize.spec.ts +0 -85
  147. package/src/service/compile_fragment_techniques.spec.ts +0 -156
  148. package/src/service/connection.spec.ts +0 -2360
  149. package/src/service/connection.ts +0 -2187
  150. package/src/service/connection_config.spec.ts +0 -734
  151. package/src/service/connection_config.ts +0 -899
  152. package/src/service/connection_federation.spec.ts +0 -184
  153. package/src/service/connection_fingerprint.spec.ts +0 -102
  154. package/src/service/connection_service.spec.ts +0 -711
  155. package/src/service/connection_service.ts +0 -291
  156. package/src/service/cron_evaluator.spec.ts +0 -79
  157. package/src/service/cron_evaluator.ts +0 -105
  158. package/src/service/db_utils.spec.ts +0 -1085
  159. package/src/service/db_utils.ts +0 -1502
  160. package/src/service/duckdb_instance_isolation.spec.ts +0 -137
  161. package/src/service/ducklake_lazy_attach.spec.ts +0 -110
  162. package/src/service/embedding_provider.spec.ts +0 -329
  163. package/src/service/embedding_provider.ts +0 -236
  164. package/src/service/environment.ts +0 -2191
  165. package/src/service/environment_admission.spec.ts +0 -344
  166. package/src/service/environment_compile.spec.ts +0 -197
  167. package/src/service/environment_store.spec.ts +0 -2274
  168. package/src/service/environment_store.ts +0 -2434
  169. package/src/service/environment_store_anchoring.spec.ts +0 -107
  170. package/src/service/environment_store_clone.spec.ts +0 -350
  171. package/src/service/explore_visibility.spec.ts +0 -434
  172. package/src/service/exports_probe.spec.ts +0 -107
  173. package/src/service/extension_fetch_policy.spec.ts +0 -256
  174. package/src/service/filter.spec.ts +0 -458
  175. package/src/service/filter.ts +0 -341
  176. package/src/service/filter_bypass.spec.ts +0 -418
  177. package/src/service/filter_integration.spec.ts +0 -1004
  178. package/src/service/freshness.spec.ts +0 -183
  179. package/src/service/freshness.ts +0 -112
  180. package/src/service/gcs_s3_utils.ts +0 -427
  181. package/src/service/given.ts +0 -105
  182. package/src/service/givens_integration.spec.ts +0 -219
  183. package/src/service/manifest_loader.spec.ts +0 -189
  184. package/src/service/manifest_loader.ts +0 -156
  185. package/src/service/materialization_build_session.spec.ts +0 -435
  186. package/src/service/materialization_build_session.ts +0 -681
  187. package/src/service/materialization_config_validation.spec.ts +0 -99
  188. package/src/service/materialization_config_validation.ts +0 -120
  189. package/src/service/materialization_eligibility.spec.ts +0 -158
  190. package/src/service/materialization_eligibility.ts +0 -305
  191. package/src/service/materialization_schedule_surface.spec.ts +0 -256
  192. package/src/service/materialization_scheduler.spec.ts +0 -289
  193. package/src/service/materialization_scheduler.ts +0 -304
  194. package/src/service/materialization_serve_transform.spec.ts +0 -1003
  195. package/src/service/materialization_serve_transform.ts +0 -779
  196. package/src/service/materialization_service.spec.ts +0 -2373
  197. package/src/service/materialization_service.ts +0 -2342
  198. package/src/service/materialization_test_fixtures.ts +0 -249
  199. package/src/service/model.spec.ts +0 -1157
  200. package/src/service/model.ts +0 -3370
  201. package/src/service/model_limits.spec.ts +0 -209
  202. package/src/service/model_limits.ts +0 -131
  203. package/src/service/model_storage_serve.spec.ts +0 -193
  204. package/src/service/model_storage_serve_joins.spec.ts +0 -193
  205. package/src/service/package.spec.ts +0 -612
  206. package/src/service/package.ts +0 -1799
  207. package/src/service/package_manifest.spec.ts +0 -230
  208. package/src/service/package_manifest.ts +0 -241
  209. package/src/service/package_memory_governor.spec.ts +0 -173
  210. package/src/service/package_memory_governor.ts +0 -233
  211. package/src/service/package_quote_bound_tables.spec.ts +0 -171
  212. package/src/service/package_race.spec.ts +0 -208
  213. package/src/service/package_reload_safety.spec.ts +0 -193
  214. package/src/service/package_rollback.spec.ts +0 -190
  215. package/src/service/package_worker_path.spec.ts +0 -645
  216. package/src/service/path_injection.spec.ts +0 -39
  217. package/src/service/persist_annotation_validation.spec.ts +0 -89
  218. package/src/service/persist_annotation_validation.ts +0 -59
  219. package/src/service/persistence_policy.spec.ts +0 -374
  220. package/src/service/proxy.spec.ts +0 -414
  221. package/src/service/proxy.ts +0 -248
  222. package/src/service/query_boundary.spec.ts +0 -470
  223. package/src/service/query_metadata.spec.ts +0 -408
  224. package/src/service/query_metadata.ts +0 -492
  225. package/src/service/query_metadata_identity.spec.ts +0 -149
  226. package/src/service/query_text.spec.ts +0 -79
  227. package/src/service/query_text.ts +0 -43
  228. package/src/service/quoting.spec.ts +0 -135
  229. package/src/service/quoting.ts +0 -78
  230. package/src/service/resolve_environment.ts +0 -15
  231. package/src/service/restricted_mode.spec.ts +0 -299
  232. package/src/service/source_extraction.ts +0 -225
  233. package/src/service/theme_store.ts +0 -199
  234. package/src/storage/DatabaseInterface.ts +0 -198
  235. package/src/storage/StorageManager.ts +0 -113
  236. package/src/storage/duckdb/ConnectionRepository.ts +0 -143
  237. package/src/storage/duckdb/DuckDBConnection.ts +0 -123
  238. package/src/storage/duckdb/DuckDBRepository.ts +0 -208
  239. package/src/storage/duckdb/EnvironmentRepository.ts +0 -148
  240. package/src/storage/duckdb/MaterializationRepository.spec.ts +0 -191
  241. package/src/storage/duckdb/MaterializationRepository.ts +0 -336
  242. package/src/storage/duckdb/PackageRepository.ts +0 -135
  243. package/src/storage/duckdb/schema.ts +0 -229
  244. package/src/stream_helpers.spec.ts +0 -280
  245. package/src/stream_helpers.ts +0 -162
  246. package/src/telemetry.ts +0 -20
  247. package/src/test_helpers/metrics_harness.ts +0 -166
  248. package/src/theme_key_parity.spec.ts +0 -57
  249. package/src/utils.ts +0 -29
  250. package/tests/fixtures/authorize-compile/model.malloy +0 -9
  251. package/tests/fixtures/authorize-compile/publisher.json +0 -4
  252. package/tests/fixtures/html-pages-nopublic/model.malloy +0 -1
  253. package/tests/fixtures/html-pages-nopublic/publisher.json +0 -5
  254. package/tests/fixtures/html-pages-test/data.csv +0 -3
  255. package/tests/fixtures/html-pages-test/public/assets/app.css +0 -3
  256. package/tests/fixtures/html-pages-test/public/barehtml.html +0 -4
  257. package/tests/fixtures/html-pages-test/public/bodymeta.html +0 -8
  258. package/tests/fixtures/html-pages-test/public/data.json +0 -1
  259. package/tests/fixtures/html-pages-test/public/fitcomment.html +0 -11
  260. package/tests/fixtures/html-pages-test/public/index.html +0 -9
  261. package/tests/fixtures/html-pages-test/public/nohead.html +0 -8
  262. package/tests/fixtures/html-pages-test/public/notfit.html +0 -13
  263. package/tests/fixtures/html-pages-test/public/slides.html +0 -12
  264. package/tests/fixtures/html-pages-test/public/sub/page2.html +0 -9
  265. package/tests/fixtures/html-pages-test/public/unterminated.html +0 -10
  266. package/tests/fixtures/html-pages-test/publisher.json +0 -5
  267. package/tests/fixtures/html-pages-test/report.malloy +0 -1
  268. package/tests/fixtures/persist-multi-level/data/orders.csv +0 -5
  269. package/tests/fixtures/persist-multi-level/multi_level.malloy +0 -18
  270. package/tests/fixtures/persist-multi-level/publisher.json +0 -5
  271. package/tests/fixtures/persist-schedule-test/data/orders.csv +0 -5
  272. package/tests/fixtures/persist-schedule-test/persist_schedule_test.malloy +0 -11
  273. package/tests/fixtures/persist-schedule-test/publisher.json +0 -7
  274. package/tests/fixtures/persist-schedule-warn-test/data/orders.csv +0 -5
  275. package/tests/fixtures/persist-schedule-warn-test/persist_warn_test.malloy +0 -11
  276. package/tests/fixtures/persist-schedule-warn-test/publisher.json +0 -6
  277. package/tests/fixtures/persist-test/data/orders.csv +0 -5
  278. package/tests/fixtures/persist-test/persist_test.malloy +0 -11
  279. package/tests/fixtures/persist-test/publisher.json +0 -5
  280. package/tests/fixtures/publisher.config.json +0 -15
  281. package/tests/fixtures/query-givens/data/orders.csv +0 -7
  282. package/tests/fixtures/query-givens/model.malloy +0 -34
  283. package/tests/fixtures/query-givens/publisher.json +0 -5
  284. package/tests/fixtures/xlsx/database.xlsx +0 -0
  285. package/tests/harness/mcp_test_setup.ts +0 -332
  286. package/tests/harness/rest_e2e.ts +0 -68
  287. package/tests/integration/authorize/compile_authorize_http.integration.spec.ts +0 -92
  288. package/tests/integration/concurrent_package/concurrent_package.integration.spec.ts +0 -280
  289. package/tests/integration/duckdb_storage/duckdb_storage.integration.spec.ts +0 -138
  290. package/tests/integration/first_boot/readiness_line.integration.spec.ts +0 -177
  291. package/tests/integration/html_pages/html_pages.integration.spec.ts +0 -440
  292. package/tests/integration/legacy_routes/legacy_routes.integration.spec.ts +0 -259
  293. package/tests/integration/materialization/environment_list.integration.spec.ts +0 -133
  294. package/tests/integration/materialization/freshness_gate.integration.spec.ts +0 -292
  295. package/tests/integration/materialization/manifest_binding.integration.spec.ts +0 -430
  296. package/tests/integration/materialization/materialization_lifecycle.integration.spec.ts +0 -441
  297. package/tests/integration/materialization/orchestrated_rebind.integration.spec.ts +0 -150
  298. package/tests/integration/materialization/reference_manifest.integration.spec.ts +0 -251
  299. package/tests/integration/materialization/schedule_edit.integration.spec.ts +0 -126
  300. package/tests/integration/materialization/scheduler.integration.spec.ts +0 -200
  301. package/tests/integration/materialization/scheduler_recovery.integration.spec.ts +0 -172
  302. package/tests/integration/materialization/scheduler_transitions.integration.spec.ts +0 -256
  303. package/tests/integration/materialization/scheduler_wiring.integration.spec.ts +0 -143
  304. package/tests/integration/mcp/mcp_execute_query_tool.integration.spec.ts +0 -438
  305. package/tests/integration/mcp/mcp_get_context_semantic.integration.spec.ts +0 -235
  306. package/tests/integration/mcp/mcp_transport.integration.spec.ts +0 -98
  307. package/tests/integration/query_givens/query_givens.integration.spec.ts +0 -146
  308. package/tests/integration/query_givens/query_givens_authorize.integration.spec.ts +0 -121
  309. package/tests/integration/sdk_givens/sdk_givens.integration.spec.ts +0 -110
  310. package/tests/integration/watch-mode/watch_mode.integration.spec.ts +0 -421
  311. package/tests/unit/controller/theme.controller.spec.ts +0 -141
  312. package/tests/unit/duckdb/attached_databases.test.ts +0 -1243
  313. package/tests/unit/duckdb/duckdb_connection.test.ts +0 -181
  314. package/tests/unit/duckdb/legacy_schema_migration.test.ts +0 -197
  315. package/tests/unit/duckdb/repositories.test.ts +0 -208
  316. package/tests/unit/ducklake/ducklake.test.ts +0 -952
  317. package/tests/unit/service/theme_store.spec.ts +0 -139
  318. package/tsconfig.json +0 -32
@@ -1,1003 +0,0 @@
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
- });