@malloy-publisher/server 0.17.3 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/admin-api-doc.yaml +757 -22
  2. package/dist/app/api-doc.yaml +160 -28
  3. package/dist/app/assets/{EnvironmentPage-Cpetyfj1.js → EnvironmentPage-CsFUI8IX.js} +1 -1
  4. package/dist/app/assets/{HomePage-RlrpQRV8.js → HomePage-B_FVtnN-.js} +1 -1
  5. package/dist/app/assets/{MainPage-C1559_mQ.js → MainPage-wFF9nPEr.js} +1 -1
  6. package/dist/app/assets/{ModelPage-D8T03Bd7.js → ModelPage-CxenqDcz.js} +2 -2
  7. package/dist/app/assets/PackagePage-dcF6vrvw.js +1 -0
  8. package/dist/app/assets/PackageSplatRoute-CASBZk0k.js +2 -0
  9. package/dist/app/assets/{RenderedResult-Cm0Wwtek.es-CfBPkvGU.js → RenderedResult--fYcsY1h.es-DzOt5Lwv.js} +3 -3
  10. package/dist/app/assets/{RouteError-DRuMstfb.js → RouteError-CUIolYwb.js} +1 -1
  11. package/dist/app/assets/{ThemeEditorPage-ss_tmVWo.js → ThemeEditorPage-DgU2YYq6.js} +1 -1
  12. package/dist/app/assets/{ToggleButtonGroup-DA9EfQQB.js → ToggleButtonGroup-Dmr-hVlD.js} +1 -1
  13. package/dist/app/assets/{documentRoutes-_ma0jaCp.js → documentRoutes-Drv-WDwO.js} +1 -1
  14. package/dist/app/assets/{editPageMounted-DxNTqmFg.js → editPageMounted-C5yJiIVi.js} +2 -2
  15. package/dist/app/assets/{index-w1w5RvZI.js → index-BIoSdsU9.js} +1 -1
  16. package/dist/app/assets/{index-BL_7q21Q.js → index-BSyL0zds.js} +97 -97
  17. package/dist/app/assets/{index-BZA1HAyp.js → index-Dtw4eTxH.js} +1 -1
  18. package/dist/app/assets/{index-DrkXqbpl.js → index-DxF3kMLJ.js} +1 -1
  19. package/dist/app/assets/{index.es-XV_AUlWO.js → index.es-CX9m4CBD.js} +10 -10
  20. package/dist/app/assets/usePackageLinkNavigate-qNjcXPcY.js +1 -0
  21. package/dist/app/assets/{usePackageRoute-ev5b1KRn.js → usePackageRoute-wJGaZEiY.js} +1 -1
  22. package/dist/app/index.html +1 -1
  23. package/dist/instrumentation.mjs +31 -17
  24. package/dist/package_load_worker.mjs +528 -377
  25. package/dist/runtime/publisher.colorScheme.spec.ts +167 -0
  26. package/dist/runtime/publisher.js +173 -3
  27. package/dist/runtime/publisher_embed.spec.ts +108 -0
  28. package/dist/server.mjs +10361 -4009
  29. package/package.json +2 -1
  30. package/dist/app/assets/PackagePage-BIl1r9eP.js +0 -1
  31. package/dist/app/assets/PackageSplatRoute-DJlJXk6p.js +0 -2
  32. 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({
@@ -849,7 +979,7 @@ var init_launch = __esm(() => {
849
979
  default: false,
850
980
  kind: "launch",
851
981
  description: "Wipe persisted storage and re-sync it from the config.",
852
- notes: "Set to `true` (or pass `--init`) to **wipe persisted storage** (`publisher_data/`) and re-sync it from the config on boot. A first boot with empty storage loads the config automatically, so you only need this to reset state or pick up config changes. Also exposed as the `start:init` / `start:dev:init` scripts.",
982
+ notes: "Set to `true` (or pass `--init`) to **wipe persisted storage** (`publisher_data/`) and re-sync it from the config on boot. A first boot with empty storage loads the config automatically, so you only need this to reset state or pick up config changes. The search index (stored value reads, embeddings and LLM output) is kept, since each entry is reused only while what it was built from is unchanged; the rows of a package the config no longer lists are deleted. Also exposed as the `start:init` / `start:dev:init` scripts.",
853
983
  shortFlags: ["--init"],
854
984
  aliases: {
855
985
  env: ["INITIALIZE_STORAGE"],
@@ -1103,7 +1233,7 @@ var init_provider_names = __esm(() => {
1103
1233
  var EGRESS_PRESETS, DEFAULT_LLM_TIMEOUT_MS = 30000, DEFAULT_LLM_CONCURRENCY = 4, DEFAULT_LLM_MAX_CALLS_PER_SYNC = 300, DEFAULT_LLM_MAX_CALLS_PER_REQUEST = 20, DIMENSION_VALUE_DEFAULTS;
1104
1234
  var init_defaults = __esm(() => {
1105
1235
  EGRESS_PRESETS = ["default", "full"];
1106
- DIMENSION_VALUE_DEFAULTS = { enabled: true };
1236
+ DIMENSION_VALUE_DEFAULTS = { enabled: true, givens: {} };
1107
1237
  });
1108
1238
 
1109
1239
  // src/settings/registry/retrieval.ts
@@ -1118,7 +1248,7 @@ var init_retrieval = __esm(() => {
1118
1248
  key: "retrieval",
1119
1249
  type: structured(),
1120
1250
  kind: "structured",
1121
- description: "Semantic retrieval: indexing limits, the LLM, the embedding provider and egress.",
1251
+ description: "Semantic retrieval: indexing limits, the LLM, the embedding provider and value search.",
1122
1252
  aliases: { file: ["retrieval"] }
1123
1253
  }),
1124
1254
  setting({
@@ -1219,9 +1349,9 @@ var init_retrieval = __esm(() => {
1219
1349
  setting({
1220
1350
  key: "retrieval.egress.preset",
1221
1351
  type: oneOf(EGRESS_PRESETS),
1222
- default: "default",
1223
- description: "What may be sent to the LLM: default (names, doc text, schema context) or full (also code and dimension values).",
1224
- notes: "`default` sends entity names, doc text (`#(doc)`, `#\"`, and the database's descriptions on a connection with `dbmeta` on) and schema context. `full` also sends code and dimension values. Access predicates (`#(access_filter)`, `#(authorize)`) never leave, whatever this says.",
1352
+ description: "No longer read: #(index) alone decides whether a dimension's values reach the embedding provider and LLM. Setting it logs a startup warning.",
1353
+ notes: "Retired. An earlier release sent `#(index)` values to the embedding provider and the LLM only under `full`. Now the `#(index)` tag decides, as it does on a hosted index. To keep values on the machine, leave `EMBEDDING_API_KEY` unset, set `retrieval.fcj.valueEmbeddings` to `false` in the package's `publisher.json`, or set `retrieval.dimensionValues.enabled` to `false`. Access predicates (`#(access_filter)`, `#(authorize)`) never leave.",
1354
+ defaultText: "_ignored_",
1225
1355
  aliases: { file: ["retrieval.egress.preset"] }
1226
1356
  }),
1227
1357
  setting({
@@ -1234,6 +1364,15 @@ var init_retrieval = __esm(() => {
1234
1364
  today: { file: "json-boolean" }
1235
1365
  }
1236
1366
  }),
1367
+ setting({
1368
+ key: "retrieval.dimensionValues.givens",
1369
+ type: structured(),
1370
+ kind: "structured",
1371
+ description: "Local development: per package, the givens the value index reads with, so a source gated by `column = $GIVEN` is indexed for the listed values only.",
1372
+ notes: 'An object of packages, each an object of givens, each one value or a list: `{ "<package>": { "REPORT_ID": [123, 456] } }`. Each `#(index)` dimension is read once per combination of the listed values (at most 50), through its gate. A source gated by `column = $GIVEN` is skipped unless its given is listed here. Never published with a package, and not a way to limit what hosted Credible indexes. See "Dimension value search" below.',
1373
+ defaultText: "_unset_ (gated sources skipped)",
1374
+ aliases: { file: ["retrieval.dimensionValues.givens"] }
1375
+ }),
1237
1376
  setting({
1238
1377
  key: "retrieval.embedding.apiKey",
1239
1378
  type: string(),
@@ -1550,15 +1689,6 @@ var init_storage = __esm(() => {
1550
1689
  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
1690
  aliases: { env: ["PUBLISHER_MATERIALIZE_GATED_SOURCES"] }
1552
1691
  }),
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
1692
  setting({
1563
1693
  key: "persist.collisionEnforcementEnabled",
1564
1694
  type: boolean(),
@@ -12675,7 +12805,7 @@ function errorMapping(error) {
12675
12805
  function errorReason(error) {
12676
12806
  return resolve(errorMapping(error).reason, error);
12677
12807
  }
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;
12808
+ 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
12809
  var init_errors2 = __esm(() => {
12680
12810
  init_constants();
12681
12811
  init_logger();
@@ -13051,6 +13181,7 @@ var init_errors2 = __esm(() => {
13051
13181
  }
13052
13182
  reason;
13053
13183
  runFailures;
13184
+ runRefused;
13054
13185
  constructor(error) {
13055
13186
  super(error.message);
13056
13187
  this.name = "MaterializationEligibilityError";
@@ -13233,6 +13364,20 @@ var init_errors2 = __esm(() => {
13233
13364
  this.name = "WriteRolledBackError";
13234
13365
  }
13235
13366
  };
13367
+ ManifestBindFailedError = class ManifestBindFailedError extends Error {
13368
+ applied;
13369
+ problem;
13370
+ get kind() {
13371
+ return "manifest_bind_failed";
13372
+ }
13373
+ constructor(manifestLocation, cause, applied, problem) {
13374
+ const detail = cause instanceof Error ? cause.message : String(cause);
13375
+ super(`The build manifest ${manifestLocation} could not be bound ` + `(${detail}), so it was not applied: the package serves what ` + `it served before.`, { cause });
13376
+ this.applied = applied;
13377
+ this.problem = problem;
13378
+ this.name = "ManifestBindFailedError";
13379
+ }
13380
+ };
13236
13381
  WriteRollbackFailedError = class WriteRollbackFailedError extends Error {
13237
13382
  get kind() {
13238
13383
  return "write_rollback_failed";
@@ -13370,6 +13515,7 @@ var init_errors2 = __esm(() => {
13370
13515
  write_conflict: WriteConflictError,
13371
13516
  installed_from_location: InstalledFromLocationError,
13372
13517
  write_rolled_back: WriteRolledBackError,
13518
+ manifest_bind_failed: ManifestBindFailedError,
13373
13519
  write_rollback_failed: WriteRollbackFailedError,
13374
13520
  connection_save: ConnectionSaveError,
13375
13521
  write_verify: WriteVerifyError,
@@ -13690,6 +13836,11 @@ var init_errors2 = __esm(() => {
13690
13836
  write_rollback_failed: { status: 500, mcp: { advice: "internal" } },
13691
13837
  connection_save: { status: 500, mcp: { advice: "internal" } },
13692
13838
  write_rolled_back: { status: 500, mcp: { advice: "internal" } },
13839
+ manifest_bind_failed: {
13840
+ status: (error) => error.problem === "not_found" ? 400 : error.problem === "invalid" ? 422 : 500,
13841
+ reason: (error) => error.problem === "not_found" ? "MANIFEST_NOT_FOUND" : error.problem === "invalid" ? "MANIFEST_INVALID" : "MANIFEST_BIND_FAILED",
13842
+ mcp: { advice: "internal" }
13843
+ },
13693
13844
  service_unavailable: BACK_PRESSURE,
13694
13845
  package_admission_refused: BACK_PRESSURE,
13695
13846
  dry_run_capacity: BACK_PRESSURE,
@@ -13805,94 +13956,6 @@ function notePositionKey(at) {
13805
13956
  }
13806
13957
  var init_annotations = () => {};
13807
13958
 
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
13959
  // src/service/motly.ts
13897
13960
  import { Annotations as Annotations2 } from "@malloydata/malloy";
13898
13961
  import { parseAnnotation } from "@malloydata/malloy-tag";
@@ -30237,23 +30300,6 @@ function serveTypePlan(mismatches, options = {}) {
30237
30300
  }
30238
30301
  return { casts, unservable };
30239
30302
  }
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
30303
  function storedColumnReadPlan(schema, declared, options = {}) {
30258
30304
  const lossy = [];
30259
30305
  if (options.ducklake) {
@@ -31538,7 +31584,7 @@ function gateColumnsExact(t) {
31538
31584
  }
31539
31585
  if (t.gateColumnTypes === undefined)
31540
31586
  return t.tier === "database";
31541
- return t.gateColumnTypes.every((type, i) => gateColumnTypeExact(type, t.gateColumnUpstreamTypes?.[i]));
31587
+ return t.gateColumnTypes.every((type) => gateColumnTypeExact(type, undefined));
31542
31588
  }
31543
31589
  function g3Table(t) {
31544
31590
  return t.tier === "database" || t.ownGateKept === true || t.holdsOnlyUngatedRows === true;
@@ -31597,30 +31643,66 @@ import { createHash } from "crypto";
31597
31643
  function contractKeyName(level, subject, keyColumn) {
31598
31644
  return `${level}:${subject ? `${subject}.` : ""}${keyColumn}`;
31599
31645
  }
31600
- function keyUniquenessOfContract(contract, sources) {
31646
+ function contractKeyWithoutLevel(name, level) {
31647
+ const prefix = `${level}:`;
31648
+ return name.startsWith(prefix) ? name.slice(prefix.length) : undefined;
31649
+ }
31650
+ function keyUniquenessOfContract(contract, sources, leaves = []) {
31601
31651
  const keys = parseContract(contract)?.keys;
31602
31652
  if (!keys)
31603
31653
  return;
31604
- const own = Object.entries(keys).find(([name, check]) => check.level === "rollup" && name.startsWith("rollup:"));
31654
+ const own = Object.entries(keys).find(([name, check]) => check.level === "rollup" && contractKeyWithoutLevel(name, "rollup") !== undefined);
31605
31655
  const parentKeys = {};
31606
31656
  const parentKeyColumns = {};
31657
+ const read = (level, subject, source) => {
31658
+ const check = keys[contractKeyName(level, subject, source.primaryKey)];
31659
+ if (check?.level !== level)
31660
+ return;
31661
+ parentKeys[source.sourceID] = (parentKeys[source.sourceID] ?? true) && passed(check);
31662
+ parentKeyColumns[source.sourceID] = source.primaryKey;
31663
+ };
31607
31664
  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
- }
31665
+ read("parent", s.relativeID, s);
31666
+ read("stored", s.relativeID, s);
31667
+ }
31668
+ const bySourceID = new Map(sources.map((s) => [s.sourceID, s]));
31669
+ for (const leaf of leaves) {
31670
+ const source = bySourceID.get(leaf.sourceID);
31671
+ if (source)
31672
+ read("leaf", leaf.joinPath, source);
31615
31673
  }
31616
31674
  const anyParent = Object.keys(parentKeys).length > 0;
31617
31675
  if (!own && !anyParent)
31618
31676
  return;
31619
31677
  return {
31620
- ...own ? { keyColumn: own[0].slice("rollup:".length), unique: own[1].unique } : {},
31678
+ ...own ? {
31679
+ keyColumn: contractKeyWithoutLevel(own[0], "rollup"),
31680
+ unique: passed(own[1])
31681
+ } : {},
31621
31682
  ...anyParent ? { parentKeys, parentKeyColumns } : {}
31622
31683
  };
31623
31684
  }
31685
+ function passed(check) {
31686
+ return check.unique && check.unverified !== true;
31687
+ }
31688
+ function contractWithoutPassedKeys(raw) {
31689
+ let value = raw;
31690
+ if (typeof value === "string") {
31691
+ try {
31692
+ value = JSON.parse(value);
31693
+ } catch {
31694
+ return raw;
31695
+ }
31696
+ }
31697
+ if (!isRecord(value) || !isRecord(value.keys))
31698
+ return raw;
31699
+ const all = Object.entries(value.keys);
31700
+ const kept = all.filter(([, check]) => !(isRecord(check) && check.unique === true && check.unverified !== true));
31701
+ if (kept.length === all.length)
31702
+ return raw;
31703
+ const { keys: _dropped, ...rest } = value;
31704
+ return kept.length > 0 ? { ...rest, keys: Object.fromEntries(kept) } : rest;
31705
+ }
31624
31706
  function isRecord(v) {
31625
31707
  return typeof v === "object" && v !== null && !Array.isArray(v);
31626
31708
  }
@@ -31660,7 +31742,8 @@ function parseContract(raw) {
31660
31742
  keys[column] = {
31661
31743
  unique: check.unique,
31662
31744
  ...typeof check.level === "string" ? { level: check.level } : {},
31663
- ...check.unverified === true ? { unverified: true } : {}
31745
+ ...check.unverified === true ? { unverified: true } : {},
31746
+ ...check.unverified === true && check.rebuiltToVerify === true ? { rebuiltToVerify: true } : {}
31664
31747
  };
31665
31748
  }
31666
31749
  }
@@ -31673,6 +31756,10 @@ function parseContract(raw) {
31673
31756
  ...Object.keys(keys).length > 0 ? { keys } : {}
31674
31757
  };
31675
31758
  }
31759
+ function servableContract(raw) {
31760
+ const contract = parseContract(raw);
31761
+ return contract && contract.columns.length > 0 ? contract : undefined;
31762
+ }
31676
31763
  function contractColumn(contract, name) {
31677
31764
  const found = columnNamed(contract.columns, name);
31678
31765
  return found ?? { name, compare: "none", gateExact: false };
@@ -31697,12 +31784,20 @@ function contractDigest(contract) {
31697
31784
  }
31698
31785
  function keyCheckPassed(contract, key) {
31699
31786
  const check = contract?.keys?.[key];
31700
- return check?.unique === true && check.unverified !== true;
31787
+ return check !== undefined && passed(check);
31701
31788
  }
31702
31789
  function keyCheckFailed(contract, key) {
31703
31790
  const check = contract?.keys?.[key];
31704
31791
  return check?.unique === false && check.unverified !== true;
31705
31792
  }
31793
+ function pairLeafCheckFailure(contract, leafKeys) {
31794
+ const failed = leafKeys.filter((k) => keyCheckFailed(contract, k));
31795
+ const unrecorded = leafKeys.filter((k) => !keyCheckPassed(contract, k) && !keyCheckFailed(contract, k));
31796
+ if (failed.length === 0 && unrecorded.length === 0)
31797
+ return;
31798
+ const named = (ks) => ks.map((k) => `'${contractKeyWithoutLevel(k, "leaf") ?? k}'`).join(", ");
31799
+ return failed.length > 0 ? `found the key ${named(failed)} held more than once or NULL` : `recorded no result for the key ${named(unrecorded)}`;
31800
+ }
31706
31801
  function weakerCompare(a, b) {
31707
31802
  return COMPARE_RANK[a] <= COMPARE_RANK[b] ? a : b;
31708
31803
  }
@@ -31753,7 +31848,9 @@ function columnCompare(args, isString, collation, name) {
31753
31848
  }
31754
31849
  if (args.stackedOn !== undefined)
31755
31850
  return args.stackedOn;
31756
- const live = args.live?.get(name);
31851
+ return liveCompare(args.live?.get(name));
31852
+ }
31853
+ function liveCompare(live) {
31757
31854
  return live === "binary" ? "exact" : live === "deterministic" ? "equality" : "none";
31758
31855
  }
31759
31856
  function weakestStringCompare(upstreams) {
@@ -31858,15 +31955,30 @@ function originOfTable(kind, sourceID) {
31858
31955
  return "persist";
31859
31956
  }
31860
31957
  }
31958
+ function pairLeafPath(p) {
31959
+ const hops = p.hops ?? [];
31960
+ const last = hops[hops.length - 1];
31961
+ return {
31962
+ names: [p.join, ...hops.map((h) => h.join)],
31963
+ keyColumn: last?.key ?? p.childKey,
31964
+ sourceID: last?.sourceID ?? p.childSourceID
31965
+ };
31966
+ }
31861
31967
  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);
31968
+ return pairPathsOf(plan).map((p) => {
31969
+ const leaf = pairLeafPath(p);
31970
+ return contractKeyName("leaf", leaf.names.join("."), leaf.keyColumn);
31971
+ });
31972
+ }
31973
+ function pairLeavesOf(plan) {
31974
+ return pairPathsOf(plan).map((p) => {
31975
+ const leaf = pairLeafPath(p);
31976
+ return { joinPath: leaf.names.join("."), sourceID: leaf.sourceID };
31868
31977
  });
31869
31978
  }
31979
+ function pairPathsOf(plan) {
31980
+ return plan.pairBlocks?.blocks ?? (plan.pair ? [plan.pair] : []);
31981
+ }
31870
31982
  function materializeKindOf(plan) {
31871
31983
  return plan.pair ? "pair" : "materialize";
31872
31984
  }
@@ -32050,26 +32162,42 @@ function bindingServesModelSource(binding, contents) {
32050
32162
  return true;
32051
32163
  return binding.sourceIDs.includes(sourceID);
32052
32164
  }
32053
- function primaryKeysOf(entry) {
32054
- const keys = entry.keyUniqueness?.parentKeys;
32055
- if (!keys || typeof keys !== "object")
32165
+ function parseKeyUniqueness(raw) {
32166
+ if (!raw || typeof raw !== "object")
32056
32167
  return;
32057
- const out = Object.fromEntries(Object.entries(keys).filter(([, v]) => typeof v === "boolean"));
32058
- return Object.keys(out).length > 0 ? out : undefined;
32168
+ const k = raw;
32169
+ const own = typeof k.keyColumn === "string" && typeof k.unique === "boolean" ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32170
+ const parentKeys = recordOf(k.parentKeys, "boolean");
32171
+ const parentKeyColumns = recordOf(k.parentKeyColumns, "string");
32172
+ if (!own && !parentKeys && !parentKeyColumns)
32173
+ return;
32174
+ return {
32175
+ ...own ?? {},
32176
+ ...parentKeys ? { parentKeys } : {},
32177
+ ...parentKeyColumns ? { parentKeyColumns } : {}
32178
+ };
32059
32179
  }
32060
- function primaryKeyColumnsOf(entry) {
32061
- const columns = entry.keyUniqueness?.parentKeyColumns;
32062
- if (!columns || typeof columns !== "object")
32180
+ function recordOf(value, of) {
32181
+ if (!value || typeof value !== "object")
32063
32182
  return;
32064
- const out = Object.fromEntries(Object.entries(columns).filter(([, v]) => typeof v === "string"));
32183
+ const out = Object.fromEntries(Object.entries(value).filter(([, v]) => typeof v === of));
32065
32184
  return Object.keys(out).length > 0 ? out : undefined;
32066
32185
  }
32186
+ function primaryKeysOf(entry) {
32187
+ return keyUniquenessOf(entry)?.parentKeys;
32188
+ }
32189
+ function primaryKeyColumnsOf(entry) {
32190
+ return keyUniquenessOf(entry)?.parentKeyColumns;
32191
+ }
32192
+ function keyUniquenessOf(entry) {
32193
+ return parseKeyUniqueness(entry.keyUniqueness);
32194
+ }
32067
32195
  function checkedKeyIs(columns, sourceID, key) {
32068
32196
  return key !== undefined && columns?.[sourceID] === key;
32069
32197
  }
32070
32198
  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;
32199
+ const k = keyUniquenessOf(entry);
32200
+ return k?.keyColumn !== undefined && k.unique !== undefined ? { keyColumn: k.keyColumn, unique: k.unique } : undefined;
32073
32201
  }
32074
32202
  function withEntryKeyChecks(binding, entry) {
32075
32203
  const {
@@ -32121,8 +32249,7 @@ function deriveServeBindings(entries, aliasesBySourceName, destinationSchema, so
32121
32249
  freshnessFallback: entry.freshnessFallback,
32122
32250
  ...primaryKeys ? { primaryKeys } : {},
32123
32251
  ...primaryKeyColumns ? { primaryKeyColumns } : {},
32124
- ...rollupKey ? { rollupKey } : {},
32125
- ...entry.upstreamSchemas?.length ? { upstreamSchemas: entry.upstreamSchemas } : {}
32252
+ ...rollupKey ? { rollupKey } : {}
32126
32253
  });
32127
32254
  }
32128
32255
  }
@@ -36740,28 +36867,13 @@ function gateColumnTypesOf(reads, schemas) {
36740
36867
  }
36741
36868
  return schemas.map((s) => typesIn(reads, s ?? []));
36742
36869
  }
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;
36870
+ function gateColumnsExactOf(reads, contracts) {
36871
+ const types = gateColumnTypesOf(reads, contracts.map((c) => c?.columns.map((col) => ({ name: col.name, type: col.nativeType }))));
36872
+ const held = new Set((reads?.columns ?? []).flat());
36873
+ return {
36874
+ types,
36875
+ exact: contracts.map((c, i) => types[i] === undefined ? undefined : (c?.columns ?? []).filter((col) => held.has(col.name)).every((col) => col.gateExact))
36876
+ };
36765
36877
  }
36766
36878
  async function gateReadsOfQuery(runnable, stored = new Set, rerooted = new Set) {
36767
36879
  try {
@@ -37161,81 +37273,17 @@ var init_served_copy_checks = __esm(() => {
37161
37273
  };
37162
37274
  });
37163
37275
 
37164
- // src/service/materialization/serve/admission_parity.ts
37165
- function readAdmissionModeFrom(read) {
37166
- modeReader = read;
37167
- }
37168
- function admissionMode() {
37169
- return modeReader();
37170
- }
37276
+ // src/service/materialization/serve/query_walks.ts
37171
37277
  function reportQueryWalk(site) {
37172
37278
  walks.set(site, (walks.get(site) ?? 0) + 1);
37173
- observer?.queryWalk?.(site);
37279
+ observer?.queryWalk(site);
37174
37280
  }
37175
37281
  function observeAdmission(o) {
37176
37282
  observer = o;
37177
37283
  }
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(() => {
37284
+ var observer, walks;
37285
+ var init_query_walks = __esm(() => {
37236
37286
  walks = new Map;
37237
- drifts = [];
37238
- allowances = [];
37239
37287
  });
37240
37288
 
37241
37289
  // src/service/materialization/serve/result_reads.ts
@@ -38153,11 +38201,14 @@ class ServedCopyServe {
38153
38201
  isCurrent(pinned = this.current()) {
38154
38202
  return this.lanes.keepsFor(0, this.freshBindings(pinned));
38155
38203
  }
38156
- rerootedSourceIDs() {
38204
+ rerootedAt(compiled, atMs) {
38205
+ return atMs === undefined ? compiled.rerooted : compiled.rerooted.filter((b) => !readsLapsedAt([b], atMs));
38206
+ }
38207
+ rerootedSourceIDs(atMs) {
38157
38208
  const compiled = this.lanes.kept(0);
38158
38209
  if (!compiled)
38159
38210
  return;
38160
- return new Set(compiled.rerooted.flatMap((b) => b.sourceIDs ?? []));
38211
+ return new Set(this.rerootedAt(compiled, atMs).flatMap((b) => b.sourceIDs ?? []));
38161
38212
  }
38162
38213
  scopeLane() {
38163
38214
  const compiled = this.lanes.kept(0);
@@ -38168,19 +38219,21 @@ class ServedCopyServe {
38168
38219
  rerooted: compiled.rerootedSourceIDs ?? new Set
38169
38220
  };
38170
38221
  }
38171
- rerootedOnDatabaseOnly() {
38222
+ rerootedOnDatabaseOnly(atMs) {
38172
38223
  const compiled = this.lanes.kept(0);
38173
38224
  if (!compiled)
38174
38225
  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)));
38226
+ const rerooted = this.rerootedAt(compiled, atMs);
38227
+ const onStorage = new Set(rerooted.filter((b) => !isDatabase(b)).flatMap((b) => b.sourceIDs ?? []));
38228
+ return new Set(rerooted.filter(isDatabase).flatMap((b) => b.sourceIDs ?? []).filter((id) => !onStorage.has(id)));
38177
38229
  }
38178
- servedThroughBaseSourceIDs() {
38230
+ servedThroughBaseSourceIDs(atMs) {
38179
38231
  const compiled = this.lanes.kept(0);
38180
38232
  if (!compiled?.throughBase)
38181
38233
  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));
38234
+ const rerooted = this.rerootedAt(compiled, atMs);
38235
+ const ids = new Set(rerooted.flatMap((b) => b.sourceIDs ?? []));
38236
+ const names = new Set(rerooted.map((b) => b.sourceName));
38184
38237
  const declined = (id) => !!compiled.optOutIDs?.has(id) || !!compiled.unsafeIDs?.has(id);
38185
38238
  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
38239
  }
@@ -38347,30 +38400,13 @@ class ServedCopyServe {
38347
38400
  await this.checkGateGraft(attempt);
38348
38401
  await checkOptOut(attempt);
38349
38402
  })() : checkSourceZone(attempt);
38350
- const mode = admissionMode();
38351
- if (mode === "probe")
38352
- return walk();
38353
38403
  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);
38404
+ if (recorded === "unrecorded") {
38405
+ reportQueryWalk("served_copy_declines");
38406
+ return walk();
38371
38407
  }
38372
- if (walked !== undefined)
38373
- throw walked;
38408
+ if (recorded)
38409
+ attempt.decline(recorded.reason, recorded.code);
38374
38410
  }
38375
38411
  async recordedDeclines(attempt, which) {
38376
38412
  const { compiled, compiling, prepared } = attempt;
@@ -40477,7 +40513,7 @@ var init_served_copy_serve = __esm(() => {
40477
40513
  init_leg_decline();
40478
40514
  init_utils();
40479
40515
  init_served_copy_checks();
40480
- init_admission_parity();
40516
+ init_query_walks();
40481
40517
  init_chain_string_reads();
40482
40518
  NOTHING_PINNED = pin(EMPTY_SNAPSHOT, new Date(0));
40483
40519
  MISSING_FIELD_CODES = new Set([
@@ -43091,7 +43127,7 @@ var init_package_retrieval_settings = __esm(() => {
43091
43127
  questions: "auto",
43092
43128
  docParts: "auto",
43093
43129
  values: true,
43094
- valueCap: 50000,
43130
+ valueCap: 5000,
43095
43131
  valueEmbeddings: true,
43096
43132
  judge: "auto",
43097
43133
  contenderShare: 0,
@@ -43224,6 +43260,18 @@ var init_render_tag_targets = __esm(() => {
43224
43260
  });
43225
43261
 
43226
43262
  // src/service/connection_type.ts
43263
+ function normalizeReadableSchemas(list) {
43264
+ const names = [
43265
+ ...new Set(Array.isArray(list) ? list.filter((name) => typeof name === "string") : [])
43266
+ ].filter((name) => name !== "main").sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
43267
+ return names.length > 0 ? names : undefined;
43268
+ }
43269
+ function managedSchemas(readableSchemas) {
43270
+ return new Set([
43271
+ "main",
43272
+ ...normalizeReadableSchemas(readableSchemas) ?? []
43273
+ ]);
43274
+ }
43227
43275
  function managedOverrideOf(connection) {
43228
43276
  const name = connection.name;
43229
43277
  return typeof name === "string" && managedOverrides.some((layer) => layer.has(name));
@@ -43244,13 +43292,16 @@ function recordConnectionType(connection, type, options = {}) {
43244
43292
  if (recordedType)
43245
43293
  recorded.set(connection, recordedType);
43246
43294
  if (options.managed === true || managedOverrideOf(connection)) {
43247
- managed.add(connection);
43295
+ managed.set(connection, options.schemas ?? MAIN_ONLY);
43248
43296
  }
43249
43297
  return connection;
43250
43298
  }
43251
43299
  function isManagedConnection(connection) {
43252
43300
  return !!connection && managed.has(connection);
43253
43301
  }
43302
+ function managedSchemasOf(connection) {
43303
+ return connection ? managed.get(connection) : undefined;
43304
+ }
43254
43305
  function resolveManagedConnections(connections) {
43255
43306
  return [...connections].filter(([, connection]) => managed.has(connection)).map(([name]) => name).sort();
43256
43307
  }
@@ -43266,10 +43317,11 @@ function resolveConnectionTypes(connections) {
43266
43317
  }
43267
43318
  return types;
43268
43319
  }
43269
- var recorded, managed, overrides, managedOverrides;
43320
+ var recorded, managed, MAIN_ONLY, overrides, managedOverrides;
43270
43321
  var init_connection_type = __esm(() => {
43271
43322
  recorded = new WeakMap;
43272
- managed = new WeakSet;
43323
+ managed = new WeakMap;
43324
+ MAIN_ONLY = managedSchemas();
43273
43325
  overrides = [];
43274
43326
  managedOverrides = [];
43275
43327
  });
@@ -45209,14 +45261,34 @@ function parseEmbedding(raw) {
45209
45261
  documentPrefix: plainString(obj.documentPrefix, "retrieval.embedding.documentPrefix", `"documentPrefix": "search_document: "`) ?? ""
45210
45262
  };
45211
45263
  }
45212
- function parseEgress(raw) {
45213
- const obj = block(raw, "retrieval.egress", ["preset"], `"egress": { "preset": "default" }`);
45214
- if (obj.preset === undefined || obj.preset === null)
45215
- return;
45216
- if (typeof obj.preset !== "string" || !EGRESS_PRESETS.includes(obj.preset)) {
45217
- throw new Error(`Invalid retrieval.egress.preset: expected one of ${EGRESS_PRESETS.join(", ")}, got ${describe2(obj.preset)}. ` + `Fix: "preset": "default" (names, doc text and schema context) or "full" (also code and dimension values).`);
45264
+ function parseValueGivens(raw) {
45265
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
45266
+ const isValue = (v) => typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v);
45267
+ if (!isObject(raw)) {
45268
+ throw new Error(`Invalid retrieval.dimensionValues.givens: expected an object of packages, got ${describe2(raw)}. Fix: ${GIVENS_FIX}`);
45218
45269
  }
45219
- return { preset: obj.preset };
45270
+ const out = {};
45271
+ for (const [pkg, givens] of Object.entries(raw)) {
45272
+ const at = `retrieval.dimensionValues.givens.${pkg}`;
45273
+ if (!isObject(givens)) {
45274
+ throw new Error(`Invalid ${at}: expected an object of givens, got ${describe2(givens)}. Fix: ${GIVENS_FIX}`);
45275
+ }
45276
+ const parsed = {};
45277
+ let combinations = 1;
45278
+ for (const [name, value] of Object.entries(givens)) {
45279
+ const list = Array.isArray(value) ? value : [value];
45280
+ if (list.length === 0 || !list.every(isValue)) {
45281
+ throw new Error(`Invalid ${at}.${name}: expected a string, number or boolean, or a non-empty list of them, got ${describe2(value)}. Fix: ${GIVENS_FIX}`);
45282
+ }
45283
+ parsed[name] = [...new Set(list)];
45284
+ combinations *= parsed[name].length;
45285
+ }
45286
+ if (combinations > MAX_GIVEN_COMBINATIONS) {
45287
+ throw new Error(`Invalid ${at}: its lists make ${combinations} combinations, and each is one read per indexed dimension; at most ${MAX_GIVEN_COMBINATIONS}. Fix: list fewer values`);
45288
+ }
45289
+ out[pkg] = parsed;
45290
+ }
45291
+ return out;
45220
45292
  }
45221
45293
  function parseDimensionValues(raw) {
45222
45294
  const fields = block(raw, "retrieval.dimensionValues", DIMENSION_VALUE_KEYS, `"dimensionValues": { "enabled": false }`);
@@ -45227,6 +45299,9 @@ function parseDimensionValues(raw) {
45227
45299
  }
45228
45300
  out.enabled = fields.enabled;
45229
45301
  }
45302
+ if (fields.givens !== undefined && fields.givens !== null) {
45303
+ out.givens = parseValueGivens(fields.givens);
45304
+ }
45230
45305
  return out;
45231
45306
  }
45232
45307
  function parseRetrievalConfig(raw) {
@@ -45253,17 +45328,16 @@ function parseRetrievalConfig(raw) {
45253
45328
  if (embedding)
45254
45329
  out.embedding = embedding;
45255
45330
  }
45256
- if (input.egress !== undefined && input.egress !== null) {
45257
- const egress = parseEgress(input.egress);
45258
- if (egress)
45259
- out.egress = egress;
45260
- }
45331
+ if (input.egress !== undefined)
45332
+ out.egressIgnored = true;
45261
45333
  if (input.dimensionValues !== undefined && input.dimensionValues !== null) {
45262
45334
  out.dimensionValues = parseDimensionValues(input.dimensionValues);
45263
45335
  }
45264
45336
  return out;
45265
45337
  }
45266
45338
  function setRetrievalConfig(config) {
45339
+ if (config?.egressIgnored)
45340
+ logger.warn(RETIRED_EGRESS_WARNING);
45267
45341
  loaded = config;
45268
45342
  }
45269
45343
  function loadedRetrievalConfig() {
@@ -45272,14 +45346,12 @@ function loadedRetrievalConfig() {
45272
45346
  function getDimensionValueSettings() {
45273
45347
  return { ...DIMENSION_VALUE_DEFAULTS, ...loaded?.dimensionValues };
45274
45348
  }
45275
- function getEgressPreset() {
45276
- return loaded?.egress?.preset ?? "default";
45277
- }
45278
- var DIMENSION_VALUE_KEYS, loaded;
45349
+ var RETIRED_EGRESS_WARNING = "retrieval.egress is no longer read and is ignored. The values of #(index) dimensions are now sent to the configured embedding provider and LLM whenever one is configured. To keep them on this machine, set retrieval.dimensionValues.enabled to false in publisher.config.json. Leaving EMBEDDING_API_KEY unset, or setting retrieval.fcj.valueEmbeddings to false, only stops values being embedded: a configured LLM still sees them. Remove the egress block to silence this warning.", MAX_GIVEN_COMBINATIONS = 50, DIMENSION_VALUE_KEYS, GIVENS_FIX = `"givens": { "<package>": { "REPORT_ID": [123, 456] } }`, loaded;
45279
45350
  var init_config = __esm(() => {
45351
+ init_logger();
45280
45352
  init_types2();
45281
45353
  init_defaults();
45282
- DIMENSION_VALUE_KEYS = ["enabled"];
45354
+ DIMENSION_VALUE_KEYS = ["enabled", "givens"];
45283
45355
  });
45284
45356
 
45285
45357
  // src/config.ts
@@ -45304,11 +45376,27 @@ function resolvePublisherConfigPath(serverRoot) {
45304
45376
  }
45305
45377
  return null;
45306
45378
  }
45379
+ function duckDBByteSize(size) {
45380
+ const groups = DUCKDB_BYTE_SIZE.exec(size.trim())?.groups;
45381
+ if (!groups)
45382
+ throw new Error(`Not a DuckDB size: "${size}"`);
45383
+ const unit = groups.unit.toUpperCase();
45384
+ return Number(groups.amount) * (unit.includes("I") ? 1024 : 1000) ** "BKMGT".indexOf(unit[0]);
45385
+ }
45307
45386
  function assertDuckDBResourceConfig() {
45308
45387
  const memoryLimit = getDuckDBMemoryLimit();
45309
45388
  if (memoryLimit !== undefined && !DUCKDB_BYTE_SIZE.test(memoryLimit)) {
45310
45389
  throw new Error(`Invalid value for PUBLISHER_DUCKDB_MEMORY_LIMIT: expected a size like ` + `"1GB" or "512MB" (or "off" to disable), got "${memoryLimit}"`);
45311
45390
  }
45391
+ for (const [key, variable] of [
45392
+ ["admin.memoryLimit", "PUBLISHER_ADMIN_MEMORY_LIMIT"],
45393
+ ["admin.maxTempDirectorySize", "PUBLISHER_ADMIN_MAX_TEMP_DIRECTORY_SIZE"]
45394
+ ]) {
45395
+ const size = settings.get(key);
45396
+ if (!DUCKDB_BYTE_SIZE.test(size)) {
45397
+ throw new Error(`Invalid value for ${variable}: expected a size like "1.5GB" or ` + `"6GiB", got "${size}"`);
45398
+ }
45399
+ }
45312
45400
  const rowGroupSizeBytes = getDuckLakeRowGroupSizeBytes();
45313
45401
  if (rowGroupSizeBytes !== undefined && !DUCKDB_BYTE_SIZE.test(rowGroupSizeBytes)) {
45314
45402
  throw new Error(`Invalid value for PUBLISHER_DUCKLAKE_ROW_GROUP_SIZE_BYTES: expected a ` + `size like "16MB", got "${rowGroupSizeBytes}"`);
@@ -45492,7 +45580,7 @@ function assembleRetrieval(file) {
45492
45580
  return { block: file, ignored };
45493
45581
  }
45494
45582
  const block = file ? structuredClone(file) : {};
45495
- for (const leaf of REGISTRY.filter((entry) => entry.key.startsWith("retrieval.") && entry.kind !== "structured")) {
45583
+ for (const leaf of REGISTRY.filter((entry) => entry.key.startsWith("retrieval."))) {
45496
45584
  const pathInBlock = leaf.key.split(".").slice(1);
45497
45585
  const parent = nodeAt(block, pathInBlock.slice(0, -1));
45498
45586
  const last = pathInBlock[pathInBlock.length - 1];
@@ -45721,7 +45809,7 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
45721
45809
  tickIntervalMs: settings.get("materialization.schedulerIntervalMs"),
45722
45810
  maxFiresPerTick: settings.get("materialization.schedulerMaxFiresPerTick")
45723
45811
  };
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 = () => ({
45812
+ }, 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
45813
  materialize: getMaterializeEnabled(),
45726
45814
  gatedSources: getMaterializeGatedSources()
45727
45815
  }), getPersistCollisionEnforce = () => settings.get("persist.collisionEnforcementEnabled"), getMcpCorsOrigins = () => {
@@ -45926,7 +46014,7 @@ var init_config2 = __esm(() => {
45926
46014
  "chartText",
45927
46015
  "value"
45928
46016
  ];
45929
- DUCKDB_BYTE_SIZE = /^(?!0+(\.0+)?\s*[A-Za-z])\d+(\.\d+)?\s*(B|KB|KIB|MB|MIB|GB|GIB|TB|TIB)$/i;
46017
+ 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
46018
  RETRIEVAL_LEAVES = REGISTRY.filter((entry) => entry.key.startsWith("retrieval.") && entry.kind !== "structured" && !entry.secret);
45931
46019
  OPENAI_COMPATIBLE_LEAVES = [
45932
46020
  "retrieval.embedding.model",
@@ -46590,6 +46678,13 @@ function gateRefusalReason(routes) {
46590
46678
  }
46591
46679
 
46592
46680
  // src/service/materialization/domain/compiled_build_plan.ts
46681
+ function stringCapabilityKey(sourceID, destination) {
46682
+ return JSON.stringify([sourceID, destination]);
46683
+ }
46684
+ function stringCapabilityKeyParts(key) {
46685
+ const [sourceID, destination] = JSON.parse(key);
46686
+ return { sourceID, destination };
46687
+ }
46593
46688
  function* sourcesInBuildOrder(build, tables) {
46594
46689
  for (const sourceID of build.order) {
46595
46690
  const source = tables[sourceID]?.source;
@@ -48290,6 +48385,11 @@ var init_rollup_measure_grammar = __esm(() => {
48290
48385
  };
48291
48386
  });
48292
48387
 
48388
+ // src/service/materialization/domain/rollup_measures.ts
48389
+ function rollupLabel(plan) {
48390
+ return `#(rollup) rollup of source "${plan.baseSourceName}" at ` + `(${plan.grainDimensions.join(", ")})`;
48391
+ }
48392
+
48293
48393
  // src/service/materialization/plan/rollup_plan.ts
48294
48394
  import { createHash as createHash7 } from "node:crypto";
48295
48395
  import { Annotations as Annotations8 } from "@malloydata/malloy";
@@ -49045,7 +49145,7 @@ function rollupReadsGivenRefusal(plan, source) {
49045
49145
  return {
49046
49146
  tier: "unservable",
49047
49147
  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.",
49148
+ 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
49149
  sourceName: plan.baseSourceName,
49050
49150
  refused: refusalKey(source.sourceID, source.name, "reads_given", tierOf(plan.storage))
49051
49151
  };
@@ -50113,15 +50213,13 @@ function pairKeyChecks(pair, blocks, sourceID, build, connection) {
50113
50213
  ...on
50114
50214
  });
50115
50215
  });
50116
- const hops = p.hops ?? [];
50117
- const last = hops[hops.length - 1];
50118
- const leafNames = [p.join, ...hops.map((h) => h.join)];
50216
+ const leaf = pairLeafPath(p);
50119
50217
  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,
50218
+ join: leaf.names.join("."),
50219
+ keyColumn: leaf.keyColumn,
50220
+ queryName: `${build}__pair_leaf_key__${leaf.names.join("__")}`,
50221
+ joinedSourceID: leaf.sourceID,
50222
+ pairLevel: leaf.names.length,
50125
50223
  recordOnly: true,
50126
50224
  ...on
50127
50225
  });
@@ -50334,6 +50432,18 @@ function reachedUpstreams(root, modelDef, map) {
50334
50432
  }
50335
50433
  return out;
50336
50434
  }
50435
+ function materializedUpstream(sourceID, map) {
50436
+ const node = map.node(sourceID);
50437
+ const def = node?.def;
50438
+ const notes = ownLevelNotes(def?.annotations);
50439
+ if (notesDeclarePersist(notes.filter((n) => routeOfNote(n.text) === "@"))) {
50440
+ return;
50441
+ }
50442
+ if (!notes.some((n) => routeOfNote(n.text) === "materialize")) {
50443
+ return;
50444
+ }
50445
+ return { name: node?.name ?? sourceID, dialect: def?.dialect };
50446
+ }
50337
50447
  function storedElsewhereReason(upstreams) {
50338
50448
  const stored = upstreams.find((u) => u.storage !== undefined);
50339
50449
  return stored ? `its upstream '${stored.name}' is stored in the storage= destination ` + `'${stored.storage}', whose table a build in the warehouse cannot ` + `read, and a downstream is never built by recomputing its upstream ` + `from raw; it is ` + `answered live, over '${stored.name}''s table` : undefined;
@@ -52690,15 +52800,6 @@ function recordKeyCheck(kind, outcome) {
52690
52800
  function recordIncompatibleDetected(trigger, code) {
52691
52801
  incompatibleDetectedCounter().add(1, { trigger, code });
52692
52802
  }
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
52803
  function recordQueryWalk(site) {
52703
52804
  queryWalkCounter().add(1, { site });
52704
52805
  }
@@ -52729,13 +52830,14 @@ function recordQueryRoute(leg, outcome, reason) {
52729
52830
  function recordChainedStorageBuild(outcome) {
52730
52831
  chainedStorageBuildCounter().add(1, { outcome });
52731
52832
  }
52732
- function recordStaleUpstreamEntry(tier) {
52733
- staleUpstreamEntryCounter().add(1, { tier });
52734
- }
52735
- function recordUpstreamRecompute(reason, build, outcome) {
52736
- upstreamRecomputeCounter().add(1, { reason, build, outcome });
52833
+ function recordUpstreamReadUnchecked(build) {
52834
+ uncheckedUpstreamReadCounter().add(1, {
52835
+ reason: "reference_types_unrecorded",
52836
+ build,
52837
+ outcome: "read_unchecked"
52838
+ });
52737
52839
  }
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;
52840
+ 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
52841
  var init_materialization_metrics = __esm(() => {
52740
52842
  init_vocabulary();
52741
52843
  init_telemetry();
@@ -52774,9 +52876,6 @@ var init_materialization_metrics = __esm(() => {
52774
52876
  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
52877
  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
52878
  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
52879
  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
52880
  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
52881
  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 +52883,7 @@ var init_materialization_metrics = __esm(() => {
52784
52883
  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
52884
  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
52885
  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.");
52886
+ 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
52887
  });
52790
52888
 
52791
52889
  // src/service/materialization/plan/incremental_declaration.ts
@@ -54730,16 +54828,12 @@ async function compileOne(args) {
54730
54828
  name: args.plan.buildSourceName
54731
54829
  },
54732
54830
  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] }
54831
+ upstreams: args.upstreams.map((u, i) => standInUpstream({
54832
+ handle: standIns[i].handle,
54833
+ name: u.name,
54834
+ sourceID: u.sourceID,
54835
+ destination: args.destination,
54836
+ columns: standIns[i].columns
54743
54837
  })),
54744
54838
  view: {
54745
54839
  authorName: args.authorName,
@@ -54778,6 +54872,19 @@ async function compileOne(args) {
54778
54872
  return why(`it does not compile there (${error instanceof Error ? error.message : String(error)})`);
54779
54873
  }
54780
54874
  }
54875
+ function standInUpstream(u) {
54876
+ return {
54877
+ entry: {
54878
+ sourceEntityId: u.handle,
54879
+ sourceName: u.name,
54880
+ physicalTableName: u.handle,
54881
+ connectionName: u.destination,
54882
+ storageDestinationName: u.destination,
54883
+ schema: u.columns.map((c) => ({ ...c }))
54884
+ },
54885
+ names: { [u.name]: [u.sourceID] }
54886
+ };
54887
+ }
54781
54888
  function storedColumnsOf2(def) {
54782
54889
  const d = def;
54783
54890
  if (d?.type !== "query_source" || !Array.isArray(d.fields))
@@ -55448,6 +55555,32 @@ function recordedCompare(names, contract) {
55448
55555
  }
55449
55556
  return "none";
55450
55557
  }
55558
+ function unboundStringReadsRefusal(reads, unbound) {
55559
+ if ("refused" in reads)
55560
+ return;
55561
+ for (const read of reads.reads) {
55562
+ const upstream = read.upstream === undefined ? undefined : unbound.get(read.upstream);
55563
+ if (upstream === undefined)
55564
+ continue;
55565
+ const name = read.names[read.names.length - 1] ?? "?";
55566
+ const verb = read.need === "exact" ? "orders" : "groups or compares";
55567
+ const { capability } = upstream;
55568
+ if (capability === "unread") {
55569
+ return `it ${verb} '${name}' from '${upstream.name}', whose table is not ` + `bound yet and whose source's string comparison has not been ` + `read yet`;
55570
+ }
55571
+ const live = [...read.names].reverse().map((n) => capability.fields.get(n)).find((c) => c !== undefined);
55572
+ const compare = liveCompare(live);
55573
+ if (!MEETS[read.need].has(compare)) {
55574
+ return `it ${verb} '${name}' from '${upstream.name}', whose table is not ` + `bound yet and whose source compares it ` + `${compare === "none" ? "unlike byte order" : `by ${compare} only`}`;
55575
+ }
55576
+ }
55577
+ return;
55578
+ }
55579
+ function capabilityFingerprint(judged) {
55580
+ if (typeof judged === "string")
55581
+ return judged;
55582
+ return JSON.stringify([...judged.fields].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
55583
+ }
55451
55584
  var MEETS;
55452
55585
  var init_string_reads = __esm(() => {
55453
55586
  init_column_contract();
@@ -55559,7 +55692,7 @@ function rollupBuildCopies(plans, text, modelFile) {
55559
55692
  plan,
55560
55693
  tier: "unservable",
55561
55694
  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}.`,
55695
+ message: `${rollupLabel(plan)} is not built, so its measures are served live: ${made.reason}.`,
55563
55696
  sourceName: plan.baseSourceName,
55564
55697
  refused: measureRefusalKey(plan.baseSourceID, plan.baseDeclaredName, undefined, plan.readTimeTerms?.length ? "reads_given" : "hidden_field", { grain: plan.grainDimensions, storage: plan.storage })
55565
55698
  });
@@ -55598,7 +55731,7 @@ function strictRollupRefusals(plans, modelDef) {
55598
55731
  plan,
55599
55732
  tier: "unservable",
55600
55733
  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}.`,
55734
+ message: `${rollupLabel(plan)} is not built, so its measures are served live: ${why}.`,
55602
55735
  sourceName: plan.baseSourceName,
55603
55736
  refused: measureRefusalKey(plan.baseSourceID, plan.baseDeclaredName, undefined, reason, { grain: plan.grainDimensions, storage: plan.storage })
55604
55737
  });
@@ -56217,7 +56350,8 @@ function emptyBuildPlanParts() {
56217
56350
  modelGateLines: noModelGateLines(),
56218
56351
  persistedViews: {},
56219
56352
  omittedSources: [],
56220
- accessReads: []
56353
+ accessReads: [],
56354
+ stringCapabilityReads: {}
56221
56355
  };
56222
56356
  }
56223
56357
  function mergeBuildPlanParts(into, from) {
@@ -56235,6 +56369,7 @@ function mergeBuildPlanParts(into, from) {
56235
56369
  into.accessReads = [
56236
56370
  ...new Set([...into.accessReads, ...from.accessReads])
56237
56371
  ].sort();
56372
+ Object.assign(into.stringCapabilityReads, from.stringCapabilityReads);
56238
56373
  }
56239
56374
  function addAnnotationFinding(parts, finding) {
56240
56375
  const key = (f) => [f.code, f.model ?? "", f.subject ?? "", f.message].join("\x00");
@@ -56388,12 +56523,9 @@ function pairParentUnusable(plan, boundContract) {
56388
56523
  const contract = boundContract(over.sourceID, tier === "same" ? plan.persist.storage : undefined);
56389
56524
  if (!contract)
56390
56525
  return;
56391
- const unpassed = leafKeys.filter((k) => !keyCheckPassed(contract, k));
56392
- if (unpassed.length === 0)
56526
+ const what = pairLeafCheckFailure(contract, leafKeys);
56527
+ if (what === undefined)
56393
56528
  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
56529
  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
56530
  }
56399
56531
  async function authorSourceGate(sourceID, authorDef, args) {
@@ -56431,7 +56563,10 @@ async function collectGeneratedRollups(parts, args) {
56431
56563
  measures: plan.measures.map((m) => m.name)
56432
56564
  },
56433
56565
  stored: [storedBase.baseSourceID]
56434
- }, plan.storage) : undefined;
56566
+ }, plan.storage, {
56567
+ modelDef: args.modelDef,
56568
+ judged: parts.stringCapabilityReads
56569
+ }) : undefined;
56435
56570
  const overStored = provenRollupOverStored(source, plan, generated.overStoredBases.get(source.sourceID), parts.tables);
56436
56571
  const unusableUpstream = storedBase && plan.storage !== undefined ? storedBaseDecline(args, source, plan, storedBase, plan.storage) : !storedBase && !overStored.overStoredBase ? rollupOverDefinition(args, plan) : undefined;
56437
56572
  parts.tables[source.sourceID] = {
@@ -56458,7 +56593,7 @@ function provenRollupOverStored(source, plan, variant, tables) {
56458
56593
  return {};
56459
56594
  return overStoredProven(source, variant, base.source) ? { overStoredBase: variant } : {};
56460
56595
  }
56461
- async function planStringReads(ports, materializer, request, destination) {
56596
+ async function planStringReads(ports, materializer, request, destination, upstreams) {
56462
56597
  if (!ports) {
56463
56598
  return { refused: "this package reads no string a build compares" };
56464
56599
  }
@@ -56471,14 +56606,30 @@ async function planStringReads(ports, materializer, request, destination) {
56471
56606
  const unstored = unstoredReadRefusal(reads);
56472
56607
  if (unstored !== undefined)
56473
56608
  return { refused: unstored, unstored: true };
56474
- if ("refused" in reads || !ports.boundContract)
56475
- return reads;
56476
- const contracts = new Map(request.stored.map((id) => [id, ports.boundContract(id, destination)]));
56477
- if ([...contracts.values()].some((c) => c === undefined))
56609
+ if ("refused" in reads)
56478
56610
  return reads;
56479
- const why = stringReadsRefusal(reads, contracts);
56611
+ const contracts = new Map(request.stored.map((id) => [id, ports.boundContract?.(id, destination)]));
56612
+ const why = ports.boundContract && [...contracts.values()].every((c) => c !== undefined) ? stringReadsRefusal(reads, contracts) : unboundStringReadsRefusal(reads, await unboundCapabilities(ports, reads, request.stored.filter((id) => contracts.get(id) === undefined), destination, upstreams));
56480
56613
  return why === undefined ? reads : { refused: why };
56481
56614
  }
56615
+ async function unboundCapabilities(ports, reads, unbound, destination, upstreams) {
56616
+ const out = new Map;
56617
+ if ("refused" in reads)
56618
+ return out;
56619
+ const map = SourceMap.of(upstreams.modelDef);
56620
+ for (const id of unbound) {
56621
+ if (!reads.reads.some((r) => r.upstream === id))
56622
+ continue;
56623
+ const upstream = materializedUpstream(id, map);
56624
+ if (upstream === undefined || capabilitiesOf(upstream.dialect).stringCollation !== "column") {
56625
+ continue;
56626
+ }
56627
+ const capability = ports.capability ? await ports.capability(id).catch(() => "unread") : "unread";
56628
+ upstreams.judged[stringCapabilityKey(id, destination)] = capabilityFingerprint(capability);
56629
+ out.set(id, { name: upstream.name, capability });
56630
+ }
56631
+ return out;
56632
+ }
56482
56633
  function viewUnusableUpstream(generated, sourceID, proven) {
56483
56634
  const unusable = generated.overStoredUnusable.get(sourceID);
56484
56635
  if (unusable !== undefined)
@@ -56512,22 +56663,17 @@ function storedBaseDecline(args, source, plan, storedBase, destination) {
56512
56663
  if (columns === undefined) {
56513
56664
  return `${base} holds no columns a stored table can stand in for`;
56514
56665
  }
56515
- const handle = "publisher_stand_in_base";
56516
56666
  const text = args.chainBuildText({
56517
56667
  downstream: { sourceID: source.sourceID, name: source.name },
56518
56668
  destination: { name: destination, schema: "main" },
56519
56669
  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
- }
56670
+ standInUpstream({
56671
+ handle: "publisher_stand_in_base",
56672
+ name: plan.baseSourceName,
56673
+ sourceID: storedBase.baseSourceID,
56674
+ destination,
56675
+ columns
56676
+ })
56531
56677
  ],
56532
56678
  rollup: {
56533
56679
  baseSourceID: storedBase.baseSourceID,
@@ -56544,11 +56690,11 @@ function storedBaseDecline(args, source, plan, storedBase, destination) {
56544
56690
  return `its model does not declare ${base}`;
56545
56691
  return "declined" in text ? `${base} cannot be re-rooted on that table: ${text.declined}` : undefined;
56546
56692
  }
56547
- function inDestinationStringReads(args, stored, planned) {
56693
+ function inDestinationStringReads(args, stored, planned, upstreams) {
56548
56694
  const run = planned.kind === "query" ? `run: ${quotedIdentifier(planned.queryName)}` : `run: ${quotedIdentifier(planned.sourceName)} -> ${quotedIdentifier(planned.viewName)}`;
56549
- return planStringReads(args.stringReads, args.materializer, { run, stored: stored.upstreams.map((u) => u.sourceID) }, planned.storage);
56695
+ return planStringReads(args.stringReads, args.materializer, { run, stored: stored.upstreams.map((u) => u.sourceID) }, planned.storage, upstreams);
56550
56696
  }
56551
- async function chainedStringReads(source, modelDef, materializer, ports) {
56697
+ async function chainedStringReads(source, modelDef, materializer, ports, judged) {
56552
56698
  const destination = declaredStorage(source)?.trim();
56553
56699
  if (!destination)
56554
56700
  return;
@@ -56560,7 +56706,7 @@ async function chainedStringReads(source, modelDef, materializer, ports) {
56560
56706
  const stored = reachedUpstreams(def, modelDef, map).filter((u) => u.storage === destination && u.sourceID !== source.sourceID).map((u) => u.sourceID);
56561
56707
  if (stored.length === 0)
56562
56708
  return;
56563
- const reads = await planStringReads(ports, materializer, { downstream: source.name, stored }, destination);
56709
+ const reads = await planStringReads(ports, materializer, { downstream: source.name, stored }, destination, { modelDef, judged });
56564
56710
  if (!("refused" in reads) || !reads.unstored)
56565
56711
  return reads;
56566
56712
  const persisted = new Set(reachedUpstreams(def, modelDef, map).map((u) => u.sourceID));
@@ -56643,7 +56789,7 @@ async function collectGeneratedPersistedViews(parts, args) {
56643
56789
  continue;
56644
56790
  }
56645
56791
  kept++;
56646
- const stringReads = inDestination && "stored" in inDestination ? await inDestinationStringReads(args, inDestination.stored, query ?? plan) : undefined;
56792
+ const stringReads = inDestination && "stored" in inDestination ? await inDestinationStringReads(args, inDestination.stored, query ?? plan, { modelDef: authorDef, judged: parts.stringCapabilityReads }) : undefined;
56647
56793
  const unusableUpstream = viewUnusableUpstream(generated, source.sourceID, overStoredBase !== undefined);
56648
56794
  parts.tables[source.sourceID] = {
56649
56795
  kind: "view",
@@ -56944,7 +57090,7 @@ async function planV1PersistSources(parts, planned, args) {
56944
57090
  modelDef: modelDefOf(malloyModel),
56945
57091
  deps: gateDepsFor(malloyModel, modelPath)
56946
57092
  };
56947
- const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads) : parts.tables[sourceID]?.stringReads;
57093
+ const stringReads = declaringModelPath(sourceIDFileURL(sourceID), packagePath, modelPath) === modelPath ? await chainedStringReads(source, classificationCtx.modelDef, materializer, args.stringReads, parts.stringCapabilityReads) : parts.tables[sourceID]?.stringReads;
56948
57094
  const destination = declaredStorage(source)?.trim();
56949
57095
  const map = SourceMap.of(classificationCtx.modelDef);
56950
57096
  const query = map.node(sourceID)?.def?.query;
@@ -57306,6 +57452,7 @@ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
57306
57452
  materializePlans: materializePlansOf(compiled.tables),
57307
57453
  asOfBuild,
57308
57454
  accessReads: [...compiled.accessReads ?? []],
57455
+ ...compiled.stringCapabilityReads && Object.keys(compiled.stringCapabilityReads).length > 0 ? { stringCapabilityReads: { ...compiled.stringCapabilityReads } } : {},
57309
57456
  eligibilityRefused: { ...counts }
57310
57457
  };
57311
57458
  }
@@ -57606,6 +57753,7 @@ var init_build_plan = __esm(() => {
57606
57753
  init_over_stored_proof();
57607
57754
  init_downstream_upstreams();
57608
57755
  init_string_reads();
57756
+ init_dialect();
57609
57757
  init_column_contract();
57610
57758
  init_source_map();
57611
57759
  init_author_model();
@@ -58390,7 +58538,10 @@ function buildWorkerMalloyConfig(job, refresh) {
58390
58538
  };
58391
58539
  port.postMessage(req);
58392
58540
  });
58393
- const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, { managed: response.metadata.managed === true });
58541
+ const proxy = recordConnectionType(new ProxyConnection(response.metadata, job.requestId, job.environmentName, refresh), response.metadata.connectionType, response.metadata.managedSchemas ? {
58542
+ managed: true,
58543
+ schemas: new Set(response.metadata.managedSchemas)
58544
+ } : {});
58394
58545
  proxies.set(effectiveName, proxy);
58395
58546
  inflight.delete(effectiveName);
58396
58547
  return proxy;