@malloy-publisher/server 0.18.4 → 0.18.6

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 (26) hide show
  1. package/dist/app/api-doc.yaml +65 -13
  2. package/dist/app/assets/{EnvironmentPage-BxNqq3cN.js → EnvironmentPage-C3gdsp81.js} +1 -1
  3. package/dist/app/assets/{HomePage-B4iN5rso.js → HomePage-DqgKtxBQ.js} +1 -1
  4. package/dist/app/assets/{MainPage-DGiMH0eU.js → MainPage-BnTI-1vD.js} +1 -1
  5. package/dist/app/assets/{ModelPage-BJmyMnQo.js → ModelPage-eLIQM9Js.js} +2 -2
  6. package/dist/app/assets/{PackagePage-D2Pay_Xy.js → PackagePage-CejLNGDv.js} +1 -1
  7. package/dist/app/assets/{PackageSplatRoute-CQ7PxhkD.js → PackageSplatRoute-CXdCJTYw.js} +2 -2
  8. package/dist/app/assets/{RenderedResult-BEJ_GMaW.es-DS2oXAjc.js → RenderedResult-cJiP774J.es-CZC2lkLE.js} +1 -1
  9. package/dist/app/assets/{RouteError-BysHaT0t.js → RouteError-_sExFuNk.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-BFyTBbqA.js → ThemeEditorPage-CaJX95t_.js} +1 -1
  11. package/dist/app/assets/{ToggleButtonGroup-eURRljZv.js → ToggleButtonGroup-DogvpiUV.js} +1 -1
  12. package/dist/app/assets/{documentRoutes-DgTzGqfC.js → documentRoutes-G_kvP2a6.js} +1 -1
  13. package/dist/app/assets/{editPageMounted-CWBeAIbE.js → editPageMounted-CM_VLUwp.js} +2 -2
  14. package/dist/app/assets/{index-N8X9kVzc.js → index-CYndXhSx.js} +1 -1
  15. package/dist/app/assets/{index-D4DhR2vg.js → index-D9nJPs77.js} +1 -1
  16. package/dist/app/assets/{index-We9Zzxmt.js → index-O_b7OJ2r.js} +1 -1
  17. package/dist/app/assets/{index-CCLHq9po.js → index-b7pou7Vk.js} +5 -5
  18. package/dist/app/assets/{index.es-D_O2KdNW.js → index.es-DQ-xbkiQ.js} +1 -1
  19. package/dist/app/assets/usePackageLinkNavigate-Lw9XmylW.js +1 -0
  20. package/dist/app/assets/{usePackageRoute-DEUbQLf3.js → usePackageRoute-yIGqS2C8.js} +1 -1
  21. package/dist/app/index.html +1 -1
  22. package/dist/instrumentation.mjs +1 -1
  23. package/dist/package_load_worker.mjs +1710 -757
  24. package/dist/server.mjs +2363 -432
  25. package/package.json +1 -1
  26. package/dist/app/assets/usePackageLinkNavigate-CllycPZP.js +0 -1
package/dist/server.mjs CHANGED
@@ -14181,7 +14181,7 @@ function errorMapping(error) {
14181
14181
  function errorReason(error) {
14182
14182
  return resolve(errorMapping(error).reason, error);
14183
14183
  }
14184
- 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, ContractCaptureFailedError, SchemaIncompatibleError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, ManifestBindFailedError, 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;
14184
+ 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, ContainerNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, ContractCaptureFailedError, SchemaIncompatibleError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, ManifestBindFailedError, 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;
14185
14185
  var init_errors2 = __esm(() => {
14186
14186
  init_constants();
14187
14187
  init_logger();
@@ -14466,6 +14466,15 @@ var init_errors2 = __esm(() => {
14466
14466
  super(message);
14467
14467
  }
14468
14468
  };
14469
+ ContainerNotFoundError = class ContainerNotFoundError extends Error {
14470
+ get kind() {
14471
+ return "container_not_found";
14472
+ }
14473
+ constructor(message) {
14474
+ super(message);
14475
+ this.name = "ContainerNotFoundError";
14476
+ }
14477
+ };
14469
14478
  StorageDestinationNotFoundError = class StorageDestinationNotFoundError extends Error {
14470
14479
  get kind() {
14471
14480
  return "storage_destination_not_found";
@@ -14865,6 +14874,7 @@ var init_errors2 = __esm(() => {
14865
14874
  result_truncated: ResultTruncatedError,
14866
14875
  result_shape: ResultShapeError,
14867
14876
  destination_not_found: DestinationNotFoundError,
14877
+ container_not_found: ContainerNotFoundError,
14868
14878
  storage_destination_not_found: StorageDestinationNotFoundError,
14869
14879
  storage_catalog_not_found: StorageCatalogNotFoundError,
14870
14880
  connection_auth: ConnectionAuthError,
@@ -15070,6 +15080,7 @@ var init_errors2 = __esm(() => {
15070
15080
  },
15071
15081
  storage_catalog_not_found: { status: 404, mcp: { advice: "internal" } },
15072
15082
  destination_not_found: { status: 422, mcp: { advice: "internal" } },
15083
+ container_not_found: { status: 422, mcp: { advice: "internal" } },
15073
15084
  connection_auth: {
15074
15085
  status: 424,
15075
15086
  message: GENERIC_AUTH_MESSAGE,
@@ -24031,11 +24042,16 @@ function recordConnectionType(connection, type, options = {}) {
24031
24042
  const recordedType = overrideOf(connection) ?? type;
24032
24043
  if (recordedType)
24033
24044
  recorded.set(connection, recordedType);
24045
+ if (options.config)
24046
+ configs.set(connection, options.config);
24034
24047
  if (options.managed === true || managedOverrideOf(connection)) {
24035
24048
  managed.set(connection, options.schemas ?? MAIN_ONLY);
24036
24049
  }
24037
24050
  return connection;
24038
24051
  }
24052
+ function connectionConfigOf(connection) {
24053
+ return connection ? configs.get(connection) : undefined;
24054
+ }
24039
24055
  function isManagedConnection(connection) {
24040
24056
  return !!connection && managed.has(connection);
24041
24057
  }
@@ -24057,10 +24073,11 @@ function resolveConnectionTypes(connections) {
24057
24073
  }
24058
24074
  return types;
24059
24075
  }
24060
- var recorded, managed, MAIN_ONLY, overrides, managedOverrides;
24076
+ var recorded, managed, configs, MAIN_ONLY, overrides, managedOverrides;
24061
24077
  var init_connection_type = __esm(() => {
24062
24078
  recorded = new WeakMap;
24063
24079
  managed = new WeakMap;
24080
+ configs = new WeakMap;
24064
24081
  MAIN_ONLY = managedSchemas();
24065
24082
  overrides = [];
24066
24083
  managedOverrides = [];
@@ -110754,6 +110771,20 @@ function readableSchemaScope(rootSlash, recorded) {
110754
110771
  }
110755
110772
  return `${rootSlash}${trimmed}/`;
110756
110773
  }
110774
+ function recordManagedScope(connection, dbName, prefixes) {
110775
+ const holder = scopeHolder(connection);
110776
+ let byName = managedScopes.get(holder);
110777
+ if (!byName) {
110778
+ byName = new Map;
110779
+ managedScopes.set(holder, byName);
110780
+ }
110781
+ byName.set(dbName, [...prefixes]);
110782
+ }
110783
+ function managedScopeOf(connection, dbName) {
110784
+ if (!connection || typeof connection !== "object")
110785
+ return;
110786
+ return managedScopes.get(scopeHolder(connection))?.get(dbName);
110787
+ }
110757
110788
  function storageSecretScope(input) {
110758
110789
  const root = input.configuredDataPath || input.recordedDataPath;
110759
110790
  if (!root || isBucketlessUrl(root))
@@ -110805,13 +110836,14 @@ function storageSecretScope(input) {
110805
110836
  }
110806
110837
  return [...new Set([mainScope, ...owners.map(([, prefix]) => prefix)])];
110807
110838
  }
110808
- var METADATA_CATALOG_PREFIX = "__ducklake_metadata_", ScopeContainmentError;
110839
+ var METADATA_CATALOG_PREFIX = "__ducklake_metadata_", managedScopes, scopeHolder = (connection) => duckDBInstanceOf(connection) ?? connection, ScopeContainmentError;
110809
110840
  var init_ducklake_catalog = __esm(() => {
110810
110841
  init_logger();
110811
110842
  init_duckdb_lockdown();
110812
110843
  init_connection_type();
110813
110844
  init_duckdb_session_setup();
110814
110845
  init_quoting();
110846
+ managedScopes = new WeakMap;
110815
110847
  ScopeContainmentError = class ScopeContainmentError extends Error {
110816
110848
  };
110817
110849
  });
@@ -111170,6 +111202,10 @@ async function secureCatalogStorage(connection, dbName, storage, input) {
111170
111202
  if (root)
111171
111203
  allowForLockdown(connection, root);
111172
111204
  }
111205
+ const allowed = (roots ?? []).filter((r) => !!r);
111206
+ if (managedView && allowed.length > 0) {
111207
+ recordManagedScope(connection, dbName, allowed);
111208
+ }
111173
111209
  }
111174
111210
  if (storage) {
111175
111211
  try {
@@ -111186,6 +111222,8 @@ async function secureCatalogStorage(connection, dbName, storage, input) {
111186
111222
  await attachCloudStorage(connection, storage, options.origin, scope);
111187
111223
  for (const prefix of scope)
111188
111224
  allowForLockdown(connection, prefix);
111225
+ if (managedView)
111226
+ recordManagedScope(connection, dbName, scope);
111189
111227
  } catch (error) {
111190
111228
  if (isInstanceLocked(connection)) {
111191
111229
  logger.error("DuckLake storage secret failed after its instance was locked; the catalog is left attached", {
@@ -133085,7 +133123,8 @@ function buildEnvironmentMalloyConfig(connections = [], environmentPath = "", is
133085
133123
  }
133086
133124
  recordConnectionType(connection, metadata?.apiConnection.type, {
133087
133125
  managed: metadata?.apiConnection.managed === true,
133088
- schemas: managedSchemas(metadata?.apiConnection.ducklakeConnection?.readableSchemas)
133126
+ schemas: managedSchemas(metadata?.apiConnection.ducklakeConnection?.readableSchemas),
133127
+ config: metadata?.apiConnection
133089
133128
  });
133090
133129
  return applyConnectionFingerprint(connection, metadata);
133091
133130
  }
@@ -133991,7 +134030,8 @@ var init_dialect = __esm(() => {
133991
134030
  catalogHidesTables: false,
133992
134031
  stringCollation: undefined,
133993
134032
  ungroupableTypes: undefined,
133994
- binary64Types: undefined
134033
+ binary64Types: undefined,
134034
+ containerCatalog: undefined
133995
134035
  });
133996
134036
  CAPABILITIES = {
133997
134037
  duckdb: Object.freeze({
@@ -134010,10 +134050,12 @@ var init_dialect = __esm(() => {
134010
134050
  utcSessions: true,
134011
134051
  leafBudget: 120,
134012
134052
  stringCollation: "instance",
134013
- binary64Types: ["DOUBLE", "FLOAT8"]
134053
+ binary64Types: ["DOUBLE", "FLOAT8"],
134054
+ containerCatalog: "duckdb_schemas"
134014
134055
  }),
134015
134056
  postgres: Object.freeze({
134016
134057
  ...NONE,
134058
+ containerCatalog: "pg_namespace",
134017
134059
  stringCollation: "column",
134018
134060
  passthroughNumericAsDouble: true,
134019
134061
  incrementalSourceRange: true,
@@ -134059,6 +134101,7 @@ var init_dialect = __esm(() => {
134059
134101
  onlyBigIntegerType: "INT64",
134060
134102
  leafBudget: 120,
134061
134103
  stringCollation: "dataset",
134104
+ containerCatalog: "dataset",
134062
134105
  ungroupableTypes: {
134063
134106
  malloy: ["json", "array", "record"],
134064
134107
  native: ["geography"]
@@ -134066,6 +134109,7 @@ var init_dialect = __esm(() => {
134066
134109
  }),
134067
134110
  snowflake: Object.freeze({
134068
134111
  ...NONE,
134112
+ containerCatalog: "schemata",
134069
134113
  decodedTablePath: true,
134070
134114
  catalogHidesTables: true,
134071
134115
  incrementalSourceRange: true,
@@ -135409,10 +135453,19 @@ function keyUniquenessOfContract(contract, sources, leaves = []) {
135409
135453
  if (source)
135410
135454
  read("leaf", leaf.joinPath, source);
135411
135455
  }
135456
+ const grainJoinKeys = {};
135457
+ for (const [name, check] of Object.entries(keys)) {
135458
+ const joinKey = contractKeyWithoutLevel(name, "grain_join");
135459
+ if (joinKey !== undefined && check.level === "grain_join") {
135460
+ grainJoinKeys[joinKey] = passed(check);
135461
+ }
135462
+ }
135412
135463
  const anyParent = Object.keys(parentKeys).length > 0;
135413
- if (!own && !anyParent)
135464
+ const anyGrainJoin = Object.keys(grainJoinKeys).length > 0;
135465
+ if (!own && !anyParent && !anyGrainJoin)
135414
135466
  return;
135415
135467
  return {
135468
+ ...anyGrainJoin ? { grainJoinKeys } : {},
135416
135469
  ...own ? {
135417
135470
  keyColumn: contractKeyWithoutLevel(own[0], "rollup"),
135418
135471
  unique: passed(own[1])
@@ -137598,6 +137651,21 @@ var init_declaration_text = __esm(() => {
137598
137651
  TERM_NOT_FOUND = "a `where:` reading a given could not be found as written in the " + "source's declaration, so it cannot be left out of the build";
137599
137652
  });
137600
137653
 
137654
+ // src/service/materialization/domain/rollup_grain.ts
137655
+ function pathColumnName(join, field) {
137656
+ return `${join}__${field}`;
137657
+ }
137658
+ function grainPathOf(grain) {
137659
+ const at = grain.indexOf(".");
137660
+ if (at < 0)
137661
+ return;
137662
+ return { join: grain.slice(0, at), field: grain.slice(at + 1) };
137663
+ }
137664
+ function grainColumnOf(grain) {
137665
+ const path = grainPathOf(grain);
137666
+ return path ? pathColumnName(path.join, path.field) : grain;
137667
+ }
137668
+
137601
137669
  // src/service/materialization/domain/table_plans.ts
137602
137670
  function splitSourceID(sourceID) {
137603
137671
  const match = /^(.+)@([a-z][a-z0-9+.-]*:.*)$/i.exec(sourceID);
@@ -137761,7 +137829,10 @@ function persistLine(plan) {
137761
137829
  return "#@ persist";
137762
137830
  }
137763
137831
  function emitRollupBuildSource(plan) {
137764
- const grain = plan.grainDimensions.map((g) => ` ${identifier(g)}`).join(`
137832
+ const grain = plan.grainDimensions.map((g) => {
137833
+ const path = grainPathOf(g);
137834
+ return path ? ` ${identifier(grainColumnOf(g))} is ${identifier(path.join)}.${identifier(path.field)}` : ` ${identifier(g)}`;
137835
+ }).join(`
137765
137836
  `);
137766
137837
  const partials = plan.rollupMeasures.flatMap((m) => m.partials).map((p) => ` ${identifier(p.column)} is ${emitMeasureExpr(p.leaf.expr)}`).join(`
137767
137838
  `);
@@ -141348,8 +141419,65 @@ var init_persist_annotation_validation = __esm(() => {
141348
141419
  SAFE_NAME_PATH = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
141349
141420
  });
141350
141421
 
141351
- // src/service/materialization/text/source_map.ts
141422
+ // src/service/governance/ir/sql_embeds.ts
141352
141423
  import { isSourceDef as isSourceDef7 } from "@malloydata/malloy";
141424
+ function sqlSelectsWithin(root) {
141425
+ const found = [];
141426
+ const seen = new Set;
141427
+ const stack = [root];
141428
+ while (stack.length > 0) {
141429
+ const node = stack.pop();
141430
+ if (Array.isArray(node)) {
141431
+ stack.push(...node);
141432
+ continue;
141433
+ }
141434
+ if (!isObj2(node) || seen.has(node))
141435
+ continue;
141436
+ seen.add(node);
141437
+ if (node.type === "sql_select" && Array.isArray(node.selectSegments)) {
141438
+ found.push(node);
141439
+ }
141440
+ stack.push(...Object.values(node));
141441
+ }
141442
+ return found;
141443
+ }
141444
+ function embeddedStructs(segment, modelDef) {
141445
+ if (segment.type === "query") {
141446
+ const ref = segment.structRef;
141447
+ let base = ref;
141448
+ if (typeof ref === "string")
141449
+ base = modelDef.contents[ref];
141450
+ if (!isObj2(base) || !isSourceDef7(base)) {
141451
+ return {
141452
+ unreadable: "its source reference does not resolve in the model",
141453
+ label: typeof ref === "string" ? ref : "<embedded query>"
141454
+ };
141455
+ }
141456
+ const structs = [base];
141457
+ const resolved = segment.compositeResolvedSourceDef;
141458
+ if (isObj2(resolved) && isSourceDef7(resolved)) {
141459
+ structs.push(resolved);
141460
+ }
141461
+ return { structs };
141462
+ }
141463
+ if (isSourceDef7(segment)) {
141464
+ return { structs: [segment] };
141465
+ }
141466
+ return {
141467
+ unreadable: `its segment shape (type ${JSON.stringify(segment.type)}) is not one Publisher reads`,
141468
+ label: labelOf(segment)
141469
+ };
141470
+ }
141471
+ var isObj2 = (value) => typeof value === "object" && value !== null, INLINE_SQL = "<inline sql()>", labelOf = (struct) => {
141472
+ const label = struct.as ?? struct.name;
141473
+ if (typeof label !== "string")
141474
+ return "<unnamed>";
141475
+ return label.startsWith("sql://") ? INLINE_SQL : label;
141476
+ };
141477
+ var init_sql_embeds = () => {};
141478
+
141479
+ // src/service/materialization/text/source_map.ts
141480
+ import { isSourceDef as isSourceDef8 } from "@malloydata/malloy";
141353
141481
  function structRefSourceId(structRef) {
141354
141482
  if (typeof structRef === "string")
141355
141483
  return structRef;
@@ -141509,7 +141637,7 @@ function reachableSourceIDs(roots, modelDef) {
141509
141637
  add(structRefSourceId(member));
141510
141638
  visit(typeof member === "string" ? byId(modelDef, member) : member);
141511
141639
  }
141512
- if (modelDef !== undefined && isSourceDef7(node)) {
141640
+ if (modelDef !== undefined && isSourceDef8(node)) {
141513
141641
  const struct = node;
141514
141642
  const model = modelDef;
141515
141643
  const declared = resolveDeclaredSource(struct, model);
@@ -141520,6 +141648,11 @@ function reachableSourceIDs(roots, modelDef) {
141520
141648
  visit(resolveQuerySourceBase(struct, model));
141521
141649
  visit(resolveCompositeResolvedBase(struct));
141522
141650
  }
141651
+ const segments = def.selectSegments;
141652
+ if (Array.isArray(segments)) {
141653
+ for (const segment of segments)
141654
+ visitEmbed(segment);
141655
+ }
141523
141656
  for (const field of def.fields ?? []) {
141524
141657
  const f = field;
141525
141658
  if (typeof f?.join === "string") {
@@ -141530,6 +141663,22 @@ function reachableSourceIDs(roots, modelDef) {
141530
141663
  }
141531
141664
  }
141532
141665
  };
141666
+ const visitEmbed = (segment) => {
141667
+ if (segment === null || typeof segment !== "object")
141668
+ return;
141669
+ const embed = segment;
141670
+ if ("sql" in embed && embed.type === undefined)
141671
+ return;
141672
+ add(structRefSourceId(embed.structRef));
141673
+ const read = modelDef !== undefined ? embeddedStructs(embed, modelDef) : undefined;
141674
+ if (read !== undefined && "structs" in read) {
141675
+ for (const struct of read.structs)
141676
+ visit(struct);
141677
+ } else {
141678
+ scanWhole(embed, 0);
141679
+ }
141680
+ visitPipeline(embed.pipeline);
141681
+ };
141533
141682
  for (const root of roots)
141534
141683
  visit(root);
141535
141684
  return ids;
@@ -141642,6 +141791,7 @@ function reachPersisted(ctx, name, isPersisted) {
141642
141791
  }
141643
141792
  var SourceMap, MAX_PIPELINE_DEPTH = 200;
141644
141793
  var init_source_map = __esm(() => {
141794
+ init_sql_embeds();
141645
141795
  init_source_graph();
141646
141796
  SourceMap = class SourceMap {
141647
141797
  modelDef;
@@ -149316,7 +149466,7 @@ var require_dist11 = __commonJS(function(exports) {
149316
149466
 
149317
149467
  // src/service/given.ts
149318
149468
  import {
149319
- isSourceDef as isSourceDef8
149469
+ isSourceDef as isSourceDef9
149320
149470
  } from "@malloydata/malloy";
149321
149471
  function presentText(tag, ...path) {
149322
149472
  const raw = tagText(tag, ...path);
@@ -149406,7 +149556,7 @@ function suggestGivenLookup(modelDef, gatesBySource, surfaced) {
149406
149556
  const bySource = new Map;
149407
149557
  const byQuery = new Map;
149408
149558
  for (const obj of Object.values(modelDef.contents)) {
149409
- if (isSourceDef8(obj)) {
149559
+ if (isSourceDef9(obj)) {
149410
149560
  const name = obj.as || obj.name;
149411
149561
  const refs = new Set;
149412
149562
  collectGivenRefs(obj.filterList, refs);
@@ -150391,6 +150541,7 @@ var init_key_check = __esm(() => {
150391
150541
  pair_level: { nullKey: "fails", onRepeat: "fail_build" },
150392
150542
  rollup_key: { nullKey: "ignored", onRepeat: "record" },
150393
150543
  parent_key: { nullKey: "fails", onRepeat: "record" },
150544
+ grain_join_key: { nullKey: "ignored", onRepeat: "record" },
150394
150545
  stored_key: { nullKey: "fails", onRepeat: "record" }
150395
150546
  };
150396
150547
  });
@@ -150439,6 +150590,11 @@ var init_key_check_text = __esm(() => {
150439
150590
  inline_join_one: { count: "matches", key: undefined, notNull: "is not" },
150440
150591
  pair_level: { count: "matches", key: undefined, isNull: "is" },
150441
150592
  rollup_key: { count: "key_rows__check", key: undefined, notNull: "!=" },
150593
+ grain_join_key: {
150594
+ count: "key_rows__check",
150595
+ key: undefined,
150596
+ notNull: "!="
150597
+ },
150442
150598
  parent_key: { count: "key_rows__check", key: "key__check", isNull: "=" }
150443
150599
  };
150444
150600
  });
@@ -152489,16 +152645,7 @@ function declarationRefusal(decl, facts, ctx) {
152489
152645
  return "skip";
152490
152646
  return unservable("hidden_field", decl, "the measure is not public, and a rollup would publish it");
152491
152647
  }
152492
- const grainProblem = decl.grain.map((g) => {
152493
- const f = byName.get(g);
152494
- if (g.includes(".")) {
152495
- return `the grain names \`${g}\`, a path; declare a dimension on the source that reads it, and name that`;
152496
- }
152497
- if (!f || !isDimension(f)) {
152498
- return `the grain names \`${g}\`, which is not a dimension of the source`;
152499
- }
152500
- return;
152501
- }).find((p) => p !== undefined);
152648
+ const grainProblem = grainProblemOf(decl.grain, facts);
152502
152649
  if (grainProblem) {
152503
152650
  if (decl.v1)
152504
152651
  return "skip";
@@ -152510,7 +152657,7 @@ function declarationRefusal(decl, facts, ctx) {
152510
152657
  measure: decl.measure
152511
152658
  };
152512
152659
  }
152513
- const timeRead = facts.windowed ? "the source's rows read the current time (a `where:` with `now` or a relative time filter such as `f'last 7 days'`, a rolling window)" : timeFields.has(decl.measure) ? "the measure reads the current time (`now`, or a relative time filter)" : decl.grain.filter((g) => timeFields.has(g)).map((g) => `its grain dimension \`${g}\` reads the current time (\`now\`, or a relative time filter)`)[0];
152660
+ const timeRead = facts.windowed ? "the source's rows read the current time (a `where:` with `now` or a relative time filter such as `f'last 7 days'`, a rolling window)" : timeFields.has(decl.measure) ? "the measure reads the current time (`now`, or a relative time filter)" : decl.grain.filter((g) => timeFields.has(g) || pathReadsCurrentTime(g, facts)).map((g) => `its grain dimension \`${g}\` reads the current time (\`now\`, or a relative time filter)`)[0];
152514
152661
  if (timeRead) {
152515
152662
  return unservable("current_time", decl, `${timeRead}, which a rollup would fix at build time while a live query reads it again at every read`);
152516
152663
  }
@@ -152529,7 +152676,12 @@ function declarationRefusal(decl, facts, ctx) {
152529
152676
  if (hiddenGrain) {
152530
152677
  return unservable("hidden_field", decl, `its grain dimension \`${hiddenGrain}\` is private on a source it extends, declared in another file, which a rollup's build copy cannot lift`);
152531
152678
  }
152532
- const unreadableGrain = decl.storage === undefined ? undefined : unreadableStoredGrain(decl.grain, byName, facts.dialect);
152679
+ const unreadableGrain = decl.storage === undefined ? undefined : unreadableStoredGrain(decl.grain, (g) => {
152680
+ if (!g.includes("."))
152681
+ return byName.get(g);
152682
+ const path = pathGrainOf(g, facts);
152683
+ return "problem" in path ? undefined : path.joined;
152684
+ }, facts.dialect);
152533
152685
  if (unreadableGrain) {
152534
152686
  return unservable("unreadable_grain", decl, `its grain dimension \`${unreadableGrain.name}\` is stored as ${unreadableGrain.storedType}, which no read of a storage destination declares, so its table would cost a build no query reads; leave out storage= to build it in the source's own warehouse, which reads it`);
152535
152687
  }
@@ -152558,11 +152710,167 @@ function declarationRefusal(decl, facts, ctx) {
152558
152710
  }
152559
152711
  return;
152560
152712
  }
152561
- function unreadableStoredGrain(grain, byName, dialect) {
152713
+ function grainProblemOf(grain, facts) {
152714
+ const { byName } = facts;
152715
+ const columns = new Map;
152716
+ return grain.map((g) => {
152717
+ const f = byName.get(g);
152718
+ if (g.includes(".")) {
152719
+ const path = pathGrainOf(g, facts);
152720
+ if ("problem" in path)
152721
+ return path.problem;
152722
+ const column = grainColumnOf(g);
152723
+ if (byName.has(column) || columns.has(column)) {
152724
+ return `the grain names \`${g}\`, stored as \`${column}\`, which is already the name of ${byName.has(column) ? "a field of the source" : `\`${columns.get(column)}\``}`;
152725
+ }
152726
+ columns.set(column, g);
152727
+ return;
152728
+ }
152729
+ if (!f || !isDimension(f)) {
152730
+ return `the grain names \`${g}\`, which is not a dimension of the source`;
152731
+ }
152732
+ columns.set(g, g);
152733
+ return;
152734
+ }).find((p) => p !== undefined);
152735
+ }
152736
+ function pathGrainOf(grain, facts) {
152737
+ const [head, second, ...rest] = grain.split(".");
152738
+ const join = facts.joins.get(head);
152739
+ const joinField = facts.byName.get(head);
152740
+ if (!join || !joinField) {
152741
+ return {
152742
+ problem: `the grain names \`${grain}\`, which reads no join of the source; a truncation or a field of a record is named through a dimension on the source that reads it`
152743
+ };
152744
+ }
152745
+ const joinedFields = new Map((joinField.fields ?? []).map((f) => [fieldNameOf(f), f]));
152746
+ const joined = joinedFields.get(second);
152747
+ if (rest.length > 0) {
152748
+ return {
152749
+ problem: joined?.join !== undefined ? `the grain names \`${grain}\`, a path through more than one join; a grain reads one join, so declare a dimension on \`${head}\`'s source that reads the rest, and name \`${head}.<that dimension>\`` : `the grain names \`${grain}\`, a truncation through a join; declare the truncated dimension on \`${head}\`'s source, and name \`${head}.<that dimension>\``
152750
+ };
152751
+ }
152752
+ if (join.relationship === "cross") {
152753
+ return {
152754
+ problem: `the grain names \`${grain}\`, through \`${head}\`, a join_cross; a path grain reads a join_one or a join_many`
152755
+ };
152756
+ }
152757
+ if (!joined || !isDimension(joined)) {
152758
+ return {
152759
+ problem: `the grain names \`${grain}\`, but \`${second}\` is not a dimension of \`${head}\`'s source`
152760
+ };
152761
+ }
152762
+ if (isHidden(joinField) || isHidden(joined)) {
152763
+ return {
152764
+ problem: `the grain names \`${grain}\`, which is not public (${isHidden(joinField) ? `the join \`${head}\`` : `\`${second}\` on its source`} is not), so a rollup's build cannot read it`
152765
+ };
152766
+ }
152767
+ return {
152768
+ join: head,
152769
+ field: second,
152770
+ joined,
152771
+ relationship: join.relationship
152772
+ };
152773
+ }
152774
+ function pathColumnsOf(grain, facts) {
152775
+ const out = [];
152776
+ const add = (entry, column, join, joined) => {
152777
+ const field = fieldNameOf(joined);
152778
+ const timeframe = joined.timeframe;
152779
+ out.push({
152780
+ grain: entry,
152781
+ column,
152782
+ join,
152783
+ field,
152784
+ ...typeof timeframe === "string" ? { timeframe } : {},
152785
+ ...fieldNotes(joined).length > 0 ? { annotated: true } : {}
152786
+ });
152787
+ };
152788
+ for (const g of grain) {
152789
+ if (g.includes(".")) {
152790
+ const path = pathGrainOf(g, facts);
152791
+ if (!("problem" in path))
152792
+ add(g, grainColumnOf(g), path.join, path.joined);
152793
+ continue;
152794
+ }
152795
+ const read = exactPathRead(facts.byName.get(g)?.e);
152796
+ if (!read)
152797
+ continue;
152798
+ const path = pathGrainOf(read.join("."), facts);
152799
+ if ("problem" in path)
152800
+ continue;
152801
+ add(g, g, path.join, path.joined);
152802
+ }
152803
+ return out;
152804
+ }
152805
+ function pathReadsCurrentTime(g, facts) {
152806
+ const path = grainPathOf(g);
152807
+ if (!path || !facts.joins.has(path.join))
152808
+ return false;
152809
+ const joinField = facts.byName.get(path.join);
152810
+ return currentTimeFields(joinField?.fields).has(path.field);
152811
+ }
152812
+ function joinOneGrainOf(grain, facts) {
152813
+ const byJoin = new Map;
152814
+ const uncovered = new Set;
152815
+ const add = (join, entry) => {
152816
+ if (facts.joins.get(join)?.relationship !== "one")
152817
+ return;
152818
+ const entries = byJoin.get(join) ?? [];
152819
+ if (!entries.includes(entry))
152820
+ entries.push(entry);
152821
+ byJoin.set(join, entries);
152822
+ };
152823
+ for (const g of grain) {
152824
+ const path = grainPathOf(g);
152825
+ if (path) {
152826
+ add(path.join, g);
152827
+ const join = facts.joins.get(path.join);
152828
+ if (!join)
152829
+ continue;
152830
+ const field = joinedSourceReads(join).fieldJoins.get(path.field);
152831
+ if (field === undefined || field.joins.size > 0 || field.nested) {
152832
+ uncovered.add(path.join);
152833
+ }
152834
+ continue;
152835
+ }
152836
+ const usage = facts.joinUsage.get(g);
152837
+ for (const j of usage?.joins ?? [])
152838
+ add(j, g);
152839
+ const onlyOnes = [...usage?.joins ?? []].every((j) => facts.joins.get(j)?.relationship === "one");
152840
+ if (usage === undefined || usage.nested || !onlyOnes) {
152841
+ for (const j of usage?.joins ?? [])
152842
+ uncovered.add(j);
152843
+ }
152844
+ }
152845
+ for (const join of byJoin.keys()) {
152846
+ const condition = facts.joins.get(join)?.condition;
152847
+ const filter = filterJoinReads(facts.byName.get(join));
152848
+ if (condition === undefined || condition.joins.size > 0 || condition.nested || filter === undefined || filter.joins.size > 0 || filter.nested) {
152849
+ uncovered.add(join);
152850
+ }
152851
+ }
152852
+ if (byJoin.size === 0)
152853
+ return {};
152854
+ return {
152855
+ joinOneGrain: [...byJoin].sort(([a], [b]) => byCodepoint3(a, b)).map(([join, entries]) => ({
152856
+ join,
152857
+ grain: entries,
152858
+ ...uncovered.has(join) ? { uncovered: true } : {}
152859
+ }))
152860
+ };
152861
+ }
152862
+ function exactPathRead(e) {
152863
+ const n = e;
152864
+ if (n?.node !== "field" || !Array.isArray(n.path) || n.path.length !== 2 || !n.path.every((p) => typeof p === "string")) {
152865
+ return;
152866
+ }
152867
+ return n.path;
152868
+ }
152869
+ function unreadableStoredGrain(grain, fieldOf, dialect) {
152562
152870
  if (dialect !== STORAGE_DIALECT)
152563
152871
  return;
152564
152872
  for (const name of grain) {
152565
- const f = byName.get(name);
152873
+ const f = fieldOf(name);
152566
152874
  if (f?.type !== "sql native" || typeof f.rawType !== "string")
152567
152875
  continue;
152568
152876
  const storedType = f.rawType.toUpperCase();
@@ -152650,6 +152958,7 @@ function rollupPlanOf({ decl, measures }, node, facts, ctx) {
152650
152958
  inherited.set(`${at.range.start.line}:${at.range.start.character}`, at);
152651
152959
  }
152652
152960
  }
152961
+ const pathColumns = pathColumnsOf(decl.grain, facts);
152653
152962
  const liftedAncestors = [...inherited.values()].sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.character - b.range.start.character);
152654
152963
  return {
152655
152964
  variant: true,
@@ -152675,7 +152984,12 @@ function rollupPlanOf({ decl, measures }, node, facts, ctx) {
152675
152984
  ...liftedAncestors.length > 0 ? { liftedAncestors } : {},
152676
152985
  ..."terms" in facts.given && facts.given.terms.length > 0 ? { readTimeTerms: facts.given.terms } : {},
152677
152986
  ...(privateGrain.length > 0 || ("terms" in facts.given) && facts.given.terms.length > 0) && facts.declaration ? { declaration: facts.declaration } : {},
152987
+ ...pathColumns.length > 0 ? { pathColumns } : {},
152988
+ ...joinOneGrainOf(decl.grain, facts),
152678
152989
  fanOutDimensions: decl.grain.filter((g) => {
152990
+ const path = grainPathOf(g);
152991
+ if (path)
152992
+ return joins.get(path.join)?.relationship !== "one";
152679
152993
  const usage = joinUsage.get(g);
152680
152994
  if (usage === undefined)
152681
152995
  return joinUsage.has(g);
@@ -152846,8 +153160,9 @@ function storedDestinationsOf(map, struct) {
152846
153160
  }
152847
153161
  function rollupKeyCheckQuery(plan) {
152848
153162
  const [key, ...rest] = plan.grainDimensions;
152849
- if (key === undefined || rest.length > 0)
153163
+ if (key === undefined || rest.length > 0 || grainPathOf(key)) {
152850
153164
  return;
153165
+ }
152851
153166
  return `run: ${keyCheckPipeline("rollup_key", rollupBaseAlias(plan.baseDeclaredName), key)}`;
152852
153167
  }
152853
153168
  function parentKeyNeedsOf(map) {
@@ -152919,6 +153234,9 @@ function storedKeyChecksOf(plans, needs, primaryKeyOf, sourceIDs) {
152919
153234
  function parentKeyCheckQuery(name, keyColumn) {
152920
153235
  return `run: ${keyCheckPipeline("parent_key", name, keyColumn)}`;
152921
153236
  }
153237
+ function grainJoinKeyCheckQuery(name, keyColumn) {
153238
+ return `run: ${keyCheckPipeline("grain_join_key", name, keyColumn)}`;
153239
+ }
152922
153240
  function joinOneKey(sourceID, keyColumn) {
152923
153241
  return `${sourceID}\x00${keyColumn}`;
152924
153242
  }
@@ -152961,6 +153279,7 @@ var init_rollup_plan = __esm(() => {
152961
153279
  init_rollup_measure_grammar();
152962
153280
  init_table_plans();
152963
153281
  init_read_text();
153282
+ init_source_graph();
152964
153283
  V1_PREAGGREGATE_NOTE = /^\s*#@\s*-?preaggregate\b/;
152965
153284
  scopes = new WeakMap;
152966
153285
  LOCK_WORDS = new Set(["and", "in", "true", "false"]);
@@ -154111,7 +154430,7 @@ function materializedUpstream(sourceID, map) {
154111
154430
  }
154112
154431
  function storedElsewhereReason(upstreams) {
154113
154432
  const stored = upstreams.find((u) => u.storage !== undefined);
154114
- return stored ? `its upstream '${stored.name}' is stored in the storage= destination ` + `'${stored.storage}', whose table a build in the warehouse cannot ` + `read, and a downstream is never built by recomputing its upstream ` + `from raw; it is ` + `answered live, over '${stored.name}''s table` : undefined;
154433
+ return stored ? `its upstream '${stored.name}' is stored in the storage= destination ` + `'${stored.storage}', whose table a build in the warehouse cannot ` + `read, and a downstream is never built by recomputing its upstream ` + `from raw; it is answered live` : undefined;
154115
154434
  }
154116
154435
  function persistOverMaterializedReason(upstreams, destination) {
154117
154436
  const stored = upstreams.find((u) => u.materialize && u.storage === destination);
@@ -154124,7 +154443,7 @@ function placementReason(downstream, upstream) {
154124
154443
  if (downstream === undefined) {
154125
154444
  return storedElsewhereReason([upstream]);
154126
154445
  }
154127
- return `its upstream '${upstream.name}' is stored in the storage= destination ` + `'${upstream.storage}', and it is built into the storage= destination ` + `'${downstream}', which cannot read that table; a downstream is never ` + `built by recomputing its upstream from raw, so it is answered live, ` + `over '${upstream.name}''s table`;
154446
+ return `its upstream '${upstream.name}' is stored in the storage= destination ` + `'${upstream.storage}', and it is built into the storage= destination ` + `'${downstream}', which cannot read that table; a downstream is never ` + `built by recomputing its upstream from raw, so it is answered live`;
154128
154447
  }
154129
154448
  var UPSTREAM_TABLE_UNUSABLE_REASON = "upstream_table_unusable";
154130
154449
  var init_downstream_upstreams = __esm(() => {
@@ -156516,10 +156835,13 @@ function parseKeyUniqueness(raw) {
156516
156835
  const own = typeof k.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
156517
156836
  const parentKeys = recordOf(k.parentKeys, "boolean");
156518
156837
  const parentKeyColumns = recordOf(k.parentKeyColumns, "string");
156519
- if (!own && !parentKeys && !parentKeyColumns)
156838
+ const grainJoinKeys = recordOf(k.grainJoinKeys, "boolean");
156839
+ if (!own && !parentKeys && !parentKeyColumns && !grainJoinKeys) {
156520
156840
  return;
156841
+ }
156521
156842
  return {
156522
156843
  ...own ?? {},
156844
+ ...grainJoinKeys ? { grainJoinKeys } : {},
156523
156845
  ...parentKeys ? { parentKeys } : {},
156524
156846
  ...parentKeyColumns ? { parentKeyColumns } : {}
156525
156847
  };
@@ -156546,21 +156868,27 @@ function rollupKeyOf(entry) {
156546
156868
  const k = keyUniquenessOf(entry);
156547
156869
  return k?.keyColumn !== undefined && k.unique !== undefined ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
156548
156870
  }
156871
+ function grainJoinKeysOf(entry) {
156872
+ return keyUniquenessOf(entry)?.grainJoinKeys;
156873
+ }
156549
156874
  function withEntryKeyChecks(binding, entry) {
156550
156875
  const {
156551
156876
  primaryKeys: _was,
156552
156877
  primaryKeyColumns: _wasColumns,
156553
156878
  rollupKey: _wasKey,
156879
+ grainJoinKeys: _wasJoinKeys,
156554
156880
  ...rest
156555
156881
  } = binding;
156556
156882
  const primaryKeys = primaryKeysOf(entry);
156557
156883
  const primaryKeyColumns = primaryKeyColumnsOf(entry);
156558
156884
  const rollupKey = isRollupOrigin(entry.origin) ? rollupKeyOf(entry) : undefined;
156885
+ const grainJoinKeys = isRollupOrigin(entry.origin) ? grainJoinKeysOf(entry) : undefined;
156559
156886
  return {
156560
156887
  ...rest,
156561
156888
  ...primaryKeys ? { primaryKeys } : {},
156562
156889
  ...primaryKeyColumns ? { primaryKeyColumns } : {},
156563
- ...rollupKey ? { rollupKey } : {}
156890
+ ...rollupKey ? { rollupKey } : {},
156891
+ ...grainJoinKeys ? { grainJoinKeys } : {}
156564
156892
  };
156565
156893
  }
156566
156894
  function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, sourceIDsFor) {
@@ -156580,6 +156908,7 @@ function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, so
156580
156908
  const primaryKeys = primaryKeysOf(entry);
156581
156909
  const primaryKeyColumns = primaryKeyColumnsOf(entry);
156582
156910
  const rollupKey = isRollupOrigin(entry.origin) ? rollupKeyOf(entry) : undefined;
156911
+ const grainJoinKeys = isRollupOrigin(entry.origin) ? grainJoinKeysOf(entry) : undefined;
156583
156912
  for (const sourceName of names) {
156584
156913
  const sourceIDs = sourceIDsFor?.(sourceName, entry.sourceEntityId);
156585
156914
  bindings.push({
@@ -156596,7 +156925,8 @@ function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, so
156596
156925
  freshnessFallback: entry.freshnessFallback,
156597
156926
  ...primaryKeys ? { primaryKeys } : {},
156598
156927
  ...primaryKeyColumns ? { primaryKeyColumns } : {},
156599
- ...rollupKey ? { rollupKey } : {}
156928
+ ...rollupKey ? { rollupKey } : {},
156929
+ ...grainJoinKeys ? { grainJoinKeys } : {}
156600
156930
  });
156601
156931
  }
156602
156932
  }
@@ -158189,11 +158519,14 @@ class GeneratedFiles {
158189
158519
  static over(factory) {
158190
158520
  return new GeneratedFiles(factory);
158191
158521
  }
158192
- async loadModel(overlay = new Map) {
158522
+ async loadModel(overlay = new Map, options = {}) {
158193
158523
  const { runtime, importBaseURL, modelURL } = await this.runtimeFor(keyedOverlay(overlay));
158194
158524
  if (!modelURL)
158195
158525
  throw new Error("no package model to load");
158196
- const materializer = runtime.loadModel(modelURL, { importBaseURL });
158526
+ const materializer = runtime.loadModel(modelURL, {
158527
+ importBaseURL,
158528
+ ...options.virtualMap ? { virtualMap: options.virtualMap } : {}
158529
+ });
158197
158530
  return { runtime, importBaseURL, materializer };
158198
158531
  }
158199
158532
  runtime(overlay = new Map) {
@@ -158269,7 +158602,7 @@ var init_generated_files = __esm(() => {
158269
158602
  });
158270
158603
 
158271
158604
  // package.json
158272
- var version = "0.18.4";
158605
+ var version = "0.18.6";
158273
158606
  var init_package = () => {};
158274
158607
 
158275
158608
  // src/version.ts
@@ -158432,7 +158765,7 @@ var init_column_contract_capture = __esm(() => {
158432
158765
  });
158433
158766
 
158434
158767
  // src/service/annotation_near_miss.ts
158435
- import { isSourceDef as isSourceDef9 } from "@malloydata/malloy";
158768
+ import { isSourceDef as isSourceDef10 } from "@malloydata/malloy";
158436
158769
  function ownedRoutes() {
158437
158770
  return getMaterializeEnabled() ? OWNED_ROUTES : OWNED_V1_ROUTES;
158438
158771
  }
@@ -158581,7 +158914,7 @@ function authoredNotes(modelDef) {
158581
158914
  add(ownModelNoteObjects(modelDef));
158582
158915
  const structs = [];
158583
158916
  for (const [name, obj] of Object.entries(modelDef.contents)) {
158584
- if (isSourceDef9(obj)) {
158917
+ if (isSourceDef10(obj)) {
158585
158918
  structs.push({ name, struct: obj });
158586
158919
  } else if (obj.type === "query") {
158587
158920
  add(ownLevelNotes(obj.annotations), name);
@@ -158591,7 +158924,7 @@ function authoredNotes(modelDef) {
158591
158924
  const entry = value.entry;
158592
158925
  if (entry.type === "source_registry_reference")
158593
158926
  continue;
158594
- if (!isSourceDef9(entry))
158927
+ if (!isSourceDef10(entry))
158595
158928
  continue;
158596
158929
  const struct = entry;
158597
158930
  structs.push({ name: struct.as ?? struct.name, struct });
@@ -161881,6 +162214,61 @@ async function compileParentKeyChecks(plans, needs, joinedKeys = []) {
161881
162214
  delete plan.parentKeyChecks;
161882
162215
  }
161883
162216
  }
162217
+ async function compileGrainJoinKeyChecks(plans, joinsOf, sourceOf, stored) {
162218
+ const compiled = new Map;
162219
+ for (const plan of plans) {
162220
+ if (plan.variant !== true)
162221
+ continue;
162222
+ const checks = [];
162223
+ for (const { join, uncovered } of plan.joinOneGrain ?? []) {
162224
+ if (uncovered) {
162225
+ logger.info("A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", {
162226
+ rollup: plan.rollupSourceName,
162227
+ join,
162228
+ reason: "the build joins past it, through another join"
162229
+ });
162230
+ continue;
162231
+ }
162232
+ const j = joinsOf(plan.baseSourceID).find((x) => x.name === join && x.relationship === "one");
162233
+ const source = j?.sourceID ? sourceOf(j.sourceID) : undefined;
162234
+ const why = j?.sourceID === undefined || j.keyColumn === undefined ? "its join is not keyed on one column of a declared source" : source === undefined ? "no model names the joined source" : [...source.reads()].some((id) => stored.has(id)) ? "the joined source reads a table the run stores" : undefined;
162235
+ if (why !== undefined || !j?.sourceID || !j.keyColumn || !source) {
162236
+ logger.info("A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", { rollup: plan.rollupSourceName, join, reason: why });
162237
+ continue;
162238
+ }
162239
+ const { sourceID, keyColumn } = j;
162240
+ const key = `${sourceID}\x00${keyColumn}`;
162241
+ let sql = compiled.get(key);
162242
+ if (sql === undefined) {
162243
+ sql = source.compile(grainJoinKeyCheckQuery(source.name, keyColumn)).catch((error) => {
162244
+ logger.warn("A #(rollup) rollup's grain join key check did not compile; queries that read nothing through the join are answered live", {
162245
+ rollup: plan.rollupSourceName,
162246
+ join,
162247
+ source: source.name,
162248
+ keyColumn,
162249
+ code: errorCodeOf(error)
162250
+ });
162251
+ return;
162252
+ });
162253
+ compiled.set(key, sql);
162254
+ }
162255
+ const text = await sql;
162256
+ if (text === undefined)
162257
+ continue;
162258
+ checks.push({
162259
+ join,
162260
+ sourceID,
162261
+ keyColumn,
162262
+ connectionName: source.connectionName,
162263
+ sql: text
162264
+ });
162265
+ }
162266
+ if (checks.length > 0)
162267
+ plan.grainJoinKeyChecks = checks;
162268
+ else
162269
+ delete plan.grainJoinKeyChecks;
162270
+ }
162271
+ }
161884
162272
  async function compileRollupKeyChecks(plans, materializer, modelPath) {
161885
162273
  for (const plan of plans) {
161886
162274
  const text = rollupKeyCheckQuery(plan);
@@ -162048,6 +162436,28 @@ var init_access_closure = __esm(() => {
162048
162436
  ]);
162049
162437
  });
162050
162438
 
162439
+ // src/service/materialization/domain/target_containers.ts
162440
+ function targetContainerKey(target) {
162441
+ return JSON.stringify([target.connectionName, target.container]);
162442
+ }
162443
+ function containerOfTableName(name) {
162444
+ const dot = name.lastIndexOf(".");
162445
+ return dot > 0 ? name.slice(0, dot) : undefined;
162446
+ }
162447
+ function missingContainerReason(target, dialect, reading) {
162448
+ const kind = capabilitiesOf(dialect).containerCatalog === "dataset" ? "dataset" : "schema";
162449
+ const where = `its name= places its table in ${kind} "${target.container}"`;
162450
+ if ("otherLocation" in reading) {
162451
+ const { location, expected } = reading.otherLocation;
162452
+ return `${where}, which is in location "${location}", but connection ` + `"${target.connectionName}" runs its queries in "${expected}"; ` + `create the ${kind} in "${expected}", or change name= to a ${kind} ` + `there`;
162453
+ }
162454
+ const project = reading.project ? ` (project "${reading.project}")` : "";
162455
+ return `${where}${project}, which connection "${target.connectionName}" does ` + `not hold, and no build creates one; create the ${kind}, or change ` + `name= to one that exists`;
162456
+ }
162457
+ var init_target_containers = __esm(() => {
162458
+ init_dialect();
162459
+ });
162460
+
162051
162461
  // src/service/materialization/domain/package_plan.ts
162052
162462
  function countRefusal(counts, reason) {
162053
162463
  counts[reason] = (counts[reason] ?? 0) + 1;
@@ -162060,7 +162470,7 @@ function noModelGateLines() {
162060
162470
  import { Manifest as Manifest2 } from "@malloydata/malloy";
162061
162471
  import * as path22 from "path";
162062
162472
  import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL11 } from "url";
162063
- import { Annotations as Annotations10, isSourceDef as isSourceDef10 } from "@malloydata/malloy";
162473
+ import { Annotations as Annotations10, isSourceDef as isSourceDef11 } from "@malloydata/malloy";
162064
162474
  function wireTerm(term) {
162065
162475
  return { code: term.code, givens: term.givens };
162066
162476
  }
@@ -162169,7 +162579,7 @@ function declaredPersistSourceIDs(malloyModel) {
162169
162579
  const ids = [];
162170
162580
  try {
162171
162581
  for (const def of Object.values(modelDefOf(malloyModel)?.contents ?? {})) {
162172
- if (!isSourceDef10(def) || !def.annotations)
162582
+ if (!isSourceDef11(def) || !def.annotations)
162173
162583
  continue;
162174
162584
  try {
162175
162585
  if (declares(new Annotations10(def.annotations), "@", "persist")) {
@@ -162185,7 +162595,7 @@ function sourceIDsWithNoteAt(malloyModel, at) {
162185
162595
  const ids = [];
162186
162596
  try {
162187
162597
  for (const def of Object.values(modelDefOf(malloyModel)?.contents ?? {})) {
162188
- if (!isSourceDef10(def) || !def.annotations || !def.sourceID)
162598
+ if (!isSourceDef11(def) || !def.annotations || !def.sourceID)
162189
162599
  continue;
162190
162600
  try {
162191
162601
  const notes = new Annotations10(def.annotations).forRoute("@");
@@ -162412,7 +162822,7 @@ function pairParentUnusable(plan, boundContract) {
162412
162822
  return `it extends '${over.sourceName}', whose pair table it is built over ` + `with its join put back, and the leaf key check of its inlined ` + `join_many, which that build relies on, ${what} when the table was ` + `built; it builds once the parent's table records the check passed`;
162413
162823
  }
162414
162824
  async function authorSourceGate(sourceID, authorDef, args) {
162415
- const authorSource = Object.values(authorDef.contents ?? {}).find((object) => isSourceDef10(object) && object.sourceID === sourceID);
162825
+ const authorSource = Object.values(authorDef.contents ?? {}).find((object) => isSourceDef11(object) && object.sourceID === sourceID);
162416
162826
  return authorSource ? await classifyPersistSourceGate({ _sourceDef: authorSource, sourceID }, authorDef, args.materializer, args.deps, args.modelPath) : { classification: "rejected", attributed: false };
162417
162827
  }
162418
162828
  async function collectGeneratedRollups(parts, args) {
@@ -162577,18 +162987,19 @@ function inDestinationStringReads(args, stored, planned, upstreams) {
162577
162987
  const run = planned.kind === "query" ? `run: ${quotedIdentifier(planned.queryName)}` : `run: ${quotedIdentifier(planned.sourceName)} -> ${quotedIdentifier(planned.viewName)}`;
162578
162988
  return planStringReads(args.stringReads, args.materializer, { run, stored: stored.upstreams.map((u) => u.sourceID) }, planned.storage, upstreams);
162579
162989
  }
162580
- async function chainedStringReads(source, modelDef, materializer, ports, judged) {
162990
+ async function chainedStringReads(source, modelDef, materializer, ports, judged, planned) {
162581
162991
  const destination = declaredStorage(source)?.trim();
162582
162992
  if (!destination)
162583
162993
  return;
162584
162994
  const map = SourceMap.of(modelDef);
162585
162995
  const def = map.node(source.sourceID)?.def;
162586
- if (def?.type !== "query_source" || typeof def.extends === "string") {
162996
+ if (def?.type !== "query_source")
162587
162997
  return;
162588
- }
162589
162998
  const stored = reachedUpstreams(def, modelDef, map).filter((u) => u.storage === destination && u.sourceID !== source.sourceID).map((u) => u.sourceID);
162590
162999
  if (stored.length === 0)
162591
163000
  return;
163001
+ if (sharesStoredBuild(source, stored, planned))
163002
+ return;
162592
163003
  const reads = await planStringReads(ports, materializer, { downstream: source.name, stored }, destination, { modelDef, judged });
162593
163004
  if (!("refused" in reads) || !reads.unstored)
162594
163005
  return reads;
@@ -162599,6 +163010,19 @@ async function chainedStringReads(source, modelDef, materializer, ports, judged)
162599
163010
  unstored: true
162600
163011
  } : reads;
162601
163012
  }
163013
+ function sharesStoredBuild(source, stored, planned) {
163014
+ const keyOf = (s) => {
163015
+ if (!s)
163016
+ return;
163017
+ try {
163018
+ return compilerBuildId(s);
163019
+ } catch {
163020
+ return;
163021
+ }
163022
+ };
163023
+ const own = keyOf(source);
163024
+ return own !== undefined && stored.some((id) => keyOf(planned.get(id)) === own);
163025
+ }
162602
163026
  async function collectGeneratedPersistedViews(parts, args) {
162603
163027
  const authorDef = modelDefOf(args.malloyModel);
162604
163028
  const { generated, refused, refusedQueries, omitted, failure } = await tryCompilePersistedViewCompanion({
@@ -162688,7 +163112,7 @@ async function collectGeneratedPersistedViews(parts, args) {
162688
163112
  parts.builds.push(...sourceBuildsOf(targets));
162689
163113
  }
162690
163114
  async function persistedQueryGate(source, query, ctx) {
162691
- const runTarget = query.sourceID !== undefined ? Object.values(ctx.authorDef.contents ?? {}).find((object) => isSourceDef10(object) && object.sourceID === query.sourceID) : inlineRunTarget(ctx.authorDef, query.queryName);
163115
+ const runTarget = query.sourceID !== undefined ? Object.values(ctx.authorDef.contents ?? {}).find((object) => isSourceDef11(object) && object.sourceID === query.sourceID) : inlineRunTarget(ctx.authorDef, query.queryName);
162692
163116
  return runTarget ? await classifyPersistSourceGate({
162693
163117
  _sourceDef: runTarget,
162694
163118
  sourceID: query.sourceID ?? source.sourceID
@@ -162753,7 +163177,7 @@ function queryStorage(query) {
162753
163177
  function inlineRunTarget(modelDef, name) {
162754
163178
  const query = (modelDef.contents ?? {})[name];
162755
163179
  const ref = query?.type === "query" ? query.structRef : undefined;
162756
- return ref && typeof ref === "object" && isSourceDef10(ref) ? ref : undefined;
163180
+ return ref && typeof ref === "object" && isSourceDef11(ref) ? ref : undefined;
162757
163181
  }
162758
163182
  function addAccessReads(parts, malloyModel) {
162759
163183
  const reads = new Set(parts.accessReads);
@@ -162945,6 +163369,7 @@ function reportPersistLineFindings(parts, targets, planned, args) {
162945
163369
  async function planV1PersistSources(parts, planned, args) {
162946
163370
  const { modelPath, packagePath, materializer, malloyModel } = args;
162947
163371
  let classificationCtx;
163372
+ const plannedByID = new Map(planned.map((s) => [s.sourceID, s]));
162948
163373
  for (const source of planned) {
162949
163374
  const sourceID = source.sourceID;
162950
163375
  try {
@@ -162974,7 +163399,7 @@ async function planV1PersistSources(parts, planned, args) {
162974
163399
  modelDef: modelDefOf(malloyModel),
162975
163400
  deps: gateDepsFor(malloyModel, modelPath)
162976
163401
  };
162977
- const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads, parts.stringCapabilityReads) : parts.tables[sourceID]?.stringReads;
163402
+ const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads, parts.stringCapabilityReads, plannedByID) : parts.tables[sourceID]?.stringReads;
162978
163403
  const destination = declaredStorage(source)?.trim();
162979
163404
  const map = SourceMap.of(classificationCtx.modelDef);
162980
163405
  const query = map.node(sourceID)?.def?.query;
@@ -163151,7 +163576,7 @@ function finishBuildPlan(parts, ctx) {
163151
163576
  addresses: planAddresses({ ...plan, tableFolds })
163152
163577
  };
163153
163578
  const refused = refuseCollidingMaterialize(refuseRewrittenNames(full));
163154
- const known = refuseUpstreamUnread(refused);
163579
+ const known = refuseMissingContainers(refuseUpstreamUnread(refused), ctx.targetContainers);
163155
163580
  return refuseOverMissingUpstreams(refuseUncomparableStrings(refuseAcrossPlacements(ctx.keepIncrementalUnbuildable ? known : refuseIncrementalUnbuildable(known))), full);
163156
163581
  }
163157
163582
  function refuseAcrossPlacements(compiled) {
@@ -163271,21 +163696,45 @@ function refuseOverMissingUpstreams(compiled, full = compiled) {
163271
163696
  return dropped.size === 0 ? compiled : withoutSources(compiled, findings, dropped);
163272
163697
  }
163273
163698
  async function finishPackagePlan(parts, ctx) {
163274
- const { getMalloyConnection, readUpstreamSchemas, ...finish } = ctx;
163699
+ const {
163700
+ getMalloyConnection,
163701
+ readUpstreamSchemas,
163702
+ readTargetContainers,
163703
+ ...finish
163704
+ } = ctx;
163275
163705
  const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
163276
163706
  const digestSkipped = [];
163277
163707
  const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
163278
163708
  const upstreamSchemas = readUpstreamSchemas ? await readUpstreamSchemas(planUpstreamTables(parts.tables)) : undefined;
163709
+ const containers = planTargetContainers(parts.tables);
163710
+ const targetContainers = readTargetContainers && containers.length > 0 ? await readTargetContainers(containers) : undefined;
163279
163711
  return {
163280
163712
  compiled: finishBuildPlan(parts, {
163281
163713
  ...finish,
163282
163714
  connectionDigests,
163283
163715
  ...upstreamSchemas ? { upstreamSchemas } : {},
163716
+ ...targetContainers ? { targetContainers } : {},
163284
163717
  connections
163285
163718
  }),
163286
163719
  digestSkipped
163287
163720
  };
163288
163721
  }
163722
+ function targetContainerOf(source) {
163723
+ if (declaredStorage(source) !== undefined)
163724
+ return;
163725
+ const name = deriveAnnotationFields(source).name;
163726
+ const container = name ? containerOfTableName(name) : undefined;
163727
+ return container ? { connectionName: source.connectionName, container } : undefined;
163728
+ }
163729
+ function planTargetContainers(tables) {
163730
+ const out = new Map;
163731
+ for (const { source } of Object.values(tables)) {
163732
+ const target = targetContainerOf(source);
163733
+ if (target)
163734
+ out.set(targetContainerKey(target), target);
163735
+ }
163736
+ return [...out.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, t]) => t);
163737
+ }
163289
163738
  function planUpstreamTables(tables) {
163290
163739
  const out = new Map;
163291
163740
  for (const { source } of Object.values(tables)) {
@@ -163452,6 +163901,26 @@ function refuseUpstreamUnread(compiled) {
163452
163901
  }
163453
163902
  return withoutSources(compiled, findings, dropped);
163454
163903
  }
163904
+ function refuseMissingContainers(compiled, readings) {
163905
+ if (!readings)
163906
+ return compiled;
163907
+ const shared = sharedTables(compiled);
163908
+ const findings = [];
163909
+ const dropped = new Set;
163910
+ for (const [sourceID, { source }] of Object.entries(compiled.tables)) {
163911
+ if (shared.has(sourceID))
163912
+ continue;
163913
+ const target = targetContainerOf(source);
163914
+ if (!target)
163915
+ continue;
163916
+ const reading = readings[targetContainerKey(target)];
163917
+ if (!reading || "found" in reading || "unread" in reading)
163918
+ continue;
163919
+ dropped.add(sourceID);
163920
+ findings.push(notBuiltFinding(compiled, sourceID, "container_not_found", missingContainerReason(target, source.dialectName, reading)));
163921
+ }
163922
+ return withoutSources(compiled, findings, dropped);
163923
+ }
163455
163924
  function notBuiltFinding(compiled, sourceID, reason, why) {
163456
163925
  const table = compiled.tables[sourceID];
163457
163926
  const source = table.source;
@@ -163656,6 +164125,7 @@ var init_build_plan = __esm(() => {
163656
164125
  init_persist_source_fields();
163657
164126
  init_quoting();
163658
164127
  init_addressing();
164128
+ init_target_containers();
163659
164129
  init_eligibility_collect();
163660
164130
  init_plan_layers();
163661
164131
  init_addressing();
@@ -164098,7 +164568,7 @@ var init_gate_registry_walk = __esm(() => {
164098
164568
  // src/service/source_extraction.ts
164099
164569
  import {
164100
164570
  isJoined as isJoined5,
164101
- isSourceDef as isSourceDef11
164571
+ isSourceDef as isSourceDef12
164102
164572
  } from "@malloydata/malloy";
164103
164573
  function joinFieldNamesUnresolvableDeclaration(field, modelDef) {
164104
164574
  const ids = [field.referenceID, field.sourceID].filter((id) => !!id);
@@ -164109,7 +164579,7 @@ function joinFieldNamesUnresolvableDeclaration(field, modelDef) {
164109
164579
  if (!entry)
164110
164580
  continue;
164111
164581
  const declared = entry.type === "source_registry_reference" ? modelDef.contents[entry.name] : entry;
164112
- if (declared && isSourceDef11(declared))
164582
+ if (declared && isSourceDef12(declared))
164113
164583
  return false;
164114
164584
  }
164115
164585
  return true;
@@ -164127,7 +164597,7 @@ function considerNoteOwner(declaredBy, note, candidate) {
164127
164597
  }
164128
164598
  }
164129
164599
  function collectSourceInfos(modelDef) {
164130
- const names = Object.keys(modelDef.contents).filter((name) => isSourceDef11(modelDef.contents[name]));
164600
+ const names = Object.keys(modelDef.contents).filter((name) => isSourceDef12(modelDef.contents[name]));
164131
164601
  const exports = [...new Set([...modelDef.exports, ...names])];
164132
164602
  return modelInfoOf({ ...modelDef, exports }).entries.filter((entry) => entry.kind === "source");
164133
164603
  }
@@ -164143,7 +164613,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
164143
164613
  const nearMissAuthorize = [];
164144
164614
  const sweptStructs = [];
164145
164615
  for (const obj of Object.values(modelDef.contents)) {
164146
- if (!isSourceDef11(obj))
164616
+ if (!isSourceDef12(obj))
164147
164617
  continue;
164148
164618
  const struct = obj;
164149
164619
  sweptStructs.push(obj);
@@ -164163,7 +164633,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
164163
164633
  const entry = value.entry;
164164
164634
  if (entry.type === "source_registry_reference")
164165
164635
  continue;
164166
- if (!isSourceDef11(entry))
164636
+ if (!isSourceDef12(entry))
164167
164637
  continue;
164168
164638
  sweptStructs.push(entry);
164169
164639
  for (const note of ownLevelNotes(entry.annotations)) {
@@ -164205,7 +164675,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
164205
164675
  });
164206
164676
  }
164207
164677
  }
164208
- const sources = Object.values(modelDef.contents).filter((obj) => isSourceDef11(obj)).map((sourceObj) => {
164678
+ const sources = Object.values(modelDef.contents).filter((obj) => isSourceDef12(obj)).map((sourceObj) => {
164209
164679
  const struct = sourceObj;
164210
164680
  const sourceName = struct.as || struct.name;
164211
164681
  const annotations = annotationTexts(struct.annotations);
@@ -164274,7 +164744,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
164274
164744
  continue;
164275
164745
  }
164276
164746
  const fieldName = field.as || field.name;
164277
- if (isJoined5(field) && isSourceDef11(field)) {
164747
+ if (isJoined5(field) && isSourceDef12(field)) {
164278
164748
  const joinedStruct = field;
164279
164749
  if (joinFieldNamesUnresolvableDeclaration(joinedStruct, modelDef)) {
164280
164750
  continue;
@@ -164339,54 +164809,6 @@ var init_source_extraction = __esm(() => {
164339
164809
  });
164340
164810
 
164341
164811
  // src/service/sql_embed_gates.ts
164342
- import { isSourceDef as isSourceDef12 } from "@malloydata/malloy";
164343
- function sqlSelectsWithin(root) {
164344
- const found = [];
164345
- const seen = new Set;
164346
- const stack = [root];
164347
- while (stack.length > 0) {
164348
- const node = stack.pop();
164349
- if (Array.isArray(node)) {
164350
- stack.push(...node);
164351
- continue;
164352
- }
164353
- if (!isObj2(node) || seen.has(node))
164354
- continue;
164355
- seen.add(node);
164356
- if (node.type === "sql_select" && Array.isArray(node.selectSegments)) {
164357
- found.push(node);
164358
- }
164359
- stack.push(...Object.values(node));
164360
- }
164361
- return found;
164362
- }
164363
- function embeddedStructs(segment, modelDef) {
164364
- if (segment.type === "query") {
164365
- const ref = segment.structRef;
164366
- let base = ref;
164367
- if (typeof ref === "string")
164368
- base = modelDef.contents[ref];
164369
- if (!isObj2(base) || !isSourceDef12(base)) {
164370
- return {
164371
- unreadable: "its source reference does not resolve in the model",
164372
- label: typeof ref === "string" ? ref : "<embedded query>"
164373
- };
164374
- }
164375
- const structs = [base];
164376
- const resolved = segment.compositeResolvedSourceDef;
164377
- if (isObj2(resolved) && isSourceDef12(resolved)) {
164378
- structs.push(resolved);
164379
- }
164380
- return { structs };
164381
- }
164382
- if (isSourceDef12(segment)) {
164383
- return { structs: [segment] };
164384
- }
164385
- return {
164386
- unreadable: `its segment shape (type ${JSON.stringify(segment.type)}) is not one Publisher reads`,
164387
- label: labelOf(segment)
164388
- };
164389
- }
164390
164812
  function runLabel(query, index, cell) {
164391
164813
  const line = isObj2(query) ? query.location?.range?.start?.line : undefined;
164392
164814
  const at = typeof line === "number" ? `line ${line + 1}` : `#${index + 1}`;
@@ -164502,13 +164924,8 @@ function assertNoSqlEmbedsOfGatedSources(modelDef, scope = {}) {
164502
164924
  ` + `Malloy compiles the embedded read into the SQL text, where no ` + `#(authorize) or #(access_filter) gate can be enforced, so every ` + `caller would read the gated rows. Query the gated source through ` + `Malloy instead (derive from it with \`->\`, or extend it), so its ` + `gate applies, or remove the gate if the source is meant to be open.`
164503
164925
  });
164504
164926
  }
164505
- var isObj2 = (value) => typeof value === "object" && value !== null, INLINE_SQL = "<inline sql()>", labelOf = (struct) => {
164506
- const label = struct.as ?? struct.name;
164507
- if (typeof label !== "string")
164508
- return "<unnamed>";
164509
- return label.startsWith("sql://") ? INLINE_SQL : label;
164510
- };
164511
164927
  var init_sql_embed_gates = __esm(() => {
164928
+ init_sql_embeds();
164512
164929
  init_errors2();
164513
164930
  init_gate_plan();
164514
164931
  });
@@ -164809,11 +165226,15 @@ function emptyKeyCheckInputs() {
164809
165226
  parentKeyNeeds: [],
164810
165227
  joinedKeyNeeds: [],
164811
165228
  primaryKeys: new Map,
165229
+ joins: new Map,
165230
+ namedSources: new Map,
164812
165231
  keyCheckCompilers: new Map
164813
165232
  };
164814
165233
  }
164815
165234
  function addKeyCheckInputs(into, malloyModel, materializer) {
164816
- const map = SourceMap.of(modelDefOf(malloyModel));
165235
+ const modelDef = modelDefOf(malloyModel);
165236
+ const map = SourceMap.of(modelDef);
165237
+ const compile = parentKeyCheckCompiler(materializer);
164817
165238
  for (const key of joinOneKeysOf(map))
164818
165239
  into.joinOneKeys.add(key);
164819
165240
  for (const node of map.nodes()) {
@@ -164821,17 +165242,29 @@ function addKeyCheckInputs(into, malloyModel, materializer) {
164821
165242
  if (key !== undefined && !into.primaryKeys.has(node.sourceID)) {
164822
165243
  into.primaryKeys.set(node.sourceID, key);
164823
165244
  }
165245
+ if (!into.joins.has(node.sourceID)) {
165246
+ into.joins.set(node.sourceID, map.joinsOf(node.sourceID));
165247
+ }
165248
+ if (node.name !== undefined && !into.namedSources.has(node.sourceID)) {
165249
+ const connection = node.def.connection;
165250
+ into.namedSources.set(node.sourceID, {
165251
+ name: node.name,
165252
+ connectionName: typeof connection === "string" ? connection : undefined,
165253
+ reads: () => reachableSourceIDs([node.def], modelDef),
165254
+ compile
165255
+ });
165256
+ }
164824
165257
  }
164825
165258
  for (const need of parentKeyNeedsOf(map)) {
164826
165259
  into.parentKeyNeeds.push({
164827
165260
  need,
164828
- compile: parentKeyCheckCompiler(materializer)
165261
+ compile
164829
165262
  });
164830
165263
  }
164831
165264
  for (const need of joinedKeyNeedsOf(map)) {
164832
165265
  into.joinedKeyNeeds.push({
164833
165266
  need,
164834
- compile: parentKeyCheckCompiler(materializer)
165267
+ compile
164835
165268
  });
164836
165269
  }
164837
165270
  }
@@ -164843,6 +165276,7 @@ async function compileRunKeyChecks(parts, inputs) {
164843
165276
  }
164844
165277
  }
164845
165278
  await compileParentKeyChecks(rollupPlans, inputs.parentKeyNeeds, inputs.joinedKeyNeeds);
165279
+ await compileGrainJoinKeyChecks(rollupPlans, (sourceID) => inputs.joins.get(sourceID) ?? [], (sourceID) => inputs.namedSources.get(sourceID), new Set(Object.keys(parts.tables).filter((sourceID) => !parts.tables[sourceID].rollup)));
164846
165280
  const storedKeyChecks = storedKeyChecksOf(rollupPlans, inputs.parentKeyNeeds.map(({ need }) => need), (sourceID) => inputs.primaryKeys.get(sourceID), Object.keys(parts.tables).filter((sourceID) => !parts.tables[sourceID].rollup));
164847
165281
  for (const [sourceID, keyColumn] of Object.entries(storedKeyChecks)) {
164848
165282
  parts.tables[sourceID].storedKeyCheck = keyColumn;
@@ -164888,7 +165322,11 @@ async function collectPackageParts(pkg, signal, keyChecks) {
164888
165322
  }
164889
165323
  function upstreamReaderOf(pkg, use) {
164890
165324
  const read = pkg.readUpstreamSchemas?.bind(pkg);
164891
- return read ? { readUpstreamSchemas: (tables) => read(tables, use) } : {};
165325
+ const containers = pkg.readTargetContainers?.bind(pkg);
165326
+ return {
165327
+ ...read ? { readUpstreamSchemas: (tables) => read(tables, use) } : {},
165328
+ ...containers ? { readTargetContainers: containers } : {}
165329
+ };
164892
165330
  }
164893
165331
  async function compilePackageBuildPlan(pkg, signal, {
164894
165332
  keepIncrementalUnbuildable = false
@@ -165664,6 +166102,110 @@ var init_passthrough_build = __esm(() => {
165664
166102
  });
165665
166103
  });
165666
166104
 
166105
+ // src/service/same_catalog_tables.ts
166106
+ function fileInScope(file, prefixes) {
166107
+ if (/[%\\\0]/.test(file))
166108
+ return false;
166109
+ const at = file.indexOf("://");
166110
+ const rest = at >= 0 ? file.slice(at + 3) : file;
166111
+ if (rest.split("/").some((part) => part === "." || part === "..")) {
166112
+ return false;
166113
+ }
166114
+ return prefixes.some((prefix) => prefix.endsWith("/") && file.startsWith(prefix));
166115
+ }
166116
+ async function fileOutsideScope(run, catalog, snapshot, tables, prefixes) {
166117
+ if (!/^\d+$/.test(snapshot))
166118
+ throw new Error("not a snapshot id");
166119
+ for (const [schema, table] of tables) {
166120
+ const files = await run(`SELECT data_file, delete_file FROM ducklake_list_files(${literal(catalog)}, ${literal(table)}, ` + `schema => ${literal(schema)}, snapshot_version => ${snapshot})`);
166121
+ for (const row of files) {
166122
+ for (const file of [row.data_file, row.delete_file]) {
166123
+ if (file === null || file === undefined)
166124
+ continue;
166125
+ if (typeof file !== "string" || !fileInScope(file, prefixes)) {
166126
+ return `the table '${schema}.${table}' holds a file outside the connection's storage scope`;
166127
+ }
166128
+ }
166129
+ }
166130
+ }
166131
+ return;
166132
+ }
166133
+ function scopeIdentity(config, prefixes) {
166134
+ const ducklake = config?.ducklakeConnection;
166135
+ return JSON.stringify([
166136
+ ducklake?.storage?.bucketUrl ?? null,
166137
+ ducklake?.catalog?.metadataSchema ?? null,
166138
+ [...prefixes].sort()
166139
+ ]);
166140
+ }
166141
+ async function sameCatalogTablesReadable(config, read) {
166142
+ if (read.tables.length === 0)
166143
+ return true;
166144
+ const [destination, managed] = await Promise.all([
166145
+ config.connections.lookupConnection(read.alias),
166146
+ config.connections.lookupConnection(read.connection)
166147
+ ]);
166148
+ const prefixes = managedScopeOf(managed, read.connection);
166149
+ if (!prefixes)
166150
+ return false;
166151
+ const run = async (sql) => (await runInternalSQL(destination, sql)).rows;
166152
+ const scopeKey = scopeIdentity(connectionConfigOf(managed), prefixes);
166153
+ const key = (schema, table) => `${scopeKey}\x00${schema.toLowerCase()}.${table.toLowerCase()}`;
166154
+ const byCatalog = new Map;
166155
+ for (const t of read.tables) {
166156
+ byCatalog.set(t[0], [...byCatalog.get(t[0]) ?? [], t]);
166157
+ }
166158
+ let known = verdicts.get(destination);
166159
+ if (!known) {
166160
+ known = new Map;
166161
+ verdicts.set(destination, known);
166162
+ }
166163
+ for (const [catalog, wanted] of byCatalog) {
166164
+ const held = known.get(catalog);
166165
+ if (held && wanted.every(([, s, t]) => held.readable.has(key(s, t)))) {
166166
+ const [row] = await run(`SELECT id FROM ${ident(catalog)}.current_snapshot()`);
166167
+ if (row && String(row.id) === held.snapshot) {
166168
+ if (wanted.some(([, s, t]) => !held.readable.get(key(s, t)))) {
166169
+ return false;
166170
+ }
166171
+ continue;
166172
+ }
166173
+ }
166174
+ const matches = wanted.map(([, s, t]) => `(lower(t.table_schema) = lower(${literal(s)}) AND lower(t.table_name) = lower(${literal(t)}))`).join(" OR ");
166175
+ const rows = await run("SELECT s.id AS snapshot_id, t.table_schema, t.table_name, t.table_type " + `FROM ${ident(catalog)}.current_snapshot() s ` + "LEFT JOIN information_schema.tables t " + `ON t.table_catalog = ${literal(catalog)} AND (${matches})`);
166176
+ if (rows.length === 0)
166177
+ return false;
166178
+ const snapshot = String(rows[0].snapshot_id);
166179
+ const types = new Map;
166180
+ for (const r of rows) {
166181
+ if (r.table_name == null)
166182
+ continue;
166183
+ const k = key(String(r.table_schema), String(r.table_name));
166184
+ types.set(k, [...types.get(k) ?? [], r.table_type]);
166185
+ }
166186
+ const base = wanted.filter(([, s, t]) => {
166187
+ const found = types.get(key(s, t)) ?? [];
166188
+ return found.length === 1 && found[0] === "BASE TABLE";
166189
+ });
166190
+ const outside = base.length === wanted.length ? await fileOutsideScope(run, catalog, snapshot, base.map(([, s, t]) => [s, t]), prefixes) : "not a base table";
166191
+ const ok = outside === undefined;
166192
+ const readable = new Map(held?.snapshot === snapshot ? held.readable : []);
166193
+ for (const [, s, t] of wanted)
166194
+ readable.set(key(s, t), ok);
166195
+ known.set(catalog, { snapshot, readable });
166196
+ if (!ok)
166197
+ return false;
166198
+ }
166199
+ return true;
166200
+ }
166201
+ var literal = (value) => `'${value.replace(/'/g, "''")}'`, ident = (value) => `"${value.replace(/"/g, '""')}"`, verdicts;
166202
+ var init_same_catalog_tables = __esm(() => {
166203
+ init_connection_type();
166204
+ init_ducklake_catalog();
166205
+ init_duckdb_lockdown();
166206
+ verdicts = new WeakMap;
166207
+ });
166208
+
165667
166209
  // src/service/materialization/run/materialization_build_session.ts
165668
166210
  import { DuckDBConnection as DuckDBConnection5 } from "@malloydata/db-duckdb";
165669
166211
  import {
@@ -165868,8 +166410,7 @@ async function applyLoadSessionSettings(session) {
165868
166410
  `memory_limit='${escapeSQL(memoryLimit)}'`,
165869
166411
  `max_temp_directory_size='${escapeSQL(settings.get("admin.maxTempDirectorySize"))}'`,
165870
166412
  "preserve_insertion_order=false",
165871
- "enable_http_metadata_cache=true",
165872
- "parquet_metadata_cache=true"
166413
+ "enable_http_metadata_cache=true"
165873
166414
  ]) {
165874
166415
  await session.runSQL(`SET ${setting}`);
165875
166416
  }
@@ -166036,7 +166577,15 @@ async function buildSameCatalogIntoStorage(params) {
166036
166577
  const captured = {};
166037
166578
  const schema = await createTableWithDeclaredTypes(session, target, params.buildSQL, { columns: params.declaredColumns ?? [], ...params.castOptions }, {
166038
166579
  captured,
166039
- ...params.replacesView ? { replacesView: params.replacesView } : {}
166580
+ ...params.replacesView ? { replacesView: params.replacesView } : {},
166581
+ ...params.sourceConnection.managed === true ? {
166582
+ beforeCreate: () => refuseOutOfScopeReads(session, params.buildSQL, {
166583
+ alias,
166584
+ destinationName,
166585
+ sourceConnection: params.sourceConnection,
166586
+ managedScope: params.managedScope
166587
+ })
166588
+ } : {}
166040
166589
  });
166041
166590
  return {
166042
166591
  storageDestinationName: destinationName,
@@ -166047,6 +166596,77 @@ async function buildSameCatalogIntoStorage(params) {
166047
166596
  };
166048
166597
  });
166049
166598
  }
166599
+ async function namesReadIn(selectSQL, alias) {
166600
+ const parsed = await serializeSQL(selectSQL);
166601
+ if (parsed.error || !Array.isArray(parsed.statements))
166602
+ return;
166603
+ const catalog = alias.toLowerCase();
166604
+ const names = [];
166605
+ const str = (v) => typeof v === "string" ? v.toLowerCase() : "";
166606
+ const walk = (node) => {
166607
+ if (node === null || typeof node !== "object")
166608
+ return;
166609
+ if (Array.isArray(node)) {
166610
+ node.forEach(walk);
166611
+ return;
166612
+ }
166613
+ const record = node;
166614
+ if (record.type === "BASE_TABLE") {
166615
+ const [c, s, t] = [
166616
+ str(record.catalog_name),
166617
+ str(record.schema_name),
166618
+ str(record.table_name)
166619
+ ];
166620
+ if (c) {
166621
+ if (c === catalog)
166622
+ names.push([s || "main", t]);
166623
+ } else if (s) {
166624
+ names.push([s, t]);
166625
+ if (s === catalog)
166626
+ names.push(["main", t]);
166627
+ } else {
166628
+ names.push(["main", t]);
166629
+ }
166630
+ }
166631
+ Object.values(record).forEach(walk);
166632
+ };
166633
+ walk(parsed.statements);
166634
+ return names;
166635
+ }
166636
+ async function refuseOutOfScopeReads(session, selectSQL, params) {
166637
+ const { alias, destinationName, sourceConnection } = params;
166638
+ const names = await namesReadIn(selectSQL, alias);
166639
+ const refuse = (why) => new BadRequestError(`Cannot materialize a source from managed connection '${sourceConnection.name}' ` + `into storage destination '${destinationName}' that ${why}: the build ` + `reads the catalog with the destination's credential, so it reads only ` + `base tables whose files the connection's own storage scope reaches.`);
166640
+ if (!names)
166641
+ throw refuse("reads SQL it cannot parse");
166642
+ if (names.length === 0)
166643
+ return;
166644
+ const run = async (sql) => (await runInternalSQL(session, sql)).rows;
166645
+ let outside;
166646
+ try {
166647
+ const types = await run("SELECT lower(table_schema) AS s, lower(table_name) AS t, table_type " + "FROM information_schema.tables " + `WHERE lower(table_catalog) = '${alias.toLowerCase().replace(/'/g, "''")}'`);
166648
+ const typeOf = new Map(types.map((r) => [`${String(r.s)}.${String(r.t)}`, r.table_type]));
166649
+ const read = names.filter(([s, t]) => typeOf.has(`${s}.${t}`));
166650
+ if (read.some(([s, t]) => typeOf.get(`${s}.${t}`) !== "BASE TABLE")) {
166651
+ throw refuse("reads a view");
166652
+ }
166653
+ if (read.length === 0)
166654
+ return;
166655
+ const [snapshot] = await run(`SELECT id FROM ${quoteIdentifier(alias, STORAGE_DIALECT)}.current_snapshot()`);
166656
+ const distinct = [...new Map(read.map((r) => [r.join("."), r])).values()];
166657
+ const prefixes = await params.managedScope?.();
166658
+ if (!prefixes) {
166659
+ throw refuse("reads tables while its storage scope is not known (the connection is not attached)");
166660
+ }
166661
+ outside = await fileOutsideScope(run, alias, String(snapshot?.id), distinct, prefixes);
166662
+ } catch (error) {
166663
+ if (error instanceof BadRequestError)
166664
+ throw error;
166665
+ throw refuse("reads tables whose files could not be checked against its storage scope");
166666
+ }
166667
+ if (outside)
166668
+ throw refuse(`reads ${outside}`);
166669
+ }
166050
166670
  function leaveOutFailing(files, err, build) {
166051
166671
  if (!(err instanceof MalloyError3) || !build.leaveOutWithin?.length) {
166052
166672
  return false;
@@ -166370,6 +166990,7 @@ async function createTableAndDescribe(session, quotedTablePath, selectSQL, optio
166370
166990
  for (const sql of options.replacesView ?? []) {
166371
166991
  await session.runSQL(sql);
166372
166992
  }
166993
+ await options.beforeCreate?.();
166373
166994
  await session.runSQL(`CREATE OR REPLACE TABLE ${quotedTablePath} AS (${selectSQL})`);
166374
166995
  let described = await describeTable(session, quotedTablePath);
166375
166996
  const renames = canonicalRenames(described, options.declaredNames ?? []);
@@ -166520,6 +167141,8 @@ var init_materialization_build_session = __esm(() => {
166520
167141
  init_passthrough_build();
166521
167142
  init_connection();
166522
167143
  init_ducklake();
167144
+ init_single_select();
167145
+ init_same_catalog_tables();
166523
167146
  init_dialects();
166524
167147
  init_duckdb_session_setup();
166525
167148
  init_connection_config();
@@ -167071,6 +167694,7 @@ function compileInputOf(b) {
167071
167694
  holdsOnlyUngatedRows: _ungated,
167072
167695
  retypedColumns: _retyped,
167073
167696
  rollupKey: _rollupKey,
167697
+ grainJoinKeys: _grainJoinKeys,
167074
167698
  ...read
167075
167699
  } = b;
167076
167700
  input = JSON.stringify(read);
@@ -167194,6 +167818,62 @@ var init_served_copy_lanes = __esm(() => {
167194
167818
  compileInputs = new WeakMap;
167195
167819
  });
167196
167820
 
167821
+ // src/service/materialization/serve/sql_embed_reads.ts
167822
+ function sqlEmbedReads(modelDefs) {
167823
+ const out = new Map;
167824
+ for (const modelDef of modelDefs) {
167825
+ for (const select of sqlSelectsWithin(modelDef)) {
167826
+ const connection = select.connection;
167827
+ if (typeof connection !== "string")
167828
+ continue;
167829
+ const segments = select.selectSegments.filter((s) => typeof s === "object" && s !== null && !(("sql" in s) && s.type === undefined));
167830
+ if (segments.length === 0)
167831
+ continue;
167832
+ const isQuery = (s) => s.type === "query";
167833
+ const read = {
167834
+ via: labelOf(select),
167835
+ connection,
167836
+ ...typeof select.sourceID === "string" ? { sourceID: select.sourceID } : {},
167837
+ reaches: reachableSourceIDs(segments.filter(isQuery), modelDef),
167838
+ bareReaches: reachableSourceIDs(segments.filter((s) => !isQuery(s)), modelDef)
167839
+ };
167840
+ const key = [
167841
+ read.via,
167842
+ connection,
167843
+ [...read.reaches].sort().join(","),
167844
+ [...read.bareReaches].sort().join(",")
167845
+ ].join("\x00");
167846
+ if (!out.has(key))
167847
+ out.set(key, read);
167848
+ }
167849
+ }
167850
+ return [...out.values()];
167851
+ }
167852
+ function conflictingSqlEmbeds(reads, sourceID, servedOn, rerooted) {
167853
+ const out = [];
167854
+ for (const read of reads) {
167855
+ if (read.sourceID !== undefined && rerooted(read.sourceID))
167856
+ continue;
167857
+ if (read.bareReaches.has(sourceID)) {
167858
+ out.push({ read, conflict: "bare" });
167859
+ } else if (read.connection !== servedOn && read.reaches.has(sourceID)) {
167860
+ out.push({ read, conflict: "cross_connection" });
167861
+ }
167862
+ }
167863
+ return out;
167864
+ }
167865
+ function ownSqlEmbedReach(struct, modelDef) {
167866
+ const select = struct;
167867
+ if (select?.type !== "sql_select" || !Array.isArray(select.selectSegments)) {
167868
+ return new Set;
167869
+ }
167870
+ return reachableSourceIDs(select.selectSegments.filter((s) => typeof s === "object" && s !== null && !(("sql" in s) && s.type === undefined)), modelDef);
167871
+ }
167872
+ var init_sql_embed_reads = __esm(() => {
167873
+ init_sql_embeds();
167874
+ init_source_map();
167875
+ });
167876
+
167197
167877
  // src/service/materialization/text/chain_build_files.ts
167198
167878
  function chainBuildFileSet(args) {
167199
167879
  const { lift } = args;
@@ -168642,7 +169322,46 @@ function namesServedCopyAlias(text) {
168642
169322
  function withoutServedCopyAliases(text) {
168643
169323
  return text.replace(new RegExp(`'?__publisher_storage_${TOKEN}_\\d+'?`, "g"), "the storage destination");
168644
169324
  }
168645
- function servedCopyConfig(packageConfig, destinations, allowed) {
169325
+ function destinationOfAlias(name) {
169326
+ return destinationsByAlias.get(name);
169327
+ }
169328
+ function servedConnectionLabel(name) {
169329
+ const destination = destinationsByAlias.get(name);
169330
+ return destination !== undefined ? `storage destination '${destination}'` : `connection '${name}'`;
169331
+ }
169332
+ function underAlias(connection, alias) {
169333
+ let views = aliasedViews.get(connection);
169334
+ if (!views) {
169335
+ views = new Map;
169336
+ aliasedViews.set(connection, views);
169337
+ }
169338
+ const known = views.get(alias);
169339
+ if (known)
169340
+ return known;
169341
+ const view = new Proxy(connection, {
169342
+ get(target, prop) {
169343
+ if (prop === "name")
169344
+ return alias;
169345
+ if (prop === "fetchSchemaForTables") {
169346
+ return async (...args) => {
169347
+ const fetched = await target.fetchSchemaForTables(...args);
169348
+ return {
169349
+ ...fetched,
169350
+ schemas: Object.fromEntries(Object.entries(fetched.schemas).map(([key, def]) => [
169351
+ key,
169352
+ { ...def, connection: alias }
169353
+ ]))
169354
+ };
169355
+ };
169356
+ }
169357
+ const value = Reflect.get(target, prop, target);
169358
+ return typeof value === "function" ? value.bind(target) : value;
169359
+ }
169360
+ });
169361
+ views.set(alias, view);
169362
+ return view;
169363
+ }
169364
+ function servedCopyConfig(packageConfig, destinations, allowed, tablesUnderAlias = new Set) {
168646
169365
  const base = toMalloyConfig(packageConfig);
168647
169366
  const config = new MalloyConfig3({ connections: {} });
168648
169367
  config.wrapConnections(() => ({
@@ -168653,7 +169372,8 @@ function servedCopyConfig(packageConfig, destinations, allowed) {
168653
169372
  if (!allowed.has(destination)) {
168654
169373
  throw new Error(`A storage destination is not available to this served copy`);
168655
169374
  }
168656
- return destinations.connections.lookupConnection(destination);
169375
+ const connection = await destinations.connections.lookupConnection(destination);
169376
+ return tablesUnderAlias.has(destination) ? underAlias(connection, name) : connection;
168657
169377
  }
168658
169378
  }
168659
169379
  return base.connections.lookupConnection(name);
@@ -168661,16 +169381,35 @@ function servedCopyConfig(packageConfig, destinations, allowed) {
168661
169381
  }));
168662
169382
  return config;
168663
169383
  }
168664
- var TOKEN, aliases, destinationsByAlias;
169384
+ var TOKEN, aliases, destinationsByAlias, aliasedViews;
168665
169385
  var init_served_copy_config = __esm(() => {
168666
169386
  init_model_runtime();
168667
169387
  TOKEN = randomBytes2(12).toString("hex");
168668
169388
  aliases = new Map;
168669
169389
  destinationsByAlias = new Map;
169390
+ aliasedViews = new WeakMap;
168670
169391
  });
168671
169392
 
168672
169393
  // src/service/materialization/text/cross_connection_text.ts
168673
169394
  import { MalloyError as MalloyError4 } from "@malloydata/malloy";
169395
+ function refusedJoinConnections(message) {
169396
+ const named = /which is on connection '([^']*)', into a source on connection '([^']*)'/.exec(message ?? "");
169397
+ return named ? { joined: named[1], into: named[2] } : undefined;
169398
+ }
169399
+ function refusedJoinPairs(error) {
169400
+ if (!isCrossConnectionRefusal(error))
169401
+ return;
169402
+ const pairs = [];
169403
+ for (const p of errorProblems(error) ?? []) {
169404
+ if (p.code !== JOIN_CONNECTION_MISMATCH)
169405
+ continue;
169406
+ const pair = refusedJoinConnections(p.message);
169407
+ if (!pair)
169408
+ return;
169409
+ pairs.push(pair);
169410
+ }
169411
+ return pairs;
169412
+ }
168674
169413
  function isJoinConnectionMismatch(code) {
168675
169414
  return code === JOIN_CONNECTION_MISMATCH;
168676
169415
  }
@@ -168787,10 +169526,12 @@ async function leaveOut(args, escalated) {
168787
169526
  continue;
168788
169527
  }
168789
169528
  cuts.push(cut);
169529
+ const connections = refused ? refusedJoinConnections(p.message) : undefined;
168790
169530
  leftOut.push({
168791
169531
  url,
168792
169532
  ...cut.left,
168793
169533
  crossConnection: refused,
169534
+ ...connections ? { connections } : {},
168794
169535
  ...cut !== own && own?.left.keyword.startsWith("join_") ? { join: own.left.name } : {}
168795
169536
  });
168796
169537
  }
@@ -169883,6 +170624,231 @@ var init_query_walks = __esm(() => {
169883
170624
  walks2 = new Map;
169884
170625
  });
169885
170626
 
170627
+ // src/service/materialization/serve/same_catalog_reads.ts
170628
+ function destinationTablePath(path, move) {
170629
+ const parts = path.split(".");
170630
+ if (!PLAIN.test(move.destination) || !parts.every((p) => PLAIN.test(p))) {
170631
+ return;
170632
+ }
170633
+ const self2 = move.connection.toLowerCase();
170634
+ const readable = (s) => move.schemas.has(s.toLowerCase());
170635
+ const at = (schema, table) => `${move.destination}.${schema}.${table}`;
170636
+ if (parts.length === 1)
170637
+ return at("main", parts[0]);
170638
+ if (parts.length === 2) {
170639
+ const [first, table] = parts;
170640
+ if (first.toLowerCase() === self2) {
170641
+ return readable(first) ? undefined : at("main", table);
170642
+ }
170643
+ return readable(first) ? at(first, table) : undefined;
170644
+ }
170645
+ if (parts.length === 3) {
170646
+ const [catalog, schema, table] = parts;
170647
+ return catalog.toLowerCase() === self2 && readable(schema) ? at(schema, table) : undefined;
170648
+ }
170649
+ return;
170650
+ }
170651
+ function literalValue(token) {
170652
+ const m = /^(['"])([^'"\\]*)\1$/.exec(token?.text ?? "");
170653
+ return m ? m[2] : undefined;
170654
+ }
170655
+ function namesConnection(token, name) {
170656
+ return token.kind === "word" && token.text === name || token.text.length === name.length + 2 && token.text.startsWith("`") && token.text.endsWith("`") && token.text.slice(1, -1) === name;
170657
+ }
170658
+ function readThroughDestination(text, move) {
170659
+ const tokens = lexAll(text);
170660
+ if (!tokens)
170661
+ return;
170662
+ const edits = [];
170663
+ const paths = [];
170664
+ for (let k = 0;k < tokens.length; k++) {
170665
+ const t = tokens[k];
170666
+ if (!namesConnection(t, move.connection))
170667
+ continue;
170668
+ if (tokens[k - 1]?.text === ".")
170669
+ continue;
170670
+ if (tokens[k + 1]?.text !== ".")
170671
+ continue;
170672
+ const method = tokens[k + 2];
170673
+ if (method?.kind !== "word")
170674
+ continue;
170675
+ if (method.text !== "table")
170676
+ return;
170677
+ const value = literalValue(tokens[k + 4]);
170678
+ if (tokens[k + 3]?.text !== "(" || value === undefined || tokens[k + 5]?.text !== ")") {
170679
+ return;
170680
+ }
170681
+ const moved = destinationTablePath(value, move);
170682
+ if (moved === undefined)
170683
+ return;
170684
+ paths.push(value);
170685
+ edits.push({
170686
+ start: t.start,
170687
+ end: tokens[k + 5].end,
170688
+ text: `${identifier(move.alias)}.table(${stringLiteral(moved)})`
170689
+ });
170690
+ k += 5;
170691
+ }
170692
+ let out = text;
170693
+ for (const e of edits.reverse()) {
170694
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
170695
+ }
170696
+ return { text: out, paths };
170697
+ }
170698
+ async function sameCatalogMoves(error, ports) {
170699
+ const pairs = refusedJoinPairs(error);
170700
+ if (!pairs?.length)
170701
+ return;
170702
+ const moves = new Map;
170703
+ for (const { joined, into } of pairs) {
170704
+ const intoDestination = destinationOfAlias(into);
170705
+ const joinedDestination = destinationOfAlias(joined);
170706
+ const [connection, alias, destination] = intoDestination !== undefined && joinedDestination === undefined ? [joined, into, intoDestination] : joinedDestination !== undefined && intoDestination === undefined ? [into, joined, joinedDestination] : [];
170707
+ if (!connection || !alias || !destination)
170708
+ return;
170709
+ const known = moves.get(connection);
170710
+ if (known) {
170711
+ if (known.alias !== alias)
170712
+ return;
170713
+ continue;
170714
+ }
170715
+ const schemas = await ports.scope(connection, alias);
170716
+ if (!schemas)
170717
+ return;
170718
+ moves.set(connection, { connection, alias, destination, schemas });
170719
+ }
170720
+ return [...moves.values()];
170721
+ }
170722
+ function movedAuthorSqlCause(modelDef, connections, rerooted) {
170723
+ const { contents } = authorModelReachContext(modelDef);
170724
+ for (const [name, def] of Object.entries(contents)) {
170725
+ const d = def;
170726
+ if (typeof d.connection !== "string" || !connections.has(d.connection)) {
170727
+ continue;
170728
+ }
170729
+ if (typeof d.sourceID === "string" && rerooted.has(d.sourceID)) {
170730
+ for (const field of Array.isArray(d.fields) ? d.fields : []) {
170731
+ const f = field;
170732
+ if (f.join === undefined)
170733
+ continue;
170734
+ const cause = authorSqlCause(field);
170735
+ if (cause)
170736
+ return `the join '${String(f.name)}' of '${name}': ${cause}`;
170737
+ }
170738
+ continue;
170739
+ }
170740
+ const cause = authorSqlCause(def);
170741
+ if (cause)
170742
+ return `the source '${name}': ${cause}`;
170743
+ }
170744
+ return;
170745
+ }
170746
+ function declaringFiles(modelDef, connections) {
170747
+ const { contents } = authorModelReachContext(modelDef);
170748
+ const urls = new Set;
170749
+ for (const def of Object.values(contents)) {
170750
+ const d = def;
170751
+ if (typeof d.connection === "string" && connections.has(d.connection) && typeof d.location?.url === "string") {
170752
+ urls.add(d.location.url);
170753
+ }
170754
+ }
170755
+ return [...urls];
170756
+ }
170757
+ async function readSameCatalogThroughDestination(args) {
170758
+ const moves = await sameCatalogMoves(args.error, args.ports);
170759
+ if (!moves) {
170760
+ return {
170761
+ declined: "a refused join is not into a managed connection's own catalog"
170762
+ };
170763
+ }
170764
+ const names = new Set(moves.map((m) => m.connection));
170765
+ const sql = movedAuthorSqlCause(args.modelDef, names, args.rerooted);
170766
+ if (sql)
170767
+ return { declined: `${sql}, which carries author SQL` };
170768
+ const urls = new Set([
170769
+ ...args.files.keys(),
170770
+ ...declaringFiles(args.modelDef, names)
170771
+ ]);
170772
+ const out = new Map(args.files);
170773
+ const moved = [];
170774
+ for (const move of moves) {
170775
+ const paths = [];
170776
+ for (const url of urls) {
170777
+ const text = out.get(url) ?? args.readText(url);
170778
+ if (text === undefined)
170779
+ return { declined: "a file it cannot read" };
170780
+ const read = readThroughDestination(text, move);
170781
+ if (!read) {
170782
+ return {
170783
+ declined: `connection '${move.connection}' is named other than in a plain .table() it can place`
170784
+ };
170785
+ }
170786
+ if (read.paths.length === 0)
170787
+ continue;
170788
+ paths.push(...read.paths);
170789
+ out.set(url, read.text);
170790
+ }
170791
+ for (const path of paths) {
170792
+ const refused = await args.ports.pathRefusal(path, move.connection, move.schemas);
170793
+ if (refused !== undefined) {
170794
+ return {
170795
+ declined: `table '${path}' is outside the connection's scope`
170796
+ };
170797
+ }
170798
+ }
170799
+ const tables = [...new Set(paths)].map((path) => {
170800
+ const [catalog, schema, table] = destinationTablePath(path, move).split(".");
170801
+ return [catalog, schema, table];
170802
+ });
170803
+ const read = {
170804
+ alias: move.alias,
170805
+ connection: move.connection,
170806
+ schemas: move.schemas,
170807
+ tables
170808
+ };
170809
+ if (!await args.ports.readable(read)) {
170810
+ return {
170811
+ declined: "a table it reads is not a base table, or holds a file outside the connection's storage scope"
170812
+ };
170813
+ }
170814
+ if (tables.length > 0)
170815
+ moved.push(read);
170816
+ }
170817
+ return {
170818
+ files: out,
170819
+ destinations: new Set(moves.map((m) => m.destination)),
170820
+ moved
170821
+ };
170822
+ }
170823
+ var PLAIN;
170824
+ var init_same_catalog_reads = __esm(() => {
170825
+ init_malloy_lexer_core();
170826
+ init_malloy_text();
170827
+ init_same_catalog_build();
170828
+ init_author_model();
170829
+ init_cross_connection_text();
170830
+ init_served_copy_config();
170831
+ PLAIN = /^[A-Za-z_][A-Za-z0-9_]*$/;
170832
+ });
170833
+
170834
+ // src/service/same_catalog_destination.ts
170835
+ async function sameCatalogScope(config, connection, alias) {
170836
+ const [source, destination] = await Promise.all([
170837
+ config.connections.lookupConnection(connection).catch(() => {
170838
+ return;
170839
+ }),
170840
+ config.connections.lookupConnection(alias).catch(() => {
170841
+ return;
170842
+ })
170843
+ ]);
170844
+ const schemas = managedSchemasOf(source);
170845
+ return schemas && isSameCatalog(connectionConfigOf(source), connectionConfigOf(destination)) ? schemas : undefined;
170846
+ }
170847
+ var init_same_catalog_destination = __esm(() => {
170848
+ init_connection_type();
170849
+ init_same_catalog_build();
170850
+ });
170851
+
169886
170852
  // src/service/materialization/serve/result_reads.ts
169887
170853
  function nonStringType2(t) {
169888
170854
  return typeof t === "string" && t !== "string";
@@ -170731,27 +171697,69 @@ import {
170731
171697
  function servedConnectionOf(b) {
170732
171698
  return isDatabase(b) ? b.destinationName : servedCopyAlias(b.destinationName);
170733
171699
  }
170734
- function readsLeftOutDefinition(compiled, error, queryString) {
171700
+ function importedFileURLs(modelDef) {
171701
+ const urls = new Set;
171702
+ const walk = (tree, depth) => {
171703
+ if (depth > 64 || typeof tree !== "object" || tree === null)
171704
+ return;
171705
+ for (const [url, below] of Object.entries(tree)) {
171706
+ if (urls.has(url))
171707
+ continue;
171708
+ urls.add(url);
171709
+ walk(below, depth + 1);
171710
+ }
171711
+ };
171712
+ walk(modelDef?.dependencies, 0);
171713
+ return [...urls];
171714
+ }
171715
+ function leftOutJoinDetail(joins) {
171716
+ const named = joins.map((j) => {
171717
+ const join = j.join ?? j.name;
171718
+ const source = j.declaration ?? (j.join !== undefined ? j.name : undefined);
171719
+ const where = source ? ` of \`${source}\`` : "";
171720
+ const across = j.connections ? ` (${servedConnectionLabel(j.connections.joined)} into ` + `${servedConnectionLabel(j.connections.into)})` : "";
171721
+ return `\`${join}\`${where}${across}`;
171722
+ });
171723
+ const subject = named.length === 0 ? "a join" : `the join${named.length === 1 ? "" : "s"} ${named.join(", ")}`;
171724
+ return `The query uses ${subject}, whose joined source is on another connection ` + "than the storage destination its table is read from, so it is answered live.";
171725
+ }
171726
+ function leftOutJoinsRead(compiled, error, queryString) {
170735
171727
  if (!compiled.leftOut?.length)
170736
- return false;
170737
- return readsMissingName(new Set(compiled.leftOut.map((l) => l.name)), error, queryString);
171728
+ return;
171729
+ const read = missingNamesRead(new Set(compiled.leftOut.map((l) => l.name)), error, queryString);
171730
+ if (read === undefined)
171731
+ return;
171732
+ const joins = compiled.leftOut.filter((l) => l.crossConnection);
171733
+ const direct = joins.filter((l) => read.has(l.name));
171734
+ return direct.length > 0 ? direct : joins;
170738
171735
  }
170739
171736
  function readsMissingName(names, error, queryString) {
171737
+ return missingNamesRead(names, error, queryString) !== undefined;
171738
+ }
171739
+ function missingNamesRead(names, error, queryString) {
170740
171740
  if (!(error instanceof MalloyError5))
170741
- return false;
170742
- return error.problems.some((p) => {
170743
- if (p.code === undefined || !MISSING_FIELD_CODES.has(p.code)) {
170744
- return false;
170745
- }
171741
+ return;
171742
+ const read = new Set;
171743
+ let any = false;
171744
+ for (const p of error.problems) {
171745
+ if (p.code === undefined || !MISSING_FIELD_CODES.has(p.code))
171746
+ continue;
170746
171747
  const start = p.at?.range?.start;
170747
171748
  const offset = start ? offsetOf(queryString, start) : -1;
170748
- if (offset < 0)
170749
- return true;
170750
- const path = /^[`A-Za-z0-9_.]+/.exec(queryString.slice(offset))?.[0];
170751
- if (!path)
170752
- return true;
170753
- return path.split(".").some((part) => names.has(part.replace(/^`|`$/g, "")));
170754
- });
171749
+ const path = offset < 0 ? undefined : /^[`A-Za-z0-9_.]+/.exec(queryString.slice(offset))?.[0];
171750
+ if (!path) {
171751
+ any = true;
171752
+ continue;
171753
+ }
171754
+ for (const part of path.split(".")) {
171755
+ const name = part.replace(/^`|`$/g, "");
171756
+ if (names.has(name)) {
171757
+ read.add(name);
171758
+ any = true;
171759
+ }
171760
+ }
171761
+ }
171762
+ return any ? read : undefined;
170755
171763
  }
170756
171764
  function rerootFailureKey(packagePath, modelPath, bindings, overlay) {
170757
171765
  const hash = createHash9("sha256");
@@ -170903,6 +171911,7 @@ class ServedCopyServe {
170903
171911
  ...asWritten ? { tableIds: asWritten.tableIds } : {}
170904
171912
  });
170905
171913
  }
171914
+ await this.recheckSameCatalog(compiled);
170906
171915
  const declined = compiled.declined?.get(queryString);
170907
171916
  if (declined !== undefined)
170908
171917
  throw declined;
@@ -170921,8 +171930,10 @@ class ServedCopyServe {
170921
171930
  try {
170922
171931
  return await work();
170923
171932
  } catch (error) {
170924
- if (readsLeftOutDefinition(compiled, error, queryString)) {
170925
- decline("the query reads a join the served copy leaves out across connections", "served_copy_cross_connection", LEFT_OUT_JOIN_DETAIL);
171933
+ const leftOutJoins = leftOutJoinsRead(compiled, error, queryString);
171934
+ if (leftOutJoins) {
171935
+ const detail = leftOutJoinDetail(leftOutJoins);
171936
+ decline(`the query reads a join the served copy leaves out across connections: ${detail}`, "served_copy_cross_connection", detail);
170926
171937
  }
170927
171938
  const zoned = new Set([...compiled.zonedLeftOut?.values() ?? []].flatMap((n) => [
170928
171939
  ...n
@@ -171110,6 +172121,7 @@ class ServedCopyServe {
171110
172121
  };
171111
172122
  }
171112
172123
  async checkJoinVariant(compiled, args) {
172124
+ await this.recheckSameCatalog(compiled);
171113
172125
  const decline = (reason, code, callerDetail) => {
171114
172126
  throw new LegDecline(code, callerDetail, { message: reason });
171115
172127
  };
@@ -171145,6 +172157,17 @@ class ServedCopyServe {
171145
172157
  decline
171146
172158
  });
171147
172159
  }
172160
+ async recheckSameCatalog(compiled) {
172161
+ if (!compiled.sameCatalogRecheck)
172162
+ return;
172163
+ const ok = await compiled.sameCatalogRecheck().catch(() => false);
172164
+ if (ok)
172165
+ return;
172166
+ logger.warn("A served copy's table read through its storage destination is no longer a base table, holds a file outside the managed connection's storage scope, or could not be checked; answering live", { modelPath: this.host.modelPath() });
172167
+ throw new LegDecline("served_copy_not_served", undefined, {
172168
+ message: "a table the served copy reads through its storage destination is no longer a base table, holds a file outside the managed connection's storage scope, or could not be checked"
172169
+ });
172170
+ }
171148
172171
  readsRollingWindow(binding) {
171149
172172
  return (binding.sourceIDs ?? []).some((id) => rollingWindowsOf(this.materializePlans[id]?.readTimeTerms).length > 0);
171150
172173
  }
@@ -171473,6 +172496,39 @@ class ServedCopyServe {
171473
172496
  rerootedSpans
171474
172497
  };
171475
172498
  }
172499
+ ownSqlEmbedReach(struct, modelDef) {
172500
+ return ownSqlEmbedReach(struct, modelDef);
172501
+ }
172502
+ withoutConflictingSqlEmbeds(candidates, map, problems) {
172503
+ const modelDef = this.host.modelDef();
172504
+ const reads = sqlEmbedReads([
172505
+ modelDef,
172506
+ ...importedFileURLs(modelDef).map((url) => this.host.siblingModelDef?.(url))
172507
+ ]);
172508
+ if (reads.length === 0)
172509
+ return candidates;
172510
+ const rerootedIDs = new Set(candidates.map((c) => c.reroot.sourceID));
172511
+ const rerooted = (sqlSourceID) => {
172512
+ const node = map.node(sqlSourceID);
172513
+ const chain = node ? map.chainOf(node.def) : [sqlSourceID];
172514
+ return chain.some((id) => rerootedIDs.has(id));
172515
+ };
172516
+ return candidates.filter((c) => {
172517
+ const conflicts = conflictingSqlEmbeds(reads, c.reroot.sourceID, servedConnectionOf(c.binding), rerooted);
172518
+ if (conflicts.length === 0)
172519
+ return true;
172520
+ const whole = conflicts.some((x) => x.conflict === "bare");
172521
+ problems.push({
172522
+ sourceName: c.reroot.sourceName,
172523
+ sourceID: c.reroot.sourceID,
172524
+ reason: whole ? "sql_embed_bare" : "sql_embed_cross_connection",
172525
+ detail: [
172526
+ ...new Set(conflicts.filter((x) => !whole || x.conflict === "bare").map(({ read }) => `\`${read.via}\` on \`${read.connection}\``))
172527
+ ].join(", ")
172528
+ });
172529
+ return false;
172530
+ });
172531
+ }
171476
172532
  rerootCandidates(bindings, map, lift, problems, lane, passedOver = new Set, twins, restatesStageZoned = false) {
171477
172533
  let candidates = [];
171478
172534
  const reservedNames = modelFieldNames(map);
@@ -171502,6 +172558,7 @@ class ServedCopyServe {
171502
172558
  const tiers = (byKey.get(keyOf(c)) ?? []).filter((o) => !passedOver.has(o.binding)).map((o) => o.binding.tier);
171503
172559
  return servedCopyReadsTier(c.binding.tier, tiers);
171504
172560
  });
172561
+ candidates = this.withoutConflictingSqlEmbeds(candidates, map, problems);
171505
172562
  const rerootedIDs = new Set(candidates.map((c) => c.reroot.sourceID));
171506
172563
  const rerootedNames = new Set(candidates.map((c) => c.reroot.sourceName));
171507
172564
  const throughBase = [];
@@ -171669,9 +172726,11 @@ class ServedCopyServe {
171669
172726
  }));
171670
172727
  const overlay = new Map(copy.files);
171671
172728
  const packagePath = this.packagePath;
171672
- const config = servedCopyConfig(this.packageConfig, destinations(), new Set(rerooted.filter((b) => !isDatabase(b)).map((b) => b.destinationName)));
171673
- const load = this.passLoader(packagePath, config);
171674
- const loaded = await this.loadCopy(state, copy, overlay, load, lift);
172729
+ const packageConfig = this.packageConfig;
172730
+ const config = servedCopyConfig(packageConfig, destinations(), new Set(rerooted.filter((b) => !isDatabase(b)).map((b) => b.destinationName)));
172731
+ const load = this.passLoader(packagePath, config, aliased);
172732
+ const underAlias = this.underAliasLoader(packagePath, packageConfig, destinations, rerooted);
172733
+ const loaded = await this.loadCopy(state, copy, overlay, load, lift, config, underAlias);
171675
172734
  if (loaded === "retry")
171676
172735
  continue;
171677
172736
  if (loaded === "failed") {
@@ -171705,10 +172764,11 @@ class ServedCopyServe {
171705
172764
  materializer,
171706
172765
  leftOut,
171707
172766
  files,
171708
- config,
172767
+ config: loaded.config ?? config,
171709
172768
  rerooted,
171710
172769
  aliased,
171711
- throughBase
172770
+ throughBase,
172771
+ sameCatalogReads: loaded.sameCatalogReads
171712
172772
  });
171713
172773
  }
171714
172774
  return {
@@ -171721,7 +172781,21 @@ class ServedCopyServe {
171721
172781
  problems
171722
172782
  };
171723
172783
  }
171724
- passLoader(packagePath, config) {
172784
+ underAliasLoader(packagePath, packageConfig, destinations, rerooted) {
172785
+ const aliased = rerooted.map((b) => ({
172786
+ ...b,
172787
+ destinationName: servedConnectionOf(b)
172788
+ }));
172789
+ return (names) => {
172790
+ const config = servedCopyConfig(packageConfig, destinations(), new Set(rerooted.filter((b) => !isDatabase(b)).map((b) => b.destinationName)), names);
172791
+ return {
172792
+ config,
172793
+ load: this.passLoader(packagePath, config, aliased)
172794
+ };
172795
+ };
172796
+ }
172797
+ passLoader(packagePath, config, aliased) {
172798
+ const virtualMap = buildVirtualMap(aliased);
171725
172799
  const modelPath = this.host.modelPath();
171726
172800
  const compiler = packageFiles(packagePath, modelPath, config);
171727
172801
  return async (files) => {
@@ -171729,11 +172803,14 @@ class ServedCopyServe {
171729
172803
  packagePath,
171730
172804
  modelPath,
171731
172805
  config,
171732
- files: keyedOverlay(files)
172806
+ files: keyedOverlay(files),
172807
+ virtualMap
171733
172808
  });
171734
172809
  if (elsewhere)
171735
172810
  return elsewhere;
171736
- const { runtime, materializer } = await compiler.loadModel(files);
172811
+ const { runtime, materializer } = await compiler.loadModel(files, {
172812
+ virtualMap
172813
+ });
171737
172814
  const model = await materializer.getModel();
171738
172815
  return {
171739
172816
  materializer,
@@ -171778,7 +172855,7 @@ class ServedCopyServe {
171778
172855
  }
171779
172856
  byKey.set(key, { error, until: asOf + REROOT_FAILURE_TTL_MS });
171780
172857
  }
171781
- async loadCopy(state, copy, overlay, load, lift) {
172858
+ async loadCopy(state, copy, overlay, load, lift, config, underAlias) {
171782
172859
  const { withoutKept, problems } = state;
171783
172860
  let materializer;
171784
172861
  let servedDef;
@@ -171811,6 +172888,9 @@ class ServedCopyServe {
171811
172888
  return "retry";
171812
172889
  }
171813
172890
  const byURL = new Map([...copy.files].map(([url, text]) => [url, text]));
172891
+ const merged = await this.readSameCatalogThroughDestination(state, err, byURL, lift, config, underAlias);
172892
+ if (merged)
172893
+ return merged;
171814
172894
  const kept = await leaveOutCrossConnectionJoins({
171815
172895
  firstError: err,
171816
172896
  overlay: byURL,
@@ -171876,6 +172956,45 @@ class ServedCopyServe {
171876
172956
  }
171877
172957
  return { materializer, servedDef, servedRuntime, leftOut, files };
171878
172958
  }
172959
+ async readSameCatalogThroughDestination(state, err, files, lift, config, underAlias) {
172960
+ const moved = await readSameCatalogThroughDestination({
172961
+ error: err,
172962
+ files,
172963
+ readText: (u) => lift.fileText(u),
172964
+ modelDef: this.host.modelDef(),
172965
+ rerooted: new Set(state.candidates.map((c) => c.reroot.sourceID)),
172966
+ ports: {
172967
+ scope: (connection, alias) => sameCatalogScope(config, connection, alias),
172968
+ pathRefusal: (path, connection, schemas) => this.host.managedTablePathRefusal ? this.host.managedTablePathRefusal(path, connection, schemas) : Promise.resolve("no managed scope check is available"),
172969
+ readable: (read) => this.host.sameCatalogTablesReadable ? this.host.sameCatalogTablesReadable(config, read) : Promise.resolve(false)
172970
+ }
172971
+ }).catch(() => ({ declined: "a read of its connections failed" }));
172972
+ if ("declined" in moved) {
172973
+ logger.debug("A served copy's join across one catalog is not read through the destination; its joins are left out", { modelPath: this.host.modelPath(), why: moved.declined });
172974
+ return;
172975
+ }
172976
+ const keyed = keyedOverlay(moved.files);
172977
+ const { config: aliased, load } = underAlias(moved.destinations);
172978
+ try {
172979
+ const loaded = await load(keyed);
172980
+ logger.debug("A served copy reads a joined source on its destination's catalog through the destination", { modelPath: this.host.modelPath() });
172981
+ return {
172982
+ materializer: loaded.materializer,
172983
+ servedDef: loaded.def,
172984
+ servedRuntime: loaded.runtime,
172985
+ leftOut: [],
172986
+ files: keyed,
172987
+ config: aliased,
172988
+ sameCatalogReads: moved.moved
172989
+ };
172990
+ } catch (again) {
172991
+ logger.debug("A served copy's same-catalog read does not compile; its joins are left out", {
172992
+ modelPath: this.host.modelPath(),
172993
+ codes: errorProblems(again)?.map((p) => p.code)
172994
+ });
172995
+ return;
172996
+ }
172997
+ }
171879
172998
  contain(state, copy, error, files, mode, remembered = false) {
171880
172999
  const { withoutKept, problems } = state;
171881
173000
  const failing = new Map(failingReroots(error, files, copy.spans, mode).map((f) => [
@@ -171930,6 +173049,7 @@ class ServedCopyServe {
171930
173049
  const { key, generation, over, lane, modelDef, servedMap } = built;
171931
173050
  const { servedDef, servedRuntime, materializer, leftOut } = built;
171932
173051
  const { files, config, rerooted, aliased, throughBase } = built;
173052
+ const sameCatalogReads = built.sameCatalogReads ?? [];
171933
173053
  const optOutIDs = new Set;
171934
173054
  for (const node of servedMap.nodes()) {
171935
173055
  if (optsOutOfPersist(node.def)) {
@@ -171941,7 +173061,9 @@ class ServedCopyServe {
171941
173061
  if (!l.crossConnection)
171942
173062
  continue;
171943
173063
  const sourceName = l.declaration ?? l.name;
173064
+ const sourceID = l.join === undefined ? candidates.find((c) => c.reroot.sourceName === sourceName && c.reroot.url === l.url)?.reroot.sourceID : undefined;
171944
173065
  problems.push({
173066
+ ...sourceID !== undefined ? { storedSourceID: sourceID } : {},
171945
173067
  sourceName,
171946
173068
  reason: "cross_connection_join",
171947
173069
  join: l.join ?? l.name,
@@ -171996,6 +173118,15 @@ class ServedCopyServe {
171996
173118
  rerooted,
171997
173119
  rerootedSourceIDs: rerootedSourceIDsOf(candidates, throughBase),
171998
173120
  ...throughBase.length > 0 ? { throughBase } : {},
173121
+ ...sameCatalogReads.length > 0 ? {
173122
+ sameCatalogRecheck: async () => {
173123
+ const readable = this.host.sameCatalogTablesReadable;
173124
+ if (!readable)
173125
+ return false;
173126
+ const each = await Promise.all(sameCatalogReads.map((r) => readable(config, r)));
173127
+ return each.every(Boolean);
173128
+ }
173129
+ } : {},
171999
173130
  aliased,
172000
173131
  problems,
172001
173132
  pairs: candidates.flatMap((c) => c.reroot.pair ? [
@@ -173136,7 +174267,7 @@ function zonedTruncations(columns, def, fieldsByName, chainZone, restatesStageZo
173136
174267
  restated: []
173137
174268
  };
173138
174269
  }
173139
- var NOTHING_PINNED, NO_DESTINATIONS = () => new MalloyConfig4({ connections: {} }), PAIR_BLOCKS_DETAIL = "The table stores more than one inlined join_many, one block of rows each, and the query reads more than one of them (live aggregates each by its own key over their cross product, which no block holds), so it is answered without this table.", LEFT_OUT_JOIN_DETAIL = "The query uses a join to a source on another connection than the destination this table is stored in, so it is answered live.", MISSING_FIELD_CODES, SERVED_COPY_WARNING_CODE = "served-copy-not-served", DECLINED_LIMIT = 1000, knownRerootFailures, REROOT_FAILURE_TTL_MS, ESCAPED_FAILURE_RETRY_MS = 30000, REROOT_FAILURES_PER_CONFIG = 64, GATE_GRAFT_DECLINE, HIDDEN_COLUMN = "a hidden column", JOIN_DEPTH_LIMIT = 8;
174270
+ var NOTHING_PINNED, NO_DESTINATIONS = () => new MalloyConfig4({ connections: {} }), PAIR_BLOCKS_DETAIL = "The table stores more than one inlined join_many, one block of rows each, and the query reads more than one of them (live aggregates each by its own key over their cross product, which no block holds), so it is answered without this table.", MISSING_FIELD_CODES, SERVED_COPY_WARNING_CODE = "served-copy-not-served", DECLINED_LIMIT = 1000, knownRerootFailures, REROOT_FAILURE_TTL_MS, ESCAPED_FAILURE_RETRY_MS = 30000, REROOT_FAILURES_PER_CONFIG = 64, GATE_GRAFT_DECLINE, HIDDEN_COLUMN = "a hidden column", JOIN_DEPTH_LIMIT = 8;
173140
174271
  var init_served_copy_serve = __esm(() => {
173141
174272
  init_ducklake_catalog_unavailable();
173142
174273
  init_served_copy_lanes();
@@ -173145,6 +174276,7 @@ var init_served_copy_serve = __esm(() => {
173145
174276
  init_filter_binding_guard();
173146
174277
  init_authorize();
173147
174278
  init_overlay_key();
174279
+ init_sql_embed_reads();
173148
174280
  init_event_loop_yield();
173149
174281
  init_package_files();
173150
174282
  init_source_map();
@@ -173172,6 +174304,8 @@ var init_served_copy_serve = __esm(() => {
173172
174304
  init_utils();
173173
174305
  init_served_copy_checks();
173174
174306
  init_query_walks();
174307
+ init_same_catalog_reads();
174308
+ init_same_catalog_destination();
173175
174309
  init_chain_string_reads();
173176
174310
  NOTHING_PINNED = pin(EMPTY_SNAPSHOT, new Date(0));
173177
174311
  MISSING_FIELD_CODES = new Set([
@@ -173307,6 +174441,92 @@ var init_storage_bindings = __esm(() => {
173307
174441
  init_stored_column_types();
173308
174442
  });
173309
174443
 
174444
+ // src/service/materialization/domain/source_decline.ts
174445
+ function byActionability(reasons) {
174446
+ const rank = (r) => {
174447
+ const at = ACTIONABLE_ORDER.indexOf(r);
174448
+ return at < 0 ? ACTIONABLE_ORDER.length : at;
174449
+ };
174450
+ return [...new Set(reasons)].map((r, i) => ({ r, i })).sort((a, b) => rank(a.r) - rank(b.r) || a.i - b.i).map((x) => x.r);
174451
+ }
174452
+ function servesInPart(reason) {
174453
+ const row = SOURCE_DECLINES[reason];
174454
+ return row.servesInPart === true;
174455
+ }
174456
+ function servedCopyOutcomes(problems, rerootedSourceIDs) {
174457
+ const bySource = new Map;
174458
+ const out = [];
174459
+ for (const p of problems) {
174460
+ const key = p.sourceID !== undefined ? `id:${p.sourceID}` : p.sourceName !== undefined ? `name:${p.sourceName}` : undefined;
174461
+ if (key === undefined) {
174462
+ out.push({ outcome: "declined", reason: p.reason });
174463
+ continue;
174464
+ }
174465
+ const reasons = bySource.get(key) ?? [];
174466
+ reasons.push(p.reason);
174467
+ bySource.set(key, reasons);
174468
+ }
174469
+ for (const [key, reasons] of bySource) {
174470
+ const leavesOut = reasons.find((r) => !servesInPart(r));
174471
+ if (leavesOut !== undefined) {
174472
+ out.push({ outcome: "declined", reason: leavesOut });
174473
+ continue;
174474
+ }
174475
+ const stillServed = key.startsWith("id:") && rerootedSourceIDs.has(key.slice(3));
174476
+ out.push({
174477
+ outcome: stillServed ? "partial" : "declined",
174478
+ reason: reasons[0]
174479
+ });
174480
+ }
174481
+ return out;
174482
+ }
174483
+ var SOURCE_DECLINES, SQL_EMBED_FIX, ACTIONABLE_ORDER, SOURCE_DECLINE_REASONS;
174484
+ var init_source_decline = __esm(() => {
174485
+ SOURCE_DECLINES = {
174486
+ build_plan_unavailable: { stage: "bind" },
174487
+ refused: { stage: "bind" },
174488
+ missing_table: { stage: "bind" },
174489
+ unquotable_name: { stage: "bind" },
174490
+ compile_failed: { stage: "served_copy" },
174491
+ cross_connection_unbuilt: { stage: "served_copy" },
174492
+ column_types: { stage: "served_copy" },
174493
+ no_declaration: { stage: "served_copy" },
174494
+ definition_not_parsed: { stage: "served_copy" },
174495
+ pair_join_not_found: { stage: "served_copy" },
174496
+ pair_not_compiled: { stage: "served_copy" },
174497
+ fields_not_carried: { stage: "served_copy" },
174498
+ read_terms_not_kept: { stage: "served_copy" },
174499
+ cross_connection_join: { stage: "served_copy", servesInPart: true },
174500
+ inline_join_kept: { stage: "served_copy", servesInPart: true },
174501
+ reroot_not_compiled: { stage: "served_copy" },
174502
+ classification_not_kept: { stage: "served_copy" },
174503
+ sql_embed_cross_connection: { stage: "served_copy" },
174504
+ sql_embed_bare: { stage: "served_copy" }
174505
+ };
174506
+ SQL_EMBED_FIX = {
174507
+ sql_embed_cross_connection: "To serve it, persist the `.sql()` source itself with the same `storage=` as the sources " + "its `%{}` reads: the copy then reads the `.sql()` source's own table, and theirs serve too. " + "Or drop `storage=` from the sources it reads, so they are built in their own database, where " + "its `%{}` reads their tables. On a DuckLake or managed connection, which builds no author SQL " + "and places every table itself, build what it reads into a warehouse table and read that with " + "`.table()`.",
174508
+ sql_embed_bare: "To serve it, embed it as a query, `%{ <source> -> { select: * } }` (whose columns are the " + "source's fields, not its SQL's): in the source's own database the copy then reads its table, " + "and in a storage destination the fix for `sql_embed_cross_connection` applies."
174509
+ };
174510
+ ACTIONABLE_ORDER = [
174511
+ "cross_connection_join",
174512
+ "cross_connection_unbuilt",
174513
+ "sql_embed_cross_connection",
174514
+ "sql_embed_bare",
174515
+ "inline_join_kept",
174516
+ "read_terms_not_kept",
174517
+ "fields_not_carried",
174518
+ "column_types",
174519
+ "classification_not_kept",
174520
+ "pair_join_not_found",
174521
+ "pair_not_compiled",
174522
+ "definition_not_parsed",
174523
+ "compile_failed",
174524
+ "no_declaration",
174525
+ "reroot_not_compiled"
174526
+ ];
174527
+ SOURCE_DECLINE_REASONS = Object.keys(SOURCE_DECLINES);
174528
+ });
174529
+
173310
174530
  // ../../node_modules/cron-parser/dist/fields/types.js
173311
174531
  var require_types3 = __commonJS(function(exports) {
173312
174532
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -180057,6 +181277,33 @@ function deploymentVerdict(s, destination, storageBound) {
180057
181277
  }
180058
181278
  return;
180059
181279
  }
181280
+ function contractLiveVerdict(s) {
181281
+ const { source, facts, subject, live } = s;
181282
+ const judged = facts.contractVerdicts?.get(source.sourceEntityId ?? "");
181283
+ if (!judged)
181284
+ return;
181285
+ const table = {
181286
+ physicalTableName: judged.physicalTableName,
181287
+ ...judged.builtAt ? { builtAt: judged.builtAt } : {}
181288
+ };
181289
+ if (judged.reason === "upstream_unread") {
181290
+ return {
181291
+ ...live("upstream_unread", `${subject}'s table is bound, but the read of a warehouse table ` + `it was built from failed, so whether that table changed since ` + `the build is not known; no query is answered from it until a ` + `read of it succeeds and finds it unchanged.`, [
181292
+ "Restore the warehouse connection, or the catalog read that failed: the package's next manifest bind or rebind reads it again.",
181293
+ "Or reload the package."
181294
+ ]),
181295
+ table
181296
+ };
181297
+ }
181298
+ return judged.reason === "contract_missing" ? {
181299
+ ...live("contract_missing", `${subject}'s table carries no column contract (it was built ` + `before contracts were recorded), so no query is answered ` + `from it until a build rebuilds it in full.`, ["Run a build: the table is rebuilt in full, with its contract."]),
181300
+ table
181301
+ } : {
181302
+ ...live("incompatible", `${subject}'s table no longer matches the column contract its ` + `build recorded (${judged.incompatibility?.code ?? "changed"}: ` + `${(judged.incompatibility?.columns ?? []).join(", ")}), so no ` + `query is answered from it until a build rebuilds it.`, ["Run a build: the table is rebuilt from its source."]),
181303
+ table,
181304
+ ...judged.incompatibility ? { incompatibility: judged.incompatibility } : {}
181305
+ };
181306
+ }
180060
181307
  function boundVerdict(s, storageBound, materialized) {
180061
181308
  const { sourceID, source, facts, origin, tier, subject, live } = s;
180062
181309
  const copy = s.servedCopy ? facts.servedCopyOutcome?.(sourceID) : undefined;
@@ -180064,7 +181311,13 @@ function boundVerdict(s, storageBound, materialized) {
180064
181311
  ...copy && copy.notServedIn.length > 0 ? { notServedIn: copy.notServedIn } : {}
180065
181312
  };
180066
181313
  const base = { ...s.base, ...where };
180067
- const notServed = () => ({
181314
+ const sqlEmbedReasons = new Set((copy?.notServedIn ?? []).flatMap((n) => n.reasons));
181315
+ const onlySqlEmbed = copy !== undefined && copy.notServedIn.length > 0 && [...sqlEmbedReasons].every((r) => r === "sql_embed_cross_connection" || r === "sql_embed_bare");
181316
+ const notServed = () => onlySqlEmbed ? {
181317
+ ...live("served_copy", `${subject}'s table is bound, but a \`.sql()\` source's ` + "`%{}` reads it " + (sqlEmbedReasons.has("sql_embed_bare") ? "whole (`%{ <source> }`), which its stored table " + "cannot be embedded as" : "with SQL that runs on another connection than its " + "table is read on (a storage destination, or a " + "managed catalog read through one), which a `%{}` " + "cannot reach") + ", so no query is answered from it (" + copy.notServedIn.map((n) => n.model).join(", ") + "). The served-copy-not-served warning names the " + "`.sql()` source.", [...sqlEmbedReasons].map((r) => SQL_EMBED_FIX[r])),
181318
+ ...where
181319
+ } : notServedAny();
181320
+ const notServedAny = () => ({
180068
181321
  ...live("served_copy", `${subject}'s table is bound, but no model's served copy reads ` + `it, so no query is answered from it` + (copy && copy.notServedIn.length > 0 ? ` (${copy.notServedIn.map((n) => `${n.model}: ${n.reasons.join(", ")}`).join("; ")})` : "") + `. The served-copy-not-served warning on each model says why.`, origin === "materialize" ? [
180069
181322
  "Fix what the served-copy-not-served warning names, if there is one.",
180070
181323
  "Or drop #(materialize) from it if a source it is built on already answers its queries."
@@ -180077,25 +181330,7 @@ function boundVerdict(s, storageBound, materialized) {
180077
181330
  const stale = () => live("stale", `${subject}'s table is past its freshness window, so no query is ` + `answered from it until a build refreshes it.`, [
180078
181331
  "Run a build, or widen the freshness window, or set its fallback to stale_ok."
180079
181332
  ]);
180080
- const contractVerdict = () => {
180081
- const judged = facts.contractVerdicts?.get(source.sourceEntityId ?? "");
180082
- if (!judged)
180083
- return;
180084
- const table = {
180085
- physicalTableName: judged.physicalTableName,
180086
- ...judged.builtAt ? { builtAt: judged.builtAt } : {}
180087
- };
180088
- return judged.reason === "contract_missing" ? {
180089
- ...live("contract_missing", `${subject}'s table carries no column contract (it was built ` + `before contracts were recorded), so no query is answered ` + `from it until a build rebuilds it in full.`, [
180090
- "Run a build: the table is rebuilt in full, with its contract."
180091
- ]),
180092
- table
180093
- } : {
180094
- ...live("incompatible", `${subject}'s table no longer matches the column contract its ` + `build recorded (${judged.incompatibility?.code ?? "changed"}: ` + `${(judged.incompatibility?.columns ?? []).join(", ")}), so no ` + `query is answered from it until a build rebuilds it.`, ["Run a build: the table is rebuilt from its source."]),
180095
- table,
180096
- ...judged.incompatibility ? { incompatibility: judged.incompatibility } : {}
180097
- };
180098
- };
181333
+ const contractVerdict = () => contractLiveVerdict(s);
180099
181334
  if (tier === "storage") {
180100
181335
  const views = facts.views?.get(sourceID);
180101
181336
  const withViews = views && views.length > 0 ? { views } : {};
@@ -180150,6 +181385,7 @@ function boundVerdict(s, storageBound, materialized) {
180150
181385
  }
180151
181386
  var MATERIALIZATION_UNREACHABLE_CODE = "materialization-unreachable", MATERIALIZATION_DESTINATION_MISSING_CODE = "materialization-destination-missing", MATERIALIZATION_CONNECTION_CANNOT_HOLD_TABLE_CODE = "materialization-connection-cannot-hold-table", MATERIALIZATION_CONTRACT_MISSING_CODE = "materialization-contract-missing", MATERIALIZATION_TABLE_INCOMPATIBLE_CODE = "materialization-table-incompatible", VERDICT_WARNING_CODES;
180152
181387
  var init_serve_verdict = __esm(() => {
181388
+ init_source_decline();
180153
181389
  init_table_plans();
180154
181390
  VERDICT_WARNING_CODES = {
180155
181391
  unreachable: MATERIALIZATION_UNREACHABLE_CODE,
@@ -180187,6 +181423,31 @@ function repeatedJoinOneKeyWarnings(plan, databaseEntries, storageBindings) {
180187
181423
  if (b.rollupKey)
180188
181424
  checks.set(b.virtualHandle, b.rollupKey);
180189
181425
  }
181426
+ const grainJoins = new Map(Object.entries(databaseEntries ?? {}).flatMap(([id, entry]) => entry.keyUniqueness?.grainJoinKeys ? [[id, entry.keyUniqueness.grainJoinKeys]] : []));
181427
+ for (const b of storageBindings) {
181428
+ if (b.grainJoinKeys)
181429
+ grainJoins.set(b.virtualHandle, b.grainJoinKeys);
181430
+ }
181431
+ for (const [sourceEntityId, keys] of grainJoins) {
181432
+ const source = bySourceEntity.get(sourceEntityId);
181433
+ const rollup = source?.preaggregate;
181434
+ if (!rollup)
181435
+ continue;
181436
+ for (const [joinKey, unique] of Object.entries(keys)) {
181437
+ if (unique)
181438
+ continue;
181439
+ const dot = joinKey.indexOf(".");
181440
+ const join = joinKey.slice(0, dot);
181441
+ const keyColumn = joinKey.slice(dot + 1);
181442
+ warnings.push({
181443
+ ...source?.modelPath ? { model: source.modelPath } : {},
181444
+ subject: rollup.baseSourceName,
181445
+ code: ROLLUP_JOIN_ONE_KEY_REPEATED_CODE,
181446
+ severity: "warn",
181447
+ message: `joins \`${join}\` on \`${keyColumn}\`, which the joined ` + `source holds more than once, found by its #(rollup) ` + `rollup's last build (grain ` + `${rollup.grainDimensions.join(", ")}): the rollup was built ` + `over that join_one, so its partials repeat the rows each ` + `key meets. Queries that read nothing through \`${join}\` are ` + `answered live. Fix the data or declare the join as join_many.`
181448
+ });
181449
+ }
181450
+ }
180190
181451
  for (const [sourceEntityId, check] of checks) {
180191
181452
  if (check?.unique !== false || check.keyColumn === undefined)
180192
181453
  continue;
@@ -180392,7 +181653,7 @@ function storageWarnings(plan, mode, databaseFresh = () => false) {
180392
181653
  }
180393
181654
  return warnings;
180394
181655
  }
180395
- function servedCopyWarnings(models, takesInline) {
181656
+ function servedCopyWarnings(models, takesInline, writesStorage) {
180396
181657
  const warnings = [];
180397
181658
  for (const [modelPath, model] of models) {
180398
181659
  const problems = model.servedCopyProblems() ?? [];
@@ -180405,7 +181666,7 @@ function servedCopyWarnings(models, takesInline) {
180405
181666
  code: SERVED_COPY_WARNING_CODE,
180406
181667
  reason: p.reason,
180407
181668
  severity: "warn",
180408
- message: servedCopyProblemMessage(p, keptInline.has(`${p.sourceName}\x00${p.join}`), p.sourceID === undefined || !takesInline ? true : takesInline(p.sourceID))
181669
+ message: servedCopyProblemMessage(p, keptInline.has(`${p.sourceName}\x00${p.join}`), p.sourceID === undefined || !takesInline ? true : takesInline(p.sourceID), writesStorage ? writesStorage(p, modelPath) : true)
180409
181670
  });
180410
181671
  for (const message of p.coverage ?? []) {
180411
181672
  warnings.push({
@@ -180564,11 +181825,11 @@ function fellBackMessage(message) {
180564
181825
  const head = message.slice(0, at);
180565
181826
  return head.endsWith(". ") || head === "" ? `${head}${instead[0].toUpperCase()}${instead.slice(1)}` : `${head}${instead}`;
180566
181827
  }
180567
- function servedCopyProblemMessage(problem, inlinedButKept = false, takesInline = true) {
180568
- const message = servedCopyProblemReasonMessage(problem, inlinedButKept, takesInline);
181828
+ function servedCopyProblemMessage(problem, inlinedButKept = false, takesInline = true, writesStorage = true) {
181829
+ const message = servedCopyProblemReasonMessage(problem, inlinedButKept, takesInline, writesStorage);
180569
181830
  return problem.servedFromDatabase ? fellBackMessage(message) : message;
180570
181831
  }
180571
- function servedCopyProblemReasonMessage(problem, inlinedButKept = false, takesInline = true) {
181832
+ function servedCopyProblemReasonMessage(problem, inlinedButKept = false, takesInline = true, writesStorage = true) {
180572
181833
  const { reason, join } = problem;
180573
181834
  switch (reason) {
180574
181835
  case "compile_failed":
@@ -180594,18 +181855,25 @@ function servedCopyProblemReasonMessage(problem, inlinedButKept = false, takesIn
180594
181855
  return "This source filters by a given in a place its stored table cannot keep, or is filtered and reached here only through a join, so the served copy leaves it as written rather than answer every caller alike.";
180595
181856
  case "fields_not_carried":
180596
181857
  return "This source inherits fields (a measure, view or join declared on the source it is built from) that its stored table does not carry, so the served copy leaves it as written.";
180597
- case "cross_connection_join":
181858
+ case "cross_connection_join": {
181859
+ const orOwnDatabase = (what, drop) => writesStorage ? `, or build ${what} in its own database (drop ${drop})` : "";
180598
181860
  if (problem.leftOutWhole) {
180599
- return `This source's join${join ? ` \`${join}\`` : ""} reads a source the served copy moves to its ` + "storage destination, so the join crosses connections there, and it cannot be left out alone " + "(what reads it cannot be left out with it). The served copy leaves this source out, so its " + "queries are answered live, and the model's other stored sources still serve. To serve it, " + "store this source in the same destination, or build the joined source in its own database " + "(drop `storage=`).";
181861
+ return `This source's join${join ? ` \`${join}\`` : ""} reads a source the served copy moves to its ` + "storage destination, so the join crosses connections there, and it cannot be left out alone " + "(what reads it cannot be left out with it). The served copy leaves this source out, so its " + "queries are answered live, and the model's other stored sources still serve. To serve it, " + "store this source in the same destination" + orOwnDatabase("the joined source", "`storage=`") + ".";
180600
181862
  }
180601
181863
  if (problem.declarerNotStored) {
180602
- return `This source's join${join ? ` \`${join}\`` : ""} reads a source the served copy reads from its ` + "storage destination, which this source's own connection cannot reach. Queries that use the " + "join are answered live; the others are answered as before. To serve them too, store this " + "source in the same destination, or build the joined source in its own database (drop its " + "`storage=`).";
181864
+ return `This source's join${join ? ` \`${join}\`` : ""} reads a source the served copy reads from its ` + "storage destination, which this source's own connection cannot reach. Queries that use the " + "join are answered live; the others are answered as before. To serve them too, store this " + "source in the same destination" + orOwnDatabase("the joined source", "its `storage=`") + ".";
180603
181865
  }
180604
- return `This source is stored in a destination its join${join ? ` \`${join}\`` : ""} cannot reach: ` + "the joined source reads another connection. Queries that use the join are answered live; " + "the others read the stored table. To serve them too, " + (inlinedButKept ? "fix what keeps the inlined join from being answered from its stored columns (the warning on " + "this join says what), materialize the joined source into the same destination, or build this " + "source in its own database (drop `storage=`)." : takesInline ? "inline the join (inline=), materialize the joined source into the same destination, or build " + "this source in its own database (drop `storage=`)." : "materialize the joined source into the same destination, or build this source in its own database (drop `storage=`).");
181866
+ const ownDatabase = orOwnDatabase("this source", "`storage=`");
181867
+ return `This source is stored in a destination its join${join ? ` \`${join}\`` : ""} cannot reach: ` + "the joined source reads another connection. Queries that use the join are answered live; " + "the others read the stored table. To serve them too, " + (inlinedButKept ? "fix what keeps the inlined join from being answered from its stored columns (the warning on " + "this join says what), " + (ownDatabase ? `materialize the joined source into the same destination${ownDatabase}.` : "or materialize the joined source into the same destination.") : takesInline ? "inline the join (inline=)" + (ownDatabase ? `, materialize the joined source into the same destination${ownDatabase}.` : " or materialize the joined source into the same destination.") : `materialize the joined source into the same destination${ownDatabase}.`);
181868
+ }
180605
181869
  case "inline_join_kept":
180606
181870
  return `This source inlines its join${join ? ` \`${join}\`` : ""} (inline=), but its served copy does not compile ` + "with the join answered from the stored columns, so the join is kept as written and every query " + "through it reads the joined source through the join" + compilerReasons(problem.detail) + " A definition that reads the joined source past one hop (a join of the joined source), or reads " + "one of its measures or views, is the usual cause.";
180607
181871
  case "classification_not_kept":
180608
181872
  return "This source's re-root changed what it exposes or how a field is classified, which the load's " + "classification checks flag on the served copy, so its queries are not answered from the " + "stored tables (a Publisher bug; please report it): " + [...problem.leaks ?? [], ...problem.coverage ?? []].join(" ");
181873
+ case "sql_embed_cross_connection":
181874
+ return "This source is read through a `.sql()` source's `%{}`" + (problem.detail ? ` (${problem.detail})` : "") + ", whose SQL runs on its own connection, while its table is read on another (a storage " + "destination, or a managed catalog read through one), which a `%{}` cannot reach. The served copy " + "leaves this source as written, so its queries are answered live, and the model's other stored " + "sources still serve. " + SQL_EMBED_FIX.sql_embed_cross_connection;
181875
+ case "sql_embed_bare":
181876
+ return "This source is embedded whole by a `.sql()` source's `%{}`" + (problem.detail ? ` (${problem.detail})` : "") + ", which Malloy allows only of a source it can compile to SQL, and its stored table is not " + "one. The served copy leaves this source as written, so its queries are answered live, and " + "the model's other stored sources still serve. " + SQL_EMBED_FIX.sql_embed_bare;
180609
181877
  }
180610
181878
  }
180611
181879
  function databaseTableUnreadWarnings(unread, plan, retryPending, storageRetryPending = false) {
@@ -180638,6 +181906,7 @@ function databaseTableUnreadWarnings(unread, plan, retryPending, storageRetryPen
180638
181906
  var MISMATCH_HANDLING_TEXT, ROLLUP_JOIN_ONE_KEY_REPEATED_CODE = "rollup-join-one-key-repeated", CHECK_DOES, TABLE_KEPT_CODE = "table-kept", KEPT_REASON_TEXT, PERSIST_READS_CURRENT_TIME_CODE = "persist-reads-current-time", DATABASE_TABLE_UNREAD_CODE = "database-table-unread", STORAGE_TABLE_UNREAD_CODE = "storage-table-unread", UNREAD_REASON_TEXT;
180639
181907
  var init_package_warnings = __esm(() => {
180640
181908
  init_annotation_reader();
181909
+ init_source_decline();
180641
181910
  init_constants();
180642
181911
  init_classification();
180643
181912
  init_load_gate_text();
@@ -180686,6 +181955,7 @@ class PlanLifecycle {
180686
181955
  connectionsChangedSinceDerived = new Set;
180687
181956
  refreshFailedTransiently = false;
180688
181957
  heldWithdrawn = new Set;
181958
+ heldWithdrawnUnread = new Set;
180689
181959
  stale;
180690
181960
  staleSeq = 0;
180691
181961
  refreshChain = Promise.resolve(true);
@@ -180762,18 +182032,24 @@ class PlanLifecycle {
180762
182032
  set databaseSourceEligibility(databaseSourceEligibility) {
180763
182033
  this.patch({ databaseSourceEligibility });
180764
182034
  }
180765
- withdraw(sourceIDs) {
182035
+ withdraw(sourceIDs, unread = []) {
180766
182036
  const record = this.state.serving;
180767
- if (!record || sourceIDs.length === 0)
182037
+ if (!record)
180768
182038
  return;
180769
- const withdrawn = new Set([
180770
- ...record.withdrawn,
180771
- ...sourceIDs.flatMap((id) => {
180772
- const address = record.plan?.sources[id]?.sourceEntityId;
180773
- return address ? [address] : [];
180774
- })
182039
+ if (sourceIDs.length === 0 && unread.length === 0 && record.withdrawnUnread.size === 0) {
182040
+ return;
182041
+ }
182042
+ const addresses = (ids) => ids.flatMap((id) => {
182043
+ const address = record.plan?.sources[id]?.sourceEntityId;
182044
+ return address ? [address] : [];
182045
+ });
182046
+ const changed = new Set([
182047
+ ...[...record.withdrawn].filter((a) => !record.withdrawnUnread.has(a)),
182048
+ ...addresses(sourceIDs)
180775
182049
  ]);
180776
- const serving = { ...record, withdrawn };
182050
+ const withdrawnUnread = new Set(addresses(unread).filter((a) => !changed.has(a)));
182051
+ const withdrawn = new Set([...changed, ...withdrawnUnread]);
182052
+ const serving = { ...record, withdrawn, withdrawnUnread };
180777
182053
  this.state = {
180778
182054
  ...this.state,
180779
182055
  serving,
@@ -180784,8 +182060,15 @@ class PlanLifecycle {
180784
182060
  get withdrawn() {
180785
182061
  return this.serving().withdrawn;
180786
182062
  }
182063
+ get withdrawnUnread() {
182064
+ return this.serving().withdrawnUnread;
182065
+ }
182066
+ get holdingWithdrawn() {
182067
+ return this.heldWithdrawn.size > 0;
182068
+ }
180787
182069
  holdWithdrawn(hold) {
180788
182070
  this.heldWithdrawn = hold ? new Set(this.withdrawn) : new Set;
182071
+ this.heldWithdrawnUnread = hold ? new Set(this.withdrawnUnread) : new Set;
180789
182072
  }
180790
182073
  servingPlan() {
180791
182074
  return this.state.serving?.plan ?? null;
@@ -180837,6 +182120,7 @@ class PlanLifecycle {
180837
182120
  asOfBuild: outcome.asOfBuild ?? {},
180838
182121
  upstreamSchemas: outcome.upstreamSchemas ?? {},
180839
182122
  withdrawn: new Set(this.heldWithdrawn),
182123
+ withdrawnUnread: new Set(this.heldWithdrawnUnread),
180840
182124
  stringCapabilityReads: outcome.stringCapabilityReads ?? {}
180841
182125
  };
180842
182126
  }
@@ -181017,6 +182301,7 @@ var init_plan_lifecycle = __esm(() => {
181017
182301
  asOfBuild: {},
181018
182302
  upstreamSchemas: {},
181019
182303
  withdrawn: new Set,
182304
+ withdrawnUnread: new Set,
181020
182305
  stringCapabilityReads: {}
181021
182306
  };
181022
182307
  });
@@ -181334,15 +182619,34 @@ function storageTableDecisions(input, tally, tables, decided, storageDecision, f
181334
182619
  }
181335
182620
  }
181336
182621
  const tablesRead = input.storageTablesRead ?? [];
181337
- const first = input.chain.map((id) => tablesRead.find((b) => b.sourceIDs?.includes(id))).find((b) => b !== undefined) ?? tablesRead[0];
182622
+ const own = input.chain.map((id) => tablesRead.find((b) => b.sourceIDs?.includes(id))).find((b) => b !== undefined);
182623
+ const embedded = tablesRead.filter((b) => b.sourceIDs?.some((id) => input.sqlEmbedReach?.has(id)));
182624
+ const answering = own ? [own] : embedded.length > 0 ? embedded : tablesRead.slice(0, 1);
181338
182625
  const placed = storageAnswered || considered.some((c) => c.outcome === "used" || c.reason === "READ_FAILED");
181339
- if (storageDecision.outcome === "used" && first && !placed) {
181340
- const t = stateOfBinding(input, first, freshStorage);
181341
- if (input.runFailed) {
181342
- skip(t, "READ_FAILED");
181343
- } else {
181344
- markUsed(t);
181345
- storageAnswered = true;
182626
+ if (storageDecision.outcome === "used" && !placed) {
182627
+ const named = new Set;
182628
+ for (const b of answering) {
182629
+ const t = stateOfBinding(input, b, freshStorage);
182630
+ if (t.tableId !== undefined) {
182631
+ if (named.has(t.tableId))
182632
+ continue;
182633
+ named.add(t.tableId);
182634
+ }
182635
+ if (input.runFailed) {
182636
+ skip(t, "READ_FAILED");
182637
+ } else if (storageAnswered) {
182638
+ if (t.tableId) {
182639
+ considered.push({
182640
+ tableId: t.tableId,
182641
+ kind: t.kind,
182642
+ ...originField(t),
182643
+ outcome: "used"
182644
+ });
182645
+ }
182646
+ } else {
182647
+ markUsed(t);
182648
+ storageAnswered = true;
182649
+ }
181346
182650
  }
181347
182651
  }
181348
182652
  } else {
@@ -181505,6 +182809,8 @@ function verdictWarningMessage(reason) {
181505
182809
  return "This table's connection cannot hold a table, so its queries are answered live.";
181506
182810
  case "incompatible":
181507
182811
  return "This table no longer matches the column contract its build recorded, so its queries are answered live until a build rebuilds it.";
182812
+ case "upstream_unread":
182813
+ return "A warehouse table this table was built from could not be read, so whether it changed is not known; its queries are answered live until a read of it succeeds.";
181508
182814
  case "contract_missing":
181509
182815
  return "This table carries no column contract, so its queries are answered live until a build rebuilds it in full.";
181510
182816
  case "types_unrecorded":
@@ -181774,88 +183080,14 @@ var MAX_NOT_CONSIDERED = 10, CONTRACT_VERDICTS, FIELD_PATH_SKIPPED_KEYS3;
181774
183080
  var init_query_path = __esm(() => {
181775
183081
  init_array_query();
181776
183082
  init_leg_decline();
181777
- CONTRACT_VERDICTS = new Set(["incompatible", "contract_missing"]);
183083
+ CONTRACT_VERDICTS = new Set([
183084
+ "incompatible",
183085
+ "contract_missing",
183086
+ "upstream_unread"
183087
+ ]);
181778
183088
  FIELD_PATH_SKIPPED_KEYS3 = new Set(["overload", "at"]);
181779
183089
  });
181780
183090
 
181781
- // src/service/materialization/domain/source_decline.ts
181782
- function byActionability(reasons) {
181783
- const rank = (r) => {
181784
- const at = ACTIONABLE_ORDER.indexOf(r);
181785
- return at < 0 ? ACTIONABLE_ORDER.length : at;
181786
- };
181787
- return [...new Set(reasons)].map((r, i) => ({ r, i })).sort((a, b) => rank(a.r) - rank(b.r) || a.i - b.i).map((x) => x.r);
181788
- }
181789
- function servesInPart(reason) {
181790
- const row = SOURCE_DECLINES[reason];
181791
- return row.servesInPart === true;
181792
- }
181793
- function servedCopyOutcomes(problems, rerootedSourceIDs) {
181794
- const bySource = new Map;
181795
- const out = [];
181796
- for (const p of problems) {
181797
- const key = p.sourceID !== undefined ? `id:${p.sourceID}` : p.sourceName !== undefined ? `name:${p.sourceName}` : undefined;
181798
- if (key === undefined) {
181799
- out.push({ outcome: "declined", reason: p.reason });
181800
- continue;
181801
- }
181802
- const reasons = bySource.get(key) ?? [];
181803
- reasons.push(p.reason);
181804
- bySource.set(key, reasons);
181805
- }
181806
- for (const [key, reasons] of bySource) {
181807
- const leavesOut = reasons.find((r) => !servesInPart(r));
181808
- if (leavesOut !== undefined) {
181809
- out.push({ outcome: "declined", reason: leavesOut });
181810
- continue;
181811
- }
181812
- const stillServed = key.startsWith("id:") && rerootedSourceIDs.has(key.slice(3));
181813
- out.push({
181814
- outcome: stillServed ? "partial" : "declined",
181815
- reason: reasons[0]
181816
- });
181817
- }
181818
- return out;
181819
- }
181820
- var SOURCE_DECLINES, ACTIONABLE_ORDER, SOURCE_DECLINE_REASONS;
181821
- var init_source_decline = __esm(() => {
181822
- SOURCE_DECLINES = {
181823
- build_plan_unavailable: { stage: "bind" },
181824
- refused: { stage: "bind" },
181825
- missing_table: { stage: "bind" },
181826
- unquotable_name: { stage: "bind" },
181827
- compile_failed: { stage: "served_copy" },
181828
- cross_connection_unbuilt: { stage: "served_copy" },
181829
- column_types: { stage: "served_copy" },
181830
- no_declaration: { stage: "served_copy" },
181831
- definition_not_parsed: { stage: "served_copy" },
181832
- pair_join_not_found: { stage: "served_copy" },
181833
- pair_not_compiled: { stage: "served_copy" },
181834
- fields_not_carried: { stage: "served_copy" },
181835
- read_terms_not_kept: { stage: "served_copy" },
181836
- cross_connection_join: { stage: "served_copy", servesInPart: true },
181837
- inline_join_kept: { stage: "served_copy", servesInPart: true },
181838
- reroot_not_compiled: { stage: "served_copy" },
181839
- classification_not_kept: { stage: "served_copy" }
181840
- };
181841
- ACTIONABLE_ORDER = [
181842
- "cross_connection_join",
181843
- "cross_connection_unbuilt",
181844
- "inline_join_kept",
181845
- "read_terms_not_kept",
181846
- "fields_not_carried",
181847
- "column_types",
181848
- "classification_not_kept",
181849
- "pair_join_not_found",
181850
- "pair_not_compiled",
181851
- "definition_not_parsed",
181852
- "compile_failed",
181853
- "no_declaration",
181854
- "reroot_not_compiled"
181855
- ];
181856
- SOURCE_DECLINE_REASONS = Object.keys(SOURCE_DECLINES);
181857
- });
181858
-
181859
183091
  // src/service/materialization/serve_verdicts.ts
181860
183092
  import { isSourceDef as isSourceDef13 } from "@malloydata/malloy";
181861
183093
  function declaresMaterialize2(def) {
@@ -184370,15 +185602,18 @@ class PackageMaterialization {
184370
185602
  ...t.builtAt ? { builtAt: t.builtAt } : {}
184371
185603
  });
184372
185604
  }
185605
+ const unread = this.plan.withdrawnUnread;
184373
185606
  for (const id of this.plan.withdrawn) {
184374
185607
  const t = tableOf(id);
184375
185608
  if (!t.physicalTableName)
184376
185609
  continue;
184377
185610
  verdicts.set(id, {
184378
- reason: "incompatible",
184379
185611
  physicalTableName: t.physicalTableName,
184380
185612
  ...t.builtAt ? { builtAt: t.builtAt } : {},
184381
- incompatibility: { code: "upstream_altered", columns: [] }
185613
+ ...unread.has(id) ? { reason: "upstream_unread" } : {
185614
+ reason: "incompatible",
185615
+ incompatibility: { code: "upstream_altered", columns: [] }
185616
+ }
184382
185617
  });
184383
185618
  }
184384
185619
  for (const i of this.observedOutcome.incompatible) {
@@ -184823,7 +186058,11 @@ class PackageMaterialization {
184823
186058
  }
184824
186059
  servedCopyWarnings() {
184825
186060
  const materialized = this.plan.materializePlans;
184826
- return servedCopyWarnings(this.owner.models(), (sourceID) => Object.hasOwn(materialized, sourceID));
186061
+ const buildPlan = this.plan.buildPlan;
186062
+ const planned = buildPlan?.sources ?? {};
186063
+ const writes = (sourceID) => Object.hasOwn(materialized, sourceID) ? materialized[sourceID].persist.storage !== undefined : Object.hasOwn(planned, sourceID) ? planned[sourceID].annotationFields?.storage !== undefined : undefined;
186064
+ const anyWrites = () => !buildPlan || Object.values(materialized).some((m) => m.persist.storage !== undefined) || Object.values(planned).some((s) => (s.origin ?? "persist") === "persist" && s.annotationFields?.storage !== undefined);
186065
+ return servedCopyWarnings(this.owner.models(), (sourceID) => Object.hasOwn(materialized, sourceID), (problem) => (problem.storedSourceID !== undefined ? writes(problem.storedSourceID) : undefined) ?? anyWrites());
184827
186066
  }
184828
186067
  storedColumnTypeWarnings() {
184829
186068
  return storedColumnTypeWarnings(this.owner.models(), this.boundTypeFindings);
@@ -186374,7 +187613,7 @@ function classifyBuildError(err) {
186374
187613
  return true;
186375
187614
  if (isUpstreamMissingError(err))
186376
187615
  return;
186377
- if (err instanceof MaterializationEligibilityError || err instanceof InlinedJoinNotUniqueError || err instanceof ChainedShapeNotCarriedError || err instanceof ModelCompilationError || err instanceof MalloyError6 || err instanceof BadRequestError || err instanceof ConnectionAuthError || err instanceof UnconfiguredConnectionError || err instanceof DestinationNotFoundError) {
187616
+ if (err instanceof MaterializationEligibilityError || err instanceof InlinedJoinNotUniqueError || err instanceof ChainedShapeNotCarriedError || err instanceof ModelCompilationError || err instanceof MalloyError6 || err instanceof BadRequestError || err instanceof ConnectionAuthError || err instanceof UnconfiguredConnectionError || err instanceof DestinationNotFoundError || err instanceof ContainerNotFoundError) {
186378
187617
  return false;
186379
187618
  }
186380
187619
  if (err instanceof ConnectionError)
@@ -187716,7 +188955,174 @@ var init_build_table_names = __esm(() => {
187716
188955
  init_run_plan();
187717
188956
  });
187718
188957
 
188958
+ // src/service/materialization/run/target_container_read.ts
188959
+ async function readTargetContainers(args) {
188960
+ const out = {};
188961
+ const distinct = new Map(args.containers.map((c) => [targetContainerKey(c), c]));
188962
+ const tasks = [...distinct].map(([key, target]) => async () => {
188963
+ out[key] = await readTargetContainerOrUnread(() => args.connection(target.connectionName), target, { timeoutMs: args.timeoutMs });
188964
+ });
188965
+ await runBounded2(tasks, CONTAINER_READ_CONCURRENCY);
188966
+ return out;
188967
+ }
188968
+ async function readTargetContainerOrUnread(connection, target, options = {}) {
188969
+ try {
188970
+ return await withTimeout2((async () => readTargetContainer(await connection(), target.container, options.runOptions))(), options.timeoutMs ?? CONTAINER_READ_TIMEOUT_MS);
188971
+ } catch (err) {
188972
+ logger.warn("A table's container could not be read; nothing is refused or stopped for it", { connectionName: target.connectionName, code: errorCodeOf(err) });
188973
+ return { unread: true };
188974
+ }
188975
+ }
188976
+ async function readTargetContainer(connection, container, runOptions) {
188977
+ const parts = container.split(".").map(unquoted2);
188978
+ if (parts.some((p) => p === ""))
188979
+ return { unread: true };
188980
+ switch (capabilitiesOf(connection.dialectName).containerCatalog) {
188981
+ case "dataset":
188982
+ return readBigQueryDataset(connection, container);
188983
+ case "pg_namespace": {
188984
+ if (parts.length > 2)
188985
+ return { unread: true };
188986
+ const [database, schema] = parts.length === 2 ? parts : [undefined, parts[0]];
188987
+ const row = await countRow(connection, `SELECT row_to_json(p) AS "row" FROM (SELECT current_database() AS db, (SELECT COUNT(*) FROM pg_catalog.pg_namespace WHERE nspname = ${literal2(schema)}) AS n) AS p`, runOptions);
188988
+ if (row === undefined || database !== undefined && String(row.db) !== database) {
188989
+ return { unread: true };
188990
+ }
188991
+ return answer(row);
188992
+ }
188993
+ case "schemata": {
188994
+ if (parts.length > 2)
188995
+ return { unread: true };
188996
+ const [database, schema] = parts.length === 2 ? parts : [undefined, parts[0]];
188997
+ const catalog = database === undefined ? "information_schema" : `"${database.replace(/"/g, '""')}".information_schema`;
188998
+ return answer(await countRow(connection, `SELECT COUNT(*) AS n FROM ${catalog}.schemata WHERE schema_name = ${literal2(schema)}`, runOptions));
188999
+ }
189000
+ case "duckdb_schemas": {
189001
+ if (parts.length > 2)
189002
+ return { unread: true };
189003
+ const where = parts.length === 2 ? `lower(database_name) = lower(${literal2(parts[0])}) AND lower(schema_name) = lower(${literal2(parts[1])})` : `(database_name = current_database() AND lower(schema_name) = lower(${literal2(parts[0])})) OR lower(database_name) = lower(${literal2(parts[0])})`;
189004
+ const sql = `SELECT COUNT(*) AS n FROM duckdb_schemas() WHERE ${where}`;
189005
+ return answer(await runAsInternalStatement(sql, () => countRow(connection, sql, runOptions)));
189006
+ }
189007
+ default:
189008
+ return { unread: true };
189009
+ }
189010
+ }
189011
+ function billingProject(internals) {
189012
+ for (const p of [
189013
+ internals.billingProjectId,
189014
+ internals.bigQuery?.projectId
189015
+ ]) {
189016
+ if (typeof p === "string" && p !== "" && !p.includes("{{"))
189017
+ return p;
189018
+ }
189019
+ return;
189020
+ }
189021
+ async function readBigQueryDataset(connection, container) {
189022
+ const internals = connection;
189023
+ const client = internals.bigQuery;
189024
+ if (!client || typeof client.dataset !== "function") {
189025
+ return { unread: true };
189026
+ }
189027
+ const lastDot = container.lastIndexOf(".");
189028
+ const dataset = unquoted2(container.slice(lastDot + 1));
189029
+ const named = lastDot > 0 ? unquoted2(container.slice(0, lastDot)) : "";
189030
+ const project = named !== "" ? named : billingProject(internals);
189031
+ let metadata;
189032
+ try {
189033
+ [metadata] = await client.dataset(dataset, project !== undefined ? { projectId: project } : {}).getMetadata();
189034
+ } catch (err) {
189035
+ if (isNotFound(err)) {
189036
+ const read = project ?? billingProject(internals);
189037
+ return {
189038
+ notFound: true,
189039
+ ...named === "" && read !== undefined ? { project: read } : {}
189040
+ };
189041
+ }
189042
+ throw err;
189043
+ }
189044
+ const expected = typeof internals.location === "string" ? internals.location : "";
189045
+ const location = typeof metadata?.location === "string" ? metadata.location : "";
189046
+ if (expected !== "" && location !== "" && expected.toLowerCase() !== location.toLowerCase()) {
189047
+ return { otherLocation: { location, expected } };
189048
+ }
189049
+ return { found: true };
189050
+ }
189051
+ function isNotFound(err) {
189052
+ const e = err;
189053
+ if (e?.code === 404)
189054
+ return true;
189055
+ return Array.isArray(e?.errors) && e.errors.some((x) => x?.reason === "notFound");
189056
+ }
189057
+ async function countRow(connection, sql, runOptions) {
189058
+ const result = await connection.runSQL(sql, {
189059
+ ...runOptions,
189060
+ rowLimit: 1
189061
+ });
189062
+ const row = (result.rows ?? [])[0];
189063
+ if (row === undefined)
189064
+ return;
189065
+ return Object.fromEntries(Object.entries(row).map(([k, v]) => [k.toLowerCase(), v]));
189066
+ }
189067
+ function answer(row) {
189068
+ const n = row === undefined ? NaN : Number(row.n);
189069
+ if (!Number.isFinite(n))
189070
+ return { unread: true };
189071
+ return n > 0 ? { found: true } : { notFound: true };
189072
+ }
189073
+ function literal2(value) {
189074
+ return `'${value.replace(/'/g, "''")}'`;
189075
+ }
189076
+ function unquoted2(segment) {
189077
+ const s = segment.trim();
189078
+ return /^(`.*`|".*")$/.test(s) ? s.slice(1, -1) : s;
189079
+ }
189080
+ function withTimeout2(promise, ms) {
189081
+ let timer;
189082
+ return Promise.race([
189083
+ promise,
189084
+ new Promise((_, reject) => {
189085
+ timer = setTimeout(() => reject(new ContainerReadTimeout(ms)), ms);
189086
+ })
189087
+ ]).finally(() => clearTimeout(timer));
189088
+ }
189089
+ async function runBounded2(tasks, limit) {
189090
+ let next = 0;
189091
+ const worker = async () => {
189092
+ while (next < tasks.length) {
189093
+ const task = tasks[next++];
189094
+ await task();
189095
+ }
189096
+ };
189097
+ await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker));
189098
+ }
189099
+ var CONTAINER_READ_TIMEOUT_MS = 15000, CONTAINER_READ_CONCURRENCY = 4, ContainerReadTimeout;
189100
+ var init_target_container_read = __esm(() => {
189101
+ init_error_code();
189102
+ init_logger();
189103
+ init_duckdb_lockdown();
189104
+ init_dialect();
189105
+ init_target_containers();
189106
+ ContainerReadTimeout = class ContainerReadTimeout extends Error {
189107
+ constructor(ms) {
189108
+ super(`the container read timed out after ${ms}ms`);
189109
+ this.name = "ContainerReadTimeout";
189110
+ }
189111
+ };
189112
+ });
189113
+
187719
189114
  // src/service/materialization/run/database_build_strategy.ts
189115
+ async function assertContainerExists(args) {
189116
+ const container = containerOfTableName(args.physicalTableName);
189117
+ if (container === undefined)
189118
+ return;
189119
+ const target = { connectionName: args.connectionName, container };
189120
+ const reading = await readTargetContainerOrUnread(async () => args.connection, target, { runOptions: args.runOptions });
189121
+ if ("notFound" in reading || "otherLocation" in reading) {
189122
+ throw new ContainerNotFoundError(`Source '${args.sourceName}' cannot be built: ` + `${missingContainerReason(target, args.connection.dialectName, reading)}.`);
189123
+ }
189124
+ }
189125
+
187720
189126
  class DatabaseTier {
187721
189127
  tier = "database";
187722
189128
  async build(request) {
@@ -187761,6 +189167,13 @@ class DatabaseTier {
187761
189167
  if (incrementalRefresh) {
187762
189168
  await resetLedger(incrementalRefresh.context, incrementalRefresh.lineage);
187763
189169
  }
189170
+ await assertContainerExists({
189171
+ connection,
189172
+ physicalTableName,
189173
+ connectionName: persistSource.connectionName,
189174
+ sourceName: persistSource.name,
189175
+ runOptions
189176
+ });
187764
189177
  const startTime = performance.now();
187765
189178
  await connection.runSQL(`DROP TABLE IF EXISTS ${quotedStaging}`, runOptions);
187766
189179
  let buildCostBytes;
@@ -188059,6 +189472,9 @@ var init_database_build_strategy = __esm(() => {
188059
189472
  init_build_table_names();
188060
189473
  init_warehouse_sql();
188061
189474
  init_duckdb_lockdown();
189475
+ init_errors2();
189476
+ init_target_containers();
189477
+ init_target_container_read();
188062
189478
  });
188063
189479
 
188064
189480
  // src/service/materialization/run/storage_admin.ts
@@ -188185,6 +189601,9 @@ async function buildFromWarehouse(ctx, refresh) {
188185
189601
  sourceConnection,
188186
189602
  buildSQL: params.storedBuildSQL,
188187
189603
  sourceCarriesAuthorSql: carriesAuthorSql(sourceDefOf(persistSource)),
189604
+ ...environment.managedStorageScope ? {
189605
+ managedScope: async () => sourceConnection.name ? environment.managedStorageScope(sourceConnection.name) : undefined
189606
+ } : {},
188188
189607
  physicalTableName,
188189
189608
  declaredColumns,
188190
189609
  castOptions,
@@ -191746,7 +193165,7 @@ function renderBuildSQL(persistSource, instruction, manifest, builtEntries, plan
191746
193165
  const { lift, reached, reachedIds } = reach;
191747
193166
  const reducedManifest = withoutEntries(manifestExcludingStorage(manifest, builtEntries, planFacts), moved);
191748
193167
  const buildManifest = manifestForCompiler(isStorageBuild ? { ...reducedManifest, strict: false } : reducedManifest, planFacts, reachedIds);
191749
- const wrongTier = Object.entries(builtEntries).filter(([address, entry]) => !entry.storageDestinationName && (address in manifest.buildManifest.entries) && !upstreamEntryIsCurrent(address, entry, planFacts));
193168
+ const wrongTier = Object.entries(builtEntries).filter(([address, entry]) => suppliedAtWrongTier(address, entry, manifest, planFacts));
191750
193169
  const staleMisses = (err) => {
191751
193170
  const message = err instanceof Error ? err.message : String(err);
191752
193171
  return wrongTier.flatMap(([address, entry]) => {
@@ -192030,7 +193449,8 @@ async function buildSource(options, storage) {
192030
193449
  liveCollations: liveCollationsOf(connection, buildSQL, environment.bigqueryBuildCompareBinary ? () => environment.bigqueryBuildCompareBinary({
192031
193450
  connection,
192032
193451
  source: persistSource,
192033
- sql: buildSQL
193452
+ sql: buildSQL,
193453
+ onUnread: (unread) => logBigQueryBuildUnread(persistSource, unread)
192034
193454
  }) : undefined)
192035
193455
  });
192036
193456
  return withExtensionReuse(built, planFacts, persistSource.sourceID);
@@ -192109,6 +193529,21 @@ function reportingDrift(environment, render) {
192109
193529
  throw err;
192110
193530
  }
192111
193531
  }
193532
+ function suppliedAtWrongTier(address, entry, manifest, planFacts) {
193533
+ return !isLegacyFailedEntry(entry) && !entry.storageDestinationName && address in manifest.buildManifest.entries && !upstreamEntryIsCurrent(address, entry, planFacts);
193534
+ }
193535
+ function logBigQueryBuildUnread(source, unread) {
193536
+ logger.warn("BigQuery catalog read did not prove a storage= build's strings byte-exact; its column contract records them compared none, which refuses a storage= table built over it that compares them", {
193537
+ sourceName: source.name,
193538
+ connectionName: source.connectionName,
193539
+ reason: unread.reason,
193540
+ ...unread.project !== undefined ? { project: unread.project } : {},
193541
+ location: unread.location ?? "per-dataset",
193542
+ ...unread.dataset !== undefined ? { dataset: unread.dataset } : {},
193543
+ ...unread.table !== undefined ? { table: unread.table } : {},
193544
+ ...unread.tableType !== undefined ? { tableType: unread.tableType } : {}
193545
+ });
193546
+ }
192112
193547
  var DATABASE2;
192113
193548
  var init_source_build = __esm(() => {
192114
193549
  init_error_code();
@@ -192120,6 +193555,7 @@ var init_source_build = __esm(() => {
192120
193555
  init_run_plan();
192121
193556
  init_author_model();
192122
193557
  init_source_map();
193558
+ init_types3();
192123
193559
  init_column_contract();
192124
193560
  init_table_plans();
192125
193561
  init_database_build_strategy();
@@ -192960,6 +194396,24 @@ async function checkRollupKeys(compiled, persistSource, entry, connection, conne
192960
194396
  };
192961
194397
  }
192962
194398
  }
194399
+ for (const check of groupsBaseRows ? rollupGrainJoinKeyChecksOf(compiled, sourceID) : []) {
194400
+ if (check.connectionName !== connectionName)
194401
+ continue;
194402
+ const record = await checkKeyAndWarn("grain_join", () => DATABASE3.checkKey({ connection }, check), {
194403
+ notRun: "A #(rollup) rollup's grain join key check did not run; queries that read nothing through the join are answered live",
194404
+ notUnique: "A source joined by a #(rollup) rollup's grain holds the join's key more than once; queries that read nothing through the join are answered live"
194405
+ }, {
194406
+ rollup: persistSource.name,
194407
+ join: check.join,
194408
+ keyColumn: check.keyColumn
194409
+ });
194410
+ if (record) {
194411
+ keys[contractKeyName("grain_join", check.join, check.keyColumn)] = {
194412
+ unique: record.unique,
194413
+ level: "grain_join"
194414
+ };
194415
+ }
194416
+ }
192963
194417
  const parents = await checkParentKeys(rollupParentKeyChecksOf(compiled, sourceID).filter((check) => groupsBaseRows || check.sourceID !== baseSourceID), connection, connectionName, persistSource.name);
192964
194418
  for (const { check, record } of parents) {
192965
194419
  const subject = relative?.(check.sourceID);
@@ -192975,6 +194429,9 @@ async function checkRollupKeys(compiled, persistSource, entry, connection, conne
192975
194429
  function rollupKeyCheckOf(compiled, sourceID) {
192976
194430
  return compiled.tables[sourceID]?.rollup?.keyCheck;
192977
194431
  }
194432
+ function rollupGrainJoinKeyChecksOf(compiled, sourceID) {
194433
+ return compiled.tables[sourceID]?.rollup?.grainJoinKeyChecks ?? [];
194434
+ }
192978
194435
  function rollupParentKeyChecksOf(compiled, sourceID) {
192979
194436
  return compiled.tables[sourceID]?.rollup?.parentKeyChecks ?? [];
192980
194437
  }
@@ -195399,6 +196856,7 @@ function readingsOf(connection) {
195399
196856
  return readings;
195400
196857
  }
195401
196858
  async function readUpstreamSchemas(args) {
196859
+ const keepLast = args.keepLastOnFailure ?? true;
195402
196860
  const out = {};
195403
196861
  const connections = new Map;
195404
196862
  const digests = new Map;
@@ -195458,8 +196916,8 @@ async function readUpstreamSchemas(args) {
195458
196916
  };
195459
196917
  readings.set(t.cached, reading);
195460
196918
  } else if (reading.unread === "read_failed") {
195461
- const last = readings.get(t.cached);
195462
- logger.warn(last ? "Upstream table's columns could not be read; keeping its last reading" : "Upstream table's columns could not be read; the sources that read it are refused until a read succeeds", { connectionName: t.table.connectionName, reason });
196919
+ const last = keepLast ? readings.get(t.cached) : undefined;
196920
+ logger.warn(last ? "Upstream table's columns could not be read; keeping its last reading" : keepLast ? "Upstream table's columns could not be read; the sources that read it are refused until a read succeeds" : "Upstream table's columns could not be read; it reads as unread", { connectionName: t.table.connectionName, reason });
195463
196921
  if (last)
195464
196922
  reading = last;
195465
196923
  }
@@ -195558,70 +197016,143 @@ var init_upstream_schema_read = __esm(() => {
195558
197016
 
195559
197017
  // src/service/materialization/serve/collation/bigquery_build.ts
195560
197018
  async function bigqueryBuildCompareBinary(args) {
197019
+ const io = catalogIO(args.connection);
197020
+ let read;
195561
197021
  try {
195562
- const read = await bigqueryCollatedPaths({
197022
+ read = await bigqueryCollatedPaths({
195563
197023
  reads: new Map,
195564
- io: catalogIO(args.connection),
197024
+ io,
195565
197025
  connectionName: args.source.connectionName,
195566
197026
  sql: args.sql,
195567
- tables: sourceReads(args.source)
197027
+ tables: sourceReads(args.source),
197028
+ datasetReadLimit: args.datasetReadLimit ?? MAX_BUILD_DATASET_READS
195568
197029
  });
195569
- return read.known && read.collated.size === 0;
195570
197030
  } catch {
197031
+ read = { known: false, unread: { reason: "read_failed" } };
197032
+ }
197033
+ if (!read.known) {
197034
+ args.onUnread?.(withJob(read.unread, io));
195571
197035
  return false;
195572
197036
  }
197037
+ return read.collated.size === 0;
197038
+ }
197039
+ function withJob(unread, io) {
197040
+ let job = {
197041
+ projects: [],
197042
+ location: undefined
197043
+ };
197044
+ try {
197045
+ job = io.jobContext();
197046
+ } catch {}
197047
+ const project = unread.project ?? job.projects[0];
197048
+ return {
197049
+ ...unread,
197050
+ ...project !== undefined ? { project } : {},
197051
+ ...job.location !== undefined ? { location: job.location } : {}
197052
+ };
195573
197053
  }
195574
197054
  async function bigqueryCollatedPaths(args) {
195575
- const unknown = { known: false };
197055
+ const unknown = (unread) => ({ known: false, unread });
195576
197056
  const { sql, tables, connectionName } = args;
197057
+ let at = {};
195577
197058
  try {
195578
197059
  if (/\bcollate\b/i.test(sql))
195579
- return unknown;
197060
+ return unknown({ reason: "collate_in_sql" });
195580
197061
  const catalog = new BigQueryCatalog(args.reads, args.io, connectionName);
195581
197062
  const { job } = catalog;
195582
- if (job.projects.length === 0)
195583
- return unknown;
197063
+ if (job.projects.length === 0) {
197064
+ return unknown({ reason: "no_job_project" });
197065
+ }
195584
197066
  const placed = [];
195585
197067
  for (const t of tables ?? []) {
195586
197068
  if (connectionName !== undefined && t.connectionName !== connectionName) {
195587
- return unknown;
197069
+ return unknown({ reason: "table_on_other_connection" });
195588
197070
  }
195589
197071
  const p = placeTable(t.table, job.projects);
195590
197072
  if (p === undefined)
195591
- return unknown;
197073
+ return unknown({ reason: "table_unplaceable" });
195592
197074
  placed.push(p);
195593
197075
  }
195594
- const clean = async (projects) => {
197076
+ const unclean = async (projects, where = {}) => {
195595
197077
  for (const project of projects) {
195596
197078
  const d = await catalog.collatedDatasets(project);
195597
- if (d === undefined || d.size > 0)
195598
- return false;
197079
+ if (d === undefined) {
197080
+ return { reason: "project_unread", project, ...where };
197081
+ }
197082
+ if (d.size > 0) {
197083
+ return { reason: "project_collated", project, ...where };
197084
+ }
195599
197085
  }
195600
- return true;
197086
+ return;
195601
197087
  };
195602
197088
  if (tables === undefined) {
195603
197089
  const projects = new Set([...job.projects, ...sqlProjects(sql)]);
195604
- return await clean(projects) ? { known: true, collated: new Map, catalog } : unknown;
197090
+ const why = await unclean(projects);
197091
+ return why ? unknown(why) : { known: true, collated: new Map, catalog };
197092
+ }
197093
+ if (new Set(placed.map((t) => t.dataset)).size <= args.datasetReadLimit) {
197094
+ const collated = new Map;
197095
+ for (const t of placed) {
197096
+ const where = { dataset: t.datasetName, table: t.name };
197097
+ at = { project: t.projects[0], ...where };
197098
+ let listed;
197099
+ try {
197100
+ listed = await catalog.datasetTables(t.dataset);
197101
+ } catch {
197102
+ return unknown({ reason: "dataset_unread", ...at });
197103
+ }
197104
+ const datasetTable = listed.get(t.name);
197105
+ if (datasetTable === undefined) {
197106
+ return unknown({ reason: "dataset_table_not_listed", ...at });
197107
+ }
197108
+ if (!TABLE_TYPES.has(datasetTable.type)) {
197109
+ const why = await unclean(t.projects, {
197110
+ ...where,
197111
+ tableType: datasetTable.type
197112
+ });
197113
+ if (why)
197114
+ return unknown(why);
197115
+ continue;
197116
+ }
197117
+ addCollated(collated, datasetTable.collated);
197118
+ }
197119
+ return { known: true, collated, catalog };
195605
197120
  }
195606
197121
  const types = await catalog.tableTypes(placed);
195607
- if (types === undefined)
195608
- return unknown;
197122
+ if (types === undefined) {
197123
+ return unknown({
197124
+ reason: "table_types_unread",
197125
+ project: placed[0]?.projects[0]
197126
+ });
197127
+ }
195609
197128
  const collated = new Map;
195610
197129
  for (const t of placed) {
197130
+ const where = { dataset: t.datasetName, table: t.name };
197131
+ at = { project: t.projects[0], ...where };
195611
197132
  if (types !== "no_region") {
195612
197133
  const type = t.projects.map((p) => types.get(`${p}.${t.datasetName}.${t.name}`)).find((x) => x !== undefined);
195613
- if (type === undefined)
195614
- return unknown;
197134
+ if (type === undefined) {
197135
+ return unknown({ reason: "table_not_listed", ...at });
197136
+ }
195615
197137
  if (!TABLE_TYPES.has(type)) {
195616
- if (!await clean(t.projects))
195617
- return unknown;
197138
+ const why = await unclean(t.projects, {
197139
+ ...where,
197140
+ tableType: type
197141
+ });
197142
+ if (why)
197143
+ return unknown(why);
195618
197144
  continue;
195619
197145
  }
195620
197146
  let inCollated = false;
195621
197147
  for (const p of t.projects) {
195622
197148
  const d = await catalog.collatedDatasets(p);
195623
- if (d === undefined)
195624
- return unknown;
197149
+ if (d === undefined) {
197150
+ return unknown({
197151
+ reason: "project_unread",
197152
+ ...at,
197153
+ project: p
197154
+ });
197155
+ }
195625
197156
  if (d.has(t.datasetName))
195626
197157
  inCollated = true;
195627
197158
  }
@@ -195630,22 +197161,30 @@ async function bigqueryCollatedPaths(args) {
195630
197161
  }
195631
197162
  const datasetTable = (await catalog.datasetTables(t.dataset)).get(t.name);
195632
197163
  if (datasetTable === undefined || !TABLE_TYPES.has(datasetTable.type)) {
195633
- return unknown;
195634
- }
195635
- for (const [path, c] of datasetTable.collated) {
195636
- let set = collated.get(path);
195637
- if (!set) {
195638
- set = new Set;
195639
- collated.set(path, set);
195640
- }
195641
- set.add(c);
197164
+ return unknown({
197165
+ reason: "dataset_table_not_listed",
197166
+ ...at,
197167
+ ...datasetTable ? { tableType: datasetTable.type } : {}
197168
+ });
195642
197169
  }
197170
+ addCollated(collated, datasetTable.collated);
195643
197171
  }
195644
197172
  return { known: true, collated, catalog };
195645
197173
  } catch {
195646
- return unknown;
197174
+ return unknown({ reason: "read_failed", ...at });
197175
+ }
197176
+ }
197177
+ function addCollated(collated, table) {
197178
+ for (const [path, c] of table) {
197179
+ let set = collated.get(path);
197180
+ if (!set) {
197181
+ set = new Set;
197182
+ collated.set(path, set);
197183
+ }
197184
+ set.add(c);
195647
197185
  }
195648
197186
  }
197187
+ var MAX_BUILD_DATASET_READS = 20;
195649
197188
  var init_bigquery_build = __esm(() => {
195650
197189
  init_source_reads();
195651
197190
  init_catalog_io();
@@ -195663,6 +197202,7 @@ var init_materialization = __esm(() => {
195663
197202
  init_manifest_loader();
195664
197203
  init_materialization_scheduler();
195665
197204
  init_upstream_schema_read();
197205
+ init_target_container_read();
195666
197206
  init_served_copy_serve();
195667
197207
  init_bigquery_build();
195668
197208
  });
@@ -369074,6 +370614,7 @@ function getEntitiesFromExplore(explore, docString, relativePath, parentPath, so
369074
370614
  nameOverride = `${joinPath}.${field.name}`;
369075
370615
  }
369076
370616
  const codeEntity = getEntityFromMalloyField(field, entitySource, docString, explore.sourceStructDef?.connection ?? null, explore.sourceStructDef && "tablePath" in explore.sourceStructDef ? explore.sourceStructDef.tablePath ?? null : null, joinMetadata, nameOverride, explore.sourceStructDef?.dialect ?? null);
370617
+ inheritJoinedDoc(codeEntity, field, explore);
369077
370618
  const fingerprint = dimIndexFingerprints.get(makeDimIndexLookupKey(sourceName, field.name));
369078
370619
  if (fingerprint) {
369079
370620
  codeEntity.dim_index_fingerprint = {
@@ -369085,6 +370626,39 @@ function getEntitiesFromExplore(explore, docString, relativePath, parentPath, so
369085
370626
  }
369086
370627
  return entities;
369087
370628
  }
370629
+ function inheritJoinedDoc(entity, field, explore) {
370630
+ if (entity.description !== undefined || field.isExploreField())
370631
+ return;
370632
+ const defs = explore.structDef.fields;
370633
+ const pathOf = (name) => {
370634
+ const e = defs?.find((f) => (f.as ?? f.name) === name)?.e;
370635
+ return e?.node === "field" && Array.isArray(e.path) && e.path.every((p) => typeof p === "string") ? e.path : undefined;
370636
+ };
370637
+ let path = pathOf(field.name);
370638
+ for (let depth = 0;path?.length === 1; depth++) {
370639
+ const link = explore.getFieldByNameIfExists(path[0]);
370640
+ if (depth >= MAX_ALIAS_CHAIN || !link || link.isExploreField() || getAccessModifier(link) !== "public" /* Public */ || getDescriptionFromTags(getTags(link)) !== undefined) {
370641
+ return;
370642
+ }
370643
+ path = pathOf(link.name);
370644
+ }
370645
+ if (path?.length !== 2)
370646
+ return;
370647
+ const [joinName, fieldName] = path;
370648
+ const join = explore.getFieldByNameIfExists(joinName);
370649
+ if (!join?.isExploreField() || getAccessModifier(join) !== "public" /* Public */) {
370650
+ return;
370651
+ }
370652
+ const joined = join.getFieldByNameIfExists(fieldName);
370653
+ if (!joined || joined.isExploreField() || getAccessModifier(joined) !== "public" /* Public */) {
370654
+ return;
370655
+ }
370656
+ const doc = getDescriptionFromTags(getTags(joined));
370657
+ if (doc === undefined)
370658
+ return;
370659
+ entity.description = doc;
370660
+ entity.doc_inherited_from = `${joinName}.${fieldName}`;
370661
+ }
369088
370662
  function planJoinAuthorizeMetadata(explore, docString, relativePath, parentPath, parentAuthorize, sourceToModelPath, topLevelExploreNames, boundary, modelGivens, modelAuthorize, alwaysSeenSourceKeys, guarded, sourceDefsByName) {
369089
370663
  const plan = [];
369090
370664
  const sourceName = composeSourceName(parentPath, explore.name);
@@ -369185,7 +370759,7 @@ function resolveJoinMetadata(plan, nonQueryableSourceNames, rootIsQueryable, see
369185
370759
  resolveJoinMetadata(descend.children, nonQueryableSourceNames, rootIsQueryable, seenSourceKeys, out);
369186
370760
  }
369187
370761
  }
369188
- var extractDocsFromExplore = (explore) => {
370762
+ var MAX_ALIAS_CHAIN = 8, extractDocsFromExplore = (explore) => {
369189
370763
  const parts = getDirectTaglines(explore).map((text) => parseDocAnnotation(text)).filter((doc) => !!doc && doc.length > 0);
369190
370764
  return parts.length > 0 ? parts.join(`
369191
370765
  `) : null;
@@ -369823,6 +371397,9 @@ function toApiField(entity) {
369823
371397
  field.dataType = entity.field_data_type;
369824
371398
  if (entity.description !== undefined)
369825
371399
  field.doc = entity.description;
371400
+ if (entity.doc_inherited_from !== undefined) {
371401
+ field.docInheritedFrom = entity.doc_inherited_from;
371402
+ }
369826
371403
  const join = entity.join_source_metadata;
369827
371404
  if (join) {
369828
371405
  field.join = {
@@ -369953,7 +371530,7 @@ function toApiSources(result) {
369953
371530
  var init_to_api = () => {};
369954
371531
 
369955
371532
  // src/package_load/protocol.ts
369956
- var PACKAGE_LOAD_PROTOCOL_VERSION = 8;
371533
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 10;
369957
371534
 
369958
371535
  // src/package_load/protocol_decode.ts
369959
371536
  function isRecord2(value) {
@@ -370441,7 +372018,10 @@ class PackageLoadPool {
370441
372018
  environmentName: qj.request.environmentName,
370442
372019
  modelPath: qj.request.modelPath,
370443
372020
  defaultConnectionName: qj.request.defaultConnectionName,
370444
- files: [...qj.request.files]
372021
+ files: [...qj.request.files],
372022
+ ...qj.request.virtualMap ? {
372023
+ virtualMap: [...qj.request.virtualMap].map(([connection, handles]) => [connection, [...handles]])
372024
+ } : {}
370445
372025
  };
370446
372026
  pw.worker.postMessage(message);
370447
372027
  return;
@@ -370452,6 +372032,7 @@ class PackageLoadPool {
370452
372032
  connections: qj.request.malloyConfig.connections,
370453
372033
  urlReader: qj.request.urlReader ?? defaultUrlReader,
370454
372034
  ...qj.request.upstreamSchemas ? { upstreamSchemas: qj.request.upstreamSchemas } : {},
372035
+ ...qj.request.targetContainers ? { targetContainers: qj.request.targetContainers } : {},
370455
372036
  resolve: (result) => {
370456
372037
  clearTimeout(timeout);
370457
372038
  const checked = checkLoadPackageResult(result);
@@ -370597,6 +372178,9 @@ class PackageLoadPool {
370597
372178
  case "upstream-schemas":
370598
372179
  this.answerWorker(pw, msg, this.handleUpstreamSchemas(pw, msg));
370599
372180
  return;
372181
+ case "target-containers":
372182
+ this.answerWorker(pw, msg, this.handleTargetContainers(pw, msg));
372183
+ return;
370600
372184
  case "read-url":
370601
372185
  this.answerWorker(pw, msg, this.handleReadUrl(pw, msg));
370602
372186
  return;
@@ -370704,6 +372288,40 @@ class PackageLoadPool {
370704
372288
  });
370705
372289
  }
370706
372290
  }
372291
+ async handleTargetContainers(pw, msg) {
372292
+ const ctx = this.jobs.get(msg.jobId);
372293
+ const reply = (response) => {
372294
+ this.postToWorker(pw, response);
372295
+ };
372296
+ if (!ctx) {
372297
+ reply({
372298
+ type: "rpc-error",
372299
+ requestId: msg.requestId,
372300
+ ok: false,
372301
+ error: { name: "Error", message: `Unknown jobId ${msg.jobId}` }
372302
+ });
372303
+ return;
372304
+ }
372305
+ try {
372306
+ const readings = ctx.targetContainers ? await ctx.targetContainers({
372307
+ containers: msg.containers,
372308
+ connection: async (name) => await ctx.connections.lookupConnection(name)
372309
+ }) : {};
372310
+ reply({
372311
+ type: "target-containers-response",
372312
+ requestId: msg.requestId,
372313
+ ok: true,
372314
+ readings
372315
+ });
372316
+ } catch (error) {
372317
+ reply({
372318
+ type: "rpc-error",
372319
+ requestId: msg.requestId,
372320
+ ok: false,
372321
+ error: serializeError(error)
372322
+ });
372323
+ }
372324
+ }
370707
372325
  async handleUpstreamSchemas(pw, msg) {
370708
372326
  const ctx = this.jobs.get(msg.jobId);
370709
372327
  const reply = (response) => {
@@ -374976,6 +376594,7 @@ async function queryPathFor(host, answer, args) {
374976
376594
  storageWarned: !storageServes(getPersistStorageMode()),
374977
376595
  considered: answer.considered,
374978
376596
  storageTablesRead: routed?.tablesRead?.map(toTable),
376597
+ sqlEmbedReach: host.servedCopy.ownSqlEmbedReach(struct, modelDef),
374979
376598
  ...answer.leg === "rollup" ? {
374980
376599
  rollupTablesRead: answer.answer.shapeBindings.filter((b) => b.kind !== "rollup").map(toTable)
374981
376600
  } : {},
@@ -376489,7 +378108,8 @@ async function compileServedCopyOnWorker(pool, args) {
376489
378108
  modelPath: args.modelPath,
376490
378109
  malloyConfig: args.config,
376491
378110
  defaultConnectionName: DEFAULT_CONNECTION,
376492
- files: args.files
378111
+ files: args.files,
378112
+ ...args.virtualMap ? { virtualMap: args.virtualMap } : {}
376493
378113
  });
376494
378114
  if (!pending)
376495
378115
  return;
@@ -379327,7 +380947,7 @@ class RollupVariantServe {
379327
380947
  const usage = branches.length > 0 ? queryFieldUsagePaths(prepared) : [];
379328
380948
  for (const [i, { branch, refusal }] of branches.entries()) {
379329
380949
  if (zoned) {
379330
- const zone = zoneDecline(branch.plan, SourceMap.of(this.host.modelDef()).node(branch.plan.baseSourceID)?.def, usage === undefined ? undefined : usage.filter((p) => p[0] === branch.join.name).map((p) => p.slice(1)), undefined, branch.plan.grainDimensions.map((d) => [d]));
380950
+ const zone = zoneDecline(branch.plan, SourceMap.of(this.host.modelDef()).node(branch.plan.baseSourceID)?.def, usage === undefined ? undefined : usage.filter((p) => p[0] === branch.join.name).map((p) => p.slice(1)), undefined, branch.plan.grainDimensions.map((d) => d.split(".")));
379331
380951
  if (zone) {
379332
380952
  first ??= zone;
379333
380953
  members.set(branch.plan.rollupSourceName, zone);
@@ -379429,9 +381049,13 @@ class RollupVariantServe {
379429
381049
  if ((recordedTimezoneOf(childDef) ?? "") !== (parentZone ?? "")) {
379430
381050
  throw new LegDecline("rollup_time_zone", `\`${name}\` is read in the query source's time zone, and its rollup was built in its own`, { shapeCheck: true });
379431
381051
  }
379432
- const grain = new Set(plan.grainDimensions);
381052
+ const grain = new Set(plan.grainDimensions.filter((g) => grainPathOf(g) === undefined));
379433
381053
  const measures = new Set(plan.rollupMeasures.map((m) => m.name));
379434
- const coarse = joinGrainDecline(name, q.shape, grain, measures);
381054
+ const coarse = joinGrainDecline(name, q.shape, grain, measures) ?? joinOneDecline(plan, {
381055
+ groupedBy: readThroughJoin(name, q.shape.groupedBy),
381056
+ filteredBy: readThroughJoin(name, q.shape.filteredBy),
381057
+ measures: readThroughJoin(name, q.shape.measures)
381058
+ }, (join) => this.grainJoinKeyUniqueness(plan, join, q.args.pinned));
379435
381059
  if (coarse)
379436
381060
  throw coarse;
379437
381061
  const missing = joinCoverageDecline(name, q.shape, grain, measures);
@@ -379684,16 +381308,10 @@ class RollupVariantServe {
379684
381308
  }
379685
381309
  const measures = new Set(plan.rollupMeasures.map((m) => m.name));
379686
381310
  const dimensions = query.extension ? extensionDimensions(query.extension, plan, measures) : [];
379687
- const grain = new Set([
379688
- ...plan.grainDimensions,
379689
- ...dimensions.map((d) => d.name)
379690
- ]);
379691
- const coarse = grainDecline(shape, grain, measures);
379692
- if (coarse)
379693
- throw coarse;
379694
- const missing = coverageDecline(shape, measures);
379695
- if (missing)
379696
- throw missing;
381311
+ const grain = queryGrainOf(plan, dimensions);
381312
+ const shapeSkip = baseShapeDecline(plan, shape, grain, measures, (join) => this.grainJoinKeyUniqueness(plan, join, args.pinned));
381313
+ if (shapeSkip)
381314
+ throw shapeSkip;
379697
381315
  if (query.zoned) {
379698
381316
  const zone = zoneDecline(plan, query.struct, query.zoned.usage, query.gates);
379699
381317
  if (zone)
@@ -379747,6 +381365,7 @@ class RollupVariantServe {
379747
381365
  }
379748
381366
  const routed = await readPreparedQuery(runnable);
379749
381367
  checkCoverage(plan, queryLevelFacts(routed));
381368
+ annotatedPathDecline(plan, routed.pipeline, query.struct);
379750
381369
  if (query.gates)
379751
381370
  proveGates(plan, query, routed, variant.modelDef);
379752
381371
  proveGivenTerms(query, routed, variant.modelDef);
@@ -379783,6 +381402,15 @@ class RollupVariantServe {
379783
381402
  const id = table?.sourceEntityId;
379784
381403
  return verdictOf(table?.binding ? table.binding.rollupKey?.unique : id === undefined ? undefined : pinned.snapshot.entries[id]?.keyUniqueness?.unique);
379785
381404
  }
381405
+ grainJoinKeyUniqueness(plan, join, pinned) {
381406
+ const keyColumn = SourceMap.of(this.host.modelDef()).joinsOf(plan.baseSourceID).find((j) => j.name === join)?.keyColumn;
381407
+ const table = this.tableOf(plan, pinned);
381408
+ const id = table?.sourceEntityId;
381409
+ if (keyColumn === undefined || table === undefined)
381410
+ return "unknown";
381411
+ const checks = table.binding ? table.binding.grainJoinKeys : id === undefined ? undefined : pinned.snapshot.entries[id]?.keyUniqueness?.grainJoinKeys;
381412
+ return verdictOf(checks?.[`${join}.${keyColumn}`]);
381413
+ }
379786
381414
  parentKeyUniqueness(plan, struct, pinned) {
379787
381415
  const sourceID = struct?.sourceID;
379788
381416
  const id = this.tableOf(plan, pinned)?.sourceEntityId;
@@ -380349,7 +381977,8 @@ function withoutLeftOut(plan, modelDef, leftOut) {
380349
381977
  ...plan,
380350
381978
  rollupMeasures: kept,
380351
381979
  ...plan.internalGrain ? { internalGrain: plan.internalGrain.filter((g) => !gone(g)) } : {},
380352
- ...plan.privateGrain ? { privateGrain: plan.privateGrain.filter((g) => !gone(g)) } : {}
381980
+ ...plan.privateGrain ? { privateGrain: plan.privateGrain.filter((g) => !gone(g)) } : {},
381981
+ ...plan.pathColumns ? { pathColumns: plan.pathColumns.filter((p) => !gone(p.column)) } : {}
380353
381982
  },
380354
381983
  dropped
380355
381984
  };
@@ -380476,7 +382105,7 @@ function parentAlias(plan) {
380476
382105
  function sourceOverRollup(plan, use, servedName, additions) {
380477
382106
  if (use.kind === "base") {
380478
382107
  const extension = additions;
380479
- return `source: ${identifier(use.localName)} is ${identifier(servedName)}${internalPartials(plan)}${reappliedTerms(plan)}${extension}`;
382108
+ return `source: ${identifier(use.localName)} is ${identifier(servedName)}${internalPartials(plan)}${pathRecords(plan)}${reappliedTerms(plan)}${extension}`;
380480
382109
  }
380481
382110
  const { join } = use.branch;
380482
382111
  const keyword = use.branch.relationship === "one" ? "join_one" : "join_many";
@@ -380518,13 +382147,59 @@ function baseFieldNotes(plan, modelDef) {
380518
382147
  function internalPartials(plan) {
380519
382148
  const hidden = [
380520
382149
  ...plan.rollupMeasures.flatMap((m) => m.partials.map((p) => p.column)),
380521
- ...plan.internalGrain ?? []
382150
+ ...plan.internalGrain ?? [],
382151
+ ...storedPathColumns(plan)
380522
382152
  ].map((n) => identifier(n)).join(", ");
380523
382153
  const priv = (plan.privateGrain ?? []).map((n) => identifier(n)).join(", ");
380524
382154
  if (!hidden && !priv)
380525
382155
  return "";
380526
382156
  return ` include {${hidden ? ` internal: ${hidden}` : ""}${priv ? ` private: ${priv}` : ""} public: * }`;
380527
382157
  }
382158
+ function storedPathColumns(plan) {
382159
+ return (plan.pathColumns ?? []).filter((p) => p.column !== p.grain).map((p) => p.column);
382160
+ }
382161
+ function pathRecords(plan) {
382162
+ const byJoin = new Map;
382163
+ for (const p of plan.pathColumns ?? []) {
382164
+ const fields = byJoin.get(p.join) ?? new Map;
382165
+ if (!fields.has(p.field))
382166
+ fields.set(p.field, p);
382167
+ byJoin.set(p.join, fields);
382168
+ }
382169
+ if (byJoin.size === 0)
382170
+ return "";
382171
+ const records = [...byJoin].map(([join, fields]) => {
382172
+ const lines = [...fields.values()].map((p) => {
382173
+ const read = p.timeframe && TIMEFRAMES.has(p.timeframe) ? `${identifier(p.column)}.${p.timeframe}` : identifier(p.column);
382174
+ return ` ${identifier(p.field)} is ${read}`;
382175
+ }).join(`,
382176
+ `);
382177
+ return ` ${identifier(join)} is {
382178
+ ${lines}
382179
+ }`;
382180
+ }).join(`
382181
+ `);
382182
+ return ` extend {
382183
+ dimension:
382184
+ ${records}
382185
+ }`;
382186
+ }
382187
+ function queryGrainOf(plan, dimensions) {
382188
+ return new Set([
382189
+ ...plan.grainDimensions,
382190
+ ...pathGrainEntries(plan).keys(),
382191
+ ...dimensions.map((d) => d.name)
382192
+ ]);
382193
+ }
382194
+ function pathGrainEntries(plan) {
382195
+ const out = new Map;
382196
+ for (const p of plan.pathColumns ?? []) {
382197
+ const path = `${p.join}.${p.field}`;
382198
+ if (!out.has(path))
382199
+ out.set(path, p.grain);
382200
+ }
382201
+ return out;
382202
+ }
380528
382203
  function reappliedTerms(plan) {
380529
382204
  const terms = plan.readTimeTerms ?? [];
380530
382205
  return terms.length > 0 ? ` extend {
@@ -380541,7 +382216,13 @@ function grainColumns(plan, modelDef) {
380541
382216
  }
380542
382217
  }
380543
382218
  const notes = baseFieldNotes(plan, modelDef);
380544
- return plan.grainDimensions.map((name) => {
382219
+ for (const p of plan.pathColumns ?? []) {
382220
+ if (p.column !== p.grain && p.timeframe !== undefined) {
382221
+ timeframes.set(p.column, p.timeframe);
382222
+ }
382223
+ }
382224
+ return plan.grainDimensions.map((grain) => {
382225
+ const name = grainColumnOf(grain);
380545
382226
  const timeframe = timeframes.get(name);
380546
382227
  return {
380547
382228
  name,
@@ -380633,6 +382314,22 @@ function proveGivenTerms(query, routed, variantModelDef) {
380633
382314
  throw contractSkip();
380634
382315
  }
380635
382316
  }
382317
+ function annotatedPathDecline(plan, pipeline, struct) {
382318
+ const annotated = new Map;
382319
+ for (const p of plan.pathColumns ?? []) {
382320
+ if (!p.annotated)
382321
+ continue;
382322
+ const fields = annotated.get(p.join) ?? new Set;
382323
+ fields.add(p.field);
382324
+ annotated.set(p.join, fields);
382325
+ }
382326
+ if (annotated.size === 0)
382327
+ return;
382328
+ const out = annotatedJoinedOutput(pipeline, struct?.fields, annotated);
382329
+ if (out.output || out.unreadable) {
382330
+ throw new LegDecline("rollup_missing_field", out.output ? `the query returns \`${out.output.path.join(".")}\`, whose annotations the rollup's record of stored columns cannot carry; a field under a name of its own (\`group_by: r is ${out.output.path.join(".")}\`), which carries none live either, is served from the rollup` : "the query's output columns cannot be read");
382331
+ }
382332
+ }
380636
382333
  function checkCoverage(plan, levels) {
380637
382334
  if (!levels) {
380638
382335
  throw new LegDecline("rollup_count_semantics", "the query has no stage the rollup can answer");
@@ -380640,6 +382337,8 @@ function checkCoverage(plan, levels) {
380640
382337
  const fanOut = new Set(plan.fanOutDimensions);
380641
382338
  const measureFanOut = new Map(plan.rollupMeasures.map((m) => [m.name, m.fanOutDimensions]));
380642
382339
  const anyMeasureFanOut = new Set(plan.rollupMeasures.flatMap((m) => m.fanOutDimensions));
382340
+ const paths = pathGrainEntries(plan);
382341
+ const grainOfRef = (ref) => ref?.length === 1 ? ref[0] : ref?.length === 2 ? paths.get(ref.join(".")) : undefined;
380643
382342
  const visit = (level, fixedAbove) => {
380644
382343
  if (level.kind !== "reduce") {
380645
382344
  throw new LegDecline("rollup_count_semantics", `a ${level.kind === "project" ? "select:" : level.kind === "index" ? "index:" : `${level.kind}`} stage reads the source's rows, which the rollup does not keep`);
@@ -380664,7 +382363,7 @@ function checkCoverage(plan, levels) {
380664
382363
  if (f.ungrouped && (fanOut.size > 0 || anyMeasureFanOut.size > 0)) {
380665
382364
  throw new LegDecline("rollup_grain_too_coarse", `\`${f.name}\` re-sums across a fan-out dimension of the rollup's grain`);
380666
382365
  }
380667
- const ref = f.ref?.length === 1 ? f.ref[0] : undefined;
382366
+ const ref = grainOfRef(f.ref);
380668
382367
  const named = ref !== undefined ? measureFanOut.get(ref) : undefined;
380669
382368
  if (ref !== undefined && named === undefined)
380670
382369
  grouped.add(ref);
@@ -380771,10 +382470,45 @@ function zoneDecline(plan, struct, usage, gates, extra = []) {
380771
382470
  return [String(field.as ?? field.name), f];
380772
382471
  }));
380773
382472
  const memo = new Map;
382473
+ const storedPaths = pathGrainEntries(plan);
382474
+ const joinOf = (name) => fields.get(name);
382475
+ const joinedOf = (join) => new Map((join.fields ?? []).map((f) => {
382476
+ const field = f;
382477
+ return [String(field.as ?? field.name), f];
382478
+ }));
382479
+ const temporal = (f) => !f || f.join !== undefined || ZONED_TYPES.has(String(f.type));
382480
+ const conditionDependsOnZone = (name) => {
382481
+ const join = joinOf(name);
382482
+ if (!join || join.join === undefined)
382483
+ return true;
382484
+ const joined = joinedOf(join);
382485
+ return hasZonedNode(join.onExpression) || fieldPathsIn(join.onExpression).some((p) => p.length === 1 ? temporal(fields.get(p[0])) : p.length !== 2 || p[0] !== name || temporal(joined.get(p[1])));
382486
+ };
382487
+ const joinedDependsOnZone = (path) => {
382488
+ const join = joinOf(path[0]);
382489
+ if (!join || conditionDependsOnZone(path[0]))
382490
+ return true;
382491
+ const joined = joinedOf(join);
382492
+ const f = joined.get(path[1]);
382493
+ if (!f || f.join !== undefined)
382494
+ return true;
382495
+ if (f.e === undefined) {
382496
+ return f.timeframe !== undefined && ZONED_TYPES.has(String(f.type));
382497
+ }
382498
+ return ZONED_TYPES.has(String(f.type)) || hasZonedNode(f.e) || fieldPathsIn(f.e).some((p) => p.length !== 1 || temporal(joined.get(p[0])) || joined.get(p[0])?.e !== undefined);
382499
+ };
382500
+ const pathJoins = new Set([...storedPaths.keys()].map((p) => p.slice(0, p.indexOf("."))));
382501
+ const conditionRead = (path) => path.length === 2 && pathJoins.has(path[0]) && fieldPathsIn(joinOf(path[0])?.onExpression).some((p) => p.join(".") === path.join("."));
382502
+ const isStoredPath = (path) => path.length === 2 && storedPaths.has(path.join("."));
380774
382503
  const storedDependsOnZone = (path) => {
380775
382504
  const [name] = path;
380776
382505
  if (name === undefined)
380777
382506
  return false;
382507
+ if (isStoredPath(path))
382508
+ return joinedDependsOnZone(path);
382509
+ if (conditionRead(path)) {
382510
+ return conditionDependsOnZone(path[0]);
382511
+ }
380778
382512
  if (path.length !== 1)
380779
382513
  return true;
380780
382514
  const f = fields.get(name);
@@ -380797,6 +382531,8 @@ function zoneDecline(plan, struct, usage, gates, extra = []) {
380797
382531
  const [name] = path;
380798
382532
  if (name === undefined)
380799
382533
  return false;
382534
+ if (isStoredPath(path))
382535
+ return joinedDependsOnZone(path);
380800
382536
  if (path.length !== 1)
380801
382537
  return true;
380802
382538
  const f = fields.get(name);
@@ -380819,6 +382555,27 @@ function grainDecline(shape, grain, measures) {
380819
382555
  }
380820
382556
  return;
380821
382557
  }
382558
+ function baseShapeDecline(plan, shape, grain, measures, keyVerdict) {
382559
+ return grainDecline(shape, grain, measures) ?? coverageDecline(shape, measures) ?? joinOneDecline(plan, shape, keyVerdict);
382560
+ }
382561
+ function joinOneDecline(plan, shape, keyVerdict) {
382562
+ const reads = [...shape.groupedBy, ...shape.filteredBy, ...shape.measures];
382563
+ const measureReads = (name, join) => plan.rollupMeasures.some((m) => m.name === name && m.partials.some((p) => p.leaf.joinPath[0] === join || p.leaf.reads.some((r) => r[0] === join)));
382564
+ let verdict = "unique";
382565
+ let past = false;
382566
+ const unread = (plan.joinOneGrain ?? []).find(({ join, grain, uncovered }) => {
382567
+ if (reads.some((p) => p.startsWith(`${join}.`) || grain.includes(p) || measureReads(p, join))) {
382568
+ return false;
382569
+ }
382570
+ past = uncovered === true;
382571
+ verdict = past ? "unknown" : keyVerdict(join);
382572
+ return !requireUnique(verdict);
382573
+ });
382574
+ if (unread === undefined)
382575
+ return;
382576
+ const why = past ? "the build joined past it, through another join no key check covers, so a repeat there would have inflated the partials it summed" : verdict === "repeated" ? "the rollup's last build found its key held more than once in the joined source, so the partials it summed are inflated" : "its key was not checked unique when the rollup was built, so a repeat would have inflated the partials it summed";
382577
+ return new LegDecline("rollup_count_semantics", `the query reads nothing through \`${unread.join}\`, a join_one the rollup's grain reads (${unread.grain.map((g) => `\`${g}\``).join(", ")}): ${why}, where live, not joining it, counts each row once`, { shapeCheck: true });
382578
+ }
380822
382579
  function coverageDecline(shape, measures) {
380823
382580
  const missing = shape.measures.find((m) => !measures.has(m));
380824
382581
  if (missing !== undefined) {
@@ -380863,6 +382620,7 @@ var init_rollup_variants = __esm(() => {
380863
382620
  init_gate_reads();
380864
382621
  init_read_text();
380865
382622
  init_table_plans();
382623
+ init_inlined_join_text();
380866
382624
  init_source_map();
380867
382625
  init_author_imports();
380868
382626
  init_join_rollup();
@@ -381014,7 +382772,7 @@ function compileErrorLine(message) {
381014
382772
  function malloynbRunQuery(cell) {
381015
382773
  return cell?.type === "code" ? lastRunStatementText(cell.text) : undefined;
381016
382774
  }
381017
- var MALLOY_VERSION, NO_PREAGGREGATE_VIOLATIONS, Model;
382775
+ var MALLOY_VERSION, RENDER_TAG_CODE = "render-tag", RENDER_TAG_CHECK_FAILED_CODE = "render-tag-check-failed", NO_PREAGGREGATE_VIOLATIONS, Model;
381018
382776
  var init_model = __esm(() => {
381019
382777
  init_telemetry();
381020
382778
  init_materialization_metrics();
@@ -381071,6 +382829,8 @@ var init_model = __esm(() => {
381071
382829
  init_model_policy();
381072
382830
  init_model_query_request();
381073
382831
  init_annotation_near_miss();
382832
+ init_managed_catalog_scope();
382833
+ init_same_catalog_tables();
381074
382834
  init_column_contract();
381075
382835
  init_model_query_request();
381076
382836
  init_model_policy();
@@ -382284,6 +384044,8 @@ var init_model = __esm(() => {
382284
384044
  }
382285
384045
  newServedCopy() {
382286
384046
  return new ServedCopyServe({
384047
+ managedTablePathRefusal,
384048
+ sameCatalogTablesReadable,
382287
384049
  authorResultShape: async (queryString, givens) => {
382288
384050
  const materializer = this.modelMaterializer;
382289
384051
  if (!materializer)
@@ -382297,6 +384059,7 @@ var init_model = __esm(() => {
382297
384059
  ensureSharedQueryModel: (materializer) => this.ensureSharedQueryModel(materializer),
382298
384060
  modelPath: () => this.modelPath,
382299
384061
  modelDef: () => this.modelDef,
384062
+ siblingModelDef: (url) => this.siblingModelDefResolver?.(url),
382300
384063
  serveDestinationConfig: () => this.servingDestinationConfig(),
382301
384064
  pinned: () => this.pinNow(),
382302
384065
  compileElsewhere: (args) => compileServedCopyOnWorker(currentPackageLoadPool(), args)
@@ -382548,6 +384311,8 @@ var init_model = __esm(() => {
382548
384311
  const destinations = this.serveDestinationConfig;
382549
384312
  const pinned = pin(makeSnapshot(bindings), new Date(0));
382550
384313
  const copy = new ServedCopyServe({
384314
+ managedTablePathRefusal,
384315
+ sameCatalogTablesReadable,
382551
384316
  modelPath: () => this.modelPath,
382552
384317
  modelDef: () => this.modelDef,
382553
384318
  serveDestinationConfig: () => destinations && storageServes(getPersistStorageMode()) ? () => compileOnlyDestinationConfig(destinations()) : undefined,
@@ -382573,6 +384338,8 @@ var init_model = __esm(() => {
382573
384338
  return out;
382574
384339
  const pinned = pin(makeSnapshot(stored), new Date(0));
382575
384340
  const copy = new ServedCopyServe({
384341
+ managedTablePathRefusal,
384342
+ sameCatalogTablesReadable,
382576
384343
  modelPath: () => this.modelPath,
382577
384344
  modelDef: () => this.modelDef,
382578
384345
  quiet: true,
@@ -383085,14 +384852,25 @@ import {
383085
384852
  MalloyError as MalloyError16,
383086
384853
  Model as MalloyModel
383087
384854
  } from "@malloydata/malloy";
384855
+ function upstreamWithdrawalSentences(withdrawn, among) {
384856
+ const pick = (sources) => among ? sources.filter((s) => among.includes(s)) : sources;
384857
+ const changed = pick(withdrawn.sources);
384858
+ const unread = pick(withdrawn.unread.sources);
384859
+ const out = [];
384860
+ if (changed.length > 0) {
384861
+ out.push(`Upstream table ${withdrawn.tables.join(", ")} changed since the ` + `last build, so ${changed.join(", ")} answer live until a reload ` + `compiles and a run rebuilds them.`);
384862
+ }
384863
+ if (unread.length > 0) {
384864
+ const tables = withdrawn.unread.tables;
384865
+ out.push((tables && tables.length > 0 ? `Upstream table ${tables.join(", ")} could not be read` : `The upstream tables of ${unread.join(", ")} could not be read`) + `, so whether it changed since the last build is not known: ` + `${unread.join(", ")} answer live until a read of it succeeds ` + `and finds it unchanged (the package's next manifest bind or ` + `rebind reads it again) or a reload plans it afresh.`);
384866
+ }
384867
+ return out;
384868
+ }
383088
384869
  function recompileFailedWarning(kept, withdrawn) {
383089
- const live = withdrawn.sources.filter((s) => kept.sources.includes(s));
383090
384870
  const parts = [
383091
- `${kept.modelPath} did not recompile, so its sources ` + `(${kept.sources.join(", ") || "none"}) are served from the model ` + `it last compiled: ${kept.error}`
384871
+ `${kept.modelPath} did not recompile, so its sources ` + `(${kept.sources.join(", ") || "none"}) are served from the model ` + `it last compiled: ${kept.error}`,
384872
+ ...upstreamWithdrawalSentences(withdrawn, kept.sources)
383092
384873
  ];
383093
- if (live.length > 0) {
383094
- parts.push(`Upstream table ${withdrawn.tables.join(", ")} changed since the ` + `last build, so ${live.join(", ")} answer live until a reload ` + `compiles and a run rebuilds them.`);
383095
- }
383096
384874
  return {
383097
384875
  code: MODEL_RECOMPILE_FAILED,
383098
384876
  model: kept.modelPath,
@@ -383113,7 +384891,7 @@ function packageLoadFailureStatus(error) {
383113
384891
  }
383114
384892
  return "error";
383115
384893
  }
383116
- var MODEL_RECOMPILE_FAILED = "model-recompile-failed", COMPUTED_PACKAGE_FIELDS, JOIN_BYPASS_NOTE, Package;
384894
+ var MODEL_RECOMPILE_FAILED = "model-recompile-failed", NOTHING_WITHDRAWN, COMPUTED_PACKAGE_FIELDS, JOIN_BYPASS_NOTE, Package;
383117
384895
  var init_package2 = __esm(() => {
383118
384896
  init_materialization();
383119
384897
  init_malloy_text();
@@ -383169,6 +384947,11 @@ var init_package2 = __esm(() => {
383169
384947
  init_secure_givens();
383170
384948
  init_persist_annotation_validation();
383171
384949
  init_package_load_gates();
384950
+ NOTHING_WITHDRAWN = {
384951
+ sources: [],
384952
+ tables: [],
384953
+ unread: { sources: [], tables: [] }
384954
+ };
383172
384955
  COMPUTED_PACKAGE_FIELDS = [
383173
384956
  "manifestBindingStatus",
383174
384957
  "manifestEntryCount",
@@ -383229,6 +385012,10 @@ var init_package2 = __esm(() => {
383229
385012
  renderTagWarnings = [];
383230
385013
  recompileFailedWarnings = [];
383231
385014
  keptModelStaleness;
385015
+ kept = {
385016
+ models: [],
385017
+ withdrawn: NOTHING_WITHDRAWN
385018
+ };
383232
385019
  compiledFrom = new Map;
383233
385020
  reloadedFor;
383234
385021
  connectionEdits = 0;
@@ -383608,7 +385395,8 @@ var init_package2 = __esm(() => {
383608
385395
  renderTagWarnings.push({
383609
385396
  model: sm.modelPath,
383610
385397
  message: `The load-time checks could not read this model ` + `(${errMessage(hydrateErr)}), so its render-tag and dashboard findings ` + `are unknown rather than clean.`,
383611
- severity: "error"
385398
+ severity: "error",
385399
+ code: RENDER_TAG_CHECK_FAILED_CODE
383612
385400
  });
383613
385401
  models.set(sm.modelPath, placeholder(sm, hydrateErr instanceof Error ? hydrateErr : new Error(String(hydrateErr))));
383614
385402
  continue;
@@ -383635,7 +385423,8 @@ var init_package2 = __esm(() => {
383635
385423
  renderTagWarnings.push({
383636
385424
  model: sm.modelPath,
383637
385425
  message: `The render-tag check did not finish for this model, so ` + `its render-tag findings are unknown rather than clean.`,
383638
- severity: "warn"
385426
+ severity: "warn",
385427
+ code: RENDER_TAG_CHECK_FAILED_CODE
383639
385428
  });
383640
385429
  }
383641
385430
  models.set(sm.modelPath, placeholder(sm, err));
@@ -383648,7 +385437,8 @@ var init_package2 = __esm(() => {
383648
385437
  model: sm.modelPath,
383649
385438
  subject: w.subject,
383650
385439
  message: w.message,
383651
- severity: w.severity
385440
+ severity: w.severity,
385441
+ code: RENDER_TAG_CODE
383652
385442
  });
383653
385443
  }
383654
385444
  const afterHydrateStart = performance.now();
@@ -383705,6 +385495,7 @@ var init_package2 = __esm(() => {
383705
385495
  const dispatchTime = performance.now();
383706
385496
  const workerOutcome = loadOutcomeOrThrow(pool.loadPackage({
383707
385497
  upstreamSchemas: readUpstreamSchemas,
385498
+ targetContainers: readTargetContainers,
383708
385499
  packagePath,
383709
385500
  packageName,
383710
385501
  environmentName,
@@ -384217,6 +386008,7 @@ var init_package2 = __esm(() => {
384217
386008
  return this.mz.refreshBuildPlan(async () => {
384218
386009
  const outcome = await loadOutcomeOrThrow(getPackageLoadPool().loadPackage({
384219
386010
  upstreamSchemas: readUpstreamSchemas,
386011
+ targetContainers: readTargetContainers,
384220
386012
  packagePath: this.packagePath,
384221
386013
  packageName: this.packageName,
384222
386014
  environmentName: this.environmentName,
@@ -384471,27 +386263,94 @@ var init_package2 = __esm(() => {
384471
386263
  async getMalloyConnection(connectionName) {
384472
386264
  return this.malloyConfig.connections.lookupConnection(connectionName);
384473
386265
  }
384474
- async withdrawChangedUpstreams() {
386266
+ async withdrawChangedUpstreams(options = {}) {
386267
+ const plan = this.mz.plan;
386268
+ const unreadBefore = plan.withdrawnUnread;
386269
+ if (options.onlyUnread && unreadBefore.size === 0) {
386270
+ return NOTHING_WITHDRAWN;
386271
+ }
386272
+ let inScope = [];
386273
+ let found;
386274
+ try {
386275
+ inScope = Object.entries(plan.servingPlan()?.sources ?? {}).filter(([, source]) => !options.onlyUnread || source.sourceEntityId !== undefined && unreadBefore.has(source.sourceEntityId));
386276
+ found = await this.readChangedUpstreams(inScope);
386277
+ } catch (error) {
386278
+ logger.warn("Could not read the upstream tables of a model kept from before a failed recompile; its stored tables answer live until a read succeeds", { packageName: this.packageName, error: errMessage(error) });
386279
+ const changedBefore = (id) => id !== undefined && plan.withdrawn.has(id) && !unreadBefore.has(id);
386280
+ const unread = inScope.filter(([, source]) => !changedBefore(source.sourceEntityId) && (source.sourceEntityId !== undefined && unreadBefore.has(source.sourceEntityId) || options.modelPaths === undefined || source.modelPath !== undefined && options.modelPaths.includes(source.modelPath)));
386281
+ found = {
386282
+ changed: [],
386283
+ changedTables: [],
386284
+ unread,
386285
+ unreadTables: undefined
386286
+ };
386287
+ if (unread.length === 0)
386288
+ return NOTHING_WITHDRAWN;
386289
+ }
386290
+ plan.withdraw(found.changed.map(([id]) => id), found.unread.map(([id]) => id));
386291
+ if (options.hold && plan.withdrawn.size > 0)
386292
+ plan.holdWithdrawn(true);
386293
+ const names = (sources) => [...new Set(sources.map(([, s]) => s.name))].sort();
386294
+ return {
386295
+ sources: names(found.changed),
386296
+ tables: found.changedTables,
386297
+ unread: { sources: names(found.unread), tables: found.unreadTables }
386298
+ };
386299
+ }
386300
+ async readChangedUpstreams(sources) {
384475
386301
  const known = this.mz.plan.upstreamSchemas;
384476
- const tables = Object.keys(known).map((key) => {
386302
+ const keys = new Set(sources.flatMap(([, s]) => (s.reads ?? []).map(upstreamTableKey).filter((key) => (key in known))));
386303
+ const tables = [...keys].map((key) => {
384477
386304
  const [connectionName, table] = JSON.parse(key);
384478
386305
  return { connectionName, table };
384479
386306
  });
384480
- if (tables.length === 0)
384481
- return { sources: [], tables: [] };
384482
- const now = await readUpstreamSchemas({
386307
+ const now = tables.length === 0 ? {} : await readUpstreamSchemas({
384483
386308
  tables,
384484
386309
  connection: (name) => this.getMalloyConnection(name),
384485
- refresh: true
386310
+ refresh: true,
386311
+ keepLastOnFailure: false
384486
386312
  });
386313
+ const unreadNow = (t) => {
386314
+ const key = upstreamTableKey(t);
386315
+ if (!(key in known))
386316
+ return false;
386317
+ const reading = now[key];
386318
+ return reading === undefined || "unread" in reading && reading.unread === "read_failed";
386319
+ };
384487
386320
  const moved = (reads, sql) => upstreamSchemaFold(reads, known, sql) !== upstreamSchemaFold(reads, now, sql);
384488
- const withdrawn = Object.entries(this.mz.plan.servingPlan()?.sources ?? {}).filter(([, source]) => source.reads !== undefined && moved(source.reads, source.sql));
384489
- const names = [...new Set(withdrawn.map(([, s]) => s.name))].sort();
384490
- const tableNames = [
384491
- ...new Set(withdrawn.flatMap(([, source]) => (source.reads ?? []).filter((r) => moved([r], source.sql)).map((r) => r.table)))
384492
- ].sort();
384493
- this.mz.plan.withdraw(withdrawn.map(([sourceID]) => sourceID));
384494
- return { sources: names, tables: tableNames };
386321
+ const changed = [];
386322
+ const unread = [];
386323
+ const changedTables = new Set;
386324
+ const unreadTables = new Set;
386325
+ for (const entry of sources) {
386326
+ const [, source] = entry;
386327
+ if (source.reads === undefined)
386328
+ continue;
386329
+ const failed = source.reads.filter(unreadNow);
386330
+ const read = source.reads.filter((t) => !unreadNow(t));
386331
+ const movedTables = read.filter((t) => moved([t], source.sql));
386332
+ if (read.length > 0 && moved(read, source.sql)) {
386333
+ changed.push(entry);
386334
+ for (const t of movedTables)
386335
+ changedTables.add(t.table);
386336
+ } else if (failed.length > 0) {
386337
+ unread.push(entry);
386338
+ for (const t of failed)
386339
+ unreadTables.add(t.table);
386340
+ }
386341
+ }
386342
+ return {
386343
+ changed,
386344
+ changedTables: [...changedTables].sort(),
386345
+ unread,
386346
+ unreadTables: [...unreadTables].sort()
386347
+ };
386348
+ }
386349
+ readTargetContainers(containers) {
386350
+ return readTargetContainers({
386351
+ containers,
386352
+ connection: (name) => this.getMalloyConnection(name)
386353
+ });
384495
386354
  }
384496
386355
  async readUpstreamSchemas(tables, use) {
384497
386356
  const connection = (name) => this.getMalloyConnection(name);
@@ -384587,13 +386446,14 @@ var init_package2 = __esm(() => {
384587
386446
  const compiledFor = Package.compileKeyOf(entries);
384588
386447
  if (options.ifChanged && this.isCompiledFor(compiledFor)) {
384589
386448
  const last = this.reloadedFor;
384590
- if (last.bound === requested && !this.mz.hasUnreadDatabaseTables()) {
386449
+ if (last.bound === requested && !this.mz.hasUnreadDatabaseTables() && this.mz.plan.withdrawnUnread.size === 0) {
384591
386450
  logger.debug("Skipped reloading models: the manifest is unchanged", {
384592
386451
  packageName: this.packageName
384593
386452
  });
384594
386453
  return false;
384595
386454
  }
384596
386455
  const quoted = last.quotedFrom === requested ? last.quoted : await this.quoteBoundTableNames(entries);
386456
+ await this.rereadWithdrawnUpstreams();
384597
386457
  await this.mz.bindCompiled({
384598
386458
  database: quoted,
384599
386459
  databaseAsGiven: true,
@@ -384637,21 +386497,18 @@ var init_package2 = __esm(() => {
384637
386497
  modelPolicy: nextModelPolicy
384638
386498
  }, "placeholder");
384639
386499
  const kept = this.keepLastGoodModels(nextModels, outcome.fileDigests);
384640
- const withdrawn = kept.length > 0 ? await this.withdrawChangedUpstreams().catch((error) => {
384641
- logger.warn("Could not read the upstream tables of a model kept from before a failed recompile", {
384642
- packageName: this.packageName,
384643
- error: errMessage(error)
384644
- });
384645
- return { sources: [], tables: [] };
384646
- }) : { sources: [], tables: [] };
386500
+ const withdrawn = kept.length > 0 ? await this.withdrawChangedUpstreams({
386501
+ modelPaths: kept.map((k) => k.modelPath)
386502
+ }) : await this.withdrawChangedUpstreams(this.mz.plan.holdingWithdrawn ? {} : { onlyUnread: true });
384647
386503
  const discoveryStarted = performance.now();
384648
386504
  const discovery = await this.discoverReportsIn(nextModels, "reload");
384649
386505
  const discoveryMs = performance.now() - discoveryStarted;
384650
386506
  this.models = nextModels;
384651
386507
  this.modelPolicy.handOffTo(nextModelPolicy);
384652
386508
  this.modelPolicy = nextModelPolicy;
386509
+ this.kept = { models: kept, withdrawn };
384653
386510
  this.recompileFailedWarnings = kept.map((k) => recompileFailedWarning(k, withdrawn));
384654
- this.mz.plan.holdWithdrawn(kept.length > 0);
386511
+ this.mz.plan.holdWithdrawn(kept.length > 0 || this.mz.plan.withdrawnUnread.size > 0);
384655
386512
  const compiledFrom = this.compiledFromOf(nextModels, outcome.fileDigests);
384656
386513
  for (const { modelPath } of kept) {
384657
386514
  const prior = this.compiledFrom.get(modelPath);
@@ -384695,6 +386552,28 @@ var init_package2 = __esm(() => {
384695
386552
  this.logEmptyDiscoveryWarnings();
384696
386553
  return true;
384697
386554
  }
386555
+ async rereadWithdrawnUpstreams() {
386556
+ if (this.mz.plan.withdrawnUnread.size === 0)
386557
+ return;
386558
+ const holding = this.mz.plan.holdingWithdrawn;
386559
+ const reread = await this.withdrawChangedUpstreams({ onlyUnread: true });
386560
+ const before = this.kept.withdrawn;
386561
+ const withdrawn = {
386562
+ sources: [...new Set([...before.sources, ...reread.sources])].sort(),
386563
+ tables: [...new Set([...before.tables, ...reread.tables])].sort(),
386564
+ unread: reread.unread
386565
+ };
386566
+ const models = this.kept.models;
386567
+ this.kept = { models, withdrawn };
386568
+ this.recompileFailedWarnings = models.map((k) => recompileFailedWarning(k, withdrawn));
386569
+ this.mz.plan.holdWithdrawn((holding || models.length > 0) && this.mz.plan.withdrawn.size > 0);
386570
+ if (this.keptModelStaleness) {
386571
+ this.keptModelStaleness = {
386572
+ ...this.keptModelStaleness,
386573
+ message: this.recompileFailedWarnings.map((w) => w.message).join(" ")
386574
+ };
386575
+ }
386576
+ }
384698
386577
  keepLastGoodModels(nextModels, digests) {
384699
386578
  const kept = [];
384700
386579
  for (const [modelPath, next] of nextModels) {
@@ -386624,7 +388503,7 @@ async function compilePackageDryRun(ctx) {
386624
388503
  }
386625
388504
  }
386626
388505
  for (const warning of renderTagWarnings) {
386627
- collect([warningAsProblem(warning, "render-tag")], warning.model);
388506
+ collect([warningAsProblem(warning, warning.code ?? RENDER_TAG_CODE)], warning.model);
386628
388507
  }
386629
388508
  for (const warning of reportWarnings) {
386630
388509
  collect([warningAsProblem(warning, warning.code ?? UNCODED_REPORT_FINDING)], warning.model);
@@ -386670,6 +388549,7 @@ async function loadPackageInWorker(ctx) {
386670
388549
  try {
386671
388550
  return await getPackageLoadPool().loadPackage({
386672
388551
  upstreamSchemas: readUpstreamSchemas,
388552
+ targetContainers: readTargetContainers,
386673
388553
  packagePath: ctx.packagePath,
386674
388554
  packageName: ctx.packageName,
386675
388555
  environmentName: ctx.environmentName,
@@ -387318,6 +389198,7 @@ function callerVisibleEvent(event) {
387318
389198
  }
387319
389199
  var STAGING_DIR_NAME2 = ".staging", RETIRED_DIR_NAME = ".retired", MANIFEST_FETCH_TIMEOUT_MS = 15000, REBIND_ATTEMPTS = 3, REBIND_RETRY_MS = 500, RETIRED_CONNECTION_DRAIN_MS = 30000, DESTINATION_READ_FIELDS, getQueryAdmissionRejectionsCounter, getPackageAdmissionRejectionsCounter, STATUS_VERSIONS_RETRY_FIRST_MS = 250, STATUS_VERSIONS_RETRY_CAP_MS = 30000, STATUS_VERSIONS_RETRIES_BEFORE_ERROR = 8, Environment;
387320
389200
  var init_environment = __esm(() => {
389201
+ init_ducklake_catalog();
387321
389202
  init_driver_errors();
387322
389203
  init_materialization_metrics();
387323
389204
  init_report();
@@ -387788,6 +389669,9 @@ var init_environment = __esm(() => {
387788
389669
  async getMalloyConnection(connectionName) {
387789
389670
  return this.malloyConfig.malloyConfig.connections.lookupConnection(connectionName);
387790
389671
  }
389672
+ async managedStorageScope(connectionName) {
389673
+ return managedScopeOf(await this.getMalloyConnection(connectionName), connectionName);
389674
+ }
387791
389675
  getEnvironmentMalloyConfig() {
387792
389676
  return this.malloyConfig.malloyConfig;
387793
389677
  }
@@ -389095,12 +390979,17 @@ var init_environment = __esm(() => {
389095
390979
  } catch (error) {
389096
390980
  logger.error(`Failed to load package ${packageName}`, { error });
389097
390981
  if (existingPackage !== undefined) {
389098
- const withdrawn = refreshSchemas ? await existingPackage.withdrawChangedUpstreams().catch(() => ({ sources: [], tables: [] })) : { sources: [], tables: [] };
390982
+ const withdrawn = refreshSchemas ? await existingPackage.withdrawChangedUpstreams({
390983
+ hold: true
390984
+ }) : undefined;
389099
390985
  const message = redactPgSecrets(error instanceof Error ? error.message : String(error));
389100
390986
  this.transition(packageName, {
389101
390987
  type: "reloadFailed",
389102
390988
  stale: {
389103
- message: withdrawn.sources.length > 0 ? `${message} Upstream table ${withdrawn.tables.join(", ")} changed since the last build, so ${withdrawn.sources.join(", ")} answer live until a reload compiles and a run rebuilds them.` : message,
390989
+ message: [
390990
+ message,
390991
+ ...withdrawn ? upstreamWithdrawalSentences(withdrawn) : []
390992
+ ].join(" "),
389104
390993
  failedAt: new Date().toISOString()
389105
390994
  }
389106
390995
  });
@@ -389310,7 +391199,9 @@ var init_environment = __esm(() => {
389310
391199
  oldPackage
389311
391200
  });
389312
391201
  if (oldPackage !== undefined && this.packages.get(packageName) === oldPackage) {
389313
- const withdrawn = await oldPackage.withdrawChangedUpstreams().catch(() => ({ sources: [], tables: [] }));
391202
+ const withdrawn = await oldPackage.withdrawChangedUpstreams({
391203
+ hold: true
391204
+ });
389314
391205
  if (withdrawn.sources.length > 0) {
389315
391206
  logger.warn("A failed publish found upstream tables changed; their stored tables answer live", {
389316
391207
  environmentName: this.environmentName,
@@ -389318,6 +391209,13 @@ var init_environment = __esm(() => {
389318
391209
  sources: withdrawn.sources
389319
391210
  });
389320
391211
  }
391212
+ if (withdrawn.unread.sources.length > 0) {
391213
+ logger.warn("A failed publish could not read upstream tables; their stored tables answer live until a read succeeds", {
391214
+ environmentName: this.environmentName,
391215
+ packageName,
391216
+ sources: withdrawn.unread.sources
391217
+ });
391218
+ }
389321
391219
  }
389322
391220
  throw err;
389323
391221
  }
@@ -389536,6 +391434,8 @@ var init_environment = __esm(() => {
389536
391434
  const recompiled = (hasDatabase || hadDatabase) && await pkg.reloadAllModels(tableNameManifest, {
389537
391435
  ifChanged: recompile === "if-changed"
389538
391436
  });
391437
+ if (!(hasDatabase || hadDatabase))
391438
+ await pkg.rereadWithdrawnUpstreams();
389539
391439
  if (hasStorage || hadStorage) {
389540
391440
  await pkg.materialization().bindCompiled({
389541
391441
  storage: storageEntries,
@@ -401495,6 +403395,29 @@ function readFieldProvenance(modelDef, sourceName, sourceTextFor) {
401495
403395
  }
401496
403396
  return provenance;
401497
403397
  }
403398
+ function fieldDocs(field, aliasOf, siblings, aliasOfField) {
403399
+ const own = entityDocs(field.annotations);
403400
+ if (field.kind !== "dimension" || own.embedDoc)
403401
+ return own;
403402
+ let path = aliasOf;
403403
+ for (let depth = 0;path !== undefined && !path.includes("."); depth++) {
403404
+ const link = siblings.find((f) => f.kind === "dimension" && memberSegment(f.name) === path);
403405
+ if (depth >= MAX_ALIAS_CHAIN2 || !link)
403406
+ return own;
403407
+ if (entityDocs(link.annotations).embedDoc)
403408
+ return own;
403409
+ path = aliasOfField(link.name);
403410
+ }
403411
+ const parts = path?.split(".") ?? [];
403412
+ if (parts.length !== 2)
403413
+ return own;
403414
+ const join = siblings.find((f) => f.kind === "join" && memberSegment(f.name) === parts[0]);
403415
+ const joined = join?.schema?.fields?.find((f) => f.kind !== "join" && memberSegment(f.name) === parts[1]);
403416
+ if (!join || !joined)
403417
+ return own;
403418
+ const inherited = entityDocs(joined.annotations);
403419
+ return inherited.embedDoc ? { ...inherited, docInheritedFrom: `${join.name}.${joined.name}` } : own;
403420
+ }
401498
403421
  function memberSegment(name) {
401499
403422
  return identifier(name);
401500
403423
  }
@@ -401820,7 +403743,7 @@ async function collectEntities(pkg) {
401820
403743
  name: field.name,
401821
403744
  source: sourceName,
401822
403745
  modelPath,
401823
- ...entityDocs(field.annotations),
403746
+ ...fieldDocs(field, fieldProvenance?.aliasOf, sourceInfo.schema.fields, (name) => provenance.get(name)?.aliasOf),
401824
403747
  ...field.kind === "view" ? {} : {
401825
403748
  dataType: malloyType(field),
401826
403749
  ...classificationOf(lineage, field.name, field.annotations)
@@ -402018,6 +403941,9 @@ function collapseAliases(entities) {
402018
403941
  keep.embedDoc = donor.embedDoc;
402019
403942
  if (donor.docSource)
402020
403943
  keep.docSource = donor.docSource;
403944
+ if (donor.docInheritedFrom) {
403945
+ keep.docInheritedFrom = donor.docInheritedFrom;
403946
+ }
402021
403947
  }
402022
403948
  }
402023
403949
  if (!keep.classifications) {
@@ -402142,7 +404068,7 @@ async function packageIndexOf(indexes, pkg, packageName) {
402142
404068
  });
402143
404069
  return built;
402144
404070
  }
402145
- var SOURCE_DOC_MAX_CHARS = 500, JOIN_DOC_MAX_CHARS = 200, AUTHORED_DOC_ROUTES, MAX_JOIN_PATH_DEPTH = 2, MAX_RECORD_DEPTH2 = 4, MAX_RECORD_MEMBERS_PER_SOURCE = 300, PLAIN_MEMBER_NAME2, JOIN_TOPOLOGY_MAX_DEPTH = 10, ONE_LINE_SUMMARY_MAX_CHARS = 120;
404071
+ var SOURCE_DOC_MAX_CHARS = 500, JOIN_DOC_MAX_CHARS = 200, AUTHORED_DOC_ROUTES, MAX_JOIN_PATH_DEPTH = 2, MAX_ALIAS_CHAIN2 = 8, MAX_RECORD_DEPTH2 = 4, MAX_RECORD_MEMBERS_PER_SOURCE = 300, PLAIN_MEMBER_NAME2, JOIN_TOPOLOGY_MAX_DEPTH = 10, ONE_LINE_SUMMARY_MAX_CHARS = 120;
402146
404072
  var init_package_entities = __esm(() => {
402147
404073
  init_access_gates();
402148
404074
  init_annotation_reader();
@@ -402250,6 +404176,7 @@ function toSourceResults(results, sourceContext, environmentName, packageName, s
402250
404176
  ...r.score !== undefined ? { relevance: r.score } : {},
402251
404177
  ...r.doc ? { description: r.doc } : {},
402252
404178
  ...r.doc && r.docSource ? { description_source: r.docSource } : {},
404179
+ ...r.doc && r.docInheritedFrom ? { description_inherited_from: r.docInheritedFrom } : {},
402253
404180
  ...r.dataType ? { data_type: r.dataType } : {},
402254
404181
  ...r.classifications ? { classifications: r.classifications } : {},
402255
404182
  ...r.classificationInferred ? { classification_inferred: true } : {},
@@ -402330,6 +404257,7 @@ function projectEntity(e, environmentName, packageName) {
402330
404257
  doc: e.doc,
402331
404258
  ...e.embedDoc ? { embedDoc: e.embedDoc } : {},
402332
404259
  ...e.docSource ? { docSource: e.docSource } : {},
404260
+ ...e.docInheritedFrom ? { docInheritedFrom: e.docInheritedFrom } : {},
402333
404261
  ...e.relationship ? { relationship: e.relationship } : {},
402334
404262
  ...e.aliases ? { aliases: e.aliases } : {},
402335
404263
  ...e.joinPath ? { joinPath: e.joinPath } : {},
@@ -402883,6 +404811,7 @@ function buildCatalog(input) {
402883
404811
  doc: e.embedDoc,
402884
404812
  displayDoc: e.doc,
402885
404813
  ...e.docSource ? { docSource: e.docSource } : {},
404814
+ ...e.docInheritedFrom ? { docInheritedFrom: e.docInheritedFrom } : {},
402886
404815
  ...e.dataType ? { dataType: e.dataType } : {},
402887
404816
  ...e.code ? { code: e.code } : {},
402888
404817
  ...e.joinPath ? { joinPath: e.joinPath } : {},
@@ -408163,6 +410092,7 @@ async function place(args, cluster, node, home, homePath, target, matched, warni
408163
410092
  doc,
408164
410093
  ...node.doc ? { embedDoc: node.doc } : {},
408165
410094
  ...node.docSource ? { docSource: node.docSource } : {},
410095
+ ...node.docInheritedFrom ? { docInheritedFrom: node.docInheritedFrom } : {},
408166
410096
  joinPath: path.join("."),
408167
410097
  ...throughFanout(entry.fanout, fieldFanout(node)) ? { relationship: throughFanout(entry.fanout, fieldFanout(node)) } : {},
408168
410098
  ...node.dataType ? { dataType: node.dataType } : {},
@@ -408196,6 +410126,7 @@ function routeRow(args, route) {
408196
410126
  doc: node.displayDoc ? `${node.displayDoc} ${note}` : note,
408197
410127
  ...node.doc ? { embedDoc: node.doc } : {},
408198
410128
  ...node.docSource ? { docSource: node.docSource } : {},
410129
+ ...node.docInheritedFrom ? { docInheritedFrom: node.docInheritedFrom } : {},
408199
410130
  joinPath,
408200
410131
  ...throughFanout(hop?.fanout, fieldFanout(node)) ? { relationship: throughFanout(hop?.fanout, fieldFanout(node)) } : {},
408201
410132
  ...node.dataType ? { dataType: node.dataType } : {},
@@ -458027,7 +459958,7 @@ function _enum(values, params) {
458027
459958
  ...normalizeParams(params)
458028
459959
  });
458029
459960
  }
458030
- function literal(value, params) {
459961
+ function literal3(value, params) {
458031
459962
  return new ZodLiteral({
458032
459963
  type: "literal",
458033
459964
  values: Array.isArray(value) ? value : [value],
@@ -458642,16 +460573,16 @@ var init_types5 = __esm(() => {
458642
460573
  });
458643
460574
  RequestIdSchema = union([string3(), number3().int()]);
458644
460575
  JSONRPCRequestSchema = object({
458645
- jsonrpc: literal(JSONRPC_VERSION),
460576
+ jsonrpc: literal3(JSONRPC_VERSION),
458646
460577
  id: RequestIdSchema,
458647
460578
  ...RequestSchema.shape
458648
460579
  }).strict();
458649
460580
  JSONRPCNotificationSchema = object({
458650
- jsonrpc: literal(JSONRPC_VERSION),
460581
+ jsonrpc: literal3(JSONRPC_VERSION),
458651
460582
  ...NotificationSchema.shape
458652
460583
  }).strict();
458653
460584
  JSONRPCResultResponseSchema = object({
458654
- jsonrpc: literal(JSONRPC_VERSION),
460585
+ jsonrpc: literal3(JSONRPC_VERSION),
458655
460586
  id: RequestIdSchema,
458656
460587
  result: ResultSchema
458657
460588
  }).strict();
@@ -458666,7 +460597,7 @@ var init_types5 = __esm(() => {
458666
460597
  ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
458667
460598
  })(ErrorCode || (ErrorCode = {}));
458668
460599
  JSONRPCErrorResponseSchema = object({
458669
- jsonrpc: literal(JSONRPC_VERSION),
460600
+ jsonrpc: literal3(JSONRPC_VERSION),
458670
460601
  id: RequestIdSchema.optional(),
458671
460602
  error: object({
458672
460603
  code: number3().int(),
@@ -458687,7 +460618,7 @@ var init_types5 = __esm(() => {
458687
460618
  reason: string3().optional()
458688
460619
  });
458689
460620
  CancelledNotificationSchema = NotificationSchema.extend({
458690
- method: literal("notifications/cancelled"),
460621
+ method: literal3("notifications/cancelled"),
458691
460622
  params: CancelledNotificationParamsSchema
458692
460623
  });
458693
460624
  IconSchema = object({
@@ -458764,7 +460695,7 @@ var init_types5 = __esm(() => {
458764
460695
  clientInfo: ImplementationSchema
458765
460696
  });
458766
460697
  InitializeRequestSchema = RequestSchema.extend({
458767
- method: literal("initialize"),
460698
+ method: literal3("initialize"),
458768
460699
  params: InitializeRequestParamsSchema
458769
460700
  });
458770
460701
  ServerCapabilitiesSchema = object({
@@ -458791,11 +460722,11 @@ var init_types5 = __esm(() => {
458791
460722
  instructions: string3().optional()
458792
460723
  });
458793
460724
  InitializedNotificationSchema = NotificationSchema.extend({
458794
- method: literal("notifications/initialized"),
460725
+ method: literal3("notifications/initialized"),
458795
460726
  params: NotificationsParamsSchema.optional()
458796
460727
  });
458797
460728
  PingRequestSchema = RequestSchema.extend({
458798
- method: literal("ping"),
460729
+ method: literal3("ping"),
458799
460730
  params: BaseRequestParamsSchema.optional()
458800
460731
  });
458801
460732
  ProgressSchema = object({
@@ -458809,7 +460740,7 @@ var init_types5 = __esm(() => {
458809
460740
  progressToken: ProgressTokenSchema
458810
460741
  });
458811
460742
  ProgressNotificationSchema = NotificationSchema.extend({
458812
- method: literal("notifications/progress"),
460743
+ method: literal3("notifications/progress"),
458813
460744
  params: ProgressNotificationParamsSchema
458814
460745
  });
458815
460746
  PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
@@ -458836,31 +460767,31 @@ var init_types5 = __esm(() => {
458836
460767
  });
458837
460768
  TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
458838
460769
  TaskStatusNotificationSchema = NotificationSchema.extend({
458839
- method: literal("notifications/tasks/status"),
460770
+ method: literal3("notifications/tasks/status"),
458840
460771
  params: TaskStatusNotificationParamsSchema
458841
460772
  });
458842
460773
  GetTaskRequestSchema = RequestSchema.extend({
458843
- method: literal("tasks/get"),
460774
+ method: literal3("tasks/get"),
458844
460775
  params: BaseRequestParamsSchema.extend({
458845
460776
  taskId: string3()
458846
460777
  })
458847
460778
  });
458848
460779
  GetTaskResultSchema = ResultSchema.merge(TaskSchema);
458849
460780
  GetTaskPayloadRequestSchema = RequestSchema.extend({
458850
- method: literal("tasks/result"),
460781
+ method: literal3("tasks/result"),
458851
460782
  params: BaseRequestParamsSchema.extend({
458852
460783
  taskId: string3()
458853
460784
  })
458854
460785
  });
458855
460786
  GetTaskPayloadResultSchema = ResultSchema.loose();
458856
460787
  ListTasksRequestSchema = PaginatedRequestSchema.extend({
458857
- method: literal("tasks/list")
460788
+ method: literal3("tasks/list")
458858
460789
  });
458859
460790
  ListTasksResultSchema = PaginatedResultSchema.extend({
458860
460791
  tasks: array(TaskSchema)
458861
460792
  });
458862
460793
  CancelTaskRequestSchema = RequestSchema.extend({
458863
- method: literal("tasks/cancel"),
460794
+ method: literal3("tasks/cancel"),
458864
460795
  params: BaseRequestParamsSchema.extend({
458865
460796
  taskId: string3()
458866
460797
  })
@@ -458911,13 +460842,13 @@ var init_types5 = __esm(() => {
458911
460842
  _meta: optional2(looseObject({}))
458912
460843
  });
458913
460844
  ListResourcesRequestSchema = PaginatedRequestSchema.extend({
458914
- method: literal("resources/list")
460845
+ method: literal3("resources/list")
458915
460846
  });
458916
460847
  ListResourcesResultSchema = PaginatedResultSchema.extend({
458917
460848
  resources: array(ResourceSchema)
458918
460849
  });
458919
460850
  ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
458920
- method: literal("resources/templates/list")
460851
+ method: literal3("resources/templates/list")
458921
460852
  });
458922
460853
  ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
458923
460854
  resourceTemplates: array(ResourceTemplateSchema)
@@ -458927,31 +460858,31 @@ var init_types5 = __esm(() => {
458927
460858
  });
458928
460859
  ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
458929
460860
  ReadResourceRequestSchema = RequestSchema.extend({
458930
- method: literal("resources/read"),
460861
+ method: literal3("resources/read"),
458931
460862
  params: ReadResourceRequestParamsSchema
458932
460863
  });
458933
460864
  ReadResourceResultSchema = ResultSchema.extend({
458934
460865
  contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
458935
460866
  });
458936
460867
  ResourceListChangedNotificationSchema = NotificationSchema.extend({
458937
- method: literal("notifications/resources/list_changed"),
460868
+ method: literal3("notifications/resources/list_changed"),
458938
460869
  params: NotificationsParamsSchema.optional()
458939
460870
  });
458940
460871
  SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
458941
460872
  SubscribeRequestSchema = RequestSchema.extend({
458942
- method: literal("resources/subscribe"),
460873
+ method: literal3("resources/subscribe"),
458943
460874
  params: SubscribeRequestParamsSchema
458944
460875
  });
458945
460876
  UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
458946
460877
  UnsubscribeRequestSchema = RequestSchema.extend({
458947
- method: literal("resources/unsubscribe"),
460878
+ method: literal3("resources/unsubscribe"),
458948
460879
  params: UnsubscribeRequestParamsSchema
458949
460880
  });
458950
460881
  ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
458951
460882
  uri: string3()
458952
460883
  });
458953
460884
  ResourceUpdatedNotificationSchema = NotificationSchema.extend({
458954
- method: literal("notifications/resources/updated"),
460885
+ method: literal3("notifications/resources/updated"),
458955
460886
  params: ResourceUpdatedNotificationParamsSchema
458956
460887
  });
458957
460888
  PromptArgumentSchema = object({
@@ -458967,7 +460898,7 @@ var init_types5 = __esm(() => {
458967
460898
  _meta: optional2(looseObject({}))
458968
460899
  });
458969
460900
  ListPromptsRequestSchema = PaginatedRequestSchema.extend({
458970
- method: literal("prompts/list")
460901
+ method: literal3("prompts/list")
458971
460902
  });
458972
460903
  ListPromptsResultSchema = PaginatedResultSchema.extend({
458973
460904
  prompts: array(PromptSchema)
@@ -458977,44 +460908,44 @@ var init_types5 = __esm(() => {
458977
460908
  arguments: record(string3(), string3()).optional()
458978
460909
  });
458979
460910
  GetPromptRequestSchema = RequestSchema.extend({
458980
- method: literal("prompts/get"),
460911
+ method: literal3("prompts/get"),
458981
460912
  params: GetPromptRequestParamsSchema
458982
460913
  });
458983
460914
  TextContentSchema = object({
458984
- type: literal("text"),
460915
+ type: literal3("text"),
458985
460916
  text: string3(),
458986
460917
  annotations: AnnotationsSchema.optional(),
458987
460918
  _meta: record(string3(), unknown()).optional()
458988
460919
  });
458989
460920
  ImageContentSchema = object({
458990
- type: literal("image"),
460921
+ type: literal3("image"),
458991
460922
  data: Base64Schema,
458992
460923
  mimeType: string3(),
458993
460924
  annotations: AnnotationsSchema.optional(),
458994
460925
  _meta: record(string3(), unknown()).optional()
458995
460926
  });
458996
460927
  AudioContentSchema = object({
458997
- type: literal("audio"),
460928
+ type: literal3("audio"),
458998
460929
  data: Base64Schema,
458999
460930
  mimeType: string3(),
459000
460931
  annotations: AnnotationsSchema.optional(),
459001
460932
  _meta: record(string3(), unknown()).optional()
459002
460933
  });
459003
460934
  ToolUseContentSchema = object({
459004
- type: literal("tool_use"),
460935
+ type: literal3("tool_use"),
459005
460936
  name: string3(),
459006
460937
  id: string3(),
459007
460938
  input: record(string3(), unknown()),
459008
460939
  _meta: record(string3(), unknown()).optional()
459009
460940
  });
459010
460941
  EmbeddedResourceSchema = object({
459011
- type: literal("resource"),
460942
+ type: literal3("resource"),
459012
460943
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
459013
460944
  annotations: AnnotationsSchema.optional(),
459014
460945
  _meta: record(string3(), unknown()).optional()
459015
460946
  });
459016
460947
  ResourceLinkSchema = ResourceSchema.extend({
459017
- type: literal("resource_link")
460948
+ type: literal3("resource_link")
459018
460949
  });
459019
460950
  ContentBlockSchema = union([
459020
460951
  TextContentSchema,
@@ -459032,7 +460963,7 @@ var init_types5 = __esm(() => {
459032
460963
  messages: array(PromptMessageSchema)
459033
460964
  });
459034
460965
  PromptListChangedNotificationSchema = NotificationSchema.extend({
459035
- method: literal("notifications/prompts/list_changed"),
460966
+ method: literal3("notifications/prompts/list_changed"),
459036
460967
  params: NotificationsParamsSchema.optional()
459037
460968
  });
459038
460969
  ToolAnnotationsSchema = object({
@@ -459050,12 +460981,12 @@ var init_types5 = __esm(() => {
459050
460981
  ...IconsSchema.shape,
459051
460982
  description: string3().optional(),
459052
460983
  inputSchema: object({
459053
- type: literal("object"),
460984
+ type: literal3("object"),
459054
460985
  properties: record(string3(), AssertObjectSchema).optional(),
459055
460986
  required: array(string3()).optional()
459056
460987
  }).catchall(unknown()),
459057
460988
  outputSchema: object({
459058
- type: literal("object"),
460989
+ type: literal3("object"),
459059
460990
  properties: record(string3(), AssertObjectSchema).optional(),
459060
460991
  required: array(string3()).optional()
459061
460992
  }).catchall(unknown()).optional(),
@@ -459064,7 +460995,7 @@ var init_types5 = __esm(() => {
459064
460995
  _meta: record(string3(), unknown()).optional()
459065
460996
  });
459066
460997
  ListToolsRequestSchema = PaginatedRequestSchema.extend({
459067
- method: literal("tools/list")
460998
+ method: literal3("tools/list")
459068
460999
  });
459069
461000
  ListToolsResultSchema = PaginatedResultSchema.extend({
459070
461001
  tools: array(ToolSchema)
@@ -459082,11 +461013,11 @@ var init_types5 = __esm(() => {
459082
461013
  arguments: record(string3(), unknown()).optional()
459083
461014
  });
459084
461015
  CallToolRequestSchema = RequestSchema.extend({
459085
- method: literal("tools/call"),
461016
+ method: literal3("tools/call"),
459086
461017
  params: CallToolRequestParamsSchema
459087
461018
  });
459088
461019
  ToolListChangedNotificationSchema = NotificationSchema.extend({
459089
- method: literal("notifications/tools/list_changed"),
461020
+ method: literal3("notifications/tools/list_changed"),
459090
461021
  params: NotificationsParamsSchema.optional()
459091
461022
  });
459092
461023
  ListChangedOptionsBaseSchema = object({
@@ -459098,7 +461029,7 @@ var init_types5 = __esm(() => {
459098
461029
  level: LoggingLevelSchema
459099
461030
  });
459100
461031
  SetLevelRequestSchema = RequestSchema.extend({
459101
- method: literal("logging/setLevel"),
461032
+ method: literal3("logging/setLevel"),
459102
461033
  params: SetLevelRequestParamsSchema
459103
461034
  });
459104
461035
  LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
@@ -459107,7 +461038,7 @@ var init_types5 = __esm(() => {
459107
461038
  data: unknown()
459108
461039
  });
459109
461040
  LoggingMessageNotificationSchema = NotificationSchema.extend({
459110
- method: literal("notifications/message"),
461041
+ method: literal3("notifications/message"),
459111
461042
  params: LoggingMessageNotificationParamsSchema
459112
461043
  });
459113
461044
  ModelHintSchema = object({
@@ -459123,7 +461054,7 @@ var init_types5 = __esm(() => {
459123
461054
  mode: _enum(["auto", "required", "none"]).optional()
459124
461055
  });
459125
461056
  ToolResultContentSchema = object({
459126
- type: literal("tool_result"),
461057
+ type: literal3("tool_result"),
459127
461058
  toolUseId: string3().describe("The unique identifier for the corresponding tool call."),
459128
461059
  content: array(ContentBlockSchema).default([]),
459129
461060
  structuredContent: object({}).loose().optional(),
@@ -459156,7 +461087,7 @@ var init_types5 = __esm(() => {
459156
461087
  toolChoice: ToolChoiceSchema.optional()
459157
461088
  });
459158
461089
  CreateMessageRequestSchema = RequestSchema.extend({
459159
- method: literal("sampling/createMessage"),
461090
+ method: literal3("sampling/createMessage"),
459160
461091
  params: CreateMessageRequestParamsSchema
459161
461092
  });
459162
461093
  CreateMessageResultSchema = ResultSchema.extend({
@@ -459172,13 +461103,13 @@ var init_types5 = __esm(() => {
459172
461103
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
459173
461104
  });
459174
461105
  BooleanSchemaSchema = object({
459175
- type: literal("boolean"),
461106
+ type: literal3("boolean"),
459176
461107
  title: string3().optional(),
459177
461108
  description: string3().optional(),
459178
461109
  default: boolean3().optional()
459179
461110
  });
459180
461111
  StringSchemaSchema = object({
459181
- type: literal("string"),
461112
+ type: literal3("string"),
459182
461113
  title: string3().optional(),
459183
461114
  description: string3().optional(),
459184
461115
  minLength: number3().optional(),
@@ -459195,14 +461126,14 @@ var init_types5 = __esm(() => {
459195
461126
  default: number3().optional()
459196
461127
  });
459197
461128
  UntitledSingleSelectEnumSchemaSchema = object({
459198
- type: literal("string"),
461129
+ type: literal3("string"),
459199
461130
  title: string3().optional(),
459200
461131
  description: string3().optional(),
459201
461132
  enum: array(string3()),
459202
461133
  default: string3().optional()
459203
461134
  });
459204
461135
  TitledSingleSelectEnumSchemaSchema = object({
459205
- type: literal("string"),
461136
+ type: literal3("string"),
459206
461137
  title: string3().optional(),
459207
461138
  description: string3().optional(),
459208
461139
  oneOf: array(object({
@@ -459212,7 +461143,7 @@ var init_types5 = __esm(() => {
459212
461143
  default: string3().optional()
459213
461144
  });
459214
461145
  LegacyTitledEnumSchemaSchema = object({
459215
- type: literal("string"),
461146
+ type: literal3("string"),
459216
461147
  title: string3().optional(),
459217
461148
  description: string3().optional(),
459218
461149
  enum: array(string3()),
@@ -459221,19 +461152,19 @@ var init_types5 = __esm(() => {
459221
461152
  });
459222
461153
  SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
459223
461154
  UntitledMultiSelectEnumSchemaSchema = object({
459224
- type: literal("array"),
461155
+ type: literal3("array"),
459225
461156
  title: string3().optional(),
459226
461157
  description: string3().optional(),
459227
461158
  minItems: number3().optional(),
459228
461159
  maxItems: number3().optional(),
459229
461160
  items: object({
459230
- type: literal("string"),
461161
+ type: literal3("string"),
459231
461162
  enum: array(string3())
459232
461163
  }),
459233
461164
  default: array(string3()).optional()
459234
461165
  });
459235
461166
  TitledMultiSelectEnumSchemaSchema = object({
459236
- type: literal("array"),
461167
+ type: literal3("array"),
459237
461168
  title: string3().optional(),
459238
461169
  description: string3().optional(),
459239
461170
  minItems: number3().optional(),
@@ -459250,30 +461181,30 @@ var init_types5 = __esm(() => {
459250
461181
  EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
459251
461182
  PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
459252
461183
  ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
459253
- mode: literal("form").optional(),
461184
+ mode: literal3("form").optional(),
459254
461185
  message: string3(),
459255
461186
  requestedSchema: object({
459256
- type: literal("object"),
461187
+ type: literal3("object"),
459257
461188
  properties: record(string3(), PrimitiveSchemaDefinitionSchema),
459258
461189
  required: array(string3()).optional()
459259
461190
  })
459260
461191
  });
459261
461192
  ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
459262
- mode: literal("url"),
461193
+ mode: literal3("url"),
459263
461194
  message: string3(),
459264
461195
  elicitationId: string3(),
459265
461196
  url: string3().url()
459266
461197
  });
459267
461198
  ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
459268
461199
  ElicitRequestSchema = RequestSchema.extend({
459269
- method: literal("elicitation/create"),
461200
+ method: literal3("elicitation/create"),
459270
461201
  params: ElicitRequestParamsSchema
459271
461202
  });
459272
461203
  ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
459273
461204
  elicitationId: string3()
459274
461205
  });
459275
461206
  ElicitationCompleteNotificationSchema = NotificationSchema.extend({
459276
- method: literal("notifications/elicitation/complete"),
461207
+ method: literal3("notifications/elicitation/complete"),
459277
461208
  params: ElicitationCompleteNotificationParamsSchema
459278
461209
  });
459279
461210
  ElicitResultSchema = ResultSchema.extend({
@@ -459281,11 +461212,11 @@ var init_types5 = __esm(() => {
459281
461212
  content: preprocess((val) => val === null ? undefined : val, record(string3(), union([string3(), number3(), boolean3(), array(string3())])).optional())
459282
461213
  });
459283
461214
  ResourceTemplateReferenceSchema = object({
459284
- type: literal("ref/resource"),
461215
+ type: literal3("ref/resource"),
459285
461216
  uri: string3()
459286
461217
  });
459287
461218
  PromptReferenceSchema = object({
459288
- type: literal("ref/prompt"),
461219
+ type: literal3("ref/prompt"),
459289
461220
  name: string3()
459290
461221
  });
459291
461222
  CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
@@ -459299,7 +461230,7 @@ var init_types5 = __esm(() => {
459299
461230
  }).optional()
459300
461231
  });
459301
461232
  CompleteRequestSchema = RequestSchema.extend({
459302
- method: literal("completion/complete"),
461233
+ method: literal3("completion/complete"),
459303
461234
  params: CompleteRequestParamsSchema
459304
461235
  });
459305
461236
  CompleteResultSchema = ResultSchema.extend({
@@ -459315,14 +461246,14 @@ var init_types5 = __esm(() => {
459315
461246
  _meta: record(string3(), unknown()).optional()
459316
461247
  });
459317
461248
  ListRootsRequestSchema = RequestSchema.extend({
459318
- method: literal("roots/list"),
461249
+ method: literal3("roots/list"),
459319
461250
  params: BaseRequestParamsSchema.optional()
459320
461251
  });
459321
461252
  ListRootsResultSchema = ResultSchema.extend({
459322
461253
  roots: array(RootSchema)
459323
461254
  });
459324
461255
  RootsListChangedNotificationSchema = NotificationSchema.extend({
459325
- method: literal("notifications/roots/list_changed"),
461256
+ method: literal3("notifications/roots/list_changed"),
459326
461257
  params: NotificationsParamsSchema.optional()
459327
461258
  });
459328
461259
  ClientRequestSchema = union([