@malloy-publisher/server 0.15.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/app/api-doc.yaml +320 -26
  2. package/dist/app/assets/{EnvironmentPage-CKUvEX7r.js → EnvironmentPage-Y9IWPC9J.js} +1 -1
  3. package/dist/app/assets/{HomePage-COpZmm3Z.js → HomePage-BOUo0MEl.js} +1 -1
  4. package/dist/app/assets/{MainPage-nIyVOgy5.js → MainPage-BkM5UDRU.js} +1 -1
  5. package/dist/app/assets/{ModelPage-BelGfTpw.js → ModelPage-PgDTkS5C.js} +2 -2
  6. package/dist/app/assets/{PackagePage-CbnVG2uD.js → PackagePage-Dn7FrQ5r.js} +1 -1
  7. package/dist/app/assets/{PackageSplatRoute-37oqxKyq.js → PackageSplatRoute-BLC29ek-.js} +2 -2
  8. package/dist/app/assets/{RenderedResult-Ct3z543g.es-QeWq894a.js → RenderedResult-vyM2wQbC.es-ha8dF24T.js} +3 -3
  9. package/dist/app/assets/{RouteError-CjmVxFgv.js → RouteError-BolMqTuz.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-BjPyhpFF.js → ThemeEditorPage-CPv1eHkI.js} +1 -1
  11. package/dist/app/assets/{ToggleButtonGroup-bM-WVZrV.js → ToggleButtonGroup-DZtImN0S.js} +1 -1
  12. package/dist/app/assets/{documentRoutes-BAPDdua3.js → documentRoutes-DI5cX3ty.js} +1 -1
  13. package/dist/app/assets/{editPageMounted-B4HEQbbz.js → editPageMounted-C--4kcld.js} +2 -2
  14. package/dist/app/assets/{index-DbRUcXfe.js → index-CbsrzNSp.js} +1 -1
  15. package/dist/app/assets/{index-C-aFb4Gn.js → index-D9wSfMZN.js} +1 -1
  16. package/dist/app/assets/{index-DUgED99B.js → index-DLToSg1f.js} +62 -62
  17. package/dist/app/assets/{index-Bx-5B05C.js → index-DyYEltlF.js} +1 -1
  18. package/dist/app/assets/{index.es-DO67FMt6.js → index.es-D8SVyfmS.js} +1 -1
  19. package/dist/app/assets/usePackageLinkNavigate-DxHGKrmZ.js +1 -0
  20. package/dist/app/assets/{usePackageRoute-Cso_p7RX.js → usePackageRoute-A_YQMrax.js} +1 -1
  21. package/dist/app/index.html +1 -1
  22. package/dist/app/mcp-app/report.js +145 -145
  23. package/dist/instrumentation.mjs +10 -2
  24. package/dist/package_load_worker.mjs +1048 -384
  25. package/dist/server.mjs +31884 -27490
  26. package/package.json +1 -1
  27. package/dist/app/assets/usePackageLinkNavigate-BgdbNERJ.js +0 -1
@@ -1968,6 +1968,14 @@ var init_admin = __esm(() => {
1968
1968
  notes: "Host binding for the admin API. Deliberately not moved by `PUBLISHER_HOST`: putting the main API on every interface does not expose the admin operations. Widen it only inside the network the orchestrator calls from, never behind a public ingress.",
1969
1969
  aliases: { env: ["PUBLISHER_ADMIN_HOST"], flags: ["--admin_host"] }
1970
1970
  }),
1971
+ setting({
1972
+ key: "admin.requestTimeoutMs",
1973
+ type: integer({ min: 1 }),
1974
+ default: 600000,
1975
+ description: "Ms the admin API keeps a request, its headers and an idle keep-alive open.",
1976
+ defaultText: "`600000` (10 min)",
1977
+ notes: "How long the admin listener lets a request run before closing its connection. A table copy or a file load answers only when the table is written, so a large table needs longer than the main API's ten minutes; raise this for the caller's largest copy, and keep the caller's own timeout above it. Applies to the admin listener alone: the main API and MCP listeners keep ten minutes."
1978
+ }),
1971
1979
  setting({
1972
1980
  key: "admin.catalogDatabase",
1973
1981
  type: string(),
@@ -2278,7 +2286,7 @@ var init_query = __esm(() => {
2278
2286
  type: integer({ min: 0 }),
2279
2287
  default: DEFAULT_PACKAGE_LOAD_SCHEMA_CACHE_BYTES,
2280
2288
  description: "Serialized schema each package-load worker caches across loads, in bytes; 0 turns it off.",
2281
- 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.",
2282
2290
  defaultText: "`16777216` (16 MiB)",
2283
2291
  aliases: { env: ["PACKAGE_LOAD_SCHEMA_CACHE_BYTES"] }
2284
2292
  })
@@ -12521,6 +12529,15 @@ function freshnessWindowSeconds(window2) {
12521
12529
  return;
12522
12530
  return count * WINDOW_UNITS[match[2]];
12523
12531
  }
12532
+ function durationSeconds(text) {
12533
+ const match = /^\s*(\d+)\s*([a-z]+)\s*$/.exec(text);
12534
+ if (!match || !Object.hasOwn(DURATION_UNITS, match[2]))
12535
+ return;
12536
+ const count = Number(match[1]);
12537
+ if (!Number.isSafeInteger(count) || count <= 0)
12538
+ return;
12539
+ return count * DURATION_UNITS[match[2]];
12540
+ }
12524
12541
  function declaredFreshnessFacts(declarations) {
12525
12542
  let window2;
12526
12543
  const fallbacks = new Set;
@@ -12548,7 +12565,7 @@ function declaredFreshnessFacts(declarations) {
12548
12565
  ...fallback !== undefined ? { freshnessFallback: fallback } : {}
12549
12566
  };
12550
12567
  }
12551
- var FRESHNESS_FALLBACKS, WINDOW_UNITS;
12568
+ var FRESHNESS_FALLBACKS, WINDOW_UNITS, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
12552
12569
  var init_freshness = __esm(() => {
12553
12570
  FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
12554
12571
  WINDOW_UNITS = {
@@ -12558,6 +12575,19 @@ var init_freshness = __esm(() => {
12558
12575
  d: 86400,
12559
12576
  w: 604800
12560
12577
  };
12578
+ DURATION_UNITS = {
12579
+ ...WINDOW_UNITS,
12580
+ second: 1,
12581
+ seconds: 1,
12582
+ minute: 60,
12583
+ minutes: 60,
12584
+ hour: 3600,
12585
+ hours: 3600,
12586
+ day: 86400,
12587
+ days: 86400,
12588
+ week: 604800,
12589
+ weeks: 604800
12590
+ };
12561
12591
  });
12562
12592
 
12563
12593
  // src/service/annotation_reader.ts
@@ -12895,6 +12925,7 @@ var init_annotation_reader = __esm(() => {
12895
12925
  "refresh",
12896
12926
  "watermark",
12897
12927
  "merge_key",
12928
+ "lookback",
12898
12929
  "freshness",
12899
12930
  "queryMetadata"
12900
12931
  ]);
@@ -12910,6 +12941,7 @@ var init_annotation_reader = __esm(() => {
12910
12941
  "refresh",
12911
12942
  "watermark",
12912
12943
  "merge_key",
12944
+ "lookback",
12913
12945
  "freshness",
12914
12946
  "queryMetadata",
12915
12947
  "inline"
@@ -14062,7 +14094,7 @@ function errorKind(error) {
14062
14094
  function errorMapping(error) {
14063
14095
  return ERROR_TABLE[errorKind(error)];
14064
14096
  }
14065
- 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, 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;
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;
14066
14098
  var init_errors2 = __esm(() => {
14067
14099
  init_constants();
14068
14100
  init_logger();
@@ -14548,6 +14580,16 @@ var init_errors2 = __esm(() => {
14548
14580
  super(message);
14549
14581
  }
14550
14582
  };
14583
+ MaterializedTableDropRefusedError = class MaterializedTableDropRefusedError extends Error {
14584
+ reason;
14585
+ get kind() {
14586
+ return "materialized_table_drop_refused";
14587
+ }
14588
+ constructor(reason, message) {
14589
+ super(message);
14590
+ this.reason = reason;
14591
+ }
14592
+ };
14551
14593
  WriteConflictError = class WriteConflictError extends Error {
14552
14594
  reason;
14553
14595
  get kind() {
@@ -14707,6 +14749,7 @@ var init_errors2 = __esm(() => {
14707
14749
  off_surface: OffSurfaceError,
14708
14750
  materialization_not_found: MaterializationNotFoundError,
14709
14751
  materialization_conflict: MaterializationConflictError,
14752
+ materialized_table_drop_refused: MaterializedTableDropRefusedError,
14710
14753
  write_conflict: WriteConflictError,
14711
14754
  installed_from_location: InstalledFromLocationError,
14712
14755
  write_rolled_back: WriteRolledBackError,
@@ -14984,6 +15027,11 @@ var init_errors2 = __esm(() => {
14984
15027
  reason: "MATERIALIZATION_CONFLICT",
14985
15028
  mcp: { advice: "internal" }
14986
15029
  },
15030
+ materialized_table_drop_refused: {
15031
+ status: 409,
15032
+ reason: (error) => error.reason,
15033
+ mcp: { advice: "internal" }
15034
+ },
14987
15035
  invalid_state_transition: { status: 409, mcp: { advice: "internal" } },
14988
15036
  write_conflict: {
14989
15037
  status: 409,
@@ -28036,184 +28084,6 @@ var init_experimental_dialects = __esm(() => {
28036
28084
  BUNDLED_EXPERIMENTAL_DIALECTS = ["sqlserver"];
28037
28085
  });
28038
28086
 
28039
- // src/materialization_metrics.ts
28040
- function routeLegOf(kind) {
28041
- return kind === "served" ? "materialized" : kind;
28042
- }
28043
- function recordScheduledFire(outcome) {
28044
- scheduledFireCounter().add(1, { outcome });
28045
- }
28046
- function recordMaterializationRun(mode, outcome, durationMs) {
28047
- runCounter().add(1, { mode, outcome });
28048
- runDuration().record(durationMs, { mode, outcome });
28049
- }
28050
- function recordBuildOutcome(labels) {
28051
- buildCounter().add(1, {
28052
- kind: labels.kind,
28053
- tier: labels.tier,
28054
- outcome: labels.outcome,
28055
- failure_class: labels.outcome === "failed" ? labels.failureClass : "none"
28056
- });
28057
- }
28058
- function recordBuildDuration(durationMs, labels) {
28059
- buildDuration().record(durationMs, {
28060
- kind: labels.kind,
28061
- tier: labels.tier,
28062
- method: labels.method
28063
- });
28064
- }
28065
- function recordBuildReadBytes(bytes, tier) {
28066
- if (typeof bytes !== "number" || !(bytes > 0))
28067
- return;
28068
- buildReadBytes().record(bytes, { tier });
28069
- }
28070
- function recordAnnotationFindings(warnings) {
28071
- for (const { code, severity } of warnings) {
28072
- if (!code)
28073
- continue;
28074
- annotationFindingsCounter().add(1, {
28075
- code,
28076
- outcome: severity === "error" ? "invalid" : "not_built"
28077
- });
28078
- }
28079
- }
28080
- function recordIncrementalStep(step, reason) {
28081
- incrementalStepCounter().add(1, reason ? { step, reason } : { step });
28082
- }
28083
- function recordBuildPlanComputeDuration(durationMs, computedIn) {
28084
- buildPlanComputeDuration().record(durationMs, { computed_in: computedIn });
28085
- }
28086
- function recordBuildPlanComputeFailed() {
28087
- buildPlanComputeFailedCounter().add(1);
28088
- }
28089
- function recordAutoLoadOutcome(outcome) {
28090
- autoLoadCounter().add(1, { outcome });
28091
- }
28092
- function recordConnectionDigestSkipped() {
28093
- connectionDigestSkipCounter().add(1);
28094
- }
28095
- function recordDuplicateTargetSkipped() {
28096
- duplicateTargetSkipCounter().add(1);
28097
- }
28098
- function recordSharedAddressInstructions() {
28099
- sharedAddressInstructionCounter().add(1);
28100
- }
28101
- function recordTableCollision() {
28102
- tableCollisionCounter().add(1);
28103
- }
28104
- function recordManifestBind(outcome) {
28105
- servedCopyBindCounter().add(1, {
28106
- scope: "manifest",
28107
- outcome,
28108
- reason: "none"
28109
- });
28110
- }
28111
- function recordSourceBound() {
28112
- servedCopyBindCounter().add(1, {
28113
- scope: "source",
28114
- outcome: "bound",
28115
- reason: "none"
28116
- });
28117
- }
28118
- function recordSourceDeclined(reason) {
28119
- servedCopyBindCounter().add(1, {
28120
- scope: "source",
28121
- outcome: "declined",
28122
- reason
28123
- });
28124
- }
28125
- function recordServedCopyOutcome(outcome, reason) {
28126
- servedCopyBindCounter().add(1, { scope: "source", outcome, reason });
28127
- }
28128
- function recordManifestBindDegraded() {
28129
- manifestBindDegradedCounter().add(1);
28130
- }
28131
- function recordDropTables(outcome, tier, occasion) {
28132
- dropTablesCounter().add(1, { outcome, tier, occasion });
28133
- }
28134
- function recordKeyCheck(kind, outcome) {
28135
- keyCheckCounter().add(1, { kind, outcome });
28136
- }
28137
- function recordQueryRouteDuration(durationMs, leg) {
28138
- queryRouteDuration().record(durationMs, { leg });
28139
- }
28140
- function recordStorageTableRetained() {
28141
- storageTableRetainedCounter().add(1);
28142
- }
28143
- function recordAttributionSkipped(reason) {
28144
- attributionSkippedCounter().add(1, { reason });
28145
- }
28146
- function recordEligibilityRefused(reason) {
28147
- const counts = eligibilityRefusalSink?.();
28148
- if (counts) {
28149
- counts[reason] = (counts[reason] ?? 0) + 1;
28150
- return;
28151
- }
28152
- eligibilityRefusedCounter().add(1, { reason });
28153
- }
28154
- function setEligibilityRefusalSink(sink) {
28155
- eligibilityRefusalSink = sink;
28156
- }
28157
- function recordStoredTypeFallback(kind) {
28158
- serveShapeTypeFallbackCounter().add(1, { kind });
28159
- }
28160
- function recordStoredColumnTypeMismatch(stage, declared) {
28161
- storedColumnTypeMismatchCounter().add(1, { stage, declared });
28162
- }
28163
- function recordQueryRoute(leg, outcome, reason) {
28164
- queryRouteCounter().add(1, { leg, outcome, reason });
28165
- }
28166
- function recordChainedStorageBuild(outcome) {
28167
- chainedStorageBuildCounter().add(1, { outcome });
28168
- }
28169
- function recordStaleUpstreamEntry(tier) {
28170
- staleUpstreamEntryCounter().add(1, { tier });
28171
- }
28172
- 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;
28173
- var init_materialization_metrics = __esm(() => {
28174
- init_telemetry();
28175
- BUILD_DURATION_BUCKETS_MS = [
28176
- 100,
28177
- 500,
28178
- 1000,
28179
- 5000,
28180
- 15000,
28181
- 60000,
28182
- 300000,
28183
- 900000,
28184
- 3600000
28185
- ];
28186
- BUILD_READ_BYTES_BUCKETS = [1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000];
28187
- runCounter = lazyCounter("publisher_materialization_runs_total", "Materialization builds completed. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
28188
- runDuration = lazyHistogram("publisher_materialization_run_duration_ms", "Wall-clock duration of a materialization build. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
28189
- 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.");
28190
- 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 });
28191
- 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 });
28192
- 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).");
28193
- 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.");
28194
- buildPlanComputeDuration = lazyHistogram("publisher_materialization_build_plan_compute_duration_ms", "Wall-clock duration of compiling a package's build plan (Package.buildPlan).");
28195
- 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.");
28196
- autoLoadCounter = lazyCounter("publisher_materialization_auto_load_total", "Auto-run manifest auto-load attempts. Label: outcome ('success'|'failure').");
28197
- connectionDigestSkipCounter = lazyCounter("publisher_materialization_connection_digest_skipped_total", "Connection digests skipped during build-plan compile because the connection did not resolve.");
28198
- 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'.");
28199
- 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.");
28200
- 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.");
28201
- 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.");
28202
- 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.");
28203
- 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).");
28204
- scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
28205
- 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; 'RUN_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.");
28206
- 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.");
28207
- 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.");
28208
- 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.");
28209
- 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.");
28210
- 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).");
28211
- 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').");
28212
- 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).");
28213
- 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.");
28214
- 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.");
28215
- });
28216
-
28217
28087
  // src/process_safety.ts
28218
28088
  function describeRejection(reason) {
28219
28089
  let message;
@@ -28530,6 +28400,39 @@ function refusalKey(sourceID, name, reason, tier) {
28530
28400
  return { sourceID, name, tier, reason };
28531
28401
  }
28532
28402
 
28403
+ // src/error_code.ts
28404
+ function errorCodeOf(err) {
28405
+ const chain = [...causeChain(err)];
28406
+ for (const e of chain) {
28407
+ if (e instanceof MaterializationEligibilityError && e.reason) {
28408
+ return e.reason;
28409
+ }
28410
+ const reason = e.reason;
28411
+ if (e instanceof ChainedShapeNotCarriedError && typeof reason === "string" && CODE_PATTERN.test(reason)) {
28412
+ return reason;
28413
+ }
28414
+ const { kind, code } = e;
28415
+ for (const candidate of [kind, code]) {
28416
+ if (typeof candidate === "string" && CODE_PATTERN.test(candidate)) {
28417
+ return candidate;
28418
+ }
28419
+ }
28420
+ if (typeof code === "number")
28421
+ return String(code);
28422
+ }
28423
+ for (const e of chain) {
28424
+ if (e.name !== "Error" && CODE_PATTERN.test(e.name))
28425
+ return e.name;
28426
+ }
28427
+ return "Error";
28428
+ }
28429
+ var CODE_PATTERN;
28430
+ var init_error_code = __esm(() => {
28431
+ init_driver_errors();
28432
+ init_errors2();
28433
+ CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
28434
+ });
28435
+
28533
28436
  // src/service/governance/ir/compiled_model.ts
28534
28437
  function modelDefOf(model) {
28535
28438
  return model._modelDef;
@@ -28656,6 +28559,8 @@ var init_dialect = __esm(() => {
28656
28559
  needsQualifiedTable: false,
28657
28560
  nestedColumns: false,
28658
28561
  driverKeepsBigIntegers: false,
28562
+ liveRoundsBigIntegersMeasured: false,
28563
+ liveWritesFloat4Shortest: false,
28659
28564
  castsToIntegerType: false,
28660
28565
  onlyBigIntegerType: undefined,
28661
28566
  foldsTableNameCase: false,
@@ -28694,7 +28599,9 @@ var init_dialect = __esm(() => {
28694
28599
  dependencyGuard: true,
28695
28600
  relationProbe: true,
28696
28601
  tableOwnership: true,
28697
- castsToIntegerType: true
28602
+ castsToIntegerType: true,
28603
+ liveRoundsBigIntegersMeasured: true,
28604
+ liveWritesFloat4Shortest: true
28698
28605
  }),
28699
28606
  standardsql: Object.freeze({
28700
28607
  ...NONE,
@@ -28777,6 +28684,9 @@ function aggregateBacked(names) {
28777
28684
  return names.filter((n) => n !== undefined && n.kind === "aggregate");
28778
28685
  }
28779
28686
  function malformedMessage(where, key, problem, detail) {
28687
+ if (key === "lookback" && (problem === "array" || problem === "empty")) {
28688
+ return `${where} declares lookback=${problem === "array" ? "[…] as a tag ARRAY" : '"" (empty)'}. ` + `Write ONE quoted duration, such as lookback="2 days", or remove the ` + `key (use -lookback to strip one inherited from a parent source).`;
28689
+ }
28780
28690
  switch (problem) {
28781
28691
  case "array":
28782
28692
  return `${where} declares ${key}=[…] as a tag ARRAY. Write ONE quoted ` + `string instead: ${key}="order_date"` + (key === "merge_key" ? `, and separate a compound key with commas inside that one ` + `string — merge_key="order_id, region".` : `.`) + ` An array value is dropped from the annotation's scalar fields, so ` + `the key would otherwise read as undeclared.`;
@@ -28812,10 +28722,11 @@ function judgeSource(source) {
28812
28722
  for (const m of d.malformed) {
28813
28723
  out.push(malformedMessage(where, m.key, m.problem, m.detail));
28814
28724
  }
28815
- if (!d.incremental && (d.declaredWatermark || d.declaredMergeKey)) {
28725
+ if (!d.incremental && (d.declaredWatermark || d.declaredMergeKey || d.declaredLookback)) {
28816
28726
  const keys = [
28817
28727
  d.declaredWatermark ? "watermark=" : undefined,
28818
- d.declaredMergeKey ? "merge_key=" : undefined
28728
+ d.declaredMergeKey ? "merge_key=" : undefined,
28729
+ d.declaredLookback ? "lookback=" : undefined
28819
28730
  ].filter((k) => k !== undefined);
28820
28731
  out.push(`${where} declares ${keys.join(" and ")} but is not ${MODE}` + (d.refresh ? ` (it declares refresh=${JSON.stringify(d.refresh)})` : "") + `. These keys describe how an INCREMENTAL refresh advances the ` + `table and are ignored by a full rebuild. Either add ${MODE}, or ` + `remove the key — and if the key is inherited from a parent source, ` + `strip it with a negation (e.g. -watermark), since removing the ` + `parent's key is not an option from the child.`);
28821
28732
  }
@@ -28847,11 +28758,31 @@ function judgeSource(source) {
28847
28758
  if (d.watermarkInMergeKeys && d.watermark !== undefined) {
28848
28759
  out.push(`${where} declares merge_key= including the watermark dimension ` + `"${d.watermark.name}". Row identity must be independent of the ` + `watermark: a row restated with a LATER watermark value would not ` + `match its predecessor, so it would be inserted alongside the old ` + `row rather than replacing it — the failure merge_key= exists to ` + `prevent. List only the identity dimensions.`);
28849
28760
  }
28761
+ out.push(...lookbackRejections(d, where));
28850
28762
  if (d.calculateFields.length > 0) {
28851
28763
  unbuildable.push(`it declares ${MODE} but computes ` + `${quoteList([...new Set(d.calculateFields)])} with calculate:. A ` + `window function is not supported on an incremental source yet: a ` + `delta recomputes only rows inside its range, so a frame that reaches ` + `outside that range assigns already-materialized rows values that ` + `later data changes, below the range start where no delta ever ` + `rewrites them. Frames strictly BACKWARD along the watermark ordering ` + `are stable and will become legal; every other frame will not. Use ` + `refresh="full", or move the window computation into the query that ` + `reads this source (plain non-additive aggregates like ` + `count_distinct are fine: a delta recomputes whole output rows from ` + `full input and never merges partial aggregates)`);
28852
28764
  }
28853
28765
  return { invalid: out, unbuildable };
28854
28766
  }
28767
+ function lookbackRejections(d, where) {
28768
+ if (d.lookback === undefined)
28769
+ return [];
28770
+ const out = [];
28771
+ if (d.lookback.seconds !== undefined && d.lookback.seconds > MAX_LOOKBACK_SECONDS) {
28772
+ out.push(`${where} declares lookback=${JSON.stringify(d.lookback.text)}, ` + `longer than the most it takes, 365 days. Every refresh re-reads ` + `its whole lookback; to recompute that much history, rebuild the ` + `table (reseed) instead.`);
28773
+ }
28774
+ if (d.lookback.seconds === undefined) {
28775
+ out.push(`${where} declares lookback=${JSON.stringify(d.lookback.text)}, ` + `which is not a duration. Write a positive whole number and one ` + `unit of ${DURATION_UNIT_TEXT}, such as lookback="2 days" or ` + `lookback="36h".`);
28776
+ }
28777
+ if (!d.declaredMergeKey) {
28778
+ out.push(`${where} declares lookback= without merge_key=. lookback= re-reads ` + `rows the table already holds, below the newest stored ` + `watermark, and merge_key= is what matches each one to its stored ` + `copy instead of applying it again. Declare merge_key= with the ` + `row's identity dimensions, or remove lookback=.`);
28779
+ }
28780
+ const watermark = d.watermark;
28781
+ if (watermark !== undefined && watermark.kind !== "unresolved" && watermark.malloyType !== "date" && watermark.malloyType !== "timestamp") {
28782
+ out.push(`${where} declares lookback= with watermark="${watermark.name}", of ` + `type ${watermark.malloyType}. lookback= is a span of time, so it ` + `needs a date or timestamp watermark; a ${watermark.malloyType} ` + `watermark's delta already starts at the newest value the source ` + `held at the last refresh. Remove lookback=.`);
28783
+ }
28784
+ return out;
28785
+ }
28855
28786
  function recordedLineage(d) {
28856
28787
  const watermark = d.watermark;
28857
28788
  return [
@@ -28910,9 +28841,11 @@ function incrementalPolicyAdvisories(sources) {
28910
28841
  }
28911
28842
  return warnings;
28912
28843
  }
28913
- var MODE = `refresh="incremental"`, INCREMENTAL_NO_MERGE_KEY_CODE = "persist-incremental-no-merge-key", INCREMENTAL_SHARED_ADDRESS_CODE = "persist-incremental-shared-address";
28844
+ var MODE = `refresh="incremental"`, MAX_LOOKBACK_SECONDS, INCREMENTAL_NO_MERGE_KEY_CODE = "persist-incremental-no-merge-key", INCREMENTAL_SHARED_ADDRESS_CODE = "persist-incremental-shared-address";
28914
28845
  var init_incremental_policy = __esm(() => {
28915
28846
  init_dialect();
28847
+ init_freshness();
28848
+ MAX_LOOKBACK_SECONDS = 365 * 86400;
28916
28849
  });
28917
28850
 
28918
28851
  // src/service/materialization/domain/table_plans.ts
@@ -29302,7 +29235,6 @@ function persistDeclarationProblems(annotations) {
29302
29235
  }
29303
29236
  var ENV_REFERENCE_REASON, PERSIST_LINE_PATTERN, UNQUOTED_NAME_PATTERN, QUOTED_NAME_VALUE_PATTERN, SAFE_NAME_PATH;
29304
29237
  var init_persist_annotation_validation = __esm(() => {
29305
- init_errors2();
29306
29238
  init_annotation_reader();
29307
29239
  init_motly();
29308
29240
  init_table_name();
@@ -29310,7 +29242,7 @@ var init_persist_annotation_validation = __esm(() => {
29310
29242
  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";
29311
29243
  PERSIST_LINE_PATTERN = /^\s*#@\s+persist\b/;
29312
29244
  UNQUOTED_NAME_PATTERN = /(?<![.\w])name\s*=\s*(?!["'])/;
29313
- QUOTED_NAME_VALUE_PATTERN = /(?<![.\w])name\s*=\s*(["'])(.*?)\1/g;
29245
+ QUOTED_NAME_VALUE_PATTERN = /(?<![.\w])name\s*=\s*(["'])((?:\\.|(?!\1)[^\\])*)\1/g;
29314
29246
  SAFE_NAME_PATH = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
29315
29247
  });
29316
29248
 
@@ -31118,7 +31050,7 @@ var init_persisted_query = __esm(() => {
31118
31050
  init_declaration();
31119
31051
  init_persist_annotation_validation();
31120
31052
  PERSIST_LINE = /^\s*#@\s*persist\b/;
31121
- INCREMENTAL_KEYS = ["watermark", "merge_key"];
31053
+ INCREMENTAL_KEYS = ["watermark", "merge_key", "lookback"];
31122
31054
  });
31123
31055
 
31124
31056
  // src/service/materialization/plan/persisted_view.ts
@@ -31269,6 +31201,25 @@ function persistedViewRefusalFinding(refusal, model) {
31269
31201
  refused: resultRefusalKey(persistedViewBuildName(refusal.sourceName, refusal.viewName), splitSourceID(refusal.sourceID)?.url ?? "", outcome.refused, refusal.storage)
31270
31202
  };
31271
31203
  }
31204
+ function persistedViewReadsGivenRefusal(plan) {
31205
+ return {
31206
+ sourceID: plan.sourceID,
31207
+ sourceName: plan.sourceName,
31208
+ viewName: plan.viewName,
31209
+ reason: READS_A_GIVEN,
31210
+ outcome: { refused: "reads_given" },
31211
+ ...plan.storage !== undefined ? { storage: plan.storage } : {}
31212
+ };
31213
+ }
31214
+ function persistedQueryReadsGivenRefusal(plan) {
31215
+ return {
31216
+ queryName: plan.queryName,
31217
+ reason: READS_A_GIVEN,
31218
+ refusal: "reads_given",
31219
+ declaringURL: plan.declaringURL,
31220
+ ...plan.storage !== undefined ? { storage: plan.storage } : {}
31221
+ };
31222
+ }
31272
31223
  function resultRefusalKey(buildSourceName, declaringURL, reason, storage) {
31273
31224
  return refusalKey(`${buildSourceName}@${persistedViewCompanionHref(declaringURL)}`, buildSourceName, reason, tierOf(storage));
31274
31225
  }
@@ -31347,7 +31298,7 @@ function persistedQueryRefusalFinding(refusal, model) {
31347
31298
  function persistedQueryRefusalKey(queryName, declaringURL, reason, storage) {
31348
31299
  return resultRefusalKey(persistedQueryBuildName(queryName), declaringURL, reason, storage);
31349
31300
  }
31350
- var PERSIST_VIEW_NOT_BUILT = "persist-view-not-built";
31301
+ 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";
31351
31302
  var init_persisted_view = __esm(() => {
31352
31303
  init_annotation_reader();
31353
31304
  init_declared_notes();
@@ -31377,6 +31328,29 @@ var init_storage_table_path = __esm(() => {
31377
31328
  init_dialect();
31378
31329
  });
31379
31330
 
31331
+ // src/service/materialization/domain/placement.ts
31332
+ function storageWritable(mode) {
31333
+ return mode !== "off";
31334
+ }
31335
+ function storageServes(mode) {
31336
+ return mode === "on";
31337
+ }
31338
+ function instructionTier(instruction, mode) {
31339
+ return instruction.destination && storageWritable(mode) ? "storage" : "database";
31340
+ }
31341
+ function instructsUnwritableDestination(instruction, mode) {
31342
+ return !!instruction.destination && !storageWritable(mode);
31343
+ }
31344
+ function readTier(facts) {
31345
+ if (!facts.storageBound) {
31346
+ return facts.declaredStorage ? "storage" : "database";
31347
+ }
31348
+ return facts.servedCopy && !facts.storageFresh && facts.databaseFresh ? "database" : "storage";
31349
+ }
31350
+ function declaredDestination(declared, mode) {
31351
+ return storageWritable(mode) ? declared : undefined;
31352
+ }
31353
+
31380
31354
  // src/service/http_retry.ts
31381
31355
  function publicMessage(error) {
31382
31356
  const own = error?.publicMessage;
@@ -32871,7 +32845,7 @@ function deriveColumns(persistSource) {
32871
32845
  } catch (err) {
32872
32846
  logger.warn("Failed to derive columns for persist source", {
32873
32847
  sourceID: persistSource.sourceID,
32874
- error: errMessage(err)
32848
+ code: errorCodeOf(err)
32875
32849
  });
32876
32850
  return [];
32877
32851
  }
@@ -32888,9 +32862,9 @@ function declaresEmptyStorage(persistSource) {
32888
32862
  return tag !== undefined && "refused" in placementOf(tag, "persist");
32889
32863
  }
32890
32864
  var init_persist_source_fields = __esm(() => {
32865
+ init_error_code();
32891
32866
  init_declaration();
32892
32867
  init_logger();
32893
- init_utils();
32894
32868
  });
32895
32869
 
32896
32870
  // src/service/materialization/plan/addressing.ts
@@ -33029,7 +33003,7 @@ function compilerBuildId(source, target) {
33029
33003
  function addressDestination(source) {
33030
33004
  if (!getPersistAddressIncludesDestination())
33031
33005
  return;
33032
- if (getPersistStorageMode() === "off")
33006
+ if (!storageWritable(getPersistStorageMode()))
33033
33007
  return;
33034
33008
  try {
33035
33009
  return declaredStorage(source);
@@ -33159,7 +33133,7 @@ function foldDistinctTableNames(plan, storedColumns) {
33159
33133
  return folds;
33160
33134
  }
33161
33135
  function storedTierOf(source) {
33162
- if (getPersistStorageMode() === "off")
33136
+ if (!storageWritable(getPersistStorageMode()))
33163
33137
  return "";
33164
33138
  try {
33165
33139
  return declaredStorage(source)?.trim() ?? "";
@@ -33218,6 +33192,9 @@ var init_addressing = __esm(() => {
33218
33192
  testAddresses = new WeakMap;
33219
33193
  });
33220
33194
 
33195
+ // src/service/materialization/domain/vocabulary.ts
33196
+ var init_vocabulary = () => {};
33197
+
33221
33198
  // src/service/materialization/domain/gate_policy.ts
33222
33199
  function ownRowLevelGate(t) {
33223
33200
  return t.gate?.rowLevel === true && t.gate.attributed && !t.gate.inheritedRowFilter;
@@ -33272,6 +33249,7 @@ function answerKeepsGates(leg, tablesRead, s, ctx) {
33272
33249
  }
33273
33250
  var ROWS, GATE_LEGS, SERVING_GATE_CONTEXT, INEXACT_GATE_TYPE;
33274
33251
  var init_gate_policy = __esm(() => {
33252
+ init_vocabulary();
33275
33253
  ROWS = {
33276
33254
  persist: (t) => persistKeepsGates(t),
33277
33255
  materialize: (t, s) => materializedKeepsGates(t, s),
@@ -33279,7 +33257,11 @@ var init_gate_policy = __esm(() => {
33279
33257
  rollup: (t, s) => !t.v1 && t.baseGateProven === true && (t.gate?.lockOnly === true || s.gatedSources || ownRowLevelGate(t)),
33280
33258
  view: () => false
33281
33259
  };
33282
- GATE_LEGS = ["view", "rollup", "served"];
33260
+ GATE_LEGS = [
33261
+ "view",
33262
+ "rollup",
33263
+ "served"
33264
+ ];
33283
33265
  SERVING_GATE_CONTEXT = {
33284
33266
  databaseReadsKeepGates: true
33285
33267
  };
@@ -33492,6 +33474,76 @@ function buildReadsCurrentTime(persistSource) {
33492
33474
  return true;
33493
33475
  }
33494
33476
  }
33477
+ function storedAsOfBuild(persistSource, kind) {
33478
+ if (kind !== "persist" && kind !== "view")
33479
+ return false;
33480
+ let def;
33481
+ try {
33482
+ def = sourceDefOf(persistSource);
33483
+ } catch {
33484
+ return false;
33485
+ }
33486
+ if (def === null || typeof def !== "object")
33487
+ return false;
33488
+ return buildReadsCurrentTime(persistSource);
33489
+ }
33490
+ function currentTimeReadsOf(persistSource, limit = 3) {
33491
+ let relation;
33492
+ try {
33493
+ const def = sourceDefOf(persistSource);
33494
+ if (def === null || typeof def !== "object")
33495
+ return [];
33496
+ const query = def.query;
33497
+ if (query !== null && typeof query === "object") {
33498
+ relation = query;
33499
+ } else {
33500
+ const {
33501
+ filterList: _readTimeFilters,
33502
+ fields: _readTimeFields,
33503
+ ...rest
33504
+ } = def;
33505
+ relation = rest;
33506
+ }
33507
+ } catch {
33508
+ return [];
33509
+ }
33510
+ const out = [];
33511
+ const seen = new WeakSet;
33512
+ const walk = (node, depth) => {
33513
+ if (out.length >= limit || depth > MAX_WALK_DEPTH2)
33514
+ return;
33515
+ if (node === null || typeof node !== "object")
33516
+ return;
33517
+ if (seen.has(node))
33518
+ return;
33519
+ seen.add(node);
33520
+ if (Array.isArray(node)) {
33521
+ for (const item of node)
33522
+ walk(item, depth + 1);
33523
+ return;
33524
+ }
33525
+ const record = node;
33526
+ const e = record.e;
33527
+ if (e !== undefined && readsCurrentTime(e)) {
33528
+ const code = record.code;
33529
+ const name = record.as ?? record.name;
33530
+ const said = record.node === "filterCondition" && typeof code === "string" ? `\`where: ${code}\`` : typeof name === "string" && record.join === undefined ? `the field \`${name}\`` : undefined;
33531
+ if (said !== undefined) {
33532
+ if (!out.includes(said))
33533
+ out.push(said);
33534
+ return;
33535
+ }
33536
+ }
33537
+ for (const [key, value] of Object.entries(record)) {
33538
+ if (key === "at" || key === "location" || key === "annotations" || key === "stableFilter") {
33539
+ continue;
33540
+ }
33541
+ walk(value, depth + 1);
33542
+ }
33543
+ };
33544
+ walk(relation, 0);
33545
+ return out;
33546
+ }
33495
33547
  function queryReadsCurrentTime(query, depth) {
33496
33548
  if (depth > MAX_WALK_DEPTH2)
33497
33549
  return true;
@@ -33850,14 +33902,66 @@ function readsCurrentTime(node, depth = 0) {
33850
33902
  const record = node;
33851
33903
  if (record.node === "now")
33852
33904
  return true;
33905
+ if (record.node === "filterMatch") {
33906
+ return filterMatchReadsCurrentTime(record, depth);
33907
+ }
33908
+ if (record.node === "filterLiteral") {
33909
+ return relativeTemporalFilter(record.filterSrc, false);
33910
+ }
33853
33911
  for (const [key, value] of Object.entries(record)) {
33854
- if (key === "at" || key === "location" || key === "annotations")
33912
+ if (key === "at" || key === "location" || key === "annotations" || key === "stableFilter") {
33855
33913
  continue;
33914
+ }
33856
33915
  if (readsCurrentTime(value, depth + 1))
33857
33916
  return true;
33858
33917
  }
33859
33918
  return false;
33860
33919
  }
33920
+ function filterMatchReadsCurrentTime(record, depth) {
33921
+ const kids = record.kids ?? {};
33922
+ if (readsCurrentTime(kids.expr, depth + 1))
33923
+ return true;
33924
+ const filter = kids.filterExpr;
33925
+ if (filter?.node !== "filterLiteral") {
33926
+ return readsCurrentTime(filter, depth + 1);
33927
+ }
33928
+ if (typeof record.dataType !== "string" || !TEMPORAL_FILTER_TYPES.has(record.dataType)) {
33929
+ return false;
33930
+ }
33931
+ return relativeTemporalFilter(filter.filterSrc, true);
33932
+ }
33933
+ function relativeTemporalFilter(src, unparseable) {
33934
+ if (typeof src !== "string")
33935
+ return unparseable;
33936
+ if (src.trim() === "")
33937
+ return false;
33938
+ let parsed;
33939
+ try {
33940
+ parsed = import_malloy_filter2.TemporalFilterExpression.parse(src).parsed;
33941
+ } catch {
33942
+ return unparseable;
33943
+ }
33944
+ if (parsed === null || parsed === undefined)
33945
+ return unparseable;
33946
+ return temporalFilterIsRelative(parsed, 0);
33947
+ }
33948
+ function temporalFilterIsRelative(node, depth) {
33949
+ if (depth > MAX_WALK_DEPTH2)
33950
+ return true;
33951
+ if (node === null || typeof node !== "object")
33952
+ return false;
33953
+ if (Array.isArray(node)) {
33954
+ return node.some((item) => temporalFilterIsRelative(item, depth + 1));
33955
+ }
33956
+ const record = node;
33957
+ if (typeof record.operator === "string" && RELATIVE_TEMPORAL_OPERATORS.has(record.operator)) {
33958
+ return true;
33959
+ }
33960
+ if (typeof record.moment === "string" && record.moment !== "literal") {
33961
+ return true;
33962
+ }
33963
+ return Object.values(record).some((value) => temporalFilterIsRelative(value, depth + 1));
33964
+ }
33861
33965
  function readNow(e) {
33862
33966
  if (!e || typeof e !== "object")
33863
33967
  return;
@@ -34017,13 +34121,14 @@ function fieldsDependingOn(fields, reads, depth = 0) {
34017
34121
  }
34018
34122
  return out;
34019
34123
  }
34020
- var MAX_WALK_DEPTH2 = 200, STAGE_PATH_SKIPPED_KEYS, JOIN_ONLY_KEYS, MAX_JOIN_DEPTH = 4, COMPARISONS, MIRROR, FIELD_PATH_SKIPPED_KEYS;
34124
+ 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;
34021
34125
  var init_persist_dynamic_terms = __esm(() => {
34022
34126
  init_declaration();
34023
34127
  init_given();
34024
34128
  init_probe_compiler();
34025
34129
  init_array_query();
34026
34130
  init_read_time_terms();
34131
+ import_malloy_filter2 = __toESM(require_dist());
34027
34132
  STAGE_PATH_SKIPPED_KEYS = new Set([
34028
34133
  "at",
34029
34134
  "location",
@@ -34037,6 +34142,16 @@ var init_persist_dynamic_terms = __esm(() => {
34037
34142
  "refSummary",
34038
34143
  "referenceID"
34039
34144
  ];
34145
+ TEMPORAL_FILTER_TYPES = new Set([
34146
+ "date",
34147
+ "timestamp",
34148
+ "timestamptz"
34149
+ ]);
34150
+ RELATIVE_TEMPORAL_OPERATORS = new Set([
34151
+ "last",
34152
+ "next",
34153
+ "in_last"
34154
+ ]);
34040
34155
  COMPARISONS = new Set([">=", ">", "<", "<="]);
34041
34156
  MIRROR = {
34042
34157
  ">=": "<=",
@@ -34047,6 +34162,19 @@ var init_persist_dynamic_terms = __esm(() => {
34047
34162
  FIELD_PATH_SKIPPED_KEYS = new Set(["at", "location", "annotations"]);
34048
34163
  });
34049
34164
 
34165
+ // src/service/materialization/domain/compiled_build_plan.ts
34166
+ function* sourcesInBuildOrder(build, tables) {
34167
+ for (const sourceID of build.order) {
34168
+ const source = tables[sourceID]?.source;
34169
+ if (source)
34170
+ yield source;
34171
+ }
34172
+ }
34173
+ function materializePlansOf(tables) {
34174
+ return Object.fromEntries(Object.entries(tables).flatMap(([sourceID, table]) => table.materialize ? [[sourceID, table.materialize]] : []));
34175
+ }
34176
+ var EVERY_SOURCE = "*";
34177
+
34050
34178
  // src/service/materialization/domain/key_check.ts
34051
34179
  function requireUnique(verdict) {
34052
34180
  return verdict === "unique";
@@ -34945,6 +35073,62 @@ var init_composite_row_filter = __esm(() => {
34945
35073
  init_authorize_routes();
34946
35074
  });
34947
35075
 
35076
+ // src/service/materialization/domain/live_big_integers.ts
35077
+ function liveRoundsBigIntegersAsPostgres(dialect) {
35078
+ return capabilitiesOf(dialect).liveRoundsBigIntegersMeasured;
35079
+ }
35080
+ function roundedAsLive(value) {
35081
+ const exact = typeof value === "bigint" || typeof value === "string" && /^-?\d+$/.test(value);
35082
+ if (!exact)
35083
+ return value;
35084
+ const nearest = Number(value);
35085
+ if (/e/i.test(String(nearest)))
35086
+ return nearest;
35087
+ return typeof value === "bigint" ? BigInt(String(nearest)) : String(nearest);
35088
+ }
35089
+ function roundValue(value, field) {
35090
+ if (value === null || value === undefined)
35091
+ return value;
35092
+ if (field.type === "number") {
35093
+ return field.numberType === "bigint" ? roundedAsLive(value) : value;
35094
+ }
35095
+ if (field.type === "array" && Array.isArray(value)) {
35096
+ if (field.fields) {
35097
+ for (const item of value)
35098
+ roundRecord(item, field);
35099
+ } else if (field.elementTypeDef) {
35100
+ const element = field.elementTypeDef;
35101
+ return value.map((item) => roundValue(item, element));
35102
+ }
35103
+ return value;
35104
+ }
35105
+ if (field.type === "record" && field.fields && typeof value === "object") {
35106
+ roundRecord(value, field);
35107
+ }
35108
+ return value;
35109
+ }
35110
+ function holdsBigInteger(field) {
35111
+ return field.numberType === "bigint" || (field.fields ?? []).some(holdsBigInteger) || field.elementTypeDef !== undefined && holdsBigInteger(field.elementTypeDef);
35112
+ }
35113
+ function roundRecord(row, struct) {
35114
+ for (const field of struct.fields ?? []) {
35115
+ const name = field.as ?? field.name;
35116
+ if (name in row)
35117
+ row[name] = roundValue(row[name], field);
35118
+ }
35119
+ }
35120
+ function roundBigIntegersAsLive(result) {
35121
+ const { structs, result: rows } = result._queryResult;
35122
+ const struct = structs[structs.length - 1];
35123
+ if (!struct || !holdsBigInteger(struct))
35124
+ return;
35125
+ for (const row of rows)
35126
+ roundRecord(row, struct);
35127
+ }
35128
+ var init_live_big_integers = __esm(() => {
35129
+ init_dialect();
35130
+ });
35131
+
34948
35132
  // src/service/quoting.ts
34949
35133
  function bareTableName(tableName) {
34950
35134
  const lastDot = tableName.lastIndexOf(".");
@@ -35379,9 +35563,13 @@ function liveKeepsBigIntegers(dialect) {
35379
35563
  return true;
35380
35564
  }
35381
35565
  }
35566
+ function storageReadsBigIntegers(dialect) {
35567
+ return liveKeepsBigIntegers(dialect) || liveRoundsBigIntegersAsPostgres(dialect);
35568
+ }
35382
35569
  function bigIntegerReads(schema, fields, options) {
35383
- if (!options.database && !liveKeepsBigIntegers(options.dialect))
35570
+ if (!options.database && !storageReadsBigIntegers(options.dialect)) {
35384
35571
  return [];
35572
+ }
35385
35573
  const byName = new Map;
35386
35574
  const declared = [];
35387
35575
  const fieldOf = (f) => f ?? {};
@@ -35430,7 +35618,7 @@ function bigIntegerReads(schema, fields, options) {
35430
35618
  return out;
35431
35619
  }
35432
35620
  function bigIntegerReadOf(field, column, options) {
35433
- if (!options.database && !liveKeepsBigIntegers(options.dialect)) {
35621
+ if (!options.database && !storageReadsBigIntegers(options.dialect)) {
35434
35622
  return;
35435
35623
  }
35436
35624
  if (!isBigIntegerField(field))
@@ -35697,6 +35885,7 @@ function canonicalStoredSchema(schema, names) {
35697
35885
  var STORED_COLUMN_TYPE_MISMATCH_CODE = "storage-column-type-mismatch", BUILD_CAST_TARGETS, CHECKED_TYPES, EXACT_INTEGER_STORAGE_TYPE = "DECIMAL(38,0)", INTEGER_TYPES, TIMESTAMPTZ_TYPES, NAIVE_TIMESTAMP_TYPES, HUGEINT_EXACT;
35698
35886
  var init_stored_column_types = __esm(() => {
35699
35887
  init_dialect();
35888
+ init_live_big_integers();
35700
35889
  init_malloy_text();
35701
35890
  init_quoting();
35702
35891
  BUILD_CAST_TARGETS = {
@@ -37436,7 +37625,7 @@ function declarationRefusal(decl, facts, ctx) {
37436
37625
  measure: decl.measure
37437
37626
  };
37438
37627
  }
37439
- 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];
37628
+ 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];
37440
37629
  if (timeRead) {
37441
37630
  return unservable("current_time", decl, `${timeRead}, which a rollup would fix at build time while a live query reads it again at every read`);
37442
37631
  }
@@ -37724,6 +37913,15 @@ function planModelRollups(map, ctx, declaredHere) {
37724
37913
  }
37725
37914
  return { plans, refused };
37726
37915
  }
37916
+ function rollupReadsGivenRefusal(plan, source) {
37917
+ return {
37918
+ tier: "unservable",
37919
+ code: ROLLUP_NOT_BUILT_CODE,
37920
+ 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.",
37921
+ sourceName: plan.baseSourceName,
37922
+ refused: refusalKey(source.sourceID, source.name, "reads_given", tierOf(plan.storage))
37923
+ };
37924
+ }
37727
37925
  function rollupRefusalFinding(refusal, model) {
37728
37926
  return {
37729
37927
  route: ROLLUP_ROUTE,
@@ -38050,6 +38248,13 @@ function referencesAuthorize(persistSource) {
38050
38248
  return true;
38051
38249
  }
38052
38250
  }
38251
+ function irCarriesAGate(def) {
38252
+ try {
38253
+ return walkForAuthorize(def, new WeakSet, 0);
38254
+ } catch {
38255
+ return true;
38256
+ }
38257
+ }
38053
38258
  function isAuthorizeAnnotation(text) {
38054
38259
  try {
38055
38260
  return parseAuthorizeAnnotation(text) !== null;
@@ -38286,11 +38491,38 @@ function assertBuildReadsNoCurrentTime(source, plan) {
38286
38491
  return;
38287
38492
  if (!buildReadsCurrentTime(source))
38288
38493
  return;
38494
+ const why = currentTimeRefusalCause(source, plan);
38495
+ if (why === undefined)
38496
+ return;
38289
38497
  throw new MaterializationEligibilityError({
38290
38498
  reason: "current_time",
38291
- 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.`
38499
+ 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).`
38292
38500
  });
38293
38501
  }
38502
+ function currentTimeRefusalCause(source, plan) {
38503
+ if (referencesAuthorize(source)) {
38504
+ return "it is protected by an #(authorize) or #(access_filter) gate, whose " + "decision a table as of its build would freeze";
38505
+ }
38506
+ if (deriveAnnotationFields(source).refresh === "incremental") {
38507
+ return "it refreshes incrementally, and a delta never re-reads the rows " + "its window has passed";
38508
+ }
38509
+ if (currentTimeAccessInput(source, plan)) {
38510
+ 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";
38511
+ }
38512
+ return;
38513
+ }
38514
+ function currentTimeAccessInput(source, plan) {
38515
+ const admitted = admitGivenPositions(source);
38516
+ if (!admitted.ok)
38517
+ return true;
38518
+ if (admitted.terms.length > 0 || (admitted.joinedTerms ?? []).length > 0) {
38519
+ return true;
38520
+ }
38521
+ const reads = plan?.accessReads;
38522
+ if (reads === undefined)
38523
+ return true;
38524
+ return reads.includes(source.sourceID) || reads.includes(EVERY_SOURCE);
38525
+ }
38294
38526
  var READ_ONLY_DIALECTS, MAX_AUTHORIZE_WALK_DEPTH = 200;
38295
38527
  var init_materialization_eligibility = __esm(() => {
38296
38528
  init_config2();
@@ -38762,7 +38994,8 @@ var init_build_file_generator = __esm(() => {
38762
38994
  "storage",
38763
38995
  "refresh",
38764
38996
  "watermark",
38765
- "merge_key"
38997
+ "merge_key",
38998
+ "lookback"
38766
38999
  ];
38767
39000
  });
38768
39001
 
@@ -39930,7 +40163,7 @@ var init_materialize_plan = __esm(() => {
39930
40163
  "number",
39931
40164
  "string"
39932
40165
  ]);
39933
- INCREMENTAL_KEYS2 = ["refresh", "watermark", "merge_key"];
40166
+ INCREMENTAL_KEYS2 = ["refresh", "watermark", "merge_key", "lookback"];
39934
40167
  });
39935
40168
 
39936
40169
  // src/service/materialization/plan/eligibility_collect.ts
@@ -40136,7 +40369,8 @@ function withoutSources(compiled, findings, drop) {
40136
40369
  function tierGateInputs(compiled) {
40137
40370
  return {
40138
40371
  tables: compiled.tables,
40139
- connectionTypes: compiled.connectionTypes
40372
+ connectionTypes: compiled.connectionTypes,
40373
+ accessReads: compiled.accessReads
40140
40374
  };
40141
40375
  }
40142
40376
  function collectSourceEligibility(compiled, verdicts = planVerdicts(compiled)) {
@@ -40176,8 +40410,8 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
40176
40410
  logger.warn("Dropping a refused database source: its content address could not be computed", {
40177
40411
  sourceID,
40178
40412
  sourceName: source.name,
40179
- refusal: errMessage(err),
40180
- error: errMessage(idErr)
40413
+ reason: errorCodeOf(err),
40414
+ code: errorCodeOf(idErr)
40181
40415
  });
40182
40416
  continue;
40183
40417
  }
@@ -40189,7 +40423,7 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
40189
40423
  try {
40190
40424
  sourceEntityId = planAddressOf(compiled, sourceID);
40191
40425
  } catch (err) {
40192
- logger.warn("Dropping an eligible database source: its content address could not be computed", { sourceID, sourceName: source.name, error: errMessage(err) });
40426
+ logger.warn("Dropping an eligible database source: its content address could not be computed", { sourceID, sourceName: source.name, code: errorCodeOf(err) });
40193
40427
  continue;
40194
40428
  }
40195
40429
  if (!(sourceEntityId in refused)) {
@@ -40342,6 +40576,7 @@ function databaseRefusalsByAddress(compiled, verdicts, include) {
40342
40576
  }
40343
40577
  var EligibilityCheckFailed;
40344
40578
  var init_eligibility_collect = __esm(() => {
40579
+ init_error_code();
40345
40580
  init_errors2();
40346
40581
  init_storage_table_path();
40347
40582
  init_table_name();
@@ -40430,10 +40665,10 @@ function planCollisions(plan, materializePlans, versionScoped) {
40430
40665
  }
40431
40666
  return out;
40432
40667
  }
40433
- function incrementalPolicySourcesOf(plan, declarations, materializePlans, persistedViews = new Map) {
40668
+ function incrementalPolicySourcesOf(plan, declarations, materializePlans, persistedViews = {}) {
40434
40669
  return Object.entries(plan?.sources ?? {}).filter(([sourceID]) => declarations[sourceID]).map(([sourceID, source]) => ({
40435
- ...persistedViews.get(sourceID) ?? { sourceName: source.name },
40436
- invalidCode: persistedViews.has(sourceID) ? PERSIST_VIEW_INVALID_CODE : materializePlans?.[sourceID] ? MATERIALIZE_INVALID_CODE : PERSIST_INVALID_CODE,
40670
+ ...persistedViews[sourceID] ?? { sourceName: source.name },
40671
+ invalidCode: persistedViews[sourceID] ? PERSIST_VIEW_INVALID_CODE : materializePlans?.[sourceID] ? MATERIALIZE_INVALID_CODE : PERSIST_INVALID_CODE,
40437
40672
  ...source.modelPath ? { modelPath: source.modelPath } : {},
40438
40673
  ...source.dialect ? { dialect: source.dialect } : {},
40439
40674
  ...source.annotationFields?.storage ? { storageDestination: source.annotationFields.storage } : {},
@@ -40448,15 +40683,27 @@ function collisionGateLines(collisions) {
40448
40683
  return collisions.map((c) => codedLine(c.enforced, MATERIALIZATION_TABLE_COLLISION_CODE));
40449
40684
  }
40450
40685
  function loadGateText(gated, judgement) {
40451
- return [
40686
+ return withNameProblems(gated.modelGateLines?.nameProblems ?? [], [
40452
40687
  ...invalidFindingLines(gated.annotationFindings.map((f) => relaxedCollision(f, judgement.enforceCollisions))),
40453
40688
  ...judgement.enforceCollisions ? collisionGateLines(planCollisions(gated.plan, gated.materializePlans, judgement.versionScoped)) : [],
40454
- ...incrementalGateLines(incrementalPolicySourcesOf(gated.plan, gated.incrementalDeclarations, gated.materializePlans, judgement.persistedViews)),
40689
+ ...incrementalGateLines(incrementalPolicySourcesOf(gated.plan, gated.incrementalDeclarations, gated.materializePlans, gated.persistedViews)),
40455
40690
  ...gated.modelGateLines?.preaggregate ?? [],
40456
40691
  ...gated.modelGateLines?.nearMiss ?? []
40457
- ].join(`
40692
+ ]);
40693
+ }
40694
+ function withNameProblems(problems, lines) {
40695
+ const unsafe = problems.flatMap((p) => p.unsafeValue === undefined ? [] : [p.unsafeValue, unescapedTagValue(p.unsafeValue)].map((value) => `its name= "${value}" is not a plain identifier path`));
40696
+ return [
40697
+ ...problems.map((p) => p.line),
40698
+ ...lines.filter(Boolean).join(`
40699
+ `).split(`
40700
+ `).filter((line) => !unsafe.some((u) => line.includes(u)))
40701
+ ].filter(Boolean).join(`
40458
40702
  `);
40459
40703
  }
40704
+ function unescapedTagValue(raw) {
40705
+ return raw.replace(/\\(.)/g, "$1");
40706
+ }
40460
40707
  function preaggregateViolationCode(code) {
40461
40708
  if (code === "unknown_key")
40462
40709
  return "rollup-unknown-key";
@@ -40682,6 +40929,177 @@ var init_annotation_near_miss = __esm(() => {
40682
40929
  ]);
40683
40930
  });
40684
40931
 
40932
+ // src/materialization_metrics.ts
40933
+ function routeLegOf(kind) {
40934
+ return kind === "served" ? "materialized" : kind;
40935
+ }
40936
+ function recordScheduledFire(outcome) {
40937
+ scheduledFireCounter().add(1, { outcome });
40938
+ }
40939
+ function recordMaterializationRun(mode, outcome, durationMs) {
40940
+ runCounter().add(1, { mode, outcome });
40941
+ runDuration().record(durationMs, { mode, outcome });
40942
+ }
40943
+ function recordBuildOutcome(labels) {
40944
+ buildCounter().add(1, {
40945
+ kind: labels.kind,
40946
+ tier: labels.tier,
40947
+ outcome: labels.outcome,
40948
+ failure_class: labels.outcome === "failed" ? labels.failureClass : "none"
40949
+ });
40950
+ }
40951
+ function recordBuildDuration(durationMs, labels) {
40952
+ buildDuration().record(durationMs, {
40953
+ kind: labels.kind,
40954
+ tier: labels.tier,
40955
+ method: labels.method
40956
+ });
40957
+ }
40958
+ function recordBuildReadBytes(bytes, tier) {
40959
+ if (typeof bytes !== "number" || !(bytes > 0))
40960
+ return;
40961
+ buildReadBytes().record(bytes, { tier });
40962
+ }
40963
+ function recordAnnotationFindings(warnings) {
40964
+ for (const { code, severity } of warnings) {
40965
+ if (!code)
40966
+ continue;
40967
+ annotationFindingsCounter().add(1, {
40968
+ code,
40969
+ outcome: severity === "error" ? "invalid" : "not_built"
40970
+ });
40971
+ }
40972
+ }
40973
+ function recordIncrementalStep(step, reason) {
40974
+ incrementalStepCounter().add(1, reason ? { step, reason } : { step });
40975
+ }
40976
+ function recordBuildPlanComputeDuration(durationMs, computedIn) {
40977
+ buildPlanComputeDuration().record(durationMs, { computed_in: computedIn });
40978
+ }
40979
+ function recordBuildPlanComputeFailed() {
40980
+ buildPlanComputeFailedCounter().add(1);
40981
+ }
40982
+ function recordAutoLoadOutcome(outcome) {
40983
+ autoLoadCounter().add(1, { outcome });
40984
+ }
40985
+ function recordConnectionDigestSkipped() {
40986
+ connectionDigestSkipCounter().add(1);
40987
+ }
40988
+ function recordDuplicateTargetSkipped() {
40989
+ duplicateTargetSkipCounter().add(1);
40990
+ }
40991
+ function recordSharedAddressInstructions() {
40992
+ sharedAddressInstructionCounter().add(1);
40993
+ }
40994
+ function recordTableCollision() {
40995
+ tableCollisionCounter().add(1);
40996
+ }
40997
+ function recordManifestBind(outcome) {
40998
+ servedCopyBindCounter().add(1, {
40999
+ scope: "manifest",
41000
+ outcome,
41001
+ reason: "none"
41002
+ });
41003
+ }
41004
+ function recordSourceBound() {
41005
+ servedCopyBindCounter().add(1, {
41006
+ scope: "source",
41007
+ outcome: "bound",
41008
+ reason: "none"
41009
+ });
41010
+ }
41011
+ function recordSourceDeclined(reason) {
41012
+ servedCopyBindCounter().add(1, {
41013
+ scope: "source",
41014
+ outcome: "declined",
41015
+ reason
41016
+ });
41017
+ }
41018
+ function recordServedCopyOutcome(outcome, reason) {
41019
+ servedCopyBindCounter().add(1, { scope: "source", outcome, reason });
41020
+ }
41021
+ function recordManifestBindDegraded() {
41022
+ manifestBindDegradedCounter().add(1);
41023
+ }
41024
+ function recordDropTables(outcome, tier, occasion) {
41025
+ dropTablesCounter().add(1, { outcome, tier, occasion });
41026
+ }
41027
+ function recordKeyCheck(kind, outcome) {
41028
+ keyCheckCounter().add(1, { kind, outcome });
41029
+ }
41030
+ function recordQueryRouteDuration(durationMs, leg) {
41031
+ queryRouteDuration().record(durationMs, { leg });
41032
+ }
41033
+ function recordStorageTableRetained() {
41034
+ storageTableRetainedCounter().add(1);
41035
+ }
41036
+ function recordAttributionSkipped(reason) {
41037
+ attributionSkippedCounter().add(1, { reason });
41038
+ }
41039
+ function recordEligibilityRefused(reason) {
41040
+ eligibilityRefusedCounter().add(1, { reason });
41041
+ }
41042
+ function recordStoredTypeFallback(kind) {
41043
+ serveShapeTypeFallbackCounter().add(1, { kind });
41044
+ }
41045
+ function recordStoredColumnTypeMismatch(stage, declared) {
41046
+ storedColumnTypeMismatchCounter().add(1, { stage, declared });
41047
+ }
41048
+ function recordQueryRoute(leg, outcome, reason) {
41049
+ queryRouteCounter().add(1, { leg, outcome, reason });
41050
+ }
41051
+ function recordChainedStorageBuild(outcome) {
41052
+ chainedStorageBuildCounter().add(1, { outcome });
41053
+ }
41054
+ function recordStaleUpstreamEntry(tier) {
41055
+ staleUpstreamEntryCounter().add(1, { tier });
41056
+ }
41057
+ 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;
41058
+ var init_materialization_metrics = __esm(() => {
41059
+ init_vocabulary();
41060
+ init_telemetry();
41061
+ BUILD_DURATION_BUCKETS_MS = [
41062
+ 100,
41063
+ 500,
41064
+ 1000,
41065
+ 5000,
41066
+ 15000,
41067
+ 60000,
41068
+ 300000,
41069
+ 900000,
41070
+ 3600000
41071
+ ];
41072
+ BUILD_READ_BYTES_BUCKETS = [1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000];
41073
+ runCounter = lazyCounter("publisher_materialization_runs_total", "Materialization builds completed. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
41074
+ runDuration = lazyHistogram("publisher_materialization_run_duration_ms", "Wall-clock duration of a materialization build. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
41075
+ 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.");
41076
+ 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 });
41077
+ 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 });
41078
+ 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).");
41079
+ 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.");
41080
+ buildPlanComputeDuration = lazyHistogram("publisher_materialization_build_plan_compute_duration_ms", "Wall-clock duration of compiling a package's build plan (Package.buildPlan).");
41081
+ 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.");
41082
+ autoLoadCounter = lazyCounter("publisher_materialization_auto_load_total", "Auto-run manifest auto-load attempts. Label: outcome ('success'|'failure').");
41083
+ connectionDigestSkipCounter = lazyCounter("publisher_materialization_connection_digest_skipped_total", "Connection digests skipped during build-plan compile because the connection did not resolve.");
41084
+ 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'.");
41085
+ 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.");
41086
+ 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.");
41087
+ 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.");
41088
+ 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.");
41089
+ 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}).");
41090
+ scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
41091
+ 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.");
41092
+ 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.");
41093
+ 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.");
41094
+ 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.");
41095
+ 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.");
41096
+ 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).");
41097
+ 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').");
41098
+ 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).");
41099
+ 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.");
41100
+ 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.");
41101
+ });
41102
+
40685
41103
  // src/service/materialization/plan/incremental_declaration.ts
40686
41104
  function safeTag(source) {
40687
41105
  try {
@@ -40794,6 +41212,13 @@ function resolveIncrementalDeclaration(source, annotationFields) {
40794
41212
  mergeKeys.push(resolveName(name, columns, aggregates));
40795
41213
  }
40796
41214
  }
41215
+ const rawLookback = readKey(tag, "lookback");
41216
+ if (rawLookback.malformed)
41217
+ malformed.push(rawLookback.malformed);
41218
+ const lookback = rawLookback.text === undefined ? undefined : {
41219
+ text: rawLookback.text,
41220
+ ...durationSeconds(rawLookback.text) !== undefined ? { seconds: durationSeconds(rawLookback.text) } : {}
41221
+ };
40797
41222
  const watermarkInMergeKeys = watermark !== undefined && mergeKeys.some((k) => k.name === watermark.name);
40798
41223
  const strategy = incremental && watermark !== undefined && watermark.kind === "dimension" ? mergeKeys.length > 0 ? "merge" : "range_replace" : undefined;
40799
41224
  const unknownKeys = [];
@@ -40811,6 +41236,8 @@ function resolveIncrementalDeclaration(source, annotationFields) {
40811
41236
  invalidRefresh,
40812
41237
  declaredWatermark: rawWatermark.declared,
40813
41238
  declaredMergeKey: rawMergeKey.declared,
41239
+ declaredLookback: rawLookback.declared,
41240
+ ...lookback ? { lookback } : {},
40814
41241
  watermark,
40815
41242
  watermarkOrderable,
40816
41243
  mergeKeys,
@@ -40828,6 +41255,7 @@ var REFRESH_MODES, ORDERABLE_TYPES;
40828
41255
  var init_incremental_declaration = __esm(() => {
40829
41256
  init_annotation_reader();
40830
41257
  init_declaration();
41258
+ init_freshness();
40831
41259
  init_persist_source_fields();
40832
41260
  init_persist_dynamic_terms();
40833
41261
  REFRESH_MODES = ["full", "incremental"];
@@ -41031,6 +41459,9 @@ async function compileInMemory(files, entry, connections, options = {}) {
41031
41459
  const model = await runtime.loadModel(new URL(entry), options.importBaseURL ? options : undefined).getModel();
41032
41460
  return { runtime, model };
41033
41461
  }
41462
+ function companionFailure(kind, error) {
41463
+ return { kind, error };
41464
+ }
41034
41465
  function companionOmissions(kind, planned) {
41035
41466
  const reason = COMPANION_FAILED[kind];
41036
41467
  return "sourceIDs" in planned ? omittedByID(planned.sourceIDs, reason) : omittedFromFile(planned.file, planned.names, reason);
@@ -41707,7 +42138,7 @@ async function tryCompileMaterializeCompanion(args) {
41707
42138
  const foreign = await crossFileParents(planned.plans, args, modelFile).catch((error) => {
41708
42139
  logger.warn("A model's extension tables could not be chained on parents in other files; they build over the raw chain", {
41709
42140
  modelPath: args.modelPath,
41710
- error: error instanceof Error ? error.message : String(error)
42141
+ code: errorCodeOf(error)
41711
42142
  });
41712
42143
  return { plans: planned.plans, parents: new Map };
41713
42144
  });
@@ -41732,12 +42163,9 @@ async function tryCompileMaterializeCompanion(args) {
41732
42163
  }
41733
42164
  return round.generated ? { generated: withStoredColumns(round.generated), refused } : { refused };
41734
42165
  } catch (error) {
41735
- logger.error("Failed to plan or compile the generated #(materialize) companion", {
41736
- modelPath: args.modelPath,
41737
- error: error instanceof Error ? error.message : String(error)
41738
- });
41739
42166
  return {
41740
42167
  refused,
42168
+ failure: companionFailure("materialize", error),
41741
42169
  omitted: companionOmissions("materialize", plannedIDs ? {
41742
42170
  sourceIDs: plannedIDs.filter((id) => !refused.some((r) => r.sourceID === id))
41743
42171
  } : { file: pathToFileURL8(modelFile).href, names: undefined })
@@ -41784,11 +42212,10 @@ async function unchainStoredChainsNotCompiling(round, compile, args, foreign = N
41784
42212
  const unstored = round.generated ? await storedChainsNotCompiling(round.generated, foreign.parents) : new Map;
41785
42213
  if (unstored.size === 0)
41786
42214
  return round;
41787
- for (const [sourceID, error] of unstored) {
42215
+ for (const sourceID of unstored.keys()) {
41788
42216
  logger.warn("A storage= extension table does not compile over its parent's stored table alone; it builds over the raw chain", {
41789
42217
  modelPath: args.modelPath,
41790
- sourceName: planOf(round.plans, sourceID)?.sourceName,
41791
- error
42218
+ sourceName: planOf(round.plans, sourceID)?.sourceName
41792
42219
  });
41793
42220
  }
41794
42221
  return compile(round.plans.map((p) => unstored.has(p.sourceID) ? withoutParent(p) : p));
@@ -42396,11 +42823,11 @@ function nextRound(error, plans, copies, ctx) {
42396
42823
  } : p);
42397
42824
  }
42398
42825
  if (plan?.buildsOver) {
42399
- 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 });
42826
+ 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) });
42400
42827
  return plans.map((p) => p === plan ? withoutParent(p) : p);
42401
42828
  }
42402
42829
  if (plan) {
42403
- 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 });
42830
+ 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) });
42404
42831
  ctx.refuse({
42405
42832
  sourceName: plan.sourceName,
42406
42833
  sourceID: plan.sourceID,
@@ -42415,7 +42842,7 @@ function nextRound(error, plans, copies, ctx) {
42415
42842
  return plans.filter((p) => p !== plan);
42416
42843
  }
42417
42844
  if (plans.some((p) => p.buildsOver)) {
42418
- 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 });
42845
+ 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) });
42419
42846
  return plans.map(withoutParent);
42420
42847
  }
42421
42848
  throw error.error;
@@ -42441,9 +42868,10 @@ async function crossFileParents(plans, args, modelFile) {
42441
42868
  const url = pathToFileURL8(file);
42442
42869
  const { model, materializer } = await files.compile(url);
42443
42870
  const def = modelDefOf(model);
42444
- const { generated } = await tryCompileMaterializeCompanion({
42871
+ const modelPath = relative.split(path13.sep).join("/");
42872
+ const { generated, failure } = await tryCompileMaterializeCompanion({
42445
42873
  packagePath: args.packagePath,
42446
- modelPath: relative.split(path13.sep).join("/"),
42874
+ modelPath,
42447
42875
  contents: def.contents ?? {},
42448
42876
  givens: def.givens ?? {},
42449
42877
  getRuntime: args.getRuntime,
@@ -42451,6 +42879,8 @@ async function crossFileParents(plans, args, modelFile) {
42451
42879
  crossFileStack: stack,
42452
42880
  crossFileCompanions: companions
42453
42881
  });
42882
+ if (failure)
42883
+ logCompanionFailure(failure, modelPath);
42454
42884
  return {
42455
42885
  ...generated ? { generated } : {},
42456
42886
  text: await files.read(url),
@@ -42461,7 +42891,7 @@ async function crossFileParents(plans, args, modelFile) {
42461
42891
  logger.warn("An extension table's parent in another file could not be planned here; it builds over the raw chain", {
42462
42892
  modelPath: args.modelPath,
42463
42893
  parentFile: path13.relative(args.packagePath, file),
42464
- error: error instanceof Error ? error.message : String(error)
42894
+ code: errorCodeOf(error)
42465
42895
  });
42466
42896
  return;
42467
42897
  });
@@ -42705,8 +43135,15 @@ async function withCrossFileColumnsKept(round, compile, args, foreign) {
42705
43135
  const ids = new Set(differ.map((p) => p.sourceID));
42706
43136
  return compile(round.plans.map((p) => ids.has(p.sourceID) ? withoutParent(p) : p));
42707
43137
  }
42708
- var STORED_TYPES, CompanionCompileError, MAX_OMISSION_ROUNDS = 4, NO_CROSS_FILE_PARENTS;
43138
+ function logCompanionFailure(failure, modelPath) {
43139
+ logger.error(COMPANION_FAILURE_TEXT[failure.kind], {
43140
+ modelPath,
43141
+ code: errorCodeOf(failure.error)
43142
+ });
43143
+ }
43144
+ var STORED_TYPES, CompanionCompileError, MAX_OMISSION_ROUNDS = 4, NO_CROSS_FILE_PARENTS, COMPANION_FAILURE_TEXT;
42709
43145
  var init_materialize_compile = __esm(() => {
43146
+ init_error_code();
42710
43147
  init_malloy_text();
42711
43148
  init_logger();
42712
43149
  init_dialect();
@@ -42747,6 +43184,13 @@ var init_materialize_compile = __esm(() => {
42747
43184
  plans: [],
42748
43185
  parents: new Map
42749
43186
  };
43187
+ COMPANION_FAILURE_TEXT = {
43188
+ materialize: "Failed to plan or compile the generated #(materialize) companion",
43189
+ persisted_view: "Failed to plan or compile the generated persisted-view companion",
43190
+ rollup: "Failed to plan or compile the generated #(rollup) companion",
43191
+ rollup_blanking: "A #(rollup) companion was not built: a `#@` line of the author's files could not be left out of it",
43192
+ 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"
43193
+ };
42750
43194
  });
42751
43195
 
42752
43196
  // src/service/materialization/plan/persisted_view_compile.ts
@@ -42800,12 +43244,7 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42800
43244
  reason: "the view has no stage to store",
42801
43245
  refusal: "no_stored_columns"
42802
43246
  };
42803
- if (pipelineReadsCurrentTime(def, stages)) {
42804
- return {
42805
- reason: "its result reads the current time, so it differs per read",
42806
- refusal: "current_time"
42807
- };
42808
- }
43247
+ const readsNow = pipelineReadsCurrentTime(def, stages);
42809
43248
  const last = stages[stages.length - 1];
42810
43249
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
42811
43250
  return {
@@ -42816,6 +43255,12 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42816
43255
  const gates = collectEntryPointGates(node.def, modelDef);
42817
43256
  if (gates.length === 0)
42818
43257
  return;
43258
+ if (readsNow) {
43259
+ return {
43260
+ 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",
43261
+ refusal: "current_time"
43262
+ };
43263
+ }
42819
43264
  const gateRefusal = gateRefusalReason(gates.map((g) => g.route));
42820
43265
  if (gates.some((g) => !g.struct)) {
42821
43266
  return {
@@ -42938,12 +43383,6 @@ async function persistedQueryRefusalReason(plan, modelDef, materializer) {
42938
43383
  reason: "its source cannot be read",
42939
43384
  refusal: "run_target_unsupported"
42940
43385
  };
42941
- if (pipelineReadsCurrentTime(def, stages)) {
42942
- return {
42943
- reason: "its result reads the current time, so it differs per read",
42944
- refusal: "current_time"
42945
- };
42946
- }
42947
43386
  const last = stages[stages.length - 1];
42948
43387
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
42949
43388
  return {
@@ -43038,13 +43477,10 @@ async function tryCompilePersistedViewCompanion(args) {
43038
43477
  refusedQueries
43039
43478
  };
43040
43479
  } catch (error) {
43041
- logger.error("Failed to plan or compile the generated persisted-view companion", {
43042
- modelPath: args.modelPath,
43043
- error: error instanceof Error ? error.message : String(error)
43044
- });
43045
43480
  return {
43046
43481
  refused,
43047
43482
  refusedQueries,
43483
+ failure: companionFailure("persisted_view", error),
43048
43484
  omitted: companionOmissions("persisted_view", {
43049
43485
  file: companionHref,
43050
43486
  names: plannedNames
@@ -43054,7 +43490,6 @@ async function tryCompilePersistedViewCompanion(args) {
43054
43490
  }
43055
43491
  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";
43056
43492
  var init_persisted_view_compile = __esm(() => {
43057
- init_logger();
43058
43493
  init_annotations();
43059
43494
  init_annotation_reader();
43060
43495
  init_authorize();
@@ -43253,9 +43688,12 @@ async function tryCompileRollupCompanion(args) {
43253
43688
  if (!text)
43254
43689
  return { refused };
43255
43690
  if (!overlay) {
43256
- 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 });
43257
43691
  return {
43258
43692
  refused,
43693
+ failure: {
43694
+ kind: "rollup_blanking",
43695
+ error: "a `#@` line of the author's files could not be set aside"
43696
+ },
43259
43697
  omitted: companionOmissions("rollup_blanking", {
43260
43698
  file: companionHref,
43261
43699
  names: plannedNames
@@ -43294,12 +43732,9 @@ async function tryCompileRollupCompanion(args) {
43294
43732
  refused
43295
43733
  };
43296
43734
  } catch (error) {
43297
- logger.error("Failed to plan or compile the generated #(rollup) companion", {
43298
- modelPath: args.modelPath,
43299
- error: error instanceof Error ? error.message : String(error)
43300
- });
43301
43735
  return {
43302
43736
  refused,
43737
+ failure: companionFailure("rollup", error),
43303
43738
  omitted: companionOmissions("rollup", {
43304
43739
  file: companionHref,
43305
43740
  names: plannedNames
@@ -43338,7 +43773,7 @@ async function compileOverStoredBases(args) {
43338
43773
  logger.warn("A rollup builds from the warehouse: its #(materialize) base's copy over the stored table did not compile", {
43339
43774
  modelPath: args.modelPath,
43340
43775
  base: name,
43341
- error: error instanceof Error ? error.message : String(error)
43776
+ code: errorCodeOf(error)
43342
43777
  });
43343
43778
  stored.delete(name);
43344
43779
  }
@@ -43352,7 +43787,7 @@ async function compileOverStoredBases(args) {
43352
43787
  }
43353
43788
  logger.warn("The rollups over #(materialize) bases build from the warehouse: their companion over the bases' stored tables did not compile", {
43354
43789
  modelPath: args.modelPath,
43355
- error: error instanceof Error ? error.message : String(error)
43790
+ code: errorCodeOf(error)
43356
43791
  });
43357
43792
  out.clear();
43358
43793
  try {
@@ -43399,7 +43834,7 @@ async function compileOverStoredBases(args) {
43399
43834
  function warnWarehouse(modelPath, error) {
43400
43835
  logger.warn("The rollups of a model build from the warehouse: their companion over the bases' stored tables did not compile", {
43401
43836
  modelPath,
43402
- error: error instanceof Error ? error.message : String(error)
43837
+ code: errorCodeOf(error)
43403
43838
  });
43404
43839
  }
43405
43840
  function parentKeyCheckCompiler(materializer) {
@@ -43421,7 +43856,7 @@ async function compileParentKeyChecks(plans, needs, joinedKeys = []) {
43421
43856
  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", {
43422
43857
  source: name,
43423
43858
  keyColumn,
43424
- error: error instanceof Error ? error.message : String(error)
43859
+ code: errorCodeOf(error)
43425
43860
  });
43426
43861
  return;
43427
43862
  });
@@ -43482,12 +43917,13 @@ async function compileRollupKeyChecks(plans, materializer, modelPath) {
43482
43917
  logger.warn("A #(rollup) rollup's key check did not compile", {
43483
43918
  modelPath,
43484
43919
  rollup: plan.rollupSourceName,
43485
- error: error instanceof Error ? error.message : String(error)
43920
+ code: errorCodeOf(error)
43486
43921
  });
43487
43922
  }
43488
43923
  }
43489
43924
  }
43490
43925
  var init_rollup_compile = __esm(() => {
43926
+ init_error_code();
43491
43927
  init_config2();
43492
43928
  init_logger();
43493
43929
  init_prepared_query();
@@ -43544,16 +43980,104 @@ var init_v1_build_companion = __esm(() => {
43544
43980
  init_generated_files();
43545
43981
  });
43546
43982
 
43547
- // src/service/materialization/domain/compiled_build_plan.ts
43548
- function* sourcesInBuildOrder(build, tables) {
43549
- for (const sourceID of build.order) {
43550
- const source = tables[sourceID]?.source;
43551
- if (source)
43552
- yield source;
43983
+ // src/service/materialization/plan/access_closure.ts
43984
+ function collectAccessReads(contents, out) {
43985
+ if (contents === null || typeof contents !== "object")
43986
+ return;
43987
+ const entries = Object.entries(contents).filter((e) => e[1] !== null && typeof e[1] === "object");
43988
+ const keyOf = (name, def) => typeof def.sourceID === "string" ? def.sourceID : `${QUERY_KEY}${name}`;
43989
+ const keys = new Map(entries.map(([name, def]) => [name, keyOf(name, def)]));
43990
+ const byName = (name) => keys.get(name) ?? EVERY_SOURCE;
43991
+ const direct = new Map;
43992
+ const access = [];
43993
+ for (const [name, def] of entries) {
43994
+ const own = typeof def.sourceID === "string" ? def.sourceID : undefined;
43995
+ const deps = new Set;
43996
+ namesIn(def, deps, own, byName, new WeakSet, 0);
43997
+ direct.set(keyOf(name, def), deps);
43998
+ if (isAccessDefinition(def))
43999
+ access.push(deps);
44000
+ }
44001
+ for (const deps of access) {
44002
+ const queue = [...deps];
44003
+ while (queue.length > 0) {
44004
+ const id = queue.pop();
44005
+ if (out.has(id))
44006
+ continue;
44007
+ out.add(id);
44008
+ for (const next of direct.get(id) ?? []) {
44009
+ if (!out.has(next))
44010
+ queue.push(next);
44011
+ }
44012
+ }
43553
44013
  }
43554
44014
  }
43555
- function materializePlansOf(tables) {
43556
- return Object.fromEntries(Object.entries(tables).flatMap(([sourceID, table]) => table.materialize ? [[sourceID, table.materialize]] : []));
44015
+ function isAccessDefinition(def) {
44016
+ if (irCarriesAGate(def))
44017
+ return true;
44018
+ try {
44019
+ return readsAGiven(def);
44020
+ } catch {
44021
+ return true;
44022
+ }
44023
+ }
44024
+ function namesIn(node, out, self2, byName, seen, depth) {
44025
+ if (node === null || typeof node !== "object")
44026
+ return;
44027
+ if (depth > MAX_WALK_DEPTH3) {
44028
+ out.add(EVERY_SOURCE);
44029
+ return;
44030
+ }
44031
+ if (seen.has(node))
44032
+ return;
44033
+ seen.add(node);
44034
+ if (Array.isArray(node)) {
44035
+ for (const item of node) {
44036
+ namesIn(item, out, self2, byName, seen, depth + 1);
44037
+ }
44038
+ return;
44039
+ }
44040
+ for (const [key, value] of Object.entries(node)) {
44041
+ if (SKIPPED_KEYS.has(key))
44042
+ continue;
44043
+ if (DEPENDENCY_KEYS.has(key) && typeof value === "string") {
44044
+ if (!(depth === 0 && key === "sourceID" && value === self2)) {
44045
+ out.add(value);
44046
+ }
44047
+ continue;
44048
+ }
44049
+ if (NAME_KEYS.has(key) && typeof value === "string") {
44050
+ out.add(byName(value));
44051
+ continue;
44052
+ }
44053
+ namesIn(value, out, self2, byName, seen, depth + 1);
44054
+ }
44055
+ }
44056
+ var MAX_WALK_DEPTH3 = 200, DEPENDENCY_KEYS, NAME_KEYS, QUERY_KEY = "query:", SKIPPED_KEYS;
44057
+ var init_access_closure = __esm(() => {
44058
+ init_probe_compiler();
44059
+ init_materialization_eligibility();
44060
+ DEPENDENCY_KEYS = new Set([
44061
+ "sourceID",
44062
+ "extends",
44063
+ "referenceID"
44064
+ ]);
44065
+ NAME_KEYS = new Set(["structRef"]);
44066
+ SKIPPED_KEYS = new Set([
44067
+ "at",
44068
+ "location",
44069
+ "annotations",
44070
+ "blockNotes",
44071
+ "notes"
44072
+ ]);
44073
+ });
44074
+
44075
+ // src/service/materialization/domain/package_plan.ts
44076
+ function countRefusal(counts, reason) {
44077
+ counts[reason] = (counts[reason] ?? 0) + 1;
44078
+ }
44079
+ function noModelGateLines() {
44080
+ return { preaggregate: [], nearMiss: [], nameProblems: [] };
43557
44081
  }
43558
44082
 
43559
44083
  // src/service/materialization/plan/build_plan.ts
@@ -43627,7 +44151,7 @@ async function resolvePackageConnections(pkg, names) {
43627
44151
  map.set(name, await pkg.getMalloyConnection(name));
43628
44152
  } catch (err) {
43629
44153
  logger.warn(`Failed to resolve connection ${name}`, {
43630
- error: errMessage(err)
44154
+ code: errorCodeOf(err)
43631
44155
  });
43632
44156
  }
43633
44157
  }
@@ -43714,7 +44238,7 @@ async function classifyPersistSourceGate(persistSource, modelDef, materializer,
43714
44238
  } catch (err) {
43715
44239
  logger.warn("Failed to classify persist source gate; refusing", {
43716
44240
  sourceID: persistSource.sourceID,
43717
- error: errMessage(err)
44241
+ code: errorCodeOf(err)
43718
44242
  });
43719
44243
  return { classification: "rejected", attributed: false };
43720
44244
  }
@@ -43725,8 +44249,10 @@ function emptyBuildPlanParts() {
43725
44249
  tables: {},
43726
44250
  droppedPersistSources: [],
43727
44251
  annotationFindings: [],
43728
- modelGateLines: { preaggregate: [], nearMiss: [] },
43729
- omittedSources: []
44252
+ modelGateLines: noModelGateLines(),
44253
+ persistedViews: {},
44254
+ omittedSources: [],
44255
+ accessReads: []
43730
44256
  };
43731
44257
  }
43732
44258
  function mergeBuildPlanParts(into, from) {
@@ -43739,6 +44265,11 @@ function mergeBuildPlanParts(into, from) {
43739
44265
  }
43740
44266
  into.modelGateLines.preaggregate.push(...from.modelGateLines.preaggregate);
43741
44267
  into.modelGateLines.nearMiss.push(...from.modelGateLines.nearMiss);
44268
+ into.modelGateLines.nameProblems.push(...from.modelGateLines.nameProblems);
44269
+ Object.assign(into.persistedViews, from.persistedViews);
44270
+ into.accessReads = [
44271
+ ...new Set([...into.accessReads, ...from.accessReads])
44272
+ ].sort();
43742
44273
  }
43743
44274
  function addAnnotationFinding(parts, finding) {
43744
44275
  const key = (f) => [f.code, f.model ?? "", f.subject ?? "", f.message].join("\x00");
@@ -43780,10 +44311,12 @@ function sourceIDFileURL(sourceID) {
43780
44311
  const url = splitSourceID(sourceID)?.url;
43781
44312
  return url?.startsWith("file:") ? url : undefined;
43782
44313
  }
43783
- function addCompanionOutcome(parts, findings, omitted) {
44314
+ function addCompanionOutcome(parts, findings, omitted, failed) {
43784
44315
  for (const finding of findings)
43785
44316
  addAnnotationFinding(parts, finding);
43786
44317
  parts.omittedSources.push(...omitted ?? []);
44318
+ if (failed?.failure)
44319
+ logCompanionFailure(failed.failure, failed.modelPath);
43787
44320
  }
43788
44321
  function withoutGivenReadingTargets(all, refuse) {
43789
44322
  for (const target of all.connections.flatMap((c) => c.targets)) {
@@ -43806,14 +44339,14 @@ function gateDepsFor(model, modelPath) {
43806
44339
  }
43807
44340
  async function collectGeneratedMaterialize(parts, args) {
43808
44341
  const authorDef = modelDefOf(args.malloyModel);
43809
- const { generated, refused, omitted } = await tryCompileMaterializeCompanion({
44342
+ const { generated, refused, omitted, failure } = await tryCompileMaterializeCompanion({
43810
44343
  ...args,
43811
44344
  contents: authorDef.contents ?? {},
43812
44345
  givens: authorDef.givens ?? {},
43813
44346
  sourceRegistry: authorDef.sourceRegistry,
43814
44347
  probe: args.materializer
43815
44348
  });
43816
- addCompanionOutcome(parts, refused.map((r) => materializeRefusalFinding(r, args.modelPath)), omitted);
44349
+ addCompanionOutcome(parts, refused.map((r) => materializeRefusalFinding(r, args.modelPath)), omitted, { failure, modelPath: args.modelPath });
43817
44350
  if (!generated)
43818
44351
  return;
43819
44352
  for (const [key, compile] of generated.checkCompilers) {
@@ -43869,8 +44402,8 @@ async function authorSourceGate(sourceID, authorDef, args) {
43869
44402
  return authorSource ? await classifyPersistSourceGate({ _sourceDef: authorSource, sourceID }, authorDef, args.materializer, args.deps, args.modelPath) : { classification: "rejected", attributed: false };
43870
44403
  }
43871
44404
  async function collectGeneratedRollups(parts, args) {
43872
- const { generated, refused, omitted } = await tryCompileRollupCompanion(args);
43873
- addCompanionOutcome(parts, refused.map((r) => rollupRefusalFinding(r, args.modelPath)), omitted);
44405
+ const { generated, refused, omitted, failure } = await tryCompileRollupCompanion(args);
44406
+ addCompanionOutcome(parts, refused.map((r) => rollupRefusalFinding(r, args.modelPath)), omitted, { failure, modelPath: args.modelPath });
43874
44407
  if (!generated)
43875
44408
  return;
43876
44409
  const planByName = new Map(generated.plans.map((p) => [p.rollupSourceName, p]));
@@ -43878,18 +44411,7 @@ async function collectGeneratedRollups(parts, args) {
43878
44411
  const plan = planByName.get(source.name);
43879
44412
  if (!plan)
43880
44413
  return;
43881
- addAnnotationFinding(parts, rollupRefusalFinding({
43882
- tier: "unservable",
43883
- code: ROLLUP_NOT_BUILT_CODE,
43884
- 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.",
43885
- sourceName: plan.baseSourceName,
43886
- refused: {
43887
- sourceID: source.sourceID,
43888
- name: source.name,
43889
- tier: tierOf(plan.storage),
43890
- reason: "reads_given"
43891
- }
43892
- }, args.modelPath));
44414
+ addAnnotationFinding(parts, rollupRefusalFinding(rollupReadsGivenRefusal(plan, source), args.modelPath));
43893
44415
  });
43894
44416
  const kept = [];
43895
44417
  for (const source of plannedSources(targets)) {
@@ -43916,7 +44438,7 @@ async function collectGeneratedRollups(parts, args) {
43916
44438
  }
43917
44439
  async function collectGeneratedPersistedViews(parts, args) {
43918
44440
  const authorDef = modelDefOf(args.malloyModel);
43919
- const { generated, refused, refusedQueries, omitted } = await tryCompilePersistedViewCompanion({
44441
+ const { generated, refused, refusedQueries, omitted, failure } = await tryCompilePersistedViewCompanion({
43920
44442
  packagePath: args.packagePath,
43921
44443
  modelPath: args.modelPath,
43922
44444
  modelDef: authorDef,
@@ -43926,29 +44448,24 @@ async function collectGeneratedPersistedViews(parts, args) {
43926
44448
  addCompanionOutcome(parts, [
43927
44449
  ...refused.map((r) => persistedViewRefusalFinding(r, args.modelPath)),
43928
44450
  ...refusedQueries.map((r) => persistedQueryRefusalFinding(r, args.modelPath))
43929
- ], omitted);
44451
+ ], omitted, { failure, modelPath: args.modelPath });
43930
44452
  if (!generated)
43931
44453
  return;
44454
+ for (const plan of generated.plans) {
44455
+ parts.persistedViews[plan.buildSourceID] = {
44456
+ sourceName: plan.sourceName,
44457
+ viewName: plan.viewName
44458
+ };
44459
+ }
43932
44460
  const planByName = new Map(generated.plans.map((p) => [p.buildSourceName, p]));
43933
44461
  const queryByID = new Map(generated.queries.map((p) => [p.buildSourceID, p]));
43934
- const readsAGiven = "its result reads a given, so it differs per caller and a table holds one caller's result";
43935
44462
  const targets = withoutGivenReadingTargets(await generated.runtime.getBuildTargets(generated.model), (source) => {
43936
44463
  const plan = planByName.get(source.name);
43937
44464
  const query = queryByID.get(source.sourceID);
43938
44465
  if (plan) {
43939
- addAnnotationFinding(parts, persistedViewRefusalFinding({
43940
- ...plan,
43941
- reason: readsAGiven,
43942
- outcome: { refused: "reads_given" }
43943
- }, args.modelPath));
44466
+ addAnnotationFinding(parts, persistedViewRefusalFinding(persistedViewReadsGivenRefusal(plan), args.modelPath));
43944
44467
  } else if (query) {
43945
- addAnnotationFinding(parts, persistedQueryRefusalFinding({
43946
- queryName: query.queryName,
43947
- reason: readsAGiven,
43948
- refusal: "reads_given",
43949
- declaringURL: query.declaringURL,
43950
- ...query.storage !== undefined ? { storage: query.storage } : {}
43951
- }, args.modelPath));
44468
+ addAnnotationFinding(parts, persistedQueryRefusalFinding(persistedQueryReadsGivenRefusal(query), args.modelPath));
43952
44469
  }
43953
44470
  });
43954
44471
  const ctx = {
@@ -44041,7 +44558,13 @@ function inlineRunTarget(modelDef, name) {
44041
44558
  const ref = query?.type === "query" ? query.structRef : undefined;
44042
44559
  return ref && typeof ref === "object" && isSourceDef12(ref) ? ref : undefined;
44043
44560
  }
44561
+ function addAccessReads(parts, malloyModel) {
44562
+ const reads = new Set(parts.accessReads);
44563
+ collectAccessReads(modelDefOf(malloyModel)?.contents ?? {}, reads);
44564
+ parts.accessReads = [...reads].sort();
44565
+ }
44044
44566
  async function collectModelBuildPlan(parts, args) {
44567
+ addAccessReads(parts, args.malloyModel);
44045
44568
  await collectGeneratedTables(parts, args);
44046
44569
  const plannable = await v1PlanModel(parts, args);
44047
44570
  if (!plannable)
@@ -44075,6 +44598,12 @@ async function collectGeneratedTables(parts, args) {
44075
44598
  addAnnotationFinding(parts, finding);
44076
44599
  }
44077
44600
  parts.modelGateLines.nearMiss.push(...nearMissGateLines(modelPath, annotationNearMisses(authoredNotes(authorDef))));
44601
+ const text = await GeneratedFiles.over(getRuntime).readIfAny(pathToFileURL12(path17.join(packagePath, modelPath))).catch(() => {
44602
+ return;
44603
+ });
44604
+ if (text !== undefined) {
44605
+ parts.modelGateLines.nameProblems.push(...persistNameProblems(text, modelPath));
44606
+ }
44078
44607
  }
44079
44608
  collectPersistQueryFindings(parts, {
44080
44609
  modelPath,
@@ -44151,12 +44680,9 @@ async function v1PlanModel(parts, args) {
44151
44680
  packagePath,
44152
44681
  modelPath,
44153
44682
  getRuntime,
44154
- onCompileFailed: (error) => {
44155
- 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) });
44156
- parts.omittedSources.push(...companionOmissions("v1_build", {
44157
- sourceIDs: declaredPersistSourceIDs(malloyModel)
44158
- }));
44159
- }
44683
+ onCompileFailed: (error) => addCompanionOutcome(parts, [], companionOmissions("v1_build", {
44684
+ sourceIDs: declaredPersistSourceIDs(malloyModel)
44685
+ }), { failure: companionFailure("v1_build", error), modelPath })
44160
44686
  });
44161
44687
  if (!companion)
44162
44688
  return;
@@ -44167,14 +44693,14 @@ async function v1PlanModel(parts, args) {
44167
44693
  }
44168
44694
  function reportPersistLineFindings(parts, targets, planned, args) {
44169
44695
  const { modelPath, packagePath, malloyModel, planModel } = args;
44170
- const parseErrors = targets.tagParseLog.filter((msg) => {
44171
- logger.warn("Persist annotation issue", {
44696
+ for (const msg of targets.tagParseLog) {
44697
+ logger.debug("Persist annotation issue", {
44172
44698
  modelPath,
44173
- message: msg.message,
44699
+ code: msg.code,
44174
44700
  severity: msg.severity
44175
44701
  });
44176
- return msg.severity === "error";
44177
- });
44702
+ }
44703
+ const parseErrors = targets.tagParseLog.filter((msg) => msg.severity === "error");
44178
44704
  const companionURL = planModel !== malloyModel ? pathToFileURL12(path17.resolve(packagePath, modelPath)).href : undefined;
44179
44705
  const authorAt = (at) => at && companionURL && at.url === companionURL ? {
44180
44706
  ...at,
@@ -44227,7 +44753,14 @@ async function planV1PersistSources(parts, planned, args) {
44227
44753
  model: declaredIn
44228
44754
  });
44229
44755
  }
44230
- } catch {}
44756
+ } catch (err) {
44757
+ logger.warn("Failed to read a persist source's annotations; planned without their findings", {
44758
+ modelPath,
44759
+ sourceID,
44760
+ sourceName: source.name,
44761
+ code: errorCodeOf(err)
44762
+ });
44763
+ }
44231
44764
  classificationCtx ??= {
44232
44765
  modelDef: modelDefOf(malloyModel),
44233
44766
  deps: gateDepsFor(malloyModel, modelPath)
@@ -44270,7 +44803,7 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44270
44803
  sourceID,
44271
44804
  sourceName: source.name,
44272
44805
  reason,
44273
- error: errMessage(err)
44806
+ code: errorCodeOf(err)
44274
44807
  });
44275
44808
  omitted.push({ sourceID, reason });
44276
44809
  }
@@ -44329,7 +44862,7 @@ function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources,
44329
44862
  };
44330
44863
  }
44331
44864
  }
44332
- function projectRefusals(plan, findings) {
44865
+ function projectRefusals(plan, findings, counts = {}) {
44333
44866
  const kept = [];
44334
44867
  const refusedSources = {
44335
44868
  ...plan?.refusedSources ?? {}
@@ -44357,7 +44890,7 @@ function projectRefusals(plan, findings) {
44357
44890
  code: finding.code,
44358
44891
  ...finding.subject !== undefined ? { subject: finding.subject } : {}
44359
44892
  };
44360
- recordEligibilityRefused(key.reason);
44893
+ countRefusal(counts, key.reason);
44361
44894
  }
44362
44895
  if (!moved)
44363
44896
  return { plan, annotationFindings: kept, refusalNotices };
@@ -44384,35 +44917,107 @@ function finishBuildPlan(parts, ctx) {
44384
44917
  }));
44385
44918
  return ctx.keepIncrementalUnbuildable ? refused : refuseIncrementalUnbuildable(refused);
44386
44919
  }
44387
- function deriveBuildPlanOutcome(compiled, materializationConfig) {
44920
+ async function finishPackagePlan(parts, ctx) {
44921
+ const { getMalloyConnection, ...finish } = ctx;
44922
+ const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
44923
+ const digestSkipped = [];
44924
+ const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
44925
+ return {
44926
+ compiled: finishBuildPlan(parts, {
44927
+ ...finish,
44928
+ connectionDigests,
44929
+ connections
44930
+ }),
44931
+ digestSkipped
44932
+ };
44933
+ }
44934
+ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
44388
44935
  const incrementalDeclarations = collectIncrementalDeclarations(compiled.tables);
44389
44936
  const verdicts = planVerdicts(compiled);
44390
44937
  for (const { counted } of verdicts.values()) {
44391
44938
  if (counted)
44392
- recordEligibilityRefused(counted);
44939
+ countRefusal(counts, counted);
44393
44940
  }
44394
44941
  const derived = compiled.builds.length === 0 && !compiled.omittedSources.length ? null : deriveBuildPlan(compiled, materializationConfig, verdicts);
44395
- const projected = projectRefusals(derived, compiled.annotationFindings.map((f) => relaxedCollision(f, getPersistCollisionEnforce())));
44942
+ const projected = projectRefusals(derived, compiled.annotationFindings.map((f) => relaxedCollision(f, getPersistCollisionEnforce())), counts);
44396
44943
  const { annotationFindings, refusalNotices } = projected;
44397
- const plan = withRefusalOrigins(projected.plan, compiled.tables, refusalNotices);
44944
+ const refusedPlan = withRefusalOrigins(projected.plan, compiled.tables, refusalNotices);
44945
+ const asOfBuild = asOfBuildOf(refusedPlan, compiled.tables);
44946
+ const plan = withAsOfBuild(refusedPlan, asOfBuild);
44398
44947
  return {
44399
44948
  plan,
44400
- droppedPersistSources: compiled.droppedPersistSources,
44949
+ tables: tablePlanDataOf(compiled.tables),
44950
+ builds: compiled.builds,
44951
+ connectionDigests: compiled.connectionDigests,
44952
+ connectionTypes: compiled.connectionTypes ?? {},
44953
+ buildConnectionNames: [
44954
+ ...new Set(compiled.builds.map((b) => b.connectionName))
44955
+ ].sort(),
44956
+ versionScoped: compiled.versionScoped === true,
44957
+ tableFolds: { ...compiled.tableFolds },
44958
+ addresses: { ...compiled.addresses },
44959
+ compilerKeys: compilerKeysOf(compiled),
44401
44960
  annotationFindings,
44402
- refusalNotices,
44961
+ droppedPersistSources: compiled.droppedPersistSources,
44403
44962
  modelGateLines: compiled.modelGateLines,
44963
+ persistedViews: compiled.persistedViews ?? {},
44964
+ refusalNotices,
44965
+ refusedRollups: refusedRollupsOf(plan, compiled.tables),
44404
44966
  sourceEligibility: collectSourceEligibility(compiled, verdicts),
44405
44967
  databaseSourceEligibility: collectDatabaseSourceEligibility(compiled, verdicts),
44968
+ rollupsKeepingGates: Object.entries(compiled.tables).filter(([, table]) => table.rollup !== undefined && rollupGateEnforcedAtRead(table.rollup)).map(([sourceID]) => sourceID).sort(),
44406
44969
  incrementalDeclarations,
44407
- buildConnectionNames: [
44408
- ...new Set(compiled.builds.map((b) => b.connectionName))
44409
- ].sort(),
44410
44970
  materializePlans: materializePlansOf(compiled.tables),
44411
- rollupsKeepingGates: Object.entries(compiled.tables).filter(([, table]) => table.rollup !== undefined && rollupGateEnforcedAtRead(table.rollup)).map(([sourceID]) => sourceID).sort(),
44412
- refusedRollups: refusedRollupsOf(plan, compiled.tables),
44413
- compilerKeys: compilerKeysOf(compiled)
44971
+ asOfBuild,
44972
+ accessReads: [...compiled.accessReads ?? []],
44973
+ eligibilityRefused: { ...counts }
44414
44974
  };
44415
44975
  }
44976
+ function withAsOfBuild(plan, asOfBuild) {
44977
+ if (!plan || Object.keys(asOfBuild).length === 0)
44978
+ return plan;
44979
+ const sources = { ...plan.sources };
44980
+ for (const sourceID of Object.keys(asOfBuild)) {
44981
+ const entry = sources[sourceID];
44982
+ if (entry)
44983
+ sources[sourceID] = { ...entry, asOfBuild: true };
44984
+ }
44985
+ return { ...plan, sources };
44986
+ }
44987
+ function asOfBuildOf(plan, tables) {
44988
+ const out = {};
44989
+ for (const [sourceID, table] of Object.entries(tables)) {
44990
+ if (!plan?.sources?.[sourceID])
44991
+ continue;
44992
+ if (!storedAsOfBuild(table.source, table.kind))
44993
+ continue;
44994
+ out[sourceID] = {
44995
+ name: table.source.name,
44996
+ ...table.modelPath ? { modelPath: table.modelPath } : {},
44997
+ reads: currentTimeReadsOf(table.source)
44998
+ };
44999
+ }
45000
+ return out;
45001
+ }
45002
+ function tablePlanDataOf(tables) {
45003
+ return Object.fromEntries(Object.entries(tables).map(([sourceID, table]) => {
45004
+ const {
45005
+ source,
45006
+ target: _target,
45007
+ overStoredBase,
45008
+ ...data
45009
+ } = table;
45010
+ return [
45011
+ sourceID,
45012
+ {
45013
+ ...data,
45014
+ name: source.name,
45015
+ connectionName: source.connectionName,
45016
+ ...overStoredBase ? { overStoredBaseCandidate: true } : {}
45017
+ }
45018
+ ];
45019
+ }));
45020
+ }
44416
45021
  function compilerKeysOf(compiled) {
44417
45022
  const keys = {};
44418
45023
  for (const [sourceID, { source, target }] of Object.entries(compiled.tables)) {
@@ -44570,7 +45175,7 @@ function collectIncrementalDeclarations(tables) {
44570
45175
  } catch (err) {
44571
45176
  logger.warn("Failed to resolve a source's incremental declaration", {
44572
45177
  sourceID,
44573
- error: errMessage(err)
45178
+ code: errorCodeOf(err)
44574
45179
  });
44575
45180
  }
44576
45181
  }
@@ -44578,6 +45183,7 @@ function collectIncrementalDeclarations(tables) {
44578
45183
  }
44579
45184
  var ORIGIN_OF_NOT_BUILT_CODE;
44580
45185
  var init_build_plan = __esm(() => {
45186
+ init_error_code();
44581
45187
  init_incremental_policy();
44582
45188
  init_load_gate_text();
44583
45189
  init_preaggregation_validation();
@@ -44605,9 +45211,9 @@ var init_build_plan = __esm(() => {
44605
45211
  init_rollup_compile();
44606
45212
  init_v1_build_companion();
44607
45213
  init_rollup_plan();
44608
- init_rollup_plan();
44609
45214
  init_config2();
44610
45215
  init_connection_type();
45216
+ init_access_closure();
44611
45217
  init_persist_dynamic_terms();
44612
45218
  init_persist_source_fields();
44613
45219
  init_quoting();
@@ -44628,7 +45234,7 @@ var init_build_plan = __esm(() => {
44628
45234
  });
44629
45235
 
44630
45236
  // src/package_load/protocol.ts
44631
- var PACKAGE_LOAD_PROTOCOL_VERSION = 5;
45237
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 7;
44632
45238
 
44633
45239
  // src/package_load/package_load_worker.ts
44634
45240
  init_malloynb();
@@ -44900,7 +45506,6 @@ class RpcWaitAccountant {
44900
45506
 
44901
45507
  // src/package_load/package_load_worker.ts
44902
45508
  init_experimental_dialects();
44903
- init_materialization_metrics();
44904
45509
  init_logger();
44905
45510
  init_process_safety();
44906
45511
 
@@ -44941,6 +45546,9 @@ class SchemaCache {
44941
45546
  this.delete(oldest);
44942
45547
  }
44943
45548
  }
45549
+ forget(key) {
45550
+ this.delete(key);
45551
+ }
44944
45552
  delete(key) {
44945
45553
  const entry = this.entries.get(key);
44946
45554
  if (!entry)
@@ -44975,6 +45583,37 @@ class SchemaCache {
44975
45583
  }
44976
45584
  }
44977
45585
 
45586
+ class DeferredForgets {
45587
+ cache;
45588
+ pending = new Set;
45589
+ running = new Set;
45590
+ constructor(cache) {
45591
+ this.cache = cache;
45592
+ }
45593
+ forget(keys) {
45594
+ for (const key of keys) {
45595
+ if (this.running.size === 0)
45596
+ this.cache.forget(key);
45597
+ else
45598
+ this.pending.add(key);
45599
+ }
45600
+ }
45601
+ jobStarted(jobId) {
45602
+ this.running.add(jobId);
45603
+ }
45604
+ jobEnded(jobId) {
45605
+ this.running.delete(jobId);
45606
+ if (this.running.size > 0)
45607
+ return;
45608
+ for (const key of this.pending)
45609
+ this.cache.forget(key);
45610
+ this.pending.clear();
45611
+ }
45612
+ get held() {
45613
+ return this.pending.size;
45614
+ }
45615
+ }
45616
+
44978
45617
  // src/package_load/worker_log.ts
44979
45618
  function plainLogEntry(entry) {
44980
45619
  const info = entry;
@@ -45061,8 +45700,8 @@ function dispatchMainResponse(message) {
45061
45700
  }
45062
45701
  }
45063
45702
  var schemaCache = new SchemaCache(workerData2?.schemaCacheBytes ?? 0);
45703
+ var deferredForgets = new DeferredForgets(schemaCache);
45064
45704
  var jobContext = new AsyncLocalStorage3;
45065
- setEligibilityRefusalSink(() => jobContext.getStore()?.refusals);
45066
45705
  var writeEntry = logger.write.bind(logger);
45067
45706
  logger.write = (entry) => {
45068
45707
  const job = jobContext.getStore();
@@ -45089,11 +45728,13 @@ class ProxyConnection {
45089
45728
  digest;
45090
45729
  jobId;
45091
45730
  cacheScope;
45092
- constructor(metadata, jobId, environmentScope) {
45731
+ refresh;
45732
+ constructor(metadata, jobId, environmentScope, refresh) {
45093
45733
  this.name = metadata.name;
45094
45734
  this.dialectName = metadata.dialectName;
45095
45735
  this.digest = metadata.digest;
45096
45736
  this.jobId = jobId;
45737
+ this.refresh = refresh;
45097
45738
  this.cacheScope = [
45098
45739
  environmentScope,
45099
45740
  this.name,
@@ -45114,8 +45755,13 @@ class ProxyConnection {
45114
45755
  const errors = {};
45115
45756
  const joined = [];
45116
45757
  const missing = {};
45758
+ const refetch = {};
45117
45759
  for (const [key, tablePath] of Object.entries(tables)) {
45118
45760
  const cacheKey = this.tableCacheKey(tablePath);
45761
+ if (this.claimRefetch(cacheKey)) {
45762
+ refetch[key] = tablePath;
45763
+ continue;
45764
+ }
45119
45765
  const hit = schemaCache.get(cacheKey);
45120
45766
  const pending = hit === undefined ? schemaCache.joinInFlight(cacheKey) : undefined;
45121
45767
  if (hit) {
@@ -45126,16 +45772,14 @@ class ProxyConnection {
45126
45772
  missing[key] = tablePath;
45127
45773
  }
45128
45774
  }
45129
- if (Object.keys(missing).length > 0) {
45130
- const request = this.fetchSchemaForTablesFromMain(missing, options);
45131
- for (const [key, tablePath] of Object.entries(missing)) {
45132
- schemaCache.trackInFlight(this.tableCacheKey(tablePath), request.then((r) => ({
45133
- value: r.schemas[key],
45134
- error: r.errors[key]
45135
- })));
45136
- }
45137
- const fetched = await request;
45138
- this.cacheTableSchemas(missing, fetched.schemas);
45775
+ const fetches = [this.fetchAndCacheTables(missing, options)];
45776
+ if (this.refresh && Object.keys(refetch).length > 0) {
45777
+ fetches.push(this.fetchAndCacheTables(refetch, {
45778
+ ...options,
45779
+ refreshTimestamp: this.refresh.timestamp
45780
+ }));
45781
+ }
45782
+ for (const fetched of await Promise.all(fetches)) {
45139
45783
  Object.assign(schemas, fetched.schemas);
45140
45784
  Object.assign(errors, fetched.errors);
45141
45785
  }
@@ -45150,6 +45794,27 @@ class ProxyConnection {
45150
45794
  }
45151
45795
  return { schemas, errors };
45152
45796
  }
45797
+ async fetchAndCacheTables(tables, options) {
45798
+ if (Object.keys(tables).length === 0)
45799
+ return { schemas: {}, errors: {} };
45800
+ const request = this.fetchSchemaForTablesFromMain(tables, options);
45801
+ for (const [key, tablePath] of Object.entries(tables)) {
45802
+ schemaCache.trackInFlight(this.tableCacheKey(tablePath), request.then((r) => ({
45803
+ value: r.schemas[key],
45804
+ error: r.errors[key]
45805
+ })));
45806
+ }
45807
+ const fetched = await request;
45808
+ this.cacheTableSchemas(tables, fetched.schemas);
45809
+ return fetched;
45810
+ }
45811
+ claimRefetch(cacheKey) {
45812
+ if (!this.refresh || this.refresh.refetched.has(cacheKey))
45813
+ return false;
45814
+ this.refresh.refetched.add(cacheKey);
45815
+ schemaCache.forget(cacheKey);
45816
+ return true;
45817
+ }
45153
45818
  cacheTableSchemas(requested, schemas) {
45154
45819
  for (const [key, schema] of Object.entries(schemas)) {
45155
45820
  const tablePath = requested[key];
@@ -45189,10 +45854,11 @@ class ProxyConnection {
45189
45854
  }
45190
45855
  return refreshed;
45191
45856
  }
45192
- const hit = schemaCache.get(cacheKey);
45857
+ const refetch = this.claimRefetch(cacheKey);
45858
+ const hit = refetch ? undefined : schemaCache.get(cacheKey);
45193
45859
  if (hit)
45194
45860
  return { structDef: hit };
45195
- const pending = schemaCache.joinInFlight(cacheKey);
45861
+ const pending = refetch ? undefined : schemaCache.joinInFlight(cacheKey);
45196
45862
  if (pending) {
45197
45863
  const answer = await pending;
45198
45864
  if (answer.value) {
@@ -45201,7 +45867,7 @@ class ProxyConnection {
45201
45867
  }
45202
45868
  return { error: answer.error ?? "No schema returned for the SQL" };
45203
45869
  }
45204
- const request = this.fetchSchemaForSQLStructFromMain(sentence, options);
45870
+ const request = this.fetchSchemaForSQLStructFromMain(sentence, refetch && this.refresh ? { ...options, refreshTimestamp: this.refresh.timestamp } : options);
45205
45871
  schemaCache.trackInFlight(cacheKey, request.then((r) => ({ value: r.structDef, error: r.error })));
45206
45872
  const result = await request;
45207
45873
  if (result.structDef !== undefined) {
@@ -45295,7 +45961,7 @@ function makeWorkerUrlReader(job) {
45295
45961
  }
45296
45962
  };
45297
45963
  }
45298
- function buildWorkerMalloyConfig(job) {
45964
+ function buildWorkerMalloyConfig(job, refresh) {
45299
45965
  const proxies = new Map;
45300
45966
  const inflight = new Map;
45301
45967
  const config = new MalloyConfig({ connections: {} }, { config: contextOverlay({ rootDirectory: job.packagePath }) });
@@ -45317,7 +45983,7 @@ function buildWorkerMalloyConfig(job) {
45317
45983
  };
45318
45984
  port.postMessage(req);
45319
45985
  });
45320
- const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName), response.metadata.connectionType);
45986
+ const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType);
45321
45987
  proxies.set(effectiveName, proxy);
45322
45988
  inflight.delete(effectiveName);
45323
45989
  return proxy;
@@ -45484,7 +46150,7 @@ async function compileMalloyModel(job, malloyConfig, modelPath, load, files) {
45484
46150
  const modelDef = compiled._modelDef;
45485
46151
  const { sources, queries, filterMap, givens, sourceInfos, warnings } = await extractCheckedModel(mm, compiled);
45486
46152
  const compileDurationMs = performance.now() - compileStart;
45487
- const { renderTagResults, renderTagResultsDigest, preaggregateCompanion } = await prepareForMainThread(job, malloyConfig, load, {
46153
+ const { renderTagResults, renderTagResultsDigest } = await prepareForMainThread(job, malloyConfig, load, {
45488
46154
  modelPath,
45489
46155
  materializer: mm,
45490
46156
  model: compiled,
@@ -45516,7 +46182,6 @@ async function compileMalloyModel(job, malloyConfig, modelPath, load, files) {
45516
46182
  gateWarnings: warnings.length > 0 ? warnings : undefined,
45517
46183
  renderTagResults,
45518
46184
  renderTagResultsDigest,
45519
- preaggregateCompanion,
45520
46185
  entities,
45521
46186
  governsAccess: governsAccess(modelDef)
45522
46187
  };
@@ -45593,11 +46258,12 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
45593
46258
  runtime: jobRuntime(job, malloyConfig, overlaidReader(makeWorkerUrlReader(job), overlay)),
45594
46259
  importBaseURL
45595
46260
  });
45596
- const companion = (job.withPreaggregateCompanions || wantsPlan) && !load.failed && !pastDeadline() ? null : undefined;
45597
46261
  if (wantsPlan && load.planLeftToMainThread) {
45598
46262
  wantsPlan = false;
45599
46263
  }
45600
- if (wantsPlan && companion !== undefined && !load.failed) {
46264
+ if (wantsPlan && (load.failed || pastDeadline())) {
46265
+ load.planLeftToMainThread = true;
46266
+ } else if (wantsPlan) {
45601
46267
  load.planStart ??= performance.now();
45602
46268
  try {
45603
46269
  const parts = emptyBuildPlanParts();
@@ -45619,14 +46285,8 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
45619
46285
  };
45620
46286
  }
45621
46287
  }
45622
- } else if (wantsPlan) {
45623
- load.planLeftToMainThread = true;
45624
46288
  }
45625
- return {
45626
- renderTagResults,
45627
- renderTagResultsDigest,
45628
- preaggregateCompanion: !job.withPreaggregateCompanions || companion === undefined ? undefined : {}
45629
- };
46289
+ return { renderTagResults, renderTagResultsDigest };
45630
46290
  }
45631
46291
  async function compileNotebookModel(job, malloyConfig, modelPath) {
45632
46292
  const compileStart = performance.now();
@@ -45703,7 +46363,8 @@ async function loadPackage(job) {
45703
46363
  const allFiles = await listPackageFiles(job.packagePath);
45704
46364
  const modelPaths = filterModelPaths(allFiles);
45705
46365
  const packageMetadata = await readPackageMetadata(job.packagePath, modelPaths);
45706
- const malloyConfig = buildWorkerMalloyConfig(job);
46366
+ const refresh = job.refreshTimestamp !== undefined ? { timestamp: job.refreshTimestamp, refetched: new Set } : undefined;
46367
+ const malloyConfig = buildWorkerMalloyConfig(job, refresh);
45707
46368
  const replacementMatchedExisting = job.replacement ? modelPaths.includes(job.replacement.modelPath) : undefined;
45708
46369
  if (job.replacement && !replacementMatchedExisting) {
45709
46370
  modelPaths.push(job.replacement.modelPath);
@@ -45748,6 +46409,7 @@ async function loadPackage(job) {
45748
46409
  packageMetadata,
45749
46410
  models,
45750
46411
  replacementMatchedExisting,
46412
+ ...refresh ? { refreshedSchemaKeys: [...refresh.refetched] } : {},
45751
46413
  loadDurationMs: loadEnd - loadStart,
45752
46414
  timings: {
45753
46415
  compileDurationMs: Math.max(0, compileEnd - compileRegionStart - schemaFetchDurationMs),
@@ -45765,10 +46427,8 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45765
46427
  return;
45766
46428
  }
45767
46429
  const start = performance.now();
45768
- const refusals = () => ({
45769
- ...jobContext.getStore()?.refusals ?? {}
45770
- });
45771
- const digestSkipped = [];
46430
+ const eligibilityRefused = {};
46431
+ let digestSkipped = [];
45772
46432
  try {
45773
46433
  if (load.planError)
45774
46434
  throw new Error(load.planError.message);
@@ -45781,21 +46441,16 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45781
46441
  throw new Error(`Model ${modelPath} did not compile`);
45782
46442
  mergeBuildPlanParts(parts, own);
45783
46443
  }
45784
- const connections = await resolvePackageConnections({
45785
- getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name)
45786
- }, parts.builds.map((b) => b.connectionName));
45787
- const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
45788
- const outcome = deriveBuildPlanOutcome(finishBuildPlan(parts, {
45789
- connectionDigests,
45790
- connections,
46444
+ const finished = await finishPackagePlan(parts, {
46445
+ getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name),
45791
46446
  versionScoped
45792
- }), materializationConfig);
46447
+ });
46448
+ digestSkipped = finished.digestSkipped;
45793
46449
  return {
45794
46450
  ok: true,
45795
- outcome,
46451
+ packagePlan: derivePackagePlan(finished.compiled, materializationConfig, eligibilityRefused),
45796
46452
  durationMs: performance.now() - (load.planStart ?? start),
45797
- digestSkipped,
45798
- eligibilityRefused: refusals()
46453
+ digestSkipped
45799
46454
  };
45800
46455
  } catch (error) {
45801
46456
  return {
@@ -45803,7 +46458,7 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45803
46458
  error: errMessage(error),
45804
46459
  durationMs: performance.now() - (load.planStart ?? start),
45805
46460
  digestSkipped,
45806
- eligibilityRefused: refusals()
46461
+ eligibilityRefused
45807
46462
  };
45808
46463
  }
45809
46464
  }
@@ -45828,15 +46483,19 @@ port.on("message", (message) => {
45828
46483
  port.postMessage(errMsg);
45829
46484
  return;
45830
46485
  }
45831
- inFlightJobs.add(message.requestId);
46486
+ jobStarted(message.requestId);
45832
46487
  runJob(message);
45833
46488
  return;
45834
46489
  }
45835
46490
  if (message.type === "compile-served-copy") {
45836
- inFlightJobs.add(message.requestId);
46491
+ jobStarted(message.requestId);
45837
46492
  runServedCopyJob(message);
45838
46493
  return;
45839
46494
  }
46495
+ if (message.type === "forget-schemas") {
46496
+ deferredForgets.forget(message.keys);
46497
+ return;
46498
+ }
45840
46499
  dispatchMainResponse(message);
45841
46500
  });
45842
46501
  async function compileServedCopy(job) {
@@ -45868,8 +46527,7 @@ async function compileServedCopy(job) {
45868
46527
  async function runServedCopyJob(job) {
45869
46528
  const context = {
45870
46529
  jobId: job.requestId,
45871
- packagePath: job.packagePath,
45872
- refusals: {}
46530
+ packagePath: job.packagePath
45873
46531
  };
45874
46532
  try {
45875
46533
  port.postMessage(await jobContext.run(context, () => compileServedCopy(job)));
@@ -45883,15 +46541,13 @@ async function runServedCopyJob(job) {
45883
46541
  };
45884
46542
  port.postMessage(result);
45885
46543
  } finally {
45886
- inFlightJobs.delete(job.requestId);
45887
- maybeExit();
46544
+ jobEnded(job.requestId);
45888
46545
  }
45889
46546
  }
45890
46547
  async function runJob(job) {
45891
46548
  const context = {
45892
46549
  jobId: job.requestId,
45893
- packagePath: job.packagePath,
45894
- refusals: {}
46550
+ packagePath: job.packagePath
45895
46551
  };
45896
46552
  try {
45897
46553
  const result = await jobContext.run(context, () => loadPackage(job));
@@ -45904,10 +46560,18 @@ async function runJob(job) {
45904
46560
  };
45905
46561
  port.postMessage(errMsg);
45906
46562
  } finally {
45907
- inFlightJobs.delete(job.requestId);
45908
- maybeExit();
46563
+ jobEnded(job.requestId);
45909
46564
  }
45910
46565
  }
46566
+ function jobStarted(jobId) {
46567
+ inFlightJobs.add(jobId);
46568
+ deferredForgets.jobStarted(jobId);
46569
+ }
46570
+ function jobEnded(jobId) {
46571
+ inFlightJobs.delete(jobId);
46572
+ deferredForgets.jobEnded(jobId);
46573
+ maybeExit();
46574
+ }
45911
46575
  function maybeExit() {
45912
46576
  if (shuttingDown && inFlightJobs.size === 0 && pendingRpc.size === 0) {
45913
46577
  setImmediate(() => process.exit(0));