@malloy-publisher/server 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/app/api-doc.yaml +266 -43
  2. package/dist/app/assets/{EnvironmentPage-Y9IWPC9J.js → EnvironmentPage-D2-0ts2G.js} +1 -1
  3. package/dist/app/assets/{HomePage-BOUo0MEl.js → HomePage-S_Bkczsx.js} +1 -1
  4. package/dist/app/assets/{MainPage-BkM5UDRU.js → MainPage-DEy4SyjJ.js} +1 -1
  5. package/dist/app/assets/{ModelPage-PgDTkS5C.js → ModelPage-BVHjDM-u.js} +2 -2
  6. package/dist/app/assets/{PackagePage-Dn7FrQ5r.js → PackagePage-Cbrg7o1X.js} +1 -1
  7. package/dist/app/assets/{PackageSplatRoute-BLC29ek-.js → PackageSplatRoute-ChFCJOWE.js} +2 -2
  8. package/dist/app/assets/{RenderedResult-vyM2wQbC.es-ha8dF24T.js → RenderedResult-BcEDcw0V.es-BD6PNbt6.js} +1 -1
  9. package/dist/app/assets/{RouteError-BolMqTuz.js → RouteError-CDSSYdLB.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-CPv1eHkI.js → ThemeEditorPage-DO2JWYOR.js} +1 -1
  11. package/dist/app/assets/{ToggleButtonGroup-DZtImN0S.js → ToggleButtonGroup-BylAiUaK.js} +1 -1
  12. package/dist/app/assets/{documentRoutes-DI5cX3ty.js → documentRoutes-CaOt2rpR.js} +1 -1
  13. package/dist/app/assets/{editPageMounted-C--4kcld.js → editPageMounted-79YCIKgP.js} +2 -2
  14. package/dist/app/assets/{index-DLToSg1f.js → index-BKjEX4_C.js} +10 -10
  15. package/dist/app/assets/{index-DyYEltlF.js → index-BOCBPBsi.js} +1 -1
  16. package/dist/app/assets/{index-D9wSfMZN.js → index-CPSEdm5f.js} +1 -1
  17. package/dist/app/assets/{index-CbsrzNSp.js → index-keJ8KKBp.js} +1 -1
  18. package/dist/app/assets/{index.es-D8SVyfmS.js → index.es-DTreXoC5.js} +1 -1
  19. package/dist/app/assets/usePackageLinkNavigate-BfSAqkJS.js +1 -0
  20. package/dist/app/assets/{usePackageRoute-A_YQMrax.js → usePackageRoute-G6fA1__J.js} +1 -1
  21. package/dist/app/index.html +1 -1
  22. package/dist/app/mcp-app/report.js +4 -4
  23. package/dist/instrumentation.mjs +2 -2
  24. package/dist/package_load_worker.mjs +1523 -456
  25. package/dist/server.mjs +29298 -24269
  26. package/dist/{sshcrypto-fqcyz88x.node → sshcrypto-wf5kpffj.node} +0 -0
  27. package/package.json +1 -1
  28. package/dist/app/assets/usePackageLinkNavigate-DxHGKrmZ.js +0 -1
@@ -2286,7 +2286,7 @@ var init_query = __esm(() => {
2286
2286
  type: integer({ min: 0 }),
2287
2287
  default: DEFAULT_PACKAGE_LOAD_SCHEMA_CACHE_BYTES,
2288
2288
  description: "Serialized schema each package-load worker caches across loads, in bytes; 0 turns it off.",
2289
- notes: "Serialized size of the table and SQL schemas each package-load worker keeps across loads, so a model's repeated and later requests for the same table skip the round trip to the main thread. Least recently used entries go first. Scoped per environment and per connection instance, so editing a connection drops its entries; a request that asks to refresh a schema is fetched again, and the result replaces the entry. Heap use is a few times the serialized size. `0` disables it; empty takes the default, and a value that is not a byte count stops the server from starting.",
2289
+ notes: "Serialized size of the table and SQL schemas each package-load worker keeps across loads, so a model's repeated and later requests for the same table skip the round trip to the main thread. Least recently used entries go first. Scoped per environment and per connection instance, so editing a connection drops its entries. An explicit refresh (a reload with `?reload=true` or `reload_package`, a publish, or a `PATCH` that reinstalls) fetches every table and SQL schema the package reads again, in the connection's own cache too, and every worker drops its old entry; a watch-mode recompile and a boot read the cached schemas. Heap use is a few times the serialized size. `0` disables it; empty takes the default, and a value that is not a byte count stops the server from starting.",
2290
2290
  defaultText: "`16777216` (16 MiB)",
2291
2291
  aliases: { env: ["PACKAGE_LOAD_SCHEMA_CACHE_BYTES"] }
2292
2292
  })
@@ -12565,7 +12565,7 @@ function declaredFreshnessFacts(declarations) {
12565
12565
  ...fallback !== undefined ? { freshnessFallback: fallback } : {}
12566
12566
  };
12567
12567
  }
12568
- var FRESHNESS_FALLBACKS, WINDOW_UNITS, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
12568
+ var FRESHNESS_FALLBACKS, WINDOW_UNITS, FRESHNESS_WINDOW_PROBLEM, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
12569
12569
  var init_freshness = __esm(() => {
12570
12570
  FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
12571
12571
  WINDOW_UNITS = {
@@ -12575,6 +12575,7 @@ var init_freshness = __esm(() => {
12575
12575
  d: 86400,
12576
12576
  w: 604800
12577
12577
  };
12578
+ FRESHNESS_WINDOW_PROBLEM = "has a freshness.window= that is not a positive duration: write a whole " + 'number greater than zero and one unit (s, m, h, d or w), such as freshness.window="24h"';
12578
12579
  DURATION_UNITS = {
12579
12580
  ...WINDOW_UNITS,
12580
12581
  second: 1,
@@ -12679,7 +12680,7 @@ function freshnessValueProblem(group) {
12679
12680
  if (group.has("window")) {
12680
12681
  const window2 = group.text("window");
12681
12682
  if (window2 === undefined || freshnessWindowSeconds(window2) === undefined) {
12682
- return 'has a freshness.window= that is not a whole number and a unit (s, m, h, d or w), such as freshness.window="24h"';
12683
+ return FRESHNESS_WINDOW_PROBLEM;
12683
12684
  }
12684
12685
  }
12685
12686
  if (group.has("fallback") && !isFreshnessFallback(group.text("fallback"))) {
@@ -14094,7 +14095,7 @@ function errorKind(error) {
14094
14095
  function errorMapping(error) {
14095
14096
  return ERROR_TABLE[errorKind(error)];
14096
14097
  }
14097
- var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, WarehouseRecomputeRefusedError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
14098
+ var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, ResultTruncatedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, ResultShapeError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, WarehouseRecomputeRefusedError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
14098
14099
  var init_errors2 = __esm(() => {
14099
14100
  init_constants();
14100
14101
  init_logger();
@@ -14334,6 +14335,15 @@ var init_errors2 = __esm(() => {
14334
14335
  return "connection_failed";
14335
14336
  }
14336
14337
  };
14338
+ ResultTruncatedError = class ResultTruncatedError extends ConnectionError {
14339
+ get kind() {
14340
+ return "result_truncated";
14341
+ }
14342
+ constructor(returned, reported) {
14343
+ super(`The database returned ${returned} of the ${reported} rows it reported, and no row limit cut them: BigQuery returns one results page of about 10 MB, and the rest of the answer was not read. The query was refused rather than answered short. Project fewer columns or return fewer rows so the answer fits in one page.`, { callerSafe: true });
14344
+ this.name = "ResultTruncatedError";
14345
+ }
14346
+ };
14337
14347
  UnconfiguredConnectionError = class UnconfiguredConnectionError extends Error {
14338
14348
  get kind() {
14339
14349
  return "unconfigured_connection";
@@ -14351,6 +14361,17 @@ var init_errors2 = __esm(() => {
14351
14361
  this.name = "ConnectionPoolExhaustedError";
14352
14362
  }
14353
14363
  };
14364
+ ResultShapeError = class ResultShapeError extends ConnectionError {
14365
+ get kind() {
14366
+ return "result_shape";
14367
+ }
14368
+ constructor(options) {
14369
+ super("The database returned a row that does not fit the result's schema, " + "so the result could not be built.", { callerSafe: true });
14370
+ if (options?.cause !== undefined)
14371
+ this.cause = options.cause;
14372
+ this.name = "ResultShapeError";
14373
+ }
14374
+ };
14354
14375
  DestinationNotFoundError = class DestinationNotFoundError extends Error {
14355
14376
  get kind() {
14356
14377
  return "destination_not_found";
@@ -14727,6 +14748,8 @@ var init_errors2 = __esm(() => {
14727
14748
  connection_failed: ConnectionFailedError,
14728
14749
  unconfigured_connection: UnconfiguredConnectionError,
14729
14750
  connection_pool_exhausted: ConnectionPoolExhaustedError,
14751
+ result_truncated: ResultTruncatedError,
14752
+ result_shape: ResultShapeError,
14730
14753
  destination_not_found: DestinationNotFoundError,
14731
14754
  storage_destination_not_found: StorageDestinationNotFoundError,
14732
14755
  storage_catalog_not_found: StorageCatalogNotFoundError,
@@ -15021,6 +15044,27 @@ var init_errors2 = __esm(() => {
15021
15044
  ]
15022
15045
  }
15023
15046
  },
15047
+ result_truncated: {
15048
+ ...CONNECTION,
15049
+ reason: "RESULT_TRUNCATED",
15050
+ log: { summary: "Database result truncated", level: "warn" },
15051
+ mcp: {
15052
+ advice: "fixed",
15053
+ suggestions: [
15054
+ NOT_TRANSIENT_CHANGE_QUERY,
15055
+ "Shrink the answer so it fits in one results page of about 10 MB: select fewer columns, aggregate, or add a LIMIT."
15056
+ ]
15057
+ }
15058
+ },
15059
+ result_shape: {
15060
+ ...CONNECTION,
15061
+ reason: "RESULT_SHAPE_MISMATCH",
15062
+ log: {
15063
+ summary: "Database result does not fit its schema",
15064
+ level: "error"
15065
+ },
15066
+ mcp: { advice: "internal" }
15067
+ },
15024
15068
  materialization_not_found: { status: 404, mcp: { advice: "internal" } },
15025
15069
  materialization_conflict: {
15026
15070
  status: 409,
@@ -16206,8 +16250,8 @@ async function liftRowLevelCondition(compiler, sourceName, exprs) {
16206
16250
  async function validateAuthorizeProbes(compiler, options) {
16207
16251
  const ownNotesOf = options.authorizeOwnNotes ?? new Map;
16208
16252
  for (const [sourceName, groups] of options.authorizeMap ?? []) {
16209
- for (const { route, exprs } of groups) {
16210
- if (exprs.length === 0)
16253
+ for (const { route, exprs, fromBase } of groups) {
16254
+ if (exprs.length === 0 || fromBase)
16211
16255
  continue;
16212
16256
  let condition;
16213
16257
  try {
@@ -17403,6 +17447,7 @@ function gatePlan(struct, graph, options) {
17403
17447
  excludeNotes: options.excludeNotes ?? [],
17404
17448
  walkMembers: true,
17405
17449
  nameHops: 0,
17450
+ baseHops: 0,
17406
17451
  ownTexts: options.ownTexts
17407
17452
  }));
17408
17453
  metComposite ||= walk.metComposite;
@@ -17430,6 +17475,8 @@ function walkRoute(walk, struct, route, visit) {
17430
17475
  fromAncestor: level.fromAncestor,
17431
17476
  treatAsOwn: visit.treatAsOwn,
17432
17477
  entryPoint: visit.entryPoint,
17478
+ baseHops: visit.baseHops,
17479
+ level: struct,
17433
17480
  ...level.failure ? { failure: level.failure } : {}
17434
17481
  });
17435
17482
  }
@@ -17481,6 +17528,7 @@ function walkRoute(walk, struct, route, visit) {
17481
17528
  exprs: ["false"],
17482
17529
  fromAncestor: false,
17483
17530
  treatAsOwn: false,
17531
+ baseHops: visit.baseHops,
17484
17532
  failure: { kind: "base_unresolvable", message }
17485
17533
  });
17486
17534
  const base = hop.kind === "resolved" ? hop.base : undefined;
@@ -17492,7 +17540,8 @@ function walkRoute(walk, struct, route, visit) {
17492
17540
  entryPoint: visit.entryPoint,
17493
17541
  excludeNotes: [],
17494
17542
  walkMembers: false,
17495
- nameHops: hop.byName ? visit.nameHops + 1 : visit.nameHops
17543
+ nameHops: hop.byName ? visit.nameHops + 1 : visit.nameHops,
17544
+ baseHops: visit.baseHops + 1
17496
17545
  }));
17497
17546
  } else {
17498
17547
  steps.push(baseFailure(hop.message));
@@ -17505,7 +17554,8 @@ function walkRoute(walk, struct, route, visit) {
17505
17554
  entryPoint: visit.entryPoint,
17506
17555
  excludeNotes: base ? ownLevelNotes(base.annotations) : [],
17507
17556
  walkMembers: true,
17508
- nameHops: visit.nameHops
17557
+ nameHops: visit.nameHops,
17558
+ baseHops: visit.baseHops + 1
17509
17559
  }));
17510
17560
  }
17511
17561
  return steps;
@@ -17587,6 +17637,21 @@ import {
17587
17637
  isJoined as isJoined2,
17588
17638
  isSourceDef as isSourceDef4
17589
17639
  } from "@malloydata/malloy";
17640
+ function derivationLevel(root, landing, contents) {
17641
+ let current = root;
17642
+ for (let depth = 0;current && depth <= ANCESTOR_WALK_MAX_DEPTH; depth++) {
17643
+ if ("sourceID" in landing ? current.sourceID === landing.sourceID : depth === landing.hops) {
17644
+ return current;
17645
+ }
17646
+ if (current.type !== "query_source")
17647
+ return;
17648
+ const query = current.query;
17649
+ const ref = query?.compositeResolvedSourceDef ?? query?.structRef;
17650
+ const base = typeof ref === "string" ? contents?.[ref] : ref;
17651
+ current = base && typeof base === "object" && isSourceDef4(base) ? base : undefined;
17652
+ }
17653
+ return;
17654
+ }
17590
17655
  function createGateClassificationDeps(givens, modelPath) {
17591
17656
  return {
17592
17657
  gateShapeCache: new Map,
@@ -17613,7 +17678,9 @@ function collectEntryPointGates(struct, modelDef, seen = new Set, treatAsOwnGate
17613
17678
  exprs: step.exprs,
17614
17679
  route: step.route,
17615
17680
  selfContained: step.fromAncestor || !step.treatAsOwn,
17616
- ...step.entryPoint ? { struct: step.entryPoint } : {}
17681
+ ...step.entryPoint ? { struct: step.entryPoint } : {},
17682
+ baseHops: step.baseHops,
17683
+ ...step.level ? { level: step.level } : {}
17617
17684
  });
17618
17685
  }
17619
17686
  return entries;
@@ -17629,17 +17696,32 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17629
17696
  if (!graftTarget) {
17630
17697
  return { shape: "rejected" };
17631
17698
  }
17699
+ let landing;
17700
+ let liftTarget = graftTarget;
17701
+ if (entry.baseHops > 0 && entry.level) {
17702
+ liftTarget = resolveGraftTarget(entry.level, originModelDef, graftScope.modelDef) ?? graftTarget;
17703
+ }
17704
+ if (entry.baseHops > 0 && entry.route !== AUTHORIZE_ROUTE) {
17705
+ const target = graftScope.modelDef.contents[graftTarget];
17706
+ const sourceID = entry.level?.sourceID;
17707
+ const candidate = sourceID !== undefined ? { sourceID } : target === entry.struct || target?.sourceID !== undefined && target.sourceID === entry.struct.sourceID ? { hops: entry.baseHops } : undefined;
17708
+ if (!entry.level || !candidate || !derivationLevel(target, candidate, graftScope.modelDef.contents)) {
17709
+ logger.debug("Row-level gate on a derivation's base has no base to graft onto; denying", { modelPath: deps.modelPath, label: entry.label });
17710
+ return { shape: "rejected" };
17711
+ }
17712
+ landing = candidate;
17713
+ }
17632
17714
  const filterText = gateFilterText(entry.exprs);
17633
- const cacheKey = `${graftScope.cacheScope}\x00${entry.route}\x00${graftTarget}\x00${filterText}`;
17715
+ const cacheKey = `${graftScope.cacheScope}\x00${entry.route}\x00${liftTarget}\x00${filterText}`;
17634
17716
  let cached = deps.gateShapeCache.get(cacheKey);
17635
17717
  if (!cached) {
17636
17718
  let condition;
17637
17719
  try {
17638
- condition = await liftGateCondition(graftTarget, filterText, graftScope.materializer);
17720
+ condition = await liftGateCondition(liftTarget, filterText, graftScope.materializer);
17639
17721
  } catch (err) {
17640
17722
  logger.debug("Row-level gate condition failed to lift; denying", {
17641
17723
  modelPath: deps.modelPath,
17642
- graftTarget,
17724
+ graftTarget: liftTarget,
17643
17725
  error: err instanceof Error ? err.message : String(err)
17644
17726
  });
17645
17727
  return { shape: "rejected" };
@@ -17659,7 +17741,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17659
17741
  givenNamesById: new Map
17660
17742
  };
17661
17743
  } else {
17662
- const targetStruct = graftScope.modelDef.contents[graftTarget];
17744
+ const targetStruct = graftScope.modelDef.contents[liftTarget];
17663
17745
  if (!isSourceDef4(targetStruct)) {
17664
17746
  classification = {
17665
17747
  shape: "rejected",
@@ -17706,7 +17788,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17706
17788
  if (unreachable !== undefined) {
17707
17789
  logger.warn("Gate accepted a given off the model surface; denying", {
17708
17790
  modelPath: deps.modelPath,
17709
- graftTarget,
17791
+ graftTarget: liftTarget,
17710
17792
  givenName: unreachable
17711
17793
  });
17712
17794
  classification = {
@@ -17733,6 +17815,7 @@ async function resolveGateShape(entry, originModelDef, graftScope, deps) {
17733
17815
  return {
17734
17816
  shape: "row_level",
17735
17817
  graftTarget,
17818
+ ...landing !== undefined ? { landing } : {},
17736
17819
  filterText,
17737
17820
  condition: cached.condition,
17738
17821
  givenNames: cached.classification.givenNames
@@ -17820,7 +17903,7 @@ function assertAuthorizeGrammarValid(modelDef, authorizeMap, authorizeOwnNotes,
17820
17903
  const ownGroupTerms = [];
17821
17904
  const declaredAdmitAllRoutes = [];
17822
17905
  const ownRoutesSeen = new Set;
17823
- for (const { route, exprs } of groups) {
17906
+ for (const { route, exprs, fromBase } of groups) {
17824
17907
  const isOwn = (authorizeOwnNotes.get(sourceName)?.get(route)?.length ?? 0) > 0 && !ownRoutesSeen.has(route);
17825
17908
  if (isOwn)
17826
17909
  ownRoutesSeen.add(route);
@@ -17833,7 +17916,7 @@ function assertAuthorizeGrammarValid(modelDef, authorizeMap, authorizeOwnNotes,
17833
17916
  if (term.scope === "admit_all" && (attributedAuthorizeOwnNotes?.get(sourceName)?.get(route)?.length ?? 0) > 0) {
17834
17917
  declaredAdmitAllRoutes.push(route);
17835
17918
  }
17836
- if (term.scope === "row_level" && isSourceDef4(struct)) {
17919
+ if (term.scope === "row_level" && !fromBase && isSourceDef4(struct)) {
17837
17920
  assertNoFanoutFieldPath(sourceName, struct, term.fieldPath, term.fieldPathSegments);
17838
17921
  }
17839
17922
  }
@@ -25178,6 +25261,9 @@ var init_filter = __esm(() => {
25178
25261
 
25179
25262
  // src/service/gate_registry_walk.ts
25180
25263
  function gateExprsForRoute(struct, modelDef, route) {
25264
+ return gateGroupsForRoute(struct, modelDef, route).map((g) => g.exprs);
25265
+ }
25266
+ function gateGroupsForRoute(struct, modelDef, route) {
25181
25267
  const { steps } = gatePlan(struct, modelDefGateGraph(modelDef), {
25182
25268
  composite: "resolved",
25183
25269
  routes: [route],
@@ -25189,7 +25275,7 @@ function gateExprsForRoute(struct, modelDef, route) {
25189
25275
  continue;
25190
25276
  if (step.failure?.kind === "unreadable")
25191
25277
  throw step.failure.error;
25192
- groups.push(step.exprs);
25278
+ groups.push({ exprs: step.exprs, fromBase: step.baseHops > 0 });
25193
25279
  }
25194
25280
  return groups;
25195
25281
  }
@@ -25348,11 +25434,15 @@ function extractSourcesFromModelDef(modelDef, givens, onParseError) {
25348
25434
  const groupsForSource = [];
25349
25435
  const routeGroupsByRoute = new Map;
25350
25436
  for (const route of CANONICAL_AUTHORIZE_ROUTES) {
25351
- const groupsForRoute = gateExprsForRoute(struct, modelDef, route);
25352
- for (const exprs of groupsForRoute) {
25353
- groupsForSource.push({ route, exprs });
25437
+ const groupsForRoute = gateGroupsForRoute(struct, modelDef, route);
25438
+ for (const { exprs, fromBase } of groupsForRoute) {
25439
+ groupsForSource.push({
25440
+ route,
25441
+ exprs,
25442
+ ...fromBase ? { fromBase: true } : {}
25443
+ });
25354
25444
  }
25355
- routeGroupsByRoute.set(route, groupsForRoute);
25445
+ routeGroupsByRoute.set(route, groupsForRoute.map((g) => g.exprs));
25356
25446
  }
25357
25447
  if (groupsForSource.length > 0) {
25358
25448
  authorizeMap.set(sourceName, groupsForSource);
@@ -28084,184 +28174,6 @@ var init_experimental_dialects = __esm(() => {
28084
28174
  BUNDLED_EXPERIMENTAL_DIALECTS = ["sqlserver"];
28085
28175
  });
28086
28176
 
28087
- // src/materialization_metrics.ts
28088
- function routeLegOf(kind) {
28089
- return kind === "served" ? "materialized" : kind;
28090
- }
28091
- function recordScheduledFire(outcome) {
28092
- scheduledFireCounter().add(1, { outcome });
28093
- }
28094
- function recordMaterializationRun(mode, outcome, durationMs) {
28095
- runCounter().add(1, { mode, outcome });
28096
- runDuration().record(durationMs, { mode, outcome });
28097
- }
28098
- function recordBuildOutcome(labels) {
28099
- buildCounter().add(1, {
28100
- kind: labels.kind,
28101
- tier: labels.tier,
28102
- outcome: labels.outcome,
28103
- failure_class: labels.outcome === "failed" ? labels.failureClass : "none"
28104
- });
28105
- }
28106
- function recordBuildDuration(durationMs, labels) {
28107
- buildDuration().record(durationMs, {
28108
- kind: labels.kind,
28109
- tier: labels.tier,
28110
- method: labels.method
28111
- });
28112
- }
28113
- function recordBuildReadBytes(bytes, tier) {
28114
- if (typeof bytes !== "number" || !(bytes > 0))
28115
- return;
28116
- buildReadBytes().record(bytes, { tier });
28117
- }
28118
- function recordAnnotationFindings(warnings) {
28119
- for (const { code, severity } of warnings) {
28120
- if (!code)
28121
- continue;
28122
- annotationFindingsCounter().add(1, {
28123
- code,
28124
- outcome: severity === "error" ? "invalid" : "not_built"
28125
- });
28126
- }
28127
- }
28128
- function recordIncrementalStep(step, reason) {
28129
- incrementalStepCounter().add(1, reason ? { step, reason } : { step });
28130
- }
28131
- function recordBuildPlanComputeDuration(durationMs, computedIn) {
28132
- buildPlanComputeDuration().record(durationMs, { computed_in: computedIn });
28133
- }
28134
- function recordBuildPlanComputeFailed() {
28135
- buildPlanComputeFailedCounter().add(1);
28136
- }
28137
- function recordAutoLoadOutcome(outcome) {
28138
- autoLoadCounter().add(1, { outcome });
28139
- }
28140
- function recordConnectionDigestSkipped() {
28141
- connectionDigestSkipCounter().add(1);
28142
- }
28143
- function recordDuplicateTargetSkipped() {
28144
- duplicateTargetSkipCounter().add(1);
28145
- }
28146
- function recordSharedAddressInstructions() {
28147
- sharedAddressInstructionCounter().add(1);
28148
- }
28149
- function recordTableCollision() {
28150
- tableCollisionCounter().add(1);
28151
- }
28152
- function recordManifestBind(outcome) {
28153
- servedCopyBindCounter().add(1, {
28154
- scope: "manifest",
28155
- outcome,
28156
- reason: "none"
28157
- });
28158
- }
28159
- function recordSourceBound() {
28160
- servedCopyBindCounter().add(1, {
28161
- scope: "source",
28162
- outcome: "bound",
28163
- reason: "none"
28164
- });
28165
- }
28166
- function recordSourceDeclined(reason) {
28167
- servedCopyBindCounter().add(1, {
28168
- scope: "source",
28169
- outcome: "declined",
28170
- reason
28171
- });
28172
- }
28173
- function recordServedCopyOutcome(outcome, reason) {
28174
- servedCopyBindCounter().add(1, { scope: "source", outcome, reason });
28175
- }
28176
- function recordManifestBindDegraded() {
28177
- manifestBindDegradedCounter().add(1);
28178
- }
28179
- function recordDropTables(outcome, tier, occasion) {
28180
- dropTablesCounter().add(1, { outcome, tier, occasion });
28181
- }
28182
- function recordKeyCheck(kind, outcome) {
28183
- keyCheckCounter().add(1, { kind, outcome });
28184
- }
28185
- function recordQueryRouteDuration(durationMs, leg) {
28186
- queryRouteDuration().record(durationMs, { leg });
28187
- }
28188
- function recordStorageTableRetained() {
28189
- storageTableRetainedCounter().add(1);
28190
- }
28191
- function recordAttributionSkipped(reason) {
28192
- attributionSkippedCounter().add(1, { reason });
28193
- }
28194
- function recordEligibilityRefused(reason) {
28195
- const counts = eligibilityRefusalSink?.();
28196
- if (counts) {
28197
- counts[reason] = (counts[reason] ?? 0) + 1;
28198
- return;
28199
- }
28200
- eligibilityRefusedCounter().add(1, { reason });
28201
- }
28202
- function setEligibilityRefusalSink(sink) {
28203
- eligibilityRefusalSink = sink;
28204
- }
28205
- function recordStoredTypeFallback(kind) {
28206
- serveShapeTypeFallbackCounter().add(1, { kind });
28207
- }
28208
- function recordStoredColumnTypeMismatch(stage, declared) {
28209
- storedColumnTypeMismatchCounter().add(1, { stage, declared });
28210
- }
28211
- function recordQueryRoute(leg, outcome, reason) {
28212
- queryRouteCounter().add(1, { leg, outcome, reason });
28213
- }
28214
- function recordChainedStorageBuild(outcome) {
28215
- chainedStorageBuildCounter().add(1, { outcome });
28216
- }
28217
- function recordStaleUpstreamEntry(tier) {
28218
- staleUpstreamEntryCounter().add(1, { tier });
28219
- }
28220
- var BUILD_DURATION_BUCKETS_MS, BUILD_READ_BYTES_BUCKETS, runCounter, runDuration, buildCounter, buildDuration, buildReadBytes, annotationFindingsCounter, incrementalStepCounter, buildPlanComputeDuration, buildPlanComputeFailedCounter, autoLoadCounter, connectionDigestSkipCounter, servedCopyBindCounter, manifestBindDegradedCounter, duplicateTargetSkipCounter, sharedAddressInstructionCounter, tableCollisionCounter, dropTablesCounter, scheduledFireCounter, queryRouteCounter, queryRouteDuration, keyCheckCounter, storageTableRetainedCounter, attributionSkippedCounter, eligibilityRefusedCounter, serveShapeTypeFallbackCounter, storedColumnTypeMismatchCounter, chainedStorageBuildCounter, staleUpstreamEntryCounter, eligibilityRefusalSink;
28221
- var init_materialization_metrics = __esm(() => {
28222
- init_telemetry();
28223
- BUILD_DURATION_BUCKETS_MS = [
28224
- 100,
28225
- 500,
28226
- 1000,
28227
- 5000,
28228
- 15000,
28229
- 60000,
28230
- 300000,
28231
- 900000,
28232
- 3600000
28233
- ];
28234
- BUILD_READ_BYTES_BUCKETS = [1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000];
28235
- runCounter = lazyCounter("publisher_materialization_runs_total", "Materialization builds completed. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
28236
- runDuration = lazyHistogram("publisher_materialization_run_duration_ms", "Wall-clock duration of a materialization build. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
28237
- buildCounter = lazyCounter("publisher_materialization_build_total", "Source builds, one per source per run at its finish or failure. Labels: " + "kind ('materialize'|'persist'|'rollup'|'view'|'query'|'pair'), tier " + "('database'|'storage'), outcome ('built'|'reused'|'refused'|'failed'|" + "'cancelled'), failure_class ('none' unless outcome is 'failed'; then " + "'deterministic'|'transient'|'unclassified'|'billed_read_lost'). " + "'billed_read_lost' is the expensive one: the warehouse read ran and was " + "charged and its rows were not captured, so a retry pays for it again.");
28238
- buildDuration = lazyHistogram("publisher_materialization_build_duration_ms", "Wall-clock duration of one source's build, for builds that ran (built or " + "failed; a skipped incremental refresh did no work and is not timed). " + "Labels: kind, tier, method ('full'|'delta').", { buckets: BUILD_DURATION_BUCKETS_MS });
28239
- buildReadBytes = lazyHistogram("publisher_materialization_build_read_bytes", "Warehouse bytes scanned by one source's build read, when the warehouse " + "reported a count; absent otherwise, never zero. Label: tier.", { unit: "By", buckets: BUILD_READ_BYTES_BUCKETS });
28240
- annotationFindingsCounter = lazyCounter("publisher_annotation_findings_total", "Coded findings on authored annotations (the #@ route, and the near-miss and malformed-route scan over every route), counted once each time a package is loaded and accepted for serving (boot, add, publish, reload; a refused publish and a gate re-run count nothing). Labels: code (e.g. 'persist-unknown-key', 'persist-unparseable', 'persist-not-built'), outcome ('invalid' for an error-severity finding, which fails the load, 'not_built' for a warning: a valid annotation not built here, and also the warn-level 'annotation-near-miss' and 'persist-incremental-no-merge-key' advisories, which build).");
28241
- incrementalStepCounter = lazyCounter("publisher_materialization_incremental_step_total", 'Refreshes of a source declared refresh="incremental". Labels: step ' + "('delta'|'seed'|'skip'), and for seed/skip a bounded reason code " + "(IncrementalStepReasonCode). A 'seed' is a full rebuild the delta path " + "declined, so a rising seed rate means the feature is not engaging — and " + "the reason label says why without a log dive.");
28242
- buildPlanComputeDuration = lazyHistogram("publisher_materialization_build_plan_compute_duration_ms", "Wall-clock duration of compiling a package's build plan (Package.buildPlan).");
28243
- buildPlanComputeFailedCounter = lazyCounter("publisher_materialization_build_plan_compute_failed_total", "Package loads whose build plan failed to compute. The ROOT-CAUSE signal for " + "served_copy_bind{reason='build_plan_unavailable'}, which fires only " + "per declined entry per load -- a package that loads once and is never " + "reloaded ticks that counter once and then sits with its database tier " + "off and a flat total, indistinguishable from healthy.");
28244
- autoLoadCounter = lazyCounter("publisher_materialization_auto_load_total", "Auto-run manifest auto-load attempts. Label: outcome ('success'|'failure').");
28245
- connectionDigestSkipCounter = lazyCounter("publisher_materialization_connection_digest_skipped_total", "Connection digests skipped during build-plan compile because the connection did not resolve.");
28246
- servedCopyBindCounter = lazyCounter("publisher_served_copy_bind_total", "Serving's binds. Labels: scope ('manifest': one manifest bind, from REST, " + "auto-load or a rebind; 'source': one source deciding whether it " + "serves), outcome ('success'|'failure'|'timeout' for a manifest; " + "'bound'|'partial'|'declined' for a source: 'partial' is a source that " + "serves with a join read as written or left out), reason ('none' when " + "bound, else why: 'build_plan_unavailable' when the package's build " + "plan failed to compute, so every database source reverts to live; " + "'refused'; 'missing_table'; or the served copy's reason, as its " + "package warning, 'inline_join_kept' and 'cross_connection_join' being " + "the partial ones). Units differ by who counts: 'bound' and the bind's " + "declines count once per stored table per bind; the served copy counts " + "once per source per model per snapshot it compiles, 'declined' beating " + "'partial'. So a source two models read is counted by each, and the " + "outcomes do not sum to a number of sources. An extension table that " + "falls back to its own blocks ('compile_failed', 'reroot_not_compiled') " + "may still serve, and is counted 'declined'.");
28247
- manifestBindDegradedCounter = lazyCounter("publisher_materialization_manifest_bind_degraded_total", "Manifest entries bound with an UNQUOTED table path because their connection " + "could not be resolved (serve-side bind) or is absent from the build " + "(build-side seed). A misconfiguration that breaks the source on a " + "case-folding engine (Snowflake); alertable.");
28248
- duplicateTargetSkipCounter = lazyCounter("publisher_materialization_duplicate_target_skipped_total", "Sources skipped because the physical table they name was already built in " + "this run. Ordinary for a package that extends a persisted source; a " + "rising count against a package with no extension means the plan is " + "enumerating one table under more names than expected.");
28249
- sharedAddressInstructionCounter = lazyCounter("publisher_materialization_shared_address_instructions_total", "Content addresses that arrived with more than one instruction naming a " + "DIFFERENT physical table. The host minted a table per source where " + "several sources share one artifact. With a sourceID on each instruction " + "every table is built and only one is recorded, so the rest are orphaned; " + "without one the last instruction wins and the earlier names are never " + "built. Wasteful, not wrong — the table's CONTENT is the same either way.");
28250
- tableCollisionCounter = lazyCounter("publisher_materialization_table_collision_total", "Two definitions with DIFFERENT content addresses materializing into ONE " + "physical table. Each build overwrites the other's rows while both " + "addresses resolve to the table at serve time, so a query is answered " + "from another source's data. A wrong answer, not wasted work — page on " + "this one. Counted, then refused before any write, unless " + "PERSIST_COLLISION_ENFORCE=false opts out, in which case the build " + "continues.");
28251
- dropTablesCounter = lazyCounter("publisher_materialization_drop_tables_total", "Physical tables dropped. Labels: outcome ('success'|'failure'), tier " + "('database'|'storage'), occasion ('delete' when a caller deleted a " + "storage destination's table, since a run's delete is record-only; " + "'reclaim' when Publisher dropped it on its own: " + "a failed run's tables, a table a readable name replaced, an archived " + "or deleted version's tables; 'caller' when a caller dropped a " + "package's materialized database table through " + "DELETE .../materializedTables/{tableName}).");
28252
- scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
28253
- queryRouteCounter = lazyCounter("publisher_query_route_total", "The router's decision on each leg it considered for a query, counted once " + "the query is answered. Labels: leg ('view'|'query'|'rollup'|'materialized'|'live'; " + "'query' is a persisted named query), " + "outcome ('used'|'skipped'|'fallback': a chosen leg whose run failed and " + "was answered live), reason ('NONE' when used, else the path report's " + "SkipReason; 'READ_FAILED' with 'fallback'). A leg that does not apply to " + "the query is not counted; 'live' is counted 'used' when it answered a " + "query the router counted a leg for.");
28254
- queryRouteDuration = lazyHistogram("publisher_query_route_duration_ms", "Wall-clock time the router spent choosing how to answer a query, for a " + "query with at least one serving leg that applied: the row-level veto " + "and each leg's compile, up to the leg chosen. Not the query's run. " + "Label: leg ('view'|'query'|'rollup'|'materialized'|'live'), the one that " + "answered.");
28255
- keyCheckCounter = lazyCounter("publisher_materialization_key_check_total", "Key checks a run made over the rows it read or wrote. Labels: kind " + "('inline_join'|'rollup'|'parent'|'pair_leaf'|'stored'), outcome " + "('unique'|'not_unique'|'not_run'|'reused'). An inline_join that is " + "not_unique fails its build; every other not_unique or not_run leaves " + "the key unknown or repeated, so queries that need it unique are " + "answered live.");
28256
- storageTableRetainedCounter = lazyCounter("publisher_storage_tables_retained_total", "Tables a FAILED run left in a storage= destination and deliberately did not " + "reclaim, because the source is refreshed incrementally and the name may be " + "the one it serves from. Not all of these are orphans — " + "a rebuild at a fresh generational name is, a seed on the live serving name " + "is not, and the manifest entry cannot separate them — so read this as an " + "upper bound on what is accumulating rather than a leak count. It is the " + "only accounting there is until reclaiming a destination exists, which is " + "why it is a counter and not just a log line: the question is a rate, not " + "whether it ever happened. Unlabelled: the destination is on the warn " + "log that accompanies each count.");
28257
- attributionSkippedCounter = lazyCounter("publisher_storage_build_attribution_skipped_total", "storage= builds whose warehouse read went out UNATTRIBUTED while tagging was " + "on. Label: reason ('job_listing_unavailable'|'tag_failed'|" + "'read_row_not_found'|'read_row_ambiguous'|'cost_query_failed'). " + "The read still ran and the " + "build still succeeded — what was lost is the label in the customer's own " + "query history, and the cost on this side. Without this an operator who " + "turns tagging on and sees nothing has a single log line to go on.");
28258
- eligibilityRefusedCounter = lazyCounter("publisher_materialization_eligibility_refused_total", "Valid materialization declarations that are not built (`#@ persist`, " + "`#(materialize)`, a persisted view or query, a rollup), once per " + "declaration per plan derivation, and the refusals only a run finds. " + "Label: reason, the build plan refusal's `RefusedSource.reason` " + "(api-doc.yaml lists the values and which are retained and no " + "longer produced).");
28259
- serveShapeTypeFallbackCounter = lazyCounter("publisher_storage_serve_shape_type_fallback_total", "Captured DuckDB column types mapped to json in a stored table's declared " + "type (type fidelity loss). Named for the retired storage serve shape. " + "Label: kind ('array'|'unrecognized').");
28260
- storedColumnTypeMismatchCounter = lazyCounter("publisher_storage_column_type_mismatch_total", "Stored columns whose DuckDB type does not serve as the type Malloy " + "declares for them (ms2data/service#6642). Labels: stage ('build' = " + "found after a storage build; 'serve' = found when a model's bindings " + "are set, then cast on read or left out of the served copy so queries " + "reading it are answered live), declared (the Malloy type).");
28261
- chainedStorageBuildCounter = lazyCounter("publisher_storage_chained_build_total", "Chained storage= source builds (a source reading a storage-materialized " + "upstream). Label: outcome ('parent_reuse'|'inline_fallback'|" + "'strict_shape_fallback'|'strict_refused'|'infra_failure'). The " + "parent_reuse share is the headline signal for how far the " + "stack-on-the-parent path gets us vs recompute-from-raw.");
28262
- staleUpstreamEntryCounter = lazyCounter("publisher_materialization_stale_upstream_entry_total", "Builds that could not use an upstream's manifest entry because it is at a " + "different tier than the upstream is declared on now (ms2data/service#7087: " + "a source moved to or from storage= keeps its content address). The build " + "recomputes that upstream from raw instead, which reads the warehouse. " + "Label: tier ('database'|'storage'), the tier of the build that " + "recomputed.");
28263
- });
28264
-
28265
28177
  // src/process_safety.ts
28266
28178
  function describeRejection(reason) {
28267
28179
  let message;
@@ -28535,6 +28447,10 @@ var init_array_query = __esm(() => {
28535
28447
  });
28536
28448
 
28537
28449
  // src/service/connection_type.ts
28450
+ function managedOverrideOf(connection) {
28451
+ const name = connection.name;
28452
+ return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
28453
+ }
28538
28454
  function overrideOf(connection) {
28539
28455
  const name = connection.name;
28540
28456
  if (typeof name !== "string")
@@ -28546,12 +28462,21 @@ function overrideOf(connection) {
28546
28462
  }
28547
28463
  return;
28548
28464
  }
28549
- function recordConnectionType(connection, type) {
28465
+ function recordConnectionType(connection, type, options = {}) {
28550
28466
  const recordedType = overrideOf(connection) ?? type;
28551
28467
  if (recordedType)
28552
28468
  recorded.set(connection, recordedType);
28469
+ if (options.managed === true || managedOverrideOf(connection)) {
28470
+ managed.add(connection);
28471
+ }
28553
28472
  return connection;
28554
28473
  }
28474
+ function isManagedConnection(connection) {
28475
+ return !!connection && managed.has(connection);
28476
+ }
28477
+ function resolveManagedConnections(connections) {
28478
+ return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
28479
+ }
28555
28480
  function connectionTypeOf(connection) {
28556
28481
  return connection ? recorded.get(connection) : undefined;
28557
28482
  }
@@ -28564,10 +28489,12 @@ function resolveConnectionTypes(connections) {
28564
28489
  }
28565
28490
  return types;
28566
28491
  }
28567
- var recorded, overrides;
28492
+ var recorded, managed, overrides, managedOverrides;
28568
28493
  var init_connection_type = __esm(() => {
28569
28494
  recorded = new WeakMap;
28495
+ managed = new WeakSet;
28570
28496
  overrides = [];
28497
+ managedOverrides = [];
28571
28498
  });
28572
28499
 
28573
28500
  // src/service/materialization/plan/refusal_key.ts
@@ -28578,6 +28505,39 @@ function refusalKey(sourceID, name, reason, tier) {
28578
28505
  return { sourceID, name, tier, reason };
28579
28506
  }
28580
28507
 
28508
+ // src/error_code.ts
28509
+ function errorCodeOf(err) {
28510
+ const chain = [...causeChain(err)];
28511
+ for (const e of chain) {
28512
+ if (e instanceof MaterializationEligibilityError && e.reason) {
28513
+ return e.reason;
28514
+ }
28515
+ const reason = e.reason;
28516
+ if (e instanceof ChainedShapeNotCarriedError && typeof reason === "string" && CODE_PATTERN.test(reason)) {
28517
+ return reason;
28518
+ }
28519
+ const { kind, code } = e;
28520
+ for (const candidate of [kind, code]) {
28521
+ if (typeof candidate === "string" && CODE_PATTERN.test(candidate)) {
28522
+ return candidate;
28523
+ }
28524
+ }
28525
+ if (typeof code === "number")
28526
+ return String(code);
28527
+ }
28528
+ for (const e of chain) {
28529
+ if (e.name !== "Error" && CODE_PATTERN.test(e.name))
28530
+ return e.name;
28531
+ }
28532
+ return "Error";
28533
+ }
28534
+ var CODE_PATTERN;
28535
+ var init_error_code = __esm(() => {
28536
+ init_driver_errors();
28537
+ init_errors2();
28538
+ CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
28539
+ });
28540
+
28581
28541
  // src/service/governance/ir/compiled_model.ts
28582
28542
  function modelDefOf(model) {
28583
28543
  return model._modelDef;
@@ -28676,6 +28636,10 @@ function givenWhereCodes(def) {
28676
28636
  var MAX_WALK_DEPTH = 200;
28677
28637
 
28678
28638
  // src/service/materialization/domain/dialect.ts
28639
+ function isBinary64Type(dialect, nativeType) {
28640
+ const named = nativeType.trim().replace(/\s+/g, " ").toUpperCase();
28641
+ return capabilitiesOf(dialect).binary64Types?.includes(named) === true;
28642
+ }
28679
28643
  function capabilitiesOf(dialect) {
28680
28644
  const name = registeredDialect(dialect);
28681
28645
  return name === undefined ? NONE : CAPABILITIES[name];
@@ -28705,6 +28669,7 @@ var init_dialect = __esm(() => {
28705
28669
  nestedColumns: false,
28706
28670
  driverKeepsBigIntegers: false,
28707
28671
  liveRoundsBigIntegersMeasured: false,
28672
+ liveWritesFloat4Shortest: false,
28708
28673
  castsToIntegerType: false,
28709
28674
  onlyBigIntegerType: undefined,
28710
28675
  foldsTableNameCase: false,
@@ -28712,7 +28677,9 @@ var init_dialect = __esm(() => {
28712
28677
  leafBudget: 50,
28713
28678
  passthroughNumericAsDouble: false,
28714
28679
  catalogHidesTables: false,
28715
- stringCollation: undefined
28680
+ stringCollation: undefined,
28681
+ ungroupableTypes: undefined,
28682
+ binary64Types: undefined
28716
28683
  });
28717
28684
  CAPABILITIES = {
28718
28685
  duckdb: Object.freeze({
@@ -28729,7 +28696,8 @@ var init_dialect = __esm(() => {
28729
28696
  foldsTableNameCase: true,
28730
28697
  utcSessions: true,
28731
28698
  leafBudget: 120,
28732
- stringCollation: "instance"
28699
+ stringCollation: "instance",
28700
+ binary64Types: ["DOUBLE", "FLOAT8"]
28733
28701
  }),
28734
28702
  postgres: Object.freeze({
28735
28703
  ...NONE,
@@ -28744,7 +28712,25 @@ var init_dialect = __esm(() => {
28744
28712
  relationProbe: true,
28745
28713
  tableOwnership: true,
28746
28714
  castsToIntegerType: true,
28747
- liveRoundsBigIntegersMeasured: true
28715
+ liveRoundsBigIntegersMeasured: true,
28716
+ liveWritesFloat4Shortest: true,
28717
+ binary64Types: ["DOUBLE PRECISION"],
28718
+ ungroupableTypes: {
28719
+ malloy: [],
28720
+ native: [
28721
+ "json",
28722
+ "xml",
28723
+ "point",
28724
+ "line",
28725
+ "lseg",
28726
+ "box",
28727
+ "path",
28728
+ "polygon",
28729
+ "circle",
28730
+ "txid_snapshot",
28731
+ "pg_snapshot"
28732
+ ]
28733
+ }
28748
28734
  }),
28749
28735
  standardsql: Object.freeze({
28750
28736
  ...NONE,
@@ -28757,7 +28743,11 @@ var init_dialect = __esm(() => {
28757
28743
  castsToIntegerType: true,
28758
28744
  onlyBigIntegerType: "INT64",
28759
28745
  leafBudget: 120,
28760
- stringCollation: "binary"
28746
+ stringCollation: "binary",
28747
+ ungroupableTypes: {
28748
+ malloy: ["json", "array", "record"],
28749
+ native: ["geography"]
28750
+ }
28761
28751
  }),
28762
28752
  snowflake: Object.freeze({
28763
28753
  ...NONE,
@@ -28768,7 +28758,15 @@ var init_dialect = __esm(() => {
28768
28758
  relationProbe: true,
28769
28759
  tableOwnership: true,
28770
28760
  castsToIntegerType: true,
28771
- leafBudget: 120
28761
+ leafBudget: 120,
28762
+ binary64Types: [
28763
+ "FLOAT",
28764
+ "FLOAT4",
28765
+ "FLOAT8",
28766
+ "DOUBLE",
28767
+ "DOUBLE PRECISION",
28768
+ "REAL"
28769
+ ]
28772
28770
  }),
28773
28771
  databricks: Object.freeze({
28774
28772
  ...NONE,
@@ -29378,7 +29376,6 @@ function persistDeclarationProblems(annotations) {
29378
29376
  }
29379
29377
  var ENV_REFERENCE_REASON, PERSIST_LINE_PATTERN, UNQUOTED_NAME_PATTERN, QUOTED_NAME_VALUE_PATTERN, SAFE_NAME_PATH;
29380
29378
  var init_persist_annotation_validation = __esm(() => {
29381
- init_errors2();
29382
29379
  init_annotation_reader();
29383
29380
  init_motly();
29384
29381
  init_table_name();
@@ -29386,7 +29383,7 @@ var init_persist_annotation_validation = __esm(() => {
29386
29383
  ENV_REFERENCE_REASON = "one of its lines reads the server's environment (`@env.`), which a " + "materialization annotation may not: Publisher never reads it, so the " + "line's directives are lost. Write the value into the model";
29387
29384
  PERSIST_LINE_PATTERN = /^\s*#@\s+persist\b/;
29388
29385
  UNQUOTED_NAME_PATTERN = /(?<![.\w])name\s*=\s*(?!["'])/;
29389
- QUOTED_NAME_VALUE_PATTERN = /(?<![.\w])name\s*=\s*(["'])(.*?)\1/g;
29386
+ QUOTED_NAME_VALUE_PATTERN = /(?<![.\w])name\s*=\s*(["'])((?:\\.|(?!\1)[^\\])*)\1/g;
29390
29387
  SAFE_NAME_PATH = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
29391
29388
  });
29392
29389
 
@@ -31345,6 +31342,25 @@ function persistedViewRefusalFinding(refusal, model) {
31345
31342
  refused: resultRefusalKey(persistedViewBuildName(refusal.sourceName, refusal.viewName), splitSourceID(refusal.sourceID)?.url ?? "", outcome.refused, refusal.storage)
31346
31343
  };
31347
31344
  }
31345
+ function persistedViewReadsGivenRefusal(plan) {
31346
+ return {
31347
+ sourceID: plan.sourceID,
31348
+ sourceName: plan.sourceName,
31349
+ viewName: plan.viewName,
31350
+ reason: READS_A_GIVEN,
31351
+ outcome: { refused: "reads_given" },
31352
+ ...plan.storage !== undefined ? { storage: plan.storage } : {}
31353
+ };
31354
+ }
31355
+ function persistedQueryReadsGivenRefusal(plan) {
31356
+ return {
31357
+ queryName: plan.queryName,
31358
+ reason: READS_A_GIVEN,
31359
+ refusal: "reads_given",
31360
+ declaringURL: plan.declaringURL,
31361
+ ...plan.storage !== undefined ? { storage: plan.storage } : {}
31362
+ };
31363
+ }
31348
31364
  function resultRefusalKey(buildSourceName, declaringURL, reason, storage) {
31349
31365
  return refusalKey(`${buildSourceName}@${persistedViewCompanionHref(declaringURL)}`, buildSourceName, reason, tierOf(storage));
31350
31366
  }
@@ -31423,7 +31439,7 @@ function persistedQueryRefusalFinding(refusal, model) {
31423
31439
  function persistedQueryRefusalKey(queryName, declaringURL, reason, storage) {
31424
31440
  return resultRefusalKey(persistedQueryBuildName(queryName), declaringURL, reason, storage);
31425
31441
  }
31426
- var PERSIST_VIEW_NOT_BUILT = "persist-view-not-built";
31442
+ var PERSIST_VIEW_NOT_BUILT = "persist-view-not-built", READS_A_GIVEN = "its result reads a given, so it differs per caller and a table holds one caller's result";
31427
31443
  var init_persisted_view = __esm(() => {
31428
31444
  init_annotation_reader();
31429
31445
  init_declared_notes();
@@ -31453,6 +31469,37 @@ var init_storage_table_path = __esm(() => {
31453
31469
  init_dialect();
31454
31470
  });
31455
31471
 
31472
+ // src/service/materialization/domain/placement.ts
31473
+ function storageWritable(mode) {
31474
+ return mode !== "off";
31475
+ }
31476
+ function storageServes(mode) {
31477
+ return mode === "on";
31478
+ }
31479
+ function instructionTier(instruction, mode) {
31480
+ return instruction.destination && storageWritable(mode) ? "storage" : "database";
31481
+ }
31482
+ function instructsUnwritableDestination(instruction, mode) {
31483
+ return !!instruction.destination && !storageWritable(mode);
31484
+ }
31485
+ function servedCopyReadsTier(tier, others) {
31486
+ return tier === "storage" || !others.includes("storage");
31487
+ }
31488
+ function readTier(facts) {
31489
+ if (!facts.storageBound) {
31490
+ return facts.declaredStorage ? "storage" : "database";
31491
+ }
31492
+ if (!facts.storageServed) {
31493
+ return facts.databaseBound ? "database" : "storage";
31494
+ }
31495
+ if (!facts.servedCopy)
31496
+ return "storage";
31497
+ return (!facts.storageFresh || facts.servedCopyOnDatabase) && facts.databaseFresh ? "database" : "storage";
31498
+ }
31499
+ function declaredDestination(declared, mode) {
31500
+ return storageWritable(mode) ? declared : undefined;
31501
+ }
31502
+
31456
31503
  // src/service/http_retry.ts
31457
31504
  function publicMessage(error) {
31458
31505
  const own = error?.publicMessage;
@@ -32947,7 +32994,7 @@ function deriveColumns(persistSource) {
32947
32994
  } catch (err) {
32948
32995
  logger.warn("Failed to derive columns for persist source", {
32949
32996
  sourceID: persistSource.sourceID,
32950
- error: errMessage(err)
32997
+ code: errorCodeOf(err)
32951
32998
  });
32952
32999
  return [];
32953
33000
  }
@@ -32964,11 +33011,171 @@ function declaresEmptyStorage(persistSource) {
32964
33011
  return tag !== undefined && "refused" in placementOf(tag, "persist");
32965
33012
  }
32966
33013
  var init_persist_source_fields = __esm(() => {
33014
+ init_error_code();
32967
33015
  init_declaration();
32968
33016
  init_logger();
32969
- init_utils();
32970
33017
  });
32971
33018
 
33019
+ // src/service/governance/ir/source_reads.ts
33020
+ function isObj2(value) {
33021
+ return value !== null && typeof value === "object" && !Array.isArray(value);
33022
+ }
33023
+ function holdsRawSqlExpression(def) {
33024
+ const seen = new Set;
33025
+ const walk = (node, depth) => {
33026
+ if (depth > MAX_DEPTH)
33027
+ return true;
33028
+ if (node === null || typeof node !== "object")
33029
+ return false;
33030
+ if (seen.has(node))
33031
+ return false;
33032
+ seen.add(node);
33033
+ if (Array.isArray(node))
33034
+ return node.some((c) => walk(c, depth + 1));
33035
+ const record = node;
33036
+ if (record.node === "genericSQLExpr")
33037
+ return true;
33038
+ return Object.entries(record).some(([key, child]) => !(record.node === "function_call" && key === "overload") && walk(child, depth + 1));
33039
+ };
33040
+ return walk(def, 0);
33041
+ }
33042
+ function joinNamed(fields, name) {
33043
+ if (!Array.isArray(fields))
33044
+ return;
33045
+ return fields.find((f) => isObj2(f) && f.join !== undefined && (f.as ?? f.name) === name);
33046
+ }
33047
+ function allJoins(fields) {
33048
+ if (!Array.isArray(fields))
33049
+ return [];
33050
+ return fields.filter((f) => isObj2(f) && f.join !== undefined).flatMap((join) => [join, ...allJoins(join.fields)]);
33051
+ }
33052
+ function resolveJoinPath(roots, path) {
33053
+ for (const fields of roots) {
33054
+ let at;
33055
+ let scope = fields;
33056
+ for (const alias of path) {
33057
+ at = joinNamed(scope, alias);
33058
+ if (!at)
33059
+ break;
33060
+ scope = at.fields;
33061
+ }
33062
+ if (at)
33063
+ return at;
33064
+ }
33065
+ throw new Unknown(`join path ${path.join(".")} did not resolve`);
33066
+ }
33067
+ function relationReads(def, out, depth) {
33068
+ if (depth > MAX_DEPTH || !isObj2(def))
33069
+ throw new Unknown("unreadable");
33070
+ switch (def.type) {
33071
+ case "table":
33072
+ if (typeof def.connection !== "string" || typeof def.tablePath !== "string") {
33073
+ throw new Unknown("table without a path");
33074
+ }
33075
+ out.push({ connectionName: def.connection, table: def.tablePath });
33076
+ return;
33077
+ case "query_source":
33078
+ queryReads(def.query, out, depth + 1);
33079
+ return;
33080
+ case "composite":
33081
+ if (!Array.isArray(def.sources))
33082
+ throw new Unknown("composite");
33083
+ for (const member of def.sources) {
33084
+ relationReads(member, out, depth + 1);
33085
+ }
33086
+ return;
33087
+ default:
33088
+ throw new Unknown(`relation type ${String(def.type)}`);
33089
+ }
33090
+ }
33091
+ function queryReads(query, out, depth) {
33092
+ if (!isObj2(query))
33093
+ throw new Unknown("query");
33094
+ const input = query.compositeResolvedSourceDef ?? query.structRef;
33095
+ if (!isObj2(input))
33096
+ throw new Unknown("unresolved structRef");
33097
+ relationReads(input, out, depth + 1);
33098
+ const pipeline = Array.isArray(query.pipeline) ? query.pipeline : [];
33099
+ pipeline.forEach((segment, index) => {
33100
+ if (!isObj2(segment))
33101
+ throw new Unknown("segment");
33102
+ const extended = Array.isArray(segment.extendSource) ? segment.extendSource : [];
33103
+ const roots = index === 0 ? [extended, input.fields] : [extended];
33104
+ const joins = Array.isArray(segment.activeJoins) ? segment.activeJoins.map((usage) => {
33105
+ if (!Array.isArray(usage.path))
33106
+ throw new Unknown("join usage");
33107
+ return resolveJoinPath(roots, usage.path);
33108
+ }) : roots.flatMap(allJoins);
33109
+ for (const join of joins)
33110
+ relationReads(join, out, depth + 1);
33111
+ });
33112
+ }
33113
+ function sourceReads(source) {
33114
+ try {
33115
+ const def = sourceDefOf(source);
33116
+ if (holdsRawSqlExpression(def))
33117
+ return;
33118
+ const out = [];
33119
+ relationReads(def, out, 0);
33120
+ const distinct = new Map(out.map((r) => [JSON.stringify([r.connectionName, r.table]), r]));
33121
+ return [...distinct.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, r]) => r);
33122
+ } catch {
33123
+ return;
33124
+ }
33125
+ }
33126
+ var MAX_DEPTH = 200, Unknown;
33127
+ var init_source_reads = __esm(() => {
33128
+ Unknown = class Unknown extends Error {
33129
+ };
33130
+ });
33131
+
33132
+ // src/service/materialization/domain/upstream_schemas.ts
33133
+ function upstreamTableKey(table) {
33134
+ return JSON.stringify([table.connectionName, table.table]);
33135
+ }
33136
+ function canonicalType(nativeType) {
33137
+ return nativeType.replace(/\s+/g, " ").replace(/\s*([(),])\s*/g, "$1").trim().toUpperCase();
33138
+ }
33139
+ function namesColumn(sql, name) {
33140
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33141
+ return new RegExp(`(^|[^A-Za-z0-9_])${escaped}($|[^A-Za-z0-9_])`, "i").test(sql);
33142
+ }
33143
+ function upstreamSchemaFold(reads, readings, sql) {
33144
+ if (!reads || !readings)
33145
+ return;
33146
+ const parts = [];
33147
+ for (const table of reads) {
33148
+ const reading = readings[upstreamTableKey(table)];
33149
+ if (!reading)
33150
+ continue;
33151
+ parts.push([
33152
+ table.connectionName,
33153
+ table.table,
33154
+ "unread" in reading ? reading.unread : reading.columns.filter((c) => namesColumn(sql, c.name)).map((c) => [c.name, canonicalType(c.nativeType)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
33155
+ ]);
33156
+ }
33157
+ return parts.length === 0 ? undefined : JSON.stringify(parts);
33158
+ }
33159
+ function upstreamSchemasOf(reads, readings) {
33160
+ if (!reads || !readings)
33161
+ return;
33162
+ const out = [];
33163
+ for (const table of reads) {
33164
+ const reading = readings[upstreamTableKey(table)];
33165
+ if (!reading)
33166
+ continue;
33167
+ out.push({
33168
+ connectionName: table.connectionName,
33169
+ table: table.table,
33170
+ ..."unread" in reading ? { unread: reading.unread } : {
33171
+ columns: reading.columns.map((c) => ({ ...c })),
33172
+ ...reading.dialect ? { dialect: reading.dialect } : {}
33173
+ }
33174
+ });
33175
+ }
33176
+ return out.length === 0 ? undefined : out;
33177
+ }
33178
+
32972
33179
  // src/service/materialization/plan/addressing.ts
32973
33180
  import { makeDigest } from "@malloydata/malloy";
32974
33181
  function sourceBuildOf(build, unbuildable) {
@@ -33088,15 +33295,34 @@ function withoutSourceIDs(build, drop) {
33088
33295
  function plannedTargetOf(source) {
33089
33296
  return buildTargets.get(source);
33090
33297
  }
33091
- function computeSourceEntityId(source, connectionDigests, target, tableFolds) {
33298
+ function computeSourceEntityId(source, connectionDigests, target, tableFolds, upstreamSchemas) {
33092
33299
  const resolved = buildTargetOf(source, target);
33093
33300
  const fold = tableFolds?.[source.sourceID];
33301
+ const upstream = upstreamFoldOf(source, upstreamSchemas, resolved.sql);
33094
33302
  const chosen = testAddresses.get(resolved);
33095
33303
  if (chosen !== undefined) {
33096
- const layout = addressText(source, "", fold);
33304
+ const layout = addressText(source, "", fold, upstream);
33097
33305
  return layout === "" ? chosen : makeDigest(chosen, layout);
33098
33306
  }
33099
- return makeDigest(connectionDigests[source.connectionName], addressText(source, resolved.sql, fold));
33307
+ return makeDigest(connectionDigests[source.connectionName], addressText(source, resolved.sql, fold, upstream));
33308
+ }
33309
+ function upstreamFoldOf(source, readings, sql) {
33310
+ if (!readings)
33311
+ return;
33312
+ return upstreamSchemaFold(upstreamTablesOf(source), readings, sql);
33313
+ }
33314
+ function upstreamTablesOf(source) {
33315
+ let known = readsBySource.get(source);
33316
+ if (!known) {
33317
+ known = { reads: sourceReads(source) };
33318
+ readsBySource.set(source, known);
33319
+ }
33320
+ return known.reads;
33321
+ }
33322
+ function upstreamSchemasOfSource(source, readings) {
33323
+ if (!readings)
33324
+ return;
33325
+ return upstreamSchemasOf(upstreamTablesOf(source), readings);
33100
33326
  }
33101
33327
  function compilerBuildId(source, target) {
33102
33328
  const resolved = buildTargetOf(source, target);
@@ -33105,7 +33331,7 @@ function compilerBuildId(source, target) {
33105
33331
  function addressDestination(source) {
33106
33332
  if (!getPersistAddressIncludesDestination())
33107
33333
  return;
33108
- if (getPersistStorageMode() === "off")
33334
+ if (!storageWritable(getPersistStorageMode()))
33109
33335
  return;
33110
33336
  try {
33111
33337
  return declaredStorage(source);
@@ -33113,7 +33339,7 @@ function addressDestination(source) {
33113
33339
  return;
33114
33340
  }
33115
33341
  }
33116
- function addressText(source, sql, tableFold) {
33342
+ function addressText(source, sql, tableFold, upstream) {
33117
33343
  let text = sql;
33118
33344
  const destination = addressDestination(source);
33119
33345
  if (destination !== undefined)
@@ -33122,6 +33348,9 @@ function addressText(source, sql, tableFold) {
33122
33348
  if (tableFold)
33123
33349
  text += `
33124
33350
  -- table: ${tableFold}`;
33351
+ if (upstream)
33352
+ text += `
33353
+ -- upstream schemas: ${upstream}`;
33125
33354
  return text;
33126
33355
  }
33127
33356
  function declarationOf(source) {
@@ -33158,7 +33387,7 @@ function planAddresses(plan) {
33158
33387
  const addresses = {};
33159
33388
  for (const [sourceID, { source, target }] of Object.entries(plan.tables)) {
33160
33389
  try {
33161
- addresses[sourceID] = computeSourceEntityId(source, plan.connectionDigests, target, plan.tableFolds);
33390
+ addresses[sourceID] = computeSourceEntityId(source, plan.connectionDigests, target, plan.tableFolds, plan.upstreamSchemas);
33162
33391
  } catch (err) {
33163
33392
  addresses[sourceID] = {
33164
33393
  unaddressable: err instanceof Error ? err.message : String(err)
@@ -33235,7 +33464,7 @@ function foldDistinctTableNames(plan, storedColumns) {
33235
33464
  return folds;
33236
33465
  }
33237
33466
  function storedTierOf(source) {
33238
- if (getPersistStorageMode() === "off")
33467
+ if (!storageWritable(getPersistStorageMode()))
33239
33468
  return "";
33240
33469
  try {
33241
33470
  return declaredStorage(source)?.trim() ?? "";
@@ -33281,7 +33510,7 @@ async function resolveConnectionDigests(connections, builds, onSkipped) {
33281
33510
  }
33282
33511
  return connectionDigests;
33283
33512
  }
33284
- var buildTargets, unkeyable, testAddresses;
33513
+ var buildTargets, unkeyable, testAddresses, readsBySource;
33285
33514
  var init_addressing = __esm(() => {
33286
33515
  init_config2();
33287
33516
  init_storage_table_path();
@@ -33289,11 +33518,16 @@ var init_addressing = __esm(() => {
33289
33518
  init_persist_source_fields();
33290
33519
  init_declaration();
33291
33520
  init_source_map();
33521
+ init_source_reads();
33292
33522
  buildTargets = new WeakMap;
33293
33523
  unkeyable = new WeakMap;
33294
33524
  testAddresses = new WeakMap;
33525
+ readsBySource = new WeakMap;
33295
33526
  });
33296
33527
 
33528
+ // src/service/materialization/domain/vocabulary.ts
33529
+ var init_vocabulary = () => {};
33530
+
33297
33531
  // src/service/materialization/domain/gate_policy.ts
33298
33532
  function ownRowLevelGate(t) {
33299
33533
  return t.gate?.rowLevel === true && t.gate.attributed && !t.gate.inheritedRowFilter;
@@ -33308,13 +33542,17 @@ function tableKeepsGates(t, s) {
33308
33542
  const row = Object.hasOwn(ROWS, t.kind) ? ROWS[t.kind] : undefined;
33309
33543
  return row ? row(t, s) === true : false;
33310
33544
  }
33311
- function gateColumnTypeExact(type) {
33312
- return !INEXACT_GATE_TYPE.test(type);
33545
+ function gateColumnTypeExact(type, upstream) {
33546
+ if (!INEXACT_GATE_TYPE.test(type))
33547
+ return true;
33548
+ if (!upstream || !isBinary64Type(STORAGE_DIALECT, type))
33549
+ return false;
33550
+ return isBinary64Type(upstream.dialect, upstream.nativeType);
33313
33551
  }
33314
33552
  function gateColumnsExact(t) {
33315
33553
  if (t.gateColumnTypes === undefined)
33316
33554
  return t.tier === "database";
33317
- return t.gateColumnTypes.every(gateColumnTypeExact);
33555
+ return t.gateColumnTypes.every((type, i) => gateColumnTypeExact(type, t.gateColumnUpstreamTypes?.[i]));
33318
33556
  }
33319
33557
  function g3Table(t) {
33320
33558
  return t.tier === "database" || t.ownGateKept === true || t.holdsOnlyUngatedRows === true;
@@ -33348,6 +33586,8 @@ function answerKeepsGates(leg, tablesRead, s, ctx) {
33348
33586
  }
33349
33587
  var ROWS, GATE_LEGS, SERVING_GATE_CONTEXT, INEXACT_GATE_TYPE;
33350
33588
  var init_gate_policy = __esm(() => {
33589
+ init_vocabulary();
33590
+ init_dialect();
33351
33591
  ROWS = {
33352
33592
  persist: (t) => persistKeepsGates(t),
33353
33593
  materialize: (t, s) => materializedKeepsGates(t, s),
@@ -33355,7 +33595,11 @@ var init_gate_policy = __esm(() => {
33355
33595
  rollup: (t, s) => !t.v1 && t.baseGateProven === true && (t.gate?.lockOnly === true || s.gatedSources || ownRowLevelGate(t)),
33356
33596
  view: () => false
33357
33597
  };
33358
- GATE_LEGS = ["view", "rollup", "served"];
33598
+ GATE_LEGS = [
33599
+ "view",
33600
+ "rollup",
33601
+ "served"
33602
+ ];
33359
33603
  SERVING_GATE_CONTEXT = {
33360
33604
  databaseReadsKeepGates: true
33361
33605
  };
@@ -33568,6 +33812,76 @@ function buildReadsCurrentTime(persistSource) {
33568
33812
  return true;
33569
33813
  }
33570
33814
  }
33815
+ function storedAsOfBuild(persistSource, kind) {
33816
+ if (kind !== "persist" && kind !== "view")
33817
+ return false;
33818
+ let def;
33819
+ try {
33820
+ def = sourceDefOf(persistSource);
33821
+ } catch {
33822
+ return false;
33823
+ }
33824
+ if (def === null || typeof def !== "object")
33825
+ return false;
33826
+ return buildReadsCurrentTime(persistSource);
33827
+ }
33828
+ function currentTimeReadsOf(persistSource, limit = 3) {
33829
+ let relation;
33830
+ try {
33831
+ const def = sourceDefOf(persistSource);
33832
+ if (def === null || typeof def !== "object")
33833
+ return [];
33834
+ const query = def.query;
33835
+ if (query !== null && typeof query === "object") {
33836
+ relation = query;
33837
+ } else {
33838
+ const {
33839
+ filterList: _readTimeFilters,
33840
+ fields: _readTimeFields,
33841
+ ...rest
33842
+ } = def;
33843
+ relation = rest;
33844
+ }
33845
+ } catch {
33846
+ return [];
33847
+ }
33848
+ const out = [];
33849
+ const seen = new WeakSet;
33850
+ const walk = (node, depth) => {
33851
+ if (out.length >= limit || depth > MAX_WALK_DEPTH2)
33852
+ return;
33853
+ if (node === null || typeof node !== "object")
33854
+ return;
33855
+ if (seen.has(node))
33856
+ return;
33857
+ seen.add(node);
33858
+ if (Array.isArray(node)) {
33859
+ for (const item of node)
33860
+ walk(item, depth + 1);
33861
+ return;
33862
+ }
33863
+ const record = node;
33864
+ const e = record.e;
33865
+ if (e !== undefined && readsCurrentTime(e)) {
33866
+ const code = record.code;
33867
+ const name = record.as ?? record.name;
33868
+ const said = record.node === "filterCondition" && typeof code === "string" ? `\`where: ${code}\`` : typeof name === "string" && record.join === undefined ? `the field \`${name}\`` : undefined;
33869
+ if (said !== undefined) {
33870
+ if (!out.includes(said))
33871
+ out.push(said);
33872
+ return;
33873
+ }
33874
+ }
33875
+ for (const [key, value] of Object.entries(record)) {
33876
+ if (key === "at" || key === "location" || key === "annotations" || key === "stableFilter") {
33877
+ continue;
33878
+ }
33879
+ walk(value, depth + 1);
33880
+ }
33881
+ };
33882
+ walk(relation, 0);
33883
+ return out;
33884
+ }
33571
33885
  function queryReadsCurrentTime(query, depth) {
33572
33886
  if (depth > MAX_WALK_DEPTH2)
33573
33887
  return true;
@@ -33926,14 +34240,66 @@ function readsCurrentTime(node, depth = 0) {
33926
34240
  const record = node;
33927
34241
  if (record.node === "now")
33928
34242
  return true;
34243
+ if (record.node === "filterMatch") {
34244
+ return filterMatchReadsCurrentTime(record, depth);
34245
+ }
34246
+ if (record.node === "filterLiteral") {
34247
+ return relativeTemporalFilter(record.filterSrc, false);
34248
+ }
33929
34249
  for (const [key, value] of Object.entries(record)) {
33930
- if (key === "at" || key === "location" || key === "annotations")
34250
+ if (key === "at" || key === "location" || key === "annotations" || key === "stableFilter") {
33931
34251
  continue;
34252
+ }
33932
34253
  if (readsCurrentTime(value, depth + 1))
33933
34254
  return true;
33934
34255
  }
33935
34256
  return false;
33936
34257
  }
34258
+ function filterMatchReadsCurrentTime(record, depth) {
34259
+ const kids = record.kids ?? {};
34260
+ if (readsCurrentTime(kids.expr, depth + 1))
34261
+ return true;
34262
+ const filter = kids.filterExpr;
34263
+ if (filter?.node !== "filterLiteral") {
34264
+ return readsCurrentTime(filter, depth + 1);
34265
+ }
34266
+ if (typeof record.dataType !== "string" || !TEMPORAL_FILTER_TYPES.has(record.dataType)) {
34267
+ return false;
34268
+ }
34269
+ return relativeTemporalFilter(filter.filterSrc, true);
34270
+ }
34271
+ function relativeTemporalFilter(src, unparseable) {
34272
+ if (typeof src !== "string")
34273
+ return unparseable;
34274
+ if (src.trim() === "")
34275
+ return false;
34276
+ let parsed;
34277
+ try {
34278
+ parsed = import_malloy_filter2.TemporalFilterExpression.parse(src).parsed;
34279
+ } catch {
34280
+ return unparseable;
34281
+ }
34282
+ if (parsed === null || parsed === undefined)
34283
+ return unparseable;
34284
+ return temporalFilterIsRelative(parsed, 0);
34285
+ }
34286
+ function temporalFilterIsRelative(node, depth) {
34287
+ if (depth > MAX_WALK_DEPTH2)
34288
+ return true;
34289
+ if (node === null || typeof node !== "object")
34290
+ return false;
34291
+ if (Array.isArray(node)) {
34292
+ return node.some((item) => temporalFilterIsRelative(item, depth + 1));
34293
+ }
34294
+ const record = node;
34295
+ if (typeof record.operator === "string" && RELATIVE_TEMPORAL_OPERATORS.has(record.operator)) {
34296
+ return true;
34297
+ }
34298
+ if (typeof record.moment === "string" && record.moment !== "literal") {
34299
+ return true;
34300
+ }
34301
+ return Object.values(record).some((value) => temporalFilterIsRelative(value, depth + 1));
34302
+ }
33937
34303
  function readNow(e) {
33938
34304
  if (!e || typeof e !== "object")
33939
34305
  return;
@@ -34093,13 +34459,14 @@ function fieldsDependingOn(fields, reads, depth = 0) {
34093
34459
  }
34094
34460
  return out;
34095
34461
  }
34096
- var MAX_WALK_DEPTH2 = 200, STAGE_PATH_SKIPPED_KEYS, JOIN_ONLY_KEYS, MAX_JOIN_DEPTH = 4, COMPARISONS, MIRROR, FIELD_PATH_SKIPPED_KEYS;
34462
+ var import_malloy_filter2, MAX_WALK_DEPTH2 = 200, STAGE_PATH_SKIPPED_KEYS, JOIN_ONLY_KEYS, MAX_JOIN_DEPTH = 4, TEMPORAL_FILTER_TYPES, RELATIVE_TEMPORAL_OPERATORS, COMPARISONS, MIRROR, FIELD_PATH_SKIPPED_KEYS;
34097
34463
  var init_persist_dynamic_terms = __esm(() => {
34098
34464
  init_declaration();
34099
34465
  init_given();
34100
34466
  init_probe_compiler();
34101
34467
  init_array_query();
34102
34468
  init_read_time_terms();
34469
+ import_malloy_filter2 = __toESM(require_dist());
34103
34470
  STAGE_PATH_SKIPPED_KEYS = new Set([
34104
34471
  "at",
34105
34472
  "location",
@@ -34113,6 +34480,16 @@ var init_persist_dynamic_terms = __esm(() => {
34113
34480
  "refSummary",
34114
34481
  "referenceID"
34115
34482
  ];
34483
+ TEMPORAL_FILTER_TYPES = new Set([
34484
+ "date",
34485
+ "timestamp",
34486
+ "timestamptz"
34487
+ ]);
34488
+ RELATIVE_TEMPORAL_OPERATORS = new Set([
34489
+ "last",
34490
+ "next",
34491
+ "in_last"
34492
+ ]);
34116
34493
  COMPARISONS = new Set([">=", ">", "<", "<="]);
34117
34494
  MIRROR = {
34118
34495
  ">=": "<=",
@@ -34123,6 +34500,19 @@ var init_persist_dynamic_terms = __esm(() => {
34123
34500
  FIELD_PATH_SKIPPED_KEYS = new Set(["at", "location", "annotations"]);
34124
34501
  });
34125
34502
 
34503
+ // src/service/materialization/domain/compiled_build_plan.ts
34504
+ function* sourcesInBuildOrder(build, tables) {
34505
+ for (const sourceID of build.order) {
34506
+ const source = tables[sourceID]?.source;
34507
+ if (source)
34508
+ yield source;
34509
+ }
34510
+ }
34511
+ function materializePlansOf(tables) {
34512
+ return Object.fromEntries(Object.entries(tables).flatMap(([sourceID, table]) => table.materialize ? [[sourceID, table.materialize]] : []));
34513
+ }
34514
+ var EVERY_SOURCE = "*";
34515
+
34126
34516
  // src/service/materialization/domain/key_check.ts
34127
34517
  function requireUnique(verdict) {
34128
34518
  return verdict === "unique";
@@ -34276,9 +34666,7 @@ function readFreshnessGroup(tag, path) {
34276
34666
  if (keys.includes("window")) {
34277
34667
  const window2 = tag.text(...path, "window");
34278
34668
  if (window2 === undefined || freshnessWindowSeconds(window2) === undefined) {
34279
- return {
34280
- invalid: "has a freshness.window= that is not a whole number and a unit " + '(s, m, h, d or w), such as freshness.window="24h"'
34281
- };
34669
+ return { invalid: FRESHNESS_WINDOW_PROBLEM };
34282
34670
  }
34283
34671
  freshness.window = window2.trim();
34284
34672
  }
@@ -37573,7 +37961,7 @@ function declarationRefusal(decl, facts, ctx) {
37573
37961
  measure: decl.measure
37574
37962
  };
37575
37963
  }
37576
- const timeRead = facts.windowed ? "the source's rows read the current time (a `where:` with `now`, a rolling window)" : timeFields.has(decl.measure) ? "the measure reads the current time (`now`)" : decl.grain.filter((g) => timeFields.has(g)).map((g) => `its grain dimension \`${g}\` reads the current time (\`now\`)`)[0];
37964
+ 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];
37577
37965
  if (timeRead) {
37578
37966
  return unservable("current_time", decl, `${timeRead}, which a rollup would fix at build time while a live query reads it again at every read`);
37579
37967
  }
@@ -37771,7 +38159,8 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
37771
38159
  label: "",
37772
38160
  exprs: ["false"],
37773
38161
  route: "authorize",
37774
- selfContained: true
38162
+ selfContained: true,
38163
+ baseHops: 0
37775
38164
  }
37776
38165
  ];
37777
38166
  unkeepable.add("(an unreadable gate)");
@@ -37779,6 +38168,9 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
37779
38168
  for (const entry of entries) {
37780
38169
  if (!entry.struct)
37781
38170
  unkeepable.add("(an unreadable gate)");
38171
+ if (entry.baseHops > 0 && canonicalAuthorizeRoute(entry.route) !== AUTHORIZE_ROUTE) {
38172
+ unkeepable.add("(a row filter on a derivation's base)");
38173
+ }
37782
38174
  for (const expr of entry.exprs) {
37783
38175
  for (const id of malloyIdentifiers(expr)) {
37784
38176
  const f = byName.get(id);
@@ -37861,6 +38253,15 @@ function planModelRollups(map, ctx, declaredHere) {
37861
38253
  }
37862
38254
  return { plans, refused };
37863
38255
  }
38256
+ function rollupReadsGivenRefusal(plan, source) {
38257
+ return {
38258
+ tier: "unservable",
38259
+ code: ROLLUP_NOT_BUILT_CODE,
38260
+ message: `#(rollup) rollup of source "${plan.baseSourceName}" at ` + `(${plan.grainDimensions.join(", ")}) is not built, so its measures ` + "are served live: its rows read a given, and a table holds one " + "value's rows.",
38261
+ sourceName: plan.baseSourceName,
38262
+ refused: refusalKey(source.sourceID, source.name, "reads_given", tierOf(plan.storage))
38263
+ };
38264
+ }
37864
38265
  function rollupRefusalFinding(refusal, model) {
37865
38266
  return {
37866
38267
  route: ROLLUP_ROUTE,
@@ -38022,6 +38423,9 @@ function unreadableSourceConnectionMessage(source, type) {
38022
38423
  const what = type === undefined ? `is not one of the environment's connections (the package's own ` + `DuckDB sandbox is not)` : type === "ducklake" ? `is a DuckLake catalog other than the destination's` : `is a '${type}' connection`;
38023
38424
  return `Source '${source.name}' cannot be materialized into a storage ` + `destination: its connection '${source.connectionName}' ${what}, ` + `which cannot be passed through to a 'storage=' build (it reads ` + `${PASSTHROUGH_SOURCE_TYPES.join(", ")} sources, and a DuckLake ` + `source into its own catalog only). ` + `The source is not built and is answered live. Drop 'storage=' to ` + `build it in its own connection, or put the source on a warehouse ` + `connection.`;
38024
38425
  }
38426
+ function catalogAuthorSqlMessage(source, { managed = false } = {}) {
38427
+ return `Source '${source.name}' cannot be materialized: its connection ` + `'${source.connectionName}' is a ${managed ? "managed database" : "DuckLake catalog"}, whose tables are ` + `built inside the catalog by SQL Malloy generates, and the source ` + `carries SQL its author wrote (an .sql() source or a sql_* ` + `expression, its own or a joined source's) or reads a file or URL as a ` + `table. The source is not built and is answered live. Express it in ` + `Malloy over the catalog's tables to build it.`;
38428
+ }
38025
38429
  var PASSTHROUGH_SOURCE_TYPES;
38026
38430
  var init_source_connection_type = __esm(() => {
38027
38431
  PASSTHROUGH_SOURCE_TYPES = [
@@ -38031,6 +38435,59 @@ var init_source_connection_type = __esm(() => {
38031
38435
  ];
38032
38436
  });
38033
38437
 
38438
+ // src/service/materialization/domain/same_catalog_build.ts
38439
+ function isSameCatalog(source, destination) {
38440
+ const a = source?.type === "ducklake" ? source.ducklakeConnection : undefined;
38441
+ const b = destination?.type === "ducklake" ? destination.ducklakeConnection : undefined;
38442
+ if (!a || !b)
38443
+ return false;
38444
+ const pa = a.catalog?.postgresConnection;
38445
+ const pb = b.catalog?.postgresConnection;
38446
+ if (!pa || !pb)
38447
+ return false;
38448
+ const path = (url) => (url ?? "").replace(/\/+$/, "");
38449
+ const pathA = path(a.storage?.bucketUrl);
38450
+ const pathB = path(b.storage?.bucketUrl);
38451
+ return !!pa.host && pa.host === pb.host && (pa.port ?? 5432) === (pb.port ?? 5432) && !!pa.databaseName && pa.databaseName === pb.databaseName && (a.catalog.metadataSchema ?? "") === (b.catalog.metadataSchema ?? "") && (pathA === "" || pathB === "" || pathA === pathB);
38452
+ }
38453
+ function carriesAuthorSql(def) {
38454
+ const seen = new Set;
38455
+ const walk = (node, depth) => {
38456
+ if (depth > MAX_DEPTH2)
38457
+ return true;
38458
+ if (node === null || typeof node !== "object")
38459
+ return false;
38460
+ if (seen.has(node))
38461
+ return false;
38462
+ seen.add(node);
38463
+ if (Array.isArray(node)) {
38464
+ return node.some((child) => walk(child, depth + 1));
38465
+ }
38466
+ const record = node;
38467
+ if (record.type === "sql_select" || record.node === "genericSQLExpr") {
38468
+ return true;
38469
+ }
38470
+ if (record.node === "function_call") {
38471
+ return Object.entries(record).some(([key, child]) => key !== "overload" && walk(child, depth + 1));
38472
+ }
38473
+ if (record.type === "table" && typeof record.tablePath === "string" && !CATALOG_TABLE_PATH.test(record.tablePath)) {
38474
+ return true;
38475
+ }
38476
+ return Object.values(record).some((child) => walk(child, depth + 1));
38477
+ };
38478
+ try {
38479
+ if (def === null || typeof def !== "object")
38480
+ return true;
38481
+ return walk(def, 0);
38482
+ } catch {
38483
+ return true;
38484
+ }
38485
+ }
38486
+ var CATALOG_TABLE_PATH, MAX_DEPTH2 = 200;
38487
+ var init_same_catalog_build = __esm(() => {
38488
+ CATALOG_TABLE_PATH = /^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)*$/;
38489
+ });
38490
+
38034
38491
  // src/service/materialization/plan/materialization_eligibility.ts
38035
38492
  function assertMaterializationEligible(persistSource, annotationFields, options = {}) {
38036
38493
  const sourceName = persistSource.name;
@@ -38067,11 +38524,29 @@ function assertMaterializationEligible(persistSource, annotationFields, options
38067
38524
  }
38068
38525
  function assertStorageBuildReadsConnection(persistSource, connectionTypes) {
38069
38526
  const type = connectionTypes?.[persistSource.connectionName];
38070
- if (type === undefined || storageBuildReadsConnectionType(type))
38527
+ if (type === undefined)
38528
+ return;
38529
+ if (!storageBuildReadsConnectionType(type)) {
38530
+ throw new MaterializationEligibilityError({
38531
+ reason: "storage_source_unsupported",
38532
+ message: unreadableSourceConnectionMessage(persistSource, type)
38533
+ });
38534
+ }
38535
+ if (type === "ducklake" && carriesAuthorSql(sourceDefOf(persistSource))) {
38536
+ throw new MaterializationEligibilityError({
38537
+ reason: "storage_source_unsupported",
38538
+ message: catalogAuthorSqlMessage(persistSource)
38539
+ });
38540
+ }
38541
+ }
38542
+ function assertManagedBuildRunsMalloySql(source, plan) {
38543
+ if (!plan?.managedConnections?.includes(source.connectionName))
38544
+ return;
38545
+ if (!carriesAuthorSql(sourceDefOf(source)))
38071
38546
  return;
38072
38547
  throw new MaterializationEligibilityError({
38073
38548
  reason: "storage_source_unsupported",
38074
- message: unreadableSourceConnectionMessage(persistSource, type)
38549
+ message: catalogAuthorSqlMessage(source, { managed: true })
38075
38550
  });
38076
38551
  }
38077
38552
  function assertMergeKeyScopeResolvable(persistSource, terms, annotationFields, what) {
@@ -38187,6 +38662,13 @@ function referencesAuthorize(persistSource) {
38187
38662
  return true;
38188
38663
  }
38189
38664
  }
38665
+ function irCarriesAGate(def) {
38666
+ try {
38667
+ return walkForAuthorize(def, new WeakSet, 0);
38668
+ } catch {
38669
+ return true;
38670
+ }
38671
+ }
38190
38672
  function isAuthorizeAnnotation(text) {
38191
38673
  try {
38192
38674
  return parseAuthorizeAnnotation(text) !== null;
@@ -38400,6 +38882,7 @@ function assertTierEligible(source, storage, plan, annotationFields = deriveAnno
38400
38882
  assertBuildReadsNoCurrentTime(source, plan);
38401
38883
  return;
38402
38884
  }
38885
+ assertManagedBuildRunsMalloySql(source, plan);
38403
38886
  const table = plan?.tables?.[source.sourceID];
38404
38887
  const rollup = table?.rollup;
38405
38888
  assertDatabasePersistNotAuthorizeGated(source, source.name, rollup ? "rollup" : "persist", table?.gate, annotationFields, { gateEnforcedAtRead: !!rollup && rollupGateEnforcedAtRead(rollup) });
@@ -38423,11 +38906,38 @@ function assertBuildReadsNoCurrentTime(source, plan) {
38423
38906
  return;
38424
38907
  if (!buildReadsCurrentTime(source))
38425
38908
  return;
38909
+ const why = currentTimeRefusalCause(source, plan);
38910
+ if (why === undefined)
38911
+ return;
38426
38912
  throw new MaterializationEligibilityError({
38427
38913
  reason: "current_time",
38428
- message: `Source '${source.name}' cannot be materialized: the relation it ` + `persists reads the current time (\`now\`), in its query, a view ` + `it runs, the \`where:\`, a field or a join of the source that ` + `query reads, or the query of a query-shaped source it is built ` + `from or joins. Its table would hold the rows as of the build and ` + `serve them until the next rebuild, while a live query reads \`now\` ` + `again every time, so it is not built and is answered live. To serve ` + `it from a table, move the \`now\` into the persisted source's own ` + `extend block (a \`where:\`, dimension or measure there is applied ` + `at every read), or stop persisting this source.`
38914
+ message: `Source '${source.name}' cannot be materialized: the relation it ` + `persists reads the current time (\`now\`, or a relative time ` + `filter such as \`f'last 7 days'\`), so its table would hold the ` + `rows as of its build, and ${why}. It is not built and is answered ` + `live. To serve it from a table, move the \`now\` or the filter into ` + `the persisted source's own extend block (a \`where:\`, dimension or ` + `measure there is applied at every read).`
38429
38915
  });
38430
38916
  }
38917
+ function currentTimeRefusalCause(source, plan) {
38918
+ if (referencesAuthorize(source)) {
38919
+ return "it is protected by an #(authorize) or #(access_filter) gate, whose " + "decision a table as of its build would freeze";
38920
+ }
38921
+ if (deriveAnnotationFields(source).refresh === "incremental") {
38922
+ return "it refreshes incrementally, and a delta never re-reads the rows " + "its window has passed";
38923
+ }
38924
+ if (currentTimeAccessInput(source, plan)) {
38925
+ return "its rows feed an access decision (it is scoped by a given, joins " + "a source scoped by one, or a source that carries a gate or reads " + "a given extends, derives from, joins or composes it), so a table " + "as of its build would keep a grant past its time";
38926
+ }
38927
+ return;
38928
+ }
38929
+ function currentTimeAccessInput(source, plan) {
38930
+ const admitted = admitGivenPositions(source);
38931
+ if (!admitted.ok)
38932
+ return true;
38933
+ if (admitted.terms.length > 0 || (admitted.joinedTerms ?? []).length > 0) {
38934
+ return true;
38935
+ }
38936
+ const reads = plan?.accessReads;
38937
+ if (reads === undefined)
38938
+ return true;
38939
+ return reads.includes(source.sourceID) || reads.includes(EVERY_SOURCE);
38940
+ }
38431
38941
  var READ_ONLY_DIALECTS, MAX_AUTHORIZE_WALK_DEPTH = 200;
38432
38942
  var init_materialization_eligibility = __esm(() => {
38433
38943
  init_config2();
@@ -38441,6 +38951,7 @@ var init_materialization_eligibility = __esm(() => {
38441
38951
  init_declaration();
38442
38952
  init_rollup_plan();
38443
38953
  init_source_connection_type();
38954
+ init_same_catalog_build();
38444
38955
  READ_ONLY_DIALECTS = new Set(["sqlserver"]);
38445
38956
  });
38446
38957
 
@@ -39032,10 +39543,10 @@ function storableDimension(field) {
39032
39543
  }
39033
39544
  return dimension;
39034
39545
  }
39035
- function storableArray(field) {
39036
- if (field.type !== "array" || field.e !== undefined)
39546
+ function storableNested(field) {
39547
+ if (field.type !== "array" && field.type !== "record")
39037
39548
  return;
39038
- if (hiddenAccess(field))
39549
+ if (field.e !== undefined)
39039
39550
  return;
39040
39551
  const dimension = typeof field.as === "string" ? field.as : typeof field.name === "string" ? field.name : undefined;
39041
39552
  return dimension;
@@ -39046,9 +39557,15 @@ function materializeColumns(def, options = {}) {
39046
39557
  const perCaller = givenReadingFields(def.fields);
39047
39558
  for (const raw of def.fields ?? []) {
39048
39559
  const field = raw;
39049
- const nested = storableArray(field);
39560
+ const nested = storableNested(field);
39050
39561
  if (nested !== undefined) {
39051
- out.push({ dimension: nested, column: nested, computed: false });
39562
+ const access = hiddenAccess(field);
39563
+ out.push({
39564
+ dimension: nested,
39565
+ column: nested,
39566
+ computed: false,
39567
+ ...access ? { access } : {}
39568
+ });
39052
39569
  continue;
39053
39570
  }
39054
39571
  const dimension = storableDimension(field);
@@ -39787,6 +40304,10 @@ function pairLayoutOf(def, map, args) {
39787
40304
  if (problem) {
39788
40305
  return new Declined(problem.reason, { refused: "inline_unsupported" });
39789
40306
  }
40307
+ const ungrouped = ungroupablePairColumn(def, map, columns);
40308
+ if (ungrouped) {
40309
+ return new Declined(ungrouped, { refused: "inline_unsupported" });
40310
+ }
39790
40311
  const pairs = laid.map((l) => l.pair);
39791
40312
  pair = pairs[0];
39792
40313
  if (pairs.length > 1) {
@@ -39846,6 +40367,48 @@ function pairLayoutOf(def, map, args) {
39846
40367
  ...pairFullRefresh ? { pairFullRefresh } : {}
39847
40368
  };
39848
40369
  }
40370
+ function ungroupablePairColumn(def, map, columns) {
40371
+ const refused = capabilitiesOf(def.dialect).ungroupableTypes;
40372
+ if (!refused)
40373
+ return;
40374
+ for (const c of columns) {
40375
+ const type = ungroupedTypeOf(storedFieldOf(def, map, c), refused);
40376
+ if (type === undefined)
40377
+ continue;
40378
+ return `inline= names a join_many, whose pair table's build groups by every ` + `stored column, and \`${c.column}\` is a ${type.toUpperCase()} column, ` + `which ${describeDialects(new Set([String(def.dialect)]))} cannot ` + "group by; leave the column out of the source (and of the joined " + "source's public dimensions), or inline no join_many";
40379
+ }
40380
+ return;
40381
+ }
40382
+ function ungroupedTypeOf(field, refused) {
40383
+ if (field?.type === "sql native") {
40384
+ const raw = typeof field.rawType === "string" ? field.rawType.toLowerCase() : "";
40385
+ return refused.native.includes(raw) ? raw : undefined;
40386
+ }
40387
+ if (typeof field?.type !== "string")
40388
+ return;
40389
+ if (refused.malloy.includes(field.type))
40390
+ return field.type;
40391
+ if (field.type === "array") {
40392
+ const element = ungroupedTypeOf(field.elementTypeDef, refused);
40393
+ return element === undefined ? undefined : `${element}[]`;
40394
+ }
40395
+ return;
40396
+ }
40397
+ function storedFieldOf(def, map, c) {
40398
+ let fields = def.fields ?? [];
40399
+ let joins = map.joinsOf(def.sourceID);
40400
+ for (const name of c.join === undefined ? [] : c.path ?? [c.join]) {
40401
+ const join = joins.find((j) => j.name === name);
40402
+ if (!join)
40403
+ return;
40404
+ fields = join.fields;
40405
+ joins = map.joinedReadsOf(join).joins;
40406
+ }
40407
+ return fields.find((raw) => {
40408
+ const f = raw;
40409
+ return (typeof f.as === "string" ? f.as : f.name) === c.dimension;
40410
+ });
40411
+ }
39849
40412
  function chainExtensionTables(plans, map) {
39850
40413
  const byID = new Map(plans.map((p) => [p.sourceID, p]));
39851
40414
  const declarationOfID = (sourceID) => declarationOf2(map.node(sourceID)?.def);
@@ -40274,7 +40837,9 @@ function withoutSources(compiled, findings, drop) {
40274
40837
  function tierGateInputs(compiled) {
40275
40838
  return {
40276
40839
  tables: compiled.tables,
40277
- connectionTypes: compiled.connectionTypes
40840
+ connectionTypes: compiled.connectionTypes,
40841
+ managedConnections: compiled.managedConnections,
40842
+ accessReads: compiled.accessReads
40278
40843
  };
40279
40844
  }
40280
40845
  function collectSourceEligibility(compiled, verdicts = planVerdicts(compiled)) {
@@ -40314,8 +40879,8 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
40314
40879
  logger.warn("Dropping a refused database source: its content address could not be computed", {
40315
40880
  sourceID,
40316
40881
  sourceName: source.name,
40317
- refusal: errMessage(err),
40318
- error: errMessage(idErr)
40882
+ reason: errorCodeOf(err),
40883
+ code: errorCodeOf(idErr)
40319
40884
  });
40320
40885
  continue;
40321
40886
  }
@@ -40327,7 +40892,7 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
40327
40892
  try {
40328
40893
  sourceEntityId = planAddressOf(compiled, sourceID);
40329
40894
  } catch (err) {
40330
- logger.warn("Dropping an eligible database source: its content address could not be computed", { sourceID, sourceName: source.name, error: errMessage(err) });
40895
+ logger.warn("Dropping an eligible database source: its content address could not be computed", { sourceID, sourceName: source.name, code: errorCodeOf(err) });
40331
40896
  continue;
40332
40897
  }
40333
40898
  if (!(sourceEntityId in refused)) {
@@ -40480,6 +41045,7 @@ function databaseRefusalsByAddress(compiled, verdicts, include) {
40480
41045
  }
40481
41046
  var EligibilityCheckFailed;
40482
41047
  var init_eligibility_collect = __esm(() => {
41048
+ init_error_code();
40483
41049
  init_errors2();
40484
41050
  init_storage_table_path();
40485
41051
  init_table_name();
@@ -40568,10 +41134,10 @@ function planCollisions(plan, materializePlans, versionScoped) {
40568
41134
  }
40569
41135
  return out;
40570
41136
  }
40571
- function incrementalPolicySourcesOf(plan, declarations, materializePlans, persistedViews = new Map) {
41137
+ function incrementalPolicySourcesOf(plan, declarations, materializePlans, persistedViews = {}) {
40572
41138
  return Object.entries(plan?.sources ?? {}).filter(([sourceID]) => declarations[sourceID]).map(([sourceID, source]) => ({
40573
- ...persistedViews.get(sourceID) ?? { sourceName: source.name },
40574
- invalidCode: persistedViews.has(sourceID) ? PERSIST_VIEW_INVALID_CODE : materializePlans?.[sourceID] ? MATERIALIZE_INVALID_CODE : PERSIST_INVALID_CODE,
41139
+ ...persistedViews[sourceID] ?? { sourceName: source.name },
41140
+ invalidCode: persistedViews[sourceID] ? PERSIST_VIEW_INVALID_CODE : materializePlans?.[sourceID] ? MATERIALIZE_INVALID_CODE : PERSIST_INVALID_CODE,
40575
41141
  ...source.modelPath ? { modelPath: source.modelPath } : {},
40576
41142
  ...source.dialect ? { dialect: source.dialect } : {},
40577
41143
  ...source.annotationFields?.storage ? { storageDestination: source.annotationFields.storage } : {},
@@ -40586,15 +41152,27 @@ function collisionGateLines(collisions) {
40586
41152
  return collisions.map((c) => codedLine(c.enforced, MATERIALIZATION_TABLE_COLLISION_CODE));
40587
41153
  }
40588
41154
  function loadGateText(gated, judgement) {
40589
- return [
41155
+ return withNameProblems(gated.modelGateLines?.nameProblems ?? [], [
40590
41156
  ...invalidFindingLines(gated.annotationFindings.map((f) => relaxedCollision(f, judgement.enforceCollisions))),
40591
41157
  ...judgement.enforceCollisions ? collisionGateLines(planCollisions(gated.plan, gated.materializePlans, judgement.versionScoped)) : [],
40592
- ...incrementalGateLines(incrementalPolicySourcesOf(gated.plan, gated.incrementalDeclarations, gated.materializePlans, judgement.persistedViews)),
41158
+ ...incrementalGateLines(incrementalPolicySourcesOf(gated.plan, gated.incrementalDeclarations, gated.materializePlans, gated.persistedViews)),
40593
41159
  ...gated.modelGateLines?.preaggregate ?? [],
40594
41160
  ...gated.modelGateLines?.nearMiss ?? []
40595
- ].join(`
41161
+ ]);
41162
+ }
41163
+ function withNameProblems(problems, lines) {
41164
+ const unsafe = problems.flatMap((p) => p.unsafeValue === undefined ? [] : [p.unsafeValue, unescapedTagValue(p.unsafeValue)].map((value) => `its name= "${value}" is not a plain identifier path`));
41165
+ return [
41166
+ ...problems.map((p) => p.line),
41167
+ ...lines.filter(Boolean).join(`
41168
+ `).split(`
41169
+ `).filter((line) => !unsafe.some((u) => line.includes(u)))
41170
+ ].filter(Boolean).join(`
40596
41171
  `);
40597
41172
  }
41173
+ function unescapedTagValue(raw) {
41174
+ return raw.replace(/\\(.)/g, "$1");
41175
+ }
40598
41176
  function preaggregateViolationCode(code) {
40599
41177
  if (code === "unknown_key")
40600
41178
  return "rollup-unknown-key";
@@ -40820,6 +41398,177 @@ var init_annotation_near_miss = __esm(() => {
40820
41398
  ]);
40821
41399
  });
40822
41400
 
41401
+ // src/materialization_metrics.ts
41402
+ function routeLegOf(kind) {
41403
+ return kind === "served" ? "materialized" : kind;
41404
+ }
41405
+ function recordScheduledFire(outcome) {
41406
+ scheduledFireCounter().add(1, { outcome });
41407
+ }
41408
+ function recordMaterializationRun(mode, outcome, durationMs) {
41409
+ runCounter().add(1, { mode, outcome });
41410
+ runDuration().record(durationMs, { mode, outcome });
41411
+ }
41412
+ function recordBuildOutcome(labels) {
41413
+ buildCounter().add(1, {
41414
+ kind: labels.kind,
41415
+ tier: labels.tier,
41416
+ outcome: labels.outcome,
41417
+ failure_class: labels.outcome === "failed" ? labels.failureClass : "none"
41418
+ });
41419
+ }
41420
+ function recordBuildDuration(durationMs, labels) {
41421
+ buildDuration().record(durationMs, {
41422
+ kind: labels.kind,
41423
+ tier: labels.tier,
41424
+ method: labels.method
41425
+ });
41426
+ }
41427
+ function recordBuildReadBytes(bytes, tier) {
41428
+ if (typeof bytes !== "number" || !(bytes > 0))
41429
+ return;
41430
+ buildReadBytes().record(bytes, { tier });
41431
+ }
41432
+ function recordAnnotationFindings(warnings) {
41433
+ for (const { code, severity } of warnings) {
41434
+ if (!code)
41435
+ continue;
41436
+ annotationFindingsCounter().add(1, {
41437
+ code,
41438
+ outcome: severity === "error" ? "invalid" : "not_built"
41439
+ });
41440
+ }
41441
+ }
41442
+ function recordIncrementalStep(step, reason) {
41443
+ incrementalStepCounter().add(1, reason ? { step, reason } : { step });
41444
+ }
41445
+ function recordBuildPlanComputeDuration(durationMs, computedIn) {
41446
+ buildPlanComputeDuration().record(durationMs, { computed_in: computedIn });
41447
+ }
41448
+ function recordBuildPlanComputeFailed() {
41449
+ buildPlanComputeFailedCounter().add(1);
41450
+ }
41451
+ function recordAutoLoadOutcome(outcome) {
41452
+ autoLoadCounter().add(1, { outcome });
41453
+ }
41454
+ function recordConnectionDigestSkipped() {
41455
+ connectionDigestSkipCounter().add(1);
41456
+ }
41457
+ function recordDuplicateTargetSkipped() {
41458
+ duplicateTargetSkipCounter().add(1);
41459
+ }
41460
+ function recordSharedAddressInstructions() {
41461
+ sharedAddressInstructionCounter().add(1);
41462
+ }
41463
+ function recordTableCollision() {
41464
+ tableCollisionCounter().add(1);
41465
+ }
41466
+ function recordManifestBind(outcome) {
41467
+ servedCopyBindCounter().add(1, {
41468
+ scope: "manifest",
41469
+ outcome,
41470
+ reason: "none"
41471
+ });
41472
+ }
41473
+ function recordSourceBound() {
41474
+ servedCopyBindCounter().add(1, {
41475
+ scope: "source",
41476
+ outcome: "bound",
41477
+ reason: "none"
41478
+ });
41479
+ }
41480
+ function recordSourceDeclined(reason) {
41481
+ servedCopyBindCounter().add(1, {
41482
+ scope: "source",
41483
+ outcome: "declined",
41484
+ reason
41485
+ });
41486
+ }
41487
+ function recordServedCopyOutcome(outcome, reason) {
41488
+ servedCopyBindCounter().add(1, { scope: "source", outcome, reason });
41489
+ }
41490
+ function recordManifestBindDegraded() {
41491
+ manifestBindDegradedCounter().add(1);
41492
+ }
41493
+ function recordDropTables(outcome, tier, occasion) {
41494
+ dropTablesCounter().add(1, { outcome, tier, occasion });
41495
+ }
41496
+ function recordKeyCheck(kind, outcome) {
41497
+ keyCheckCounter().add(1, { kind, outcome });
41498
+ }
41499
+ function recordQueryRouteDuration(durationMs, leg) {
41500
+ queryRouteDuration().record(durationMs, { leg });
41501
+ }
41502
+ function recordStorageTableRetained() {
41503
+ storageTableRetainedCounter().add(1);
41504
+ }
41505
+ function recordAttributionSkipped(reason) {
41506
+ attributionSkippedCounter().add(1, { reason });
41507
+ }
41508
+ function recordEligibilityRefused(reason) {
41509
+ eligibilityRefusedCounter().add(1, { reason });
41510
+ }
41511
+ function recordStoredTypeFallback(kind) {
41512
+ serveShapeTypeFallbackCounter().add(1, { kind });
41513
+ }
41514
+ function recordStoredColumnTypeMismatch(stage, declared) {
41515
+ storedColumnTypeMismatchCounter().add(1, { stage, declared });
41516
+ }
41517
+ function recordQueryRoute(leg, outcome, reason) {
41518
+ queryRouteCounter().add(1, { leg, outcome, reason });
41519
+ }
41520
+ function recordChainedStorageBuild(outcome) {
41521
+ chainedStorageBuildCounter().add(1, { outcome });
41522
+ }
41523
+ function recordStaleUpstreamEntry(tier) {
41524
+ staleUpstreamEntryCounter().add(1, { tier });
41525
+ }
41526
+ var BUILD_DURATION_BUCKETS_MS, BUILD_READ_BYTES_BUCKETS, runCounter, runDuration, buildCounter, buildDuration, buildReadBytes, annotationFindingsCounter, incrementalStepCounter, buildPlanComputeDuration, buildPlanComputeFailedCounter, autoLoadCounter, connectionDigestSkipCounter, servedCopyBindCounter, manifestBindDegradedCounter, duplicateTargetSkipCounter, sharedAddressInstructionCounter, tableCollisionCounter, dropTablesCounter, scheduledFireCounter, queryRouteCounter, queryRouteDuration, keyCheckCounter, storageTableRetainedCounter, attributionSkippedCounter, eligibilityRefusedCounter, serveShapeTypeFallbackCounter, storedColumnTypeMismatchCounter, chainedStorageBuildCounter, staleUpstreamEntryCounter;
41527
+ var init_materialization_metrics = __esm(() => {
41528
+ init_vocabulary();
41529
+ init_telemetry();
41530
+ BUILD_DURATION_BUCKETS_MS = [
41531
+ 100,
41532
+ 500,
41533
+ 1000,
41534
+ 5000,
41535
+ 15000,
41536
+ 60000,
41537
+ 300000,
41538
+ 900000,
41539
+ 3600000
41540
+ ];
41541
+ BUILD_READ_BYTES_BUCKETS = [1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000];
41542
+ runCounter = lazyCounter("publisher_materialization_runs_total", "Materialization builds completed. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
41543
+ runDuration = lazyHistogram("publisher_materialization_run_duration_ms", "Wall-clock duration of a materialization build. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
41544
+ buildCounter = lazyCounter("publisher_materialization_build_total", "Source builds, one per source per run at its finish or failure. Labels: " + "kind ('materialize'|'persist'|'rollup'|'view'|'query'|'pair'), tier " + "('database'|'storage'), outcome ('built'|'reused'|'refused'|'failed'|" + "'cancelled'), failure_class ('none' unless outcome is 'failed'; then " + "'deterministic'|'transient'|'unclassified'|'billed_read_lost'). " + "'billed_read_lost' is the expensive one: the warehouse read ran and was " + "charged and its rows were not captured, so a retry pays for it again.");
41545
+ buildDuration = lazyHistogram("publisher_materialization_build_duration_ms", "Wall-clock duration of one source's build, for builds that ran (built or " + "failed; a skipped incremental refresh did no work and is not timed). " + "Labels: kind, tier, method ('full'|'delta').", { buckets: BUILD_DURATION_BUCKETS_MS });
41546
+ buildReadBytes = lazyHistogram("publisher_materialization_build_read_bytes", "Warehouse bytes scanned by one source's build read, when the warehouse " + "reported a count; absent otherwise, never zero. Label: tier.", { unit: "By", buckets: BUILD_READ_BYTES_BUCKETS });
41547
+ annotationFindingsCounter = lazyCounter("publisher_annotation_findings_total", "Coded findings on authored annotations (the #@ route, and the near-miss and malformed-route scan over every route), counted once each time a package is loaded and accepted for serving (boot, add, publish, reload; a refused publish and a gate re-run count nothing). Labels: code (e.g. 'persist-unknown-key', 'persist-unparseable', 'persist-not-built'), outcome ('invalid' for an error-severity finding, which fails the load, 'not_built' for a warning: a valid annotation not built here, and also the warn-level 'annotation-near-miss' and 'persist-incremental-no-merge-key' advisories, which build).");
41548
+ incrementalStepCounter = lazyCounter("publisher_materialization_incremental_step_total", 'Refreshes of a source declared refresh="incremental". Labels: step ' + "('delta'|'seed'|'skip'), and for seed/skip a bounded reason code " + "(IncrementalStepReasonCode). A 'seed' is a full rebuild the delta path " + "declined, so a rising seed rate means the feature is not engaging — and " + "the reason label says why without a log dive.");
41549
+ buildPlanComputeDuration = lazyHistogram("publisher_materialization_build_plan_compute_duration_ms", "Wall-clock duration of compiling a package's build plan (Package.buildPlan).");
41550
+ buildPlanComputeFailedCounter = lazyCounter("publisher_materialization_build_plan_compute_failed_total", "Package loads whose build plan failed to compute. The ROOT-CAUSE signal for " + "served_copy_bind{reason='build_plan_unavailable'}, which fires only " + "per declined entry per load -- a package that loads once and is never " + "reloaded ticks that counter once and then sits with its database tier " + "off and a flat total, indistinguishable from healthy.");
41551
+ autoLoadCounter = lazyCounter("publisher_materialization_auto_load_total", "Auto-run manifest auto-load attempts. Label: outcome ('success'|'failure').");
41552
+ connectionDigestSkipCounter = lazyCounter("publisher_materialization_connection_digest_skipped_total", "Connection digests skipped during build-plan compile because the connection did not resolve.");
41553
+ servedCopyBindCounter = lazyCounter("publisher_served_copy_bind_total", "Serving's binds. Labels: scope ('manifest': one manifest bind, from REST, " + "auto-load or a rebind; 'source': one source deciding whether it " + "serves), outcome ('success'|'failure'|'timeout' for a manifest; " + "'bound'|'partial'|'declined' for a source: 'partial' is a source that " + "serves with a join read as written or left out), reason ('none' when " + "bound, else why: 'build_plan_unavailable' when the package's build " + "plan failed to compute, so every database source reverts to live; " + "'refused'; 'missing_table'; or the served copy's reason, as its " + "package warning, 'inline_join_kept' and 'cross_connection_join' being " + "the partial ones). Units differ by who counts: 'bound' and the bind's " + "declines count once per stored table per bind; the served copy counts " + "once per source per model per snapshot it compiles, 'declined' beating " + "'partial'. So a source two models read is counted by each, and the " + "outcomes do not sum to a number of sources. An extension table that " + "falls back to its own blocks ('compile_failed', 'reroot_not_compiled') " + "may still serve, and is counted 'declined'.");
41554
+ manifestBindDegradedCounter = lazyCounter("publisher_materialization_manifest_bind_degraded_total", "Manifest entries bound with an UNQUOTED table path because their connection " + "could not be resolved (serve-side bind) or is absent from the build " + "(build-side seed). A misconfiguration that breaks the source on a " + "case-folding engine (Snowflake); alertable.");
41555
+ duplicateTargetSkipCounter = lazyCounter("publisher_materialization_duplicate_target_skipped_total", "Sources skipped because the physical table they name was already built in " + "this run. Ordinary for a package that extends a persisted source; a " + "rising count against a package with no extension means the plan is " + "enumerating one table under more names than expected.");
41556
+ sharedAddressInstructionCounter = lazyCounter("publisher_materialization_shared_address_instructions_total", "Content addresses that arrived with more than one instruction naming a " + "DIFFERENT physical table. The host minted a table per source where " + "several sources share one artifact. With a sourceID on each instruction " + "every table is built and only one is recorded, so the rest are orphaned; " + "without one the last instruction wins and the earlier names are never " + "built. Wasteful, not wrong — the table's CONTENT is the same either way.");
41557
+ tableCollisionCounter = lazyCounter("publisher_materialization_table_collision_total", "Two definitions with DIFFERENT content addresses materializing into ONE " + "physical table. Each build overwrites the other's rows while both " + "addresses resolve to the table at serve time, so a query is answered " + "from another source's data. A wrong answer, not wasted work — page on " + "this one. Counted, then refused before any write, unless " + "PERSIST_COLLISION_ENFORCE=false opts out, in which case the build " + "continues.");
41558
+ dropTablesCounter = lazyCounter("publisher_materialization_drop_tables_total", "Physical tables dropped. Labels: outcome ('success'|'failure'), tier " + "('database'|'storage'), occasion ('delete' when a caller deleted a " + "storage destination's table, since a run's delete is record-only; " + "'reclaim' when Publisher dropped it on its own: " + "a failed run's tables, a table a readable name replaced, an archived " + "or deleted version's tables; 'caller' when a caller dropped a " + "package's materialized database table through " + "DELETE .../materializedTables/{tableName}).");
41559
+ scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
41560
+ queryRouteCounter = lazyCounter("publisher_query_route_total", "The router's decision on each leg it considered for a query, counted once " + "the query is answered. Labels: leg ('view'|'query'|'rollup'|'materialized'|'live'; " + "'query' is a persisted named query), " + "outcome ('used'|'skipped'|'fallback': a chosen leg whose run failed and " + "was answered live), reason ('NONE' when used, else the path report's " + "SkipReason; 'READ_FAILED' with 'fallback'). A leg that does not apply to " + "the query is not counted; 'live' is counted 'used' when it answered a " + "query the router counted a leg for.");
41561
+ queryRouteDuration = lazyHistogram("publisher_query_route_duration_ms", "Wall-clock time the router spent choosing how to answer a query, for a " + "query with at least one serving leg that applied: the row-level veto " + "and each leg's compile, up to the leg chosen. Not the query's run. " + "Label: leg ('view'|'query'|'rollup'|'materialized'|'live'), the one that " + "answered.");
41562
+ keyCheckCounter = lazyCounter("publisher_materialization_key_check_total", "Key checks a run made over the rows it read or wrote. Labels: kind " + "('inline_join'|'rollup'|'parent'|'pair_leaf'|'stored'), outcome " + "('unique'|'not_unique'|'not_run'|'reused'). An inline_join that is " + "not_unique fails its build; every other not_unique or not_run leaves " + "the key unknown or repeated, so queries that need it unique are " + "answered live.");
41563
+ storageTableRetainedCounter = lazyCounter("publisher_storage_tables_retained_total", "Tables a FAILED run left in a storage= destination and deliberately did not " + "reclaim, because the source is refreshed incrementally and the name may be " + "the one it serves from. Not all of these are orphans — " + "a rebuild at a fresh generational name is, a seed on the live serving name " + "is not, and the manifest entry cannot separate them — so read this as an " + "upper bound on what is accumulating rather than a leak count. It is the " + "only accounting there is until reclaiming a destination exists, which is " + "why it is a counter and not just a log line: the question is a rate, not " + "whether it ever happened. Unlabelled: the destination is on the warn " + "log that accompanies each count.");
41564
+ attributionSkippedCounter = lazyCounter("publisher_storage_build_attribution_skipped_total", "storage= builds whose warehouse read went out UNATTRIBUTED while tagging was " + "on. Label: reason ('job_listing_unavailable'|'tag_failed'|" + "'read_row_not_found'|'read_row_ambiguous'|'cost_query_failed'). " + "The read still ran and the " + "build still succeeded — what was lost is the label in the customer's own " + "query history, and the cost on this side. Without this an operator who " + "turns tagging on and sees nothing has a single log line to go on.");
41565
+ eligibilityRefusedCounter = lazyCounter("publisher_materialization_eligibility_refused_total", "Valid materialization declarations that are not built (`#@ persist`, " + "`#(materialize)`, a persisted view or query, a rollup), once per " + "declaration per plan derivation, and the refusals only a run finds. " + "Label: reason, the build plan refusal's `RefusedSource.reason` " + "(api-doc.yaml lists the values and which are retained and no " + "longer produced).");
41566
+ serveShapeTypeFallbackCounter = lazyCounter("publisher_storage_serve_shape_type_fallback_total", "Captured DuckDB column types mapped to json in a stored table's declared " + "type (type fidelity loss). " + "Label: kind ('array'|'unrecognized').");
41567
+ storedColumnTypeMismatchCounter = lazyCounter("publisher_storage_column_type_mismatch_total", "Stored columns whose DuckDB type does not serve as the type Malloy " + "declares for them. Labels: stage ('build' = " + "found after a storage build; 'serve' = found when a model's bindings " + "are set, then cast on read or left out of the served copy so queries " + "reading it are answered live), declared (the Malloy type).");
41568
+ chainedStorageBuildCounter = lazyCounter("publisher_storage_chained_build_total", "Chained storage= source builds (a source reading a storage-materialized " + "upstream). Label: outcome ('parent_reuse'|'inline_fallback'|" + "'strict_shape_fallback'|'strict_refused'|'infra_failure'). The " + "parent_reuse share is the headline signal for how far the " + "stack-on-the-parent path gets us vs recompute-from-raw.");
41569
+ staleUpstreamEntryCounter = lazyCounter("publisher_materialization_stale_upstream_entry_total", "Builds that could not use an upstream's manifest entry because it is at a " + "different tier than the upstream is declared on now (a source moved to " + "or from storage= keeps its content address). The build " + "recomputes that upstream from raw instead, which reads the warehouse. " + "Label: tier ('database'|'storage'), the tier of the build that " + "recomputed.");
41570
+ });
41571
+
40823
41572
  // src/service/materialization/plan/incremental_declaration.ts
40824
41573
  function safeTag(source) {
40825
41574
  try {
@@ -41179,6 +41928,9 @@ async function compileInMemory(files, entry, connections, options = {}) {
41179
41928
  const model = await runtime.loadModel(new URL(entry), options.importBaseURL ? options : undefined).getModel();
41180
41929
  return { runtime, model };
41181
41930
  }
41931
+ function companionFailure(kind, error) {
41932
+ return { kind, error };
41933
+ }
41182
41934
  function companionOmissions(kind, planned) {
41183
41935
  const reason = COMPANION_FAILED[kind];
41184
41936
  return "sourceIDs" in planned ? omittedByID(planned.sourceIDs, reason) : omittedFromFile(planned.file, planned.names, reason);
@@ -41855,7 +42607,7 @@ async function tryCompileMaterializeCompanion(args) {
41855
42607
  const foreign = await crossFileParents(planned.plans, args, modelFile).catch((error) => {
41856
42608
  logger.warn("A model's extension tables could not be chained on parents in other files; they build over the raw chain", {
41857
42609
  modelPath: args.modelPath,
41858
- error: error instanceof Error ? error.message : String(error)
42610
+ code: errorCodeOf(error)
41859
42611
  });
41860
42612
  return { plans: planned.plans, parents: new Map };
41861
42613
  });
@@ -41880,12 +42632,9 @@ async function tryCompileMaterializeCompanion(args) {
41880
42632
  }
41881
42633
  return round.generated ? { generated: withStoredColumns(round.generated), refused } : { refused };
41882
42634
  } catch (error) {
41883
- logger.error("Failed to plan or compile the generated #(materialize) companion", {
41884
- modelPath: args.modelPath,
41885
- error: error instanceof Error ? error.message : String(error)
41886
- });
41887
42635
  return {
41888
42636
  refused,
42637
+ failure: companionFailure("materialize", error),
41889
42638
  omitted: companionOmissions("materialize", plannedIDs ? {
41890
42639
  sourceIDs: plannedIDs.filter((id) => !refused.some((r) => r.sourceID === id))
41891
42640
  } : { file: pathToFileURL8(modelFile).href, names: undefined })
@@ -41932,11 +42681,10 @@ async function unchainStoredChainsNotCompiling(round, compile, args, foreign = N
41932
42681
  const unstored = round.generated ? await storedChainsNotCompiling(round.generated, foreign.parents) : new Map;
41933
42682
  if (unstored.size === 0)
41934
42683
  return round;
41935
- for (const [sourceID, error] of unstored) {
42684
+ for (const sourceID of unstored.keys()) {
41936
42685
  logger.warn("A storage= extension table does not compile over its parent's stored table alone; it builds over the raw chain", {
41937
42686
  modelPath: args.modelPath,
41938
- sourceName: planOf(round.plans, sourceID)?.sourceName,
41939
- error
42687
+ sourceName: planOf(round.plans, sourceID)?.sourceName
41940
42688
  });
41941
42689
  }
41942
42690
  return compile(round.plans.map((p) => unstored.has(p.sourceID) ? withoutParent(p) : p));
@@ -42544,11 +43292,11 @@ function nextRound(error, plans, copies, ctx) {
42544
43292
  } : p);
42545
43293
  }
42546
43294
  if (plan?.buildsOver) {
42547
- logger.warn("An extension table of a #(materialize) model did not compile over its parent's build source; it builds over the raw chain", { modelPath, sourceName: plan.sourceName, error: error.message });
43295
+ logger.warn("An extension table of a #(materialize) model did not compile over its parent's build source; it builds over the raw chain", { modelPath, sourceName: plan.sourceName, code: errorCodeOf(error) });
42548
43296
  return plans.map((p) => p === plan ? withoutParent(p) : p);
42549
43297
  }
42550
43298
  if (plan) {
42551
- logger.error("A #(materialize) source's generated build did not compile; it is not built, and the model's other sources are", { modelPath, sourceName: plan.sourceName, error: error.message });
43299
+ logger.error("A #(materialize) source's generated build did not compile; it is not built, and the model's other sources are", { modelPath, sourceName: plan.sourceName, code: errorCodeOf(error) });
42552
43300
  ctx.refuse({
42553
43301
  sourceName: plan.sourceName,
42554
43302
  sourceID: plan.sourceID,
@@ -42563,7 +43311,7 @@ function nextRound(error, plans, copies, ctx) {
42563
43311
  return plans.filter((p) => p !== plan);
42564
43312
  }
42565
43313
  if (plans.some((p) => p.buildsOver)) {
42566
- logger.warn("Extension tables of a #(materialize) model did not compile over their parents' build sources; they build over the raw chain", { modelPath, error: error.message });
43314
+ logger.warn("Extension tables of a #(materialize) model did not compile over their parents' build sources; they build over the raw chain", { modelPath, code: errorCodeOf(error) });
42567
43315
  return plans.map(withoutParent);
42568
43316
  }
42569
43317
  throw error.error;
@@ -42589,9 +43337,10 @@ async function crossFileParents(plans, args, modelFile) {
42589
43337
  const url = pathToFileURL8(file);
42590
43338
  const { model, materializer } = await files.compile(url);
42591
43339
  const def = modelDefOf(model);
42592
- const { generated } = await tryCompileMaterializeCompanion({
43340
+ const modelPath = relative.split(path13.sep).join("/");
43341
+ const { generated, failure } = await tryCompileMaterializeCompanion({
42593
43342
  packagePath: args.packagePath,
42594
- modelPath: relative.split(path13.sep).join("/"),
43343
+ modelPath,
42595
43344
  contents: def.contents ?? {},
42596
43345
  givens: def.givens ?? {},
42597
43346
  getRuntime: args.getRuntime,
@@ -42599,6 +43348,8 @@ async function crossFileParents(plans, args, modelFile) {
42599
43348
  crossFileStack: stack,
42600
43349
  crossFileCompanions: companions
42601
43350
  });
43351
+ if (failure)
43352
+ logCompanionFailure(failure, modelPath);
42602
43353
  return {
42603
43354
  ...generated ? { generated } : {},
42604
43355
  text: await files.read(url),
@@ -42609,7 +43360,7 @@ async function crossFileParents(plans, args, modelFile) {
42609
43360
  logger.warn("An extension table's parent in another file could not be planned here; it builds over the raw chain", {
42610
43361
  modelPath: args.modelPath,
42611
43362
  parentFile: path13.relative(args.packagePath, file),
42612
- error: error instanceof Error ? error.message : String(error)
43363
+ code: errorCodeOf(error)
42613
43364
  });
42614
43365
  return;
42615
43366
  });
@@ -42853,8 +43604,15 @@ async function withCrossFileColumnsKept(round, compile, args, foreign) {
42853
43604
  const ids = new Set(differ.map((p) => p.sourceID));
42854
43605
  return compile(round.plans.map((p) => ids.has(p.sourceID) ? withoutParent(p) : p));
42855
43606
  }
42856
- var STORED_TYPES, CompanionCompileError, MAX_OMISSION_ROUNDS = 4, NO_CROSS_FILE_PARENTS;
43607
+ function logCompanionFailure(failure, modelPath) {
43608
+ logger.error(COMPANION_FAILURE_TEXT[failure.kind], {
43609
+ modelPath,
43610
+ code: errorCodeOf(failure.error)
43611
+ });
43612
+ }
43613
+ var STORED_TYPES, CompanionCompileError, MAX_OMISSION_ROUNDS = 4, NO_CROSS_FILE_PARENTS, COMPANION_FAILURE_TEXT;
42857
43614
  var init_materialize_compile = __esm(() => {
43615
+ init_error_code();
42858
43616
  init_malloy_text();
42859
43617
  init_logger();
42860
43618
  init_dialect();
@@ -42895,6 +43653,13 @@ var init_materialize_compile = __esm(() => {
42895
43653
  plans: [],
42896
43654
  parents: new Map
42897
43655
  };
43656
+ COMPANION_FAILURE_TEXT = {
43657
+ materialize: "Failed to plan or compile the generated #(materialize) companion",
43658
+ persisted_view: "Failed to plan or compile the generated persisted-view companion",
43659
+ rollup: "Failed to plan or compile the generated #(rollup) companion",
43660
+ rollup_blanking: "A #(rollup) companion was not built: a `#@` line of the author's files could not be left out of it",
43661
+ v1_build: "The v1 build copy of a model could not be read or did not compile; its #@ persist sources are left out of the build plan"
43662
+ };
42898
43663
  });
42899
43664
 
42900
43665
  // src/service/materialization/plan/persisted_view_compile.ts
@@ -42948,12 +43713,7 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42948
43713
  reason: "the view has no stage to store",
42949
43714
  refusal: "no_stored_columns"
42950
43715
  };
42951
- if (pipelineReadsCurrentTime(def, stages)) {
42952
- return {
42953
- reason: "its result reads the current time, so it differs per read",
42954
- refusal: "current_time"
42955
- };
42956
- }
43716
+ const readsNow = pipelineReadsCurrentTime(def, stages);
42957
43717
  const last = stages[stages.length - 1];
42958
43718
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
42959
43719
  return {
@@ -42964,6 +43724,12 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42964
43724
  const gates = collectEntryPointGates(node.def, modelDef);
42965
43725
  if (gates.length === 0)
42966
43726
  return;
43727
+ if (readsNow) {
43728
+ return {
43729
+ reason: "its result reads the current time and its source carries a " + "row-level gate, whose decision a result stored as of its build " + "would freeze",
43730
+ refusal: "current_time"
43731
+ };
43732
+ }
42967
43733
  const gateRefusal = gateRefusalReason(gates.map((g) => g.route));
42968
43734
  if (gates.some((g) => !g.struct)) {
42969
43735
  return {
@@ -42971,6 +43737,13 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42971
43737
  refusal: gateRefusal
42972
43738
  };
42973
43739
  }
43740
+ const throughDerivation = gates.filter((g) => g.baseHops > 0 && canonicalAuthorizeRoute(g.route) !== AUTHORIZE_ROUTE);
43741
+ if (throughDerivation.length > 0) {
43742
+ return {
43743
+ reason: "its source inherits a row filter through `->`, which filters the derivation's base, not the rows a stored result holds",
43744
+ refusal: gateRefusalReason(throughDerivation.map((g) => g.route))
43745
+ };
43746
+ }
42974
43747
  const gatedWhy = "its source carries a row-level gate (#(access_filter) or #(authorize))";
42975
43748
  if (stages.length !== 1 || last.type !== "reduce") {
42976
43749
  return {
@@ -43086,12 +43859,6 @@ async function persistedQueryRefusalReason(plan, modelDef, materializer) {
43086
43859
  reason: "its source cannot be read",
43087
43860
  refusal: "run_target_unsupported"
43088
43861
  };
43089
- if (pipelineReadsCurrentTime(def, stages)) {
43090
- return {
43091
- reason: "its result reads the current time, so it differs per read",
43092
- refusal: "current_time"
43093
- };
43094
- }
43095
43862
  const last = stages[stages.length - 1];
43096
43863
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
43097
43864
  return {
@@ -43186,13 +43953,10 @@ async function tryCompilePersistedViewCompanion(args) {
43186
43953
  refusedQueries
43187
43954
  };
43188
43955
  } catch (error) {
43189
- logger.error("Failed to plan or compile the generated persisted-view companion", {
43190
- modelPath: args.modelPath,
43191
- error: error instanceof Error ? error.message : String(error)
43192
- });
43193
43956
  return {
43194
43957
  refused,
43195
43958
  refusedQueries,
43959
+ failure: companionFailure("persisted_view", error),
43196
43960
  omitted: companionOmissions("persisted_view", {
43197
43961
  file: companionHref,
43198
43962
  names: plannedNames
@@ -43202,10 +43966,10 @@ async function tryCompilePersistedViewCompanion(args) {
43202
43966
  }
43203
43967
  var GATE_NOTE_ROUTES, GATED_QUERY_REASON = "it reaches a row-level gate (#(access_filter) or #(authorize)), and a persisted query is never built over a gated source; it is answered live under the gate";
43204
43968
  var init_persisted_view_compile = __esm(() => {
43205
- init_logger();
43206
43969
  init_annotations();
43207
43970
  init_annotation_reader();
43208
43971
  init_authorize();
43972
+ init_authorize_routes();
43209
43973
  init_gate_classification();
43210
43974
  init_prepared_query();
43211
43975
  init_malloy_text();
@@ -43401,9 +44165,12 @@ async function tryCompileRollupCompanion(args) {
43401
44165
  if (!text)
43402
44166
  return { refused };
43403
44167
  if (!overlay) {
43404
- logger.error("A #(rollup) companion was not built: a `#@` line of the author's files could not be left out of it", { modelPath: args.modelPath });
43405
44168
  return {
43406
44169
  refused,
44170
+ failure: {
44171
+ kind: "rollup_blanking",
44172
+ error: "a `#@` line of the author's files could not be set aside"
44173
+ },
43407
44174
  omitted: companionOmissions("rollup_blanking", {
43408
44175
  file: companionHref,
43409
44176
  names: plannedNames
@@ -43442,12 +44209,9 @@ async function tryCompileRollupCompanion(args) {
43442
44209
  refused
43443
44210
  };
43444
44211
  } catch (error) {
43445
- logger.error("Failed to plan or compile the generated #(rollup) companion", {
43446
- modelPath: args.modelPath,
43447
- error: error instanceof Error ? error.message : String(error)
43448
- });
43449
44212
  return {
43450
44213
  refused,
44214
+ failure: companionFailure("rollup", error),
43451
44215
  omitted: companionOmissions("rollup", {
43452
44216
  file: companionHref,
43453
44217
  names: plannedNames
@@ -43486,7 +44250,7 @@ async function compileOverStoredBases(args) {
43486
44250
  logger.warn("A rollup builds from the warehouse: its #(materialize) base's copy over the stored table did not compile", {
43487
44251
  modelPath: args.modelPath,
43488
44252
  base: name,
43489
- error: error instanceof Error ? error.message : String(error)
44253
+ code: errorCodeOf(error)
43490
44254
  });
43491
44255
  stored.delete(name);
43492
44256
  }
@@ -43500,7 +44264,7 @@ async function compileOverStoredBases(args) {
43500
44264
  }
43501
44265
  logger.warn("The rollups over #(materialize) bases build from the warehouse: their companion over the bases' stored tables did not compile", {
43502
44266
  modelPath: args.modelPath,
43503
- error: error instanceof Error ? error.message : String(error)
44267
+ code: errorCodeOf(error)
43504
44268
  });
43505
44269
  out.clear();
43506
44270
  try {
@@ -43547,7 +44311,7 @@ async function compileOverStoredBases(args) {
43547
44311
  function warnWarehouse(modelPath, error) {
43548
44312
  logger.warn("The rollups of a model build from the warehouse: their companion over the bases' stored tables did not compile", {
43549
44313
  modelPath,
43550
- error: error instanceof Error ? error.message : String(error)
44314
+ code: errorCodeOf(error)
43551
44315
  });
43552
44316
  }
43553
44317
  function parentKeyCheckCompiler(materializer) {
@@ -43569,7 +44333,7 @@ async function compileParentKeyChecks(plans, needs, joinedKeys = []) {
43569
44333
  logger.warn("A source's primary key check did not compile; queries it answers through a #(rollup) rollup read through a join are answered live", {
43570
44334
  source: name,
43571
44335
  keyColumn,
43572
- error: error instanceof Error ? error.message : String(error)
44336
+ code: errorCodeOf(error)
43573
44337
  });
43574
44338
  return;
43575
44339
  });
@@ -43630,12 +44394,13 @@ async function compileRollupKeyChecks(plans, materializer, modelPath) {
43630
44394
  logger.warn("A #(rollup) rollup's key check did not compile", {
43631
44395
  modelPath,
43632
44396
  rollup: plan.rollupSourceName,
43633
- error: error instanceof Error ? error.message : String(error)
44397
+ code: errorCodeOf(error)
43634
44398
  });
43635
44399
  }
43636
44400
  }
43637
44401
  }
43638
44402
  var init_rollup_compile = __esm(() => {
44403
+ init_error_code();
43639
44404
  init_config2();
43640
44405
  init_logger();
43641
44406
  init_prepared_query();
@@ -43692,16 +44457,104 @@ var init_v1_build_companion = __esm(() => {
43692
44457
  init_generated_files();
43693
44458
  });
43694
44459
 
43695
- // src/service/materialization/domain/compiled_build_plan.ts
43696
- function* sourcesInBuildOrder(build, tables) {
43697
- for (const sourceID of build.order) {
43698
- const source = tables[sourceID]?.source;
43699
- if (source)
43700
- yield source;
44460
+ // src/service/materialization/plan/access_closure.ts
44461
+ function collectAccessReads(contents, out) {
44462
+ if (contents === null || typeof contents !== "object")
44463
+ return;
44464
+ const entries = Object.entries(contents).filter((e) => e[1] !== null && typeof e[1] === "object");
44465
+ const keyOf = (name, def) => typeof def.sourceID === "string" ? def.sourceID : `${QUERY_KEY}${name}`;
44466
+ const keys = new Map(entries.map(([name, def]) => [name, keyOf(name, def)]));
44467
+ const byName = (name) => keys.get(name) ?? EVERY_SOURCE;
44468
+ const direct = new Map;
44469
+ const access = [];
44470
+ for (const [name, def] of entries) {
44471
+ const own = typeof def.sourceID === "string" ? def.sourceID : undefined;
44472
+ const deps = new Set;
44473
+ namesIn(def, deps, own, byName, new WeakSet, 0);
44474
+ direct.set(keyOf(name, def), deps);
44475
+ if (isAccessDefinition(def))
44476
+ access.push(deps);
44477
+ }
44478
+ for (const deps of access) {
44479
+ const queue = [...deps];
44480
+ while (queue.length > 0) {
44481
+ const id = queue.pop();
44482
+ if (out.has(id))
44483
+ continue;
44484
+ out.add(id);
44485
+ for (const next of direct.get(id) ?? []) {
44486
+ if (!out.has(next))
44487
+ queue.push(next);
44488
+ }
44489
+ }
43701
44490
  }
43702
44491
  }
43703
- function materializePlansOf(tables) {
43704
- return Object.fromEntries(Object.entries(tables).flatMap(([sourceID, table]) => table.materialize ? [[sourceID, table.materialize]] : []));
44492
+ function isAccessDefinition(def) {
44493
+ if (irCarriesAGate(def))
44494
+ return true;
44495
+ try {
44496
+ return readsAGiven(def);
44497
+ } catch {
44498
+ return true;
44499
+ }
44500
+ }
44501
+ function namesIn(node, out, self2, byName, seen, depth) {
44502
+ if (node === null || typeof node !== "object")
44503
+ return;
44504
+ if (depth > MAX_WALK_DEPTH3) {
44505
+ out.add(EVERY_SOURCE);
44506
+ return;
44507
+ }
44508
+ if (seen.has(node))
44509
+ return;
44510
+ seen.add(node);
44511
+ if (Array.isArray(node)) {
44512
+ for (const item of node) {
44513
+ namesIn(item, out, self2, byName, seen, depth + 1);
44514
+ }
44515
+ return;
44516
+ }
44517
+ for (const [key, value] of Object.entries(node)) {
44518
+ if (SKIPPED_KEYS.has(key))
44519
+ continue;
44520
+ if (DEPENDENCY_KEYS.has(key) && typeof value === "string") {
44521
+ if (!(depth === 0 && key === "sourceID" && value === self2)) {
44522
+ out.add(value);
44523
+ }
44524
+ continue;
44525
+ }
44526
+ if (NAME_KEYS.has(key) && typeof value === "string") {
44527
+ out.add(byName(value));
44528
+ continue;
44529
+ }
44530
+ namesIn(value, out, self2, byName, seen, depth + 1);
44531
+ }
44532
+ }
44533
+ var MAX_WALK_DEPTH3 = 200, DEPENDENCY_KEYS, NAME_KEYS, QUERY_KEY = "query:", SKIPPED_KEYS;
44534
+ var init_access_closure = __esm(() => {
44535
+ init_probe_compiler();
44536
+ init_materialization_eligibility();
44537
+ DEPENDENCY_KEYS = new Set([
44538
+ "sourceID",
44539
+ "extends",
44540
+ "referenceID"
44541
+ ]);
44542
+ NAME_KEYS = new Set(["structRef"]);
44543
+ SKIPPED_KEYS = new Set([
44544
+ "at",
44545
+ "location",
44546
+ "annotations",
44547
+ "blockNotes",
44548
+ "notes"
44549
+ ]);
44550
+ });
44551
+
44552
+ // src/service/materialization/domain/package_plan.ts
44553
+ function countRefusal(counts, reason) {
44554
+ counts[reason] = (counts[reason] ?? 0) + 1;
44555
+ }
44556
+ function noModelGateLines() {
44557
+ return { preaggregate: [], nearMiss: [], nameProblems: [] };
43705
44558
  }
43706
44559
 
43707
44560
  // src/service/materialization/plan/build_plan.ts
@@ -43741,7 +44594,7 @@ function storedColumnNames(persistSource) {
43741
44594
  let names;
43742
44595
  try {
43743
44596
  const columnOf = storedColumnOf(persistSource);
43744
- names = exploreOf(persistSource).intrinsicFields.filter((f) => f.isAtomicField()).map((f) => columnOf(f.name)).filter((n) => typeof n === "string" && n.length > 0);
44597
+ names = exploreOf(persistSource).intrinsicFields.filter((f) => f.isAtomicField() || isNestedColumn(f)).map((f) => columnOf(f.name)).filter((n) => typeof n === "string" && n.length > 0);
43745
44598
  } catch (err) {
43746
44599
  throw new Error(`the compiled source's field list could not be read (${errMessage(err)})`);
43747
44600
  }
@@ -43750,6 +44603,10 @@ function storedColumnNames(persistSource) {
43750
44603
  }
43751
44604
  return names;
43752
44605
  }
44606
+ function isNestedColumn(field) {
44607
+ const f = field;
44608
+ return f.isExploreField?.() === true;
44609
+ }
43753
44610
  function projectToStoredColumns(persistSource, buildSQL) {
43754
44611
  let cols;
43755
44612
  try {
@@ -43775,7 +44632,7 @@ async function resolvePackageConnections(pkg, names) {
43775
44632
  map.set(name, await pkg.getMalloyConnection(name));
43776
44633
  } catch (err) {
43777
44634
  logger.warn(`Failed to resolve connection ${name}`, {
43778
- error: errMessage(err)
44635
+ code: errorCodeOf(err)
43779
44636
  });
43780
44637
  }
43781
44638
  }
@@ -43862,7 +44719,7 @@ async function classifyPersistSourceGate(persistSource, modelDef, materializer,
43862
44719
  } catch (err) {
43863
44720
  logger.warn("Failed to classify persist source gate; refusing", {
43864
44721
  sourceID: persistSource.sourceID,
43865
- error: errMessage(err)
44722
+ code: errorCodeOf(err)
43866
44723
  });
43867
44724
  return { classification: "rejected", attributed: false };
43868
44725
  }
@@ -43873,8 +44730,10 @@ function emptyBuildPlanParts() {
43873
44730
  tables: {},
43874
44731
  droppedPersistSources: [],
43875
44732
  annotationFindings: [],
43876
- modelGateLines: { preaggregate: [], nearMiss: [] },
43877
- omittedSources: []
44733
+ modelGateLines: noModelGateLines(),
44734
+ persistedViews: {},
44735
+ omittedSources: [],
44736
+ accessReads: []
43878
44737
  };
43879
44738
  }
43880
44739
  function mergeBuildPlanParts(into, from) {
@@ -43887,6 +44746,11 @@ function mergeBuildPlanParts(into, from) {
43887
44746
  }
43888
44747
  into.modelGateLines.preaggregate.push(...from.modelGateLines.preaggregate);
43889
44748
  into.modelGateLines.nearMiss.push(...from.modelGateLines.nearMiss);
44749
+ into.modelGateLines.nameProblems.push(...from.modelGateLines.nameProblems);
44750
+ Object.assign(into.persistedViews, from.persistedViews);
44751
+ into.accessReads = [
44752
+ ...new Set([...into.accessReads, ...from.accessReads])
44753
+ ].sort();
43890
44754
  }
43891
44755
  function addAnnotationFinding(parts, finding) {
43892
44756
  const key = (f) => [f.code, f.model ?? "", f.subject ?? "", f.message].join("\x00");
@@ -43928,10 +44792,12 @@ function sourceIDFileURL(sourceID) {
43928
44792
  const url = splitSourceID(sourceID)?.url;
43929
44793
  return url?.startsWith("file:") ? url : undefined;
43930
44794
  }
43931
- function addCompanionOutcome(parts, findings, omitted) {
44795
+ function addCompanionOutcome(parts, findings, omitted, failed) {
43932
44796
  for (const finding of findings)
43933
44797
  addAnnotationFinding(parts, finding);
43934
44798
  parts.omittedSources.push(...omitted ?? []);
44799
+ if (failed?.failure)
44800
+ logCompanionFailure(failed.failure, failed.modelPath);
43935
44801
  }
43936
44802
  function withoutGivenReadingTargets(all, refuse) {
43937
44803
  for (const target of all.connections.flatMap((c) => c.targets)) {
@@ -43954,14 +44820,14 @@ function gateDepsFor(model, modelPath) {
43954
44820
  }
43955
44821
  async function collectGeneratedMaterialize(parts, args) {
43956
44822
  const authorDef = modelDefOf(args.malloyModel);
43957
- const { generated, refused, omitted } = await tryCompileMaterializeCompanion({
44823
+ const { generated, refused, omitted, failure } = await tryCompileMaterializeCompanion({
43958
44824
  ...args,
43959
44825
  contents: authorDef.contents ?? {},
43960
44826
  givens: authorDef.givens ?? {},
43961
44827
  sourceRegistry: authorDef.sourceRegistry,
43962
44828
  probe: args.materializer
43963
44829
  });
43964
- addCompanionOutcome(parts, refused.map((r) => materializeRefusalFinding(r, args.modelPath)), omitted);
44830
+ addCompanionOutcome(parts, refused.map((r) => materializeRefusalFinding(r, args.modelPath)), omitted, { failure, modelPath: args.modelPath });
43965
44831
  if (!generated)
43966
44832
  return;
43967
44833
  for (const [key, compile] of generated.checkCompilers) {
@@ -44017,8 +44883,8 @@ async function authorSourceGate(sourceID, authorDef, args) {
44017
44883
  return authorSource ? await classifyPersistSourceGate({ _sourceDef: authorSource, sourceID }, authorDef, args.materializer, args.deps, args.modelPath) : { classification: "rejected", attributed: false };
44018
44884
  }
44019
44885
  async function collectGeneratedRollups(parts, args) {
44020
- const { generated, refused, omitted } = await tryCompileRollupCompanion(args);
44021
- addCompanionOutcome(parts, refused.map((r) => rollupRefusalFinding(r, args.modelPath)), omitted);
44886
+ const { generated, refused, omitted, failure } = await tryCompileRollupCompanion(args);
44887
+ addCompanionOutcome(parts, refused.map((r) => rollupRefusalFinding(r, args.modelPath)), omitted, { failure, modelPath: args.modelPath });
44022
44888
  if (!generated)
44023
44889
  return;
44024
44890
  const planByName = new Map(generated.plans.map((p) => [p.rollupSourceName, p]));
@@ -44026,18 +44892,7 @@ async function collectGeneratedRollups(parts, args) {
44026
44892
  const plan = planByName.get(source.name);
44027
44893
  if (!plan)
44028
44894
  return;
44029
- addAnnotationFinding(parts, rollupRefusalFinding({
44030
- tier: "unservable",
44031
- code: ROLLUP_NOT_BUILT_CODE,
44032
- message: `#(rollup) rollup of source "${plan.baseSourceName}" at ` + `(${plan.grainDimensions.join(", ")}) is not built, so its measures ` + "are served live: its rows read a given, and a table holds one " + "value's rows.",
44033
- sourceName: plan.baseSourceName,
44034
- refused: {
44035
- sourceID: source.sourceID,
44036
- name: source.name,
44037
- tier: tierOf(plan.storage),
44038
- reason: "reads_given"
44039
- }
44040
- }, args.modelPath));
44895
+ addAnnotationFinding(parts, rollupRefusalFinding(rollupReadsGivenRefusal(plan, source), args.modelPath));
44041
44896
  });
44042
44897
  const kept = [];
44043
44898
  for (const source of plannedSources(targets)) {
@@ -44064,7 +44919,7 @@ async function collectGeneratedRollups(parts, args) {
44064
44919
  }
44065
44920
  async function collectGeneratedPersistedViews(parts, args) {
44066
44921
  const authorDef = modelDefOf(args.malloyModel);
44067
- const { generated, refused, refusedQueries, omitted } = await tryCompilePersistedViewCompanion({
44922
+ const { generated, refused, refusedQueries, omitted, failure } = await tryCompilePersistedViewCompanion({
44068
44923
  packagePath: args.packagePath,
44069
44924
  modelPath: args.modelPath,
44070
44925
  modelDef: authorDef,
@@ -44074,29 +44929,24 @@ async function collectGeneratedPersistedViews(parts, args) {
44074
44929
  addCompanionOutcome(parts, [
44075
44930
  ...refused.map((r) => persistedViewRefusalFinding(r, args.modelPath)),
44076
44931
  ...refusedQueries.map((r) => persistedQueryRefusalFinding(r, args.modelPath))
44077
- ], omitted);
44932
+ ], omitted, { failure, modelPath: args.modelPath });
44078
44933
  if (!generated)
44079
44934
  return;
44935
+ for (const plan of generated.plans) {
44936
+ parts.persistedViews[plan.buildSourceID] = {
44937
+ sourceName: plan.sourceName,
44938
+ viewName: plan.viewName
44939
+ };
44940
+ }
44080
44941
  const planByName = new Map(generated.plans.map((p) => [p.buildSourceName, p]));
44081
44942
  const queryByID = new Map(generated.queries.map((p) => [p.buildSourceID, p]));
44082
- const readsAGiven = "its result reads a given, so it differs per caller and a table holds one caller's result";
44083
44943
  const targets = withoutGivenReadingTargets(await generated.runtime.getBuildTargets(generated.model), (source) => {
44084
44944
  const plan = planByName.get(source.name);
44085
44945
  const query = queryByID.get(source.sourceID);
44086
44946
  if (plan) {
44087
- addAnnotationFinding(parts, persistedViewRefusalFinding({
44088
- ...plan,
44089
- reason: readsAGiven,
44090
- outcome: { refused: "reads_given" }
44091
- }, args.modelPath));
44947
+ addAnnotationFinding(parts, persistedViewRefusalFinding(persistedViewReadsGivenRefusal(plan), args.modelPath));
44092
44948
  } else if (query) {
44093
- addAnnotationFinding(parts, persistedQueryRefusalFinding({
44094
- queryName: query.queryName,
44095
- reason: readsAGiven,
44096
- refusal: "reads_given",
44097
- declaringURL: query.declaringURL,
44098
- ...query.storage !== undefined ? { storage: query.storage } : {}
44099
- }, args.modelPath));
44949
+ addAnnotationFinding(parts, persistedQueryRefusalFinding(persistedQueryReadsGivenRefusal(query), args.modelPath));
44100
44950
  }
44101
44951
  });
44102
44952
  const ctx = {
@@ -44189,7 +45039,13 @@ function inlineRunTarget(modelDef, name) {
44189
45039
  const ref = query?.type === "query" ? query.structRef : undefined;
44190
45040
  return ref && typeof ref === "object" && isSourceDef12(ref) ? ref : undefined;
44191
45041
  }
45042
+ function addAccessReads(parts, malloyModel) {
45043
+ const reads = new Set(parts.accessReads);
45044
+ collectAccessReads(modelDefOf(malloyModel)?.contents ?? {}, reads);
45045
+ parts.accessReads = [...reads].sort();
45046
+ }
44192
45047
  async function collectModelBuildPlan(parts, args) {
45048
+ addAccessReads(parts, args.malloyModel);
44193
45049
  await collectGeneratedTables(parts, args);
44194
45050
  const plannable = await v1PlanModel(parts, args);
44195
45051
  if (!plannable)
@@ -44223,6 +45079,12 @@ async function collectGeneratedTables(parts, args) {
44223
45079
  addAnnotationFinding(parts, finding);
44224
45080
  }
44225
45081
  parts.modelGateLines.nearMiss.push(...nearMissGateLines(modelPath, annotationNearMisses(authoredNotes(authorDef))));
45082
+ const text = await GeneratedFiles.over(getRuntime).readIfAny(pathToFileURL12(path17.join(packagePath, modelPath))).catch(() => {
45083
+ return;
45084
+ });
45085
+ if (text !== undefined) {
45086
+ parts.modelGateLines.nameProblems.push(...persistNameProblems(text, modelPath));
45087
+ }
44226
45088
  }
44227
45089
  collectPersistQueryFindings(parts, {
44228
45090
  modelPath,
@@ -44299,12 +45161,9 @@ async function v1PlanModel(parts, args) {
44299
45161
  packagePath,
44300
45162
  modelPath,
44301
45163
  getRuntime,
44302
- onCompileFailed: (error) => {
44303
- logger.error("The v1 build copy of a model could not be read or did not compile; its #@ persist sources are left out of the build plan", { modelPath, error: errMessage(error) });
44304
- parts.omittedSources.push(...companionOmissions("v1_build", {
44305
- sourceIDs: declaredPersistSourceIDs(malloyModel)
44306
- }));
44307
- }
45164
+ onCompileFailed: (error) => addCompanionOutcome(parts, [], companionOmissions("v1_build", {
45165
+ sourceIDs: declaredPersistSourceIDs(malloyModel)
45166
+ }), { failure: companionFailure("v1_build", error), modelPath })
44308
45167
  });
44309
45168
  if (!companion)
44310
45169
  return;
@@ -44315,14 +45174,14 @@ async function v1PlanModel(parts, args) {
44315
45174
  }
44316
45175
  function reportPersistLineFindings(parts, targets, planned, args) {
44317
45176
  const { modelPath, packagePath, malloyModel, planModel } = args;
44318
- const parseErrors = targets.tagParseLog.filter((msg) => {
44319
- logger.warn("Persist annotation issue", {
45177
+ for (const msg of targets.tagParseLog) {
45178
+ logger.debug("Persist annotation issue", {
44320
45179
  modelPath,
44321
- message: msg.message,
45180
+ code: msg.code,
44322
45181
  severity: msg.severity
44323
45182
  });
44324
- return msg.severity === "error";
44325
- });
45183
+ }
45184
+ const parseErrors = targets.tagParseLog.filter((msg) => msg.severity === "error");
44326
45185
  const companionURL = planModel !== malloyModel ? pathToFileURL12(path17.resolve(packagePath, modelPath)).href : undefined;
44327
45186
  const authorAt = (at) => at && companionURL && at.url === companionURL ? {
44328
45187
  ...at,
@@ -44375,7 +45234,14 @@ async function planV1PersistSources(parts, planned, args) {
44375
45234
  model: declaredIn
44376
45235
  });
44377
45236
  }
44378
- } catch {}
45237
+ } catch (err) {
45238
+ logger.warn("Failed to read a persist source's annotations; planned without their findings", {
45239
+ modelPath,
45240
+ sourceID,
45241
+ sourceName: source.name,
45242
+ code: errorCodeOf(err)
45243
+ });
45244
+ }
44379
45245
  classificationCtx ??= {
44380
45246
  modelDef: modelDefOf(malloyModel),
44381
45247
  deps: gateDepsFor(malloyModel, modelPath)
@@ -44407,18 +45273,23 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44407
45273
  const decided = verdicts.get(sourceID).wire;
44408
45274
  if ("failed" in decided)
44409
45275
  throw decided.failed;
44410
- if (decided.refused)
44411
- refusedSources[sourceID] = decided.refused;
45276
+ if (decided.refused) {
45277
+ const freshness = resolveFreshness(source, packageMaterialization, table.rollup?.freshness);
45278
+ refusedSources[sourceID] = {
45279
+ ...decided.refused,
45280
+ ...freshness ? { freshness } : {}
45281
+ };
45282
+ }
44412
45283
  if (!decided.inPlan)
44413
45284
  continue;
44414
- wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization);
45285
+ wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization, compiled.upstreamSchemas);
44415
45286
  } catch (err) {
44416
45287
  const reason = isUnkeyable(source) ? "unkeyable" : err instanceof EligibilityCheckFailed ? "eligibility_check_failed" : "projection_failed";
44417
45288
  logger.warn("Failed to project a persist source into the build plan", {
44418
45289
  sourceID,
44419
45290
  sourceName: source.name,
44420
45291
  reason,
44421
- error: errMessage(err)
45292
+ code: errorCodeOf(err)
44422
45293
  });
44423
45294
  omitted.push({ sourceID, reason });
44424
45295
  }
@@ -44431,7 +45302,7 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44431
45302
  ...finalizeOmissions(omitted, new Set(Object.keys(wireSources)))
44432
45303
  };
44433
45304
  }
44434
- function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterialization) {
45305
+ function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterialization, upstreamSchemaReadings) {
44435
45306
  const { source, rollup, modelPath } = table;
44436
45307
  return {
44437
45308
  name: source.name,
@@ -44450,11 +45321,21 @@ function wireSourceOf(table, annotationFields, sourceEntityId, packageMaterializ
44450
45321
  freshness: resolveFreshness(source, packageMaterialization, rollup?.freshness),
44451
45322
  queryMetadata: resolveQueryMetadata(source, packageMaterialization),
44452
45323
  columns: deriveColumns(source),
45324
+ ...readsOf(source),
45325
+ ...upstreamSchemasFieldOf(source, upstreamSchemaReadings),
44453
45326
  ...planDynamicFields(source),
44454
45327
  annotationFields,
44455
45328
  modelPath
44456
45329
  };
44457
45330
  }
45331
+ function upstreamSchemasFieldOf(source, readings) {
45332
+ const upstreamSchemas = upstreamSchemasOfSource(source, readings);
45333
+ return upstreamSchemas ? { upstreamSchemas } : {};
45334
+ }
45335
+ function readsOf(source) {
45336
+ const reads = sourceReads(source);
45337
+ return reads === undefined ? {} : { reads };
45338
+ }
44458
45339
  function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources, refusedSources) {
44459
45340
  const { tables } = compiled;
44460
45341
  const v1 = (id) => !tables[id]?.materialize;
@@ -44473,11 +45354,12 @@ function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources,
44473
45354
  modelPath: tables[sourceID]?.modelPath,
44474
45355
  tier: "database",
44475
45356
  reason: sibling.reason ?? "authorize",
45357
+ ...planned.freshness ? { freshness: planned.freshness } : {},
44476
45358
  message: `'${planned.name}' is not built: it shares its table with ` + `'${sibling.name}', which the eligibility gate refuses for a ` + `database build, and a database table is served to every ` + `source on it. ${sibling.message}`
44477
45359
  };
44478
45360
  }
44479
45361
  }
44480
- function projectRefusals(plan, findings) {
45362
+ function projectRefusals(plan, findings, counts = {}) {
44481
45363
  const kept = [];
44482
45364
  const refusedSources = {
44483
45365
  ...plan?.refusedSources ?? {}
@@ -44505,7 +45387,7 @@ function projectRefusals(plan, findings) {
44505
45387
  code: finding.code,
44506
45388
  ...finding.subject !== undefined ? { subject: finding.subject } : {}
44507
45389
  };
44508
- recordEligibilityRefused(key.reason);
45390
+ countRefusal(counts, key.reason);
44509
45391
  }
44510
45392
  if (!moved)
44511
45393
  return { plan, annotationFindings: kept, refusalNotices };
@@ -44520,7 +45402,9 @@ function finishBuildPlan(parts, ctx) {
44520
45402
  ...ctx.versionScoped ? { versionScoped: true } : {},
44521
45403
  ...parts,
44522
45404
  connectionDigests: ctx.connectionDigests,
45405
+ ...ctx.upstreamSchemas ? { upstreamSchemas: ctx.upstreamSchemas } : {},
44523
45406
  connectionTypes: resolveConnectionTypes(ctx.connections),
45407
+ managedConnections: resolveManagedConnections(ctx.connections),
44524
45408
  connections: ctx.connections,
44525
45409
  ...ctx.keyCheckCompilers && ctx.keyCheckCompilers.size > 0 ? { keyCheckCompilers: ctx.keyCheckCompilers } : {}
44526
45410
  };
@@ -44530,37 +45414,123 @@ function finishBuildPlan(parts, ctx) {
44530
45414
  tableFolds,
44531
45415
  addresses: planAddresses({ ...plan, tableFolds })
44532
45416
  }));
44533
- return ctx.keepIncrementalUnbuildable ? refused : refuseIncrementalUnbuildable(refused);
45417
+ const known = refuseUpstreamUnread(refused);
45418
+ return ctx.keepIncrementalUnbuildable ? known : refuseIncrementalUnbuildable(known);
45419
+ }
45420
+ async function finishPackagePlan(parts, ctx) {
45421
+ const { getMalloyConnection, readUpstreamSchemas, ...finish } = ctx;
45422
+ const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
45423
+ const digestSkipped = [];
45424
+ const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
45425
+ const upstreamSchemas = readUpstreamSchemas ? await readUpstreamSchemas(planUpstreamTables(parts.tables)) : undefined;
45426
+ return {
45427
+ compiled: finishBuildPlan(parts, {
45428
+ ...finish,
45429
+ connectionDigests,
45430
+ ...upstreamSchemas ? { upstreamSchemas } : {},
45431
+ connections
45432
+ }),
45433
+ digestSkipped
45434
+ };
45435
+ }
45436
+ function planUpstreamTables(tables) {
45437
+ const out = new Map;
45438
+ for (const { source } of Object.values(tables)) {
45439
+ for (const read of upstreamTablesOf(source) ?? []) {
45440
+ out.set(upstreamTableKey(read), read);
45441
+ }
45442
+ }
45443
+ return [...out.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, t]) => t);
44534
45444
  }
44535
- function deriveBuildPlanOutcome(compiled, materializationConfig) {
45445
+ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
44536
45446
  const incrementalDeclarations = collectIncrementalDeclarations(compiled.tables);
44537
45447
  const verdicts = planVerdicts(compiled);
44538
45448
  for (const { counted } of verdicts.values()) {
44539
45449
  if (counted)
44540
- recordEligibilityRefused(counted);
45450
+ countRefusal(counts, counted);
44541
45451
  }
44542
45452
  const derived = compiled.builds.length === 0 && !compiled.omittedSources.length ? null : deriveBuildPlan(compiled, materializationConfig, verdicts);
44543
- const projected = projectRefusals(derived, compiled.annotationFindings.map((f) => relaxedCollision(f, getPersistCollisionEnforce())));
45453
+ const projected = projectRefusals(derived, compiled.annotationFindings.map((f) => relaxedCollision(f, getPersistCollisionEnforce())), counts);
44544
45454
  const { annotationFindings, refusalNotices } = projected;
44545
- const plan = withRefusalOrigins(projected.plan, compiled.tables, refusalNotices);
45455
+ const refusedPlan = withRefusalOrigins(projected.plan, compiled.tables, refusalNotices);
45456
+ const asOfBuild = asOfBuildOf(refusedPlan, compiled.tables);
45457
+ const plan = withAsOfBuild(refusedPlan, asOfBuild);
44546
45458
  return {
44547
45459
  plan,
44548
- droppedPersistSources: compiled.droppedPersistSources,
45460
+ tables: tablePlanDataOf(compiled.tables),
45461
+ builds: compiled.builds,
45462
+ connectionDigests: compiled.connectionDigests,
45463
+ connectionTypes: compiled.connectionTypes ?? {},
45464
+ managedConnections: compiled.managedConnections ?? [],
45465
+ buildConnectionNames: [
45466
+ ...new Set(compiled.builds.map((b) => b.connectionName))
45467
+ ].sort(),
45468
+ versionScoped: compiled.versionScoped === true,
45469
+ tableFolds: { ...compiled.tableFolds },
45470
+ upstreamSchemas: { ...compiled.upstreamSchemas },
45471
+ addresses: { ...compiled.addresses },
45472
+ compilerKeys: compilerKeysOf(compiled),
44549
45473
  annotationFindings,
44550
- refusalNotices,
45474
+ droppedPersistSources: compiled.droppedPersistSources,
44551
45475
  modelGateLines: compiled.modelGateLines,
45476
+ persistedViews: compiled.persistedViews ?? {},
45477
+ refusalNotices,
45478
+ refusedRollups: refusedRollupsOf(plan, compiled.tables),
44552
45479
  sourceEligibility: collectSourceEligibility(compiled, verdicts),
44553
45480
  databaseSourceEligibility: collectDatabaseSourceEligibility(compiled, verdicts),
45481
+ rollupsKeepingGates: Object.entries(compiled.tables).filter(([, table]) => table.rollup !== undefined && rollupGateEnforcedAtRead(table.rollup)).map(([sourceID]) => sourceID).sort(),
44554
45482
  incrementalDeclarations,
44555
- buildConnectionNames: [
44556
- ...new Set(compiled.builds.map((b) => b.connectionName))
44557
- ].sort(),
44558
45483
  materializePlans: materializePlansOf(compiled.tables),
44559
- rollupsKeepingGates: Object.entries(compiled.tables).filter(([, table]) => table.rollup !== undefined && rollupGateEnforcedAtRead(table.rollup)).map(([sourceID]) => sourceID).sort(),
44560
- refusedRollups: refusedRollupsOf(plan, compiled.tables),
44561
- compilerKeys: compilerKeysOf(compiled)
45484
+ asOfBuild,
45485
+ accessReads: [...compiled.accessReads ?? []],
45486
+ eligibilityRefused: { ...counts }
44562
45487
  };
44563
45488
  }
45489
+ function withAsOfBuild(plan, asOfBuild) {
45490
+ if (!plan || Object.keys(asOfBuild).length === 0)
45491
+ return plan;
45492
+ const sources = { ...plan.sources };
45493
+ for (const sourceID of Object.keys(asOfBuild)) {
45494
+ const entry = sources[sourceID];
45495
+ if (entry)
45496
+ sources[sourceID] = { ...entry, asOfBuild: true };
45497
+ }
45498
+ return { ...plan, sources };
45499
+ }
45500
+ function asOfBuildOf(plan, tables) {
45501
+ const out = {};
45502
+ for (const [sourceID, table] of Object.entries(tables)) {
45503
+ if (!plan?.sources?.[sourceID])
45504
+ continue;
45505
+ if (!storedAsOfBuild(table.source, table.kind))
45506
+ continue;
45507
+ out[sourceID] = {
45508
+ name: table.source.name,
45509
+ ...table.modelPath ? { modelPath: table.modelPath } : {},
45510
+ reads: currentTimeReadsOf(table.source)
45511
+ };
45512
+ }
45513
+ return out;
45514
+ }
45515
+ function tablePlanDataOf(tables) {
45516
+ return Object.fromEntries(Object.entries(tables).map(([sourceID, table]) => {
45517
+ const {
45518
+ source,
45519
+ target: _target,
45520
+ overStoredBase,
45521
+ ...data
45522
+ } = table;
45523
+ return [
45524
+ sourceID,
45525
+ {
45526
+ ...data,
45527
+ name: source.name,
45528
+ connectionName: source.connectionName,
45529
+ ...overStoredBase ? { overStoredBaseCandidate: true } : {}
45530
+ }
45531
+ ];
45532
+ }));
45533
+ }
44564
45534
  function compilerKeysOf(compiled) {
44565
45535
  const keys = {};
44566
45536
  for (const [sourceID, { source, target }] of Object.entries(compiled.tables)) {
@@ -44592,36 +45562,64 @@ function refuseIncrementalUnbuildable(compiled) {
44592
45562
  if (reason === undefined)
44593
45563
  continue;
44594
45564
  dropped.add(sourceID);
44595
- const model = compiled.tables[sourceID]?.modelPath ?? "";
44596
- const plan = compiled.tables[sourceID]?.materialize;
44597
- const tier = tierOf(declaredStorage(source));
44598
- const refused = refusalKey(sourceID, source.name, "incremental_unsupported", tier);
44599
- findings.push(plan ? materializeRefusalFinding({
44600
- sourceName: plan.sourceName,
45565
+ findings.push(notBuiltFinding(compiled, sourceID, "incremental_unsupported", reason));
45566
+ }
45567
+ return withoutSources(compiled, findings, dropped);
45568
+ }
45569
+ function refuseUpstreamUnread(compiled) {
45570
+ const readings = compiled.upstreamSchemas;
45571
+ if (!readings)
45572
+ return compiled;
45573
+ const findings = [];
45574
+ const dropped = new Set;
45575
+ for (const [sourceID, { source }] of Object.entries(compiled.tables)) {
45576
+ const unread = (upstreamTablesOf(source) ?? []).filter((t) => {
45577
+ const reading = readings[upstreamTableKey(t)];
45578
+ return reading !== undefined && "unread" in reading ? reading.unread === "read_failed" : false;
45579
+ });
45580
+ if (unread.length === 0)
45581
+ continue;
45582
+ dropped.add(sourceID);
45583
+ const tables = unread.map((t) => `"${t.table}" on connection "${t.connectionName}"`).join(", ");
45584
+ findings.push(notBuiltFinding(compiled, sourceID, "upstream_unread", `the columns of ${tables}, which its build reads, could not be ` + "read from the warehouse's catalog, so its table's address is " + "not known; it is planned once a reload, or a plan refresh, " + "reads them"));
45585
+ }
45586
+ return withoutSources(compiled, findings, dropped);
45587
+ }
45588
+ function notBuiltFinding(compiled, sourceID, reason, why) {
45589
+ const table = compiled.tables[sourceID];
45590
+ const source = table.source;
45591
+ const model = table.modelPath ?? "";
45592
+ const tier = tierOf(declaredStorage(source));
45593
+ const refused = refusalKey(sourceID, source.name, reason, tier);
45594
+ if (table.materialize) {
45595
+ return materializeRefusalFinding({
45596
+ sourceName: table.materialize.sourceName,
44601
45597
  sourceID,
44602
- reason,
44603
- outcome: {
44604
- refused: { reason: "incremental_unsupported", tier }
44605
- }
44606
- }, model) : view ? {
44607
- ...persistedViewRefusalFinding({
44608
- ...view,
44609
- sourceID,
44610
- reason,
44611
- outcome: { refused: "incremental_unsupported" }
44612
- }, model),
45598
+ reason: why,
45599
+ outcome: { refused: { reason, tier } }
45600
+ }, model);
45601
+ }
45602
+ const view = persistedViewOf(source);
45603
+ if (view) {
45604
+ return {
45605
+ ...persistedViewRefusalFinding({ ...view, sourceID, reason: why, outcome: { refused: reason } }, model),
44613
45606
  refused
45607
+ };
45608
+ }
45609
+ return {
45610
+ route: "@",
45611
+ tier: "unservable",
45612
+ ...table.kind === "rollup" ? {
45613
+ code: ROLLUP_NOT_BUILT_CODE,
45614
+ message: `Rollup "${source.name}" is not built, so its measures are answered live: ${why}.`
44614
45615
  } : {
44615
- route: "@",
44616
- tier: "unservable",
44617
45616
  code: PERSIST_NOT_BUILT_CODE,
44618
- message: `#@ persist source "${source.name}" is not built, so it is answered live: ${reason}.`,
44619
- subject: source.name,
44620
- model,
44621
- refused
44622
- });
44623
- }
44624
- return withoutSources(compiled, findings, dropped);
45617
+ message: `#@ persist source "${source.name}" is not built, so it is answered live: ${why}.`
45618
+ },
45619
+ subject: source.name,
45620
+ model,
45621
+ refused
45622
+ };
44625
45623
  }
44626
45624
  function persistedViewOf(source) {
44627
45625
  if (!isPersistedResultSourceID(source.sourceID))
@@ -44718,7 +45716,7 @@ function collectIncrementalDeclarations(tables) {
44718
45716
  } catch (err) {
44719
45717
  logger.warn("Failed to resolve a source's incremental declaration", {
44720
45718
  sourceID,
44721
- error: errMessage(err)
45719
+ code: errorCodeOf(err)
44722
45720
  });
44723
45721
  }
44724
45722
  }
@@ -44726,6 +45724,7 @@ function collectIncrementalDeclarations(tables) {
44726
45724
  }
44727
45725
  var ORIGIN_OF_NOT_BUILT_CODE;
44728
45726
  var init_build_plan = __esm(() => {
45727
+ init_error_code();
44729
45728
  init_incremental_policy();
44730
45729
  init_load_gate_text();
44731
45730
  init_preaggregation_validation();
@@ -44753,9 +45752,10 @@ var init_build_plan = __esm(() => {
44753
45752
  init_rollup_compile();
44754
45753
  init_v1_build_companion();
44755
45754
  init_rollup_plan();
44756
- init_rollup_plan();
44757
45755
  init_config2();
44758
45756
  init_connection_type();
45757
+ init_source_reads();
45758
+ init_access_closure();
44759
45759
  init_persist_dynamic_terms();
44760
45760
  init_persist_source_fields();
44761
45761
  init_quoting();
@@ -44776,7 +45776,7 @@ var init_build_plan = __esm(() => {
44776
45776
  });
44777
45777
 
44778
45778
  // src/package_load/protocol.ts
44779
- var PACKAGE_LOAD_PROTOCOL_VERSION = 5;
45779
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 8;
44780
45780
 
44781
45781
  // src/package_load/package_load_worker.ts
44782
45782
  init_malloynb();
@@ -45048,7 +46048,6 @@ class RpcWaitAccountant {
45048
46048
 
45049
46049
  // src/package_load/package_load_worker.ts
45050
46050
  init_experimental_dialects();
45051
- init_materialization_metrics();
45052
46051
  init_logger();
45053
46052
  init_process_safety();
45054
46053
 
@@ -45089,6 +46088,9 @@ class SchemaCache {
45089
46088
  this.delete(oldest);
45090
46089
  }
45091
46090
  }
46091
+ forget(key) {
46092
+ this.delete(key);
46093
+ }
45092
46094
  delete(key) {
45093
46095
  const entry = this.entries.get(key);
45094
46096
  if (!entry)
@@ -45123,6 +46125,37 @@ class SchemaCache {
45123
46125
  }
45124
46126
  }
45125
46127
 
46128
+ class DeferredForgets {
46129
+ cache;
46130
+ pending = new Set;
46131
+ running = new Set;
46132
+ constructor(cache) {
46133
+ this.cache = cache;
46134
+ }
46135
+ forget(keys) {
46136
+ for (const key of keys) {
46137
+ if (this.running.size === 0)
46138
+ this.cache.forget(key);
46139
+ else
46140
+ this.pending.add(key);
46141
+ }
46142
+ }
46143
+ jobStarted(jobId) {
46144
+ this.running.add(jobId);
46145
+ }
46146
+ jobEnded(jobId) {
46147
+ this.running.delete(jobId);
46148
+ if (this.running.size > 0)
46149
+ return;
46150
+ for (const key of this.pending)
46151
+ this.cache.forget(key);
46152
+ this.pending.clear();
46153
+ }
46154
+ get held() {
46155
+ return this.pending.size;
46156
+ }
46157
+ }
46158
+
45126
46159
  // src/package_load/worker_log.ts
45127
46160
  function plainLogEntry(entry) {
45128
46161
  const info = entry;
@@ -45191,7 +46224,7 @@ function callMain(send) {
45191
46224
  }
45192
46225
  var schemaWait = new RpcWaitAccountant;
45193
46226
  function dispatchMainResponse(message) {
45194
- if (message.type === "schema-for-tables-response" || message.type === "schema-for-sql-response" || message.type === "read-url-response" || message.type === "connection-metadata-response") {
46227
+ if (message.type === "schema-for-tables-response" || message.type === "schema-for-sql-response" || message.type === "upstream-schemas-response" || message.type === "read-url-response" || message.type === "connection-metadata-response") {
45195
46228
  const pending = pendingRpc.get(message.requestId);
45196
46229
  if (!pending)
45197
46230
  return;
@@ -45209,8 +46242,8 @@ function dispatchMainResponse(message) {
45209
46242
  }
45210
46243
  }
45211
46244
  var schemaCache = new SchemaCache(workerData2?.schemaCacheBytes ?? 0);
46245
+ var deferredForgets = new DeferredForgets(schemaCache);
45212
46246
  var jobContext = new AsyncLocalStorage3;
45213
- setEligibilityRefusalSink(() => jobContext.getStore()?.refusals);
45214
46247
  var writeEntry = logger.write.bind(logger);
45215
46248
  logger.write = (entry) => {
45216
46249
  const job = jobContext.getStore();
@@ -45237,11 +46270,13 @@ class ProxyConnection {
45237
46270
  digest;
45238
46271
  jobId;
45239
46272
  cacheScope;
45240
- constructor(metadata, jobId, environmentScope) {
46273
+ refresh;
46274
+ constructor(metadata, jobId, environmentScope, refresh) {
45241
46275
  this.name = metadata.name;
45242
46276
  this.dialectName = metadata.dialectName;
45243
46277
  this.digest = metadata.digest;
45244
46278
  this.jobId = jobId;
46279
+ this.refresh = refresh;
45245
46280
  this.cacheScope = [
45246
46281
  environmentScope,
45247
46282
  this.name,
@@ -45262,8 +46297,13 @@ class ProxyConnection {
45262
46297
  const errors = {};
45263
46298
  const joined = [];
45264
46299
  const missing = {};
46300
+ const refetch = {};
45265
46301
  for (const [key, tablePath] of Object.entries(tables)) {
45266
46302
  const cacheKey = this.tableCacheKey(tablePath);
46303
+ if (this.claimRefetch(cacheKey)) {
46304
+ refetch[key] = tablePath;
46305
+ continue;
46306
+ }
45267
46307
  const hit = schemaCache.get(cacheKey);
45268
46308
  const pending = hit === undefined ? schemaCache.joinInFlight(cacheKey) : undefined;
45269
46309
  if (hit) {
@@ -45274,16 +46314,14 @@ class ProxyConnection {
45274
46314
  missing[key] = tablePath;
45275
46315
  }
45276
46316
  }
45277
- if (Object.keys(missing).length > 0) {
45278
- const request = this.fetchSchemaForTablesFromMain(missing, options);
45279
- for (const [key, tablePath] of Object.entries(missing)) {
45280
- schemaCache.trackInFlight(this.tableCacheKey(tablePath), request.then((r) => ({
45281
- value: r.schemas[key],
45282
- error: r.errors[key]
45283
- })));
45284
- }
45285
- const fetched = await request;
45286
- this.cacheTableSchemas(missing, fetched.schemas);
46317
+ const fetches = [this.fetchAndCacheTables(missing, options)];
46318
+ if (this.refresh && Object.keys(refetch).length > 0) {
46319
+ fetches.push(this.fetchAndCacheTables(refetch, {
46320
+ ...options,
46321
+ refreshTimestamp: this.refresh.timestamp
46322
+ }));
46323
+ }
46324
+ for (const fetched of await Promise.all(fetches)) {
45287
46325
  Object.assign(schemas, fetched.schemas);
45288
46326
  Object.assign(errors, fetched.errors);
45289
46327
  }
@@ -45298,6 +46336,27 @@ class ProxyConnection {
45298
46336
  }
45299
46337
  return { schemas, errors };
45300
46338
  }
46339
+ async fetchAndCacheTables(tables, options) {
46340
+ if (Object.keys(tables).length === 0)
46341
+ return { schemas: {}, errors: {} };
46342
+ const request = this.fetchSchemaForTablesFromMain(tables, options);
46343
+ for (const [key, tablePath] of Object.entries(tables)) {
46344
+ schemaCache.trackInFlight(this.tableCacheKey(tablePath), request.then((r) => ({
46345
+ value: r.schemas[key],
46346
+ error: r.errors[key]
46347
+ })));
46348
+ }
46349
+ const fetched = await request;
46350
+ this.cacheTableSchemas(tables, fetched.schemas);
46351
+ return fetched;
46352
+ }
46353
+ claimRefetch(cacheKey) {
46354
+ if (!this.refresh || this.refresh.refetched.has(cacheKey))
46355
+ return false;
46356
+ this.refresh.refetched.add(cacheKey);
46357
+ schemaCache.forget(cacheKey);
46358
+ return true;
46359
+ }
45301
46360
  cacheTableSchemas(requested, schemas) {
45302
46361
  for (const [key, schema] of Object.entries(schemas)) {
45303
46362
  const tablePath = requested[key];
@@ -45337,10 +46396,11 @@ class ProxyConnection {
45337
46396
  }
45338
46397
  return refreshed;
45339
46398
  }
45340
- const hit = schemaCache.get(cacheKey);
46399
+ const refetch = this.claimRefetch(cacheKey);
46400
+ const hit = refetch ? undefined : schemaCache.get(cacheKey);
45341
46401
  if (hit)
45342
46402
  return { structDef: hit };
45343
- const pending = schemaCache.joinInFlight(cacheKey);
46403
+ const pending = refetch ? undefined : schemaCache.joinInFlight(cacheKey);
45344
46404
  if (pending) {
45345
46405
  const answer = await pending;
45346
46406
  if (answer.value) {
@@ -45349,7 +46409,7 @@ class ProxyConnection {
45349
46409
  }
45350
46410
  return { error: answer.error ?? "No schema returned for the SQL" };
45351
46411
  }
45352
- const request = this.fetchSchemaForSQLStructFromMain(sentence, options);
46412
+ const request = this.fetchSchemaForSQLStructFromMain(sentence, refetch && this.refresh ? { ...options, refreshTimestamp: this.refresh.timestamp } : options);
45353
46413
  schemaCache.trackInFlight(cacheKey, request.then((r) => ({ value: r.structDef, error: r.error })));
45354
46414
  const result = await request;
45355
46415
  if (result.structDef !== undefined) {
@@ -45443,7 +46503,7 @@ function makeWorkerUrlReader(job) {
45443
46503
  }
45444
46504
  };
45445
46505
  }
45446
- function buildWorkerMalloyConfig(job) {
46506
+ function buildWorkerMalloyConfig(job, refresh) {
45447
46507
  const proxies = new Map;
45448
46508
  const inflight = new Map;
45449
46509
  const config = new MalloyConfig({ connections: {} }, { config: contextOverlay({ rootDirectory: job.packagePath }) });
@@ -45465,7 +46525,7 @@ function buildWorkerMalloyConfig(job) {
45465
46525
  };
45466
46526
  port.postMessage(req);
45467
46527
  });
45468
- const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName), response.metadata.connectionType);
46528
+ const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, { managed: response.metadata.managed === true });
45469
46529
  proxies.set(effectiveName, proxy);
45470
46530
  inflight.delete(effectiveName);
45471
46531
  return proxy;
@@ -45632,7 +46692,7 @@ async function compileMalloyModel(job, malloyConfig, modelPath, load, files) {
45632
46692
  const modelDef = compiled._modelDef;
45633
46693
  const { sources, queries, filterMap, givens, sourceInfos, warnings } = await extractCheckedModel(mm, compiled);
45634
46694
  const compileDurationMs = performance.now() - compileStart;
45635
- const { renderTagResults, renderTagResultsDigest, preaggregateCompanion } = await prepareForMainThread(job, malloyConfig, load, {
46695
+ const { renderTagResults, renderTagResultsDigest } = await prepareForMainThread(job, malloyConfig, load, {
45636
46696
  modelPath,
45637
46697
  materializer: mm,
45638
46698
  model: compiled,
@@ -45664,7 +46724,6 @@ async function compileMalloyModel(job, malloyConfig, modelPath, load, files) {
45664
46724
  gateWarnings: warnings.length > 0 ? warnings : undefined,
45665
46725
  renderTagResults,
45666
46726
  renderTagResultsDigest,
45667
- preaggregateCompanion,
45668
46727
  entities,
45669
46728
  governsAccess: governsAccess(modelDef)
45670
46729
  };
@@ -45741,11 +46800,12 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
45741
46800
  runtime: jobRuntime(job, malloyConfig, overlaidReader(makeWorkerUrlReader(job), overlay)),
45742
46801
  importBaseURL
45743
46802
  });
45744
- const companion = (job.withPreaggregateCompanions || wantsPlan) && !load.failed && !pastDeadline() ? null : undefined;
45745
46803
  if (wantsPlan && load.planLeftToMainThread) {
45746
46804
  wantsPlan = false;
45747
46805
  }
45748
- if (wantsPlan && companion !== undefined && !load.failed) {
46806
+ if (wantsPlan && (load.failed || pastDeadline())) {
46807
+ load.planLeftToMainThread = true;
46808
+ } else if (wantsPlan) {
45749
46809
  load.planStart ??= performance.now();
45750
46810
  try {
45751
46811
  const parts = emptyBuildPlanParts();
@@ -45767,14 +46827,8 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
45767
46827
  };
45768
46828
  }
45769
46829
  }
45770
- } else if (wantsPlan) {
45771
- load.planLeftToMainThread = true;
45772
46830
  }
45773
- return {
45774
- renderTagResults,
45775
- renderTagResultsDigest,
45776
- preaggregateCompanion: !job.withPreaggregateCompanions || companion === undefined ? undefined : {}
45777
- };
46831
+ return { renderTagResults, renderTagResultsDigest };
45778
46832
  }
45779
46833
  async function compileNotebookModel(job, malloyConfig, modelPath) {
45780
46834
  const compileStart = performance.now();
@@ -45851,7 +46905,8 @@ async function loadPackage(job) {
45851
46905
  const allFiles = await listPackageFiles(job.packagePath);
45852
46906
  const modelPaths = filterModelPaths(allFiles);
45853
46907
  const packageMetadata = await readPackageMetadata(job.packagePath, modelPaths);
45854
- const malloyConfig = buildWorkerMalloyConfig(job);
46908
+ const refresh = job.refreshTimestamp !== undefined ? { timestamp: job.refreshTimestamp, refetched: new Set } : undefined;
46909
+ const malloyConfig = buildWorkerMalloyConfig(job, refresh);
45855
46910
  const replacementMatchedExisting = job.replacement ? modelPaths.includes(job.replacement.modelPath) : undefined;
45856
46911
  if (job.replacement && !replacementMatchedExisting) {
45857
46912
  modelPaths.push(job.replacement.modelPath);
@@ -45887,7 +46942,7 @@ async function loadPackage(job) {
45887
46942
  const schemaFetchDurationMs = schemaWait.waitMs;
45888
46943
  const schemaFetchCount = schemaWait.fetches;
45889
46944
  const schemaCacheHits = schemaCache.hits - schemaCacheHitsAtStart;
45890
- const buildPlan = await finishWorkerBuildPlan(malloyConfig, modelPaths, load, packageMetadata.materialization ?? null, !!job.publishedVersion && packageMetadata.scope === "version");
46945
+ const buildPlan = await finishWorkerBuildPlan(malloyConfig, modelPaths, load, packageMetadata.materialization ?? null, !!job.publishedVersion && packageMetadata.scope === "version", job.requestId);
45891
46946
  const loadEnd = performance.now();
45892
46947
  return {
45893
46948
  type: "load-package-result",
@@ -45896,6 +46951,7 @@ async function loadPackage(job) {
45896
46951
  packageMetadata,
45897
46952
  models,
45898
46953
  replacementMatchedExisting,
46954
+ ...refresh ? { refreshedSchemaKeys: [...refresh.refetched] } : {},
45899
46955
  loadDurationMs: loadEnd - loadStart,
45900
46956
  timings: {
45901
46957
  compileDurationMs: Math.max(0, compileEnd - compileRegionStart - schemaFetchDurationMs),
@@ -45908,15 +46964,13 @@ async function loadPackage(job) {
45908
46964
  buildPlan
45909
46965
  };
45910
46966
  }
45911
- async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped) {
46967
+ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped, jobId) {
45912
46968
  if (!load.planParts || load.failed || load.planLeftToMainThread) {
45913
46969
  return;
45914
46970
  }
45915
46971
  const start = performance.now();
45916
- const refusals = () => ({
45917
- ...jobContext.getStore()?.refusals ?? {}
45918
- });
45919
- const digestSkipped = [];
46972
+ const eligibilityRefused = {};
46973
+ let digestSkipped = [];
45920
46974
  try {
45921
46975
  if (load.planError)
45922
46976
  throw new Error(load.planError.message);
@@ -45929,21 +46983,25 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45929
46983
  throw new Error(`Model ${modelPath} did not compile`);
45930
46984
  mergeBuildPlanParts(parts, own);
45931
46985
  }
45932
- const connections = await resolvePackageConnections({
45933
- getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name)
45934
- }, parts.builds.map((b) => b.connectionName));
45935
- const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
45936
- const outcome = deriveBuildPlanOutcome(finishBuildPlan(parts, {
45937
- connectionDigests,
45938
- connections,
45939
- versionScoped
45940
- }), materializationConfig);
46986
+ const finished = await finishPackagePlan(parts, {
46987
+ getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name),
46988
+ versionScoped,
46989
+ readUpstreamSchemas: async (tables) => (await callMain((requestId) => {
46990
+ const req = {
46991
+ type: "upstream-schemas",
46992
+ requestId,
46993
+ jobId,
46994
+ tables
46995
+ };
46996
+ port.postMessage(req);
46997
+ })).readings
46998
+ });
46999
+ digestSkipped = finished.digestSkipped;
45941
47000
  return {
45942
47001
  ok: true,
45943
- outcome,
47002
+ packagePlan: derivePackagePlan(finished.compiled, materializationConfig, eligibilityRefused),
45944
47003
  durationMs: performance.now() - (load.planStart ?? start),
45945
- digestSkipped,
45946
- eligibilityRefused: refusals()
47004
+ digestSkipped
45947
47005
  };
45948
47006
  } catch (error) {
45949
47007
  return {
@@ -45951,7 +47009,7 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45951
47009
  error: errMessage(error),
45952
47010
  durationMs: performance.now() - (load.planStart ?? start),
45953
47011
  digestSkipped,
45954
- eligibilityRefused: refusals()
47012
+ eligibilityRefused
45955
47013
  };
45956
47014
  }
45957
47015
  }
@@ -45976,15 +47034,19 @@ port.on("message", (message) => {
45976
47034
  port.postMessage(errMsg);
45977
47035
  return;
45978
47036
  }
45979
- inFlightJobs.add(message.requestId);
47037
+ jobStarted(message.requestId);
45980
47038
  runJob(message);
45981
47039
  return;
45982
47040
  }
45983
47041
  if (message.type === "compile-served-copy") {
45984
- inFlightJobs.add(message.requestId);
47042
+ jobStarted(message.requestId);
45985
47043
  runServedCopyJob(message);
45986
47044
  return;
45987
47045
  }
47046
+ if (message.type === "forget-schemas") {
47047
+ deferredForgets.forget(message.keys);
47048
+ return;
47049
+ }
45988
47050
  dispatchMainResponse(message);
45989
47051
  });
45990
47052
  async function compileServedCopy(job) {
@@ -46016,8 +47078,7 @@ async function compileServedCopy(job) {
46016
47078
  async function runServedCopyJob(job) {
46017
47079
  const context = {
46018
47080
  jobId: job.requestId,
46019
- packagePath: job.packagePath,
46020
- refusals: {}
47081
+ packagePath: job.packagePath
46021
47082
  };
46022
47083
  try {
46023
47084
  port.postMessage(await jobContext.run(context, () => compileServedCopy(job)));
@@ -46031,15 +47092,13 @@ async function runServedCopyJob(job) {
46031
47092
  };
46032
47093
  port.postMessage(result);
46033
47094
  } finally {
46034
- inFlightJobs.delete(job.requestId);
46035
- maybeExit();
47095
+ jobEnded(job.requestId);
46036
47096
  }
46037
47097
  }
46038
47098
  async function runJob(job) {
46039
47099
  const context = {
46040
47100
  jobId: job.requestId,
46041
- packagePath: job.packagePath,
46042
- refusals: {}
47101
+ packagePath: job.packagePath
46043
47102
  };
46044
47103
  try {
46045
47104
  const result = await jobContext.run(context, () => loadPackage(job));
@@ -46052,10 +47111,18 @@ async function runJob(job) {
46052
47111
  };
46053
47112
  port.postMessage(errMsg);
46054
47113
  } finally {
46055
- inFlightJobs.delete(job.requestId);
46056
- maybeExit();
47114
+ jobEnded(job.requestId);
46057
47115
  }
46058
47116
  }
47117
+ function jobStarted(jobId) {
47118
+ inFlightJobs.add(jobId);
47119
+ deferredForgets.jobStarted(jobId);
47120
+ }
47121
+ function jobEnded(jobId) {
47122
+ inFlightJobs.delete(jobId);
47123
+ deferredForgets.jobEnded(jobId);
47124
+ maybeExit();
47125
+ }
46059
47126
  function maybeExit() {
46060
47127
  if (shuttingDown && inFlightJobs.size === 0 && pendingRpc.size === 0) {
46061
47128
  setImmediate(() => process.exit(0));