@malloy-publisher/server 0.16.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.
@@ -2286,7 +2286,7 @@ var init_query = __esm(() => {
2286
2286
  type: integer({ min: 0 }),
2287
2287
  default: DEFAULT_PACKAGE_LOAD_SCHEMA_CACHE_BYTES,
2288
2288
  description: "Serialized schema each package-load worker caches across loads, in bytes; 0 turns it off.",
2289
- notes: "Serialized size of the table and SQL schemas each package-load worker keeps across loads, so a model's repeated and later requests for the same table skip the round trip to the main thread. Least recently used entries go first. Scoped per environment and per connection instance, so editing a connection drops its entries; a request that asks to refresh a schema is fetched again, and the result replaces the entry. Heap use is a few times the serialized size. `0` disables it; empty takes the default, and a value that is not a byte count stops the server from starting.",
2289
+ notes: "Serialized size of the table and SQL schemas each package-load worker keeps across loads, so a model's repeated and later requests for the same table skip the round trip to the main thread. Least recently used entries go first. Scoped per environment and per connection instance, so editing a connection drops its entries. An explicit refresh (a reload with `?reload=true` or `reload_package`, a publish, or a `PATCH` that reinstalls) fetches every table and SQL schema the package reads again, in the connection's own cache too, and every worker drops its old entry; a watch-mode recompile and a boot read the cached schemas. Heap use is a few times the serialized size. `0` disables it; empty takes the default, and a value that is not a byte count stops the server from starting.",
2290
2290
  defaultText: "`16777216` (16 MiB)",
2291
2291
  aliases: { env: ["PACKAGE_LOAD_SCHEMA_CACHE_BYTES"] }
2292
2292
  })
@@ -28084,184 +28084,6 @@ var init_experimental_dialects = __esm(() => {
28084
28084
  BUNDLED_EXPERIMENTAL_DIALECTS = ["sqlserver"];
28085
28085
  });
28086
28086
 
28087
- // src/materialization_metrics.ts
28088
- function routeLegOf(kind) {
28089
- return kind === "served" ? "materialized" : kind;
28090
- }
28091
- function recordScheduledFire(outcome) {
28092
- scheduledFireCounter().add(1, { outcome });
28093
- }
28094
- function recordMaterializationRun(mode, outcome, durationMs) {
28095
- runCounter().add(1, { mode, outcome });
28096
- runDuration().record(durationMs, { mode, outcome });
28097
- }
28098
- function recordBuildOutcome(labels) {
28099
- buildCounter().add(1, {
28100
- kind: labels.kind,
28101
- tier: labels.tier,
28102
- outcome: labels.outcome,
28103
- failure_class: labels.outcome === "failed" ? labels.failureClass : "none"
28104
- });
28105
- }
28106
- function recordBuildDuration(durationMs, labels) {
28107
- buildDuration().record(durationMs, {
28108
- kind: labels.kind,
28109
- tier: labels.tier,
28110
- method: labels.method
28111
- });
28112
- }
28113
- function recordBuildReadBytes(bytes, tier) {
28114
- if (typeof bytes !== "number" || !(bytes > 0))
28115
- return;
28116
- buildReadBytes().record(bytes, { tier });
28117
- }
28118
- function recordAnnotationFindings(warnings) {
28119
- for (const { code, severity } of warnings) {
28120
- if (!code)
28121
- continue;
28122
- annotationFindingsCounter().add(1, {
28123
- code,
28124
- outcome: severity === "error" ? "invalid" : "not_built"
28125
- });
28126
- }
28127
- }
28128
- function recordIncrementalStep(step, reason) {
28129
- incrementalStepCounter().add(1, reason ? { step, reason } : { step });
28130
- }
28131
- function recordBuildPlanComputeDuration(durationMs, computedIn) {
28132
- buildPlanComputeDuration().record(durationMs, { computed_in: computedIn });
28133
- }
28134
- function recordBuildPlanComputeFailed() {
28135
- buildPlanComputeFailedCounter().add(1);
28136
- }
28137
- function recordAutoLoadOutcome(outcome) {
28138
- autoLoadCounter().add(1, { outcome });
28139
- }
28140
- function recordConnectionDigestSkipped() {
28141
- connectionDigestSkipCounter().add(1);
28142
- }
28143
- function recordDuplicateTargetSkipped() {
28144
- duplicateTargetSkipCounter().add(1);
28145
- }
28146
- function recordSharedAddressInstructions() {
28147
- sharedAddressInstructionCounter().add(1);
28148
- }
28149
- function recordTableCollision() {
28150
- tableCollisionCounter().add(1);
28151
- }
28152
- function recordManifestBind(outcome) {
28153
- servedCopyBindCounter().add(1, {
28154
- scope: "manifest",
28155
- outcome,
28156
- reason: "none"
28157
- });
28158
- }
28159
- function recordSourceBound() {
28160
- servedCopyBindCounter().add(1, {
28161
- scope: "source",
28162
- outcome: "bound",
28163
- reason: "none"
28164
- });
28165
- }
28166
- function recordSourceDeclined(reason) {
28167
- servedCopyBindCounter().add(1, {
28168
- scope: "source",
28169
- outcome: "declined",
28170
- reason
28171
- });
28172
- }
28173
- function recordServedCopyOutcome(outcome, reason) {
28174
- servedCopyBindCounter().add(1, { scope: "source", outcome, reason });
28175
- }
28176
- function recordManifestBindDegraded() {
28177
- manifestBindDegradedCounter().add(1);
28178
- }
28179
- function recordDropTables(outcome, tier, occasion) {
28180
- dropTablesCounter().add(1, { outcome, tier, occasion });
28181
- }
28182
- function recordKeyCheck(kind, outcome) {
28183
- keyCheckCounter().add(1, { kind, outcome });
28184
- }
28185
- function recordQueryRouteDuration(durationMs, leg) {
28186
- queryRouteDuration().record(durationMs, { leg });
28187
- }
28188
- function recordStorageTableRetained() {
28189
- storageTableRetainedCounter().add(1);
28190
- }
28191
- function recordAttributionSkipped(reason) {
28192
- attributionSkippedCounter().add(1, { reason });
28193
- }
28194
- function recordEligibilityRefused(reason) {
28195
- const counts = eligibilityRefusalSink?.();
28196
- if (counts) {
28197
- counts[reason] = (counts[reason] ?? 0) + 1;
28198
- return;
28199
- }
28200
- eligibilityRefusedCounter().add(1, { reason });
28201
- }
28202
- function setEligibilityRefusalSink(sink) {
28203
- eligibilityRefusalSink = sink;
28204
- }
28205
- function recordStoredTypeFallback(kind) {
28206
- serveShapeTypeFallbackCounter().add(1, { kind });
28207
- }
28208
- function recordStoredColumnTypeMismatch(stage, declared) {
28209
- storedColumnTypeMismatchCounter().add(1, { stage, declared });
28210
- }
28211
- function recordQueryRoute(leg, outcome, reason) {
28212
- queryRouteCounter().add(1, { leg, outcome, reason });
28213
- }
28214
- function recordChainedStorageBuild(outcome) {
28215
- chainedStorageBuildCounter().add(1, { outcome });
28216
- }
28217
- function recordStaleUpstreamEntry(tier) {
28218
- staleUpstreamEntryCounter().add(1, { tier });
28219
- }
28220
- var BUILD_DURATION_BUCKETS_MS, BUILD_READ_BYTES_BUCKETS, runCounter, runDuration, buildCounter, buildDuration, buildReadBytes, annotationFindingsCounter, incrementalStepCounter, buildPlanComputeDuration, buildPlanComputeFailedCounter, autoLoadCounter, connectionDigestSkipCounter, servedCopyBindCounter, manifestBindDegradedCounter, duplicateTargetSkipCounter, sharedAddressInstructionCounter, tableCollisionCounter, dropTablesCounter, scheduledFireCounter, queryRouteCounter, queryRouteDuration, keyCheckCounter, storageTableRetainedCounter, attributionSkippedCounter, eligibilityRefusedCounter, serveShapeTypeFallbackCounter, storedColumnTypeMismatchCounter, chainedStorageBuildCounter, staleUpstreamEntryCounter, eligibilityRefusalSink;
28221
- var init_materialization_metrics = __esm(() => {
28222
- init_telemetry();
28223
- BUILD_DURATION_BUCKETS_MS = [
28224
- 100,
28225
- 500,
28226
- 1000,
28227
- 5000,
28228
- 15000,
28229
- 60000,
28230
- 300000,
28231
- 900000,
28232
- 3600000
28233
- ];
28234
- BUILD_READ_BYTES_BUCKETS = [1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000];
28235
- runCounter = lazyCounter("publisher_materialization_runs_total", "Materialization builds completed. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
28236
- runDuration = lazyHistogram("publisher_materialization_run_duration_ms", "Wall-clock duration of a materialization build. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
28237
- buildCounter = lazyCounter("publisher_materialization_build_total", "Source builds, one per source per run at its finish or failure. Labels: " + "kind ('materialize'|'persist'|'rollup'|'view'|'query'|'pair'), tier " + "('database'|'storage'), outcome ('built'|'reused'|'refused'|'failed'|" + "'cancelled'), failure_class ('none' unless outcome is 'failed'; then " + "'deterministic'|'transient'|'unclassified'|'billed_read_lost'). " + "'billed_read_lost' is the expensive one: the warehouse read ran and was " + "charged and its rows were not captured, so a retry pays for it again.");
28238
- buildDuration = lazyHistogram("publisher_materialization_build_duration_ms", "Wall-clock duration of one source's build, for builds that ran (built or " + "failed; a skipped incremental refresh did no work and is not timed). " + "Labels: kind, tier, method ('full'|'delta').", { buckets: BUILD_DURATION_BUCKETS_MS });
28239
- buildReadBytes = lazyHistogram("publisher_materialization_build_read_bytes", "Warehouse bytes scanned by one source's build read, when the warehouse " + "reported a count; absent otherwise, never zero. Label: tier.", { unit: "By", buckets: BUILD_READ_BYTES_BUCKETS });
28240
- annotationFindingsCounter = lazyCounter("publisher_annotation_findings_total", "Coded findings on authored annotations (the #@ route, and the near-miss and malformed-route scan over every route), counted once each time a package is loaded and accepted for serving (boot, add, publish, reload; a refused publish and a gate re-run count nothing). Labels: code (e.g. 'persist-unknown-key', 'persist-unparseable', 'persist-not-built'), outcome ('invalid' for an error-severity finding, which fails the load, 'not_built' for a warning: a valid annotation not built here, and also the warn-level 'annotation-near-miss' and 'persist-incremental-no-merge-key' advisories, which build).");
28241
- incrementalStepCounter = lazyCounter("publisher_materialization_incremental_step_total", 'Refreshes of a source declared refresh="incremental". Labels: step ' + "('delta'|'seed'|'skip'), and for seed/skip a bounded reason code " + "(IncrementalStepReasonCode). A 'seed' is a full rebuild the delta path " + "declined, so a rising seed rate means the feature is not engaging — and " + "the reason label says why without a log dive.");
28242
- buildPlanComputeDuration = lazyHistogram("publisher_materialization_build_plan_compute_duration_ms", "Wall-clock duration of compiling a package's build plan (Package.buildPlan).");
28243
- buildPlanComputeFailedCounter = lazyCounter("publisher_materialization_build_plan_compute_failed_total", "Package loads whose build plan failed to compute. The ROOT-CAUSE signal for " + "served_copy_bind{reason='build_plan_unavailable'}, which fires only " + "per declined entry per load -- a package that loads once and is never " + "reloaded ticks that counter once and then sits with its database tier " + "off and a flat total, indistinguishable from healthy.");
28244
- autoLoadCounter = lazyCounter("publisher_materialization_auto_load_total", "Auto-run manifest auto-load attempts. Label: outcome ('success'|'failure').");
28245
- connectionDigestSkipCounter = lazyCounter("publisher_materialization_connection_digest_skipped_total", "Connection digests skipped during build-plan compile because the connection did not resolve.");
28246
- servedCopyBindCounter = lazyCounter("publisher_served_copy_bind_total", "Serving's binds. Labels: scope ('manifest': one manifest bind, from REST, " + "auto-load or a rebind; 'source': one source deciding whether it " + "serves), outcome ('success'|'failure'|'timeout' for a manifest; " + "'bound'|'partial'|'declined' for a source: 'partial' is a source that " + "serves with a join read as written or left out), reason ('none' when " + "bound, else why: 'build_plan_unavailable' when the package's build " + "plan failed to compute, so every database source reverts to live; " + "'refused'; 'missing_table'; or the served copy's reason, as its " + "package warning, 'inline_join_kept' and 'cross_connection_join' being " + "the partial ones). Units differ by who counts: 'bound' and the bind's " + "declines count once per stored table per bind; the served copy counts " + "once per source per model per snapshot it compiles, 'declined' beating " + "'partial'. So a source two models read is counted by each, and the " + "outcomes do not sum to a number of sources. An extension table that " + "falls back to its own blocks ('compile_failed', 'reroot_not_compiled') " + "may still serve, and is counted 'declined'.");
28247
- manifestBindDegradedCounter = lazyCounter("publisher_materialization_manifest_bind_degraded_total", "Manifest entries bound with an UNQUOTED table path because their connection " + "could not be resolved (serve-side bind) or is absent from the build " + "(build-side seed). A misconfiguration that breaks the source on a " + "case-folding engine (Snowflake); alertable.");
28248
- duplicateTargetSkipCounter = lazyCounter("publisher_materialization_duplicate_target_skipped_total", "Sources skipped because the physical table they name was already built in " + "this run. Ordinary for a package that extends a persisted source; a " + "rising count against a package with no extension means the plan is " + "enumerating one table under more names than expected.");
28249
- sharedAddressInstructionCounter = lazyCounter("publisher_materialization_shared_address_instructions_total", "Content addresses that arrived with more than one instruction naming a " + "DIFFERENT physical table. The host minted a table per source where " + "several sources share one artifact. With a sourceID on each instruction " + "every table is built and only one is recorded, so the rest are orphaned; " + "without one the last instruction wins and the earlier names are never " + "built. Wasteful, not wrong — the table's CONTENT is the same either way.");
28250
- tableCollisionCounter = lazyCounter("publisher_materialization_table_collision_total", "Two definitions with DIFFERENT content addresses materializing into ONE " + "physical table. Each build overwrites the other's rows while both " + "addresses resolve to the table at serve time, so a query is answered " + "from another source's data. A wrong answer, not wasted work — page on " + "this one. Counted, then refused before any write, unless " + "PERSIST_COLLISION_ENFORCE=false opts out, in which case the build " + "continues.");
28251
- dropTablesCounter = lazyCounter("publisher_materialization_drop_tables_total", "Physical tables dropped. Labels: outcome ('success'|'failure'), tier " + "('database'|'storage'), occasion ('delete' when a caller deleted a " + "storage destination's table, since a run's delete is record-only; " + "'reclaim' when Publisher dropped it on its own: " + "a failed run's tables, a table a readable name replaced, an archived " + "or deleted version's tables; 'caller' when a caller dropped a " + "package's materialized database table through " + "DELETE .../materializedTables/{tableName}).");
28252
- scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
28253
- queryRouteCounter = lazyCounter("publisher_query_route_total", "The router's decision on each leg it considered for a query, counted once " + "the query is answered. Labels: leg ('view'|'query'|'rollup'|'materialized'|'live'; " + "'query' is a persisted named query), " + "outcome ('used'|'skipped'|'fallback': a chosen leg whose run failed and " + "was answered live), reason ('NONE' when used, else the path report's " + "SkipReason; 'READ_FAILED' with 'fallback'). A leg that does not apply to " + "the query is not counted; 'live' is counted 'used' when it answered a " + "query the router counted a leg for.");
28254
- queryRouteDuration = lazyHistogram("publisher_query_route_duration_ms", "Wall-clock time the router spent choosing how to answer a query, for a " + "query with at least one serving leg that applied: the row-level veto " + "and each leg's compile, up to the leg chosen. Not the query's run. " + "Label: leg ('view'|'query'|'rollup'|'materialized'|'live'), the one that " + "answered.");
28255
- keyCheckCounter = lazyCounter("publisher_materialization_key_check_total", "Key checks a run made over the rows it read or wrote. Labels: kind " + "('inline_join'|'rollup'|'parent'|'pair_leaf'|'stored'), outcome " + "('unique'|'not_unique'|'not_run'|'reused'). An inline_join that is " + "not_unique fails its build; every other not_unique or not_run leaves " + "the key unknown or repeated, so queries that need it unique are " + "answered live.");
28256
- storageTableRetainedCounter = lazyCounter("publisher_storage_tables_retained_total", "Tables a FAILED run left in a storage= destination and deliberately did not " + "reclaim, because the source is refreshed incrementally and the name may be " + "the one it serves from. Not all of these are orphans — " + "a rebuild at a fresh generational name is, a seed on the live serving name " + "is not, and the manifest entry cannot separate them — so read this as an " + "upper bound on what is accumulating rather than a leak count. It is the " + "only accounting there is until reclaiming a destination exists, which is " + "why it is a counter and not just a log line: the question is a rate, not " + "whether it ever happened. Unlabelled: the destination is on the warn " + "log that accompanies each count.");
28257
- attributionSkippedCounter = lazyCounter("publisher_storage_build_attribution_skipped_total", "storage= builds whose warehouse read went out UNATTRIBUTED while tagging was " + "on. Label: reason ('job_listing_unavailable'|'tag_failed'|" + "'read_row_not_found'|'read_row_ambiguous'|'cost_query_failed'). " + "The read still ran and the " + "build still succeeded — what was lost is the label in the customer's own " + "query history, and the cost on this side. Without this an operator who " + "turns tagging on and sees nothing has a single log line to go on.");
28258
- eligibilityRefusedCounter = lazyCounter("publisher_materialization_eligibility_refused_total", "Valid materialization declarations that are not built (`#@ persist`, " + "`#(materialize)`, a persisted view or query, a rollup), once per " + "declaration per plan derivation, and the refusals only a run finds. " + "Label: reason, the build plan refusal's `RefusedSource.reason` " + "(api-doc.yaml lists the values and which are retained and no " + "longer produced).");
28259
- serveShapeTypeFallbackCounter = lazyCounter("publisher_storage_serve_shape_type_fallback_total", "Captured DuckDB column types mapped to json in a stored table's declared " + "type (type fidelity loss). Named for the retired storage serve shape. " + "Label: kind ('array'|'unrecognized').");
28260
- storedColumnTypeMismatchCounter = lazyCounter("publisher_storage_column_type_mismatch_total", "Stored columns whose DuckDB type does not serve as the type Malloy " + "declares for them (ms2data/service#6642). Labels: stage ('build' = " + "found after a storage build; 'serve' = found when a model's bindings " + "are set, then cast on read or left out of the served copy so queries " + "reading it are answered live), declared (the Malloy type).");
28261
- chainedStorageBuildCounter = lazyCounter("publisher_storage_chained_build_total", "Chained storage= source builds (a source reading a storage-materialized " + "upstream). Label: outcome ('parent_reuse'|'inline_fallback'|" + "'strict_shape_fallback'|'strict_refused'|'infra_failure'). The " + "parent_reuse share is the headline signal for how far the " + "stack-on-the-parent path gets us vs recompute-from-raw.");
28262
- staleUpstreamEntryCounter = lazyCounter("publisher_materialization_stale_upstream_entry_total", "Builds that could not use an upstream's manifest entry because it is at a " + "different tier than the upstream is declared on now (ms2data/service#7087: " + "a source moved to or from storage= keeps its content address). The build " + "recomputes that upstream from raw instead, which reads the warehouse. " + "Label: tier ('database'|'storage'), the tier of the build that " + "recomputed.");
28263
- });
28264
-
28265
28087
  // src/process_safety.ts
28266
28088
  function describeRejection(reason) {
28267
28089
  let message;
@@ -28578,6 +28400,39 @@ function refusalKey(sourceID, name, reason, tier) {
28578
28400
  return { sourceID, name, tier, reason };
28579
28401
  }
28580
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
+
28581
28436
  // src/service/governance/ir/compiled_model.ts
28582
28437
  function modelDefOf(model) {
28583
28438
  return model._modelDef;
@@ -28705,6 +28560,7 @@ var init_dialect = __esm(() => {
28705
28560
  nestedColumns: false,
28706
28561
  driverKeepsBigIntegers: false,
28707
28562
  liveRoundsBigIntegersMeasured: false,
28563
+ liveWritesFloat4Shortest: false,
28708
28564
  castsToIntegerType: false,
28709
28565
  onlyBigIntegerType: undefined,
28710
28566
  foldsTableNameCase: false,
@@ -28744,7 +28600,8 @@ var init_dialect = __esm(() => {
28744
28600
  relationProbe: true,
28745
28601
  tableOwnership: true,
28746
28602
  castsToIntegerType: true,
28747
- liveRoundsBigIntegersMeasured: true
28603
+ liveRoundsBigIntegersMeasured: true,
28604
+ liveWritesFloat4Shortest: true
28748
28605
  }),
28749
28606
  standardsql: Object.freeze({
28750
28607
  ...NONE,
@@ -29378,7 +29235,6 @@ function persistDeclarationProblems(annotations) {
29378
29235
  }
29379
29236
  var ENV_REFERENCE_REASON, PERSIST_LINE_PATTERN, UNQUOTED_NAME_PATTERN, QUOTED_NAME_VALUE_PATTERN, SAFE_NAME_PATH;
29380
29237
  var init_persist_annotation_validation = __esm(() => {
29381
- init_errors2();
29382
29238
  init_annotation_reader();
29383
29239
  init_motly();
29384
29240
  init_table_name();
@@ -29386,7 +29242,7 @@ var init_persist_annotation_validation = __esm(() => {
29386
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";
29387
29243
  PERSIST_LINE_PATTERN = /^\s*#@\s+persist\b/;
29388
29244
  UNQUOTED_NAME_PATTERN = /(?<![.\w])name\s*=\s*(?!["'])/;
29389
- QUOTED_NAME_VALUE_PATTERN = /(?<![.\w])name\s*=\s*(["'])(.*?)\1/g;
29245
+ QUOTED_NAME_VALUE_PATTERN = /(?<![.\w])name\s*=\s*(["'])((?:\\.|(?!\1)[^\\])*)\1/g;
29390
29246
  SAFE_NAME_PATH = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
29391
29247
  });
29392
29248
 
@@ -31345,6 +31201,25 @@ function persistedViewRefusalFinding(refusal, model) {
31345
31201
  refused: resultRefusalKey(persistedViewBuildName(refusal.sourceName, refusal.viewName), splitSourceID(refusal.sourceID)?.url ?? "", outcome.refused, refusal.storage)
31346
31202
  };
31347
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
+ }
31348
31223
  function resultRefusalKey(buildSourceName, declaringURL, reason, storage) {
31349
31224
  return refusalKey(`${buildSourceName}@${persistedViewCompanionHref(declaringURL)}`, buildSourceName, reason, tierOf(storage));
31350
31225
  }
@@ -31423,7 +31298,7 @@ function persistedQueryRefusalFinding(refusal, model) {
31423
31298
  function persistedQueryRefusalKey(queryName, declaringURL, reason, storage) {
31424
31299
  return resultRefusalKey(persistedQueryBuildName(queryName), declaringURL, reason, storage);
31425
31300
  }
31426
- 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";
31427
31302
  var init_persisted_view = __esm(() => {
31428
31303
  init_annotation_reader();
31429
31304
  init_declared_notes();
@@ -31453,6 +31328,29 @@ var init_storage_table_path = __esm(() => {
31453
31328
  init_dialect();
31454
31329
  });
31455
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
+
31456
31354
  // src/service/http_retry.ts
31457
31355
  function publicMessage(error) {
31458
31356
  const own = error?.publicMessage;
@@ -32947,7 +32845,7 @@ function deriveColumns(persistSource) {
32947
32845
  } catch (err) {
32948
32846
  logger.warn("Failed to derive columns for persist source", {
32949
32847
  sourceID: persistSource.sourceID,
32950
- error: errMessage(err)
32848
+ code: errorCodeOf(err)
32951
32849
  });
32952
32850
  return [];
32953
32851
  }
@@ -32964,9 +32862,9 @@ function declaresEmptyStorage(persistSource) {
32964
32862
  return tag !== undefined && "refused" in placementOf(tag, "persist");
32965
32863
  }
32966
32864
  var init_persist_source_fields = __esm(() => {
32865
+ init_error_code();
32967
32866
  init_declaration();
32968
32867
  init_logger();
32969
- init_utils();
32970
32868
  });
32971
32869
 
32972
32870
  // src/service/materialization/plan/addressing.ts
@@ -33105,7 +33003,7 @@ function compilerBuildId(source, target) {
33105
33003
  function addressDestination(source) {
33106
33004
  if (!getPersistAddressIncludesDestination())
33107
33005
  return;
33108
- if (getPersistStorageMode() === "off")
33006
+ if (!storageWritable(getPersistStorageMode()))
33109
33007
  return;
33110
33008
  try {
33111
33009
  return declaredStorage(source);
@@ -33235,7 +33133,7 @@ function foldDistinctTableNames(plan, storedColumns) {
33235
33133
  return folds;
33236
33134
  }
33237
33135
  function storedTierOf(source) {
33238
- if (getPersistStorageMode() === "off")
33136
+ if (!storageWritable(getPersistStorageMode()))
33239
33137
  return "";
33240
33138
  try {
33241
33139
  return declaredStorage(source)?.trim() ?? "";
@@ -33294,6 +33192,9 @@ var init_addressing = __esm(() => {
33294
33192
  testAddresses = new WeakMap;
33295
33193
  });
33296
33194
 
33195
+ // src/service/materialization/domain/vocabulary.ts
33196
+ var init_vocabulary = () => {};
33197
+
33297
33198
  // src/service/materialization/domain/gate_policy.ts
33298
33199
  function ownRowLevelGate(t) {
33299
33200
  return t.gate?.rowLevel === true && t.gate.attributed && !t.gate.inheritedRowFilter;
@@ -33348,6 +33249,7 @@ function answerKeepsGates(leg, tablesRead, s, ctx) {
33348
33249
  }
33349
33250
  var ROWS, GATE_LEGS, SERVING_GATE_CONTEXT, INEXACT_GATE_TYPE;
33350
33251
  var init_gate_policy = __esm(() => {
33252
+ init_vocabulary();
33351
33253
  ROWS = {
33352
33254
  persist: (t) => persistKeepsGates(t),
33353
33255
  materialize: (t, s) => materializedKeepsGates(t, s),
@@ -33355,7 +33257,11 @@ var init_gate_policy = __esm(() => {
33355
33257
  rollup: (t, s) => !t.v1 && t.baseGateProven === true && (t.gate?.lockOnly === true || s.gatedSources || ownRowLevelGate(t)),
33356
33258
  view: () => false
33357
33259
  };
33358
- GATE_LEGS = ["view", "rollup", "served"];
33260
+ GATE_LEGS = [
33261
+ "view",
33262
+ "rollup",
33263
+ "served"
33264
+ ];
33359
33265
  SERVING_GATE_CONTEXT = {
33360
33266
  databaseReadsKeepGates: true
33361
33267
  };
@@ -33568,6 +33474,76 @@ function buildReadsCurrentTime(persistSource) {
33568
33474
  return true;
33569
33475
  }
33570
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
+ }
33571
33547
  function queryReadsCurrentTime(query, depth) {
33572
33548
  if (depth > MAX_WALK_DEPTH2)
33573
33549
  return true;
@@ -33926,14 +33902,66 @@ function readsCurrentTime(node, depth = 0) {
33926
33902
  const record = node;
33927
33903
  if (record.node === "now")
33928
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
+ }
33929
33911
  for (const [key, value] of Object.entries(record)) {
33930
- if (key === "at" || key === "location" || key === "annotations")
33912
+ if (key === "at" || key === "location" || key === "annotations" || key === "stableFilter") {
33931
33913
  continue;
33914
+ }
33932
33915
  if (readsCurrentTime(value, depth + 1))
33933
33916
  return true;
33934
33917
  }
33935
33918
  return false;
33936
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
+ }
33937
33965
  function readNow(e) {
33938
33966
  if (!e || typeof e !== "object")
33939
33967
  return;
@@ -34093,13 +34121,14 @@ function fieldsDependingOn(fields, reads, depth = 0) {
34093
34121
  }
34094
34122
  return out;
34095
34123
  }
34096
- 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;
34097
34125
  var init_persist_dynamic_terms = __esm(() => {
34098
34126
  init_declaration();
34099
34127
  init_given();
34100
34128
  init_probe_compiler();
34101
34129
  init_array_query();
34102
34130
  init_read_time_terms();
34131
+ import_malloy_filter2 = __toESM(require_dist());
34103
34132
  STAGE_PATH_SKIPPED_KEYS = new Set([
34104
34133
  "at",
34105
34134
  "location",
@@ -34113,6 +34142,16 @@ var init_persist_dynamic_terms = __esm(() => {
34113
34142
  "refSummary",
34114
34143
  "referenceID"
34115
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
+ ]);
34116
34155
  COMPARISONS = new Set([">=", ">", "<", "<="]);
34117
34156
  MIRROR = {
34118
34157
  ">=": "<=",
@@ -34123,6 +34162,19 @@ var init_persist_dynamic_terms = __esm(() => {
34123
34162
  FIELD_PATH_SKIPPED_KEYS = new Set(["at", "location", "annotations"]);
34124
34163
  });
34125
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
+
34126
34178
  // src/service/materialization/domain/key_check.ts
34127
34179
  function requireUnique(verdict) {
34128
34180
  return verdict === "unique";
@@ -37573,7 +37625,7 @@ function declarationRefusal(decl, facts, ctx) {
37573
37625
  measure: decl.measure
37574
37626
  };
37575
37627
  }
37576
- const timeRead = facts.windowed ? "the source's rows read the current time (a `where:` with `now`, a rolling window)" : timeFields.has(decl.measure) ? "the measure reads the current time (`now`)" : decl.grain.filter((g) => timeFields.has(g)).map((g) => `its grain dimension \`${g}\` reads the current time (\`now\`)`)[0];
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];
37577
37629
  if (timeRead) {
37578
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`);
37579
37631
  }
@@ -37861,6 +37913,15 @@ function planModelRollups(map, ctx, declaredHere) {
37861
37913
  }
37862
37914
  return { plans, refused };
37863
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
+ }
37864
37925
  function rollupRefusalFinding(refusal, model) {
37865
37926
  return {
37866
37927
  route: ROLLUP_ROUTE,
@@ -38187,6 +38248,13 @@ function referencesAuthorize(persistSource) {
38187
38248
  return true;
38188
38249
  }
38189
38250
  }
38251
+ function irCarriesAGate(def) {
38252
+ try {
38253
+ return walkForAuthorize(def, new WeakSet, 0);
38254
+ } catch {
38255
+ return true;
38256
+ }
38257
+ }
38190
38258
  function isAuthorizeAnnotation(text) {
38191
38259
  try {
38192
38260
  return parseAuthorizeAnnotation(text) !== null;
@@ -38423,11 +38491,38 @@ function assertBuildReadsNoCurrentTime(source, plan) {
38423
38491
  return;
38424
38492
  if (!buildReadsCurrentTime(source))
38425
38493
  return;
38494
+ const why = currentTimeRefusalCause(source, plan);
38495
+ if (why === undefined)
38496
+ return;
38426
38497
  throw new MaterializationEligibilityError({
38427
38498
  reason: "current_time",
38428
- message: `Source '${source.name}' cannot be materialized: the relation it ` + `persists reads the current time (\`now\`), in its query, a view ` + `it runs, the \`where:\`, a field or a join of the source that ` + `query reads, or the query of a query-shaped source it is built ` + `from or joins. Its table would hold the rows as of the build and ` + `serve them until the next rebuild, while a live query reads \`now\` ` + `again every time, so it is not built and is answered live. To serve ` + `it from a table, move the \`now\` into the persisted source's own ` + `extend block (a \`where:\`, dimension or measure there is applied ` + `at every read), or stop persisting this source.`
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).`
38429
38500
  });
38430
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
+ }
38431
38526
  var READ_ONLY_DIALECTS, MAX_AUTHORIZE_WALK_DEPTH = 200;
38432
38527
  var init_materialization_eligibility = __esm(() => {
38433
38528
  init_config2();
@@ -40274,7 +40369,8 @@ function withoutSources(compiled, findings, drop) {
40274
40369
  function tierGateInputs(compiled) {
40275
40370
  return {
40276
40371
  tables: compiled.tables,
40277
- connectionTypes: compiled.connectionTypes
40372
+ connectionTypes: compiled.connectionTypes,
40373
+ accessReads: compiled.accessReads
40278
40374
  };
40279
40375
  }
40280
40376
  function collectSourceEligibility(compiled, verdicts = planVerdicts(compiled)) {
@@ -40314,8 +40410,8 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
40314
40410
  logger.warn("Dropping a refused database source: its content address could not be computed", {
40315
40411
  sourceID,
40316
40412
  sourceName: source.name,
40317
- refusal: errMessage(err),
40318
- error: errMessage(idErr)
40413
+ reason: errorCodeOf(err),
40414
+ code: errorCodeOf(idErr)
40319
40415
  });
40320
40416
  continue;
40321
40417
  }
@@ -40327,7 +40423,7 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
40327
40423
  try {
40328
40424
  sourceEntityId = planAddressOf(compiled, sourceID);
40329
40425
  } catch (err) {
40330
- 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) });
40331
40427
  continue;
40332
40428
  }
40333
40429
  if (!(sourceEntityId in refused)) {
@@ -40480,6 +40576,7 @@ function databaseRefusalsByAddress(compiled, verdicts, include) {
40480
40576
  }
40481
40577
  var EligibilityCheckFailed;
40482
40578
  var init_eligibility_collect = __esm(() => {
40579
+ init_error_code();
40483
40580
  init_errors2();
40484
40581
  init_storage_table_path();
40485
40582
  init_table_name();
@@ -40568,10 +40665,10 @@ function planCollisions(plan, materializePlans, versionScoped) {
40568
40665
  }
40569
40666
  return out;
40570
40667
  }
40571
- function incrementalPolicySourcesOf(plan, declarations, materializePlans, persistedViews = new Map) {
40668
+ function incrementalPolicySourcesOf(plan, declarations, materializePlans, persistedViews = {}) {
40572
40669
  return Object.entries(plan?.sources ?? {}).filter(([sourceID]) => declarations[sourceID]).map(([sourceID, source]) => ({
40573
- ...persistedViews.get(sourceID) ?? { sourceName: source.name },
40574
- invalidCode: persistedViews.has(sourceID) ? PERSIST_VIEW_INVALID_CODE : materializePlans?.[sourceID] ? MATERIALIZE_INVALID_CODE : PERSIST_INVALID_CODE,
40670
+ ...persistedViews[sourceID] ?? { sourceName: source.name },
40671
+ invalidCode: persistedViews[sourceID] ? PERSIST_VIEW_INVALID_CODE : materializePlans?.[sourceID] ? MATERIALIZE_INVALID_CODE : PERSIST_INVALID_CODE,
40575
40672
  ...source.modelPath ? { modelPath: source.modelPath } : {},
40576
40673
  ...source.dialect ? { dialect: source.dialect } : {},
40577
40674
  ...source.annotationFields?.storage ? { storageDestination: source.annotationFields.storage } : {},
@@ -40586,15 +40683,27 @@ function collisionGateLines(collisions) {
40586
40683
  return collisions.map((c) => codedLine(c.enforced, MATERIALIZATION_TABLE_COLLISION_CODE));
40587
40684
  }
40588
40685
  function loadGateText(gated, judgement) {
40589
- return [
40686
+ return withNameProblems(gated.modelGateLines?.nameProblems ?? [], [
40590
40687
  ...invalidFindingLines(gated.annotationFindings.map((f) => relaxedCollision(f, judgement.enforceCollisions))),
40591
40688
  ...judgement.enforceCollisions ? collisionGateLines(planCollisions(gated.plan, gated.materializePlans, judgement.versionScoped)) : [],
40592
- ...incrementalGateLines(incrementalPolicySourcesOf(gated.plan, gated.incrementalDeclarations, gated.materializePlans, judgement.persistedViews)),
40689
+ ...incrementalGateLines(incrementalPolicySourcesOf(gated.plan, gated.incrementalDeclarations, gated.materializePlans, gated.persistedViews)),
40593
40690
  ...gated.modelGateLines?.preaggregate ?? [],
40594
40691
  ...gated.modelGateLines?.nearMiss ?? []
40595
- ].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(`
40596
40702
  `);
40597
40703
  }
40704
+ function unescapedTagValue(raw) {
40705
+ return raw.replace(/\\(.)/g, "$1");
40706
+ }
40598
40707
  function preaggregateViolationCode(code) {
40599
40708
  if (code === "unknown_key")
40600
40709
  return "rollup-unknown-key";
@@ -40820,6 +40929,177 @@ var init_annotation_near_miss = __esm(() => {
40820
40929
  ]);
40821
40930
  });
40822
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
+
40823
41103
  // src/service/materialization/plan/incremental_declaration.ts
40824
41104
  function safeTag(source) {
40825
41105
  try {
@@ -41179,6 +41459,9 @@ async function compileInMemory(files, entry, connections, options = {}) {
41179
41459
  const model = await runtime.loadModel(new URL(entry), options.importBaseURL ? options : undefined).getModel();
41180
41460
  return { runtime, model };
41181
41461
  }
41462
+ function companionFailure(kind, error) {
41463
+ return { kind, error };
41464
+ }
41182
41465
  function companionOmissions(kind, planned) {
41183
41466
  const reason = COMPANION_FAILED[kind];
41184
41467
  return "sourceIDs" in planned ? omittedByID(planned.sourceIDs, reason) : omittedFromFile(planned.file, planned.names, reason);
@@ -41855,7 +42138,7 @@ async function tryCompileMaterializeCompanion(args) {
41855
42138
  const foreign = await crossFileParents(planned.plans, args, modelFile).catch((error) => {
41856
42139
  logger.warn("A model's extension tables could not be chained on parents in other files; they build over the raw chain", {
41857
42140
  modelPath: args.modelPath,
41858
- error: error instanceof Error ? error.message : String(error)
42141
+ code: errorCodeOf(error)
41859
42142
  });
41860
42143
  return { plans: planned.plans, parents: new Map };
41861
42144
  });
@@ -41880,12 +42163,9 @@ async function tryCompileMaterializeCompanion(args) {
41880
42163
  }
41881
42164
  return round.generated ? { generated: withStoredColumns(round.generated), refused } : { refused };
41882
42165
  } catch (error) {
41883
- logger.error("Failed to plan or compile the generated #(materialize) companion", {
41884
- modelPath: args.modelPath,
41885
- error: error instanceof Error ? error.message : String(error)
41886
- });
41887
42166
  return {
41888
42167
  refused,
42168
+ failure: companionFailure("materialize", error),
41889
42169
  omitted: companionOmissions("materialize", plannedIDs ? {
41890
42170
  sourceIDs: plannedIDs.filter((id) => !refused.some((r) => r.sourceID === id))
41891
42171
  } : { file: pathToFileURL8(modelFile).href, names: undefined })
@@ -41932,11 +42212,10 @@ async function unchainStoredChainsNotCompiling(round, compile, args, foreign = N
41932
42212
  const unstored = round.generated ? await storedChainsNotCompiling(round.generated, foreign.parents) : new Map;
41933
42213
  if (unstored.size === 0)
41934
42214
  return round;
41935
- for (const [sourceID, error] of unstored) {
42215
+ for (const sourceID of unstored.keys()) {
41936
42216
  logger.warn("A storage= extension table does not compile over its parent's stored table alone; it builds over the raw chain", {
41937
42217
  modelPath: args.modelPath,
41938
- sourceName: planOf(round.plans, sourceID)?.sourceName,
41939
- error
42218
+ sourceName: planOf(round.plans, sourceID)?.sourceName
41940
42219
  });
41941
42220
  }
41942
42221
  return compile(round.plans.map((p) => unstored.has(p.sourceID) ? withoutParent(p) : p));
@@ -42544,11 +42823,11 @@ function nextRound(error, plans, copies, ctx) {
42544
42823
  } : p);
42545
42824
  }
42546
42825
  if (plan?.buildsOver) {
42547
- logger.warn("An extension table of a #(materialize) model did not compile over its parent's build source; it builds over the raw chain", { modelPath, sourceName: plan.sourceName, error: error.message });
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) });
42548
42827
  return plans.map((p) => p === plan ? withoutParent(p) : p);
42549
42828
  }
42550
42829
  if (plan) {
42551
- logger.error("A #(materialize) source's generated build did not compile; it is not built, and the model's other sources are", { modelPath, sourceName: plan.sourceName, error: error.message });
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) });
42552
42831
  ctx.refuse({
42553
42832
  sourceName: plan.sourceName,
42554
42833
  sourceID: plan.sourceID,
@@ -42563,7 +42842,7 @@ function nextRound(error, plans, copies, ctx) {
42563
42842
  return plans.filter((p) => p !== plan);
42564
42843
  }
42565
42844
  if (plans.some((p) => p.buildsOver)) {
42566
- logger.warn("Extension tables of a #(materialize) model did not compile over their parents' build sources; they build over the raw chain", { modelPath, error: error.message });
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) });
42567
42846
  return plans.map(withoutParent);
42568
42847
  }
42569
42848
  throw error.error;
@@ -42589,9 +42868,10 @@ async function crossFileParents(plans, args, modelFile) {
42589
42868
  const url = pathToFileURL8(file);
42590
42869
  const { model, materializer } = await files.compile(url);
42591
42870
  const def = modelDefOf(model);
42592
- const { generated } = await tryCompileMaterializeCompanion({
42871
+ const modelPath = relative.split(path13.sep).join("/");
42872
+ const { generated, failure } = await tryCompileMaterializeCompanion({
42593
42873
  packagePath: args.packagePath,
42594
- modelPath: relative.split(path13.sep).join("/"),
42874
+ modelPath,
42595
42875
  contents: def.contents ?? {},
42596
42876
  givens: def.givens ?? {},
42597
42877
  getRuntime: args.getRuntime,
@@ -42599,6 +42879,8 @@ async function crossFileParents(plans, args, modelFile) {
42599
42879
  crossFileStack: stack,
42600
42880
  crossFileCompanions: companions
42601
42881
  });
42882
+ if (failure)
42883
+ logCompanionFailure(failure, modelPath);
42602
42884
  return {
42603
42885
  ...generated ? { generated } : {},
42604
42886
  text: await files.read(url),
@@ -42609,7 +42891,7 @@ async function crossFileParents(plans, args, modelFile) {
42609
42891
  logger.warn("An extension table's parent in another file could not be planned here; it builds over the raw chain", {
42610
42892
  modelPath: args.modelPath,
42611
42893
  parentFile: path13.relative(args.packagePath, file),
42612
- error: error instanceof Error ? error.message : String(error)
42894
+ code: errorCodeOf(error)
42613
42895
  });
42614
42896
  return;
42615
42897
  });
@@ -42853,8 +43135,15 @@ async function withCrossFileColumnsKept(round, compile, args, foreign) {
42853
43135
  const ids = new Set(differ.map((p) => p.sourceID));
42854
43136
  return compile(round.plans.map((p) => ids.has(p.sourceID) ? withoutParent(p) : p));
42855
43137
  }
42856
- 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;
42857
43145
  var init_materialize_compile = __esm(() => {
43146
+ init_error_code();
42858
43147
  init_malloy_text();
42859
43148
  init_logger();
42860
43149
  init_dialect();
@@ -42895,6 +43184,13 @@ var init_materialize_compile = __esm(() => {
42895
43184
  plans: [],
42896
43185
  parents: new Map
42897
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
+ };
42898
43194
  });
42899
43195
 
42900
43196
  // src/service/materialization/plan/persisted_view_compile.ts
@@ -42948,12 +43244,7 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42948
43244
  reason: "the view has no stage to store",
42949
43245
  refusal: "no_stored_columns"
42950
43246
  };
42951
- if (pipelineReadsCurrentTime(def, stages)) {
42952
- return {
42953
- reason: "its result reads the current time, so it differs per read",
42954
- refusal: "current_time"
42955
- };
42956
- }
43247
+ const readsNow = pipelineReadsCurrentTime(def, stages);
42957
43248
  const last = stages[stages.length - 1];
42958
43249
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
42959
43250
  return {
@@ -42964,6 +43255,12 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
42964
43255
  const gates = collectEntryPointGates(node.def, modelDef);
42965
43256
  if (gates.length === 0)
42966
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
+ }
42967
43264
  const gateRefusal = gateRefusalReason(gates.map((g) => g.route));
42968
43265
  if (gates.some((g) => !g.struct)) {
42969
43266
  return {
@@ -43086,12 +43383,6 @@ async function persistedQueryRefusalReason(plan, modelDef, materializer) {
43086
43383
  reason: "its source cannot be read",
43087
43384
  refusal: "run_target_unsupported"
43088
43385
  };
43089
- if (pipelineReadsCurrentTime(def, stages)) {
43090
- return {
43091
- reason: "its result reads the current time, so it differs per read",
43092
- refusal: "current_time"
43093
- };
43094
- }
43095
43386
  const last = stages[stages.length - 1];
43096
43387
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
43097
43388
  return {
@@ -43186,13 +43477,10 @@ async function tryCompilePersistedViewCompanion(args) {
43186
43477
  refusedQueries
43187
43478
  };
43188
43479
  } catch (error) {
43189
- logger.error("Failed to plan or compile the generated persisted-view companion", {
43190
- modelPath: args.modelPath,
43191
- error: error instanceof Error ? error.message : String(error)
43192
- });
43193
43480
  return {
43194
43481
  refused,
43195
43482
  refusedQueries,
43483
+ failure: companionFailure("persisted_view", error),
43196
43484
  omitted: companionOmissions("persisted_view", {
43197
43485
  file: companionHref,
43198
43486
  names: plannedNames
@@ -43202,7 +43490,6 @@ async function tryCompilePersistedViewCompanion(args) {
43202
43490
  }
43203
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";
43204
43492
  var init_persisted_view_compile = __esm(() => {
43205
- init_logger();
43206
43493
  init_annotations();
43207
43494
  init_annotation_reader();
43208
43495
  init_authorize();
@@ -43401,9 +43688,12 @@ async function tryCompileRollupCompanion(args) {
43401
43688
  if (!text)
43402
43689
  return { refused };
43403
43690
  if (!overlay) {
43404
- logger.error("A #(rollup) companion was not built: a `#@` line of the author's files could not be left out of it", { modelPath: args.modelPath });
43405
43691
  return {
43406
43692
  refused,
43693
+ failure: {
43694
+ kind: "rollup_blanking",
43695
+ error: "a `#@` line of the author's files could not be set aside"
43696
+ },
43407
43697
  omitted: companionOmissions("rollup_blanking", {
43408
43698
  file: companionHref,
43409
43699
  names: plannedNames
@@ -43442,12 +43732,9 @@ async function tryCompileRollupCompanion(args) {
43442
43732
  refused
43443
43733
  };
43444
43734
  } catch (error) {
43445
- logger.error("Failed to plan or compile the generated #(rollup) companion", {
43446
- modelPath: args.modelPath,
43447
- error: error instanceof Error ? error.message : String(error)
43448
- });
43449
43735
  return {
43450
43736
  refused,
43737
+ failure: companionFailure("rollup", error),
43451
43738
  omitted: companionOmissions("rollup", {
43452
43739
  file: companionHref,
43453
43740
  names: plannedNames
@@ -43486,7 +43773,7 @@ async function compileOverStoredBases(args) {
43486
43773
  logger.warn("A rollup builds from the warehouse: its #(materialize) base's copy over the stored table did not compile", {
43487
43774
  modelPath: args.modelPath,
43488
43775
  base: name,
43489
- error: error instanceof Error ? error.message : String(error)
43776
+ code: errorCodeOf(error)
43490
43777
  });
43491
43778
  stored.delete(name);
43492
43779
  }
@@ -43500,7 +43787,7 @@ async function compileOverStoredBases(args) {
43500
43787
  }
43501
43788
  logger.warn("The rollups over #(materialize) bases build from the warehouse: their companion over the bases' stored tables did not compile", {
43502
43789
  modelPath: args.modelPath,
43503
- error: error instanceof Error ? error.message : String(error)
43790
+ code: errorCodeOf(error)
43504
43791
  });
43505
43792
  out.clear();
43506
43793
  try {
@@ -43547,7 +43834,7 @@ async function compileOverStoredBases(args) {
43547
43834
  function warnWarehouse(modelPath, error) {
43548
43835
  logger.warn("The rollups of a model build from the warehouse: their companion over the bases' stored tables did not compile", {
43549
43836
  modelPath,
43550
- error: error instanceof Error ? error.message : String(error)
43837
+ code: errorCodeOf(error)
43551
43838
  });
43552
43839
  }
43553
43840
  function parentKeyCheckCompiler(materializer) {
@@ -43569,7 +43856,7 @@ async function compileParentKeyChecks(plans, needs, joinedKeys = []) {
43569
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", {
43570
43857
  source: name,
43571
43858
  keyColumn,
43572
- error: error instanceof Error ? error.message : String(error)
43859
+ code: errorCodeOf(error)
43573
43860
  });
43574
43861
  return;
43575
43862
  });
@@ -43630,12 +43917,13 @@ async function compileRollupKeyChecks(plans, materializer, modelPath) {
43630
43917
  logger.warn("A #(rollup) rollup's key check did not compile", {
43631
43918
  modelPath,
43632
43919
  rollup: plan.rollupSourceName,
43633
- error: error instanceof Error ? error.message : String(error)
43920
+ code: errorCodeOf(error)
43634
43921
  });
43635
43922
  }
43636
43923
  }
43637
43924
  }
43638
43925
  var init_rollup_compile = __esm(() => {
43926
+ init_error_code();
43639
43927
  init_config2();
43640
43928
  init_logger();
43641
43929
  init_prepared_query();
@@ -43692,16 +43980,104 @@ var init_v1_build_companion = __esm(() => {
43692
43980
  init_generated_files();
43693
43981
  });
43694
43982
 
43695
- // src/service/materialization/domain/compiled_build_plan.ts
43696
- function* sourcesInBuildOrder(build, tables) {
43697
- for (const sourceID of build.order) {
43698
- const source = tables[sourceID]?.source;
43699
- if (source)
43700
- yield source;
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
+ }
43701
44013
  }
43702
44014
  }
43703
- function materializePlansOf(tables) {
43704
- 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: [] };
43705
44081
  }
43706
44082
 
43707
44083
  // src/service/materialization/plan/build_plan.ts
@@ -43775,7 +44151,7 @@ async function resolvePackageConnections(pkg, names) {
43775
44151
  map.set(name, await pkg.getMalloyConnection(name));
43776
44152
  } catch (err) {
43777
44153
  logger.warn(`Failed to resolve connection ${name}`, {
43778
- error: errMessage(err)
44154
+ code: errorCodeOf(err)
43779
44155
  });
43780
44156
  }
43781
44157
  }
@@ -43862,7 +44238,7 @@ async function classifyPersistSourceGate(persistSource, modelDef, materializer,
43862
44238
  } catch (err) {
43863
44239
  logger.warn("Failed to classify persist source gate; refusing", {
43864
44240
  sourceID: persistSource.sourceID,
43865
- error: errMessage(err)
44241
+ code: errorCodeOf(err)
43866
44242
  });
43867
44243
  return { classification: "rejected", attributed: false };
43868
44244
  }
@@ -43873,8 +44249,10 @@ function emptyBuildPlanParts() {
43873
44249
  tables: {},
43874
44250
  droppedPersistSources: [],
43875
44251
  annotationFindings: [],
43876
- modelGateLines: { preaggregate: [], nearMiss: [] },
43877
- omittedSources: []
44252
+ modelGateLines: noModelGateLines(),
44253
+ persistedViews: {},
44254
+ omittedSources: [],
44255
+ accessReads: []
43878
44256
  };
43879
44257
  }
43880
44258
  function mergeBuildPlanParts(into, from) {
@@ -43887,6 +44265,11 @@ function mergeBuildPlanParts(into, from) {
43887
44265
  }
43888
44266
  into.modelGateLines.preaggregate.push(...from.modelGateLines.preaggregate);
43889
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();
43890
44273
  }
43891
44274
  function addAnnotationFinding(parts, finding) {
43892
44275
  const key = (f) => [f.code, f.model ?? "", f.subject ?? "", f.message].join("\x00");
@@ -43928,10 +44311,12 @@ function sourceIDFileURL(sourceID) {
43928
44311
  const url = splitSourceID(sourceID)?.url;
43929
44312
  return url?.startsWith("file:") ? url : undefined;
43930
44313
  }
43931
- function addCompanionOutcome(parts, findings, omitted) {
44314
+ function addCompanionOutcome(parts, findings, omitted, failed) {
43932
44315
  for (const finding of findings)
43933
44316
  addAnnotationFinding(parts, finding);
43934
44317
  parts.omittedSources.push(...omitted ?? []);
44318
+ if (failed?.failure)
44319
+ logCompanionFailure(failed.failure, failed.modelPath);
43935
44320
  }
43936
44321
  function withoutGivenReadingTargets(all, refuse) {
43937
44322
  for (const target of all.connections.flatMap((c) => c.targets)) {
@@ -43954,14 +44339,14 @@ function gateDepsFor(model, modelPath) {
43954
44339
  }
43955
44340
  async function collectGeneratedMaterialize(parts, args) {
43956
44341
  const authorDef = modelDefOf(args.malloyModel);
43957
- const { generated, refused, omitted } = await tryCompileMaterializeCompanion({
44342
+ const { generated, refused, omitted, failure } = await tryCompileMaterializeCompanion({
43958
44343
  ...args,
43959
44344
  contents: authorDef.contents ?? {},
43960
44345
  givens: authorDef.givens ?? {},
43961
44346
  sourceRegistry: authorDef.sourceRegistry,
43962
44347
  probe: args.materializer
43963
44348
  });
43964
- 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 });
43965
44350
  if (!generated)
43966
44351
  return;
43967
44352
  for (const [key, compile] of generated.checkCompilers) {
@@ -44017,8 +44402,8 @@ async function authorSourceGate(sourceID, authorDef, args) {
44017
44402
  return authorSource ? await classifyPersistSourceGate({ _sourceDef: authorSource, sourceID }, authorDef, args.materializer, args.deps, args.modelPath) : { classification: "rejected", attributed: false };
44018
44403
  }
44019
44404
  async function collectGeneratedRollups(parts, args) {
44020
- const { generated, refused, omitted } = await tryCompileRollupCompanion(args);
44021
- 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 });
44022
44407
  if (!generated)
44023
44408
  return;
44024
44409
  const planByName = new Map(generated.plans.map((p) => [p.rollupSourceName, p]));
@@ -44026,18 +44411,7 @@ async function collectGeneratedRollups(parts, args) {
44026
44411
  const plan = planByName.get(source.name);
44027
44412
  if (!plan)
44028
44413
  return;
44029
- addAnnotationFinding(parts, rollupRefusalFinding({
44030
- tier: "unservable",
44031
- code: ROLLUP_NOT_BUILT_CODE,
44032
- message: `#(rollup) rollup of source "${plan.baseSourceName}" at ` + `(${plan.grainDimensions.join(", ")}) is not built, so its measures ` + "are served live: its rows read a given, and a table holds one " + "value's rows.",
44033
- sourceName: plan.baseSourceName,
44034
- refused: {
44035
- sourceID: source.sourceID,
44036
- name: source.name,
44037
- tier: tierOf(plan.storage),
44038
- reason: "reads_given"
44039
- }
44040
- }, args.modelPath));
44414
+ addAnnotationFinding(parts, rollupRefusalFinding(rollupReadsGivenRefusal(plan, source), args.modelPath));
44041
44415
  });
44042
44416
  const kept = [];
44043
44417
  for (const source of plannedSources(targets)) {
@@ -44064,7 +44438,7 @@ async function collectGeneratedRollups(parts, args) {
44064
44438
  }
44065
44439
  async function collectGeneratedPersistedViews(parts, args) {
44066
44440
  const authorDef = modelDefOf(args.malloyModel);
44067
- const { generated, refused, refusedQueries, omitted } = await tryCompilePersistedViewCompanion({
44441
+ const { generated, refused, refusedQueries, omitted, failure } = await tryCompilePersistedViewCompanion({
44068
44442
  packagePath: args.packagePath,
44069
44443
  modelPath: args.modelPath,
44070
44444
  modelDef: authorDef,
@@ -44074,29 +44448,24 @@ async function collectGeneratedPersistedViews(parts, args) {
44074
44448
  addCompanionOutcome(parts, [
44075
44449
  ...refused.map((r) => persistedViewRefusalFinding(r, args.modelPath)),
44076
44450
  ...refusedQueries.map((r) => persistedQueryRefusalFinding(r, args.modelPath))
44077
- ], omitted);
44451
+ ], omitted, { failure, modelPath: args.modelPath });
44078
44452
  if (!generated)
44079
44453
  return;
44454
+ for (const plan of generated.plans) {
44455
+ parts.persistedViews[plan.buildSourceID] = {
44456
+ sourceName: plan.sourceName,
44457
+ viewName: plan.viewName
44458
+ };
44459
+ }
44080
44460
  const planByName = new Map(generated.plans.map((p) => [p.buildSourceName, p]));
44081
44461
  const queryByID = new Map(generated.queries.map((p) => [p.buildSourceID, p]));
44082
- const readsAGiven = "its result reads a given, so it differs per caller and a table holds one caller's result";
44083
44462
  const targets = withoutGivenReadingTargets(await generated.runtime.getBuildTargets(generated.model), (source) => {
44084
44463
  const plan = planByName.get(source.name);
44085
44464
  const query = queryByID.get(source.sourceID);
44086
44465
  if (plan) {
44087
- addAnnotationFinding(parts, persistedViewRefusalFinding({
44088
- ...plan,
44089
- reason: readsAGiven,
44090
- outcome: { refused: "reads_given" }
44091
- }, args.modelPath));
44466
+ addAnnotationFinding(parts, persistedViewRefusalFinding(persistedViewReadsGivenRefusal(plan), args.modelPath));
44092
44467
  } else if (query) {
44093
- addAnnotationFinding(parts, persistedQueryRefusalFinding({
44094
- queryName: query.queryName,
44095
- reason: readsAGiven,
44096
- refusal: "reads_given",
44097
- declaringURL: query.declaringURL,
44098
- ...query.storage !== undefined ? { storage: query.storage } : {}
44099
- }, args.modelPath));
44468
+ addAnnotationFinding(parts, persistedQueryRefusalFinding(persistedQueryReadsGivenRefusal(query), args.modelPath));
44100
44469
  }
44101
44470
  });
44102
44471
  const ctx = {
@@ -44189,7 +44558,13 @@ function inlineRunTarget(modelDef, name) {
44189
44558
  const ref = query?.type === "query" ? query.structRef : undefined;
44190
44559
  return ref && typeof ref === "object" && isSourceDef12(ref) ? ref : undefined;
44191
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
+ }
44192
44566
  async function collectModelBuildPlan(parts, args) {
44567
+ addAccessReads(parts, args.malloyModel);
44193
44568
  await collectGeneratedTables(parts, args);
44194
44569
  const plannable = await v1PlanModel(parts, args);
44195
44570
  if (!plannable)
@@ -44223,6 +44598,12 @@ async function collectGeneratedTables(parts, args) {
44223
44598
  addAnnotationFinding(parts, finding);
44224
44599
  }
44225
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
+ }
44226
44607
  }
44227
44608
  collectPersistQueryFindings(parts, {
44228
44609
  modelPath,
@@ -44299,12 +44680,9 @@ async function v1PlanModel(parts, args) {
44299
44680
  packagePath,
44300
44681
  modelPath,
44301
44682
  getRuntime,
44302
- onCompileFailed: (error) => {
44303
- logger.error("The v1 build copy of a model could not be read or did not compile; its #@ persist sources are left out of the build plan", { modelPath, error: errMessage(error) });
44304
- parts.omittedSources.push(...companionOmissions("v1_build", {
44305
- sourceIDs: declaredPersistSourceIDs(malloyModel)
44306
- }));
44307
- }
44683
+ onCompileFailed: (error) => addCompanionOutcome(parts, [], companionOmissions("v1_build", {
44684
+ sourceIDs: declaredPersistSourceIDs(malloyModel)
44685
+ }), { failure: companionFailure("v1_build", error), modelPath })
44308
44686
  });
44309
44687
  if (!companion)
44310
44688
  return;
@@ -44315,14 +44693,14 @@ async function v1PlanModel(parts, args) {
44315
44693
  }
44316
44694
  function reportPersistLineFindings(parts, targets, planned, args) {
44317
44695
  const { modelPath, packagePath, malloyModel, planModel } = args;
44318
- const parseErrors = targets.tagParseLog.filter((msg) => {
44319
- logger.warn("Persist annotation issue", {
44696
+ for (const msg of targets.tagParseLog) {
44697
+ logger.debug("Persist annotation issue", {
44320
44698
  modelPath,
44321
- message: msg.message,
44699
+ code: msg.code,
44322
44700
  severity: msg.severity
44323
44701
  });
44324
- return msg.severity === "error";
44325
- });
44702
+ }
44703
+ const parseErrors = targets.tagParseLog.filter((msg) => msg.severity === "error");
44326
44704
  const companionURL = planModel !== malloyModel ? pathToFileURL12(path17.resolve(packagePath, modelPath)).href : undefined;
44327
44705
  const authorAt = (at) => at && companionURL && at.url === companionURL ? {
44328
44706
  ...at,
@@ -44375,7 +44753,14 @@ async function planV1PersistSources(parts, planned, args) {
44375
44753
  model: declaredIn
44376
44754
  });
44377
44755
  }
44378
- } 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
+ }
44379
44764
  classificationCtx ??= {
44380
44765
  modelDef: modelDefOf(malloyModel),
44381
44766
  deps: gateDepsFor(malloyModel, modelPath)
@@ -44418,7 +44803,7 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
44418
44803
  sourceID,
44419
44804
  sourceName: source.name,
44420
44805
  reason,
44421
- error: errMessage(err)
44806
+ code: errorCodeOf(err)
44422
44807
  });
44423
44808
  omitted.push({ sourceID, reason });
44424
44809
  }
@@ -44477,7 +44862,7 @@ function refuseDatabaseTablesSharedWithARefusal(compiled, verdicts, wireSources,
44477
44862
  };
44478
44863
  }
44479
44864
  }
44480
- function projectRefusals(plan, findings) {
44865
+ function projectRefusals(plan, findings, counts = {}) {
44481
44866
  const kept = [];
44482
44867
  const refusedSources = {
44483
44868
  ...plan?.refusedSources ?? {}
@@ -44505,7 +44890,7 @@ function projectRefusals(plan, findings) {
44505
44890
  code: finding.code,
44506
44891
  ...finding.subject !== undefined ? { subject: finding.subject } : {}
44507
44892
  };
44508
- recordEligibilityRefused(key.reason);
44893
+ countRefusal(counts, key.reason);
44509
44894
  }
44510
44895
  if (!moved)
44511
44896
  return { plan, annotationFindings: kept, refusalNotices };
@@ -44532,35 +44917,107 @@ function finishBuildPlan(parts, ctx) {
44532
44917
  }));
44533
44918
  return ctx.keepIncrementalUnbuildable ? refused : refuseIncrementalUnbuildable(refused);
44534
44919
  }
44535
- 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 = {}) {
44536
44935
  const incrementalDeclarations = collectIncrementalDeclarations(compiled.tables);
44537
44936
  const verdicts = planVerdicts(compiled);
44538
44937
  for (const { counted } of verdicts.values()) {
44539
44938
  if (counted)
44540
- recordEligibilityRefused(counted);
44939
+ countRefusal(counts, counted);
44541
44940
  }
44542
44941
  const derived = compiled.builds.length === 0 && !compiled.omittedSources.length ? null : deriveBuildPlan(compiled, materializationConfig, verdicts);
44543
- const projected = projectRefusals(derived, compiled.annotationFindings.map((f) => relaxedCollision(f, getPersistCollisionEnforce())));
44942
+ const projected = projectRefusals(derived, compiled.annotationFindings.map((f) => relaxedCollision(f, getPersistCollisionEnforce())), counts);
44544
44943
  const { annotationFindings, refusalNotices } = projected;
44545
- 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);
44546
44947
  return {
44547
44948
  plan,
44548
- 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),
44549
44960
  annotationFindings,
44550
- refusalNotices,
44961
+ droppedPersistSources: compiled.droppedPersistSources,
44551
44962
  modelGateLines: compiled.modelGateLines,
44963
+ persistedViews: compiled.persistedViews ?? {},
44964
+ refusalNotices,
44965
+ refusedRollups: refusedRollupsOf(plan, compiled.tables),
44552
44966
  sourceEligibility: collectSourceEligibility(compiled, verdicts),
44553
44967
  databaseSourceEligibility: collectDatabaseSourceEligibility(compiled, verdicts),
44968
+ rollupsKeepingGates: Object.entries(compiled.tables).filter(([, table]) => table.rollup !== undefined && rollupGateEnforcedAtRead(table.rollup)).map(([sourceID]) => sourceID).sort(),
44554
44969
  incrementalDeclarations,
44555
- buildConnectionNames: [
44556
- ...new Set(compiled.builds.map((b) => b.connectionName))
44557
- ].sort(),
44558
44970
  materializePlans: materializePlansOf(compiled.tables),
44559
- rollupsKeepingGates: Object.entries(compiled.tables).filter(([, table]) => table.rollup !== undefined && rollupGateEnforcedAtRead(table.rollup)).map(([sourceID]) => sourceID).sort(),
44560
- refusedRollups: refusedRollupsOf(plan, compiled.tables),
44561
- compilerKeys: compilerKeysOf(compiled)
44971
+ asOfBuild,
44972
+ accessReads: [...compiled.accessReads ?? []],
44973
+ eligibilityRefused: { ...counts }
44562
44974
  };
44563
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
+ }
44564
45021
  function compilerKeysOf(compiled) {
44565
45022
  const keys = {};
44566
45023
  for (const [sourceID, { source, target }] of Object.entries(compiled.tables)) {
@@ -44718,7 +45175,7 @@ function collectIncrementalDeclarations(tables) {
44718
45175
  } catch (err) {
44719
45176
  logger.warn("Failed to resolve a source's incremental declaration", {
44720
45177
  sourceID,
44721
- error: errMessage(err)
45178
+ code: errorCodeOf(err)
44722
45179
  });
44723
45180
  }
44724
45181
  }
@@ -44726,6 +45183,7 @@ function collectIncrementalDeclarations(tables) {
44726
45183
  }
44727
45184
  var ORIGIN_OF_NOT_BUILT_CODE;
44728
45185
  var init_build_plan = __esm(() => {
45186
+ init_error_code();
44729
45187
  init_incremental_policy();
44730
45188
  init_load_gate_text();
44731
45189
  init_preaggregation_validation();
@@ -44753,9 +45211,9 @@ var init_build_plan = __esm(() => {
44753
45211
  init_rollup_compile();
44754
45212
  init_v1_build_companion();
44755
45213
  init_rollup_plan();
44756
- init_rollup_plan();
44757
45214
  init_config2();
44758
45215
  init_connection_type();
45216
+ init_access_closure();
44759
45217
  init_persist_dynamic_terms();
44760
45218
  init_persist_source_fields();
44761
45219
  init_quoting();
@@ -44776,7 +45234,7 @@ var init_build_plan = __esm(() => {
44776
45234
  });
44777
45235
 
44778
45236
  // src/package_load/protocol.ts
44779
- var PACKAGE_LOAD_PROTOCOL_VERSION = 5;
45237
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 7;
44780
45238
 
44781
45239
  // src/package_load/package_load_worker.ts
44782
45240
  init_malloynb();
@@ -45048,7 +45506,6 @@ class RpcWaitAccountant {
45048
45506
 
45049
45507
  // src/package_load/package_load_worker.ts
45050
45508
  init_experimental_dialects();
45051
- init_materialization_metrics();
45052
45509
  init_logger();
45053
45510
  init_process_safety();
45054
45511
 
@@ -45089,6 +45546,9 @@ class SchemaCache {
45089
45546
  this.delete(oldest);
45090
45547
  }
45091
45548
  }
45549
+ forget(key) {
45550
+ this.delete(key);
45551
+ }
45092
45552
  delete(key) {
45093
45553
  const entry = this.entries.get(key);
45094
45554
  if (!entry)
@@ -45123,6 +45583,37 @@ class SchemaCache {
45123
45583
  }
45124
45584
  }
45125
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
+
45126
45617
  // src/package_load/worker_log.ts
45127
45618
  function plainLogEntry(entry) {
45128
45619
  const info = entry;
@@ -45209,8 +45700,8 @@ function dispatchMainResponse(message) {
45209
45700
  }
45210
45701
  }
45211
45702
  var schemaCache = new SchemaCache(workerData2?.schemaCacheBytes ?? 0);
45703
+ var deferredForgets = new DeferredForgets(schemaCache);
45212
45704
  var jobContext = new AsyncLocalStorage3;
45213
- setEligibilityRefusalSink(() => jobContext.getStore()?.refusals);
45214
45705
  var writeEntry = logger.write.bind(logger);
45215
45706
  logger.write = (entry) => {
45216
45707
  const job = jobContext.getStore();
@@ -45237,11 +45728,13 @@ class ProxyConnection {
45237
45728
  digest;
45238
45729
  jobId;
45239
45730
  cacheScope;
45240
- constructor(metadata, jobId, environmentScope) {
45731
+ refresh;
45732
+ constructor(metadata, jobId, environmentScope, refresh) {
45241
45733
  this.name = metadata.name;
45242
45734
  this.dialectName = metadata.dialectName;
45243
45735
  this.digest = metadata.digest;
45244
45736
  this.jobId = jobId;
45737
+ this.refresh = refresh;
45245
45738
  this.cacheScope = [
45246
45739
  environmentScope,
45247
45740
  this.name,
@@ -45262,8 +45755,13 @@ class ProxyConnection {
45262
45755
  const errors = {};
45263
45756
  const joined = [];
45264
45757
  const missing = {};
45758
+ const refetch = {};
45265
45759
  for (const [key, tablePath] of Object.entries(tables)) {
45266
45760
  const cacheKey = this.tableCacheKey(tablePath);
45761
+ if (this.claimRefetch(cacheKey)) {
45762
+ refetch[key] = tablePath;
45763
+ continue;
45764
+ }
45267
45765
  const hit = schemaCache.get(cacheKey);
45268
45766
  const pending = hit === undefined ? schemaCache.joinInFlight(cacheKey) : undefined;
45269
45767
  if (hit) {
@@ -45274,16 +45772,14 @@ class ProxyConnection {
45274
45772
  missing[key] = tablePath;
45275
45773
  }
45276
45774
  }
45277
- if (Object.keys(missing).length > 0) {
45278
- const request = this.fetchSchemaForTablesFromMain(missing, options);
45279
- for (const [key, tablePath] of Object.entries(missing)) {
45280
- schemaCache.trackInFlight(this.tableCacheKey(tablePath), request.then((r) => ({
45281
- value: r.schemas[key],
45282
- error: r.errors[key]
45283
- })));
45284
- }
45285
- const fetched = await request;
45286
- this.cacheTableSchemas(missing, fetched.schemas);
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)) {
45287
45783
  Object.assign(schemas, fetched.schemas);
45288
45784
  Object.assign(errors, fetched.errors);
45289
45785
  }
@@ -45298,6 +45794,27 @@ class ProxyConnection {
45298
45794
  }
45299
45795
  return { schemas, errors };
45300
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
+ }
45301
45818
  cacheTableSchemas(requested, schemas) {
45302
45819
  for (const [key, schema] of Object.entries(schemas)) {
45303
45820
  const tablePath = requested[key];
@@ -45337,10 +45854,11 @@ class ProxyConnection {
45337
45854
  }
45338
45855
  return refreshed;
45339
45856
  }
45340
- const hit = schemaCache.get(cacheKey);
45857
+ const refetch = this.claimRefetch(cacheKey);
45858
+ const hit = refetch ? undefined : schemaCache.get(cacheKey);
45341
45859
  if (hit)
45342
45860
  return { structDef: hit };
45343
- const pending = schemaCache.joinInFlight(cacheKey);
45861
+ const pending = refetch ? undefined : schemaCache.joinInFlight(cacheKey);
45344
45862
  if (pending) {
45345
45863
  const answer = await pending;
45346
45864
  if (answer.value) {
@@ -45349,7 +45867,7 @@ class ProxyConnection {
45349
45867
  }
45350
45868
  return { error: answer.error ?? "No schema returned for the SQL" };
45351
45869
  }
45352
- const request = this.fetchSchemaForSQLStructFromMain(sentence, options);
45870
+ const request = this.fetchSchemaForSQLStructFromMain(sentence, refetch && this.refresh ? { ...options, refreshTimestamp: this.refresh.timestamp } : options);
45353
45871
  schemaCache.trackInFlight(cacheKey, request.then((r) => ({ value: r.structDef, error: r.error })));
45354
45872
  const result = await request;
45355
45873
  if (result.structDef !== undefined) {
@@ -45443,7 +45961,7 @@ function makeWorkerUrlReader(job) {
45443
45961
  }
45444
45962
  };
45445
45963
  }
45446
- function buildWorkerMalloyConfig(job) {
45964
+ function buildWorkerMalloyConfig(job, refresh) {
45447
45965
  const proxies = new Map;
45448
45966
  const inflight = new Map;
45449
45967
  const config = new MalloyConfig({ connections: {} }, { config: contextOverlay({ rootDirectory: job.packagePath }) });
@@ -45465,7 +45983,7 @@ function buildWorkerMalloyConfig(job) {
45465
45983
  };
45466
45984
  port.postMessage(req);
45467
45985
  });
45468
- 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);
45469
45987
  proxies.set(effectiveName, proxy);
45470
45988
  inflight.delete(effectiveName);
45471
45989
  return proxy;
@@ -45632,7 +46150,7 @@ async function compileMalloyModel(job, malloyConfig, modelPath, load, files) {
45632
46150
  const modelDef = compiled._modelDef;
45633
46151
  const { sources, queries, filterMap, givens, sourceInfos, warnings } = await extractCheckedModel(mm, compiled);
45634
46152
  const compileDurationMs = performance.now() - compileStart;
45635
- const { renderTagResults, renderTagResultsDigest, preaggregateCompanion } = await prepareForMainThread(job, malloyConfig, load, {
46153
+ const { renderTagResults, renderTagResultsDigest } = await prepareForMainThread(job, malloyConfig, load, {
45636
46154
  modelPath,
45637
46155
  materializer: mm,
45638
46156
  model: compiled,
@@ -45664,7 +46182,6 @@ async function compileMalloyModel(job, malloyConfig, modelPath, load, files) {
45664
46182
  gateWarnings: warnings.length > 0 ? warnings : undefined,
45665
46183
  renderTagResults,
45666
46184
  renderTagResultsDigest,
45667
- preaggregateCompanion,
45668
46185
  entities,
45669
46186
  governsAccess: governsAccess(modelDef)
45670
46187
  };
@@ -45741,11 +46258,12 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
45741
46258
  runtime: jobRuntime(job, malloyConfig, overlaidReader(makeWorkerUrlReader(job), overlay)),
45742
46259
  importBaseURL
45743
46260
  });
45744
- const companion = (job.withPreaggregateCompanions || wantsPlan) && !load.failed && !pastDeadline() ? null : undefined;
45745
46261
  if (wantsPlan && load.planLeftToMainThread) {
45746
46262
  wantsPlan = false;
45747
46263
  }
45748
- if (wantsPlan && companion !== undefined && !load.failed) {
46264
+ if (wantsPlan && (load.failed || pastDeadline())) {
46265
+ load.planLeftToMainThread = true;
46266
+ } else if (wantsPlan) {
45749
46267
  load.planStart ??= performance.now();
45750
46268
  try {
45751
46269
  const parts = emptyBuildPlanParts();
@@ -45767,14 +46285,8 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
45767
46285
  };
45768
46286
  }
45769
46287
  }
45770
- } else if (wantsPlan) {
45771
- load.planLeftToMainThread = true;
45772
46288
  }
45773
- return {
45774
- renderTagResults,
45775
- renderTagResultsDigest,
45776
- preaggregateCompanion: !job.withPreaggregateCompanions || companion === undefined ? undefined : {}
45777
- };
46289
+ return { renderTagResults, renderTagResultsDigest };
45778
46290
  }
45779
46291
  async function compileNotebookModel(job, malloyConfig, modelPath) {
45780
46292
  const compileStart = performance.now();
@@ -45851,7 +46363,8 @@ async function loadPackage(job) {
45851
46363
  const allFiles = await listPackageFiles(job.packagePath);
45852
46364
  const modelPaths = filterModelPaths(allFiles);
45853
46365
  const packageMetadata = await readPackageMetadata(job.packagePath, modelPaths);
45854
- const malloyConfig = buildWorkerMalloyConfig(job);
46366
+ const refresh = job.refreshTimestamp !== undefined ? { timestamp: job.refreshTimestamp, refetched: new Set } : undefined;
46367
+ const malloyConfig = buildWorkerMalloyConfig(job, refresh);
45855
46368
  const replacementMatchedExisting = job.replacement ? modelPaths.includes(job.replacement.modelPath) : undefined;
45856
46369
  if (job.replacement && !replacementMatchedExisting) {
45857
46370
  modelPaths.push(job.replacement.modelPath);
@@ -45896,6 +46409,7 @@ async function loadPackage(job) {
45896
46409
  packageMetadata,
45897
46410
  models,
45898
46411
  replacementMatchedExisting,
46412
+ ...refresh ? { refreshedSchemaKeys: [...refresh.refetched] } : {},
45899
46413
  loadDurationMs: loadEnd - loadStart,
45900
46414
  timings: {
45901
46415
  compileDurationMs: Math.max(0, compileEnd - compileRegionStart - schemaFetchDurationMs),
@@ -45913,10 +46427,8 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45913
46427
  return;
45914
46428
  }
45915
46429
  const start = performance.now();
45916
- const refusals = () => ({
45917
- ...jobContext.getStore()?.refusals ?? {}
45918
- });
45919
- const digestSkipped = [];
46430
+ const eligibilityRefused = {};
46431
+ let digestSkipped = [];
45920
46432
  try {
45921
46433
  if (load.planError)
45922
46434
  throw new Error(load.planError.message);
@@ -45929,21 +46441,16 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45929
46441
  throw new Error(`Model ${modelPath} did not compile`);
45930
46442
  mergeBuildPlanParts(parts, own);
45931
46443
  }
45932
- const connections = await resolvePackageConnections({
45933
- getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name)
45934
- }, parts.builds.map((b) => b.connectionName));
45935
- const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
45936
- const outcome = deriveBuildPlanOutcome(finishBuildPlan(parts, {
45937
- connectionDigests,
45938
- connections,
46444
+ const finished = await finishPackagePlan(parts, {
46445
+ getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name),
45939
46446
  versionScoped
45940
- }), materializationConfig);
46447
+ });
46448
+ digestSkipped = finished.digestSkipped;
45941
46449
  return {
45942
46450
  ok: true,
45943
- outcome,
46451
+ packagePlan: derivePackagePlan(finished.compiled, materializationConfig, eligibilityRefused),
45944
46452
  durationMs: performance.now() - (load.planStart ?? start),
45945
- digestSkipped,
45946
- eligibilityRefused: refusals()
46453
+ digestSkipped
45947
46454
  };
45948
46455
  } catch (error) {
45949
46456
  return {
@@ -45951,7 +46458,7 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
45951
46458
  error: errMessage(error),
45952
46459
  durationMs: performance.now() - (load.planStart ?? start),
45953
46460
  digestSkipped,
45954
- eligibilityRefused: refusals()
46461
+ eligibilityRefused
45955
46462
  };
45956
46463
  }
45957
46464
  }
@@ -45976,15 +46483,19 @@ port.on("message", (message) => {
45976
46483
  port.postMessage(errMsg);
45977
46484
  return;
45978
46485
  }
45979
- inFlightJobs.add(message.requestId);
46486
+ jobStarted(message.requestId);
45980
46487
  runJob(message);
45981
46488
  return;
45982
46489
  }
45983
46490
  if (message.type === "compile-served-copy") {
45984
- inFlightJobs.add(message.requestId);
46491
+ jobStarted(message.requestId);
45985
46492
  runServedCopyJob(message);
45986
46493
  return;
45987
46494
  }
46495
+ if (message.type === "forget-schemas") {
46496
+ deferredForgets.forget(message.keys);
46497
+ return;
46498
+ }
45988
46499
  dispatchMainResponse(message);
45989
46500
  });
45990
46501
  async function compileServedCopy(job) {
@@ -46016,8 +46527,7 @@ async function compileServedCopy(job) {
46016
46527
  async function runServedCopyJob(job) {
46017
46528
  const context = {
46018
46529
  jobId: job.requestId,
46019
- packagePath: job.packagePath,
46020
- refusals: {}
46530
+ packagePath: job.packagePath
46021
46531
  };
46022
46532
  try {
46023
46533
  port.postMessage(await jobContext.run(context, () => compileServedCopy(job)));
@@ -46031,15 +46541,13 @@ async function runServedCopyJob(job) {
46031
46541
  };
46032
46542
  port.postMessage(result);
46033
46543
  } finally {
46034
- inFlightJobs.delete(job.requestId);
46035
- maybeExit();
46544
+ jobEnded(job.requestId);
46036
46545
  }
46037
46546
  }
46038
46547
  async function runJob(job) {
46039
46548
  const context = {
46040
46549
  jobId: job.requestId,
46041
- packagePath: job.packagePath,
46042
- refusals: {}
46550
+ packagePath: job.packagePath
46043
46551
  };
46044
46552
  try {
46045
46553
  const result = await jobContext.run(context, () => loadPackage(job));
@@ -46052,10 +46560,18 @@ async function runJob(job) {
46052
46560
  };
46053
46561
  port.postMessage(errMsg);
46054
46562
  } finally {
46055
- inFlightJobs.delete(job.requestId);
46056
- maybeExit();
46563
+ jobEnded(job.requestId);
46057
46564
  }
46058
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
+ }
46059
46575
  function maybeExit() {
46060
46576
  if (shuttingDown && inFlightJobs.size === 0 && pendingRpc.size === 0) {
46061
46577
  setImmediate(() => process.exit(0));