@malloy-publisher/server 0.16.1 → 0.17.0

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 (28) hide show
  1. package/dist/app/api-doc.yaml +202 -32
  2. package/dist/app/assets/{EnvironmentPage-Y9IWPC9J.js → EnvironmentPage-D2-0ts2G.js} +1 -1
  3. package/dist/app/assets/{HomePage-BOUo0MEl.js → HomePage-S_Bkczsx.js} +1 -1
  4. package/dist/app/assets/{MainPage-BkM5UDRU.js → MainPage-DEy4SyjJ.js} +1 -1
  5. package/dist/app/assets/{ModelPage-PgDTkS5C.js → ModelPage-BVHjDM-u.js} +2 -2
  6. package/dist/app/assets/{PackagePage-Dn7FrQ5r.js → PackagePage-Cbrg7o1X.js} +1 -1
  7. package/dist/app/assets/{PackageSplatRoute-BLC29ek-.js → PackageSplatRoute-ChFCJOWE.js} +2 -2
  8. package/dist/app/assets/{RenderedResult-vyM2wQbC.es-ha8dF24T.js → RenderedResult-BcEDcw0V.es-BD6PNbt6.js} +1 -1
  9. package/dist/app/assets/{RouteError-BolMqTuz.js → RouteError-CDSSYdLB.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-CPv1eHkI.js → ThemeEditorPage-DO2JWYOR.js} +1 -1
  11. package/dist/app/assets/{ToggleButtonGroup-DZtImN0S.js → ToggleButtonGroup-BylAiUaK.js} +1 -1
  12. package/dist/app/assets/{documentRoutes-DI5cX3ty.js → documentRoutes-CaOt2rpR.js} +1 -1
  13. package/dist/app/assets/{editPageMounted-C--4kcld.js → editPageMounted-79YCIKgP.js} +2 -2
  14. package/dist/app/assets/{index-DLToSg1f.js → index-BKjEX4_C.js} +10 -10
  15. package/dist/app/assets/{index-DyYEltlF.js → index-BOCBPBsi.js} +1 -1
  16. package/dist/app/assets/{index-D9wSfMZN.js → index-CPSEdm5f.js} +1 -1
  17. package/dist/app/assets/{index-CbsrzNSp.js → index-keJ8KKBp.js} +1 -1
  18. package/dist/app/assets/{index.es-D8SVyfmS.js → index.es-DTreXoC5.js} +1 -1
  19. package/dist/app/assets/usePackageLinkNavigate-BfSAqkJS.js +1 -0
  20. package/dist/app/assets/{usePackageRoute-A_YQMrax.js → usePackageRoute-G6fA1__J.js} +1 -1
  21. package/dist/app/index.html +1 -1
  22. package/dist/app/mcp-app/report.js +4 -4
  23. package/dist/instrumentation.mjs +1 -1
  24. package/dist/package_load_worker.mjs +638 -87
  25. package/dist/server.mjs +2470 -648
  26. package/dist/{sshcrypto-fqcyz88x.node → sshcrypto-wf5kpffj.node} +0 -0
  27. package/package.json +1 -1
  28. package/dist/app/assets/usePackageLinkNavigate-DxHGKrmZ.js +0 -1
@@ -12565,7 +12565,7 @@ function declaredFreshnessFacts(declarations) {
12565
12565
  ...fallback !== undefined ? { freshnessFallback: fallback } : {}
12566
12566
  };
12567
12567
  }
12568
- var FRESHNESS_FALLBACKS, WINDOW_UNITS, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
12568
+ 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
12569
  var init_freshness = __esm(() => {
12570
12570
  FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
12571
12571
  WINDOW_UNITS = {
@@ -12575,6 +12575,7 @@ var init_freshness = __esm(() => {
12575
12575
  d: 86400,
12576
12576
  w: 604800
12577
12577
  };
12578
+ 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
12579
  DURATION_UNITS = {
12579
12580
  ...WINDOW_UNITS,
12580
12581
  second: 1,
@@ -12679,7 +12680,7 @@ function freshnessValueProblem(group) {
12679
12680
  if (group.has("window")) {
12680
12681
  const window2 = group.text("window");
12681
12682
  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"';
12683
+ return FRESHNESS_WINDOW_PROBLEM;
12683
12684
  }
12684
12685
  }
12685
12686
  if (group.has("fallback") && !isFreshnessFallback(group.text("fallback"))) {
@@ -14094,7 +14095,7 @@ function errorKind(error) {
14094
14095
  function errorMapping(error) {
14095
14096
  return ERROR_TABLE[errorKind(error)];
14096
14097
  }
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;
14098
+ 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
14099
  var init_errors2 = __esm(() => {
14099
14100
  init_constants();
14100
14101
  init_logger();
@@ -14334,6 +14335,15 @@ var init_errors2 = __esm(() => {
14334
14335
  return "connection_failed";
14335
14336
  }
14336
14337
  };
14338
+ ResultTruncatedError = class ResultTruncatedError extends ConnectionError {
14339
+ get kind() {
14340
+ return "result_truncated";
14341
+ }
14342
+ constructor(returned, reported) {
14343
+ 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 });
14344
+ this.name = "ResultTruncatedError";
14345
+ }
14346
+ };
14337
14347
  UnconfiguredConnectionError = class UnconfiguredConnectionError extends Error {
14338
14348
  get kind() {
14339
14349
  return "unconfigured_connection";
@@ -14351,6 +14361,17 @@ var init_errors2 = __esm(() => {
14351
14361
  this.name = "ConnectionPoolExhaustedError";
14352
14362
  }
14353
14363
  };
14364
+ ResultShapeError = class ResultShapeError extends ConnectionError {
14365
+ get kind() {
14366
+ return "result_shape";
14367
+ }
14368
+ constructor(options) {
14369
+ super("The database returned a row that does not fit the result's schema, " + "so the result could not be built.", { callerSafe: true });
14370
+ if (options?.cause !== undefined)
14371
+ this.cause = options.cause;
14372
+ this.name = "ResultShapeError";
14373
+ }
14374
+ };
14354
14375
  DestinationNotFoundError = class DestinationNotFoundError extends Error {
14355
14376
  get kind() {
14356
14377
  return "destination_not_found";
@@ -14727,6 +14748,8 @@ var init_errors2 = __esm(() => {
14727
14748
  connection_failed: ConnectionFailedError,
14728
14749
  unconfigured_connection: UnconfiguredConnectionError,
14729
14750
  connection_pool_exhausted: ConnectionPoolExhaustedError,
14751
+ result_truncated: ResultTruncatedError,
14752
+ result_shape: ResultShapeError,
14730
14753
  destination_not_found: DestinationNotFoundError,
14731
14754
  storage_destination_not_found: StorageDestinationNotFoundError,
14732
14755
  storage_catalog_not_found: StorageCatalogNotFoundError,
@@ -15021,6 +15044,27 @@ var init_errors2 = __esm(() => {
15021
15044
  ]
15022
15045
  }
15023
15046
  },
15047
+ result_truncated: {
15048
+ ...CONNECTION,
15049
+ reason: "RESULT_TRUNCATED",
15050
+ log: { summary: "Database result truncated", level: "warn" },
15051
+ mcp: {
15052
+ advice: "fixed",
15053
+ suggestions: [
15054
+ NOT_TRANSIENT_CHANGE_QUERY,
15055
+ "Shrink the answer so it fits in one results page of about 10 MB: select fewer columns, aggregate, or add a LIMIT."
15056
+ ]
15057
+ }
15058
+ },
15059
+ result_shape: {
15060
+ ...CONNECTION,
15061
+ reason: "RESULT_SHAPE_MISMATCH",
15062
+ log: {
15063
+ summary: "Database result does not fit its schema",
15064
+ level: "error"
15065
+ },
15066
+ mcp: { advice: "internal" }
15067
+ },
15024
15068
  materialization_not_found: { status: 404, mcp: { advice: "internal" } },
15025
15069
  materialization_conflict: {
15026
15070
  status: 409,
@@ -16206,8 +16250,8 @@ async function liftRowLevelCondition(compiler, sourceName, exprs) {
16206
16250
  async function validateAuthorizeProbes(compiler, options) {
16207
16251
  const ownNotesOf = options.authorizeOwnNotes ?? new Map;
16208
16252
  for (const [sourceName, groups] of options.authorizeMap ?? []) {
16209
- for (const { route, exprs } of groups) {
16210
- if (exprs.length === 0)
16253
+ for (const { route, exprs, fromBase } of groups) {
16254
+ if (exprs.length === 0 || fromBase)
16211
16255
  continue;
16212
16256
  let condition;
16213
16257
  try {
@@ -17403,6 +17447,7 @@ function gatePlan(struct, graph, options) {
17403
17447
  excludeNotes: options.excludeNotes ?? [],
17404
17448
  walkMembers: true,
17405
17449
  nameHops: 0,
17450
+ baseHops: 0,
17406
17451
  ownTexts: options.ownTexts
17407
17452
  }));
17408
17453
  metComposite ||= walk.metComposite;
@@ -17430,6 +17475,8 @@ function walkRoute(walk, struct, route, visit) {
17430
17475
  fromAncestor: level.fromAncestor,
17431
17476
  treatAsOwn: visit.treatAsOwn,
17432
17477
  entryPoint: visit.entryPoint,
17478
+ baseHops: visit.baseHops,
17479
+ level: struct,
17433
17480
  ...level.failure ? { failure: level.failure } : {}
17434
17481
  });
17435
17482
  }
@@ -17481,6 +17528,7 @@ function walkRoute(walk, struct, route, visit) {
17481
17528
  exprs: ["false"],
17482
17529
  fromAncestor: false,
17483
17530
  treatAsOwn: false,
17531
+ baseHops: visit.baseHops,
17484
17532
  failure: { kind: "base_unresolvable", message }
17485
17533
  });
17486
17534
  const base = hop.kind === "resolved" ? hop.base : undefined;
@@ -17492,7 +17540,8 @@ function walkRoute(walk, struct, route, visit) {
17492
17540
  entryPoint: visit.entryPoint,
17493
17541
  excludeNotes: [],
17494
17542
  walkMembers: false,
17495
- nameHops: hop.byName ? visit.nameHops + 1 : visit.nameHops
17543
+ nameHops: hop.byName ? visit.nameHops + 1 : visit.nameHops,
17544
+ baseHops: visit.baseHops + 1
17496
17545
  }));
17497
17546
  } else {
17498
17547
  steps.push(baseFailure(hop.message));
@@ -17505,7 +17554,8 @@ function walkRoute(walk, struct, route, visit) {
17505
17554
  entryPoint: visit.entryPoint,
17506
17555
  excludeNotes: base ? ownLevelNotes(base.annotations) : [],
17507
17556
  walkMembers: true,
17508
- nameHops: visit.nameHops
17557
+ nameHops: visit.nameHops,
17558
+ baseHops: visit.baseHops + 1
17509
17559
  }));
17510
17560
  }
17511
17561
  return steps;
@@ -17587,6 +17637,21 @@ import {
17587
17637
  isJoined as isJoined2,
17588
17638
  isSourceDef as isSourceDef4
17589
17639
  } from "@malloydata/malloy";
17640
+ function derivationLevel(root, landing, contents) {
17641
+ let current = root;
17642
+ for (let depth = 0;current && depth <= ANCESTOR_WALK_MAX_DEPTH; depth++) {
17643
+ if ("sourceID" in landing ? current.sourceID === landing.sourceID : depth === landing.hops) {
17644
+ return current;
17645
+ }
17646
+ if (current.type !== "query_source")
17647
+ return;
17648
+ const query = current.query;
17649
+ const ref = query?.compositeResolvedSourceDef ?? query?.structRef;
17650
+ const base = typeof ref === "string" ? contents?.[ref] : ref;
17651
+ current = base && typeof base === "object" && isSourceDef4(base) ? base : undefined;
17652
+ }
17653
+ return;
17654
+ }
17590
17655
  function createGateClassificationDeps(givens, modelPath) {
17591
17656
  return {
17592
17657
  gateShapeCache: new Map,
@@ -17613,7 +17678,9 @@ function collectEntryPointGates(struct, modelDef, seen = new Set, treatAsOwnGate
17613
17678
  exprs: step.exprs,
17614
17679
  route: step.route,
17615
17680
  selfContained: step.fromAncestor || !step.treatAsOwn,
17616
- ...step.entryPoint ? { struct: step.entryPoint } : {}
17681
+ ...step.entryPoint ? { struct: step.entryPoint } : {},
17682
+ baseHops: step.baseHops,
17683
+ ...step.level ? { level: step.level } : {}
17617
17684
  });
17618
17685
  }
17619
17686
  return entries;
@@ -17629,17 +17696,32 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17629
17696
  if (!graftTarget) {
17630
17697
  return { shape: "rejected" };
17631
17698
  }
17699
+ let landing;
17700
+ let liftTarget = graftTarget;
17701
+ if (entry.baseHops > 0 && entry.level) {
17702
+ liftTarget = resolveGraftTarget(entry.level, originModelDef, graftScope.modelDef) ?? graftTarget;
17703
+ }
17704
+ if (entry.baseHops > 0 && entry.route !== AUTHORIZE_ROUTE) {
17705
+ const target = graftScope.modelDef.contents[graftTarget];
17706
+ const sourceID = entry.level?.sourceID;
17707
+ const candidate = sourceID !== undefined ? { sourceID } : target === entry.struct || target?.sourceID !== undefined && target.sourceID === entry.struct.sourceID ? { hops: entry.baseHops } : undefined;
17708
+ if (!entry.level || !candidate || !derivationLevel(target, candidate, graftScope.modelDef.contents)) {
17709
+ logger.debug("Row-level gate on a derivation's base has no base to graft onto; denying", { modelPath: deps.modelPath, label: entry.label });
17710
+ return { shape: "rejected" };
17711
+ }
17712
+ landing = candidate;
17713
+ }
17632
17714
  const filterText = gateFilterText(entry.exprs);
17633
- const cacheKey = `${graftScope.cacheScope}\x00${entry.route}\x00${graftTarget}\x00${filterText}`;
17715
+ const cacheKey = `${graftScope.cacheScope}\x00${entry.route}\x00${liftTarget}\x00${filterText}`;
17634
17716
  let cached = deps.gateShapeCache.get(cacheKey);
17635
17717
  if (!cached) {
17636
17718
  let condition;
17637
17719
  try {
17638
- condition = await liftGateCondition(graftTarget, filterText, graftScope.materializer);
17720
+ condition = await liftGateCondition(liftTarget, filterText, graftScope.materializer);
17639
17721
  } catch (err) {
17640
17722
  logger.debug("Row-level gate condition failed to lift; denying", {
17641
17723
  modelPath: deps.modelPath,
17642
- graftTarget,
17724
+ graftTarget: liftTarget,
17643
17725
  error: err instanceof Error ? err.message : String(err)
17644
17726
  });
17645
17727
  return { shape: "rejected" };
@@ -17659,7 +17741,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17659
17741
  givenNamesById: new Map
17660
17742
  };
17661
17743
  } else {
17662
- const targetStruct = graftScope.modelDef.contents[graftTarget];
17744
+ const targetStruct = graftScope.modelDef.contents[liftTarget];
17663
17745
  if (!isSourceDef4(targetStruct)) {
17664
17746
  classification = {
17665
17747
  shape: "rejected",
@@ -17706,7 +17788,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17706
17788
  if (unreachable !== undefined) {
17707
17789
  logger.warn("Gate accepted a given off the model surface; denying", {
17708
17790
  modelPath: deps.modelPath,
17709
- graftTarget,
17791
+ graftTarget: liftTarget,
17710
17792
  givenName: unreachable
17711
17793
  });
17712
17794
  classification = {
@@ -17733,6 +17815,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17733
17815
  return {
17734
17816
  shape: "row_level",
17735
17817
  graftTarget,
17818
+ ...landing !== undefined ? { landing } : {},
17736
17819
  filterText,
17737
17820
  condition: cached.condition,
17738
17821
  givenNames: cached.classification.givenNames
@@ -17820,7 +17903,7 @@ function assertAuthorizeGrammarValid(modelDef, authorizeMap, authorizeOwnNotes,
17820
17903
  const ownGroupTerms = [];
17821
17904
  const declaredAdmitAllRoutes = [];
17822
17905
  const ownRoutesSeen = new Set;
17823
- for (const { route, exprs } of groups) {
17906
+ for (const { route, exprs, fromBase } of groups) {
17824
17907
  const isOwn = (authorizeOwnNotes.get(sourceName)?.get(route)?.length ?? 0) > 0 && !ownRoutesSeen.has(route);
17825
17908
  if (isOwn)
17826
17909
  ownRoutesSeen.add(route);
@@ -17833,7 +17916,7 @@ function assertAuthorizeGrammarValid(modelDef, authorizeMap, authorizeOwnNotes,
17833
17916
  if (term.scope === "admit_all" && (attributedAuthorizeOwnNotes?.get(sourceName)?.get(route)?.length ?? 0) > 0) {
17834
17917
  declaredAdmitAllRoutes.push(route);
17835
17918
  }
17836
- if (term.scope === "row_level" && isSourceDef4(struct)) {
17919
+ if (term.scope === "row_level" && !fromBase && isSourceDef4(struct)) {
17837
17920
  assertNoFanoutFieldPath(sourceName, struct, term.fieldPath, term.fieldPathSegments);
17838
17921
  }
17839
17922
  }
@@ -25178,6 +25261,9 @@ var init_filter = __esm(() => {
25178
25261
 
25179
25262
  // src/service/gate_registry_walk.ts
25180
25263
  function gateExprsForRoute(struct, modelDef, route) {
25264
+ return gateGroupsForRoute(struct, modelDef, route).map((g) => g.exprs);
25265
+ }
25266
+ function gateGroupsForRoute(struct, modelDef, route) {
25181
25267
  const { steps } = gatePlan(struct, modelDefGateGraph(modelDef), {
25182
25268
  composite: "resolved",
25183
25269
  routes: [route],
@@ -25189,7 +25275,7 @@ function gateExprsForRoute(struct, modelDef, route) {
25189
25275
  continue;
25190
25276
  if (step.failure?.kind === "unreadable")
25191
25277
  throw step.failure.error;
25192
- groups.push(step.exprs);
25278
+ groups.push({ exprs: step.exprs, fromBase: step.baseHops > 0 });
25193
25279
  }
25194
25280
  return groups;
25195
25281
  }
@@ -25348,11 +25434,15 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
25348
25434
  const groupsForSource = [];
25349
25435
  const routeGroupsByRoute = new Map;
25350
25436
  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 });
25437
+ const groupsForRoute = gateGroupsForRoute(struct, modelDef, route);
25438
+ for (const { exprs, fromBase } of groupsForRoute) {
25439
+ groupsForSource.push({
25440
+ route,
25441
+ exprs,
25442
+ ...fromBase ? { fromBase: true } : {}
25443
+ });
25354
25444
  }
25355
- routeGroupsByRoute.set(route, groupsForRoute);
25445
+ routeGroupsByRoute.set(route, groupsForRoute.map((g) => g.exprs));
25356
25446
  }
25357
25447
  if (groupsForSource.length > 0) {
25358
25448
  authorizeMap.set(sourceName, groupsForSource);
@@ -28357,6 +28447,10 @@ var init_array_query = __esm(() => {
28357
28447
  });
28358
28448
 
28359
28449
  // src/service/connection_type.ts
28450
+ function managedOverrideOf(connection) {
28451
+ const name = connection.name;
28452
+ return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
28453
+ }
28360
28454
  function overrideOf(connection) {
28361
28455
  const name = connection.name;
28362
28456
  if (typeof name !== "string")
@@ -28368,12 +28462,21 @@ function overrideOf(connection) {
28368
28462
  }
28369
28463
  return;
28370
28464
  }
28371
- function recordConnectionType(connection, type) {
28465
+ function recordConnectionType(connection, type, options = {}) {
28372
28466
  const recordedType = overrideOf(connection) ?? type;
28373
28467
  if (recordedType)
28374
28468
  recorded.set(connection, recordedType);
28469
+ if (options.managed === true || managedOverrideOf(connection)) {
28470
+ managed.add(connection);
28471
+ }
28375
28472
  return connection;
28376
28473
  }
28474
+ function isManagedConnection(connection) {
28475
+ return !!connection && managed.has(connection);
28476
+ }
28477
+ function resolveManagedConnections(connections) {
28478
+ return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
28479
+ }
28377
28480
  function connectionTypeOf(connection) {
28378
28481
  return connection ? recorded.get(connection) : undefined;
28379
28482
  }
@@ -28386,10 +28489,12 @@ function resolveConnectionTypes(connections) {
28386
28489
  }
28387
28490
  return types;
28388
28491
  }
28389
- var recorded, overrides;
28492
+ var recorded, managed, overrides, managedOverrides;
28390
28493
  var init_connection_type = __esm(() => {
28391
28494
  recorded = new WeakMap;
28495
+ managed = new WeakSet;
28392
28496
  overrides = [];
28497
+ managedOverrides = [];
28393
28498
  });
28394
28499
 
28395
28500
  // src/service/materialization/plan/refusal_key.ts
@@ -28531,6 +28636,10 @@ function givenWhereCodes(def) {
28531
28636
  var MAX_WALK_DEPTH = 200;
28532
28637
 
28533
28638
  // src/service/materialization/domain/dialect.ts
28639
+ function isBinary64Type(dialect, nativeType) {
28640
+ const named = nativeType.trim().replace(/\s+/g, " ").toUpperCase();
28641
+ return capabilitiesOf(dialect).binary64Types?.includes(named) === true;
28642
+ }
28534
28643
  function capabilitiesOf(dialect) {
28535
28644
  const name = registeredDialect(dialect);
28536
28645
  return name === undefined ? NONE : CAPABILITIES[name];
@@ -28568,7 +28677,9 @@ var init_dialect = __esm(() => {
28568
28677
  leafBudget: 50,
28569
28678
  passthroughNumericAsDouble: false,
28570
28679
  catalogHidesTables: false,
28571
- stringCollation: undefined
28680
+ stringCollation: undefined,
28681
+ ungroupableTypes: undefined,
28682
+ binary64Types: undefined
28572
28683
  });
28573
28684
  CAPABILITIES = {
28574
28685
  duckdb: Object.freeze({
@@ -28585,7 +28696,8 @@ var init_dialect = __esm(() => {
28585
28696
  foldsTableNameCase: true,
28586
28697
  utcSessions: true,
28587
28698
  leafBudget: 120,
28588
- stringCollation: "instance"
28699
+ stringCollation: "instance",
28700
+ binary64Types: ["DOUBLE", "FLOAT8"]
28589
28701
  }),
28590
28702
  postgres: Object.freeze({
28591
28703
  ...NONE,
@@ -28601,7 +28713,24 @@ var init_dialect = __esm(() => {
28601
28713
  tableOwnership: true,
28602
28714
  castsToIntegerType: true,
28603
28715
  liveRoundsBigIntegersMeasured: true,
28604
- liveWritesFloat4Shortest: true
28716
+ liveWritesFloat4Shortest: true,
28717
+ binary64Types: ["DOUBLE PRECISION"],
28718
+ ungroupableTypes: {
28719
+ malloy: [],
28720
+ native: [
28721
+ "json",
28722
+ "xml",
28723
+ "point",
28724
+ "line",
28725
+ "lseg",
28726
+ "box",
28727
+ "path",
28728
+ "polygon",
28729
+ "circle",
28730
+ "txid_snapshot",
28731
+ "pg_snapshot"
28732
+ ]
28733
+ }
28605
28734
  }),
28606
28735
  standardsql: Object.freeze({
28607
28736
  ...NONE,
@@ -28614,7 +28743,11 @@ var init_dialect = __esm(() => {
28614
28743
  castsToIntegerType: true,
28615
28744
  onlyBigIntegerType: "INT64",
28616
28745
  leafBudget: 120,
28617
- stringCollation: "binary"
28746
+ stringCollation: "binary",
28747
+ ungroupableTypes: {
28748
+ malloy: ["json", "array", "record"],
28749
+ native: ["geography"]
28750
+ }
28618
28751
  }),
28619
28752
  snowflake: Object.freeze({
28620
28753
  ...NONE,
@@ -28625,7 +28758,15 @@ var init_dialect = __esm(() => {
28625
28758
  relationProbe: true,
28626
28759
  tableOwnership: true,
28627
28760
  castsToIntegerType: true,
28628
- leafBudget: 120
28761
+ leafBudget: 120,
28762
+ binary64Types: [
28763
+ "FLOAT",
28764
+ "FLOAT4",
28765
+ "FLOAT8",
28766
+ "DOUBLE",
28767
+ "DOUBLE PRECISION",
28768
+ "REAL"
28769
+ ]
28629
28770
  }),
28630
28771
  databricks: Object.freeze({
28631
28772
  ...NONE,
@@ -31341,11 +31482,19 @@ function instructionTier(instruction, mode) {
31341
31482
  function instructsUnwritableDestination(instruction, mode) {
31342
31483
  return !!instruction.destination && !storageWritable(mode);
31343
31484
  }
31485
+ function servedCopyReadsTier(tier, others) {
31486
+ return tier === "storage" || !others.includes("storage");
31487
+ }
31344
31488
  function readTier(facts) {
31345
31489
  if (!facts.storageBound) {
31346
31490
  return facts.declaredStorage ? "storage" : "database";
31347
31491
  }
31348
- return facts.servedCopy && !facts.storageFresh && facts.databaseFresh ? "database" : "storage";
31492
+ if (!facts.storageServed) {
31493
+ return facts.databaseBound ? "database" : "storage";
31494
+ }
31495
+ if (!facts.servedCopy)
31496
+ return "storage";
31497
+ return (!facts.storageFresh || facts.servedCopyOnDatabase) && facts.databaseFresh ? "database" : "storage";
31349
31498
  }
31350
31499
  function declaredDestination(declared, mode) {
31351
31500
  return storageWritable(mode) ? declared : undefined;
@@ -32867,6 +33016,166 @@ var init_persist_source_fields = __esm(() => {
32867
33016
  init_logger();
32868
33017
  });
32869
33018
 
33019
+ // src/service/governance/ir/source_reads.ts
33020
+ function isObj2(value) {
33021
+ return value !== null && typeof value === "object" && !Array.isArray(value);
33022
+ }
33023
+ function holdsRawSqlExpression(def) {
33024
+ const seen = new Set;
33025
+ const walk = (node, depth) => {
33026
+ if (depth > MAX_DEPTH)
33027
+ return true;
33028
+ if (node === null || typeof node !== "object")
33029
+ return false;
33030
+ if (seen.has(node))
33031
+ return false;
33032
+ seen.add(node);
33033
+ if (Array.isArray(node))
33034
+ return node.some((c) => walk(c, depth + 1));
33035
+ const record = node;
33036
+ if (record.node === "genericSQLExpr")
33037
+ return true;
33038
+ return Object.entries(record).some(([key, child]) => !(record.node === "function_call" && key === "overload") && walk(child, depth + 1));
33039
+ };
33040
+ return walk(def, 0);
33041
+ }
33042
+ function joinNamed(fields, name) {
33043
+ if (!Array.isArray(fields))
33044
+ return;
33045
+ return fields.find((f) => isObj2(f) && f.join !== undefined && (f.as ?? f.name) === name);
33046
+ }
33047
+ function allJoins(fields) {
33048
+ if (!Array.isArray(fields))
33049
+ return [];
33050
+ return fields.filter((f) => isObj2(f) && f.join !== undefined).flatMap((join) => [join, ...allJoins(join.fields)]);
33051
+ }
33052
+ function resolveJoinPath(roots, path) {
33053
+ for (const fields of roots) {
33054
+ let at;
33055
+ let scope = fields;
33056
+ for (const alias of path) {
33057
+ at = joinNamed(scope, alias);
33058
+ if (!at)
33059
+ break;
33060
+ scope = at.fields;
33061
+ }
33062
+ if (at)
33063
+ return at;
33064
+ }
33065
+ throw new Unknown(`join path ${path.join(".")} did not resolve`);
33066
+ }
33067
+ function relationReads(def, out, depth) {
33068
+ if (depth > MAX_DEPTH || !isObj2(def))
33069
+ throw new Unknown("unreadable");
33070
+ switch (def.type) {
33071
+ case "table":
33072
+ if (typeof def.connection !== "string" || typeof def.tablePath !== "string") {
33073
+ throw new Unknown("table without a path");
33074
+ }
33075
+ out.push({ connectionName: def.connection, table: def.tablePath });
33076
+ return;
33077
+ case "query_source":
33078
+ queryReads(def.query, out, depth + 1);
33079
+ return;
33080
+ case "composite":
33081
+ if (!Array.isArray(def.sources))
33082
+ throw new Unknown("composite");
33083
+ for (const member of def.sources) {
33084
+ relationReads(member, out, depth + 1);
33085
+ }
33086
+ return;
33087
+ default:
33088
+ throw new Unknown(`relation type ${String(def.type)}`);
33089
+ }
33090
+ }
33091
+ function queryReads(query, out, depth) {
33092
+ if (!isObj2(query))
33093
+ throw new Unknown("query");
33094
+ const input = query.compositeResolvedSourceDef ?? query.structRef;
33095
+ if (!isObj2(input))
33096
+ throw new Unknown("unresolved structRef");
33097
+ relationReads(input, out, depth + 1);
33098
+ const pipeline = Array.isArray(query.pipeline) ? query.pipeline : [];
33099
+ pipeline.forEach((segment, index) => {
33100
+ if (!isObj2(segment))
33101
+ throw new Unknown("segment");
33102
+ const extended = Array.isArray(segment.extendSource) ? segment.extendSource : [];
33103
+ const roots = index === 0 ? [extended, input.fields] : [extended];
33104
+ const joins = Array.isArray(segment.activeJoins) ? segment.activeJoins.map((usage) => {
33105
+ if (!Array.isArray(usage.path))
33106
+ throw new Unknown("join usage");
33107
+ return resolveJoinPath(roots, usage.path);
33108
+ }) : roots.flatMap(allJoins);
33109
+ for (const join of joins)
33110
+ relationReads(join, out, depth + 1);
33111
+ });
33112
+ }
33113
+ function sourceReads(source) {
33114
+ try {
33115
+ const def = sourceDefOf(source);
33116
+ if (holdsRawSqlExpression(def))
33117
+ return;
33118
+ const out = [];
33119
+ relationReads(def, out, 0);
33120
+ const distinct = new Map(out.map((r) => [JSON.stringify([r.connectionName, r.table]), r]));
33121
+ return [...distinct.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, r]) => r);
33122
+ } catch {
33123
+ return;
33124
+ }
33125
+ }
33126
+ var MAX_DEPTH = 200, Unknown;
33127
+ var init_source_reads = __esm(() => {
33128
+ Unknown = class Unknown extends Error {
33129
+ };
33130
+ });
33131
+
33132
+ // src/service/materialization/domain/upstream_schemas.ts
33133
+ function upstreamTableKey(table) {
33134
+ return JSON.stringify([table.connectionName, table.table]);
33135
+ }
33136
+ function canonicalType(nativeType) {
33137
+ return nativeType.replace(/\s+/g, " ").replace(/\s*([(),])\s*/g, "$1").trim().toUpperCase();
33138
+ }
33139
+ function namesColumn(sql, name) {
33140
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33141
+ return new RegExp(`(^|[^A-Za-z0-9_])${escaped}($|[^A-Za-z0-9_])`, "i").test(sql);
33142
+ }
33143
+ function upstreamSchemaFold(reads, readings, sql) {
33144
+ if (!reads || !readings)
33145
+ return;
33146
+ const parts = [];
33147
+ for (const table of reads) {
33148
+ const reading = readings[upstreamTableKey(table)];
33149
+ if (!reading)
33150
+ continue;
33151
+ parts.push([
33152
+ table.connectionName,
33153
+ table.table,
33154
+ "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)
33155
+ ]);
33156
+ }
33157
+ return parts.length === 0 ? undefined : JSON.stringify(parts);
33158
+ }
33159
+ function upstreamSchemasOf(reads, readings) {
33160
+ if (!reads || !readings)
33161
+ return;
33162
+ const out = [];
33163
+ for (const table of reads) {
33164
+ const reading = readings[upstreamTableKey(table)];
33165
+ if (!reading)
33166
+ continue;
33167
+ out.push({
33168
+ connectionName: table.connectionName,
33169
+ table: table.table,
33170
+ ..."unread" in reading ? { unread: reading.unread } : {
33171
+ columns: reading.columns.map((c) => ({ ...c })),
33172
+ ...reading.dialect ? { dialect: reading.dialect } : {}
33173
+ }
33174
+ });
33175
+ }
33176
+ return out.length === 0 ? undefined : out;
33177
+ }
33178
+
32870
33179
  // src/service/materialization/plan/addressing.ts
32871
33180
  import { makeDigest } from "@malloydata/malloy";
32872
33181
  function sourceBuildOf(build, unbuildable) {
@@ -32986,15 +33295,34 @@ function withoutSourceIDs(build, drop) {
32986
33295
  function plannedTargetOf(source) {
32987
33296
  return buildTargets.get(source);
32988
33297
  }
32989
- function computeSourceEntityId(source, connectionDigests, target, tableFolds) {
33298
+ function computeSourceEntityId(source, connectionDigests, target, tableFolds, upstreamSchemas) {
32990
33299
  const resolved = buildTargetOf(source, target);
32991
33300
  const fold = tableFolds?.[source.sourceID];
33301
+ const upstream = upstreamFoldOf(source, upstreamSchemas, resolved.sql);
32992
33302
  const chosen = testAddresses.get(resolved);
32993
33303
  if (chosen !== undefined) {
32994
- const layout = addressText(source, "", fold);
33304
+ const layout = addressText(source, "", fold, upstream);
32995
33305
  return layout === "" ? chosen : makeDigest(chosen, layout);
32996
33306
  }
32997
- return makeDigest(connectionDigests[source.connectionName], addressText(source, resolved.sql, fold));
33307
+ return makeDigest(connectionDigests[source.connectionName], addressText(source, resolved.sql, fold, upstream));
33308
+ }
33309
+ function upstreamFoldOf(source, readings, sql) {
33310
+ if (!readings)
33311
+ return;
33312
+ return upstreamSchemaFold(upstreamTablesOf(source), readings, sql);
33313
+ }
33314
+ function upstreamTablesOf(source) {
33315
+ let known = readsBySource.get(source);
33316
+ if (!known) {
33317
+ known = { reads: sourceReads(source) };
33318
+ readsBySource.set(source, known);
33319
+ }
33320
+ return known.reads;
33321
+ }
33322
+ function upstreamSchemasOfSource(source, readings) {
33323
+ if (!readings)
33324
+ return;
33325
+ return upstreamSchemasOf(upstreamTablesOf(source), readings);
32998
33326
  }
32999
33327
  function compilerBuildId(source, target) {
33000
33328
  const resolved = buildTargetOf(source, target);
@@ -33011,7 +33339,7 @@ function addressDestination(source) {
33011
33339
  return;
33012
33340
  }
33013
33341
  }
33014
- function addressText(source, sql, tableFold) {
33342
+ function addressText(source, sql, tableFold, upstream) {
33015
33343
  let text = sql;
33016
33344
  const destination = addressDestination(source);
33017
33345
  if (destination !== undefined)
@@ -33020,6 +33348,9 @@ function addressText(source, sql, tableFold) {
33020
33348
  if (tableFold)
33021
33349
  text += `
33022
33350
  -- table: ${tableFold}`;
33351
+ if (upstream)
33352
+ text += `
33353
+ -- upstream schemas: ${upstream}`;
33023
33354
  return text;
33024
33355
  }
33025
33356
  function declarationOf(source) {
@@ -33056,7 +33387,7 @@ function planAddresses(plan) {
33056
33387
  const addresses = {};
33057
33388
  for (const [sourceID, { source, target }] of Object.entries(plan.tables)) {
33058
33389
  try {
33059
- addresses[sourceID] = computeSourceEntityId(source, plan.connectionDigests, target, plan.tableFolds);
33390
+ addresses[sourceID] = computeSourceEntityId(source, plan.connectionDigests, target, plan.tableFolds, plan.upstreamSchemas);
33060
33391
  } catch (err) {
33061
33392
  addresses[sourceID] = {
33062
33393
  unaddressable: err instanceof Error ? err.message : String(err)
@@ -33179,7 +33510,7 @@ async function resolveConnectionDigests(connections, builds, onSkipped) {
33179
33510
  }
33180
33511
  return connectionDigests;
33181
33512
  }
33182
- var buildTargets, unkeyable, testAddresses;
33513
+ var buildTargets, unkeyable, testAddresses, readsBySource;
33183
33514
  var init_addressing = __esm(() => {
33184
33515
  init_config2();
33185
33516
  init_storage_table_path();
@@ -33187,9 +33518,11 @@ var init_addressing = __esm(() => {
33187
33518
  init_persist_source_fields();
33188
33519
  init_declaration();
33189
33520
  init_source_map();
33521
+ init_source_reads();
33190
33522
  buildTargets = new WeakMap;
33191
33523
  unkeyable = new WeakMap;
33192
33524
  testAddresses = new WeakMap;
33525
+ readsBySource = new WeakMap;
33193
33526
  });
33194
33527
 
33195
33528
  // src/service/materialization/domain/vocabulary.ts
@@ -33209,13 +33542,17 @@ function tableKeepsGates(t, s) {
33209
33542
  const row = Object.hasOwn(ROWS, t.kind) ? ROWS[t.kind] : undefined;
33210
33543
  return row ? row(t, s) === true : false;
33211
33544
  }
33212
- function gateColumnTypeExact(type) {
33213
- return !INEXACT_GATE_TYPE.test(type);
33545
+ function gateColumnTypeExact(type, upstream) {
33546
+ if (!INEXACT_GATE_TYPE.test(type))
33547
+ return true;
33548
+ if (!upstream || !isBinary64Type(STORAGE_DIALECT, type))
33549
+ return false;
33550
+ return isBinary64Type(upstream.dialect, upstream.nativeType);
33214
33551
  }
33215
33552
  function gateColumnsExact(t) {
33216
33553
  if (t.gateColumnTypes === undefined)
33217
33554
  return t.tier === "database";
33218
- return t.gateColumnTypes.every(gateColumnTypeExact);
33555
+ return t.gateColumnTypes.every((type, i) => gateColumnTypeExact(type, t.gateColumnUpstreamTypes?.[i]));
33219
33556
  }
33220
33557
  function g3Table(t) {
33221
33558
  return t.tier === "database" || t.ownGateKept === true || t.holdsOnlyUngatedRows === true;
@@ -33250,6 +33587,7 @@ function answerKeepsGates(leg, tablesRead, s, ctx) {
33250
33587
  var ROWS, GATE_LEGS, SERVING_GATE_CONTEXT, INEXACT_GATE_TYPE;
33251
33588
  var init_gate_policy = __esm(() => {
33252
33589
  init_vocabulary();
33590
+ init_dialect();
33253
33591
  ROWS = {
33254
33592
  persist: (t) => persistKeepsGates(t),
33255
33593
  materialize: (t, s) => materializedKeepsGates(t, s),
@@ -34328,9 +34666,7 @@ function readFreshnessGroup(tag, path) {
34328
34666
  if (keys.includes("window")) {
34329
34667
  const window2 = tag.text(...path, "window");
34330
34668
  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
- };
34669
+ return { invalid: FRESHNESS_WINDOW_PROBLEM };
34334
34670
  }
34335
34671
  freshness.window = window2.trim();
34336
34672
  }
@@ -37823,7 +38159,8 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
37823
38159
  label: "",
37824
38160
  exprs: ["false"],
37825
38161
  route: "authorize",
37826
- selfContained: true
38162
+ selfContained: true,
38163
+ baseHops: 0
37827
38164
  }
37828
38165
  ];
37829
38166
  unkeepable.add("(an unreadable gate)");
@@ -37831,6 +38168,9 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
37831
38168
  for (const entry of entries) {
37832
38169
  if (!entry.struct)
37833
38170
  unkeepable.add("(an unreadable gate)");
38171
+ if (entry.baseHops > 0 && canonicalAuthorizeRoute(entry.route) !== AUTHORIZE_ROUTE) {
38172
+ unkeepable.add("(a row filter on a derivation's base)");
38173
+ }
37834
38174
  for (const expr of entry.exprs) {
37835
38175
  for (const id of malloyIdentifiers(expr)) {
37836
38176
  const f = byName.get(id);
@@ -38083,6 +38423,9 @@ function unreadableSourceConnectionMessage(source, type) {
38083
38423
  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
38424
  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
38425
  }
38426
+ function catalogAuthorSqlMessage(source, { managed = false } = {}) {
38427
+ 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.`;
38428
+ }
38086
38429
  var PASSTHROUGH_SOURCE_TYPES;
38087
38430
  var init_source_connection_type = __esm(() => {
38088
38431
  PASSTHROUGH_SOURCE_TYPES = [
@@ -38092,6 +38435,59 @@ var init_source_connection_type = __esm(() => {
38092
38435
  ];
38093
38436
  });
38094
38437
 
38438
+ // src/service/materialization/domain/same_catalog_build.ts
38439
+ function isSameCatalog(source, destination) {
38440
+ const a = source?.type === "ducklake" ? source.ducklakeConnection : undefined;
38441
+ const b = destination?.type === "ducklake" ? destination.ducklakeConnection : undefined;
38442
+ if (!a || !b)
38443
+ return false;
38444
+ const pa = a.catalog?.postgresConnection;
38445
+ const pb = b.catalog?.postgresConnection;
38446
+ if (!pa || !pb)
38447
+ return false;
38448
+ const path = (url) => (url ?? "").replace(/\/+$/, "");
38449
+ const pathA = path(a.storage?.bucketUrl);
38450
+ const pathB = path(b.storage?.bucketUrl);
38451
+ 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);
38452
+ }
38453
+ function carriesAuthorSql(def) {
38454
+ const seen = new Set;
38455
+ const walk = (node, depth) => {
38456
+ if (depth > MAX_DEPTH2)
38457
+ return true;
38458
+ if (node === null || typeof node !== "object")
38459
+ return false;
38460
+ if (seen.has(node))
38461
+ return false;
38462
+ seen.add(node);
38463
+ if (Array.isArray(node)) {
38464
+ return node.some((child) => walk(child, depth + 1));
38465
+ }
38466
+ const record = node;
38467
+ if (record.type === "sql_select" || record.node === "genericSQLExpr") {
38468
+ return true;
38469
+ }
38470
+ if (record.node === "function_call") {
38471
+ return Object.entries(record).some(([key, child]) => key !== "overload" && walk(child, depth + 1));
38472
+ }
38473
+ if (record.type === "table" && typeof record.tablePath === "string" && !CATALOG_TABLE_PATH.test(record.tablePath)) {
38474
+ return true;
38475
+ }
38476
+ return Object.values(record).some((child) => walk(child, depth + 1));
38477
+ };
38478
+ try {
38479
+ if (def === null || typeof def !== "object")
38480
+ return true;
38481
+ return walk(def, 0);
38482
+ } catch {
38483
+ return true;
38484
+ }
38485
+ }
38486
+ var CATALOG_TABLE_PATH, MAX_DEPTH2 = 200;
38487
+ var init_same_catalog_build = __esm(() => {
38488
+ CATALOG_TABLE_PATH = /^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)*$/;
38489
+ });
38490
+
38095
38491
  // src/service/materialization/plan/materialization_eligibility.ts
38096
38492
  function assertMaterializationEligible(persistSource, annotationFields, options = {}) {
38097
38493
  const sourceName = persistSource.name;
@@ -38128,11 +38524,29 @@ function assertMaterializationEligible(persistSource, annotationFields, options
38128
38524
  }
38129
38525
  function assertStorageBuildReadsConnection(persistSource, connectionTypes) {
38130
38526
  const type = connectionTypes?.[persistSource.connectionName];
38131
- if (type === undefined || storageBuildReadsConnectionType(type))
38527
+ if (type === undefined)
38528
+ return;
38529
+ if (!storageBuildReadsConnectionType(type)) {
38530
+ throw new MaterializationEligibilityError({
38531
+ reason: "storage_source_unsupported",
38532
+ message: unreadableSourceConnectionMessage(persistSource, type)
38533
+ });
38534
+ }
38535
+ if (type === "ducklake" && carriesAuthorSql(sourceDefOf(persistSource))) {
38536
+ throw new MaterializationEligibilityError({
38537
+ reason: "storage_source_unsupported",
38538
+ message: catalogAuthorSqlMessage(persistSource)
38539
+ });
38540
+ }
38541
+ }
38542
+ function assertManagedBuildRunsMalloySql(source, plan) {
38543
+ if (!plan?.managedConnections?.includes(source.connectionName))
38544
+ return;
38545
+ if (!carriesAuthorSql(sourceDefOf(source)))
38132
38546
  return;
38133
38547
  throw new MaterializationEligibilityError({
38134
38548
  reason: "storage_source_unsupported",
38135
- message: unreadableSourceConnectionMessage(persistSource, type)
38549
+ message: catalogAuthorSqlMessage(source, { managed: true })
38136
38550
  });
38137
38551
  }
38138
38552
  function assertMergeKeyScopeResolvable(persistSource, terms, annotationFields, what) {
@@ -38468,6 +38882,7 @@ function assertTierEligible(source, storage, plan, annotationFields = deriveAnno
38468
38882
  assertBuildReadsNoCurrentTime(source, plan);
38469
38883
  return;
38470
38884
  }
38885
+ assertManagedBuildRunsMalloySql(source, plan);
38471
38886
  const table = plan?.tables?.[source.sourceID];
38472
38887
  const rollup = table?.rollup;
38473
38888
  assertDatabasePersistNotAuthorizeGated(source, source.name, rollup ? "rollup" : "persist", table?.gate, annotationFields, { gateEnforcedAtRead: !!rollup && rollupGateEnforcedAtRead(rollup) });
@@ -38536,6 +38951,7 @@ var init_materialization_eligibility = __esm(() => {
38536
38951
  init_declaration();
38537
38952
  init_rollup_plan();
38538
38953
  init_source_connection_type();
38954
+ init_same_catalog_build();
38539
38955
  READ_ONLY_DIALECTS = new Set(["sqlserver"]);
38540
38956
  });
38541
38957
 
@@ -39127,10 +39543,10 @@ function storableDimension(field) {
39127
39543
  }
39128
39544
  return dimension;
39129
39545
  }
39130
- function storableArray(field) {
39131
- if (field.type !== "array" || field.e !== undefined)
39546
+ function storableNested(field) {
39547
+ if (field.type !== "array" && field.type !== "record")
39132
39548
  return;
39133
- if (hiddenAccess(field))
39549
+ if (field.e !== undefined)
39134
39550
  return;
39135
39551
  const dimension = typeof field.as === "string" ? field.as : typeof field.name === "string" ? field.name : undefined;
39136
39552
  return dimension;
@@ -39141,9 +39557,15 @@ function materializeColumns(def, options = {}) {
39141
39557
  const perCaller = givenReadingFields(def.fields);
39142
39558
  for (const raw of def.fields ?? []) {
39143
39559
  const field = raw;
39144
- const nested = storableArray(field);
39560
+ const nested = storableNested(field);
39145
39561
  if (nested !== undefined) {
39146
- out.push({ dimension: nested, column: nested, computed: false });
39562
+ const access = hiddenAccess(field);
39563
+ out.push({
39564
+ dimension: nested,
39565
+ column: nested,
39566
+ computed: false,
39567
+ ...access ? { access } : {}
39568
+ });
39147
39569
  continue;
39148
39570
  }
39149
39571
  const dimension = storableDimension(field);
@@ -39882,6 +40304,10 @@ function pairLayoutOf(def, map, args) {
39882
40304
  if (problem) {
39883
40305
  return new Declined(problem.reason, { refused: "inline_unsupported" });
39884
40306
  }
40307
+ const ungrouped = ungroupablePairColumn(def, map, columns);
40308
+ if (ungrouped) {
40309
+ return new Declined(ungrouped, { refused: "inline_unsupported" });
40310
+ }
39885
40311
  const pairs = laid.map((l) => l.pair);
39886
40312
  pair = pairs[0];
39887
40313
  if (pairs.length > 1) {
@@ -39941,6 +40367,48 @@ function pairLayoutOf(def, map, args) {
39941
40367
  ...pairFullRefresh ? { pairFullRefresh } : {}
39942
40368
  };
39943
40369
  }
40370
+ function ungroupablePairColumn(def, map, columns) {
40371
+ const refused = capabilitiesOf(def.dialect).ungroupableTypes;
40372
+ if (!refused)
40373
+ return;
40374
+ for (const c of columns) {
40375
+ const type = ungroupedTypeOf(storedFieldOf(def, map, c), refused);
40376
+ if (type === undefined)
40377
+ continue;
40378
+ 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";
40379
+ }
40380
+ return;
40381
+ }
40382
+ function ungroupedTypeOf(field, refused) {
40383
+ if (field?.type === "sql native") {
40384
+ const raw = typeof field.rawType === "string" ? field.rawType.toLowerCase() : "";
40385
+ return refused.native.includes(raw) ? raw : undefined;
40386
+ }
40387
+ if (typeof field?.type !== "string")
40388
+ return;
40389
+ if (refused.malloy.includes(field.type))
40390
+ return field.type;
40391
+ if (field.type === "array") {
40392
+ const element = ungroupedTypeOf(field.elementTypeDef, refused);
40393
+ return element === undefined ? undefined : `${element}[]`;
40394
+ }
40395
+ return;
40396
+ }
40397
+ function storedFieldOf(def, map, c) {
40398
+ let fields = def.fields ?? [];
40399
+ let joins = map.joinsOf(def.sourceID);
40400
+ for (const name of c.join === undefined ? [] : c.path ?? [c.join]) {
40401
+ const join = joins.find((j) => j.name === name);
40402
+ if (!join)
40403
+ return;
40404
+ fields = join.fields;
40405
+ joins = map.joinedReadsOf(join).joins;
40406
+ }
40407
+ return fields.find((raw) => {
40408
+ const f = raw;
40409
+ return (typeof f.as === "string" ? f.as : f.name) === c.dimension;
40410
+ });
40411
+ }
39944
40412
  function chainExtensionTables(plans, map) {
39945
40413
  const byID = new Map(plans.map((p) => [p.sourceID, p]));
39946
40414
  const declarationOfID = (sourceID) => declarationOf2(map.node(sourceID)?.def);
@@ -40370,6 +40838,7 @@ function tierGateInputs(compiled) {
40370
40838
  return {
40371
40839
  tables: compiled.tables,
40372
40840
  connectionTypes: compiled.connectionTypes,
40841
+ managedConnections: compiled.managedConnections,
40373
40842
  accessReads: compiled.accessReads
40374
40843
  };
40375
40844
  }
@@ -43268,6 +43737,13 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
43268
43737
  refusal: gateRefusal
43269
43738
  };
43270
43739
  }
43740
+ const throughDerivation = gates.filter((g) => g.baseHops > 0 && canonicalAuthorizeRoute(g.route) !== AUTHORIZE_ROUTE);
43741
+ if (throughDerivation.length > 0) {
43742
+ return {
43743
+ reason: "its source inherits a row filter through `->`, which filters the derivation's base, not the rows a stored result holds",
43744
+ refusal: gateRefusalReason(throughDerivation.map((g) => g.route))
43745
+ };
43746
+ }
43271
43747
  const gatedWhy = "its source carries a row-level gate (#(access_filter) or #(authorize))";
43272
43748
  if (stages.length !== 1 || last.type !== "reduce") {
43273
43749
  return {
@@ -43493,6 +43969,7 @@ var init_persisted_view_compile = __esm(() => {
43493
43969
  init_annotations();
43494
43970
  init_annotation_reader();
43495
43971
  init_authorize();
43972
+ init_authorize_routes();
43496
43973
  init_gate_classification();
43497
43974
  init_prepared_query();
43498
43975
  init_malloy_text();
@@ -44117,7 +44594,7 @@ function storedColumnNames(persistSource) {
44117
44594
  let names;
44118
44595
  try {
44119
44596
  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);
44597
+ names = exploreOf(persistSource).intrinsicFields.filter((f) => f.isAtomicField() || isNestedColumn(f)).map((f) => columnOf(f.name)).filter((n) => typeof n === "string" && n.length > 0);
44121
44598
  } catch (err) {
44122
44599
  throw new Error(`the compiled source's field list could not be read (${errMessage(err)})`);
44123
44600
  }
@@ -44126,6 +44603,10 @@ function storedColumnNames(persistSource) {
44126
44603
  }
44127
44604
  return names;
44128
44605
  }
44606
+ function isNestedColumn(field) {
44607
+ const f = field;
44608
+ return f.isExploreField?.() === true;
44609
+ }
44129
44610
  function projectToStoredColumns(persistSource, buildSQL) {
44130
44611
  let cols;
44131
44612
  try {
@@ -44792,11 +45273,16 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44792
45273
  const decided = verdicts.get(sourceID).wire;
44793
45274
  if ("failed" in decided)
44794
45275
  throw decided.failed;
44795
- if (decided.refused)
44796
- refusedSources[sourceID] = decided.refused;
45276
+ if (decided.refused) {
45277
+ const freshness = resolveFreshness(source, packageMaterialization, table.rollup?.freshness);
45278
+ refusedSources[sourceID] = {
45279
+ ...decided.refused,
45280
+ ...freshness ? { freshness } : {}
45281
+ };
45282
+ }
44797
45283
  if (!decided.inPlan)
44798
45284
  continue;
44799
- wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization);
45285
+ wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization, compiled.upstreamSchemas);
44800
45286
  } catch (err) {
44801
45287
  const reason = isUnkeyable(source) ? "unkeyable" : err instanceof EligibilityCheckFailed ? "eligibility_check_failed" : "projection_failed";
44802
45288
  logger.warn("Failed to project a persist source into the build plan", {
@@ -44816,7 +45302,7 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44816
45302
  ...finalizeOmissions(omitted, new Set(Object.keys(wireSources)))
44817
45303
  };
44818
45304
  }
44819
- function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterialization) {
45305
+ function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterialization, upstreamSchemaReadings) {
44820
45306
  const { source, rollup, modelPath } = table;
44821
45307
  return {
44822
45308
  name: source.name,
@@ -44835,11 +45321,21 @@ function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterializ
44835
45321
  freshness: resolveFreshness(source, packageMaterialization, rollup?.freshness),
44836
45322
  queryMetadata: resolveQueryMetadata(source, packageMaterialization),
44837
45323
  columns: deriveColumns(source),
45324
+ ...readsOf(source),
45325
+ ...upstreamSchemasFieldOf(source, upstreamSchemaReadings),
44838
45326
  ...planDynamicFields(source),
44839
45327
  annotationFields,
44840
45328
  modelPath
44841
45329
  };
44842
45330
  }
45331
+ function upstreamSchemasFieldOf(source, readings) {
45332
+ const upstreamSchemas = upstreamSchemasOfSource(source, readings);
45333
+ return upstreamSchemas ? { upstreamSchemas } : {};
45334
+ }
45335
+ function readsOf(source) {
45336
+ const reads = sourceReads(source);
45337
+ return reads === undefined ? {} : { reads };
45338
+ }
44843
45339
  function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources, refusedSources) {
44844
45340
  const { tables } = compiled;
44845
45341
  const v1 = (id) => !tables[id]?.materialize;
@@ -44858,6 +45354,7 @@ function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources,
44858
45354
  modelPath: tables[sourceID]?.modelPath,
44859
45355
  tier: "database",
44860
45356
  reason: sibling.reason ?? "authorize",
45357
+ ...planned.freshness ? { freshness: planned.freshness } : {},
44861
45358
  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
45359
  };
44863
45360
  }
@@ -44905,7 +45402,9 @@ function finishBuildPlan(parts, ctx) {
44905
45402
  ...ctx.versionScoped ? { versionScoped: true } : {},
44906
45403
  ...parts,
44907
45404
  connectionDigests: ctx.connectionDigests,
45405
+ ...ctx.upstreamSchemas ? { upstreamSchemas: ctx.upstreamSchemas } : {},
44908
45406
  connectionTypes: resolveConnectionTypes(ctx.connections),
45407
+ managedConnections: resolveManagedConnections(ctx.connections),
44909
45408
  connections: ctx.connections,
44910
45409
  ...ctx.keyCheckCompilers && ctx.keyCheckCompilers.size > 0 ? { keyCheckCompilers: ctx.keyCheckCompilers } : {}
44911
45410
  };
@@ -44915,22 +45414,34 @@ function finishBuildPlan(parts, ctx) {
44915
45414
  tableFolds,
44916
45415
  addresses: planAddresses({ ...plan, tableFolds })
44917
45416
  }));
44918
- return ctx.keepIncrementalUnbuildable ? refused : refuseIncrementalUnbuildable(refused);
45417
+ const known = refuseUpstreamUnread(refused);
45418
+ return ctx.keepIncrementalUnbuildable ? known : refuseIncrementalUnbuildable(known);
44919
45419
  }
44920
45420
  async function finishPackagePlan(parts, ctx) {
44921
- const { getMalloyConnection, ...finish } = ctx;
45421
+ const { getMalloyConnection, readUpstreamSchemas, ...finish } = ctx;
44922
45422
  const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
44923
45423
  const digestSkipped = [];
44924
45424
  const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
45425
+ const upstreamSchemas = readUpstreamSchemas ? await readUpstreamSchemas(planUpstreamTables(parts.tables)) : undefined;
44925
45426
  return {
44926
45427
  compiled: finishBuildPlan(parts, {
44927
45428
  ...finish,
44928
45429
  connectionDigests,
45430
+ ...upstreamSchemas ? { upstreamSchemas } : {},
44929
45431
  connections
44930
45432
  }),
44931
45433
  digestSkipped
44932
45434
  };
44933
45435
  }
45436
+ function planUpstreamTables(tables) {
45437
+ const out = new Map;
45438
+ for (const { source } of Object.values(tables)) {
45439
+ for (const read of upstreamTablesOf(source) ?? []) {
45440
+ out.set(upstreamTableKey(read), read);
45441
+ }
45442
+ }
45443
+ return [...out.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, t]) => t);
45444
+ }
44934
45445
  function derivePackagePlan(compiled, materializationConfig, counts = {}) {
44935
45446
  const incrementalDeclarations = collectIncrementalDeclarations(compiled.tables);
44936
45447
  const verdicts = planVerdicts(compiled);
@@ -44950,11 +45461,13 @@ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
44950
45461
  builds: compiled.builds,
44951
45462
  connectionDigests: compiled.connectionDigests,
44952
45463
  connectionTypes: compiled.connectionTypes ?? {},
45464
+ managedConnections: compiled.managedConnections ?? [],
44953
45465
  buildConnectionNames: [
44954
45466
  ...new Set(compiled.builds.map((b) => b.connectionName))
44955
45467
  ].sort(),
44956
45468
  versionScoped: compiled.versionScoped === true,
44957
45469
  tableFolds: { ...compiled.tableFolds },
45470
+ upstreamSchemas: { ...compiled.upstreamSchemas },
44958
45471
  addresses: { ...compiled.addresses },
44959
45472
  compilerKeys: compilerKeysOf(compiled),
44960
45473
  annotationFindings,
@@ -45049,36 +45562,64 @@ function refuseIncrementalUnbuildable(compiled) {
45049
45562
  if (reason === undefined)
45050
45563
  continue;
45051
45564
  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,
45565
+ findings.push(notBuiltFinding(compiled, sourceID, "incremental_unsupported", reason));
45566
+ }
45567
+ return withoutSources(compiled, findings, dropped);
45568
+ }
45569
+ function refuseUpstreamUnread(compiled) {
45570
+ const readings = compiled.upstreamSchemas;
45571
+ if (!readings)
45572
+ return compiled;
45573
+ const findings = [];
45574
+ const dropped = new Set;
45575
+ for (const [sourceID, { source }] of Object.entries(compiled.tables)) {
45576
+ const unread = (upstreamTablesOf(source) ?? []).filter((t) => {
45577
+ const reading = readings[upstreamTableKey(t)];
45578
+ return reading !== undefined && "unread" in reading ? reading.unread === "read_failed" : false;
45579
+ });
45580
+ if (unread.length === 0)
45581
+ continue;
45582
+ dropped.add(sourceID);
45583
+ const tables = unread.map((t) => `"${t.table}" on connection "${t.connectionName}"`).join(", ");
45584
+ 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"));
45585
+ }
45586
+ return withoutSources(compiled, findings, dropped);
45587
+ }
45588
+ function notBuiltFinding(compiled, sourceID, reason, why) {
45589
+ const table = compiled.tables[sourceID];
45590
+ const source = table.source;
45591
+ const model = table.modelPath ?? "";
45592
+ const tier = tierOf(declaredStorage(source));
45593
+ const refused = refusalKey(sourceID, source.name, reason, tier);
45594
+ if (table.materialize) {
45595
+ return materializeRefusalFinding({
45596
+ sourceName: table.materialize.sourceName,
45058
45597
  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),
45598
+ reason: why,
45599
+ outcome: { refused: { reason, tier } }
45600
+ }, model);
45601
+ }
45602
+ const view = persistedViewOf(source);
45603
+ if (view) {
45604
+ return {
45605
+ ...persistedViewRefusalFinding({ ...view, sourceID, reason: why, outcome: { refused: reason } }, model),
45070
45606
  refused
45607
+ };
45608
+ }
45609
+ return {
45610
+ route: "@",
45611
+ tier: "unservable",
45612
+ ...table.kind === "rollup" ? {
45613
+ code: ROLLUP_NOT_BUILT_CODE,
45614
+ message: `Rollup "${source.name}" is not built, so its measures are answered live: ${why}.`
45071
45615
  } : {
45072
- route: "@",
45073
- tier: "unservable",
45074
45616
  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);
45617
+ message: `#@ persist source "${source.name}" is not built, so it is answered live: ${why}.`
45618
+ },
45619
+ subject: source.name,
45620
+ model,
45621
+ refused
45622
+ };
45082
45623
  }
45083
45624
  function persistedViewOf(source) {
45084
45625
  if (!isPersistedResultSourceID(source.sourceID))
@@ -45213,6 +45754,7 @@ var init_build_plan = __esm(() => {
45213
45754
  init_rollup_plan();
45214
45755
  init_config2();
45215
45756
  init_connection_type();
45757
+ init_source_reads();
45216
45758
  init_access_closure();
45217
45759
  init_persist_dynamic_terms();
45218
45760
  init_persist_source_fields();
@@ -45234,7 +45776,7 @@ var init_build_plan = __esm(() => {
45234
45776
  });
45235
45777
 
45236
45778
  // src/package_load/protocol.ts
45237
- var PACKAGE_LOAD_PROTOCOL_VERSION = 7;
45779
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 8;
45238
45780
 
45239
45781
  // src/package_load/package_load_worker.ts
45240
45782
  init_malloynb();
@@ -45682,7 +46224,7 @@ function callMain(send) {
45682
46224
  }
45683
46225
  var schemaWait = new RpcWaitAccountant;
45684
46226
  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") {
46227
+ 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
46228
  const pending = pendingRpc.get(message.requestId);
45687
46229
  if (!pending)
45688
46230
  return;
@@ -45983,7 +46525,7 @@ function buildWorkerMalloyConfig(job, refresh) {
45983
46525
  };
45984
46526
  port.postMessage(req);
45985
46527
  });
45986
- const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType);
46528
+ const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, { managed: response.metadata.managed === true });
45987
46529
  proxies.set(effectiveName, proxy);
45988
46530
  inflight.delete(effectiveName);
45989
46531
  return proxy;
@@ -46400,7 +46942,7 @@ async function loadPackage(job) {
46400
46942
  const schemaFetchDurationMs = schemaWait.waitMs;
46401
46943
  const schemaFetchCount = schemaWait.fetches;
46402
46944
  const schemaCacheHits = schemaCache.hits - schemaCacheHitsAtStart;
46403
- const buildPlan = await finishWorkerBuildPlan(malloyConfig, modelPaths, load, packageMetadata.materialization ?? null, !!job.publishedVersion && packageMetadata.scope === "version");
46945
+ const buildPlan = await finishWorkerBuildPlan(malloyConfig, modelPaths, load, packageMetadata.materialization ?? null, !!job.publishedVersion && packageMetadata.scope === "version", job.requestId);
46404
46946
  const loadEnd = performance.now();
46405
46947
  return {
46406
46948
  type: "load-package-result",
@@ -46422,7 +46964,7 @@ async function loadPackage(job) {
46422
46964
  buildPlan
46423
46965
  };
46424
46966
  }
46425
- async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped) {
46967
+ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped, jobId) {
46426
46968
  if (!load.planParts || load.failed || load.planLeftToMainThread) {
46427
46969
  return;
46428
46970
  }
@@ -46443,7 +46985,16 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
46443
46985
  }
46444
46986
  const finished = await finishPackagePlan(parts, {
46445
46987
  getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name),
46446
- versionScoped
46988
+ versionScoped,
46989
+ readUpstreamSchemas: async (tables) => (await callMain((requestId) => {
46990
+ const req = {
46991
+ type: "upstream-schemas",
46992
+ requestId,
46993
+ jobId,
46994
+ tables
46995
+ };
46996
+ port.postMessage(req);
46997
+ })).readings
46447
46998
  });
46448
46999
  digestSkipped = finished.digestSkipped;
46449
47000
  return {