@malloy-publisher/server 0.17.3 → 0.18.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/admin-api-doc.yaml +757 -22
  2. package/dist/app/api-doc.yaml +129 -28
  3. package/dist/app/assets/{EnvironmentPage-Cpetyfj1.js → EnvironmentPage-BYi5H87v.js} +1 -1
  4. package/dist/app/assets/{HomePage-RlrpQRV8.js → HomePage-DB-CSs0p.js} +1 -1
  5. package/dist/app/assets/{MainPage-C1559_mQ.js → MainPage-2j-MpcYJ.js} +1 -1
  6. package/dist/app/assets/{ModelPage-D8T03Bd7.js → ModelPage-BQE-ZC6E.js} +2 -2
  7. package/dist/app/assets/{PackagePage-BIl1r9eP.js → PackagePage-BMv6ojk4.js} +1 -1
  8. package/dist/app/assets/{PackageSplatRoute-DJlJXk6p.js → PackageSplatRoute-BOAFRQKR.js} +2 -2
  9. package/dist/app/assets/{RenderedResult-Cm0Wwtek.es-CfBPkvGU.js → RenderedResult-QdYnecnr.es-PKDmuES7.js} +1 -1
  10. package/dist/app/assets/{RouteError-DRuMstfb.js → RouteError-7Fw_wYUy.js} +1 -1
  11. package/dist/app/assets/{ThemeEditorPage-ss_tmVWo.js → ThemeEditorPage-DmiRg7rU.js} +1 -1
  12. package/dist/app/assets/{ToggleButtonGroup-DA9EfQQB.js → ToggleButtonGroup-BXVbLuei.js} +1 -1
  13. package/dist/app/assets/{documentRoutes-_ma0jaCp.js → documentRoutes-DWIPC8nU.js} +1 -1
  14. package/dist/app/assets/{editPageMounted-DxNTqmFg.js → editPageMounted-BaGHeFZ5.js} +2 -2
  15. package/dist/app/assets/{index-DrkXqbpl.js → index-APmAmrTn.js} +1 -1
  16. package/dist/app/assets/{index-BZA1HAyp.js → index-BRdik0lA.js} +1 -1
  17. package/dist/app/assets/{index-w1w5RvZI.js → index-CHfKShi-.js} +1 -1
  18. package/dist/app/assets/{index-BL_7q21Q.js → index-OQqQyWrE.js} +5 -5
  19. package/dist/app/assets/{index.es-XV_AUlWO.js → index.es-DLFu6xFm.js} +1 -1
  20. package/dist/app/assets/usePackageLinkNavigate-DTlEYsed.js +1 -0
  21. package/dist/app/assets/{usePackageRoute-ev5b1KRn.js → usePackageRoute-pIAy965Q.js} +1 -1
  22. package/dist/app/index.html +1 -1
  23. package/dist/instrumentation.mjs +16 -11
  24. package/dist/package_load_worker.mjs +387 -337
  25. package/dist/server.mjs +8831 -3479
  26. package/package.json +2 -1
  27. package/dist/app/assets/usePackageLinkNavigate-BKkPNdJ4.js +0 -1
@@ -86,6 +86,105 @@ var init_ducklake_catalog_unavailable = __esm(() => {
86
86
  UNAVAILABLE_MESSAGE = /^DuckLake catalog "[^"]+" is not attached on its DuckDB instance/;
87
87
  });
88
88
 
89
+ // src/service/materialization/domain/freshness.ts
90
+ function freshnessOf(facts, at) {
91
+ if (facts.freshnessWindowSeconds == null)
92
+ return "fresh";
93
+ if (facts.dataAsOf == null)
94
+ return "fresh";
95
+ const dataAsOfMs = Date.parse(facts.dataAsOf);
96
+ if (Number.isNaN(dataAsOfMs))
97
+ return "fresh";
98
+ const ageSeconds = (at.getTime() - dataAsOfMs) / 1000;
99
+ if (ageSeconds <= facts.freshnessWindowSeconds)
100
+ return "fresh";
101
+ return facts.freshnessFallback === "stale_ok" ? "stale_ok" : "stale";
102
+ }
103
+ function stopsReadAt(facts) {
104
+ if (facts.freshnessWindowSeconds == null || facts.dataAsOf == null) {
105
+ return;
106
+ }
107
+ if (facts.freshnessFallback === "stale_ok")
108
+ return;
109
+ const dataAsOfMs = Date.parse(facts.dataAsOf);
110
+ if (Number.isNaN(dataAsOfMs))
111
+ return;
112
+ return dataAsOfMs + facts.freshnessWindowSeconds * 1000 + 1;
113
+ }
114
+ function isFreshnessFallback(value) {
115
+ return typeof value === "string" && FRESHNESS_FALLBACKS.includes(value);
116
+ }
117
+ function freshnessWindowSeconds(window2) {
118
+ const match = /^\s*(\d+)\s*([smhdw])\s*$/.exec(window2);
119
+ if (!match)
120
+ return;
121
+ const count = Number(match[1]);
122
+ if (!Number.isSafeInteger(count) || count <= 0)
123
+ return;
124
+ return count * WINDOW_UNITS[match[2]];
125
+ }
126
+ function durationSeconds(text) {
127
+ const match = /^\s*(\d+)\s*([a-z]+)\s*$/.exec(text);
128
+ if (!match || !Object.hasOwn(DURATION_UNITS, match[2]))
129
+ return;
130
+ const count = Number(match[1]);
131
+ if (!Number.isSafeInteger(count) || count <= 0)
132
+ return;
133
+ return count * DURATION_UNITS[match[2]];
134
+ }
135
+ function declaredFreshnessFacts(declarations) {
136
+ let window2;
137
+ const fallbacks = new Set;
138
+ let declared = false;
139
+ for (const d of declarations) {
140
+ if (!d)
141
+ continue;
142
+ if (d.window !== undefined) {
143
+ declared = true;
144
+ const seconds = freshnessWindowSeconds(d.window);
145
+ if (seconds !== undefined) {
146
+ window2 = window2 === undefined ? seconds : Math.min(window2, seconds);
147
+ }
148
+ }
149
+ if (d.fallback !== undefined) {
150
+ declared = true;
151
+ fallbacks.add(d.fallback);
152
+ }
153
+ }
154
+ if (!declared)
155
+ return;
156
+ const fallback = fallbacks.has("live") ? "live" : fallbacks.has("fail") ? "fail" : fallbacks.has("stale_ok") ? "stale_ok" : undefined;
157
+ return {
158
+ ...window2 !== undefined ? { freshnessWindowSeconds: window2 } : {},
159
+ ...fallback !== undefined ? { freshnessFallback: fallback } : {}
160
+ };
161
+ }
162
+ var FRESHNESS_FALLBACKS, WINDOW_UNITS, FRESHNESS_WINDOW_PROBLEM, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
163
+ var init_freshness = __esm(() => {
164
+ FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
165
+ WINDOW_UNITS = {
166
+ s: 1,
167
+ m: 60,
168
+ h: 3600,
169
+ d: 86400,
170
+ w: 604800
171
+ };
172
+ FRESHNESS_WINDOW_PROBLEM = "has a freshness.window= that is not a positive duration: write a whole " + 'number greater than zero and one unit (s, m, h, d or w), such as freshness.window="24h"';
173
+ DURATION_UNITS = {
174
+ ...WINDOW_UNITS,
175
+ second: 1,
176
+ seconds: 1,
177
+ minute: 60,
178
+ minutes: 60,
179
+ hour: 3600,
180
+ hours: 3600,
181
+ day: 86400,
182
+ days: 86400,
183
+ week: 604800,
184
+ weeks: 604800
185
+ };
186
+ });
187
+
89
188
  // src/service/materialization/serve/served_copy_lanes.ts
90
189
  function compileInputOf(b) {
91
190
  let input = compileInputs.get(b);
@@ -108,6 +207,16 @@ function compileInputOf(b) {
108
207
  function compileKeyOf(bindings) {
109
208
  return bindings.map(compileInputOf).sort().join("\x00");
110
209
  }
210
+ function readsLapsedAt(bindings, atMs) {
211
+ return bindings.some((b) => {
212
+ const at = stopsReadAt({
213
+ dataAsOf: b.freshAsOf,
214
+ freshnessWindowSeconds: b.freshnessWindowSeconds,
215
+ freshnessFallback: b.freshnessFallback
216
+ });
217
+ return at !== undefined && at <= atMs;
218
+ });
219
+ }
111
220
  function sameBindings(a, b) {
112
221
  return a.length === b.length && a.every((x, i) => x === b[i]);
113
222
  }
@@ -138,7 +247,7 @@ class CompiledCopyLanes {
138
247
  inFlight = new Map;
139
248
  generation = 0;
140
249
  turns = 0;
141
- keptTurn = new Map;
250
+ keptBy = new Map;
142
251
  constructor(compile) {
143
252
  this.compile = compile;
144
253
  }
@@ -157,9 +266,15 @@ class CompiledCopyLanes {
157
266
  async ensure(bindings, lane, asOfMs) {
158
267
  const turn = ++this.turns;
159
268
  const keep = (compiled) => {
160
- if ((this.keptTurn.get(lane) ?? 0) > turn)
161
- return;
162
- this.keptTurn.set(lane, turn);
269
+ const by = this.keptBy.get(lane);
270
+ const kept = this.compiled.get(lane);
271
+ if (by && kept) {
272
+ if (readsLapsedAt(compiled.over, by.asOfMs))
273
+ return;
274
+ if (!readsLapsedAt(kept.over, asOfMs) && by.turn > turn)
275
+ return;
276
+ }
277
+ this.keptBy.set(lane, { turn, asOfMs });
163
278
  this.compiled.set(lane, compiled);
164
279
  };
165
280
  const generation = this.generation;
@@ -201,6 +316,7 @@ class CompiledCopyLanes {
201
316
  }
202
317
  var compileInputs;
203
318
  var init_served_copy_lanes = __esm(() => {
319
+ init_freshness();
204
320
  compileInputs = new WeakMap;
205
321
  });
206
322
 
@@ -762,12 +878,26 @@ var init_admin = __esm(() => {
762
878
  defaultText: "`600000` (10 min)",
763
879
  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."
764
880
  }),
881
+ setting({
882
+ key: "admin.memoryLimit",
883
+ type: string(),
884
+ default: "1.5GB",
885
+ description: "Most memory one admin table load or copy session may use, as a DuckDB size (1.5GB).",
886
+ notes: "The `memory_limit` of the DuckDB session an admin table load or copy runs in, as a flat DuckDB size (`1.5GB`, `512MB`). The session uses the lower of this and `PUBLISHER_DUCKDB_MEMORY_LIMIT`, so a pod whose general limit is smaller is never raised by the default: to give a load more than 1.5GB, raise both. A keyed load and a keyless replace both size their comparison passes to half of the session's effective limit. Validated at startup."
887
+ }),
888
+ setting({
889
+ key: "admin.maxTempDirectorySize",
890
+ type: string(),
891
+ default: "6GiB",
892
+ description: "Most spill one admin table load or copy session may write, as a DuckDB size (6GiB).",
893
+ notes: "The `max_temp_directory_size` of the DuckDB session an admin table load or copy runs in, as a flat DuckDB size (`6GiB`, `20GB`). Keep it under the pod's ephemeral storage. A load or table PUT that outgrows it (or the memory limit) answers `422 LOAD_TOO_LARGE`; a full disk is a `500`. Validated at startup."
894
+ }),
765
895
  setting({
766
896
  key: "admin.catalogDatabase",
767
897
  type: string(),
768
898
  secret: true,
769
899
  description: "libpq connection string of the database the admin API finds DuckLake catalogs in.",
770
- notes: "A libpq connection string (keyword or `postgres://` form) for the Postgres database holding the catalogs the admin API manages. Unset, the admin API's catalog routes answer `503 CATALOG_DATABASE_NOT_CONFIGURED`.",
900
+ notes: "A libpq connection string (keyword or `postgres://` form) for the Postgres database holding the catalogs the admin API manages. Unset, the admin API's catalog routes answer `503 CATALOG_DATABASE_NOT_CONFIGURED`. The string also opens the connection that holds a table load's advisory lock, so it must name one host (no `service`, `hostaddr` or list of hosts, and no `PGSERVICE` or `PGHOSTADDR` in the environment; either fails startup). It also refuses what the lock connection cannot honor: `channel_binding=require`, `gssencmode=require`, any `require_auth`, `sslcrl`, `sslcrldir`, an `ssl_min_protocol_version` of `TLSv1.3` (from the string or the matching `PG*` variable), a missing or unreadable `sslrootcert`, `sslcert` or `sslkey` file, and `sslmode=verify-ca` with no `sslrootcert` while `NODE_EXTRA_CA_CERTS` is unset. It must reach Postgres directly or through a session-mode pooler, not a transaction-mode one such as PgBouncer.",
771
901
  aliases: { env: ["PUBLISHER_ADMIN_CATALOG_DATABASE"] }
772
902
  }),
773
903
  setting({
@@ -1550,15 +1680,6 @@ var init_storage = __esm(() => {
1550
1680
  notes: "Off by default until a security review of gated tables at rest. Off, a query whose entry point carries a row-level gate (`#(authorize)`, `#(access_filter)`) is answered from a stored table only when every table the answer reads is a database table, a `storage=` table that every source stored in it is proven to fill with ungated rows only, or a table kept under its source's own gate: a v1 `#@ persist` or `#(materialize)`, database or `storage=`, whose gate is proven to be its entry point's own row filter or lock (not a row filter it inherits, not one reached through a join, not one whose build substitutes a given) is built, and the served copy grafts and proves that gate on it, so each caller gets live's rows; database and `storage=` behave the same, ahead of that review. A `storage=` table built this way holds every row of the gated source, ungated, at rest in the destination, readable by anyone with direct access to it. Off, such a query is never answered from a `storage=` table proven neither way (one a gated source shares, say) or a persisted view, and from a rollup, in the database or `storage=`, only from one whose base's gates are all its own, each reading grain dimensions only, or are locks reading no row field (inherited at any depth), or, through a join, from an ungated joined source's rollup when the gate reads only the querying source's own plain columns (in a `storage=` destination, beside the querying source's own table there, admitted past its own gate or holding only ungated rows). On, the served copy may answer it from any stored table: the served copy is the author's own text, gates included, so the row filter is grafted and proven on the served compile exactly as on live. A persisted view and a `#(rollup)` rollup, in the database or `storage=`, are let through the same way, each redeclaring the queried source with its gates; a rollup only when every gate reads its grain dimensions. A v1 `#@ preaggregate` rollup is the rollup leg's and is let through as a `#(rollup)` one is. A gate that cannot be grafted on the served copy denies, as it does live. It also decides whether a `#(rollup)` rollup or a database persisted view over a gated source is built: on, it is; off, a view is not, and a rollup only when its base's gates are its own, or locks, as above (a `storage=` view over one is refused either way). A `storage=` table or rollup is read past a gate only when every column the gate reads is stored exactly and compared as its source compares it (no binary float, unless its column contract records it `gateExact`: a destination `DOUBLE` copying a warehouse 8-byte double unchanged; no 128-bit integer; no zone; a known collation). Never configure a destination's catalog, schema or data path as a connection models can name: its stored tables hold gated sources' rows with no gate. Read at startup.",
1551
1681
  aliases: { env: ["PUBLISHER_MATERIALIZE_GATED_SOURCES"] }
1552
1682
  }),
1553
- setting({
1554
- key: "materialize.admissionMode",
1555
- type: oneOf(["probe", "lookup", "shadow"]),
1556
- default: "lookup",
1557
- temporary: true,
1558
- description: "TEMPORARY, removed with the per-query probes: how read admission judges a stored answer's strings (probe, lookup or shadow).",
1559
- notes: "**Temporary**: a transitional test and canary setting, removed together with the per-query probes it switches between; do not depend on it. It picks how read admission judges its collation facts. `probe`: each query reads the source's and the stored table's collations from the warehouse, as Publisher always has. `lookup` (the default): each query looks them up in what the load, the bind and the build recorded (the source's string columns at each bind, and each table's column contract), with no catalog read and no extra compile; the same setting picks whether the per-source facts the served copy's compile, the bind and the plans record (the served copy's declines, the gates' and row scope's reads and flags, the rollup candidates, the path report's source chain) are looked up or walked per query. `shadow`: both run, the probe (or walk) decides, and every disagreement is logged at warn as `admission parity drift` and counted in `publisher_admission_parity_drift_total`. Read on every query.",
1560
- aliases: { env: ["PUBLISHER_ADMISSION_MODE"] }
1561
- }),
1562
1683
  setting({
1563
1684
  key: "persist.collisionEnforcementEnabled",
1564
1685
  type: boolean(),
@@ -12675,7 +12796,7 @@ function errorMapping(error) {
12675
12796
  function errorReason(error) {
12676
12797
  return resolve(errorMapping(error).reason, error);
12677
12798
  }
12678
- var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, ResultTruncatedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, ResultShapeError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, ContractCaptureFailedError, SchemaIncompatibleError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, 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;
12799
+ var GENERIC_INTERNAL_MESSAGE = "Internal server error.", GENERIC_UPSTREAM_MESSAGE = "Upstream connection error.", GENERIC_UNREACHABLE_MESSAGE = "The database connection is down: the database could not be reached, so the query did not run.", GENERIC_AUTH_MESSAGE = "The database rejected the connection's credentials. Check the connection's user, password, key or token.", MAX_LOGGED_DETAIL_CHARS = 2000, PACKAGE_VERSION_ERROR_STATUS, PackageVersionError, FILESYSTEM_ACCESS_DESCRIPTIONS, POSTGRES_STATEMENT_SQLSTATES, POSTGRES_UNDEFINED_TABLE = "42P01", POSTGRES_RELATION_MISSING, BuildPlanUnavailableError, BuildPlanRefreshingError, NotImplementedError, BadRequestError, BuildInstructionsInvalidError, TableOwnershipError, InvalidArgumentError, CompileRefusedError, InvalidModelPathError, InvalidQueryRequestError, RenderTagRefusedError, UnparseableTextError, EnvironmentNotFoundError, PackageNotFoundError, ModelNotFoundError, DashboardNotFoundError, SkillNotFoundError, AgentNotFoundError, ConflictError, ConnectionNotFoundError, TableNotFoundError, ConnectionError, ConnectionFailedError, ResultTruncatedError, UnconfiguredConnectionError, ConnectionPoolExhaustedError, ResultShapeError, DestinationNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, ContractCaptureFailedError, SchemaIncompatibleError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, AccessDeniedError, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, ManifestBindFailedError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, PackageAdmissionRefusedError, DryRunCapacityError, PayloadTooLargeError, ResponseUnserializableError, QueryTimeoutError, ERROR_CLASSES, UNHANDLED_LOG, UNHANDLED, NOT_TRANSIENT_CHANGE_QUERY = "This is not transient. The same query will fail the same way, so change the query rather than retrying it.", BACK_PRESSURE_SUGGESTIONS, BACK_PRESSURE, TOO_LARGE, BAD_REQUEST, NOT_FOUND, CONNECTION, ERROR_TABLE;
12679
12800
  var init_errors2 = __esm(() => {
12680
12801
  init_constants();
12681
12802
  init_logger();
@@ -13051,6 +13172,7 @@ var init_errors2 = __esm(() => {
13051
13172
  }
13052
13173
  reason;
13053
13174
  runFailures;
13175
+ runRefused;
13054
13176
  constructor(error) {
13055
13177
  super(error.message);
13056
13178
  this.name = "MaterializationEligibilityError";
@@ -13233,6 +13355,18 @@ var init_errors2 = __esm(() => {
13233
13355
  this.name = "WriteRolledBackError";
13234
13356
  }
13235
13357
  };
13358
+ ManifestBindFailedError = class ManifestBindFailedError extends Error {
13359
+ applied;
13360
+ get kind() {
13361
+ return "manifest_bind_failed";
13362
+ }
13363
+ constructor(manifestLocation, cause, applied) {
13364
+ const detail = cause instanceof Error ? cause.message : String(cause);
13365
+ super(`The build manifest ${manifestLocation} could not be bound ` + `(${detail}), so it was not applied: the package serves what ` + `it served before.`, { cause });
13366
+ this.applied = applied;
13367
+ this.name = "ManifestBindFailedError";
13368
+ }
13369
+ };
13236
13370
  WriteRollbackFailedError = class WriteRollbackFailedError extends Error {
13237
13371
  get kind() {
13238
13372
  return "write_rollback_failed";
@@ -13370,6 +13504,7 @@ var init_errors2 = __esm(() => {
13370
13504
  write_conflict: WriteConflictError,
13371
13505
  installed_from_location: InstalledFromLocationError,
13372
13506
  write_rolled_back: WriteRolledBackError,
13507
+ manifest_bind_failed: ManifestBindFailedError,
13373
13508
  write_rollback_failed: WriteRollbackFailedError,
13374
13509
  connection_save: ConnectionSaveError,
13375
13510
  write_verify: WriteVerifyError,
@@ -13690,6 +13825,11 @@ var init_errors2 = __esm(() => {
13690
13825
  write_rollback_failed: { status: 500, mcp: { advice: "internal" } },
13691
13826
  connection_save: { status: 500, mcp: { advice: "internal" } },
13692
13827
  write_rolled_back: { status: 500, mcp: { advice: "internal" } },
13828
+ manifest_bind_failed: {
13829
+ status: 500,
13830
+ reason: "MANIFEST_BIND_FAILED",
13831
+ mcp: { advice: "internal" }
13832
+ },
13693
13833
  service_unavailable: BACK_PRESSURE,
13694
13834
  package_admission_refused: BACK_PRESSURE,
13695
13835
  dry_run_capacity: BACK_PRESSURE,
@@ -13805,94 +13945,6 @@ function notePositionKey(at) {
13805
13945
  }
13806
13946
  var init_annotations = () => {};
13807
13947
 
13808
- // src/service/materialization/domain/freshness.ts
13809
- function freshnessOf(facts, at) {
13810
- if (facts.freshnessWindowSeconds == null)
13811
- return "fresh";
13812
- if (facts.dataAsOf == null)
13813
- return "fresh";
13814
- const dataAsOfMs = Date.parse(facts.dataAsOf);
13815
- if (Number.isNaN(dataAsOfMs))
13816
- return "fresh";
13817
- const ageSeconds = (at.getTime() - dataAsOfMs) / 1000;
13818
- if (ageSeconds <= facts.freshnessWindowSeconds)
13819
- return "fresh";
13820
- return facts.freshnessFallback === "stale_ok" ? "stale_ok" : "stale";
13821
- }
13822
- function isFreshnessFallback(value) {
13823
- return typeof value === "string" && FRESHNESS_FALLBACKS.includes(value);
13824
- }
13825
- function freshnessWindowSeconds(window2) {
13826
- const match = /^\s*(\d+)\s*([smhdw])\s*$/.exec(window2);
13827
- if (!match)
13828
- return;
13829
- const count = Number(match[1]);
13830
- if (!Number.isSafeInteger(count) || count <= 0)
13831
- return;
13832
- return count * WINDOW_UNITS[match[2]];
13833
- }
13834
- function durationSeconds(text) {
13835
- const match = /^\s*(\d+)\s*([a-z]+)\s*$/.exec(text);
13836
- if (!match || !Object.hasOwn(DURATION_UNITS, match[2]))
13837
- return;
13838
- const count = Number(match[1]);
13839
- if (!Number.isSafeInteger(count) || count <= 0)
13840
- return;
13841
- return count * DURATION_UNITS[match[2]];
13842
- }
13843
- function declaredFreshnessFacts(declarations) {
13844
- let window2;
13845
- const fallbacks = new Set;
13846
- let declared = false;
13847
- for (const d of declarations) {
13848
- if (!d)
13849
- continue;
13850
- if (d.window !== undefined) {
13851
- declared = true;
13852
- const seconds = freshnessWindowSeconds(d.window);
13853
- if (seconds !== undefined) {
13854
- window2 = window2 === undefined ? seconds : Math.min(window2, seconds);
13855
- }
13856
- }
13857
- if (d.fallback !== undefined) {
13858
- declared = true;
13859
- fallbacks.add(d.fallback);
13860
- }
13861
- }
13862
- if (!declared)
13863
- return;
13864
- const fallback = fallbacks.has("live") ? "live" : fallbacks.has("fail") ? "fail" : fallbacks.has("stale_ok") ? "stale_ok" : undefined;
13865
- return {
13866
- ...window2 !== undefined ? { freshnessWindowSeconds: window2 } : {},
13867
- ...fallback !== undefined ? { freshnessFallback: fallback } : {}
13868
- };
13869
- }
13870
- var FRESHNESS_FALLBACKS, WINDOW_UNITS, FRESHNESS_WINDOW_PROBLEM, DURATION_UNITS, DURATION_UNIT_TEXT = "seconds, minutes, hours, days or weeks (s, m, h, d or w)";
13871
- var init_freshness = __esm(() => {
13872
- FRESHNESS_FALLBACKS = ["live", "stale_ok", "fail"];
13873
- WINDOW_UNITS = {
13874
- s: 1,
13875
- m: 60,
13876
- h: 3600,
13877
- d: 86400,
13878
- w: 604800
13879
- };
13880
- FRESHNESS_WINDOW_PROBLEM = "has a freshness.window= that is not a positive duration: write a whole " + 'number greater than zero and one unit (s, m, h, d or w), such as freshness.window="24h"';
13881
- DURATION_UNITS = {
13882
- ...WINDOW_UNITS,
13883
- second: 1,
13884
- seconds: 1,
13885
- minute: 60,
13886
- minutes: 60,
13887
- hour: 3600,
13888
- hours: 3600,
13889
- day: 86400,
13890
- days: 86400,
13891
- week: 604800,
13892
- weeks: 604800
13893
- };
13894
- });
13895
-
13896
13948
  // src/service/motly.ts
13897
13949
  import { Annotations as Annotations2 } from "@malloydata/malloy";
13898
13950
  import { parseAnnotation } from "@malloydata/malloy-tag";
@@ -30237,23 +30289,6 @@ function serveTypePlan(mismatches, options = {}) {
30237
30289
  }
30238
30290
  return { casts, unservable };
30239
30291
  }
30240
- function driftedColumnRead(column, declaredType, options = {}) {
30241
- if (column.leftOut || !column.observedType)
30242
- return { read: "left_out" };
30243
- const [cast] = serveTypePlan([
30244
- {
30245
- column: column.column,
30246
- storedType: column.observedType,
30247
- declaredType
30248
- }
30249
- ], options).casts;
30250
- if (cast)
30251
- return { read: "cast", castTo: cast.castTo };
30252
- return storedTypeServesAs(column.observedType, declaredType) !== false ? { read: "as_is" } : { read: "left_out" };
30253
- }
30254
- function driftDeclaredType(declared, column, builtType) {
30255
- return declared?.find((c) => c.name === column)?.type ?? storedMalloyType(builtType) ?? builtType;
30256
- }
30257
30292
  function storedColumnReadPlan(schema, declared, options = {}) {
30258
30293
  const lossy = [];
30259
30294
  if (options.ducklake) {
@@ -31538,7 +31573,7 @@ function gateColumnsExact(t) {
31538
31573
  }
31539
31574
  if (t.gateColumnTypes === undefined)
31540
31575
  return t.tier === "database";
31541
- return t.gateColumnTypes.every((type, i) => gateColumnTypeExact(type, t.gateColumnUpstreamTypes?.[i]));
31576
+ return t.gateColumnTypes.every((type) => gateColumnTypeExact(type, undefined));
31542
31577
  }
31543
31578
  function g3Table(t) {
31544
31579
  return t.tier === "database" || t.ownGateKept === true || t.holdsOnlyUngatedRows === true;
@@ -31597,30 +31632,66 @@ import { createHash } from "crypto";
31597
31632
  function contractKeyName(level, subject, keyColumn) {
31598
31633
  return `${level}:${subject ? `${subject}.` : ""}${keyColumn}`;
31599
31634
  }
31600
- function keyUniquenessOfContract(contract, sources) {
31635
+ function contractKeyWithoutLevel(name, level) {
31636
+ const prefix = `${level}:`;
31637
+ return name.startsWith(prefix) ? name.slice(prefix.length) : undefined;
31638
+ }
31639
+ function keyUniquenessOfContract(contract, sources, leaves = []) {
31601
31640
  const keys = parseContract(contract)?.keys;
31602
31641
  if (!keys)
31603
31642
  return;
31604
- const own = Object.entries(keys).find(([name, check]) => check.level === "rollup" && name.startsWith("rollup:"));
31643
+ const own = Object.entries(keys).find(([name, check]) => check.level === "rollup" && contractKeyWithoutLevel(name, "rollup") !== undefined);
31605
31644
  const parentKeys = {};
31606
31645
  const parentKeyColumns = {};
31646
+ const read = (level, subject, source) => {
31647
+ const check = keys[contractKeyName(level, subject, source.primaryKey)];
31648
+ if (check?.level !== level)
31649
+ return;
31650
+ parentKeys[source.sourceID] = (parentKeys[source.sourceID] ?? true) && passed(check);
31651
+ parentKeyColumns[source.sourceID] = source.primaryKey;
31652
+ };
31607
31653
  for (const s of sources) {
31608
- for (const level of ["parent", "stored"]) {
31609
- const check = keys[contractKeyName(level, s.relativeID, s.primaryKey)];
31610
- if (check?.level !== level)
31611
- continue;
31612
- parentKeys[s.sourceID] = (parentKeys[s.sourceID] ?? true) && check.unique;
31613
- parentKeyColumns[s.sourceID] = s.primaryKey;
31614
- }
31654
+ read("parent", s.relativeID, s);
31655
+ read("stored", s.relativeID, s);
31656
+ }
31657
+ const bySourceID = new Map(sources.map((s) => [s.sourceID, s]));
31658
+ for (const leaf of leaves) {
31659
+ const source = bySourceID.get(leaf.sourceID);
31660
+ if (source)
31661
+ read("leaf", leaf.joinPath, source);
31615
31662
  }
31616
31663
  const anyParent = Object.keys(parentKeys).length > 0;
31617
31664
  if (!own && !anyParent)
31618
31665
  return;
31619
31666
  return {
31620
- ...own ? { keyColumn: own[0].slice("rollup:".length), unique: own[1].unique } : {},
31667
+ ...own ? {
31668
+ keyColumn: contractKeyWithoutLevel(own[0], "rollup"),
31669
+ unique: passed(own[1])
31670
+ } : {},
31621
31671
  ...anyParent ? { parentKeys, parentKeyColumns } : {}
31622
31672
  };
31623
31673
  }
31674
+ function passed(check) {
31675
+ return check.unique && check.unverified !== true;
31676
+ }
31677
+ function contractWithoutPassedKeys(raw) {
31678
+ let value = raw;
31679
+ if (typeof value === "string") {
31680
+ try {
31681
+ value = JSON.parse(value);
31682
+ } catch {
31683
+ return raw;
31684
+ }
31685
+ }
31686
+ if (!isRecord(value) || !isRecord(value.keys))
31687
+ return raw;
31688
+ const all = Object.entries(value.keys);
31689
+ const kept = all.filter(([, check]) => !(isRecord(check) && check.unique === true && check.unverified !== true));
31690
+ if (kept.length === all.length)
31691
+ return raw;
31692
+ const { keys: _dropped, ...rest } = value;
31693
+ return kept.length > 0 ? { ...rest, keys: Object.fromEntries(kept) } : rest;
31694
+ }
31624
31695
  function isRecord(v) {
31625
31696
  return typeof v === "object" && v !== null && !Array.isArray(v);
31626
31697
  }
@@ -31660,7 +31731,8 @@ function parseContract(raw) {
31660
31731
  keys[column] = {
31661
31732
  unique: check.unique,
31662
31733
  ...typeof check.level === "string" ? { level: check.level } : {},
31663
- ...check.unverified === true ? { unverified: true } : {}
31734
+ ...check.unverified === true ? { unverified: true } : {},
31735
+ ...check.unverified === true && check.rebuiltToVerify === true ? { rebuiltToVerify: true } : {}
31664
31736
  };
31665
31737
  }
31666
31738
  }
@@ -31673,6 +31745,10 @@ function parseContract(raw) {
31673
31745
  ...Object.keys(keys).length > 0 ? { keys } : {}
31674
31746
  };
31675
31747
  }
31748
+ function servableContract(raw) {
31749
+ const contract = parseContract(raw);
31750
+ return contract && contract.columns.length > 0 ? contract : undefined;
31751
+ }
31676
31752
  function contractColumn(contract, name) {
31677
31753
  const found = columnNamed(contract.columns, name);
31678
31754
  return found ?? { name, compare: "none", gateExact: false };
@@ -31697,12 +31773,20 @@ function contractDigest(contract) {
31697
31773
  }
31698
31774
  function keyCheckPassed(contract, key) {
31699
31775
  const check = contract?.keys?.[key];
31700
- return check?.unique === true && check.unverified !== true;
31776
+ return check !== undefined && passed(check);
31701
31777
  }
31702
31778
  function keyCheckFailed(contract, key) {
31703
31779
  const check = contract?.keys?.[key];
31704
31780
  return check?.unique === false && check.unverified !== true;
31705
31781
  }
31782
+ function pairLeafCheckFailure(contract, leafKeys) {
31783
+ const failed = leafKeys.filter((k) => keyCheckFailed(contract, k));
31784
+ const unrecorded = leafKeys.filter((k) => !keyCheckPassed(contract, k) && !keyCheckFailed(contract, k));
31785
+ if (failed.length === 0 && unrecorded.length === 0)
31786
+ return;
31787
+ const named = (ks) => ks.map((k) => `'${contractKeyWithoutLevel(k, "leaf") ?? k}'`).join(", ");
31788
+ return failed.length > 0 ? `found the key ${named(failed)} held more than once or NULL` : `recorded no result for the key ${named(unrecorded)}`;
31789
+ }
31706
31790
  function weakerCompare(a, b) {
31707
31791
  return COMPARE_RANK[a] <= COMPARE_RANK[b] ? a : b;
31708
31792
  }
@@ -31858,15 +31942,30 @@ function originOfTable(kind, sourceID) {
31858
31942
  return "persist";
31859
31943
  }
31860
31944
  }
31945
+ function pairLeafPath(p) {
31946
+ const hops = p.hops ?? [];
31947
+ const last = hops[hops.length - 1];
31948
+ return {
31949
+ names: [p.join, ...hops.map((h) => h.join)],
31950
+ keyColumn: last?.key ?? p.childKey,
31951
+ sourceID: last?.sourceID ?? p.childSourceID
31952
+ };
31953
+ }
31861
31954
  function pairLeafContractKeys(plan) {
31862
- const pairs = plan.pairBlocks?.blocks ?? (plan.pair ? [plan.pair] : []);
31863
- return pairs.map((p) => {
31864
- const names = [p.join, ...(p.hops ?? []).map((h) => h.join)];
31865
- const hops = p.hops ?? [];
31866
- const key = hops.length > 0 ? hops[hops.length - 1].key : p.childKey;
31867
- return contractKeyName("leaf", names.join("."), key);
31955
+ return pairPathsOf(plan).map((p) => {
31956
+ const leaf = pairLeafPath(p);
31957
+ return contractKeyName("leaf", leaf.names.join("."), leaf.keyColumn);
31958
+ });
31959
+ }
31960
+ function pairLeavesOf(plan) {
31961
+ return pairPathsOf(plan).map((p) => {
31962
+ const leaf = pairLeafPath(p);
31963
+ return { joinPath: leaf.names.join("."), sourceID: leaf.sourceID };
31868
31964
  });
31869
31965
  }
31966
+ function pairPathsOf(plan) {
31967
+ return plan.pairBlocks?.blocks ?? (plan.pair ? [plan.pair] : []);
31968
+ }
31870
31969
  function materializeKindOf(plan) {
31871
31970
  return plan.pair ? "pair" : "materialize";
31872
31971
  }
@@ -32050,26 +32149,42 @@ function bindingServesModelSource(binding, contents) {
32050
32149
  return true;
32051
32150
  return binding.sourceIDs.includes(sourceID);
32052
32151
  }
32053
- function primaryKeysOf(entry) {
32054
- const keys = entry.keyUniqueness?.parentKeys;
32055
- if (!keys || typeof keys !== "object")
32152
+ function parseKeyUniqueness(raw) {
32153
+ if (!raw || typeof raw !== "object")
32056
32154
  return;
32057
- const out = Object.fromEntries(Object.entries(keys).filter(([, v]) => typeof v === "boolean"));
32058
- return Object.keys(out).length > 0 ? out : undefined;
32155
+ const k = raw;
32156
+ const own = typeof k.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32157
+ const parentKeys = recordOf(k.parentKeys, "boolean");
32158
+ const parentKeyColumns = recordOf(k.parentKeyColumns, "string");
32159
+ if (!own && !parentKeys && !parentKeyColumns)
32160
+ return;
32161
+ return {
32162
+ ...own ?? {},
32163
+ ...parentKeys ? { parentKeys } : {},
32164
+ ...parentKeyColumns ? { parentKeyColumns } : {}
32165
+ };
32059
32166
  }
32060
- function primaryKeyColumnsOf(entry) {
32061
- const columns = entry.keyUniqueness?.parentKeyColumns;
32062
- if (!columns || typeof columns !== "object")
32167
+ function recordOf(value, of) {
32168
+ if (!value || typeof value !== "object")
32063
32169
  return;
32064
- const out = Object.fromEntries(Object.entries(columns).filter(([, v]) => typeof v === "string"));
32170
+ const out = Object.fromEntries(Object.entries(value).filter(([, v]) => typeof v === of));
32065
32171
  return Object.keys(out).length > 0 ? out : undefined;
32066
32172
  }
32173
+ function primaryKeysOf(entry) {
32174
+ return keyUniquenessOf(entry)?.parentKeys;
32175
+ }
32176
+ function primaryKeyColumnsOf(entry) {
32177
+ return keyUniquenessOf(entry)?.parentKeyColumns;
32178
+ }
32179
+ function keyUniquenessOf(entry) {
32180
+ return parseKeyUniqueness(entry.keyUniqueness);
32181
+ }
32067
32182
  function checkedKeyIs(columns, sourceID, key) {
32068
32183
  return key !== undefined && columns?.[sourceID] === key;
32069
32184
  }
32070
32185
  function rollupKeyOf(entry) {
32071
- const k = entry.keyUniqueness;
32072
- return typeof k?.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32186
+ const k = keyUniquenessOf(entry);
32187
+ return k?.keyColumn !== undefined && k.unique !== undefined ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32073
32188
  }
32074
32189
  function withEntryKeyChecks(binding, entry) {
32075
32190
  const {
@@ -32121,8 +32236,7 @@ function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, so
32121
32236
  freshnessFallback: entry.freshnessFallback,
32122
32237
  ...primaryKeys ? { primaryKeys } : {},
32123
32238
  ...primaryKeyColumns ? { primaryKeyColumns } : {},
32124
- ...rollupKey ? { rollupKey } : {},
32125
- ...entry.upstreamSchemas?.length ? { upstreamSchemas: entry.upstreamSchemas } : {}
32239
+ ...rollupKey ? { rollupKey } : {}
32126
32240
  });
32127
32241
  }
32128
32242
  }
@@ -36740,28 +36854,13 @@ function gateColumnTypesOf(reads, schemas) {
36740
36854
  }
36741
36855
  return schemas.map((s) => typesIn(reads, s ?? []));
36742
36856
  }
36743
- function gateColumnUpstreamTypesOf(reads, schemas, upstreams) {
36744
- const types = gateColumnTypesOf(reads, schemas);
36745
- return schemas.map((schema, i) => {
36746
- if (types[i] === undefined || reads === undefined)
36747
- return;
36748
- const held = new Set(reads.columns.flat());
36749
- return (schema ?? []).filter((c) => held.has(c.name)).map((c) => upstreamTypeOf(reads, c.name, upstreams[i]));
36750
- });
36751
- }
36752
- function upstreamTypeOf(reads, name, upstreams) {
36753
- const origins = reads.columns.flatMap((names, j) => names.includes(name) ? [reads.columnOrigins?.[j]] : []);
36754
- const origin = origins[0];
36755
- if (origin === undefined || origins.some((o) => o === undefined || o.connectionName !== origin.connectionName || o.table !== origin.table || o.column !== origin.column)) {
36756
- return;
36757
- }
36758
- const table = upstreams?.find((u) => u.connectionName === origin.connectionName && u.table === origin.table);
36759
- if (!table?.columns || !table.dialect)
36760
- return;
36761
- const exact = table.columns.filter((c) => c.name === origin.column);
36762
- const folded = table.columns.filter((c) => c.name.toLowerCase() === origin.column.toLowerCase());
36763
- const column = exact.length === 1 ? exact[0] : folded.length === 1 ? folded[0] : undefined;
36764
- return column ? { dialect: table.dialect, nativeType: column.nativeType } : undefined;
36857
+ function gateColumnsExactOf(reads, contracts) {
36858
+ const types = gateColumnTypesOf(reads, contracts.map((c) => c?.columns.map((col) => ({ name: col.name, type: col.nativeType }))));
36859
+ const held = new Set((reads?.columns ?? []).flat());
36860
+ return {
36861
+ types,
36862
+ exact: contracts.map((c, i) => types[i] === undefined ? undefined : (c?.columns ?? []).filter((col) => held.has(col.name)).every((col) => col.gateExact))
36863
+ };
36765
36864
  }
36766
36865
  async function gateReadsOfQuery(runnable, stored = new Set, rerooted = new Set) {
36767
36866
  try {
@@ -37161,81 +37260,17 @@ var init_served_copy_checks = __esm(() => {
37161
37260
  };
37162
37261
  });
37163
37262
 
37164
- // src/service/materialization/serve/admission_parity.ts
37165
- function readAdmissionModeFrom(read) {
37166
- modeReader = read;
37167
- }
37168
- function admissionMode() {
37169
- return modeReader();
37170
- }
37263
+ // src/service/materialization/serve/query_walks.ts
37171
37264
  function reportQueryWalk(site) {
37172
37265
  walks.set(site, (walks.get(site) ?? 0) + 1);
37173
- observer?.queryWalk?.(site);
37266
+ observer?.queryWalk(site);
37174
37267
  }
37175
37268
  function observeAdmission(o) {
37176
37269
  observer = o;
37177
37270
  }
37178
- function reportCatalogRead(site) {
37179
- observer?.catalogRead(site);
37180
- }
37181
- function reportProbeCompile(site) {
37182
- observer?.probeCompile(site);
37183
- }
37184
- function record(drift) {
37185
- const allowed = allowances[allowances.length - 1];
37186
- const kept = allowed ? { ...drift, allowed } : drift;
37187
- if (drifts.length >= MAX_KEPT)
37188
- drifts.shift();
37189
- drifts.push(kept);
37190
- observer?.drift(kept);
37191
- }
37192
- function disagree(a, b) {
37193
- return a === undefined !== (b === undefined);
37194
- }
37195
- function shadowFact(side, walked, recorded, show, tables = []) {
37196
- const old = show(walked);
37197
- const now = show(recorded);
37198
- if (old !== now)
37199
- record({ side, probe: old, lookup: now, tables });
37200
- return walked;
37201
- }
37202
- function shadowProbe(probe, lookup) {
37203
- return {
37204
- async sourceRefusal(args) {
37205
- const [old, now] = await Promise.all([
37206
- probe.sourceRefusal(args),
37207
- lookup.sourceRefusal(args).catch(threw)
37208
- ]);
37209
- if (disagree(old, now)) {
37210
- record({ side: "source", probe: old, lookup: now, tables: [] });
37211
- }
37212
- return old;
37213
- },
37214
- async storedRefusal(args) {
37215
- const [old, now] = await Promise.all([
37216
- probe.storedRefusal(args),
37217
- lookup.storedRefusal(args).catch(threw)
37218
- ]);
37219
- if (disagree(old, now)) {
37220
- record({
37221
- side: "stored",
37222
- probe: old,
37223
- lookup: now,
37224
- tables: handlesOf(args.tables)
37225
- });
37226
- }
37227
- return old;
37228
- }
37229
- };
37230
- }
37231
- function handlesOf(tables) {
37232
- return tables.flatMap((t) => typeof t.virtualHandle === "string" ? [t.virtualHandle] : []);
37233
- }
37234
- var observer, modeReader = () => "lookup", walks, drifts, MAX_KEPT = 1000, allowances, threw = (err) => `the lookup failed: ${err instanceof Error ? err.message : String(err)}`;
37235
- var init_admission_parity = __esm(() => {
37271
+ var observer, walks;
37272
+ var init_query_walks = __esm(() => {
37236
37273
  walks = new Map;
37237
- drifts = [];
37238
- allowances = [];
37239
37274
  });
37240
37275
 
37241
37276
  // src/service/materialization/serve/result_reads.ts
@@ -38153,11 +38188,14 @@ class ServedCopyServe {
38153
38188
  isCurrent(pinned = this.current()) {
38154
38189
  return this.lanes.keepsFor(0, this.freshBindings(pinned));
38155
38190
  }
38156
- rerootedSourceIDs() {
38191
+ rerootedAt(compiled, atMs) {
38192
+ return atMs === undefined ? compiled.rerooted : compiled.rerooted.filter((b) => !readsLapsedAt([b], atMs));
38193
+ }
38194
+ rerootedSourceIDs(atMs) {
38157
38195
  const compiled = this.lanes.kept(0);
38158
38196
  if (!compiled)
38159
38197
  return;
38160
- return new Set(compiled.rerooted.flatMap((b) => b.sourceIDs ?? []));
38198
+ return new Set(this.rerootedAt(compiled, atMs).flatMap((b) => b.sourceIDs ?? []));
38161
38199
  }
38162
38200
  scopeLane() {
38163
38201
  const compiled = this.lanes.kept(0);
@@ -38168,19 +38206,21 @@ class ServedCopyServe {
38168
38206
  rerooted: compiled.rerootedSourceIDs ?? new Set
38169
38207
  };
38170
38208
  }
38171
- rerootedOnDatabaseOnly() {
38209
+ rerootedOnDatabaseOnly(atMs) {
38172
38210
  const compiled = this.lanes.kept(0);
38173
38211
  if (!compiled)
38174
38212
  return;
38175
- const onStorage = new Set(compiled.rerooted.filter((b) => !isDatabase(b)).flatMap((b) => b.sourceIDs ?? []));
38176
- return new Set(compiled.rerooted.filter(isDatabase).flatMap((b) => b.sourceIDs ?? []).filter((id) => !onStorage.has(id)));
38213
+ const rerooted = this.rerootedAt(compiled, atMs);
38214
+ const onStorage = new Set(rerooted.filter((b) => !isDatabase(b)).flatMap((b) => b.sourceIDs ?? []));
38215
+ return new Set(rerooted.filter(isDatabase).flatMap((b) => b.sourceIDs ?? []).filter((id) => !onStorage.has(id)));
38177
38216
  }
38178
- servedThroughBaseSourceIDs() {
38217
+ servedThroughBaseSourceIDs(atMs) {
38179
38218
  const compiled = this.lanes.kept(0);
38180
38219
  if (!compiled?.throughBase)
38181
38220
  return new Set;
38182
- const ids = new Set(compiled.rerooted.flatMap((b) => b.sourceIDs ?? []));
38183
- const names = new Set(compiled.rerooted.map((b) => b.sourceName));
38221
+ const rerooted = this.rerootedAt(compiled, atMs);
38222
+ const ids = new Set(rerooted.flatMap((b) => b.sourceIDs ?? []));
38223
+ const names = new Set(rerooted.map((b) => b.sourceName));
38184
38224
  const declined = (id) => !!compiled.optOutIDs?.has(id) || !!compiled.unsafeIDs?.has(id);
38185
38225
  return new Set(compiled.throughBase.filter((e) => (e.chain.some((id) => ids.has(id)) || e.baseName !== undefined && names.has(e.baseName)) && !declined(e.sourceID) && !e.chain.some(declined)).map((e) => e.sourceID));
38186
38226
  }
@@ -38347,30 +38387,13 @@ class ServedCopyServe {
38347
38387
  await this.checkGateGraft(attempt);
38348
38388
  await checkOptOut(attempt);
38349
38389
  })() : checkSourceZone(attempt);
38350
- const mode = admissionMode();
38351
- if (mode === "probe")
38352
- return walk();
38353
38390
  const recorded = await this.recordedDeclines(attempt, which);
38354
- if (mode === "lookup") {
38355
- if (recorded === "unrecorded") {
38356
- reportQueryWalk("served_copy_declines");
38357
- return walk();
38358
- }
38359
- if (recorded)
38360
- attempt.decline(recorded.reason, recorded.code);
38361
- return;
38362
- }
38363
- let walked;
38364
- try {
38365
- await walk();
38366
- } catch (err) {
38367
- walked = err;
38368
- }
38369
- if (recorded !== "unrecorded") {
38370
- shadowFact("served_copy_declines", walked, recorded, (d) => d === undefined ? undefined : d instanceof LegDecline ? d.code : d instanceof Error ? `error: ${d.message}` : d.code);
38391
+ if (recorded === "unrecorded") {
38392
+ reportQueryWalk("served_copy_declines");
38393
+ return walk();
38371
38394
  }
38372
- if (walked !== undefined)
38373
- throw walked;
38395
+ if (recorded)
38396
+ attempt.decline(recorded.reason, recorded.code);
38374
38397
  }
38375
38398
  async recordedDeclines(attempt, which) {
38376
38399
  const { compiled, compiling, prepared } = attempt;
@@ -40477,7 +40500,7 @@ var init_served_copy_serve = __esm(() => {
40477
40500
  init_leg_decline();
40478
40501
  init_utils();
40479
40502
  init_served_copy_checks();
40480
- init_admission_parity();
40503
+ init_query_walks();
40481
40504
  init_chain_string_reads();
40482
40505
  NOTHING_PINNED = pin(EMPTY_SNAPSHOT, new Date(0));
40483
40506
  MISSING_FIELD_CODES = new Set([
@@ -43224,6 +43247,18 @@ var init_render_tag_targets = __esm(() => {
43224
43247
  });
43225
43248
 
43226
43249
  // src/service/connection_type.ts
43250
+ function normalizeReadableSchemas(list) {
43251
+ const names = [
43252
+ ...new Set(Array.isArray(list) ? list.filter((name) => typeof name === "string") : [])
43253
+ ].filter((name) => name !== "main").sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
43254
+ return names.length > 0 ? names : undefined;
43255
+ }
43256
+ function managedSchemas(readableSchemas) {
43257
+ return new Set([
43258
+ "main",
43259
+ ...normalizeReadableSchemas(readableSchemas) ?? []
43260
+ ]);
43261
+ }
43227
43262
  function managedOverrideOf(connection) {
43228
43263
  const name = connection.name;
43229
43264
  return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
@@ -43244,13 +43279,16 @@ function recordConnectionType(connection, type, options = {}) {
43244
43279
  if (recordedType)
43245
43280
  recorded.set(connection, recordedType);
43246
43281
  if (options.managed === true || managedOverrideOf(connection)) {
43247
- managed.add(connection);
43282
+ managed.set(connection, options.schemas ?? MAIN_ONLY);
43248
43283
  }
43249
43284
  return connection;
43250
43285
  }
43251
43286
  function isManagedConnection(connection) {
43252
43287
  return !!connection && managed.has(connection);
43253
43288
  }
43289
+ function managedSchemasOf(connection) {
43290
+ return connection ? managed.get(connection) : undefined;
43291
+ }
43254
43292
  function resolveManagedConnections(connections) {
43255
43293
  return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
43256
43294
  }
@@ -43266,10 +43304,11 @@ function resolveConnectionTypes(connections) {
43266
43304
  }
43267
43305
  return types;
43268
43306
  }
43269
- var recorded, managed, overrides, managedOverrides;
43307
+ var recorded, managed, MAIN_ONLY, overrides, managedOverrides;
43270
43308
  var init_connection_type = __esm(() => {
43271
43309
  recorded = new WeakMap;
43272
- managed = new WeakSet;
43310
+ managed = new WeakMap;
43311
+ MAIN_ONLY = managedSchemas();
43273
43312
  overrides = [];
43274
43313
  managedOverrides = [];
43275
43314
  });
@@ -45304,11 +45343,27 @@ function resolvePublisherConfigPath(serverRoot) {
45304
45343
  }
45305
45344
  return null;
45306
45345
  }
45346
+ function duckDBByteSize(size) {
45347
+ const groups = DUCKDB_BYTE_SIZE.exec(size.trim())?.groups;
45348
+ if (!groups)
45349
+ throw new Error(`Not a DuckDB size: "${size}"`);
45350
+ const unit = groups.unit.toUpperCase();
45351
+ return Number(groups.amount) * (unit.includes("I") ? 1024 : 1000) ** "BKMGT".indexOf(unit[0]);
45352
+ }
45307
45353
  function assertDuckDBResourceConfig() {
45308
45354
  const memoryLimit = getDuckDBMemoryLimit();
45309
45355
  if (memoryLimit !== undefined && !DUCKDB_BYTE_SIZE.test(memoryLimit)) {
45310
45356
  throw new Error(`Invalid value for PUBLISHER_DUCKDB_MEMORY_LIMIT: expected a size like ` + `"1GB" or "512MB" (or "off" to disable), got "${memoryLimit}"`);
45311
45357
  }
45358
+ for (const [key, variable] of [
45359
+ ["admin.memoryLimit", "PUBLISHER_ADMIN_MEMORY_LIMIT"],
45360
+ ["admin.maxTempDirectorySize", "PUBLISHER_ADMIN_MAX_TEMP_DIRECTORY_SIZE"]
45361
+ ]) {
45362
+ const size = settings.get(key);
45363
+ if (!DUCKDB_BYTE_SIZE.test(size)) {
45364
+ throw new Error(`Invalid value for ${variable}: expected a size like "1.5GB" or ` + `"6GiB", got "${size}"`);
45365
+ }
45366
+ }
45312
45367
  const rowGroupSizeBytes = getDuckLakeRowGroupSizeBytes();
45313
45368
  if (rowGroupSizeBytes !== undefined && !DUCKDB_BYTE_SIZE.test(rowGroupSizeBytes)) {
45314
45369
  throw new Error(`Invalid value for PUBLISHER_DUCKLAKE_ROW_GROUP_SIZE_BYTES: expected a ` + `size like "16MB", got "${rowGroupSizeBytes}"`);
@@ -45721,7 +45776,7 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
45721
45776
  tickIntervalMs: settings.get("materialization.schedulerIntervalMs"),
45722
45777
  maxFiresPerTick: settings.get("materialization.schedulerMaxFiresPerTick")
45723
45778
  };
45724
- }, getMaxQueryRows = () => settings.get("query.maxRows"), getMaxResponseBytes = () => settings.get("query.maxResponseBytes"), getDefaultQueryRowLimit = () => settings.get("query.defaultRowLimit"), getQueryTimeoutMs = () => settings.get("query.timeoutMs"), getMaxConcurrentQueries = () => settings.get("query.maxConcurrent"), getPostgresPoolMax = () => settings.get("postgres.poolMax"), getExtensionFetchPolicy = () => settings.get("duckdb.extensionFetchPolicy"), ALLOW_DUCKDB_SETUP_SQL_ENV = "PUBLISHER_ALLOW_DUCKDB_SETUP_SQL", isDuckdbSetupSqlAllowed = () => settings.get("allow.duckdbSetupSql"), getS3CredentialChainPolicy = () => settings.get("allow.s3CredentialChain"), getPersistStorageMode = () => settings.get("persist.storageMode"), getPersistAddressIncludesDestination = () => settings.get("persist.addressIncludesDestination"), getMaterializeEnabled = () => settings.get("materialize.enabled"), getMaterializeGatedSources = () => settings.get("materialize.gatedSources"), getAdmissionMode = () => settings.get("materialize.admissionMode"), gateSwitches = () => ({
45779
+ }, getMaxQueryRows = () => settings.get("query.maxRows"), getMaxResponseBytes = () => settings.get("query.maxResponseBytes"), getDefaultQueryRowLimit = () => settings.get("query.defaultRowLimit"), getQueryTimeoutMs = () => settings.get("query.timeoutMs"), getMaxConcurrentQueries = () => settings.get("query.maxConcurrent"), getPostgresPoolMax = () => settings.get("postgres.poolMax"), getExtensionFetchPolicy = () => settings.get("duckdb.extensionFetchPolicy"), ALLOW_DUCKDB_SETUP_SQL_ENV = "PUBLISHER_ALLOW_DUCKDB_SETUP_SQL", isDuckdbSetupSqlAllowed = () => settings.get("allow.duckdbSetupSql"), getS3CredentialChainPolicy = () => settings.get("allow.s3CredentialChain"), getPersistStorageMode = () => settings.get("persist.storageMode"), getPersistAddressIncludesDestination = () => settings.get("persist.addressIncludesDestination"), getMaterializeEnabled = () => settings.get("materialize.enabled"), getMaterializeGatedSources = () => settings.get("materialize.gatedSources"), gateSwitches = () => ({
45725
45780
  materialize: getMaterializeEnabled(),
45726
45781
  gatedSources: getMaterializeGatedSources()
45727
45782
  }), getPersistCollisionEnforce = () => settings.get("persist.collisionEnforcementEnabled"), getMcpCorsOrigins = () => {
@@ -45926,7 +45981,7 @@ var init_config2 = __esm(() => {
45926
45981
  "chartText",
45927
45982
  "value"
45928
45983
  ];
45929
- DUCKDB_BYTE_SIZE = /^(?!0+(\.0+)?\s*[A-Za-z])\d+(\.\d+)?\s*(B|KB|KIB|MB|MIB|GB|GIB|TB|TIB)$/i;
45984
+ DUCKDB_BYTE_SIZE = /^(?!0+(\.0+)?\s*[A-Za-z])(?<amount>\d+(\.\d+)?)\s*(?<unit>B|KB|KIB|MB|MIB|GB|GIB|TB|TIB)$/i;
45930
45985
  RETRIEVAL_LEAVES = REGISTRY.filter((entry) => entry.key.startsWith("retrieval.") && entry.kind !== "structured" && !entry.secret);
45931
45986
  OPENAI_COMPATIBLE_LEAVES = [
45932
45987
  "retrieval.embedding.model",
@@ -48290,6 +48345,11 @@ var init_rollup_measure_grammar = __esm(() => {
48290
48345
  };
48291
48346
  });
48292
48347
 
48348
+ // src/service/materialization/domain/rollup_measures.ts
48349
+ function rollupLabel(plan) {
48350
+ return `#(rollup) rollup of source "${plan.baseSourceName}" at ` + `(${plan.grainDimensions.join(", ")})`;
48351
+ }
48352
+
48293
48353
  // src/service/materialization/plan/rollup_plan.ts
48294
48354
  import { createHash as createHash7 } from "node:crypto";
48295
48355
  import { Annotations as Annotations8 } from "@malloydata/malloy";
@@ -49045,7 +49105,7 @@ function rollupReadsGivenRefusal(plan, source) {
49045
49105
  return {
49046
49106
  tier: "unservable",
49047
49107
  code: ROLLUP_NOT_BUILT_CODE,
49048
- message: `#(rollup) rollup of source "${plan.baseSourceName}" at ` + `(${plan.grainDimensions.join(", ")}) is not built, so its measures ` + "are served live: its rows read a given, and a table holds one " + "value's rows.",
49108
+ message: `${rollupLabel(plan)} is not built, so its measures ` + "are served live: its rows read a given, and a table holds one " + "value's rows.",
49049
49109
  sourceName: plan.baseSourceName,
49050
49110
  refused: refusalKey(source.sourceID, source.name, "reads_given", tierOf(plan.storage))
49051
49111
  };
@@ -50113,15 +50173,13 @@ function pairKeyChecks(pair, blocks, sourceID, build, connection) {
50113
50173
  ...on
50114
50174
  });
50115
50175
  });
50116
- const hops = p.hops ?? [];
50117
- const last = hops[hops.length - 1];
50118
- const leafNames = [p.join, ...hops.map((h) => h.join)];
50176
+ const leaf = pairLeafPath(p);
50119
50177
  out.push({
50120
- join: leafNames.join("."),
50121
- keyColumn: last?.key ?? p.childKey,
50122
- queryName: `${build}__pair_leaf_key__${leafNames.join("__")}`,
50123
- joinedSourceID: last?.sourceID ?? p.childSourceID,
50124
- pairLevel: leafNames.length,
50178
+ join: leaf.names.join("."),
50179
+ keyColumn: leaf.keyColumn,
50180
+ queryName: `${build}__pair_leaf_key__${leaf.names.join("__")}`,
50181
+ joinedSourceID: leaf.sourceID,
50182
+ pairLevel: leaf.names.length,
50125
50183
  recordOnly: true,
50126
50184
  ...on
50127
50185
  });
@@ -52690,15 +52748,6 @@ function recordKeyCheck(kind, outcome) {
52690
52748
  function recordIncompatibleDetected(trigger, code) {
52691
52749
  incompatibleDetectedCounter().add(1, { trigger, code });
52692
52750
  }
52693
- function recordQueryCatalogRead(site) {
52694
- queryCatalogReadCounter().add(1, { site });
52695
- }
52696
- function recordQueryProbeCompile(site) {
52697
- queryProbeCompileCounter().add(1, { site });
52698
- }
52699
- function recordAdmissionParityDrift(side, direction) {
52700
- admissionParityDriftCounter().add(1, { side, direction });
52701
- }
52702
52751
  function recordQueryWalk(site) {
52703
52752
  queryWalkCounter().add(1, { site });
52704
52753
  }
@@ -52729,13 +52778,14 @@ function recordQueryRoute(leg, outcome, reason) {
52729
52778
  function recordChainedStorageBuild(outcome) {
52730
52779
  chainedStorageBuildCounter().add(1, { outcome });
52731
52780
  }
52732
- function recordStaleUpstreamEntry(tier) {
52733
- staleUpstreamEntryCounter().add(1, { tier });
52734
- }
52735
- function recordUpstreamRecompute(reason, build, outcome) {
52736
- upstreamRecomputeCounter().add(1, { reason, build, outcome });
52781
+ function recordUpstreamReadUnchecked(build) {
52782
+ uncheckedUpstreamReadCounter().add(1, {
52783
+ reason: "reference_types_unrecorded",
52784
+ build,
52785
+ outcome: "read_unchecked"
52786
+ });
52737
52787
  }
52738
- var BUILD_DURATION_BUCKETS_MS, BUILD_READ_BYTES_BUCKETS, runCounter, runDuration, buildCounter, buildDuration, buildReadBytes, annotationFindingsCounter, incrementalStepCounter, buildPlanComputeDuration, buildPlanComputeFailedCounter, autoLoadCounter, connectionDigestSkipCounter, servedCopyBindCounter, manifestBindDegradedCounter, duplicateTargetSkipCounter, sharedAddressInstructionCounter, tableCollisionCounter, dropTablesCounter, scheduledFireCounter, queryRouteCounter, queryRouteDuration, keyCheckCounter, contractCaptureCounter, incompatibleDetectedCounter, queryCatalogReadCounter, queryProbeCompileCounter, admissionParityDriftCounter, queryWalkCounter, storageTableRetainedCounter, attributionSkippedCounter, eligibilityRefusedCounter, serveShapeTypeFallbackCounter, storedColumnTypeMismatchCounter, chainedStorageBuildCounter, upstreamRecomputeCounter, staleUpstreamEntryCounter;
52788
+ var BUILD_DURATION_BUCKETS_MS, BUILD_READ_BYTES_BUCKETS, runCounter, runDuration, buildCounter, buildDuration, buildReadBytes, annotationFindingsCounter, incrementalStepCounter, buildPlanComputeDuration, buildPlanComputeFailedCounter, autoLoadCounter, connectionDigestSkipCounter, servedCopyBindCounter, manifestBindDegradedCounter, duplicateTargetSkipCounter, sharedAddressInstructionCounter, tableCollisionCounter, dropTablesCounter, scheduledFireCounter, queryRouteCounter, queryRouteDuration, keyCheckCounter, contractCaptureCounter, incompatibleDetectedCounter, queryWalkCounter, storageTableRetainedCounter, attributionSkippedCounter, eligibilityRefusedCounter, serveShapeTypeFallbackCounter, storedColumnTypeMismatchCounter, chainedStorageBuildCounter, uncheckedUpstreamReadCounter;
52739
52789
  var init_materialization_metrics = __esm(() => {
52740
52790
  init_vocabulary();
52741
52791
  init_telemetry();
@@ -52774,9 +52824,6 @@ var init_materialization_metrics = __esm(() => {
52774
52824
  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.");
52775
52825
  contractCaptureCounter = lazyCounter("publisher_materialization_contract_capture_total", "Column contracts a build captured over the table it wrote. Labels: tier " + "('database'|'storage'), outcome ('captured'|'unread'). An unread " + "capture records no contract: the table is not served from until it " + "is rebuilt (serve verdict reason contract_missing).");
52776
52826
  incompatibleDetectedCounter = lazyCounter("publisher_materialization_incompatible_detected_total", "Bound tables a bind's catalog read, or a standalone run's read of the " + "tables it would carry, found no longer matching the column contract " + "their build recorded, so they answer live until rebuilt (a run " + "rebuilds them rather than carry them). " + "Labels: trigger ('bind'|'run'), code ('column_gone'|'column_retyped'|" + "'collation_changed'|'declared_moved'|...). A failed stored read is " + "never counted: it leaves the table unread until that read.");
52777
- queryCatalogReadCounter = lazyCounter("publisher_query_catalog_reads_total", "Catalog reads read admission made while answering a query, to judge a " + "stored answer's string comparisons. Labels: site " + "('source_probe'|'stored_probe'). Zero under lookup admission " + "(materialize.admissionMode), which reads what load, bind and build " + "recorded instead.");
52778
- queryProbeCompileCounter = lazyCounter("publisher_query_probe_compiles_total", "Compiles read admission made while answering a query, beyond the " + "query's own: a probe query or the query's SQL, to read a source's " + "collation. Labels: site ('source_probe'|'stored_probe'). Zero under " + "lookup admission.");
52779
- admissionParityDriftCounter = lazyCounter("publisher_admission_parity_drift_total", "Shadow admission's disagreements (materialize.admissionMode=shadow): a " + "query whose probe and lookup judged a stored answer's string " + "comparisons differently, or whose walk and recorded fact differ. The " + "probe or walk decided. Labels: side ('source'|'stored'|" + "'served_copy_declines'|'scope'|'rollup_candidates'|'path_chain'|'gate_exact'), direction ('probe_refuses'|" + "'lookup_refuses'|'differs').");
52780
52827
  queryWalkCounter = lazyCounter("publisher_query_walks_total", "IR walks a query made for a fact the served copy's compile or the bind " + "records, because the record did not cover the query (an inline " + "extend, an unrecorded lane or stored set). Labels: site " + "('served_copy_declines'|'scope'|'rollup_candidates'|'path_chain').");
52781
52828
  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.");
52782
52829
  attributionSkippedCounter = lazyCounter("publisher_storage_build_attribution_skipped_total", "storage= builds whose warehouse read went out UNATTRIBUTED while tagging was " + "on. Label: reason ('job_listing_unavailable'|'tag_failed'|" + "'read_row_not_found'|'read_row_ambiguous'|'cost_query_failed'). " + "The read still ran and the " + "build still succeeded — what was lost is the label in the customer's own " + "query history, and the cost on this side. Without this an operator who " + "turns tagging on and sees nothing has a single log line to go on.");
@@ -52784,8 +52831,7 @@ var init_materialization_metrics = __esm(() => {
52784
52831
  serveShapeTypeFallbackCounter = lazyCounter("publisher_storage_serve_shape_type_fallback_total", "Captured DuckDB column types mapped to json in a stored table's declared " + "type (type fidelity loss). " + "Label: kind ('array'|'unrecognized').");
52785
52832
  storedColumnTypeMismatchCounter = lazyCounter("publisher_storage_column_type_mismatch_total", "Stored columns whose DuckDB type does not serve as the type Malloy " + "declares for them. Labels: stage ('build' = " + "found after a storage build; 'serve' = found when a model's bindings " + "are set, then cast on read or left out of the served copy so queries " + "reading it are answered live), declared (the Malloy type).");
52786
52833
  chainedStorageBuildCounter = lazyCounter("publisher_storage_chained_build_total", "Chained storage= source builds (a source reading a storage-materialized " + "upstream). Label: outcome ('parent_reuse'|'strict_refused'|" + "'infra_failure'; 'inline_fallback' and 'strict_shape_fallback' are " + "retained but no longer produced: no build recomputes its upstreams " + "from raw).");
52787
- upstreamRecomputeCounter = lazyCounter("publisher_materialization_upstream_recompute_total", "Builds that could not check a stored upstream's database table against " + "the column types its build recorded. Labels: reason ('moved', a " + "column retyped or dropped since its build; 'unreadable', its columns " + "could not be read; 'types_unrecorded', its build recorded no column " + "types; 'reference_types_unrecorded', a host's reference carried no " + "nativeSchema (a storage= one, no contract); 'persisted_result', a persisted view or query, which " + "builds from its source's definition by design), build ('chained' for a build over the upstream, " + "'rollup' for a database rollup over its stored base), and outcome " + "('recomputed' from its definition, or 'read_unchecked': a strict " + "host-instructed build read the referenced table as before).");
52788
- staleUpstreamEntryCounter = lazyCounter("publisher_materialization_stale_upstream_entry_total", "Builds that could not use an upstream's manifest entry because it is at a " + "different tier than the upstream is declared on now (a source moved to " + "or from storage= keeps its content address). The build " + "recomputes that upstream from raw instead, which reads the warehouse. " + "Label: tier ('database'|'storage'), the tier of the build that " + "recomputed.");
52834
+ uncheckedUpstreamReadCounter = lazyCounter("publisher_materialization_upstream_recompute_total", "Builds that read a stored upstream's database table unchecked: a host's " + "reference carried no nativeSchema (a storage= one, no contract), so the " + "table's columns could not be " + "checked against its build. No build recomputes an upstream, so this is " + "the only reason and outcome produced. Labels: reason " + "('reference_types_unrecorded'), build ('chained' for a build over the " + "upstream, 'rollup' for a database rollup over its stored base), and " + "outcome ('read_unchecked'). The reasons 'moved', 'unreadable', " + "'types_unrecorded' and 'persisted_result' and the outcome 'recomputed' " + "are retired: such a build is refused.");
52789
52835
  });
52790
52836
 
52791
52837
  // src/service/materialization/plan/incremental_declaration.ts
@@ -54730,16 +54776,12 @@ async function compileOne(args) {
54730
54776
  name: args.plan.buildSourceName
54731
54777
  },
54732
54778
  destination: { name: args.destination, schema: "main" },
54733
- upstreams: args.upstreams.map((u, i) => ({
54734
- entry: {
54735
- sourceEntityId: standIns[i].handle,
54736
- sourceName: u.name,
54737
- physicalTableName: standIns[i].handle,
54738
- connectionName: args.destination,
54739
- storageDestinationName: args.destination,
54740
- schema: standIns[i].columns.map((c) => ({ ...c }))
54741
- },
54742
- names: { [u.name]: [u.sourceID] }
54779
+ upstreams: args.upstreams.map((u, i) => standInUpstream({
54780
+ handle: standIns[i].handle,
54781
+ name: u.name,
54782
+ sourceID: u.sourceID,
54783
+ destination: args.destination,
54784
+ columns: standIns[i].columns
54743
54785
  })),
54744
54786
  view: {
54745
54787
  authorName: args.authorName,
@@ -54778,6 +54820,19 @@ async function compileOne(args) {
54778
54820
  return why(`it does not compile there (${error instanceof Error ? error.message : String(error)})`);
54779
54821
  }
54780
54822
  }
54823
+ function standInUpstream(u) {
54824
+ return {
54825
+ entry: {
54826
+ sourceEntityId: u.handle,
54827
+ sourceName: u.name,
54828
+ physicalTableName: u.handle,
54829
+ connectionName: u.destination,
54830
+ storageDestinationName: u.destination,
54831
+ schema: u.columns.map((c) => ({ ...c }))
54832
+ },
54833
+ names: { [u.name]: [u.sourceID] }
54834
+ };
54835
+ }
54781
54836
  function storedColumnsOf2(def) {
54782
54837
  const d = def;
54783
54838
  if (d?.type !== "query_source" || !Array.isArray(d.fields))
@@ -55559,7 +55614,7 @@ function rollupBuildCopies(plans, text, modelFile) {
55559
55614
  plan,
55560
55615
  tier: "unservable",
55561
55616
  code: ROLLUP_NOT_BUILT_CODE,
55562
- message: `#(rollup) rollup of source "${plan.baseSourceName}" at (${plan.grainDimensions.join(", ")}) is not built, so its measures are served live: ${made.reason}.`,
55617
+ message: `${rollupLabel(plan)} is not built, so its measures are served live: ${made.reason}.`,
55563
55618
  sourceName: plan.baseSourceName,
55564
55619
  refused: measureRefusalKey(plan.baseSourceID, plan.baseDeclaredName, undefined, plan.readTimeTerms?.length ? "reads_given" : "hidden_field", { grain: plan.grainDimensions, storage: plan.storage })
55565
55620
  });
@@ -55598,7 +55653,7 @@ function strictRollupRefusals(plans, modelDef) {
55598
55653
  plan,
55599
55654
  tier: "unservable",
55600
55655
  code: ROLLUP_NOT_BUILT_CODE,
55601
- message: `#(rollup) rollup of source "${plan.baseSourceName}" at (${plan.grainDimensions.join(", ")}) is not built, so its measures are served live: ${why}.`,
55656
+ message: `${rollupLabel(plan)} is not built, so its measures are served live: ${why}.`,
55602
55657
  sourceName: plan.baseSourceName,
55603
55658
  refused: measureRefusalKey(plan.baseSourceID, plan.baseDeclaredName, undefined, reason, { grain: plan.grainDimensions, storage: plan.storage })
55604
55659
  });
@@ -56388,12 +56443,9 @@ function pairParentUnusable(plan, boundContract) {
56388
56443
  const contract = boundContract(over.sourceID, tier === "same" ? plan.persist.storage : undefined);
56389
56444
  if (!contract)
56390
56445
  return;
56391
- const unpassed = leafKeys.filter((k) => !keyCheckPassed(contract, k));
56392
- if (unpassed.length === 0)
56446
+ const what = pairLeafCheckFailure(contract, leafKeys);
56447
+ if (what === undefined)
56393
56448
  return;
56394
- const failed = unpassed.filter((k) => keyCheckFailed(contract, k));
56395
- const shown = (keys) => keys.map((k) => `'${k.replace(/^leaf:/, "")}'`).join(", ");
56396
- const what = failed.length > 0 ? `found the key ${shown(failed)} held more than once or NULL` : `recorded no result for the key ${shown(unpassed)}`;
56397
56449
  return `it extends '${over.sourceName}', whose pair table it is built over ` + `with its join put back, and the leaf key check of its inlined ` + `join_many, which that build relies on, ${what} when the table was ` + `built; it builds once the parent's table records the check passed`;
56398
56450
  }
56399
56451
  async function authorSourceGate(sourceID, authorDef, args) {
@@ -56512,22 +56564,17 @@ function storedBaseDecline(args, source, plan, storedBase, destination) {
56512
56564
  if (columns === undefined) {
56513
56565
  return `${base} holds no columns a stored table can stand in for`;
56514
56566
  }
56515
- const handle = "publisher_stand_in_base";
56516
56567
  const text = args.chainBuildText({
56517
56568
  downstream: { sourceID: source.sourceID, name: source.name },
56518
56569
  destination: { name: destination, schema: "main" },
56519
56570
  upstreams: [
56520
- {
56521
- entry: {
56522
- sourceEntityId: handle,
56523
- sourceName: plan.baseSourceName,
56524
- physicalTableName: handle,
56525
- connectionName: destination,
56526
- storageDestinationName: destination,
56527
- schema: columns.map((c) => ({ ...c }))
56528
- },
56529
- names: { [plan.baseSourceName]: [storedBase.baseSourceID] }
56530
- }
56571
+ standInUpstream({
56572
+ handle: "publisher_stand_in_base",
56573
+ name: plan.baseSourceName,
56574
+ sourceID: storedBase.baseSourceID,
56575
+ destination,
56576
+ columns
56577
+ })
56531
56578
  ],
56532
56579
  rollup: {
56533
56580
  baseSourceID: storedBase.baseSourceID,
@@ -58390,7 +58437,10 @@ function buildWorkerMalloyConfig(job, refresh) {
58390
58437
  };
58391
58438
  port.postMessage(req);
58392
58439
  });
58393
- const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, { managed: response.metadata.managed === true });
58440
+ const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, response.metadata.managedSchemas ? {
58441
+ managed: true,
58442
+ schemas: new Set(response.metadata.managedSchemas)
58443
+ } : {});
58394
58444
  proxies.set(effectiveName, proxy);
58395
58445
  inflight.delete(effectiveName);
58396
58446
  return proxy;