@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
@@ -197,6 +197,7 @@ function compileInputOf(b) {
197
197
  holdsOnlyUngatedRows: _ungated,
198
198
  retypedColumns: _retyped,
199
199
  rollupKey: _rollupKey,
200
+ grainJoinKeys: _grainJoinKeys,
200
201
  ...read
201
202
  } = b;
202
203
  input = JSON.stringify(read);
@@ -337,6 +338,7 @@ var init_key_check = __esm(() => {
337
338
  pair_level: { nullKey: "fails", onRepeat: "fail_build" },
338
339
  rollup_key: { nullKey: "ignored", onRepeat: "record" },
339
340
  parent_key: { nullKey: "fails", onRepeat: "record" },
341
+ grain_join_key: { nullKey: "ignored", onRepeat: "record" },
340
342
  stored_key: { nullKey: "fails", onRepeat: "record" }
341
343
  };
342
344
  });
@@ -12805,7 +12807,7 @@ function errorMapping(error) {
12805
12807
  function errorReason(error) {
12806
12808
  return resolve(errorMapping(error).reason, error);
12807
12809
  }
12808
- 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;
12810
+ 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;
12809
12811
  var init_errors2 = __esm(() => {
12810
12812
  init_constants();
12811
12813
  init_logger();
@@ -13090,6 +13092,15 @@ var init_errors2 = __esm(() => {
13090
13092
  super(message);
13091
13093
  }
13092
13094
  };
13095
+ ContainerNotFoundError = class ContainerNotFoundError extends Error {
13096
+ get kind() {
13097
+ return "container_not_found";
13098
+ }
13099
+ constructor(message) {
13100
+ super(message);
13101
+ this.name = "ContainerNotFoundError";
13102
+ }
13103
+ };
13093
13104
  StorageDestinationNotFoundError = class StorageDestinationNotFoundError extends Error {
13094
13105
  get kind() {
13095
13106
  return "storage_destination_not_found";
@@ -13489,6 +13500,7 @@ var init_errors2 = __esm(() => {
13489
13500
  result_truncated: ResultTruncatedError,
13490
13501
  result_shape: ResultShapeError,
13491
13502
  destination_not_found: DestinationNotFoundError,
13503
+ container_not_found: ContainerNotFoundError,
13492
13504
  storage_destination_not_found: StorageDestinationNotFoundError,
13493
13505
  storage_catalog_not_found: StorageCatalogNotFoundError,
13494
13506
  connection_auth: ConnectionAuthError,
@@ -13694,6 +13706,7 @@ var init_errors2 = __esm(() => {
13694
13706
  },
13695
13707
  storage_catalog_not_found: { status: 404, mcp: { advice: "internal" } },
13696
13708
  destination_not_found: { status: 422, mcp: { advice: "internal" } },
13709
+ container_not_found: { status: 422, mcp: { advice: "internal" } },
13697
13710
  connection_auth: {
13698
13711
  status: 424,
13699
13712
  message: GENERIC_AUTH_MESSAGE,
@@ -18256,6 +18269,536 @@ function keyedOverlay(files) {
18256
18269
  }
18257
18270
  var init_overlay_key = () => {};
18258
18271
 
18272
+ // src/service/governance/ir/sql_embeds.ts
18273
+ import { isSourceDef as isSourceDef6 } from "@malloydata/malloy";
18274
+ function sqlSelectsWithin(root) {
18275
+ const found = [];
18276
+ const seen = new Set;
18277
+ const stack = [root];
18278
+ while (stack.length > 0) {
18279
+ const node = stack.pop();
18280
+ if (Array.isArray(node)) {
18281
+ stack.push(...node);
18282
+ continue;
18283
+ }
18284
+ if (!isObj(node) || seen.has(node))
18285
+ continue;
18286
+ seen.add(node);
18287
+ if (node.type === "sql_select" && Array.isArray(node.selectSegments)) {
18288
+ found.push(node);
18289
+ }
18290
+ stack.push(...Object.values(node));
18291
+ }
18292
+ return found;
18293
+ }
18294
+ function embeddedStructs(segment, modelDef) {
18295
+ if (segment.type === "query") {
18296
+ const ref = segment.structRef;
18297
+ let base = ref;
18298
+ if (typeof ref === "string")
18299
+ base = modelDef.contents[ref];
18300
+ if (!isObj(base) || !isSourceDef6(base)) {
18301
+ return {
18302
+ unreadable: "its source reference does not resolve in the model",
18303
+ label: typeof ref === "string" ? ref : "<embedded query>"
18304
+ };
18305
+ }
18306
+ const structs = [base];
18307
+ const resolved = segment.compositeResolvedSourceDef;
18308
+ if (isObj(resolved) && isSourceDef6(resolved)) {
18309
+ structs.push(resolved);
18310
+ }
18311
+ return { structs };
18312
+ }
18313
+ if (isSourceDef6(segment)) {
18314
+ return { structs: [segment] };
18315
+ }
18316
+ return {
18317
+ unreadable: `its segment shape (type ${JSON.stringify(segment.type)}) is not one Publisher reads`,
18318
+ label: labelOf(segment)
18319
+ };
18320
+ }
18321
+ var isObj = (value) => typeof value === "object" && value !== null, INLINE_SQL = "<inline sql()>", labelOf = (struct) => {
18322
+ const label = struct.as ?? struct.name;
18323
+ if (typeof label !== "string")
18324
+ return "<unnamed>";
18325
+ return label.startsWith("sql://") ? INLINE_SQL : label;
18326
+ };
18327
+ var init_sql_embeds = () => {};
18328
+
18329
+ // src/service/materialization/text/source_map.ts
18330
+ import { isSourceDef as isSourceDef7 } from "@malloydata/malloy";
18331
+ function structRefSourceId(structRef) {
18332
+ if (typeof structRef === "string")
18333
+ return structRef;
18334
+ const sourceID = structRef?.sourceID;
18335
+ return typeof sourceID === "string" && sourceID.length > 0 ? sourceID : undefined;
18336
+ }
18337
+ function byId(model, id) {
18338
+ const entry = model?.sourceRegistry?.[id]?.entry;
18339
+ if (!entry)
18340
+ return;
18341
+ if (entry.type === "source_registry_reference" && entry.name) {
18342
+ return model?.contents?.[entry.name];
18343
+ }
18344
+ return entry;
18345
+ }
18346
+ function baseEdgeOf(def, modelDef) {
18347
+ const edge = sourceBaseEdge(def, modelDef);
18348
+ return edge && {
18349
+ hop: edge.hop,
18350
+ sourceID: edge.sourceID,
18351
+ def: edge.def
18352
+ };
18353
+ }
18354
+ function compositeMemberIds(def) {
18355
+ if (def.type !== "composite" || !Array.isArray(def.sources))
18356
+ return [];
18357
+ return def.sources.flatMap((member) => {
18358
+ const id = structRefSourceId(member);
18359
+ return id === undefined ? [] : [id];
18360
+ });
18361
+ }
18362
+ function kindOf(def, base) {
18363
+ if (def.type === "composite")
18364
+ return "composite";
18365
+ if (!base)
18366
+ return "table";
18367
+ if (base.hop === "extends")
18368
+ return "extend";
18369
+ if (base.hop === "rename")
18370
+ return "rename";
18371
+ return "query";
18372
+ }
18373
+ function detachedNode(def) {
18374
+ const d = def;
18375
+ if (!d || typeof d !== "object" || typeof d.sourceID !== "string") {
18376
+ return;
18377
+ }
18378
+ const base = baseEdgeOf(d, undefined);
18379
+ return {
18380
+ sourceID: d.sourceID,
18381
+ name: undefined,
18382
+ kind: kindOf(d, base),
18383
+ base,
18384
+ members: compositeMemberIds(d),
18385
+ def: d
18386
+ };
18387
+ }
18388
+ function sourceChain(struct, modelDef) {
18389
+ return SourceMap.of(modelDef).chainOf(struct);
18390
+ }
18391
+ function pipelineReferences(pipeline) {
18392
+ const out = [];
18393
+ let tooDeep = false;
18394
+ const walk = (node, depth) => {
18395
+ if (tooDeep)
18396
+ return;
18397
+ if (depth > MAX_PIPELINE_DEPTH) {
18398
+ tooDeep = true;
18399
+ return;
18400
+ }
18401
+ if (node === null || typeof node !== "object")
18402
+ return;
18403
+ if (Array.isArray(node)) {
18404
+ for (const item of node)
18405
+ walk(item, depth + 1);
18406
+ return;
18407
+ }
18408
+ const record = node;
18409
+ if (typeof record.join === "string") {
18410
+ const sourceID = typeof record.sourceID === "string" ? record.sourceID : undefined;
18411
+ out.push({ sourceID, ref: sourceID ?? node });
18412
+ return;
18413
+ }
18414
+ if (record.structRef !== undefined) {
18415
+ out.push({
18416
+ sourceID: structRefSourceId(record.structRef),
18417
+ ref: record.structRef
18418
+ });
18419
+ }
18420
+ for (const [key, value] of Object.entries(record)) {
18421
+ if (key === "structRef")
18422
+ continue;
18423
+ walk(value, depth + 1);
18424
+ }
18425
+ };
18426
+ walk(pipeline, 0);
18427
+ return tooDeep ? undefined : out;
18428
+ }
18429
+ function reachableSourceIDs(roots, modelDef) {
18430
+ const ids = new Set;
18431
+ const seen = new Set;
18432
+ const add = (value) => {
18433
+ if (typeof value === "string" && value.length > 0)
18434
+ ids.add(value);
18435
+ };
18436
+ const scanWhole = (node, depth) => {
18437
+ if (depth > MAX_PIPELINE_DEPTH || node === null || typeof node !== "object")
18438
+ return;
18439
+ if (Array.isArray(node)) {
18440
+ for (const item of node)
18441
+ scanWhole(item, depth + 1);
18442
+ return;
18443
+ }
18444
+ const record = node;
18445
+ for (const key of ["sourceID", "referenceID", "extends"])
18446
+ add(record[key]);
18447
+ for (const value of Object.values(record))
18448
+ scanWhole(value, depth + 1);
18449
+ };
18450
+ const visitPipeline = (pipeline) => {
18451
+ if (pipeline === undefined)
18452
+ return;
18453
+ const refs = pipelineReferences(pipeline);
18454
+ if (refs === undefined) {
18455
+ scanWhole(pipeline, 0);
18456
+ return;
18457
+ }
18458
+ for (const { sourceID, ref } of refs) {
18459
+ add(sourceID);
18460
+ if (ref !== null && typeof ref === "object")
18461
+ visit(ref);
18462
+ }
18463
+ };
18464
+ const visit = (node) => {
18465
+ if (node === null || typeof node !== "object" || seen.has(node))
18466
+ return;
18467
+ seen.add(node);
18468
+ const def = node;
18469
+ add(def.sourceID);
18470
+ add(def.referenceID);
18471
+ add(def.extends);
18472
+ if (def.structRef !== undefined) {
18473
+ add(structRefSourceId(def.structRef));
18474
+ if (typeof def.structRef === "object")
18475
+ visit(def.structRef);
18476
+ }
18477
+ visitPipeline(def.pipeline);
18478
+ if (def.query) {
18479
+ add(structRefSourceId(def.query.structRef));
18480
+ if (def.query.structRef && typeof def.query.structRef === "object") {
18481
+ visit(def.query.structRef);
18482
+ }
18483
+ visit(def.query.compositeResolvedSourceDef);
18484
+ visitPipeline(def.query.pipeline);
18485
+ }
18486
+ for (const member of def.sources ?? []) {
18487
+ add(structRefSourceId(member));
18488
+ visit(typeof member === "string" ? byId(modelDef, member) : member);
18489
+ }
18490
+ if (modelDef !== undefined && isSourceDef7(node)) {
18491
+ const struct = node;
18492
+ const model = modelDef;
18493
+ const declared = resolveDeclaredSource(struct, model);
18494
+ if (declared.kind === "resolved")
18495
+ visit(declared.source);
18496
+ visit(resolveExtendedSource(struct, model));
18497
+ visit(inferredExtendedSource(struct, model));
18498
+ visit(resolveQuerySourceBase(struct, model));
18499
+ visit(resolveCompositeResolvedBase(struct));
18500
+ }
18501
+ const segments = def.selectSegments;
18502
+ if (Array.isArray(segments)) {
18503
+ for (const segment of segments)
18504
+ visitEmbed(segment);
18505
+ }
18506
+ for (const field of def.fields ?? []) {
18507
+ const f = field;
18508
+ if (typeof f?.join === "string") {
18509
+ add(f.sourceID);
18510
+ visit(field);
18511
+ } else if (f?.pipeline !== undefined) {
18512
+ visitPipeline(f.pipeline);
18513
+ }
18514
+ }
18515
+ };
18516
+ const visitEmbed = (segment) => {
18517
+ if (segment === null || typeof segment !== "object")
18518
+ return;
18519
+ const embed = segment;
18520
+ if ("sql" in embed && embed.type === undefined)
18521
+ return;
18522
+ add(structRefSourceId(embed.structRef));
18523
+ const read = modelDef !== undefined ? embeddedStructs(embed, modelDef) : undefined;
18524
+ if (read !== undefined && "structs" in read) {
18525
+ for (const struct of read.structs)
18526
+ visit(struct);
18527
+ } else {
18528
+ scanWhole(embed, 0);
18529
+ }
18530
+ visitPipeline(embed.pipeline);
18531
+ };
18532
+ for (const root of roots)
18533
+ visit(root);
18534
+ return ids;
18535
+ }
18536
+ function fieldKey(field) {
18537
+ const f = field;
18538
+ if (typeof f?.as === "string")
18539
+ return f.as;
18540
+ return typeof f?.name === "string" ? f.name : "";
18541
+ }
18542
+ function reachPersisted(ctx, name, isPersisted) {
18543
+ const persisted = new Map;
18544
+ const rawLeaves = new Set;
18545
+ const rawVia = new Set;
18546
+ const visited = new Set;
18547
+ const seen = new Set;
18548
+ const defName = (def) => {
18549
+ const id = def.sourceID;
18550
+ return typeof id === "string" ? ctx.sourceNameById.get(id) : undefined;
18551
+ };
18552
+ const reachRaw = (leaf, via) => {
18553
+ rawLeaves.add(leaf);
18554
+ rawVia.add(via);
18555
+ };
18556
+ const nameOf = (sourceID) => sourceID.split("@")[0];
18557
+ const follow = (ref, via) => {
18558
+ if (typeof ref === "string") {
18559
+ const next = ctx.sourceNameById.get(ref);
18560
+ if (next !== undefined) {
18561
+ visit(ctx.contents[next], next, false, via);
18562
+ return;
18563
+ }
18564
+ const refName = nameOf(ref);
18565
+ if (isPersisted(refName, ref)) {
18566
+ visited.add(refName);
18567
+ persisted.set(ref, { name: refName, sourceID: ref });
18568
+ return;
18569
+ }
18570
+ reachRaw(refName, via);
18571
+ return;
18572
+ }
18573
+ if (ref !== null && typeof ref === "object") {
18574
+ const def = ref;
18575
+ visit(def, defName(def), false, via);
18576
+ return;
18577
+ }
18578
+ reachRaw("(unnamed)", via);
18579
+ };
18580
+ const followJoins = (fields, sourceName) => {
18581
+ for (const field of fields ?? []) {
18582
+ const f = field;
18583
+ if (typeof f.join !== "string")
18584
+ continue;
18585
+ follow(typeof f.sourceID === "string" ? f.sourceID : field, sourceName);
18586
+ }
18587
+ };
18588
+ const ownJoins = (def) => {
18589
+ const baseName = typeof def.extends === "string" ? ctx.sourceNameById.get(def.extends) : undefined;
18590
+ const baseFields = new Set((baseName ? ctx.contents[baseName]?.fields ?? [] : []).map(fieldKey));
18591
+ return (def.fields ?? []).filter((f) => !baseFields.has(fieldKey(f)));
18592
+ };
18593
+ const visit = (def, sourceName, root, via) => {
18594
+ const label = sourceName ?? via;
18595
+ if (!def) {
18596
+ reachRaw(label, via);
18597
+ return;
18598
+ }
18599
+ if (seen.has(def))
18600
+ return;
18601
+ seen.add(def);
18602
+ if (!root && sourceName !== undefined)
18603
+ visited.add(sourceName);
18604
+ const sourceID = def.sourceID;
18605
+ if (!root && sourceName !== undefined && typeof sourceID === "string" && isPersisted(sourceName, sourceID)) {
18606
+ persisted.set(sourceID, { name: sourceName, sourceID });
18607
+ if (typeof def.extends === "string") {
18608
+ followJoins(ownJoins(def), sourceName);
18609
+ }
18610
+ return;
18611
+ }
18612
+ const base = typeof def.extends === "string" ? def.extends : def.type === "query_source" ? def.query?.structRef : undefined;
18613
+ if (base === undefined) {
18614
+ const inferred = inferredExtendedSource(def, ctx);
18615
+ if (inferred) {
18616
+ follow(inferred, label);
18617
+ const baseFields = new Set((inferred.fields ?? []).map(fieldKey));
18618
+ followJoins((def.fields ?? []).filter((f) => !baseFields.has(fieldKey(f))), label);
18619
+ return;
18620
+ }
18621
+ reachRaw(label, via);
18622
+ return;
18623
+ }
18624
+ follow(base, label);
18625
+ if (typeof def.extends !== "string") {
18626
+ const refs = pipelineReferences(def.query?.pipeline);
18627
+ for (const { ref } of refs ?? [{ ref: undefined }]) {
18628
+ follow(ref, label);
18629
+ }
18630
+ }
18631
+ followJoins(def.fields, label);
18632
+ };
18633
+ visit(ctx.contents[name], name, true, name);
18634
+ return {
18635
+ persisted: [...persisted.values()],
18636
+ raw: rawLeaves.size > 0,
18637
+ rawLeaves: [...rawLeaves],
18638
+ rawVia: [...rawVia],
18639
+ visited: [...visited]
18640
+ };
18641
+ }
18642
+ var SourceMap, MAX_PIPELINE_DEPTH = 200;
18643
+ var init_source_map = __esm(() => {
18644
+ init_sql_embeds();
18645
+ init_source_graph();
18646
+ SourceMap = class SourceMap {
18647
+ modelDef;
18648
+ static memo = new WeakMap;
18649
+ nodesById = new Map;
18650
+ idsByName = new Map;
18651
+ constructor(modelDef) {
18652
+ this.modelDef = modelDef;
18653
+ const model = modelDef;
18654
+ for (const [name, value] of Object.entries(model?.contents ?? {})) {
18655
+ const def = value;
18656
+ if (typeof def?.sourceID !== "string")
18657
+ continue;
18658
+ this.idsByName.set(name, def.sourceID);
18659
+ this.add(def, name);
18660
+ }
18661
+ for (const id of Object.keys(model?.sourceRegistry ?? {})) {
18662
+ if (this.nodesById.has(id))
18663
+ continue;
18664
+ const def = byId(model, id);
18665
+ if (def && typeof def.sourceID === "string")
18666
+ this.add(def, undefined);
18667
+ }
18668
+ }
18669
+ static of(modelDef) {
18670
+ if (modelDef === null || typeof modelDef !== "object") {
18671
+ return new SourceMap(modelDef);
18672
+ }
18673
+ let map = SourceMap.memo.get(modelDef);
18674
+ if (!map) {
18675
+ map = new SourceMap(modelDef);
18676
+ SourceMap.memo.set(modelDef, map);
18677
+ }
18678
+ return map;
18679
+ }
18680
+ add(def, name) {
18681
+ const sourceID = def.sourceID;
18682
+ if (this.nodesById.has(sourceID))
18683
+ return;
18684
+ const base = baseEdgeOf(def, this.modelDef);
18685
+ this.nodesById.set(sourceID, {
18686
+ sourceID,
18687
+ name,
18688
+ kind: kindOf(def, base),
18689
+ base,
18690
+ members: compositeMemberIds(def),
18691
+ def
18692
+ });
18693
+ }
18694
+ model() {
18695
+ return this.modelDef;
18696
+ }
18697
+ node(sourceID) {
18698
+ return this.nodesById.get(sourceID);
18699
+ }
18700
+ sourceIDOf(name) {
18701
+ return this.idsByName.get(name);
18702
+ }
18703
+ joinsOf(sourceID) {
18704
+ const node = this.nodesById.get(sourceID);
18705
+ return node ? sourceJoins(node.def) : [];
18706
+ }
18707
+ fieldJoinsOf(sourceID) {
18708
+ const node = this.nodesById.get(sourceID);
18709
+ return node ? fieldJoinUsage(node.def) : new Map;
18710
+ }
18711
+ filterJoinsOf(sourceID) {
18712
+ const node = this.nodesById.get(sourceID);
18713
+ return node ? filterJoinReads(node.def) : undefined;
18714
+ }
18715
+ joinedReadsOf(join) {
18716
+ return joinedSourceReads(join);
18717
+ }
18718
+ nodes() {
18719
+ return [...this.nodesById.values()];
18720
+ }
18721
+ chainOf(struct) {
18722
+ const out = [];
18723
+ const seen = new Set;
18724
+ let current = struct;
18725
+ for (let hops = 0;current && hops < 64; hops++) {
18726
+ if (seen.has(current))
18727
+ break;
18728
+ seen.add(current);
18729
+ const id = current.sourceID;
18730
+ if (typeof id === "string" && !out.includes(id))
18731
+ out.push(id);
18732
+ const next = nextSourceInChain(current, this.modelDef);
18733
+ if (!next) {
18734
+ for (const ref of [current.referenceID, current.extends]) {
18735
+ if (typeof ref === "string" && !out.includes(ref))
18736
+ out.push(ref);
18737
+ }
18738
+ }
18739
+ current = next;
18740
+ }
18741
+ return out;
18742
+ }
18743
+ };
18744
+ });
18745
+
18746
+ // src/service/materialization/serve/sql_embed_reads.ts
18747
+ function sqlEmbedReads(modelDefs) {
18748
+ const out = new Map;
18749
+ for (const modelDef of modelDefs) {
18750
+ for (const select of sqlSelectsWithin(modelDef)) {
18751
+ const connection = select.connection;
18752
+ if (typeof connection !== "string")
18753
+ continue;
18754
+ const segments = select.selectSegments.filter((s) => typeof s === "object" && s !== null && !(("sql" in s) && s.type === undefined));
18755
+ if (segments.length === 0)
18756
+ continue;
18757
+ const isQuery = (s) => s.type === "query";
18758
+ const read = {
18759
+ via: labelOf(select),
18760
+ connection,
18761
+ ...typeof select.sourceID === "string" ? { sourceID: select.sourceID } : {},
18762
+ reaches: reachableSourceIDs(segments.filter(isQuery), modelDef),
18763
+ bareReaches: reachableSourceIDs(segments.filter((s) => !isQuery(s)), modelDef)
18764
+ };
18765
+ const key = [
18766
+ read.via,
18767
+ connection,
18768
+ [...read.reaches].sort().join(","),
18769
+ [...read.bareReaches].sort().join(",")
18770
+ ].join("\x00");
18771
+ if (!out.has(key))
18772
+ out.set(key, read);
18773
+ }
18774
+ }
18775
+ return [...out.values()];
18776
+ }
18777
+ function conflictingSqlEmbeds(reads, sourceID, servedOn, rerooted) {
18778
+ const out = [];
18779
+ for (const read of reads) {
18780
+ if (read.sourceID !== undefined && rerooted(read.sourceID))
18781
+ continue;
18782
+ if (read.bareReaches.has(sourceID)) {
18783
+ out.push({ read, conflict: "bare" });
18784
+ } else if (read.connection !== servedOn && read.reaches.has(sourceID)) {
18785
+ out.push({ read, conflict: "cross_connection" });
18786
+ }
18787
+ }
18788
+ return out;
18789
+ }
18790
+ function ownSqlEmbedReach(struct, modelDef) {
18791
+ const select = struct;
18792
+ if (select?.type !== "sql_select" || !Array.isArray(select.selectSegments)) {
18793
+ return new Set;
18794
+ }
18795
+ return reachableSourceIDs(select.selectSegments.filter((s) => typeof s === "object" && s !== null && !(("sql" in s) && s.type === undefined)), modelDef);
18796
+ }
18797
+ var init_sql_embed_reads = __esm(() => {
18798
+ init_sql_embeds();
18799
+ init_source_map();
18800
+ });
18801
+
18259
18802
  // src/service/event_loop_yield.ts
18260
18803
  function yieldToEventLoop() {
18261
18804
  return new Promise((resolve) => setImmediate(resolve));
@@ -19051,7 +19594,7 @@ var init_gate_registry_walk = __esm(() => {
19051
19594
  // src/service/source_extraction.ts
19052
19595
  import {
19053
19596
  isJoined as isJoined4,
19054
- isSourceDef as isSourceDef6
19597
+ isSourceDef as isSourceDef8
19055
19598
  } from "@malloydata/malloy";
19056
19599
  function joinFieldNamesUnresolvableDeclaration(field, modelDef) {
19057
19600
  const ids = [field.referenceID, field.sourceID].filter((id) => !!id);
@@ -19062,7 +19605,7 @@ function joinFieldNamesUnresolvableDeclaration(field, modelDef) {
19062
19605
  if (!entry)
19063
19606
  continue;
19064
19607
  const declared = entry.type === "source_registry_reference" ? modelDef.contents[entry.name] : entry;
19065
- if (declared && isSourceDef6(declared))
19608
+ if (declared && isSourceDef8(declared))
19066
19609
  return false;
19067
19610
  }
19068
19611
  return true;
@@ -19080,7 +19623,7 @@ function considerNoteOwner(declaredBy, note, candidate) {
19080
19623
  }
19081
19624
  }
19082
19625
  function collectSourceInfos(modelDef) {
19083
- const names = Object.keys(modelDef.contents).filter((name) => isSourceDef6(modelDef.contents[name]));
19626
+ const names = Object.keys(modelDef.contents).filter((name) => isSourceDef8(modelDef.contents[name]));
19084
19627
  const exports = [...new Set([...modelDef.exports, ...names])];
19085
19628
  return modelInfoOf({ ...modelDef, exports }).entries.filter((entry) => entry.kind === "source");
19086
19629
  }
@@ -19096,7 +19639,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
19096
19639
  const nearMissAuthorize = [];
19097
19640
  const sweptStructs = [];
19098
19641
  for (const obj of Object.values(modelDef.contents)) {
19099
- if (!isSourceDef6(obj))
19642
+ if (!isSourceDef8(obj))
19100
19643
  continue;
19101
19644
  const struct = obj;
19102
19645
  sweptStructs.push(obj);
@@ -19116,7 +19659,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
19116
19659
  const entry = value.entry;
19117
19660
  if (entry.type === "source_registry_reference")
19118
19661
  continue;
19119
- if (!isSourceDef6(entry))
19662
+ if (!isSourceDef8(entry))
19120
19663
  continue;
19121
19664
  sweptStructs.push(entry);
19122
19665
  for (const note of ownLevelNotes(entry.annotations)) {
@@ -19158,7 +19701,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
19158
19701
  });
19159
19702
  }
19160
19703
  }
19161
- const sources = Object.values(modelDef.contents).filter((obj) => isSourceDef6(obj)).map((sourceObj) => {
19704
+ const sources = Object.values(modelDef.contents).filter((obj) => isSourceDef8(obj)).map((sourceObj) => {
19162
19705
  const struct = sourceObj;
19163
19706
  const sourceName = struct.as || struct.name;
19164
19707
  const annotations = annotationTexts(struct.annotations);
@@ -19227,7 +19770,7 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
19227
19770
  continue;
19228
19771
  }
19229
19772
  const fieldName = field.as || field.name;
19230
- if (isJoined4(field) && isSourceDef6(field)) {
19773
+ if (isJoined4(field) && isSourceDef8(field)) {
19231
19774
  const joinedStruct = field;
19232
19775
  if (joinFieldNamesUnresolvableDeclaration(joinedStruct, modelDef)) {
19233
19776
  continue;
@@ -19292,54 +19835,6 @@ var init_source_extraction = __esm(() => {
19292
19835
  });
19293
19836
 
19294
19837
  // src/service/sql_embed_gates.ts
19295
- import { isSourceDef as isSourceDef7 } from "@malloydata/malloy";
19296
- function sqlSelectsWithin(root) {
19297
- const found = [];
19298
- const seen = new Set;
19299
- const stack = [root];
19300
- while (stack.length > 0) {
19301
- const node = stack.pop();
19302
- if (Array.isArray(node)) {
19303
- stack.push(...node);
19304
- continue;
19305
- }
19306
- if (!isObj(node) || seen.has(node))
19307
- continue;
19308
- seen.add(node);
19309
- if (node.type === "sql_select" && Array.isArray(node.selectSegments)) {
19310
- found.push(node);
19311
- }
19312
- stack.push(...Object.values(node));
19313
- }
19314
- return found;
19315
- }
19316
- function embeddedStructs(segment, modelDef) {
19317
- if (segment.type === "query") {
19318
- const ref = segment.structRef;
19319
- let base = ref;
19320
- if (typeof ref === "string")
19321
- base = modelDef.contents[ref];
19322
- if (!isObj(base) || !isSourceDef7(base)) {
19323
- return {
19324
- unreadable: "its source reference does not resolve in the model",
19325
- label: typeof ref === "string" ? ref : "<embedded query>"
19326
- };
19327
- }
19328
- const structs = [base];
19329
- const resolved = segment.compositeResolvedSourceDef;
19330
- if (isObj(resolved) && isSourceDef7(resolved)) {
19331
- structs.push(resolved);
19332
- }
19333
- return { structs };
19334
- }
19335
- if (isSourceDef7(segment)) {
19336
- return { structs: [segment] };
19337
- }
19338
- return {
19339
- unreadable: `its segment shape (type ${JSON.stringify(segment.type)}) is not one Publisher reads`,
19340
- label: labelOf(segment)
19341
- };
19342
- }
19343
19838
  function runLabel(query, index, cell) {
19344
19839
  const line = isObj(query) ? query.location?.range?.start?.line : undefined;
19345
19840
  const at = typeof line === "number" ? `line ${line + 1}` : `#${index + 1}`;
@@ -19455,13 +19950,8 @@ function assertNoSqlEmbedsOfGatedSources(modelDef, scope = {}) {
19455
19950
  ` + `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.`
19456
19951
  });
19457
19952
  }
19458
- var isObj = (value) => typeof value === "object" && value !== null, INLINE_SQL = "<inline sql()>", labelOf = (struct) => {
19459
- const label = struct.as ?? struct.name;
19460
- if (typeof label !== "string")
19461
- return "<unnamed>";
19462
- return label.startsWith("sql://") ? INLINE_SQL : label;
19463
- };
19464
19953
  var init_sql_embed_gates = __esm(() => {
19954
+ init_sql_embeds();
19465
19955
  init_errors2();
19466
19956
  init_gate_plan();
19467
19957
  });
@@ -20336,401 +20826,6 @@ function offsetOf(text, pos) {
20336
20826
  return offset + pos.character;
20337
20827
  }
20338
20828
 
20339
- // src/service/materialization/text/source_map.ts
20340
- import { isSourceDef as isSourceDef8 } from "@malloydata/malloy";
20341
- function structRefSourceId(structRef) {
20342
- if (typeof structRef === "string")
20343
- return structRef;
20344
- const sourceID = structRef?.sourceID;
20345
- return typeof sourceID === "string" && sourceID.length > 0 ? sourceID : undefined;
20346
- }
20347
- function byId(model, id) {
20348
- const entry = model?.sourceRegistry?.[id]?.entry;
20349
- if (!entry)
20350
- return;
20351
- if (entry.type === "source_registry_reference" && entry.name) {
20352
- return model?.contents?.[entry.name];
20353
- }
20354
- return entry;
20355
- }
20356
- function baseEdgeOf(def, modelDef) {
20357
- const edge = sourceBaseEdge(def, modelDef);
20358
- return edge && {
20359
- hop: edge.hop,
20360
- sourceID: edge.sourceID,
20361
- def: edge.def
20362
- };
20363
- }
20364
- function compositeMemberIds(def) {
20365
- if (def.type !== "composite" || !Array.isArray(def.sources))
20366
- return [];
20367
- return def.sources.flatMap((member) => {
20368
- const id = structRefSourceId(member);
20369
- return id === undefined ? [] : [id];
20370
- });
20371
- }
20372
- function kindOf(def, base) {
20373
- if (def.type === "composite")
20374
- return "composite";
20375
- if (!base)
20376
- return "table";
20377
- if (base.hop === "extends")
20378
- return "extend";
20379
- if (base.hop === "rename")
20380
- return "rename";
20381
- return "query";
20382
- }
20383
- function detachedNode(def) {
20384
- const d = def;
20385
- if (!d || typeof d !== "object" || typeof d.sourceID !== "string") {
20386
- return;
20387
- }
20388
- const base = baseEdgeOf(d, undefined);
20389
- return {
20390
- sourceID: d.sourceID,
20391
- name: undefined,
20392
- kind: kindOf(d, base),
20393
- base,
20394
- members: compositeMemberIds(d),
20395
- def: d
20396
- };
20397
- }
20398
- function sourceChain(struct, modelDef) {
20399
- return SourceMap.of(modelDef).chainOf(struct);
20400
- }
20401
- function pipelineReferences(pipeline) {
20402
- const out = [];
20403
- let tooDeep = false;
20404
- const walk = (node, depth) => {
20405
- if (tooDeep)
20406
- return;
20407
- if (depth > MAX_PIPELINE_DEPTH) {
20408
- tooDeep = true;
20409
- return;
20410
- }
20411
- if (node === null || typeof node !== "object")
20412
- return;
20413
- if (Array.isArray(node)) {
20414
- for (const item of node)
20415
- walk(item, depth + 1);
20416
- return;
20417
- }
20418
- const record = node;
20419
- if (typeof record.join === "string") {
20420
- const sourceID = typeof record.sourceID === "string" ? record.sourceID : undefined;
20421
- out.push({ sourceID, ref: sourceID ?? node });
20422
- return;
20423
- }
20424
- if (record.structRef !== undefined) {
20425
- out.push({
20426
- sourceID: structRefSourceId(record.structRef),
20427
- ref: record.structRef
20428
- });
20429
- }
20430
- for (const [key, value] of Object.entries(record)) {
20431
- if (key === "structRef")
20432
- continue;
20433
- walk(value, depth + 1);
20434
- }
20435
- };
20436
- walk(pipeline, 0);
20437
- return tooDeep ? undefined : out;
20438
- }
20439
- function reachableSourceIDs(roots, modelDef) {
20440
- const ids = new Set;
20441
- const seen = new Set;
20442
- const add = (value) => {
20443
- if (typeof value === "string" && value.length > 0)
20444
- ids.add(value);
20445
- };
20446
- const scanWhole = (node, depth) => {
20447
- if (depth > MAX_PIPELINE_DEPTH || node === null || typeof node !== "object")
20448
- return;
20449
- if (Array.isArray(node)) {
20450
- for (const item of node)
20451
- scanWhole(item, depth + 1);
20452
- return;
20453
- }
20454
- const record = node;
20455
- for (const key of ["sourceID", "referenceID", "extends"])
20456
- add(record[key]);
20457
- for (const value of Object.values(record))
20458
- scanWhole(value, depth + 1);
20459
- };
20460
- const visitPipeline = (pipeline) => {
20461
- if (pipeline === undefined)
20462
- return;
20463
- const refs = pipelineReferences(pipeline);
20464
- if (refs === undefined) {
20465
- scanWhole(pipeline, 0);
20466
- return;
20467
- }
20468
- for (const { sourceID, ref } of refs) {
20469
- add(sourceID);
20470
- if (ref !== null && typeof ref === "object")
20471
- visit(ref);
20472
- }
20473
- };
20474
- const visit = (node) => {
20475
- if (node === null || typeof node !== "object" || seen.has(node))
20476
- return;
20477
- seen.add(node);
20478
- const def = node;
20479
- add(def.sourceID);
20480
- add(def.referenceID);
20481
- add(def.extends);
20482
- if (def.structRef !== undefined) {
20483
- add(structRefSourceId(def.structRef));
20484
- if (typeof def.structRef === "object")
20485
- visit(def.structRef);
20486
- }
20487
- visitPipeline(def.pipeline);
20488
- if (def.query) {
20489
- add(structRefSourceId(def.query.structRef));
20490
- if (def.query.structRef && typeof def.query.structRef === "object") {
20491
- visit(def.query.structRef);
20492
- }
20493
- visit(def.query.compositeResolvedSourceDef);
20494
- visitPipeline(def.query.pipeline);
20495
- }
20496
- for (const member of def.sources ?? []) {
20497
- add(structRefSourceId(member));
20498
- visit(typeof member === "string" ? byId(modelDef, member) : member);
20499
- }
20500
- if (modelDef !== undefined && isSourceDef8(node)) {
20501
- const struct = node;
20502
- const model = modelDef;
20503
- const declared = resolveDeclaredSource(struct, model);
20504
- if (declared.kind === "resolved")
20505
- visit(declared.source);
20506
- visit(resolveExtendedSource(struct, model));
20507
- visit(inferredExtendedSource(struct, model));
20508
- visit(resolveQuerySourceBase(struct, model));
20509
- visit(resolveCompositeResolvedBase(struct));
20510
- }
20511
- for (const field of def.fields ?? []) {
20512
- const f = field;
20513
- if (typeof f?.join === "string") {
20514
- add(f.sourceID);
20515
- visit(field);
20516
- } else if (f?.pipeline !== undefined) {
20517
- visitPipeline(f.pipeline);
20518
- }
20519
- }
20520
- };
20521
- for (const root of roots)
20522
- visit(root);
20523
- return ids;
20524
- }
20525
- function fieldKey(field) {
20526
- const f = field;
20527
- if (typeof f?.as === "string")
20528
- return f.as;
20529
- return typeof f?.name === "string" ? f.name : "";
20530
- }
20531
- function reachPersisted(ctx, name, isPersisted) {
20532
- const persisted = new Map;
20533
- const rawLeaves = new Set;
20534
- const rawVia = new Set;
20535
- const visited = new Set;
20536
- const seen = new Set;
20537
- const defName = (def) => {
20538
- const id = def.sourceID;
20539
- return typeof id === "string" ? ctx.sourceNameById.get(id) : undefined;
20540
- };
20541
- const reachRaw = (leaf, via) => {
20542
- rawLeaves.add(leaf);
20543
- rawVia.add(via);
20544
- };
20545
- const nameOf = (sourceID) => sourceID.split("@")[0];
20546
- const follow = (ref, via) => {
20547
- if (typeof ref === "string") {
20548
- const next = ctx.sourceNameById.get(ref);
20549
- if (next !== undefined) {
20550
- visit(ctx.contents[next], next, false, via);
20551
- return;
20552
- }
20553
- const refName = nameOf(ref);
20554
- if (isPersisted(refName, ref)) {
20555
- visited.add(refName);
20556
- persisted.set(ref, { name: refName, sourceID: ref });
20557
- return;
20558
- }
20559
- reachRaw(refName, via);
20560
- return;
20561
- }
20562
- if (ref !== null && typeof ref === "object") {
20563
- const def = ref;
20564
- visit(def, defName(def), false, via);
20565
- return;
20566
- }
20567
- reachRaw("(unnamed)", via);
20568
- };
20569
- const followJoins = (fields, sourceName) => {
20570
- for (const field of fields ?? []) {
20571
- const f = field;
20572
- if (typeof f.join !== "string")
20573
- continue;
20574
- follow(typeof f.sourceID === "string" ? f.sourceID : field, sourceName);
20575
- }
20576
- };
20577
- const ownJoins = (def) => {
20578
- const baseName = typeof def.extends === "string" ? ctx.sourceNameById.get(def.extends) : undefined;
20579
- const baseFields = new Set((baseName ? ctx.contents[baseName]?.fields ?? [] : []).map(fieldKey));
20580
- return (def.fields ?? []).filter((f) => !baseFields.has(fieldKey(f)));
20581
- };
20582
- const visit = (def, sourceName, root, via) => {
20583
- const label = sourceName ?? via;
20584
- if (!def) {
20585
- reachRaw(label, via);
20586
- return;
20587
- }
20588
- if (seen.has(def))
20589
- return;
20590
- seen.add(def);
20591
- if (!root && sourceName !== undefined)
20592
- visited.add(sourceName);
20593
- const sourceID = def.sourceID;
20594
- if (!root && sourceName !== undefined && typeof sourceID === "string" && isPersisted(sourceName, sourceID)) {
20595
- persisted.set(sourceID, { name: sourceName, sourceID });
20596
- if (typeof def.extends === "string") {
20597
- followJoins(ownJoins(def), sourceName);
20598
- }
20599
- return;
20600
- }
20601
- const base = typeof def.extends === "string" ? def.extends : def.type === "query_source" ? def.query?.structRef : undefined;
20602
- if (base === undefined) {
20603
- const inferred = inferredExtendedSource(def, ctx);
20604
- if (inferred) {
20605
- follow(inferred, label);
20606
- const baseFields = new Set((inferred.fields ?? []).map(fieldKey));
20607
- followJoins((def.fields ?? []).filter((f) => !baseFields.has(fieldKey(f))), label);
20608
- return;
20609
- }
20610
- reachRaw(label, via);
20611
- return;
20612
- }
20613
- follow(base, label);
20614
- if (typeof def.extends !== "string") {
20615
- const refs = pipelineReferences(def.query?.pipeline);
20616
- for (const { ref } of refs ?? [{ ref: undefined }]) {
20617
- follow(ref, label);
20618
- }
20619
- }
20620
- followJoins(def.fields, label);
20621
- };
20622
- visit(ctx.contents[name], name, true, name);
20623
- return {
20624
- persisted: [...persisted.values()],
20625
- raw: rawLeaves.size > 0,
20626
- rawLeaves: [...rawLeaves],
20627
- rawVia: [...rawVia],
20628
- visited: [...visited]
20629
- };
20630
- }
20631
- var SourceMap, MAX_PIPELINE_DEPTH = 200;
20632
- var init_source_map = __esm(() => {
20633
- init_source_graph();
20634
- SourceMap = class SourceMap {
20635
- modelDef;
20636
- static memo = new WeakMap;
20637
- nodesById = new Map;
20638
- idsByName = new Map;
20639
- constructor(modelDef) {
20640
- this.modelDef = modelDef;
20641
- const model = modelDef;
20642
- for (const [name, value] of Object.entries(model?.contents ?? {})) {
20643
- const def = value;
20644
- if (typeof def?.sourceID !== "string")
20645
- continue;
20646
- this.idsByName.set(name, def.sourceID);
20647
- this.add(def, name);
20648
- }
20649
- for (const id of Object.keys(model?.sourceRegistry ?? {})) {
20650
- if (this.nodesById.has(id))
20651
- continue;
20652
- const def = byId(model, id);
20653
- if (def && typeof def.sourceID === "string")
20654
- this.add(def, undefined);
20655
- }
20656
- }
20657
- static of(modelDef) {
20658
- if (modelDef === null || typeof modelDef !== "object") {
20659
- return new SourceMap(modelDef);
20660
- }
20661
- let map = SourceMap.memo.get(modelDef);
20662
- if (!map) {
20663
- map = new SourceMap(modelDef);
20664
- SourceMap.memo.set(modelDef, map);
20665
- }
20666
- return map;
20667
- }
20668
- add(def, name) {
20669
- const sourceID = def.sourceID;
20670
- if (this.nodesById.has(sourceID))
20671
- return;
20672
- const base = baseEdgeOf(def, this.modelDef);
20673
- this.nodesById.set(sourceID, {
20674
- sourceID,
20675
- name,
20676
- kind: kindOf(def, base),
20677
- base,
20678
- members: compositeMemberIds(def),
20679
- def
20680
- });
20681
- }
20682
- model() {
20683
- return this.modelDef;
20684
- }
20685
- node(sourceID) {
20686
- return this.nodesById.get(sourceID);
20687
- }
20688
- sourceIDOf(name) {
20689
- return this.idsByName.get(name);
20690
- }
20691
- joinsOf(sourceID) {
20692
- const node = this.nodesById.get(sourceID);
20693
- return node ? sourceJoins(node.def) : [];
20694
- }
20695
- fieldJoinsOf(sourceID) {
20696
- const node = this.nodesById.get(sourceID);
20697
- return node ? fieldJoinUsage(node.def) : new Map;
20698
- }
20699
- filterJoinsOf(sourceID) {
20700
- const node = this.nodesById.get(sourceID);
20701
- return node ? filterJoinReads(node.def) : undefined;
20702
- }
20703
- joinedReadsOf(join) {
20704
- return joinedSourceReads(join);
20705
- }
20706
- nodes() {
20707
- return [...this.nodesById.values()];
20708
- }
20709
- chainOf(struct) {
20710
- const out = [];
20711
- const seen = new Set;
20712
- let current = struct;
20713
- for (let hops = 0;current && hops < 64; hops++) {
20714
- if (seen.has(current))
20715
- break;
20716
- seen.add(current);
20717
- const id = current.sourceID;
20718
- if (typeof id === "string" && !out.includes(id))
20719
- out.push(id);
20720
- const next = nextSourceInChain(current, this.modelDef);
20721
- if (!next) {
20722
- for (const ref of [current.referenceID, current.extends]) {
20723
- if (typeof ref === "string" && !out.includes(ref))
20724
- out.push(ref);
20725
- }
20726
- }
20727
- current = next;
20728
- }
20729
- return out;
20730
- }
20731
- };
20732
- });
20733
-
20734
20829
  // src/service/materialization/text/persist_blanking.ts
20735
20830
  function sourceNotes(annotations, depth = 0) {
20736
20831
  if (!annotations || typeof annotations !== "object" || depth > 64)
@@ -20840,11 +20935,14 @@ class GeneratedFiles {
20840
20935
  static over(factory) {
20841
20936
  return new GeneratedFiles(factory);
20842
20937
  }
20843
- async loadModel(overlay = new Map) {
20938
+ async loadModel(overlay = new Map, options = {}) {
20844
20939
  const { runtime, importBaseURL, modelURL } = await this.runtimeFor(keyedOverlay(overlay));
20845
20940
  if (!modelURL)
20846
20941
  throw new Error("no package model to load");
20847
- const materializer = runtime.loadModel(modelURL, { importBaseURL });
20942
+ const materializer = runtime.loadModel(modelURL, {
20943
+ importBaseURL,
20944
+ ...options.virtualMap ? { virtualMap: options.virtualMap } : {}
20945
+ });
20848
20946
  return { runtime, importBaseURL, materializer };
20849
20947
  }
20850
20948
  runtime(overlay = new Map) {
@@ -29819,7 +29917,8 @@ var init_dialect = __esm(() => {
29819
29917
  catalogHidesTables: false,
29820
29918
  stringCollation: undefined,
29821
29919
  ungroupableTypes: undefined,
29822
- binary64Types: undefined
29920
+ binary64Types: undefined,
29921
+ containerCatalog: undefined
29823
29922
  });
29824
29923
  CAPABILITIES = {
29825
29924
  duckdb: Object.freeze({
@@ -29838,10 +29937,12 @@ var init_dialect = __esm(() => {
29838
29937
  utcSessions: true,
29839
29938
  leafBudget: 120,
29840
29939
  stringCollation: "instance",
29841
- binary64Types: ["DOUBLE", "FLOAT8"]
29940
+ binary64Types: ["DOUBLE", "FLOAT8"],
29941
+ containerCatalog: "duckdb_schemas"
29842
29942
  }),
29843
29943
  postgres: Object.freeze({
29844
29944
  ...NONE,
29945
+ containerCatalog: "pg_namespace",
29845
29946
  stringCollation: "column",
29846
29947
  passthroughNumericAsDouble: true,
29847
29948
  incrementalSourceRange: true,
@@ -29887,6 +29988,7 @@ var init_dialect = __esm(() => {
29887
29988
  onlyBigIntegerType: "INT64",
29888
29989
  leafBudget: 120,
29889
29990
  stringCollation: "dataset",
29991
+ containerCatalog: "dataset",
29890
29992
  ungroupableTypes: {
29891
29993
  malloy: ["json", "array", "record"],
29892
29994
  native: ["geography"]
@@ -29894,6 +29996,7 @@ var init_dialect = __esm(() => {
29894
29996
  }),
29895
29997
  snowflake: Object.freeze({
29896
29998
  ...NONE,
29999
+ containerCatalog: "schemata",
29897
30000
  decodedTablePath: true,
29898
30001
  catalogHidesTables: true,
29899
30002
  incrementalSourceRange: true,
@@ -31699,10 +31802,19 @@ function keyUniquenessOfContract(contract, sources, leaves = []) {
31699
31802
  if (source)
31700
31803
  read("leaf", leaf.joinPath, source);
31701
31804
  }
31805
+ const grainJoinKeys = {};
31806
+ for (const [name, check] of Object.entries(keys)) {
31807
+ const joinKey = contractKeyWithoutLevel(name, "grain_join");
31808
+ if (joinKey !== undefined && check.level === "grain_join") {
31809
+ grainJoinKeys[joinKey] = passed(check);
31810
+ }
31811
+ }
31702
31812
  const anyParent = Object.keys(parentKeys).length > 0;
31703
- if (!own && !anyParent)
31813
+ const anyGrainJoin = Object.keys(grainJoinKeys).length > 0;
31814
+ if (!own && !anyParent && !anyGrainJoin)
31704
31815
  return;
31705
31816
  return {
31817
+ ...anyGrainJoin ? { grainJoinKeys } : {},
31706
31818
  ...own ? {
31707
31819
  keyColumn: contractKeyWithoutLevel(own[0], "rollup"),
31708
31820
  unique: passed(own[1])
@@ -32203,10 +32315,13 @@ function parseKeyUniqueness(raw) {
32203
32315
  const own = typeof k.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32204
32316
  const parentKeys = recordOf(k.parentKeys, "boolean");
32205
32317
  const parentKeyColumns = recordOf(k.parentKeyColumns, "string");
32206
- if (!own && !parentKeys && !parentKeyColumns)
32318
+ const grainJoinKeys = recordOf(k.grainJoinKeys, "boolean");
32319
+ if (!own && !parentKeys && !parentKeyColumns && !grainJoinKeys) {
32207
32320
  return;
32321
+ }
32208
32322
  return {
32209
32323
  ...own ?? {},
32324
+ ...grainJoinKeys ? { grainJoinKeys } : {},
32210
32325
  ...parentKeys ? { parentKeys } : {},
32211
32326
  ...parentKeyColumns ? { parentKeyColumns } : {}
32212
32327
  };
@@ -32233,21 +32348,27 @@ function rollupKeyOf(entry) {
32233
32348
  const k = keyUniquenessOf(entry);
32234
32349
  return k?.keyColumn !== undefined && k.unique !== undefined ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32235
32350
  }
32351
+ function grainJoinKeysOf(entry) {
32352
+ return keyUniquenessOf(entry)?.grainJoinKeys;
32353
+ }
32236
32354
  function withEntryKeyChecks(binding, entry) {
32237
32355
  const {
32238
32356
  primaryKeys: _was,
32239
32357
  primaryKeyColumns: _wasColumns,
32240
32358
  rollupKey: _wasKey,
32359
+ grainJoinKeys: _wasJoinKeys,
32241
32360
  ...rest
32242
32361
  } = binding;
32243
32362
  const primaryKeys = primaryKeysOf(entry);
32244
32363
  const primaryKeyColumns = primaryKeyColumnsOf(entry);
32245
32364
  const rollupKey = isRollupOrigin(entry.origin) ? rollupKeyOf(entry) : undefined;
32365
+ const grainJoinKeys = isRollupOrigin(entry.origin) ? grainJoinKeysOf(entry) : undefined;
32246
32366
  return {
32247
32367
  ...rest,
32248
32368
  ...primaryKeys ? { primaryKeys } : {},
32249
32369
  ...primaryKeyColumns ? { primaryKeyColumns } : {},
32250
- ...rollupKey ? { rollupKey } : {}
32370
+ ...rollupKey ? { rollupKey } : {},
32371
+ ...grainJoinKeys ? { grainJoinKeys } : {}
32251
32372
  };
32252
32373
  }
32253
32374
  function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, sourceIDsFor) {
@@ -32267,6 +32388,7 @@ function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, so
32267
32388
  const primaryKeys = primaryKeysOf(entry);
32268
32389
  const primaryKeyColumns = primaryKeyColumnsOf(entry);
32269
32390
  const rollupKey = isRollupOrigin(entry.origin) ? rollupKeyOf(entry) : undefined;
32391
+ const grainJoinKeys = isRollupOrigin(entry.origin) ? grainJoinKeysOf(entry) : undefined;
32270
32392
  for (const sourceName of names) {
32271
32393
  const sourceIDs = sourceIDsFor?.(sourceName, entry.sourceEntityId);
32272
32394
  bindings.push({
@@ -32283,7 +32405,8 @@ function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, so
32283
32405
  freshnessFallback: entry.freshnessFallback,
32284
32406
  ...primaryKeys ? { primaryKeys } : {},
32285
32407
  ...primaryKeyColumns ? { primaryKeyColumns } : {},
32286
- ...rollupKey ? { rollupKey } : {}
32408
+ ...rollupKey ? { rollupKey } : {},
32409
+ ...grainJoinKeys ? { grainJoinKeys } : {}
32287
32410
  });
32288
32411
  }
32289
32412
  }
@@ -33735,7 +33858,46 @@ function namesServedCopyAlias(text) {
33735
33858
  function withoutServedCopyAliases(text) {
33736
33859
  return text.replace(new RegExp(`'?__publisher_storage_${TOKEN}_\\d+'?`, "g"), "the storage destination");
33737
33860
  }
33738
- function servedCopyConfig(packageConfig, destinations, allowed) {
33861
+ function destinationOfAlias(name) {
33862
+ return destinationsByAlias.get(name);
33863
+ }
33864
+ function servedConnectionLabel(name) {
33865
+ const destination = destinationsByAlias.get(name);
33866
+ return destination !== undefined ? `storage destination '${destination}'` : `connection '${name}'`;
33867
+ }
33868
+ function underAlias(connection, alias) {
33869
+ let views = aliasedViews.get(connection);
33870
+ if (!views) {
33871
+ views = new Map;
33872
+ aliasedViews.set(connection, views);
33873
+ }
33874
+ const known = views.get(alias);
33875
+ if (known)
33876
+ return known;
33877
+ const view = new Proxy(connection, {
33878
+ get(target, prop) {
33879
+ if (prop === "name")
33880
+ return alias;
33881
+ if (prop === "fetchSchemaForTables") {
33882
+ return async (...args) => {
33883
+ const fetched = await target.fetchSchemaForTables(...args);
33884
+ return {
33885
+ ...fetched,
33886
+ schemas: Object.fromEntries(Object.entries(fetched.schemas).map(([key, def]) => [
33887
+ key,
33888
+ { ...def, connection: alias }
33889
+ ]))
33890
+ };
33891
+ };
33892
+ }
33893
+ const value = Reflect.get(target, prop, target);
33894
+ return typeof value === "function" ? value.bind(target) : value;
33895
+ }
33896
+ });
33897
+ views.set(alias, view);
33898
+ return view;
33899
+ }
33900
+ function servedCopyConfig(packageConfig, destinations, allowed, tablesUnderAlias = new Set) {
33739
33901
  const base = toMalloyConfig(packageConfig);
33740
33902
  const config = new MalloyConfig2({ connections: {} });
33741
33903
  config.wrapConnections(() => ({
@@ -33746,7 +33908,8 @@ function servedCopyConfig(packageConfig, destinations, allowed) {
33746
33908
  if (!allowed.has(destination)) {
33747
33909
  throw new Error(`A storage destination is not available to this served copy`);
33748
33910
  }
33749
- return destinations.connections.lookupConnection(destination);
33911
+ const connection = await destinations.connections.lookupConnection(destination);
33912
+ return tablesUnderAlias.has(destination) ? underAlias(connection, name) : connection;
33750
33913
  }
33751
33914
  }
33752
33915
  return base.connections.lookupConnection(name);
@@ -33754,16 +33917,35 @@ function servedCopyConfig(packageConfig, destinations, allowed) {
33754
33917
  }));
33755
33918
  return config;
33756
33919
  }
33757
- var TOKEN, aliases, destinationsByAlias;
33920
+ var TOKEN, aliases, destinationsByAlias, aliasedViews;
33758
33921
  var init_served_copy_config = __esm(() => {
33759
33922
  init_model_runtime();
33760
33923
  TOKEN = randomBytes(12).toString("hex");
33761
33924
  aliases = new Map;
33762
33925
  destinationsByAlias = new Map;
33926
+ aliasedViews = new WeakMap;
33763
33927
  });
33764
33928
 
33765
33929
  // src/service/materialization/text/cross_connection_text.ts
33766
33930
  import { MalloyError as MalloyError3 } from "@malloydata/malloy";
33931
+ function refusedJoinConnections(message) {
33932
+ const named = /which is on connection '([^']*)', into a source on connection '([^']*)'/.exec(message ?? "");
33933
+ return named ? { joined: named[1], into: named[2] } : undefined;
33934
+ }
33935
+ function refusedJoinPairs(error) {
33936
+ if (!isCrossConnectionRefusal(error))
33937
+ return;
33938
+ const pairs = [];
33939
+ for (const p of errorProblems(error) ?? []) {
33940
+ if (p.code !== JOIN_CONNECTION_MISMATCH)
33941
+ continue;
33942
+ const pair = refusedJoinConnections(p.message);
33943
+ if (!pair)
33944
+ return;
33945
+ pairs.push(pair);
33946
+ }
33947
+ return pairs;
33948
+ }
33767
33949
  function isJoinConnectionMismatch(code) {
33768
33950
  return code === JOIN_CONNECTION_MISMATCH;
33769
33951
  }
@@ -33880,10 +34062,12 @@ async function leaveOut(args, escalated) {
33880
34062
  continue;
33881
34063
  }
33882
34064
  cuts.push(cut);
34065
+ const connections = refused ? refusedJoinConnections(p.message) : undefined;
33883
34066
  leftOut.push({
33884
34067
  url,
33885
34068
  ...cut.left,
33886
34069
  crossConnection: refused,
34070
+ ...connections ? { connections } : {},
33887
34071
  ...cut !== own && own?.left.keyword.startsWith("join_") ? { join: own.left.name } : {}
33888
34072
  });
33889
34073
  }
@@ -37348,6 +37532,437 @@ var init_query_walks = __esm(() => {
37348
37532
  walks = new Map;
37349
37533
  });
37350
37534
 
37535
+ // src/service/materialization/domain/same_catalog_build.ts
37536
+ function isSameCatalog(source, destination) {
37537
+ const a = source?.type === "ducklake" ? source.ducklakeConnection : undefined;
37538
+ const b = destination?.type === "ducklake" ? destination.ducklakeConnection : undefined;
37539
+ if (!a || !b)
37540
+ return false;
37541
+ const pa = a.catalog?.postgresConnection;
37542
+ const pb = b.catalog?.postgresConnection;
37543
+ if (!pa || !pb)
37544
+ return false;
37545
+ const path = (url) => (url ?? "").replace(/\/+$/, "");
37546
+ const pathA = path(a.storage?.bucketUrl);
37547
+ const pathB = path(b.storage?.bucketUrl);
37548
+ return !!pa.host && pa.host === pb.host && (pa.port ?? 5432) === (pb.port ?? 5432) && !!pa.databaseName && pa.databaseName === pb.databaseName && (a.catalog.metadataSchema ?? "") === (b.catalog.metadataSchema ?? "") && (pathA === "" || pathB === "" || pathA === pathB);
37549
+ }
37550
+ function carriesAuthorSql(def) {
37551
+ return authorSqlCause(def) !== undefined;
37552
+ }
37553
+ function authorSqlCause(def) {
37554
+ const seen = new Set;
37555
+ const walk = (node, depth, frames) => {
37556
+ if (depth > MAX_DEPTH3)
37557
+ return { found: UNREADABLE2, frames };
37558
+ if (node === null || typeof node !== "object")
37559
+ return;
37560
+ if (seen.has(node))
37561
+ return;
37562
+ seen.add(node);
37563
+ if (Array.isArray(node)) {
37564
+ for (const child of node) {
37565
+ const hit = walk(child, depth + 1, frames);
37566
+ if (hit)
37567
+ return hit;
37568
+ }
37569
+ return;
37570
+ }
37571
+ const record = node;
37572
+ if (typeof record.join === "string") {
37573
+ frames = [
37574
+ ...frames,
37575
+ {
37576
+ kind: "join",
37577
+ as: String(record.as ?? record.name ?? ""),
37578
+ source: sourceNameOf(record)
37579
+ }
37580
+ ];
37581
+ }
37582
+ if (record.type === "sql_select") {
37583
+ return { found: { kind: "sql_source" }, frames };
37584
+ }
37585
+ if (record.node === "genericSQLExpr") {
37586
+ return { found: { kind: "sql_expression" }, frames };
37587
+ }
37588
+ if (record.type === "table" && typeof record.tablePath === "string" && !CATALOG_TABLE_PATH.test(record.tablePath)) {
37589
+ return {
37590
+ found: { kind: "file_table", path: record.tablePath },
37591
+ frames
37592
+ };
37593
+ }
37594
+ for (const [key, child] of Object.entries(record)) {
37595
+ if (record.node === "function_call" && key === "overload")
37596
+ continue;
37597
+ const hit = key === "fields" && Array.isArray(child) ? walkFields(child, depth + 1, frames) : walk(child, depth + 1, key === "structRef" && child !== null && typeof child === "object" ? [
37598
+ ...frames,
37599
+ {
37600
+ kind: "reads",
37601
+ source: sourceNameOf(child)
37602
+ }
37603
+ ] : frames);
37604
+ if (hit)
37605
+ return hit;
37606
+ }
37607
+ return;
37608
+ };
37609
+ const walkFields = (fields, depth, frames) => {
37610
+ if (depth > MAX_DEPTH3)
37611
+ return { found: UNREADABLE2, frames };
37612
+ if (seen.has(fields))
37613
+ return;
37614
+ seen.add(fields);
37615
+ for (const field of fields) {
37616
+ const f = field;
37617
+ const named = f !== null && typeof f === "object" && typeof f.name === "string" && typeof f.join !== "string";
37618
+ const hit = walk(field, depth + 1, named ? [...frames, { kind: "field", name: String(f.name) }] : frames);
37619
+ if (hit)
37620
+ return hit;
37621
+ }
37622
+ return;
37623
+ };
37624
+ try {
37625
+ if (def === null || typeof def !== "object")
37626
+ return describe([], UNREADABLE2);
37627
+ const hit = walk(def, 0, []);
37628
+ return hit ? describe(hit.frames, hit.found) : undefined;
37629
+ } catch {
37630
+ return describe([], UNREADABLE2);
37631
+ }
37632
+ }
37633
+ function sourceNameOf(record) {
37634
+ const id = typeof record.sourceID === "string" ? record.sourceID : "";
37635
+ const name = typeof record.name === "string" ? record.name : "";
37636
+ return id.split("@")[0] || (name.startsWith("sql://") ? "" : name);
37637
+ }
37638
+ function describe(frames, found) {
37639
+ if (found.kind === "unreadable") {
37640
+ return "its definition could not be read to check for SQL its author wrote";
37641
+ }
37642
+ frames = frames.filter((frame, i) => frame.kind !== "reads" || i === frames.length - 1 && found.kind !== "sql_expression");
37643
+ const parts = [];
37644
+ let lead = true;
37645
+ for (const frame of frames) {
37646
+ const possessive = lead ? "its" : "whose";
37647
+ const subject = lead ? "it" : "which";
37648
+ lead = false;
37649
+ if (frame.kind === "join") {
37650
+ parts.push(`${possessive} join '${frame.as}'` + (frame.source ? ` reads source '${frame.source}'` : ""));
37651
+ } else if (frame.kind === "reads") {
37652
+ parts.push(frame.source ? `${subject} reads source '${frame.source}'` : `${subject} reads a source`);
37653
+ } else {
37654
+ parts.push(`${possessive} field '${frame.name}'`);
37655
+ }
37656
+ }
37657
+ const last = frames[frames.length - 1];
37658
+ const subject = frames.length === 0 ? "it" : ", which";
37659
+ const what = found.kind === "sql_source" ? `${subject} is an .sql() source` : found.kind === "file_table" ? `${subject} reads '${found.path.replace(/^'|'$/g, "")}' as a table` : last?.kind === "field" ? " uses a sql_* expression" : `${subject} uses a sql_* expression`;
37660
+ return (parts.join(", ") + what).replace(/^ /, "");
37661
+ }
37662
+ var CATALOG_TABLE_PATH, MAX_DEPTH3 = 200, UNREADABLE2;
37663
+ var init_same_catalog_build = __esm(() => {
37664
+ CATALOG_TABLE_PATH = /^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)*$/;
37665
+ UNREADABLE2 = { kind: "unreadable" };
37666
+ });
37667
+
37668
+ // src/service/materialization/serve/same_catalog_reads.ts
37669
+ function destinationTablePath(path, move) {
37670
+ const parts = path.split(".");
37671
+ if (!PLAIN.test(move.destination) || !parts.every((p) => PLAIN.test(p))) {
37672
+ return;
37673
+ }
37674
+ const self2 = move.connection.toLowerCase();
37675
+ const readable = (s) => move.schemas.has(s.toLowerCase());
37676
+ const at = (schema, table) => `${move.destination}.${schema}.${table}`;
37677
+ if (parts.length === 1)
37678
+ return at("main", parts[0]);
37679
+ if (parts.length === 2) {
37680
+ const [first, table] = parts;
37681
+ if (first.toLowerCase() === self2) {
37682
+ return readable(first) ? undefined : at("main", table);
37683
+ }
37684
+ return readable(first) ? at(first, table) : undefined;
37685
+ }
37686
+ if (parts.length === 3) {
37687
+ const [catalog, schema, table] = parts;
37688
+ return catalog.toLowerCase() === self2 && readable(schema) ? at(schema, table) : undefined;
37689
+ }
37690
+ return;
37691
+ }
37692
+ function literalValue(token) {
37693
+ const m = /^(['"])([^'"\\]*)\1$/.exec(token?.text ?? "");
37694
+ return m ? m[2] : undefined;
37695
+ }
37696
+ function namesConnection(token, name) {
37697
+ 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;
37698
+ }
37699
+ function readThroughDestination(text, move) {
37700
+ const tokens = lexAll(text);
37701
+ if (!tokens)
37702
+ return;
37703
+ const edits = [];
37704
+ const paths = [];
37705
+ for (let k = 0;k < tokens.length; k++) {
37706
+ const t = tokens[k];
37707
+ if (!namesConnection(t, move.connection))
37708
+ continue;
37709
+ if (tokens[k - 1]?.text === ".")
37710
+ continue;
37711
+ if (tokens[k + 1]?.text !== ".")
37712
+ continue;
37713
+ const method = tokens[k + 2];
37714
+ if (method?.kind !== "word")
37715
+ continue;
37716
+ if (method.text !== "table")
37717
+ return;
37718
+ const value = literalValue(tokens[k + 4]);
37719
+ if (tokens[k + 3]?.text !== "(" || value === undefined || tokens[k + 5]?.text !== ")") {
37720
+ return;
37721
+ }
37722
+ const moved = destinationTablePath(value, move);
37723
+ if (moved === undefined)
37724
+ return;
37725
+ paths.push(value);
37726
+ edits.push({
37727
+ start: t.start,
37728
+ end: tokens[k + 5].end,
37729
+ text: `${identifier(move.alias)}.table(${stringLiteral(moved)})`
37730
+ });
37731
+ k += 5;
37732
+ }
37733
+ let out = text;
37734
+ for (const e of edits.reverse()) {
37735
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
37736
+ }
37737
+ return { text: out, paths };
37738
+ }
37739
+ async function sameCatalogMoves(error, ports) {
37740
+ const pairs = refusedJoinPairs(error);
37741
+ if (!pairs?.length)
37742
+ return;
37743
+ const moves = new Map;
37744
+ for (const { joined, into } of pairs) {
37745
+ const intoDestination = destinationOfAlias(into);
37746
+ const joinedDestination = destinationOfAlias(joined);
37747
+ const [connection, alias, destination] = intoDestination !== undefined && joinedDestination === undefined ? [joined, into, intoDestination] : joinedDestination !== undefined && intoDestination === undefined ? [into, joined, joinedDestination] : [];
37748
+ if (!connection || !alias || !destination)
37749
+ return;
37750
+ const known = moves.get(connection);
37751
+ if (known) {
37752
+ if (known.alias !== alias)
37753
+ return;
37754
+ continue;
37755
+ }
37756
+ const schemas = await ports.scope(connection, alias);
37757
+ if (!schemas)
37758
+ return;
37759
+ moves.set(connection, { connection, alias, destination, schemas });
37760
+ }
37761
+ return [...moves.values()];
37762
+ }
37763
+ function movedAuthorSqlCause(modelDef, connections, rerooted) {
37764
+ const { contents } = authorModelReachContext(modelDef);
37765
+ for (const [name, def] of Object.entries(contents)) {
37766
+ const d = def;
37767
+ if (typeof d.connection !== "string" || !connections.has(d.connection)) {
37768
+ continue;
37769
+ }
37770
+ if (typeof d.sourceID === "string" && rerooted.has(d.sourceID)) {
37771
+ for (const field of Array.isArray(d.fields) ? d.fields : []) {
37772
+ const f = field;
37773
+ if (f.join === undefined)
37774
+ continue;
37775
+ const cause = authorSqlCause(field);
37776
+ if (cause)
37777
+ return `the join '${String(f.name)}' of '${name}': ${cause}`;
37778
+ }
37779
+ continue;
37780
+ }
37781
+ const cause = authorSqlCause(def);
37782
+ if (cause)
37783
+ return `the source '${name}': ${cause}`;
37784
+ }
37785
+ return;
37786
+ }
37787
+ function declaringFiles(modelDef, connections) {
37788
+ const { contents } = authorModelReachContext(modelDef);
37789
+ const urls = new Set;
37790
+ for (const def of Object.values(contents)) {
37791
+ const d = def;
37792
+ if (typeof d.connection === "string" && connections.has(d.connection) && typeof d.location?.url === "string") {
37793
+ urls.add(d.location.url);
37794
+ }
37795
+ }
37796
+ return [...urls];
37797
+ }
37798
+ async function readSameCatalogThroughDestination(args) {
37799
+ const moves = await sameCatalogMoves(args.error, args.ports);
37800
+ if (!moves) {
37801
+ return {
37802
+ declined: "a refused join is not into a managed connection's own catalog"
37803
+ };
37804
+ }
37805
+ const names = new Set(moves.map((m) => m.connection));
37806
+ const sql = movedAuthorSqlCause(args.modelDef, names, args.rerooted);
37807
+ if (sql)
37808
+ return { declined: `${sql}, which carries author SQL` };
37809
+ const urls = new Set([
37810
+ ...args.files.keys(),
37811
+ ...declaringFiles(args.modelDef, names)
37812
+ ]);
37813
+ const out = new Map(args.files);
37814
+ const moved = [];
37815
+ for (const move of moves) {
37816
+ const paths = [];
37817
+ for (const url of urls) {
37818
+ const text = out.get(url) ?? args.readText(url);
37819
+ if (text === undefined)
37820
+ return { declined: "a file it cannot read" };
37821
+ const read = readThroughDestination(text, move);
37822
+ if (!read) {
37823
+ return {
37824
+ declined: `connection '${move.connection}' is named other than in a plain .table() it can place`
37825
+ };
37826
+ }
37827
+ if (read.paths.length === 0)
37828
+ continue;
37829
+ paths.push(...read.paths);
37830
+ out.set(url, read.text);
37831
+ }
37832
+ for (const path of paths) {
37833
+ const refused = await args.ports.pathRefusal(path, move.connection, move.schemas);
37834
+ if (refused !== undefined) {
37835
+ return {
37836
+ declined: `table '${path}' is outside the connection's scope`
37837
+ };
37838
+ }
37839
+ }
37840
+ const tables = [...new Set(paths)].map((path) => {
37841
+ const [catalog, schema, table] = destinationTablePath(path, move).split(".");
37842
+ return [catalog, schema, table];
37843
+ });
37844
+ const read = {
37845
+ alias: move.alias,
37846
+ connection: move.connection,
37847
+ schemas: move.schemas,
37848
+ tables
37849
+ };
37850
+ if (!await args.ports.readable(read)) {
37851
+ return {
37852
+ declined: "a table it reads is not a base table, or holds a file outside the connection's storage scope"
37853
+ };
37854
+ }
37855
+ if (tables.length > 0)
37856
+ moved.push(read);
37857
+ }
37858
+ return {
37859
+ files: out,
37860
+ destinations: new Set(moves.map((m) => m.destination)),
37861
+ moved
37862
+ };
37863
+ }
37864
+ var PLAIN;
37865
+ var init_same_catalog_reads = __esm(() => {
37866
+ init_malloy_lexer_core();
37867
+ init_malloy_text();
37868
+ init_same_catalog_build();
37869
+ init_author_model();
37870
+ init_cross_connection_text();
37871
+ init_served_copy_config();
37872
+ PLAIN = /^[A-Za-z_][A-Za-z0-9_]*$/;
37873
+ });
37874
+
37875
+ // src/service/connection_type.ts
37876
+ function normalizeReadableSchemas(list) {
37877
+ const names = [
37878
+ ...new Set(Array.isArray(list) ? list.filter((name) => typeof name === "string") : [])
37879
+ ].filter((name) => name !== "main").sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
37880
+ return names.length > 0 ? names : undefined;
37881
+ }
37882
+ function managedSchemas(readableSchemas) {
37883
+ return new Set([
37884
+ "main",
37885
+ ...normalizeReadableSchemas(readableSchemas) ?? []
37886
+ ]);
37887
+ }
37888
+ function managedOverrideOf(connection) {
37889
+ const name = connection.name;
37890
+ return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
37891
+ }
37892
+ function overrideOf(connection) {
37893
+ const name = connection.name;
37894
+ if (typeof name !== "string")
37895
+ return;
37896
+ for (let i = overrides.length - 1;i >= 0; i--) {
37897
+ const type = overrides[i].get(name);
37898
+ if (type !== undefined)
37899
+ return type;
37900
+ }
37901
+ return;
37902
+ }
37903
+ function recordConnectionType(connection, type, options = {}) {
37904
+ const recordedType = overrideOf(connection) ?? type;
37905
+ if (recordedType)
37906
+ recorded.set(connection, recordedType);
37907
+ if (options.config)
37908
+ configs.set(connection, options.config);
37909
+ if (options.managed === true || managedOverrideOf(connection)) {
37910
+ managed.set(connection, options.schemas ?? MAIN_ONLY);
37911
+ }
37912
+ return connection;
37913
+ }
37914
+ function connectionConfigOf(connection) {
37915
+ return connection ? configs.get(connection) : undefined;
37916
+ }
37917
+ function isManagedConnection(connection) {
37918
+ return !!connection && managed.has(connection);
37919
+ }
37920
+ function managedSchemasOf(connection) {
37921
+ return connection ? managed.get(connection) : undefined;
37922
+ }
37923
+ function resolveManagedConnections(connections) {
37924
+ return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
37925
+ }
37926
+ function connectionTypeOf(connection) {
37927
+ return connection ? recorded.get(connection) : undefined;
37928
+ }
37929
+ function resolveConnectionTypes(connections) {
37930
+ const types = {};
37931
+ for (const [name, connection] of connections) {
37932
+ const type = connectionTypeOf(connection);
37933
+ if (type !== undefined)
37934
+ types[name] = type;
37935
+ }
37936
+ return types;
37937
+ }
37938
+ var recorded, managed, configs, MAIN_ONLY, overrides, managedOverrides;
37939
+ var init_connection_type = __esm(() => {
37940
+ recorded = new WeakMap;
37941
+ managed = new WeakMap;
37942
+ configs = new WeakMap;
37943
+ MAIN_ONLY = managedSchemas();
37944
+ overrides = [];
37945
+ managedOverrides = [];
37946
+ });
37947
+
37948
+ // src/service/same_catalog_destination.ts
37949
+ async function sameCatalogScope(config, connection, alias) {
37950
+ const [source, destination] = await Promise.all([
37951
+ config.connections.lookupConnection(connection).catch(() => {
37952
+ return;
37953
+ }),
37954
+ config.connections.lookupConnection(alias).catch(() => {
37955
+ return;
37956
+ })
37957
+ ]);
37958
+ const schemas = managedSchemasOf(source);
37959
+ return schemas && isSameCatalog(connectionConfigOf(source), connectionConfigOf(destination)) ? schemas : undefined;
37960
+ }
37961
+ var init_same_catalog_destination = __esm(() => {
37962
+ init_connection_type();
37963
+ init_same_catalog_build();
37964
+ });
37965
+
37351
37966
  // src/service/materialization/serve/result_reads.ts
37352
37967
  function nonStringType2(t) {
37353
37968
  return typeof t === "string" && t !== "string";
@@ -38196,27 +38811,69 @@ import {
38196
38811
  function servedConnectionOf(b) {
38197
38812
  return isDatabase(b) ? b.destinationName : servedCopyAlias(b.destinationName);
38198
38813
  }
38199
- function readsLeftOutDefinition(compiled, error, queryString) {
38814
+ function importedFileURLs(modelDef) {
38815
+ const urls = new Set;
38816
+ const walk = (tree, depth) => {
38817
+ if (depth > 64 || typeof tree !== "object" || tree === null)
38818
+ return;
38819
+ for (const [url, below] of Object.entries(tree)) {
38820
+ if (urls.has(url))
38821
+ continue;
38822
+ urls.add(url);
38823
+ walk(below, depth + 1);
38824
+ }
38825
+ };
38826
+ walk(modelDef?.dependencies, 0);
38827
+ return [...urls];
38828
+ }
38829
+ function leftOutJoinDetail(joins) {
38830
+ const named = joins.map((j) => {
38831
+ const join = j.join ?? j.name;
38832
+ const source = j.declaration ?? (j.join !== undefined ? j.name : undefined);
38833
+ const where = source ? ` of \`${source}\`` : "";
38834
+ const across = j.connections ? ` (${servedConnectionLabel(j.connections.joined)} into ` + `${servedConnectionLabel(j.connections.into)})` : "";
38835
+ return `\`${join}\`${where}${across}`;
38836
+ });
38837
+ const subject = named.length === 0 ? "a join" : `the join${named.length === 1 ? "" : "s"} ${named.join(", ")}`;
38838
+ 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.";
38839
+ }
38840
+ function leftOutJoinsRead(compiled, error, queryString) {
38200
38841
  if (!compiled.leftOut?.length)
38201
- return false;
38202
- return readsMissingName(new Set(compiled.leftOut.map((l) => l.name)), error, queryString);
38842
+ return;
38843
+ const read = missingNamesRead(new Set(compiled.leftOut.map((l) => l.name)), error, queryString);
38844
+ if (read === undefined)
38845
+ return;
38846
+ const joins = compiled.leftOut.filter((l) => l.crossConnection);
38847
+ const direct = joins.filter((l) => read.has(l.name));
38848
+ return direct.length > 0 ? direct : joins;
38203
38849
  }
38204
38850
  function readsMissingName(names, error, queryString) {
38851
+ return missingNamesRead(names, error, queryString) !== undefined;
38852
+ }
38853
+ function missingNamesRead(names, error, queryString) {
38205
38854
  if (!(error instanceof MalloyError4))
38206
- return false;
38207
- return error.problems.some((p) => {
38208
- if (p.code === undefined || !MISSING_FIELD_CODES.has(p.code)) {
38209
- return false;
38210
- }
38855
+ return;
38856
+ const read = new Set;
38857
+ let any = false;
38858
+ for (const p of error.problems) {
38859
+ if (p.code === undefined || !MISSING_FIELD_CODES.has(p.code))
38860
+ continue;
38211
38861
  const start = p.at?.range?.start;
38212
38862
  const offset = start ? offsetOf(queryString, start) : -1;
38213
- if (offset < 0)
38214
- return true;
38215
- const path = /^[`A-Za-z0-9_.]+/.exec(queryString.slice(offset))?.[0];
38216
- if (!path)
38217
- return true;
38218
- return path.split(".").some((part) => names.has(part.replace(/^`|`$/g, "")));
38219
- });
38863
+ const path = offset < 0 ? undefined : /^[`A-Za-z0-9_.]+/.exec(queryString.slice(offset))?.[0];
38864
+ if (!path) {
38865
+ any = true;
38866
+ continue;
38867
+ }
38868
+ for (const part of path.split(".")) {
38869
+ const name = part.replace(/^`|`$/g, "");
38870
+ if (names.has(name)) {
38871
+ read.add(name);
38872
+ any = true;
38873
+ }
38874
+ }
38875
+ }
38876
+ return any ? read : undefined;
38220
38877
  }
38221
38878
  function rerootFailureKey(packagePath, modelPath, bindings, overlay) {
38222
38879
  const hash = createHash2("sha256");
@@ -38368,6 +39025,7 @@ class ServedCopyServe {
38368
39025
  ...asWritten ? { tableIds: asWritten.tableIds } : {}
38369
39026
  });
38370
39027
  }
39028
+ await this.recheckSameCatalog(compiled);
38371
39029
  const declined = compiled.declined?.get(queryString);
38372
39030
  if (declined !== undefined)
38373
39031
  throw declined;
@@ -38386,8 +39044,10 @@ class ServedCopyServe {
38386
39044
  try {
38387
39045
  return await work();
38388
39046
  } catch (error) {
38389
- if (readsLeftOutDefinition(compiled, error, queryString)) {
38390
- decline("the query reads a join the served copy leaves out across connections", "served_copy_cross_connection", LEFT_OUT_JOIN_DETAIL);
39047
+ const leftOutJoins = leftOutJoinsRead(compiled, error, queryString);
39048
+ if (leftOutJoins) {
39049
+ const detail = leftOutJoinDetail(leftOutJoins);
39050
+ decline(`the query reads a join the served copy leaves out across connections: ${detail}`, "served_copy_cross_connection", detail);
38391
39051
  }
38392
39052
  const zoned = new Set([...compiled.zonedLeftOut?.values() ?? []].flatMap((n) => [
38393
39053
  ...n
@@ -38575,6 +39235,7 @@ class ServedCopyServe {
38575
39235
  };
38576
39236
  }
38577
39237
  async checkJoinVariant(compiled, args) {
39238
+ await this.recheckSameCatalog(compiled);
38578
39239
  const decline = (reason, code, callerDetail) => {
38579
39240
  throw new LegDecline(code, callerDetail, { message: reason });
38580
39241
  };
@@ -38610,6 +39271,17 @@ class ServedCopyServe {
38610
39271
  decline
38611
39272
  });
38612
39273
  }
39274
+ async recheckSameCatalog(compiled) {
39275
+ if (!compiled.sameCatalogRecheck)
39276
+ return;
39277
+ const ok = await compiled.sameCatalogRecheck().catch(() => false);
39278
+ if (ok)
39279
+ return;
39280
+ 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() });
39281
+ throw new LegDecline("served_copy_not_served", undefined, {
39282
+ 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"
39283
+ });
39284
+ }
38613
39285
  readsRollingWindow(binding) {
38614
39286
  return (binding.sourceIDs ?? []).some((id) => rollingWindowsOf(this.materializePlans[id]?.readTimeTerms).length > 0);
38615
39287
  }
@@ -38938,6 +39610,39 @@ class ServedCopyServe {
38938
39610
  rerootedSpans
38939
39611
  };
38940
39612
  }
39613
+ ownSqlEmbedReach(struct, modelDef) {
39614
+ return ownSqlEmbedReach(struct, modelDef);
39615
+ }
39616
+ withoutConflictingSqlEmbeds(candidates, map, problems) {
39617
+ const modelDef = this.host.modelDef();
39618
+ const reads = sqlEmbedReads([
39619
+ modelDef,
39620
+ ...importedFileURLs(modelDef).map((url) => this.host.siblingModelDef?.(url))
39621
+ ]);
39622
+ if (reads.length === 0)
39623
+ return candidates;
39624
+ const rerootedIDs = new Set(candidates.map((c) => c.reroot.sourceID));
39625
+ const rerooted = (sqlSourceID) => {
39626
+ const node = map.node(sqlSourceID);
39627
+ const chain = node ? map.chainOf(node.def) : [sqlSourceID];
39628
+ return chain.some((id) => rerootedIDs.has(id));
39629
+ };
39630
+ return candidates.filter((c) => {
39631
+ const conflicts = conflictingSqlEmbeds(reads, c.reroot.sourceID, servedConnectionOf(c.binding), rerooted);
39632
+ if (conflicts.length === 0)
39633
+ return true;
39634
+ const whole = conflicts.some((x) => x.conflict === "bare");
39635
+ problems.push({
39636
+ sourceName: c.reroot.sourceName,
39637
+ sourceID: c.reroot.sourceID,
39638
+ reason: whole ? "sql_embed_bare" : "sql_embed_cross_connection",
39639
+ detail: [
39640
+ ...new Set(conflicts.filter((x) => !whole || x.conflict === "bare").map(({ read }) => `\`${read.via}\` on \`${read.connection}\``))
39641
+ ].join(", ")
39642
+ });
39643
+ return false;
39644
+ });
39645
+ }
38941
39646
  rerootCandidates(bindings, map, lift, problems, lane, passedOver = new Set, twins, restatesStageZoned = false) {
38942
39647
  let candidates = [];
38943
39648
  const reservedNames = modelFieldNames(map);
@@ -38967,6 +39672,7 @@ class ServedCopyServe {
38967
39672
  const tiers = (byKey.get(keyOf(c)) ?? []).filter((o) => !passedOver.has(o.binding)).map((o) => o.binding.tier);
38968
39673
  return servedCopyReadsTier(c.binding.tier, tiers);
38969
39674
  });
39675
+ candidates = this.withoutConflictingSqlEmbeds(candidates, map, problems);
38970
39676
  const rerootedIDs = new Set(candidates.map((c) => c.reroot.sourceID));
38971
39677
  const rerootedNames = new Set(candidates.map((c) => c.reroot.sourceName));
38972
39678
  const throughBase = [];
@@ -39134,9 +39840,11 @@ class ServedCopyServe {
39134
39840
  }));
39135
39841
  const overlay = new Map(copy.files);
39136
39842
  const packagePath = this.packagePath;
39137
- const config = servedCopyConfig(this.packageConfig, destinations(), new Set(rerooted.filter((b) => !isDatabase(b)).map((b) => b.destinationName)));
39138
- const load = this.passLoader(packagePath, config);
39139
- const loaded = await this.loadCopy(state, copy, overlay, load, lift);
39843
+ const packageConfig = this.packageConfig;
39844
+ const config = servedCopyConfig(packageConfig, destinations(), new Set(rerooted.filter((b) => !isDatabase(b)).map((b) => b.destinationName)));
39845
+ const load = this.passLoader(packagePath, config, aliased);
39846
+ const underAlias = this.underAliasLoader(packagePath, packageConfig, destinations, rerooted);
39847
+ const loaded = await this.loadCopy(state, copy, overlay, load, lift, config, underAlias);
39140
39848
  if (loaded === "retry")
39141
39849
  continue;
39142
39850
  if (loaded === "failed") {
@@ -39170,10 +39878,11 @@ class ServedCopyServe {
39170
39878
  materializer,
39171
39879
  leftOut,
39172
39880
  files,
39173
- config,
39881
+ config: loaded.config ?? config,
39174
39882
  rerooted,
39175
39883
  aliased,
39176
- throughBase
39884
+ throughBase,
39885
+ sameCatalogReads: loaded.sameCatalogReads
39177
39886
  });
39178
39887
  }
39179
39888
  return {
@@ -39186,7 +39895,21 @@ class ServedCopyServe {
39186
39895
  problems
39187
39896
  };
39188
39897
  }
39189
- passLoader(packagePath, config) {
39898
+ underAliasLoader(packagePath, packageConfig, destinations, rerooted) {
39899
+ const aliased = rerooted.map((b) => ({
39900
+ ...b,
39901
+ destinationName: servedConnectionOf(b)
39902
+ }));
39903
+ return (names) => {
39904
+ const config = servedCopyConfig(packageConfig, destinations(), new Set(rerooted.filter((b) => !isDatabase(b)).map((b) => b.destinationName)), names);
39905
+ return {
39906
+ config,
39907
+ load: this.passLoader(packagePath, config, aliased)
39908
+ };
39909
+ };
39910
+ }
39911
+ passLoader(packagePath, config, aliased) {
39912
+ const virtualMap = buildVirtualMap(aliased);
39190
39913
  const modelPath = this.host.modelPath();
39191
39914
  const compiler = packageFiles(packagePath, modelPath, config);
39192
39915
  return async (files) => {
@@ -39194,11 +39917,14 @@ class ServedCopyServe {
39194
39917
  packagePath,
39195
39918
  modelPath,
39196
39919
  config,
39197
- files: keyedOverlay(files)
39920
+ files: keyedOverlay(files),
39921
+ virtualMap
39198
39922
  });
39199
39923
  if (elsewhere)
39200
39924
  return elsewhere;
39201
- const { runtime, materializer } = await compiler.loadModel(files);
39925
+ const { runtime, materializer } = await compiler.loadModel(files, {
39926
+ virtualMap
39927
+ });
39202
39928
  const model = await materializer.getModel();
39203
39929
  return {
39204
39930
  materializer,
@@ -39243,7 +39969,7 @@ class ServedCopyServe {
39243
39969
  }
39244
39970
  byKey.set(key, { error, until: asOf + REROOT_FAILURE_TTL_MS });
39245
39971
  }
39246
- async loadCopy(state, copy, overlay, load, lift) {
39972
+ async loadCopy(state, copy, overlay, load, lift, config, underAlias) {
39247
39973
  const { withoutKept, problems } = state;
39248
39974
  let materializer;
39249
39975
  let servedDef;
@@ -39276,6 +40002,9 @@ class ServedCopyServe {
39276
40002
  return "retry";
39277
40003
  }
39278
40004
  const byURL = new Map([...copy.files].map(([url, text]) => [url, text]));
40005
+ const merged = await this.readSameCatalogThroughDestination(state, err, byURL, lift, config, underAlias);
40006
+ if (merged)
40007
+ return merged;
39279
40008
  const kept = await leaveOutCrossConnectionJoins({
39280
40009
  firstError: err,
39281
40010
  overlay: byURL,
@@ -39341,6 +40070,45 @@ class ServedCopyServe {
39341
40070
  }
39342
40071
  return { materializer, servedDef, servedRuntime, leftOut, files };
39343
40072
  }
40073
+ async readSameCatalogThroughDestination(state, err, files, lift, config, underAlias) {
40074
+ const moved = await readSameCatalogThroughDestination({
40075
+ error: err,
40076
+ files,
40077
+ readText: (u) => lift.fileText(u),
40078
+ modelDef: this.host.modelDef(),
40079
+ rerooted: new Set(state.candidates.map((c) => c.reroot.sourceID)),
40080
+ ports: {
40081
+ scope: (connection, alias) => sameCatalogScope(config, connection, alias),
40082
+ pathRefusal: (path, connection, schemas) => this.host.managedTablePathRefusal ? this.host.managedTablePathRefusal(path, connection, schemas) : Promise.resolve("no managed scope check is available"),
40083
+ readable: (read) => this.host.sameCatalogTablesReadable ? this.host.sameCatalogTablesReadable(config, read) : Promise.resolve(false)
40084
+ }
40085
+ }).catch(() => ({ declined: "a read of its connections failed" }));
40086
+ if ("declined" in moved) {
40087
+ 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 });
40088
+ return;
40089
+ }
40090
+ const keyed = keyedOverlay(moved.files);
40091
+ const { config: aliased, load } = underAlias(moved.destinations);
40092
+ try {
40093
+ const loaded = await load(keyed);
40094
+ logger.debug("A served copy reads a joined source on its destination's catalog through the destination", { modelPath: this.host.modelPath() });
40095
+ return {
40096
+ materializer: loaded.materializer,
40097
+ servedDef: loaded.def,
40098
+ servedRuntime: loaded.runtime,
40099
+ leftOut: [],
40100
+ files: keyed,
40101
+ config: aliased,
40102
+ sameCatalogReads: moved.moved
40103
+ };
40104
+ } catch (again) {
40105
+ logger.debug("A served copy's same-catalog read does not compile; its joins are left out", {
40106
+ modelPath: this.host.modelPath(),
40107
+ codes: errorProblems(again)?.map((p) => p.code)
40108
+ });
40109
+ return;
40110
+ }
40111
+ }
39344
40112
  contain(state, copy, error, files, mode, remembered = false) {
39345
40113
  const { withoutKept, problems } = state;
39346
40114
  const failing = new Map(failingReroots(error, files, copy.spans, mode).map((f) => [
@@ -39395,6 +40163,7 @@ class ServedCopyServe {
39395
40163
  const { key, generation, over, lane, modelDef, servedMap } = built;
39396
40164
  const { servedDef, servedRuntime, materializer, leftOut } = built;
39397
40165
  const { files, config, rerooted, aliased, throughBase } = built;
40166
+ const sameCatalogReads = built.sameCatalogReads ?? [];
39398
40167
  const optOutIDs = new Set;
39399
40168
  for (const node of servedMap.nodes()) {
39400
40169
  if (optsOutOfPersist(node.def)) {
@@ -39406,7 +40175,9 @@ class ServedCopyServe {
39406
40175
  if (!l.crossConnection)
39407
40176
  continue;
39408
40177
  const sourceName = l.declaration ?? l.name;
40178
+ const sourceID = l.join === undefined ? candidates.find((c) => c.reroot.sourceName === sourceName && c.reroot.url === l.url)?.reroot.sourceID : undefined;
39409
40179
  problems.push({
40180
+ ...sourceID !== undefined ? { storedSourceID: sourceID } : {},
39410
40181
  sourceName,
39411
40182
  reason: "cross_connection_join",
39412
40183
  join: l.join ?? l.name,
@@ -39461,6 +40232,15 @@ class ServedCopyServe {
39461
40232
  rerooted,
39462
40233
  rerootedSourceIDs: rerootedSourceIDsOf(candidates, throughBase),
39463
40234
  ...throughBase.length > 0 ? { throughBase } : {},
40235
+ ...sameCatalogReads.length > 0 ? {
40236
+ sameCatalogRecheck: async () => {
40237
+ const readable = this.host.sameCatalogTablesReadable;
40238
+ if (!readable)
40239
+ return false;
40240
+ const each = await Promise.all(sameCatalogReads.map((r) => readable(config, r)));
40241
+ return each.every(Boolean);
40242
+ }
40243
+ } : {},
39464
40244
  aliased,
39465
40245
  problems,
39466
40246
  pairs: candidates.flatMap((c) => c.reroot.pair ? [
@@ -40601,7 +41381,7 @@ function zonedTruncations(columns, def, fieldsByName, chainZone, restatesStageZo
40601
41381
  restated: []
40602
41382
  };
40603
41383
  }
40604
- var NOTHING_PINNED, NO_DESTINATIONS = () => new MalloyConfig3({ 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;
41384
+ var NOTHING_PINNED, NO_DESTINATIONS = () => new MalloyConfig3({ 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;
40605
41385
  var init_served_copy_serve = __esm(() => {
40606
41386
  init_ducklake_catalog_unavailable();
40607
41387
  init_served_copy_lanes();
@@ -40610,6 +41390,7 @@ var init_served_copy_serve = __esm(() => {
40610
41390
  init_filter_binding_guard();
40611
41391
  init_authorize();
40612
41392
  init_overlay_key();
41393
+ init_sql_embed_reads();
40613
41394
  init_event_loop_yield();
40614
41395
  init_package_files();
40615
41396
  init_source_map();
@@ -40637,6 +41418,8 @@ var init_served_copy_serve = __esm(() => {
40637
41418
  init_utils();
40638
41419
  init_served_copy_checks();
40639
41420
  init_query_walks();
41421
+ init_same_catalog_reads();
41422
+ init_same_catalog_destination();
40640
41423
  init_chain_string_reads();
40641
41424
  NOTHING_PINNED = pin(EMPTY_SNAPSHOT, new Date(0));
40642
41425
  MISSING_FIELD_CODES = new Set([
@@ -41275,7 +42058,7 @@ function computeSourceContentSha(packagePath, contentPaths, extra, contentShas)
41275
42058
  try {
41276
42059
  hash.update(fs5.readFileSync(confinedPackagePathSync(packagePath, pathToFileURL6(absolute))));
41277
42060
  } catch {
41278
- hash.update(UNREADABLE2);
42061
+ hash.update(UNREADABLE3);
41279
42062
  }
41280
42063
  }
41281
42064
  hash.update("\x00");
@@ -41302,7 +42085,7 @@ function canonicalSha(value) {
41302
42085
  function mintServedRevision() {
41303
42086
  return randomUUID();
41304
42087
  }
41305
- var UNREADABLE2 = "\x00<unreadable>\x00", MANIFEST_AGENTS_MAX_BYTES;
42088
+ var UNREADABLE3 = "\x00<unreadable>\x00", MANIFEST_AGENTS_MAX_BYTES;
41306
42089
  var init_package_revision = __esm(() => {
41307
42090
  init_utils();
41308
42091
  MANIFEST_AGENTS_MAX_BYTES = 1024 * 1024;
@@ -42495,6 +43278,7 @@ function getEntitiesFromExplore(explore, docString, relativePath, parentPath, so
42495
43278
  nameOverride = `${joinPath}.${field.name}`;
42496
43279
  }
42497
43280
  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);
43281
+ inheritJoinedDoc(codeEntity, field, explore);
42498
43282
  const fingerprint = dimIndexFingerprints.get(makeDimIndexLookupKey(sourceName, field.name));
42499
43283
  if (fingerprint) {
42500
43284
  codeEntity.dim_index_fingerprint = {
@@ -42506,6 +43290,39 @@ function getEntitiesFromExplore(explore, docString, relativePath, parentPath, so
42506
43290
  }
42507
43291
  return entities;
42508
43292
  }
43293
+ function inheritJoinedDoc(entity, field, explore) {
43294
+ if (entity.description !== undefined || field.isExploreField())
43295
+ return;
43296
+ const defs = explore.structDef.fields;
43297
+ const pathOf = (name) => {
43298
+ const e = defs?.find((f) => (f.as ?? f.name) === name)?.e;
43299
+ return e?.node === "field" && Array.isArray(e.path) && e.path.every((p) => typeof p === "string") ? e.path : undefined;
43300
+ };
43301
+ let path = pathOf(field.name);
43302
+ for (let depth = 0;path?.length === 1; depth++) {
43303
+ const link = explore.getFieldByNameIfExists(path[0]);
43304
+ if (depth >= MAX_ALIAS_CHAIN || !link || link.isExploreField() || getAccessModifier(link) !== "public" /* Public */ || getDescriptionFromTags(getTags(link)) !== undefined) {
43305
+ return;
43306
+ }
43307
+ path = pathOf(link.name);
43308
+ }
43309
+ if (path?.length !== 2)
43310
+ return;
43311
+ const [joinName, fieldName] = path;
43312
+ const join = explore.getFieldByNameIfExists(joinName);
43313
+ if (!join?.isExploreField() || getAccessModifier(join) !== "public" /* Public */) {
43314
+ return;
43315
+ }
43316
+ const joined = join.getFieldByNameIfExists(fieldName);
43317
+ if (!joined || joined.isExploreField() || getAccessModifier(joined) !== "public" /* Public */) {
43318
+ return;
43319
+ }
43320
+ const doc = getDescriptionFromTags(getTags(joined));
43321
+ if (doc === undefined)
43322
+ return;
43323
+ entity.description = doc;
43324
+ entity.doc_inherited_from = `${joinName}.${fieldName}`;
43325
+ }
42509
43326
  function planJoinAuthorizeMetadata(explore, docString, relativePath, parentPath, parentAuthorize, sourceToModelPath, topLevelExploreNames, boundary, modelGivens, modelAuthorize, alwaysSeenSourceKeys, guarded, sourceDefsByName) {
42510
43327
  const plan = [];
42511
43328
  const sourceName = composeSourceName(parentPath, explore.name);
@@ -42606,7 +43423,7 @@ function resolveJoinMetadata(plan, nonQueryableSourceNames, rootIsQueryable, see
42606
43423
  resolveJoinMetadata(descend.children, nonQueryableSourceNames, rootIsQueryable, seenSourceKeys, out);
42607
43424
  }
42608
43425
  }
42609
- var extractDocsFromExplore = (explore) => {
43426
+ var MAX_ALIAS_CHAIN = 8, extractDocsFromExplore = (explore) => {
42610
43427
  const parts = getDirectTaglines(explore).map((text) => parseDocAnnotation(text)).filter((doc) => !!doc && doc.length > 0);
42611
43428
  return parts.length > 0 ? parts.join(`
42612
43429
  `) : null;
@@ -43181,26 +43998,26 @@ function fcjSettingsOf(retrieval) {
43181
43998
  function fail(message) {
43182
43999
  throw new PackageManifestError(message);
43183
44000
  }
43184
- function describe(value) {
44001
+ function describe2(value) {
43185
44002
  return JSON.stringify(value) ?? "nothing";
43186
44003
  }
43187
44004
  function resolvePromptPath(packageRoot, rel, promptKey = "judge") {
43188
44005
  const key = `retrieval.prompts.${promptKey}`;
43189
44006
  const fix = `Fix: use a path inside the package, e.g. "prompts/${promptKey}.md".`;
43190
44007
  if (rel.includes("\x00") || path10.isAbsolute(rel) || /^[A-Za-z]:[\\/]/.test(rel) || rel.startsWith("\\")) {
43191
- fail(`Invalid publisher.json ${key}: ${describe(rel)} is an absolute path. ${fix}`);
44008
+ fail(`Invalid publisher.json ${key}: ${describe2(rel)} is an absolute path. ${fix}`);
43192
44009
  }
43193
44010
  const root = path10.resolve(packageRoot);
43194
44011
  const resolved = path10.resolve(root, rel);
43195
44012
  const within = path10.relative(root, resolved);
43196
44013
  if (within === "" || stepsOutside(within)) {
43197
- fail(`Invalid publisher.json ${key}: ${describe(rel)} resolves outside the package directory. ${fix}`);
44014
+ fail(`Invalid publisher.json ${key}: ${describe2(rel)} resolves outside the package directory. ${fix}`);
43198
44015
  }
43199
44016
  return resolved;
43200
44017
  }
43201
44018
  function objectBlock(raw, key, valid, fix) {
43202
44019
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
43203
- fail(`Invalid publisher.json ${key}: expected an object, got ${describe(raw)}. Fix: ${fix}`);
44020
+ fail(`Invalid publisher.json ${key}: expected an object, got ${describe2(raw)}. Fix: ${fix}`);
43204
44021
  }
43205
44022
  const obj = raw;
43206
44023
  const unknown = Object.keys(obj).filter((k) => !valid.includes(k));
@@ -43214,7 +44031,7 @@ function parseEnabled(value, key) {
43214
44031
  return "auto";
43215
44032
  if (value === "auto" || value === true || value === false)
43216
44033
  return value;
43217
- return fail(`Invalid publisher.json ${key}: expected "auto", true or false, got ${describe(value)}. ` + `Fix: "enabled": "auto" (on when the server has an LLM), true (require one) or false.`);
44034
+ return fail(`Invalid publisher.json ${key}: expected "auto", true or false, got ${describe2(value)}. ` + `Fix: "enabled": "auto" (on when the server has an LLM), true (require one) or false.`);
43218
44035
  }
43219
44036
  function parseSourceSummary(raw) {
43220
44037
  const obj = objectBlock(raw, "retrieval.sourceSummary", SOURCE_SUMMARY_KEYS, `"sourceSummary": { "enabled": "auto" }`);
@@ -43226,42 +44043,42 @@ function fcjNumber(obj, key, check) {
43226
44043
  const value = obj[key] ?? DEFAULT_FCJ_SETTINGS[key];
43227
44044
  const ok = typeof value === "number" && Number.isFinite(value) && value >= check.min && value <= check.max && (!check.integer || Number.isSafeInteger(value));
43228
44045
  if (!ok) {
43229
- fail(`Invalid publisher.json retrieval.fcj.${key}: expected ${check.integer ? "an integer" : "a number"} from ${check.min} to ${check.max}, got ${describe(obj[key])}. ` + `Fix: "${key}": ${JSON.stringify(DEFAULT_FCJ_SETTINGS[key])}`);
44046
+ fail(`Invalid publisher.json retrieval.fcj.${key}: expected ${check.integer ? "an integer" : "a number"} from ${check.min} to ${check.max}, got ${describe2(obj[key])}. ` + `Fix: "${key}": ${JSON.stringify(DEFAULT_FCJ_SETTINGS[key])}`);
43230
44047
  }
43231
44048
  return value;
43232
44049
  }
43233
44050
  function fcjBoolean(obj, key) {
43234
44051
  const value = obj[key] ?? DEFAULT_FCJ_SETTINGS[key];
43235
44052
  if (typeof value !== "boolean") {
43236
- fail(`Invalid publisher.json retrieval.fcj.${key}: expected true or false, got ${describe(obj[key])}. ` + `Fix: "${key}": ${JSON.stringify(DEFAULT_FCJ_SETTINGS[key])}`);
44053
+ fail(`Invalid publisher.json retrieval.fcj.${key}: expected true or false, got ${describe2(obj[key])}. ` + `Fix: "${key}": ${JSON.stringify(DEFAULT_FCJ_SETTINGS[key])}`);
43237
44054
  }
43238
44055
  return value;
43239
44056
  }
43240
44057
  function fcjConnect(obj) {
43241
44058
  const value = obj.connect ?? DEFAULT_FCJ_SETTINGS.connect;
43242
44059
  if (!FCJ_CONNECT_MODES.includes(value)) {
43243
- fail(`Invalid publisher.json retrieval.fcj.connect: expected one of ${FCJ_CONNECT_MODES.join(", ")}, got ${describe(obj.connect)}. ` + `Fix: "connect": "clusters" (source groups) or "list" (the find stage's top listTopK per target).`);
44060
+ fail(`Invalid publisher.json retrieval.fcj.connect: expected one of ${FCJ_CONNECT_MODES.join(", ")}, got ${describe2(obj.connect)}. ` + `Fix: "connect": "clusters" (source groups) or "list" (the find stage's top listTopK per target).`);
43244
44061
  }
43245
44062
  return value;
43246
44063
  }
43247
44064
  function fcjQuestionsPrompt(obj) {
43248
44065
  const value = obj.questionsPrompt ?? DEFAULT_FCJ_SETTINGS.questionsPrompt;
43249
44066
  if (!QUESTIONS_PROMPTS.includes(value)) {
43250
- fail(`Invalid publisher.json retrieval.fcj.questionsPrompt: expected one of ${QUESTIONS_PROMPTS.join(", ")}, got ${describe(obj.questionsPrompt)}. ` + `Fix: "questionsPrompt": "questions" (what a person asks), "phrases" (what an agent types as a search target) or "values" (questions that filter by the field's values).`);
44067
+ fail(`Invalid publisher.json retrieval.fcj.questionsPrompt: expected one of ${QUESTIONS_PROMPTS.join(", ")}, got ${describe2(obj.questionsPrompt)}. ` + `Fix: "questionsPrompt": "questions" (what a person asks), "phrases" (what an agent types as a search target) or "values" (questions that filter by the field's values).`);
43251
44068
  }
43252
44069
  return value;
43253
44070
  }
43254
44071
  function fcjAlsoLikely(obj) {
43255
44072
  const value = obj.alsoLikely ?? DEFAULT_FCJ_SETTINGS.alsoLikely;
43256
44073
  if (!FCJ_ALSO_LIKELY.includes(value)) {
43257
- fail(`Invalid publisher.json retrieval.fcj.alsoLikely: expected "auto", true or false, got ${describe(obj.alsoLikely)}. ` + `Fix: "alsoLikely": "auto" (on with connect "list", off with "clusters").`);
44074
+ fail(`Invalid publisher.json retrieval.fcj.alsoLikely: expected "auto", true or false, got ${describe2(obj.alsoLikely)}. ` + `Fix: "alsoLikely": "auto" (on with connect "list", off with "clusters").`);
43258
44075
  }
43259
44076
  return value;
43260
44077
  }
43261
44078
  function fcjJoinedCopies(obj) {
43262
44079
  const value = obj.joinedCopies ?? DEFAULT_FCJ_SETTINGS.joinedCopies;
43263
44080
  if (!FCJ_JOINED_COPIES.includes(value)) {
43264
- fail(`Invalid publisher.json retrieval.fcj.joinedCopies: expected one of ${FCJ_JOINED_COPIES.join(", ")}, got ${describe(obj.joinedCopies)}. ` + `Fix: "joinedCopies": "indexed" (joined copies are searchable rows) or "routes" (each field is searched on its own source and shown with its routes).`);
44081
+ fail(`Invalid publisher.json retrieval.fcj.joinedCopies: expected one of ${FCJ_JOINED_COPIES.join(", ")}, got ${describe2(obj.joinedCopies)}. ` + `Fix: "joinedCopies": "indexed" (joined copies are searchable rows) or "routes" (each field is searched on its own source and shown with its routes).`);
43265
44082
  }
43266
44083
  return value;
43267
44084
  }
@@ -43272,7 +44089,7 @@ function fcjJudgeLlm(obj) {
43272
44089
  const example = `"judgeLlm": { "model": "claude-haiku-5-5" }`;
43273
44090
  const o = objectBlock(raw, "retrieval.fcj.judgeLlm", ["model"], example);
43274
44091
  if (typeof o.model !== "string" || o.model.trim() === "") {
43275
- fail(`Invalid publisher.json retrieval.fcj.judgeLlm.model: expected a non-empty string, got ${describe(o.model)}. ` + `The provider, host and key are the server's retrieval.llm settings. Fix: ${example}`);
44092
+ fail(`Invalid publisher.json retrieval.fcj.judgeLlm.model: expected a non-empty string, got ${describe2(o.model)}. ` + `The provider, host and key are the server's retrieval.llm settings. Fix: ${example}`);
43276
44093
  }
43277
44094
  return { model: o.model.trim() };
43278
44095
  }
@@ -43321,7 +44138,7 @@ function parsePackageRetrieval(raw) {
43321
44138
  return { promptPaths: {} };
43322
44139
  }
43323
44140
  if (typeof raw !== "object" || Array.isArray(raw)) {
43324
- fail(`Invalid publisher.json retrieval: expected an object, got ${describe(raw)}. ` + `Fix: "retrieval": { "fcj": { "perTarget": 30 } }`);
44141
+ fail(`Invalid publisher.json retrieval: expected an object, got ${describe2(raw)}. ` + `Fix: "retrieval": { "fcj": { "perTarget": 30 } }`);
43325
44142
  }
43326
44143
  const obj = raw;
43327
44144
  const unknown = Object.keys(obj).filter((k) => !RETRIEVAL_KEYS.includes(k) && !(k in IGNORED_RETRIEVAL_KEYS));
@@ -43333,7 +44150,7 @@ function parsePackageRetrieval(raw) {
43333
44150
  const promptPaths = {};
43334
44151
  if (obj.prompts !== undefined && obj.prompts !== null) {
43335
44152
  if (typeof obj.prompts !== "object" || Array.isArray(obj.prompts)) {
43336
- fail(`Invalid publisher.json retrieval.prompts: expected an object, got ${describe(obj.prompts)}. ` + `Fix: "prompts": { "judge": "prompts/judge.md" }`);
44153
+ fail(`Invalid publisher.json retrieval.prompts: expected an object, got ${describe2(obj.prompts)}. ` + `Fix: "prompts": { "judge": "prompts/judge.md" }`);
43337
44154
  }
43338
44155
  const prompts = obj.prompts;
43339
44156
  const badPrompt = Object.keys(prompts).filter((k) => !PROMPT_KEYS.includes(k) && !(k in IGNORED_PROMPT_KEYS));
@@ -43345,7 +44162,7 @@ function parsePackageRetrieval(raw) {
43345
44162
  if (value === undefined || value === null)
43346
44163
  continue;
43347
44164
  if (typeof value !== "string" || value.trim() === "") {
43348
- fail(`Invalid publisher.json retrieval.prompts.${key}: expected a file path inside the package, got ${describe(value)}. ` + `Fix: "${key}": "prompts/${key}.md"`);
44165
+ fail(`Invalid publisher.json retrieval.prompts.${key}: expected a file path inside the package, got ${describe2(value)}. ` + `Fix: "${key}": "prompts/${key}.md"`);
43349
44166
  }
43350
44167
  promptPaths[key] = value;
43351
44168
  }
@@ -43391,16 +44208,16 @@ async function readPromptFile(packageRoot, key, rel) {
43391
44208
  } catch (error) {
43392
44209
  if (!(error instanceof ImportOutsidePackageError))
43393
44210
  throw error;
43394
- return fail(`Invalid publisher.json ${at}: ${describe(rel)} resolves outside the package directory through a link. ` + `Fix: copy the file into the package.`);
44211
+ return fail(`Invalid publisher.json ${at}: ${describe2(rel)} resolves outside the package directory through a link. ` + `Fix: copy the file into the package.`);
43395
44212
  }
43396
44213
  text = await fs8.promises.readFile(realFile, "utf8");
43397
44214
  } catch (error) {
43398
44215
  if (error instanceof PackageManifestError)
43399
44216
  throw error;
43400
- return fail(`Invalid publisher.json ${at}: cannot read ${describe(rel)} (${callerVisibleText(error.message, packageRoot)}). ` + `Fix: create the file inside the package or remove the key.`);
44217
+ return fail(`Invalid publisher.json ${at}: cannot read ${describe2(rel)} (${callerVisibleText(error.message, packageRoot)}). ` + `Fix: create the file inside the package or remove the key.`);
43401
44218
  }
43402
44219
  if (text.trim() === "") {
43403
- fail(`Invalid publisher.json ${at}: ${describe(rel)} is empty. ` + `Fix: write the prompt, or remove the key to use the built-in one.`);
44220
+ fail(`Invalid publisher.json ${at}: ${describe2(rel)} is empty. ` + `Fix: write the prompt, or remove the key to use the built-in one.`);
43404
44221
  }
43405
44222
  return {
43406
44223
  path: rel,
@@ -43605,73 +44422,6 @@ var init_render_tag_targets = __esm(() => {
43605
44422
  init_malloy_text();
43606
44423
  });
43607
44424
 
43608
- // src/service/connection_type.ts
43609
- function normalizeReadableSchemas(list) {
43610
- const names = [
43611
- ...new Set(Array.isArray(list) ? list.filter((name) => typeof name === "string") : [])
43612
- ].filter((name) => name !== "main").sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
43613
- return names.length > 0 ? names : undefined;
43614
- }
43615
- function managedSchemas(readableSchemas) {
43616
- return new Set([
43617
- "main",
43618
- ...normalizeReadableSchemas(readableSchemas) ?? []
43619
- ]);
43620
- }
43621
- function managedOverrideOf(connection) {
43622
- const name = connection.name;
43623
- return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
43624
- }
43625
- function overrideOf(connection) {
43626
- const name = connection.name;
43627
- if (typeof name !== "string")
43628
- return;
43629
- for (let i = overrides.length - 1;i >= 0; i--) {
43630
- const type = overrides[i].get(name);
43631
- if (type !== undefined)
43632
- return type;
43633
- }
43634
- return;
43635
- }
43636
- function recordConnectionType(connection, type, options = {}) {
43637
- const recordedType = overrideOf(connection) ?? type;
43638
- if (recordedType)
43639
- recorded.set(connection, recordedType);
43640
- if (options.managed === true || managedOverrideOf(connection)) {
43641
- managed.set(connection, options.schemas ?? MAIN_ONLY);
43642
- }
43643
- return connection;
43644
- }
43645
- function isManagedConnection(connection) {
43646
- return !!connection && managed.has(connection);
43647
- }
43648
- function managedSchemasOf(connection) {
43649
- return connection ? managed.get(connection) : undefined;
43650
- }
43651
- function resolveManagedConnections(connections) {
43652
- return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
43653
- }
43654
- function connectionTypeOf(connection) {
43655
- return connection ? recorded.get(connection) : undefined;
43656
- }
43657
- function resolveConnectionTypes(connections) {
43658
- const types = {};
43659
- for (const [name, connection] of connections) {
43660
- const type = connectionTypeOf(connection);
43661
- if (type !== undefined)
43662
- types[name] = type;
43663
- }
43664
- return types;
43665
- }
43666
- var recorded, managed, MAIN_ONLY, overrides, managedOverrides;
43667
- var init_connection_type = __esm(() => {
43668
- recorded = new WeakMap;
43669
- managed = new WeakMap;
43670
- MAIN_ONLY = managedSchemas();
43671
- overrides = [];
43672
- managedOverrides = [];
43673
- });
43674
-
43675
44425
  // src/service/materialization/plan/refusal_key.ts
43676
44426
  function tierOf(storage) {
43677
44427
  return storage !== undefined ? "storage" : "database";
@@ -44187,6 +44937,21 @@ var init_persist_annotation_validation = __esm(() => {
44187
44937
  SAFE_NAME_PATH = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
44188
44938
  });
44189
44939
 
44940
+ // src/service/materialization/domain/rollup_grain.ts
44941
+ function pathColumnName(join, field) {
44942
+ return `${join}__${field}`;
44943
+ }
44944
+ function grainPathOf(grain) {
44945
+ const at = grain.indexOf(".");
44946
+ if (at < 0)
44947
+ return;
44948
+ return { join: grain.slice(0, at), field: grain.slice(at + 1) };
44949
+ }
44950
+ function grainColumnOf(grain) {
44951
+ const path = grainPathOf(grain);
44952
+ return path ? pathColumnName(path.join, path.field) : grain;
44953
+ }
44954
+
44190
44955
  // src/service/materialization/text/read_text.ts
44191
44956
  import * as path11 from "path";
44192
44957
  import { fileURLToPath as fileURLToPath8 } from "url";
@@ -44284,7 +45049,10 @@ function persistLine(plan) {
44284
45049
  return "#@ persist";
44285
45050
  }
44286
45051
  function emitRollupBuildSource(plan) {
44287
- const grain = plan.grainDimensions.map((g) => ` ${identifier(g)}`).join(`
45052
+ const grain = plan.grainDimensions.map((g) => {
45053
+ const path = grainPathOf(g);
45054
+ return path ? ` ${identifier(grainColumnOf(g))} is ${identifier(path.join)}.${identifier(path.field)}` : ` ${identifier(g)}`;
45055
+ }).join(`
44288
45056
  `);
44289
45057
  const partials = plan.rollupMeasures.flatMap((m) => m.partials).map((p) => ` ${identifier(p.column)} is ${emitMeasureExpr(p.leaf.expr)}`).join(`
44290
45058
  `);
@@ -45467,7 +46235,7 @@ var init_types2 = __esm(() => {
45467
46235
  });
45468
46236
 
45469
46237
  // src/retrieval/config.ts
45470
- function describe2(value) {
46238
+ function describe3(value) {
45471
46239
  return value === undefined ? "nothing" : JSON.stringify(value);
45472
46240
  }
45473
46241
  function positiveInt(value, key, fix) {
@@ -45475,7 +46243,7 @@ function positiveInt(value, key, fix) {
45475
46243
  return;
45476
46244
  const parsed = typeof value === "string" && /^\d+$/.test(value.trim()) ? Number(value.trim()) : value;
45477
46245
  if (typeof parsed !== "number" || !Number.isSafeInteger(parsed) || parsed <= 0) {
45478
- throw new Error(`Invalid ${key}: expected a positive integer, got ${describe2(value)}. Fix: ${fix}`);
46246
+ throw new Error(`Invalid ${key}: expected a positive integer, got ${describe3(value)}. Fix: ${fix}`);
45479
46247
  }
45480
46248
  return parsed;
45481
46249
  }
@@ -45483,7 +46251,7 @@ function nonEmptyString(value, key, fix) {
45483
46251
  if (value === undefined || value === null)
45484
46252
  return;
45485
46253
  if (typeof value !== "string" || value.trim() === "") {
45486
- throw new Error(`Invalid ${key}: expected a non-empty string, got ${describe2(value)}. Fix: ${fix}`);
46254
+ throw new Error(`Invalid ${key}: expected a non-empty string, got ${describe3(value)}. Fix: ${fix}`);
45487
46255
  }
45488
46256
  return value.trim();
45489
46257
  }
@@ -45491,7 +46259,7 @@ function plainString(value, key, fix) {
45491
46259
  if (value === undefined || value === null)
45492
46260
  return;
45493
46261
  if (typeof value !== "string") {
45494
- throw new Error(`Invalid ${key}: expected a string, got ${describe2(value)}. Fix: ${fix}`);
46262
+ throw new Error(`Invalid ${key}: expected a string, got ${describe3(value)}. Fix: ${fix}`);
45495
46263
  }
45496
46264
  return value;
45497
46265
  }
@@ -45502,13 +46270,13 @@ function url(value, key, fix) {
45502
46270
  try {
45503
46271
  new URL(text);
45504
46272
  } catch {
45505
- throw new Error(`Invalid ${key}: expected a URL, got ${describe2(value)}. Fix: ${fix}`);
46273
+ throw new Error(`Invalid ${key}: expected a URL, got ${describe3(value)}. Fix: ${fix}`);
45506
46274
  }
45507
46275
  return text.replace(/\/+$/, "");
45508
46276
  }
45509
46277
  function block(raw, key, valid, fix) {
45510
46278
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
45511
- throw new Error(`Invalid ${key}: expected an object, got ${describe2(raw)}. Fix: ${fix}`);
46279
+ throw new Error(`Invalid ${key}: expected an object, got ${describe3(raw)}. Fix: ${fix}`);
45512
46280
  }
45513
46281
  const obj = raw;
45514
46282
  const unknown = Object.keys(obj).filter((k) => !valid.includes(k));
@@ -45521,7 +46289,7 @@ function providerName(value, key, allowed, fix) {
45521
46289
  if (value === undefined || value === null)
45522
46290
  return;
45523
46291
  if (typeof value !== "string" || !allowed.includes(value)) {
45524
- throw new Error(`Invalid ${key}: expected one of ${allowed.join(", ")}, got ${describe2(value)}. Fix: ${fix}`);
46292
+ throw new Error(`Invalid ${key}: expected one of ${allowed.join(", ")}, got ${describe3(value)}. Fix: ${fix}`);
45525
46293
  }
45526
46294
  return value;
45527
46295
  }
@@ -45622,20 +46390,20 @@ function parseValueGivens(raw) {
45622
46390
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
45623
46391
  const isValue = (v) => typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v);
45624
46392
  if (!isObject(raw)) {
45625
- throw new Error(`Invalid retrieval.dimensionValues.givens: expected an object of packages, got ${describe2(raw)}. Fix: ${GIVENS_FIX}`);
46393
+ throw new Error(`Invalid retrieval.dimensionValues.givens: expected an object of packages, got ${describe3(raw)}. Fix: ${GIVENS_FIX}`);
45626
46394
  }
45627
46395
  const out = {};
45628
46396
  for (const [pkg, givens] of Object.entries(raw)) {
45629
46397
  const at = `retrieval.dimensionValues.givens.${pkg}`;
45630
46398
  if (!isObject(givens)) {
45631
- throw new Error(`Invalid ${at}: expected an object of givens, got ${describe2(givens)}. Fix: ${GIVENS_FIX}`);
46399
+ throw new Error(`Invalid ${at}: expected an object of givens, got ${describe3(givens)}. Fix: ${GIVENS_FIX}`);
45632
46400
  }
45633
46401
  const parsed = {};
45634
46402
  let combinations = 1;
45635
46403
  for (const [name, value] of Object.entries(givens)) {
45636
46404
  const list = Array.isArray(value) ? value : [value];
45637
46405
  if (list.length === 0 || !list.every(isValue)) {
45638
- throw new Error(`Invalid ${at}.${name}: expected a string, number or boolean, or a non-empty list of them, got ${describe2(value)}. Fix: ${GIVENS_FIX}`);
46406
+ throw new Error(`Invalid ${at}.${name}: expected a string, number or boolean, or a non-empty list of them, got ${describe3(value)}. Fix: ${GIVENS_FIX}`);
45639
46407
  }
45640
46408
  parsed[name] = [...new Set(list)];
45641
46409
  combinations *= parsed[name].length;
@@ -45652,7 +46420,7 @@ function parseDimensionValues(raw) {
45652
46420
  const out = {};
45653
46421
  if (fields.enabled !== undefined && fields.enabled !== null) {
45654
46422
  if (typeof fields.enabled !== "boolean") {
45655
- throw new Error(`Invalid retrieval.dimensionValues.enabled: expected a boolean, got ${describe2(fields.enabled)}. Fix: "enabled": false`);
46423
+ throw new Error(`Invalid retrieval.dimensionValues.enabled: expected a boolean, got ${describe3(fields.enabled)}. Fix: "enabled": false`);
45656
46424
  }
45657
46425
  out.enabled = fields.enabled;
45658
46426
  }
@@ -46419,7 +47187,7 @@ function isObj2(value) {
46419
47187
  function holdsRawSqlExpression(def) {
46420
47188
  const seen = new Set;
46421
47189
  const walk = (node, depth) => {
46422
- if (depth > MAX_DEPTH3)
47190
+ if (depth > MAX_DEPTH4)
46423
47191
  return true;
46424
47192
  if (node === null || typeof node !== "object")
46425
47193
  return false;
@@ -46461,7 +47229,7 @@ function resolveJoinPath(roots, path) {
46461
47229
  throw new Unknown(`join path ${path.join(".")} did not resolve`);
46462
47230
  }
46463
47231
  function relationReads(def, out, depth) {
46464
- if (depth > MAX_DEPTH3 || !isObj2(def))
47232
+ if (depth > MAX_DEPTH4 || !isObj2(def))
46465
47233
  throw new Unknown("unreadable");
46466
47234
  switch (def.type) {
46467
47235
  case "table":
@@ -46527,7 +47295,7 @@ function queryTableReads(entry, pipeline) {
46527
47295
  }
46528
47296
  });
46529
47297
  }
46530
- var MAX_DEPTH3 = 200, Unknown;
47298
+ var MAX_DEPTH4 = 200, Unknown;
46531
47299
  var init_source_reads = __esm(() => {
46532
47300
  Unknown = class Unknown extends Error {
46533
47301
  };
@@ -47127,6 +47895,11 @@ var init_key_check_text = __esm(() => {
47127
47895
  inline_join_one: { count: "matches", key: undefined, notNull: "is not" },
47128
47896
  pair_level: { count: "matches", key: undefined, isNull: "is" },
47129
47897
  rollup_key: { count: "key_rows__check", key: undefined, notNull: "!=" },
47898
+ grain_join_key: {
47899
+ count: "key_rows__check",
47900
+ key: undefined,
47901
+ notNull: "!="
47902
+ },
47130
47903
  parent_key: { count: "key_rows__check", key: "key__check", isNull: "=" }
47131
47904
  };
47132
47905
  });
@@ -49181,16 +49954,7 @@ function declarationRefusal(decl, facts, ctx) {
49181
49954
  return "skip";
49182
49955
  return unservable("hidden_field", decl, "the measure is not public, and a rollup would publish it");
49183
49956
  }
49184
- const grainProblem = decl.grain.map((g) => {
49185
- const f = byName.get(g);
49186
- if (g.includes(".")) {
49187
- return `the grain names \`${g}\`, a path; declare a dimension on the source that reads it, and name that`;
49188
- }
49189
- if (!f || !isDimension(f)) {
49190
- return `the grain names \`${g}\`, which is not a dimension of the source`;
49191
- }
49192
- return;
49193
- }).find((p) => p !== undefined);
49957
+ const grainProblem = grainProblemOf(decl.grain, facts);
49194
49958
  if (grainProblem) {
49195
49959
  if (decl.v1)
49196
49960
  return "skip";
@@ -49202,7 +49966,7 @@ function declarationRefusal(decl, facts, ctx) {
49202
49966
  measure: decl.measure
49203
49967
  };
49204
49968
  }
49205
- 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];
49969
+ 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];
49206
49970
  if (timeRead) {
49207
49971
  return unservable("current_time", decl, `${timeRead}, which a rollup would fix at build time while a live query reads it again at every read`);
49208
49972
  }
@@ -49221,7 +49985,12 @@ function declarationRefusal(decl, facts, ctx) {
49221
49985
  if (hiddenGrain) {
49222
49986
  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`);
49223
49987
  }
49224
- const unreadableGrain = decl.storage === undefined ? undefined : unreadableStoredGrain(decl.grain, byName, facts.dialect);
49988
+ const unreadableGrain = decl.storage === undefined ? undefined : unreadableStoredGrain(decl.grain, (g) => {
49989
+ if (!g.includes("."))
49990
+ return byName.get(g);
49991
+ const path = pathGrainOf(g, facts);
49992
+ return "problem" in path ? undefined : path.joined;
49993
+ }, facts.dialect);
49225
49994
  if (unreadableGrain) {
49226
49995
  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`);
49227
49996
  }
@@ -49250,11 +50019,167 @@ function declarationRefusal(decl, facts, ctx) {
49250
50019
  }
49251
50020
  return;
49252
50021
  }
49253
- function unreadableStoredGrain(grain, byName, dialect) {
50022
+ function grainProblemOf(grain, facts) {
50023
+ const { byName } = facts;
50024
+ const columns = new Map;
50025
+ return grain.map((g) => {
50026
+ const f = byName.get(g);
50027
+ if (g.includes(".")) {
50028
+ const path = pathGrainOf(g, facts);
50029
+ if ("problem" in path)
50030
+ return path.problem;
50031
+ const column = grainColumnOf(g);
50032
+ if (byName.has(column) || columns.has(column)) {
50033
+ 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)}\``}`;
50034
+ }
50035
+ columns.set(column, g);
50036
+ return;
50037
+ }
50038
+ if (!f || !isDimension(f)) {
50039
+ return `the grain names \`${g}\`, which is not a dimension of the source`;
50040
+ }
50041
+ columns.set(g, g);
50042
+ return;
50043
+ }).find((p) => p !== undefined);
50044
+ }
50045
+ function pathGrainOf(grain, facts) {
50046
+ const [head, second, ...rest] = grain.split(".");
50047
+ const join = facts.joins.get(head);
50048
+ const joinField = facts.byName.get(head);
50049
+ if (!join || !joinField) {
50050
+ return {
50051
+ 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`
50052
+ };
50053
+ }
50054
+ const joinedFields = new Map((joinField.fields ?? []).map((f) => [fieldNameOf2(f), f]));
50055
+ const joined = joinedFields.get(second);
50056
+ if (rest.length > 0) {
50057
+ return {
50058
+ 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>\``
50059
+ };
50060
+ }
50061
+ if (join.relationship === "cross") {
50062
+ return {
50063
+ problem: `the grain names \`${grain}\`, through \`${head}\`, a join_cross; a path grain reads a join_one or a join_many`
50064
+ };
50065
+ }
50066
+ if (!joined || !isDimension(joined)) {
50067
+ return {
50068
+ problem: `the grain names \`${grain}\`, but \`${second}\` is not a dimension of \`${head}\`'s source`
50069
+ };
50070
+ }
50071
+ if (isHidden(joinField) || isHidden(joined)) {
50072
+ return {
50073
+ 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`
50074
+ };
50075
+ }
50076
+ return {
50077
+ join: head,
50078
+ field: second,
50079
+ joined,
50080
+ relationship: join.relationship
50081
+ };
50082
+ }
50083
+ function pathColumnsOf(grain, facts) {
50084
+ const out = [];
50085
+ const add = (entry, column, join, joined) => {
50086
+ const field = fieldNameOf2(joined);
50087
+ const timeframe = joined.timeframe;
50088
+ out.push({
50089
+ grain: entry,
50090
+ column,
50091
+ join,
50092
+ field,
50093
+ ...typeof timeframe === "string" ? { timeframe } : {},
50094
+ ...fieldNotes(joined).length > 0 ? { annotated: true } : {}
50095
+ });
50096
+ };
50097
+ for (const g of grain) {
50098
+ if (g.includes(".")) {
50099
+ const path = pathGrainOf(g, facts);
50100
+ if (!("problem" in path))
50101
+ add(g, grainColumnOf(g), path.join, path.joined);
50102
+ continue;
50103
+ }
50104
+ const read = exactPathRead(facts.byName.get(g)?.e);
50105
+ if (!read)
50106
+ continue;
50107
+ const path = pathGrainOf(read.join("."), facts);
50108
+ if ("problem" in path)
50109
+ continue;
50110
+ add(g, g, path.join, path.joined);
50111
+ }
50112
+ return out;
50113
+ }
50114
+ function pathReadsCurrentTime(g, facts) {
50115
+ const path = grainPathOf(g);
50116
+ if (!path || !facts.joins.has(path.join))
50117
+ return false;
50118
+ const joinField = facts.byName.get(path.join);
50119
+ return currentTimeFields(joinField?.fields).has(path.field);
50120
+ }
50121
+ function joinOneGrainOf(grain, facts) {
50122
+ const byJoin = new Map;
50123
+ const uncovered = new Set;
50124
+ const add = (join, entry) => {
50125
+ if (facts.joins.get(join)?.relationship !== "one")
50126
+ return;
50127
+ const entries = byJoin.get(join) ?? [];
50128
+ if (!entries.includes(entry))
50129
+ entries.push(entry);
50130
+ byJoin.set(join, entries);
50131
+ };
50132
+ for (const g of grain) {
50133
+ const path = grainPathOf(g);
50134
+ if (path) {
50135
+ add(path.join, g);
50136
+ const join = facts.joins.get(path.join);
50137
+ if (!join)
50138
+ continue;
50139
+ const field = joinedSourceReads(join).fieldJoins.get(path.field);
50140
+ if (field === undefined || field.joins.size > 0 || field.nested) {
50141
+ uncovered.add(path.join);
50142
+ }
50143
+ continue;
50144
+ }
50145
+ const usage = facts.joinUsage.get(g);
50146
+ for (const j of usage?.joins ?? [])
50147
+ add(j, g);
50148
+ const onlyOnes = [...usage?.joins ?? []].every((j) => facts.joins.get(j)?.relationship === "one");
50149
+ if (usage === undefined || usage.nested || !onlyOnes) {
50150
+ for (const j of usage?.joins ?? [])
50151
+ uncovered.add(j);
50152
+ }
50153
+ }
50154
+ for (const join of byJoin.keys()) {
50155
+ const condition = facts.joins.get(join)?.condition;
50156
+ const filter = filterJoinReads(facts.byName.get(join));
50157
+ if (condition === undefined || condition.joins.size > 0 || condition.nested || filter === undefined || filter.joins.size > 0 || filter.nested) {
50158
+ uncovered.add(join);
50159
+ }
50160
+ }
50161
+ if (byJoin.size === 0)
50162
+ return {};
50163
+ return {
50164
+ joinOneGrain: [...byJoin].sort(([a], [b]) => byCodepoint2(a, b)).map(([join, entries]) => ({
50165
+ join,
50166
+ grain: entries,
50167
+ ...uncovered.has(join) ? { uncovered: true } : {}
50168
+ }))
50169
+ };
50170
+ }
50171
+ function exactPathRead(e) {
50172
+ const n = e;
50173
+ if (n?.node !== "field" || !Array.isArray(n.path) || n.path.length !== 2 || !n.path.every((p) => typeof p === "string")) {
50174
+ return;
50175
+ }
50176
+ return n.path;
50177
+ }
50178
+ function unreadableStoredGrain(grain, fieldOf, dialect) {
49254
50179
  if (dialect !== STORAGE_DIALECT)
49255
50180
  return;
49256
50181
  for (const name of grain) {
49257
- const f = byName.get(name);
50182
+ const f = fieldOf(name);
49258
50183
  if (f?.type !== "sql native" || typeof f.rawType !== "string")
49259
50184
  continue;
49260
50185
  const storedType = f.rawType.toUpperCase();
@@ -49342,6 +50267,7 @@ function rollupPlanOf({ decl, measures }, node, facts, ctx) {
49342
50267
  inherited.set(`${at.range.start.line}:${at.range.start.character}`, at);
49343
50268
  }
49344
50269
  }
50270
+ const pathColumns = pathColumnsOf(decl.grain, facts);
49345
50271
  const liftedAncestors = [...inherited.values()].sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.character - b.range.start.character);
49346
50272
  return {
49347
50273
  variant: true,
@@ -49367,7 +50293,12 @@ function rollupPlanOf({ decl, measures }, node, facts, ctx) {
49367
50293
  ...liftedAncestors.length > 0 ? { liftedAncestors } : {},
49368
50294
  ..."terms" in facts.given && facts.given.terms.length > 0 ? { readTimeTerms: facts.given.terms } : {},
49369
50295
  ...(privateGrain.length > 0 || ("terms" in facts.given) && facts.given.terms.length > 0) && facts.declaration ? { declaration: facts.declaration } : {},
50296
+ ...pathColumns.length > 0 ? { pathColumns } : {},
50297
+ ...joinOneGrainOf(decl.grain, facts),
49370
50298
  fanOutDimensions: decl.grain.filter((g) => {
50299
+ const path = grainPathOf(g);
50300
+ if (path)
50301
+ return joins.get(path.join)?.relationship !== "one";
49371
50302
  const usage = joinUsage.get(g);
49372
50303
  if (usage === undefined)
49373
50304
  return joinUsage.has(g);
@@ -49538,8 +50469,9 @@ function storedDestinationsOf(map, struct) {
49538
50469
  }
49539
50470
  function rollupKeyCheckQuery(plan) {
49540
50471
  const [key, ...rest] = plan.grainDimensions;
49541
- if (key === undefined || rest.length > 0)
50472
+ if (key === undefined || rest.length > 0 || grainPathOf(key)) {
49542
50473
  return;
50474
+ }
49543
50475
  return `run: ${keyCheckPipeline("rollup_key", rollupBaseAlias(plan.baseDeclaredName), key)}`;
49544
50476
  }
49545
50477
  function parentKeyNeedsOf(map) {
@@ -49611,6 +50543,9 @@ function storedKeyChecksOf(plans, needs, primaryKeyOf, sourceIDs) {
49611
50543
  function parentKeyCheckQuery(name, keyColumn) {
49612
50544
  return `run: ${keyCheckPipeline("parent_key", name, keyColumn)}`;
49613
50545
  }
50546
+ function grainJoinKeyCheckQuery(name, keyColumn) {
50547
+ return `run: ${keyCheckPipeline("grain_join_key", name, keyColumn)}`;
50548
+ }
49614
50549
  function joinOneKey(sourceID, keyColumn) {
49615
50550
  return `${sourceID}\x00${keyColumn}`;
49616
50551
  }
@@ -49653,6 +50588,7 @@ var init_rollup_plan = __esm(() => {
49653
50588
  init_rollup_measure_grammar();
49654
50589
  init_table_plans();
49655
50590
  init_read_text();
50591
+ init_source_graph();
49656
50592
  V1_PREAGGREGATE_NOTE = /^\s*#@\s*-?preaggregate\b/;
49657
50593
  scopes = new WeakMap;
49658
50594
  LOCK_WORDS = new Set(["and", "in", "true", "false"]);
@@ -49681,139 +50617,6 @@ var init_source_connection_type = __esm(() => {
49681
50617
  ];
49682
50618
  });
49683
50619
 
49684
- // src/service/materialization/domain/same_catalog_build.ts
49685
- function isSameCatalog(source, destination) {
49686
- const a = source?.type === "ducklake" ? source.ducklakeConnection : undefined;
49687
- const b = destination?.type === "ducklake" ? destination.ducklakeConnection : undefined;
49688
- if (!a || !b)
49689
- return false;
49690
- const pa = a.catalog?.postgresConnection;
49691
- const pb = b.catalog?.postgresConnection;
49692
- if (!pa || !pb)
49693
- return false;
49694
- const path = (url) => (url ?? "").replace(/\/+$/, "");
49695
- const pathA = path(a.storage?.bucketUrl);
49696
- const pathB = path(b.storage?.bucketUrl);
49697
- return !!pa.host && pa.host === pb.host && (pa.port ?? 5432) === (pb.port ?? 5432) && !!pa.databaseName && pa.databaseName === pb.databaseName && (a.catalog.metadataSchema ?? "") === (b.catalog.metadataSchema ?? "") && (pathA === "" || pathB === "" || pathA === pathB);
49698
- }
49699
- function carriesAuthorSql(def) {
49700
- return authorSqlCause(def) !== undefined;
49701
- }
49702
- function authorSqlCause(def) {
49703
- const seen = new Set;
49704
- const walk = (node, depth, frames) => {
49705
- if (depth > MAX_DEPTH4)
49706
- return { found: UNREADABLE3, frames };
49707
- if (node === null || typeof node !== "object")
49708
- return;
49709
- if (seen.has(node))
49710
- return;
49711
- seen.add(node);
49712
- if (Array.isArray(node)) {
49713
- for (const child of node) {
49714
- const hit = walk(child, depth + 1, frames);
49715
- if (hit)
49716
- return hit;
49717
- }
49718
- return;
49719
- }
49720
- const record = node;
49721
- if (typeof record.join === "string") {
49722
- frames = [
49723
- ...frames,
49724
- {
49725
- kind: "join",
49726
- as: String(record.as ?? record.name ?? ""),
49727
- source: sourceNameOf(record)
49728
- }
49729
- ];
49730
- }
49731
- if (record.type === "sql_select") {
49732
- return { found: { kind: "sql_source" }, frames };
49733
- }
49734
- if (record.node === "genericSQLExpr") {
49735
- return { found: { kind: "sql_expression" }, frames };
49736
- }
49737
- if (record.type === "table" && typeof record.tablePath === "string" && !CATALOG_TABLE_PATH.test(record.tablePath)) {
49738
- return {
49739
- found: { kind: "file_table", path: record.tablePath },
49740
- frames
49741
- };
49742
- }
49743
- for (const [key, child] of Object.entries(record)) {
49744
- if (record.node === "function_call" && key === "overload")
49745
- continue;
49746
- const hit = key === "fields" && Array.isArray(child) ? walkFields(child, depth + 1, frames) : walk(child, depth + 1, key === "structRef" && child !== null && typeof child === "object" ? [
49747
- ...frames,
49748
- {
49749
- kind: "reads",
49750
- source: sourceNameOf(child)
49751
- }
49752
- ] : frames);
49753
- if (hit)
49754
- return hit;
49755
- }
49756
- return;
49757
- };
49758
- const walkFields = (fields, depth, frames) => {
49759
- if (depth > MAX_DEPTH4)
49760
- return { found: UNREADABLE3, frames };
49761
- if (seen.has(fields))
49762
- return;
49763
- seen.add(fields);
49764
- for (const field of fields) {
49765
- const f = field;
49766
- const named = f !== null && typeof f === "object" && typeof f.name === "string" && typeof f.join !== "string";
49767
- const hit = walk(field, depth + 1, named ? [...frames, { kind: "field", name: String(f.name) }] : frames);
49768
- if (hit)
49769
- return hit;
49770
- }
49771
- return;
49772
- };
49773
- try {
49774
- if (def === null || typeof def !== "object")
49775
- return describe3([], UNREADABLE3);
49776
- const hit = walk(def, 0, []);
49777
- return hit ? describe3(hit.frames, hit.found) : undefined;
49778
- } catch {
49779
- return describe3([], UNREADABLE3);
49780
- }
49781
- }
49782
- function sourceNameOf(record) {
49783
- const id = typeof record.sourceID === "string" ? record.sourceID : "";
49784
- const name = typeof record.name === "string" ? record.name : "";
49785
- return id.split("@")[0] || (name.startsWith("sql://") ? "" : name);
49786
- }
49787
- function describe3(frames, found) {
49788
- if (found.kind === "unreadable") {
49789
- return "its definition could not be read to check for SQL its author wrote";
49790
- }
49791
- frames = frames.filter((frame, i) => frame.kind !== "reads" || i === frames.length - 1 && found.kind !== "sql_expression");
49792
- const parts = [];
49793
- let lead = true;
49794
- for (const frame of frames) {
49795
- const possessive = lead ? "its" : "whose";
49796
- const subject = lead ? "it" : "which";
49797
- lead = false;
49798
- if (frame.kind === "join") {
49799
- parts.push(`${possessive} join '${frame.as}'` + (frame.source ? ` reads source '${frame.source}'` : ""));
49800
- } else if (frame.kind === "reads") {
49801
- parts.push(frame.source ? `${subject} reads source '${frame.source}'` : `${subject} reads a source`);
49802
- } else {
49803
- parts.push(`${possessive} field '${frame.name}'`);
49804
- }
49805
- }
49806
- const last = frames[frames.length - 1];
49807
- const subject = frames.length === 0 ? "it" : ", which";
49808
- const what = found.kind === "sql_source" ? `${subject} is an .sql() source` : found.kind === "file_table" ? `${subject} reads '${found.path.replace(/^'|'$/g, "")}' as a table` : last?.kind === "field" ? " uses a sql_* expression" : `${subject} uses a sql_* expression`;
49809
- return (parts.join(", ") + what).replace(/^ /, "");
49810
- }
49811
- var CATALOG_TABLE_PATH, MAX_DEPTH4 = 200, UNREADABLE3;
49812
- var init_same_catalog_build = __esm(() => {
49813
- CATALOG_TABLE_PATH = /^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)*$/;
49814
- UNREADABLE3 = { kind: "unreadable" };
49815
- });
49816
-
49817
50620
  // src/service/materialization/plan/materialization_eligibility.ts
49818
50621
  function assertMaterializationEligible(persistSource, annotationFields, options = {}) {
49819
50622
  const sourceName = persistSource.name;
@@ -50803,7 +51606,7 @@ function materializedUpstream(sourceID, map) {
50803
51606
  }
50804
51607
  function storedElsewhereReason(upstreams) {
50805
51608
  const stored = upstreams.find((u) => u.storage !== undefined);
50806
- 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;
51609
+ 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;
50807
51610
  }
50808
51611
  function persistOverMaterializedReason(upstreams, destination) {
50809
51612
  const stored = upstreams.find((u) => u.materialize && u.storage === destination);
@@ -50816,7 +51619,7 @@ function placementReason(downstream, upstream) {
50816
51619
  if (downstream === undefined) {
50817
51620
  return storedElsewhereReason([upstream]);
50818
51621
  }
50819
- 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`;
51622
+ 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`;
50820
51623
  }
50821
51624
  var UPSTREAM_TABLE_UNUSABLE_REASON = "upstream_table_unusable";
50822
51625
  var init_downstream_upstreams = __esm(() => {
@@ -56355,6 +57158,61 @@ async function compileParentKeyChecks(plans, needs, joinedKeys = []) {
56355
57158
  delete plan.parentKeyChecks;
56356
57159
  }
56357
57160
  }
57161
+ async function compileGrainJoinKeyChecks(plans, joinsOf, sourceOf, stored) {
57162
+ const compiled = new Map;
57163
+ for (const plan of plans) {
57164
+ if (plan.variant !== true)
57165
+ continue;
57166
+ const checks = [];
57167
+ for (const { join, uncovered } of plan.joinOneGrain ?? []) {
57168
+ if (uncovered) {
57169
+ logger.info("A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", {
57170
+ rollup: plan.rollupSourceName,
57171
+ join,
57172
+ reason: "the build joins past it, through another join"
57173
+ });
57174
+ continue;
57175
+ }
57176
+ const j = joinsOf(plan.baseSourceID).find((x) => x.name === join && x.relationship === "one");
57177
+ const source = j?.sourceID ? sourceOf(j.sourceID) : undefined;
57178
+ 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;
57179
+ if (why !== undefined || !j?.sourceID || !j.keyColumn || !source) {
57180
+ 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 });
57181
+ continue;
57182
+ }
57183
+ const { sourceID, keyColumn } = j;
57184
+ const key = `${sourceID}\x00${keyColumn}`;
57185
+ let sql = compiled.get(key);
57186
+ if (sql === undefined) {
57187
+ sql = source.compile(grainJoinKeyCheckQuery(source.name, keyColumn)).catch((error) => {
57188
+ logger.warn("A #(rollup) rollup's grain join key check did not compile; queries that read nothing through the join are answered live", {
57189
+ rollup: plan.rollupSourceName,
57190
+ join,
57191
+ source: source.name,
57192
+ keyColumn,
57193
+ code: errorCodeOf(error)
57194
+ });
57195
+ return;
57196
+ });
57197
+ compiled.set(key, sql);
57198
+ }
57199
+ const text = await sql;
57200
+ if (text === undefined)
57201
+ continue;
57202
+ checks.push({
57203
+ join,
57204
+ sourceID,
57205
+ keyColumn,
57206
+ connectionName: source.connectionName,
57207
+ sql: text
57208
+ });
57209
+ }
57210
+ if (checks.length > 0)
57211
+ plan.grainJoinKeyChecks = checks;
57212
+ else
57213
+ delete plan.grainJoinKeyChecks;
57214
+ }
57215
+ }
56358
57216
  async function compileRollupKeyChecks(plans, materializer, modelPath) {
56359
57217
  for (const plan of plans) {
56360
57218
  const text = rollupKeyCheckQuery(plan);
@@ -56522,6 +57380,28 @@ var init_access_closure = __esm(() => {
56522
57380
  ]);
56523
57381
  });
56524
57382
 
57383
+ // src/service/materialization/domain/target_containers.ts
57384
+ function targetContainerKey(target) {
57385
+ return JSON.stringify([target.connectionName, target.container]);
57386
+ }
57387
+ function containerOfTableName(name) {
57388
+ const dot = name.lastIndexOf(".");
57389
+ return dot > 0 ? name.slice(0, dot) : undefined;
57390
+ }
57391
+ function missingContainerReason(target, dialect, reading) {
57392
+ const kind = capabilitiesOf(dialect).containerCatalog === "dataset" ? "dataset" : "schema";
57393
+ const where = `its name= places its table in ${kind} "${target.container}"`;
57394
+ if ("otherLocation" in reading) {
57395
+ const { location, expected } = reading.otherLocation;
57396
+ 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`;
57397
+ }
57398
+ const project = reading.project ? ` (project "${reading.project}")` : "";
57399
+ 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`;
57400
+ }
57401
+ var init_target_containers = __esm(() => {
57402
+ init_dialect();
57403
+ });
57404
+
56525
57405
  // src/service/materialization/domain/package_plan.ts
56526
57406
  function countRefusal(counts, reason) {
56527
57407
  counts[reason] = (counts[reason] ?? 0) + 1;
@@ -57051,18 +57931,19 @@ function inDestinationStringReads(args, stored, planned, upstreams) {
57051
57931
  const run = planned.kind === "query" ? `run: ${quotedIdentifier(planned.queryName)}` : `run: ${quotedIdentifier(planned.sourceName)} -> ${quotedIdentifier(planned.viewName)}`;
57052
57932
  return planStringReads(args.stringReads, args.materializer, { run, stored: stored.upstreams.map((u) => u.sourceID) }, planned.storage, upstreams);
57053
57933
  }
57054
- async function chainedStringReads(source, modelDef, materializer, ports, judged) {
57934
+ async function chainedStringReads(source, modelDef, materializer, ports, judged, planned) {
57055
57935
  const destination = declaredStorage(source)?.trim();
57056
57936
  if (!destination)
57057
57937
  return;
57058
57938
  const map = SourceMap.of(modelDef);
57059
57939
  const def = map.node(source.sourceID)?.def;
57060
- if (def?.type !== "query_source" || typeof def.extends === "string") {
57940
+ if (def?.type !== "query_source")
57061
57941
  return;
57062
- }
57063
57942
  const stored = reachedUpstreams(def, modelDef, map).filter((u) => u.storage === destination && u.sourceID !== source.sourceID).map((u) => u.sourceID);
57064
57943
  if (stored.length === 0)
57065
57944
  return;
57945
+ if (sharesStoredBuild(source, stored, planned))
57946
+ return;
57066
57947
  const reads = await planStringReads(ports, materializer, { downstream: source.name, stored }, destination, { modelDef, judged });
57067
57948
  if (!("refused" in reads) || !reads.unstored)
57068
57949
  return reads;
@@ -57073,6 +57954,19 @@ async function chainedStringReads(source, modelDef, materializer, ports, judged)
57073
57954
  unstored: true
57074
57955
  } : reads;
57075
57956
  }
57957
+ function sharesStoredBuild(source, stored, planned) {
57958
+ const keyOf = (s) => {
57959
+ if (!s)
57960
+ return;
57961
+ try {
57962
+ return compilerBuildId(s);
57963
+ } catch {
57964
+ return;
57965
+ }
57966
+ };
57967
+ const own = keyOf(source);
57968
+ return own !== undefined && stored.some((id) => keyOf(planned.get(id)) === own);
57969
+ }
57076
57970
  async function collectGeneratedPersistedViews(parts, args) {
57077
57971
  const authorDef = modelDefOf(args.malloyModel);
57078
57972
  const { generated, refused, refusedQueries, omitted, failure } = await tryCompilePersistedViewCompanion({
@@ -57419,6 +58313,7 @@ function reportPersistLineFindings(parts, targets, planned, args) {
57419
58313
  async function planV1PersistSources(parts, planned, args) {
57420
58314
  const { modelPath, packagePath, materializer, malloyModel } = args;
57421
58315
  let classificationCtx;
58316
+ const plannedByID = new Map(planned.map((s) => [s.sourceID, s]));
57422
58317
  for (const source of planned) {
57423
58318
  const sourceID = source.sourceID;
57424
58319
  try {
@@ -57448,7 +58343,7 @@ async function planV1PersistSources(parts, planned, args) {
57448
58343
  modelDef: modelDefOf(malloyModel),
57449
58344
  deps: gateDepsFor(malloyModel, modelPath)
57450
58345
  };
57451
- const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads, parts.stringCapabilityReads) : parts.tables[sourceID]?.stringReads;
58346
+ const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads, parts.stringCapabilityReads, plannedByID) : parts.tables[sourceID]?.stringReads;
57452
58347
  const destination = declaredStorage(source)?.trim();
57453
58348
  const map = SourceMap.of(classificationCtx.modelDef);
57454
58349
  const query = map.node(sourceID)?.def?.query;
@@ -57625,7 +58520,7 @@ function finishBuildPlan(parts, ctx) {
57625
58520
  addresses: planAddresses({ ...plan, tableFolds })
57626
58521
  };
57627
58522
  const refused = refuseCollidingMaterialize(refuseRewrittenNames(full));
57628
- const known = refuseUpstreamUnread(refused);
58523
+ const known = refuseMissingContainers(refuseUpstreamUnread(refused), ctx.targetContainers);
57629
58524
  return refuseOverMissingUpstreams(refuseUncomparableStrings(refuseAcrossPlacements(ctx.keepIncrementalUnbuildable ? known : refuseIncrementalUnbuildable(known))), full);
57630
58525
  }
57631
58526
  function refuseAcrossPlacements(compiled) {
@@ -57745,21 +58640,45 @@ function refuseOverMissingUpstreams(compiled, full = compiled) {
57745
58640
  return dropped.size === 0 ? compiled : withoutSources(compiled, findings, dropped);
57746
58641
  }
57747
58642
  async function finishPackagePlan(parts, ctx) {
57748
- const { getMalloyConnection, readUpstreamSchemas, ...finish } = ctx;
58643
+ const {
58644
+ getMalloyConnection,
58645
+ readUpstreamSchemas,
58646
+ readTargetContainers,
58647
+ ...finish
58648
+ } = ctx;
57749
58649
  const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
57750
58650
  const digestSkipped = [];
57751
58651
  const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
57752
58652
  const upstreamSchemas = readUpstreamSchemas ? await readUpstreamSchemas(planUpstreamTables(parts.tables)) : undefined;
58653
+ const containers = planTargetContainers(parts.tables);
58654
+ const targetContainers = readTargetContainers && containers.length > 0 ? await readTargetContainers(containers) : undefined;
57753
58655
  return {
57754
58656
  compiled: finishBuildPlan(parts, {
57755
58657
  ...finish,
57756
58658
  connectionDigests,
57757
58659
  ...upstreamSchemas ? { upstreamSchemas } : {},
58660
+ ...targetContainers ? { targetContainers } : {},
57758
58661
  connections
57759
58662
  }),
57760
58663
  digestSkipped
57761
58664
  };
57762
58665
  }
58666
+ function targetContainerOf(source) {
58667
+ if (declaredStorage(source) !== undefined)
58668
+ return;
58669
+ const name = deriveAnnotationFields(source).name;
58670
+ const container = name ? containerOfTableName(name) : undefined;
58671
+ return container ? { connectionName: source.connectionName, container } : undefined;
58672
+ }
58673
+ function planTargetContainers(tables) {
58674
+ const out = new Map;
58675
+ for (const { source } of Object.values(tables)) {
58676
+ const target = targetContainerOf(source);
58677
+ if (target)
58678
+ out.set(targetContainerKey(target), target);
58679
+ }
58680
+ return [...out.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, t]) => t);
58681
+ }
57763
58682
  function planUpstreamTables(tables) {
57764
58683
  const out = new Map;
57765
58684
  for (const { source } of Object.values(tables)) {
@@ -57926,6 +58845,26 @@ function refuseUpstreamUnread(compiled) {
57926
58845
  }
57927
58846
  return withoutSources(compiled, findings, dropped);
57928
58847
  }
58848
+ function refuseMissingContainers(compiled, readings) {
58849
+ if (!readings)
58850
+ return compiled;
58851
+ const shared = sharedTables(compiled);
58852
+ const findings = [];
58853
+ const dropped = new Set;
58854
+ for (const [sourceID, { source }] of Object.entries(compiled.tables)) {
58855
+ if (shared.has(sourceID))
58856
+ continue;
58857
+ const target = targetContainerOf(source);
58858
+ if (!target)
58859
+ continue;
58860
+ const reading = readings[targetContainerKey(target)];
58861
+ if (!reading || "found" in reading || "unread" in reading)
58862
+ continue;
58863
+ dropped.add(sourceID);
58864
+ findings.push(notBuiltFinding(compiled, sourceID, "container_not_found", missingContainerReason(target, source.dialectName, reading)));
58865
+ }
58866
+ return withoutSources(compiled, findings, dropped);
58867
+ }
57929
58868
  function notBuiltFinding(compiled, sourceID, reason, why) {
57930
58869
  const table = compiled.tables[sourceID];
57931
58870
  const source = table.source;
@@ -58130,6 +59069,7 @@ var init_build_plan = __esm(() => {
58130
59069
  init_persist_source_fields();
58131
59070
  init_quoting();
58132
59071
  init_addressing();
59072
+ init_target_containers();
58133
59073
  init_eligibility_collect();
58134
59074
  init_plan_layers();
58135
59075
  init_addressing();
@@ -58146,7 +59086,7 @@ var init_build_plan = __esm(() => {
58146
59086
  });
58147
59087
 
58148
59088
  // src/package_load/protocol.ts
58149
- var PACKAGE_LOAD_PROTOCOL_VERSION = 8;
59089
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 10;
58150
59090
 
58151
59091
  // src/package_load/package_load_worker.ts
58152
59092
  init_served_copy_serve();
@@ -58399,7 +59339,7 @@ function callMain(send) {
58399
59339
  }
58400
59340
  var schemaWait = new RpcWaitAccountant;
58401
59341
  function dispatchMainResponse(message) {
58402
- if (message.type === "schema-for-tables-response" || message.type === "schema-for-sql-response" || message.type === "upstream-schemas-response" || message.type === "read-url-response" || message.type === "connection-metadata-response") {
59342
+ if (message.type === "schema-for-tables-response" || message.type === "schema-for-sql-response" || message.type === "upstream-schemas-response" || message.type === "target-containers-response" || message.type === "read-url-response" || message.type === "connection-metadata-response") {
58403
59343
  const pending = pendingRpc.get(message.requestId);
58404
59344
  if (!pending)
58405
59345
  return;
@@ -59175,6 +60115,15 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
59175
60115
  tables
59176
60116
  };
59177
60117
  port.postMessage(req);
60118
+ })).readings,
60119
+ readTargetContainers: async (containers) => (await callMain((requestId) => {
60120
+ const req = {
60121
+ type: "target-containers",
60122
+ requestId,
60123
+ jobId,
60124
+ containers
60125
+ };
60126
+ port.postMessage(req);
59178
60127
  })).readings
59179
60128
  });
59180
60129
  digestSkipped = finished.digestSkipped;
@@ -59250,7 +60199,11 @@ async function compileServedCopy(job) {
59250
60199
  config: buildWorkerMalloyConfig(job)
59251
60200
  });
59252
60201
  const modelURL = pathToFileURL17(path20.join(job.packagePath, job.modelPath));
59253
- const model = await runtime.loadModel(modelURL, { importBaseURL: new URL(".", modelURL) }).getModel();
60202
+ const virtualMap = job.virtualMap ? new Map(job.virtualMap.map(([connection, handles]) => [connection, new Map(handles)])) : undefined;
60203
+ const model = await runtime.loadModel(modelURL, {
60204
+ importBaseURL: new URL(".", modelURL),
60205
+ ...virtualMap ? { virtualMap } : {}
60206
+ }).getModel();
59254
60207
  return done({ modelDef: model._modelDef });
59255
60208
  } catch (error) {
59256
60209
  return done({ error: serializeError(error) });