@malloy-publisher/server 0.18.7 → 0.18.8

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 (30) hide show
  1. package/README.docker.md +18 -18
  2. package/README.md +2 -2
  3. package/dist/admin-api-doc.yaml +10 -41
  4. package/dist/app/api-doc.yaml +292 -136
  5. package/dist/app/assets/{EnvironmentPage-nfT0sfcF.js → EnvironmentPage-B9eJXM9R.js} +1 -1
  6. package/dist/app/assets/{HomePage-CLVuGwtd.js → HomePage-CUCq65Mm.js} +1 -1
  7. package/dist/app/assets/{MainPage-BPN92PmE.js → MainPage-DMCpsSwG.js} +1 -1
  8. package/dist/app/assets/{ModelPage-BtYHo01_.js → ModelPage-CRpHJTqZ.js} +2 -2
  9. package/dist/app/assets/{PackagePage-BYTMF_z7.js → PackagePage-CrgssVfP.js} +1 -1
  10. package/dist/app/assets/PackageSplatRoute-Dh1u1dZ4.js +2 -0
  11. package/dist/app/assets/{RenderedResult-BkBdGb49.es-BeM14Cw6.js → RenderedResult-DW_0pVGi.es-CQe3gbdA.js} +3 -3
  12. package/dist/app/assets/{RouteError-O8rWhL-e.js → RouteError-C11mhFOT.js} +1 -1
  13. package/dist/app/assets/{ThemeEditorPage-BPlQ20Nk.js → ThemeEditorPage-CQdYTEul.js} +1 -1
  14. package/dist/app/assets/{ToggleButtonGroup-ZFDdg4WD.js → ToggleButtonGroup-CPXIFQqB.js} +1 -1
  15. package/dist/app/assets/{documentRoutes-D2CHPd13.js → documentRoutes-DarwM5Zm.js} +1 -1
  16. package/dist/app/assets/{editPageMounted-CK5o2lS_.js → editPageMounted-DmeRc7t9.js} +2 -2
  17. package/dist/app/assets/{index-BvIvG2Vi.js → index-BNAHVKoh.js} +1 -1
  18. package/dist/app/assets/{index-Dd4jjg8n.js → index-BX1A_FPA.js} +109 -109
  19. package/dist/app/assets/{index-w9WgUNKi.js → index-C0mf24Mk.js} +1 -1
  20. package/dist/app/assets/{index-m8b6Cq0X.js → index-CHCSj9_S.js} +1 -1
  21. package/dist/app/assets/{index.es-c9W9AVnk.js → index.es-B1q1T-14.js} +10 -10
  22. package/dist/app/assets/usePackageLinkNavigate-iOWW_Iek.js +1 -0
  23. package/dist/app/assets/{usePackageRoute-DZUIBpcE.js → usePackageRoute-BNCiKCRB.js} +1 -1
  24. package/dist/app/index.html +1 -1
  25. package/dist/instrumentation.mjs +171 -88
  26. package/dist/package_load_worker.mjs +1226 -660
  27. package/dist/server.mjs +5992 -2644
  28. package/package.json +1 -1
  29. package/dist/app/assets/PackageSplatRoute-M9_ZKB-f.js +0 -2
  30. package/dist/app/assets/usePackageLinkNavigate-DFEdCQJt.js +0 -1
@@ -631,7 +631,7 @@ function describeRange(range) {
631
631
  ].filter((part) => part !== undefined);
632
632
  return parts.length > 0 ? ` ${parts.join(" and ")}` : "";
633
633
  }
634
- var Mismatch, TRUE_SPELLINGS, FALSE_SPELLINGS, BooleanType, INTEGER, IntegerType, DECIMAL, NumberType, EnumType, ListType, StringType, StructuredType, boolean = () => new BooleanType, integer = (range) => new IntegerType(range), number = (range) => new NumberType(range), oneOf = (values) => new EnumType(values), list = (options) => new ListType(options?.ordered ?? true), string = (options) => new StringType(options?.trim ?? true), structured = () => new StructuredType;
634
+ var Mismatch, TRUE_SPELLINGS, FALSE_SPELLINGS, BooleanType, INTEGER, IntegerType, DECIMAL, NumberType, EnumType, ListType, StringType, StructuredType, boolean = () => new BooleanType, integer = (range) => new IntegerType(range), number = (range) => new NumberType(range), oneOf = (values) => new EnumType(values), list = (options) => new ListType(options?.ordered ?? true), string = (options) => new StringType(options?.trim ?? true, options?.pattern, options?.expected), structured = () => new StructuredType;
635
635
  var init_types = __esm(() => {
636
636
  Mismatch = class Mismatch extends Error {
637
637
  constructor() {
@@ -745,13 +745,22 @@ var init_types = __esm(() => {
745
745
  };
746
746
  StringType = class StringType extends SettingType {
747
747
  trim;
748
- expected = "a string";
749
- constructor(trim = true) {
748
+ pattern;
749
+ expected;
750
+ constructor(trim = true, pattern, expected) {
750
751
  super();
751
752
  this.trim = trim;
753
+ this.pattern = pattern;
754
+ this.expected = expected ?? "a string";
752
755
  }
753
756
  fromString(raw) {
754
- return this.trim ? raw.trim() : raw;
757
+ const value = this.trim ? raw.trim() : raw;
758
+ if (this.pattern && !this.pattern.test(value))
759
+ throw new Mismatch;
760
+ return value;
761
+ }
762
+ allows(value) {
763
+ return typeof value !== "string" || this.pattern === undefined || this.pattern.test(value);
755
764
  }
756
765
  };
757
766
  StructuredType = class StructuredType extends SettingType {
@@ -786,7 +795,7 @@ var init_access = __esm(() => {
786
795
  type: boolean(),
787
796
  default: false,
788
797
  description: "Allow setupSQL on environment-authored DuckDB connections.",
789
- notes: "Set to `true` to let environment-level `duckdb` connections carry `setupSQL`. Unset, a connection with `setupSQL` is refused at config load, on create and update, and by the connection test. `setupSQL` runs arbitrary DuckDB statements on the server, including writing host files and loading extensions, so enable it only where the people who author connections are trusted with the host. Refused under `EXTENSION_FETCH_POLICY=local-only` either way. Same boolean spellings as `PUBLISHER_ALLOW_UNVERIFIED_SSH_HOST_KEY`; any other value fails config load.",
798
+ notes: "Set to `true` to let environment-level `duckdb` connections carry `setupSQL`. Unset, a connection with `setupSQL` is refused at config load, on create and update, and by the connection test. `setupSQL` runs arbitrary DuckDB statements on the server, including writing host files and loading extensions, so enable it only where the people who author connections are trusted with the host. Refused under `PUBLISHER_DUCKDB_EXTENSION_FETCH_POLICY=local-only` either way. Same boolean spellings as `PUBLISHER_ALLOW_UNVERIFIED_SSH_HOST_KEY`; any other value fails config load.",
790
799
  aliases: { env: ["PUBLISHER_ALLOW_DUCKDB_SETUP_SQL"] }
791
800
  }),
792
801
  setting({
@@ -854,30 +863,6 @@ var init_access = __esm(() => {
854
863
  env: ["SHUTDOWN_GRACEFUL_CLOSE_TIMEOUT_SECONDS"],
855
864
  flags: ["--shutdown_graceful_close_timeout_seconds"]
856
865
  }
857
- }),
858
- setting({
859
- key: "workloadLog.store",
860
- type: oneOf(["off", "on"]),
861
- default: "off",
862
- description: "on keeps every access record, with its workload shape, in publisher.db's workload_log table; off only logs it.",
863
- notes: "`on` or `off`: whether the workload log (materialization v2, T1) is also kept locally, in the `workload_log` table of Publisher's own metadata database (`publisher.db`), beside the log line every query already writes. Off by default: the access record goes to the log either way. Each row is one access record with its workload shape, without the values of `#(secure)` givens. Bounded by `PUBLISHER_WORKLOAD_LOG_RETENTION_DAYS` and `PUBLISHER_WORKLOAD_LOG_MAX_ROWS`, flushed every two seconds, so a process that exits loses at most that interval's records; a failed write drops its batch and never fails a query. See [access-record.md](access-record.md#the-workload-log). Any other value fails startup.",
864
- aliases: { env: ["PUBLISHER_WORKLOAD_LOG_STORE"] }
865
- }),
866
- setting({
867
- key: "workloadLog.retentionDays",
868
- type: integer({ min: 1 }),
869
- default: 30,
870
- description: "Days the workload log's local store keeps a record.",
871
- notes: "How many days a row stays in the workload log's local store (`PUBLISHER_WORKLOAD_LOG_STORE=on`); older rows are deleted on each flush. Read only when the store is on.",
872
- aliases: { env: ["PUBLISHER_WORKLOAD_LOG_RETENTION_DAYS"] }
873
- }),
874
- setting({
875
- key: "workloadLog.maxRows",
876
- type: integer({ min: 1 }),
877
- default: 1e6,
878
- description: "Rows the workload log's local store holds; the oldest go first.",
879
- notes: "The most rows the workload log's local store (`PUBLISHER_WORKLOAD_LOG_STORE=on`) keeps, whatever their age; past it the oldest are deleted on each flush. Read only when the store is on.",
880
- aliases: { env: ["PUBLISHER_WORKLOAD_LOG_MAX_ROWS"] }
881
866
  })
882
867
  ];
883
868
  });
@@ -912,21 +897,21 @@ var init_admin = __esm(() => {
912
897
  default: 600000,
913
898
  description: "Ms the admin API keeps a request, its headers and an idle keep-alive open.",
914
899
  defaultText: "`600000` (10 min)",
915
- 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."
900
+ notes: "How long the admin listener lets a request run before closing its connection. A table PUT or a 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 write, and keep the caller's own timeout above it. Applies to the admin listener alone: the main API and MCP listeners keep ten minutes."
916
901
  }),
917
902
  setting({
918
903
  key: "admin.memoryLimit",
919
904
  type: string(),
920
905
  default: "1.5GB",
921
- description: "Most memory one admin table load or copy session may use, as a DuckDB size (1.5GB).",
922
- 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."
906
+ description: "Most memory one admin table load or table PUT session may use, as a DuckDB size (1.5GB).",
907
+ notes: "The `memory_limit` of the DuckDB session an admin table load or table PUT 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."
923
908
  }),
924
909
  setting({
925
910
  key: "admin.maxTempDirectorySize",
926
911
  type: string(),
927
912
  default: "6GiB",
928
- description: "Most spill one admin table load or copy session may write, as a DuckDB size (6GiB).",
929
- 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."
913
+ description: "Most spill one admin table load or table PUT session may write, as a DuckDB size (6GiB).",
914
+ notes: "The `max_temp_directory_size` of the DuckDB session an admin table load or table PUT 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."
930
915
  }),
931
916
  setting({
932
917
  key: "admin.catalogDatabase",
@@ -1002,7 +987,7 @@ var init_launch = __esm(() => {
1002
987
  default: (resolving) => !resolving.isSet("root") && !resolving.isSet("config") && resolving.env("NODE_ENV") !== "test",
1003
988
  kind: "launch",
1004
989
  description: "Serve the bundled sample config when the server root has none; on when neither {root} nor {config} is given.",
1005
- notes: "Set to `true` to fall back to the sample config bundled inside the installed package when neither `--config` is passed nor a `publisher.config.json` exists at the server root. The server sets this itself on a zero-flag start (so a bare `npx @malloy-publisher/server` boots the samples); passing `--config` or `--server_root` leaves it unset. Because the bundled config lives inside the install, relative package locations resolve against the server root in this mode rather than the config's directory.",
990
+ notes: "Set to `true` to fall back to the sample config bundled inside the installed package when neither `--config` is passed nor a `publisher.config.json` exists at the server root. The server sets this itself on a zero-flag start (so a bare `npx @malloy-publisher/server` boots the samples); passing `--config` or `--root` leaves it unset. Because the bundled config lives inside the install, relative package locations resolve against the server root in this mode rather than the config's directory.",
1006
991
  defaultText: "on unless `root` or `config` is given; never in tests",
1007
992
  aliases: {
1008
993
  env: ["PUBLISHER_USE_BUNDLED_DEFAULT"],
@@ -1125,10 +1110,11 @@ var init_mcp = __esm(() => {
1125
1110
  });
1126
1111
 
1127
1112
  // src/settings/registry/query.ts
1128
- var query;
1113
+ var SNOWFLAKE_APPLICATION_NAME, query;
1129
1114
  var init_query = __esm(() => {
1130
1115
  init_constants();
1131
1116
  init_types();
1117
+ SNOWFLAKE_APPLICATION_NAME = /^[A-Za-z][A-Za-z0-9._-]{1,50}$/;
1132
1118
  query = [
1133
1119
  setting({
1134
1120
  key: "query.maxRows",
@@ -1152,7 +1138,7 @@ var init_query = __esm(() => {
1152
1138
  type: integer({ min: 1 }),
1153
1139
  default: DEFAULT_QUERY_ROW_LIMIT,
1154
1140
  description: "Row limit of a model query that sets none of its own.",
1155
- notes: "Default `LIMIT` applied to model queries that don't include their own. Always ≤ `PUBLISHER_MAX_QUERY_ROWS`. `0` is rejected.",
1141
+ notes: "Default `LIMIT` applied to model queries that don't include their own. Always ≤ `PUBLISHER_QUERY_MAX_ROWS`. `0` is rejected.",
1156
1142
  aliases: { env: ["PUBLISHER_DEFAULT_QUERY_ROW_LIMIT"] }
1157
1143
  }),
1158
1144
  setting({
@@ -1177,7 +1163,7 @@ var init_query = __esm(() => {
1177
1163
  type: boolean(),
1178
1164
  default: false,
1179
1165
  description: "Attach per-query metadata to every statement.",
1180
- notes: "`on` attaches per-query metadata to every statement, as a leading SQL comment where the connection has no native tag; `off` attaches none. Only `on` and `off` are read. See [query-metadata.md](query-metadata.md).",
1166
+ notes: "`on` attaches per-query metadata to every statement, as a leading SQL comment where the connection has no native tag; `off` attaches none. Any boolean spelling is read; the deprecated `PUBLISHER_QUERY_METADATA` reads only `on` and `off`. See [query-metadata.md](query-metadata.md).",
1181
1167
  aliases: {
1182
1168
  env: ["PUBLISHER_QUERY_METADATA"],
1183
1169
  today: { reads: "on-off" }
@@ -1191,12 +1177,24 @@ var init_query = __esm(() => {
1191
1177
  notes: "Per-process cap on open database sessions for each Postgres connection, including one reached through an SSH proxy. Each query uses its own session and closes it; when all are busy a query waits up to 30 s for one, then fails with HTTP 502. Across a fleet the ceiling is roughly this value times the pods serving the environment, so size it against the role's `CONNECTION LIMIT`. Must be a positive integer.",
1192
1178
  aliases: { env: ["PUBLISHER_POSTGRES_POOL_MAX"] }
1193
1179
  }),
1180
+ setting({
1181
+ key: "snowflake.applicationName",
1182
+ type: string({
1183
+ trim: false,
1184
+ pattern: SNOWFLAKE_APPLICATION_NAME,
1185
+ expected: `a letter, then 1 to 50 letters, digits, ".", "-" or "_" (Snowflake's rule), like "Acme_Publisher"`
1186
+ }),
1187
+ fileForbidden: true,
1188
+ noFlag: true,
1189
+ description: "Client application name every Snowflake session reports (a Snowflake partner's connection identifier).",
1190
+ notes: "The name every Snowflake session Publisher opens reports to Snowflake as its client application (`CLIENT_ENVIRONMENT:APPLICATION` in `SNOWFLAKE.ACCOUNT_USAGE.SESSIONS`). A Snowflake technology partner sets it to the connection string identifier it registered with the Snowflake Partner Network, so Snowflake can attribute the sessions to it. Unset, Publisher sets none and each driver reports its own default. Applied on both Snowflake paths: the snowflake-sdk connection behind live queries and connection tests (`application`), and, in the Docker image, the ADBC driver behind DuckDB-attached Snowflake and `storage=` build passthrough (`adbc.snowflake.sql.client_option.app_name`, set by the driver shim in `packages/server/adbc-shim/`). The ADBC driver puts its own `[ADBC][Go-<version>]` prefix in front of the name, so those sessions report `[ADBC][Go-<driver version>]<name>`. Must start with a letter, followed by 1 to 50 letters, digits, `.`, `-` or `_`, which is snowflake-sdk's rule; anything else fails startup, and the value is not trimmed, so a trailing newline from a secret file fails it too (the shim reads the variable as it is). An environment variable only, with no flag or config-file key: the ADBC driver sees only the process environment, so any other source would tag one path and not the other."
1191
+ }),
1194
1192
  setting({
1195
1193
  key: "memory.maxBytes",
1196
1194
  type: integer({ min: 0 }),
1197
1195
  default: 0,
1198
1196
  description: "Process RSS ceiling for the memory governor, in bytes; 0 turns the governor off.",
1199
- notes: "Enables the RSS-based memory governor. When set, the governor samples process RSS every `PUBLISHER_MEMORY_CHECK_INTERVAL_MS` ms and rejects new package loads and queries with HTTP 503 once RSS crosses `PUBLISHER_MEMORY_HIGH_WATER_FRACTION × PUBLISHER_MAX_MEMORY_BYTES`, until it drops below `PUBLISHER_MEMORY_LOW_WATER_FRACTION ×`. Unset or `0` disables.",
1197
+ notes: "Enables the RSS-based memory governor. When set, the governor samples process RSS every `PUBLISHER_MEMORY_CHECK_INTERVAL_MS` ms and rejects new package loads and queries with HTTP 503 once RSS crosses `PUBLISHER_MEMORY_HIGH_WATER_FRACTION × PUBLISHER_MEMORY_MAX_BYTES`, until it drops below `PUBLISHER_MEMORY_LOW_WATER_FRACTION ×`. Unset or `0` disables.",
1200
1198
  defaultText: "`0` (the governor is off)",
1201
1199
  aliases: { env: ["PUBLISHER_MAX_MEMORY_BYTES"] }
1202
1200
  }),
@@ -1205,7 +1203,7 @@ var init_query = __esm(() => {
1205
1203
  type: number({ above: 0, below: 1 }),
1206
1204
  default: 0.8,
1207
1205
  description: "Share of {memory.maxBytes} at which new package loads are refused.",
1208
- notes: "High-water mark (fraction of `PUBLISHER_MAX_MEMORY_BYTES`). Must be in `(0, 1)` and strictly above the low-water mark.",
1206
+ notes: "High-water mark (fraction of `PUBLISHER_MEMORY_MAX_BYTES`). Must be in `(0, 1)` and strictly above the low-water mark.",
1209
1207
  aliases: { env: ["PUBLISHER_MEMORY_HIGH_WATER_FRACTION"] }
1210
1208
  }),
1211
1209
  setting({
@@ -1213,7 +1211,7 @@ var init_query = __esm(() => {
1213
1211
  type: number({ above: 0, below: 1 }),
1214
1212
  default: 0.7,
1215
1213
  description: "Share of {memory.maxBytes} at which loads are admitted again; below the high-water mark.",
1216
- notes: "Low-water mark (fraction of `PUBLISHER_MAX_MEMORY_BYTES`). Hysteresis: back-pressure clears when RSS dips below this value.",
1214
+ notes: "Low-water mark (fraction of `PUBLISHER_MEMORY_MAX_BYTES`). Hysteresis: back-pressure clears when RSS dips below this value.",
1217
1215
  aliases: { env: ["PUBLISHER_MEMORY_LOW_WATER_FRACTION"] }
1218
1216
  }),
1219
1217
  setting({
@@ -1228,8 +1226,8 @@ var init_query = __esm(() => {
1228
1226
  key: "memory.backpressureEnabled",
1229
1227
  type: boolean(),
1230
1228
  default: true,
1231
- description: "Refuse loads above the high-water mark; off only samples and reports.",
1232
- notes: "Set to `false` to disable the 503 behavior while keeping RSS monitoring — useful for a metrics-only rollout before enabling enforcement.",
1229
+ description: "The memory governor's 503 refusals above the high-water mark; off keeps its sampling and reporting.",
1230
+ notes: "Set to `false` to turn off the memory governor's 503 refusals while it keeps sampling RSS and reporting it. For an operator who needs the refusals off, for example while a workload's memory profile is investigated, without a code change.",
1233
1231
  aliases: { env: ["PUBLISHER_MEMORY_BACKPRESSURE"] }
1234
1232
  }),
1235
1233
  setting({
@@ -1254,7 +1252,7 @@ var init_query = __esm(() => {
1254
1252
  type: integer({ min: 0 }),
1255
1253
  default: DEFAULT_PACKAGE_LOAD_SCHEMA_CACHE_BYTES,
1256
1254
  description: "Serialized schema each package-load worker caches across loads, in bytes; 0 turns it off.",
1257
- notes: "Serialized size of the table and SQL schemas each package-load worker keeps across loads, so a model's repeated and later requests for the same table skip the round trip to the main thread. Least recently used entries go first. Scoped per environment and per connection instance, so editing a connection drops its entries. An explicit refresh (a reload with `?reload=true` or `reload_package`, a publish, or a `PATCH` that reinstalls) fetches every table and SQL schema the package reads again, in the connection's own cache too, and every worker drops its old entry; a watch-mode recompile and a boot read the cached schemas. Heap use is a few times the serialized size. `0` disables it; empty takes the default, and a value that is not a byte count stops the server from starting.",
1255
+ notes: "Serialized size of the table and SQL schemas each package-load worker keeps across loads, so a model's repeated and later requests for the same table skip the round trip to the main thread. Least recently used entries go first. Scoped per environment and per connection instance, so editing a connection drops its entries. An explicit refresh (a reload with `?reload=true` or `reload_package`, or a publish) fetches every table and SQL schema the package reads again, in the connection's own cache too, and every worker drops its old entry; a watch-mode recompile and a boot read the cached schemas. Heap use is a few times the serialized size. `0` disables it; empty takes the default, and a value that is not a byte count stops the server from starting.",
1258
1256
  defaultText: "`16777216` (16 MiB)",
1259
1257
  aliases: { env: ["PACKAGE_LOAD_SCHEMA_CACHE_BYTES"] }
1260
1258
  })
@@ -1282,9 +1280,8 @@ var init_provider_names = __esm(() => {
1282
1280
  });
1283
1281
 
1284
1282
  // src/retrieval/defaults.ts
1285
- 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;
1283
+ var 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;
1286
1284
  var init_defaults = __esm(() => {
1287
- EGRESS_PRESETS = ["default", "full"];
1288
1285
  DIMENSION_VALUE_DEFAULTS = { enabled: true, givens: {} };
1289
1286
  });
1290
1287
 
@@ -1368,7 +1365,7 @@ var init_retrieval = __esm(() => {
1368
1365
  key: "retrieval.embedding.provider",
1369
1366
  type: oneOf(EMBEDDING_PROVIDER_NAMES),
1370
1367
  description: "Embedding provider; unset reads the OpenAI-compatible settings.",
1371
- notes: "Which provider serves embeddings. Unset: an OpenAI-compatible endpoint, set by `retrieval.embedding.baseUrl` and the rest. It decides which other `retrieval.embedding` fields apply: every provider but `openai` needs `model`, `openai-compatible` needs `baseUrl`, and `vertex` needs `projectId` and `location`. A `google` or `vertex` provider never reads `EMBEDDING_MODEL`, `EMBEDDING_API_BASE` or `EMBEDDING_DIMENSIONS`, which were only ever the OpenAI-compatible provider's.",
1368
+ notes: "Which provider serves embeddings. Unset: an OpenAI-compatible endpoint, set by `retrieval.embedding.baseUrl` and the rest. It decides which other `retrieval.embedding` fields apply: every provider but `openai` needs `model`, `openai-compatible` needs `baseUrl`, and `vertex` needs `projectId` and `location`. A `google` or `vertex` provider never reads `PUBLISHER_RETRIEVAL_EMBEDDING_MODEL`, `PUBLISHER_RETRIEVAL_EMBEDDING_BASE_URL` or `PUBLISHER_RETRIEVAL_EMBEDDING_DIMENSIONS`, which were only ever the OpenAI-compatible provider's.",
1372
1369
  defaultText: "_unset_ (OpenAI-compatible)",
1373
1370
  aliases: { file: ["retrieval.embedding.provider"] }
1374
1371
  }),
@@ -1398,14 +1395,6 @@ var init_retrieval = __esm(() => {
1398
1395
  defaultText: "empty",
1399
1396
  aliases: { file: ["retrieval.embedding.documentPrefix"] }
1400
1397
  }),
1401
- setting({
1402
- key: "retrieval.egress.preset",
1403
- type: oneOf(EGRESS_PRESETS),
1404
- description: "No longer read: #(index) alone decides whether a dimension's values reach the embedding provider and LLM. Setting it logs a startup warning.",
1405
- 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.",
1406
- defaultText: "_ignored_",
1407
- aliases: { file: ["retrieval.egress.preset"] }
1408
- }),
1409
1398
  setting({
1410
1399
  key: "retrieval.dimensionValues.enabled",
1411
1400
  type: boolean(),
@@ -1478,7 +1467,7 @@ var init_retrieval = __esm(() => {
1478
1467
  type: boolean(),
1479
1468
  default: false,
1480
1469
  description: "Let search_database_schema send a connection's table and column names to the embedding provider.",
1481
- notes: "Allows `search_database_schema` to send a connection's schema name, table names, column names and column types, plus the agent's search text, to the embedding endpoint for semantic ranking. Never row values. A second switch on top of `EMBEDDING_API_KEY`, which alone covers only your own model text; unset, schema search still works and ranks lexically. Accepts `1`/`true`/`yes`/`on` and `0`/`false`/`no`/`off`. It is read when the tool is called, not at startup, so an unrecognised value does not stop the server: the tool logs a warning and ranks lexically for that call. See \"Semantic ranking for search_database_schema\" below.",
1470
+ notes: "Allows `search_database_schema` to send a connection's schema name, table names, column names and column types, plus the agent's search text, to the embedding endpoint for semantic ranking. Never row values. A second switch on top of `PUBLISHER_RETRIEVAL_EMBEDDING_API_KEY`, which alone covers only your own model text; unset, schema search still works and ranks lexically. Accepts `1`/`true`/`yes`/`on` and `0`/`false`/`no`/`off`. It is read when the tool is called, not at startup, so an unrecognised value does not stop the server: the tool logs a warning and ranks lexically for that call. See \"Semantic ranking for search_database_schema\" below.",
1482
1471
  aliases: { env: ["EMBEDDING_INDEX_CONNECTION_SCHEMA"] }
1483
1472
  }),
1484
1473
  setting({
@@ -1575,15 +1564,6 @@ var init_server = __esm(() => {
1575
1564
  notes: "The request header whose value the per-query access record copies as `caller`: the identity the gateway in front of Publisher asserts. Opaque to Publisher; see [access-record.md](access-record.md).",
1576
1565
  aliases: { env: ["PUBLISHER_CALLER_HEADER"] }
1577
1566
  }),
1578
- setting({
1579
- key: "packageVersioning",
1580
- type: oneOf(["off", "on"]),
1581
- default: "on",
1582
- description: "on publishes a package from a location as the version its publisher.json declares; off installs it in place. A transition setting #1381 removes.",
1583
- notes: "`on` or `off`: whether a publish from a location publishes an immutable [package version](package-versions.md) numbered by its `publisher.json` `version` (a missing or non-semver `version` is then a 400), or installs the package in place as before versions. A transition setting: a future release removes it and requires a `version` ([#1381](https://github.com/malloydata/publisher/issues/1381)). Versions published while it was on keep serving when it is off. Any other value fails startup.",
1584
- noFlag: true,
1585
- aliases: { env: ["PUBLISHER_PACKAGE_VERSIONING"] }
1586
- }),
1587
1567
  setting({
1588
1568
  key: "versionPromotion",
1589
1569
  type: oneOf(["on-publish", "explicit"]),
@@ -1676,7 +1656,7 @@ var init_storage = __esm(() => {
1676
1656
  key: "duckdb.memoryLimit",
1677
1657
  type: string(),
1678
1658
  description: "memory_limit of every DuckDB session, as a DuckDB size (1GB), or off; unset warns at boot.",
1679
- notes: "DuckDB `memory_limit` applied to **every** DuckDB session and instance Publisher owns, as a flat value (`1GB`, `512MB`) passed to DuckDB verbatim. `off` or unset leaves DuckDB's own default, which is roughly 80% of the container's memory computed **per instance** — so N instances in one process commit N times that share, and the kernel kills the process while each of them still believes it is inside its budget. Measured in a 3 GiB container: three instances each reported a 2.3 GiB limit, 6.9 GiB of committed budget against 3 GiB of real memory. **Sizing:** the divisor is not a number of builds. Count 1 metadata store + 1 serve-shape gate session + 1 environment lookup funnel + one sandbox per loaded package × `PACKAGE_LOAD_WORKERS` (package loads run in `worker_threads`, so same address space and same cgroup) + one per in-flight materialization build, and nothing bounds concurrent builds. Budget roughly (container memory − resident baseline) ÷ that count. DuckDB does not reserve the limit up front, so an idle instance costs far less than its budget — the limit caps what it may reach, and it is the sum of the caps that has to fit. Too low fails a query with a DuckDB out-of-memory error and leaves the process up, which is the intended trade against losing the pod and every package on it. Validated at startup.",
1659
+ notes: "DuckDB `memory_limit` applied to **every** DuckDB session and instance Publisher owns, as a flat value (`1GB`, `512MB`) passed to DuckDB verbatim. `off` or unset leaves DuckDB's own default, which is roughly 80% of the container's memory computed **per instance** — so N instances in one process commit N times that share, and the kernel kills the process while each of them still believes it is inside its budget. Measured in a 3 GiB container: three instances each reported a 2.3 GiB limit, 6.9 GiB of committed budget against 3 GiB of real memory. **Sizing:** the divisor is not a number of builds. Count 1 metadata store + 1 serve-shape gate session + 1 environment lookup funnel + one sandbox per loaded package × `PUBLISHER_PACKAGE_LOAD_WORKERS` (package loads run in `worker_threads`, so same address space and same cgroup) + one per in-flight materialization build, and nothing bounds concurrent builds. Budget roughly (container memory − resident baseline) ÷ that count. DuckDB does not reserve the limit up front, so an idle instance costs far less than its budget — the limit caps what it may reach, and it is the sum of the caps that has to fit. Too low fails a query with a DuckDB out-of-memory error and leaves the process up, which is the intended trade against losing the pod and every package on it. Validated at startup.",
1680
1660
  aliases: { env: ["PUBLISHER_DUCKDB_MEMORY_LIMIT"] }
1681
1661
  }),
1682
1662
  setting({
@@ -1723,7 +1703,7 @@ var init_storage = __esm(() => {
1723
1703
  default: false,
1724
1704
  fileForbidden: true,
1725
1705
  description: "Simulated materialization: an authoring mode that makes no materialization write. A variable or flag only, never the config file.",
1726
- notes: "Simulated materialization, an authoring mode for a local watch-mode server: it is meant to plan, simulate the build of, and serve through the real router every materialized source of the watched packages, over tables that are never created, with rows coming back live. **What ships now is its guard, not the simulation**: while it is on, nothing materializes, so no package is served from a table. While it is on, the server makes no materialization write on any path. Every write route answers 409 `SIMULATION_ACTIVE`: creating a materialization (REST, the CLI and the scheduler), deleting one, dropping a materialized table, a storage destination's table drop and file cleanup, every admin catalog write, deleting or archiving a version, deleting a package that has versions, deleting an environment, changing watch mode at runtime, and binding a manifest (`PATCH …/packages/{pkg}` with a `manifestLocation`, `PUT …/versions/{v}/manifest`). The scheduler does not start and the reclaimer is skipped. No host manifest is bound and no table from this server's run store is rebound: a package or version with a `manifestLocation` serves live with a `simulation-manifest-bound` warning, and its manifest is never fetched. A storage destination entry of type `publisher` is accepted, but no lookup of a destination by name finds it and nothing queries through it. Startup fails (`PUBLISHER_INIT_FAILED`) with it on and `frozenConfig` on, or with no watched environment (`--watch-env`). A variable or flag only: a config file can travel between servers, so the file cannot turn it on. See [materialization.md](materialization.md#simulated-materialization-groundwork)."
1706
+ notes: "Simulated materialization, an authoring mode for a local watch-mode server: it plans, simulates the build of, and serves through the real router every materialized source of the packages watch mode mounts in place, over tables that are never created, with rows coming back live: the path report, the summary, the `/status` digest, the access record and the metrics say `mode: simulated`, and each item's facts say what is exact, predicted or knowable only on the host. Direct connections only in this release. While it is on, the server makes no materialization write on any path. Every write route answers 409 `SIMULATION_ACTIVE`: creating a materialization (REST, the CLI and the scheduler), deleting one, dropping a materialized table, a storage destination's table drop and file cleanup, every admin catalog write, deleting or archiving a version, deleting a package that has versions, deleting an environment, changing watch mode at runtime, and binding a manifest (`PATCH …/packages/{pkg}` with a `manifestLocation`, `PUT …/versions/{v}/manifest`). The scheduler does not start and the reclaimer is skipped. No host manifest is bound and no table from this server's run store is rebound: a package or version with a `manifestLocation` serves live with a `simulation-manifest-bound` warning, and its manifest is never fetched. A storage destination entry of type `publisher` is accepted, but no lookup of a destination by name finds it and nothing queries through it. Startup fails (`PUBLISHER_INIT_FAILED`) with it on and `frozenConfig` on, or with no watched environment (`--watch-env`). A variable or flag only: a config file can travel between servers, so the file cannot turn it on. See [materialization.md](materialization.md#simulated-materialization)."
1727
1707
  }),
1728
1708
  setting({
1729
1709
  key: "materialization.schedulerEnabled",
@@ -1741,16 +1721,6 @@ var init_storage = __esm(() => {
1741
1721
  notes: "How often the scheduler sweeps for due schedules, in ms. Minimum `1000`. Only read when the scheduler is enabled.",
1742
1722
  defaultText: "`60000` (1 min)",
1743
1723
  aliases: { env: ["PUBLISHER_MATERIALIZATION_SCHEDULER_INTERVAL_MS"] }
1744
- }),
1745
- setting({
1746
- key: "materialization.schedulerMaxFiresPerTick",
1747
- type: integer({ min: 1 }),
1748
- default: 10,
1749
- description: "Packages the scheduler fires per look.",
1750
- notes: "Stampede guard: max packages fired per sweep. A capped package fires on a later tick. Must be a positive integer.",
1751
- aliases: {
1752
- env: ["PUBLISHER_MATERIALIZATION_SCHEDULER_MAX_FIRES_PER_TICK"]
1753
- }
1754
1724
  })
1755
1725
  ];
1756
1726
  });
@@ -1819,6 +1789,60 @@ var init_retired = __esm(() => {
1819
1789
  flags: ["--materialize-gated-sources", "--no-materialize-gated-sources"],
1820
1790
  file: "materialize.gatedSources",
1821
1791
  now: "it stays off until a security review: a stored table answers past a row-level gate only under its source's own gate"
1792
+ },
1793
+ {
1794
+ key: "packageVersioning",
1795
+ env: ["PUBLISHER_PACKAGE_VERSIONING"],
1796
+ flags: [],
1797
+ file: "packageVersioning",
1798
+ now: "a publish from a location always publishes the immutable version its publisher.json declares, and a missing or non-semver version is refused (400)"
1799
+ },
1800
+ {
1801
+ key: "materialization.schedulerMaxFiresPerTick",
1802
+ env: ["PUBLISHER_MATERIALIZATION_SCHEDULER_MAX_FIRES_PER_TICK"],
1803
+ flags: ["--materialization-scheduler-max-fires-per-tick"],
1804
+ takesValue: true,
1805
+ file: "materialization.schedulerMaxFiresPerTick",
1806
+ now: "the scheduler fires at most 10 packages per sweep, and a capped package fires on a later one"
1807
+ },
1808
+ {
1809
+ key: "workloadLog.store",
1810
+ env: ["PUBLISHER_WORKLOAD_LOG_STORE"],
1811
+ flags: ["--workload-log-store"],
1812
+ takesValue: true,
1813
+ file: "workloadLog.store",
1814
+ now: "Publisher keeps no local copy of the access records; they go to the log only"
1815
+ },
1816
+ {
1817
+ key: "workloadLog.retentionDays",
1818
+ env: ["PUBLISHER_WORKLOAD_LOG_RETENTION_DAYS"],
1819
+ flags: ["--workload-log-retention-days"],
1820
+ takesValue: true,
1821
+ file: "workloadLog.retentionDays",
1822
+ now: "Publisher keeps no local copy of the access records; they go to the log only"
1823
+ },
1824
+ {
1825
+ key: "workloadLog.maxRows",
1826
+ env: ["PUBLISHER_WORKLOAD_LOG_MAX_ROWS"],
1827
+ flags: ["--workload-log-max-rows"],
1828
+ takesValue: true,
1829
+ file: "workloadLog.maxRows",
1830
+ now: "Publisher keeps no local copy of the access records; they go to the log only"
1831
+ },
1832
+ {
1833
+ key: "retrieval.egress.preset",
1834
+ env: ["PUBLISHER_RETRIEVAL_EGRESS_PRESET"],
1835
+ flags: ["--retrieval-egress-preset"],
1836
+ takesValue: true,
1837
+ file: "retrieval.egress",
1838
+ now: "the #(index) tag alone decides whether a dimension's values reach the configured embedding provider and LLM; to keep them on this machine, set retrieval.dimensionValues.enabled to false"
1839
+ },
1840
+ {
1841
+ key: "retrieval.indexing.maxEntities",
1842
+ env: [],
1843
+ flags: [],
1844
+ file: "retrieval.indexing",
1845
+ now: "the search index has no entity cap"
1822
1846
  }
1823
1847
  ];
1824
1848
  });
@@ -1947,6 +1971,8 @@ class Loader {
1947
1971
  deprecated = new Set;
1948
1972
  unknownFlags = [];
1949
1973
  flagsWithoutValue = [];
1974
+ retiredFlags = [];
1975
+ flagsAsValues = [];
1950
1976
  valuesAfterSwitches = [];
1951
1977
  file = {};
1952
1978
  configPath;
@@ -2009,16 +2035,29 @@ class Loader {
2009
2035
  filePaths(entry) {
2010
2036
  return namesOf(entry).file;
2011
2037
  }
2038
+ isFlagName(arg) {
2039
+ return this.byFlag.has(arg) || RETIRED_SETTINGS.some((r) => r.flags.some(namesFlag(arg)));
2040
+ }
2041
+ valueAfter(name, i) {
2042
+ const next = this.argv[i + 1];
2043
+ if (!next)
2044
+ return;
2045
+ if (this.isFlagName(next))
2046
+ this.flagsAsValues.push({ name, value: next });
2047
+ return next;
2048
+ }
2012
2049
  readFlags() {
2013
2050
  for (let i = 0;i < this.argv.length; i++) {
2014
2051
  const name = this.argv[i];
2015
2052
  const flag = this.byFlag.get(name);
2016
2053
  if (!flag) {
2017
2054
  const retired = RETIRED_SETTINGS.find((r) => r.flags.some(namesFlag(name)));
2018
- if (retired?.takesValue && !name.includes("=") && this.argv[i + 1] !== undefined) {
2019
- i++;
2055
+ if (retired) {
2056
+ if (this.readRetiredFlag(retired, name, i))
2057
+ i++;
2058
+ continue;
2020
2059
  }
2021
- if (name.startsWith("-") && name !== "--help" && name !== "-h" && !retired) {
2060
+ if (name.startsWith("-") && name !== "--help" && name !== "-h") {
2022
2061
  this.unknownFlags.push(name);
2023
2062
  }
2024
2063
  continue;
@@ -2030,7 +2069,7 @@ class Loader {
2030
2069
  if (next !== undefined && readsAsBoolean(flag.entry, next)) {
2031
2070
  this.valuesAfterSwitches.push({ name, flag, next });
2032
2071
  }
2033
- } else if (this.argv[i + 1]) {
2072
+ } else if (this.valueAfter(name, i) !== undefined) {
2034
2073
  raw = this.argv[i + 1];
2035
2074
  i++;
2036
2075
  } else {
@@ -2042,6 +2081,27 @@ class Loader {
2042
2081
  this.flags.set(flag.entry.key, hits);
2043
2082
  }
2044
2083
  }
2084
+ readRetiredFlag(retired, name, i) {
2085
+ if (!retired.takesValue) {
2086
+ this.retiredFlags.push({ retired, name });
2087
+ return false;
2088
+ }
2089
+ const joined = name.indexOf("=");
2090
+ if (joined !== -1) {
2091
+ if (name.slice(joined + 1).trim() !== "") {
2092
+ this.retiredFlags.push({ retired, name });
2093
+ }
2094
+ return false;
2095
+ }
2096
+ const value = this.valueAfter(name, i);
2097
+ if (value === undefined) {
2098
+ this.flagsWithoutValue.push(name);
2099
+ return false;
2100
+ }
2101
+ if (value.trim() !== "")
2102
+ this.retiredFlags.push({ retired, name });
2103
+ return true;
2104
+ }
2045
2105
  warnAboutFlags() {
2046
2106
  const current = [...this.byFlag].filter(([, flag]) => !flag.old).map(([name]) => name);
2047
2107
  for (const name of this.unknownFlags) {
@@ -2055,6 +2115,11 @@ class Loader {
2055
2115
  message: `${name} has no value after it, so it is ignored.`
2056
2116
  });
2057
2117
  }
2118
+ for (const { name, value } of this.flagsAsValues) {
2119
+ this.warnings.push({
2120
+ message: `${name} took '${value}' as its value, so ${value} is not read as a flag. If ${name} was meant to have a value of its own, write it after ${name}.`
2121
+ });
2122
+ }
2058
2123
  for (const { name, flag, next } of this.valuesAfterSwitches) {
2059
2124
  const on = flag.switches;
2060
2125
  const opposite = namesOf(flag.entry).flags.find((other) => !other.old && this.byFlag.get(other.name)?.switches === !on && this.byFlag.get(other.name)?.entry === flag.entry);
@@ -2065,6 +2130,16 @@ class Loader {
2065
2130
  }
2066
2131
  }
2067
2132
  warnAboutRetired() {
2133
+ const isSet = (value) => {
2134
+ if (value === undefined || value === null)
2135
+ return false;
2136
+ if (typeof value === "string")
2137
+ return value.trim() !== "";
2138
+ if (typeof value === "object") {
2139
+ return Object.values(value).some(isSet);
2140
+ }
2141
+ return true;
2142
+ };
2068
2143
  const fileHas = (key) => {
2069
2144
  let node = this.file;
2070
2145
  for (const part of key.split(".")) {
@@ -2073,12 +2148,12 @@ class Loader {
2073
2148
  }
2074
2149
  node = node[part];
2075
2150
  }
2076
- return true;
2151
+ return isSet(node);
2077
2152
  };
2078
2153
  for (const retired of RETIRED_SETTINGS) {
2079
2154
  const names = [
2080
- ...retired.env.filter((name) => this.env[name] !== undefined),
2081
- ...this.argv.filter((arg) => retired.flags.some((flag) => namesFlag(arg)(flag))),
2155
+ ...retired.env.filter((name) => isSet(this.env[name])),
2156
+ ...this.retiredFlags.filter((hit) => hit.retired === retired).map((hit) => hit.name),
2082
2157
  ...fileHas(retired.file) ? [
2083
2158
  `"${retired.file}" in ${this.configPath ?? PUBLISHER_CONFIG_NAME}`
2084
2159
  ] : []
@@ -2094,6 +2169,8 @@ class Loader {
2094
2169
  const read = this.registry.flatMap((entry) => this.filePaths(entry).map(({ path }) => path));
2095
2170
  const whole = new Set(this.registry.filter((entry) => entry.kind === "structured").flatMap((entry) => this.filePaths(entry).map(({ path }) => path)));
2096
2171
  const file = this.configPath ?? PUBLISHER_CONFIG_NAME;
2172
+ const unfiled = this.registry.filter((entry) => entry.kind === "launch" || entry.fileForbidden).map((entry) => entry.key);
2173
+ const otherNames = (entry) => entry.noFlag ? `a variable only (${derivedEnvName(entry.key)})` : `a variable or a flag only (${derivedEnvName(entry.key)}, ${derivedFlagName(entry.key)})`;
2097
2174
  const visit = (node, prefix) => {
2098
2175
  for (const [name, value] of Object.entries(node)) {
2099
2176
  const key = prefix ? `${prefix}.${name}` : name;
@@ -2101,7 +2178,7 @@ class Loader {
2101
2178
  continue;
2102
2179
  if (RETIRED_SETTINGS.some((r) => r.file === key))
2103
2180
  continue;
2104
- if (read.some((path) => path.startsWith(`${key}.`)) || RETIRED_SETTINGS.some((r) => r.file.startsWith(`${key}.`))) {
2181
+ if (read.some((path) => path.startsWith(`${key}.`)) || unfiled.some((path) => path.startsWith(`${key}.`)) || RETIRED_SETTINGS.some((r) => r.file.startsWith(`${key}.`))) {
2105
2182
  if (value && typeof value === "object" && !Array.isArray(value)) {
2106
2183
  visit(value, key);
2107
2184
  }
@@ -2110,13 +2187,13 @@ class Loader {
2110
2187
  const launch = this.byKey.get(key);
2111
2188
  if (launch?.kind === "launch") {
2112
2189
  this.warnings.push({
2113
- message: `"${key}" in ${file} is ignored: it decides which file is read, or must not come from one, so it is a variable or a flag only (${derivedEnvName(key)}, ${derivedFlagName(key)}).`
2190
+ message: `"${key}" in ${file} is ignored: it decides which file is read, or must not come from one, so it is ${otherNames(launch)}.`
2114
2191
  });
2115
2192
  continue;
2116
2193
  }
2117
2194
  if (launch?.fileForbidden) {
2118
2195
  this.warnings.push({
2119
- message: `"${key}" in ${file} is ignored: a config file can travel between servers, so it is a variable or a flag only (${derivedEnvName(key)}, ${derivedFlagName(key)}).`
2196
+ message: `"${key}" in ${file} is ignored: it is never read from a config file, so it is ${otherNames(launch)}.`
2120
2197
  });
2121
2198
  continue;
2122
2199
  }
@@ -12579,6 +12656,10 @@ var init_logger = __esm(() => {
12579
12656
  });
12580
12657
 
12581
12658
  // src/driver_errors.ts
12659
+ function hasDeterministicMarker(message) {
12660
+ const lower = message.toLowerCase();
12661
+ return DETERMINISTIC_MARKERS.some((m) => lower.includes(m));
12662
+ }
12582
12663
  function isMysqlConfigFault(code) {
12583
12664
  return typeof code === "string" && (MYSQL_CONFIG_CODES.has(code) || code.startsWith("HANDSHAKE_"));
12584
12665
  }
@@ -12703,8 +12784,20 @@ function isUnderStorageLocation(url, locations) {
12703
12784
  return prefix === "" || at.path === prefix || at.path.startsWith(`${prefix}/`);
12704
12785
  });
12705
12786
  }
12706
- var NODE_CONNECTION_CODES, POSTGRES_CONNECTION_SQLSTATE, CODELESS_CONNECTION_MESSAGES, MYSQL_CONFIG_CODES, SQLSERVER_CONNECTION_CODES, TLS_VERIFICATION_CODES, POSTGRES_AUTH_SQLSTATE, MYSQL_AUTH_CODES, SQLSERVER_AUTH_CODES, SNOWFLAKE_AUTH_CODES, OBJECT_STORE_REFUSAL, OTHER_OBJECT_STORE_REFUSALS;
12787
+ var DETERMINISTIC_MARKERS, NODE_CONNECTION_CODES, POSTGRES_CONNECTION_SQLSTATE, CODELESS_CONNECTION_MESSAGES, MYSQL_CONFIG_CODES, SQLSERVER_CONNECTION_CODES, TLS_VERIFICATION_CODES, POSTGRES_AUTH_SQLSTATE, MYSQL_AUTH_CODES, SQLSERVER_AUTH_CODES, SNOWFLAKE_AUTH_CODES, OBJECT_STORE_REFUSAL, OTHER_OBJECT_STORE_REFUSALS;
12707
12788
  var init_driver_errors = __esm(() => {
12789
+ DETERMINISTIC_MARKERS = [
12790
+ "failed to compile",
12791
+ "compilation error",
12792
+ "syntax error",
12793
+ "parser error",
12794
+ "invalid input syntax for type",
12795
+ "division by zero",
12796
+ "numeric field overflow",
12797
+ "value too long for type",
12798
+ "permission denied",
12799
+ "access denied"
12800
+ ];
12708
12801
  NODE_CONNECTION_CODES = new Set([
12709
12802
  "ECONNREFUSED",
12710
12803
  "ECONNRESET",
@@ -12890,6 +12983,9 @@ function httpError(code, message, reason) {
12890
12983
  }
12891
12984
  };
12892
12985
  }
12986
+ function noFreeDatabaseSessionMessage(name, max, waitSeconds) {
12987
+ return `Connection '${name}' ${NO_FREE_DATABASE_SESSION}: this server opens at most ${max} at a time for it, and none came free within ${waitSeconds} s. Retry once fewer queries are running on this connection.`;
12988
+ }
12893
12989
  function storageAccessFailure(error, subject, subjectKind = "source") {
12894
12990
  if (error instanceof StorageAccessDeniedError)
12895
12991
  return error;
@@ -12907,6 +13003,30 @@ function toQueryTextProblem(problem) {
12907
13003
  ...problem.at ? { at: { range: problem.at.range } } : {}
12908
13004
  };
12909
13005
  }
13006
+ function driverMessageOf(message) {
13007
+ let driverMessage = message;
13008
+ for (const prefix of SCHEMA_READ_PREFIXES) {
13009
+ driverMessage = driverMessage.replace(prefix, "");
13010
+ }
13011
+ return driverMessage;
13012
+ }
13013
+ function databaseBusyMarker(message) {
13014
+ if (!message || hasDeterministicMarker(message))
13015
+ return;
13016
+ const driverMessage = driverMessageOf(message);
13017
+ if (SESSION_CAP.test(driverMessage))
13018
+ return NO_FREE_DATABASE_SESSION;
13019
+ if (MYSQL_USER_CONNECTIONS.test(driverMessage)) {
13020
+ return "max_user_connections";
13021
+ }
13022
+ return DATABASE_BUSY_MARKERS.find((marker) => driverMessage.startsWith(marker));
13023
+ }
13024
+ function databaseRefusedRead(message) {
13025
+ if (!message || hasDeterministicMarker(message))
13026
+ return false;
13027
+ const driverMessage = driverMessageOf(message);
13028
+ return DATABASE_REFUSED_MARKERS.some((marker) => driverMessage.startsWith(marker)) || MYSQL_USER_CONNECTIONS.test(driverMessage) || driverMessage.startsWith("Connection terminated unexpectedly");
13029
+ }
12910
13030
  function errorKind(error) {
12911
13031
  if (error instanceof Error) {
12912
13032
  const kind = error.kind;
@@ -12926,7 +13046,7 @@ function errorMapping(error) {
12926
13046
  function errorReason(error) {
12927
13047
  return resolve(errorMapping(error).reason, error);
12928
13048
  }
12929
- 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, ContainerNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, ContractCaptureFailedError, SchemaIncompatibleError, UpstreamContractInsufficientError, UpstreamContractUnreadError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, SimulationActiveError, AccessDeniedError, INHERITED_FILTER_WHY, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, INDEX_SOURCE_UNBUILT_PHRASES, IndexSourceUnbuiltError, 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;
13049
+ 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, VersionRegistryUnboundError, 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, NO_FREE_DATABASE_SESSION = "has no free database session", ResultShapeError, DestinationNotFoundError, ContainerNotFoundError, StorageDestinationNotFoundError, StorageCatalogNotFoundError, ConnectionAuthError, StorageAccessDeniedError, UnsupportedCatalogFormatError, ModelCompilationError, VersionFilesMissingError, PackageManifestError, MaterializationEligibilityError, ChainedUpstreamMissingError, ChainedShapeNotCarriedError, ContractCaptureFailedError, SchemaIncompatibleError, UpstreamContractInsufficientError, UpstreamContractUnreadError, PublisherConfigError, ServerConfigurationError, FrozenConfigError, SimulationActiveError, AccessDeniedError, INHERITED_FILTER_WHY, QueryCompileError, NotQueryableError, OffSurfaceError, MaterializationNotFoundError, INDEX_SOURCE_UNBUILT_PHRASES, IndexSourceUnbuiltError, MaterializationConflictError, MaterializedTableDropRefusedError, WriteConflictError, InstalledFromLocationError, WriteRolledBackError, ManifestBindFailedError, WriteRollbackFailedError, ConnectionSaveError, WriteVerifyError, InvalidStateTransitionError, ServiceUnavailableError, DatabaseBusyError, DATABASE_REFUSED_MARKERS, DATABASE_BUSY_MARKERS, MYSQL_USER_CONNECTIONS, SESSION_CAP, SCHEMA_READ_PREFIXES, 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;
12930
13050
  var init_errors2 = __esm(() => {
12931
13051
  init_constants();
12932
13052
  init_logger();
@@ -12940,6 +13060,7 @@ var init_errors2 = __esm(() => {
12940
13060
  VERSION_NOT_FOUND: 404,
12941
13061
  VERSION_CONFLICT: 409,
12942
13062
  PACKAGE_IS_VERSIONED: 409,
13063
+ PACKAGE_NOT_VERSIONED: 409,
12943
13064
  VERSION_IS_LATEST: 409,
12944
13065
  VERSION_IS_LAST_ACTIVE: 409,
12945
13066
  VERSION_BUILDING: 409,
@@ -12991,6 +13112,15 @@ var init_errors2 = __esm(() => {
12991
13112
  "42P22"
12992
13113
  ]);
12993
13114
  POSTGRES_RELATION_MISSING = /^relation ".*" does not exist$/;
13115
+ VersionRegistryUnboundError = class VersionRegistryUnboundError extends Error {
13116
+ get kind() {
13117
+ return "version_registry_unbound";
13118
+ }
13119
+ constructor(environmentName) {
13120
+ super(`Environment ${environmentName} has no version registry bound yet, so it cannot publish a package version. Retry once the environment is added; if it persists, check the server log for why its database row was not written.`);
13121
+ this.name = "VersionRegistryUnboundError";
13122
+ }
13123
+ };
12994
13124
  BuildPlanUnavailableError = class BuildPlanUnavailableError extends Error {
12995
13125
  get kind() {
12996
13126
  return "build_plan_unavailable";
@@ -13622,6 +13752,43 @@ var init_errors2 = __esm(() => {
13622
13752
  super(message, options);
13623
13753
  }
13624
13754
  };
13755
+ DatabaseBusyError = class DatabaseBusyError extends ServiceUnavailableError {
13756
+ get kind() {
13757
+ return "database_busy";
13758
+ }
13759
+ connectionName;
13760
+ constructor(connectionName, detail) {
13761
+ super(`Connection '${connectionName}' could not serve a schema read while this package loaded, so the load stopped instead of compiling without it: ${detail}`);
13762
+ this.name = "DatabaseBusyError";
13763
+ this.connectionName = connectionName;
13764
+ }
13765
+ };
13766
+ DATABASE_REFUSED_MARKERS = [
13767
+ "sorry, too many clients already",
13768
+ "remaining connection slots are reserved",
13769
+ "too many connections for role",
13770
+ "too many connections for database",
13771
+ "the database system is starting up",
13772
+ "the database system is shutting down",
13773
+ "the database system is in recovery mode",
13774
+ "the database system is not yet accepting connections",
13775
+ "the database system is not accepting connections",
13776
+ "no more connections allowed",
13777
+ "Too many connections",
13778
+ "(EMAXCONNSESSION)"
13779
+ ];
13780
+ DATABASE_BUSY_MARKERS = [
13781
+ ...DATABASE_REFUSED_MARKERS,
13782
+ "out of shared memory",
13783
+ "canceling statement due to statement timeout",
13784
+ "(ECHECKOUTTIMEOUT)"
13785
+ ];
13786
+ MYSQL_USER_CONNECTIONS = /^User \S+ (already has more than|has exceeded the) 'max_user_connections' (active connections|resource)/;
13787
+ SESSION_CAP = new RegExp(`^Connection '[^']*' ${NO_FREE_DATABASE_SESSION}`);
13788
+ SCHEMA_READ_PREFIXES = [
13789
+ /^Error fetching schema for [^:]*: /,
13790
+ /^Invalid SQL, /
13791
+ ];
13625
13792
  PackageAdmissionRefusedError = class PackageAdmissionRefusedError extends ServiceUnavailableError {
13626
13793
  get kind() {
13627
13794
  return "package_admission_refused";
@@ -13662,6 +13829,7 @@ var init_errors2 = __esm(() => {
13662
13829
  package_version: PackageVersionError,
13663
13830
  build_plan_unavailable: BuildPlanUnavailableError,
13664
13831
  build_plan_refreshing: BuildPlanRefreshingError,
13832
+ version_registry_unbound: VersionRegistryUnboundError,
13665
13833
  not_implemented: NotImplementedError,
13666
13834
  bad_request: BadRequestError,
13667
13835
  table_ownership: TableOwnershipError,
@@ -13725,6 +13893,7 @@ var init_errors2 = __esm(() => {
13725
13893
  write_verify: WriteVerifyError,
13726
13894
  invalid_state_transition: InvalidStateTransitionError,
13727
13895
  service_unavailable: ServiceUnavailableError,
13896
+ database_busy: DatabaseBusyError,
13728
13897
  package_admission_refused: PackageAdmissionRefusedError,
13729
13898
  dry_run_capacity: DryRunCapacityError,
13730
13899
  payload_too_large: PayloadTooLargeError,
@@ -13902,6 +14071,16 @@ var init_errors2 = __esm(() => {
13902
14071
  },
13903
14072
  mcpSetup: "package"
13904
14073
  },
14074
+ version_registry_unbound: {
14075
+ status: 503,
14076
+ mcp: {
14077
+ advice: "fixed",
14078
+ suggestions: [
14079
+ "Retry once the environment is added; if it persists, the server log says why its database row was not written."
14080
+ ]
14081
+ },
14082
+ mcpSetup: "package"
14083
+ },
13905
14084
  connection_not_found: NOT_FOUND,
13906
14085
  storage_destination_not_found: {
13907
14086
  status: 404,
@@ -14070,6 +14249,17 @@ var init_errors2 = __esm(() => {
14070
14249
  mcp: { advice: "internal" }
14071
14250
  },
14072
14251
  service_unavailable: BACK_PRESSURE,
14252
+ database_busy: {
14253
+ status: 503,
14254
+ mcp: {
14255
+ advice: "fixed",
14256
+ suggestions: [
14257
+ "Retry in a minute or two: the package's database was busy, and the package itself may be fine.",
14258
+ "If this persists, reduce the load on that database, or raise PUBLISHER_POSTGRES_POOL_MAX when the message says this server opened all the sessions it may."
14259
+ ]
14260
+ },
14261
+ mcpSetup: "resource"
14262
+ },
14073
14263
  package_admission_refused: BACK_PRESSURE,
14074
14264
  dry_run_capacity: BACK_PRESSURE,
14075
14265
  payload_too_large: TOO_LARGE,
@@ -19161,7 +19351,6 @@ var init_dialect = __esm(() => {
19161
19351
  mergeGatedByServerVersion: false,
19162
19352
  pairDelta: false,
19163
19353
  transactionalSwap: false,
19164
- dependencyGuard: false,
19165
19354
  relationProbe: false,
19166
19355
  tableOwnership: false,
19167
19356
  needsQualifiedTable: false,
@@ -19178,6 +19367,7 @@ var init_dialect = __esm(() => {
19178
19367
  passthroughNumericAsDouble: false,
19179
19368
  catalogHidesTables: false,
19180
19369
  stringCollation: undefined,
19370
+ describesWithoutRunning: false,
19181
19371
  ungroupableTypes: undefined,
19182
19372
  binary64Types: undefined,
19183
19373
  containerCatalog: undefined
@@ -19199,6 +19389,7 @@ var init_dialect = __esm(() => {
19199
19389
  utcSessions: true,
19200
19390
  leafBudget: 120,
19201
19391
  stringCollation: "instance",
19392
+ describesWithoutRunning: true,
19202
19393
  binary64Types: ["DOUBLE", "FLOAT8"],
19203
19394
  containerCatalog: "duckdb_schemas"
19204
19395
  }),
@@ -19206,6 +19397,7 @@ var init_dialect = __esm(() => {
19206
19397
  ...NONE,
19207
19398
  containerCatalog: "pg_namespace",
19208
19399
  stringCollation: "column",
19400
+ describesWithoutRunning: true,
19209
19401
  passthroughNumericAsDouble: true,
19210
19402
  incrementalSourceRange: true,
19211
19403
  incrementalTargetDml: true,
@@ -19213,7 +19405,6 @@ var init_dialect = __esm(() => {
19213
19405
  mergeGatedByServerVersion: true,
19214
19406
  decodedTablePath: true,
19215
19407
  transactionalSwap: true,
19216
- dependencyGuard: true,
19217
19408
  relationProbe: true,
19218
19409
  tableOwnership: true,
19219
19410
  castsToIntegerType: true,
@@ -19246,10 +19437,12 @@ var init_dialect = __esm(() => {
19246
19437
  relationProbe: true,
19247
19438
  tableOwnership: true,
19248
19439
  needsQualifiedTable: true,
19440
+ nestedColumns: true,
19249
19441
  castsToIntegerType: true,
19250
19442
  onlyBigIntegerType: "INT64",
19251
19443
  leafBudget: 120,
19252
19444
  stringCollation: "dataset",
19445
+ describesWithoutRunning: true,
19253
19446
  containerCatalog: "dataset",
19254
19447
  ungroupableTypes: {
19255
19448
  malloy: ["json", "array", "record"],
@@ -19318,21 +19511,18 @@ var init_dialect = __esm(() => {
19318
19511
  });
19319
19512
 
19320
19513
  // src/service/materialization/domain/vocabulary.ts
19321
- var init_vocabulary = () => {};
19514
+ var LEGS;
19515
+ var init_vocabulary = __esm(() => {
19516
+ LEGS = ["view", "query", "rollup", "served"];
19517
+ });
19322
19518
 
19323
19519
  // src/service/materialization/domain/gate_policy.ts
19324
19520
  function ownRowLevelGate(t) {
19325
19521
  return t.gate?.rowLevel === true && t.gate.attributed && !t.gate.inheritedRowFilter;
19326
19522
  }
19327
- function materializedKeepsGates(t, s) {
19328
- return s.materialize && ownRowLevelGate(t);
19329
- }
19330
- function persistKeepsGates(t) {
19331
- return ownRowLevelGate(t);
19332
- }
19333
- function tableKeepsGates(t, s) {
19523
+ function tableKeepsGates(t) {
19334
19524
  const row = Object.hasOwn(ROWS, t.kind) ? ROWS[t.kind] : undefined;
19335
- return row ? row(t, s) === true : false;
19525
+ return row ? row(t) === true : false;
19336
19526
  }
19337
19527
  function gateColumnTypeExact(type, upstream) {
19338
19528
  if (upstream && FIXED_WIDTH_CHAR_TYPE.test(upstream.nativeType)) {
@@ -19358,39 +19548,35 @@ function g3Table(t) {
19358
19548
  function g3RollupTable(t) {
19359
19549
  return g3Table(t) || t.gatesReadNoColumn === true;
19360
19550
  }
19361
- function legMayPassGate(leg, s, ctx) {
19551
+ function legMayPassGate(leg) {
19362
19552
  switch (leg) {
19363
- case "view":
19364
- return s.gatedSources;
19365
19553
  case "rollup":
19366
19554
  case "served":
19367
- return s.gatedSources || ctx.databaseReadsKeepGates;
19555
+ return true;
19368
19556
  default:
19369
19557
  return false;
19370
19558
  }
19371
19559
  }
19372
- function answerKeepsGates(leg, tablesRead, s, ctx) {
19373
- if (!legMayPassGate(leg, s, ctx))
19560
+ function answerKeepsGates(leg, tablesRead) {
19561
+ if (!legMayPassGate(leg))
19374
19562
  return false;
19375
19563
  if (!tablesRead.every(gateColumnsExact))
19376
19564
  return false;
19377
- if (s.gatedSources)
19378
- return true;
19379
- if (!ctx.databaseReadsKeepGates || tablesRead.length === 0)
19565
+ if (tablesRead.length === 0)
19380
19566
  return false;
19381
19567
  if (leg === "served")
19382
19568
  return tablesRead.every(g3Table);
19383
19569
  return leg === "rollup" && tablesRead.every(g3RollupTable);
19384
19570
  }
19385
- var ROWS, GATE_LEGS, SERVING_GATE_CONTEXT, INEXACT_GATE_TYPE, FIXED_WIDTH_CHAR_TYPE;
19571
+ var ROWS, GATE_LEGS, INEXACT_GATE_TYPE, FIXED_WIDTH_CHAR_TYPE;
19386
19572
  var init_gate_policy = __esm(() => {
19387
19573
  init_vocabulary();
19388
19574
  init_dialect();
19389
19575
  ROWS = {
19390
- persist: (t) => persistKeepsGates(t),
19391
- materialize: (t, s) => materializedKeepsGates(t, s),
19392
- pair: (t, s) => materializedKeepsGates(t, s),
19393
- rollup: (t, s) => !t.v1 && t.baseGateProven === true && (t.gate?.lockOnly === true || s.gatedSources || ownRowLevelGate(t)),
19576
+ persist: (t) => ownRowLevelGate(t),
19577
+ materialize: (t) => ownRowLevelGate(t),
19578
+ pair: (t) => ownRowLevelGate(t),
19579
+ rollup: (t) => !t.declaredByPersist && t.baseGateProven === true && (t.gate?.lockOnly === true || ownRowLevelGate(t)),
19394
19580
  view: () => false
19395
19581
  };
19396
19582
  GATE_LEGS = [
@@ -19398,9 +19584,6 @@ var init_gate_policy = __esm(() => {
19398
19584
  "rollup",
19399
19585
  "served"
19400
19586
  ];
19401
- SERVING_GATE_CONTEXT = {
19402
- databaseReadsKeepGates: true
19403
- };
19404
19587
  INEXACT_GATE_TYPE = /\b(DOUBLE|FLOAT[0-9]*|REAL|HUGEINT|UHUGEINT|U?INT128)\b/i;
19405
19588
  FIXED_WIDTH_CHAR_TYPE = /^\s*(bpchar|n?char|character|national\s+char(acter)?)\b(?!\s+varying)/i;
19406
19589
  });
@@ -19792,7 +19975,7 @@ function declaredMoves(contract, declared) {
19792
19975
  return now !== undefined && now !== "" && now !== c.declaredType ? [c.name] : [];
19793
19976
  });
19794
19977
  }
19795
- var CONTRACT_VERSION = 1, COMPARES, FIRST_RELEASE_READING_DATASET_CATALOGS, DUCKDB_GEOMETRY_CRS, COMPARE_RANK;
19978
+ var CONTRACT_VERSION = 1, COMPARES, FIRST_RELEASE_READING_DATASET_CATALOGS, DUCKDB_GEOMETRY_CRS, COMPARE_RANK, INCOMPATIBLE_CODES;
19796
19979
  var init_column_contract = __esm(() => {
19797
19980
  init_collation();
19798
19981
  init_dialect();
@@ -19805,6 +19988,12 @@ var init_column_contract = __esm(() => {
19805
19988
  equality: 1,
19806
19989
  exact: 2
19807
19990
  };
19991
+ INCOMPATIBLE_CODES = [
19992
+ "column_gone",
19993
+ "column_retyped",
19994
+ "collation_changed",
19995
+ "declared_moved"
19996
+ ];
19808
19997
  });
19809
19998
 
19810
19999
  // src/service/materialization/domain/table_plans.ts
@@ -19859,6 +20048,18 @@ function pairLeafContractKeys(plan) {
19859
20048
  return contractKeyName("leaf", leaf.names.join("."), leaf.keyColumn);
19860
20049
  });
19861
20050
  }
20051
+ function pairLevelRowColumn(level) {
20052
+ return level === 1 ? "__child_row" : `__child_row_${level}`;
20053
+ }
20054
+ function pairKeyColumns(pair) {
20055
+ const names = [pair.join];
20056
+ const keys = [pair.parentKey, `${pair.join}__${pair.childKey}`];
20057
+ for (const hop of pair.hops ?? []) {
20058
+ names.push(hop.join);
20059
+ keys.push(`${names.join("__")}__${hop.key}`);
20060
+ }
20061
+ return keys;
20062
+ }
19862
20063
  function pairLeavesOf(plan) {
19863
20064
  return pairPathsOf(plan).map((p) => {
19864
20065
  const leaf = pairLeafPath(p);
@@ -20099,7 +20300,22 @@ function joinsBeyondInferredBase(def, ctx) {
20099
20300
  const baseFields = new Set((inferred?.fields ?? []).map(fieldKey));
20100
20301
  return (def.fields ?? []).filter((f) => !baseFields.has(fieldKey(f)));
20101
20302
  }
20102
- function reachPersisted(ctx, name, isPersisted) {
20303
+ function joinsHeldOnChain(chain, sourceID, storedJoins) {
20304
+ const held = new Set;
20305
+ if (typeof sourceID !== "string" || !storedJoins)
20306
+ return held;
20307
+ let at = sourceID;
20308
+ let hop;
20309
+ for (let hops = 0;at !== undefined && hop !== "query" && hops < 64; hops++) {
20310
+ for (const join of storedJoins(at) ?? [])
20311
+ held.add(join);
20312
+ const next = chain.node(at)?.base;
20313
+ hop = next?.hop;
20314
+ at = next?.sourceID;
20315
+ }
20316
+ return held;
20317
+ }
20318
+ function reachPersisted(ctx, name, isPersisted, storedJoins) {
20103
20319
  const persisted = new Map;
20104
20320
  const chain = SourceMap.of({ contents: ctx.contents });
20105
20321
  const chainedOver = (sourceID) => {
@@ -20151,10 +20367,11 @@ function reachPersisted(ctx, name, isPersisted) {
20151
20367
  }
20152
20368
  reachRaw("(unnamed)", via);
20153
20369
  };
20154
- const followJoins = (fields, sourceName) => {
20370
+ const followJoins = (fields, sourceName, heldBy) => {
20371
+ const held = joinsHeldOnChain(chain, heldBy, storedJoins);
20155
20372
  for (const field of fields ?? []) {
20156
20373
  const f = field;
20157
- if (typeof f.join !== "string")
20374
+ if (typeof f.join !== "string" || held.has(fieldKey(field)))
20158
20375
  continue;
20159
20376
  follow(typeof f.sourceID === "string" ? f.sourceID : field, sourceName);
20160
20377
  }
@@ -20176,7 +20393,7 @@ function reachPersisted(ctx, name, isPersisted) {
20176
20393
  if (typeof def.extends === "string") {
20177
20394
  followJoins(ownJoins(def, ctx), sourceName);
20178
20395
  } else if (def.type !== "query_source") {
20179
- followJoins(joinsBeyondInferredBase(def, ctx), sourceName);
20396
+ followJoins(joinsBeyondInferredBase(def, ctx), sourceName, sourceID);
20180
20397
  }
20181
20398
  return;
20182
20399
  }
@@ -20208,7 +20425,7 @@ function reachPersisted(ctx, name, isPersisted) {
20208
20425
  follow(ref, label);
20209
20426
  }
20210
20427
  }
20211
- followJoins(def.fields, label);
20428
+ followJoins(def.fields, label, def.extends);
20212
20429
  };
20213
20430
  visit(ctx.contents[name], name, true, name);
20214
20431
  return {
@@ -20456,6 +20673,29 @@ var init_data_styles = __esm(() => {
20456
20673
 
20457
20674
  // src/path_safety.ts
20458
20675
  import * as path3 from "path";
20676
+ function caseVariantOf(name, existing) {
20677
+ const folded = name.toLowerCase();
20678
+ for (const other of existing) {
20679
+ if (other !== name && other.toLowerCase() === folded)
20680
+ return other;
20681
+ }
20682
+ return;
20683
+ }
20684
+ function assertNoCaseVariantEnvironment(name, existing) {
20685
+ const variant = caseVariantOf(name, existing);
20686
+ if (variant !== undefined) {
20687
+ throw new BadRequestError(`Environment name "${name}" differs only in letter case from the ` + `existing environment "${variant}". Environment names must ` + `differ in more than case; choose another name.`);
20688
+ }
20689
+ }
20690
+ function assertBodyNamesPath(kind, pathName, body) {
20691
+ const bodyName = body !== null && typeof body === "object" ? body.name : undefined;
20692
+ if (bodyName === undefined || bodyName === pathName)
20693
+ return;
20694
+ if (typeof bodyName !== "string") {
20695
+ throw new BadRequestError(`The body's name must be a string.`);
20696
+ }
20697
+ throw new BadRequestError(`The body names ${kind} ${JSON.stringify(bodyName)}, but the URL names ` + `${JSON.stringify(pathName)}. A ${kind} write applies only to the ` + `${kind} its URL names, and cannot rename it.`);
20698
+ }
20459
20699
  function assertSafePackageName(packageName) {
20460
20700
  if (typeof packageName !== "string" || !SAFE_NAME_RE.test(packageName)) {
20461
20701
  throw new BadRequestError(`Invalid package name: must be 1-255 characters of letters, digits, "-", "_", or "." and must not start with "."`);
@@ -20513,6 +20753,7 @@ var init_path_safety = __esm(() => {
20513
20753
 
20514
20754
  // src/utils.ts
20515
20755
  import { MalloyError as MalloyError2 } from "@malloydata/malloy";
20756
+ import { createHash as createHash2 } from "crypto";
20516
20757
  import * as fs3 from "fs";
20517
20758
  import * as path4 from "path";
20518
20759
  import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL3 } from "url";
@@ -20730,11 +20971,15 @@ function compiledImports(modelDef) {
20730
20971
  }
20731
20972
  function compiledTextReader(modelDef, packageRoot) {
20732
20973
  let allowed;
20974
+ const recorded = compiledTextsOf(modelDef);
20733
20975
  return (url) => {
20734
20976
  allowed ??= compiledFileUrls(modelDef);
20735
20977
  const href = hrefOf(url);
20736
20978
  if (href === undefined || !allowed.has(href))
20737
20979
  return;
20980
+ const kept = recorded?.get(href);
20981
+ if (kept !== undefined)
20982
+ return kept;
20738
20983
  try {
20739
20984
  return packageRoot !== undefined ? readPackageURLSync(packageRoot, href) : fs3.readFileSync(fileURLToPath3(href), "utf8");
20740
20985
  } catch {
@@ -20742,6 +20987,32 @@ function compiledTextReader(modelDef, packageRoot) {
20742
20987
  }
20743
20988
  };
20744
20989
  }
20990
+ function recordCompiledTexts(packageRoot, modelDef, digests) {
20991
+ if (!modelDef || typeof modelDef !== "object" || digests.size === 0) {
20992
+ return false;
20993
+ }
20994
+ const texts = new Map;
20995
+ for (const [url, digest] of digests) {
20996
+ const href = hrefOf(url);
20997
+ if (href === undefined)
20998
+ return false;
20999
+ let text;
21000
+ try {
21001
+ text = readPackageURLSync(packageRoot, href);
21002
+ } catch {
21003
+ return false;
21004
+ }
21005
+ if (createHash2("sha256").update(text).digest("hex") !== digest) {
21006
+ return false;
21007
+ }
21008
+ texts.set(href, text);
21009
+ }
21010
+ compiledTexts.set(modelDef, texts);
21011
+ return true;
21012
+ }
21013
+ function compiledTextsOf(modelDef) {
21014
+ return modelDef && typeof modelDef === "object" ? compiledTexts.get(modelDef) : undefined;
21015
+ }
20745
21016
  function packageURLReader(packageRoot) {
20746
21017
  return { readURL: (url) => readPackageURL(packageRoot, url) };
20747
21018
  }
@@ -20791,7 +21062,7 @@ function ignoreDotfiles(file) {
20791
21062
  function errMessage(err) {
20792
21063
  return err instanceof Error ? err.message : String(err);
20793
21064
  }
20794
- var IMPORT_OUTSIDE_PACKAGE_MESSAGE = "imports must stay inside the package", ImportOutsidePackageError, MAX_LINK_HOPS = 40;
21065
+ var IMPORT_OUTSIDE_PACKAGE_MESSAGE = "imports must stay inside the package", ImportOutsidePackageError, MAX_LINK_HOPS = 40, compiledTexts;
20795
21066
  var init_utils = __esm(() => {
20796
21067
  init_path_safety();
20797
21068
  ImportOutsidePackageError = class ImportOutsidePackageError extends Error {
@@ -20800,6 +21071,7 @@ var init_utils = __esm(() => {
20800
21071
  this.name = "ImportOutsidePackageError";
20801
21072
  }
20802
21073
  };
21074
+ compiledTexts = new WeakMap;
20803
21075
  });
20804
21076
 
20805
21077
  // src/service/deprecated/malloynb.ts
@@ -21892,7 +22164,19 @@ function finalizeOmissions(recorded, planned) {
21892
22164
  omittedFiles: [...files.values()].sort(byKey((e) => e.file))
21893
22165
  };
21894
22166
  }
21895
- var byKey = (key) => (a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0;
22167
+ var OMITTED_SOURCE_REASONS, byKey = (key) => (a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0;
22168
+ var init_omitted_sources = __esm(() => {
22169
+ OMITTED_SOURCE_REASONS = [
22170
+ "unkeyable",
22171
+ "eligibility_check_failed",
22172
+ "projection_failed",
22173
+ "rollup_companion_failed",
22174
+ "rollup_companion_blanking_failed",
22175
+ "materialize_companion_failed",
22176
+ "persisted_view_companion_failed",
22177
+ "persist_companion_failed"
22178
+ ];
22179
+ });
21896
22180
 
21897
22181
  // src/service/malloy_lexer_core.ts
21898
22182
  function isNameCode(code, text, at) {
@@ -22651,6 +22935,7 @@ function declaredInModel(modelFile, otherScheme) {
22651
22935
  }
22652
22936
  var COMPANION_FAILED;
22653
22937
  var init_generated_files = __esm(() => {
22938
+ init_omitted_sources();
22654
22939
  init_overlay_key();
22655
22940
  init_persist_blanking();
22656
22941
  COMPANION_FAILED = {
@@ -22658,7 +22943,6 @@ var init_generated_files = __esm(() => {
22658
22943
  rollup_blanking: "rollup_companion_blanking_failed",
22659
22944
  materialize: "materialize_companion_failed",
22660
22945
  persisted_view: "persisted_view_companion_failed",
22661
- v1_build: "v1_build_companion_failed",
22662
22946
  persist: "persist_companion_failed"
22663
22947
  };
22664
22948
  });
@@ -22670,11 +22954,104 @@ function packageFiles(packagePath, modelPath, config) {
22670
22954
  return { runtime, importBaseURL, modelURL };
22671
22955
  });
22672
22956
  }
22957
+ function servedPackageFiles(packagePath, modelPath, config, recorded) {
22958
+ if (!recorded)
22959
+ return packageFiles(packagePath, modelPath, config);
22960
+ const base = keyedOverlay(recorded);
22961
+ return GeneratedFiles.over(async (overlay) => {
22962
+ const { runtime, importBaseURL, modelURL } = await createModelRuntime(packagePath, modelPath, config, { overlay: new Map([...base, ...overlay]) });
22963
+ return { runtime, importBaseURL, modelURL };
22964
+ });
22965
+ }
22673
22966
  var init_package_files = __esm(() => {
22674
22967
  init_model_runtime();
22968
+ init_overlay_key();
22675
22969
  init_generated_files();
22676
22970
  });
22677
22971
 
22972
+ // src/service/materialization/text/pair_reroot.ts
22973
+ function pairsOf(plan) {
22974
+ return plan.pairBlocks?.blocks ?? (plan.pair ? [plan.pair] : []);
22975
+ }
22976
+ function pairRerootJoins(plan) {
22977
+ return pairsOf(plan).map((p) => p.join);
22978
+ }
22979
+ function pairRerootBase(plan, options = {}) {
22980
+ const pairs = pairsOf(plan);
22981
+ if (pairs.length === 0)
22982
+ return;
22983
+ const mat = options.from ?? identifier(plan.buildSourceName);
22984
+ const firstJoins = new Set(pairs.map((p) => p.join));
22985
+ const lane = plan.pairBlocks?.laneColumn;
22986
+ const laneTerm = (k) => lane === undefined ? [] : [`${identifier(lane)} = ${k}`];
22987
+ const own = plan.columns.filter((c) => (c.join === undefined || !firstJoins.has(c.join)) && (options.columns === undefined || options.columns.has(c.column)));
22988
+ if (own.length === 0)
22989
+ return;
22990
+ const parentKey = pairs[0].parentKey;
22991
+ const parentWhere = [identifier(pairs[0].parentRowColumn), ...laneTerm(0)];
22992
+ const joins = [];
22993
+ for (const [k, pair] of pairs.entries()) {
22994
+ const join = levelJoin(plan, pair, 1, parentKey, laneTerm(k), mat);
22995
+ if (join === undefined)
22996
+ return;
22997
+ joins.push(...indented(join));
22998
+ }
22999
+ return `${mat} -> {
23000
+ where: ${parentWhere.join(" and ")}
23001
+ ` + ` select: ${own.map((c) => identifier(c.column)).join(", ")}
23002
+ ` + `} extend {
23003
+ primary_key: ${identifier(parentKey)}
23004
+ ${joins.join(`
23005
+ `)}
23006
+ }`;
23007
+ }
23008
+ function levelJoin(plan, pair, level, parentField, laneTerms, mat) {
23009
+ const names = [pair.join, ...(pair.hops ?? []).map((h) => h.join)];
23010
+ const keyFields = [pair.childKey, ...(pair.hops ?? []).map((h) => h.key)];
23011
+ const keyColumns = pairKeyColumns(pair);
23012
+ const depth = names.length;
23013
+ const columns = plan.columns.filter((c) => c.join === pair.join && pathOf(c).length === level);
23014
+ const keyField = keyFields[level - 1];
23015
+ const keyColumn = keyColumns[level];
23016
+ if (!columns.some((c) => c.column === keyColumn))
23017
+ return;
23018
+ const where = [
23019
+ ...level < depth ? [identifier(pairLevelRowColumn(level))] : [],
23020
+ `${identifier(keyColumn)} is not null`,
23021
+ ...laneTerms
23022
+ ];
23023
+ const select = [
23024
+ `${identifier(PAIR_PARENT_KEY_FIELD)} is ${identifier(keyColumns[level - 1])}`,
23025
+ ...columns.map((c) => `${identifier(c.dimension)} is ${identifier(c.column)}`)
23026
+ ];
23027
+ const inner = level < depth ? levelJoin(plan, pair, level + 1, keyField, laneTerms, mat) : "";
23028
+ if (inner === undefined)
23029
+ return;
23030
+ const name = identifier(names[level - 1]);
23031
+ const head = [
23032
+ `join_many: ${name} is ${mat} -> {`,
23033
+ ` where: ${where.join(" and ")}`,
23034
+ ` select: ${select.join(", ")}`,
23035
+ "} extend {",
23036
+ ` primary_key: ${identifier(keyField)}`
23037
+ ];
23038
+ const tail = `} on ${name}.${identifier(PAIR_PARENT_KEY_FIELD)} = ${identifier(parentField)}`;
23039
+ return [...head, ...indented(inner), tail].join(`
23040
+ `);
23041
+ }
23042
+ function indented(text) {
23043
+ return text === "" ? [] : text.split(`
23044
+ `).map((line) => " " + line);
23045
+ }
23046
+ function pathOf(c) {
23047
+ return c.path ?? (c.join !== undefined ? [c.join] : []);
23048
+ }
23049
+ var PAIR_PARENT_KEY_FIELD = "__pair_parent_key";
23050
+ var init_pair_reroot = __esm(() => {
23051
+ init_malloy_text();
23052
+ init_table_plans();
23053
+ });
23054
+
22678
23055
  // src/service/materialization/text/definition_cut.ts
22679
23056
  function statementsOf(text, tokens) {
22680
23057
  const out = [];
@@ -22885,7 +23262,10 @@ function chainBuildFileSet(args) {
22885
23262
  }
22886
23263
  const isStored = (n, id) => stored.has(id) || storedNames.has(n);
22887
23264
  const own = lift.contents[downstreamName];
22888
- const reached = typeof own?.sourceID === "string" && isStored(downstreamName, own.sourceID) ? { raw: false, rawLeaves: [], visited: [] } : reachPersisted(lift, downstreamName, isStored);
23265
+ const reached = typeof own?.sourceID === "string" && isStored(downstreamName, own.sourceID) ? { raw: false, rawLeaves: [], visited: [] } : reachPersisted(lift, downstreamName, isStored, (sourceID) => {
23266
+ const joins = args.reroots.find((r) => r.sourceID === sourceID)?.storedJoins;
23267
+ return joins ? new Set(joins) : undefined;
23268
+ });
22889
23269
  if (reached.raw) {
22890
23270
  return why(`it reads ${reached.rawLeaves.join(", ")}, which no re-rooted upstream stands in for`);
22891
23271
  }
@@ -31721,9 +32101,6 @@ function quoteIdentifier(identifier, dialect) {
31721
32101
  }
31722
32102
  return '"' + identifier.replace(/"/g, '""') + '"';
31723
32103
  }
31724
- function decodeBackslashEscapes(sql, dialect) {
31725
- return dialect === "standardsql" ? sql.replace(/\\(.)/g, "$1") : sql;
31726
- }
31727
32104
  function quoteTablePath(tableName, dialect) {
31728
32105
  return quotePathParts(tableName.split("."), dialect);
31729
32106
  }
@@ -32062,11 +32439,75 @@ function storedColumnsOfOutput(fields, options) {
32062
32439
  return out;
32063
32440
  }
32064
32441
  function spelledNativeType(nativeType, dialect) {
32442
+ if (ANGLE_NESTED.test(nativeType)) {
32443
+ return capabilitiesOf(dialect).nestedColumns ? spelledAngleNested(nativeType, dialect, 0) : undefined;
32444
+ }
32065
32445
  if (isArrayType(nativeType))
32066
32446
  return;
32447
+ return spelledScalar(nativeType, dialect);
32448
+ }
32449
+ function spelledScalar(nativeType, dialect) {
32067
32450
  const [spelled] = storedColumnsOfOutput([{ name: "c", ...getDialect(dialect).sqlTypeToMalloyType(nativeType) }], { nested: false, bigint: true, timestamptz: true });
32068
32451
  return spelled?.type;
32069
32452
  }
32453
+ function spelledAngleNested(nativeType, dialect, depth) {
32454
+ if (depth > 16)
32455
+ return;
32456
+ const type = nativeType.trim();
32457
+ const nested = /^(ARRAY|STRUCT)\s*<([\s\S]*)>$/i.exec(type);
32458
+ if (!nested) {
32459
+ return /[<>]/.test(type) ? undefined : spelledScalar(type, dialect);
32460
+ }
32461
+ const [, kind, body] = nested;
32462
+ if (kind.toUpperCase() === "ARRAY") {
32463
+ const element = spelledAngleNested(body, dialect, depth + 1);
32464
+ return element === undefined ? undefined : `${element}[]`;
32465
+ }
32466
+ const members = splitTopLevel(body);
32467
+ if (members === undefined)
32468
+ return;
32469
+ const parts = [];
32470
+ for (const member of members) {
32471
+ const m = STRUCT_MEMBER.exec(member);
32472
+ if (!m)
32473
+ return;
32474
+ const name = m[1] ?? m[2];
32475
+ const spelled = spelledAngleNested(m[3], dialect, depth + 1);
32476
+ if (spelled === undefined)
32477
+ return;
32478
+ parts.push(`"${name.replace(/"/g, '""')}" ${spelled}`);
32479
+ }
32480
+ return `STRUCT(${parts.join(", ")})`;
32481
+ }
32482
+ function splitTopLevel(text) {
32483
+ const out = [];
32484
+ let depth = 0;
32485
+ let quoted = false;
32486
+ let start = 0;
32487
+ for (let i = 0;i < text.length; i++) {
32488
+ const ch = text[i];
32489
+ if (quoted) {
32490
+ if (ch === "\\")
32491
+ i++;
32492
+ else if (ch === "`")
32493
+ quoted = false;
32494
+ } else if (ch === "`") {
32495
+ quoted = true;
32496
+ } else if (ch === "<" || ch === "(") {
32497
+ depth++;
32498
+ } else if (ch === ">" || ch === ")") {
32499
+ if (--depth < 0)
32500
+ return;
32501
+ } else if (ch === "," && depth === 0) {
32502
+ out.push(text.slice(start, i));
32503
+ start = i + 1;
32504
+ }
32505
+ }
32506
+ if (depth !== 0 || quoted)
32507
+ return;
32508
+ out.push(text.slice(start));
32509
+ return out;
32510
+ }
32070
32511
  function isStringNativeType(nativeType, dialect) {
32071
32512
  try {
32072
32513
  return getDialect(dialect).sqlTypeToMalloyType(nativeType).type === "string";
@@ -32325,9 +32766,12 @@ function fitStoredType(t, field, keepsBigIntegers) {
32325
32766
  const liveFields = live.fields;
32326
32767
  if (liveFields.length !== t.fields.length)
32327
32768
  return;
32769
+ const matched = new Set;
32328
32770
  const parts = [];
32329
32771
  for (const f of t.fields) {
32330
- const match = liveFields.find((l) => (l.as ?? l.name) === f.name);
32772
+ const match = liveFields.find((l) => (l.as ?? l.name) === f.name && !matched.has(l));
32773
+ if (match)
32774
+ matched.add(match);
32331
32775
  const inner = match && fitStoredType(f.type, match, keepsBigIntegers);
32332
32776
  if (!inner)
32333
32777
  return;
@@ -32478,7 +32922,7 @@ function storedClass(nativeType) {
32478
32922
  return "decimal";
32479
32923
  return spelled;
32480
32924
  }
32481
- var STORED_COLUMN_TYPE_MISMATCH_CODE = "storage-column-type-mismatch", BUILD_CAST_TARGETS, CHECKED_TYPES, EXACT_INTEGER_STORAGE_TYPE = "DECIMAL(38,0)", INTEGER_TYPES, TIMESTAMPTZ_TYPES, NAIVE_TIMESTAMP_TYPES, HUGEINT_EXACT, NUMERIC_CLASSES;
32925
+ var STORED_COLUMN_TYPE_MISMATCH_CODE = "storage-column-type-mismatch", BUILD_CAST_TARGETS, CHECKED_TYPES, EXACT_INTEGER_STORAGE_TYPE = "DECIMAL(38,0)", INTEGER_TYPES, TIMESTAMPTZ_TYPES, NAIVE_TIMESTAMP_TYPES, ANGLE_NESTED, STRUCT_MEMBER, HUGEINT_EXACT, NUMERIC_CLASSES;
32482
32926
  var init_stored_column_types = __esm(() => {
32483
32927
  init_dialect();
32484
32928
  init_live_big_integers();
@@ -32500,6 +32944,8 @@ var init_stored_column_types = __esm(() => {
32500
32944
  INTEGER_TYPES = /^(TINYINT|SMALLINT|INTEGER|INT|INT1|INT2|INT4|INT8|BIGINT|HUGEINT|UTINYINT|USMALLINT|UINTEGER|UBIGINT|UHUGEINT|SHORT|LONG|SIGNED)$/;
32501
32945
  TIMESTAMPTZ_TYPES = /^(TIMESTAMP WITH TIME ZONE|TIMESTAMPTZ)$/;
32502
32946
  NAIVE_TIMESTAMP_TYPES = /^(TIMESTAMP|TIMESTAMP_S|TIMESTAMP_MS|TIMESTAMP_NS|TIMESTAMP_US|DATETIME)$/;
32947
+ ANGLE_NESTED = /^\s*(ARRAY|STRUCT)\s*</i;
32948
+ STRUCT_MEMBER = /^\s*(?:`((?:[^`\\]|\\.)+)`|([A-Za-z_][A-Za-z0-9_]*))\s+([\s\S]+)$/;
32503
32949
  HUGEINT_EXACT = /^(TINYINT|SMALLINT|INTEGER|INT|INT1|INT2|INT4|INT8|BIGINT|HUGEINT|INT128|UTINYINT|USMALLINT|UINTEGER|UBIGINT|SHORT|LONG|SIGNED|(DECIMAL|NUMERIC)\(\s*\d+\s*,\s*0\s*\))$/;
32504
32950
  NUMERIC_CLASSES = new Set(["integer", "float", "decimal"]);
32505
32951
  });
@@ -32537,7 +32983,7 @@ function fieldsByName(fields) {
32537
32983
  }
32538
32984
  return out;
32539
32985
  }
32540
- function pathOf(n) {
32986
+ function pathOf2(n) {
32541
32987
  return Array.isArray(n.path) && n.path.every((p) => typeof p === "string") ? n.path : undefined;
32542
32988
  }
32543
32989
  function children(n) {
@@ -32646,7 +33092,7 @@ class Walker {
32646
33092
  throw new Refusal("an aggregate where a value was expected");
32647
33093
  }
32648
33094
  if (n.node === "field") {
32649
- const p = pathOf(n);
33095
+ const p = pathOf2(n);
32650
33096
  if (!p)
32651
33097
  throw new Refusal("a field reference that cannot be read");
32652
33098
  return this.readsOfPath(p, depth + 1);
@@ -32704,7 +33150,7 @@ class Walker {
32704
33150
  let present = ctx.present ?? [];
32705
33151
  for (const c of Array.isArray(kids.filterList) ? kids.filterList : []) {
32706
33152
  const e = c.e ?? {};
32707
- const named = e.node === "field" ? pathOf(e) : undefined;
33153
+ const named = e.node === "field" ? pathOf2(e) : undefined;
32708
33154
  const presentAt = this.presentLevel(named);
32709
33155
  if (presentAt !== undefined) {
32710
33156
  present = [...present, presentAt];
@@ -32726,7 +33172,7 @@ class Walker {
32726
33172
  return;
32727
33173
  }
32728
33174
  case "field": {
32729
- const p = pathOf(n);
33175
+ const p = pathOf2(n);
32730
33176
  if (!p)
32731
33177
  throw new Refusal("a field reference that cannot be read");
32732
33178
  if (p.length === 1) {
@@ -32817,7 +33263,7 @@ function pairMeasurePresence(sourceFields, pair) {
32817
33263
  }
32818
33264
  function storedColumnOf(pair, level, aggregate) {
32819
33265
  const arg = aggregate.e ?? {};
32820
- const path = arg.node === "field" ? pathOf(arg) : undefined;
33266
+ const path = arg.node === "field" ? pathOf2(arg) : undefined;
32821
33267
  return path !== undefined && path.length === level + 1 && levelOfNames(path, pair) === level && !(pair.computedFields ?? []).includes(path.join("."));
32822
33268
  }
32823
33269
  function flatPairQueryRefusal(query, source, pair, scoped = false) {
@@ -32877,7 +33323,7 @@ function checkSegment(outer, sourceFields, segment, pair, scoped, reach, depth)
32877
33323
  const nests = [];
32878
33324
  for (const qf of queryFields) {
32879
33325
  if (qf.type === "fieldref") {
32880
- const p = pathOf(qf);
33326
+ const p = pathOf2(qf);
32881
33327
  if (!p)
32882
33328
  throw new Refusal("a field reference that cannot be read");
32883
33329
  if (p[0] === pair.join) {
@@ -33077,7 +33523,7 @@ class LevelScan {
33077
33523
  }
33078
33524
  }
33079
33525
  if (n.node === "field" || n.type === "fieldref") {
33080
- const p = pathOf(n);
33526
+ const p = pathOf2(n);
33081
33527
  if (!p)
33082
33528
  throw new Refusal("a field reference that cannot be read");
33083
33529
  return Math.max(level, this.path(p, fields, depth + 1));
@@ -33246,10 +33692,11 @@ function heldReadBinding(kind, sourceEntityId, entry) {
33246
33692
  ...retypedColumns.length > 0 ? { retypedColumns } : {}
33247
33693
  };
33248
33694
  }
33249
- function makeSnapshot(bindings, entries = {}, withdrawn, compilerKeys, contracts) {
33695
+ function makeSnapshot(bindings, entries = {}, withdrawn, compilerKeys, contracts, mode) {
33250
33696
  return Object.freeze({
33251
33697
  bindings,
33252
33698
  entries,
33699
+ ...mode ? { mode } : {},
33253
33700
  ...withdrawn && withdrawn.size > 0 ? { withdrawn } : {},
33254
33701
  ...compilerKeys && Object.keys(compilerKeys).length > 0 ? { compilerKeys } : {},
33255
33702
  ...contracts && contracts.size > 0 ? { contracts } : {}
@@ -33323,12 +33770,12 @@ function pin(snapshot, asOf) {
33323
33770
  }
33324
33771
  });
33325
33772
  }
33326
- function pairsOf(keys) {
33773
+ function pairsOf2(keys) {
33327
33774
  return Symbol.iterator in keys ? keys : Object.entries(keys);
33328
33775
  }
33329
33776
  function filings(entries, keys, claimed) {
33330
33777
  const filed = new Map;
33331
- for (const [address, key] of pairsOf(keys)) {
33778
+ for (const [address, key] of pairsOf2(keys)) {
33332
33779
  if (key === address || claimed.has(key) || !(address in entries) || key in entries || filed.has(key)) {
33333
33780
  continue;
33334
33781
  }
@@ -33503,10 +33950,11 @@ function readTier(facts) {
33503
33950
  if (!facts.storageBound) {
33504
33951
  return facts.declaredStorage ? "storage" : "database";
33505
33952
  }
33506
- if (!facts.servedCopy)
33507
- return "storage";
33508
33953
  return (!facts.storageFresh || facts.servedCopyOnDatabase) && facts.databaseFresh ? "database" : "storage";
33509
33954
  }
33955
+ function freshTwinReadsDatabase(storage, databaseFresh) {
33956
+ return storage?.state === "stale" && databaseFresh;
33957
+ }
33510
33958
 
33511
33959
  // src/service/materialization/text/author_model.ts
33512
33960
  function authorModelLiftContext(modelDef, readFile) {
@@ -34372,7 +34820,7 @@ function buildServedCopy(reroots, fileText) {
34372
34820
  const spans = declarationSpans(declaration, {
34373
34821
  throughIncludes: r.keepsIncludes === true
34374
34822
  });
34375
- if (spans && !spans.queryShaped && !spans.connectionRooted && !r.storedDimensions && !r.refinementRooted) {
34823
+ if (spans && !spans.queryShaped && !spans.connectionRooted && !r.storedDimensions && !r.refinementRooted && !r.queryRooted) {
34376
34824
  refused.push({
34377
34825
  sourceName: r.sourceName,
34378
34826
  url,
@@ -34484,7 +34932,11 @@ function rerootDeclaration(declaration, r) {
34484
34932
  });
34485
34933
  if (!spans)
34486
34934
  return;
34487
- const virtual = `${identifier(r.connectionAlias)}.virtual(${stringLiteral(r.virtualHandle)})` + `::${identifier(r.typeName)}` + (r.zone ? ` extend { timezone: ${stringLiteral(r.zone)} }` : "");
34935
+ const joinedBack = r.pair ? r.pairJoinedBack : undefined;
34936
+ const base = rerootBase(r, joinedBack);
34937
+ if (base === undefined)
34938
+ return;
34939
+ const virtual = base + (r.zone ? ` extend { timezone: ${stringLiteral(r.zone)} }` : "");
34488
34940
  const name = declaration.slice(0, spans.nameEnd).trimEnd();
34489
34941
  const inlined = r.inlinedJoins ?? [];
34490
34942
  const reserved = [
@@ -34540,7 +34992,12 @@ function rerootDeclaration(declaration, r) {
34540
34992
  extend = opened;
34541
34993
  }
34542
34994
  let pairHead = "";
34543
- if (r.pair) {
34995
+ if (joinedBack) {
34996
+ const dropped = pairRerootJoins(joinedBack).reduce((text, join) => text === undefined ? undefined : dropJoinDefinition(text, join, "join_many"), extend);
34997
+ if (dropped === undefined)
34998
+ return;
34999
+ extend = dropped;
35000
+ } else if (r.pair) {
34544
35001
  let replaced = replacePairJoin(extend, r.pair.join, pairRecord(r.pair, r.pair.levelPresent), r.pair.access !== undefined);
34545
35002
  for (const other of r.pair.block?.others ?? []) {
34546
35003
  if (replaced === undefined)
@@ -34575,6 +35032,18 @@ function rerootDeclaration(declaration, r) {
34575
35032
  ])}` : "";
34576
35033
  return `${name} is ${virtual}${reread}${hide}${pairHead}${castAhead}${renames}${extend ? ` ${extend}` : ""}`;
34577
35034
  }
35035
+ function rerootBase(r, joinedBack) {
35036
+ const table = `${identifier(r.connectionAlias)}.virtual(${stringLiteral(r.virtualHandle)})` + `::${identifier(r.typeName)}`;
35037
+ if (!joinedBack)
35038
+ return table;
35039
+ return pairRerootBase(joinedBack, {
35040
+ from: table,
35041
+ columns: new Set([
35042
+ ...(r.columns ?? []).map((c) => c.name),
35043
+ ...(r.inlinedJoins ?? []).flatMap((j) => j.columns.map((c) => c.column))
35044
+ ])
35045
+ });
35046
+ }
34578
35047
  function servedExtend(text, storedDimensions, timeframed, withRenames) {
34579
35048
  let extend = text;
34580
35049
  const stored = new Set(storedDimensions ?? []);
@@ -34893,12 +35362,32 @@ ${rest}`;
34893
35362
  var SERVED_COPY_FLAG = "##! experimental { virtual_source }", SERVED_COPY_ACCESS_FLAG = "##! experimental { virtual_source access_modifiers }";
34894
35363
  var init_served_copy = __esm(() => {
34895
35364
  init_malloy_text();
35365
+ init_pair_reroot();
34896
35366
  init_stored_column_types();
34897
35367
  init_declaration_text();
34898
35368
  init_malloy_lexer_core();
34899
35369
  init_inlined_join_text();
34900
35370
  });
34901
35371
 
35372
+ // src/service/served_copy_metering.ts
35373
+ function registerDestinationGeneration(generation, sources) {
35374
+ generationSources.set(generation, sources);
35375
+ }
35376
+ function destinationGenerationSources(generation) {
35377
+ return generationSources.get(generation);
35378
+ }
35379
+ function bindServedCopyMetering(connections, sourceOf) {
35380
+ servedSources.set(connections, sourceOf);
35381
+ }
35382
+ function servedCopyMeteredSource(connections, connectionName) {
35383
+ return servedSources.get(connections)?.(connectionName);
35384
+ }
35385
+ var generationSources, servedSources;
35386
+ var init_served_copy_metering = __esm(() => {
35387
+ generationSources = new WeakMap;
35388
+ servedSources = new WeakMap;
35389
+ });
35390
+
34902
35391
  // src/service/materialization/serve/served_copy_config.ts
34903
35392
  import { randomBytes } from "crypto";
34904
35393
  import { MalloyConfig as MalloyConfig2 } from "@malloydata/malloy";
@@ -34974,11 +35463,19 @@ function servedCopyConfig(packageConfig, destinations, allowed, tablesUnderAlias
34974
35463
  return base.connections.lookupConnection(name);
34975
35464
  }
34976
35465
  }));
35466
+ const sources = destinationGenerationSources(destinations);
35467
+ if (sources) {
35468
+ bindServedCopyMetering(config.connections, (name) => {
35469
+ const destination = destinationsByAlias.get(name);
35470
+ return destination !== undefined && allowed.has(destination) ? sources.get(destination) : undefined;
35471
+ });
35472
+ }
34977
35473
  return config;
34978
35474
  }
34979
35475
  var TOKEN, aliases, destinationsByAlias, aliasedViews;
34980
35476
  var init_served_copy_config = __esm(() => {
34981
35477
  init_model_runtime();
35478
+ init_served_copy_metering();
34982
35479
  TOKEN = randomBytes(12).toString("hex");
34983
35480
  aliases = new Map;
34984
35481
  destinationsByAlias = new Map;
@@ -36658,6 +37155,7 @@ var init_leg_decline = __esm(() => {
36658
37155
  rollup_stale: { reason: "STALE" },
36659
37156
  rollup_row_level_gate: { reason: "ROW_LEVEL_GATE" },
36660
37157
  rollup_cross_connection: { reason: "CROSS_CONNECTION" },
37158
+ view_row_level_gate: { reason: "ROW_LEVEL_GATE" },
36661
37159
  view_missing_field: { reason: "MISSING_FIELD" },
36662
37160
  view_shape_mismatch: { reason: "SHAPE_MISMATCH" },
36663
37161
  view_not_built: { reason: "NOT_BUILT" },
@@ -36666,6 +37164,7 @@ var init_leg_decline = __esm(() => {
36666
37164
  reason: "NOT_SERVED",
36667
37165
  code: "destination_missing"
36668
37166
  },
37167
+ query_row_level_gate: { reason: "ROW_LEVEL_GATE" },
36669
37168
  query_missing_field: { reason: "MISSING_FIELD" },
36670
37169
  query_shape_mismatch: { reason: "SHAPE_MISMATCH" },
36671
37170
  query_not_built: { reason: "NOT_BUILT" },
@@ -36679,11 +37178,41 @@ var init_leg_decline = __esm(() => {
36679
37178
  served_copy_stale: { reason: "STALE" },
36680
37179
  served_copy_not_served: { reason: "NOT_SERVED", code: "served_copy" },
36681
37180
  served_copy_opt_out: { reason: "OPTED_OUT" },
37181
+ served_copy_row_level_gate: { reason: "ROW_LEVEL_GATE" },
36682
37182
  served_copy_count_semantics: { reason: "COUNT_SEMANTICS" },
36683
37183
  served_copy_joined_annotations: { reason: "MISSING_FIELD" },
36684
37184
  served_copy_column_left_out: { reason: "MISSING_FIELD" },
36685
37185
  served_copy_pair_shape: { reason: "COUNT_SEMANTICS" },
36686
- served_copy_pair_parent_only: { reason: "COUNT_SEMANTICS" }
37186
+ served_copy_pair_parent_only: { reason: "COUNT_SEMANTICS" },
37187
+ served_copy_as_of_build_access: {
37188
+ reason: "NOT_SERVED",
37189
+ code: "served_copy"
37190
+ },
37191
+ served_copy_row_scope_inexact: { reason: "NOT_SERVED", code: "served_copy" },
37192
+ served_copy_row_scope_comparison: {
37193
+ reason: "NOT_SERVED",
37194
+ code: "served_copy"
37195
+ },
37196
+ served_copy_filter_comparison: { reason: "NOT_SERVED", code: "served_copy" },
37197
+ served_copy_result_order_comparison: {
37198
+ reason: "NOT_SERVED",
37199
+ code: "served_copy"
37200
+ },
37201
+ rollup_as_of_build_access: { reason: "ROW_LEVEL_GATE" },
37202
+ rollup_row_scope_inexact: { reason: "ROW_LEVEL_GATE" },
37203
+ rollup_row_scope_comparison: { reason: "ROW_LEVEL_GATE" },
37204
+ rollup_filter_comparison: { reason: "COMPARISON_SEMANTICS" },
37205
+ rollup_result_order_comparison: { reason: "COMPARISON_SEMANTICS" },
37206
+ view_as_of_build_access: { reason: "ROW_LEVEL_GATE" },
37207
+ view_row_scope_inexact: { reason: "ROW_LEVEL_GATE" },
37208
+ view_row_scope_comparison: { reason: "ROW_LEVEL_GATE" },
37209
+ view_filter_comparison: { reason: "COMPARISON_SEMANTICS" },
37210
+ view_result_order_comparison: { reason: "COMPARISON_SEMANTICS" },
37211
+ query_as_of_build_access: { reason: "ROW_LEVEL_GATE" },
37212
+ query_row_scope_inexact: { reason: "ROW_LEVEL_GATE" },
37213
+ query_row_scope_comparison: { reason: "ROW_LEVEL_GATE" },
37214
+ query_filter_comparison: { reason: "COMPARISON_SEMANTICS" },
37215
+ query_result_order_comparison: { reason: "COMPARISON_SEMANTICS" }
36687
37216
  };
36688
37217
  LegDecline = class LegDecline extends Error {
36689
37218
  code;
@@ -39300,6 +39829,33 @@ var init_same_catalog_destination = __esm(() => {
39300
39829
  init_same_catalog_build();
39301
39830
  });
39302
39831
 
39832
+ // src/service/materialization/serve/compile_timing.ts
39833
+ function compileStarted(leg) {
39834
+ return observer2?.started(leg) ?? (() => {
39835
+ return;
39836
+ });
39837
+ }
39838
+ async function reportedVariantCompile(leg, compile) {
39839
+ const ended = compileStarted(leg);
39840
+ let variant;
39841
+ try {
39842
+ variant = await compile();
39843
+ } catch (err) {
39844
+ ended("inline", "failed");
39845
+ throw err;
39846
+ }
39847
+ if (variant.refusal === undefined) {
39848
+ ended("inline", variant.error === undefined ? "compiled" : "failed");
39849
+ }
39850
+ return variant;
39851
+ }
39852
+ function observeCompiles(o) {
39853
+ const previous = observer2;
39854
+ observer2 = o;
39855
+ return previous;
39856
+ }
39857
+ var observer2;
39858
+
39303
39859
  // src/service/materialization/serve/result_reads.ts
39304
39860
  function nonStringType2(t) {
39305
39861
  return typeof t === "string" && t !== "string";
@@ -40276,7 +40832,7 @@ var init_chain_string_reads = __esm(() => {
40276
40832
  });
40277
40833
 
40278
40834
  // src/service/materialization/serve/served_copy_serve.ts
40279
- import { createHash as createHash2 } from "crypto";
40835
+ import { createHash as createHash3 } from "crypto";
40280
40836
  import {
40281
40837
  MalloyError as MalloyError4,
40282
40838
  MalloyConfig as MalloyConfig3
@@ -40349,7 +40905,7 @@ function missingNamesRead(names, error, queryString) {
40349
40905
  return any ? read : undefined;
40350
40906
  }
40351
40907
  function rerootFailureKey(packagePath, modelPath, bindings, overlay) {
40352
- const hash = createHash2("sha256");
40908
+ const hash = createHash3("sha256");
40353
40909
  hash.update(JSON.stringify(bindings)).update("\x00");
40354
40910
  for (const [url, text] of [...overlay].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
40355
40911
  hash.update(url).update("\x00").update(text).update("\x00");
@@ -40447,6 +41003,19 @@ class ServedCopyServe {
40447
41003
  }
40448
41004
  return out;
40449
41005
  }
41006
+ gateDeclinesSource(name) {
41007
+ const compiled = this.lanes.kept(0);
41008
+ if (!compiled || !this.mayHaveRowLevelGates(compiled))
41009
+ return false;
41010
+ return this.gateCannotGraft(compiled, name);
41011
+ }
41012
+ chainDeclinedSourceIDs() {
41013
+ const compiled = this.lanes.kept(0);
41014
+ return new Set([
41015
+ ...compiled?.optOutIDs ?? [],
41016
+ ...compiled?.unsafeIDs ?? []
41017
+ ]);
41018
+ }
40450
41019
  mayHaveRowLevelGates(compiled) {
40451
41020
  compiled.hasRowLevelGates ??= JSON.stringify(this.host.modelDef() ?? {}).includes("access_filter");
40452
41021
  return compiled.hasRowLevelGates;
@@ -40829,7 +41398,7 @@ class ServedCopyServe {
40829
41398
  return;
40830
41399
  ({ columns, columnsLeftOut, inlinedJoins } = stored);
40831
41400
  } else {
40832
- const stored = v1ColumnsOf(subject);
41401
+ const stored = persistColumnsOf(subject);
40833
41402
  if (!stored)
40834
41403
  return;
40835
41404
  ({ columns, columnsLeftOut } = stored);
@@ -40892,7 +41461,8 @@ class ServedCopyServe {
40892
41461
  ...!plan ? {
40893
41462
  keepsIncludes: true,
40894
41463
  outputNames: queryOutputNames(def.fields),
40895
- ...refinesUnfilteredBase(map.node(node.sourceID), map) ? { refinementRooted: true } : {}
41464
+ ...refinesUnfilteredBase(map.node(node.sourceID), map) ? { refinementRooted: true } : {},
41465
+ ...refinesNamedQuery(map.node(node.sourceID), map) ? { queryRooted: true } : {}
40896
41466
  } : {},
40897
41467
  sourceID: node.sourceID,
40898
41468
  authorDef: node.def,
@@ -41022,7 +41592,10 @@ class ServedCopyServe {
41022
41592
  const map = SourceMap.of(modelDef);
41023
41593
  const lift = authorModelLiftContext(modelDef, compiledTextReader(modelDef, this.packagePath));
41024
41594
  const problems = [];
41025
- const { candidates } = this.rerootCandidates(bindings.filter((b) => b.kind !== "rollup"), map, lift, problems, 0);
41595
+ const candidates = this.rerootCandidates(bindings.filter((b) => b.kind !== "rollup"), map, lift, problems, 0).candidates.map((c) => {
41596
+ const plan = c.reroot.pair ? this.materializePlans[c.reroot.sourceID] : undefined;
41597
+ return plan ? { ...c, reroot: { ...c.reroot, pairJoinedBack: plan } } : c;
41598
+ });
41026
41599
  const why = (detail) => ({ declined: detail });
41027
41600
  if (candidates.length === 0) {
41028
41601
  return why(problems.length > 0 ? `no stored upstream could be re-rooted (${problems.map((p) => `'${p.sourceName}': ${p.reason}`).join(", ")})` : "no stored upstream could be re-rooted");
@@ -41039,7 +41612,10 @@ class ServedCopyServe {
41039
41612
  ...view.keepAlso ? { keepAlso: view.keepAlso } : {}
41040
41613
  } : {},
41041
41614
  bindings,
41042
- reroots: candidates.map((c) => c.reroot),
41615
+ reroots: candidates.map((c) => ({
41616
+ ...c.reroot,
41617
+ ...c.reroot.pairJoinedBack ? { storedJoins: pairRerootJoins(c.reroot.pairJoinedBack) } : {}
41618
+ })),
41043
41619
  importsOf: compiledImports(modelDef)
41044
41620
  });
41045
41621
  if ("declined" in set)
@@ -41329,21 +41905,12 @@ class ServedCopyServe {
41329
41905
  const copy = buildServedCopy(state.candidates.map((c) => c.reroot), (u) => lift.fileText(u));
41330
41906
  const refused = new Set(copy.refused.map((r) => `${r.url}\x00${r.sourceName}`));
41331
41907
  if (pass === 0) {
41332
- for (const r of copy.refused) {
41333
- if (r.reason === "not_query_shaped")
41334
- continue;
41335
- const sourceID = state.candidates.find((c) => c.reroot.url === r.url && c.reroot.sourceName === r.sourceName)?.reroot.sourceID;
41336
- problems.push({
41337
- sourceName: r.sourceName,
41338
- ...sourceID ? { sourceID } : {},
41339
- reason: r.reason,
41340
- ...r.hiddenUnstored ? { hiddenUnstored: r.hiddenUnstored } : {}
41341
- });
41342
- }
41908
+ problems.push(...refusalProblems(copy.refused, state.candidates, throughBase));
41343
41909
  }
41344
41910
  state.candidates = state.candidates.filter((c) => !refused.has(`${c.reroot.url}\x00${c.reroot.sourceName}`));
41345
41911
  if (state.candidates.length === 0) {
41346
41912
  problems.push(...state.pairsDropped);
41913
+ problems.push(...baseDroppedProblems(throughBase, [], problems));
41347
41914
  return {
41348
41915
  key,
41349
41916
  generation,
@@ -41434,24 +42001,40 @@ class ServedCopyServe {
41434
42001
  const modelPath = this.host.modelPath();
41435
42002
  const compiler = packageFiles(packagePath, modelPath, config);
41436
42003
  return async (files) => {
41437
- const elsewhere = await this.host.compileElsewhere?.({
41438
- packagePath,
41439
- modelPath,
41440
- config,
41441
- files: keyedOverlay(files),
41442
- virtualMap
41443
- });
41444
- if (elsewhere)
42004
+ const offThread = compileStarted("served");
42005
+ let elsewhere;
42006
+ try {
42007
+ elsewhere = await this.host.compileElsewhere?.({
42008
+ packagePath,
42009
+ modelPath,
42010
+ config,
42011
+ files: keyedOverlay(files),
42012
+ virtualMap
42013
+ });
42014
+ } catch (err) {
42015
+ offThread("worker", "failed");
42016
+ throw err;
42017
+ }
42018
+ if (elsewhere) {
42019
+ offThread("worker", "compiled");
41445
42020
  return elsewhere;
41446
- const { runtime, materializer } = await compiler.loadModel(files, {
41447
- virtualMap
41448
- });
41449
- const model = await materializer.getModel();
41450
- return {
41451
- materializer,
41452
- def: modelDefOf(model),
41453
- runtime
41454
- };
42021
+ }
42022
+ const inline = compileStarted("served");
42023
+ try {
42024
+ const { runtime, materializer } = await compiler.loadModel(files, {
42025
+ virtualMap
42026
+ });
42027
+ const model = await materializer.getModel();
42028
+ inline("inline", "compiled");
42029
+ return {
42030
+ materializer,
42031
+ def: modelDefOf(model),
42032
+ runtime
42033
+ };
42034
+ } catch (err) {
42035
+ inline("inline", "failed");
42036
+ throw err;
42037
+ }
41455
42038
  };
41456
42039
  }
41457
42040
  forgetFailures() {
@@ -41693,6 +42276,7 @@ class ServedCopyServe {
41693
42276
  }
41694
42277
  problems.push(...crossConnectionProblems(leftOut, candidates, over, modelDef, servedDef));
41695
42278
  const unsafeIDs = classificationCeiling(this.host.modelPath(), modelDef, servedDef, servedMap, problems);
42279
+ problems.push(...baseDroppedProblems(throughBase, candidates, problems));
41696
42280
  const compiled = {
41697
42281
  key,
41698
42282
  generation,
@@ -42160,7 +42744,7 @@ function materializedOwnColumns(subject, plan, read) {
42160
42744
  }
42161
42745
  if (type === undefined && c.column === c.dimension && isListOrRecord(fieldsByName.get(c.dimension))) {
42162
42746
  columnsLeftOut.push(c.column);
42163
- subject.leftOutWhy.set(c.column, leftOutPhrase(subject.columnRef(c.column), fieldsByName.get(c.dimension), undefined));
42747
+ subject.leftOutWhy.set(c.column, leftOutPhrase(subject.columnRef(c.column), fieldsByName.get(c.dimension), nativeTypeLookup(binding.nativeSchema)(c.column)));
42164
42748
  continue;
42165
42749
  }
42166
42750
  if (type === undefined || c.column !== c.dimension) {
@@ -42212,11 +42796,11 @@ function driftsFromLive(storedType, field) {
42212
42796
  const type = field?.type;
42213
42797
  return typeof type === "string" && storedTypeServesAs(storedType, type) === false;
42214
42798
  }
42215
- function v1ColumnsOf(subject) {
42799
+ function persistColumnsOf(subject) {
42216
42800
  const { binding, node, sourceName, def, fieldsByName, timeframeOf } = subject;
42217
42801
  const { problems } = subject;
42218
42802
  let columnsLeftOut = [];
42219
- const narrowed = v1StoredColumns(binding.schema, def.fields);
42803
+ const narrowed = persistStoredColumns(binding.schema, def.fields);
42220
42804
  const typePlan = storedColumnReadPlan(narrowed, declaredColumnsOf(def.fields), { queryTimezone: queryTimezoneOf(def), ducklake: !isDatabase(binding) });
42221
42805
  const castTo = new Map(typePlan.casts.map((c) => [
42222
42806
  c.column,
@@ -42228,15 +42812,15 @@ function v1ColumnsOf(subject) {
42228
42812
  for (const name of leftOut) {
42229
42813
  subject.leftOutWhy.set(name, leftOutPhrase(subject.columnRef(name), fieldsByName.get(name), storedTypeOf.get(name)));
42230
42814
  }
42815
+ const nativeTypeOf = nativeTypeLookup(binding.nativeSchema);
42231
42816
  const stored = new Set(binding.schema.map((c) => c.name.toLowerCase()));
42232
42817
  for (const f of def.fields ?? []) {
42233
42818
  const name = String(f.as ?? f.name ?? "");
42234
42819
  if (typeof f.join === "string" && (f.type === "array" || f.type === "record") && name !== "" && !stored.has(name.toLowerCase())) {
42235
42820
  columnsLeftOut.push(name);
42236
- subject.leftOutWhy.set(name, leftOutPhrase(subject.columnRef(name), f, undefined));
42821
+ subject.leftOutWhy.set(name, leftOutPhrase(subject.columnRef(name), f, nativeTypeOf(typeof f.name === "string" ? f.name : name)));
42237
42822
  }
42238
42823
  }
42239
- const nativeTypeOf = nativeTypeLookup(binding.nativeSchema);
42240
42824
  for (const f of def.fields ?? []) {
42241
42825
  if (typeof f.name !== "string" || f.join !== undefined || f.e !== undefined || !liveTypesAsNative(f)) {
42242
42826
  continue;
@@ -42740,7 +43324,7 @@ function storedColumnsWithAccess(schema, fields) {
42740
43324
  }
42741
43325
  return out;
42742
43326
  }
42743
- function v1StoredColumns(schema, fields) {
43327
+ function persistStoredColumns(schema, fields) {
42744
43328
  return [
42745
43329
  ...storedColumnsWithAccess(schema, fields).map(({ name, type }) => ({
42746
43330
  name,
@@ -42767,6 +43351,45 @@ function unnamedStoredColumns(schema, fields) {
42767
43351
  }
42768
43352
  return schema.filter((c) => !names.has(c.name.toLowerCase())).map((c) => ({ name: c.name, type: c.type }));
42769
43353
  }
43354
+ function refusalProblems(refused, candidates, throughBase) {
43355
+ return refused.flatMap((r) => {
43356
+ const sourceID = candidates.find((c) => c.reroot.url === r.url && c.reroot.sourceName === r.sourceName)?.reroot.sourceID;
43357
+ if (r.reason === "not_query_shaped" && throughBase.some((t) => t.sourceID === sourceID)) {
43358
+ return [];
43359
+ }
43360
+ return [
43361
+ {
43362
+ sourceName: r.sourceName,
43363
+ ...sourceID ? { sourceID } : {},
43364
+ reason: r.reason === "not_query_shaped" ? "refinement_left_as_written" : r.reason,
43365
+ ...r.hiddenUnstored ? { hiddenUnstored: r.hiddenUnstored } : {}
43366
+ }
43367
+ ];
43368
+ });
43369
+ }
43370
+ function baseDroppedProblems(throughBase, candidates, problems) {
43371
+ const ids = new Set(candidates.map((c) => c.reroot.sourceID));
43372
+ const names = new Set(candidates.map((c) => c.reroot.sourceName));
43373
+ return throughBase.filter((t) => !t.chain.some((id) => ids.has(id)) && !(t.baseName !== undefined && names.has(t.baseName)) && !ids.has(t.sourceID) && !problems.some((p) => p.sourceID === t.sourceID)).map((t) => ({
43374
+ sourceName: t.sourceName,
43375
+ sourceID: t.sourceID,
43376
+ reason: "refinement_left_as_written"
43377
+ }));
43378
+ }
43379
+ function refinesNamedQuery(node, map) {
43380
+ let at = node;
43381
+ for (let hops = 0;at && hops < 64; hops++) {
43382
+ const base = at.base;
43383
+ if (!base)
43384
+ return false;
43385
+ if (base.hop === "query")
43386
+ return true;
43387
+ if (!refinesUnfilteredBase(at, map))
43388
+ return false;
43389
+ at = base.sourceID === undefined ? undefined : map.node(base.sourceID);
43390
+ }
43391
+ return false;
43392
+ }
42770
43393
  function refinesUnfilteredBase(node, map) {
42771
43394
  const base = node?.base;
42772
43395
  if (!base || base.hop !== "extends" && base.hop !== "rename") {
@@ -42953,6 +43576,7 @@ var init_served_copy_serve = __esm(() => {
42953
43576
  init_sql_embed_reads();
42954
43577
  init_event_loop_yield();
42955
43578
  init_package_files();
43579
+ init_pair_reroot();
42956
43580
  init_source_map();
42957
43581
  init_chain_build_files();
42958
43582
  init_persist_dynamic_terms();
@@ -43004,6 +43628,12 @@ function lazyInstrument(create) {
43004
43628
  instrumentResets.push(() => instrument = null);
43005
43629
  return () => instrument ??= create();
43006
43630
  }
43631
+ function withoutMetrics(fn) {
43632
+ return metricsSuppressed.run(true, fn);
43633
+ }
43634
+ function withMetrics(fn) {
43635
+ return metricsSuppressed.exit(fn);
43636
+ }
43007
43637
  function metricsAreSuppressed() {
43008
43638
  return metricsSuppressed.getStore() === true;
43009
43639
  }
@@ -43256,7 +43886,7 @@ import {
43256
43886
  CacheManager,
43257
43887
  InMemoryModelCache
43258
43888
  } from "@malloydata/malloy";
43259
- import { createHash as createHash3 } from "crypto";
43889
+ import { createHash as createHash4 } from "crypto";
43260
43890
  import * as path6 from "path";
43261
43891
  import { fileURLToPath as fileURLToPath5, pathToFileURL as pathToFileURL5 } from "url";
43262
43892
  function jobFiles(inner) {
@@ -43320,7 +43950,7 @@ function fileTextDigests(files) {
43320
43950
  const key = urlKey(url);
43321
43951
  if (!key.startsWith("file:"))
43322
43952
  continue;
43323
- digests[key] = createHash3("sha256").update(text).digest("hex");
43953
+ digests[key] = createHash4("sha256").update(text).digest("hex");
43324
43954
  }
43325
43955
  return digests;
43326
43956
  }
@@ -43606,12 +44236,12 @@ function compareText(a, b) {
43606
44236
  }
43607
44237
 
43608
44238
  // src/service/package_revision.ts
43609
- import { createHash as createHash4, randomUUID } from "crypto";
44239
+ import { createHash as createHash5, randomUUID } from "crypto";
43610
44240
  import fs5 from "fs";
43611
44241
  import path7 from "path";
43612
44242
  import { pathToFileURL as pathToFileURL6 } from "url";
43613
44243
  function computeSourceContentSha(packagePath, contentPaths, extra, contentShas) {
43614
- const hash = createHash4("sha256");
44244
+ const hash = createHash5("sha256");
43615
44245
  for (const relativePath of [...contentPaths].sort()) {
43616
44246
  hash.update(relativePath);
43617
44247
  hash.update("\x00");
@@ -43645,7 +44275,7 @@ function boundedManifestValue(value) {
43645
44275
  return "[unreadable: too deep or too large]";
43646
44276
  }
43647
44277
  function canonicalSha(value) {
43648
- return createHash4("sha256").update(canonicalJson(value)).digest("hex");
44278
+ return createHash5("sha256").update(canonicalJson(value)).digest("hex");
43649
44279
  }
43650
44280
  function mintServedRevision() {
43651
44281
  return randomUUID();
@@ -44724,9 +45354,9 @@ var init_dim_index_discovery = __esm(() => {
44724
45354
  });
44725
45355
 
44726
45356
  // src/service/entities/dim_index_entity_id.ts
44727
- import { createHash as createHash5 } from "crypto";
45357
+ import { createHash as createHash6 } from "crypto";
44728
45358
  function computeSqlFingerprint(compiledSql) {
44729
- return createHash5("sha256").update(compiledSql, "utf8").digest("hex");
45359
+ return createHash6("sha256").update(compiledSql, "utf8").digest("hex");
44730
45360
  }
44731
45361
  function buildFingerprintQuery(sourceName, dimensionPath, requiredFilterDimensions, gateDimensions = []) {
44732
45362
  const sortedFilters = [...requiredFilterDimensions].sort();
@@ -45547,7 +46177,7 @@ var init_package_relative_text = __esm(() => {
45547
46177
  });
45548
46178
 
45549
46179
  // src/service/package_retrieval_settings.ts
45550
- import { createHash as createHash6 } from "crypto";
46180
+ import { createHash as createHash7 } from "crypto";
45551
46181
  import * as fs8 from "fs";
45552
46182
  import * as path10 from "path";
45553
46183
  import { pathToFileURL as pathToFileURL9 } from "url";
@@ -45787,7 +46417,7 @@ async function readPromptFile(packageRoot, key, rel) {
45787
46417
  return {
45788
46418
  path: rel,
45789
46419
  text,
45790
- hash: createHash6("sha256").update(text).digest("hex")
46420
+ hash: createHash7("sha256").update(text).digest("hex")
45791
46421
  };
45792
46422
  }
45793
46423
  async function readPackageRetrieval(packageRoot, raw) {
@@ -45809,7 +46439,7 @@ function assertRequiredStagesAvailable(retrieval, llmConfigured) {
45809
46439
  if (llmConfigured)
45810
46440
  return;
45811
46441
  if (retrieval.sourceSummary?.enabled === true) {
45812
- fail(`Invalid publisher.json retrieval.sourceSummary.enabled: true needs an LLM, and this server has none configured. ` + `Fix: set retrieval.llm in publisher.config.json and LLM_API_KEY in the server's environment, ` + `or set "enabled": "auto" (on only when an LLM is configured) or false.`);
46442
+ fail(`Invalid publisher.json retrieval.sourceSummary.enabled: true needs an LLM, and this server has none configured. ` + `Fix: set retrieval.llm in publisher.config.json and PUBLISHER_RETRIEVAL_LLM_API_KEY in the server's environment, ` + `or set "enabled": "auto" (on only when an LLM is configured) or false.`);
45813
46443
  }
45814
46444
  }
45815
46445
  var QUESTIONS_PROMPTS, DEFAULT_QUESTIONS_PER_NODE = 3, RETRIEVAL_KEYS, PROMPT_KEYS, SOURCE_SUMMARY_KEYS, IGNORED_RETRIEVAL_KEYS, IGNORED_PROMPT_KEYS, FCJ_CONNECT_MODES, FCJ_ALSO_LIKELY, FCJ_JOINED_COPIES, DEFAULT_FCJ_SETTINGS, DEFAULT_PACKAGE_RETRIEVAL, FCJ_KEYS;
@@ -46040,7 +46670,7 @@ var init_error_code = __esm(() => {
46040
46670
  });
46041
46671
 
46042
46672
  // src/service/materialization/domain/table_name.ts
46043
- import { createHash as createHash7 } from "crypto";
46673
+ import { createHash as createHash8 } from "crypto";
46044
46674
  function leafBudget(dialect, inDestination) {
46045
46675
  if (inDestination)
46046
46676
  return DESTINATION_LEAF_BUDGET;
@@ -46144,7 +46774,7 @@ function fitPrefix(prefix, room) {
46144
46774
  }
46145
46775
  function readableTableName(args) {
46146
46776
  const { identity } = args;
46147
- const hash = createHash7("sha256").update(JSON.stringify([
46777
+ const hash = createHash8("sha256").update(JSON.stringify([
46148
46778
  "publisher-table/1",
46149
46779
  identity.environmentName,
46150
46780
  identity.packageName,
@@ -47132,6 +47762,29 @@ var init_persisted_view = __esm(() => {
47132
47762
  init_persisted_query();
47133
47763
  });
47134
47764
 
47765
+ // src/service/materialization/plan/plan_diagnostics.ts
47766
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
47767
+ function reportPlanDiagnostic(level, code, message, fields) {
47768
+ const diagnostic = { code, level, message, fields };
47769
+ const into = collecting.getStore();
47770
+ if (into)
47771
+ into.push(diagnostic);
47772
+ else
47773
+ unscoped?.(diagnostic);
47774
+ }
47775
+ function collectPlanDiagnostics(into, fn) {
47776
+ return collecting.run(into, fn);
47777
+ }
47778
+ function observeUnscopedPlanDiagnostics(observer) {
47779
+ const previous = unscoped;
47780
+ unscoped = observer;
47781
+ return previous;
47782
+ }
47783
+ var collecting, unscoped;
47784
+ var init_plan_diagnostics = __esm(() => {
47785
+ collecting = new AsyncLocalStorage3;
47786
+ });
47787
+
47135
47788
  // src/service/http_retry.ts
47136
47789
  function publicMessage(error) {
47137
47790
  const own = error?.publicMessage;
@@ -47142,6 +47795,10 @@ function publicMessage(error) {
47142
47795
  function malformedReply(what, where, detail) {
47143
47796
  return new HttpRequestError(`${what} from ${where} malformed: ${detail}`, undefined, false, undefined, `${what} malformed: ${detail}`);
47144
47797
  }
47798
+ function backoffDelayMs(policy, n) {
47799
+ const exponential = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (n - 1));
47800
+ return exponential / 2 + policy.random() * exponential / 2;
47801
+ }
47145
47802
  function isRetryableStatus(status) {
47146
47803
  return status === 429 || status === 408 || status >= 500;
47147
47804
  }
@@ -47163,9 +47820,7 @@ async function withRetry(attempt, policy, label = "Request", onRetry) {
47163
47820
  if (!(error instanceof HttpRequestError) || !error.retryable || n >= policy.maxAttempts) {
47164
47821
  throw error;
47165
47822
  }
47166
- const exponential = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (n - 1));
47167
- const jittered = exponential / 2 + policy.random() * exponential / 2;
47168
- const delay = Math.max(jittered, error.retryAfterMs ?? 0);
47823
+ const delay = Math.max(backoffDelayMs(policy, n), error.retryAfterMs ?? 0);
47169
47824
  if (delay > policy.maxDelayMs || waited + delay > policy.maxTotalDelayMs) {
47170
47825
  throw error;
47171
47826
  }
@@ -47675,7 +48330,7 @@ class OpenAiCompatibleChat {
47675
48330
  signal: req.signal,
47676
48331
  timeoutMs: req.timeoutMs,
47677
48332
  secrets: [this.apiKey],
47678
- authHint: "LLM_API_KEY",
48333
+ authHint: "PUBLISHER_RETRIEVAL_LLM_API_KEY",
47679
48334
  what: "Chat request"
47680
48335
  });
47681
48336
  const content = reply?.choices?.[0]?.message?.content;
@@ -47706,7 +48361,7 @@ function openAiEmbedChunk(args) {
47706
48361
  signal,
47707
48362
  timeoutMs,
47708
48363
  secrets: [args.apiKey],
47709
- authHint: "EMBEDDING_API_KEY",
48364
+ authHint: "PUBLISHER_RETRIEVAL_EMBEDDING_API_KEY",
47710
48365
  what: "Embedding request"
47711
48366
  });
47712
48367
  const data = json?.data;
@@ -47937,16 +48592,11 @@ function parseRetrievalConfig(raw) {
47937
48592
  if (raw === undefined || raw === null)
47938
48593
  return;
47939
48594
  if (typeof raw !== "object" || Array.isArray(raw)) {
47940
- throw new Error(`Invalid retrieval: expected an object, got ${JSON.stringify(raw)}. ` + `Fix: "retrieval": { "indexing": { "maxEntities": 20000 } }`);
48595
+ throw new Error(`Invalid retrieval: expected an object, got ${JSON.stringify(raw)}. ` + `Fix: "retrieval": { "dimensionValues": { "enabled": false } }`);
47941
48596
  }
47942
- const input = block(raw, "retrieval", ["indexing", "llm", "embedding", "egress", "dimensionValues"], `"retrieval": { "indexing": { "maxEntities": 20000 } }`);
48597
+ const live = Object.fromEntries(Object.entries(raw).filter(([key]) => !RETIRED_BLOCKS.includes(key)));
48598
+ const input = block(live, "retrieval", ["llm", "embedding", "dimensionValues"], `"retrieval": { "dimensionValues": { "enabled": false } }`);
47943
48599
  const out = {};
47944
- const indexing = input.indexing;
47945
- if (indexing !== undefined && indexing !== null) {
47946
- const fields = block(indexing, "retrieval.indexing", ["maxEntities"], `"indexing": { "maxEntities": 20000 }`);
47947
- const maxEntities = positiveInt(fields.maxEntities, "retrieval.indexing.maxEntities", "set it to e.g. 20000");
47948
- out.indexing = maxEntities === undefined ? {} : { maxEntities };
47949
- }
47950
48600
  if (input.llm !== undefined && input.llm !== null) {
47951
48601
  const llm = parseLlm(input.llm);
47952
48602
  if (llm)
@@ -47957,16 +48607,12 @@ function parseRetrievalConfig(raw) {
47957
48607
  if (embedding)
47958
48608
  out.embedding = embedding;
47959
48609
  }
47960
- if (input.egress !== undefined)
47961
- out.egressIgnored = true;
47962
48610
  if (input.dimensionValues !== undefined && input.dimensionValues !== null) {
47963
48611
  out.dimensionValues = parseDimensionValues(input.dimensionValues);
47964
48612
  }
47965
48613
  return out;
47966
48614
  }
47967
48615
  function setRetrievalConfig(config) {
47968
- if (config?.egressIgnored)
47969
- logger.warn(RETIRED_EGRESS_WARNING);
47970
48616
  loaded = config;
47971
48617
  }
47972
48618
  function loadedRetrievalConfig() {
@@ -47975,11 +48621,11 @@ function loadedRetrievalConfig() {
47975
48621
  function getDimensionValueSettings() {
47976
48622
  return { ...DIMENSION_VALUE_DEFAULTS, ...loaded?.dimensionValues };
47977
48623
  }
47978
- 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;
48624
+ var MAX_GIVEN_COMBINATIONS = 50, RETIRED_BLOCKS, DIMENSION_VALUE_KEYS, GIVENS_FIX = `"givens": { "<package>": { "REPORT_ID": [123, 456] } }`, loaded;
47979
48625
  var init_config = __esm(() => {
47980
- init_logger();
47981
48626
  init_types2();
47982
48627
  init_defaults();
48628
+ RETIRED_BLOCKS = ["indexing", "egress"];
47983
48629
  DIMENSION_VALUE_KEYS = ["enabled", "givens"];
47984
48630
  });
47985
48631
 
@@ -48113,7 +48759,7 @@ function embeddingStartupNotices(file) {
48113
48759
  if (!key && (provider === "openai" || provider === "openai-compatible" || provider === "google")) {
48114
48760
  notices.push({
48115
48761
  level: "warn",
48116
- message: `retrieval.embedding names provider "${provider}" but EMBEDDING_API_KEY is not set, so semantic search is off and get_context ranks lexically. ` + `Fix: set EMBEDDING_API_KEY in the server's environment.`
48762
+ message: `retrieval.embedding names provider "${provider}" but PUBLISHER_RETRIEVAL_EMBEDDING_API_KEY is not set, so semantic search is off and get_context ranks lexically. ` + `Fix: set PUBLISHER_RETRIEVAL_EMBEDDING_API_KEY in the server's environment.`
48117
48763
  });
48118
48764
  }
48119
48765
  const reembeds = "Changing the model or its dimensions re-embeds every package.";
@@ -48371,6 +49017,16 @@ function mergeThemes(base, override) {
48371
49017
  }
48372
49018
  return merged;
48373
49019
  }
49020
+ function warnOnCaseVariantEnvironments(names) {
49021
+ const seen = [];
49022
+ for (const name of names) {
49023
+ const variant = caseVariantOf(name, seen);
49024
+ if (variant !== undefined) {
49025
+ logger.warn(`Environment "${name}" in ${PUBLISHER_CONFIG_NAME} differs only in letter case from environment "${variant}". On a case-insensitive file system both resolve to one directory, and "${name}"'s DuckDB connections that share a name with "${variant}"'s fail with DuckDBFileScopeConflictError; rename one of them.`, { code: "ENVIRONMENT_NAME_CASE_VARIANT" });
49026
+ }
49027
+ seen.push(name);
49028
+ }
49029
+ }
48374
49030
  var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig = () => {
48375
49031
  const maxMemoryBytes = settings.get("memory.maxBytes");
48376
49032
  if (maxMemoryBytes === 0) {
@@ -48410,7 +49066,7 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
48410
49066
  try {
48411
49067
  new URL(baseUrl);
48412
49068
  } catch {
48413
- throw new Error(`Invalid value for EMBEDDING_API_BASE: expected a URL, got "${rawBase}"`);
49069
+ throw new Error(`Invalid value for PUBLISHER_RETRIEVAL_EMBEDDING_BASE_URL: expected a URL, got "${rawBase}"`);
48414
49070
  }
48415
49071
  const model = embeddingValue("retrieval.embedding.model", file) || DEFAULT_EMBEDDING_MODEL;
48416
49072
  const dimensions = embeddingValue("retrieval.embedding.dimensions", file);
@@ -48435,13 +49091,9 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
48435
49091
  return null;
48436
49092
  }
48437
49093
  return {
48438
- tickIntervalMs: settings.get("materialization.schedulerIntervalMs"),
48439
- maxFiresPerTick: settings.get("materialization.schedulerMaxFiresPerTick")
49094
+ tickIntervalMs: settings.get("materialization.schedulerIntervalMs")
48440
49095
  };
48441
- }, 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"), getPersistAddressIncludesDestination = () => settings.get("persist.addressIncludesDestination"), gateSwitches = () => ({
48442
- materialize: true,
48443
- gatedSources: false
48444
- }), getMcpCorsOrigins = () => {
49096
+ }, 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"), getSnowflakeApplicationName = () => settings.get("snowflake.applicationName"), 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"), getPersistAddressIncludesDestination = () => settings.get("persist.addressIncludesDestination"), getMcpCorsOrigins = () => {
48445
49097
  const origins = settings.get("mcp.corsOrigins");
48446
49098
  if (origins.length === 1 && origins[0] === "*")
48447
49099
  return "*";
@@ -48520,7 +49172,7 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
48520
49172
  ...retrieval ? { retrieval } : {},
48521
49173
  environments
48522
49174
  };
48523
- }, isPackageInlineFieldsEnabled = () => settings.get("packageInlineFields") === "on", isVersioningEnabled = () => settings.get("packageVersioning") === "on", getModelPageMode = () => settings.get("modelPage"), getVersionPromotionMode = () => settings.get("versionPromotion"), RETRIEVAL_LEAVES, OPENAI_COMPATIBLE_LEAVES, getRetrievalConfig = (serverRoot) => getPublisherConfig(serverRoot).retrieval, isPublisherConfigFrozen = () => {
49175
+ }, isPackageInlineFieldsEnabled = () => settings.get("packageInlineFields") === "on", getModelPageMode = () => settings.get("modelPage"), getVersionPromotionMode = () => settings.get("versionPromotion"), RETRIEVAL_LEAVES, OPENAI_COMPATIBLE_LEAVES, getRetrievalConfig = (serverRoot) => getPublisherConfig(serverRoot).retrieval, isPublisherConfigFrozen = () => {
48524
49176
  const current = Settings.current();
48525
49177
  try {
48526
49178
  if (current.fileError)
@@ -48609,6 +49261,7 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
48609
49261
  ...resolvedTheme ? { theme: resolvedTheme } : {}
48610
49262
  });
48611
49263
  }
49264
+ warnOnCaseVariantEnvironments(validEnvironments.map((env) => env.name));
48612
49265
  return {
48613
49266
  ...rawConfig.theme ? { theme: rawConfig.theme } : {},
48614
49267
  environments: validEnvironments
@@ -48624,6 +49277,7 @@ var BUNDLED_DEFAULT_CONFIG_PATH, PER_MODE_COLOR_KEYS, getMemoryGovernorConfig =
48624
49277
  var init_config2 = __esm(() => {
48625
49278
  init_constants();
48626
49279
  init_logger();
49280
+ init_path_safety();
48627
49281
  init_openai_compatible();
48628
49282
  init_settings2();
48629
49283
  init_config();
@@ -48660,7 +49314,7 @@ function deriveColumns(persistSource) {
48660
49314
  type: String(f.type)
48661
49315
  }));
48662
49316
  } catch (err) {
48663
- logger.warn("Failed to derive columns for persist source", {
49317
+ reportPlanDiagnostic("warn", "persist_columns_underived", "Failed to derive columns for persist source", {
48664
49318
  sourceID: persistSource.sourceID,
48665
49319
  code: errorCodeOf(err)
48666
49320
  });
@@ -48696,10 +49350,59 @@ function unboundParameterNamesOf(def) {
48696
49350
  }
48697
49351
  return unbound;
48698
49352
  }
49353
+ function unboundParameterReason(sourceName, unbound) {
49354
+ const list = unbound.map((p) => `'${p}'`).join(", ");
49355
+ const bound = unbound.map((p) => `${p} is …`).join(", ");
49356
+ return `it declares unbound parameter(s) ${list}; a source with an unbound ` + `parameter is not stored. Bind it (\`${sourceName}(${bound})\`) to store it`;
49357
+ }
49358
+ function readsBoundArgument(def) {
49359
+ if (def === null || typeof def !== "object")
49360
+ return false;
49361
+ const args = def.arguments;
49362
+ if (args === null || typeof args !== "object" || Object.keys(args).length === 0) {
49363
+ return false;
49364
+ }
49365
+ const bound = new Set(Object.keys(args));
49366
+ const seen = new WeakSet;
49367
+ const reads = (node, depth, top) => {
49368
+ if (node === null || typeof node !== "object" || seen.has(node)) {
49369
+ return false;
49370
+ }
49371
+ if (depth > MAX_ARGUMENT_WALK_DEPTH)
49372
+ return true;
49373
+ seen.add(node);
49374
+ const n = node;
49375
+ if (!top && typeof n.join === "string")
49376
+ return false;
49377
+ if (n.node === "parameter") {
49378
+ const [name] = Array.isArray(n.path) ? n.path : [];
49379
+ return typeof name === "string" && bound.has(name);
49380
+ }
49381
+ return Object.entries(node).some(([key, value]) => !(top && (key === "arguments" || key === "parameters")) && reads(value, depth + 1, false));
49382
+ };
49383
+ return reads(def, 0, true);
49384
+ }
49385
+ function boundInvocationReason(sourceName) {
49386
+ return `it extends a bound invocation of a source that reads the parameter ` + `it binds, which cannot be keyed as a stored relation, so it is not ` + `stored. Write it as a query source over the invocation ` + `(\`source: ${sourceName} is s(x is …) -> { select: * } extend { … }\`), ` + `which is stored, or persist that query shape with #@ persist`;
49387
+ }
49388
+ function unkeyableInChain(map, sourceID) {
49389
+ let node = map.node(sourceID);
49390
+ for (let hops = 0;node && hops < 64; hops++) {
49391
+ if (readsBoundArgument(node.def))
49392
+ return node.sourceID;
49393
+ const base = node.base;
49394
+ if (!base || base.hop === "query" || base.sourceID === undefined) {
49395
+ return;
49396
+ }
49397
+ node = map.node(base.sourceID);
49398
+ }
49399
+ return;
49400
+ }
49401
+ var MAX_ARGUMENT_WALK_DEPTH = 200;
48699
49402
  var init_persist_source_fields = __esm(() => {
48700
49403
  init_error_code();
48701
49404
  init_declaration();
48702
- init_logger();
49405
+ init_plan_diagnostics();
48703
49406
  });
48704
49407
 
48705
49408
  // src/service/governance/ir/source_reads.ts
@@ -49006,7 +49709,9 @@ function plannedSources(targets) {
49006
49709
  function isUnkeyable(source) {
49007
49710
  return unkeyable.has(source);
49008
49711
  }
49009
- function attachBuildTarget(source, built) {
49712
+ function attachBuildTarget(source, attached) {
49713
+ const forced = forcedUnkeyable?.(source);
49714
+ const built = forced !== undefined ? { unkeyable: forced } : attached;
49010
49715
  if ("target" in built) {
49011
49716
  buildTargets.set(source, built.target);
49012
49717
  unkeyable.delete(source);
@@ -49306,7 +50011,7 @@ async function resolveConnectionDigests(connections, builds, onSkipped) {
49306
50011
  }
49307
50012
  return connectionDigests;
49308
50013
  }
49309
- var buildTargets, unkeyable, testAddresses, presentedSourceIDs, readsBySource;
50014
+ var buildTargets, unkeyable, testAddresses, forcedUnkeyable, presentedSourceIDs, readsBySource;
49310
50015
  var init_addressing = __esm(() => {
49311
50016
  init_config2();
49312
50017
  init_storage_table_path();
@@ -49330,6 +50035,25 @@ function gateRefusalReason(routes) {
49330
50035
  }
49331
50036
  return "authorize";
49332
50037
  }
50038
+ function gateKindName(reason) {
50039
+ return reason === "access_filter" ? "#(access_filter)" : "#(authorize)";
50040
+ }
50041
+ function gateKindsName(routes, code = false) {
50042
+ let filter = false;
50043
+ let lock = false;
50044
+ for (const route of routes) {
50045
+ if (route === "access_filter")
50046
+ filter = true;
50047
+ else
50048
+ lock = true;
50049
+ }
50050
+ const kinds = [
50051
+ ...filter ? [gateKindName("access_filter")] : [],
50052
+ ...lock || !filter ? [gateKindName("authorize")] : []
50053
+ ];
50054
+ const quoted = kinds.map((k) => code ? `\`${k}\`` : k);
50055
+ return quoted.join(" and an ");
50056
+ }
49333
50057
 
49334
50058
  // src/service/materialization/domain/compiled_build_plan.ts
49335
50059
  function stringCapabilityKey(sourceID, destination) {
@@ -50549,7 +51273,7 @@ function rollupLabel(plan) {
50549
51273
  }
50550
51274
 
50551
51275
  // src/service/materialization/plan/rollup_plan.ts
50552
- import { createHash as createHash8 } from "node:crypto";
51276
+ import { createHash as createHash9 } from "node:crypto";
50553
51277
  import { Annotations as Annotations8 } from "@malloydata/malloy";
50554
51278
  function isRollupRoute(route) {
50555
51279
  return route === ROLLUP_ROUTE || route === ROLLUP_ALIAS_ROUTE;
@@ -50558,10 +51282,10 @@ function rollupsServeGatedBases(placement, own, lockOnly) {
50558
51282
  return tableKeepsGates({
50559
51283
  kind: "rollup",
50560
51284
  tier: placement.storage === undefined ? "database" : "storage",
50561
- v1: false,
51285
+ declaredByPersist: false,
50562
51286
  baseGateProven: true,
50563
51287
  gate: baseGateOf(own, lockOnly)
50564
- }, gateSwitches());
51288
+ });
50565
51289
  }
50566
51290
  function baseGateOf(own, lockOnly) {
50567
51291
  return {
@@ -50581,10 +51305,10 @@ function rollupGateEnforcedAtRead(plan) {
50581
51305
  return tableKeepsGates({
50582
51306
  kind: "rollup",
50583
51307
  tier: plan.storage === undefined ? "database" : "storage",
50584
- v1: !variant,
51308
+ declaredByPersist: !variant,
50585
51309
  baseGateProven: variant && plan.baseGated === true,
50586
51310
  gate: baseGateOf(variant && plan.baseGateOwn === true, variant && plan.baseGateLocksOnly === true)
50587
- }, gateSwitches());
51311
+ });
50588
51312
  }
50589
51313
  function measureRefusalKey(baseSourceID, baseName, measure, reason, table) {
50590
51314
  const url = splitSourceID(baseSourceID)?.url ?? "";
@@ -50682,7 +51406,7 @@ function byCodepoint2(a, b) {
50682
51406
  return a < b ? -1 : a > b ? 1 : 0;
50683
51407
  }
50684
51408
  function digest(parts) {
50685
- return createHash8("sha256").update(parts.join("\x00")).digest("hex").slice(0, 8);
51409
+ return createHash9("sha256").update(parts.join("\x00")).digest("hex").slice(0, 8);
50686
51410
  }
50687
51411
  function rollupName(baseDeclaredName, packageRelativeSourceID, grain, placement) {
50688
51412
  const slug = grain.join("_").replace(/[^A-Za-z0-9_]/g, "_");
@@ -50964,9 +51688,18 @@ function rollupFactsOf(map, node, def, byName, sourceName) {
50964
51688
  joinsRead,
50965
51689
  dialect: typeof def.dialect === "string" ? def.dialect : undefined,
50966
51690
  compositeRowFilter: rowFilterOnComposite(def, map.model()),
51691
+ unboundParameters: unboundParametersOf(def),
51692
+ readsBoundArgument: unkeyableInChain(map, node.sourceID) !== undefined,
50967
51693
  unservable
50968
51694
  };
50969
51695
  }
51696
+ function unboundParametersOf(def) {
51697
+ try {
51698
+ return unboundParameterNamesOf(def);
51699
+ } catch {
51700
+ return ["(unreadable)"];
51701
+ }
51702
+ }
50970
51703
  function declarationRefusal(decl, facts, ctx) {
50971
51704
  const { byName, sourceName, unservable, gate, timeFields, zone } = facts;
50972
51705
  const field = byName.get(decl.measure);
@@ -50983,6 +51716,12 @@ function declarationRefusal(decl, facts, ctx) {
50983
51716
  measure: decl.measure
50984
51717
  };
50985
51718
  }
51719
+ if (facts.unboundParameters.length > 0) {
51720
+ return unservable("free_parameter", decl, unboundParameterReason(sourceName, facts.unboundParameters));
51721
+ }
51722
+ if (facts.readsBoundArgument) {
51723
+ return unservable("bound_invocation_unkeyable", decl, boundInvocationReason(sourceName));
51724
+ }
50986
51725
  const timeRead = facts.windowed ? "the source's rows read the current time (a `where:` with `now` or a relative time filter such as `f'last 7 days'`, a rolling window)" : timeFields.has(decl.measure) ? "the measure reads the current time (`now`, or a relative time filter)" : decl.grain.filter((g) => timeFields.has(g) || pathReadsCurrentTime(g, facts)).map((g) => `its grain dimension \`${g}\` reads the current time (\`now\`, or a relative time filter)`)[0];
50987
51726
  if (timeRead) {
50988
51727
  return unservable("current_time", decl, `${timeRead}, which a rollup would fix at build time while a live query reads it again at every read`);
@@ -51019,20 +51758,20 @@ function declarationRefusal(decl, facts, ctx) {
51019
51758
  return unservable("given_where_over_unstored_field", decl, `the source's \`where:\` reads a given and ${[...new Set(ungrained)].map((c) => `\`${c}\``).join(", ")}, which the grain does not keep, so it could not be re-applied to the rollup's rows per caller`);
51020
51759
  }
51021
51760
  if (gate.declared && facts.compositeRowFilter) {
51022
- return unservable(gate.reason.base, decl, "the source reads a row-level gate (`#(access_filter)`) declared on a composite source, which live refuses every caller, so no rollup of it is read");
51761
+ return unservable(gate.reason.base, decl, `the source reads a row-level gate (\`${gateKindName(gate.reason.base)}\`) declared on a composite source, which live refuses every caller, so no rollup of it is read`);
51023
51762
  }
51024
51763
  if (gate.declared && !(ctx.readUnderGates ?? rollupsServeGatedBases(decl, gate.own, lockOnlyAt(decl, facts)))) {
51025
- return unservable(gate.reason.base, decl, `the source's row-level gate (\`#(access_filter)\` or \`#(authorize)\`) ${notOwnGate(gate)}, and a rollup keeps only its base's own gate, so its table would cost a build no query reads`);
51764
+ return unservable(gate.reason.base, decl, `the source's ${gate.baseKinds ?? `\`${gateKindName(gate.reason.base)}\``} gate ${notOwnGate(gate)}, and a rollup keeps only its base's own gate, so its table would cost a build no query reads`);
51026
51765
  }
51027
51766
  if (gate.declared && gate.joinGated) {
51028
- return unservable(gate.reason.joined, decl, "a source it joins has a row-level gate, which a rollup cannot re-apply to its rows");
51767
+ return unservable(gate.reason.joined, decl, `a source it joins has ${gate.joinedKinds ? `an ${gate.joinedKinds}` : "a"} gate, which a rollup cannot re-apply to its rows`);
51029
51768
  }
51030
51769
  const ungated = [
51031
51770
  ...gate.unkeepable,
51032
51771
  ...gate.dimensions.filter((g) => !decl.grain.includes(g))
51033
51772
  ];
51034
51773
  if (ungated.length > 0) {
51035
- return unservable(gate.reason.base, decl, `the source's access filter reads ${ungated.map((g) => `\`${g}\``).join(", ")}, which the grain does not keep, so the rollup's rows could not be filtered per caller`);
51774
+ return unservable(gate.reason.base, decl, `the source's \`${gateKindName(gate.reason.base)}\` gate reads ${ungated.map((g) => `\`${g}\``).join(", ")}, which the grain does not keep, so the rollup's rows could not be filtered per caller`);
51036
51775
  }
51037
51776
  return;
51038
51777
  }
@@ -51404,6 +52143,8 @@ function gateFieldNames(def, byName, modelDef, joinUsage, scope) {
51404
52143
  base: gateRefusalReason(entries.map((e) => e.route)),
51405
52144
  joined: gateRefusalReason(joinedRoutes)
51406
52145
  },
52146
+ baseKinds: gateKindsName(entries.map((e) => e.route), true),
52147
+ joinedKinds: gateKindsName(joinedRoutes, true),
51407
52148
  lockOnly: locksReadNoRowField(entries, dimensions, unkeepable),
51408
52149
  own: entries.length > 0 && unkeepable.size === 0 && entries.every((e) => !e.selfContained && e.struct !== undefined) && gateNotesDeclaredBy(def, scope),
51409
52150
  declaredHere: gateNotesDeclaredBy(def, scope),
@@ -51608,7 +52349,6 @@ function joinOneKeysOf(map) {
51608
52349
  var ROLLUP_ROUTE = "rollup", ROLLUP_ALIAS_ROUTE = "preaggregate", fieldNameOf2 = (f) => typeof f.as === "string" ? f.as : typeof f.name === "string" ? f.name : undefined, isMeasure = (f) => f.expressionType === "aggregate" && f.join === undefined && f.type !== "turtle", isDimension = (f) => f.join === undefined && f.type !== "turtle" && f.expressionType !== "aggregate" && f.expressionType !== "ungrouped_aggregate" && f.expressionType !== "analytic", isHidden = (f) => f?.accessModifier != null && f.accessModifier !== "public", scopes, NAME_SLUG_LIMIT = 40, PREAGGREGATE_SPELLING = "#@ preaggregate", LOCK_WORDS;
51609
52350
  var init_rollup_plan = __esm(() => {
51610
52351
  init_key_check_text();
51611
- init_config2();
51612
52352
  init_gate_policy();
51613
52353
  init_preaggregate_synonym();
51614
52354
  init_rollup_base();
@@ -51620,6 +52360,7 @@ var init_rollup_plan = __esm(() => {
51620
52360
  init_authorize_routes();
51621
52361
  init_malloy_lexer_core();
51622
52362
  init_annotation_reader();
52363
+ init_persist_source_fields();
51623
52364
  init_dialect();
51624
52365
  init_stored_column_types();
51625
52366
  init_declaration();
@@ -51665,21 +52406,7 @@ var init_source_connection_type = __esm(() => {
51665
52406
  function assertMaterializationEligible(persistSource, annotationFields, options = {}) {
51666
52407
  const sourceName = persistSource.name;
51667
52408
  assertStorageBuildReadsConnection(persistSource, options.connectionTypes);
51668
- let unbound;
51669
- try {
51670
- unbound = unboundParameterNamesOf(sourceDefOf(persistSource));
51671
- } catch (err) {
51672
- throw new MaterializationEligibilityError({
51673
- reason: "free_parameter",
51674
- message: `Source '${sourceName}' cannot be materialized into a storage ` + `destination: its parameter surface could not be determined ` + `(${err instanceof Error ? err.message : String(err)}), so the ` + `publisher cannot prove the source has no free parameters. This is ` + `refused for safety. Drop 'storage=' to serve it live from the ` + `source warehouse.`
51675
- });
51676
- }
51677
- if (unbound.length > 0) {
51678
- throw new MaterializationEligibilityError({
51679
- reason: "free_parameter",
51680
- message: `Source '${sourceName}' cannot be materialized into a storage ` + `destination: it has unbound parameter(s) ` + `${unbound.map((p) => `'${p}'`).join(", ")}. A source with a free ` + `parameter is a template instantiated per query, so there is no ` + `single relation to materialize. Bind the parameter to a constant, ` + `or drop 'storage=' to serve it live from the source warehouse.`
51681
- });
51682
- }
52409
+ assertNoUnboundParameter(persistSource);
51683
52410
  const classified = admitGivenPositions(persistSource);
51684
52411
  if (!classified.ok) {
51685
52412
  throw new MaterializationEligibilityError({
@@ -51689,9 +52416,10 @@ function assertMaterializationEligible(persistSource, annotationFields, options
51689
52416
  }
51690
52417
  assertMergeKeyScopeResolvable(persistSource, readTimeDynamicTerms(persistSource), annotationFields, `Source '${sourceName}'`);
51691
52418
  if (!options.gateEnforcedAtRead && referencesAuthorize(persistSource)) {
52419
+ const reason = gateReasonOf(persistSource);
51692
52420
  throw new MaterializationEligibilityError({
51693
- reason: gateReasonOf(persistSource),
51694
- message: `Source '${sourceName}' cannot be materialized into a storage ` + `destination: it is protected by a gate — #(authorize) or ` + `#(access_filter), its own or a joined source's. Both are evaluated ` + `per request; a materialized-once table served frozen carries no ` + `gate, so it would be served to everyone, bypassing authorization. ` + `This is refused for safety. Serve this source live (drop ` + `'storage=').`
52421
+ reason,
52422
+ message: `Source '${sourceName}' cannot be materialized into a storage ` + `destination: it is protected by an ${gateKindsOf(persistSource)} ` + `gate, its own or a joined source's. A gate is evaluated ` + `per request; a materialized-once table served frozen carries no ` + `gate, so it would be served to everyone, bypassing authorization. ` + `This is refused for safety. Serve this source live (drop ` + `'storage=').`
51695
52423
  });
51696
52424
  }
51697
52425
  }
@@ -51784,22 +52512,24 @@ function assertDatabasePersistNotAuthorizeGated(persistSource, sourceName = pers
51784
52512
  if (origin === "persist" && tableKeepsGates({
51785
52513
  kind: "persist",
51786
52514
  tier: "database",
51787
- v1: true,
52515
+ declaredByPersist: true,
51788
52516
  gate: {
51789
52517
  rowLevel: gateOutcome?.classification === "row_level",
51790
52518
  attributed: gateOutcome?.attributed === true,
51791
52519
  inheritedRowFilter: false
51792
52520
  }
51793
- }, gateSwitches())) {
52521
+ })) {
51794
52522
  return;
51795
52523
  }
51796
- const gated = origin === "rollup" ? `the source '${sourceName}' rolls up is protected by an ` + `#(authorize) gate (its own, a joined source's, or inherited ` + `from a source it derives from)` : `it is protected by an #(authorize) gate (its own, a joined ` + `source's, or inherited from a source it derives from)`;
52524
+ const reason = gateReasonOf(persistSource);
52525
+ const kind = gateKindsOf(persistSource);
52526
+ const gated = origin === "rollup" ? `the source '${sourceName}' rolls up is protected by an ` + `${kind} gate (its own, a joined source's, or inherited ` + `from a source it derives from)` : `it is protected by an ${kind} gate (its own, a joined ` + `source's, or inherited from a source it derives from)`;
51797
52527
  const remedy = origin === "rollup" ? `If the gate is on the rolled-up source itself, remove the ` + `'#@ preaggregate' annotation or move the gate to a source that ` + `is not pre-aggregated. If it is reached through a join or a ` + `derivation instead, that source is already unaggregated -- the ` + `fix is to stop pre-aggregating this entry point, not to move ` + `the gate again.` : `If the gate is on this source itself, drop '#@ persist' or ` + `move the gate to a source that is not materialized. If it is ` + `reached through a join or a derivation instead, that source is ` + `already not materialized -- express the condition as this ` + `entry point's own row-level gate, or stop persisting it.`;
51798
52528
  const what = origin === "rollup" ? `Pre-aggregation rollup '${sourceName}' cannot be built` : `Source '${sourceName}' cannot be materialized (database ` + `'#@ persist')`;
51799
52529
  const alsoRollup = origin === "rollup" ? ` A rollup also groups ACROSS the gated column, so it could not ` + `be row-filtered afterwards even in principle.` : "";
51800
52530
  throw new MaterializationEligibilityError({
51801
- reason: gateReasonOf(persistSource),
51802
- message: `${what}: ${gated}. An authorize expression is evaluated per ` + `request; without a proven row-level, fully-attributed ` + `classification this pass cannot show the served artifact matches ` + `what a live query would enforce.` + `${alsoRollup} This is refused for safety. ${remedy}`
52531
+ reason,
52532
+ message: `${what}: ${gated}. A gate expression is evaluated per ` + `request; without a proven row-level, fully-attributed ` + `classification this pass cannot show the served artifact matches ` + `what a live query would enforce.` + `${alsoRollup} This is refused for safety. ${remedy}`
51803
52533
  });
51804
52534
  }
51805
52535
  function assertDatabaseTablePlaceable(persistSource, sourceName, origin, annotationFields) {
@@ -51874,13 +52604,19 @@ function walkForAuthorize(node, seen, depth) {
51874
52604
  return false;
51875
52605
  }
51876
52606
  function gateReasonOf(persistSource) {
52607
+ return gateRefusalReason(gateRoutesOf(persistSource));
52608
+ }
52609
+ function gateKindsOf(persistSource) {
52610
+ return gateKindsName(gateRoutesOf(persistSource));
52611
+ }
52612
+ function gateRoutesOf(persistSource) {
51877
52613
  const routes = new Set;
51878
52614
  try {
51879
52615
  walkForGateRoutes(sourceDefOf(persistSource), new WeakSet, 0, routes);
51880
52616
  } catch {
51881
52617
  routes.add("authorize");
51882
52618
  }
51883
- return gateRefusalReason(routes);
52619
+ return routes;
51884
52620
  }
51885
52621
  function walkForGateRoutes(node, seen, depth, routes) {
51886
52622
  if (depth > MAX_AUTHORIZE_WALK_DEPTH) {
@@ -51981,14 +52717,19 @@ function gateEnforcedAtRead(sourceID, plan, storage = false) {
51981
52717
  if (!materialized) {
51982
52718
  if (!storage || isPersistedResultSourceID(sourceID))
51983
52719
  return false;
51984
- return tableKeepsGates({ kind: "persist", tier: "storage", v1: true, gate }, gateSwitches());
52720
+ return tableKeepsGates({
52721
+ kind: "persist",
52722
+ tier: "storage",
52723
+ declaredByPersist: true,
52724
+ gate
52725
+ });
51985
52726
  }
51986
52727
  return tableKeepsGates({
51987
52728
  kind: "materialize",
51988
52729
  tier: !storage && materialized.persist?.storage === undefined ? "database" : "storage",
51989
- v1: false,
52730
+ declaredByPersist: false,
51990
52731
  gate
51991
- }, gateSwitches());
52732
+ });
51992
52733
  }
51993
52734
  function storageKeepsOwnGate(source, plan) {
51994
52735
  return referencesAuthorize(source) && gateEnforcedAtRead(source.sourceID, plan, true);
@@ -51997,7 +52738,7 @@ function holdsOnlyUngatedRows(source) {
51997
52738
  return !referencesAuthorize(source);
51998
52739
  }
51999
52740
  function inheritedRowFilterRefusal(sourceName, tier) {
52000
- return `Source '${sourceName}' cannot be materialized (${tier}): it reads an ` + `#(access_filter) row-level gate from a source it derives from or ` + `extends, not one it declares itself. A table of it would hold every ` + `caller's rows, and the served copy, which reads the table in place of ` + `the source that declares the gate, cannot apply that gate to it, so ` + `every query would be answered live anyway. It is not built: no ` + `answer changes. To serve it from a table, declare the row-level gate ` + `on this source itself.`;
52741
+ return `Source '${sourceName}' cannot be materialized (${tier}): it reads an ` + `#(access_filter) row-level gate from a source it derives from or ` + `extends, not one it declares itself. A table of it would hold every ` + `caller's rows, and the served copy, which reads the table in place of ` + `the source that declares the gate, cannot apply that gate to it, so ` + `no query would be answered from that table. It is not built: no ` + `answer changes. To serve it from a table, declare the row-level gate ` + `on this source itself.`;
52001
52742
  }
52002
52743
  function assertStorageRowFilterNotInherited(source, plan) {
52003
52744
  const table = plan?.tables?.[source.sourceID];
@@ -52017,6 +52758,42 @@ function assertStorageRowFilterNotInherited(source, plan) {
52017
52758
  });
52018
52759
  }
52019
52760
  }
52761
+ function unkeyableRefusal(source, err) {
52762
+ if (!isUnkeyable(source))
52763
+ return;
52764
+ let bound = false;
52765
+ try {
52766
+ bound = readsBoundArgument(sourceDefOf(source));
52767
+ } catch {
52768
+ bound = false;
52769
+ }
52770
+ return new MaterializationEligibilityError({
52771
+ reason: bound ? "bound_invocation_unkeyable" : "address_unresolved",
52772
+ message: `'${source.name}' cannot be materialized: ` + (bound ? boundInvocationReason(source.name) : `its build cannot be keyed as a stored relation (${err instanceof Error ? err.message : String(err)})`) + ". It is not built and serves live; the package's other sources are built."
52773
+ });
52774
+ }
52775
+ function assertKeyable(source) {
52776
+ const refusal = unkeyableRefusal(source, new Error("Malloy could not key its build"));
52777
+ if (refusal)
52778
+ throw refusal;
52779
+ }
52780
+ function assertNoUnboundParameter(source) {
52781
+ let unbound;
52782
+ try {
52783
+ unbound = unboundParameterNamesOf(sourceDefOf(source));
52784
+ } catch (err) {
52785
+ throw new MaterializationEligibilityError({
52786
+ reason: "free_parameter",
52787
+ message: `'${source.name}' cannot be materialized: its parameter surface ` + `could not be determined (${err instanceof Error ? err.message : String(err)}), ` + `so it cannot be proven to have no unbound parameter. It serves live.`
52788
+ });
52789
+ }
52790
+ if (unbound.length > 0) {
52791
+ throw new MaterializationEligibilityError({
52792
+ reason: "free_parameter",
52793
+ message: `'${source.name}' cannot be materialized: ${unboundParameterReason(source.name, unbound)}. It serves live.`
52794
+ });
52795
+ }
52796
+ }
52020
52797
  function assertPlacementNamed(source) {
52021
52798
  if (!declaresEmptyStorage(source))
52022
52799
  return;
@@ -52046,15 +52823,17 @@ function assertTierEligible(source, storage, plan, annotationFields = deriveAnno
52046
52823
  const rollup = table?.rollup;
52047
52824
  assertDatabasePersistNotAuthorizeGated(source, source.name, rollup ? "rollup" : "persist", table?.gate, annotationFields, { gateEnforcedAtRead: !!rollup && rollupGateEnforcedAtRead(rollup) });
52048
52825
  if (table?.materialize && referencesAuthorize(source) && !gateEnforcedAtRead(source.sourceID, plan)) {
52826
+ const reason = gateReasonOf(source);
52049
52827
  throw new MaterializationEligibilityError({
52050
- reason: gateReasonOf(source),
52051
- message: `Source '${source.name}' cannot be materialized (database ` + `'#(materialize)'): it is protected by an #(authorize) or ` + `#(access_filter) gate, and its table is read only through the ` + `served copy, which keeps only the entry point's own row-level ` + `gate. The source serves live.`
52828
+ reason,
52829
+ message: `Source '${source.name}' cannot be materialized (database ` + `'#(materialize)'): it is protected by an ` + `${gateKindsOf(source)} gate, and its table is read only through the ` + `served copy, which keeps only the entry point's own row-level ` + `gate. The source serves live.`
52052
52830
  });
52053
52831
  }
52054
- if (isPersistedResultSourceID(source.sourceID) && !gateSwitches().gatedSources && referencesAuthorize(source)) {
52832
+ if (isPersistedResultSourceID(source.sourceID) && referencesAuthorize(source)) {
52833
+ const reason = gateReasonOf(source);
52055
52834
  throw new MaterializationEligibilityError({
52056
- reason: gateReasonOf(source),
52057
- message: `'${source.name}' cannot be materialized (database): the ` + `source it reads is protected by an #(authorize) or ` + `#(access_filter) gate, and a persisted view's or query's table ` + `is not read past a gate, so it would be built and never read. ` + `It is not built, and its queries are answered live, as on ` + `'storage='.`
52835
+ reason,
52836
+ message: `'${source.name}' cannot be materialized (database): the ` + `source it reads is protected by an ${gateKindsOf(source)} ` + `gate, and a persisted view's or query's table ` + `is not read past a gate, so it would be built and never read. ` + `It is not built, and its queries are answered live, as on ` + `'storage='.`
52058
52837
  });
52059
52838
  }
52060
52839
  assertBuildReadsNoCurrentTime(source, plan);
@@ -52075,7 +52854,7 @@ function assertBuildReadsNoCurrentTime(source, plan) {
52075
52854
  }
52076
52855
  function currentTimeRefusalCause(source, plan) {
52077
52856
  if (referencesAuthorize(source)) {
52078
- return "it is protected by an #(authorize) or #(access_filter) gate, whose " + "decision a table as of its build would freeze";
52857
+ return `it is protected by an ${gateKindsOf(source)} gate, ` + "whose decision a table as of its build would freeze";
52079
52858
  }
52080
52859
  if (deriveAnnotationFields(source).refresh === "incremental") {
52081
52860
  return "it refreshes incrementally, and a delta never re-reads the rows " + "its window has passed";
@@ -52099,7 +52878,7 @@ function currentTimeAccessInput(source, plan) {
52099
52878
  }
52100
52879
  var READ_ONLY_DIALECTS, MAX_AUTHORIZE_WALK_DEPTH = 200;
52101
52880
  var init_materialization_eligibility = __esm(() => {
52102
- init_config2();
52881
+ init_addressing();
52103
52882
  init_gate_policy();
52104
52883
  init_dialect();
52105
52884
  init_errors2();
@@ -52239,9 +53018,6 @@ var init_rolling_window = __esm(() => {
52239
53018
  function buildSourceName(declaredName) {
52240
53019
  return `${declaredName}__mat`;
52241
53020
  }
52242
- function pairLevelRowColumn(level) {
52243
- return level === 1 ? "__child_row" : `__child_row_${level}`;
52244
- }
52245
53021
  function givenReadTerms(plan) {
52246
53022
  return (plan.readTimeTerms ?? []).filter((t) => t.kind === "given");
52247
53023
  }
@@ -52287,15 +53063,6 @@ ${head}
52287
53063
  ${body}
52288
53064
  }${readTime}`;
52289
53065
  }
52290
- function pairKeyColumns(pair) {
52291
- const names = [pair.join];
52292
- const keys = [pair.parentKey, `${pair.join}__${pair.childKey}`];
52293
- for (const hop of pair.hops ?? []) {
52294
- names.push(hop.join);
52295
- keys.push(`${names.join("__")}__${hop.key}`);
52296
- }
52297
- return keys;
52298
- }
52299
53066
  function pairFlags(pair, levels) {
52300
53067
  const keys = pairKeyColumns(pair).map(identifier);
52301
53068
  const flag = (column, level) => ` ${identifier(column)} is row_number() { partition_by: ${keys.slice(0, Math.min(level, keys.length - 1) + 1).join(", ")} } = 1`;
@@ -52922,98 +53689,14 @@ var init_downstream_upstreams = __esm(() => {
52922
53689
  init_declaration();
52923
53690
  });
52924
53691
 
52925
- // src/service/materialization/plan/pair_reroot.ts
52926
- function pairsOf2(plan) {
52927
- return plan.pairBlocks?.blocks ?? (plan.pair ? [plan.pair] : []);
52928
- }
52929
- function pairRerootJoins(plan) {
52930
- return pairsOf2(plan).map((p) => p.join);
52931
- }
52932
- function pairRerootBase(plan) {
52933
- const pairs = pairsOf2(plan);
52934
- if (pairs.length === 0)
52935
- return;
52936
- const mat = identifier(plan.buildSourceName);
52937
- const firstJoins = new Set(pairs.map((p) => p.join));
52938
- const lane = plan.pairBlocks?.laneColumn;
52939
- const laneTerm = (k) => lane === undefined ? [] : [`${identifier(lane)} = ${k}`];
52940
- const own = plan.columns.filter((c) => c.join === undefined || !firstJoins.has(c.join));
52941
- if (own.length === 0)
52942
- return;
52943
- const parentKey = pairs[0].parentKey;
52944
- const parentWhere = [identifier(pairs[0].parentRowColumn), ...laneTerm(0)];
52945
- const joins = [];
52946
- for (const [k, pair] of pairs.entries()) {
52947
- const join = levelJoin(plan, pair, 1, parentKey, laneTerm(k), mat);
52948
- if (join === undefined)
52949
- return;
52950
- joins.push(...indented(join));
52951
- }
52952
- return `${mat} -> {
52953
- where: ${parentWhere.join(" and ")}
52954
- ` + ` select: ${own.map((c) => identifier(c.column)).join(", ")}
52955
- ` + `} extend {
52956
- primary_key: ${identifier(parentKey)}
52957
- ${joins.join(`
52958
- `)}
52959
- }`;
52960
- }
52961
- function levelJoin(plan, pair, level, parentField, laneTerms, mat) {
52962
- const names = [pair.join, ...(pair.hops ?? []).map((h) => h.join)];
52963
- const keyFields = [pair.childKey, ...(pair.hops ?? []).map((h) => h.key)];
52964
- const keyColumns = pairKeyColumns(pair);
52965
- const depth = names.length;
52966
- const columns = plan.columns.filter((c) => c.join === pair.join && pathOf2(c).length === level);
52967
- const keyField = keyFields[level - 1];
52968
- const keyColumn = keyColumns[level];
52969
- if (!columns.some((c) => c.column === keyColumn))
52970
- return;
52971
- const where = [
52972
- ...level < depth ? [identifier(pairLevelRowColumn(level))] : [],
52973
- `${identifier(keyColumn)} is not null`,
52974
- ...laneTerms
52975
- ];
52976
- const select = [
52977
- `${identifier(PAIR_PARENT_KEY_FIELD)} is ${identifier(keyColumns[level - 1])}`,
52978
- ...columns.map((c) => `${identifier(c.dimension)} is ${identifier(c.column)}`)
52979
- ];
52980
- const inner = level < depth ? levelJoin(plan, pair, level + 1, keyField, laneTerms, mat) : "";
52981
- if (inner === undefined)
52982
- return;
52983
- const name = identifier(names[level - 1]);
52984
- const head = [
52985
- `join_many: ${name} is ${mat} -> {`,
52986
- ` where: ${where.join(" and ")}`,
52987
- ` select: ${select.join(", ")}`,
52988
- "} extend {",
52989
- ` primary_key: ${identifier(keyField)}`
52990
- ];
52991
- const tail = `} on ${name}.${identifier(PAIR_PARENT_KEY_FIELD)} = ${identifier(parentField)}`;
52992
- return [...head, ...indented(inner), tail].join(`
52993
- `);
52994
- }
52995
- function indented(text) {
52996
- return text === "" ? [] : text.split(`
52997
- `).map((line) => " " + line);
52998
- }
52999
- function pathOf2(c) {
53000
- return c.path ?? (c.join !== undefined ? [c.join] : []);
53001
- }
53002
- var PAIR_PARENT_KEY_FIELD = "__pair_parent_key";
53003
- var init_pair_reroot = __esm(() => {
53004
- init_malloy_text();
53005
- init_build_file_generator();
53006
- init_table_plans();
53007
- });
53008
-
53009
53692
  // src/service/materialization/plan/materialize_plan.ts
53010
- import { createHash as createHash9 } from "crypto";
53693
+ import { createHash as createHash10 } from "crypto";
53011
53694
  import { Annotations as Annotations9, isAtomic } from "@malloydata/malloy";
53012
53695
  function materializeTableName(sourceName) {
53013
53696
  if (PLAIN_TABLE_NAME.test(sourceName))
53014
53697
  return sourceName;
53015
53698
  const folded = sourceName.replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
53016
- const hash = createHash9("sha256").update(sourceName).digest("hex");
53699
+ const hash = createHash10("sha256").update(sourceName).digest("hex");
53017
53700
  return `${folded || "source"}_${hash.slice(0, 8)}`;
53018
53701
  }
53019
53702
  function readMaterializeDeclaration(def, contents = {}) {
@@ -53582,7 +54265,10 @@ function planModelMaterialize(contents, declaredHere, givens, probed, zoneFreeRo
53582
54265
  plans.push(planned);
53583
54266
  }
53584
54267
  }
53585
- const unbuilt = new Map(refused.filter((r) => ("refused" in r.outcome) && r.outcome.refused.reason === "free_parameter").flatMap((r) => r.sourceID === undefined ? [] : [[r.sourceID, r.sourceName]]));
54268
+ const unbuilt = new Map(refused.flatMap((r) => {
54269
+ const why = "refused" in r.outcome ? UNBUILT_BY_REASON[r.outcome.refused.reason] : undefined;
54270
+ return r.sourceID === undefined || why === undefined ? [] : [[r.sourceID, { name: r.sourceName, why }]];
54271
+ }));
53586
54272
  const chained = chainExtensionTables(plans, map, ctx.contents, unbuilt);
53587
54273
  refused.push(...chained.refused);
53588
54274
  return { plans: chained.plans, refused };
@@ -53613,7 +54299,7 @@ function planSource(name, def, ctx) {
53613
54299
  const invalid = invalidValuesOf(declaration);
53614
54300
  if (invalid)
53615
54301
  return invalid;
53616
- const free = freeParameterRefusal(def);
54302
+ const free = freeParameterRefusal(name, def) ?? boundInvocationRefusal(name, def, ctx);
53617
54303
  const incoherent = free ? incoherentIncrementalOf(declaration) : undefined;
53618
54304
  if (incoherent)
53619
54305
  return incoherent;
@@ -53755,7 +54441,7 @@ function incoherentIncrementalOf(declaration) {
53755
54441
  malformed: MATERIALIZE_INVALID_CODE
53756
54442
  });
53757
54443
  }
53758
- function freeParameterRefusal(def) {
54444
+ function freeParameterRefusal(name, def) {
53759
54445
  let unbound;
53760
54446
  try {
53761
54447
  unbound = unboundParameterNamesOf(def);
@@ -53764,7 +54450,20 @@ function freeParameterRefusal(def) {
53764
54450
  }
53765
54451
  if (unbound.length === 0)
53766
54452
  return;
53767
- return new Declined(`it has unbound parameter(s) ${unbound.map((p) => `'${p}'`).join(", ")}: ` + "a source with a free parameter is a template instantiated per query, " + "so there is no single relation to store; store a query source over " + "a bound invocation instead, such as " + "`source: s1 is s(x is 1) -> { select: * }`, under #(materialize)", { refused: "free_parameter" });
54453
+ return new Declined(unboundParameterReason(name, unbound), {
54454
+ refused: "free_parameter"
54455
+ });
54456
+ }
54457
+ function boundInvocationRefusal(name, def, ctx) {
54458
+ const at = typeof def.sourceID === "string" ? unkeyableInChain(ctx.map, def.sourceID) : readsBoundArgument(def) ? def.sourceID : undefined;
54459
+ if (at === undefined)
54460
+ return;
54461
+ const model = ctx.map.model();
54462
+ if (ctx.map.chainOf(def).slice(1).some((id) => materializedUnbuiltReason(model, id) !== undefined)) {
54463
+ return;
54464
+ }
54465
+ const via = at === def.sourceID ? "" : `it extends '${ctx.map.node(at)?.name ?? at}', which `;
54466
+ return new Declined(via ? `${via}${boundInvocationReason(name).replace(/^it /, "")}` : boundInvocationReason(name), { refused: "bound_invocation_unkeyable" });
53768
54467
  }
53769
54468
  function inlinedJoinsOf2(def, declaration, map) {
53770
54469
  let inline = [];
@@ -54031,7 +54730,7 @@ function chainExtensionTables(plans, map, contents, unbuilt = new Map) {
54031
54730
  node = map.node(base.sourceID);
54032
54731
  }
54033
54732
  if (unbuiltParent !== undefined) {
54034
- refused.push(extensionRefusal(plan, unbuiltParent, UNBUILT_PARENT));
54733
+ refused.push(extensionRefusal(plan, unbuiltParent.name, unbuiltParent.why));
54035
54734
  continue;
54036
54735
  }
54037
54736
  if (!parent || parent.sourceID === plan.sourceID)
@@ -54077,19 +54776,22 @@ function chainExtensionTables(plans, map, contents, unbuilt = new Map) {
54077
54776
  const ids = new Set(refused.map((r) => r.sourceID));
54078
54777
  return { plans: plans.filter((p) => !ids.has(p.sourceID)), refused };
54079
54778
  }
54080
- function materializedWithFreeParameter(modelDef, sourceID) {
54779
+ function materializedUnbuiltReason(modelDef, sourceID) {
54081
54780
  const map = SourceMap.of(modelDef);
54082
54781
  const def = map.node(sourceID)?.def;
54083
54782
  if (!def)
54084
- return false;
54783
+ return;
54085
54784
  const contents = modelDef.contents ?? {};
54086
54785
  try {
54087
- if (readMaterializeDeclaration(def, contents) === undefined)
54088
- return false;
54786
+ if (readMaterializeDeclaration(def, contents) === undefined) {
54787
+ return;
54788
+ }
54089
54789
  } catch {
54090
- return false;
54790
+ return;
54091
54791
  }
54092
- return freeParameterRefusal(def) !== undefined;
54792
+ if (freeParameterRefusal("", def) !== undefined)
54793
+ return UNBUILT_PARENT;
54794
+ return unkeyableInChain(map, sourceID) !== undefined ? UNKEYABLE_PARENT : undefined;
54093
54795
  }
54094
54796
  function storedParentOf(plan) {
54095
54797
  const pairParent = plan.pair !== undefined || plan.pairBlocks !== undefined;
@@ -54428,7 +55130,7 @@ function extensionFullRefreshFinding(plan, model) {
54428
55130
  model
54429
55131
  };
54430
55132
  }
54431
- var CARRIED_GROUPS, FRESHNESS_PROPERTIES, PLAIN_PROPERTY, PLAIN_TABLE_NAME, PLANNED_KEYS, MATERIALIZE_PAIR_FULL_REFRESH_CODE = "materialize-pair-full-refresh", MATERIALIZE_EXTENSION_FULL_REFRESH_CODE = "materialize-extension-full-refresh", MATERIALIZE_EXTENSION_KEEPS_MOVED_ROWS_CODE = "materialize-extension-keeps-moved-rows", GENERATOR_KEYS, MATERIALIZE_UNKNOWN_KEY_CODE = "materialize-unknown-key", WATERMARK_LIST_REASON, MATERIALIZE_RETIRED_KEY_CODE = "materialize-retired-key", MATERIALIZE_UNPARSEABLE_CODE = "materialize-unparseable", ATOMIC_TYPES, NULLABLE_TYPES, PAIR_WATERMARK_TYPES, INCREMENTAL_KEYS2, UNBUILT_PARENT = "whose table is not built because it has an unbound parameter";
55133
+ var CARRIED_GROUPS, FRESHNESS_PROPERTIES, PLAIN_PROPERTY, PLAIN_TABLE_NAME, PLANNED_KEYS, MATERIALIZE_PAIR_FULL_REFRESH_CODE = "materialize-pair-full-refresh", MATERIALIZE_EXTENSION_FULL_REFRESH_CODE = "materialize-extension-full-refresh", MATERIALIZE_EXTENSION_KEEPS_MOVED_ROWS_CODE = "materialize-extension-keeps-moved-rows", GENERATOR_KEYS, MATERIALIZE_UNKNOWN_KEY_CODE = "materialize-unknown-key", WATERMARK_LIST_REASON, MATERIALIZE_RETIRED_KEY_CODE = "materialize-retired-key", MATERIALIZE_UNPARSEABLE_CODE = "materialize-unparseable", ATOMIC_TYPES, NULLABLE_TYPES, PAIR_WATERMARK_TYPES, INCREMENTAL_KEYS2, UNBUILT_PARENT = "whose table is not built because it has an unbound parameter", UNKEYABLE_PARENT = "whose table is not built because it extends a bound invocation that cannot be keyed", UNBUILT_BY_REASON;
54432
55134
  var init_materialize_plan = __esm(() => {
54433
55135
  init_annotation_reader();
54434
55136
  init_build_file_generator();
@@ -54443,7 +55145,6 @@ var init_materialize_plan = __esm(() => {
54443
55145
  init_source_map();
54444
55146
  init_table_plans();
54445
55147
  init_downstream_upstreams();
54446
- init_pair_reroot();
54447
55148
  init_persist_dynamic_terms();
54448
55149
  init_probe_compiler();
54449
55150
  init_materialize_read_time();
@@ -54488,6 +55189,10 @@ var init_materialize_plan = __esm(() => {
54488
55189
  "string"
54489
55190
  ]);
54490
55191
  INCREMENTAL_KEYS2 = ["refresh", "watermark", "merge_key", "lookback"];
55192
+ UNBUILT_BY_REASON = {
55193
+ free_parameter: UNBUILT_PARENT,
55194
+ bound_invocation_unkeyable: UNKEYABLE_PARENT
55195
+ };
54491
55196
  });
54492
55197
 
54493
55198
  // src/service/materialization/plan/eligibility_collect.ts
@@ -54732,7 +55437,7 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
54732
55437
  try {
54733
55438
  sourceEntityId = planAddressOf(compiled, sourceID);
54734
55439
  } catch (idErr) {
54735
- logger.warn("Dropping a refused database source: its content address could not be computed", {
55440
+ reportPlanDiagnostic("warn", "refused_source_unaddressable", "Dropping a refused database source: its content address could not be computed", {
54736
55441
  sourceID,
54737
55442
  sourceName: source.name,
54738
55443
  reason: errorCodeOf(err),
@@ -54748,7 +55453,7 @@ function collectDatabaseSourceEligibility(compiled, verdicts = planVerdicts(comp
54748
55453
  try {
54749
55454
  sourceEntityId = planAddressOf(compiled, sourceID);
54750
55455
  } catch (err) {
54751
- logger.warn("Dropping an eligible database source: its content address could not be computed", { sourceID, sourceName: source.name, code: errorCodeOf(err) });
55456
+ reportPlanDiagnostic("warn", "eligible_source_unaddressable", "Dropping an eligible database source: its content address could not be computed", { sourceID, sourceName: source.name, code: errorCodeOf(err) });
54752
55457
  continue;
54753
55458
  }
54754
55459
  if (!(sourceEntityId in refused)) {
@@ -54781,6 +55486,7 @@ function eligibilityOf(table, annotationFields, ctx) {
54781
55486
  if (!rollup) {
54782
55487
  const err = refusalOf(() => {
54783
55488
  assertPlacementNamed(source);
55489
+ assertNoUnboundParameter(source);
54784
55490
  if (declaresStorage) {
54785
55491
  assertTierEligible(source, true, ctx.gateInputs, annotationFields);
54786
55492
  } else if (ctx.database !== undefined) {
@@ -54905,7 +55611,7 @@ var init_eligibility_collect = __esm(() => {
54905
55611
  init_errors2();
54906
55612
  init_storage_table_path();
54907
55613
  init_table_name();
54908
- init_logger();
55614
+ init_plan_diagnostics();
54909
55615
  init_utils();
54910
55616
  init_addressing();
54911
55617
  init_materialization_eligibility();
@@ -55226,193 +55932,6 @@ var init_annotation_near_miss = __esm(() => {
55226
55932
  ]);
55227
55933
  });
55228
55934
 
55229
- // src/materialization_metrics.ts
55230
- function routeLegOf(kind) {
55231
- return kind === "served" ? "materialized" : kind;
55232
- }
55233
- function recordScheduledFire(outcome) {
55234
- scheduledFireCounter().add(1, { outcome });
55235
- }
55236
- function recordMaterializationRun(mode, outcome, durationMs) {
55237
- runCounter().add(1, { mode, outcome });
55238
- runDuration().record(durationMs, { mode, outcome });
55239
- }
55240
- function recordBuildOutcome(labels) {
55241
- buildCounter().add(1, {
55242
- kind: labels.kind,
55243
- tier: labels.tier,
55244
- outcome: labels.outcome,
55245
- failure_class: labels.outcome === "failed" ? labels.failureClass : "none"
55246
- });
55247
- }
55248
- function recordBuildDuration(durationMs, labels) {
55249
- buildDuration().record(durationMs, {
55250
- kind: labels.kind,
55251
- tier: labels.tier,
55252
- method: labels.method
55253
- });
55254
- }
55255
- function recordBuildReadBytes(bytes, tier) {
55256
- if (typeof bytes !== "number" || !(bytes > 0))
55257
- return;
55258
- buildReadBytes().record(bytes, { tier });
55259
- }
55260
- function recordAnnotationFindings(warnings) {
55261
- for (const { code, severity } of warnings) {
55262
- if (!code)
55263
- continue;
55264
- annotationFindingsCounter().add(1, {
55265
- code,
55266
- outcome: severity === "error" ? "invalid" : "not_built"
55267
- });
55268
- }
55269
- }
55270
- function recordIncrementalStep(step, reason) {
55271
- incrementalStepCounter().add(1, reason ? { step, reason } : { step });
55272
- }
55273
- function recordBuildPlanComputeDuration(durationMs, computedIn) {
55274
- buildPlanComputeDuration().record(durationMs, { computed_in: computedIn });
55275
- }
55276
- function recordBuildPlanComputeFailed() {
55277
- buildPlanComputeFailedCounter().add(1);
55278
- }
55279
- function recordAutoLoadOutcome(outcome) {
55280
- autoLoadCounter().add(1, { outcome });
55281
- }
55282
- function recordConnectionDigestSkipped() {
55283
- connectionDigestSkipCounter().add(1);
55284
- }
55285
- function recordDuplicateTargetSkipped() {
55286
- duplicateTargetSkipCounter().add(1);
55287
- }
55288
- function recordSharedAddressInstructions() {
55289
- sharedAddressInstructionCounter().add(1);
55290
- }
55291
- function recordTableCollision() {
55292
- tableCollisionCounter().add(1);
55293
- }
55294
- function recordManifestBind(outcome) {
55295
- servedCopyBindCounter().add(1, {
55296
- scope: "manifest",
55297
- outcome,
55298
- reason: "none"
55299
- });
55300
- }
55301
- function recordSourceBound() {
55302
- servedCopyBindCounter().add(1, {
55303
- scope: "source",
55304
- outcome: "bound",
55305
- reason: "none"
55306
- });
55307
- }
55308
- function recordSourceDeclined(reason) {
55309
- servedCopyBindCounter().add(1, {
55310
- scope: "source",
55311
- outcome: "declined",
55312
- reason
55313
- });
55314
- }
55315
- function recordServedCopyOutcome(outcome, reason) {
55316
- servedCopyBindCounter().add(1, { scope: "source", outcome, reason });
55317
- }
55318
- function recordManifestBindDegraded() {
55319
- manifestBindDegradedCounter().add(1);
55320
- }
55321
- function recordDropTables(outcome, tier, occasion) {
55322
- dropTablesCounter().add(1, { outcome, tier, occasion });
55323
- }
55324
- function recordKeyCheck(kind, outcome) {
55325
- keyCheckCounter().add(1, { kind, outcome });
55326
- }
55327
- function recordIncompatibleDetected(trigger, code) {
55328
- incompatibleDetectedCounter().add(1, { trigger, code });
55329
- }
55330
- function recordQueryWalk(site) {
55331
- queryWalkCounter().add(1, { site });
55332
- }
55333
- function recordContractCapture(tier, outcome) {
55334
- contractCaptureCounter().add(1, { tier, outcome });
55335
- }
55336
- function recordQueryRouteDuration(durationMs, leg) {
55337
- queryRouteDuration().record(durationMs, { leg });
55338
- }
55339
- function recordStorageTableRetained() {
55340
- storageTableRetainedCounter().add(1);
55341
- }
55342
- function recordAttributionSkipped(reason) {
55343
- attributionSkippedCounter().add(1, { reason });
55344
- }
55345
- function recordEligibilityRefused(reason) {
55346
- eligibilityRefusedCounter().add(1, { reason });
55347
- }
55348
- function recordStoredTypeFallback(kind) {
55349
- serveShapeTypeFallbackCounter().add(1, { kind });
55350
- }
55351
- function recordStoredColumnTypeMismatch(stage, declared) {
55352
- storedColumnTypeMismatchCounter().add(1, { stage, declared });
55353
- }
55354
- function recordQueryRoute(leg, outcome, reason) {
55355
- queryRouteCounter().add(1, { leg, outcome, reason });
55356
- }
55357
- function recordChainedStorageBuild(outcome) {
55358
- chainedStorageBuildCounter().add(1, { outcome });
55359
- }
55360
- function recordUpstreamReadUnchecked(build) {
55361
- uncheckedUpstreamReadCounter().add(1, {
55362
- reason: "reference_types_unrecorded",
55363
- build,
55364
- outcome: "read_unchecked"
55365
- });
55366
- }
55367
- 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;
55368
- var init_materialization_metrics = __esm(() => {
55369
- init_vocabulary();
55370
- init_telemetry();
55371
- BUILD_DURATION_BUCKETS_MS = [
55372
- 100,
55373
- 500,
55374
- 1000,
55375
- 5000,
55376
- 15000,
55377
- 60000,
55378
- 300000,
55379
- 900000,
55380
- 3600000
55381
- ];
55382
- BUILD_READ_BYTES_BUCKETS = [1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000];
55383
- runCounter = lazyCounter("publisher_materialization_runs_total", "Materialization builds completed. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
55384
- runDuration = lazyHistogram("publisher_materialization_run_duration_ms", "Wall-clock duration of a materialization build. Labels: mode ('auto'|'orchestrated'), outcome ('success'|'partial'|'failed'|'cancelled').");
55385
- buildCounter = lazyCounter("publisher_materialization_build_total", "Source builds, one per source per run at its finish or failure. Labels: " + "kind ('materialize'|'persist'|'rollup'|'view'|'query'|'pair'), tier " + "('database'|'storage'), outcome ('built'|'reused'|'refused'|'failed'|" + "'cancelled'), failure_class ('none' unless outcome is 'failed'; then " + "'deterministic'|'transient'|'unclassified'|'billed_read_lost'). " + "'billed_read_lost' is the expensive one: the warehouse read ran and was " + "charged and its rows were not captured, so a retry pays for it again.");
55386
- buildDuration = lazyHistogram("publisher_materialization_build_duration_ms", "Wall-clock duration of one source's build, for builds that ran (built or " + "failed; a skipped incremental refresh did no work and is not timed). " + "Labels: kind, tier, method ('full'|'delta').", { buckets: BUILD_DURATION_BUCKETS_MS });
55387
- buildReadBytes = lazyHistogram("publisher_materialization_build_read_bytes", "Warehouse bytes scanned by one source's build read, when the warehouse " + "reported a count; absent otherwise, never zero. Label: tier.", { unit: "By", buckets: BUILD_READ_BYTES_BUCKETS });
55388
- annotationFindingsCounter = lazyCounter("publisher_annotation_findings_total", "Coded findings on authored annotations (the #@ route, and the near-miss and malformed-route scan over every route), counted once each time a package is loaded and accepted for serving (boot, add, publish, reload; a refused publish and a gate re-run count nothing). Labels: code (e.g. 'persist-unknown-key', 'persist-unparseable', 'persist-not-built'), outcome ('invalid' for an error-severity finding, which fails the load, 'not_built' for a warning: a valid annotation not built here, and also the warn-level 'annotation-near-miss' and 'persist-incremental-no-merge-key' advisories, which build).");
55389
- incrementalStepCounter = lazyCounter("publisher_materialization_incremental_step_total", 'Refreshes of a source declared refresh="incremental". Labels: step ' + "('delta'|'seed'|'skip'), and for seed/skip a bounded reason code " + "(IncrementalStepReasonCode). A 'seed' is a full rebuild the delta path " + "declined, so a rising seed rate means the feature is not engaging — and " + "the reason label says why without a log dive.");
55390
- buildPlanComputeDuration = lazyHistogram("publisher_materialization_build_plan_compute_duration_ms", "Wall-clock duration of compiling a package's build plan (Package.buildPlan).");
55391
- buildPlanComputeFailedCounter = lazyCounter("publisher_materialization_build_plan_compute_failed_total", "Package loads whose build plan failed to compute. The ROOT-CAUSE signal for " + "served_copy_bind{reason='build_plan_unavailable'}, which fires only " + "per declined entry per load -- a package that loads once and is never " + "reloaded ticks that counter once and then sits with its database tier " + "off and a flat total, indistinguishable from healthy.");
55392
- autoLoadCounter = lazyCounter("publisher_materialization_auto_load_total", "Auto-run manifest auto-load attempts. Label: outcome ('success'|'failure').");
55393
- connectionDigestSkipCounter = lazyCounter("publisher_materialization_connection_digest_skipped_total", "Connection digests skipped during build-plan compile because the connection did not resolve.");
55394
- servedCopyBindCounter = lazyCounter("publisher_served_copy_bind_total", "Serving's binds. Labels: scope ('manifest': one manifest bind, from REST, " + "auto-load or a rebind; 'source': one source deciding whether it " + "serves), outcome ('success'|'failure'|'timeout' for a manifest; " + "'bound'|'partial'|'declined' for a source: 'partial' is a source that " + "serves with a join read as written or left out), reason ('none' when " + "bound, else why: 'build_plan_unavailable' when the package's build " + "plan failed to compute, so every database source reverts to live; " + "'refused'; 'missing_table'; or the served copy's reason, as its " + "package warning, 'inline_join_kept' and 'cross_connection_join' being " + "the partial ones). Units differ by who counts: 'bound' and the bind's " + "declines count once per stored table per bind; the served copy counts " + "once per source per model per snapshot it compiles, 'declined' beating " + "'partial'. So a source two models read is counted by each, and the " + "outcomes do not sum to a number of sources. An extension table that " + "falls back to its own blocks ('compile_failed', 'reroot_not_compiled') " + "may still serve, and is counted 'declined'.");
55395
- manifestBindDegradedCounter = lazyCounter("publisher_materialization_manifest_bind_degraded_total", "Manifest entries bound with an UNQUOTED table path because their connection " + "could not be resolved (serve-side bind) or is absent from the build " + "(build-side seed). A misconfiguration that breaks the source on a " + "case-folding engine (Snowflake); alertable.");
55396
- duplicateTargetSkipCounter = lazyCounter("publisher_materialization_duplicate_target_skipped_total", "Sources skipped because the physical table they name was already built in " + "this run. Ordinary for a package that extends a persisted source; a " + "rising count against a package with no extension means the plan is " + "enumerating one table under more names than expected.");
55397
- sharedAddressInstructionCounter = lazyCounter("publisher_materialization_shared_address_instructions_total", "Content addresses that arrived with more than one instruction naming a " + "DIFFERENT physical table. The host minted a table per source where " + "several sources share one artifact. With a sourceID on each instruction " + "every table is built and only one is recorded, so the rest are orphaned; " + "without one the last instruction wins and the earlier names are never " + "built. Wasteful, not wrong — the table's CONTENT is the same either way.");
55398
- tableCollisionCounter = lazyCounter("publisher_materialization_table_collision_total", "Two definitions with DIFFERENT content addresses materializing into ONE " + "physical table. Each build overwrites the other's rows while both " + "addresses resolve to the table at serve time, so a query is answered " + "from another source's data. A wrong answer, not wasted work — page on " + "this one. Counted, then refused before any write.");
55399
- dropTablesCounter = lazyCounter("publisher_materialization_drop_tables_total", "Physical tables dropped. Labels: outcome ('success'|'failure'), tier " + "('database'|'storage'), occasion ('delete' when a caller deleted a " + "storage destination's table, since a run's delete is record-only; " + "'reclaim' when Publisher dropped it on its own: " + "a failed run's tables, a table a readable name replaced, an archived " + "or deleted version's tables; 'caller' when a caller dropped a " + "package's materialized database table through " + "DELETE .../materializedTables/{tableName}).");
55400
- scheduledFireCounter = lazyCounter("publisher_materialization_scheduled_fires_total", "Standalone-scheduler attempts to fire a package's materialization.schedule. " + "Label: outcome ('fired'|'conflict'|'error').");
55401
- queryRouteCounter = lazyCounter("publisher_query_route_total", "The router's decision on each leg it considered for a query, counted once " + "the query is answered. Labels: leg ('view'|'query'|'rollup'|'materialized'|'live'; " + "'query' is a persisted named query), " + "outcome ('used'|'skipped'|'fallback': a chosen leg whose run failed and " + "was answered live), reason ('NONE' when used, else the path report's " + "SkipReason; 'READ_FAILED' with 'fallback'). A leg that does not apply to " + "the query is not counted; 'live' is counted 'used' when it answered a " + "query the router counted a leg for.");
55402
- queryRouteDuration = lazyHistogram("publisher_query_route_duration_ms", "Wall-clock time the router spent choosing how to answer a query, for a " + "query with at least one serving leg that applied: the row-level veto " + "and each leg's compile, up to the leg chosen. Not the query's run. " + "Label: leg ('view'|'query'|'rollup'|'materialized'|'live'), the one that " + "answered.");
55403
- 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.");
55404
- 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).");
55405
- 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.");
55406
- 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').");
55407
- 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.");
55408
- 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.");
55409
- eligibilityRefusedCounter = lazyCounter("publisher_materialization_eligibility_refused_total", "Valid materialization declarations that are not built (`#@ persist`, " + "`#(materialize)`, a persisted view or query, a rollup), once per " + "declaration per plan derivation, and the refusals only a run finds. " + "Label: reason, the build plan refusal's `RefusedSource.reason` " + "(api-doc.yaml lists the values and which are retained and no " + "longer produced).");
55410
- 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').");
55411
- 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).");
55412
- 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).");
55413
- 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.");
55414
- });
55415
-
55416
55935
  // src/service/materialization/domain/build_cancelled.ts
55417
55936
  var BuildCancelledError;
55418
55937
  var init_build_cancelled = __esm(() => {
@@ -55963,7 +56482,7 @@ async function tryCompileMaterializeCompanion(args) {
55963
56482
  refused.push(...planned.refused);
55964
56483
  plannedIDs = planned.plans.map((p) => p.sourceID);
55965
56484
  const foreign = await crossFileParents(planned.plans, args, modelFile).catch((error) => {
55966
- logger.warn("A model's extension tables could not be chained on parents in other files; they are refused", {
56485
+ reportPlanDiagnostic("warn", "cross_file_chain_failed", "A model's extension tables could not be chained on parents in other files; they are refused", {
55967
56486
  modelPath: args.modelPath,
55968
56487
  code: errorCodeOf(error)
55969
56488
  });
@@ -56051,7 +56570,7 @@ async function unchainStoredChainsNotCompiling(round, compile, args, refused, fo
56051
56570
  const plan = planOf(round.plans, sourceID);
56052
56571
  if (!plan)
56053
56572
  continue;
56054
- logger.warn("A storage= extension table does not compile over its parent's stored table alone; it is refused", { modelPath: args.modelPath, sourceName: plan.sourceName });
56573
+ reportPlanDiagnostic("warn", "storage_extension_unchained", "A storage= extension table does not compile over its parent's stored table alone; it is refused", { modelPath: args.modelPath, sourceName: plan.sourceName });
56055
56574
  refuseUnchained(refused, plan, `whose stored table its build does not compile over in its ` + `destination (${why})`);
56056
56575
  }
56057
56576
  return compile(round.plans.filter((p) => !unstored.has(p.sourceID)));
@@ -56698,7 +57217,7 @@ function nextRound(error, plans, copies, ctx) {
56698
57217
  const omitted = plan?.buildsOver && (omissionRounds.get(plan.sourceID) ?? 0) < MAX_OMISSION_ROUNDS ? copyOmissions(error, copies.get(plan.sourceID), plan) : [];
56699
57218
  if (plan?.buildsOver && omitted.length > 0) {
56700
57219
  omissionRounds.set(plan.sourceID, (omissionRounds.get(plan.sourceID) ?? 0) + 1);
56701
- logger.warn("A chained #(materialize) build copy leaves out declarations that do not compile over the parent's build source", {
57220
+ reportPlanDiagnostic("warn", "chained_copy_omits_declarations", "A chained #(materialize) build copy leaves out declarations that do not compile over the parent's build source", {
56702
57221
  modelPath,
56703
57222
  sourceName: plan.sourceName,
56704
57223
  omitted: omitted.map((o) => splitSourceID(o.sourceID)?.name)
@@ -56713,12 +57232,12 @@ function nextRound(error, plans, copies, ctx) {
56713
57232
  } : p);
56714
57233
  }
56715
57234
  if (plan?.buildsOver) {
56716
- logger.warn("An extension table of a #(materialize) model did not compile over its parent's build source; it is refused", { modelPath, sourceName: plan.sourceName, code: errorCodeOf(error) });
57235
+ reportPlanDiagnostic("warn", "extension_not_over_parent", "An extension table of a #(materialize) model did not compile over its parent's build source; it is refused", { modelPath, sourceName: plan.sourceName, code: errorCodeOf(error) });
56717
57236
  ctx.refuse(unchainedRefusal(plan, `whose table its build does not compile over: ${firstProblem(error)}`));
56718
57237
  return plans.filter((p) => p !== plan);
56719
57238
  }
56720
57239
  if (plan) {
56721
- logger.error("A #(materialize) source's generated build did not compile; it is not built, and the model's other sources are", { modelPath, sourceName: plan.sourceName, code: errorCodeOf(error) });
57240
+ reportPlanDiagnostic("error", "generated_build_failed", "A #(materialize) source's generated build did not compile; it is not built, and the model's other sources are", { modelPath, sourceName: plan.sourceName, code: errorCodeOf(error) });
56722
57241
  ctx.refuse({
56723
57242
  sourceName: plan.sourceName,
56724
57243
  sourceID: plan.sourceID,
@@ -56733,7 +57252,7 @@ function nextRound(error, plans, copies, ctx) {
56733
57252
  return plans.filter((p) => p !== plan);
56734
57253
  }
56735
57254
  if (plans.some((p) => p.buildsOver)) {
56736
- logger.warn("Extension tables of a #(materialize) model did not compile over their parents' build sources; they are refused", { modelPath, code: errorCodeOf(error) });
57255
+ reportPlanDiagnostic("warn", "extensions_not_over_parents", "Extension tables of a #(materialize) model did not compile over their parents' build sources; they are refused", { modelPath, code: errorCodeOf(error) });
56737
57256
  for (const p of plans.filter((q) => q.buildsOver)) {
56738
57257
  ctx.refuse(unchainedRefusal(p, `and the model's builds over their parents' tables do not ` + `compile: ${firstProblem(error)}`));
56739
57258
  }
@@ -56775,7 +57294,7 @@ async function compileCrossFileCompanion(args, file, stack, companions) {
56775
57294
  crossFileCompanions: companions
56776
57295
  });
56777
57296
  if (failure)
56778
- logCompanionFailure(failure, modelPath);
57297
+ reportCompanionFailure(failure, modelPath);
56779
57298
  return {
56780
57299
  ...generated ? { generated } : {},
56781
57300
  ...failure ? { failed: true } : {},
@@ -56795,7 +57314,7 @@ async function crossFileParents(plans, args, modelFile) {
56795
57314
  let found = companions.get(file);
56796
57315
  if (!found) {
56797
57316
  found = compileCrossFileCompanion(args, file, stack, companions).catch((error) => {
56798
- logger.warn("An extension table's parent in another file could not be planned here; the extension is refused", {
57317
+ reportPlanDiagnostic("warn", "cross_file_parent_unplanned", "An extension table's parent in another file could not be planned here; the extension is refused", {
56799
57318
  modelPath: args.modelPath,
56800
57319
  parentFile: path13.relative(args.packagePath, file),
56801
57320
  code: errorCodeOf(error)
@@ -56919,9 +57438,10 @@ function chainOver(plan, companion, entryID, below, via) {
56919
57438
  };
56920
57439
  }
56921
57440
  if (!parent || !generated) {
56922
- if (materializedWithFreeParameter(companion.modelDef, candidate.sourceID)) {
57441
+ const unbuiltWhy = materializedUnbuiltReason(companion.modelDef, candidate.sourceID);
57442
+ if (unbuiltWhy !== undefined) {
56923
57443
  return {
56924
- refuse: extensionRefusal(plan, splitSourceID(candidate.sourceID)?.name, UNBUILT_PARENT)
57444
+ refuse: extensionRefusal(plan, splitSourceID(candidate.sourceID)?.name, unbuiltWhy)
56925
57445
  };
56926
57446
  }
56927
57447
  continue;
@@ -57078,7 +57598,7 @@ function crossFileCopy(plan, parent, ctx, liftAccess) {
57078
57598
  liftAccess
57079
57599
  });
57080
57600
  if ("reason" in made) {
57081
- logger.warn("An extension table's build copy could not read its parent in another file re-rooted; it is refused", { sourceName: plan.sourceName, reason: made.reason });
57601
+ reportPlanDiagnostic("warn", "cross_file_parent_not_rerooted", "An extension table's build copy could not read its parent in another file re-rooted; it is refused", { sourceName: plan.sourceName, reason: made.reason });
57082
57602
  return;
57083
57603
  }
57084
57604
  const urlOf = (file) => pathToFileURL10(copyOf.get(pathToFileURL10(file).href)).href;
@@ -57133,15 +57653,16 @@ async function withCrossFileColumnsKept(round, compile, args, refused, foreign)
57133
57653
  if (differ.length === 0)
57134
57654
  return round;
57135
57655
  for (const plan of differ) {
57136
- logger.warn("An extension table over its parent in another file does not keep its columns over the parent's build source; it is refused", { modelPath: args.modelPath, sourceName: plan.sourceName });
57656
+ reportPlanDiagnostic("warn", "cross_file_columns_differ", "An extension table over its parent in another file does not keep its columns over the parent's build source; it is refused", { modelPath: args.modelPath, sourceName: plan.sourceName });
57137
57657
  refuseUnchained(refused, plan, `declared in another file, whose table its build would not store ` + `the same columns, with the same types, over`);
57138
57658
  }
57139
57659
  const ids = new Set(differ.map((p) => p.sourceID));
57140
57660
  return compile(round.plans.filter((p) => !ids.has(p.sourceID)));
57141
57661
  }
57142
- function logCompanionFailure(failure, modelPath) {
57143
- logger.error(COMPANION_FAILURE_TEXT[failure.kind], {
57662
+ function reportCompanionFailure(failure, modelPath) {
57663
+ reportPlanDiagnostic("error", "companion_failed", COMPANION_FAILURE_TEXT[failure.kind], {
57144
57664
  modelPath,
57665
+ kind: failure.kind,
57145
57666
  code: errorCodeOf(failure.error)
57146
57667
  });
57147
57668
  }
@@ -57149,7 +57670,7 @@ var STORED_TYPES, CompanionCompileError, MAX_OMISSION_ROUNDS = 4, NO_CROSS_FILE_
57149
57670
  var init_materialize_compile = __esm(() => {
57150
57671
  init_error_code();
57151
57672
  init_malloy_text();
57152
- init_logger();
57673
+ init_plan_diagnostics();
57153
57674
  init_dialect();
57154
57675
  init_key_check();
57155
57676
  init_materialize_build_copy();
@@ -57196,7 +57717,6 @@ var init_materialize_compile = __esm(() => {
57196
57717
  persisted_view: "Failed to plan or compile the generated persisted-view companion",
57197
57718
  rollup: "Failed to plan or compile the generated #(rollup) companion",
57198
57719
  rollup_blanking: "A #(rollup) companion was not built: a `#@` line of the author's files could not be left out of it",
57199
- v1_build: "The v1 build copy of a model could not be read or did not compile; its #@ persist sources are left out of the build plan",
57200
57720
  persist: "Failed to plan a model's #@ persist sources; the ones it declares are left out of the build plan"
57201
57721
  };
57202
57722
  });
@@ -57368,16 +57888,16 @@ async function compileStorageOverStored(args) {
57368
57888
  const upstreams = reached.filter((u) => !parents.has(u.sourceID));
57369
57889
  if (upstreams.length === 0)
57370
57890
  continue;
57371
- const pair = upstreams.find((u) => overPairTable(u.sourceID, materialized));
57372
- out.set(c.plan.buildSourceID, pair ? {
57373
- refused: `its upstream '${pair.name}' is a pair table, one row ` + `per pair of an inlined join_many, which a view or ` + `query is not yet built over in its destination`
57891
+ const overPair = upstreams.find((u) => overPairParent(u.sourceID, materialized));
57892
+ out.set(c.plan.buildSourceID, overPair ? {
57893
+ refused: `its upstream '${overPair.name}' is a pair table, one row ` + `per pair of an inlined join_many, which a view or ` + `query is not yet built over in its destination`
57374
57894
  } : await compileOne({ ...args, map, destination, upstreams, ...c }));
57375
57895
  }
57376
57896
  return out;
57377
57897
  }
57378
- function overPairTable(sourceID, materialized) {
57379
- const seen = new Set;
57380
- for (let id = sourceID;id !== undefined && !seen.has(id); id = materialized[id]?.buildsOver?.sourceID) {
57898
+ function overPairParent(sourceID, materialized) {
57899
+ const seen = new Set([sourceID]);
57900
+ for (let id = materialized[sourceID]?.buildsOver?.sourceID;id !== undefined && !seen.has(id); id = materialized[id]?.buildsOver?.sourceID) {
57381
57901
  seen.add(id);
57382
57902
  const plan = materialized[id];
57383
57903
  if (plan?.pair || plan?.pairBlocks)
@@ -57420,10 +57940,13 @@ async function compileOverStandIns(args, downstream, view) {
57420
57940
  if (columns === undefined) {
57421
57941
  return why(`its upstream '${u.name}' is not a query whose output columns a stored table holds`);
57422
57942
  }
57943
+ const plan = args.materializePlans?.[u.sourceID];
57944
+ const leafKeys = plan && (plan.pair || plan.pairBlocks) ? pairLeafContractKeys(plan) : [];
57423
57945
  standIns.push({
57424
57946
  sourceID: u.sourceID,
57425
57947
  handle: `publisher_stand_in_${i}`,
57426
- columns
57948
+ columns,
57949
+ ...leafKeys.length > 0 ? { pairLeafKeys: leafKeys } : {}
57427
57950
  });
57428
57951
  }
57429
57952
  const request = {
@@ -57521,6 +58044,7 @@ function storedTypeOf(type, numberType) {
57521
58044
  }
57522
58045
  }
57523
58046
  var init_storage_over_stored = __esm(() => {
58047
+ init_table_plans();
57524
58048
  init_generated_files();
57525
58049
  init_read_text();
57526
58050
  init_source_map();
@@ -57555,7 +58079,8 @@ function computesAcrossGroups(stage) {
57555
58079
  });
57556
58080
  }
57557
58081
  async function persistedViewRefusalReason(plan, modelDef, materializer) {
57558
- const node = SourceMap.of(modelDef).node(plan.sourceID);
58082
+ const map = SourceMap.of(modelDef);
58083
+ const node = map.node(plan.sourceID);
57559
58084
  const localName = node?.name;
57560
58085
  if (!node || !localName) {
57561
58086
  return {
@@ -57563,6 +58088,9 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
57563
58088
  refusal: "run_target_unsupported"
57564
58089
  };
57565
58090
  }
58091
+ const unkeyable = unkeyableRefusal2(map, plan.sourceID, localName);
58092
+ if (unkeyable)
58093
+ return unkeyable;
57566
58094
  const def = node.def;
57567
58095
  let stages;
57568
58096
  try {
@@ -57611,7 +58139,8 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
57611
58139
  refusal: gateRefusalReason(throughDerivation.map((g) => g.route))
57612
58140
  };
57613
58141
  }
57614
- const gatedWhy = "its source carries a row-level gate (#(access_filter) or #(authorize))";
58142
+ const gatedBy = (routes) => `its source carries an ${gateKindsName(routes)} gate`;
58143
+ const gatedWhy = gatedBy(gates.map((g) => g.route));
57615
58144
  if (stages.length !== 1 || last.type !== "reduce") {
57616
58145
  return {
57617
58146
  reason: `${gatedWhy}, which a multi-stage or non-grouping view's stored result cannot keep`,
@@ -57632,6 +58161,7 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
57632
58161
  }
57633
58162
  const grouped = groupedNames(last);
57634
58163
  for (const gate of gates) {
58164
+ const refusal = gateRefusalReason([gate.route]);
57635
58165
  const filterText = gateFilterText(gate.exprs);
57636
58166
  let paths;
57637
58167
  try {
@@ -57640,8 +58170,8 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
57640
58170
  paths = (condition.refSummary?.fieldUsage ?? []).map((u) => u.path);
57641
58171
  } catch {
57642
58172
  return {
57643
- reason: `${gatedWhy} that could not be read against the view`,
57644
- refusal: gateRefusalReason([gate.route])
58173
+ reason: `${gatedBy([gate.route])} that could not be read against the view`,
58174
+ refusal
57645
58175
  };
57646
58176
  }
57647
58177
  for (const p of paths) {
@@ -57649,8 +58179,8 @@ async function persistedViewRefusalReason(plan, modelDef, materializer) {
57649
58179
  continue;
57650
58180
  if (p.length !== 1 || typeof p[0] !== "string" || !grouped.has(p[0])) {
57651
58181
  return {
57652
- reason: `the access filter of its source reads \`${p.join(".")}\`, which the view does not group by, so its stored rows could not be filtered per caller`,
57653
- refusal: gateRefusalReason([gate.route])
58182
+ reason: `the ${gateKindName(refusal)} gate of its source reads \`${p.join(".")}\`, which the view does not group by, so its stored rows could not be filtered per caller`,
58183
+ refusal
57654
58184
  };
57655
58185
  }
57656
58186
  }
@@ -57669,6 +58199,16 @@ function joinedGateRoutes(struct, modelDef, seen = new Set) {
57669
58199
  }
57670
58200
  return routes;
57671
58201
  }
58202
+ function unkeyableRefusal2(map, sourceID, sourceName) {
58203
+ const at = unkeyableInChain(map, sourceID);
58204
+ if (at === undefined)
58205
+ return;
58206
+ const why = boundInvocationReason(sourceName);
58207
+ return {
58208
+ reason: at === sourceID ? `its source ${why.replace(/^it /, "")}` : `its source extends '${map.node(at)?.name ?? at}', which ${why.replace(/^it /, "")}`,
58209
+ refusal: "bound_invocation_unkeyable"
58210
+ };
58211
+ }
57672
58212
  function inheritedGateNoteRoutes(sourceID, modelDef) {
57673
58213
  const map = SourceMap.of(modelDef);
57674
58214
  const node = map.node(sourceID);
@@ -57734,6 +58274,12 @@ async function persistedQueryRefusalReason(plan, modelDef, materializer) {
57734
58274
  reason: "its source cannot be read",
57735
58275
  refusal: "run_target_unsupported"
57736
58276
  };
58277
+ const unkeyable = plan.sourceID !== undefined ? unkeyableRefusal2(SourceMap.of(modelDef), plan.sourceID, node?.name ?? plan.sourceName ?? plan.queryName) : readsBoundArgument(def) ? {
58278
+ reason: boundInvocationReason(plan.queryName),
58279
+ refusal: "bound_invocation_unkeyable"
58280
+ } : undefined;
58281
+ if (unkeyable)
58282
+ return unkeyable;
57737
58283
  const last = stages[stages.length - 1];
57738
58284
  if ((last.outputStruct?.fields ?? []).some(isNested)) {
57739
58285
  return {
@@ -57748,7 +58294,7 @@ async function persistedQueryRefusalReason(plan, modelDef, materializer) {
57748
58294
  ];
57749
58295
  if (gateRoutes.length > 0) {
57750
58296
  return {
57751
- reason: GATED_QUERY_REASON,
58297
+ reason: gatedQueryReason(gateRoutes),
57752
58298
  refusal: gateRefusalReason(gateRoutes)
57753
58299
  };
57754
58300
  }
@@ -57768,6 +58314,9 @@ function queryRefusalOf(plan, refusal) {
57768
58314
  ...plan.storage !== undefined ? { storage: plan.storage } : {}
57769
58315
  };
57770
58316
  }
58317
+ function gatedQueryReason(routes) {
58318
+ return `it reaches an ${gateKindsName(routes)} gate, and a persisted query is never built over a gated source; it is answered live under the gate`;
58319
+ }
57771
58320
  async function tryCompilePersistedViewCompanion(args) {
57772
58321
  const modelFile = path16.resolve(args.packagePath, args.modelPath);
57773
58322
  const companionHref = persistedViewCompanionHref(pathToFileURL13(modelFile).href);
@@ -58043,8 +58592,9 @@ async function compileOverStoredGroup(args, inputs, ids) {
58043
58592
  return;
58044
58593
  }
58045
58594
  }
58046
- var GATE_NOTE_ROUTES, GATED_QUERY_REASON = "it reaches a row-level gate (#(access_filter) or #(authorize)), and a persisted query is never built over a gated source; it is answered live under the gate";
58595
+ var GATE_NOTE_ROUTES;
58047
58596
  var init_persisted_view_compile = __esm(() => {
58597
+ init_persist_source_fields();
58048
58598
  init_annotations();
58049
58599
  init_declaration();
58050
58600
  init_persist_blanking();
@@ -58065,7 +58615,6 @@ var init_persisted_view_compile = __esm(() => {
58065
58615
  init_overlay_key();
58066
58616
  init_downstream_upstreams();
58067
58617
  init_storage_over_stored();
58068
- init_pair_reroot();
58069
58618
  GATE_NOTE_ROUTES = new Set(["access_filter", "authorize"]);
58070
58619
  });
58071
58620
 
@@ -58649,7 +59198,7 @@ async function compileOverStoredBases(args) {
58649
59198
  try {
58650
59199
  await files.compile(new URL(copy.url), new Map([...materializedFiles, [copy.url, copy.text]]));
58651
59200
  } catch (error) {
58652
- logger.warn("A rollup builds from the warehouse: its #(materialize) base's copy over the stored table did not compile", {
59201
+ reportPlanDiagnostic("warn", "rollup_base_copy_failed", "A rollup builds from the warehouse: its #(materialize) base's copy over the stored table did not compile", {
58653
59202
  modelPath: args.modelPath,
58654
59203
  base: name,
58655
59204
  code: errorCodeOf(error)
@@ -58664,7 +59213,7 @@ async function compileOverStoredBases(args) {
58664
59213
  warnWarehouse(args.modelPath, error);
58665
59214
  return out;
58666
59215
  }
58667
- logger.warn("The rollups over #(materialize) bases build from the warehouse: their companion over the bases' stored tables did not compile", {
59216
+ reportPlanDiagnostic("warn", "rollup_bases_copy_failed", "The rollups over #(materialize) bases build from the warehouse: their companion over the bases' stored tables did not compile", {
58668
59217
  modelPath: args.modelPath,
58669
59218
  code: errorCodeOf(error)
58670
59219
  });
@@ -58726,7 +59275,7 @@ async function compileOverStoredBases(args) {
58726
59275
  }
58727
59276
  }
58728
59277
  function warnWarehouse(modelPath, error) {
58729
- logger.warn("The rollups of a model build from the warehouse: their companion over the bases' stored tables did not compile", {
59278
+ reportPlanDiagnostic("warn", "rollups_from_warehouse", "The rollups of a model build from the warehouse: their companion over the bases' stored tables did not compile", {
58730
59279
  modelPath,
58731
59280
  code: errorCodeOf(error)
58732
59281
  });
@@ -58747,8 +59296,8 @@ async function compileParentKeyChecks(plans, needs, joinedKeys = []) {
58747
59296
  let sql = compiled.get(sourceID);
58748
59297
  if (sql === undefined) {
58749
59298
  sql = compile(parentKeyCheckQuery(name, keyColumn)).catch((error) => {
58750
- logger.warn("A source's primary key check did not compile; queries it answers through a #(rollup) rollup read through a join are answered live", {
58751
- source: name,
59299
+ reportPlanDiagnostic("warn", "parent_key_check_uncompiled", "A source's primary key check did not compile; queries it answers through a #(rollup) rollup read through a join are answered live", {
59300
+ sourceName: name,
58752
59301
  keyColumn,
58753
59302
  code: errorCodeOf(error)
58754
59303
  });
@@ -58806,7 +59355,7 @@ async function compileGrainJoinKeyChecks(plans, joinsOf, sourceOf, stored) {
58806
59355
  const checks = [];
58807
59356
  for (const { join, uncovered } of plan.joinOneGrain ?? []) {
58808
59357
  if (uncovered) {
58809
- logger.info("A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", {
59358
+ reportPlanDiagnostic("info", "grain_join_unchecked", "A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", {
58810
59359
  rollup: plan.rollupSourceName,
58811
59360
  join,
58812
59361
  reason: "the build joins past it, through another join"
@@ -58817,7 +59366,7 @@ async function compileGrainJoinKeyChecks(plans, joinsOf, sourceOf, stored) {
58817
59366
  const source = j?.sourceID ? sourceOf(j.sourceID) : undefined;
58818
59367
  const why = j?.sourceID === undefined || j.keyColumn === undefined ? "its join is not keyed on one column of a declared source" : source === undefined ? "no model names the joined source" : [...source.reads()].some((id) => stored.has(id)) ? "the joined source reads a table the run stores" : undefined;
58819
59368
  if (why !== undefined || !j?.sourceID || !j.keyColumn || !source) {
58820
- logger.info("A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", { rollup: plan.rollupSourceName, join, reason: why });
59369
+ reportPlanDiagnostic("info", "grain_join_unchecked", "A #(rollup) rollup's grain join key is not checked; queries that read nothing through the join are answered live", { rollup: plan.rollupSourceName, join, reason: why });
58821
59370
  continue;
58822
59371
  }
58823
59372
  const { sourceID, keyColumn } = j;
@@ -58825,10 +59374,10 @@ async function compileGrainJoinKeyChecks(plans, joinsOf, sourceOf, stored) {
58825
59374
  let sql = compiled.get(key);
58826
59375
  if (sql === undefined) {
58827
59376
  sql = source.compile(grainJoinKeyCheckQuery(source.name, keyColumn)).catch((error) => {
58828
- logger.warn("A #(rollup) rollup's grain join key check did not compile; queries that read nothing through the join are answered live", {
59377
+ reportPlanDiagnostic("warn", "grain_join_check_uncompiled", "A #(rollup) rollup's grain join key check did not compile; queries that read nothing through the join are answered live", {
58829
59378
  rollup: plan.rollupSourceName,
58830
59379
  join,
58831
- source: source.name,
59380
+ sourceName: source.name,
58832
59381
  keyColumn,
58833
59382
  code: errorCodeOf(error)
58834
59383
  });
@@ -58863,7 +59412,7 @@ async function compileRollupKeyChecks(plans, materializer, modelPath) {
58863
59412
  const sql = await materializer.loadQuery(text).getSQL();
58864
59413
  plan.keyCheck = { keyColumn, sql };
58865
59414
  } catch (error) {
58866
- logger.warn("A #(rollup) rollup's key check did not compile", {
59415
+ reportPlanDiagnostic("warn", "rollup_key_check_uncompiled", "A #(rollup) rollup's key check did not compile", {
58867
59416
  modelPath,
58868
59417
  rollup: plan.rollupSourceName,
58869
59418
  code: errorCodeOf(error)
@@ -58873,7 +59422,7 @@ async function compileRollupKeyChecks(plans, materializer, modelPath) {
58873
59422
  }
58874
59423
  var init_rollup_compile = __esm(() => {
58875
59424
  init_error_code();
58876
- init_logger();
59425
+ init_plan_diagnostics();
58877
59426
  init_prepared_query();
58878
59427
  init_generated_files();
58879
59428
  init_rollup_plan();
@@ -59350,7 +59899,6 @@ function projectToStoredColumns(persistSource, buildSQL) {
59350
59899
  try {
59351
59900
  cols = storedColumnNames(persistSource);
59352
59901
  } catch (err) {
59353
- recordEligibilityRefused("public_surface_unknown");
59354
59902
  throw new MaterializationEligibilityError({
59355
59903
  reason: "public_surface_unknown",
59356
59904
  message: `Source '${persistSource.name}' cannot be materialized into a ` + `storage destination: its column surface could not be ` + `determined — ${errMessage(err)}. The publisher writes a stored ` + `table's columns as the source declares them, so it refuses the ` + `build rather than materialize columns the source drops. This ` + `usually means the compiled-source shape changed; drop 'storage=' ` + `to serve this source live in the meantime.`
@@ -59369,7 +59917,8 @@ async function resolvePackageConnections(pkg, names) {
59369
59917
  try {
59370
59918
  map.set(name, await pkg.getMalloyConnection(name));
59371
59919
  } catch (err) {
59372
- logger.warn(`Failed to resolve connection ${name}`, {
59920
+ reportPlanDiagnostic("warn", "connection_unresolved", `Failed to resolve connection ${name}`, {
59921
+ connectionName: name,
59373
59922
  code: errorCodeOf(err)
59374
59923
  });
59375
59924
  }
@@ -59396,7 +59945,7 @@ async function classifyPersistSourceGate(persistSource, modelDef, materializer,
59396
59945
  ...inheritedRowFilter ? { inheritedRowFilter } : {}
59397
59946
  };
59398
59947
  } catch (err) {
59399
- logger.warn("Failed to classify persist source gate; refusing", {
59948
+ reportPlanDiagnostic("warn", "persist_gate_unclassified", "Failed to classify persist source gate; refusing", {
59400
59949
  sourceID: persistSource.sourceID,
59401
59950
  code: errorCodeOf(err)
59402
59951
  });
@@ -59461,7 +60010,7 @@ function addCompanionOutcome(parts, findings, omitted, failed) {
59461
60010
  addAnnotationFinding(parts, finding);
59462
60011
  parts.omittedSources.push(...omitted ?? []);
59463
60012
  if (failed?.failure)
59464
- logCompanionFailure(failed.failure, failed.modelPath);
60013
+ reportCompanionFailure(failed.failure, failed.modelPath);
59465
60014
  }
59466
60015
  function withoutGivenReadingTargets(all, refuse) {
59467
60016
  for (const target of all.connections.flatMap((c) => c.targets)) {
@@ -60112,7 +60661,7 @@ async function planPersistFile(parts, args, file) {
60112
60661
  const selection = selectPersistSources(contents, (url) => sameFile2(url, file.href), file.modelPath);
60113
60662
  for (const finding of selection.findings) {
60114
60663
  if (finding.code === "persist-unparseable") {
60115
- logger.debug("Persist annotation issue", {
60664
+ reportPlanDiagnostic("debug", "persist_annotation_unparseable", "Persist annotation issue", {
60116
60665
  modelPath: file.modelPath,
60117
60666
  code: finding.code,
60118
60667
  severity: "error"
@@ -60168,7 +60717,7 @@ async function planPersistFile(parts, args, file) {
60168
60717
  });
60169
60718
  if (omitted.size > 0) {
60170
60719
  parts.omittedSources.push(...omittedByID(omitted.keys(), "persist_companion_failed"));
60171
- logger.warn("A #@ persist companion left sources out of the plan", {
60720
+ reportPlanDiagnostic("warn", "persist_companion_omitted", "A #@ persist companion left sources out of the plan", {
60172
60721
  modelPath: file.modelPath,
60173
60722
  count: omitted.size
60174
60723
  });
@@ -60219,7 +60768,7 @@ function addPersistLineFindings(parts, source, modelPath) {
60219
60768
  });
60220
60769
  }
60221
60770
  } catch (err) {
60222
- logger.warn("Failed to read a persist source's annotations; planned without their findings", {
60771
+ reportPlanDiagnostic("warn", "persist_annotations_unread", "Failed to read a persist source's annotations; planned without their findings", {
60223
60772
  modelPath,
60224
60773
  sourceID: source.sourceID,
60225
60774
  sourceName: source.name,
@@ -60420,7 +60969,7 @@ function deriveBuildPlan(compiled, packageMaterialization, verdicts = planVerdic
60420
60969
  wireSources[sourceID] = wireSourceOf(table, decided.annotationFields, planAddressOf(compiled, sourceID), packageMaterialization, compiled.upstreamSchemas);
60421
60970
  } catch (err) {
60422
60971
  const reason = isUnkeyable(source) ? "unkeyable" : err instanceof EligibilityCheckFailed ? "eligibility_check_failed" : "projection_failed";
60423
- logger.warn("Failed to project a persist source into the build plan", {
60972
+ reportPlanDiagnostic("warn", "persist_projection_failed", "Failed to project a persist source into the build plan", {
60424
60973
  sourceID,
60425
60974
  sourceName: source.name,
60426
60975
  reason,
@@ -60719,21 +61268,17 @@ async function finishPackagePlan(parts, ctx) {
60719
61268
  ...finish
60720
61269
  } = ctx;
60721
61270
  const connections = await resolvePackageConnections({ getMalloyConnection }, parts.builds.map((b) => b.connectionName));
60722
- const digestSkipped = [];
60723
- const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (name) => digestSkipped.push(name));
61271
+ const connectionDigests = await resolveConnectionDigests(connections, parts.builds, (connectionName) => reportPlanDiagnostic("warn", "connection_digest_skipped", "Skipping connection digest; connection did not resolve", { connectionName }));
60724
61272
  const upstreamSchemas = readUpstreamSchemas ? await readUpstreamSchemas(planUpstreamTables(parts.tables)) : undefined;
60725
61273
  const containers = planTargetContainers(parts.tables);
60726
61274
  const targetContainers = readTargetContainers && containers.length > 0 ? await readTargetContainers(containers) : undefined;
60727
- return {
60728
- compiled: finishBuildPlan(parts, {
60729
- ...finish,
60730
- connectionDigests,
60731
- ...upstreamSchemas ? { upstreamSchemas } : {},
60732
- ...targetContainers ? { targetContainers } : {},
60733
- connections
60734
- }),
60735
- digestSkipped
60736
- };
61275
+ return finishBuildPlan(parts, {
61276
+ ...finish,
61277
+ connectionDigests,
61278
+ ...upstreamSchemas ? { upstreamSchemas } : {},
61279
+ ...targetContainers ? { targetContainers } : {},
61280
+ connections
61281
+ });
60737
61282
  }
60738
61283
  function targetContainerOf(source) {
60739
61284
  if (declaredStorage(source) !== undefined)
@@ -60801,6 +61346,7 @@ function derivePackagePlan(compiled, materializationConfig, counts = {}) {
60801
61346
  asOfBuild,
60802
61347
  accessReads: [...compiled.accessReads ?? []],
60803
61348
  ...compiled.stringCapabilityReads && Object.keys(compiled.stringCapabilityReads).length > 0 ? { stringCapabilityReads: { ...compiled.stringCapabilityReads } } : {},
61349
+ ...compiled.missingContainers && Object.keys(compiled.missingContainers).length > 0 ? { missingContainers: { ...compiled.missingContainers } } : {},
60804
61350
  eligibilityRefused: { ...counts }
60805
61351
  };
60806
61352
  }
@@ -60922,6 +61468,7 @@ function refuseMissingContainers(compiled, readings) {
60922
61468
  const shared = sharedTables(compiled);
60923
61469
  const findings = [];
60924
61470
  const dropped = new Set;
61471
+ const missing = {};
60925
61472
  for (const [sourceID, { source }] of Object.entries(compiled.tables)) {
60926
61473
  if (shared.has(sourceID))
60927
61474
  continue;
@@ -60932,9 +61479,14 @@ function refuseMissingContainers(compiled, readings) {
60932
61479
  if (!reading || "found" in reading || "unread" in reading)
60933
61480
  continue;
60934
61481
  dropped.add(sourceID);
61482
+ missing[sourceID] = target;
60935
61483
  findings.push(notBuiltFinding(compiled, sourceID, "container_not_found", missingContainerReason(target, source.dialectName, reading)));
60936
61484
  }
60937
- return withoutSources(compiled, findings, dropped);
61485
+ const kept = withoutSources(compiled, findings, dropped);
61486
+ return dropped.size === 0 ? kept : {
61487
+ ...kept,
61488
+ missingContainers: { ...kept.missingContainers, ...missing }
61489
+ };
60938
61490
  }
60939
61491
  function notBuiltFinding(compiled, sourceID, reason, why) {
60940
61492
  const table = compiled.tables[sourceID];
@@ -61065,7 +61617,7 @@ function collectIncrementalDeclarations(tables) {
61065
61617
  ...pairDeclaration(declaration, plan)
61066
61618
  };
61067
61619
  } catch (err) {
61068
- logger.warn("Failed to resolve a source's incremental declaration", {
61620
+ reportPlanDiagnostic("warn", "incremental_declaration_unread", "Failed to resolve a source's incremental declaration", {
61069
61621
  sourceID,
61070
61622
  code: errorCodeOf(err)
61071
61623
  });
@@ -61101,8 +61653,7 @@ var init_build_plan = __esm(() => {
61101
61653
  init_declaration();
61102
61654
  init_persist_annotation_validation();
61103
61655
  init_errors2();
61104
- init_logger();
61105
- init_materialization_metrics();
61656
+ init_plan_diagnostics();
61106
61657
  init_utils();
61107
61658
  init_gate_classification();
61108
61659
  init_given();
@@ -61111,7 +61662,6 @@ var init_build_plan = __esm(() => {
61111
61662
  init_generated_files();
61112
61663
  init_table_plans();
61113
61664
  init_materialize_plan();
61114
- init_build_file_generator();
61115
61665
  init_leg_containment();
61116
61666
  init_read_text();
61117
61667
  init_materialize_compile();
@@ -61145,10 +61695,12 @@ var init_build_plan = __esm(() => {
61145
61695
  init_freshness();
61146
61696
  init_eligibility_collect();
61147
61697
  init_plan_layers();
61698
+ init_omitted_sources();
61148
61699
  init_addressing();
61149
61700
  init_eligibility_collect();
61150
61701
  init_plan_layers();
61151
61702
  init_persist_source_fields();
61703
+ init_plan_diagnostics();
61152
61704
  ORIGIN_OF_NOT_BUILT_CODE = {
61153
61705
  [PERSIST_NOT_BUILT_CODE]: "persist",
61154
61706
  [MATERIALIZE_NOT_BUILT_CODE]: "materialize",
@@ -61159,7 +61711,7 @@ var init_build_plan = __esm(() => {
61159
61711
  });
61160
61712
 
61161
61713
  // src/package_load/protocol.ts
61162
- var PACKAGE_LOAD_PROTOCOL_VERSION = 10;
61714
+ var PACKAGE_LOAD_PROTOCOL_VERSION = 11;
61163
61715
 
61164
61716
  // src/package_load/package_load_worker.ts
61165
61717
  init_served_copy_serve();
@@ -61188,8 +61740,8 @@ import {
61188
61740
  } from "@malloydata/malloy";
61189
61741
  import * as fs11 from "fs";
61190
61742
  import * as path19 from "path";
61191
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
61192
- import { createHash as createHash10 } from "node:crypto";
61743
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
61744
+ import { createHash as createHash11 } from "node:crypto";
61193
61745
  import { parentPort, threadId, workerData as workerData2 } from "node:worker_threads";
61194
61746
  import { fileURLToPath as fileURLToPath12, pathToFileURL as pathToFileURL16 } from "url";
61195
61747
 
@@ -61431,7 +61983,7 @@ function dispatchMainResponse(message) {
61431
61983
  }
61432
61984
  var schemaCache = new SchemaCache(workerData2?.schemaCacheBytes ?? 0);
61433
61985
  var deferredForgets = new DeferredForgets(schemaCache);
61434
- var jobContext = new AsyncLocalStorage3;
61986
+ var jobContext = new AsyncLocalStorage4;
61435
61987
  var writeEntry = logger.write.bind(logger);
61436
61988
  logger.write = (entry) => {
61437
61989
  const job = jobContext.getStore();
@@ -61952,7 +62504,7 @@ var REFERENCE_ID = /reference_id = \\"[0-9a-f-]{36}\\"/g;
61952
62504
  function digestRenderTagResults(results) {
61953
62505
  try {
61954
62506
  const json = JSON.stringify(results).replace(REFERENCE_ID, "reference_id = \\\"\\\"");
61955
- return createHash10("sha256").update(json).digest("hex");
62507
+ return createHash11("sha256").update(json).digest("hex");
61956
62508
  } catch {
61957
62509
  return;
61958
62510
  }
@@ -62003,7 +62555,7 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
62003
62555
  load.planStart ??= performance.now();
62004
62556
  try {
62005
62557
  const parts = emptyBuildPlanParts();
62006
- await collectModelBuildPlan(parts, {
62558
+ await collectPlanDiagnostics(load.planDiagnostics ??= [], () => collectModelBuildPlan(parts, {
62007
62559
  modelPath,
62008
62560
  packagePath: job.packagePath,
62009
62561
  materializer,
@@ -62013,7 +62565,7 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
62013
62565
  crossFileCompanions: load.crossFileCompanions ??= newCrossFileCompanions(),
62014
62566
  chainBuildText: planChainBuildText(job.packagePath, malloyConfig),
62015
62567
  stringReads: { read: chainBuildStringReads }
62016
- });
62568
+ }));
62017
62569
  load.planParts?.set(modelPath, parts);
62018
62570
  } catch (error) {
62019
62571
  if (!load.planError || order < load.planError.order) {
@@ -62022,6 +62574,8 @@ async function prepareForMainThread(job, malloyConfig, load, model) {
62022
62574
  message: `${modelPath}: ${errMessage(error)}`
62023
62575
  };
62024
62576
  }
62577
+ } finally {
62578
+ sendPlanFindings(job.requestId, load);
62025
62579
  }
62026
62580
  }
62027
62581
  return { renderTagResults, renderTagResultsDigest };
@@ -62161,13 +62715,26 @@ async function loadPackage(job) {
62161
62715
  buildPlan
62162
62716
  };
62163
62717
  }
62718
+ function sendPlanFindings(jobId, load) {
62719
+ const found = load.planDiagnostics ?? [];
62720
+ const sent = load.planDiagnosticsSent ?? 0;
62721
+ if (found.length <= sent)
62722
+ return;
62723
+ const msg = {
62724
+ type: "plan-findings",
62725
+ jobId,
62726
+ diagnostics: found.slice(sent)
62727
+ };
62728
+ port.postMessage(msg);
62729
+ load.planDiagnosticsSent = found.length;
62730
+ }
62164
62731
  async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializationConfig, versionScoped, jobId) {
62165
62732
  if (!load.planParts || load.failed || load.planLeftToMainThread) {
62166
62733
  return;
62167
62734
  }
62168
62735
  const start = performance.now();
62169
62736
  const eligibilityRefused = {};
62170
- let digestSkipped = [];
62737
+ const diagnostics = load.planDiagnostics ?? [];
62171
62738
  try {
62172
62739
  if (load.planError)
62173
62740
  throw new Error(load.planError.message);
@@ -62180,7 +62747,7 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
62180
62747
  throw new Error(`Model ${modelPath} did not compile`);
62181
62748
  mergeBuildPlanParts(parts, own);
62182
62749
  }
62183
- const finished = await finishPackagePlan(parts, {
62750
+ const finished = await collectPlanDiagnostics(diagnostics, () => finishPackagePlan(parts, {
62184
62751
  getMalloyConnection: (name) => malloyConfig.connections.lookupConnection(name),
62185
62752
  versionScoped,
62186
62753
  readUpstreamSchemas: async (tables) => (await callMain((requestId) => {
@@ -62201,20 +62768,19 @@ async function finishWorkerBuildPlan(malloyConfig, modelPaths, load, materializa
62201
62768
  };
62202
62769
  port.postMessage(req);
62203
62770
  })).readings
62204
- });
62205
- digestSkipped = finished.digestSkipped;
62771
+ }));
62206
62772
  return {
62207
62773
  ok: true,
62208
- packagePlan: derivePackagePlan(finished.compiled, materializationConfig, eligibilityRefused),
62774
+ packagePlan: collectPlanDiagnostics(diagnostics, () => derivePackagePlan(finished, materializationConfig, eligibilityRefused)),
62209
62775
  durationMs: performance.now() - (load.planStart ?? start),
62210
- digestSkipped
62776
+ diagnostics
62211
62777
  };
62212
62778
  } catch (error) {
62213
62779
  return {
62214
62780
  ok: false,
62215
62781
  error: errMessage(error),
62216
62782
  durationMs: performance.now() - (load.planStart ?? start),
62217
- digestSkipped,
62783
+ diagnostics,
62218
62784
  eligibilityRefused
62219
62785
  };
62220
62786
  }