@malloy-publisher/server 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/app/api-doc.yaml +256 -15
  2. package/dist/app/assets/{EnvironmentPage-CKUvEX7r.js → EnvironmentPage-Y9IWPC9J.js} +1 -1
  3. package/dist/app/assets/{HomePage-COpZmm3Z.js → HomePage-BOUo0MEl.js} +1 -1
  4. package/dist/app/assets/{MainPage-nIyVOgy5.js → MainPage-BkM5UDRU.js} +1 -1
  5. package/dist/app/assets/{ModelPage-BelGfTpw.js → ModelPage-PgDTkS5C.js} +2 -2
  6. package/dist/app/assets/{PackagePage-CbnVG2uD.js → PackagePage-Dn7FrQ5r.js} +1 -1
  7. package/dist/app/assets/{PackageSplatRoute-37oqxKyq.js → PackageSplatRoute-BLC29ek-.js} +2 -2
  8. package/dist/app/assets/{RenderedResult-Ct3z543g.es-QeWq894a.js → RenderedResult-vyM2wQbC.es-ha8dF24T.js} +3 -3
  9. package/dist/app/assets/{RouteError-CjmVxFgv.js → RouteError-BolMqTuz.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-BjPyhpFF.js → ThemeEditorPage-CPv1eHkI.js} +1 -1
  11. package/dist/app/assets/{ToggleButtonGroup-bM-WVZrV.js → ToggleButtonGroup-DZtImN0S.js} +1 -1
  12. package/dist/app/assets/{documentRoutes-BAPDdua3.js → documentRoutes-DI5cX3ty.js} +1 -1
  13. package/dist/app/assets/{editPageMounted-B4HEQbbz.js → editPageMounted-C--4kcld.js} +2 -2
  14. package/dist/app/assets/{index-DbRUcXfe.js → index-CbsrzNSp.js} +1 -1
  15. package/dist/app/assets/{index-C-aFb4Gn.js → index-D9wSfMZN.js} +1 -1
  16. package/dist/app/assets/{index-DUgED99B.js → index-DLToSg1f.js} +62 -62
  17. package/dist/app/assets/{index-Bx-5B05C.js → index-DyYEltlF.js} +1 -1
  18. package/dist/app/assets/{index.es-DO67FMt6.js → index.es-D8SVyfmS.js} +1 -1
  19. package/dist/app/assets/usePackageLinkNavigate-DxHGKrmZ.js +1 -0
  20. package/dist/app/assets/{usePackageRoute-Cso_p7RX.js → usePackageRoute-A_YQMrax.js} +1 -1
  21. package/dist/app/index.html +1 -1
  22. package/dist/app/mcp-app/report.js +145 -145
  23. package/dist/instrumentation.mjs +9 -1
  24. package/dist/package_load_worker.mjs +161 -13
  25. package/dist/server.mjs +1415 -228
  26. package/package.json +1 -1
  27. package/dist/app/assets/usePackageLinkNavigate-BgdbNERJ.js +0 -1
package/dist/server.mjs CHANGED
@@ -431,6 +431,14 @@ var init_admin = __esm(() => {
431
431
  notes: "Host binding for the admin API. Deliberately not moved by `PUBLISHER_HOST`: putting the main API on every interface does not expose the admin operations. Widen it only inside the network the orchestrator calls from, never behind a public ingress.",
432
432
  aliases: { env: ["PUBLISHER_ADMIN_HOST"], flags: ["--admin_host"] }
433
433
  }),
434
+ setting({
435
+ key: "admin.requestTimeoutMs",
436
+ type: integer({ min: 1 }),
437
+ default: 600000,
438
+ description: "Ms the admin API keeps a request, its headers and an idle keep-alive open.",
439
+ defaultText: "`600000` (10 min)",
440
+ notes: "How long the admin listener lets a request run before closing its connection. A table copy or a file load answers only when the table is written, so a large table needs longer than the main API's ten minutes; raise this for the caller's largest copy, and keep the caller's own timeout above it. Applies to the admin listener alone: the main API and MCP listeners keep ten minutes."
441
+ }),
434
442
  setting({
435
443
  key: "admin.catalogDatabase",
436
444
  type: string(),
@@ -14110,7 +14118,7 @@ function errorKind(error) {
14110
14118
  function errorMapping(error) {
14111
14119
  return ERROR_TABLE[errorKind(error)];
14112
14120
  }
14113
- var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, WarehouseRecomputeRefusedError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
14121
+ var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, WarehouseRecomputeRefusedError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
14114
14122
  var init_errors2 = __esm(() => {
14115
14123
  init_constants();
14116
14124
  init_logger();
@@ -14596,6 +14604,16 @@ var init_errors2 = __esm(() => {
14596
14604
  super(message);
14597
14605
  }
14598
14606
  };
14607
+ MaterializedTableDropRefusedError = class MaterializedTableDropRefusedError extends Error {
14608
+ reason;
14609
+ get kind() {
14610
+ return "materialized_table_drop_refused";
14611
+ }
14612
+ constructor(reason, message) {
14613
+ super(message);
14614
+ this.reason = reason;
14615
+ }
14616
+ };
14599
14617
  WriteConflictError = class WriteConflictError extends Error {
14600
14618
  reason;
14601
14619
  get kind() {
@@ -14755,6 +14773,7 @@ var init_errors2 = __esm(() => {
14755
14773
  off_surface: OffSurfaceError,
14756
14774
  materialization_not_found: MaterializationNotFoundError,
14757
14775
  materialization_conflict: MaterializationConflictError,
14776
+ materialized_table_drop_refused: MaterializedTableDropRefusedError,
14758
14777
  write_conflict: WriteConflictError,
14759
14778
  installed_from_location: InstalledFromLocationError,
14760
14779
  write_rolled_back: WriteRolledBackError,
@@ -15032,6 +15051,11 @@ var init_errors2 = __esm(() => {
15032
15051
  reason: "MATERIALIZATION_CONFLICT",
15033
15052
  mcp: { advice: "internal" }
15034
15053
  },
15054
+ materialized_table_drop_refused: {
15055
+ status: 409,
15056
+ reason: (error) => error.reason,
15057
+ mcp: { advice: "internal" }
15058
+ },
15035
15059
  invalid_state_transition: { status: 409, mcp: { advice: "internal" } },
15036
15060
  write_conflict: {
15037
15061
  status: 409,
@@ -15660,6 +15684,15 @@ function freshnessWindowSeconds(window2) {
15660
15684
  return;
15661
15685
  return count * WINDOW_UNITS[match[2]];
15662
15686
  }
15687
+ function durationSeconds(text) {
15688
+ const match = /^\s*(\d+)\s*([a-z]+)\s*$/.exec(text);
15689
+ if (!match || !Object.hasOwn(DURATION_UNITS, match[2]))
15690
+ return;
15691
+ const count = Number(match[1]);
15692
+ if (!Number.isSafeInteger(count) || count <= 0)
15693
+ return;
15694
+ return count * DURATION_UNITS[match[2]];
15695
+ }
15663
15696
  function declaredFreshnessFacts(declarations) {
15664
15697
  let window2;
15665
15698
  const fallbacks = new Set;
@@ -15687,7 +15720,7 @@ function declaredFreshnessFacts(declarations) {
15687
15720
  ...fallback !== undefined ? { freshnessFallback: fallback } : {}
15688
15721
  };
15689
15722
  }
15690
- var FRESHNESS_FALLBACKS, WINDOW_UNITS;
15723
+ var FRESHNESS_FALLBACKS, WINDOW_UNITS, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
15691
15724
  var init_freshness = __esm(() => {
15692
15725
  FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
15693
15726
  WINDOW_UNITS = {
@@ -15697,6 +15730,19 @@ var init_freshness = __esm(() => {
15697
15730
  d: 86400,
15698
15731
  w: 604800
15699
15732
  };
15733
+ DURATION_UNITS = {
15734
+ ...WINDOW_UNITS,
15735
+ second: 1,
15736
+ seconds: 1,
15737
+ minute: 60,
15738
+ minutes: 60,
15739
+ hour: 3600,
15740
+ hours: 3600,
15741
+ day: 86400,
15742
+ days: 86400,
15743
+ week: 604800,
15744
+ weeks: 604800
15745
+ };
15700
15746
  });
15701
15747
 
15702
15748
  // src/service/annotation_reader.ts
@@ -16034,6 +16080,7 @@ var init_annotation_reader = __esm(() => {
16034
16080
  "refresh",
16035
16081
  "watermark",
16036
16082
  "merge_key",
16083
+ "lookback",
16037
16084
  "freshness",
16038
16085
  "queryMetadata"
16039
16086
  ]);
@@ -16049,6 +16096,7 @@ var init_annotation_reader = __esm(() => {
16049
16096
  "refresh",
16050
16097
  "watermark",
16051
16098
  "merge_key",
16099
+ "lookback",
16052
16100
  "freshness",
16053
16101
  "queryMetadata",
16054
16102
  "inline"
@@ -128578,9 +128626,9 @@ var init_materialization_metrics = __esm(() => {
128578
128626
  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.");
128579
128627
  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.");
128580
128628
  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.");
128581
- 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).");
128629
+ 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}).");
128582
128630
  scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
128583
- queryRouteCounter = lazyCounter("publisher_query_route_total", "The router's decision on each leg it considered for a query, counted once " + "the query is answered. Labels: leg ('view'|'query'|'rollup'|'materialized'|'live'; " + "'query' is a persisted named query), " + "outcome ('used'|'skipped'|'fallback': a chosen leg whose run failed and " + "was answered live), reason ('NONE' when used, else the path report's " + "SkipReason; 'RUN_FAILED' with 'fallback'). A leg that does not apply to " + "the query is not counted; 'live' is counted 'used' when it answered a " + "query the router counted a leg for.");
128631
+ 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.");
128584
128632
  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.");
128585
128633
  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.");
128586
128634
  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.");
@@ -128819,6 +128867,7 @@ var init_dialect = __esm(() => {
128819
128867
  needsQualifiedTable: false,
128820
128868
  nestedColumns: false,
128821
128869
  driverKeepsBigIntegers: false,
128870
+ liveRoundsBigIntegersMeasured: false,
128822
128871
  castsToIntegerType: false,
128823
128872
  onlyBigIntegerType: undefined,
128824
128873
  foldsTableNameCase: false,
@@ -128857,7 +128906,8 @@ var init_dialect = __esm(() => {
128857
128906
  dependencyGuard: true,
128858
128907
  relationProbe: true,
128859
128908
  tableOwnership: true,
128860
- castsToIntegerType: true
128909
+ castsToIntegerType: true,
128910
+ liveRoundsBigIntegersMeasured: true
128861
128911
  }),
128862
128912
  standardsql: Object.freeze({
128863
128913
  ...NONE,
@@ -130936,7 +130986,7 @@ var init_persisted_query = __esm(() => {
130936
130986
  init_declaration();
130937
130987
  init_persist_annotation_validation();
130938
130988
  PERSIST_LINE = /^\s*#@\s*persist\b/;
130939
- INCREMENTAL_KEYS = ["watermark", "merge_key"];
130989
+ INCREMENTAL_KEYS = ["watermark", "merge_key", "lookback"];
130940
130990
  });
130941
130991
 
130942
130992
  // src/service/materialization/plan/persisted_view.ts
@@ -140083,6 +140133,62 @@ var init_composite_row_filter = __esm(() => {
140083
140133
  init_authorize_routes();
140084
140134
  });
140085
140135
 
140136
+ // src/service/materialization/domain/live_big_integers.ts
140137
+ function liveRoundsBigIntegersAsPostgres(dialect) {
140138
+ return capabilitiesOf(dialect).liveRoundsBigIntegersMeasured;
140139
+ }
140140
+ function roundedAsLive(value) {
140141
+ const exact = typeof value === "bigint" || typeof value === "string" && /^-?\d+$/.test(value);
140142
+ if (!exact)
140143
+ return value;
140144
+ const nearest = Number(value);
140145
+ if (/e/i.test(String(nearest)))
140146
+ return nearest;
140147
+ return typeof value === "bigint" ? BigInt(String(nearest)) : String(nearest);
140148
+ }
140149
+ function roundValue(value, field) {
140150
+ if (value === null || value === undefined)
140151
+ return value;
140152
+ if (field.type === "number") {
140153
+ return field.numberType === "bigint" ? roundedAsLive(value) : value;
140154
+ }
140155
+ if (field.type === "array" && Array.isArray(value)) {
140156
+ if (field.fields) {
140157
+ for (const item of value)
140158
+ roundRecord(item, field);
140159
+ } else if (field.elementTypeDef) {
140160
+ const element = field.elementTypeDef;
140161
+ return value.map((item) => roundValue(item, element));
140162
+ }
140163
+ return value;
140164
+ }
140165
+ if (field.type === "record" && field.fields && typeof value === "object") {
140166
+ roundRecord(value, field);
140167
+ }
140168
+ return value;
140169
+ }
140170
+ function holdsBigInteger(field) {
140171
+ return field.numberType === "bigint" || (field.fields ?? []).some(holdsBigInteger) || field.elementTypeDef !== undefined && holdsBigInteger(field.elementTypeDef);
140172
+ }
140173
+ function roundRecord(row, struct) {
140174
+ for (const field of struct.fields ?? []) {
140175
+ const name = field.as ?? field.name;
140176
+ if (name in row)
140177
+ row[name] = roundValue(row[name], field);
140178
+ }
140179
+ }
140180
+ function roundBigIntegersAsLive(result) {
140181
+ const { structs, result: rows } = result._queryResult;
140182
+ const struct = structs[structs.length - 1];
140183
+ if (!struct || !holdsBigInteger(struct))
140184
+ return;
140185
+ for (const row of rows)
140186
+ roundRecord(row, struct);
140187
+ }
140188
+ var init_live_big_integers = __esm(() => {
140189
+ init_dialect();
140190
+ });
140191
+
140086
140192
  // src/service/materialization/subselect.ts
140087
140193
  function fromSubselect(selectSQL, alias) {
140088
140194
  const inner = selectSQL.replace(/[\s;]+$/, "");
@@ -140360,9 +140466,13 @@ function liveKeepsBigIntegers(dialect) {
140360
140466
  return true;
140361
140467
  }
140362
140468
  }
140469
+ function storageReadsBigIntegers(dialect) {
140470
+ return liveKeepsBigIntegers(dialect) || liveRoundsBigIntegersAsPostgres(dialect);
140471
+ }
140363
140472
  function bigIntegerReads(schema, fields, options) {
140364
- if (!options.database && !liveKeepsBigIntegers(options.dialect))
140473
+ if (!options.database && !storageReadsBigIntegers(options.dialect)) {
140365
140474
  return [];
140475
+ }
140366
140476
  const byName = new Map;
140367
140477
  const declared = [];
140368
140478
  const fieldOf = (f) => f ?? {};
@@ -140411,7 +140521,7 @@ function bigIntegerReads(schema, fields, options) {
140411
140521
  return out;
140412
140522
  }
140413
140523
  function bigIntegerReadOf(field, column, options) {
140414
- if (!options.database && !liveKeepsBigIntegers(options.dialect)) {
140524
+ if (!options.database && !storageReadsBigIntegers(options.dialect)) {
140415
140525
  return;
140416
140526
  }
140417
140527
  if (!isBigIntegerField(field))
@@ -140678,6 +140788,7 @@ function canonicalStoredSchema(schema, names) {
140678
140788
  var STORED_COLUMN_TYPE_MISMATCH_CODE = "storage-column-type-mismatch", BUILD_CAST_TARGETS, CHECKED_TYPES, EXACT_INTEGER_STORAGE_TYPE = "DECIMAL(38,0)", INTEGER_TYPES, TIMESTAMPTZ_TYPES, NAIVE_TIMESTAMP_TYPES, HUGEINT_EXACT;
140679
140789
  var init_stored_column_types = __esm(() => {
140680
140790
  init_dialect();
140791
+ init_live_big_integers();
140681
140792
  init_malloy_text();
140682
140793
  init_quoting();
140683
140794
  BUILD_CAST_TARGETS = {
@@ -143743,7 +143854,8 @@ var init_build_file_generator = __esm(() => {
143743
143854
  "storage",
143744
143855
  "refresh",
143745
143856
  "watermark",
143746
- "merge_key"
143857
+ "merge_key",
143858
+ "lookback"
143747
143859
  ];
143748
143860
  });
143749
143861
 
@@ -144911,7 +145023,7 @@ var init_materialize_plan = __esm(() => {
144911
145023
  "number",
144912
145024
  "string"
144913
145025
  ]);
144914
- INCREMENTAL_KEYS2 = ["refresh", "watermark", "merge_key"];
145026
+ INCREMENTAL_KEYS2 = ["refresh", "watermark", "merge_key", "lookback"];
144915
145027
  });
144916
145028
 
144917
145029
  // src/service/materialization/plan/eligibility_collect.ts
@@ -145361,6 +145473,9 @@ function aggregateBacked(names) {
145361
145473
  return names.filter((n) => n !== undefined && n.kind === "aggregate");
145362
145474
  }
145363
145475
  function malformedMessage(where, key, problem, detail) {
145476
+ if (key === "lookback" && (problem === "array" || problem === "empty")) {
145477
+ return `${where} declares lookback=${problem === "array" ? "[…] as a tag ARRAY" : '"" (empty)'}. ` + `Write ONE quoted duration, such as lookback="2 days", or remove the ` + `key (use -lookback to strip one inherited from a parent source).`;
145478
+ }
145364
145479
  switch (problem) {
145365
145480
  case "array":
145366
145481
  return `${where} declares ${key}=[…] as a tag ARRAY. Write ONE quoted ` + `string instead: ${key}="order_date"` + (key === "merge_key" ? `, and separate a compound key with commas inside that one ` + `string — merge_key="order_id, region".` : `.`) + ` An array value is dropped from the annotation's scalar fields, so ` + `the key would otherwise read as undeclared.`;
@@ -145396,10 +145511,11 @@ function judgeSource(source) {
145396
145511
  for (const m of d.malformed) {
145397
145512
  out.push(malformedMessage(where, m.key, m.problem, m.detail));
145398
145513
  }
145399
- if (!d.incremental && (d.declaredWatermark || d.declaredMergeKey)) {
145514
+ if (!d.incremental && (d.declaredWatermark || d.declaredMergeKey || d.declaredLookback)) {
145400
145515
  const keys = [
145401
145516
  d.declaredWatermark ? "watermark=" : undefined,
145402
- d.declaredMergeKey ? "merge_key=" : undefined
145517
+ d.declaredMergeKey ? "merge_key=" : undefined,
145518
+ d.declaredLookback ? "lookback=" : undefined
145403
145519
  ].filter((k) => k !== undefined);
145404
145520
  out.push(`${where} declares ${keys.join(" and ")} but is not ${MODE}` + (d.refresh ? ` (it declares refresh=${JSON.stringify(d.refresh)})` : "") + `. These keys describe how an INCREMENTAL refresh advances the ` + `table and are ignored by a full rebuild. Either add ${MODE}, or ` + `remove the key — and if the key is inherited from a parent source, ` + `strip it with a negation (e.g. -watermark), since removing the ` + `parent's key is not an option from the child.`);
145405
145521
  }
@@ -145431,11 +145547,31 @@ function judgeSource(source) {
145431
145547
  if (d.watermarkInMergeKeys && d.watermark !== undefined) {
145432
145548
  out.push(`${where} declares merge_key= including the watermark dimension ` + `"${d.watermark.name}". Row identity must be independent of the ` + `watermark: a row restated with a LATER watermark value would not ` + `match its predecessor, so it would be inserted alongside the old ` + `row rather than replacing it — the failure merge_key= exists to ` + `prevent. List only the identity dimensions.`);
145433
145549
  }
145550
+ out.push(...lookbackRejections(d, where));
145434
145551
  if (d.calculateFields.length > 0) {
145435
145552
  unbuildable.push(`it declares ${MODE} but computes ` + `${quoteList([...new Set(d.calculateFields)])} with calculate:. A ` + `window function is not supported on an incremental source yet: a ` + `delta recomputes only rows inside its range, so a frame that reaches ` + `outside that range assigns already-materialized rows values that ` + `later data changes, below the range start where no delta ever ` + `rewrites them. Frames strictly BACKWARD along the watermark ordering ` + `are stable and will become legal; every other frame will not. Use ` + `refresh="full", or move the window computation into the query that ` + `reads this source (plain non-additive aggregates like ` + `count_distinct are fine: a delta recomputes whole output rows from ` + `full input and never merges partial aggregates)`);
145436
145553
  }
145437
145554
  return { invalid: out, unbuildable };
145438
145555
  }
145556
+ function lookbackRejections(d, where) {
145557
+ if (d.lookback === undefined)
145558
+ return [];
145559
+ const out = [];
145560
+ if (d.lookback.seconds !== undefined && d.lookback.seconds > MAX_LOOKBACK_SECONDS) {
145561
+ out.push(`${where} declares lookback=${JSON.stringify(d.lookback.text)}, ` + `longer than the most it takes, 365 days. Every refresh re-reads ` + `its whole lookback; to recompute that much history, rebuild the ` + `table (reseed) instead.`);
145562
+ }
145563
+ if (d.lookback.seconds === undefined) {
145564
+ out.push(`${where} declares lookback=${JSON.stringify(d.lookback.text)}, ` + `which is not a duration. Write a positive whole number and one ` + `unit of ${DURATION_UNIT_TEXT}, such as lookback="2 days" or ` + `lookback="36h".`);
145565
+ }
145566
+ if (!d.declaredMergeKey) {
145567
+ out.push(`${where} declares lookback= without merge_key=. lookback= re-reads ` + `rows the table already holds, below the newest stored ` + `watermark, and merge_key= is what matches each one to its stored ` + `copy instead of applying it again. Declare merge_key= with the ` + `row's identity dimensions, or remove lookback=.`);
145568
+ }
145569
+ const watermark = d.watermark;
145570
+ if (watermark !== undefined && watermark.kind !== "unresolved" && watermark.malloyType !== "date" && watermark.malloyType !== "timestamp") {
145571
+ out.push(`${where} declares lookback= with watermark="${watermark.name}", of ` + `type ${watermark.malloyType}. lookback= is a span of time, so it ` + `needs a date or timestamp watermark; a ${watermark.malloyType} ` + `watermark's delta already starts at the newest value the source ` + `held at the last refresh. Remove lookback=.`);
145572
+ }
145573
+ return out;
145574
+ }
145439
145575
  function recordedLineage(d) {
145440
145576
  const watermark = d.watermark;
145441
145577
  return [
@@ -145494,9 +145630,11 @@ function incrementalPolicyAdvisories(sources) {
145494
145630
  }
145495
145631
  return warnings;
145496
145632
  }
145497
- var MODE = `refresh="incremental"`, INCREMENTAL_NO_MERGE_KEY_CODE = "persist-incremental-no-merge-key", INCREMENTAL_SHARED_ADDRESS_CODE = "persist-incremental-shared-address";
145633
+ var MODE = `refresh="incremental"`, MAX_LOOKBACK_SECONDS, INCREMENTAL_NO_MERGE_KEY_CODE = "persist-incremental-no-merge-key", INCREMENTAL_SHARED_ADDRESS_CODE = "persist-incremental-shared-address";
145498
145634
  var init_incremental_policy = __esm(() => {
145499
145635
  init_dialect();
145636
+ init_freshness();
145637
+ MAX_LOOKBACK_SECONDS = 365 * 86400;
145500
145638
  });
145501
145639
 
145502
145640
  // src/service/materialization/plan/load_gate_text.ts
@@ -145844,34 +145982,34 @@ function relationProbeSql(segments, dialect) {
145844
145982
  switch (knownDialect) {
145845
145983
  case "duckdb": {
145846
145984
  const match = (column) => duckdbNameMatch(segments, column);
145847
- return `SELECT 'VIEW' AS kind, comment FROM duckdb_views() WHERE NOT internal AND ${match("view_name")} ` + `UNION ALL SELECT 'TABLE' AS kind, comment FROM duckdb_tables() WHERE ${match("table_name")}`;
145985
+ return `SELECT 'VIEW' AS kind, comment, database_name AS location_database, schema_name AS location_schema, view_name AS location_name ` + `FROM duckdb_views() WHERE NOT internal AND ${match("view_name")} ` + `UNION ALL SELECT 'TABLE' AS kind, comment, database_name AS location_database, schema_name AS location_schema, table_name AS location_name ` + `FROM duckdb_tables() WHERE ${match("table_name")}`;
145848
145986
  }
145849
145987
  case "postgres":
145850
- return `SELECT row_to_json(p) AS "row" FROM (` + `SELECT CASE c.relkind WHEN 'v' THEN 'VIEW' ELSE 'TABLE' END AS kind, ` + `obj_description(c.oid, 'pg_class') AS comment FROM pg_class c ` + `WHERE c.oid = to_regclass(${lit(quotedPath2(segments, knownDialect))})) AS p`;
145988
+ return `SELECT row_to_json(p) AS "row" FROM (` + `SELECT CASE c.relkind WHEN 'v' THEN 'VIEW' ELSE 'TABLE' END AS kind, ` + `obj_description(c.oid, 'pg_class') AS comment, ` + `current_database() AS location_database, n.nspname AS location_schema, c.relname AS location_name ` + `FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace ` + `WHERE c.oid = to_regclass(${lit(quotedPath2(segments, knownDialect))})) AS p`;
145851
145989
  case "standardsql": {
145852
145990
  if (segments.length < 2) {
145853
145991
  throw new RelationProbeUnsupportedError(`a BigQuery name needs a dataset-qualified name, not '${name}'`);
145854
145992
  }
145855
145993
  const schema = `${quotedPath2(segments.slice(0, -1), knownDialect)}.INFORMATION_SCHEMA`;
145856
- return `SELECT t.table_type AS kind, o.option_value AS comment ` + `FROM ${schema}.TABLES t LEFT JOIN ${schema}.TABLE_OPTIONS o ` + `ON o.table_name = t.table_name AND o.option_name = 'description' ` + `WHERE t.table_name = ${lit(name)}`;
145994
+ return `SELECT t.table_type AS kind, o.option_value AS comment, ` + `t.table_catalog AS location_database, t.table_schema AS location_schema, t.table_name AS location_name ` + `FROM ${schema}.TABLES t LEFT JOIN ${schema}.TABLE_OPTIONS o ` + `ON o.table_name = t.table_name AND o.option_name = 'description' ` + `WHERE t.table_name = ${lit(name)}`;
145857
145995
  }
145858
145996
  case "snowflake": {
145859
145997
  const from = segments.length === 3 ? `${quoteIdentifier(segments[0], dialect)}.INFORMATION_SCHEMA.TABLES` : "INFORMATION_SCHEMA.TABLES";
145860
145998
  const schema = segments.length === 1 ? "CURRENT_SCHEMA()" : lit(segments[segments.length - 2]);
145861
- return `SELECT TABLE_TYPE AS "kind", COMMENT AS "comment" FROM ${from} ` + `WHERE TABLE_SCHEMA = ${schema} AND TABLE_NAME = ${lit(name)}`;
145999
+ return `SELECT TABLE_TYPE AS "kind", COMMENT AS "comment", ` + `TABLE_CATALOG AS "location_database", TABLE_SCHEMA AS "location_schema", TABLE_NAME AS "location_name" FROM ${from} ` + `WHERE TABLE_SCHEMA = ${schema} AND TABLE_NAME = ${lit(name)}`;
145862
146000
  }
145863
146001
  case "databricks":
145864
146002
  case "trino": {
145865
146003
  const from = segments.length === 3 ? `${quoteIdentifier(segments[0], dialect)}.information_schema.tables` : "information_schema.tables";
145866
146004
  const schema = segments.length > 1 ? `lower(${lit(segments[segments.length - 2])})` : knownDialect === "databricks" ? "current_schema()" : "current_schema";
145867
146005
  if (knownDialect === "databricks") {
145868
- return `SELECT table_type AS kind, comment FROM ${from} ` + `WHERE table_schema = ${schema} AND table_name = lower(${lit(name)})`;
146006
+ return `SELECT table_type AS kind, comment, ` + `table_catalog AS location_database, table_schema AS location_schema, table_name AS location_name FROM ${from} ` + `WHERE table_schema = ${schema} AND table_name = lower(${lit(name)})`;
145869
146007
  }
145870
- return `SELECT t.table_type AS kind, c.comment AS comment FROM ${from} t ` + `LEFT JOIN system.metadata.table_comments c ON c.catalog_name = t.table_catalog ` + `AND c.schema_name = t.table_schema AND c.table_name = t.table_name ` + `WHERE t.table_schema = ${schema} AND t.table_name = lower(${lit(name)})`;
146008
+ return `SELECT t.table_type AS kind, c.comment AS comment, ` + `t.table_catalog AS location_database, t.table_schema AS location_schema, t.table_name AS location_name FROM ${from} t ` + `LEFT JOIN system.metadata.table_comments c ON c.catalog_name = t.table_catalog ` + `AND c.schema_name = t.table_schema AND c.table_name = t.table_name ` + `WHERE t.table_schema = ${schema} AND t.table_name = lower(${lit(name)})`;
145871
146009
  }
145872
146010
  case "sqlserver":
145873
146011
  assertSqlServerShape(segments);
145874
- return `SELECT CASE o.type WHEN 'V' THEN 'VIEW' ELSE 'TABLE' END AS kind, ` + `CAST(ep.value AS nvarchar(4000)) AS comment FROM sys.objects o ` + `LEFT JOIN sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id ` + `AND ep.minor_id = 0 AND ep.name = N'MS_Description' ` + `WHERE o.object_id = OBJECT_ID(${lit(quotedPath2(segments, knownDialect))})`;
146012
+ return `SELECT CASE o.type WHEN 'V' THEN 'VIEW' ELSE 'TABLE' END AS kind, ` + `CAST(ep.value AS nvarchar(4000)) AS comment, ` + `DB_NAME() AS location_database, SCHEMA_NAME(o.schema_id) AS location_schema, o.name AS location_name FROM sys.objects o ` + `LEFT JOIN sys.extended_properties ep ON ep.class = 1 AND ep.major_id = o.object_id ` + `AND ep.minor_id = 0 AND ep.name = N'MS_Description' ` + `WHERE o.object_id = OBJECT_ID(${lit(quotedPath2(segments, knownDialect))})`;
145875
146013
  case "mysql":
145876
146014
  case "presto":
145877
146015
  throw unsupportedDialect(dialect);
@@ -145992,12 +146130,12 @@ function ownedTableProbeSql(segments, dialect) {
145992
146130
  const knownDialect = registeredDialect(dialect);
145993
146131
  if (knownDialect === "mysql") {
145994
146132
  const schema = segments.length > 1 ? lit(segments[segments.length - 2]) : "DATABASE()";
145995
- return `SELECT TABLE_TYPE AS kind, TABLE_COMMENT AS comment FROM information_schema.TABLES ` + `WHERE TABLE_SCHEMA = ${schema} AND TABLE_NAME = ${lit(name)}`;
146133
+ return `SELECT TABLE_TYPE AS kind, TABLE_COMMENT AS comment, ` + `TABLE_SCHEMA AS location_schema, TABLE_NAME AS location_name FROM information_schema.TABLES ` + `WHERE TABLE_SCHEMA = ${schema} AND TABLE_NAME = ${lit(name)}`;
145996
146134
  }
145997
146135
  if (knownDialect === "presto") {
145998
146136
  const schema = segments.length > 1 ? `lower(${lit(segments[segments.length - 2])})` : "current_schema";
145999
146137
  const from = segments.length === 3 ? `${quoteTablePath(segments[0], dialect)}.information_schema.tables` : "information_schema.tables";
146000
- return `SELECT table_type AS kind, CAST(NULL AS varchar) AS comment FROM ${from} ` + `WHERE table_schema = ${schema} AND table_name = lower(${lit(name)})`;
146138
+ return `SELECT table_type AS kind, CAST(NULL AS varchar) AS comment, ` + `table_catalog AS location_database, table_schema AS location_schema, table_name AS location_name FROM ${from} ` + `WHERE table_schema = ${schema} AND table_name = lower(${lit(name)})`;
146001
146139
  }
146002
146140
  return relationProbeSql(segments, dialect);
146003
146141
  }
@@ -146043,6 +146181,47 @@ function probeSelect(dialect, innerSelect) {
146043
146181
  const knownDialect = registeredDialect(dialect);
146044
146182
  return knownDialect === "postgres" ? `SELECT row_to_json(__p) AS "row" FROM (${innerSelect}) AS __p` : innerSelect;
146045
146183
  }
146184
+ function withStatementTimeout(dialect, sql, timeoutMs) {
146185
+ const knownDialect = registeredDialect(dialect);
146186
+ const ms = Math.max(1, Math.round(timeoutMs));
146187
+ switch (knownDialect) {
146188
+ case "postgres":
146189
+ return `SELECT set_config('statement_timeout', (SELECT CASE WHEN ` + `setting::bigint > 0 AND setting::bigint < ${ms} THEN setting ` + `ELSE '${ms}' END FROM pg_settings WHERE name = ` + `'statement_timeout'), true); ${sql}`;
146190
+ case "duckdb":
146191
+ case "standardsql":
146192
+ case "snowflake":
146193
+ case "databricks":
146194
+ case "trino":
146195
+ case "presto":
146196
+ case "mysql":
146197
+ case "sqlserver":
146198
+ return sql;
146199
+ default:
146200
+ unregistered(knownDialect);
146201
+ return sql;
146202
+ }
146203
+ }
146204
+ function watermarkTextSql(dialect, malloyType, expression) {
146205
+ const knownDialect = registeredDialect(dialect);
146206
+ switch (knownDialect) {
146207
+ case "snowflake":
146208
+ return malloyType === "date" ? `TO_CHAR(${expression}, 'YYYY-MM-DD')` : `TO_CHAR(CONVERT_TIMEZONE('UTC', ${expression})::TIMESTAMP_NTZ, ` + `'YYYY-MM-DD HH24:MI:SS')`;
146209
+ case "standardsql":
146210
+ return `CAST(${expression} AS STRING)`;
146211
+ case "postgres":
146212
+ return malloyType === "date" ? `to_char(${expression}, 'YYYY-MM-DD')` : `to_char(${expression}, 'YYYY-MM-DD HH24:MI:SSOF')`;
146213
+ case "duckdb":
146214
+ case "databricks":
146215
+ case "trino":
146216
+ case "presto":
146217
+ case "mysql":
146218
+ case "sqlserver":
146219
+ return `CAST(${expression} AS VARCHAR)`;
146220
+ default:
146221
+ unregistered(knownDialect);
146222
+ return `CAST(${expression} AS VARCHAR)`;
146223
+ }
146224
+ }
146046
146225
  function targetColumnsProbeSql(dialect, segments) {
146047
146226
  const alias = quoteIdentifier("column_name", dialect);
146048
146227
  const knownDialect = registeredDialect(dialect);
@@ -146729,6 +146908,13 @@ function resolveIncrementalDeclaration(source, annotationFields) {
146729
146908
  mergeKeys.push(resolveName(name, columns, aggregates));
146730
146909
  }
146731
146910
  }
146911
+ const rawLookback = readKey(tag, "lookback");
146912
+ if (rawLookback.malformed)
146913
+ malformed.push(rawLookback.malformed);
146914
+ const lookback = rawLookback.text === undefined ? undefined : {
146915
+ text: rawLookback.text,
146916
+ ...durationSeconds(rawLookback.text) !== undefined ? { seconds: durationSeconds(rawLookback.text) } : {}
146917
+ };
146732
146918
  const watermarkInMergeKeys = watermark !== undefined && mergeKeys.some((k) => k.name === watermark.name);
146733
146919
  const strategy = incremental && watermark !== undefined && watermark.kind === "dimension" ? mergeKeys.length > 0 ? "merge" : "range_replace" : undefined;
146734
146920
  const unknownKeys = [];
@@ -146746,6 +146932,8 @@ function resolveIncrementalDeclaration(source, annotationFields) {
146746
146932
  invalidRefresh,
146747
146933
  declaredWatermark: rawWatermark.declared,
146748
146934
  declaredMergeKey: rawMergeKey.declared,
146935
+ declaredLookback: rawLookback.declared,
146936
+ ...lookback ? { lookback } : {},
146749
146937
  watermark,
146750
146938
  watermarkOrderable,
146751
146939
  mergeKeys,
@@ -146763,6 +146951,7 @@ var REFRESH_MODES, ORDERABLE_TYPES;
146763
146951
  var init_incremental_declaration = __esm(() => {
146764
146952
  init_annotation_reader();
146765
146953
  init_declaration();
146954
+ init_freshness();
146766
146955
  init_persist_source_fields();
146767
146956
  init_persist_dynamic_terms();
146768
146957
  REFRESH_MODES = ["full", "incremental"];
@@ -153869,7 +154058,28 @@ var init_bindings = __esm(() => {
153869
154058
  init_dialect();
153870
154059
  });
153871
154060
 
154061
+ // src/service/materialization/serve/gate_paths.ts
154062
+ function fieldPathsIn(e, out = [], depth = 0) {
154063
+ if (depth > 64 || e === null || typeof e !== "object")
154064
+ return out;
154065
+ if (Array.isArray(e)) {
154066
+ for (const x of e)
154067
+ fieldPathsIn(x, out, depth + 1);
154068
+ return out;
154069
+ }
154070
+ const n = e;
154071
+ if (n.node === "field" && Array.isArray(n.path) && n.path.every((p) => typeof p === "string")) {
154072
+ out.push(n.path);
154073
+ }
154074
+ for (const v of Object.values(e))
154075
+ fieldPathsIn(v, out, depth + 1);
154076
+ return out;
154077
+ }
154078
+
153872
154079
  // src/service/materialization/serve/gate_collation.ts
154080
+ import {
154081
+ EMPTY_BUILD_MANIFEST
154082
+ } from "@malloydata/malloy";
153873
154083
  function storedTypeIsString(type) {
153874
154084
  return STRING_STORED_TYPE.test(type);
153875
154085
  }
@@ -153962,15 +154172,29 @@ function stringPaths(struct, paths) {
153962
154172
  const seen = new Set;
153963
154173
  for (const path of paths) {
153964
154174
  let at = struct;
154175
+ let owner = struct;
153965
154176
  let field;
153966
154177
  for (const name of path) {
154178
+ owner = at;
153967
154179
  field = (at?.fields ?? []).find((f) => String(f.as ?? f.name) === name);
153968
154180
  if (!field)
153969
154181
  return;
153970
154182
  at = field;
153971
154183
  }
153972
- if (field?.type !== "string")
154184
+ if (field?.type !== "string") {
154185
+ if (owner?.query !== undefined) {
154186
+ return;
154187
+ }
154188
+ if (field?.e !== undefined) {
154189
+ const prefix = path.slice(0, -1);
154190
+ const listed = new Set(paths.map((p) => p.join(".")));
154191
+ const reads = fieldPathsIn(field.e);
154192
+ if (reads.length === 0 || !reads.every((p) => listed.has([...prefix, ...p].join(".")))) {
154193
+ return;
154194
+ }
154195
+ }
153973
154196
  continue;
154197
+ }
153974
154198
  const key = path.join(".");
153975
154199
  if (seen.has(key))
153976
154200
  continue;
@@ -153979,6 +154203,14 @@ function stringPaths(struct, paths) {
153979
154203
  }
153980
154204
  return out;
153981
154205
  }
154206
+ async function probeSql(args) {
154207
+ const ref = args.path.map((p) => identifier(p)).join(".");
154208
+ const { sql } = await args.runtime._loadModelFromModelDef(args.modelDef).loadQuery(`run: ${identifier(args.entryName)} extend { dimension: gate_probe_value__ is ${ref} } -> { select: probe_value is gate_probe_value__; limit: 1 }`).getPreparedResult({
154209
+ ...args.givens ? { givens: args.givens } : {},
154210
+ buildManifest: EMPTY_BUILD_MANIFEST
154211
+ });
154212
+ return sql;
154213
+ }
153982
154214
  async function probe(args) {
153983
154215
  const read = capabilitiesOf(args.dialect).stringCollation;
153984
154216
  if (read === "binary")
@@ -153988,8 +154220,7 @@ async function probe(args) {
153988
154220
  if (args.path.some((p) => malloyIdentifiers(p).length !== 1)) {
153989
154221
  return "unknown";
153990
154222
  }
153991
- const ref = args.path.map((p) => identifier(p)).join(".");
153992
- const { sql } = await args.runtime._loadModelFromModelDef(args.modelDef).loadQuery(`run: ${identifier(args.entryName)} extend { dimension: gate_probe_value__ is ${ref} } -> { select: probe_value is gate_probe_value__; limit: 1 }`).getPreparedResult(args.givens ? { givens: args.givens } : {});
154223
+ const sql = await probeSql(args);
153993
154224
  const connection = await args.runtime.connections.lookupConnection(args.connectionName);
153994
154225
  try {
153995
154226
  return read === "instance" ? await duckdbCollation(connection, sql) : await postgresCollation(connection, unfinalizedPostgresSQL(sql));
@@ -154046,7 +154277,13 @@ async function storedTableCollationRefusal(args) {
154046
154277
  if (!runtime)
154047
154278
  return "no runtime";
154048
154279
  const need = equalityOnly ? ["binary", "deterministic"] : ["binary"];
154280
+ const perColumn = capabilitiesOf(sourceDialect).stringCollation === "column";
154281
+ let sameCollationNeeded = false;
154049
154282
  for (const t of args.tables) {
154283
+ if (perColumn && t.tier === "database") {
154284
+ sameCollationNeeded = true;
154285
+ continue;
154286
+ }
154050
154287
  let collation;
154051
154288
  try {
154052
154289
  collation = await storedSide(t, args, runtime, sourceDialect);
@@ -154057,7 +154294,146 @@ async function storedTableCollationRefusal(args) {
154057
154294
  return `a stored table compares strings under a ${collation} collation`;
154058
154295
  }
154059
154296
  }
154060
- return;
154297
+ if (!sameCollationNeeded)
154298
+ return;
154299
+ let why;
154300
+ try {
154301
+ why = await databaseCollationRefusal({
154302
+ tables: args.tables.filter((t) => t.tier === "database"),
154303
+ authorRunnable: args.authorRunnable,
154304
+ storedRuntime: runtime,
154305
+ reads: args.reads,
154306
+ ...args.givens ? { givens: args.givens } : {}
154307
+ });
154308
+ } catch {
154309
+ why = "a collation that could not be read";
154310
+ }
154311
+ return why === undefined ? undefined : `a stored table does not keep its source's collation: ${why}`;
154312
+ }
154313
+ async function postgresCollationIdentity(connection, sql) {
154314
+ const [row] = await pgRows(connection, `SELECT ${PG_COLLATION_IDENTITY} AS id FROM pg_collation c, pg_database d WHERE c.oid = (pg_collation_for((SELECT q.probe_value FROM (${sql}) q LIMIT 1)))::regcollation AND d.datname = current_database()`);
154315
+ return typeof row?.id === "string" ? row.id : undefined;
154316
+ }
154317
+ async function postgresDefaultIdentity(connection) {
154318
+ const [row] = await pgRows(connection, `SELECT ${PG_COLLATION_IDENTITY} AS id FROM pg_collation c, pg_database d WHERE c.collname = 'default' AND c.collnamespace = 'pg_catalog'::regnamespace AND d.datname = current_database()`);
154319
+ return typeof row?.id === "string" ? row.id : undefined;
154320
+ }
154321
+ async function postgresColumnIdentities(connection, tablePath) {
154322
+ const path = tablePath.replace(/'/g, "''");
154323
+ const columns = await pgRows(connection, `SELECT a.attname AS col, CASE WHEN a.attcollation = 0 THEN NULL ELSE (SELECT ${PG_COLLATION_IDENTITY} FROM pg_collation c, pg_database d WHERE c.oid = a.attcollation AND d.datname = current_database()) END AS id FROM pg_attribute a WHERE a.attrelid = '${path}'::regclass AND a.attnum > 0 AND NOT a.attisdropped`);
154324
+ return new Map(columns.map((c) => [
154325
+ String(c.col),
154326
+ typeof c.id === "string" ? c.id : null
154327
+ ]));
154328
+ }
154329
+ function namedEntryOf(structRef, struct, modelDef) {
154330
+ if (typeof structRef === "string")
154331
+ return structRef;
154332
+ const s = struct;
154333
+ if (typeof s?.as !== "string")
154334
+ return;
154335
+ const base = modelDef.contents?.[s.as];
154336
+ if (base === undefined)
154337
+ return;
154338
+ if (s.extends !== undefined && s.extends !== base.sourceID)
154339
+ return;
154340
+ if (s.type !== base.type || s.name !== base.name || s.connection !== base.connection) {
154341
+ return;
154342
+ }
154343
+ const fields = new Set((s.fields ?? []).map((f) => JSON.stringify(f)));
154344
+ if (!(base.fields ?? []).every((f) => fields.has(JSON.stringify(f)))) {
154345
+ return;
154346
+ }
154347
+ const same = (a, b) => JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
154348
+ if (!same(base.filterList, s.filterList))
154349
+ return;
154350
+ try {
154351
+ const gates = (x) => {
154352
+ const entries = collectEntryPointGates(x, modelDef, new Set, true);
154353
+ if (entries.some((e) => e.struct === undefined))
154354
+ return;
154355
+ return entries.map((e) => [e.route, [...e.exprs]]);
154356
+ };
154357
+ const own = gates(struct);
154358
+ if (own === undefined || !same(gates(base), own))
154359
+ return;
154360
+ } catch {
154361
+ return;
154362
+ }
154363
+ return s.as;
154364
+ }
154365
+ async function databaseCollationRefusal(args) {
154366
+ const { reads } = args;
154367
+ if (reads === undefined || reads.unresolved)
154368
+ return "gate reads unread";
154369
+ if (!reads.entryPathsComplete)
154370
+ return "a scope from elsewhere";
154371
+ const prepared = await readPreparedQuery(args.authorRunnable);
154372
+ const modelDef = prepared.modelDef;
154373
+ if (!modelDef)
154374
+ return "no author compile";
154375
+ const struct = resolveStructRefSource(prepared.structRef, modelDef);
154376
+ const entryName = namedEntryOf(prepared.structRef, struct, modelDef);
154377
+ if (entryName === undefined)
154378
+ return "no named entry point";
154379
+ const connectionName = typeof struct?.connection === "string" ? struct.connection : undefined;
154380
+ const runtime = args.authorRunnable.runtime;
154381
+ if (!runtime)
154382
+ return "no runtime";
154383
+ const source = await runtime.connections.lookupConnection(connectionName);
154384
+ const paths = stringPaths(struct, reads.entryPaths);
154385
+ if (paths === undefined)
154386
+ return "an unreadable gate path";
154387
+ const compared = new Set;
154388
+ for (const path of paths) {
154389
+ const id = await postgresCollationIdentity(source, unfinalizedPostgresSQL(await probeSql({
154390
+ runtime,
154391
+ modelDef,
154392
+ entryName,
154393
+ path,
154394
+ ...args.givens ? { givens: args.givens } : {}
154395
+ })));
154396
+ if (id === undefined)
154397
+ return `\`${path.join(".")}\` unread`;
154398
+ compared.add(id);
154399
+ }
154400
+ const sourceDefault = await postgresDefaultIdentity(source);
154401
+ if (sourceDefault === undefined)
154402
+ return "the source's default unread";
154403
+ const held = new Map;
154404
+ for (const t of args.tables) {
154405
+ if (t.tablePath === undefined)
154406
+ return "a table with no path";
154407
+ const connection = await args.storedRuntime.connections.lookupConnection(t.destinationName ?? connectionName);
154408
+ if (await postgresDefaultIdentity(connection) !== sourceDefault) {
154409
+ return "a stored table's connection has another default collation";
154410
+ }
154411
+ for (const [col, id] of await postgresColumnIdentities(connection, t.tablePath)) {
154412
+ held.set(col, id);
154413
+ }
154414
+ }
154415
+ const ownWhere = new Set(fieldPathsIn(struct?.filterList).flat());
154416
+ const rollupRead = args.tables.some((t) => t.kind === "rollup");
154417
+ let storedStrings = 0;
154418
+ for (const names of reads.columns) {
154419
+ const found = names.filter((n) => held.has(n));
154420
+ if (found.length === 0) {
154421
+ if (rollupRead && names.some((n) => ownWhere.has(n)))
154422
+ continue;
154423
+ return "a scope column no stored table holds";
154424
+ }
154425
+ for (const n of found) {
154426
+ const id = held.get(n);
154427
+ if (id === null || id === undefined)
154428
+ continue;
154429
+ storedStrings++;
154430
+ compared.add(id);
154431
+ }
154432
+ }
154433
+ if (storedStrings > 0 && paths.length === 0) {
154434
+ return "a stored string column with no compared source path";
154435
+ }
154436
+ return compared.size <= 1 ? undefined : "a column under another collation";
154061
154437
  }
154062
154438
  function tableNameOf(path) {
154063
154439
  const parts = path.match(/"(?:[^"]|"")*"|`[^`]*`|[^.]+/g) ?? [path];
@@ -154124,33 +154500,18 @@ async function comparesNoString(args) {
154124
154500
  const { reads } = args;
154125
154501
  return reads !== undefined && !reads.unresolved && reads.comparesNoString;
154126
154502
  }
154127
- var probes, STRING_STORED_TYPE, DUCKDB_COLLATE_DEFINITIONS = "SELECT (SELECT count(*) FROM duckdb_tables() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_views() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_functions() WHERE NOT internal AND function_type IN ('macro', 'table_macro') AND (macro_definition IS NULL OR macro_definition ILIKE '%collate%')) AS n", PG_COLLATION_COLUMNS = "c.collname AS name, c.collisdeterministic AS det, c.collcollate AS cc, c.collprovider AS prov, d.datcollate AS dbc, to_jsonb(d) ->> 'datlocprovider' AS dbp";
154503
+ var probes, STRING_STORED_TYPE, DUCKDB_COLLATE_DEFINITIONS = "SELECT (SELECT count(*) FROM duckdb_tables() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_views() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_functions() WHERE NOT internal AND function_type IN ('macro', 'table_macro') AND (macro_definition IS NULL OR macro_definition ILIKE '%collate%')) AS n", PG_COLLATION_COLUMNS = "c.collname AS name, c.collisdeterministic AS det, c.collcollate AS cc, c.collprovider AS prov, d.datcollate AS dbc, to_jsonb(d) ->> 'datlocprovider' AS dbp", PG_COLLATION_IDENTITY = `CASE WHEN c.collname = 'default' AND c.collnamespace = 'pg_catalog'::regnamespace THEN concat_ws('|', 'db', coalesce(to_jsonb(d) ->> 'datlocprovider', ''), d.datcollate, d.datctype, coalesce(to_jsonb(d) ->> 'daticulocale', ''), coalesce(to_jsonb(d) ->> 'datlocale', ''), coalesce(to_jsonb(d) ->> 'daticurules', ''), coalesce(to_jsonb(d) ->> 'datcollversion', '')) ELSE concat_ws('|', 'coll', c.collprovider, c.collisdeterministic::text, coalesce(c.collcollate, ''), coalesce(c.collctype, ''), coalesce(to_jsonb(c) ->> 'colliculocale', ''), coalesce(to_jsonb(c) ->> 'colllocale', ''), coalesce(to_jsonb(c) ->> 'collicurules', ''), coalesce(to_jsonb(c) ->> 'collversion', '')) END`;
154128
154504
  var init_gate_collation = __esm(() => {
154129
154505
  init_query_text();
154130
154506
  init_prepared_query();
154131
154507
  init_malloy_text();
154508
+ init_gate_classification();
154132
154509
  init_dialect();
154133
154510
  probes = new WeakMap;
154134
154511
  STRING_STORED_TYPE = /\b(VARCHAR|TEXT|STRING|CHAR|CHARACTER)\b/i;
154135
154512
  });
154136
154513
 
154137
154514
  // src/service/materialization/serve/gate_reads.ts
154138
- function fieldPathsIn(e, out = [], depth = 0) {
154139
- if (depth > 64 || e === null || typeof e !== "object")
154140
- return out;
154141
- if (Array.isArray(e)) {
154142
- for (const x of e)
154143
- fieldPathsIn(x, out, depth + 1);
154144
- return out;
154145
- }
154146
- const n = e;
154147
- if (n.node === "field" && Array.isArray(n.path) && n.path.every((p) => typeof p === "string")) {
154148
- out.push(n.path);
154149
- }
154150
- for (const v of Object.values(e))
154151
- fieldPathsIn(v, out, depth + 1);
154152
- return out;
154153
- }
154154
154515
  function gateIdentifiers(exprs) {
154155
154516
  return [...new Set(exprs.flatMap((expr) => malloyIdentifiers(expr)))];
154156
154517
  }
@@ -154276,6 +154637,31 @@ class GateReadWalk {
154276
154637
  equalityOrNotString(e, source) {
154277
154638
  return equalityOnlyExpr(e) || this.leavesNotString(e, source);
154278
154639
  }
154640
+ isStored(source) {
154641
+ const s = source;
154642
+ if (typeof s?.sourceID === "string" && this.stored.has(s.sourceID)) {
154643
+ return true;
154644
+ }
154645
+ if (s?.query === undefined)
154646
+ return false;
154647
+ const query = JSON.stringify(s.query);
154648
+ return this.storedQueries().has(query);
154649
+ }
154650
+ storedQueriesMemo;
154651
+ storedQueries() {
154652
+ if (this.storedQueriesMemo)
154653
+ return this.storedQueriesMemo;
154654
+ const out = new Set;
154655
+ const contents = this.modelDef?.contents ?? {};
154656
+ for (const c of Object.values(contents)) {
154657
+ const d = c;
154658
+ if (typeof d?.sourceID === "string" && this.stored.has(d.sourceID) && d.query !== undefined) {
154659
+ out.add(JSON.stringify(d.query));
154660
+ }
154661
+ }
154662
+ this.storedQueriesMemo = out;
154663
+ return out;
154664
+ }
154279
154665
  tooDeep() {
154280
154666
  return ++this.steps > 4096;
154281
154667
  }
@@ -154284,7 +154670,7 @@ class GateReadWalk {
154284
154670
  const base = typeof ref === "string" ? this.modelDef?.contents?.[ref] : ref;
154285
154671
  return base === null ? undefined : base;
154286
154672
  }
154287
- resolve(source, path, chain, joins = []) {
154673
+ resolve(source, path, chain, joins = [], entry = false) {
154288
154674
  if (this.tooDeep() || path.length === 0) {
154289
154675
  this.unresolved = true;
154290
154676
  return;
@@ -154300,12 +154686,12 @@ class GateReadWalk {
154300
154686
  this.unresolved = true;
154301
154687
  return;
154302
154688
  }
154303
- this.resolve(f, path.slice(1), [...chain, path[0]], [...joins, path[0]]);
154689
+ this.resolve(f, path.slice(1), [...chain, path[0]], [...joins, path[0]], entry);
154304
154690
  return;
154305
154691
  }
154306
- this.field(source, f, chain, joins);
154692
+ this.field(source, f, chain, joins, entry);
154307
154693
  }
154308
- field(source, f, chain, joins) {
154694
+ field(source, f, chain, joins, entry) {
154309
154695
  const name = activeName3(f);
154310
154696
  const stored = typeof f.name === "string" ? f.name : name;
154311
154697
  this.names.add(name);
@@ -154314,15 +154700,25 @@ class GateReadWalk {
154314
154700
  if (f.e !== undefined) {
154315
154701
  if (!this.equalityOrNotString(f.e, source))
154316
154702
  this.equalityOnly = false;
154317
- for (const p of fieldPathsIn(f.e))
154318
- this.resolve(source, p, along, joins);
154703
+ if (!this.leavesNotString(f.e, source))
154704
+ this.comparesNoString = false;
154705
+ const reads = fieldPathsIn(f.e);
154706
+ if (reads.length === 0)
154707
+ this.entryPathsComplete = false;
154708
+ for (const p of reads) {
154709
+ if (entry)
154710
+ this.entryPaths.push([...joins, ...p]);
154711
+ else
154712
+ this.entryPathsComplete = false;
154713
+ this.resolve(source, p, along, joins, entry);
154714
+ }
154319
154715
  return;
154320
154716
  }
154321
154717
  if (f.join !== undefined) {
154322
154718
  this.unresolved = true;
154323
154719
  return;
154324
154720
  }
154325
- if (source?.query !== undefined) {
154721
+ if (source?.query !== undefined && !this.isStored(source)) {
154326
154722
  this.throughStages(source, stored, along, joins);
154327
154723
  return;
154328
154724
  }
@@ -154358,6 +154754,10 @@ class GateReadWalk {
154358
154754
  } else if (qf.e !== undefined) {
154359
154755
  if (!equalityOnlyExpr(qf.e))
154360
154756
  this.equalityOnly = false;
154757
+ if (!this.leavesNotString(qf.e, undefined)) {
154758
+ this.comparesNoString = false;
154759
+ }
154760
+ this.entryPathsComplete = false;
154361
154761
  const read = fieldPathsIn(qf.e);
154362
154762
  if (read.length === 0)
154363
154763
  this.unresolved = true;
@@ -154412,8 +154812,7 @@ class GateReadWalk {
154412
154812
  }
154413
154813
  this.scopeMembers(source, depth, at, own);
154414
154814
  this.scopeJoins(source, depth, at);
154415
- const built = typeof s.sourceID === "string" && this.stored.has(s.sourceID);
154416
- if (s.query !== undefined && !built) {
154815
+ if (s.query !== undefined && !this.isStored(source)) {
154417
154816
  this.scopeQuery(source, s.query, depth);
154418
154817
  }
154419
154818
  }
@@ -154482,9 +154881,9 @@ function gateReads(struct, exprs, modelDef, stored = new Set, rowFilterExprs = e
154482
154881
  }
154483
154882
  for (const p of read.paths) {
154484
154883
  walk.entryPaths.push(p);
154485
- walk.resolve(struct, p, []);
154884
+ walk.resolve(struct, p, [], [], true);
154486
154885
  }
154487
- walk.scope(struct, 0, (p) => walk.resolve(struct, p, []), true);
154886
+ walk.scope(struct, 0, (p) => walk.resolve(struct, p, [], [], true), true);
154488
154887
  return {
154489
154888
  names: walk.names,
154490
154889
  columns: walk.columns,
@@ -155580,6 +155979,62 @@ function keptAncestorChain(map, sourceID, url) {
155580
155979
  }
155581
155980
  return out;
155582
155981
  }
155982
+ function keptAncestorChainOrDeclared(map, sourceID, url, fileText) {
155983
+ const chain = keptAncestorChain(map, sourceID, url);
155984
+ const node = map.node(sourceID);
155985
+ if (chain.length > 0 || !node || node.base !== undefined)
155986
+ return chain;
155987
+ const base = declaredTableBase(node.def, url, map, fileText);
155988
+ if (!base)
155989
+ return chain;
155990
+ return [base, ...keptAncestorChain(map, base.sourceID, base.url)];
155991
+ }
155992
+ function declaredTableBase(def, url, map, fileText) {
155993
+ const own = def;
155994
+ if (own?.type !== "table")
155995
+ return;
155996
+ const text = fileText(url);
155997
+ const range = locatedIn(def, url);
155998
+ if (text === undefined || !range)
155999
+ return;
156000
+ const name = declaredBaseName(text, range);
156001
+ if (name === undefined)
156002
+ return;
156003
+ const parentID = [`${name}@${url}`, map.sourceIDOf(name)].find((id) => id !== undefined && map.node(id) !== undefined);
156004
+ const parent = parentID ? map.node(parentID) : undefined;
156005
+ const base = parent?.def;
156006
+ if (!parent || base?.type !== "table" || base.connection !== own.connection || base.tablePath !== own.tablePath) {
156007
+ return;
156008
+ }
156009
+ const parentURL = declaringURLOf(parent.def);
156010
+ const parentRange = parentURL ? locatedIn(parent.def, parentURL) : undefined;
156011
+ if (!parentURL || !parentRange)
156012
+ return;
156013
+ const baseNames = new Set(fieldNames(base));
156014
+ const inherited = fieldList(own).filter((f) => !declaredIn2(f, url, range));
156015
+ if (!inherited.every((f) => baseNames.has(fieldName4(f) ?? ""))) {
156016
+ return;
156017
+ }
156018
+ return { sourceID: parent.sourceID, url: parentURL, range: parentRange };
156019
+ }
156020
+ function fieldList(def) {
156021
+ return Array.isArray(def.fields) ? def.fields : [];
156022
+ }
156023
+ function fieldName4(field) {
156024
+ const f = field;
156025
+ const name = f?.as ?? f?.name;
156026
+ return typeof name === "string" ? name : undefined;
156027
+ }
156028
+ function fieldNames(def) {
156029
+ return fieldList(def).flatMap((f) => fieldName4(f) ?? []);
156030
+ }
156031
+ function declaredIn2(field, url, range) {
156032
+ const at = locatedIn(field, url);
156033
+ if (!at)
156034
+ return false;
156035
+ const before = (a, b) => a.line < b.line || a.line === b.line && a.character <= b.character;
156036
+ return before(range.start, at.start) && before(at.end, range.end);
156037
+ }
155583
156038
  function confirmedAncestors(fileText, ownURL, own, chain) {
155584
156039
  const out = [];
155585
156040
  let child = own;
@@ -156453,7 +156908,7 @@ class ServedCopyServe {
156453
156908
  if (this.inFlightLanes.get(lane) === started) {
156454
156909
  this.inFlightLanes.delete(lane);
156455
156910
  }
156456
- });
156911
+ }).catch(() => {});
156457
156912
  inFlight = started;
156458
156913
  }
156459
156914
  const awaited = await inFlight.promise;
@@ -156641,7 +157096,7 @@ class ServedCopyServe {
156641
157096
  const plan = this.materializePlans[reroot.sourceID];
156642
157097
  if (!plan)
156643
157098
  return;
156644
- const confirmed = confirmedAncestors(fileText, reroot.url, reroot.range, keptAncestorChain(map, reroot.sourceID, reroot.url));
157099
+ const confirmed = confirmedAncestors(fileText, reroot.url, reroot.range, keptAncestorChainOrDeclared(map, reroot.sourceID, reroot.url, fileText));
156645
157100
  const needed = confirmed.some((a) => this.materializePlans[a.sourceID] !== undefined) || confirmed.some((a) => declaresBlocks(map.node(a.sourceID)?.def));
156646
157101
  if (!needed)
156647
157102
  return;
@@ -157928,12 +158383,12 @@ function hasOwnNode(map, sourceID) {
157928
158383
  function modelFieldNames(map) {
157929
158384
  const names = new Set;
157930
158385
  for (const node of map.nodes()) {
157931
- for (const n of fieldNames(node.def))
158386
+ for (const n of fieldNames2(node.def))
157932
158387
  names.add(n);
157933
158388
  }
157934
158389
  return [...names];
157935
158390
  }
157936
- function fieldNames(def) {
158391
+ function fieldNames2(def) {
157937
158392
  const fields = def?.fields;
157938
158393
  return new Set((fields ?? []).map((f) => typeof f.as === "string" ? f.as : f.name).filter((n) => typeof n === "string"));
157939
158394
  }
@@ -164997,6 +165452,9 @@ var init_cron_evaluator = __esm(() => {
164997
165452
  ]);
164998
165453
  });
164999
165454
 
165455
+ // src/service/materialization/domain/incremental.ts
165456
+ var INCREMENTAL_LATE_ROWS_CODE = "persist-incremental-late-rows";
165457
+
165000
165458
  // src/service/materialization/serve/native_schema_notices.ts
165001
165459
  function nativeSchemaNotices(bindings, modelDef, materializePlans) {
165002
165460
  const map = SourceMap.of(modelDef);
@@ -165295,6 +165753,30 @@ function repeatedJoinOneKeyWarnings(plan, databaseEntries, storageBindings) {
165295
165753
  }
165296
165754
  return warnings;
165297
165755
  }
165756
+ function lateRowWarnings(plan, bound) {
165757
+ if (bound.size === 0)
165758
+ return [];
165759
+ const bySourceEntity = new Map(Object.values(plan?.sources ?? {}).flatMap((source) => source.sourceEntityId ? [[source.sourceEntityId, source]] : []));
165760
+ return [...bound].flatMap(([sourceEntityId, late]) => {
165761
+ const source = bySourceEntity.get(sourceEntityId);
165762
+ if (!source)
165763
+ return [];
165764
+ const rows = late.count === 1 ? "1 row" : `${late.count} rows`;
165765
+ const them = late.count === 1 ? "it" : "them";
165766
+ const annotation = source.origin === "materialize" ? "#(materialize)" : "#@ persist";
165767
+ const fields = source.annotationFields ?? {};
165768
+ const lookback = fields.lookback ? `widen its lookback= (now ${JSON.stringify(fields.lookback)})` : fields.merge_key ? "declare a lookback= on it" : "declare a merge_key= (the row's identity) and a lookback= on it";
165769
+ return [
165770
+ {
165771
+ ...source.modelPath ? { model: source.modelPath } : {},
165772
+ subject: source.name,
165773
+ code: INCREMENTAL_LATE_ROWS_CODE,
165774
+ severity: "warn",
165775
+ message: `its incremental refreshes found ${rows} in the source stamped ` + `just below where a delta started reading (the newest ` + `watermark its table held, less any lookback=), which the ` + `table does not hold. No delta reads below that point, so ` + `queries served from the table leave ${them} out, and this ` + `stays until the table is rebuilt. Rebuild it once (a run ` + `with reseed) to recover ${them}, and, so later deltas read ` + `such rows, ${lookback} in its ${annotation} annotation, as ` + `long as rows can arrive late. The count is a lower bound (a ` + `stretch of the source is checked once), and this warning ` + `stays until a full rebuild, even after a wider lookback= has ` + `written the rows. The run's manifest entry names the window ` + `(\`lateRows\`).`
165776
+ }
165777
+ ];
165778
+ });
165779
+ }
165298
165780
  function keptTableWarnings(plan, kept) {
165299
165781
  if (kept.length === 0)
165300
165782
  return [];
@@ -166020,6 +166502,7 @@ function buildQueryPath(input) {
166020
166502
  }
166021
166503
  if (!storageAnswered && !rollupAnswered) {
166022
166504
  let answered = false;
166505
+ let gateNamed = false;
166023
166506
  for (const t of tables) {
166024
166507
  if (t.tier !== "database" || t.kind !== "materialized" || t.unbuilt || t.binding)
166025
166508
  continue;
@@ -166028,7 +166511,10 @@ function buildQueryPath(input) {
166028
166511
  } else if (!answered && readByRun(input, t)) {
166029
166512
  markUsed(t);
166030
166513
  answered = true;
166031
- } else if (storageDecision?.code === "served_copy_column_left_out" && storageDecision.outcome !== "used" && t.tableId !== undefined && storageDecision.tableIds?.includes(t.tableId)) {
166514
+ } else if (!gateNamed && storageDecision?.reason === "row_level_gate" && storageDecision.outcome !== "used") {
166515
+ skip(t, "ROW_LEVEL_GATE");
166516
+ gateNamed = true;
166517
+ } else if ((storageDecision?.code === "served_copy_column_left_out" || storageDecision?.code === "served_copy_not_served") && storageDecision.outcome !== "used" && t.tableId !== undefined && storageDecision.tableIds?.includes(t.tableId)) {
166032
166518
  skip(t, skipReasonOf(storageDecision), storageDecision.callerDetail);
166033
166519
  }
166034
166520
  }
@@ -167134,6 +167620,7 @@ class PackageMaterialization {
167134
167620
  unreadRetry;
167135
167621
  observedOutcome = { drifted: [], unread: [] };
167136
167622
  storageBindings = [];
167623
+ storageLateRows = new Map;
167137
167624
  snapshotMemo;
167138
167625
  publishedBindings;
167139
167626
  manifestBindingStatus = "unbound";
@@ -167302,6 +167789,7 @@ class PackageMaterialization {
167302
167789
  }
167303
167790
  if (update.storage) {
167304
167791
  this.storageBindings = this.admitStorage(update.storage);
167792
+ this.storageLateRows = new Map(Object.entries(update.storage).flatMap(([id, entry]) => entry.lateRows ? [[id, entry.lateRows]] : []));
167305
167793
  }
167306
167794
  this.publish(update.models);
167307
167795
  if (update.database && update.observed) {
@@ -167644,6 +168132,17 @@ class PackageMaterialization {
167644
168132
  keptTableWarnings() {
167645
168133
  return keptTableWarnings(this.plan.buildPlan, this.keptTables);
167646
168134
  }
168135
+ boundLateRows() {
168136
+ const bound = new Map(this.storageLateRows);
168137
+ for (const [id, entry] of Object.entries(this.databaseEntries ?? {})) {
168138
+ if (entry.lateRows)
168139
+ bound.set(id, entry.lateRows);
168140
+ }
168141
+ return bound;
168142
+ }
168143
+ lateRowWarnings() {
168144
+ return lateRowWarnings(this.plan.buildPlan, this.boundLateRows());
168145
+ }
167647
168146
  repeatedJoinOneKeyWarnings() {
167648
168147
  return repeatedJoinOneKeyWarnings(this.plan.buildPlan, this.databaseEntries, this.storageBindings);
167649
168148
  }
@@ -167766,6 +168265,119 @@ var init_package_materialization = __esm(() => {
167766
168265
  init_source_map();
167767
168266
  });
167768
168267
 
168268
+ // src/service/materialization/run/manifest_loader.ts
168269
+ import { Storage } from "@google-cloud/storage";
168270
+ import * as fs12 from "fs/promises";
168271
+ import { fileURLToPath as fileURLToPath9 } from "url";
168272
+ function parseBucketUri(uri, scheme) {
168273
+ const rest = uri.slice(scheme.length);
168274
+ const slash = rest.indexOf("/");
168275
+ if (slash <= 0 || slash === rest.length - 1) {
168276
+ throw new Error(`Malformed manifest URI: ${uri}`);
168277
+ }
168278
+ return { bucket: rest.slice(0, slash), key: rest.slice(slash + 1) };
168279
+ }
168280
+ async function readManifestBytes(uri) {
168281
+ if (uri.startsWith("gs://")) {
168282
+ const { bucket, key } = parseBucketUri(uri, "gs://");
168283
+ gcsClient ??= new Storage;
168284
+ const [contents] = await gcsClient.bucket(bucket).file(key).download();
168285
+ return contents.toString("utf8");
168286
+ }
168287
+ if (uri.startsWith("s3://")) {
168288
+ const { bucket, key } = parseBucketUri(uri, "s3://");
168289
+ s3Client ??= new import_client_s32.S3({ followRegionRedirects: true });
168290
+ const res = await s3Client.send(new import_client_s32.GetObjectCommand({ Bucket: bucket, Key: key }));
168291
+ if (!res.Body) {
168292
+ throw new Error(`Empty S3 response for manifest URI: ${uri}`);
168293
+ }
168294
+ return res.Body.transformToString();
168295
+ }
168296
+ if (uri.startsWith("file://")) {
168297
+ return fs12.readFile(fileURLToPath9(uri), "utf8");
168298
+ }
168299
+ return fs12.readFile(uri, "utf8");
168300
+ }
168301
+ async function fetchManifestEntries(uri) {
168302
+ const raw = await readManifestBytes(uri);
168303
+ let parsed;
168304
+ try {
168305
+ parsed = JSON.parse(raw);
168306
+ } catch (err) {
168307
+ throw new Error(`Failed to parse build manifest at ${uri}: ${err instanceof Error ? err.message : String(err)}`);
168308
+ }
168309
+ return splitManifestEntries(parsed.entries ?? {}, uri);
168310
+ }
168311
+ function isUsableTableName2(name) {
168312
+ return isUsableTableName(name);
168313
+ }
168314
+ function splitManifestEntries(entries, source, from = "host", { quiet = false } = {}) {
168315
+ const readKeyUniqueness = from === "store";
168316
+ const tableNameManifest = {};
168317
+ const storageEntries = {};
168318
+ for (const [sourceEntityId, entry] of Object.entries(entries)) {
168319
+ if (isLegacyFailedEntry(entry)) {
168320
+ if (!quiet) {
168321
+ logger.warn("Manifest entry records a failed source; skipping", {
168322
+ source,
168323
+ sourceEntityId
168324
+ });
168325
+ }
168326
+ continue;
168327
+ }
168328
+ const physicalTableName = entry?.physicalTableName;
168329
+ if (!physicalTableName) {
168330
+ if (!quiet) {
168331
+ logger.warn("Manifest entry has no physicalTableName; skipping", {
168332
+ source,
168333
+ sourceEntityId
168334
+ });
168335
+ }
168336
+ continue;
168337
+ }
168338
+ if (!isUsableTableName2(physicalTableName)) {
168339
+ if (!quiet) {
168340
+ logger.warn("Manifest entry names a table this server cannot read safely (a backslash or control character, quotes that do not parse, or an empty part); skipping, so its source answers live", { source, sourceEntityId });
168341
+ }
168342
+ continue;
168343
+ }
168344
+ if (entry.storageDestinationName) {
168345
+ const { keyUniqueness: _unread, ...plain } = entry;
168346
+ const keyUniqueness = readKeyUniqueness ? keyUniquenessOnEntry(entry) : undefined;
168347
+ storageEntries[sourceEntityId] = keyUniqueness ? { ...plain, keyUniqueness } : plain;
168348
+ continue;
168349
+ }
168350
+ tableNameManifest[sourceEntityId] = {
168351
+ tableName: physicalTableName,
168352
+ connectionName: entry.connectionName,
168353
+ dataAsOf: entry.dataAsOf,
168354
+ freshnessWindowSeconds: entry.freshnessWindowSeconds,
168355
+ freshnessFallback: entry.freshnessFallback,
168356
+ ...boundSchemaOf(entry.schema),
168357
+ ...boundNativeSchemaOf(entry.nativeSchema),
168358
+ ...entry.lateRows ? { lateRows: entry.lateRows } : {},
168359
+ ...readKeyUniqueness && keyUniquenessOnEntry(entry) ? { keyUniqueness: keyUniquenessOnEntry(entry) } : {}
168360
+ };
168361
+ }
168362
+ return { tableNameManifest, storageEntries };
168363
+ }
168364
+ function keyUniquenessOnEntry(entry) {
168365
+ const k = entry.keyUniqueness;
168366
+ if (!k)
168367
+ return;
168368
+ const own = typeof k.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
168369
+ const parentKeys = k.parentKeys && typeof k.parentKeys === "object" ? Object.fromEntries(Object.entries(k.parentKeys).filter(([, unique]) => typeof unique === "boolean")) : {};
168370
+ const anyParent = Object.keys(parentKeys).length > 0;
168371
+ return own || anyParent ? { ...own ?? {}, ...anyParent ? { parentKeys } : {} } : undefined;
168372
+ }
168373
+ var import_client_s32, gcsClient, s3Client;
168374
+ var init_manifest_loader = __esm(() => {
168375
+ init_stored_column_types();
168376
+ init_quoting();
168377
+ init_logger();
168378
+ import_client_s32 = __toESM(require_dist_cjs75());
168379
+ });
168380
+
167769
168381
  // src/storage/duckdb/rows.ts
167770
168382
  function newId() {
167771
168383
  return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
@@ -168991,7 +169603,7 @@ function isRenderableWatermarkType(malloyType) {
168991
169603
  return RENDERABLE_TYPES.has(malloyType);
168992
169604
  }
168993
169605
  function secondsPrecision(value) {
168994
- const match = value.trim().match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})(?:\.\d+)?Z?$/);
169606
+ const match = value.trim().match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})(?:\.\d+)?(?:Z|\s?[+-]00(?::?00)?)?$/);
168995
169607
  if (!match) {
168996
169608
  throw new Error(`not a UTC ISO-8601 timestamp: ${JSON.stringify(value)} (expected YYYY-MM-DDTHH:MM:SS, with no zone offset)`);
168997
169609
  }
@@ -169051,6 +169663,34 @@ function canonicalBoundValue(malloyType, raw) {
169051
169663
  function snapshotBound(malloyType, now) {
169052
169664
  return canonicalBoundValue(malloyType, now);
169053
169665
  }
169666
+ function isTimeWatermark(malloyType) {
169667
+ return malloyType === "date" || malloyType === "timestamp";
169668
+ }
169669
+ function boundMillis(bound) {
169670
+ return bound.malloyType === "date" ? Date.parse(`${datePrecision(bound.value)}T00:00:00Z`) : Date.parse(`${secondsPrecision(bound.value).replace(" ", "T")}Z`);
169671
+ }
169672
+ function boundMinusSeconds(bound, seconds) {
169673
+ const ms = bound.malloyType === "date" ? Math.ceil(seconds / 86400) * MS_PER_DAY : seconds * 1000;
169674
+ return canonicalBoundValue(bound.malloyType, new Date(boundMillis(bound) - ms));
169675
+ }
169676
+ function deltaLowerBound(params) {
169677
+ const { recorded, stored } = params;
169678
+ const base = stored !== undefined && compareBounds(stored, recorded) < 0 ? stored : recorded;
169679
+ return params.lookbackSeconds ? boundMinusSeconds(base, params.lookbackSeconds) : base;
169680
+ }
169681
+ function lateRowsWindowStart(start, end, lookbackSeconds = 0) {
169682
+ if (start.malloyType === "number") {
169683
+ const width = Number(end.value) - Number(start.value);
169684
+ return width > 0 ? canonicalBoundValue("number", Number(start.value) - width) : undefined;
169685
+ }
169686
+ if (!isTimeWatermark(start.malloyType))
169687
+ return;
169688
+ const cap = Math.max(lookbackSeconds, LATE_ROWS_WINDOW_CAP_SECONDS) * 1000;
169689
+ const width = Math.min(boundMillis(end) - boundMillis(start), cap);
169690
+ if (!(width > 0))
169691
+ return;
169692
+ return canonicalBoundValue(start.malloyType, new Date(boundMillis(start) - width));
169693
+ }
169054
169694
  function deltaSelect(params) {
169055
169695
  const watermark = quoteIdentifier(params.watermarkName, params.dialect);
169056
169696
  return `SELECT * FROM (${params.sourceSQL}) AS __d ` + `WHERE ${watermark} >= ${renderSqlBound(params.start, params.dialect)}` + (params.end ? ` AND ${watermark} < ${renderSqlBound(params.end, params.dialect)}` : "");
@@ -169111,6 +169751,33 @@ async function probeMaxWatermark(runner, dialect, innerSelect, watermarkName, ma
169111
169751
  return { error: errMessage(err), errorCode: errorCodeOf(err) };
169112
169752
  }
169113
169753
  }
169754
+ async function probeStoredWatermark(params) {
169755
+ const { dialect, atOrBelow } = params;
169756
+ const type = atOrBelow.malloyType;
169757
+ if (type !== "date" && type !== "timestamp") {
169758
+ return { error: `a ${type} watermark has no stored boundary to read` };
169759
+ }
169760
+ const column = quoteIdentifier(params.column, dialect);
169761
+ const sql = probeSelect(dialect, `SELECT ${watermarkTextSql(dialect, type, `MAX(${column})`)} AS ` + `${probeAlias("watermark_max", dialect)} ` + `FROM ${params.quotedTablePath} ` + `WHERE ${column} <= ${renderSqlBound(atOrBelow, dialect)}`);
169762
+ let raw;
169763
+ try {
169764
+ const result = await params.runner(sql);
169765
+ raw = probeRows(result.rows)[0]?.["watermark_max"];
169766
+ } catch (err) {
169767
+ return { error: errMessage(err), errorCode: errorCodeOf(err) };
169768
+ }
169769
+ if (raw === null || raw === undefined)
169770
+ return {};
169771
+ try {
169772
+ return { bound: canonicalBoundValue(type, raw) };
169773
+ } catch (err) {
169774
+ return {
169775
+ error: errMessage(err),
169776
+ errorCode: errorCodeOf(err),
169777
+ unparseable: true
169778
+ };
169779
+ }
169780
+ }
169114
169781
  async function probePostgresVersion(runner) {
169115
169782
  try {
169116
169783
  const result = await runner(probeSelect("postgres", `SELECT current_setting('server_version_num') AS version_num`));
@@ -169127,7 +169794,9 @@ function compareBounds(a, b) {
169127
169794
  }
169128
169795
  if (a.malloyType === "number")
169129
169796
  return Number(a.value) - Number(b.value);
169130
- return a.value < b.value ? -1 : a.value > b.value ? 1 : 0;
169797
+ const text = (bound) => bound.malloyType === "timestamp" ? bound.value.replace("T", " ") : bound.value;
169798
+ const [x, y] = [text(a), text(b)];
169799
+ return x < y ? -1 : x > y ? 1 : 0;
169131
169800
  }
169132
169801
  function shapeMismatch(deltaColumns, targetColumns) {
169133
169802
  const target = new Set(targetColumns);
@@ -169287,6 +169956,34 @@ async function resolveDeltaEnd(target, lineage, now) {
169287
169956
  }
169288
169957
  return target.probeSourceFrontier();
169289
169958
  }
169959
+ async function resolveDeltaStart(target, lineage, recorded) {
169960
+ if (!isTimeWatermark(recorded.malloyType))
169961
+ return { bound: recorded };
169962
+ const stored = await probeStoredWatermark({
169963
+ runner: target.runner,
169964
+ dialect: target.dialect,
169965
+ quotedTablePath: target.quotedTablePath,
169966
+ column: target.storedColumn?.(lineage.watermarkName) ?? lineage.watermarkName,
169967
+ atOrBelow: recorded
169968
+ });
169969
+ if (stored.error !== undefined) {
169970
+ if (stored.unparseable) {
169971
+ logger.warn("The newest stored watermark is not a UTC ISO-8601 date or " + "timestamp, so this incremental source is rebuilt in full on " + "every refresh. Check that the connection's setupSQL does not " + "set a session time zone other than UTC (for a timestamp with " + "time zone), and that the stored watermark holds no " + "-infinity, which a storage= destination reads as text", {
169972
+ physicalTableName: lineage.physicalTableName,
169973
+ watermark: lineage.watermarkName,
169974
+ errorCode: stored.errorCode
169975
+ });
169976
+ }
169977
+ return { error: stored.error };
169978
+ }
169979
+ return {
169980
+ bound: deltaLowerBound({
169981
+ recorded,
169982
+ stored: stored.bound,
169983
+ lookbackSeconds: lineage.lookbackSeconds
169984
+ })
169985
+ };
169986
+ }
169290
169987
  function warehouseDeltaTarget(params) {
169291
169988
  const { dialect, runner, lineage, sourceSQL } = params;
169292
169989
  return {
@@ -169302,6 +169999,13 @@ function warehouseDeltaTarget(params) {
169302
169999
  start,
169303
170000
  end
169304
170001
  }),
170002
+ windowRows: async (start, end, columns) => `SELECT ${columns.map((c) => quoteIdentifier(c, dialect)).join(", ")} ` + `FROM (${deltaSelect({
170003
+ dialect,
170004
+ sourceSQL,
170005
+ watermarkName: lineage.watermarkName,
170006
+ start,
170007
+ end
170008
+ })}) AS __c`,
169305
170009
  probeSourceFrontier: () => probeMaxWatermark(runner, dialect, sourceSQL, lineage.watermarkName, lineage.watermarkType)
169306
170010
  };
169307
170011
  }
@@ -169349,17 +170053,26 @@ async function planIncrementalStep(inputs) {
169349
170053
  reason: `the target table is empty while a covered_through boundary of ` + `${ledgerEntry.coveredThroughValue} is recorded, so its rows were ` + `removed outside this ledger` + (rows.error ? ` (${rows.error})` : "")
169350
170054
  };
169351
170055
  }
169352
- const start = {
170056
+ const recorded = {
169353
170057
  malloyType: ledgerEntry.coveredThroughType,
169354
170058
  value: ledgerEntry.coveredThroughValue
169355
170059
  };
170060
+ const lower = await resolveDeltaStart(target, lineage, recorded);
170061
+ if (lower.error !== undefined) {
170062
+ return {
170063
+ mode: "seed",
170064
+ reasonCode: "table_unreadable",
170065
+ reason: `the newest stored watermark could not be read (${lower.error})`
170066
+ };
170067
+ }
170068
+ const start = lower.bound;
169356
170069
  const end = await resolveDeltaEnd(target, lineage, inputs.now);
169357
170070
  if (!end.bound) {
169358
170071
  return {
169359
170072
  mode: "skip",
169360
170073
  reasonCode: end.error ? "frontier_unreadable" : "not_advanced",
169361
170074
  reason: end.error ? `the watermark frontier could not be read (${end.error})` : "the source has no rows with a non-null watermark",
169362
- coveredThrough: start
170075
+ coveredThrough: recorded
169363
170076
  };
169364
170077
  }
169365
170078
  if (compareBounds(end.bound, start) <= 0) {
@@ -169367,7 +170080,7 @@ async function planIncrementalStep(inputs) {
169367
170080
  mode: "skip",
169368
170081
  reasonCode: "not_advanced",
169369
170082
  reason: `the watermark has not advanced past ${start.value} ` + `(frontier: ${end.bound.value})`,
169370
- coveredThrough: start
170083
+ coveredThrough: recorded
169371
170084
  };
169372
170085
  }
169373
170086
  const shape = shapeMismatch(inputs.columns, probe.columns);
@@ -169419,7 +170132,104 @@ async function seedCoveredThrough(runner, dialect, lineage, quotedTablePath, now
169419
170132
  const type = lineage.watermarkType;
169420
170133
  return type === "date" || type === "timestamp" ? { bound: snapshotBound(type, now) } : frontier;
169421
170134
  }
169422
- var INCREMENTAL_SOURCE_RANGE_DIALECTS, INCREMENTAL_TARGET_DML_DIALECTS, MERGE_CAPABLE_DIALECTS, RENDERABLE_TYPES, DECODED_PATH_DIALECTS, POSTGRES_MERGE_MIN_VERSION_NUM = 150000, PAIR_GUARD_MESSAGE = "pair table parent-row check: a parent does not have exactly one parent-row flag";
170135
+ function lateRowsSql(params) {
170136
+ const { dialect, quotedTablePath, windowSQL, matchColumns } = params;
170137
+ const q = (name) => quoteIdentifier(name, dialect);
170138
+ const w = q(params.watermark);
170139
+ const inWindow = `${w} >= ${renderSqlBound(params.from, dialect)} AND ` + `${w} < ${renderSqlBound(params.to, dialect)}`;
170140
+ const alias = probeAlias("late_rows", dialect);
170141
+ if (matchColumns.length === 0) {
170142
+ return probeSelect(dialect, `SELECT (SELECT COUNT(*) FROM (${windowSQL}) AS __s) - ` + `(SELECT COUNT(*) FROM ${quotedTablePath} WHERE ${inWindow}) ` + `AS ${alias}`);
170143
+ }
170144
+ const stored = [...new Set([params.watermark, ...matchColumns])].map(q).join(", ");
170145
+ const on = [
170146
+ `__t.${w} = __s.${w}`,
170147
+ ...matchColumns.filter((c) => c !== params.watermark).map((c) => `(__t.${q(c)} = __s.${q(c)} OR ` + `(__t.${q(c)} IS NULL AND __s.${q(c)} IS NULL))`)
170148
+ ].join(" AND ");
170149
+ return probeSelect(dialect, `SELECT COUNT(*) AS ${alias} FROM (${windowSQL}) AS __s ` + `LEFT JOIN (SELECT 1 AS __present, ${stored} FROM ` + `${quotedTablePath} WHERE ${inWindow}) AS __t ON ${on} ` + `WHERE __t.__present IS NULL`);
170150
+ }
170151
+ function wireBoundValue(bound) {
170152
+ return bound.malloyType === "timestamp" ? bound.value.replace(" ", "T") : bound.value;
170153
+ }
170154
+ async function countLateRows(params) {
170155
+ const { target, lineage, start, end, carried } = params;
170156
+ const kept = carried ? { lateRows: carried } : {};
170157
+ const windowRows = target.windowRows;
170158
+ if (lineage.pair || !windowRows)
170159
+ return kept;
170160
+ let from = lateRowsWindowStart(start, end, lineage.lookbackSeconds);
170161
+ if (!from)
170162
+ return kept;
170163
+ if (carried) {
170164
+ const checkedTo = { malloyType: start.malloyType, value: carried.to };
170165
+ if (compareBounds(checkedTo, from) > 0)
170166
+ from = checkedTo;
170167
+ if (compareBounds(from, start) >= 0)
170168
+ return kept;
170169
+ }
170170
+ const windowFrom = from;
170171
+ const column = (field) => target.storedColumn?.(field) ?? field;
170172
+ const watermark = column(lineage.watermarkName);
170173
+ const matchColumns = lineage.mergeKeys.length > 0 ? [
170174
+ ...new Set([...lineage.mergeKeys, ...lineage.scopeColumns ?? []].map(column))
170175
+ ] : [];
170176
+ const timeoutMs = params.timeoutMs ?? LATE_ROWS_CHECK_TIMEOUT_MS;
170177
+ const abort = new AbortController;
170178
+ const check = (async () => {
170179
+ const windowSQL = await windowRows(windowFrom, start, [
170180
+ ...new Set([watermark, ...matchColumns])
170181
+ ]);
170182
+ const result = await target.runner(withStatementTimeout(target.dialect, lateRowsSql({
170183
+ dialect: target.dialect,
170184
+ quotedTablePath: target.quotedTablePath,
170185
+ windowSQL,
170186
+ watermark,
170187
+ matchColumns,
170188
+ from: windowFrom,
170189
+ to: start
170190
+ }), timeoutMs), { abortSignal: abort.signal });
170191
+ return Number(probeRows(result.rows)[0]?.["late_rows"]);
170192
+ })();
170193
+ check.catch(() => {
170194
+ return;
170195
+ });
170196
+ let timer;
170197
+ const timedOut = new Promise((_, reject) => {
170198
+ timer = setTimeout(() => {
170199
+ abort.abort();
170200
+ reject(Object.assign(new Error(`the late-row check took longer than ${timeoutMs} ms`), { code: "late_rows_check_timeout" }));
170201
+ }, timeoutMs);
170202
+ });
170203
+ try {
170204
+ const count = await Promise.race([check, timedOut]);
170205
+ if (!Number.isFinite(count) || count <= 0)
170206
+ return kept;
170207
+ return {
170208
+ lateRows: {
170209
+ count: count + (carried?.count ?? 0),
170210
+ from: carried?.from ?? wireBoundValue(windowFrom),
170211
+ to: wireBoundValue(start)
170212
+ }
170213
+ };
170214
+ } catch (err) {
170215
+ if (abort.signal.aborted) {
170216
+ let settle;
170217
+ await Promise.race([
170218
+ check.catch(() => {
170219
+ return;
170220
+ }),
170221
+ new Promise((resolve) => {
170222
+ settle = setTimeout(resolve, LATE_ROWS_SETTLE_MS);
170223
+ })
170224
+ ]);
170225
+ clearTimeout(settle);
170226
+ }
170227
+ return { ...kept, error: errMessage(err), errorCode: errorCodeOf(err) };
170228
+ } finally {
170229
+ clearTimeout(timer);
170230
+ }
170231
+ }
170232
+ var INCREMENTAL_SOURCE_RANGE_DIALECTS, INCREMENTAL_TARGET_DML_DIALECTS, MERGE_CAPABLE_DIALECTS, RENDERABLE_TYPES, MS_PER_DAY = 86400000, LATE_ROWS_WINDOW_CAP_SECONDS, DECODED_PATH_DIALECTS, POSTGRES_MERGE_MIN_VERSION_NUM = 150000, PAIR_GUARD_MESSAGE = "pair table parent-row check: a parent does not have exactly one parent-row flag", LATE_ROWS_CHECK_TIMEOUT_MS = 60000, LATE_ROWS_SETTLE_MS = 5000;
169423
170233
  var init_incremental_apply = __esm(() => {
169424
170234
  init_build_cancelled();
169425
170235
  init_logger();
@@ -169433,6 +170243,7 @@ var init_incremental_apply = __esm(() => {
169433
170243
  INCREMENTAL_TARGET_DML_DIALECTS = dialectsWith("incrementalTargetDml");
169434
170244
  MERGE_CAPABLE_DIALECTS = dialectsWith("merge");
169435
170245
  RENDERABLE_TYPES = new Set(["date", "timestamp", "number", "string"]);
170246
+ LATE_ROWS_WINDOW_CAP_SECONDS = 7 * 86400;
169436
170247
  DECODED_PATH_DIALECTS = new Set([
169437
170248
  "postgres",
169438
170249
  "snowflake",
@@ -170860,6 +171671,45 @@ async function exactNumericColumns(session, numericRead, quotedTablePath) {
170860
171671
  });
170861
171672
  return stored.length > 0 ? { columns, stored } : undefined;
170862
171673
  }
171674
+ function sessionRunner(session) {
171675
+ return async (sql, options) => {
171676
+ const signal = options?.abortSignal;
171677
+ if (!signal)
171678
+ return session.runSQL(sql);
171679
+ const interrupt = () => {
171680
+ const connection = session.connection;
171681
+ try {
171682
+ connection?.interrupt?.();
171683
+ } catch {}
171684
+ };
171685
+ if (signal.aborted)
171686
+ throw new Error("the statement was cancelled");
171687
+ signal.addEventListener("abort", interrupt, { once: true });
171688
+ try {
171689
+ return await session.runSQL(sql);
171690
+ } finally {
171691
+ signal.removeEventListener("abort", interrupt);
171692
+ }
171693
+ };
171694
+ }
171695
+ function storageWindowRows(params) {
171696
+ if (params.sourceType === "bigquery")
171697
+ return {};
171698
+ const sourceDialect = params.persistSource.dialectName;
171699
+ return {
171700
+ windowRows: async (start, end, columns) => {
171701
+ const projected = `SELECT ${columns.map((c) => quoteIdentifier(c, sourceDialect)).join(", ")} ` + `FROM (${projectToStoredColumns(params.persistSource, deltaSelect({
171702
+ dialect: sourceDialect,
171703
+ sourceSQL: params.buildSQL,
171704
+ watermarkName: params.watermarkColumn,
171705
+ start,
171706
+ end
171707
+ }))}) AS __c`;
171708
+ const read = await issuePassthroughRead(params.session, params.sourceType, params.handle, projected, params.queryMetadata);
171709
+ return read.selectSQL;
171710
+ }
171711
+ };
171712
+ }
170863
171713
  function storageDeltaTarget(params) {
170864
171714
  const {
170865
171715
  session,
@@ -170899,7 +171749,7 @@ function storageDeltaTarget(params) {
170899
171749
  target: {
170900
171750
  dialect: STORAGE_DIALECT,
170901
171751
  storedColumn,
170902
- runner: (sql) => session.runSQL(sql),
171752
+ runner: sessionRunner(session),
170903
171753
  quotedTablePath,
170904
171754
  logicalTablePath,
170905
171755
  deltaRows: async (start, end) => {
@@ -170915,6 +171765,15 @@ function storageDeltaTarget(params) {
170915
171765
  readCost = read.cost;
170916
171766
  return exact ? guardDeltaDecimals(read.selectSQL, exact.stored) : read.selectSQL;
170917
171767
  },
171768
+ ...storageWindowRows({
171769
+ session,
171770
+ sourceType,
171771
+ handle,
171772
+ persistSource,
171773
+ buildSQL,
171774
+ watermarkColumn,
171775
+ queryMetadata
171776
+ }),
170918
171777
  probeSourceFrontier: async () => {
170919
171778
  const column = quoteIdentifier(watermarkColumn, sourceDialect);
170920
171779
  const alias = quoteIdentifier("watermark_max", sourceDialect);
@@ -171022,7 +171881,8 @@ function incrementalLineage(params) {
171022
171881
  scopeColumns: d.scopeColumns,
171023
171882
  strategy: d.strategy,
171024
171883
  ...d.rollingWindow?.length ? { rollingWindow: d.rollingWindow } : {},
171025
- ...d.pair ? { pair: d.pair } : {}
171884
+ ...d.pair ? { pair: d.pair } : {},
171885
+ ...d.lookback?.seconds ? { lookbackSeconds: d.lookback.seconds } : {}
171026
171886
  };
171027
171887
  }
171028
171888
  async function planSourceRefresh(params) {
@@ -171128,6 +171988,7 @@ async function advanceLedgerAfterSeed(params) {
171128
171988
  }
171129
171989
  async function applyIncrementalStep(params) {
171130
171990
  const { context, lineage, step, target } = params;
171991
+ const carried = context.priorLateRows?.get(lineage.sourceEntityId);
171131
171992
  if (step.mode !== "delta") {
171132
171993
  reportIncrementalStep({
171133
171994
  step,
@@ -171142,7 +172003,8 @@ async function applyIncrementalStep(params) {
171142
172003
  return {
171143
172004
  applied: true,
171144
172005
  coveredThrough: step.coveredThrough,
171145
- refresh: "none"
172006
+ refresh: "none",
172007
+ ...carried ? { lateRows: carried } : {}
171146
172008
  };
171147
172009
  }
171148
172010
  const startTime = performance.now();
@@ -171180,12 +172042,54 @@ async function applyIncrementalStep(params) {
171180
172042
  physicalTableName: lineage.physicalTableName,
171181
172043
  durationMs
171182
172044
  });
172045
+ const lateRows = target.abortSignal?.aborted ? carried : await reportLateRows({
172046
+ target,
172047
+ lineage,
172048
+ step,
172049
+ carried,
172050
+ sourceName: params.sourceName,
172051
+ packageName: context.packageName
172052
+ });
171183
172053
  return {
171184
172054
  applied: true,
171185
172055
  durationMs,
171186
172056
  coveredThrough: step.coveredThrough,
171187
- refresh: "delta"
172057
+ refresh: "delta",
172058
+ ...lateRows ? { lateRows } : {}
172059
+ };
172060
+ }
172061
+ async function reportLateRows(params) {
172062
+ const { lineage, step } = params;
172063
+ const found = await countLateRows({
172064
+ target: params.target,
172065
+ lineage,
172066
+ start: step.start,
172067
+ end: step.end,
172068
+ carried: params.carried
172069
+ });
172070
+ const at = {
172071
+ packageName: params.packageName,
172072
+ sourceName: params.sourceName,
172073
+ physicalTableName: lineage.physicalTableName
171188
172074
  };
172075
+ if (found.error !== undefined) {
172076
+ logger.warn("Could not check an incremental delta for late rows", {
172077
+ ...at,
172078
+ errorCode: found.errorCode
172079
+ });
172080
+ return found.lateRows;
172081
+ }
172082
+ if (found.lateRows && found.lateRows !== params.carried) {
172083
+ logger.warn("An incremental source's table is missing rows stamped below its " + "delta's lower bound", {
172084
+ ...at,
172085
+ code: INCREMENTAL_LATE_ROWS_CODE,
172086
+ count: found.lateRows.count
172087
+ });
172088
+ }
172089
+ return found.lateRows;
172090
+ }
172091
+ function lateRowsFields(lateRows) {
172092
+ return lateRows ? { lateRows } : {};
171189
172093
  }
171190
172094
  function reportIncrementalStep(params) {
171191
172095
  const { step, sourceName, packageName, physicalTableName } = params;
@@ -171278,6 +172182,7 @@ async function refreshOneSourceIncrementally(params) {
171278
172182
  queryCostBytes: null,
171279
172183
  ...ledgerFields(lineage, outcome.coveredThrough),
171280
172184
  ...refreshFields(outcome.refresh),
172185
+ ...lateRowsFields(outcome.lateRows),
171281
172186
  ...nativeSchema?.length ? { nativeSchema } : {}
171282
172187
  };
171283
172188
  }
@@ -171348,7 +172253,8 @@ function storageRefreshFor(params) {
171348
172253
  durationMs: outcome.durationMs,
171349
172254
  coveredThrough: outcome.coveredThrough,
171350
172255
  refresh: outcome.refresh ?? "none",
171351
- readCost: readCost()
172256
+ readCost: readCost(),
172257
+ ...outcome.lateRows ? { lateRows: outcome.lateRows } : {}
171352
172258
  };
171353
172259
  },
171354
172260
  afterSeed: ({ session, quotedTablePath }) => advanceLedgerAfterSeed({
@@ -172045,6 +172951,7 @@ class StorageBuildStrategy {
172045
172951
  buildDurationMs: result.refresh ? result.refresh.durationMs ?? null : durationMs,
172046
172952
  ...ledgerFields(incrementalRefresh?.lineage, result.refresh?.coveredThrough ?? result.seededThrough),
172047
172953
  ...refreshFields(result.refresh?.refresh ?? (incrementalRefresh ? "full" : undefined)),
172954
+ ...lateRowsFields(result.refresh?.lateRows),
172048
172955
  ...dependsOnStorageUpstream ? {
172049
172956
  upstreamReuse: result.upstreamReuse ?? "recomputed",
172050
172957
  ...upstreamRecomputeReason ? { upstreamRecomputeReason } : {}
@@ -172778,7 +173685,7 @@ function parseNameViewComment(comment) {
172778
173685
  const owner = values.get("owner");
172779
173686
  return target !== undefined && owner !== undefined ? { target, owner } : undefined;
172780
173687
  }
172781
- function parseOwnedTableComment(comment) {
173688
+ function parseOwnedTableMark(comment) {
172782
173689
  if (typeof comment !== "string")
172783
173690
  return;
172784
173691
  let text = comment.trim();
@@ -172786,18 +173693,32 @@ function parseOwnedTableComment(comment) {
172786
173693
  text = text.slice(1, -1);
172787
173694
  }
172788
173695
  const fields = text.split(" ");
172789
- if (fields.length !== 2 || fields[0] !== OWNED_TABLE_MARK)
173696
+ if (fields.length < 2 || fields.length > 3)
172790
173697
  return;
172791
- if (!fields[1].startsWith("owner="))
173698
+ if (fields[0] !== OWNED_TABLE_MARK)
172792
173699
  return;
172793
- const encoded = fields[1].slice("owner=".length);
172794
- if (encoded === "")
172795
- return;
172796
- try {
172797
- return decodeURIComponent(encoded);
172798
- } catch {
173700
+ const decode = (field, key) => {
173701
+ if (!field.startsWith(`${key}=`))
173702
+ return;
173703
+ const encoded = field.slice(key.length + 1);
173704
+ if (encoded === "")
173705
+ return;
173706
+ try {
173707
+ return decodeURIComponent(encoded);
173708
+ } catch {
173709
+ return;
173710
+ }
173711
+ };
173712
+ const owner = decode(fields[1], "owner");
173713
+ if (owner === undefined)
172799
173714
  return;
172800
- }
173715
+ if (fields.length === 2)
173716
+ return { owner };
173717
+ const table = decode(fields[2], "table");
173718
+ return table === undefined ? undefined : { owner, table };
173719
+ }
173720
+ function parseOwnedTableComment(comment) {
173721
+ return parseOwnedTableMark(comment)?.owner;
172801
173722
  }
172802
173723
  function pathSegments(path) {
172803
173724
  return path.split(".");
@@ -173045,14 +173966,33 @@ function hasAuthorTableName(compiled, persistSource) {
173045
173966
  function encodeMarkValue(value) {
173046
173967
  return encodeURIComponent(value).replace(/'/g, "%27");
173047
173968
  }
173048
- function ownedTableComment(owner) {
173049
- return `${OWNED_TABLE_MARK} owner=${encodeMarkValue(owner)}`;
173969
+ function ownedTableComment(owner, table) {
173970
+ const mark = `${OWNED_TABLE_MARK} owner=${encodeMarkValue(owner)}`;
173971
+ return table === undefined ? mark : `${mark} table=${encodeMarkValue(table)}`;
173972
+ }
173973
+ function tableLocationOf(rows) {
173974
+ const tables = rows.filter((row) => String(field3(row, "kind") ?? "").toUpperCase() !== "VIEW");
173975
+ if (tables.length !== 1)
173976
+ return;
173977
+ return relationLocationOf(tables[0]);
173978
+ }
173979
+ function relationLocationOf(row) {
173980
+ const part = (key) => {
173981
+ const value = field3(row, key);
173982
+ return typeof value === "string" && value !== "" ? value : undefined;
173983
+ };
173984
+ const schema = part("location_schema");
173985
+ const name = part("location_name");
173986
+ if (schema === undefined || name === undefined)
173987
+ return;
173988
+ const database = part("location_database");
173989
+ return [...database === undefined ? [] : [database], schema, name].map((p) => encodeURIComponent(p).replace(/\./g, "%2E")).join(".");
173050
173990
  }
173051
173991
  function tableOwnershipDialectSupported(dialect) {
173052
173992
  return capabilitiesOf(dialect).tableOwnership;
173053
173993
  }
173054
- function ownedTableMarkSql(segments, owner, dialect) {
173055
- return tableCommentSql(segments, ownedTableComment(owner), dialect);
173994
+ function ownedTableMarkSql(segments, owner, dialect, location) {
173995
+ return tableCommentSql(segments, ownedTableComment(owner, location), dialect);
173056
173996
  }
173057
173997
  function tableHolderOf(rows, owner) {
173058
173998
  if (rows.length === 0)
@@ -173093,6 +174033,21 @@ function tableHolderOf(rows, owner) {
173093
174033
  return { state: "unmarked" };
173094
174034
  return table ? { state: "ours" } : { state: "ours", view: true };
173095
174035
  }
174036
+ function markedFor(rows, owner) {
174037
+ const holder = tableHolderOf(rows, owner);
174038
+ if (holder.state !== "ours" || holder.view)
174039
+ return holder;
174040
+ for (const row of rows) {
174041
+ if (String(field3(row, "kind") ?? "").toUpperCase() === "VIEW")
174042
+ continue;
174043
+ const location = relationLocationOf(row);
174044
+ const marked = parseOwnedTableMark(field3(row, "comment"))?.table;
174045
+ if (location === undefined || marked !== location) {
174046
+ return { state: "unmarked" };
174047
+ }
174048
+ }
174049
+ return holder;
174050
+ }
173096
174051
  function field3(row, name) {
173097
174052
  if (name in row)
173098
174053
  return row[name];
@@ -173137,7 +174092,14 @@ async function assertTableOwnable(site, target, owner, sourceName, ownRecords) {
173137
174092
  }
173138
174093
  async function markOwnedTable(site, physicalTableName, owner) {
173139
174094
  try {
173140
- await site.run(ownedTableMarkSql(site.segments(physicalTableName), owner, site.dialect));
174095
+ const segments = site.segments(physicalTableName);
174096
+ let location;
174097
+ if (tableOwnershipDialectSupported(site.dialect)) {
174098
+ location = await site.run(ownedTableProbeSql(segments, site.dialect)).then(tableLocationOf, () => {
174099
+ return;
174100
+ });
174101
+ }
174102
+ await site.run(ownedTableMarkSql(segments, owner, site.dialect, location));
173141
174103
  } catch (err) {
173142
174104
  logger.warn("Could not mark a built table as this package's; its run's records say so instead", { physicalTableName, owner, error: errMessage(err) });
173143
174105
  }
@@ -173253,6 +174215,16 @@ function upstreamsBySourceID(builds) {
173253
174215
  }
173254
174216
  return out;
173255
174217
  }
174218
+ function builtDatabaseTarget(run, built) {
174219
+ if (built.storageDestinationName || !built.connectionName)
174220
+ return;
174221
+ if (!runPackageOf(run))
174222
+ return;
174223
+ return {
174224
+ physicalTableName: built.physicalTableName,
174225
+ connectionName: built.connectionName
174226
+ };
174227
+ }
173256
174228
  async function markBuiltOwnedTable(run, persistSource, ownedTarget, connection) {
173257
174229
  await atTableSite(ownedTarget, tableSiteContext(run, connection), (site) => markOwnedTable(site, ownedTarget.physicalTableName, packageOwnerOf(run))).catch((err) => logger.warn("Could not reach a built table to mark it", {
173258
174230
  sourceName: persistSource.name,
@@ -173613,8 +174585,9 @@ class InstructedBuild {
173613
174585
  if (compiled.tables[persistSource.sourceID]?.rollup) {
173614
174586
  built = { ...built, origin: "rollup" };
173615
174587
  }
173616
- if (ownedTarget) {
173617
- await markBuiltOwnedTable(run, persistSource, ownedTarget, connection);
174588
+ const markTarget = ownedTarget ?? builtDatabaseTarget(run, built);
174589
+ if (markTarget) {
174590
+ await markBuiltOwnedTable(run, persistSource, markTarget, connection);
173618
174591
  }
173619
174592
  return built;
173620
174593
  };
@@ -174203,118 +175176,6 @@ var init_instructed_build = __esm(() => {
174203
175176
  authorNamedByRun = new WeakMap;
174204
175177
  });
174205
175178
 
174206
- // src/service/materialization/run/manifest_loader.ts
174207
- import { Storage } from "@google-cloud/storage";
174208
- import * as fs12 from "fs/promises";
174209
- import { fileURLToPath as fileURLToPath9 } from "url";
174210
- function parseBucketUri(uri, scheme) {
174211
- const rest = uri.slice(scheme.length);
174212
- const slash = rest.indexOf("/");
174213
- if (slash <= 0 || slash === rest.length - 1) {
174214
- throw new Error(`Malformed manifest URI: ${uri}`);
174215
- }
174216
- return { bucket: rest.slice(0, slash), key: rest.slice(slash + 1) };
174217
- }
174218
- async function readManifestBytes(uri) {
174219
- if (uri.startsWith("gs://")) {
174220
- const { bucket, key } = parseBucketUri(uri, "gs://");
174221
- gcsClient ??= new Storage;
174222
- const [contents] = await gcsClient.bucket(bucket).file(key).download();
174223
- return contents.toString("utf8");
174224
- }
174225
- if (uri.startsWith("s3://")) {
174226
- const { bucket, key } = parseBucketUri(uri, "s3://");
174227
- s3Client ??= new import_client_s32.S3({ followRegionRedirects: true });
174228
- const res = await s3Client.send(new import_client_s32.GetObjectCommand({ Bucket: bucket, Key: key }));
174229
- if (!res.Body) {
174230
- throw new Error(`Empty S3 response for manifest URI: ${uri}`);
174231
- }
174232
- return res.Body.transformToString();
174233
- }
174234
- if (uri.startsWith("file://")) {
174235
- return fs12.readFile(fileURLToPath9(uri), "utf8");
174236
- }
174237
- return fs12.readFile(uri, "utf8");
174238
- }
174239
- async function fetchManifestEntries(uri) {
174240
- const raw = await readManifestBytes(uri);
174241
- let parsed;
174242
- try {
174243
- parsed = JSON.parse(raw);
174244
- } catch (err) {
174245
- throw new Error(`Failed to parse build manifest at ${uri}: ${err instanceof Error ? err.message : String(err)}`);
174246
- }
174247
- return splitManifestEntries(parsed.entries ?? {}, uri);
174248
- }
174249
- function isUsableTableName2(name) {
174250
- return isUsableTableName(name);
174251
- }
174252
- function splitManifestEntries(entries, source, from = "host", { quiet = false } = {}) {
174253
- const readKeyUniqueness = from === "store";
174254
- const tableNameManifest = {};
174255
- const storageEntries = {};
174256
- for (const [sourceEntityId, entry] of Object.entries(entries)) {
174257
- if (isLegacyFailedEntry(entry)) {
174258
- if (!quiet) {
174259
- logger.warn("Manifest entry records a failed source; skipping", {
174260
- source,
174261
- sourceEntityId
174262
- });
174263
- }
174264
- continue;
174265
- }
174266
- const physicalTableName = entry?.physicalTableName;
174267
- if (!physicalTableName) {
174268
- if (!quiet) {
174269
- logger.warn("Manifest entry has no physicalTableName; skipping", {
174270
- source,
174271
- sourceEntityId
174272
- });
174273
- }
174274
- continue;
174275
- }
174276
- if (!isUsableTableName2(physicalTableName)) {
174277
- if (!quiet) {
174278
- logger.warn("Manifest entry names a table this server cannot read safely (a backslash or control character, quotes that do not parse, or an empty part); skipping, so its source answers live", { source, sourceEntityId });
174279
- }
174280
- continue;
174281
- }
174282
- if (entry.storageDestinationName) {
174283
- const { keyUniqueness: _unread, ...plain } = entry;
174284
- const keyUniqueness = readKeyUniqueness ? keyUniquenessOnEntry(entry) : undefined;
174285
- storageEntries[sourceEntityId] = keyUniqueness ? { ...plain, keyUniqueness } : plain;
174286
- continue;
174287
- }
174288
- tableNameManifest[sourceEntityId] = {
174289
- tableName: physicalTableName,
174290
- connectionName: entry.connectionName,
174291
- dataAsOf: entry.dataAsOf,
174292
- freshnessWindowSeconds: entry.freshnessWindowSeconds,
174293
- freshnessFallback: entry.freshnessFallback,
174294
- ...boundSchemaOf(entry.schema),
174295
- ...boundNativeSchemaOf(entry.nativeSchema),
174296
- ...readKeyUniqueness && keyUniquenessOnEntry(entry) ? { keyUniqueness: keyUniquenessOnEntry(entry) } : {}
174297
- };
174298
- }
174299
- return { tableNameManifest, storageEntries };
174300
- }
174301
- function keyUniquenessOnEntry(entry) {
174302
- const k = entry.keyUniqueness;
174303
- if (!k)
174304
- return;
174305
- const own = typeof k.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
174306
- const parentKeys = k.parentKeys && typeof k.parentKeys === "object" ? Object.fromEntries(Object.entries(k.parentKeys).filter(([, unique]) => typeof unique === "boolean")) : {};
174307
- const anyParent = Object.keys(parentKeys).length > 0;
174308
- return own || anyParent ? { ...own ?? {}, ...anyParent ? { parentKeys } : {} } : undefined;
174309
- }
174310
- var import_client_s32, gcsClient, s3Client;
174311
- var init_manifest_loader = __esm(() => {
174312
- init_stored_column_types();
174313
- init_quoting();
174314
- init_logger();
174315
- import_client_s32 = __toESM(require_dist_cjs75());
174316
- });
174317
-
174318
175179
  // src/service/materialization/run/manifest_committer.ts
174319
175180
  function rebindsOwnVersionAfter(served) {
174320
175181
  return served?.autoLoadStep !== "timeout";
@@ -175417,6 +176278,43 @@ function keptAfter(run, runs, reader, fresh) {
175417
176278
  write: tables.length > 0 || keptTablesIn(before?.metadata ?? null).length > 0 || Array.isArray(run.metadata?.[KEPT_TABLES_KEY])
175418
176279
  };
175419
176280
  }
176281
+ function apiConnectionOf(environment, connectionName) {
176282
+ try {
176283
+ return environment.getApiConnection(connectionName);
176284
+ } catch {
176285
+ return;
176286
+ }
176287
+ }
176288
+ function sqlStateOf(err) {
176289
+ for (let e = err, depth = 0;e && depth < 8; depth++) {
176290
+ const code = e.code;
176291
+ if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code))
176292
+ return code;
176293
+ e = e.cause;
176294
+ }
176295
+ return;
176296
+ }
176297
+ function dropRefusalOf(err, where) {
176298
+ if (dependedOn(err)) {
176299
+ return new MaterializedTableDropRefusedError("TABLE_IN_USE", `Table ${where} is not dropped (TABLE_IN_USE): other objects in the ` + `warehouse (a view, a foreign key) depend on it. Drop or repoint ` + `them first.`);
176300
+ }
176301
+ const state = sqlStateOf(err);
176302
+ if (state === "42501") {
176303
+ return new MaterializedTableDropRefusedError("TABLE_OWNED_ELSEWHERE", `Table ${where} is not dropped (TABLE_OWNED_ELSEWHERE): the ` + `connection may not drop it, so it is not a table this ` + `package's builds own.`);
176304
+ }
176305
+ if (state === "42809") {
176306
+ return new MaterializedTableDropRefusedError("TABLE_OWNED_ELSEWHERE", `Table ${where} is not dropped (TABLE_OWNED_ELSEWHERE): the name ` + `holds something other than a table, which no build of this ` + `package makes.`);
176307
+ }
176308
+ return;
176309
+ }
176310
+ function servingReadersOf(runs) {
176311
+ const readers = [{}];
176312
+ const versions = new Set(runs.map((m) => m.version).filter((v) => v !== null));
176313
+ for (const v of versions) {
176314
+ readers.push({ versionId: v }, { versionId: v, owned: v });
176315
+ }
176316
+ return readers;
176317
+ }
175420
176318
 
175421
176319
  class Reclaimer {
175422
176320
  deps;
@@ -175457,6 +176355,191 @@ class Reclaimer {
175457
176355
  return (name) => pkg.getMalloyConnection(name);
175458
176356
  return async (name) => name === "duckdb" ? undefined : environment.getMalloyConnection(name);
175459
176357
  }
176358
+ async dropConnectionTable(request) {
176359
+ const { environment, environmentId, packageName, physicalTableName } = request;
176360
+ const withRunLock = this.deps.withRunLock ?? ((_e, _i, _p, _v, fn) => fn());
176361
+ const withTableLock = this.deps.withTableLock ?? ((_i, _p, fn) => fn());
176362
+ return withRunLock(environment, environmentId, packageName, undefined, () => withTableLock(environmentId, packageName, () => withOwnedNameLock(physicalTableName, async () => {
176363
+ const runs = await this.repository.listMaterializations(environmentId, packageName) ?? [];
176364
+ const evidence = this.assertDroppable(request, runs);
176365
+ await this.assertNotBound(request);
176366
+ return this.probeAndDrop(request, evidence);
176367
+ })));
176368
+ }
176369
+ assertDroppable(request, runs) {
176370
+ const {
176371
+ packageName,
176372
+ connectionName,
176373
+ physicalTableName,
176374
+ materializationId
176375
+ } = request;
176376
+ const active = runs.find((m) => isActiveRun(m.status));
176377
+ if (active) {
176378
+ throw new MaterializationConflictError(`Run ${active.id} of package ${packageName} is ${active.status}; ` + `drop the table once it settles.`);
176379
+ }
176380
+ const named = materializationId === undefined ? undefined : runs.find((m) => m.id === materializationId);
176381
+ if (materializationId !== undefined && !named) {
176382
+ throw new MaterializationNotFoundError(`Materialization ${materializationId} not found for package ${packageName}`);
176383
+ }
176384
+ const inUse = (why) => new MaterializedTableDropRefusedError("TABLE_IN_USE", `Table '${physicalTableName}' on connection '${connectionName}' ` + `is not dropped (TABLE_IN_USE): ${why}. Delete or replace ` + `that run first.`);
176385
+ const namesIt = (e) => !!e.physicalTableName && mayBeOneTableAnywhere(e.physicalTableName, physicalTableName);
176386
+ const committedNaming = runs.find((m) => m.id !== materializationId && m.status === "MANIFEST_FILE_READY" && Object.values(m.manifest?.entries ?? {}).some(namesIt));
176387
+ if (committedNaming) {
176388
+ throw inUse(`committed run ${committedNaming.id} of the package names a ` + `table '${physicalTableName}'`);
176389
+ }
176390
+ if (named?.status === "MANIFEST_FILE_READY" && Object.values(named.manifest?.entries ?? {}).some(namesIt) && servingReadersOf(runs).some((reader) => newestServingRun(runs, reader)?.id === named.id)) {
176391
+ throw inUse(`run ${named.id} is the newest run the package or one of its ` + `versions serves from`);
176392
+ }
176393
+ const copyOf = runs.flatMap((m) => reclaimableEntries(m)).find((e) => e.physicalTableName && [stagingSuffix, backupSuffix].some((suffix) => mayBeOneTableAnywhere(physicalTableName, `${e.physicalTableName}${suffix(e.sourceEntityId)}`)));
176394
+ if (copyOf) {
176395
+ throw new InvalidArgumentError(`Table '${physicalTableName}' is the staging or backup copy of ` + `'${copyOf.physicalTableName}', and is dropped with it: drop ` + `'${copyOf.physicalTableName}' instead.`);
176396
+ }
176397
+ const recordsHere = (m) => reclaimableEntries(m).find((e) => !e.storageDestinationName && e.connectionName === connectionName && e.physicalTableName === physicalTableName);
176398
+ const namedEntry = named ? recordsHere(named) : undefined;
176399
+ let recorded = namedEntry;
176400
+ for (const m of runs) {
176401
+ if (recorded)
176402
+ break;
176403
+ if (!isActiveRun(m.status))
176404
+ recorded = recordsHere(m);
176405
+ }
176406
+ return {
176407
+ namedRecordsIt: namedEntry !== undefined,
176408
+ ...recorded ? { recorded } : {}
176409
+ };
176410
+ }
176411
+ async assertNotBound(request) {
176412
+ const { environment, environmentId, connectionName, physicalTableName } = request;
176413
+ const identity = tableIdentity(physicalTableName);
176414
+ const copies = [];
176415
+ for (const pkg of environment.getLoadedPackages()) {
176416
+ copies.push({
176417
+ label: `package '${pkg.getPackageName()}'`,
176418
+ names: pkg.boundTableNames?.() ?? []
176419
+ });
176420
+ }
176421
+ const versions = environment.getVersionService() === null ? [] : await this.repository.listVersionsByEnvironment(environmentId);
176422
+ for (const row of versions) {
176423
+ const pkg = environment.peekVersion(row.packageName, row.versionId);
176424
+ if (!pkg)
176425
+ continue;
176426
+ copies.push({
176427
+ label: `version ${row.versionId} of package '${row.packageName}'`,
176428
+ names: pkg.boundTableNames?.() ?? []
176429
+ });
176430
+ }
176431
+ const bound = copies.find((c) => c.names.some((name) => tableIdentity(name) === identity));
176432
+ if (bound) {
176433
+ throw new MaterializedTableDropRefusedError("TABLE_IN_USE", `Table '${physicalTableName}' on connection '${connectionName}' ` + `is not dropped (TABLE_IN_USE): ${bound.label} is bound to a ` + `table by that name and may be serving it. Rebind it (build ` + `again, or delete the run it serves) first.`);
176434
+ }
176435
+ }
176436
+ async probeAndDrop(request, evidence) {
176437
+ const {
176438
+ environment,
176439
+ environmentName,
176440
+ environmentId,
176441
+ packageName,
176442
+ connectionName,
176443
+ connection,
176444
+ physicalTableName,
176445
+ materializationId
176446
+ } = request;
176447
+ const where = `'${physicalTableName}' on connection '${connectionName}'`;
176448
+ const unverified = (why) => new MaterializedTableDropRefusedError("TABLE_OWNERSHIP_UNVERIFIED", `Table ${where} is not dropped (TABLE_OWNERSHIP_UNVERIFIED): ${why}.`);
176449
+ const runOptions = statementRunOptions(environment, connectionName, {
176450
+ queryClass: "ops",
176451
+ environment: environmentName,
176452
+ package: packageName,
176453
+ ...materializationId ? { runId: materializationId } : {}
176454
+ });
176455
+ const site = databaseTableSite(connection, runOptions);
176456
+ if (!capabilitiesOf(site.dialect).tableOwnership) {
176457
+ throw unverified(`whose it is cannot be read on dialect '${site.dialect}'`);
176458
+ }
176459
+ const owner = packageOwner(environmentName, packageName);
176460
+ const redacted = (err) => redactConnectionSecrets(errMessage(err), apiConnectionOf(environment, connectionName));
176461
+ let holder;
176462
+ try {
176463
+ const segments = site.segments(physicalTableName);
176464
+ holder = markedFor(await site.run(ownedTableProbeSql(segments, site.dialect)), owner);
176465
+ } catch (err) {
176466
+ logger.warn("Could not read who holds a table a caller would drop", {
176467
+ environmentName,
176468
+ packageName,
176469
+ connectionName,
176470
+ physicalTableName,
176471
+ error: redacted(err)
176472
+ });
176473
+ throw unverified("whose it is could not be read (the probe failed)");
176474
+ }
176475
+ if (holder.state === "free" || holder.state === "ours" && holder.view) {
176476
+ if (evidence.recorded)
176477
+ return "absent";
176478
+ throw new TableNotFoundError(`No table ${where}, and no run of package ${packageName} records ` + `one there.`);
176479
+ }
176480
+ if (holder.state === "taken") {
176481
+ logger.warn("Refused a caller's drop of a table another holds", {
176482
+ environmentName,
176483
+ packageName,
176484
+ connectionName,
176485
+ physicalTableName,
176486
+ holder: holder.holder
176487
+ });
176488
+ throw new MaterializedTableDropRefusedError("TABLE_OWNED_ELSEWHERE", `Table ${where} is not dropped (TABLE_OWNED_ELSEWHERE): the name ` + `is held by a table or view that is not package ` + `${packageName}'s.`);
176489
+ }
176490
+ if (holder.state === "unmarked" && !evidence.namedRecordsIt) {
176491
+ throw unverified(materializationId === undefined ? `it carries no Publisher ownership mark. Pass the ` + `materializationId of the run that built it, while that ` + `run's record exists` : `it carries no Publisher ownership mark, and run ` + `${materializationId} does not record it on this connection`);
176492
+ }
176493
+ const leftoversOf = evidence.recorded?.sourceEntityId;
176494
+ const tier = { connection, runOptions };
176495
+ try {
176496
+ await DATABASE2.drop(tier, { physicalTableName });
176497
+ } catch (err) {
176498
+ recordDropTables("failure", "database", "caller");
176499
+ logger.warn("Failed to drop a materialized table at a caller's request", {
176500
+ environmentName,
176501
+ packageName,
176502
+ connectionName,
176503
+ physicalTableName,
176504
+ error: redacted(err)
176505
+ });
176506
+ throw dropRefusalOf(err, where) ?? databaseAccessFailure(err) ?? new Error(`Dropping table ${where} failed: ${redacted(err)}`);
176507
+ }
176508
+ recordDropTables("success", "database", "caller");
176509
+ logger.info("Dropped a materialized table at a caller's request", {
176510
+ environmentName,
176511
+ packageName,
176512
+ connectionName,
176513
+ physicalTableName,
176514
+ ...materializationId ? { runId: materializationId } : {},
176515
+ mark: holder.state
176516
+ });
176517
+ if (leftoversOf) {
176518
+ for (const copy of [
176519
+ `${physicalTableName}${stagingSuffix(leftoversOf)}`,
176520
+ `${physicalTableName}${backupSuffix(leftoversOf)}`
176521
+ ]) {
176522
+ await DATABASE2.drop(tier, { physicalTableName: copy }).catch((err) => {
176523
+ recordDropTables("failure", "database", "caller");
176524
+ logger.warn("Dropped a table at a caller's request, but not a build's leftover copy of it", {
176525
+ environmentName,
176526
+ packageName,
176527
+ connectionName,
176528
+ physicalTableName: copy,
176529
+ error: redacted(err)
176530
+ });
176531
+ });
176532
+ }
176533
+ }
176534
+ await this.forgetBoundaries(environmentId, [
176535
+ {
176536
+ sourceEntityId: leftoversOf ?? "",
176537
+ connectionName,
176538
+ physicalTableName
176539
+ }
176540
+ ]);
176541
+ return "dropped";
176542
+ }
175460
176543
  async dropManifestEntries(environment, environmentName, packageName, materializationId, occasion, entries, stillReferenced, connectionFor, nameViews, skipped) {
175461
176544
  const m = { id: materializationId };
175462
176545
  const owed = [];
@@ -175836,6 +176919,7 @@ function logRetiredByView(materializationId, physicalTableName) {
175836
176919
  }
175837
176920
  var DATABASE2, STORAGE2, RENAMED_TABLES_KEY = "renamedTables", KEPT_TABLES_KEY = "keptTables", TRANSIENT_GUARDS, KEPT_PROBES_AT_ONCE = 4;
175838
176921
  var init_reclaimer = __esm(() => {
176922
+ init_errors2();
175839
176923
  init_logger();
175840
176924
  init_quoting();
175841
176925
  init_materialization_metrics();
@@ -175849,6 +176933,8 @@ var init_reclaimer = __esm(() => {
175849
176933
  init_leftover_name_views();
175850
176934
  init_table_mark_sql();
175851
176935
  init_table_ownership();
176936
+ init_warehouse_sql();
176937
+ init_database_build_strategy();
175852
176938
  init_table_site();
175853
176939
  init_dialect();
175854
176940
  init_run_instructions();
@@ -176578,7 +177664,8 @@ class MaterializationService {
176578
177664
  if (!versions)
176579
177665
  return fn();
176580
177666
  return versions.withVersionLock(packageName, versionId, () => this.claims.withTableLock(environmentId, packageName, fn));
176581
- }
177667
+ },
177668
+ withTableLock: (environmentId, packageName, fn) => this.claims.withTableLock(environmentId, packageName, fn)
176582
177669
  });
176583
177670
  const real = this.realCollaborators();
176584
177671
  this.collaborators = {
@@ -176847,6 +177934,9 @@ class MaterializationService {
176847
177934
  now: new Date(startedAt),
176848
177935
  ledger: opts.ledger
176849
177936
  });
177937
+ if (incremental) {
177938
+ incremental.priorLateRows = pkg.boundLateRows?.();
177939
+ }
176850
177940
  const derived = await this.deriveRunInstructions(run, target, incremental);
176851
177941
  const { instructions } = derived;
176852
177942
  await this.claimRunTables(run, target, instructions, state);
@@ -177168,12 +178258,54 @@ Fix the files and reload the package, then run again.`);
177168
178258
  await this.repository.deleteMaterialization(id);
177169
178259
  await this.committer.rebindLoadedVersions(environmentName, packageName);
177170
178260
  }
178261
+ async dropMaterializedTable(environmentName, packageName, connectionName, tableName, options = {}) {
178262
+ const versionId = options.versionId ?? VersionRef.LATEST;
178263
+ const environmentId = await this.resolveEnvironmentId(environmentName);
178264
+ const environment = await this.host.getEnvironment(parseEnvironmentName(environmentName), false);
178265
+ await this.resolveRunVersion(environmentName, packageName, versionId);
178266
+ if (options.materializationId !== undefined) {
178267
+ await this.getMaterialization(environmentName, packageName, options.materializationId, versionId);
178268
+ }
178269
+ if (!isUsableTableName2(tableName)) {
178270
+ throw new InvalidArgumentError(`tableName '${tableName}' must be a table path with no empty part, no backslash or control character, and only whole quoted parts`);
178271
+ }
178272
+ const pkg = await environment.getPackage(parsePackageName(packageName), false, { versionId });
178273
+ let connection;
178274
+ try {
178275
+ connection = await pkg.getMalloyConnection(connectionName);
178276
+ } catch (error) {
178277
+ if (error instanceof UnconfiguredConnectionError) {
178278
+ throw new ConnectionNotFoundError(`Package ${packageName} reaches no connection ${connectionName}`);
178279
+ }
178280
+ throw databaseAccessFailure(error) ?? error;
178281
+ }
178282
+ try {
178283
+ quoteTablePath(tableName, connection.dialectName);
178284
+ } catch (error) {
178285
+ if (error instanceof UnquotableIdentifierError) {
178286
+ throw new InvalidArgumentError(error.message);
178287
+ }
178288
+ throw error;
178289
+ }
178290
+ return this.reclaimer.dropConnectionTable({
178291
+ environment,
178292
+ environmentName,
178293
+ environmentId,
178294
+ packageName,
178295
+ connectionName,
178296
+ connection,
178297
+ physicalTableName: tableName,
178298
+ ...options.materializationId !== undefined ? { materializationId: options.materializationId } : {}
178299
+ });
178300
+ }
177171
178301
  resolveEnvironmentId(environmentName) {
177172
178302
  return resolveEnvironmentId(this.repository, environmentName);
177173
178303
  }
177174
178304
  }
177175
178305
  var init_materialization_service = __esm(() => {
177176
178306
  init_errors2();
178307
+ init_quoting();
178308
+ init_manifest_loader();
177177
178309
  init_logger();
177178
178310
  init_config2();
177179
178311
  init_MaterializationRepository();
@@ -177837,6 +178969,9 @@ class MaterializationController {
177837
178969
  async getMaterialization(environmentName, packageName, materializationId, versionId = VersionRef.LATEST) {
177838
178970
  return toWire(await this.materializationService.getMaterialization(environmentName, packageName, materializationId, versionId));
177839
178971
  }
178972
+ async dropMaterializedTable(environmentName, packageName, connectionName, tableName, options = {}) {
178973
+ await this.materializationService.dropMaterializedTable(environmentName, packageName, connectionName, tableName, options);
178974
+ }
177840
178975
  async deleteMaterialization(environmentName, packageName, materializationId, options = {}) {
177841
178976
  return this.materializationService.deleteMaterialization(environmentName, packageName, materializationId, options);
177842
178977
  }
@@ -190172,17 +191307,17 @@ Present coverage in this order:
190172
191307
  {
190173
191308
  name: "malloy-materialization",
190174
191309
  description: "Add, confirm and debug Malloy Persistence materializations in a package - persist an expensive source so queries read a pre-built table, in the source's own warehouse or in a storage destination. Read this whenever the user wants to materialize a source, add a persist annotation, speed up a slow source, build one stored rollup over another, tune what to persist, or asks why a persist source isn't building or isn't being read.",
190175
- body: "# Materialization (Malloy Persistence)\n\nMaterialize an expensive source once so queries read a **pre-built table** instead of recomputing it every time. You tag a source `#@ persist`, a materialization run builds it into a physical table, and queries against it are rewritten to read that table.\n\n> **The #1 gotcha, up front:** if a persist source isn't materializing, it is almost always one of four things - no build ever ran (a standalone Publisher does not build on publish - see **Building and refreshing**), a build ran and failed or lost that one source (a run can finish ready with `failures`; read them), the model declaring the source has no `##! experimental.persistence` flag and nothing flagged imports it (it is skipped without a warning), or the package was reloaded since the build (a reload drops the bindings until the next run). Jump to **Debugging a no-op build**.\n\nThis file is the core. The details live beside it, one topic per file, and each is a prompt of its own:\n\n- `reference/annotation.md` - the `#@ persist` tag: what can carry it, the name rules, identity and reuse, readers of a persisted source, and every option with where it is explained.\n- `reference/policy.md` - the `publisher.json` block: `scope`, `queryMetadata`, and where the rules are enforced.\n- `reference/storage.md` - building into a **storage destination** (`storage=`), where a given may sit, which sources that tier refuses, and how a stored table is served.\n- `reference/chaining.md` - one stored source built **over another stored source**: what makes it reuse the parent's table or recompute from the warehouse, and how to read which happened.\n- `reference/refresh.md` - keeping a table current: `freshness`, `schedule`, and `refresh=\"incremental\"`.\n- `reference/access-filter.md` - persisting a `#(access_filter)`-gated source, and the bound on a stale access decision.\n- `reference/tuning.md` - reading the materialization history to decide what to persist, stop persisting, or reschedule (recommendations only).\n\n## v1 or v2: which spelling to write\n\nPublisher has two spellings. **v1** is `#@ persist` on a source and `#@ preaggregate` on a measure, and every server reads it. **v2** is `#(materialize)` on a source and `#(rollup)` on a measure, on by default behind the server switch `PUBLISHER_MATERIALIZE` (`false` turns it off; the switch is removed one release after the default ships). Since the v1 cutover both are served the same way: a stored table by the served copy (the author's own files with each stored source re-rooted on its table), a rollup by the rollup leg, so a query reads a table only when the path report says so. Everything else in this skill describes v1 unless it says otherwise.\n\n**Pick by what the server runs, then by where the table goes:**\n\n| The server | A table in a storage destination | A table in the source's own warehouse | A rollup on a measure |\n|---|---|---|---|\n| `PUBLISHER_MATERIALIZE` on (the default) | `#(materialize) storage=\"lake\"` (needs `PERSIST_STORAGE_MODE=on` too) | `#(materialize)`, or `#(materialize) name=\"schema.table\"` to name and place it | `#(rollup) grain=[\"a\", \"b\"]` |\n| switch off (`PUBLISHER_MATERIALIZE=false`) | `#@ persist name=\"...\" storage=\"lake\"` | `#@ persist name=\"...\"` | `#@ preaggregate grain=\"a, b\"` |\n\nSo for new work, write v2 where the server has the switch on, and v1 where it is off. A source with a row-level gate (`#(authorize)`, `#(access_filter)`) of its own is built and served past that gate on either tier, database or `storage=`, `#(materialize)` or `#@ persist`, with `PUBLISHER_MATERIALIZE_GATED_SOURCES` off: the table holds every caller's rows and the gate is re-applied on every read. A `storage=` table puts those rows, ungated, in the destination, where anyone with direct access to it can read them; say so when you materialize a gated source there. A row filter it inherits, a gate reached through a join, or a gate over a source whose build reads a given is refused on both tiers. Ask whoever runs the server if you cannot tell; the startup log lists `materialize.enabled=true from PUBLISHER_MATERIALIZE` when it is on. **With the switch off, `#(materialize)` is ignored with no warning at all** (no build, no serve verdict, answered live), and `#(rollup)` is only an `annotation-near-miss` warning, so a v2 annotation on a v1 server looks exactly like a build that never ran.\n\n```malloy\n// v2, switch on: no ##! experimental.persistence needed in this file\n#(materialize) name=\"east_orders\" storage=\"lake\"\nsource: east_orders is orders_base extend {\n where: region = 'east'\n measure: order_count is count()\n}\n\nsource: sales is orders_base extend {\n #(rollup) grain=[\"category\"]\n #(rollup) grain=[\"category\", \"region\"]\n measure: revenue is amount.sum()\n}\n```\n\nWhat is different about v2, briefly:\n\n- **It stores the source as written** - every dimension (computed, private and internal ones too) with its `where:` applied, not a query's output - so a plain `extend` over a table is fine and needs no `-> { select: * }`. Keys are closed: `name`, `storage`, `refresh`, `watermark`, `merge_key`, `freshness.*`, `queryMetadata.*`, `inline`. Any other key fails the publish and the load (`materialize-unknown-key`; the retired `partition=` is `materialize-retired-key`).\n- **The base must not declare measures, views or joins**, unless the base is materialized too. A `#(materialize)` source that inherits one is built but never read: `served-copy-not-served` (\"This source inherits fields ...\"), serve verdict `live` / `served_copy`, every query live. Build over a base with none (as above), or keep the query shape (`orders -> { select: * } extend { ... }`) and declare the measures after it.\n- **Joins are references by default.** `inline=[\"j\"]` stores a join_one as `j__<field>` columns, or a join_many as a pair table; an incremental pair table names a watermark on each side, `watermark=[\"updated_at\", \"j.updated_at\"]`.\n- **`#@ persist` on a view and `#@ -persist` on a reader are the same in both.** A persisted view is built only with the switch on, and so is `#@ persist` on a named `query:` (`reference/annotation.md`). Off, either is answered live, its line is still read (an invalid one fails the load), and a valid one warns `persist-view-not-built` or `persist-query-not-built`. `#@ preaggregate` is deprecated (a `deprecated-preaggregate-annotation` warning with the switch on; it still builds). So is `#(preaggregate)`, `#(rollup)`'s former name: it is read the same for one release, with the same warning, and a measure that carries both fails the load (`rollup-invalid`). Write `#(rollup)`.\n- **Confirm it the v2 way.** The package's serve verdicts (`GET .../packages/{pkg}/status`, `serveVerdicts`) read `serves`; a query's path report reads `servedBy.kind: \"materialized\"` with `via: \"served_copy\"` (a rollup: `kind: \"rollup\"`; a persisted view: `kind: \"view\"`; a persisted named query: `kind: \"query\"`). `manifestBindingStatus` does not cover v2 tables.\n\n**Existing v1 code is not wrong**, and moving it is optional. When asked to move it, follow `docs/materialization-migration.md` in the Publisher repository: one v1 spelling at a time, a dry-run publish (`POST .../packages?dryRun=true`) to read the warnings and serve verdicts, a build (every migrated source rebuilds once, because its content address moves), then the path report and a served-versus-live comparison against an opted-out reader (`#@ -persist source: x_live is x extend {}`, declared in a model file, not in the query text). Keep the v1 source's `name=` when you move it: an unversioned or `scope: \"package\"` package's table stays at that name (the package's own runs wrote it). Without `name=`, a v2 table takes a readable name, `<package>__<file>__<source>__p<hash>`, and on BigQuery a database table then is not built: a `#(materialize)` or `#@ persist` source with no dataset-qualified `name=`, or a rollup whose `name=` (or its base's) gives no dataset, is refused at plan (reason `needs_qualified_name`) and serves live, so give it a dataset-qualified `name=`. Under `scope: \"version\"` a `name=` sets the start of the table's name, schema or dataset included, and the version and a hash follow it (`analytics.summary_t__v1_2_0__p<hash>`), and no view is ever made at `name=`.\n\n## The recipe (get this right and it just works)\n\n1. **`##! experimental.persistence` on every `.malloy` file that declares a `#@ persist` source** (a file whose only materializations are v2 `#(materialize)` needs none). Either form enables it:\n - `##! experimental.persistence`, or\n - `##! experimental { access_modifiers, sql_functions, persistence }` (add `persistence` to the existing list).\n\n **Why it matters:** the build plan walks only the models that carry the flag, and skips every other file **without a warning**. The flag is a property of the model being *walked*, not of the file that declares the annotation: a flagged model builds every persist source its walk reaches, including ones declared in a flagless file it imports, and a flagless file's persist sources build only when some flagged model imports it. So a `#@ persist` in a flagless file that nothing flagged imports is silently never built, while adding a flagged entry model that imports it starts building tables that were inert - neither state warns. Put the flag in the declaring file itself: that is the one placement whose effect does not depend on what else imports it. A file with no persist source of its own does not need the flag; adding it anyway is harmless. (`#@ preaggregate` rollups are the one exception: they build from an unflagged file, because they live in a model Publisher synthesizes.)\n\n2. **`#@ persist name=\"...\"` on a query-based source, with the name quoted:**\n ```malloy\n #@ persist name=\"my_dataset.my_table\"\n source: my_rollup is some_source -> { group_by: ...; aggregate: ... }\n ```\n - **Only `query_source` and `sql_select` sources are persistable** - a `-> { ... }` pipeline or a `conn.sql(\"...\")`, including one refined by a trailing `extend { ... }`. A `#@ persist` on a *plain* `extend` over a bare `conn.table(...)` is **refused, not ignored**: the package warns, and every run that covers it fails naming the source, so a whole-package run builds nothing until you fix it. Persist a query source instead (`source: x is raw -> { where: ...; select: * }`).\n - **Quote the name, once.** A bare `name=my_table` fails the package load with `persist annotation name must be quoted`; a name quoted *inside* the quotes (`name=\"\\\"My Table\\\"\"`) also fails the load, as not a plain identifier path. Publisher quotes each segment itself, so mixed case and reserved words need no extra quoting. The target's container must already exist and be writable by the connection.\n - **The name is not the identity.** A persist source is identified by a content address of its connection and SQL, so a rebuild with unchanged logic reuses the table and two sources with the same body share one. An `extend` of a persisted source reads the same table and is not a second build target.\n - **A `name=` is one table on its schema, whichever package asks.** Publisher's own builds give a table with no `name=` a readable name, `<package>__<file>__<source>__p<8 hex>` (`ecommerce__orders__orders__p3f9c2a1b`), the hex a hash of the environment, package, model and source, so packages sharing a schema never collide. A `name=` is used as written and marked as its package's; if another package already holds it, that source's build is refused (`table-owned-elsewhere` in the run's failures) and it answers live. Give it a different `name=`.\n\n The name rules, bound arguments, `#@ -persist`, and every option (`storage=`, `refresh=`, `freshness.*`, `queryMetadata.*`) are in `reference/annotation.md`.\n\n3. **Package persistence policy in `publisher.json`** (all optional):\n ```jsonc\n {\n \"name\": \"my-package\",\n \"queryMetadata\": { \"team\": \"finance\" }, // root level: tags every statement a build OR a query issues\n \"materialization\": {\n \"scope\": \"package\", // default; \"version\" = each published version owns its own tables\n \"freshness\": { \"window\": \"24h\", \"fallback\": \"live\" }\n }\n }\n ```\n - **`scope`** is a package-level contract about sharing tables across versions; on a standalone server it changes nothing except gating `schedule`. Its deprecated root-level home still works, but the two homes disagreeing **fails the load**.\n - **`freshness`** bounds how old a served table may be, the same way on every mechanism (rollups included) and in both deployments: a standalone run stamps the window on the tables it builds and rebuilds one past it on its next run; a **hosted control plane** stamps its own manifest and schedules refreshes to meet it. `fail` behaves like `live` today; only `stale_ok` keeps serving a stale table.\n - **`queryMetadata`** tags every build statement and every query for the backend's cost attribution. Root level; the home inside `materialization` is deprecated. Observability only.\n - **`schedule`** is a 5-field UTC cron that **requires `scope: \"version\"`** and **excludes `freshness`**; it fires only on a standalone server whose scheduler is enabled.\n\n The coherence rules are rejected at publish and at a policy edit, warned at load, and skipped by the scheduler. `reference/policy.md` has `scope` and `queryMetadata` in full; `reference/refresh.md` has `freshness` and `schedule`.\n\n## Building and refreshing (standalone vs. hosted)\n\nA `#@ persist` tag declares *what* to materialize; it does not by itself build anything.\n\n- **Standalone Publisher:** publishing or loading a package only computes its build plan - **no table is built until a materialization run executes.** Trigger one explicitly (`malloy-pub materialize --environment <env> --package <pkg> --wait`, or the materialization API), or turn on the opt-in local scheduler (off unless `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER` is set) to fire the package's `schedule` cron. Refresh is a re-run or that cron; `freshness` is not a refresh trigger here, so a freshness-only standalone package builds once and is not auto-refreshed. Two flags to know: `--force-refresh` builds every source even when its content address is unchanged (which is what every scheduler fire does), and `--reseed` is the only thing that rebuilds an incremental source from scratch. `--wait` gives up after **120 s by default** (`--timeout <s>`) and exits non-zero while the build keeps running; `malloy-pub get materialization <id>` then shows where it got to.\n- **Hosted (control-plane) deployment:** the build runs automatically on publish, best-effort - a build failure does **not** fail the publish (which is why a broken persist can look like a silent no-op), and the control plane drives refresh to meet the `freshness` objective.\n\nTwo mechanics either way. **One build at a time per package**: a second run requested while one is active is rejected with a 409 conflict rather than queued, and the scheduler skips a fire while a run is active. **A build can be partial**: `sourceNames` on the request builds only the sources it names and leaves the others exactly as they were (live if never built), which is how to add one source to a package without rebuilding the rest.\n\nEither way, a successful publish alone does not prove a table exists - confirm the build separately.\n\n## Confirming it worked\n\nA green run is not proof, and neither is a fast query (on small data a live recompute is fast too). Check what the server says it serves:\n\n1. **The run lists your source, and did not lose it.** A run's detail (`malloy-pub get materialization <id> --environment <env> --package <pkg>`) carries `manifest.entries`, a map keyed by `sourceEntityId` whose values name each built or reused source (`sourceName`) and its physical table. A run can finish `MANIFEST_FILE_READY` having built nothing (every source skipped for a missing flag, or carried forward unchanged) **or having lost a source**: a source that failed is absent from `entries` and present in `manifest.failures` with its error, and a source the eligibility gate refused is in `metadata.refusedSources`, while the run still reads ready. `metadata.sourcesBuilt` / `sourcesReused` / `sourcesFailed` / `sourcesRefused` are the counts. For a source built over another stored source, the entry's `upstreamReuse` says whether it read the parent's table (`reused`) or recomputed it (`recomputed`, with `upstreamRecomputeReason`) - see `reference/chaining.md`.\n2. **The package is bound to those tables.** On a standalone Publisher the package's serving state, `GET /api/v0/environments/{env}/packages/{pkg}/status`, reports `manifestBindingStatus` and `manifestEntryCount` (an older server: its entry in `GET /api/v0/status`, or the package's details). The count covers tables built in the source's own warehouse only: it reads `bound` with a nonzero count when such a table is bound and `unbound` otherwise. A `storage=` table never counts there - it appears under the package's `storageServeBindings`, so a package whose only persist sources are `storage=` reads `unbound` while serving from the store. `live_fallback` is a hosted-only status: a configured `manifestLocation` could not be fetched or bound, and the previously bound manifest (if any) stays in force.\n3. **The query names the table.** A query's full result (the REST query response without `compactJson`) carries the SQL it ran. Served from the table, its `FROM` names the physical table; computed live, it carries the source's own SQL instead. This is the per-query proof.\n4. **A reload unbinds them.** Reloading the package - including the automatic reload when a watched file is saved - drops the binding, and queries compute live until the next materialization run, which reuses unchanged tables and binds them again. (A server *restart* re-establishes the bindings from its store; a reload does not.) After editing a model, run a build before you trust a timing.\n\nA query response's `servedFrom` field names the tier that answered: `database` for a table built in the source's own connection, `storage` for a `storage=` table, `live_fallback` when a `storage=` read failed and live answered, and empty when no table answered. The path report's `servedBy.tier` names the same tier.\n\n## Debugging a no-op build\n\nSymptom: no table was built and the source still recomputes on every query. Check, in order:\n\n0. **Did a build actually run?** On a standalone Publisher, publish/load does **not** build - run `malloy-pub materialize` (or enable the scheduler). \"Publishes fine, no table\" is the *expected* standalone state, not a model bug. On a hosted deployment the build is automatic but best-effort, so a failure is silent - look for a `FAILED` run, and for a ready run with `failures`.\n1. **Did the run fail, or lose this source?** A `FAILED` run's `error` names what stopped it. A ready run's `manifest.failures` names each source that did not build, and `metadata.refusedSources` each one the gate refused, with the reason to act on. The package flags some of these before any run: an unbuildable persist source appears in its warnings, and `GET …/packages/{pkg}/build-plan` lists the sources a run will build, the ones it will refuse, and under `omittedSources` any the planner itself failed on (a code per source, or under `omittedFiles` a file whose sources it could not name; the server log has the error). A `#@ persist` on a non-persistable source fails every run that covers it, naming the source.\n2. **The declaring model is missing the persistence flag** and nothing flagged imports it: skipped without any warning, the run succeeds, the source is simply absent from what was built. Add the flag to the declaring file.\n3. **An unquoted persist name** - a bare `name=foo` **always** stops the load with `persist annotation name must be quoted`. (If you got *no* error at all, it isn't this.)\n4. **The package was reloaded** after the build (a saved file under watch mode counts). The tables exist and the run reads ready; the binding is gone. Run a build. And if a watched edit failed to compile, the server keeps serving the **old** model and its binding, and records the error under `staleCompileErrors` on `/status` - so \"still bound\" after an edit can mean the edit never took.\n5. **A `storage=` source serves live while the store is switched off.** With `PERSIST_STORAGE_MODE=off` a `storage=` source is skipped by the build and served live, with no error; it is never built into the warehouse instead. See `reference/storage.md`.\n\n**Isolation test** - add a trivial, self-contained persist source in its own file and rebuild:\n```malloy\n##! experimental.persistence\nsource: smoke_raw is my_conn.table('some_dataset.some_table')\n#@ persist name=\"scratch_dataset.persist_smoke_test\"\nsource: persist_smoke is smoke_raw -> { aggregate: n is count() }\n```\nIf **even this** doesn't build after a real run, the problem is package-wide: read the run's error (a non-persistable source anywhere fails the whole run and names it), then check that the connection can write the target dataset. If the smoke source builds and your real one doesn't, your real source is the problem: its file's flag, or its entry in `failures` / `refusedSources`. Delete the smoke file, delete its run (`malloy-pub delete materialization <id>`, record-only), and drop its table yourself through the connection.\n\n## Gotchas\n\n- **Flag every file that declares a persist source** - a flagless model nothing flagged imports is skipped without a warning.\n- **A `#@ persist` on a plain `extend` over `conn.table(...)` fails the run** - every run that covers it, naming the source.\n- **A tag doesn't build** - only an explicit run, the standalone scheduler, or a hosted control plane does.\n- **Quote the name, once** - bare stops the load, and so does a name with quotes inside it; Publisher quotes each segment for you.\n- **A ready run can still have lost a source** - read `manifest.failures` and `metadata.refusedSources`.\n- **A reload unbinds; a restart rebinds** - run a build before trusting a timing.\n- **Reuse is by content address, not by name** - `--force-refresh` and every scheduler fire defeat it.\n- **Removing a persist source does not drop its table** - and neither does `delete materialization`, which is record-only. Drop the table yourself through its connection once no remaining ready run, of any version (list runs per version with `versionId`), names a table with that name in any place; serving reverts to live in place.\n- **A given inside the persisted query is refused; in the source's own `extend` block it is applied per caller; inherited from a base it is refused and the source answers live** - `reference/storage.md`.\n- **A join to a non-persisted source, or a nested column, serves live for the queries that touch it** - the source's own fields still serve from the table.\n- **A `#(access_filter)`-gated source freezes its gating column when persisted** - `#@ preaggregate` refuses it outright; a `storage=` table holds every caller's rows, ungated, in the destination; `reference/access-filter.md`.\n\n## Reference files over MCP\n\nThis skill's `reference/` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read `reference/<name>.md`, get the prompt named `malloy-materialization/<name>` instead.\n\nAvailable: access-filter, annotation, chaining, policy, refresh, storage, tuning."
191310
+ body: "# Materialization (Malloy Persistence)\n\nMaterialize an expensive source once so queries read a **pre-built table** instead of recomputing it every time. You tag a source `#@ persist`, a materialization run builds it into a physical table, and queries against it are rewritten to read that table.\n\n> **The #1 gotcha, up front:** if a persist source isn't materializing, it is almost always one of four things - no build ever ran (a standalone Publisher does not build on publish - see **Building and refreshing**), a build ran and failed or lost that one source (a run can finish ready with `failures`; read them), the model declaring the source has no `##! experimental.persistence` flag and nothing flagged imports it (it is skipped without a warning), or the package was reloaded since the build (a reload drops the bindings until the next run). Jump to **Debugging a no-op build**.\n\nThis file is the core. The details live beside it, one topic per file, and each is a prompt of its own:\n\n- `reference/annotation.md` - the `#@ persist` tag: what can carry it, the name rules, identity and reuse, readers of a persisted source, and every option with where it is explained.\n- `reference/policy.md` - the `publisher.json` block: `scope`, `queryMetadata`, and where the rules are enforced.\n- `reference/storage.md` - building into a **storage destination** (`storage=`), where a given may sit, which sources that tier refuses, and how a stored table is served.\n- `reference/chaining.md` - one stored source built **over another stored source**: what makes it reuse the parent's table or recompute from the warehouse, and how to read which happened.\n- `reference/refresh.md` - keeping a table current: `freshness`, `schedule`, and `refresh=\"incremental\"`.\n- `reference/access-filter.md` - persisting a `#(access_filter)`-gated source, and the bound on a stale access decision.\n- `reference/tuning.md` - reading the materialization history to decide what to persist, stop persisting, or reschedule (recommendations only).\n\n## v1 or v2: which spelling to write\n\nPublisher has two spellings. **v1** is `#@ persist` on a source and `#@ preaggregate` on a measure, and every server reads it. **v2** is `#(materialize)` on a source and `#(rollup)` on a measure, on by default behind the server switch `PUBLISHER_MATERIALIZE` (`false` turns it off; the switch is removed one release after the default ships). Since the v1 cutover both are served the same way: a stored table by the served copy (the author's own files with each stored source re-rooted on its table), a rollup by the rollup leg, so a query reads a table only when the path report says so. Everything else in this skill describes v1 unless it says otherwise.\n\n**Pick by what the server runs, then by where the table goes:**\n\n| The server | A table in a storage destination | A table in the source's own warehouse | A rollup on a measure |\n|---|---|---|---|\n| `PUBLISHER_MATERIALIZE` on (the default) | `#(materialize) storage=\"lake\"` (needs `PERSIST_STORAGE_MODE=on` too) | `#(materialize)`, or `#(materialize) name=\"schema.table\"` to name and place it | `#(rollup) grain=[\"a\", \"b\"]` |\n| switch off (`PUBLISHER_MATERIALIZE=false`) | `#@ persist name=\"...\" storage=\"lake\"` | `#@ persist name=\"...\"` | `#@ preaggregate grain=\"a, b\"` |\n\nSo for new work, write v2 where the server has the switch on, and v1 where it is off. A source with a row-level gate (`#(authorize)`, `#(access_filter)`) of its own is built and served past that gate on either tier, database or `storage=`, `#(materialize)` or `#@ persist`, with `PUBLISHER_MATERIALIZE_GATED_SOURCES` off: the table holds every caller's rows and the gate is re-applied on every read. A `storage=` table puts those rows, ungated, in the destination, where anyone with direct access to it can read them; say so when you materialize a gated source there. A row filter it inherits, a gate reached through a join, or a gate over a source whose build reads a given is refused on both tiers. Ask whoever runs the server if you cannot tell; the startup log lists `materialize.enabled=true from PUBLISHER_MATERIALIZE` when it is on. **With the switch off, `#(materialize)` is ignored with no warning at all** (no build, no serve verdict, answered live), and `#(rollup)` is only an `annotation-near-miss` warning, so a v2 annotation on a v1 server looks exactly like a build that never ran.\n\n```malloy\n// v2, switch on: no ##! experimental.persistence needed in this file\n#(materialize) name=\"east_orders\" storage=\"lake\"\nsource: east_orders is orders_base extend {\n where: region = 'east'\n measure: order_count is count()\n}\n\nsource: sales is orders_base extend {\n #(rollup) grain=[\"category\"]\n #(rollup) grain=[\"category\", \"region\"]\n measure: revenue is amount.sum()\n}\n```\n\nWhat is different about v2, briefly:\n\n- **It stores the source as written** - every dimension (computed, private and internal ones too) with its `where:` applied, not a query's output - so a plain `extend` over a table is fine and needs no `-> { select: * }`. Keys are closed: `name`, `storage`, `refresh`, `watermark`, `merge_key`, `lookback`, `freshness.*`, `queryMetadata.*`, `inline`. Any other key fails the publish and the load (`materialize-unknown-key`; the retired `partition=` is `materialize-retired-key`).\n- **The base must not declare measures, views or joins**, unless the base is materialized too. A `#(materialize)` source that inherits one is built but never read: `served-copy-not-served` (\"This source inherits fields ...\"), serve verdict `live` / `served_copy`, every query live. Build over a base with none (as above), or keep the query shape (`orders -> { select: * } extend { ... }`) and declare the measures after it.\n- **Joins are references by default.** `inline=[\"j\"]` stores a join_one as `j__<field>` columns, or a join_many as a pair table; an incremental pair table names a watermark on each side, `watermark=[\"updated_at\", \"j.updated_at\"]`.\n- **`#@ persist` on a view and `#@ -persist` on a reader are the same in both.** A persisted view is built only with the switch on, and so is `#@ persist` on a named `query:` (`reference/annotation.md`). Off, either is answered live, its line is still read (an invalid one fails the load), and a valid one warns `persist-view-not-built` or `persist-query-not-built`. `#@ preaggregate` is deprecated (a `deprecated-preaggregate-annotation` warning with the switch on; it still builds). So is `#(preaggregate)`, `#(rollup)`'s former name: it is read the same for one release, with the same warning, and a measure that carries both fails the load (`rollup-invalid`). Write `#(rollup)`.\n- **Confirm it the v2 way.** The package's serve verdicts (`GET .../packages/{pkg}/status`, `serveVerdicts`) read `serves`; a query's path report reads `servedBy.kind: \"materialized\"` with `via: \"served_copy\"` (a rollup: `kind: \"rollup\"`; a persisted view: `kind: \"view\"`; a persisted named query: `kind: \"query\"`). `manifestBindingStatus` does not cover v2 tables.\n\n**Existing v1 code is not wrong**, and moving it is optional. When asked to move it, follow `docs/materialization-migration.md` in the Publisher repository: one v1 spelling at a time, a dry-run publish (`POST .../packages?dryRun=true`) to read the warnings and serve verdicts, a build (every migrated source rebuilds once, because its content address moves), then the path report and a served-versus-live comparison against an opted-out reader (`#@ -persist source: x_live is x extend {}`, declared in a model file, not in the query text). Keep the v1 source's `name=` when you move it: an unversioned or `scope: \"package\"` package's table stays at that name (the package's own runs wrote it). Without `name=`, a v2 table takes a readable name, `<package>__<file>__<source>__p<hash>`, and on BigQuery a database table then is not built: a `#(materialize)` or `#@ persist` source with no dataset-qualified `name=`, or a rollup whose `name=` (or its base's) gives no dataset, is refused at plan (reason `needs_qualified_name`) and serves live, so give it a dataset-qualified `name=`. Under `scope: \"version\"` a `name=` sets the start of the table's name, schema or dataset included, and the version and a hash follow it (`analytics.summary_t__v1_2_0__p<hash>`), and no view is ever made at `name=`.\n\n## The recipe (get this right and it just works)\n\n1. **`##! experimental.persistence` on every `.malloy` file that declares a `#@ persist` source** (a file whose only materializations are v2 `#(materialize)` needs none). Either form enables it:\n - `##! experimental.persistence`, or\n - `##! experimental { access_modifiers, sql_functions, persistence }` (add `persistence` to the existing list).\n\n **Why it matters:** the build plan walks only the models that carry the flag, and skips every other file **without a warning**. The flag is a property of the model being *walked*, not of the file that declares the annotation: a flagged model builds every persist source its walk reaches, including ones declared in a flagless file it imports, and a flagless file's persist sources build only when some flagged model imports it. So a `#@ persist` in a flagless file that nothing flagged imports is silently never built, while adding a flagged entry model that imports it starts building tables that were inert - neither state warns. Put the flag in the declaring file itself: that is the one placement whose effect does not depend on what else imports it. A file with no persist source of its own does not need the flag; adding it anyway is harmless. (`#@ preaggregate` rollups are the one exception: they build from an unflagged file, because they live in a model Publisher synthesizes.)\n\n2. **`#@ persist name=\"...\"` on a query-based source, with the name quoted:**\n ```malloy\n #@ persist name=\"my_dataset.my_table\"\n source: my_rollup is some_source -> { group_by: ...; aggregate: ... }\n ```\n - **Only `query_source` and `sql_select` sources are persistable** - a `-> { ... }` pipeline or a `conn.sql(\"...\")`, including one refined by a trailing `extend { ... }`. A `#@ persist` on a *plain* `extend` over a bare `conn.table(...)` is **refused, not ignored**: the package warns, and every run that covers it fails naming the source, so a whole-package run builds nothing until you fix it. Persist a query source instead (`source: x is raw -> { where: ...; select: * }`).\n - **Quote the name, once.** A bare `name=my_table` fails the package load with `persist annotation name must be quoted`; a name quoted *inside* the quotes (`name=\"\\\"My Table\\\"\"`) also fails the load, as not a plain identifier path. Publisher quotes each segment itself, so mixed case and reserved words need no extra quoting. The target's container must already exist and be writable by the connection.\n - **The name is not the identity.** A persist source is identified by a content address of its connection and SQL, so a rebuild with unchanged logic reuses the table and two sources with the same body share one. An `extend` of a persisted source reads the same table and is not a second build target.\n - **A `name=` is one table on its schema, whichever package asks.** Publisher's own builds give a table with no `name=` a readable name, `<package>__<file>__<source>__p<8 hex>` (`ecommerce__orders__orders__p3f9c2a1b`), the hex a hash of the environment, package, model and source, so packages sharing a schema never collide. A `name=` is used as written and marked as its package's; if another package already holds it, that source's build is refused (`table-owned-elsewhere` in the run's failures) and it answers live. Give it a different `name=`.\n\n The name rules, bound arguments, `#@ -persist`, and every option (`storage=`, `refresh=`, `freshness.*`, `queryMetadata.*`) are in `reference/annotation.md`.\n\n3. **Package persistence policy in `publisher.json`** (all optional):\n ```jsonc\n {\n \"name\": \"my-package\",\n \"queryMetadata\": { \"team\": \"finance\" }, // root level: tags every statement a build OR a query issues\n \"materialization\": {\n \"scope\": \"package\", // default; \"version\" = each published version owns its own tables\n \"freshness\": { \"window\": \"24h\", \"fallback\": \"live\" }\n }\n }\n ```\n - **`scope`** is a package-level contract about sharing tables across versions; on a standalone server it changes nothing except gating `schedule`. Its deprecated root-level home still works, but the two homes disagreeing **fails the load**.\n - **`freshness`** bounds how old a served table may be, the same way on every mechanism (rollups included) and in both deployments: a standalone run stamps the window on the tables it builds and rebuilds one past it on its next run; a **hosted control plane** stamps its own manifest and schedules refreshes to meet it. `fail` behaves like `live` today; only `stale_ok` keeps serving a stale table.\n - **`queryMetadata`** tags every build statement and every query for the backend's cost attribution. Root level; the home inside `materialization` is deprecated. Observability only.\n - **`schedule`** is a 5-field UTC cron that **requires `scope: \"version\"`** and **excludes `freshness`**; it fires only on a standalone server whose scheduler is enabled.\n\n The coherence rules are rejected at publish and at a policy edit, warned at load, and skipped by the scheduler. `reference/policy.md` has `scope` and `queryMetadata` in full; `reference/refresh.md` has `freshness` and `schedule`.\n\n## Building and refreshing (standalone vs. hosted)\n\nA `#@ persist` tag declares *what* to materialize; it does not by itself build anything.\n\n- **Standalone Publisher:** publishing or loading a package only computes its build plan - **no table is built until a materialization run executes.** Trigger one explicitly (`malloy-pub materialize --environment <env> --package <pkg> --wait`, or the materialization API), or turn on the opt-in local scheduler (off unless `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER` is set) to fire the package's `schedule` cron. Refresh is a re-run or that cron; `freshness` is not a refresh trigger here, so a freshness-only standalone package builds once and is not auto-refreshed. Two flags to know: `--force-refresh` builds every source even when its content address is unchanged (which is what every scheduler fire does), and `--reseed` is the only thing that rebuilds an incremental source from scratch. `--wait` gives up after **120 s by default** (`--timeout <s>`) and exits non-zero while the build keeps running; `malloy-pub get materialization <id>` then shows where it got to.\n- **Hosted (control-plane) deployment:** the build runs automatically on publish, best-effort - a build failure does **not** fail the publish (which is why a broken persist can look like a silent no-op), and the control plane drives refresh to meet the `freshness` objective.\n\nTwo mechanics either way. **One build at a time per package**: a second run requested while one is active is rejected with a 409 conflict rather than queued, and the scheduler skips a fire while a run is active. **A build can be partial**: `sourceNames` on the request builds only the sources it names and leaves the others exactly as they were (live if never built), which is how to add one source to a package without rebuilding the rest.\n\nEither way, a successful publish alone does not prove a table exists - confirm the build separately.\n\n## Confirming it worked\n\nA green run is not proof, and neither is a fast query (on small data a live recompute is fast too). Check what the server says it serves:\n\n1. **The run lists your source, and did not lose it.** A run's detail (`malloy-pub get materialization <id> --environment <env> --package <pkg>`) carries `manifest.entries`, a map keyed by `sourceEntityId` whose values name each built or reused source (`sourceName`) and its physical table. A run can finish `MANIFEST_FILE_READY` having built nothing (every source skipped for a missing flag, or carried forward unchanged) **or having lost a source**: a source that failed is absent from `entries` and present in `manifest.failures` with its error, and a source the eligibility gate refused is in `metadata.refusedSources`, while the run still reads ready. `metadata.sourcesBuilt` / `sourcesReused` / `sourcesFailed` / `sourcesRefused` are the counts. For a source built over another stored source, the entry's `upstreamReuse` says whether it read the parent's table (`reused`) or recomputed it (`recomputed`, with `upstreamRecomputeReason`) - see `reference/chaining.md`.\n2. **The package is bound to those tables.** On a standalone Publisher the package's serving state, `GET /api/v0/environments/{env}/packages/{pkg}/status`, reports `manifestBindingStatus` and `manifestEntryCount` (an older server: its entry in `GET /api/v0/status`, or the package's details). The count covers tables built in the source's own warehouse only: it reads `bound` with a nonzero count when such a table is bound and `unbound` otherwise. A `storage=` table never counts there - it appears under the package's `storageServeBindings`, so a package whose only persist sources are `storage=` reads `unbound` while serving from the store. `live_fallback` is a hosted-only status: a configured `manifestLocation` could not be fetched or bound, and the previously bound manifest (if any) stays in force.\n3. **The query names the table.** A query's full result (the REST query response without `compactJson`) carries the SQL it ran. Served from the table, its `FROM` names the physical table; computed live, it carries the source's own SQL instead. This is the per-query proof.\n4. **A reload unbinds them.** Reloading the package - including the automatic reload when a watched file is saved - drops the binding, and queries compute live until the next materialization run, which reuses unchanged tables and binds them again. (A server *restart* re-establishes the bindings from its store; a reload does not.) After editing a model, run a build before you trust a timing.\n\nA query response's `servedFrom` field names the tier that answered: `database` for a table built in the source's own connection, `storage` for a `storage=` table, `live_fallback` when a `storage=` read failed and live answered, and empty when no table answered. The path report's `servedBy.tier` names the same tier.\n\n## Debugging a no-op build\n\nSymptom: no table was built and the source still recomputes on every query. Check, in order:\n\n0. **Did a build actually run?** On a standalone Publisher, publish/load does **not** build - run `malloy-pub materialize` (or enable the scheduler). \"Publishes fine, no table\" is the *expected* standalone state, not a model bug. On a hosted deployment the build is automatic but best-effort, so a failure is silent - look for a `FAILED` run, and for a ready run with `failures`.\n1. **Did the run fail, or lose this source?** A `FAILED` run's `error` names what stopped it. A ready run's `manifest.failures` names each source that did not build, and `metadata.refusedSources` each one the gate refused, with the reason to act on. The package flags some of these before any run: an unbuildable persist source appears in its warnings, and `GET …/packages/{pkg}/build-plan` lists the sources a run will build, the ones it will refuse, and under `omittedSources` any the planner itself failed on (a code per source, or under `omittedFiles` a file whose sources it could not name; the server log has the error). A `#@ persist` on a non-persistable source fails every run that covers it, naming the source.\n2. **The declaring model is missing the persistence flag** and nothing flagged imports it: skipped without any warning, the run succeeds, the source is simply absent from what was built. Add the flag to the declaring file.\n3. **An unquoted persist name** - a bare `name=foo` **always** stops the load with `persist annotation name must be quoted`. (If you got *no* error at all, it isn't this.)\n4. **The package was reloaded** after the build (a saved file under watch mode counts). The tables exist and the run reads ready; the binding is gone. Run a build. And if a watched edit failed to compile, the server keeps serving the **old** model and its binding, and records the error under `staleCompileErrors` on `/status` - so \"still bound\" after an edit can mean the edit never took.\n5. **A `storage=` source serves live while the store is switched off.** With `PERSIST_STORAGE_MODE=off` a `storage=` source is skipped by the build and served live, with no error; it is never built into the warehouse instead. See `reference/storage.md`.\n\n**Isolation test** - add a trivial, self-contained persist source in its own file and rebuild:\n```malloy\n##! experimental.persistence\nsource: smoke_raw is my_conn.table('some_dataset.some_table')\n#@ persist name=\"scratch_dataset.persist_smoke_test\"\nsource: persist_smoke is smoke_raw -> { aggregate: n is count() }\n```\nIf **even this** doesn't build after a real run, the problem is package-wide: read the run's error (a non-persistable source anywhere fails the whole run and names it), then check that the connection can write the target dataset. If the smoke source builds and your real one doesn't, your real source is the problem: its file's flag, or its entry in `failures` / `refusedSources`. Delete the smoke file, delete its run (`malloy-pub delete materialization <id>`, record-only), and drop its table (`DELETE …/connections/{connectionName}/materializedTables/{physicalTableName}`, which refuses a table still in use).\n\n## Gotchas\n\n- **Flag every file that declares a persist source** - a flagless model nothing flagged imports is skipped without a warning.\n- **A `#@ persist` on a plain `extend` over `conn.table(...)` fails the run** - every run that covers it, naming the source.\n- **A tag doesn't build** - only an explicit run, the standalone scheduler, or a hosted control plane does.\n- **Quote the name, once** - bare stops the load, and so does a name with quotes inside it; Publisher quotes each segment for you.\n- **A ready run can still have lost a source** - read `manifest.failures` and `metadata.refusedSources`.\n- **A reload unbinds; a restart rebinds** - run a build before trusting a timing.\n- **Reuse is by content address, not by name** - `--force-refresh` and every scheduler fire defeat it.\n- **Removing a persist source does not drop its table** - and neither does `delete materialization`, which is record-only. Drop the table once no remaining ready run, of any version (list runs per version with `versionId`), names a table with that name in any place: `DELETE …/connections/{connectionName}/materializedTables/{physicalTableName}` checks that itself and answers 409 `TABLE_IN_USE` otherwise; serving reverts to live in place.\n- **A given inside the persisted query is refused; in the source's own `extend` block it is applied per caller; inherited from a base it is refused and the source answers live** - `reference/storage.md`.\n- **A join to a non-persisted source, or a nested column, serves live for the queries that touch it** - the source's own fields still serve from the table.\n- **A `#(access_filter)`-gated source freezes its gating column when persisted** - `#@ preaggregate` refuses it outright; a `storage=` table holds every caller's rows, ungated, in the destination; `reference/access-filter.md`.\n\n## Reference files over MCP\n\nThis skill's `reference/` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read `reference/<name>.md`, get the prompt named `malloy-materialization/<name>` instead.\n\nAvailable: access-filter, annotation, chaining, policy, refresh, storage, tuning."
190176
191311
  },
190177
191312
  {
190178
191313
  name: "malloy-materialization/access-filter",
190179
191314
  description: "Persisting a `#(access_filter)`-gated source. Reference detail for the malloy-materialization skill.",
190180
- body: "# Persisting a `#(access_filter)`-gated source\n\nA gated source **can** be persisted, on either tier but only in one shape, and the thing to be careful about is not refused by anything - you have to decide it.\n\n- **A rollup (`#(rollup)` or `#@ preaggregate`) over a gated source is built only where its gate holds on the rollup's rows**: database, every gate the base's own (declared on the base's own statement, not inherited from a source it extends, not through a join), and every field it reads a grain dimension. The gate is then re-applied on every read, as on a stored source (with `PUBLISHER_MATERIALIZE_GATED_SOURCES` on, an inherited gate too). Any other gated rollup is refused, naming it. The build skips a refused source, records it on the run (`metadata.refusedSources`), and builds the rest of the package. A run fails on a refusal only when every authored source it targeted was refused, or when `sourceNames` named this one; a refused rollup never fails it. (`#@ preaggregate` stores a rollup Publisher derives from a measure you annotated with a grain, rather than a source you wrote.) A rollup also groups *across* the gated column, so it could not be row-filtered afterwards even in principle.\n- **A `#@ persist`, database or `storage=`, is admitted** when the gate is the entry point's **own row filter** (or an `#(authorize)` lock): declared on the persisted source itself, and classified as a row filter. Both tiers follow the same rule (so does `#(materialize)`): the table holds every caller's rows and the gate is re-applied on every read through Publisher. (`#@ persist storage=<name>` materializes into a separate registered storage destination and serves from there, rather than building in the source's own connection.) **A `storage=` table puts those rows, ungated, at rest in the destination**, where anyone with direct access to the destination reads every row; tell the author before choosing that tier for a gated source, and make sure no connection a model can name reaches the destination (its catalog, schema or data path): stored tables are named predictably, so any package could read the gated rows through it. It is refused in three cases: the gate is reached only through a join, it does not classify as a row filter at all, or the persisted source inherits it from a source it derives from or extends (`source: mine is gated -> { ... }`, `gated extend { ... }`, across imports or two hops away). A table of an inherited gate would hold every caller's rows, and the served copy, which reads the table in place of the source that declares the gate, cannot apply the gate to it, so every query would answer live anyway: it is not built. Declare the gate on the persisted source itself to serve it from a table.\n\n**What to be wary of.** Persisting does not weaken the gate: it changes only where rows are read FROM, and the gate still runs live on every query as that query's own `WHERE`, so filtered rows come back filtered. What freezes is the **column the gate filters on**. A row whose access decision changes - it changes owner, say - keeps being served under its OLD decision until the next rebuild. That is a stale *access decision*, not merely stale data, and nothing raises an error.\n\n**None of this is needed for the gate to work.** It is enforced live on every query either way; what needs a bound is how long a *stale* decision can survive. Of the three controls that look like that bound, only the first is:\n\n- **`freshness.window=\"24h\"` with `freshness.fallback=\"live\"` is the bound** (`reference/refresh.md`). The serve path re-checks freshness per query, so once the artifact ages past the window it drops out of the serving set and the query recomputes live, correctly filtered - whether or not a rebuild ever lands. Three details decide whether you actually get that. **`fallback` must not be `stale_ok`**: under `stale_ok` a stale artifact keeps being served, which voids the bound (`live` and `fail` both bound it today). Window and fallback resolve *independently, per field*, across the source, model-file and package layers, so a package-level `stale_ok` silently defeats a window you set on the source. Prefer the **per-source** spelling `#@ persist name=\"...\" freshness.window=\"24h\" freshness.fallback=\"live\"` over the package-wide `materialization.freshness` key: the gated source is what needs the bound, and setting it package-wide forces every other persisted source to recompute once stale too. And **a content-identical sibling shares the artifact, so it shares the window**: reuse is keyed on the content-addressed `sourceEntityId`, which folds the connection and the SQL but *not* the source name, so two persist sources whose bodies compute the same SQL, with the same `name=` or none, resolve to one table carrying one freshness policy (different `name=`s are different tables). A host that folds the siblings' policies keeps the tightest window any of them declares - a sibling declaring nothing cannot loosen yours, and yours pulls that sibling's reads off the table once it lapses - and keeps the bounding fallback, so a sibling's `stale_ok` cannot void your bound either. If two sources need genuinely different windows, give them different `name=`s or genuinely different SQL.\n\n Both of those are properties of the **host** that assembles the manifest, not of the annotation: the publisher reports freshness per source and does no folding itself. Where the host does not fold, which sibling's policy reaches the wire is unspecified; a host that folds does so when it next publishes a version's manifest, not retroactively to manifests already distributed - so you can declare the window correctly and not have it in force yet.\n- **A cron alone is not a bound.** A failed build or a stopped scheduler leaves the source serving its old decisions indefinitely. `freshness` and `schedule` are mutually exclusive; for a gated source, take the window.\n- **`refresh=\"incremental\"` does not bound revocation.** The delta only re-reads rows in `[covered_through, frontier)`, so a row that changes owner *without its watermark advancing* is never re-read - while the entry still reports an advancing `coveredThrough` and reads as healthy. Only a full rebuild recomputes the gating column.\n\n**The window binds on a standalone server and under a control plane alike.** A standalone run stamps the declared window and the table's `dataAsOf` on the manifest it commits, as a control plane stamps the manifest it distributes, so the table ages out per query either way. Under a control plane, the control plane's manifest decides: what it stamps applies whatever the model declares.\n\nWhen recommending `#@ persist` on a gated source, pair it with a freshness window and say out loud what staleness the author is accepting. A gated source with neither a window nor a full-rebuild cadence has no bound on how long a revoked row keeps being served."
191315
+ body: "# Persisting a `#(access_filter)`-gated source\n\nA gated source **can** be persisted, on either tier but only in one shape, and the thing to be careful about is not refused by anything - you have to decide it.\n\n- **A rollup (`#(rollup)` or `#@ preaggregate`) over a gated source is built only where its gate holds on the rollup's rows**: database, every gate the base's own (declared on the base's own statement, not inherited from a source it extends, not through a join), and every field it reads a grain dimension. The gate is then re-applied on every read, as on a stored source (with `PUBLISHER_MATERIALIZE_GATED_SOURCES` on, an inherited gate too). Any other gated rollup is refused, naming it. The build skips a refused source, records it on the run (`metadata.refusedSources`), and builds the rest of the package. A run fails on a refusal only when every authored source it targeted was refused, or when `sourceNames` named this one; a refused rollup never fails it. (`#@ preaggregate` stores a rollup Publisher derives from a measure you annotated with a grain, rather than a source you wrote.) A rollup also groups *across* the gated column, so it could not be row-filtered afterwards even in principle.\n- **A `#@ persist`, database or `storage=`, is admitted** when the gate is the entry point's **own row filter** (or an `#(authorize)` lock): declared on the persisted source itself, and classified as a row filter. Both tiers follow the same rule (so does `#(materialize)`): the table holds every caller's rows and the gate is re-applied on every read through Publisher. (`#@ persist storage=<name>` materializes into a separate registered storage destination and serves from there, rather than building in the source's own connection.) **A `storage=` table puts those rows, ungated, at rest in the destination**, where anyone with direct access to the destination reads every row; tell the author before choosing that tier for a gated source, and make sure no connection a model can name reaches the destination (its catalog, schema or data path): stored tables are named predictably, so any package could read the gated rows through it. It is refused in three cases: the gate is reached only through a join, it does not classify as a row filter at all, or the persisted source inherits it from a source it derives from or extends (`source: mine is gated -> { ... }`, `gated extend { ... }`, across imports or two hops away). A table of an inherited gate would hold every caller's rows, and the served copy, which reads the table in place of the source that declares the gate, cannot apply the gate to it, so every query would answer live anyway: it is not built. Declare the gate on the persisted source itself to serve it from a table.\n\n**What to be wary of.** Persisting does not weaken the gate: it changes only where rows are read FROM, and the gate still runs live on every query as that query's own `WHERE`, so filtered rows come back filtered. What freezes is the **column the gate filters on**. A row whose access decision changes - it changes owner, say - keeps being served under its OLD decision until the next rebuild. That is a stale *access decision*, not merely stale data, and nothing raises an error.\n\n**None of this is needed for the gate to work.** It is enforced live on every query either way; what needs a bound is how long a *stale* decision can survive. Of the three controls that look like that bound, only the first is:\n\n- **`freshness.window=\"24h\"` with `freshness.fallback=\"live\"` is the bound** (`reference/refresh.md`). The serve path re-checks freshness per query, so once the artifact ages past the window it drops out of the serving set and the query recomputes live, correctly filtered - whether or not a rebuild ever lands. Three details decide whether you actually get that. **`fallback` must not be `stale_ok`**: under `stale_ok` a stale artifact keeps being served, which voids the bound (`live` and `fail` both bound it today). Window and fallback resolve *independently, per field*, across the source, model-file and package layers, so a package-level `stale_ok` silently defeats a window you set on the source. Prefer the **per-source** spelling `#@ persist name=\"...\" freshness.window=\"24h\" freshness.fallback=\"live\"` over the package-wide `materialization.freshness` key: the gated source is what needs the bound, and setting it package-wide forces every other persisted source to recompute once stale too. And **a content-identical sibling shares the artifact, so it shares the window**: reuse is keyed on the content-addressed `sourceEntityId`, which folds the connection and the SQL but *not* the source name, so two persist sources whose bodies compute the same SQL, with the same `name=` or none, resolve to one table carrying one freshness policy (different `name=`s are different tables). A host that folds the siblings' policies keeps the tightest window any of them declares - a sibling declaring nothing cannot loosen yours, and yours pulls that sibling's reads off the table once it lapses - and keeps the bounding fallback, so a sibling's `stale_ok` cannot void your bound either. If two sources need genuinely different windows, give them different `name=`s or genuinely different SQL.\n\n Both of those are properties of the **host** that assembles the manifest, not of the annotation: the publisher reports freshness per source and does no folding itself. Where the host does not fold, which sibling's policy reaches the wire is unspecified; a host that folds does so when it next publishes a version's manifest, not retroactively to manifests already distributed - so you can declare the window correctly and not have it in force yet.\n- **A cron alone is not a bound.** A failed build or a stopped scheduler leaves the source serving its old decisions indefinitely. `freshness` and `schedule` are mutually exclusive; for a gated source, take the window.\n- **`refresh=\"incremental\"` does not bound revocation.** The delta only re-reads rows from the newest stored watermark (less any `lookback=`) to the frontier, so a row that changes owner *without its watermark advancing* is never re-read - while the entry still reports an advancing `coveredThrough` and reads as healthy. Only a full rebuild recomputes the gating column.\n\n**The window binds on a standalone server and under a control plane alike.** A standalone run stamps the declared window and the table's `dataAsOf` on the manifest it commits, as a control plane stamps the manifest it distributes, so the table ages out per query either way. Under a control plane, the control plane's manifest decides: what it stamps applies whatever the model declares.\n\nWhen recommending `#@ persist` on a gated source, pair it with a freshness window and say out loud what staleness the author is accepting. A gated source with neither a window nor a full-rebuild cadence has no bound on how long a revoked row keeps being served."
190181
191316
  },
190182
191317
  {
190183
191318
  name: "malloy-materialization/annotation",
190184
191319
  description: "The `#@ persist` annotation. Reference detail for the malloy-materialization skill.",
190185
- body: '# The `#@ persist` annotation\n\n```malloy\n#@ persist name="my_dataset.my_table"\nsource: my_rollup is some_source -> { group_by: ...; aggregate: ... }\n```\n\n## What can carry it\n\n**Only `query_source` and `sql_select` sources are persistable** - a source whose definition has a `-> { ... }` pipeline or a `conn.sql("...")`, including one refined by a trailing `extend { ... }`. What is **not** persistable is a *plain* `extend` over a bare `conn.table(...)` (a filtered pass-through). A `#@ persist` on such a source (or on a table base with only added fields, such as `duckdb.table(\'x\') extend { measure: … }`, or on an unbound parameterized source) is **not ignored**: the publish and the load fail, naming the source (code `persist-not-materializable`). Persist a query source instead (`source: x is raw -> { where: ...; select: * }`), or remove the annotation.\n\n**A named `query:` persists its result only with `PUBLISHER_MATERIALIZE` on.** Then `#@ persist` on a top-level `query:` builds its result (as `<query>__query`), and the table answers `run: q`, a `queryName` call, a report naming `q`, and `run: q -> { … }`; a refinement (`q + { … }`) and any use of `q` inside another definition are answered live. A query that reaches a row-level gate (its source\'s own, an inherited one, or a joined source\'s), or reads a given or `now`, is not built; persist a view on a gated source instead. Whenever it is not built, the package carries a `warn` with code `persist-query-not-built` saying why, and the workaround that works everywhere: persist a source over it (`#@ persist` on `source: q_result is q`) and query that source.\n\n**A parameterized source must have its argument bound.** `#@ persist` on `high_value(min_amount is 500) -> { ... }` builds one fixed relation; on the free template `high_value -> { ... }` it is refused (`free_parameter`), since there is no single relation to store. A `given` the persisted *query* reads is refused the same way (`reads_given`); a given in the source\'s own `extend` block is applied per caller at read. `reference/storage.md` says where a given may sit. A persisted query that reads `now` (in its stages, a view it runs, the `where:`, a field or a join of the source it reads, `select: *` included, or the query of a query-shaped source it is built from or joins) is refused too (`current_time`, a `persist-not-built` warning, answered live), since its table would hold the rows as of the build; `now` in the source\'s own `extend` block is applied at every read and builds.\n\n**A mistake on the line fails the load.** A `#@` line that does not parse (`persist-unparseable`), a key Publisher does not read (`merge_keys=` for `merge_key=`, `persist-unknown-key`), a retired key (`partition=`, `sharing=`, `schedule=`, `realization=`; `persist-retired-key`, and on `#(materialize)` `materialize-retired-key`), and a value that is wrong as written (an empty or non-text `storage=`, an `@env.` reference; `persist-invalid`) each fail the publish and the load, on every path: publish, reload, restart, watch mode. A `#@` line Malloy never routes to persistence (`#@persist` with no space, `# persist`, `#(persist)`, or a misspelled directive such as `#@ persits`) fails the same way, code `materialization-near-miss`, naming the spelling it meant. The error has one line per mistake, each ending with its code in brackets, and shows in the publish response and `/status` `loadErrors`; a failed reload keeps serving the previous model (`stale: true`). Fix what it names and reload. A _valid_ annotation Publisher cannot build (an unconfigured destination, a gate, a dialect that cannot refresh incrementally) is different: that declaration alone is refused with a `warn` under its mechanism\'s not-built code (`persist-not-built`, formerly `persist-source-refused`; `materialize-not-built`; `persist-view-not-built`; `persist-query-not-built`; `rollup-not-built`), answered live, and the package loads. The build plan\'s `refusedSources` holds one record for it, with the reason.\n\n## The name\n\n- **Quote it, once.** `name="my_table"`, or a path `name="dataset.table"` / `name="project.dataset.table"`. A **bare** `name=my_table` fails the package **load** - so every publish and every restart - with `persist annotation name must be quoted`; it never silently no-ops.\n- **Plain identifier segments only**: dot-separated segments of letters, digits, underscores and hyphens. A quoted name holding a space, quote, semicolon or backtick is rejected with its own message (`persist annotation name must be a plain identifier path`), because the name is inlined into DDL. Publisher quotes each segment for the target warehouse, so case is preserved (`name="OrdersDaily"`) and reserved words work (`name="order"`); never add quotes inside the value.\n- **Never quote inside the quotes.** `name="\\"Quoted Tbl\\""` fails the load (`persist-invalid`): a name must be a plain identifier path (letters, digits, `_`, `-`, dot-separated), and Publisher quotes each segment for the warehouse itself.\n- **One name per table.** Two distinct persist sources that resolve to the same `name=` in the same destination clobber each other (the second build overwrites the first, and dropping one drops the other\'s). The publish and the load fail (`materialization-table-collision`). A deployment that opts out with `PERSIST_COLLISION_ENFORCE=false` loads the package instead, refuses both sources alone (`persist-not-built`), and answers them live rather than from the shared table. A shared *body* is fine (it shares one table by content address); a shared name over different bodies is not.\n- **The target\'s container must exist.** `name="analytics.daily"` puts the table in `analytics`, which the connection must be able to write and which Publisher does not create. The source can *read* anything the connection can read.\n- **The name is not the identity.** In a standalone Publisher `name=` is the physical table, rebuilt in place; a hosted deployment may assign the physical name itself. A `storage=` destination takes a single undotted name, since placement there is the destination\'s.\n\n## Identity and reuse\n\nA persist source\'s identity is its **`sourceEntityId`**: a content address of its connection and its canonical SQL. Not the name, not the file, not the package version. So:\n\n- **A rebuild with unchanged persist logic reuses the existing table** (skip-if-unchanged); changing the SQL builds fresh under a new address. `--force-refresh` and every scheduler fire defeat the skip; an incremental source is exempt from it and advances by its boundary instead (`reference/refresh.md`).\n- **Two sources whose bodies compile to the same SQL share one table** when they name the same one (the same `name=`, or none), and share one freshness policy and one incremental boundary with it. Different `name=`s are different tables, each built under its own name.\n- **A republish by itself builds nothing on a standalone server**; reuse is a property of the next *run*.\n\n## Readers of a persisted source\n\n- **An `extend` of a persisted source reads the stored table** and is not a build target of its own: it inherits the parent\'s tag and the same address, so the two names are one table. To make a distinct non-persisted intermediate, pipe first: `base -> { select: * } extend { ... }`.\n- **A query over a persisted source** (`orders is _orders_fact -> { select: * }`, the private-fact / public-wrapper idiom) reads the table too, with the fact\'s `extend`-block filters applied per caller, and is not a build target.\n- **`#@ -persist`** on an extension opts it out: it recomputes from raw on every query and never reads the table. Reach for it when a reader must not see stale rows, and remember it forgoes exactly the work persistence was there to save. It is Malloy core\'s own opt-out, not a Publisher extension, and it stays supported: it is not deprecated, and the in-development `#(materialize)` path honours it the same way.\n- Which queries over a reader route to the table is decided per query - a join to a non-persisted source or a nested column serves live for the queries that touch it (`reference/storage.md`).\n\n## Every option\n\n| On the tag | What it does | Where it is explained |\n|---|---|---|\n| `name="..."` | the target table (required) | above |\n| `storage=<destination>` | build into a storage destination and serve from it | `reference/storage.md` |\n| `refresh="incremental" watermark="col" [merge_key="a,b"]` | refresh by bounded delta instead of a full rebuild | `reference/refresh.md` |\n| `freshness.window="24h" freshness.fallback="live"` | per-source freshness objective (hosted deployments) | `reference/refresh.md` |\n| `#@ queryMetadata.<key>="v"` (sibling line) | per-source cost-attribution properties | `reference/policy.md` |\n| `#@ -persist` (on a reader) | opt a reader out of the table | above |\n| `#@ preaggregate grain="..."` (on a measure) | store a derived rollup | `reference/storage.md` |\n\n`storage=` and `name=` may be written beside the route\'s key or inside it: `#@ persist storage="lake"` and `#@ persist { storage="lake" }` place the table the same way, on every route (`#@ persist`, a persisted view, `#@ preaggregate`, `#(materialize)`, `#(rollup)`). When both are written, the one inside the key wins, even when it names nothing. A `storage=` that is empty or only whitespace, or that is a list or a block rather than text, fails the publish and the load (`persist-invalid`, or the route\'s own `*-invalid` code): name the destination, or drop the key to build in the source\'s own warehouse.\n\nOn a server with `PUBLISHER_MATERIALIZE` on, the v2 spelling `#(materialize)` takes the same keys, plus `inline=[...]`, as a closed set (an unknown key fails the publish and the load), and `#(rollup) grain=["a", "b"]` replaces `#@ preaggregate`.\n\nA rollup (`#(rollup)` or `#@ preaggregate`) takes `name=` too, as a prefix: `name="analytics.orders_rollup"` creates `analytics.orders_rollup__p<hash>`, the container placing it and the leaf starting its name, as `name=` does under `scope: "version"`; the hash, and so the identity, stays Publisher\'s. Without `name=` the table takes the readable name `<pkg>__<file>__<base>_by_<grain>__p<hash>`, in its base\'s database `name=` container if it has one (`#@ persist` or `#(materialize)`). The leaf is lowercased in the name; one the name would otherwise rewrite (a space, punctuation, a leading digit, `__`), an empty one, or one ending in `__p<8 hex>`, fails the load (`rollup-invalid`). Changing the leaf renames the table (rebuilt once; the old one is dropped). `namespace="analytics"` is the deprecated spelling of the container alone, with a `deprecated-rollup-namespace` warning. The main skill\'s "v1 or v2" section says when to write which.\n\nAn unrecognized key on the tag fails the publish and the load (`persist-unknown-key`). The retired per-source `sharing=` and `schedule=` fail them too (`persist-retired-key`): scope and schedule are declared once for the package (`reference/policy.md`). So does `realization=`, even `"COPY"`: every table is built by CREATE TABLE AS SELECT.'
191320
+ body: '# The `#@ persist` annotation\n\n```malloy\n#@ persist name="my_dataset.my_table"\nsource: my_rollup is some_source -> { group_by: ...; aggregate: ... }\n```\n\n## What can carry it\n\n**Only `query_source` and `sql_select` sources are persistable** - a source whose definition has a `-> { ... }` pipeline or a `conn.sql("...")`, including one refined by a trailing `extend { ... }`. What is **not** persistable is a *plain* `extend` over a bare `conn.table(...)` (a filtered pass-through). A `#@ persist` on such a source (or on a table base with only added fields, such as `duckdb.table(\'x\') extend { measure: … }`, or on an unbound parameterized source) is **not ignored**: the publish and the load fail, naming the source (code `persist-not-materializable`). Persist a query source instead (`source: x is raw -> { where: ...; select: * }`), or remove the annotation.\n\n**A named `query:` persists its result only with `PUBLISHER_MATERIALIZE` on.** Then `#@ persist` on a top-level `query:` builds its result (as `<query>__query`), and the table answers `run: q`, a `queryName` call, a report naming `q`, and `run: q -> { … }`; a refinement (`q + { … }`) and any use of `q` inside another definition are answered live. A query that reaches a row-level gate (its source\'s own, an inherited one, or a joined source\'s), or reads a given or `now`, is not built; persist a view on a gated source instead. Whenever it is not built, the package carries a `warn` with code `persist-query-not-built` saying why, and the workaround that works everywhere: persist a source over it (`#@ persist` on `source: q_result is q`) and query that source.\n\n**A parameterized source must have its argument bound.** `#@ persist` on `high_value(min_amount is 500) -> { ... }` builds one fixed relation; on the free template `high_value -> { ... }` it is refused (`free_parameter`), since there is no single relation to store. A `given` the persisted *query* reads is refused the same way (`reads_given`); a given in the source\'s own `extend` block is applied per caller at read. `reference/storage.md` says where a given may sit. A persisted query that reads `now` (in its stages, a view it runs, the `where:`, a field or a join of the source it reads, `select: *` included, or the query of a query-shaped source it is built from or joins) is refused too (`current_time`, a `persist-not-built` warning, answered live), since its table would hold the rows as of the build; `now` in the source\'s own `extend` block is applied at every read and builds.\n\n**A mistake on the line fails the load.** A `#@` line that does not parse (`persist-unparseable`), a key Publisher does not read (`merge_keys=` for `merge_key=`, `persist-unknown-key`), a retired key (`partition=`, `sharing=`, `schedule=`, `realization=`; `persist-retired-key`, and on `#(materialize)` `materialize-retired-key`), and a value that is wrong as written (an empty or non-text `storage=`, an `@env.` reference; `persist-invalid`) each fail the publish and the load, on every path: publish, reload, restart, watch mode. A `#@` line Malloy never routes to persistence (`#@persist` with no space, `# persist`, `#(persist)`, or a misspelled directive such as `#@ persits`) fails the same way, code `materialization-near-miss`, naming the spelling it meant. The error has one line per mistake, each ending with its code in brackets, and shows in the publish response and `/status` `loadErrors`; a failed reload keeps serving the previous model (`stale: true`). Fix what it names and reload. A _valid_ annotation Publisher cannot build (an unconfigured destination, a gate, a dialect that cannot refresh incrementally) is different: that declaration alone is refused with a `warn` under its mechanism\'s not-built code (`persist-not-built`, formerly `persist-source-refused`; `materialize-not-built`; `persist-view-not-built`; `persist-query-not-built`; `rollup-not-built`), answered live, and the package loads. The build plan\'s `refusedSources` holds one record for it, with the reason.\n\n## The name\n\n- **Quote it, once.** `name="my_table"`, or a path `name="dataset.table"` / `name="project.dataset.table"`. A **bare** `name=my_table` fails the package **load** - so every publish and every restart - with `persist annotation name must be quoted`; it never silently no-ops.\n- **Plain identifier segments only**: dot-separated segments of letters, digits, underscores and hyphens. A quoted name holding a space, quote, semicolon or backtick is rejected with its own message (`persist annotation name must be a plain identifier path`), because the name is inlined into DDL. Publisher quotes each segment for the target warehouse, so case is preserved (`name="OrdersDaily"`) and reserved words work (`name="order"`); never add quotes inside the value.\n- **Never quote inside the quotes.** `name="\\"Quoted Tbl\\""` fails the load (`persist-invalid`): a name must be a plain identifier path (letters, digits, `_`, `-`, dot-separated), and Publisher quotes each segment for the warehouse itself.\n- **One name per table.** Two distinct persist sources that resolve to the same `name=` in the same destination clobber each other (the second build overwrites the first, and dropping one drops the other\'s). The publish and the load fail (`materialization-table-collision`). A deployment that opts out with `PERSIST_COLLISION_ENFORCE=false` loads the package instead, refuses both sources alone (`persist-not-built`), and answers them live rather than from the shared table. A shared *body* is fine (it shares one table by content address); a shared name over different bodies is not.\n- **The target\'s container must exist.** `name="analytics.daily"` puts the table in `analytics`, which the connection must be able to write and which Publisher does not create. The source can *read* anything the connection can read.\n- **The name is not the identity.** In a standalone Publisher `name=` is the physical table, rebuilt in place; a hosted deployment may assign the physical name itself. A `storage=` destination takes a single undotted name, since placement there is the destination\'s.\n\n## Identity and reuse\n\nA persist source\'s identity is its **`sourceEntityId`**: a content address of its connection and its canonical SQL. Not the name, not the file, not the package version. So:\n\n- **A rebuild with unchanged persist logic reuses the existing table** (skip-if-unchanged); changing the SQL builds fresh under a new address. `--force-refresh` and every scheduler fire defeat the skip; an incremental source is exempt from it and advances by its boundary instead (`reference/refresh.md`).\n- **Two sources whose bodies compile to the same SQL share one table** when they name the same one (the same `name=`, or none), and share one freshness policy and one incremental boundary with it. Different `name=`s are different tables, each built under its own name.\n- **A republish by itself builds nothing on a standalone server**; reuse is a property of the next *run*.\n\n## Readers of a persisted source\n\n- **An `extend` of a persisted source reads the stored table** and is not a build target of its own: it inherits the parent\'s tag and the same address, so the two names are one table. To make a distinct non-persisted intermediate, pipe first: `base -> { select: * } extend { ... }`.\n- **A query over a persisted source** (`orders is _orders_fact -> { select: * }`, the private-fact / public-wrapper idiom) reads the table too, with the fact\'s `extend`-block filters applied per caller, and is not a build target.\n- **`#@ -persist`** on an extension opts it out: it recomputes from raw on every query and never reads the table. Reach for it when a reader must not see stale rows, and remember it forgoes exactly the work persistence was there to save. It is Malloy core\'s own opt-out, not a Publisher extension, and it stays supported: it is not deprecated, and the in-development `#(materialize)` path honours it the same way.\n- Which queries over a reader route to the table is decided per query - a join to a non-persisted source or a nested column serves live for the queries that touch it (`reference/storage.md`).\n\n## Every option\n\n| On the tag | What it does | Where it is explained |\n|---|---|---|\n| `name="..."` | the target table (required) | above |\n| `storage=<destination>` | build into a storage destination and serve from it | `reference/storage.md` |\n| `refresh="incremental" watermark="col" [merge_key="a,b"] [lookback="2 days"]` | refresh by bounded delta instead of a full rebuild; `lookback=` re-reads late rows (needs `merge_key=` and a date or timestamp watermark) | `reference/refresh.md` |\n| `freshness.window="24h" freshness.fallback="live"` | per-source freshness objective (hosted deployments) | `reference/refresh.md` |\n| `#@ queryMetadata.<key>="v"` (sibling line) | per-source cost-attribution properties | `reference/policy.md` |\n| `#@ -persist` (on a reader) | opt a reader out of the table | above |\n| `#@ preaggregate grain="..."` (on a measure) | store a derived rollup | `reference/storage.md` |\n\n`storage=` and `name=` may be written beside the route\'s key or inside it: `#@ persist storage="lake"` and `#@ persist { storage="lake" }` place the table the same way, on every route (`#@ persist`, a persisted view, `#@ preaggregate`, `#(materialize)`, `#(rollup)`). When both are written, the one inside the key wins, even when it names nothing. A `storage=` that is empty or only whitespace, or that is a list or a block rather than text, fails the publish and the load (`persist-invalid`, or the route\'s own `*-invalid` code): name the destination, or drop the key to build in the source\'s own warehouse.\n\nOn a server with `PUBLISHER_MATERIALIZE` on, the v2 spelling `#(materialize)` takes the same keys, plus `inline=[...]`, as a closed set (an unknown key fails the publish and the load), and `#(rollup) grain=["a", "b"]` replaces `#@ preaggregate`.\n\nA rollup (`#(rollup)` or `#@ preaggregate`) takes `name=` too, as a prefix: `name="analytics.orders_rollup"` creates `analytics.orders_rollup__p<hash>`, the container placing it and the leaf starting its name, as `name=` does under `scope: "version"`; the hash, and so the identity, stays Publisher\'s. Without `name=` the table takes the readable name `<pkg>__<file>__<base>_by_<grain>__p<hash>`, in its base\'s database `name=` container if it has one (`#@ persist` or `#(materialize)`). The leaf is lowercased in the name; one the name would otherwise rewrite (a space, punctuation, a leading digit, `__`), an empty one, or one ending in `__p<8 hex>`, fails the load (`rollup-invalid`). Changing the leaf renames the table (rebuilt once; the old one is dropped). `namespace="analytics"` is the deprecated spelling of the container alone, with a `deprecated-rollup-namespace` warning. The main skill\'s "v1 or v2" section says when to write which.\n\nAn unrecognized key on the tag fails the publish and the load (`persist-unknown-key`). The retired per-source `sharing=` and `schedule=` fail them too (`persist-retired-key`): scope and schedule are declared once for the package (`reference/policy.md`). So does `realization=`, even `"COPY"`: every table is built by CREATE TABLE AS SELECT.'
190186
191321
  },
190187
191322
  {
190188
191323
  name: "malloy-materialization/chaining",
@@ -190239,7 +191374,7 @@ The \`publisher_storage_chained_build_total{outcome}\` counter reports the path
190239
191374
  {
190240
191375
  name: "malloy-materialization/refresh",
190241
191376
  description: "Keeping a table current: freshness, schedule, incremental refresh. Reference detail for the malloy-materialization skill.",
190242
- body: '# Keeping a table current: freshness, schedule, incremental refresh\n\nA persisted table is a snapshot. Three declarations govern when it is rebuilt and what a reader gets in the meantime; which of them does anything depends on who drives the builds.\n\n## `freshness`: the objective tier\n\n```malloy\n#@ persist name="daily_orders" freshness.window="24h" freshness.fallback="live"\n```\n\nor package-wide in `publisher.json` under `materialization.freshness`, or per model file with `## materialization.freshness.window="24h"`. The three layers resolve **per field** - source, then model file, then package - so a source that declares only `window` takes its `fallback` from the package. That is how a package-level `stale_ok` silently defeats a window set on one source.\n\n- `window` is how old a table may be before it is stale. `fallback` says what a query over a stale table does: `live` and `fail` both skip the table and compute live (`fail` is reserved to error later; today it behaves as `live`); `stale_ok` keeps serving the stale table.\n- A **hosted control plane** enforces the objective: it refreshes the table to stay within the window and stamps each manifest entry with `dataAsOf` and the window, and the serve path re-checks freshness **per query**, so a table that ages past its window drops out of the serving set whether or not a rebuild ever lands.\n- A **standalone** run stamps the same fields itself: each table it builds carries the declared window and fallback and a `dataAsOf` of the run\'s start (or of an older stored table it was built from), so the serve path ages it exactly as it ages a hosted table. Its next run rebuilds a table past its window instead of carrying it forward; nothing rebuilds it the moment the window passes, so trigger runs yourself (the package `schedule` excludes `freshness`). A window is a whole number and a unit (`90s`, `30m`, `24h`, `7d`, `2w`) and a fallback is `live`, `stale_ok` or `fail`; anything else fails the load on every mechanism. A table is never fresher than what it read: a rebuilt windowed table rebuilds a carried upstream of unknown age, and takes an older upstream\'s `dataAsOf`.\n- A **rollup** takes the same keys on `#(rollup)` or `#@ preaggregate`, and otherwise its base\'s own declaration, then the model file\'s and the package\'s, so it goes stale with its base. Measures of one rollup share one freshness; two that disagree, an unknown key in the group, or a window that does not read as above fail the load.\n- Two sources whose bodies compile to the same SQL, with the same `name=` or none, share one table, and a host that folds their policies keeps the tightest window and the bounding fallback for both. If two sources need different windows, give them different SQL or different `name=`s.\n\n## `schedule`: the power tier\n\n```jsonc\n{ "name": "orders", "materialization": { "scope": "version", "schedule": "0 6 * * *" } }\n```\n\n- A 5-field UTC cron; `L`, `W`, `#`, `?` are rejected at publish. It **requires `scope: "version"`** and is **mutually exclusive with `freshness`** - including a per-source `freshness.*`.\n- It fires only on a standalone Publisher whose scheduler is enabled with `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER`; without that, a schedule is inert. The scheduler sweeps loaded packages, skips one whose policy is invalid or that a control plane manages (`manifestLocation` set), fires at most a bounded number per tick, fires once to catch up after downtime, and skips a fire while a run is already active.\n- **Every scheduled fire is a forced run** (`forceRefresh: true`): every source is rebuilt whether or not its content address changed. A scheduled run therefore never reports reused sources, and a cron that is too frequent shows as build time, not as reuse.\n- `malloy-pub schedule set "<cron>"` writes the schedule and sets `scope: version` in one PATCH; it **replaces the whole `materialization` block**, dropping an existing `freshness` policy (it says so). `schedule clear` removes the cron and leaves `scope: version` in place; moving back to `package` scope is an edit to `publisher.json`. A published version (by default, any package outside a watched environment) refuses both with 409 `PACKAGE_IS_VERSIONED`: set the schedule in its `publisher.json` and publish a new version.\n\n## `refresh="incremental"`: bounded deltas\n\n```malloy\n#@ persist name="daily_orders" refresh="incremental" watermark="order_date"\nsource: daily_orders is orders -> { group_by: order_date; aggregate: revenue is amount.sum() }\n```\n\n- `watermark=` names one of the source\'s own output columns - real, orderable, non-aggregate. Publisher records how far the table is materialized (`covered_through`) and each refresh recomputes only `[covered_through, frontier)`, half-open, so the frontier value itself is left for the next run. A `date`/`timestamp` watermark takes the run\'s start time as the frontier; a numeric or string one reads `max(watermark)` from the source. Two refreshes within the same day of a date-watermarked source produce an empty range and skip - correct, and it looks like nothing happened.\n- Add `merge_key="col,..."` when a row can be **restated** with a new watermark value; the delta is then applied as a `MERGE` on that identity instead of a delete-and-reinsert of the range. On a caller-scoped source (a given or gate in the `extend` block) the table holds every caller\'s rows, so the match also carries the scope columns - declare the key as you would for an unscoped source. A scope term that reaches through a join is refused (`merge_key_scope_unresolved`) rather than scoped partially.\n- **Coverage belongs to the table.** Moving a source between tiers (adding or removing `storage=`), renaming its physical table, or changing its SQL re-seeds it in full; the boundary is measured against the table it was recorded on.\n- **An invalid declaration fails the package load**, not just the publish: `watermark=` without `refresh="incremental"`, `merge_key=` without a watermark, a watermark that names no materialized column or an aggregate, a `calculate:` field, or an unsupported dialect. Postgres, BigQuery and Snowflake sources only (the dialect that has to express the range); a DuckDB source has to say `refresh="full"`.\n- **`forceRefresh` never re-seeds**; it only defeats skip-if-unchanged, and an incremental source is exempt from that anyway. Ask for a full rebuild with `reseed` (`malloy-pub materialize --reseed`, or per source on the build instruction). Keeping them apart is what lets a schedule drive deltas at all, since every scheduled fire is forced.\n- Each manifest entry reports what the run **did**: `refresh: delta | full | none`, with `ledger.coveredThrough` as the boundary now in force. Every fallback - no recorded boundary, a boundary measured on a different table or watermark, drifted columns, `MERGE` on a Postgres older than 15 - rebuilds in full and succeeds, so a source quietly rebuilding on every run looks exactly like one advancing unless you read `refresh`. The reason codes (`forced`, `no_boundary`, `lineage_changed`, `table_renamed`, `merge_unsupported`, `table_unreadable`, `table_emptied`, `shape_mismatch`, `ledger_unreadable`, `chained_storage`, `frontier_unreadable`, `not_advanced`) say why.\n- Two sources that compile to identical SQL, with the same `name=` or none, share one table **and one boundary**; if their incremental declarations differ, neither ever advances. Publisher warns and names both.\n- `storage=` is supported: the warehouse computes the bounded range and the DML lands in the destination. A **chained** stored source always rebuilds in full (`chained_storage`): see `reference/chaining.md`.\n- The boundary lives in the publisher\'s own per-process store. A host that spreads a package\'s refreshes over several workers holds the ledger itself: it stores each entry\'s `ledger` object and sends them back as `buildInstructions.ledger` on the next run. Standalone, the store is the publisher\'s, always.\n\n## Which refresh a gated source needs\n\nA `#(access_filter)`-gated source that is persisted freezes the column its gate filters on, so its "refresh" is also the bound on how long a revoked row keeps being served. Only a freshness window with `fallback: live` on a hosted deployment bounds that; a cron alone does not, and an incremental delta never re-reads a row whose watermark did not move. See `reference/access-filter.md`.'
191377
+ body: '# Keeping a table current: freshness, schedule, incremental refresh\n\nA persisted table is a snapshot. Three declarations govern when it is rebuilt and what a reader gets in the meantime; which of them does anything depends on who drives the builds.\n\n## `freshness`: the objective tier\n\n```malloy\n#@ persist name="daily_orders" freshness.window="24h" freshness.fallback="live"\n```\n\nor package-wide in `publisher.json` under `materialization.freshness`, or per model file with `## materialization.freshness.window="24h"`. The three layers resolve **per field** - source, then model file, then package - so a source that declares only `window` takes its `fallback` from the package. That is how a package-level `stale_ok` silently defeats a window set on one source.\n\n- `window` is how old a table may be before it is stale. `fallback` says what a query over a stale table does: `live` and `fail` both skip the table and compute live (`fail` is reserved to error later; today it behaves as `live`); `stale_ok` keeps serving the stale table.\n- A **hosted control plane** enforces the objective: it refreshes the table to stay within the window and stamps each manifest entry with `dataAsOf` and the window, and the serve path re-checks freshness **per query**, so a table that ages past its window drops out of the serving set whether or not a rebuild ever lands.\n- A **standalone** run stamps the same fields itself: each table it builds carries the declared window and fallback and a `dataAsOf` of the run\'s start (or of an older stored table it was built from), so the serve path ages it exactly as it ages a hosted table. Its next run rebuilds a table past its window instead of carrying it forward; nothing rebuilds it the moment the window passes, so trigger runs yourself (the package `schedule` excludes `freshness`). A window is a whole number and a unit (`90s`, `30m`, `24h`, `7d`, `2w`) and a fallback is `live`, `stale_ok` or `fail`; anything else fails the load on every mechanism. A table is never fresher than what it read: a rebuilt windowed table rebuilds a carried upstream of unknown age, and takes an older upstream\'s `dataAsOf`.\n- A **rollup** takes the same keys on `#(rollup)` or `#@ preaggregate`, and otherwise its base\'s own declaration, then the model file\'s and the package\'s, so it goes stale with its base. Measures of one rollup share one freshness; two that disagree, an unknown key in the group, or a window that does not read as above fail the load.\n- Two sources whose bodies compile to the same SQL, with the same `name=` or none, share one table, and a host that folds their policies keeps the tightest window and the bounding fallback for both. If two sources need different windows, give them different SQL or different `name=`s.\n\n## `schedule`: the power tier\n\n```jsonc\n{ "name": "orders", "materialization": { "scope": "version", "schedule": "0 6 * * *" } }\n```\n\n- A 5-field UTC cron; `L`, `W`, `#`, `?` are rejected at publish. It **requires `scope: "version"`** and is **mutually exclusive with `freshness`** - including a per-source `freshness.*`.\n- It fires only on a standalone Publisher whose scheduler is enabled with `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER`; without that, a schedule is inert. The scheduler sweeps loaded packages, skips one whose policy is invalid or that a control plane manages (`manifestLocation` set), fires at most a bounded number per tick, fires once to catch up after downtime, and skips a fire while a run is already active.\n- **Every scheduled fire is a forced run** (`forceRefresh: true`): every source is rebuilt whether or not its content address changed. A scheduled run therefore never reports reused sources, and a cron that is too frequent shows as build time, not as reuse.\n- `malloy-pub schedule set "<cron>"` writes the schedule and sets `scope: version` in one PATCH; it **replaces the whole `materialization` block**, dropping an existing `freshness` policy (it says so). `schedule clear` removes the cron and leaves `scope: version` in place; moving back to `package` scope is an edit to `publisher.json`. A published version (by default, any package outside a watched environment) refuses both with 409 `PACKAGE_IS_VERSIONED`: set the schedule in its `publisher.json` and publish a new version.\n\n## `refresh="incremental"`: bounded deltas\n\n```malloy\n#@ persist name="daily_orders" refresh="incremental" watermark="order_date"\nsource: daily_orders is orders -> { group_by: order_date; aggregate: revenue is amount.sum() }\n```\n\n- `watermark=` names one of the source\'s own output columns - real, orderable, non-aggregate. Publisher records how far each refresh reached (`covered_through`) and the next recomputes only `[start, frontier)`, half-open, so the frontier value itself is left for the next run. A `date`/`timestamp` watermark takes the run\'s start time as the frontier and **starts at the newest watermark the stored table holds** (one `max()` over the table), so a row stamped after the newest stored row is read however late it loads; it never starts at the previous run\'s start time, which would skip such a row for good. The start is inclusive: a merge or a range replace re-reads the newest stored instant without writing it twice. A numeric or string watermark reads `max(watermark)` from the source as its frontier, and the next range starts there; two refreshes of one with no new rows skip - correct, and it looks like nothing happened.\n- **Without `merge_key=`, a refresh replaces the whole range it re-reads**, from the newest stored row (on a `date` watermark, the whole newest stored day): a stored row the source no longer holds there is removed. A source that drops or trims recent rows (a staging table keeping only the latest day) notices; declare `merge_key=` for append-only behaviour, since a merge never deletes.\n- **Late rows: `lookback="2 days"`.** There is no lookback unless declared. A row stamped *below* the newest stored row, loaded after it, is below every later delta. `lookback=` starts each delta that much further back (`[newest stored − lookback, frontier)`), and the merge key matches the rows read again. A positive whole number and one unit, `seconds`/`minutes`/`hours`/`days`/`weeks` spelled out or as `s`/`m`/`h`/`d`/`w` (`"36h"`), at most 365 days; no month or year. It needs a `date` or `timestamp` watermark **and** `merge_key=`; anything else fails the load (`persist-invalid` on `#@ persist`, `materialize-invalid` on `#(materialize)`). Size it to how late rows really arrive: each day of lookback is re-read every refresh.\n- **Missed rows are reported.** After each delta, one check counts the source\'s rows in the window just below where the delta started (as wide as the delta\'s own range, capped at 7 days or the lookback, whichever is longer) that the table lacks. Any found are on the manifest entry as `lateRows` (`count`, `from`, `to`) and on the package as a `persist-incremental-late-rows` warning: the served table undercounts. Both are carried, with later findings added, until the source is rebuilt in full. Recover with one `reseed`, then add or widen `lookback=`. The count is a lower bound (a slice is checked once, so a row landing in an already-checked slice is not counted), and the report stays until a full rebuild even after a widened lookback has written the rows. A row older than the window is not seen; pair tables, string watermarks and `storage=` sources on BigQuery are not checked; the check gives up after 60 seconds and never fails the run.\n- **A zoned timestamp watermark (`timestamptz`) in a session time zone other than UTC** (set by the connection\'s setupSQL) reads back with that zone\'s offset, so the source rebuilds in full each refresh, logged at `warn`. A plain `timestamp` or `date` watermark is not affected.\n- **An invalid declaration fails the package load**, not just the publish: `watermark=` without `refresh="incremental"`, `merge_key=` without a watermark, a watermark that names no materialized column or an aggregate, or a `lookback=` that is not a duration, is over 365 days, lacks `merge_key=`, or sits on a number or string watermark (`persist-invalid`; `materialize-invalid` on `#(materialize)`). (A `calculate:` field or an unsupported dialect is valid but refuses the source alone.) Postgres, BigQuery and Snowflake sources only (the dialect that has to express the range); a DuckDB source has to say `refresh="full"`.\n- **`forceRefresh` never re-seeds**; it only defeats skip-if-unchanged, and an incremental source is exempt from that anyway. Ask for a full rebuild with `reseed` (`malloy-pub materialize --reseed`, or per source on the build instruction). Keeping them apart is what lets a schedule drive deltas at all, since every scheduled fire is forced.\n- Each manifest entry reports what the run **did**: `refresh: delta | full | none`, with `ledger.coveredThrough` as the boundary now in force. Every fallback - no recorded boundary, a boundary measured on a different table or watermark, drifted columns, `MERGE` on a Postgres older than 15 - rebuilds in full and succeeds, so a source quietly rebuilding on every run looks exactly like one advancing unless you read `refresh`. The reason codes (`forced`, `no_boundary`, `lineage_changed`, `table_renamed`, `merge_unsupported`, `table_unreadable`, `table_emptied`, `shape_mismatch`, `ledger_unreadable`, `chained_storage`, `frontier_unreadable`, `not_advanced`) say why.\n- Two sources that compile to identical SQL, with the same `name=` or none, share one table **and one boundary**; if their incremental declarations differ, neither ever advances. Publisher warns and names both.\n- `storage=` is supported: the warehouse computes the bounded range and the DML lands in the destination. A **chained** stored source always rebuilds in full (`chained_storage`): see `reference/chaining.md`.\n- The boundary lives in the publisher\'s own per-process store. A host that spreads a package\'s refreshes over several workers holds the ledger itself: it stores each entry\'s `ledger` object and sends them back as `buildInstructions.ledger` on the next run. Standalone, the store is the publisher\'s, always.\n\n## Which refresh a gated source needs\n\nA `#(access_filter)`-gated source that is persisted freezes the column its gate filters on, so its "refresh" is also the bound on how long a revoked row keeps being served. Only a freshness window with `fallback: live` on a hosted deployment bounds that; a cron alone does not, and an incremental delta never re-reads a row whose watermark did not move. See `reference/access-filter.md`.'
190243
191378
  },
190244
191379
  {
190245
191380
  name: "malloy-materialization/storage",
@@ -190249,7 +191384,7 @@ The \`publisher_storage_chained_build_total{outcome}\` counter reports the path
190249
191384
  {
190250
191385
  name: "malloy-materialization/tuning",
190251
191386
  description: "Tuning materializations for cost and performance. Reference detail for the malloy-materialization skill.",
190252
- body: "# Tuning materializations for cost and performance\n\nThis skill turns the signals the open-source Publisher already records (the materialization history, per-run and per-source timings, which sources were built vs reused, and for the storage tier how queries were routed) into concrete, **recommendations-only** advice: which sources to persist, which to stop persisting, which to chain, and how to schedule them. The Publisher has the raw signals, and you read them with the `malloy-pub` CLI.\n\n> **Recommendations only. Never change a model, schedule, or scope without the user's explicit go-ahead.** Present the findings and the proposed edits, then apply them only when asked. Persisting the wrong source wastes storage and rebuild time; unpersisting a hot one makes queries slow. Let the user decide.\n\nAssumes the `malloy-pub` CLI is on PATH and points at the server (`--url` or `MALLOY_PUBLISHER_URL`). Substitute the real environment and package for `<env>` / `<pkg>`.\n\n## Step 1: Take inventory\n\nEstablish what the package persists today and how it is governed.\n\n- **Persist sources:** the sources annotated `#@ persist name=\"...\"` in the package's `.malloy` files, with their tier (`storage=` or not) and `refresh=`. Read the models (or `get_context` the package) to list them, and read `GET …/packages/{pkg}/build-plan` for what a run will build and what it will refuse.\n- **Schedule + scope:**\n\n ```bash\n malloy-pub schedule view --environment <env> --package <pkg>\n ```\n\n This prints the cron (or `none`, meaning on-demand only), the persist **scope** (`package` = artifacts reused across versions; `version` = per published version), and whether a freshness policy is set. It also says when a control plane manages the package (`manifestLocation` set): leave that package's cadence alone, the control plane refreshes it. And remember the standalone scheduler only runs with `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER` set; a cron on a server without it is inert.\n\n## Step 2: Read the materialization history\n\nThe history is where cost lives. Each run records its trigger, timing, and per source what it did.\n\n- **For one package** (newest first; `--limit` / `--offset` page it):\n\n ```bash\n malloy-pub list materialization --environment <env> --package <pkg>\n ```\n\n Columns: ID, Status, **Trigger** (`scheduler` vs `on_demand`; a run recorded before 0.15 says `SCHEDULER` vs `ON_DEMAND`), Started, Completed, Error.\n\n- **A single run's detail** (the cost signals):\n\n ```bash\n malloy-pub get materialization <id> --environment <env> --package <pkg>\n ```\n\n In the JSON, read:\n - `metadata.durationMs`: how long the whole run took.\n - `metadata.sourcesBuilt` / `sourcesReused` / `sourcesFailed`: how much work the run did. A run that reused most sources was cheap. **A scheduler run never reuses**: every scheduled fire is forced, so its `sourcesReused` is 0 by construction; judge a scheduled run by its duration and its per-source entries instead. An incremental source is counted as built even when its refresh applied nothing.\n - `metadata.sourcesRefused` and `metadata.refusedSources` (present only when a source was refused, and only on a run the publisher planned itself): sources the eligibility gate skipped. Each one serves live on every query, so a refused source the user expected to be persisted is a finding in its own right; its entry's `message` says what to change.\n - `manifest.entries` - a map keyed by `sourceEntityId`. Each entry carries `sourceName`, `physicalTableName`, `realization`, and the per-source cost signals: `buildDurationMs`; `queryCostBytes` where the warehouse reports it; `refresh: delta | full | none` for an incremental source (a `full` on an unchanged source every run is a source that never advances); `upstreamReuse: reused | recomputed` for a chained source (a `recomputed` with `upstreamRecomputeReason` is a chain that went back to the warehouse).\n - `manifest.failures`: sources the run lost while still finishing ready.\n\nLook across several runs, not one: the pattern over the recent history (how often it rebuilds, how long each source takes, what reuses) is the signal.\n\n- **For `storage=` tables, how queries were routed.** `publisher_query_route_total{leg, outcome, reason}` on the metrics endpoint counts each serving leg the router considered: `used` when it answered, `skipped` with the reason, and `fallback` when its stored run failed and live answered, and each query response's `servedFrom` says it per query. For a table built in the source's own warehouse there is no route counter, but each response's `servedFrom` reads `database` when one answered, so a log of responses measures it. Say so when it matters.\n\n## Step 3: Analyze and recommend\n\nWeigh rebuild cost against query benefit. Common findings:\n\n- **Persist candidate:** an expensive, frequently-queried source that is _not_ persisted (recomputed on every query). Recommend adding `#@ persist name=\"...\"`. Strongest when the source is a heavy aggregate/join reused by many queries and its inputs change slowly. If the source carries a `#(access_filter)` gate, check which case it is first. A gate reached only through a `join_*`, or not classifying as a row filter, means the database persist is **refused** - the build skips it and it serves live - so do not recommend persisting it at all. Where the gate is the source's own row filter the persist is admitted, and then only recommend it alongside a freshness window (`freshness.fallback=\"live\"`): the gating column freezes at build time, so without one a revoked row can be served under its old access decision indefinitely (see `access-filter.md`).\n- **Removal candidate:** a persisted source that is cheap to compute, rarely queried, or rebuilt far more often than it is read. Recommend dropping the `#@ persist` annotation (and its table): the storage + rebuild cost is not buying anything.\n- **Chain candidate:** a `storage=` rollup whose intermediates re-read the warehouse on every build while a stored root already holds the rows. Rewire the intermediates onto the stored root (declaration order, a distinct `-> { select: * }` intermediate, joins onto stored siblings - `chaining.md`), and read `upstreamReuse` on the next run to confirm the chain holds. Keep a self-join or a wide hash aggregate over a large fact **in the warehouse**: chained, it builds in the destination's engine under its memory bound.\n- **Denominator candidate:** a ratio whose numerator is a rollup and whose denominator counts the fact table per query. Persist the denominator at its own grain.\n- **Cadence mismatch:** a scheduler cadence out of step with how fast the data changes or how long a build takes. If the build's `durationMs` approaches the interval, the cadence is too aggressive. If queries routinely read stale data, tighten it. For an incremental source, `refresh: delta` with small `buildDurationMs` per fire is the cheap steady state; `refresh: full` every fire means the boundary is being lost (read the reason).\n- **Scope mismatch:** `scope: version` re-materializes per published version (right when versions must be isolated, e.g. a schedule); `scope: package` reuses one lineage across versions (cheaper when versions can share). A schedule _requires_ `version`. If a package carries a schedule it does not need, clearing it is step one; the scope itself is edited in `publisher.json` (the CLI does not move it back).\n\nFrame each recommendation with the evidence from Step 2 (the run IDs, timings, built/reused counts, per-entry fields) so the user can judge it.\n\n## Step 4: Apply (only once approved)\n\n- **Add a persist source:** add the `#@ persist` annotation in the `.malloy` file (use the modeling workflow to validate and reload), then rebuild so it is materialized:\n\n ```bash\n malloy-pub materialize --environment <env> --package <pkg> --wait --timeout 900\n ```\n\n (`--wait` gives up after 120 s by default and exits non-zero while the build continues; raise `--timeout` for a real build.)\n\n- **Remove a persist source:** delete the `#@ persist` annotation, rebuild, delete the old runs, then drop the old table yourself:\n\n ```bash\n malloy-pub materialize --environment <env> --package <pkg> --wait\n malloy-pub delete materialization <old-id> --environment <env> --package <pkg>\n ```\n\n > Deleting a run is **record-only**: it never drops a table. It re-derives the package's serve bindings from the latest remaining ready run (or clears them to serve live), so a delete does not break queries. To drop the old table, read its `physicalTableName` from the old run's manifest, check that no remaining ready run, of any version, names a table with that name in any place (the runs list answers for the latest version only, so list each version's runs with `versionId`; with the stable names an auto-run assigns, a table the new run carried forward is still served, and two destination names can reach one DuckLake), then drop it through its connection.\n\n- **Change the schedule / cadence:**\n\n ```bash\n malloy-pub schedule set \"0 6 * * *\" --environment <env> --package <pkg> # 5-field UTC cron\n malloy-pub schedule clear --environment <env> --package <pkg>\n ```\n\n `set` also sets `scope: version` (a schedule requires it) and **replaces the whole `materialization` block, dropping an existing `freshness` policy**; the server rejects an invalid cron or an illegal scope/freshness combination, so a rejection means the change was unsafe. `clear` leaves `scope: version` in place. Both edit the package through a PATCH, which a published version (by default, any package outside a watched environment) refuses with 409 `PACKAGE_IS_VERSIONED`: there, set or remove `materialization.schedule` in `publisher.json` and publish a new version.\n\n- **Change the scope:** `scope` is declared in the package's `publisher.json` under `materialization` (`\"scope\": \"package\"` or `\"version\"`; the root-level form is deprecated but still read). Edit it there, then reload/republish the package. Remember a schedule pins scope to `version`, so clear the schedule first if moving to `package`.\n\nAfter applying, re-run Step 2 on the next few builds to confirm the change did what you predicted (more reuse, shorter builds, a chain that reports `reused`, or a table that is actually read).\n\n## What this skill does not do\n\n- It does not decide for the user or apply changes silently; every edit needs an explicit go-ahead.\n- It cannot measure reads of a table built in the source's own warehouse (only the storage tier reports routing), so \"rarely queried\" there is a judgment from the model and the user's knowledge, not a measured metric. Say so when it matters."
191387
+ body: "# Tuning materializations for cost and performance\n\nThis skill turns the signals the open-source Publisher already records (the materialization history, per-run and per-source timings, which sources were built vs reused, and for the storage tier how queries were routed) into concrete, **recommendations-only** advice: which sources to persist, which to stop persisting, which to chain, and how to schedule them. The Publisher has the raw signals, and you read them with the `malloy-pub` CLI.\n\n> **Recommendations only. Never change a model, schedule, or scope without the user's explicit go-ahead.** Present the findings and the proposed edits, then apply them only when asked. Persisting the wrong source wastes storage and rebuild time; unpersisting a hot one makes queries slow. Let the user decide.\n\nAssumes the `malloy-pub` CLI is on PATH and points at the server (`--url` or `MALLOY_PUBLISHER_URL`). Substitute the real environment and package for `<env>` / `<pkg>`.\n\n## Step 1: Take inventory\n\nEstablish what the package persists today and how it is governed.\n\n- **Persist sources:** the sources annotated `#@ persist name=\"...\"` in the package's `.malloy` files, with their tier (`storage=` or not) and `refresh=`. Read the models (or `get_context` the package) to list them, and read `GET …/packages/{pkg}/build-plan` for what a run will build and what it will refuse.\n- **Schedule + scope:**\n\n ```bash\n malloy-pub schedule view --environment <env> --package <pkg>\n ```\n\n This prints the cron (or `none`, meaning on-demand only), the persist **scope** (`package` = artifacts reused across versions; `version` = per published version), and whether a freshness policy is set. It also says when a control plane manages the package (`manifestLocation` set): leave that package's cadence alone, the control plane refreshes it. And remember the standalone scheduler only runs with `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER` set; a cron on a server without it is inert.\n\n## Step 2: Read the materialization history\n\nThe history is where cost lives. Each run records its trigger, timing, and per source what it did.\n\n- **For one package** (newest first; `--limit` / `--offset` page it):\n\n ```bash\n malloy-pub list materialization --environment <env> --package <pkg>\n ```\n\n Columns: ID, Status, **Trigger** (`scheduler` vs `on_demand`; a run recorded before 0.15 says `SCHEDULER` vs `ON_DEMAND`), Started, Completed, Error.\n\n- **A single run's detail** (the cost signals):\n\n ```bash\n malloy-pub get materialization <id> --environment <env> --package <pkg>\n ```\n\n In the JSON, read:\n - `metadata.durationMs`: how long the whole run took.\n - `metadata.sourcesBuilt` / `sourcesReused` / `sourcesFailed`: how much work the run did. A run that reused most sources was cheap. **A scheduler run never reuses**: every scheduled fire is forced, so its `sourcesReused` is 0 by construction; judge a scheduled run by its duration and its per-source entries instead. An incremental source is counted as built even when its refresh applied nothing.\n - `metadata.sourcesRefused` and `metadata.refusedSources` (present only when a source was refused, and only on a run the publisher planned itself): sources the eligibility gate skipped. Each one serves live on every query, so a refused source the user expected to be persisted is a finding in its own right; its entry's `message` says what to change.\n - `manifest.entries` - a map keyed by `sourceEntityId`. Each entry carries `sourceName`, `physicalTableName`, `realization`, and the per-source cost signals: `buildDurationMs`; `queryCostBytes` where the warehouse reports it; `refresh: delta | full | none` for an incremental source (a `full` on an unchanged source every run is a source that never advances); `upstreamReuse: reused | recomputed` for a chained source (a `recomputed` with `upstreamRecomputeReason` is a chain that went back to the warehouse).\n - `manifest.failures`: sources the run lost while still finishing ready.\n\nLook across several runs, not one: the pattern over the recent history (how often it rebuilds, how long each source takes, what reuses) is the signal.\n\n- **For `storage=` tables, how queries were routed.** `publisher_query_route_total{leg, outcome, reason}` on the metrics endpoint counts each serving leg the router considered: `used` when it answered, `skipped` with the reason, and `fallback` when its stored run failed and live answered, and each query response's `servedFrom` says it per query. For a table built in the source's own warehouse there is no route counter, but each response's `servedFrom` reads `database` when one answered, so a log of responses measures it. Say so when it matters.\n\n## Step 3: Analyze and recommend\n\nWeigh rebuild cost against query benefit. Common findings:\n\n- **Persist candidate:** an expensive, frequently-queried source that is _not_ persisted (recomputed on every query). Recommend adding `#@ persist name=\"...\"`. Strongest when the source is a heavy aggregate/join reused by many queries and its inputs change slowly. If the source carries a `#(access_filter)` gate, check which case it is first. A gate reached only through a `join_*`, or not classifying as a row filter, means the database persist is **refused** - the build skips it and it serves live - so do not recommend persisting it at all. Where the gate is the source's own row filter the persist is admitted, and then only recommend it alongside a freshness window (`freshness.fallback=\"live\"`): the gating column freezes at build time, so without one a revoked row can be served under its old access decision indefinitely (see `access-filter.md`).\n- **Removal candidate:** a persisted source that is cheap to compute, rarely queried, or rebuilt far more often than it is read. Recommend dropping the `#@ persist` annotation (and its table): the storage + rebuild cost is not buying anything.\n- **Chain candidate:** a `storage=` rollup whose intermediates re-read the warehouse on every build while a stored root already holds the rows. Rewire the intermediates onto the stored root (declaration order, a distinct `-> { select: * }` intermediate, joins onto stored siblings - `chaining.md`), and read `upstreamReuse` on the next run to confirm the chain holds. Keep a self-join or a wide hash aggregate over a large fact **in the warehouse**: chained, it builds in the destination's engine under its memory bound.\n- **Denominator candidate:** a ratio whose numerator is a rollup and whose denominator counts the fact table per query. Persist the denominator at its own grain.\n- **Cadence mismatch:** a scheduler cadence out of step with how fast the data changes or how long a build takes. If the build's `durationMs` approaches the interval, the cadence is too aggressive. If queries routinely read stale data, tighten it. For an incremental source, `refresh: delta` with small `buildDurationMs` per fire is the cheap steady state; `refresh: full` every fire means the boundary is being lost (read the reason).\n- **Scope mismatch:** `scope: version` re-materializes per published version (right when versions must be isolated, e.g. a schedule); `scope: package` reuses one lineage across versions (cheaper when versions can share). A schedule _requires_ `version`. If a package carries a schedule it does not need, clearing it is step one; the scope itself is edited in `publisher.json` (the CLI does not move it back).\n\nFrame each recommendation with the evidence from Step 2 (the run IDs, timings, built/reused counts, per-entry fields) so the user can judge it.\n\n## Step 4: Apply (only once approved)\n\n- **Add a persist source:** add the `#@ persist` annotation in the `.malloy` file (use the modeling workflow to validate and reload), then rebuild so it is materialized:\n\n ```bash\n malloy-pub materialize --environment <env> --package <pkg> --wait --timeout 900\n ```\n\n (`--wait` gives up after 120 s by default and exits non-zero while the build continues; raise `--timeout` for a real build.)\n\n- **Remove a persist source:** delete the `#@ persist` annotation, rebuild, delete the old runs, then drop the old table yourself:\n\n ```bash\n malloy-pub materialize --environment <env> --package <pkg> --wait\n malloy-pub delete materialization <old-id> --environment <env> --package <pkg>\n ```\n\n > Deleting a run is **record-only**: it never drops a table. It re-derives the package's serve bindings from the latest remaining ready run (or clears them to serve live), so a delete does not break queries. To drop the old table, read its `physicalTableName` from the old run's manifest, check that no remaining ready run, of any version, names a table with that name in any place (the runs list answers for the latest version only, so list each version's runs with `versionId`; with the stable names an auto-run assigns, a table the new run carried forward is still served, and two destination names can reach one DuckLake), then drop it: a database table through `DELETE …/packages/{pkg}/connections/{connectionName}/materializedTables/{physicalTableName}`, which makes that check itself and refuses a table it cannot prove is the package's and unused (pass `?materializationId=<run>` for a table built before 0.16.0), a `storage=` table through the admin API.\n\n- **Change the schedule / cadence:**\n\n ```bash\n malloy-pub schedule set \"0 6 * * *\" --environment <env> --package <pkg> # 5-field UTC cron\n malloy-pub schedule clear --environment <env> --package <pkg>\n ```\n\n `set` also sets `scope: version` (a schedule requires it) and **replaces the whole `materialization` block, dropping an existing `freshness` policy**; the server rejects an invalid cron or an illegal scope/freshness combination, so a rejection means the change was unsafe. `clear` leaves `scope: version` in place. Both edit the package through a PATCH, which a published version (by default, any package outside a watched environment) refuses with 409 `PACKAGE_IS_VERSIONED`: there, set or remove `materialization.schedule` in `publisher.json` and publish a new version.\n\n- **Change the scope:** `scope` is declared in the package's `publisher.json` under `materialization` (`\"scope\": \"package\"` or `\"version\"`; the root-level form is deprecated but still read). Edit it there, then reload/republish the package. Remember a schedule pins scope to `version`, so clear the schedule first if moving to `package`.\n\nAfter applying, re-run Step 2 on the next few builds to confirm the change did what you predicted (more reuse, shorter builds, a chain that reports `reused`, or a table that is actually read).\n\n## What this skill does not do\n\n- It does not decide for the user or apply changes silently; every edit needs an explicit go-ahead.\n- It cannot measure reads of a table built in the source's own warehouse (only the storage tier reports routing), so \"rarely queried\" there is a judgment from the model and the user's knowledge, not a measured metric. Say so when it matters."
190253
191388
  },
190254
191389
  {
190255
191390
  name: "malloy-model",
@@ -349544,7 +350679,7 @@ var require_src140 = __commonJS(function(exports) {
349544
350679
  });
349545
350680
 
349546
350681
  // package.json
349547
- var version = "0.15.0";
350682
+ var version = "0.16.0";
349548
350683
  var init_package = () => {};
349549
350684
 
349550
350685
  // src/version.ts
@@ -354937,7 +356072,8 @@ function rollupLeg(rollups) {
354937
356072
  gateTablesRead: answer.gateTablesRead ?? (answer.binding ? [answer.binding] : [
354938
356073
  {
354939
356074
  tier: answer.virtualMap ? "storage" : "database",
354940
- ...answer.databaseTablePath ? { tablePath: answer.databaseTablePath } : {}
356075
+ ...answer.databaseTablePath ? { tablePath: answer.databaseTablePath } : {},
356076
+ ...{ kind: "rollup" }
354941
356077
  }
354942
356078
  ]),
354943
356079
  shapeBindings: answer.virtualMap ? answer.bindings ?? (answer.binding ? [answer.binding] : []) : [],
@@ -355238,13 +356374,20 @@ async function withGateColumnTypes(tables, gateReadsFor) {
355238
356374
  async function assertRowScopeExact(answer, gateReadsFor, authorRunnable, leg, givens) {
355239
356375
  const tables = answer.gateTablesRead ?? answer.tablesRead ?? [];
355240
356376
  const judged = await withGateColumnTypes(tables, gateReadsFor);
355241
- if (judged === tables)
355242
- return;
355243
356377
  const reads = await gateReadsFor(tables);
356378
+ if (reads === undefined && judged === tables)
356379
+ return;
355244
356380
  if (reads !== undefined && (!reads.scoped || reads.gated))
355245
356381
  return;
355246
- const decline = (why) => leg === "served" ? new LegDecline("served_copy_not_served", why) : new LegDecline("rollup_row_level_gate", why, { shapeCheck: true });
355247
- if (leg === "served" && !judged.every(gateColumnsExact)) {
356382
+ const tableIds = tables.flatMap((t) => {
356383
+ const handle = t.virtualHandle;
356384
+ return typeof handle === "string" ? [handle] : [];
356385
+ });
356386
+ const decline = (why) => leg === "served" ? new LegDecline("served_copy_not_served", why, { tableIds }) : new LegDecline("rollup_row_level_gate", why, {
356387
+ shapeCheck: true,
356388
+ tableIds
356389
+ });
356390
+ if (leg === "served" && judged !== tables && !judged.every(gateColumnsExact)) {
355248
356391
  throw decline("the query's source scopes its rows by a column a stored table does not hold exactly");
355249
356392
  }
355250
356393
  if (await storedComparisonRefusal(answer, judged, authorRunnable, () => gateReadsFor(tables), givens) !== undefined) {
@@ -355282,7 +356425,8 @@ async function storedComparisonRefusal(answer, tables, authorRunnable, readsOf,
355282
356425
  answerRunnable: answer.runnable,
355283
356426
  virtualMap: answer.virtualMap,
355284
356427
  authorRunnable,
355285
- reads
356428
+ reads,
356429
+ ...givens ? { givens } : {}
355286
356430
  });
355287
356431
  }
355288
356432
  function answerOf(route) {
@@ -355560,7 +356704,7 @@ var init_drill_metadata = () => {};
355560
356704
 
355561
356705
  // src/service/query_execution.ts
355562
356706
  import {
355563
- EMPTY_BUILD_MANIFEST,
356707
+ EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST2,
355564
356708
  MalloyError as MalloyError8
355565
356709
  } from "@malloydata/malloy";
355566
356710
  async function prepareAndRun(runnable, options, run) {
@@ -355569,7 +356713,7 @@ async function prepareAndRun(runnable, options, run) {
355569
356713
  async function prepareAndRunUntraced(runnable, options, run) {
355570
356714
  options = {
355571
356715
  ...options,
355572
- buildManifest: options.buildManifest ?? EMPTY_BUILD_MANIFEST
356716
+ buildManifest: options.buildManifest ?? EMPTY_BUILD_MANIFEST2
355573
356717
  };
355574
356718
  const prepared = await runnable.getPreparedResult(options);
355575
356719
  const preparedLimit = prepared.resultExplore.limit;
@@ -355762,7 +356906,7 @@ var init_model_query_compile = __esm(() => {
355762
356906
 
355763
356907
  // src/service/model_serving.ts
355764
356908
  import {
355765
- EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST2,
356909
+ EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST3,
355766
356910
  Annotations as Annotations11,
355767
356911
  MalloyError as MalloyError11
355768
356912
  } from "@malloydata/malloy";
@@ -356013,7 +357157,7 @@ run: ${sourceName ? `${quotedIdentifier(sourceName)} -> ` : ""}${quotedIdentifie
356013
357157
  const effectiveBuildManifest = runManifestOf(answer, {
356014
357158
  pinned: buildManifest,
356015
357159
  withoutRollups: args.viewManifest,
356016
- live: EMPTY_BUILD_MANIFEST2
357160
+ live: EMPTY_BUILD_MANIFEST3
356017
357161
  });
356018
357162
  const maxRows = getMaxQueryRows();
356019
357163
  const maxBytes = getMaxResponseBytes();
@@ -356052,6 +357196,9 @@ run: ${sourceName ? `${quotedIdentifier(sourceName)} -> ` : ""}${quotedIdentifie
356052
357196
  answer = answeredWith(answer, retried.read);
356053
357197
  executionTime = performance.now() - ctx.startTime;
356054
357198
  }
357199
+ if (answer.leg !== "live" && !answer.runFailed) {
357200
+ await roundStoredAnswerAsLive(run.result, prepared.liveRunnable);
357201
+ }
356055
357202
  return { run, answer, executionTime, maxRows, maxBytes };
356056
357203
  }
356057
357204
  async retryLive(ctx, governed, prepared, answer, runOptions) {
@@ -356068,7 +357215,7 @@ run: ${sourceName ? `${quotedIdentifier(sourceName)} -> ` : ""}${quotedIdentifie
356068
357215
  try {
356069
357216
  const run = await prepareAndRun(governedLive, {
356070
357217
  givens: prepared.surfaceGivens,
356071
- buildManifest: recordingManifest(EMPTY_BUILD_MANIFEST2, retryRead)
357218
+ buildManifest: recordingManifest(EMPTY_BUILD_MANIFEST3, retryRead)
356072
357219
  }, runOptions);
356073
357220
  return { run, read: retryRead };
356074
357221
  } catch (retryError) {
@@ -356464,6 +357611,17 @@ function governRequestOf(r) {
356464
357611
  ceiling: r.ceiling
356465
357612
  };
356466
357613
  }
357614
+ async function roundStoredAnswerAsLive(result, liveRunnable) {
357615
+ let dialect;
357616
+ try {
357617
+ dialect = (await liveRunnable.getPreparedQuery()).dialect;
357618
+ } catch {
357619
+ return;
357620
+ }
357621
+ if (!liveRoundsBigIntegersAsPostgres(dialect))
357622
+ return;
357623
+ roundBigIntegersAsLive(result);
357624
+ }
356467
357625
  var queryExecutionHistogram, queryScannedBytesCounter;
356468
357626
  var init_model_serving = __esm(() => {
356469
357627
  init_telemetry();
@@ -356475,6 +357633,7 @@ var init_model_serving = __esm(() => {
356475
357633
  init_access_record();
356476
357634
  init_binding();
356477
357635
  init_leg();
357636
+ init_live_big_integers();
356478
357637
  init_authorize();
356479
357638
  init_filter();
356480
357639
  init_annotations();
@@ -359407,7 +360566,7 @@ var init_join_rollup = __esm(() => {
359407
360566
  // src/service/materialization/serve/rollup_variants.ts
359408
360567
  import * as path33 from "path";
359409
360568
  import { fileURLToPath as fileURLToPath18, pathToFileURL as pathToFileURL19 } from "url";
359410
- import { EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST3 } from "@malloydata/malloy";
360569
+ import { EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST4 } from "@malloydata/malloy";
359411
360570
 
359412
360571
  class RollupVariantServe {
359413
360572
  host;
@@ -359845,7 +361004,7 @@ class RollupVariantServe {
359845
361004
  sql = (await runnable.getPreparedResult({
359846
361005
  virtualMap,
359847
361006
  ...q.args.givens ? { givens: q.args.givens } : {},
359848
- buildManifest: EMPTY_BUILD_MANIFEST3
361007
+ buildManifest: EMPTY_BUILD_MANIFEST4
359849
361008
  })).sql;
359850
361009
  } catch {
359851
361010
  if (leftOutHere) {
@@ -359952,7 +361111,7 @@ class RollupVariantServe {
359952
361111
  result = await runnable.getPreparedResult({
359953
361112
  ...table.virtualMap ? { virtualMap: table.virtualMap } : {},
359954
361113
  ...args.givens ? { givens: args.givens } : {},
359955
- buildManifest: table.virtualMap ? EMPTY_BUILD_MANIFEST3 : args.pinned.compilerManifest
361114
+ buildManifest: table.virtualMap ? EMPTY_BUILD_MANIFEST4 : args.pinned.compilerManifest
359956
361115
  });
359957
361116
  } catch {
359958
361117
  throw new LegDecline("rollup_missing_field", notCompiledDetail(variant));
@@ -361162,7 +362321,7 @@ var init_model_policy = __esm(() => {
361162
362321
 
361163
362322
  // src/service/model.ts
361164
362323
  import {
361165
- EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST4,
362324
+ EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST5,
361166
362325
  isSourceDef as isSourceDef20,
361167
362326
  MalloyError as MalloyError14,
361168
362327
  Annotations as Annotations12
@@ -362304,7 +363463,7 @@ var init_model = __esm(() => {
362304
363463
  if (!materializer)
362305
363464
  return;
362306
363465
  return resultShapeOf(await materializer.loadRestrictedQuery(queryString).getPreparedResult({
362307
- buildManifest: EMPTY_BUILD_MANIFEST4,
363466
+ buildManifest: EMPTY_BUILD_MANIFEST5,
362308
363467
  givens
362309
363468
  }));
362310
363469
  },
@@ -363786,9 +364945,25 @@ var init_package2 = __esm(() => {
363786
364945
  getPackageName() {
363787
364946
  return this.packageName;
363788
364947
  }
364948
+ boundLateRows() {
364949
+ return this.mz.boundLateRows();
364950
+ }
363789
364951
  forgetKeyUniqueness(sourceEntityIds) {
363790
364952
  this.mz.forgetKeyUniqueness(sourceEntityIds);
363791
364953
  }
364954
+ boundTableNames() {
364955
+ const names = new Set;
364956
+ for (const entries of [
364957
+ this.mz.getBuildManifestEntries(),
364958
+ this.mz.boundDatabaseEntries()
364959
+ ]) {
364960
+ for (const entry of Object.values(entries ?? {})) {
364961
+ if (entry.tableName)
364962
+ names.add(entry.tableName);
364963
+ }
364964
+ }
364965
+ return [...names];
364966
+ }
363792
364967
  setKeptTables(tables) {
363793
364968
  this.mz.setKeptTables(tables);
363794
364969
  }
@@ -364058,6 +365233,7 @@ var init_package2 = __esm(() => {
364058
365233
  ...this.mz.databaseTableUnreadWarnings(),
364059
365234
  ...this.mz.servedCopyWarnings(),
364060
365235
  ...this.mz.repeatedJoinOneKeyWarnings(),
365236
+ ...this.mz.lateRowWarnings(),
364061
365237
  ...this.mz.keptTableWarnings(),
364062
365238
  ...this.mz.annotationFindingWarnings(),
364063
365239
  ...this.annotationNearMissWarnings(),
@@ -378030,10 +379206,10 @@ var init_mcp_config = __esm(() => {
378030
379206
  });
378031
379207
 
378032
379208
  // src/listen.ts
378033
- function longTimeouts(server) {
378034
- server.timeout = LONG_REQUEST_MS;
378035
- server.keepAliveTimeout = LONG_REQUEST_MS;
378036
- server.headersTimeout = LONG_REQUEST_MS;
379209
+ function longTimeouts(server, timeoutMs = LONG_REQUEST_MS) {
379210
+ server.timeout = timeoutMs;
379211
+ server.keepAliveTimeout = timeoutMs;
379212
+ server.headersTimeout = timeoutMs;
378037
379213
  return server;
378038
379214
  }
378039
379215
  function logListening(label, server, requestedHost, requestedPort) {
@@ -430337,6 +431513,17 @@ function registerMaterializationRoutes(app, pkg, { materializationController })
430337
431513
  }
430338
431514
  return materializationController.stopMaterialization(req.params.environmentName, req.params.packageName, req.params.materializationId, versionRefOf(req));
430339
431515
  }));
431516
+ app.delete(`${pkg}/connections/:connectionName/materializedTables/:tableName`, apiRoute(async (req, res) => {
431517
+ const materializationId = req.query.materializationId;
431518
+ if (materializationId !== undefined && (typeof materializationId !== "string" || materializationId === "")) {
431519
+ throw new BadRequestError(`Invalid materializationId ${JSON.stringify(materializationId)}: ` + `expected one run id. Fix: ${req.method} ${req.path}` + `?materializationId=<id>, or omit it.`);
431520
+ }
431521
+ await materializationController.dropMaterializedTable(req.params.environmentName, req.params.packageName, req.params.connectionName, req.params.tableName, {
431522
+ ...materializationId !== undefined ? { materializationId } : {},
431523
+ versionId: versionRefOf(req)
431524
+ });
431525
+ res.status(204).send();
431526
+ }));
430340
431527
  app.delete(materialization, apiRoute(async (req, res) => {
430341
431528
  assertNoDropTables(req);
430342
431529
  await materializationController.deleteMaterialization(req.params.environmentName, req.params.packageName, req.params.materializationId, { versionId: versionRefOf(req) });
@@ -460796,7 +461983,7 @@ async function buildApp(settings) {
460796
461983
  });
460797
461984
  if (adminServer) {
460798
461985
  adminServer.on("error", fatalListenError("Admin", ADMIN_PORT, "--admin_port", mainServer));
460799
- longTimeouts(adminServer);
461986
+ longTimeouts(adminServer, settings.get("admin.requestTimeoutMs"));
460800
461987
  }
460801
461988
  const otherServers = adminServer ? [adminServer] : [];
460802
461989
  return {
@@ -460900,7 +462087,7 @@ var init_admin_server = __esm(() => {
460900
462087
  logger.error(error.code === "EADDRINUSE" ? `Port ${ADMIN_PORT} in use; pass --admin_port <n>` : `Admin listener failed on port ${ADMIN_PORT}: ${error.message}`);
460901
462088
  process.exit(1);
460902
462089
  });
460903
- longTimeouts(adminServer);
462090
+ longTimeouts(adminServer, settings.get("admin.requestTimeoutMs"));
460904
462091
  registerSignalHandlers(null, null, settings.get("shutdown.drainDurationSeconds"), settings.get("shutdown.gracefulCloseTimeoutSeconds"), [adminServer]);
460905
462092
  });
460906
462093