@malloy-publisher/server 0.16.1 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/app/api-doc.yaml +371 -645
  2. package/dist/app/assets/{EnvironmentPage-Y9IWPC9J.js → EnvironmentPage-DF2PahCR.js} +1 -1
  3. package/dist/app/assets/{HomePage-BOUo0MEl.js → HomePage-DIYlgPCz.js} +1 -1
  4. package/dist/app/assets/{MainPage-BkM5UDRU.js → MainPage-C7PGAA5k.js} +1 -1
  5. package/dist/app/assets/ModelPage-BMoBnrW7.js +2 -0
  6. package/dist/app/assets/PackagePage-DD2vLSFe.js +1 -0
  7. package/dist/app/assets/{PackageSplatRoute-BLC29ek-.js → PackageSplatRoute-BYIMwnLL.js} +2 -2
  8. package/dist/app/assets/{RenderedResult-vyM2wQbC.es-ha8dF24T.js → RenderedResult-CYJ2Y9Fm.es-C8nokn71.js} +7 -7
  9. package/dist/app/assets/{RouteError-BolMqTuz.js → RouteError-B8dE60Vs.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-CPv1eHkI.js → ThemeEditorPage-D0wf74fh.js} +1 -1
  11. package/dist/app/assets/{ToggleButtonGroup-DZtImN0S.js → ToggleButtonGroup-CX0_J2zR.js} +1 -1
  12. package/dist/app/assets/{documentRoutes-DI5cX3ty.js → documentRoutes-DgSMAc0m.js} +1 -1
  13. package/dist/app/assets/{editPageMounted-C--4kcld.js → editPageMounted-BUGVg-_g.js} +2 -2
  14. package/dist/app/assets/{index-DyYEltlF.js → index-BQL8UUcK.js} +1 -1
  15. package/dist/app/assets/{index-D9wSfMZN.js → index-BiOT4K_d.js} +1 -1
  16. package/dist/app/assets/{index-CbsrzNSp.js → index-DAQjZOAL.js} +1 -1
  17. package/dist/app/assets/index-DRkw60sj.js +512 -0
  18. package/dist/app/assets/{index.es-D8SVyfmS.js → index.es-DgNl8IqU.js} +20 -20
  19. package/dist/app/assets/usePackageLinkNavigate-bHr_AFYo.js +1 -0
  20. package/dist/app/assets/{usePackageRoute-A_YQMrax.js → usePackageRoute-BhB6txS6.js} +1 -1
  21. package/dist/app/index.html +1 -1
  22. package/dist/app/mcp-app/report.js +2683 -757
  23. package/dist/instrumentation.mjs +4 -4
  24. package/dist/package_load_worker.mjs +836 -125
  25. package/dist/server.mjs +4520 -1743
  26. package/dist/{sshcrypto-fqcyz88x.node → sshcrypto-wf5kpffj.node} +0 -0
  27. package/package.json +1 -1
  28. package/dist/app/assets/ModelPage-PgDTkS5C.js +0 -2
  29. package/dist/app/assets/PackagePage-Dn7FrQ5r.js +0 -1
  30. package/dist/app/assets/index-DLToSg1f.js +0 -512
  31. package/dist/app/assets/usePackageLinkNavigate-DxHGKrmZ.js +0 -1
@@ -76,6 +76,71 @@ var init_constants = __esm(() => {
76
76
 
77
77
  // src/service/deprecated/malloynb.ts
78
78
  import { MalloySQLParser } from "@malloydata/malloy-sql";
79
+ function listMalloynbCellFindings(notebooks, limits) {
80
+ const warnings = [];
81
+ let listed = 0;
82
+ let unlisted = 0;
83
+ const past = [];
84
+ const pastByReason = new Map;
85
+ for (const { model, refusals } of notebooks) {
86
+ const shown = Math.max(0, Math.min(limits.perNotebook, limits.perPackage - listed));
87
+ const kept = refusals.slice(0, shown);
88
+ const rest = refusals.slice(shown);
89
+ warnings.push(...kept.map((r) => r.finding));
90
+ listed += kept.length;
91
+ if (rest.length === 0)
92
+ continue;
93
+ unlisted += rest.length;
94
+ if (kept.length === 0) {
95
+ past.push({ model, cells: rest.length });
96
+ for (const { finding } of rest) {
97
+ const reason = finding.reason ?? "unknown";
98
+ pastByReason.set(reason, (pastByReason.get(reason) ?? 0) + 1);
99
+ }
100
+ continue;
101
+ }
102
+ const byReason = new Map;
103
+ for (const { cell, finding } of rest) {
104
+ const reason = finding.reason ?? "unknown";
105
+ const cells = byReason.get(reason);
106
+ if (cells)
107
+ cells.push(cell);
108
+ else
109
+ byReason.set(reason, [cell]);
110
+ }
111
+ const groups = Array.from(byReason, ([reason, cells]) => `${cells.length === 1 ? "cell" : "cells"} ${numberList(cells)} (${reason})`).join("; ");
112
+ warnings.push({
113
+ model,
114
+ code: MALLOYNB_CELLS_UNLISTED,
115
+ severity: "warn",
116
+ message: `${rest.length} more ${rest.length === 1 ? "cell" : "cells"} of ` + `${model} won't run for any reader in the Console, not listed ` + `one by one: ${groups}. ${FIX_AND_RELOAD}`
117
+ });
118
+ }
119
+ if (past.length > 0) {
120
+ const cells = past.reduce((sum, notebook) => sum + notebook.cells, 0);
121
+ const named = past.slice(0, limits.notebooksNamed).map((notebook) => `${notebook.cells} in ${notebook.model}`);
122
+ const others = past.slice(limits.notebooksNamed);
123
+ if (others.length > 0) {
124
+ const otherCells = others.reduce((sum, n) => sum + n.cells, 0);
125
+ named.push(`${otherCells} in ${others.length} other ` + `${others.length === 1 ? "notebook" : "notebooks"}`);
126
+ }
127
+ const reasons = Array.from(pastByReason, ([reason, count]) => `${count} ${reason}`);
128
+ warnings.push({
129
+ code: MALLOYNB_CELLS_UNLISTED,
130
+ severity: "warn",
131
+ message: `${cells} more ${cells === 1 ? "cell" : "cells"}, in ` + `${past.length} more ` + `${past.length === 1 ? "notebook" : "notebooks"}, won't run for ` + `any reader in the Console, not listed because the package lists ` + `at most ${limits.perPackage} one by one: ${wordList(named)}. ` + `By reason: ${wordList(reasons)}. ${FIX_AND_RELOAD}`
132
+ });
133
+ }
134
+ return { warnings, unlisted };
135
+ }
136
+ function numberList(numbers) {
137
+ return wordList(numbers.map(String));
138
+ }
139
+ function wordList(words) {
140
+ if (words.length === 1)
141
+ return words[0];
142
+ return `${words.slice(0, -1).join(", ")} and ${words[words.length - 1]}`;
143
+ }
79
144
  function isMalloynbPath(modelPath) {
80
145
  return modelPath.endsWith(NOTEBOOK_FILE_SUFFIX);
81
146
  }
@@ -83,8 +148,15 @@ function parseMalloynb(fileContents, modelPath) {
83
148
  return MalloySQLParser.parse(fileContents.replace(/\r\n/g, `
84
149
  `), modelPath);
85
150
  }
151
+ var MALLOYNB_CELL_REFUSED = "malloynb-cell-refused", MALLOYNB_CELLS_UNLISTED = "malloynb-cells-unlisted", MALLOYNB_CELL_CHECK_FAILED = "malloynb-cell-check-failed", MALLOYNB_CELLS_LISTED, FIX_AND_RELOAD;
86
152
  var init_malloynb = __esm(() => {
87
153
  init_constants();
154
+ MALLOYNB_CELLS_LISTED = {
155
+ perNotebook: 10,
156
+ perPackage: 50,
157
+ notebooksNamed: 10
158
+ };
159
+ FIX_AND_RELOAD = "The legacy .malloynb section of docs/reports.md gives the fix for each " + "reason, and a reload after fixing lists what remains.";
88
160
  });
89
161
 
90
162
  // ../../node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js
@@ -2167,7 +2239,7 @@ var init_query = __esm(() => {
2167
2239
  type: integer({ min: 0 }),
2168
2240
  default: DEFAULT_MAX_QUERY_ROWS,
2169
2241
  description: "Row cap on ad-hoc connection SQL; 0 leaves only the byte cap.",
2170
- notes: "Maximum rows returned per query on every query surface (`/connections/.../sqlQuery`, model query, notebook cell, MCP `executeQuery`). Forwarded to the connector / Malloy `runnable.run` as the effective row limit; queries that exceed the cap fail with HTTP 413. Set to `0` to disable. A caller-supplied `rowLimit` smaller than the cap is preserved.",
2242
+ notes: "Maximum rows returned per query on every query surface (`/connections/.../sqlQuery`, model query, MCP `executeQuery`). Forwarded to the connector / Malloy `runnable.run` as the effective row limit; queries that exceed the cap fail with HTTP 413. Set to `0` to disable. A caller-supplied `rowLimit` smaller than the cap is preserved.",
2171
2243
  aliases: { env: ["PUBLISHER_MAX_QUERY_ROWS"] }
2172
2244
  }),
2173
2245
  setting({
@@ -2175,7 +2247,7 @@ var init_query = __esm(() => {
2175
2247
  type: integer({ min: 0 }),
2176
2248
  default: DEFAULT_MAX_RESPONSE_BYTES,
2177
2249
  description: "Byte cap on ad-hoc connection SQL responses; 0 leaves only the row cap.",
2178
- notes: "Maximum JSON-serialized response size, for ad-hoc SQL, model queries and notebook cells. Streaming-capable connections (Postgres, DuckDB) enforce mid-stream and abort the driver immediately; non-streaming connections enforce post-buffer. Exceeding the cap fails with HTTP 413. Set to `0` to disable. See the note below the table.",
2250
+ notes: "Maximum JSON-serialized response size, for ad-hoc SQL and model queries. Streaming-capable connections (Postgres, DuckDB) enforce mid-stream and abort the driver immediately; non-streaming connections enforce post-buffer. Exceeding the cap fails with HTTP 413. Set to `0` to disable. See the note below the table.",
2179
2251
  defaultText: "`50000000` (50 MB)",
2180
2252
  aliases: { env: ["PUBLISHER_MAX_RESPONSE_BYTES"] }
2181
2253
  }),
@@ -2632,7 +2704,7 @@ var init_server = __esm(() => {
2632
2704
  type: oneOf(["explorer", "viewer"]),
2633
2705
  default: "explorer",
2634
2706
  description: "The page the Console shows for a model, reported on /status as modelPage: explorer, or viewer, which builds no query and takes the Explorer out of the legacy notebook too.",
2635
- notes: "`explorer` or `viewer`: the page the Console shows for a model, reported on `/status` as `modelPage`. `explorer` is the [Explorer](explorer.md), which writes the queries it builds back to Malloy with string values unescaped (`escapeString` in `@malloydata/malloy-interfaces` is a TODO), so a drilled value holding a double quote rewrites its query; the server's restricted mode and `#(authorize)` still bound what that query can read. `viewer` shows the model viewer, which builds no query, and also takes the Explorer's \"Data sources\" dialog out of the legacy notebook; there a given's option list also quotes every name. The Console keeps both pages, and shows the viewer if `/status` cannot be read. Any other value fails startup.",
2707
+ notes: "`explorer` or `viewer`: the page the Console shows for a model, reported on `/status` as `modelPage`. `explorer` is the [Explorer](explorer.md), which builds queries; the server's restricted mode and `#(authorize)` bound what those queries can read. `viewer` shows the model viewer, which builds no query, and also takes the Explorer's \"Data sources\" dialog out of the legacy notebook; there a given's option list also quotes every name. The Console keeps both pages, and shows the viewer if `/status` cannot be read. Any other value fails startup.",
2636
2708
  noFlag: true,
2637
2709
  aliases: { env: ["PUBLISHER_MODEL_PAGE"] }
2638
2710
  }),
@@ -12565,7 +12637,7 @@ function declaredFreshnessFacts(declarations) {
12565
12637
  ...fallback !== undefined ? { freshnessFallback: fallback } : {}
12566
12638
  };
12567
12639
  }
12568
- var FRESHNESS_FALLBACKS, WINDOW_UNITS, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
12640
+ var FRESHNESS_FALLBACKS, WINDOW_UNITS, FRESHNESS_WINDOW_PROBLEM, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
12569
12641
  var init_freshness = __esm(() => {
12570
12642
  FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
12571
12643
  WINDOW_UNITS = {
@@ -12575,6 +12647,7 @@ var init_freshness = __esm(() => {
12575
12647
  d: 86400,
12576
12648
  w: 604800
12577
12649
  };
12650
+ FRESHNESS_WINDOW_PROBLEM = "has a freshness.window= that is not a positive duration: write a whole " + 'number greater than zero and one unit (s, m, h, d or w), such as freshness.window="24h"';
12578
12651
  DURATION_UNITS = {
12579
12652
  ...WINDOW_UNITS,
12580
12653
  second: 1,
@@ -12679,7 +12752,7 @@ function freshnessValueProblem(group) {
12679
12752
  if (group.has("window")) {
12680
12753
  const window2 = group.text("window");
12681
12754
  if (window2 === undefined || freshnessWindowSeconds(window2) === undefined) {
12682
- return 'has a freshness.window= that is not a whole number and a unit (s, m, h, d or w), such as freshness.window="24h"';
12755
+ return FRESHNESS_WINDOW_PROBLEM;
12683
12756
  }
12684
12757
  }
12685
12758
  if (group.has("fallback") && !isFreshnessFallback(group.text("fallback"))) {
@@ -13385,18 +13458,16 @@ ${body}`;
13385
13458
  if (modelDef && runCount !== modelDef.queryList.length) {
13386
13459
  return refuse({
13387
13460
  line: 1,
13388
- message: `Line 1: the notebook reader found ${runCount} run: statements where Malloy compiled ${modelDef.queryList.length}, so its query cells cannot be matched to their results. Fix: none in the file; report it, since the reader and the compiler disagree.`
13461
+ message: `Line 1: the notebook reader and the Malloy compiler disagree on the number of run: statements. The reader found ${runCount} and the compiler ${modelDef.queryList.length}. Fix: none in the file; report it.`
13389
13462
  });
13390
13463
  }
13391
13464
  const cells = [];
13392
13465
  const annotations = [];
13393
13466
  let lineRun;
13394
- let runsSeen = 0;
13395
13467
  items.forEach((item, index) => {
13396
13468
  const belowTag = index > artifactAt;
13397
13469
  if (item.kind === "statement") {
13398
13470
  lineRun = undefined;
13399
- const queryIndex = item.run ? runsSeen++ : undefined;
13400
13471
  const pushed = item.run && belowTag ? {
13401
13472
  kind: "query",
13402
13473
  type: "code",
@@ -13410,8 +13481,7 @@ ${body}`;
13410
13481
  caption: item.caption
13411
13482
  },
13412
13483
  startLine: item.startLine,
13413
- endLine: item.endLine,
13414
- queryIndex
13484
+ endLine: item.endLine
13415
13485
  } : {
13416
13486
  kind: "definition",
13417
13487
  type: "code",
@@ -14094,7 +14164,7 @@ function errorKind(error) {
14094
14164
  function errorMapping(error) {
14095
14165
  return ERROR_TABLE[errorKind(error)];
14096
14166
  }
14097
- var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, WarehouseRecomputeRefusedError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
14167
+ var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, ResultTruncatedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, ResultShapeError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, WarehouseRecomputeRefusedError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
14098
14168
  var init_errors2 = __esm(() => {
14099
14169
  init_constants();
14100
14170
  init_logger();
@@ -14334,6 +14404,15 @@ var init_errors2 = __esm(() => {
14334
14404
  return "connection_failed";
14335
14405
  }
14336
14406
  };
14407
+ ResultTruncatedError = class ResultTruncatedError extends ConnectionError {
14408
+ get kind() {
14409
+ return "result_truncated";
14410
+ }
14411
+ constructor(returned, reported) {
14412
+ super(`The database returned ${returned} of the ${reported} rows it reported, and no row limit cut them: BigQuery returns one results page of about 10 MB, and the rest of the answer was not read. The query was refused rather than answered short. Project fewer columns or return fewer rows so the answer fits in one page.`, { callerSafe: true });
14413
+ this.name = "ResultTruncatedError";
14414
+ }
14415
+ };
14337
14416
  UnconfiguredConnectionError = class UnconfiguredConnectionError extends Error {
14338
14417
  get kind() {
14339
14418
  return "unconfigured_connection";
@@ -14351,6 +14430,17 @@ var init_errors2 = __esm(() => {
14351
14430
  this.name = "ConnectionPoolExhaustedError";
14352
14431
  }
14353
14432
  };
14433
+ ResultShapeError = class ResultShapeError extends ConnectionError {
14434
+ get kind() {
14435
+ return "result_shape";
14436
+ }
14437
+ constructor(options) {
14438
+ super("The database returned a row that does not fit the result's schema, " + "so the result could not be built.", { callerSafe: true });
14439
+ if (options?.cause !== undefined)
14440
+ this.cause = options.cause;
14441
+ this.name = "ResultShapeError";
14442
+ }
14443
+ };
14354
14444
  DestinationNotFoundError = class DestinationNotFoundError extends Error {
14355
14445
  get kind() {
14356
14446
  return "destination_not_found";
@@ -14727,6 +14817,8 @@ var init_errors2 = __esm(() => {
14727
14817
  connection_failed: ConnectionFailedError,
14728
14818
  unconfigured_connection: UnconfiguredConnectionError,
14729
14819
  connection_pool_exhausted: ConnectionPoolExhaustedError,
14820
+ result_truncated: ResultTruncatedError,
14821
+ result_shape: ResultShapeError,
14730
14822
  destination_not_found: DestinationNotFoundError,
14731
14823
  storage_destination_not_found: StorageDestinationNotFoundError,
14732
14824
  storage_catalog_not_found: StorageCatalogNotFoundError,
@@ -15021,6 +15113,27 @@ var init_errors2 = __esm(() => {
15021
15113
  ]
15022
15114
  }
15023
15115
  },
15116
+ result_truncated: {
15117
+ ...CONNECTION,
15118
+ reason: "RESULT_TRUNCATED",
15119
+ log: { summary: "Database result truncated", level: "warn" },
15120
+ mcp: {
15121
+ advice: "fixed",
15122
+ suggestions: [
15123
+ NOT_TRANSIENT_CHANGE_QUERY,
15124
+ "Shrink the answer so it fits in one results page of about 10 MB: select fewer columns, aggregate, or add a LIMIT."
15125
+ ]
15126
+ }
15127
+ },
15128
+ result_shape: {
15129
+ ...CONNECTION,
15130
+ reason: "RESULT_SHAPE_MISMATCH",
15131
+ log: {
15132
+ summary: "Database result does not fit its schema",
15133
+ level: "error"
15134
+ },
15135
+ mcp: { advice: "internal" }
15136
+ },
15024
15137
  materialization_not_found: { status: 404, mcp: { advice: "internal" } },
15025
15138
  materialization_conflict: {
15026
15139
  status: 409,
@@ -15469,6 +15582,9 @@ function probeFilterList(view) {
15469
15582
  const ref = view.structRef;
15470
15583
  return ref?.filterList;
15471
15584
  }
15585
+ function requiresUniqueKey(requirement) {
15586
+ return requirement !== undefined && requirement !== false;
15587
+ }
15472
15588
  function joinGrainAggregatePaths(view) {
15473
15589
  const out = [];
15474
15590
  let unreadable = false;
@@ -15483,9 +15599,9 @@ function joinGrainAggregatePaths(view) {
15483
15599
  const usage = node.expandedFieldUsage;
15484
15600
  if (Array.isArray(usage)) {
15485
15601
  for (const u of usage) {
15486
- if (!u || u.uniqueKeyRequirement === undefined)
15602
+ if (!u || !requiresUniqueKey(u.uniqueKeyRequirement))
15487
15603
  continue;
15488
- if (!Array.isArray(u.path) || u.path.some((p) => typeof p !== "string")) {
15604
+ if (u.uniqueKeyRequirement !== true || !Array.isArray(u.path) || u.path.some((p) => typeof p !== "string")) {
15489
15605
  unreadable = true;
15490
15606
  continue;
15491
15607
  }
@@ -15775,9 +15891,9 @@ function aggregateOutsideJoin(view, sourceDef, join) {
15775
15891
  if (!Array.isArray(usage))
15776
15892
  return;
15777
15893
  for (const u of usage) {
15778
- if (!u || u.uniqueKeyRequirement === undefined)
15894
+ if (!u || !requiresUniqueKey(u.uniqueKeyRequirement))
15779
15895
  continue;
15780
- if (!Array.isArray(u.path)) {
15896
+ if (u.uniqueKeyRequirement !== true || !Array.isArray(u.path)) {
15781
15897
  unreadable = true;
15782
15898
  continue;
15783
15899
  }
@@ -16206,8 +16322,8 @@ async function liftRowLevelCondition(compiler, sourceName, exprs) {
16206
16322
  async function validateAuthorizeProbes(compiler, options) {
16207
16323
  const ownNotesOf = options.authorizeOwnNotes ?? new Map;
16208
16324
  for (const [sourceName, groups] of options.authorizeMap ?? []) {
16209
- for (const { route, exprs } of groups) {
16210
- if (exprs.length === 0)
16325
+ for (const { route, exprs, fromBase } of groups) {
16326
+ if (exprs.length === 0 || fromBase)
16211
16327
  continue;
16212
16328
  let condition;
16213
16329
  try {
@@ -17403,6 +17519,7 @@ function gatePlan(struct, graph, options) {
17403
17519
  excludeNotes: options.excludeNotes ?? [],
17404
17520
  walkMembers: true,
17405
17521
  nameHops: 0,
17522
+ baseHops: 0,
17406
17523
  ownTexts: options.ownTexts
17407
17524
  }));
17408
17525
  metComposite ||= walk.metComposite;
@@ -17430,6 +17547,8 @@ function walkRoute(walk, struct, route, visit) {
17430
17547
  fromAncestor: level.fromAncestor,
17431
17548
  treatAsOwn: visit.treatAsOwn,
17432
17549
  entryPoint: visit.entryPoint,
17550
+ baseHops: visit.baseHops,
17551
+ level: struct,
17433
17552
  ...level.failure ? { failure: level.failure } : {}
17434
17553
  });
17435
17554
  }
@@ -17481,6 +17600,7 @@ function walkRoute(walk, struct, route, visit) {
17481
17600
  exprs: ["false"],
17482
17601
  fromAncestor: false,
17483
17602
  treatAsOwn: false,
17603
+ baseHops: visit.baseHops,
17484
17604
  failure: { kind: "base_unresolvable", message }
17485
17605
  });
17486
17606
  const base = hop.kind === "resolved" ? hop.base : undefined;
@@ -17492,7 +17612,8 @@ function walkRoute(walk, struct, route, visit) {
17492
17612
  entryPoint: visit.entryPoint,
17493
17613
  excludeNotes: [],
17494
17614
  walkMembers: false,
17495
- nameHops: hop.byName ? visit.nameHops + 1 : visit.nameHops
17615
+ nameHops: hop.byName ? visit.nameHops + 1 : visit.nameHops,
17616
+ baseHops: visit.baseHops + 1
17496
17617
  }));
17497
17618
  } else {
17498
17619
  steps.push(baseFailure(hop.message));
@@ -17505,7 +17626,8 @@ function walkRoute(walk, struct, route, visit) {
17505
17626
  entryPoint: visit.entryPoint,
17506
17627
  excludeNotes: base ? ownLevelNotes(base.annotations) : [],
17507
17628
  walkMembers: true,
17508
- nameHops: visit.nameHops
17629
+ nameHops: visit.nameHops,
17630
+ baseHops: visit.baseHops + 1
17509
17631
  }));
17510
17632
  }
17511
17633
  return steps;
@@ -17587,6 +17709,21 @@ import {
17587
17709
  isJoined as isJoined2,
17588
17710
  isSourceDef as isSourceDef4
17589
17711
  } from "@malloydata/malloy";
17712
+ function derivationLevel(root, landing, contents) {
17713
+ let current = root;
17714
+ for (let depth = 0;current && depth <= ANCESTOR_WALK_MAX_DEPTH; depth++) {
17715
+ if ("sourceID" in landing ? current.sourceID === landing.sourceID : depth === landing.hops) {
17716
+ return current;
17717
+ }
17718
+ if (current.type !== "query_source")
17719
+ return;
17720
+ const query = current.query;
17721
+ const ref = query?.compositeResolvedSourceDef ?? query?.structRef;
17722
+ const base = typeof ref === "string" ? contents?.[ref] : ref;
17723
+ current = base && typeof base === "object" && isSourceDef4(base) ? base : undefined;
17724
+ }
17725
+ return;
17726
+ }
17590
17727
  function createGateClassificationDeps(givens, modelPath) {
17591
17728
  return {
17592
17729
  gateShapeCache: new Map,
@@ -17613,7 +17750,9 @@ function collectEntryPointGates(struct, modelDef, seen = new Set, treatAsOwnGate
17613
17750
  exprs: step.exprs,
17614
17751
  route: step.route,
17615
17752
  selfContained: step.fromAncestor || !step.treatAsOwn,
17616
- ...step.entryPoint ? { struct: step.entryPoint } : {}
17753
+ ...step.entryPoint ? { struct: step.entryPoint } : {},
17754
+ baseHops: step.baseHops,
17755
+ ...step.level ? { level: step.level } : {}
17617
17756
  });
17618
17757
  }
17619
17758
  return entries;
@@ -17629,17 +17768,32 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17629
17768
  if (!graftTarget) {
17630
17769
  return { shape: "rejected" };
17631
17770
  }
17771
+ let landing;
17772
+ let liftTarget = graftTarget;
17773
+ if (entry.baseHops > 0 && entry.level) {
17774
+ liftTarget = resolveGraftTarget(entry.level, originModelDef, graftScope.modelDef) ?? graftTarget;
17775
+ }
17776
+ if (entry.baseHops > 0 && entry.route !== AUTHORIZE_ROUTE) {
17777
+ const target = graftScope.modelDef.contents[graftTarget];
17778
+ const sourceID = entry.level?.sourceID;
17779
+ const candidate = sourceID !== undefined ? { sourceID } : target === entry.struct || target?.sourceID !== undefined && target.sourceID === entry.struct.sourceID ? { hops: entry.baseHops } : undefined;
17780
+ if (!entry.level || !candidate || !derivationLevel(target, candidate, graftScope.modelDef.contents)) {
17781
+ logger.debug("Row-level gate on a derivation's base has no base to graft onto; denying", { modelPath: deps.modelPath, label: entry.label });
17782
+ return { shape: "rejected" };
17783
+ }
17784
+ landing = candidate;
17785
+ }
17632
17786
  const filterText = gateFilterText(entry.exprs);
17633
- const cacheKey = `${graftScope.cacheScope}\x00${entry.route}\x00${graftTarget}\x00${filterText}`;
17787
+ const cacheKey = `${graftScope.cacheScope}\x00${entry.route}\x00${liftTarget}\x00${filterText}`;
17634
17788
  let cached = deps.gateShapeCache.get(cacheKey);
17635
17789
  if (!cached) {
17636
17790
  let condition;
17637
17791
  try {
17638
- condition = await liftGateCondition(graftTarget, filterText, graftScope.materializer);
17792
+ condition = await liftGateCondition(liftTarget, filterText, graftScope.materializer);
17639
17793
  } catch (err) {
17640
17794
  logger.debug("Row-level gate condition failed to lift; denying", {
17641
17795
  modelPath: deps.modelPath,
17642
- graftTarget,
17796
+ graftTarget: liftTarget,
17643
17797
  error: err instanceof Error ? err.message : String(err)
17644
17798
  });
17645
17799
  return { shape: "rejected" };
@@ -17659,7 +17813,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17659
17813
  givenNamesById: new Map
17660
17814
  };
17661
17815
  } else {
17662
- const targetStruct = graftScope.modelDef.contents[graftTarget];
17816
+ const targetStruct = graftScope.modelDef.contents[liftTarget];
17663
17817
  if (!isSourceDef4(targetStruct)) {
17664
17818
  classification = {
17665
17819
  shape: "rejected",
@@ -17706,7 +17860,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17706
17860
  if (unreachable !== undefined) {
17707
17861
  logger.warn("Gate accepted a given off the model surface; denying", {
17708
17862
  modelPath: deps.modelPath,
17709
- graftTarget,
17863
+ graftTarget: liftTarget,
17710
17864
  givenName: unreachable
17711
17865
  });
17712
17866
  classification = {
@@ -17733,6 +17887,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17733
17887
  return {
17734
17888
  shape: "row_level",
17735
17889
  graftTarget,
17890
+ ...landing !== undefined ? { landing } : {},
17736
17891
  filterText,
17737
17892
  condition: cached.condition,
17738
17893
  givenNames: cached.classification.givenNames
@@ -17820,7 +17975,7 @@ function assertAuthorizeGrammarValid(modelDef, authorizeMap, authorizeOwnNotes,
17820
17975
  const ownGroupTerms = [];
17821
17976
  const declaredAdmitAllRoutes = [];
17822
17977
  const ownRoutesSeen = new Set;
17823
- for (const { route, exprs } of groups) {
17978
+ for (const { route, exprs, fromBase } of groups) {
17824
17979
  const isOwn = (authorizeOwnNotes.get(sourceName)?.get(route)?.length ?? 0) > 0 && !ownRoutesSeen.has(route);
17825
17980
  if (isOwn)
17826
17981
  ownRoutesSeen.add(route);
@@ -17833,7 +17988,7 @@ function assertAuthorizeGrammarValid(modelDef, authorizeMap, authorizeOwnNotes,
17833
17988
  if (term.scope === "admit_all" && (attributedAuthorizeOwnNotes?.get(sourceName)?.get(route)?.length ?? 0) > 0) {
17834
17989
  declaredAdmitAllRoutes.push(route);
17835
17990
  }
17836
- if (term.scope === "row_level" && isSourceDef4(struct)) {
17991
+ if (term.scope === "row_level" && !fromBase && isSourceDef4(struct)) {
17837
17992
  assertNoFanoutFieldPath(sourceName, struct, term.fieldPath, term.fieldPathSegments);
17838
17993
  }
17839
17994
  }
@@ -25178,6 +25333,9 @@ var init_filter = __esm(() => {
25178
25333
 
25179
25334
  // src/service/gate_registry_walk.ts
25180
25335
  function gateExprsForRoute(struct, modelDef, route) {
25336
+ return gateGroupsForRoute(struct, modelDef, route).map((g) => g.exprs);
25337
+ }
25338
+ function gateGroupsForRoute(struct, modelDef, route) {
25181
25339
  const { steps } = gatePlan(struct, modelDefGateGraph(modelDef), {
25182
25340
  composite: "resolved",
25183
25341
  routes: [route],
@@ -25189,7 +25347,7 @@ function gateExprsForRoute(struct, modelDef, route) {
25189
25347
  continue;
25190
25348
  if (step.failure?.kind === "unreadable")
25191
25349
  throw step.failure.error;
25192
- groups.push(step.exprs);
25350
+ groups.push({ exprs: step.exprs, fromBase: step.baseHops > 0 });
25193
25351
  }
25194
25352
  return groups;
25195
25353
  }
@@ -25348,11 +25506,15 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
25348
25506
  const groupsForSource = [];
25349
25507
  const routeGroupsByRoute = new Map;
25350
25508
  for (const route of CANONICAL_AUTHORIZE_ROUTES) {
25351
- const groupsForRoute = gateExprsForRoute(struct, modelDef, route);
25352
- for (const exprs of groupsForRoute) {
25353
- groupsForSource.push({ route, exprs });
25509
+ const groupsForRoute = gateGroupsForRoute(struct, modelDef, route);
25510
+ for (const { exprs, fromBase } of groupsForRoute) {
25511
+ groupsForSource.push({
25512
+ route,
25513
+ exprs,
25514
+ ...fromBase ? { fromBase: true } : {}
25515
+ });
25354
25516
  }
25355
- routeGroupsByRoute.set(route, groupsForRoute);
25517
+ routeGroupsByRoute.set(route, groupsForRoute.map((g) => g.exprs));
25356
25518
  }
25357
25519
  if (groupsForSource.length > 0) {
25358
25520
  authorizeMap.set(sourceName, groupsForSource);
@@ -25511,17 +25673,6 @@ var init_model_load_checks = __esm(() => {
25511
25673
 
25512
25674
  // src/service/model_notebook_cell.ts
25513
25675
  import { MalloySQLStatementType } from "@malloydata/malloy-sql";
25514
- function declaredGivensPerCell(cells) {
25515
- return cells.map((cell) => {
25516
- if (!cell.modelDef)
25517
- return;
25518
- const registry = cell.modelDef.givens ?? {};
25519
- return {
25520
- ids: new Set(Object.keys(registry)),
25521
- names: new Set(Object.values(registry).map((g) => g.name))
25522
- };
25523
- });
25524
- }
25525
25676
  async function tileQueryInfo(materializer, text) {
25526
25677
  try {
25527
25678
  const def = (await materializer.extendModel(text).getModel())._modelDef;
@@ -25579,7 +25730,6 @@ async function compileNotebookCells(runtime, importBaseURL, statements) {
25579
25730
  cells.push({
25580
25731
  type: "code",
25581
25732
  text: statement.text,
25582
- materializer,
25583
25733
  modelDef,
25584
25734
  newSources,
25585
25735
  query,
@@ -28357,6 +28507,10 @@ var init_array_query = __esm(() => {
28357
28507
  });
28358
28508
 
28359
28509
  // src/service/connection_type.ts
28510
+ function managedOverrideOf(connection) {
28511
+ const name = connection.name;
28512
+ return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
28513
+ }
28360
28514
  function overrideOf(connection) {
28361
28515
  const name = connection.name;
28362
28516
  if (typeof name !== "string")
@@ -28368,12 +28522,21 @@ function overrideOf(connection) {
28368
28522
  }
28369
28523
  return;
28370
28524
  }
28371
- function recordConnectionType(connection, type) {
28525
+ function recordConnectionType(connection, type, options = {}) {
28372
28526
  const recordedType = overrideOf(connection) ?? type;
28373
28527
  if (recordedType)
28374
28528
  recorded.set(connection, recordedType);
28529
+ if (options.managed === true || managedOverrideOf(connection)) {
28530
+ managed.add(connection);
28531
+ }
28375
28532
  return connection;
28376
28533
  }
28534
+ function isManagedConnection(connection) {
28535
+ return !!connection && managed.has(connection);
28536
+ }
28537
+ function resolveManagedConnections(connections) {
28538
+ return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
28539
+ }
28377
28540
  function connectionTypeOf(connection) {
28378
28541
  return connection ? recorded.get(connection) : undefined;
28379
28542
  }
@@ -28386,10 +28549,12 @@ function resolveConnectionTypes(connections) {
28386
28549
  }
28387
28550
  return types;
28388
28551
  }
28389
- var recorded, overrides;
28552
+ var recorded, managed, overrides, managedOverrides;
28390
28553
  var init_connection_type = __esm(() => {
28391
28554
  recorded = new WeakMap;
28555
+ managed = new WeakSet;
28392
28556
  overrides = [];
28557
+ managedOverrides = [];
28393
28558
  });
28394
28559
 
28395
28560
  // src/service/materialization/plan/refusal_key.ts
@@ -28531,6 +28696,10 @@ function givenWhereCodes(def) {
28531
28696
  var MAX_WALK_DEPTH = 200;
28532
28697
 
28533
28698
  // src/service/materialization/domain/dialect.ts
28699
+ function isBinary64Type(dialect, nativeType) {
28700
+ const named = nativeType.trim().replace(/\s+/g, " ").toUpperCase();
28701
+ return capabilitiesOf(dialect).binary64Types?.includes(named) === true;
28702
+ }
28534
28703
  function capabilitiesOf(dialect) {
28535
28704
  const name = registeredDialect(dialect);
28536
28705
  return name === undefined ? NONE : CAPABILITIES[name];
@@ -28568,7 +28737,9 @@ var init_dialect = __esm(() => {
28568
28737
  leafBudget: 50,
28569
28738
  passthroughNumericAsDouble: false,
28570
28739
  catalogHidesTables: false,
28571
- stringCollation: undefined
28740
+ stringCollation: undefined,
28741
+ ungroupableTypes: undefined,
28742
+ binary64Types: undefined
28572
28743
  });
28573
28744
  CAPABILITIES = {
28574
28745
  duckdb: Object.freeze({
@@ -28585,7 +28756,8 @@ var init_dialect = __esm(() => {
28585
28756
  foldsTableNameCase: true,
28586
28757
  utcSessions: true,
28587
28758
  leafBudget: 120,
28588
- stringCollation: "instance"
28759
+ stringCollation: "instance",
28760
+ binary64Types: ["DOUBLE", "FLOAT8"]
28589
28761
  }),
28590
28762
  postgres: Object.freeze({
28591
28763
  ...NONE,
@@ -28601,7 +28773,24 @@ var init_dialect = __esm(() => {
28601
28773
  tableOwnership: true,
28602
28774
  castsToIntegerType: true,
28603
28775
  liveRoundsBigIntegersMeasured: true,
28604
- liveWritesFloat4Shortest: true
28776
+ liveWritesFloat4Shortest: true,
28777
+ binary64Types: ["DOUBLE PRECISION"],
28778
+ ungroupableTypes: {
28779
+ malloy: [],
28780
+ native: [
28781
+ "json",
28782
+ "xml",
28783
+ "point",
28784
+ "line",
28785
+ "lseg",
28786
+ "box",
28787
+ "path",
28788
+ "polygon",
28789
+ "circle",
28790
+ "txid_snapshot",
28791
+ "pg_snapshot"
28792
+ ]
28793
+ }
28605
28794
  }),
28606
28795
  standardsql: Object.freeze({
28607
28796
  ...NONE,
@@ -28614,7 +28803,11 @@ var init_dialect = __esm(() => {
28614
28803
  castsToIntegerType: true,
28615
28804
  onlyBigIntegerType: "INT64",
28616
28805
  leafBudget: 120,
28617
- stringCollation: "binary"
28806
+ stringCollation: "dataset",
28807
+ ungroupableTypes: {
28808
+ malloy: ["json", "array", "record"],
28809
+ native: ["geography"]
28810
+ }
28618
28811
  }),
28619
28812
  snowflake: Object.freeze({
28620
28813
  ...NONE,
@@ -28625,7 +28818,15 @@ var init_dialect = __esm(() => {
28625
28818
  relationProbe: true,
28626
28819
  tableOwnership: true,
28627
28820
  castsToIntegerType: true,
28628
- leafBudget: 120
28821
+ leafBudget: 120,
28822
+ binary64Types: [
28823
+ "FLOAT",
28824
+ "FLOAT4",
28825
+ "FLOAT8",
28826
+ "DOUBLE",
28827
+ "DOUBLE PRECISION",
28828
+ "REAL"
28829
+ ]
28629
28830
  }),
28630
28831
  databricks: Object.freeze({
28631
28832
  ...NONE,
@@ -29825,6 +30026,39 @@ function skipAnnotation(text, i, blank) {
29825
30026
  }
29826
30027
  return at;
29827
30028
  }
30029
+ function annotationsBefore(text, from, to) {
30030
+ let found = [];
30031
+ const keep = () => {
30032
+ return;
30033
+ };
30034
+ let i = from;
30035
+ while (i < to) {
30036
+ const code = text.charCodeAt(i);
30037
+ if (isSpaceCode(code, text, i)) {
30038
+ i += unitsAt(text, i);
30039
+ continue;
30040
+ }
30041
+ let end = -1;
30042
+ if (code === 35) {
30043
+ end = skipAnnotation(text, i, keep);
30044
+ if (end >= 0) {
30045
+ found.push({ from: i, to: end, model: text.startsWith("##", i) });
30046
+ }
30047
+ } else if (text.startsWith("--", i) || text.startsWith("//", i)) {
30048
+ end = toEndOfLine(text, i);
30049
+ } else if (text.startsWith("/*", i)) {
30050
+ const close = text.indexOf("*/", i + 2);
30051
+ end = close === -1 ? text.length : close + 2;
30052
+ }
30053
+ if (end < 0) {
30054
+ found = [];
30055
+ i += unitsAt(text, i);
30056
+ continue;
30057
+ }
30058
+ i = end;
30059
+ }
30060
+ return found;
30061
+ }
29828
30062
  function closesBlock(text, at, column, closer) {
29829
30063
  for (let c = 0;c < column; c++) {
29830
30064
  const code = text.charCodeAt(at + c);
@@ -31341,11 +31575,19 @@ function instructionTier(instruction, mode) {
31341
31575
  function instructsUnwritableDestination(instruction, mode) {
31342
31576
  return !!instruction.destination && !storageWritable(mode);
31343
31577
  }
31578
+ function servedCopyReadsTier(tier, others) {
31579
+ return tier === "storage" || !others.includes("storage");
31580
+ }
31344
31581
  function readTier(facts) {
31345
31582
  if (!facts.storageBound) {
31346
31583
  return facts.declaredStorage ? "storage" : "database";
31347
31584
  }
31348
- return facts.servedCopy && !facts.storageFresh && facts.databaseFresh ? "database" : "storage";
31585
+ if (!facts.storageServed) {
31586
+ return facts.databaseBound ? "database" : "storage";
31587
+ }
31588
+ if (!facts.servedCopy)
31589
+ return "storage";
31590
+ return (!facts.storageFresh || facts.servedCopyOnDatabase) && facts.databaseFresh ? "database" : "storage";
31349
31591
  }
31350
31592
  function declaredDestination(declared, mode) {
31351
31593
  return storageWritable(mode) ? declared : undefined;
@@ -32867,6 +33109,174 @@ var init_persist_source_fields = __esm(() => {
32867
33109
  init_logger();
32868
33110
  });
32869
33111
 
33112
+ // src/service/governance/ir/source_reads.ts
33113
+ function isObj2(value) {
33114
+ return value !== null && typeof value === "object" && !Array.isArray(value);
33115
+ }
33116
+ function holdsRawSqlExpression(def) {
33117
+ const seen = new Set;
33118
+ const walk = (node, depth) => {
33119
+ if (depth > MAX_DEPTH)
33120
+ return true;
33121
+ if (node === null || typeof node !== "object")
33122
+ return false;
33123
+ if (seen.has(node))
33124
+ return false;
33125
+ seen.add(node);
33126
+ if (Array.isArray(node))
33127
+ return node.some((c) => walk(c, depth + 1));
33128
+ const record = node;
33129
+ if (record.node === "genericSQLExpr")
33130
+ return true;
33131
+ return Object.entries(record).some(([key, child]) => !(record.node === "function_call" && key === "overload") && walk(child, depth + 1));
33132
+ };
33133
+ return walk(def, 0);
33134
+ }
33135
+ function joinNamed(fields, name) {
33136
+ if (!Array.isArray(fields))
33137
+ return;
33138
+ return fields.find((f) => isObj2(f) && f.join !== undefined && (f.as ?? f.name) === name);
33139
+ }
33140
+ function allJoins(fields) {
33141
+ if (!Array.isArray(fields))
33142
+ return [];
33143
+ return fields.filter((f) => isObj2(f) && f.join !== undefined).flatMap((join) => [join, ...allJoins(join.fields)]);
33144
+ }
33145
+ function resolveJoinPath(roots, path) {
33146
+ for (const fields of roots) {
33147
+ let at;
33148
+ let scope = fields;
33149
+ for (const alias of path) {
33150
+ at = joinNamed(scope, alias);
33151
+ if (!at)
33152
+ break;
33153
+ scope = at.fields;
33154
+ }
33155
+ if (at)
33156
+ return at;
33157
+ }
33158
+ throw new Unknown(`join path ${path.join(".")} did not resolve`);
33159
+ }
33160
+ function relationReads(def, out, depth) {
33161
+ if (depth > MAX_DEPTH || !isObj2(def))
33162
+ throw new Unknown("unreadable");
33163
+ switch (def.type) {
33164
+ case "table":
33165
+ if (typeof def.connection !== "string" || typeof def.tablePath !== "string") {
33166
+ throw new Unknown("table without a path");
33167
+ }
33168
+ out.push({ connectionName: def.connection, table: def.tablePath });
33169
+ return;
33170
+ case "query_source":
33171
+ queryReads(def.query, out, depth + 1);
33172
+ return;
33173
+ case "composite":
33174
+ if (!Array.isArray(def.sources))
33175
+ throw new Unknown("composite");
33176
+ for (const member of def.sources) {
33177
+ relationReads(member, out, depth + 1);
33178
+ }
33179
+ return;
33180
+ default:
33181
+ throw new Unknown(`relation type ${String(def.type)}`);
33182
+ }
33183
+ }
33184
+ function queryReads(query, out, depth) {
33185
+ if (!isObj2(query))
33186
+ throw new Unknown("query");
33187
+ const input = query.compositeResolvedSourceDef ?? query.structRef;
33188
+ if (!isObj2(input))
33189
+ throw new Unknown("unresolved structRef");
33190
+ relationReads(input, out, depth + 1);
33191
+ const pipeline = Array.isArray(query.pipeline) ? query.pipeline : [];
33192
+ pipeline.forEach((segment, index) => {
33193
+ if (!isObj2(segment))
33194
+ throw new Unknown("segment");
33195
+ const extended = Array.isArray(segment.extendSource) ? segment.extendSource : [];
33196
+ const roots = index === 0 ? [extended, input.fields] : [extended];
33197
+ const joins = Array.isArray(segment.activeJoins) ? segment.activeJoins.map((usage) => {
33198
+ if (!Array.isArray(usage.path))
33199
+ throw new Unknown("join usage");
33200
+ return resolveJoinPath(roots, usage.path);
33201
+ }) : roots.flatMap(allJoins);
33202
+ for (const join of joins)
33203
+ relationReads(join, out, depth + 1);
33204
+ });
33205
+ }
33206
+ function sourceReads(source) {
33207
+ try {
33208
+ const def = sourceDefOf(source);
33209
+ if (holdsRawSqlExpression(def))
33210
+ return;
33211
+ const out = [];
33212
+ relationReads(def, out, 0);
33213
+ const distinct = new Map(out.map((r) => [JSON.stringify([r.connectionName, r.table]), r]));
33214
+ return [...distinct.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, r]) => r);
33215
+ } catch {
33216
+ return;
33217
+ }
33218
+ }
33219
+ function queryTableReads(entry, pipeline) {
33220
+ return sourceReads({
33221
+ _sourceDef: {
33222
+ type: "query_source",
33223
+ query: { structRef: entry, pipeline }
33224
+ }
33225
+ });
33226
+ }
33227
+ var MAX_DEPTH = 200, Unknown;
33228
+ var init_source_reads = __esm(() => {
33229
+ Unknown = class Unknown extends Error {
33230
+ };
33231
+ });
33232
+
33233
+ // src/service/materialization/domain/upstream_schemas.ts
33234
+ function upstreamTableKey(table) {
33235
+ return JSON.stringify([table.connectionName, table.table]);
33236
+ }
33237
+ function canonicalType(nativeType) {
33238
+ return nativeType.replace(/\s+/g, " ").replace(/\s*([(),])\s*/g, "$1").trim().toUpperCase();
33239
+ }
33240
+ function namesColumn(sql, name) {
33241
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33242
+ return new RegExp(`(^|[^A-Za-z0-9_])${escaped}($|[^A-Za-z0-9_])`, "i").test(sql);
33243
+ }
33244
+ function upstreamSchemaFold(reads, readings, sql) {
33245
+ if (!reads || !readings)
33246
+ return;
33247
+ const parts = [];
33248
+ for (const table of reads) {
33249
+ const reading = readings[upstreamTableKey(table)];
33250
+ if (!reading)
33251
+ continue;
33252
+ parts.push([
33253
+ table.connectionName,
33254
+ table.table,
33255
+ "unread" in reading ? reading.unread : reading.columns.filter((c) => namesColumn(sql, c.name)).map((c) => [c.name, canonicalType(c.nativeType)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
33256
+ ]);
33257
+ }
33258
+ return parts.length === 0 ? undefined : JSON.stringify(parts);
33259
+ }
33260
+ function upstreamSchemasOf(reads, readings) {
33261
+ if (!reads || !readings)
33262
+ return;
33263
+ const out = [];
33264
+ for (const table of reads) {
33265
+ const reading = readings[upstreamTableKey(table)];
33266
+ if (!reading)
33267
+ continue;
33268
+ out.push({
33269
+ connectionName: table.connectionName,
33270
+ table: table.table,
33271
+ ..."unread" in reading ? { unread: reading.unread } : {
33272
+ columns: reading.columns.map((c) => ({ ...c })),
33273
+ ...reading.dialect ? { dialect: reading.dialect } : {}
33274
+ }
33275
+ });
33276
+ }
33277
+ return out.length === 0 ? undefined : out;
33278
+ }
33279
+
32870
33280
  // src/service/materialization/plan/addressing.ts
32871
33281
  import { makeDigest } from "@malloydata/malloy";
32872
33282
  function sourceBuildOf(build, unbuildable) {
@@ -32986,15 +33396,34 @@ function withoutSourceIDs(build, drop) {
32986
33396
  function plannedTargetOf(source) {
32987
33397
  return buildTargets.get(source);
32988
33398
  }
32989
- function computeSourceEntityId(source, connectionDigests, target, tableFolds) {
33399
+ function computeSourceEntityId(source, connectionDigests, target, tableFolds, upstreamSchemas) {
32990
33400
  const resolved = buildTargetOf(source, target);
32991
33401
  const fold = tableFolds?.[source.sourceID];
33402
+ const upstream = upstreamFoldOf(source, upstreamSchemas, resolved.sql);
32992
33403
  const chosen = testAddresses.get(resolved);
32993
33404
  if (chosen !== undefined) {
32994
- const layout = addressText(source, "", fold);
33405
+ const layout = addressText(source, "", fold, upstream);
32995
33406
  return layout === "" ? chosen : makeDigest(chosen, layout);
32996
33407
  }
32997
- return makeDigest(connectionDigests[source.connectionName], addressText(source, resolved.sql, fold));
33408
+ return makeDigest(connectionDigests[source.connectionName], addressText(source, resolved.sql, fold, upstream));
33409
+ }
33410
+ function upstreamFoldOf(source, readings, sql) {
33411
+ if (!readings)
33412
+ return;
33413
+ return upstreamSchemaFold(upstreamTablesOf(source), readings, sql);
33414
+ }
33415
+ function upstreamTablesOf(source) {
33416
+ let known = readsBySource.get(source);
33417
+ if (!known) {
33418
+ known = { reads: sourceReads(source) };
33419
+ readsBySource.set(source, known);
33420
+ }
33421
+ return known.reads;
33422
+ }
33423
+ function upstreamSchemasOfSource(source, readings) {
33424
+ if (!readings)
33425
+ return;
33426
+ return upstreamSchemasOf(upstreamTablesOf(source), readings);
32998
33427
  }
32999
33428
  function compilerBuildId(source, target) {
33000
33429
  const resolved = buildTargetOf(source, target);
@@ -33011,7 +33440,7 @@ function addressDestination(source) {
33011
33440
  return;
33012
33441
  }
33013
33442
  }
33014
- function addressText(source, sql, tableFold) {
33443
+ function addressText(source, sql, tableFold, upstream) {
33015
33444
  let text = sql;
33016
33445
  const destination = addressDestination(source);
33017
33446
  if (destination !== undefined)
@@ -33020,6 +33449,9 @@ function addressText(source, sql, tableFold) {
33020
33449
  if (tableFold)
33021
33450
  text += `
33022
33451
  -- table: ${tableFold}`;
33452
+ if (upstream)
33453
+ text += `
33454
+ -- upstream schemas: ${upstream}`;
33023
33455
  return text;
33024
33456
  }
33025
33457
  function declarationOf(source) {
@@ -33056,7 +33488,7 @@ function planAddresses(plan) {
33056
33488
  const addresses = {};
33057
33489
  for (const [sourceID, { source, target }] of Object.entries(plan.tables)) {
33058
33490
  try {
33059
- addresses[sourceID] = computeSourceEntityId(source, plan.connectionDigests, target, plan.tableFolds);
33491
+ addresses[sourceID] = computeSourceEntityId(source, plan.connectionDigests, target, plan.tableFolds, plan.upstreamSchemas);
33060
33492
  } catch (err) {
33061
33493
  addresses[sourceID] = {
33062
33494
  unaddressable: err instanceof Error ? err.message : String(err)
@@ -33179,7 +33611,7 @@ async function resolveConnectionDigests(connections, builds, onSkipped) {
33179
33611
  }
33180
33612
  return connectionDigests;
33181
33613
  }
33182
- var buildTargets, unkeyable, testAddresses;
33614
+ var buildTargets, unkeyable, testAddresses, readsBySource;
33183
33615
  var init_addressing = __esm(() => {
33184
33616
  init_config2();
33185
33617
  init_storage_table_path();
@@ -33187,9 +33619,11 @@ var init_addressing = __esm(() => {
33187
33619
  init_persist_source_fields();
33188
33620
  init_declaration();
33189
33621
  init_source_map();
33622
+ init_source_reads();
33190
33623
  buildTargets = new WeakMap;
33191
33624
  unkeyable = new WeakMap;
33192
33625
  testAddresses = new WeakMap;
33626
+ readsBySource = new WeakMap;
33193
33627
  });
33194
33628
 
33195
33629
  // src/service/materialization/domain/vocabulary.ts
@@ -33209,13 +33643,17 @@ function tableKeepsGates(t, s) {
33209
33643
  const row = Object.hasOwn(ROWS, t.kind) ? ROWS[t.kind] : undefined;
33210
33644
  return row ? row(t, s) === true : false;
33211
33645
  }
33212
- function gateColumnTypeExact(type) {
33213
- return !INEXACT_GATE_TYPE.test(type);
33646
+ function gateColumnTypeExact(type, upstream) {
33647
+ if (!INEXACT_GATE_TYPE.test(type))
33648
+ return true;
33649
+ if (!upstream || !isBinary64Type(STORAGE_DIALECT, type))
33650
+ return false;
33651
+ return isBinary64Type(upstream.dialect, upstream.nativeType);
33214
33652
  }
33215
33653
  function gateColumnsExact(t) {
33216
33654
  if (t.gateColumnTypes === undefined)
33217
33655
  return t.tier === "database";
33218
- return t.gateColumnTypes.every(gateColumnTypeExact);
33656
+ return t.gateColumnTypes.every((type, i) => gateColumnTypeExact(type, t.gateColumnUpstreamTypes?.[i]));
33219
33657
  }
33220
33658
  function g3Table(t) {
33221
33659
  return t.tier === "database" || t.ownGateKept === true || t.holdsOnlyUngatedRows === true;
@@ -33250,6 +33688,7 @@ function answerKeepsGates(leg, tablesRead, s, ctx) {
33250
33688
  var ROWS, GATE_LEGS, SERVING_GATE_CONTEXT, INEXACT_GATE_TYPE;
33251
33689
  var init_gate_policy = __esm(() => {
33252
33690
  init_vocabulary();
33691
+ init_dialect();
33253
33692
  ROWS = {
33254
33693
  persist: (t) => persistKeepsGates(t),
33255
33694
  materialize: (t, s) => materializedKeepsGates(t, s),
@@ -34328,9 +34767,7 @@ function readFreshnessGroup(tag, path) {
34328
34767
  if (keys.includes("window")) {
34329
34768
  const window2 = tag.text(...path, "window");
34330
34769
  if (window2 === undefined || freshnessWindowSeconds(window2) === undefined) {
34331
- return {
34332
- invalid: "has a freshness.window= that is not a whole number and a unit " + '(s, m, h, d or w), such as freshness.window="24h"'
34333
- };
34770
+ return { invalid: FRESHNESS_WINDOW_PROBLEM };
34334
34771
  }
34335
34772
  freshness.window = window2.trim();
34336
34773
  }
@@ -35509,6 +35946,15 @@ function storedColumnsOfOutput(fields, options) {
35509
35946
  }
35510
35947
  return out;
35511
35948
  }
35949
+ function spelledNativeType(nativeType, dialect) {
35950
+ if (isArrayType(nativeType))
35951
+ return;
35952
+ const [spelled] = storedColumnsOfOutput([{ name: "c", ...getDialect2(dialect).sqlTypeToMalloyType(nativeType) }], { nested: false, bigint: true, timestamptz: true });
35953
+ return spelled?.type;
35954
+ }
35955
+ function isArrayType(type) {
35956
+ return /\[\s*\d*\s*\]\s*$/.test(type) || /^\s*ARRAY\b/i.test(type);
35957
+ }
35512
35958
  function storedTypeOfField(field, nested, depth, bigint = false, timestamptz = false) {
35513
35959
  if (depth > 16 || field === null || typeof field !== "object") {
35514
35960
  return;
@@ -36031,6 +36477,50 @@ function extractRunTargetSourceNames(query) {
36031
36477
  }
36032
36478
  return [];
36033
36479
  }
36480
+ function lastRunStatementText(text) {
36481
+ const tokens = tokenize2(stripMalloyCommentsAndLiterals(text));
36482
+ const colonStatement = (k, words) => words.some((word) => isWord(tokens, k, word)) && textIs(tokens, k + 1, ":");
36483
+ let depth = 0;
36484
+ let open = -1;
36485
+ let last = -1;
36486
+ let found;
36487
+ for (let k = 0;k < tokens.count; k++) {
36488
+ const opens = depth === 0 && (textIs(tokens, k, ";") || isWord(tokens, k, "import") || isWord(tokens, k, "export") || colonStatement(k, COLON_STATEMENTS));
36489
+ if (opens) {
36490
+ if (open >= 0)
36491
+ found = [open, last];
36492
+ open = colonStatement(k, ["run"]) ? k : -1;
36493
+ last = k + 1;
36494
+ if (open >= 0)
36495
+ k++;
36496
+ continue;
36497
+ }
36498
+ last = k;
36499
+ if (tokens.kind[k] !== PUNCT)
36500
+ continue;
36501
+ const code = tokens.source.charCodeAt(tokens.start[k]);
36502
+ if (code === 40 || code === 91 || code === 123)
36503
+ depth++;
36504
+ else if (code === 41 || code === 93 || code === 125)
36505
+ depth = Math.max(0, depth - 1);
36506
+ }
36507
+ if (open >= 0)
36508
+ found = [open, last];
36509
+ if (!found)
36510
+ return;
36511
+ const [run, end] = found;
36512
+ let from = tokens.start[run];
36513
+ const before = annotationsBefore(text, run > 0 ? rawEnd(tokens, run - 1) : 0, from);
36514
+ for (const tag of before.reverse()) {
36515
+ if (tag.model)
36516
+ break;
36517
+ from = tag.from;
36518
+ }
36519
+ return text.slice(from, rawEnd(tokens, end));
36520
+ }
36521
+ function rawEnd(tokens, k) {
36522
+ return tokens.end[k] + (tokens.kind[k] === QUOTED ? 1 : 0);
36523
+ }
36034
36524
  function namesOutside(tokens, headFrom, headTo) {
36035
36525
  const names = new Set;
36036
36526
  for (let k = 0;k < tokens.count; k++) {
@@ -36445,10 +36935,11 @@ function locateProblemsInCallerText(problems, callerText, prefixLines) {
36445
36935
  };
36446
36936
  });
36447
36937
  }
36448
- var UNREADABLE_BASE = "`", PUNCT = 0, NAME = 1, QUOTED = 2;
36938
+ var UNREADABLE_BASE = "`", COLON_STATEMENTS, PUNCT = 0, NAME = 1, QUOTED = 2;
36449
36939
  var init_query_text = __esm(() => {
36450
36940
  init_malloy_lexer_core();
36451
36941
  init_malloy_lexer_core();
36942
+ COLON_STATEMENTS = ["run", "source", "query", "given", "sql", "type"];
36452
36943
  });
36453
36944
 
36454
36945
  // src/service/materialization/plan/materialize_read_time.ts
@@ -37823,7 +38314,8 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
37823
38314
  label: "",
37824
38315
  exprs: ["false"],
37825
38316
  route: "authorize",
37826
- selfContained: true
38317
+ selfContained: true,
38318
+ baseHops: 0
37827
38319
  }
37828
38320
  ];
37829
38321
  unkeepable.add("(an unreadable gate)");
@@ -37831,6 +38323,9 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
37831
38323
  for (const entry of entries) {
37832
38324
  if (!entry.struct)
37833
38325
  unkeepable.add("(an unreadable gate)");
38326
+ if (entry.baseHops > 0 && canonicalAuthorizeRoute(entry.route) !== AUTHORIZE_ROUTE) {
38327
+ unkeepable.add("(a row filter on a derivation's base)");
38328
+ }
37834
38329
  for (const expr of entry.exprs) {
37835
38330
  for (const id of malloyIdentifiers(expr)) {
37836
38331
  const f = byName.get(id);
@@ -38083,6 +38578,9 @@ function unreadableSourceConnectionMessage(source, type) {
38083
38578
  const what = type === undefined ? `is not one of the environment's connections (the package's own ` + `DuckDB sandbox is not)` : type === "ducklake" ? `is a DuckLake catalog other than the destination's` : `is a '${type}' connection`;
38084
38579
  return `Source '${source.name}' cannot be materialized into a storage ` + `destination: its connection '${source.connectionName}' ${what}, ` + `which cannot be passed through to a 'storage=' build (it reads ` + `${PASSTHROUGH_SOURCE_TYPES.join(", ")} sources, and a DuckLake ` + `source into its own catalog only). ` + `The source is not built and is answered live. Drop 'storage=' to ` + `build it in its own connection, or put the source on a warehouse ` + `connection.`;
38085
38580
  }
38581
+ function catalogAuthorSqlMessage(source, { managed = false } = {}) {
38582
+ return `Source '${source.name}' cannot be materialized: its connection ` + `'${source.connectionName}' is a ${managed ? "managed database" : "DuckLake catalog"}, whose tables are ` + `built inside the catalog by SQL Malloy generates, and the source ` + `carries SQL its author wrote (an .sql() source or a sql_* ` + `expression, its own or a joined source's) or reads a file or URL as a ` + `table. The source is not built and is answered live. Express it in ` + `Malloy over the catalog's tables to build it.`;
38583
+ }
38086
38584
  var PASSTHROUGH_SOURCE_TYPES;
38087
38585
  var init_source_connection_type = __esm(() => {
38088
38586
  PASSTHROUGH_SOURCE_TYPES = [
@@ -38092,6 +38590,59 @@ var init_source_connection_type = __esm(() => {
38092
38590
  ];
38093
38591
  });
38094
38592
 
38593
+ // src/service/materialization/domain/same_catalog_build.ts
38594
+ function isSameCatalog(source, destination) {
38595
+ const a = source?.type === "ducklake" ? source.ducklakeConnection : undefined;
38596
+ const b = destination?.type === "ducklake" ? destination.ducklakeConnection : undefined;
38597
+ if (!a || !b)
38598
+ return false;
38599
+ const pa = a.catalog?.postgresConnection;
38600
+ const pb = b.catalog?.postgresConnection;
38601
+ if (!pa || !pb)
38602
+ return false;
38603
+ const path = (url) => (url ?? "").replace(/\/+$/, "");
38604
+ const pathA = path(a.storage?.bucketUrl);
38605
+ const pathB = path(b.storage?.bucketUrl);
38606
+ return !!pa.host && pa.host === pb.host && (pa.port ?? 5432) === (pb.port ?? 5432) && !!pa.databaseName && pa.databaseName === pb.databaseName && (a.catalog.metadataSchema ?? "") === (b.catalog.metadataSchema ?? "") && (pathA === "" || pathB === "" || pathA === pathB);
38607
+ }
38608
+ function carriesAuthorSql(def) {
38609
+ const seen = new Set;
38610
+ const walk = (node, depth) => {
38611
+ if (depth > MAX_DEPTH2)
38612
+ return true;
38613
+ if (node === null || typeof node !== "object")
38614
+ return false;
38615
+ if (seen.has(node))
38616
+ return false;
38617
+ seen.add(node);
38618
+ if (Array.isArray(node)) {
38619
+ return node.some((child) => walk(child, depth + 1));
38620
+ }
38621
+ const record = node;
38622
+ if (record.type === "sql_select" || record.node === "genericSQLExpr") {
38623
+ return true;
38624
+ }
38625
+ if (record.node === "function_call") {
38626
+ return Object.entries(record).some(([key, child]) => key !== "overload" && walk(child, depth + 1));
38627
+ }
38628
+ if (record.type === "table" && typeof record.tablePath === "string" && !CATALOG_TABLE_PATH.test(record.tablePath)) {
38629
+ return true;
38630
+ }
38631
+ return Object.values(record).some((child) => walk(child, depth + 1));
38632
+ };
38633
+ try {
38634
+ if (def === null || typeof def !== "object")
38635
+ return true;
38636
+ return walk(def, 0);
38637
+ } catch {
38638
+ return true;
38639
+ }
38640
+ }
38641
+ var CATALOG_TABLE_PATH, MAX_DEPTH2 = 200;
38642
+ var init_same_catalog_build = __esm(() => {
38643
+ CATALOG_TABLE_PATH = /^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)*$/;
38644
+ });
38645
+
38095
38646
  // src/service/materialization/plan/materialization_eligibility.ts
38096
38647
  function assertMaterializationEligible(persistSource, annotationFields, options = {}) {
38097
38648
  const sourceName = persistSource.name;
@@ -38128,11 +38679,29 @@ function assertMaterializationEligible(persistSource, annotationFields, options
38128
38679
  }
38129
38680
  function assertStorageBuildReadsConnection(persistSource, connectionTypes) {
38130
38681
  const type = connectionTypes?.[persistSource.connectionName];
38131
- if (type === undefined || storageBuildReadsConnectionType(type))
38682
+ if (type === undefined)
38683
+ return;
38684
+ if (!storageBuildReadsConnectionType(type)) {
38685
+ throw new MaterializationEligibilityError({
38686
+ reason: "storage_source_unsupported",
38687
+ message: unreadableSourceConnectionMessage(persistSource, type)
38688
+ });
38689
+ }
38690
+ if (type === "ducklake" && carriesAuthorSql(sourceDefOf(persistSource))) {
38691
+ throw new MaterializationEligibilityError({
38692
+ reason: "storage_source_unsupported",
38693
+ message: catalogAuthorSqlMessage(persistSource)
38694
+ });
38695
+ }
38696
+ }
38697
+ function assertManagedBuildRunsMalloySql(source, plan) {
38698
+ if (!plan?.managedConnections?.includes(source.connectionName))
38699
+ return;
38700
+ if (!carriesAuthorSql(sourceDefOf(source)))
38132
38701
  return;
38133
38702
  throw new MaterializationEligibilityError({
38134
38703
  reason: "storage_source_unsupported",
38135
- message: unreadableSourceConnectionMessage(persistSource, type)
38704
+ message: catalogAuthorSqlMessage(source, { managed: true })
38136
38705
  });
38137
38706
  }
38138
38707
  function assertMergeKeyScopeResolvable(persistSource, terms, annotationFields, what) {
@@ -38468,6 +39037,7 @@ function assertTierEligible(source, storage, plan, annotationFields = deriveAnno
38468
39037
  assertBuildReadsNoCurrentTime(source, plan);
38469
39038
  return;
38470
39039
  }
39040
+ assertManagedBuildRunsMalloySql(source, plan);
38471
39041
  const table = plan?.tables?.[source.sourceID];
38472
39042
  const rollup = table?.rollup;
38473
39043
  assertDatabasePersistNotAuthorizeGated(source, source.name, rollup ? "rollup" : "persist", table?.gate, annotationFields, { gateEnforcedAtRead: !!rollup && rollupGateEnforcedAtRead(rollup) });
@@ -38536,6 +39106,7 @@ var init_materialization_eligibility = __esm(() => {
38536
39106
  init_declaration();
38537
39107
  init_rollup_plan();
38538
39108
  init_source_connection_type();
39109
+ init_same_catalog_build();
38539
39110
  READ_ONLY_DIALECTS = new Set(["sqlserver"]);
38540
39111
  });
38541
39112
 
@@ -39127,10 +39698,10 @@ function storableDimension(field) {
39127
39698
  }
39128
39699
  return dimension;
39129
39700
  }
39130
- function storableArray(field) {
39131
- if (field.type !== "array" || field.e !== undefined)
39701
+ function storableNested(field) {
39702
+ if (field.type !== "array" && field.type !== "record")
39132
39703
  return;
39133
- if (hiddenAccess(field))
39704
+ if (field.e !== undefined)
39134
39705
  return;
39135
39706
  const dimension = typeof field.as === "string" ? field.as : typeof field.name === "string" ? field.name : undefined;
39136
39707
  return dimension;
@@ -39141,9 +39712,15 @@ function materializeColumns(def, options = {}) {
39141
39712
  const perCaller = givenReadingFields(def.fields);
39142
39713
  for (const raw of def.fields ?? []) {
39143
39714
  const field = raw;
39144
- const nested = storableArray(field);
39715
+ const nested = storableNested(field);
39145
39716
  if (nested !== undefined) {
39146
- out.push({ dimension: nested, column: nested, computed: false });
39717
+ const access = hiddenAccess(field);
39718
+ out.push({
39719
+ dimension: nested,
39720
+ column: nested,
39721
+ computed: false,
39722
+ ...access ? { access } : {}
39723
+ });
39147
39724
  continue;
39148
39725
  }
39149
39726
  const dimension = storableDimension(field);
@@ -39882,6 +40459,10 @@ function pairLayoutOf(def, map, args) {
39882
40459
  if (problem) {
39883
40460
  return new Declined(problem.reason, { refused: "inline_unsupported" });
39884
40461
  }
40462
+ const ungrouped = ungroupablePairColumn(def, map, columns);
40463
+ if (ungrouped) {
40464
+ return new Declined(ungrouped, { refused: "inline_unsupported" });
40465
+ }
39885
40466
  const pairs = laid.map((l) => l.pair);
39886
40467
  pair = pairs[0];
39887
40468
  if (pairs.length > 1) {
@@ -39941,6 +40522,48 @@ function pairLayoutOf(def, map, args) {
39941
40522
  ...pairFullRefresh ? { pairFullRefresh } : {}
39942
40523
  };
39943
40524
  }
40525
+ function ungroupablePairColumn(def, map, columns) {
40526
+ const refused = capabilitiesOf(def.dialect).ungroupableTypes;
40527
+ if (!refused)
40528
+ return;
40529
+ for (const c of columns) {
40530
+ const type = ungroupedTypeOf(storedFieldOf(def, map, c), refused);
40531
+ if (type === undefined)
40532
+ continue;
40533
+ return `inline= names a join_many, whose pair table's build groups by every ` + `stored column, and \`${c.column}\` is a ${type.toUpperCase()} column, ` + `which ${describeDialects(new Set([String(def.dialect)]))} cannot ` + "group by; leave the column out of the source (and of the joined " + "source's public dimensions), or inline no join_many";
40534
+ }
40535
+ return;
40536
+ }
40537
+ function ungroupedTypeOf(field, refused) {
40538
+ if (field?.type === "sql native") {
40539
+ const raw = typeof field.rawType === "string" ? field.rawType.toLowerCase() : "";
40540
+ return refused.native.includes(raw) ? raw : undefined;
40541
+ }
40542
+ if (typeof field?.type !== "string")
40543
+ return;
40544
+ if (refused.malloy.includes(field.type))
40545
+ return field.type;
40546
+ if (field.type === "array") {
40547
+ const element = ungroupedTypeOf(field.elementTypeDef, refused);
40548
+ return element === undefined ? undefined : `${element}[]`;
40549
+ }
40550
+ return;
40551
+ }
40552
+ function storedFieldOf(def, map, c) {
40553
+ let fields = def.fields ?? [];
40554
+ let joins = map.joinsOf(def.sourceID);
40555
+ for (const name of c.join === undefined ? [] : c.path ?? [c.join]) {
40556
+ const join = joins.find((j) => j.name === name);
40557
+ if (!join)
40558
+ return;
40559
+ fields = join.fields;
40560
+ joins = map.joinedReadsOf(join).joins;
40561
+ }
40562
+ return fields.find((raw) => {
40563
+ const f = raw;
40564
+ return (typeof f.as === "string" ? f.as : f.name) === c.dimension;
40565
+ });
40566
+ }
39944
40567
  function chainExtensionTables(plans, map) {
39945
40568
  const byID = new Map(plans.map((p) => [p.sourceID, p]));
39946
40569
  const declarationOfID = (sourceID) => declarationOf2(map.node(sourceID)?.def);
@@ -40370,6 +40993,7 @@ function tierGateInputs(compiled) {
40370
40993
  return {
40371
40994
  tables: compiled.tables,
40372
40995
  connectionTypes: compiled.connectionTypes,
40996
+ managedConnections: compiled.managedConnections,
40373
40997
  accessReads: compiled.accessReads
40374
40998
  };
40375
40999
  }
@@ -41510,12 +42134,12 @@ function statementsOf(text, tokens) {
41510
42134
  }
41511
42135
  return out;
41512
42136
  }
41513
- function definitionCutAt(text, offset) {
42137
+ function definitionCutAt(text, offset, topLevel = false) {
41514
42138
  const tokens = lexAll(text);
41515
42139
  if (!tokens)
41516
42140
  return;
41517
42141
  const statements = statementsOf(text, tokens);
41518
- const holding = statements.filter((s) => DEFINITION_KEYWORDS.has(s.keyword.text) && s.keyword.start <= offset && offset < s.end && (s.keyword.depth === 0 || s.keyword.text !== "source" && s.keyword.text !== "query"));
42142
+ const holding = statements.filter((s) => DEFINITION_KEYWORDS.has(s.keyword.text) && s.keyword.start <= offset && offset < s.end && (s.keyword.depth === 0 ? !topLevel || s.keyword.text === "source" || s.keyword.text === "query" : !topLevel && s.keyword.text !== "source" && s.keyword.text !== "query"));
41519
42143
  if (holding.length === 0)
41520
42144
  return;
41521
42145
  const stmt = holding.reduce((a, b) => b.keyword.depth > a.keyword.depth || b.keyword.depth === a.keyword.depth && b.keyword.start > a.keyword.start ? b : a);
@@ -41562,19 +42186,24 @@ function definitionCutAt(text, offset) {
41562
42186
  name,
41563
42187
  ...declaration && declaration !== name ? { declaration } : {}
41564
42188
  };
41565
- if (defs.length === 1) {
41566
- const head = statementHead(tokens, tokens.indexOf(stmt.keyword));
41567
- const before = tokens.filter((t) => t.end <= head.start);
41568
- return {
41569
- start: annotationsStart(text, before[before.length - 1]?.end ?? 0, head.start),
41570
- end: stmtLast.end,
41571
- left
41572
- };
41573
- }
42189
+ const head = statementHead(tokens, tokens.indexOf(stmt.keyword));
42190
+ const before = tokens.filter((t) => t.end <= head.start);
42191
+ const whole = {
42192
+ start: annotationsStart(text, before[before.length - 1]?.end ?? 0, head.start),
42193
+ end: stmtLast.end
42194
+ };
42195
+ if (defs.length === 1)
42196
+ return { ...whole, left };
42197
+ const statement = { ...whole, definitions: defs.length };
41574
42198
  if (index === 0) {
41575
- return { start: stmt.colon.end, end: def.fullEnd, left };
42199
+ return { start: stmt.colon.end, end: def.fullEnd, left, statement };
41576
42200
  }
41577
- return { start: defs[index - 1].lastEnd, end: def.lastEnd, left };
42201
+ return {
42202
+ start: defs[index - 1].lastEnd,
42203
+ end: def.lastEnd,
42204
+ left,
42205
+ statement
42206
+ };
41578
42207
  }
41579
42208
  function annotationsStart(text, floor, keyword) {
41580
42209
  const lineStart = text.lastIndexOf(`
@@ -43268,6 +43897,13 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
43268
43897
  refusal: gateRefusal
43269
43898
  };
43270
43899
  }
43900
+ const throughDerivation = gates.filter((g) => g.baseHops > 0 && canonicalAuthorizeRoute(g.route) !== AUTHORIZE_ROUTE);
43901
+ if (throughDerivation.length > 0) {
43902
+ return {
43903
+ reason: "its source inherits a row filter through `->`, which filters the derivation's base, not the rows a stored result holds",
43904
+ refusal: gateRefusalReason(throughDerivation.map((g) => g.route))
43905
+ };
43906
+ }
43271
43907
  const gatedWhy = "its source carries a row-level gate (#(access_filter) or #(authorize))";
43272
43908
  if (stages.length !== 1 || last.type !== "reduce") {
43273
43909
  return {
@@ -43493,6 +44129,7 @@ var init_persisted_view_compile = __esm(() => {
43493
44129
  init_annotations();
43494
44130
  init_annotation_reader();
43495
44131
  init_authorize();
44132
+ init_authorize_routes();
43496
44133
  init_gate_classification();
43497
44134
  init_prepared_query();
43498
44135
  init_malloy_text();
@@ -44117,7 +44754,7 @@ function storedColumnNames(persistSource) {
44117
44754
  let names;
44118
44755
  try {
44119
44756
  const columnOf = storedColumnOf(persistSource);
44120
- names = exploreOf(persistSource).intrinsicFields.filter((f) => f.isAtomicField()).map((f) => columnOf(f.name)).filter((n) => typeof n === "string" && n.length > 0);
44757
+ names = exploreOf(persistSource).intrinsicFields.filter((f) => f.isAtomicField() || isNestedColumn(f)).map((f) => columnOf(f.name)).filter((n) => typeof n === "string" && n.length > 0);
44121
44758
  } catch (err) {
44122
44759
  throw new Error(`the compiled source's field list could not be read (${errMessage(err)})`);
44123
44760
  }
@@ -44126,6 +44763,10 @@ function storedColumnNames(persistSource) {
44126
44763
  }
44127
44764
  return names;
44128
44765
  }
44766
+ function isNestedColumn(field) {
44767
+ const f = field;
44768
+ return f.isExploreField?.() === true;
44769
+ }
44129
44770
  function projectToStoredColumns(persistSource, buildSQL) {
44130
44771
  let cols;
44131
44772
  try {
@@ -44792,11 +45433,16 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44792
45433
  const decided = verdicts.get(sourceID).wire;
44793
45434
  if ("failed" in decided)
44794
45435
  throw decided.failed;
44795
- if (decided.refused)
44796
- refusedSources[sourceID] = decided.refused;
45436
+ if (decided.refused) {
45437
+ const freshness = resolveFreshness(source, packageMaterialization, table.rollup?.freshness);
45438
+ refusedSources[sourceID] = {
45439
+ ...decided.refused,
45440
+ ...freshness ? { freshness } : {}
45441
+ };
45442
+ }
44797
45443
  if (!decided.inPlan)
44798
45444
  continue;
44799
- wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization);
45445
+ wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization, compiled.upstreamSchemas);
44800
45446
  } catch (err) {
44801
45447
  const reason = isUnkeyable(source) ? "unkeyable" : err instanceof EligibilityCheckFailed ? "eligibility_check_failed" : "projection_failed";
44802
45448
  logger.warn("Failed to project a persist source into the build plan", {
@@ -44816,7 +45462,7 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44816
45462
  ...finalizeOmissions(omitted, new Set(Object.keys(wireSources)))
44817
45463
  };
44818
45464
  }
44819
- function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterialization) {
45465
+ function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterialization, upstreamSchemaReadings) {
44820
45466
  const { source, rollup, modelPath } = table;
44821
45467
  return {
44822
45468
  name: source.name,
@@ -44835,11 +45481,21 @@ function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterializ
44835
45481
  freshness: resolveFreshness(source, packageMaterialization, rollup?.freshness),
44836
45482
  queryMetadata: resolveQueryMetadata(source, packageMaterialization),
44837
45483
  columns: deriveColumns(source),
45484
+ ...readsOf(source),
45485
+ ...upstreamSchemasFieldOf(source, upstreamSchemaReadings),
44838
45486
  ...planDynamicFields(source),
44839
45487
  annotationFields,
44840
45488
  modelPath
44841
45489
  };
44842
45490
  }
45491
+ function upstreamSchemasFieldOf(source, readings) {
45492
+ const upstreamSchemas = upstreamSchemasOfSource(source, readings);
45493
+ return upstreamSchemas ? { upstreamSchemas } : {};
45494
+ }
45495
+ function readsOf(source) {
45496
+ const reads = sourceReads(source);
45497
+ return reads === undefined ? {} : { reads };
45498
+ }
44843
45499
  function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources, refusedSources) {
44844
45500
  const { tables } = compiled;
44845
45501
  const v1 = (id) => !tables[id]?.materialize;
@@ -44858,6 +45514,7 @@ function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources,
44858
45514
  modelPath: tables[sourceID]?.modelPath,
44859
45515
  tier: "database",
44860
45516
  reason: sibling.reason ?? "authorize",
45517
+ ...planned.freshness ? { freshness: planned.freshness } : {},
44861
45518
  message: `'${planned.name}' is not built: it shares its table with ` + `'${sibling.name}', which the eligibility gate refuses for a ` + `database build, and a database table is served to every ` + `source on it. ${sibling.message}`
44862
45519
  };
44863
45520
  }
@@ -44905,7 +45562,9 @@ function finishBuildPlan(parts, ctx) {
44905
45562
  ...ctx.versionScoped ? { versionScoped: true } : {},
44906
45563
  ...parts,
44907
45564
  connectionDigests: ctx.connectionDigests,
45565
+ ...ctx.upstreamSchemas ? { upstreamSchemas: ctx.upstreamSchemas } : {},
44908
45566
  connectionTypes: resolveConnectionTypes(ctx.connections),
45567
+ managedConnections: resolveManagedConnections(ctx.connections),
44909
45568
  connections: ctx.connections,
44910
45569
  ...ctx.keyCheckCompilers && ctx.keyCheckCompilers.size > 0 ? { keyCheckCompilers: ctx.keyCheckCompilers } : {}
44911
45570
  };
@@ -44915,22 +45574,34 @@ function finishBuildPlan(parts, ctx) {
44915
45574
  tableFolds,
44916
45575
  addresses: planAddresses({ ...plan, tableFolds })
44917
45576
  }));
44918
- return ctx.keepIncrementalUnbuildable ? refused : refuseIncrementalUnbuildable(refused);
45577
+ const known = refuseUpstreamUnread(refused);
45578
+ return ctx.keepIncrementalUnbuildable ? known : refuseIncrementalUnbuildable(known);
44919
45579
  }
44920
45580
  async function finishPackagePlan(parts, ctx) {
44921
- const { getMalloyConnection, ...finish } = ctx;
45581
+ const { getMalloyConnection, readUpstreamSchemas, ...finish } = ctx;
44922
45582
  const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
44923
45583
  const digestSkipped = [];
44924
45584
  const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
45585
+ const upstreamSchemas = readUpstreamSchemas ? await readUpstreamSchemas(planUpstreamTables(parts.tables)) : undefined;
44925
45586
  return {
44926
45587
  compiled: finishBuildPlan(parts, {
44927
45588
  ...finish,
44928
45589
  connectionDigests,
45590
+ ...upstreamSchemas ? { upstreamSchemas } : {},
44929
45591
  connections
44930
45592
  }),
44931
45593
  digestSkipped
44932
45594
  };
44933
45595
  }
45596
+ function planUpstreamTables(tables) {
45597
+ const out = new Map;
45598
+ for (const { source } of Object.values(tables)) {
45599
+ for (const read of upstreamTablesOf(source) ?? []) {
45600
+ out.set(upstreamTableKey(read), read);
45601
+ }
45602
+ }
45603
+ return [...out.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, t]) => t);
45604
+ }
44934
45605
  function derivePackagePlan(compiled, materializationConfig, counts = {}) {
44935
45606
  const incrementalDeclarations = collectIncrementalDeclarations(compiled.tables);
44936
45607
  const verdicts = planVerdicts(compiled);
@@ -44950,11 +45621,13 @@ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
44950
45621
  builds: compiled.builds,
44951
45622
  connectionDigests: compiled.connectionDigests,
44952
45623
  connectionTypes: compiled.connectionTypes ?? {},
45624
+ managedConnections: compiled.managedConnections ?? [],
44953
45625
  buildConnectionNames: [
44954
45626
  ...new Set(compiled.builds.map((b) => b.connectionName))
44955
45627
  ].sort(),
44956
45628
  versionScoped: compiled.versionScoped === true,
44957
45629
  tableFolds: { ...compiled.tableFolds },
45630
+ upstreamSchemas: { ...compiled.upstreamSchemas },
44958
45631
  addresses: { ...compiled.addresses },
44959
45632
  compilerKeys: compilerKeysOf(compiled),
44960
45633
  annotationFindings,
@@ -45049,36 +45722,64 @@ function refuseIncrementalUnbuildable(compiled) {
45049
45722
  if (reason === undefined)
45050
45723
  continue;
45051
45724
  dropped.add(sourceID);
45052
- const model = compiled.tables[sourceID]?.modelPath ?? "";
45053
- const plan = compiled.tables[sourceID]?.materialize;
45054
- const tier = tierOf(declaredStorage(source));
45055
- const refused = refusalKey(sourceID, source.name, "incremental_unsupported", tier);
45056
- findings.push(plan ? materializeRefusalFinding({
45057
- sourceName: plan.sourceName,
45725
+ findings.push(notBuiltFinding(compiled, sourceID, "incremental_unsupported", reason));
45726
+ }
45727
+ return withoutSources(compiled, findings, dropped);
45728
+ }
45729
+ function refuseUpstreamUnread(compiled) {
45730
+ const readings = compiled.upstreamSchemas;
45731
+ if (!readings)
45732
+ return compiled;
45733
+ const findings = [];
45734
+ const dropped = new Set;
45735
+ for (const [sourceID, { source }] of Object.entries(compiled.tables)) {
45736
+ const unread = (upstreamTablesOf(source) ?? []).filter((t) => {
45737
+ const reading = readings[upstreamTableKey(t)];
45738
+ return reading !== undefined && "unread" in reading ? reading.unread === "read_failed" : false;
45739
+ });
45740
+ if (unread.length === 0)
45741
+ continue;
45742
+ dropped.add(sourceID);
45743
+ const tables = unread.map((t) => `"${t.table}" on connection "${t.connectionName}"`).join(", ");
45744
+ findings.push(notBuiltFinding(compiled, sourceID, "upstream_unread", `the columns of ${tables}, which its build reads, could not be ` + "read from the warehouse's catalog, so its table's address is " + "not known; it is planned once a reload, or a plan refresh, " + "reads them"));
45745
+ }
45746
+ return withoutSources(compiled, findings, dropped);
45747
+ }
45748
+ function notBuiltFinding(compiled, sourceID, reason, why) {
45749
+ const table = compiled.tables[sourceID];
45750
+ const source = table.source;
45751
+ const model = table.modelPath ?? "";
45752
+ const tier = tierOf(declaredStorage(source));
45753
+ const refused = refusalKey(sourceID, source.name, reason, tier);
45754
+ if (table.materialize) {
45755
+ return materializeRefusalFinding({
45756
+ sourceName: table.materialize.sourceName,
45058
45757
  sourceID,
45059
- reason,
45060
- outcome: {
45061
- refused: { reason: "incremental_unsupported", tier }
45062
- }
45063
- }, model) : view ? {
45064
- ...persistedViewRefusalFinding({
45065
- ...view,
45066
- sourceID,
45067
- reason,
45068
- outcome: { refused: "incremental_unsupported" }
45069
- }, model),
45758
+ reason: why,
45759
+ outcome: { refused: { reason, tier } }
45760
+ }, model);
45761
+ }
45762
+ const view = persistedViewOf(source);
45763
+ if (view) {
45764
+ return {
45765
+ ...persistedViewRefusalFinding({ ...view, sourceID, reason: why, outcome: { refused: reason } }, model),
45070
45766
  refused
45767
+ };
45768
+ }
45769
+ return {
45770
+ route: "@",
45771
+ tier: "unservable",
45772
+ ...table.kind === "rollup" ? {
45773
+ code: ROLLUP_NOT_BUILT_CODE,
45774
+ message: `Rollup "${source.name}" is not built, so its measures are answered live: ${why}.`
45071
45775
  } : {
45072
- route: "@",
45073
- tier: "unservable",
45074
45776
  code: PERSIST_NOT_BUILT_CODE,
45075
- message: `#@ persist source "${source.name}" is not built, so it is answered live: ${reason}.`,
45076
- subject: source.name,
45077
- model,
45078
- refused
45079
- });
45080
- }
45081
- return withoutSources(compiled, findings, dropped);
45777
+ message: `#@ persist source "${source.name}" is not built, so it is answered live: ${why}.`
45778
+ },
45779
+ subject: source.name,
45780
+ model,
45781
+ refused
45782
+ };
45082
45783
  }
45083
45784
  function persistedViewOf(source) {
45084
45785
  if (!isPersistedResultSourceID(source.sourceID))
@@ -45213,6 +45914,7 @@ var init_build_plan = __esm(() => {
45213
45914
  init_rollup_plan();
45214
45915
  init_config2();
45215
45916
  init_connection_type();
45917
+ init_source_reads();
45216
45918
  init_access_closure();
45217
45919
  init_persist_dynamic_terms();
45218
45920
  init_persist_source_fields();
@@ -45234,7 +45936,7 @@ var init_build_plan = __esm(() => {
45234
45936
  });
45235
45937
 
45236
45938
  // src/package_load/protocol.ts
45237
- var PACKAGE_LOAD_PROTOCOL_VERSION = 7;
45939
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 8;
45238
45940
 
45239
45941
  // src/package_load/package_load_worker.ts
45240
45942
  init_malloynb();
@@ -45682,7 +46384,7 @@ function callMain(send) {
45682
46384
  }
45683
46385
  var schemaWait = new RpcWaitAccountant;
45684
46386
  function dispatchMainResponse(message) {
45685
- if (message.type === "schema-for-tables-response" || message.type === "schema-for-sql-response" || message.type === "read-url-response" || message.type === "connection-metadata-response") {
46387
+ if (message.type === "schema-for-tables-response" || message.type === "schema-for-sql-response" || message.type === "upstream-schemas-response" || message.type === "read-url-response" || message.type === "connection-metadata-response") {
45686
46388
  const pending = pendingRpc.get(message.requestId);
45687
46389
  if (!pending)
45688
46390
  return;
@@ -45983,7 +46685,7 @@ function buildWorkerMalloyConfig(job, refresh) {
45983
46685
  };
45984
46686
  port.postMessage(req);
45985
46687
  });
45986
- const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType);
46688
+ const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, { managed: response.metadata.managed === true });
45987
46689
  proxies.set(effectiveName, proxy);
45988
46690
  inflight.delete(effectiveName);
45989
46691
  return proxy;
@@ -46400,7 +47102,7 @@ async function loadPackage(job) {
46400
47102
  const schemaFetchDurationMs = schemaWait.waitMs;
46401
47103
  const schemaFetchCount = schemaWait.fetches;
46402
47104
  const schemaCacheHits = schemaCache.hits - schemaCacheHitsAtStart;
46403
- const buildPlan = await finishWorkerBuildPlan(malloyConfig, modelPaths, load, packageMetadata.materialization ?? null, !!job.publishedVersion && packageMetadata.scope === "version");
47105
+ const buildPlan = await finishWorkerBuildPlan(malloyConfig, modelPaths, load, packageMetadata.materialization ?? null, !!job.publishedVersion && packageMetadata.scope === "version", job.requestId);
46404
47106
  const loadEnd = performance.now();
46405
47107
  return {
46406
47108
  type: "load-package-result",
@@ -46422,7 +47124,7 @@ async function loadPackage(job) {
46422
47124
  buildPlan
46423
47125
  };
46424
47126
  }
46425
- async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped) {
47127
+ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped, jobId) {
46426
47128
  if (!load.planParts || load.failed || load.planLeftToMainThread) {
46427
47129
  return;
46428
47130
  }
@@ -46443,7 +47145,16 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
46443
47145
  }
46444
47146
  const finished = await finishPackagePlan(parts, {
46445
47147
  getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name),
46446
- versionScoped
47148
+ versionScoped,
47149
+ readUpstreamSchemas: async (tables) => (await callMain((requestId) => {
47150
+ const req = {
47151
+ type: "upstream-schemas",
47152
+ requestId,
47153
+ jobId,
47154
+ tables
47155
+ };
47156
+ port.postMessage(req);
47157
+ })).readings
46447
47158
  });
46448
47159
  digestSkipped = finished.digestSkipped;
46449
47160
  return {