@malloy-publisher/skills 0.1.67 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +385 -128
  2. package/package.json +62 -61
  3. package/skills/eval-answer/SKILL.md +1 -1
  4. package/skills/eval-diagnose/SKILL.md +1 -1
  5. package/skills/eval-import/SKILL.md +1 -1
  6. package/skills/eval-improve/SKILL.md +1 -1
  7. package/skills/eval-judge/SKILL.md +1 -1
  8. package/skills/eval-loop/SKILL.md +1 -1
  9. package/skills/eval-report/SKILL.md +1 -1
  10. package/skills/malloy-analysis/SKILL.md +1 -1
  11. package/skills/malloy-analysis-report/SKILL.md +1 -1
  12. package/skills/malloy-charts/SKILL.md +1 -1
  13. package/skills/malloy-classify/SKILL.md +1 -1
  14. package/skills/malloy-compliance-review/SKILL.md +1 -1
  15. package/skills/malloy-dashboards/SKILL.md +1 -1
  16. package/skills/malloy-define/SKILL.md +1 -1
  17. package/skills/malloy-define-workflow/SKILL.md +1 -1
  18. package/skills/malloy-discover/SKILL.md +1 -1
  19. package/skills/malloy-document/SKILL.md +1 -1
  20. package/skills/malloy-excel-review/SKILL.md +1 -1
  21. package/skills/malloy-getting-started/SKILL.md +1 -1
  22. package/skills/malloy-gotchas-modeling/SKILL.md +1 -1
  23. package/skills/malloy-html-data-apps/SKILL.md +2 -2
  24. package/skills/malloy-lookml-review/SKILL.md +1 -1
  25. package/skills/malloy-materialization/SKILL.md +17 -18
  26. package/skills/malloy-materialization/reference/access-filter.md +3 -3
  27. package/skills/malloy-materialization/reference/annotation.md +6 -7
  28. package/skills/malloy-materialization/reference/chaining.md +10 -30
  29. package/skills/malloy-materialization/reference/estimating.md +2 -2
  30. package/skills/malloy-materialization/reference/refresh.md +4 -4
  31. package/skills/malloy-materialization/reference/serving.md +61 -0
  32. package/skills/malloy-materialization/reference/tuning.md +5 -6
  33. package/skills/malloy-materialization/reference/why-live.md +8 -8
  34. package/skills/malloy-model/SKILL.md +2 -2
  35. package/skills/malloy-model-as-you-go/SKILL.md +1 -1
  36. package/skills/malloy-modeling/SKILL.md +1 -1
  37. package/skills/malloy-notebooks/SKILL.md +1 -1
  38. package/skills/malloy-phrase-detection/SKILL.md +1 -1
  39. package/skills/malloy-powerbi-review/SKILL.md +1 -1
  40. package/skills/malloy-publish/SKILL.md +1 -1
  41. package/skills/malloy-queries/SKILL.md +1 -1
  42. package/skills/malloy-reports/SKILL.md +1 -1
  43. package/skills/malloy-review/SKILL.md +1 -1
  44. package/skills/malloy-run-workflow/SKILL.md +1 -1
  45. package/skills/malloy-source-unreachable/SKILL.md +1 -1
  46. package/skills/malloy-materialization/reference/storage.md +0 -85
@@ -5,60 +5,40 @@ SPDX-License-Identifier: MIT
5
5
 
6
6
  # Chaining: one stored source built over another
7
7
 
8
- A stored source can be built over another stored source's table instead of recomputing it from the warehouse. Under `#(materialize)` that link is an **extension**: a source that `extend`s a materialized source and declares its own `#(materialize)` gets a table of its own, built over its parent's stored table. When both are `storage=` in the same destination, the build runs in the destination's own engine over the parent's table, never re-scanning the warehouse, and the child is a pure function of the parent's stored rows.
8
+ A stored source can be built over another stored source's table instead of recomputing it from raw. Under `#(materialize)` that link is an **extension**: a source that `extend`s a materialized source and declares its own `#(materialize)` gets a table of its own, built in the warehouse over its parent's stored table, so the child is a function of the parent's stored rows.
9
9
 
10
10
  ```malloy
11
- #(materialize) name="daily_orders" storage="lake"
11
+ #(materialize) name="analytics.daily_orders"
12
12
  source: daily_orders is orders -> { group_by: order_date; aggregate: total_amount is amount.sum() } extend {
13
13
  measure: amount_total is total_amount.sum()
14
14
  }
15
15
 
16
16
  // Its own table, built over daily_orders' stored table (the plan's buildsOver and dependsOn name daily_orders).
17
- #(materialize) name="recent_orders" storage="lake"
17
+ #(materialize) name="analytics.recent_orders"
18
18
  source: recent_orders is daily_orders extend {
19
19
  where: order_date >= @2024-02-01
20
20
  }
21
21
  ```
22
22
 
23
- **A query-shaped `#(materialize)` source over another does not chain.** `#(materialize) storage="lake"` on `monthly_orders is daily_orders -> { group_by: order_month is order_date.month; … }` starts a build of its own: it depends on nothing, and its build recomputes `daily_orders`' query from the warehouse. That is correct, only not cheaper. To roll a stored source up to a coarser grain without re-reading the warehouse, put `#(rollup) grain=[…]` on its measure instead (a `storage=` rollup over a base stored in the same destination may be built from the base's table; `docs/preaggregation.md`).
23
+ **A query-shaped `#(materialize)` source over another does not chain.** `#(materialize)` on `monthly_orders is daily_orders -> { group_by: order_month is order_date.month; … }` starts a build of its own: it depends on nothing, and its build recomputes `daily_orders`' query from the warehouse. That is correct, only not cheaper. To roll a stored source up to a coarser grain without recomputing it, put `#(rollup) grain=[…]` on its measure instead (a rollup over a persisted base builds from the base's table; `docs/preaggregation.md`).
24
24
 
25
- **Legacy `#@ persist` chains** do link through a query: `#@ persist storage="lake"` on both `daily_orders` and `monthly_orders is daily_orders -> { … }` builds `monthly_orders` over `daily_orders`' table. In such a chain the downstream need not name the upstream directly. Non-materialized sources between them - a `select: *` wrapper, an `extend` that adds a dimension, a named source over an inline `(parent extend { ... }) -> { ... }`, a query over the upstream, a parent reached only through an `import` - are carried into the build in dependency order, under the `##!` flags of the files that declare them, and declaring the author model's `given:`s, so the downstream still reads the upstream's table through them.
25
+ **Legacy `#@ persist` chains** do link through a query: `#@ persist` on both `daily_orders` and `monthly_orders is daily_orders -> { … }` builds `monthly_orders` over `daily_orders`' table. In such a chain the downstream need not name the upstream directly. Non-materialized sources between them - a `select: *` wrapper, an `extend` that adds a dimension, a named source over an inline `(parent extend { ... }) -> { ... }`, a query over the upstream, a parent reached only through an `import` - are carried into the build in dependency order, under the `##!` flags of the files that declare them, and declaring the author model's `given:`s, so the downstream still reads the upstream's table through them.
26
26
 
27
- ## The four rules that decide reuse
27
+ ## The two rules that decide reuse
28
28
 
29
29
  1. **Declare the stored roots before the sources that read them.** Malloy resolves names in file order. A rollup rewired to read a stored root that is declared further down fails to compile with `Reference to undefined object`, and so does everything after it. When you chain an existing package onto its roots, move the roots up.
30
30
  2. **An extension decides for itself whether it is a new table.** `rollup_base is daily_orders extend { ... }` with no `#(materialize)` of its own reads the parent's table and is not a build target. With its own `#(materialize)` it gets a table of its own, built by reading the parent's table rather than recomputing the chain. The same holds for an extension of a source that still carries v1 `#@ persist`: its own `#(materialize)` builds over the base's stored table.
31
- 3. **Every join on the path must land on a stored table.** An intermediate that joins a source nothing materializes - a `join_cross: sp is species_live` where only `species_base` is stored - reaches the warehouse, and the downstream is refused (no engine reads both the lake and the warehouse), never recomputed from the warehouse with the upstream inlined. The annotation-only fixes come first: materialize the joined source too (`#(materialize)` on it, in the same destination), or build the downstream in the warehouse with no `storage=` (and on the upstreams it reads). Re-pointing the join at a stored sibling changes the model's shape: a tier-2 change (`reference/estimating.md`), shown as its own diff and approved on its own.
32
- 4. **A chained build runs in the destination's engine, under its memory bound.** The rows are read from the lake and rolled up in DuckDB with the build session's `memory_limit`. A grouped rollup fits; a self-join or a wide hash aggregate over a large fact may not, and fails with DuckDB's `Out of Memory Error` on every attempt. Such a source belongs in the warehouse: keep its input unmaterialized so it is built there and only its result is copied in. Placement is a cost decision the build does not make for you.
33
-
34
- ## The named-base rule, for a string Publisher cannot trace (legacy `#@ persist` chains)
35
-
36
- The destination compares strings byte for byte (`reference/storage.md` § Collation), so Publisher checks that each string a chained downstream groups, orders or filters compares there as it does live. This rule is about legacy chains written with v1 `#@ persist`: a `#(materialize) storage=` downstream over an extend of a `#(materialize)` base is built from the warehouse, not over the base's table, so none of this applies to it.
37
-
38
- For a `#@ persist storage=` downstream over a `#@ persist` stored source, string reads are followed to the stored upstream's columns through a named base, or through the fields, `where:`s and joins an inline extend of the stored source declares. So `(orders_base extend { dimension: r is lower(region_name) }) -> { group_by: r … }` is judged exactly as the same extend declared as a named source. Each string is judged by the column it reads, whatever the downstream names it.
39
-
40
- A read that cannot be traced is refused (`upstream_table_unusable`) with "the base its strings are read on is not named". The fix depends on why:
41
-
42
- - **An unnamed query, or a base more than one source declares:** declare the base as a named source and build over it.
43
- - **A string read through a join to a source not stored in this downstream's destination** (stored nowhere, in another destination, or in its warehouse): join a source stored in the same destination.
44
- - **Raw SQL** (a `sql_` function or a `name!(…)` call) in what the extend declares, or in a source it joins: no chained build carries raw SQL, named base or not, so the downstream answers live. Write the expression in Malloy instead.
45
-
46
- Each of those fixes changes the model's shape (it extracts a named base, re-points a join, or rewrites an expression): show the diff and get explicit approval for it on its own, after the annotation-only options (`reference/estimating.md`): building the chain in the warehouse with no `storage=`, leaving the downstream unmaterialized, or moving the chain to `#(materialize)` (a `#(materialize) storage=` downstream over an extend of a `#(materialize)` base is built from the warehouse, so this check does not apply to it). Read the refusal's message before proposing anything: it names which case applies.
47
31
 
48
32
  ## What the build does when it cannot reuse
49
33
 
50
- A chained build (an extension with its own `#(materialize)`, or a legacy `#@ persist` downstream) that cannot be built over the stored tables is **refused, never built by recomputing its upstreams from the warehouse**, in every build, standalone or orchestrated. A query-shaped `#(materialize)` source over another materialized source is not a chained build: it is built from the warehouse, as above. Where the plan can tell, it refuses when the package is planned, as `upstream_table_unusable` with a message naming the upstream and why: it reaches the warehouse through an intermediate (rule 3), its upstream lives in a _different_ destination (except an extension with its own `#(materialize)`, which reads a parent in another destination attached read-only), or it groups, filters or orders a string its upstream's table records as compared otherwise than live (its column contract's `compare`). What only a run can find fails that run's build: a materialized upstream the build neither materialized nor was handed by reference, or a shape over stored upstreams the build could not carry (a refinement the ladder below drops). Either way the source answers live. `strictUpstreams` and `warehouseReach` are accepted and ignored.
34
+ A chained build (an extension with its own `#(materialize)`, or a legacy `#@ persist` downstream) that cannot be built over its upstreams' stored tables is **refused, never built by recomputing its upstreams from raw**, in every build, standalone or orchestrated. A query-shaped `#(materialize)` source over another materialized source is not a chained build: it is built from the warehouse, as above. Where the plan can tell, it refuses when the package is planned, as `upstream_table_unusable` with a message naming the upstream and why (for example an upstream that is itself refused, or not planned, so it has no table). What only a run can find fails that run's build: a materialized upstream the build neither materialized nor was handed by reference, or an upstream table altered since its build (`schema_incompatible`, retryable: the plan is derived again). Either way the source answers live. `strictUpstreams` and `warehouseReach` are accepted and ignored.
51
35
 
52
- A chained build re-declares on each parent's binding what the parent's `extend` block adds - its `where:`, dimensions, measures, joins and views - and thins them when they do not compile in the destination, in tiers: a view first, then a join, then a dimension or measure that reads a join the destination cannot bind. **The `where:` is never thinned**: a stored source declared `extend { where: total > 100 }` holds every row and is filtered when read, so a child built over it without that filter would sum the unfiltered rows.
36
+ **The `where:` is never dropped**: a stored source declared `extend { where: total > 100 }` holds every row and is filtered when read, so a child built over it applies that filter too.
53
37
 
54
38
  ## Reading which happened
55
39
 
56
40
  A manifest entry for a chained build carries `upstreamReuse: "reused"`: every materialized upstream was read from its table, so the rows are a function of those snapshots. A chained build that cannot read its upstreams' tables is refused or fails, and carries no `upstreamReuse`. `upstreamReuse: "recomputed"` (with `upstreamRecomputeReason`) is retained in the API and no longer planned; an entry is not expected to carry it. A query-shaped `#(materialize)` source over another is not a chained build, so its entry carries neither: it was built from the warehouse, and its rows reflect the warehouse at _that build's_ time rather than the upstream's snapshot, so the two can disagree when their refresh cadences differ. The field is not a location and never names a table.
57
41
 
58
- The `publisher_storage_chained_build_total{outcome}` counter reports the path each chained build took: `parent_reuse`, `strict_refused` (no build over its stored upstreams exists), `infra_failure` (the destination was unreachable or the build died in it - kept distinct so a store outage or an out-of-memory is not read as an un-carriable shape).
59
-
60
- ## Three limits to know
42
+ ## A limit to know
61
43
 
62
- - A refresh of a chained `refresh="incremental"` source always rebuilds in full (`chained_storage` reason): its parent's delta can restate rows below the child's own frontier where no delta of the child's would revisit them. The exception is a `#(materialize)` extension of a `#(materialize)` parent on one tier: it follows the parent's refresh. On the parent's watermark it deltas from no later than the parent's delta start. On another watermark it rebuilds whenever the parent changed (`upstream_watermark_differs`). After a missed parent refresh it rebuilds (`upstream_generation_skipped`).
63
- - A database `#(materialize)` (no `storage=`) cannot read a `storage=` upstream's table, because the warehouse cannot see the lake: a database extension of a `storage=` parent is refused at plan (`upstream_table_unusable`) and answers live.
64
- - A chained build carries the intermediates' _text_, written for the source warehouse, into the destination's dialect. A construct the destination lacks fails the carry, and under strict that is a refusal rather than a recompute.
44
+ A `#(materialize)` extension of an incremental `#(materialize)` parent follows the parent's refresh. On the parent's watermark it deltas from no later than the parent's delta start. On another watermark it rebuilds whenever the parent changed (`upstream_watermark_differs`). After a missed parent refresh it rebuilds (`upstream_generation_skipped`).
@@ -28,7 +28,7 @@ This file covers the question to answer **before** any annotation is written: is
28
28
  | Which queries a table would serve, and which it would not | the path reports of the author's own queries, run against the local server with simulation on (`SKILL.md` § Validate before publish) | `simulated`: the router's real decision over placeholder tables |
29
29
  | A source's fate (refused, would build, would serve) and its facts | the per-source materialization summary the local server returns on reload and status | each fact carries `basis`: `exact`, `predicted` or `not_knowable_locally` |
30
30
  | Predicted table size | the summary's `rowCount` and `bytes` facts under simulation: the stats of the tables the build reads, summed | `predicted`, an upper bound (`band.high`); `not_knowable_locally` when the build reads nothing Publisher can name (inline SQL) |
31
- | Key uniqueness (behind an inlined `join_many`, a key-dependent rollup) | the summary's `keyUniqueness` fact: simulation runs one aggregate per key check, returning only a count (a `storage=` table's own key compares `count()` with `count(distinct key)` over the rows its build SQL selects). Run the same yourself only for a key it did not judge, after the first pass | `predicted` (`method: aggregate`); a real build confirms it |
31
+ | Key uniqueness (behind an inlined `join_many`, a key-dependent rollup) | the summary's `keyUniqueness` fact: simulation runs one aggregate per key check, returning only a count. Run the same yourself only for a key it did not judge, after the first pass | `predicted` (`method: aggregate`); a real build confirms it |
32
32
  | Build cost | the summary's `buildCost` fact under simulation (the bytes the build reads), or the same sum from table stats yourself | `predicted`, an upper bound, wide band. There is no SQL cost estimate yet, and a proxy connection may not allow `conn.sql()` or table functions (such as a warehouse's job history), so this band is the honest number |
33
33
  | Query frequency, cost basis (per byte, per slot, per hour) | the author | `stated by the author`. Ask; never invent a workload |
34
34
 
@@ -73,7 +73,7 @@ Test it, do not reason about it: for each narrow candidate, run one aggregate th
73
73
 
74
74
  **Tier 1, annotations on the existing shape.** Propose these first, and only these when they are enough:
75
75
 
76
- - `#(materialize)` on an existing source, with its options: `inline=` for a join it should store with it, or reference joins (the default); `storage="<destination>"`, or the database tier (no `storage=`);
76
+ - `#(materialize)` on an existing source, with its options: `inline=` for a join it should store with it, or reference joins (the default);
77
77
  - `#(rollup) grain=[…]` on an existing measure;
78
78
  - `#@ persist` on an existing view or named query;
79
79
  - refresh settings: `freshness.*`, `refresh="incremental"` with `watermark=`, `merge_key=`, `lookback=`.
@@ -44,14 +44,14 @@ source: daily_orders is orders -> { group_by: order_date; aggregate: revenue is
44
44
  - `watermark=` names one of the source's own output columns - real, orderable, non-aggregate. Publisher records how far each refresh reached (`covered_through`) and the next recomputes only `[start, frontier)`, half-open, so the frontier value itself is left for the next run. A `date`/`timestamp` watermark takes the run's start time as the frontier and **starts at the newest watermark the stored table holds** (one `max()` over the table), so a row stamped after the newest stored row is read however late it loads; it never starts at the previous run's start time, which would skip such a row for good. The start is inclusive: a merge or a range replace re-reads the newest stored instant without writing it twice. A numeric or string watermark reads `max(watermark)` from the source as its frontier, and the next range starts there; two refreshes of one with no new rows skip - correct, and it looks like nothing happened.
45
45
  - **Without `merge_key=`, a refresh replaces the whole range it re-reads**, from the newest stored row (on a `date` watermark, the whole newest stored day): a stored row the source no longer holds there is removed. A source that drops or trims recent rows (a staging table keeping only the latest day) notices; declare `merge_key=` for append-only behaviour, since a merge never deletes.
46
46
  - **Late rows: `lookback="2 days"`.** There is no lookback unless declared. A row stamped _below_ the newest stored row, loaded after it, is below every later delta. `lookback=` starts each delta that much further back (`[newest stored − lookback, frontier)`), and the merge key matches the rows read again. A positive whole number and one unit, `seconds`/`minutes`/`hours`/`days`/`weeks` spelled out or as `s`/`m`/`h`/`d`/`w` (`"36h"`), at most 365 days; no month or year. It needs a `date` or `timestamp` watermark **and** `merge_key=`; anything else fails the load (`materialize-invalid`). Size it to how late rows really arrive: each day of lookback is re-read every refresh.
47
- - **Missed rows are reported.** After each delta, one check counts the source's rows in the window just below where the delta started (as wide as the delta's own range, capped at 7 days or the lookback, whichever is longer) that the table lacks. Any found are on the manifest entry as `lateRows` (`count`, `from`, `to`) and on the package as a `persist-incremental-late-rows` warning: the served table undercounts. Both are carried, with later findings added, until the source is rebuilt in full. Recover with one `reseed`, then add or widen `lookback=`. The count is a lower bound (a slice is checked once, so a row landing in an already-checked slice is not counted), and the report stays until a full rebuild even after a widened lookback has written the rows. A row older than the window is not seen; pair tables, string watermarks and `storage=` sources on BigQuery are not checked; the check gives up after 60 seconds and never fails the run.
47
+ - **Missed rows are reported.** After each delta, one check counts the source's rows in the window just below where the delta started (as wide as the delta's own range, capped at 7 days or the lookback, whichever is longer) that the table lacks. Any found are on the manifest entry as `lateRows` (`count`, `from`, `to`) and on the package as a `persist-incremental-late-rows` warning: the served table undercounts. Both are carried, with later findings added, until the source is rebuilt in full. Recover with one `reseed`, then add or widen `lookback=`. The count is a lower bound (a slice is checked once, so a row landing in an already-checked slice is not counted), and the report stays until a full rebuild even after a widened lookback has written the rows. A row older than the window is not seen; pair tables and string watermarks are not checked; the check gives up after 60 seconds and never fails the run.
48
48
  - **A zoned timestamp watermark (`timestamptz`) in a session time zone other than UTC** (set by the connection's setupSQL) reads back with that zone's offset, so the source rebuilds in full each refresh, logged at `warn`. A plain `timestamp` or `date` watermark is not affected.
49
49
  - **An invalid declaration fails the package load**, not just the publish: `watermark=` without `refresh="incremental"`, `merge_key=` without a watermark, a watermark that names no materialized column or an aggregate, or a `lookback=` that is not a duration, is over 365 days, lacks `merge_key=`, or sits on a number or string watermark (`materialize-invalid`). (A `calculate:` field or an unsupported dialect is valid but refuses the source alone.) Postgres, BigQuery and Snowflake sources only (the dialect that has to express the range); a DuckDB source has to say `refresh="full"`.
50
50
  - **`forceRefresh` never re-seeds**; it only defeats skip-if-unchanged, and an incremental source is exempt from that anyway. Ask for a full rebuild with `reseed` (`malloy-pub materialize --reseed`, or per source on the build instruction). Keeping them apart is what lets a schedule drive deltas at all, since every scheduled fire is forced.
51
- - Each manifest entry reports what the run **did**: `refresh: delta | full | none`, with `ledger.coveredThrough` as the boundary now in force. Every fallback - no recorded boundary, a boundary measured on a different table or watermark, drifted columns, `MERGE` on a Postgres older than 15 - rebuilds in full and succeeds, so a source quietly rebuilding on every run looks exactly like one advancing unless you read `refresh`. The reason codes (`forced`, `no_boundary`, `lineage_changed`, `table_renamed`, `merge_unsupported`, `table_unreadable`, `table_emptied`, `shape_mismatch`, `ledger_unreadable`, `ledger_unheld`, `chained_storage`, `merge_key_not_unique`, `upstream_generation_skipped`, `upstream_watermark_differs`, `frontier_unreadable`, `not_advanced`) say why.
52
- - **An upstream column widened after the build** (INTEGER to BIGINT, REAL to DOUBLE PRECISION) is invisible to Malloy's types, so before each delta the delta's column types are compared with the stored ones; a stored column that cannot hold the delta's values exactly rebuilds the source in full (`shape_mismatch`). Read for a Postgres, DuckDB or MotherDuck database table and a `storage=` table with a Postgres source; BigQuery cannot widen (one integer type, one float type); Snowflake is not checked.
51
+ - Each manifest entry reports what the run **did**: `refresh: delta | full | none`, with `ledger.coveredThrough` as the boundary now in force. Every fallback - no recorded boundary, a boundary measured on a different table or watermark, drifted columns, `MERGE` on a Postgres older than 15 - rebuilds in full and succeeds, so a source quietly rebuilding on every run looks exactly like one advancing unless you read `refresh`. The reason codes (`forced`, `no_boundary`, `lineage_changed`, `table_renamed`, `merge_unsupported`, `table_unreadable`, `table_emptied`, `shape_mismatch`, `ledger_unreadable`, `ledger_unheld`, `merge_key_not_unique`, `upstream_generation_skipped`, `upstream_watermark_differs`, `frontier_unreadable`, `not_advanced`) say why.
52
+ - **An upstream column widened after the build** (INTEGER to BIGINT, REAL to DOUBLE PRECISION) is invisible to Malloy's types, so before each delta the delta's column types are compared with the stored ones; a stored column that cannot hold the delta's values exactly rebuilds the source in full (`shape_mismatch`). Read for a Postgres, DuckDB or MotherDuck database table; BigQuery cannot widen (one integer type, one float type); Snowflake is not checked.
53
53
  - **`merge_key=` must be unique in the source.** A merge cannot store two rows under one key, so a delta that reads a key twice is rolled back and the source rebuilt in full (`merge_key_not_unique`; on Snowflake, found by a probe after the delta, which makes the next refresh rebuild), and a rebuilt table that holds a key twice records no boundary, so it is rebuilt in full on every refresh until the key is unique. Both raise a `persist-incremental-merge-key-not-unique` warning naming the source; fix the key (or drop `merge_key=`) and the next rebuild clears it. The warning is held in memory: after a restart it reappears on the next refresh. A key repeated *across* refreshes is not caught: a later delta's row replaces the stored one, as a restatement, so a source whose key is not a row's identity over time (a log of versions) keeps one row per key where live has several.
54
- - `storage=` is supported: the warehouse computes the bounded range and the DML lands in the destination. A **chained** stored source always rebuilds in full (`chained_storage`): see `reference/chaining.md`.
54
+ - A **chained** stored source (a `#(materialize)` extension of an incremental parent) follows its parent's refresh: see `reference/chaining.md`.
55
55
  - The boundary lives in the publisher's own per-process store. A host that spreads a package's refreshes over several workers holds the ledger itself: it stores each entry's `ledger` object and sends them back as `buildInstructions.ledger` on the next run. Standalone, the store is the publisher's, always.
56
56
 
57
57
  ## Which refresh a gated source needs
@@ -0,0 +1,61 @@
1
+ <!--
2
+ Copyright (c) Credible Data Inc.
3
+ SPDX-License-Identifier: MIT
4
+ -->
5
+
6
+ # Where a table is built, and how a stored table is served
7
+
8
+ A materialized source is built **in its own connection**: the warehouse runs the build and the table lands beside the data, at the name the plan gives it (`reference/annotation.md`). A rollup is built beside its base, and a persisted view or named query beside its source.
9
+
10
+ ```malloy
11
+ #(materialize) name="analytics.daily_orders"
12
+ source: daily_orders is orders -> { group_by: order_date; aggregate: total is amount.sum() }
13
+ ```
14
+
15
+ - **A copy in a lake is an extract, not a materialization.** To keep a copy of a query's rows in a managed DuckLake database, read in place of the origin and never answered live, write `#(extract) into="<managed connection>.<name>"` on a query-shaped target (a named query, a view, or a query-shaped source): see `docs/extracts.md` in the Publisher repository, which is in development. Never write `storage=`. A `storage=` on a source, view or named query is rewritten at load into a generated extract, with a `storage-rewritten` warning, and is then answered only from that copy (409 `EXTRACT_AWAITING_BUILD` until its first build), never live; a declaration the rewrite cannot convert fails the package's load. A `storage=` on a rollup is dropped with a `storage-rewritten` warning, and the rollup is built in its base's warehouse. To keep a table in the source's own warehouse, drop `storage=`.
16
+ - **A source on a managed DuckLake connection** (`managed: true`) is built in that connection's own catalog, on a build session that attaches it read-write, and served as any database table. Its `name=` must place the table in `main` or a schema the connection's `readableSchemas` lists, or its build is refused. That session runs only SQL Malloy generated: a source with `.sql()` or a `sql_*` expression anywhere beneath it, or a table read from a file or URL, is refused at load (`materialize-not-built`, reason `managed_author_sql`) and answered live. A build whose SQL reads a view, or a table outside the schemas the connection reads, is refused before anything is written.
17
+ - **A connection that cannot create tables** (SQL Server today) refuses the source (`connection_cannot_hold_table`), and it answers live.
18
+ - **Hidden columns are stored.** A stored table holds every column its source declares, `private:` and `internal:` ones included (a renamed one under the name its query gives it; an `except:`-ed one not at all, unless another source with identical SQL shares the table and stores it), and the served copy hides them again: a measure over a hidden column is answered from the table, and a caller is refused a hidden column in live's words. The values are at rest in the warehouse, readable by anyone with direct access to the table, never through Publisher. To keep a value out of the table, leave it out of the source's query, do not just hide it. `#(carries)` checks what a caller can reach, not what a table stores.
19
+ - `partition=` is not supported: a stored table is written unpartitioned, and a package whose `#(materialize)` carries `partition=` fails the publish and the load (`materialize-retired-key`). Remove the key; it was a layout only, so the cost is scan time and no answer changes.
20
+
21
+ ## Where a given may sit
22
+
23
+ A materialized table is built once, with no caller present, so a `given` has to be somewhere the build never reads it.
24
+
25
+ - **In the materialized source's own `where:` - honoured per caller.** `#(materialize)` on `fact is raw extend { where: org_id = $ORG_ID }` leaves the term out of the build, stores every caller's rows in one table, and re-applies the term per caller at read. One table serves every tenant, and a term a caller writes on an extension of it still scopes what is read. A dimension of its own that reads a given is not stored; the served copy computes it at read.
26
+ - **Inherited from a base - refused, answered live.** `#(materialize)` on `r is scoped extend { ... }`, where `scoped is raw extend { where: org_id = $ORG_ID }`, is not built: only the materialized source's own declaration is re-applied over its table at read. It is refused with a `materialize-not-built` warning and answers live, correctly but at live speed. The same holds for a given-reading dimension a base declares. To serve it from a table, move the given-reading `where:` onto the materialized source itself, and let extensions that materialize nothing read its table. An extension that declares its own `#(materialize)` over such a parent is refused too (`upstream_table_unusable`), and its queries are answered from the parent's table.
27
+ - **Inside a persisted view's or named query's result - refused.** A view or query whose result reads a given differs per caller, so it is not built (`reads_given`, `persist-view-not-built` / `persist-query-not-built`).
28
+
29
+ A `#(access_filter)` gate is the same shape with a different source of truth; see `reference/access-filter.md`.
30
+
31
+ ## Shaping a rollup for its reads
32
+
33
+ A stored rollup pays at build time so that reads are cheap; the grain and the inputs decide whether they are.
34
+
35
+ - **Grain to the reads, not to the data.** Group by exactly the columns the queries filter or group by. Every extra dimension multiplies the row count, and a rollup that approaches the fact table's size saves nothing.
36
+ - **A source's own filters shrink its table.** The `where:` a materialized source already declares is applied by the build. A term that reads a given is left out of the build and re-applied at read, and a rolling time window is re-applied at every read.
37
+ - **A distinct count needs its field in the grain.** `#(rollup)` stores `count(x)` only when `x` is a grain entry (`grain=["region", "customer_id"]` for `count(customer_id)`); the rollup keeps one row per value of `x`, and a coarser query counts the stored values, exactly. With `x` outside the grain the load fails (`rollup-not-mergeable`). Size the grain before adding `x`: a high-cardinality `x` can make the rollup nearly as large as the fact, so check its rollup reduction and flag it under 10x (`reference/estimating.md`).
38
+ - **An average is a sum and a count, rolled up, and a measure over them.** Put `#(rollup)` on the sum and the count at the grain the reads need, and declare `avg is total / nullif(n, 0)` with no line of its own: it is served from any rollup that stores both. A measure with an aggregate of its own (`total / count()`) or a filter on a dimension is not, without a `#(rollup)` line of its own; one with `all()` or `exclude()` cannot be rolled up. Their queries answer live with `MISSING_FIELD`. Publisher 0.18.9 and earlier serve the declared average only with its own `#(rollup)` line at the parts' grain, so when the path report skips the rollup with `MISSING_FIELD` for it, add that line.
39
+ - **Give a ratio both halves.** A percentage whose numerator is a rollup and whose denominator is a count over the fact table still scans the fact per query. Put `#(rollup)` on the denominator's existing measure at the same grain first.
40
+ - **Strings compare as the table records them.** A rollup, persisted view or persisted query answers a query only when every string the query filters, groups or orders by compares in the table as it does live; otherwise that query is answered live and its path report names the skip (`COMPARISON_SEMANTICS`).
41
+
42
+ Three more shapings change the model, so each is a tier-2 change (`reference/estimating.md`), proposed only after the annotations above fall short, as its own diff with its own approval: adding a `where:` to bake a filter into a source, a new source holding the denominator at its own grain, and `except:`-ing columns no reader uses from a wide stored copy.
43
+
44
+ ## How a stored table is served
45
+
46
+ A query against a package with bound tables is compiled over the **served copy**: your own files, held in memory, with each materialized source's definition replaced by its stored table under the same name. Its `extend` blocks, annotations and every other line are your text, so an extension, a join to it, a view, a named query or a source in a file that imports it reads the stored table with no change to how it is written. A reader whose query reaches a stored source whose table is stale past its freshness window is served **live** instead.
47
+
48
+ Routing is decided per query, not per source, so one source can serve some queries from its table and others live:
49
+
50
+ - **The served copy reads the author's own text** over the stored table (its views, joins, measures and filters as written), so nothing is thinned: a source whose re-root does not compile is left as written and answers live, with a `served-copy-not-served` warning, and the model's other stored sources still serve.
51
+ - A **stale** table (past its freshness window, with `fallback` `live` or `fail`) leaves the serving set, and a run-time read failure under `fallback: live` degrades that query to live.
52
+
53
+ What the server reports:
54
+
55
+ - `QueryResult.servedFrom`: `database` when a stored table in the source's own connection answered, `live_fallback` when a stored table was chosen but a run-time read failure degraded the query to a live recompute, `extract` when an extract's copy answered the query or part of it, the path report saying which parts (each extract's data age is `path.servedBy.extracts[].dataAsOf`), and empty when no table answered (no binding, or an ineligible query; the path report says which).
56
+ - `publisher_query_route_total{leg, outcome, reason}` counts each leg the router considered (`used`, `skipped` with the path report's reason, `fallback` when a stored run failed and live answered), and each query's path report names the table that answered (`servedBy.via: served_copy`) or why each one was skipped.
57
+ - A query's full result carries the SQL it ran; served from a table, its `FROM` names the physical table.
58
+
59
+ ## Rollups
60
+
61
+ `#(rollup) grain=["category", "order_day"]` on a **measure** stores a rollup Publisher derives at that grain, in its base's warehouse, and routes to it when a query groups by a subset of the grain; queries do not change. Write one line per grain. It builds through the same plan, manifest and scheduler as `#(materialize)`, inherits the base source's freshness, and refuses a gated source unless its gate holds on the rollup's rows (`reference/access-filter.md`). A rollup on a measure the published surface hides is not built; the package loads and warns. A hidden (`private` or `internal`) grain dimension is stored and stays hidden; a `where:` of the source's own that reads a given over grain dimensions is left out of the build and re-applied per caller at read; and a query that sets its own `timezone:` but reads no date or timestamp is answered from the rollup. See `docs/preaggregation.md` for grain choice.
@@ -5,7 +5,7 @@ SPDX-License-Identifier: MIT
5
5
 
6
6
  # Tuning materializations for cost and performance
7
7
 
8
- This skill turns the signals the open-source Publisher already records (the materialization history, per-run and per-source timings, which sources were built vs reused, and for the storage tier how queries were routed) into concrete, **recommendations-only** advice: which sources to materialize, which to stop materializing, which to chain, and how to schedule them. The Publisher has the raw signals, and you read them with the `malloy-pub` CLI.
8
+ This skill turns the signals the open-source Publisher already records (the materialization history, per-run and per-source timings, which sources were built vs reused, and how queries were routed) into concrete, **recommendations-only** advice: which sources to materialize, which to stop materializing, which to chain, and how to schedule them. The Publisher has the raw signals, and you read them with the `malloy-pub` CLI.
9
9
 
10
10
  This file reads what is already annotated and built. Whether to materialize something new, and what, is `reference/estimating.md`: measure first, show its tradeoff table, and validate locally before publishing (the main skill's **Validate before publish**). A recommendation here that adds a materialization goes through that file's tradeoff table and approval, and prefers annotations on the model as it is to any change of its shape.
11
11
 
@@ -17,7 +17,7 @@ Assumes the `malloy-pub` CLI is on PATH (`npm i -g @malloy-publisher/cli`, or pr
17
17
 
18
18
  Establish what the package materializes today and how it is governed.
19
19
 
20
- - **Materialized sources:** the sources annotated `#(materialize)` in the package's `.malloy` files (and any rollups, `#(rollup)`, and persisted views or queries, `#@ persist`), with their tier (`storage=` or not) and `refresh=`. Read the models (or `get_context` the package) to list them, and read `GET …/packages/{pkg}/build-plan` for what a run will build and what it will refuse.
20
+ - **Materialized sources:** the sources annotated `#(materialize)` in the package's `.malloy` files (and any rollups, `#(rollup)`, and persisted views or queries, `#@ persist`), with their `refresh=`. Read the models (or `get_context` the package) to list them, and read `GET …/packages/{pkg}/build-plan` for what a run will build and what it will refuse.
21
21
  - **Schedule + scope:**
22
22
 
23
23
  ```bash
@@ -53,7 +53,7 @@ The history is where cost lives. Each run records its trigger, timing, and per s
53
53
 
54
54
  Look across several runs, not one: the pattern over the recent history (how often it rebuilds, how long each source takes, what reuses) is the signal.
55
55
 
56
- - **For `storage=` tables, how queries were routed.** `publisher_query_route_total{leg, outcome, reason}` on the metrics endpoint counts each serving leg the router considered: `used` when it answered, `skipped` with the reason, and `fallback` when its stored run failed and live answered, and each query response's `servedFrom` says it per query. For a table built in the source's own warehouse there is no route counter, but each response's `servedFrom` reads `database` when one answered, so a log of responses measures it. Say so when it matters.
56
+ - **How queries were routed.** `publisher_query_route_total{leg, outcome, reason}` on the metrics endpoint counts each serving leg the router considered: `used` when it answered, `skipped` with the reason, and `fallback` when its stored run failed and live answered, plus `leg="extract"` for a query that read an extract, and each query response's `servedFrom` (`database` when a stored table answered) says it per query.
57
57
 
58
58
  ## Step 3: Analyze and recommend
59
59
 
@@ -61,7 +61,7 @@ Weigh rebuild cost against query benefit. Common findings:
61
61
 
62
62
  - **Materialize candidate:** an expensive, frequently-queried source that is _not_ materialized (recomputed on every query). Recommend adding `#(materialize)`. Strongest when the source is a heavy aggregate/join reused by many queries and its inputs change slowly. If the source carries a `#(access_filter)` gate, check which case it is first. A gate reached only through a `join_*`, a row filter inherited from a source it derives from or extends, or a gate not classifying as a row filter, means the materialization is **refused** - the build skips it and it serves live - so do not recommend materializing it at all. Where the gate is the source's own row filter it is admitted, and then only recommend it alongside a freshness window (`freshness.fallback="live"`): the gating column freezes at build time, so without one a revoked row can be served under its old access decision indefinitely (see `access-filter.md`).
63
63
  - **Removal candidate:** a materialized source that is cheap to compute, rarely queried, or rebuilt far more often than it is read. Recommend dropping the `#(materialize)` annotation (and its table): the storage + rebuild cost is not buying anything.
64
- - **Chain candidate:** a `storage=` rollup whose intermediates re-read the warehouse on every build while a stored root already holds the rows. First try annotations: `#(materialize)` on the intermediates or the sources they join, so every leg lands on a stored table, or a `#(rollup)` on the stored root's measure in place of a query-shaped rollup source (a query-shaped `#(materialize)` source over another is built from the warehouse, not over its table; `chaining.md`). Rewiring the intermediates onto the stored root (moving declarations, a new extension with its own `#(materialize)`, joins re-pointed at stored siblings - `chaining.md`) changes the model's shape: a tier-2 change (`reference/estimating.md`), shown as its own diff and approved on its own. Then read `upstreamReuse` on the next run to confirm the chain holds. Keep a self-join or a wide hash aggregate over a large fact **in the warehouse**: chained, it builds in the destination's engine under its memory bound.
64
+ - **Chain candidate:** a stored rollup or source whose intermediates recompute from raw on every build while a stored root already holds the rows. First try annotations: `#(materialize)` on the intermediates or the sources they join, so every leg lands on a stored table, or a `#(rollup)` on the stored root's measure in place of a query-shaped rollup source (a query-shaped `#(materialize)` source over another is built from the warehouse, not over its table; `chaining.md`). Rewiring the intermediates onto the stored root (moving declarations, a new extension with its own `#(materialize)`, joins re-pointed at stored siblings - `chaining.md`) changes the model's shape: a tier-2 change (`reference/estimating.md`), shown as its own diff and approved on its own. Then read `upstreamReuse` on the next run to confirm the chain holds.
65
65
  - **Denominator candidate:** a ratio whose numerator is a rollup and whose denominator counts the fact table per query. Lead with `#(rollup)` on the denominator's existing measure at the grain the ratio reads. A new source holding the denominator at its own grain is a tier-2 shape change, proposed only if the rollup falls short, with its own diff and approval.
66
66
  - **Cadence mismatch:** a scheduler cadence out of step with how fast the data changes or how long a build takes. If the build's `durationMs` approaches the interval, the cadence is too aggressive. If queries routinely read stale data, tighten it. For an incremental source, `refresh: delta` with small `buildDurationMs` per fire is the cheap steady state; `refresh: full` every fire means the boundary is being lost (read the reason).
67
67
  - **Scope mismatch:** `scope: version` re-materializes per published version (right when versions must be isolated, e.g. a schedule); `scope: package` reuses one lineage across versions (cheaper when versions can share). A schedule _requires_ `version`. If a package carries a schedule it does not need, clearing it is step one; the scope itself is edited in `publisher.json` (the CLI does not move it back).
@@ -85,7 +85,7 @@ Frame each recommendation with the evidence from Step 2 (the run IDs, timings, b
85
85
  malloy-pub delete materialization <old-id> --environment <env> --package <pkg>
86
86
  ```
87
87
 
88
- > Deleting a run is **record-only**: it never drops a table. It re-derives the package's serve bindings from the latest remaining ready run (or clears them to serve live), so a delete does not break queries. To drop the old table, read its `physicalTableName` from the old run's manifest, check that no remaining ready run, of any version, names a table with that name in any place (the runs list answers for the latest version only, so list each version's runs with `versionId`; with the stable names an auto-run assigns, a table the new run carried forward is still served, and two destination names can reach one DuckLake), then drop it: a database table through `DELETE …/packages/{pkg}/connections/{connectionName}/materializedTables/{physicalTableName}`, which makes that check itself and refuses a table it cannot prove is the package's and unused (pass `?materializationId=<run>` for a table built before 0.16.0), a `storage=` table through the admin API.
88
+ > Deleting a run is **record-only**: it never drops a table. It re-derives the package's serve bindings from the latest remaining ready run (or clears them to serve live), so a delete does not break queries. To drop the old table, read its `physicalTableName` from the old run's manifest, check that no remaining ready run, of any version, names a table with that name in any place (the runs list answers for the latest version only, so list each version's runs with `versionId`; with the stable names an auto-run assigns, a table the new run carried forward is still served), then drop it through `DELETE …/packages/{pkg}/connections/{connectionName}/materializedTables/{physicalTableName}`, which makes that check itself and refuses a table it cannot prove is the package's and unused (pass `?materializationId=<run>` for a table built before 0.16.0). An extract's generation is dropped through `DELETE …/packages/{pkg}/storageDestinations/{destinationName}/materializedTables/{tableName}` instead.
89
89
 
90
90
  - **Change the schedule / cadence:**
91
91
 
@@ -103,4 +103,3 @@ After applying, re-run Step 2 on the next few builds to confirm the change did w
103
103
  ## What this skill does not do
104
104
 
105
105
  - It does not decide for the user or apply changes silently; every edit needs an explicit go-ahead.
106
- - It cannot measure reads of a table built in the source's own warehouse (only the storage tier reports routing), so "rarely queried" there is a judgment from the model and the user's knowledge, not a measured metric. Say so when it matters.
@@ -9,17 +9,17 @@ Symptom: the source still recomputes on every query. Each rung names the field t
9
9
 
10
10
  0. **Did a build actually run?** First read the answer's `servedBy.mode`, or the server's simulation setting: a simulated item's summary reads `built` with `mode: "simulated"`, so `state` alone does not tell you a table exists. **In simulation, every answer's rows are live by design** (`measuredOn: "live"`): the question there is whether `servedBy` names the table, and no build runs at all, so `malloy-pub materialize` answers 409 `SIMULATION_ACTIVE`. For a real local build, restart without `--materialize-simulate`. On a standalone Publisher that is not simulating, publish/load does **not** build - run `malloy-pub materialize` (or enable the scheduler). "Publishes fine, no table" is the *expected* standalone state, not a model bug. On a hosted deployment the build is automatic but best-effort, so a failure is silent - look for a `FAILED` run, and for a ready run with `failures`.
11
11
  1. **`awaiting_build`** (`serves: after_build`). Nothing is bound yet: no build has bound a table (rung 0). This is not the `*-not-built` warning, which means refused.
12
- 2. **`not_buildable`.** Planned, but a build here skips it, for `reason`: `destination_missing` (`storage=` names a destination this environment does not configure; add it, or drop `storage=`), `connection_cannot_hold_table` (built in its own warehouse on a connection that creates no tables; add `storage=` to build it into a storage destination, or drop the annotation), `upstream_unread` (its table was withdrawn after a failed recompile, reload or publish, and an upstream table it was built from could not be read; fix the upstream's read and reload), or `materialization_off` (a `#(materialize)` source in a package none of whose model files has a served copy: every one is a notebook or a report). The item's `fixes` say what to change.
12
+ 2. **`not_buildable`.** Planned, but a build here skips it, for `reason`: `connection_cannot_hold_table` (built in its own warehouse on a connection that creates no tables; drop the annotation), `upstream_unread` (its table was withdrawn after a failed recompile, reload or publish, and an upstream table it was built from could not be read; fix the upstream's read and reload), or `materialization_off` (a `#(materialize)` source in a package none of whose model files has a served copy: every one is a notebook or a report). The item's `fixes` say what to change.
13
13
  3. **`refused`** (serve verdict `live`, reason `refused`). The package's warnings name each declaration Publisher will not build (`materialize-not-built`, `rollup-not-built`, `persist-view-not-built`, `persist-query-not-built`); `GET …/packages/{pkg}/build-plan` lists them in `refusedSources`, each with its `reason`, and under `omittedSources` any the planner itself failed on. The reasons you will meet most:
14
- - **`upstream_table_unusable`**: a chained build cannot read its upstream's table where it runs. The message names the upstream and why: an intermediate reaches the warehouse, the upstream is in another destination or tier, or a **collation refusal**. Either the build groups, filters or orders a string its upstream's table records as compared otherwise than live ("which the table of its upstream '…' records as compared by … only"), or, in a legacy `#@ persist` chain, it reads one Publisher could not trace to a stored upstream's column ("the base its strings are read on is not named", or a message naming raw SQL or a join to a source not stored in the destination). The first is `reference/storage.md` § Collation; the second is the named-base rule in `reference/chaining.md`, whose fixes are shape changes that need approval.
14
+ - **`upstream_table_unusable`**: a chained build cannot read its upstream's table. The message names the upstream and why (for example an upstream that is itself refused, so it has no table); see `reference/chaining.md`.
15
15
  - **`free_parameter`**: the source has a parameter left unbound, so it is a template instantiated per query, with no single relation to store. Store a query source over a bound invocation instead, `source: s1 is s(x is 1) -> { select: * }`, with `#(materialize)` on `s1`. That adds a source, so it is a shape change: show the diff and get approval.
16
16
  - **`bound_invocation_unkeyable`**: the source extends a bound invocation of a source that reads the parameter it binds (`source: e is s(x is 50) extend { … }`), whose build cannot be keyed. Write it as a query source over the invocation, `s(x is 50) -> { select: * } extend { … }`, which is stored; that rewrites the source's definition, so it is a shape change. **`address_unresolved`**: a run could not key some other shape of source; that source alone is not built, the rest of the package is, and its message carries Malloy's error.
17
- - **`storage_source_unsupported`**: `storage=` on a connection the storage tier cannot build from (the package's DuckDB sandbox, an environment DuckDB connection), or, in a destination's own catalog, a source with raw SQL or a file read. Drop `storage=`, or move the source to a warehouse connection.
18
- - **`inherited_persist`**: rare. Publisher could not tell a source's own notes from those it inherits along a v1 `#@ persist` chain, so it refuses the source alone (a `persist-not-built` warning) and it answers live; read the message. **`needs_qualified_name`**: a BigQuery database table with no dataset in `name=`. An inherited given or gate: move it onto the materialized source itself (`reference/storage.md`, `reference/access-filter.md`).
19
- 4. **`failed`, or a ready run's `manifest.failures`.** These are what only a run can find. Two of them name, in `staleUpstreams`, the upstreams that clear them: **`upstream_contract_insufficient`** (an upstream's manifest entry carries no column contract this build can read) and **`upstream_contract_unread`** (an upstream's contract records a string verdict its build's catalog read never obtained). Both are retryable, not refusals: the source builds once those upstreams are rebuilt. A control plane rebuilds them for you. On a standalone server, build the named upstreams with `forceRefresh` and `sourceNames` (`POST …/materializations` with `{"forceRefresh": true, "sourceNames": [...]}`), then build the downstream again. If the upstream's rebuild still cannot read its catalog, the downstream keeps failing `upstream_contract_unread`, and the upstream's build log says why.
20
- 5. **`served_copy`: built but not served.** A `served-copy-not-served` warning, or a serve verdict `live` / `served_copy`, means the table exists but the served copy cannot answer from it. `notServedIn` names each model and its reasons (a base whose block cannot be carried, fields not carried, a join the destination cannot reach). A reason `not_rerooted` (the served copy left the bound source as written and named no other reason) is a Publisher defect, not a model mistake: report it rather than reshaping the model.
21
- 6. **Other verdict reasons.** `stale` (past its freshness window), `contract_missing` or `incompatible` (the bound table no longer holds what its contract records; rebuild it), `row_level_gate`, `shadowed` (its storage table is bound, but every model's source of that name is another source), `upstream_unread` (as in rung 2), and `unreachable` (nothing on the published surface reads it). The verdict's `fixes` say what to change.
22
- 7. **Does the query take a path the table cannot answer?** Read the path report's `considered`: each skipped table carries a `reason` (and often a `code` and `detail`). `NOT_BUILT` (no table bound: build it), `NOT_SERVED` (its verdict is `live`, `code` naming the verdict's reason, or the served copy declined this one query, `code` `served_copy`), `OPTED_OUT` (`#@ -persist`), `MISSING_FIELD` (a field the table lacks, a nested column among them), `SHAPE_MISMATCH` (not a call of the persisted view or query), `ROW_LEVEL_GATE`, `GRAIN_TOO_COARSE` (a rollup's grain does not cover the query's groups or filters), `TIME_ZONE`, `CROSS_CONNECTION` (a join the table's connection cannot reach), `COUNT_SEMANTICS`, `STALE`, `READ_FAILED` (chosen, but the read failed and live answered). A skip a leg declined also names its `declineCode` (`served_copy_filter_comparison`, `served_copy_result_order_comparison`, ...), and a string comparison a stored table does not reproduce names its `comparison`: the `field` it compares, how that field compares at its source (`compare`) and `why` (`strings_unread`: its comparison could not be read; `collation_mismatch`: it compares under a collation the stored table does not keep; `caller_collate`: the query's own SQL sets one). `notConsidered` lists nearby tables this query cannot use (a sibling's, or an extension's), which is where moving the query or an annotation would help. Each is decided per query; the source's other queries still read the table.
17
+ - **`managed_author_sql`**: a source on a managed DuckLake connection with raw SQL (`.sql()`, a `sql_*` expression) or a file read beneath it, which a build in that catalog does not run. Write it in Malloy over the catalog's tables, or leave it unmaterialized (`reference/serving.md`).
18
+ - **`inherited_persist`**: rare. Publisher could not tell a source's own notes from those it inherits along a v1 `#@ persist` chain, so it refuses the source alone (a `persist-not-built` warning) and it answers live; read the message. **`needs_qualified_name`**: a BigQuery database table with no dataset in `name=`. An inherited given or gate: move it onto the materialized source itself (`reference/serving.md`, `reference/access-filter.md`).
19
+ 4. **`failed`, or a ready run's `manifest.failures`.** These are what only a run can find: each failure carries its `reason`, a `code` where a client may branch on it (`schema_incompatible`, `contract_capture_failed`, `table-owned-elsewhere`, ...), and whether it is `retryable`. To rebuild one source on a standalone server, `POST …/materializations` with `{"forceRefresh": true, "sourceNames": [...]}`.
20
+ 5. **`served_copy`: built but not served.** A `served-copy-not-served` warning, or a serve verdict `live` / `served_copy`, means the table exists but the served copy cannot answer from it. `notServedIn` names each model and its reasons (a base whose block cannot be carried, fields not carried, a join read as written). A reason `not_rerooted` (the served copy left the bound source as written and named no other reason) is a Publisher defect, not a model mistake: report it rather than reshaping the model.
21
+ 6. **Other verdict reasons.** `stale` (past its freshness window), `contract_missing` or `incompatible` (the bound table no longer holds what its contract records; rebuild it), `row_level_gate`, `upstream_unread` (as in rung 2), and `unreachable` (nothing on the published surface reads it). The verdict's `fixes` say what to change.
22
+ 7. **Does the query take a path the table cannot answer?** Read the path report's `considered`: each skipped table carries a `reason` (and often a `code` and `detail`). `NOT_BUILT` (no table bound: build it), `NOT_SERVED` (its verdict is `live`, `code` naming the verdict's reason, or the served copy declined this one query, `code` `served_copy`), `OPTED_OUT` (`#@ -persist`), `MISSING_FIELD` (a field the table lacks, a nested column among them), `SHAPE_MISMATCH` (not a call of the persisted view or query), `ROW_LEVEL_GATE`, `GRAIN_TOO_COARSE` (a rollup's grain does not cover the query's groups or filters), `TIME_ZONE`, `COUNT_SEMANTICS`, `STALE`, `READ_FAILED` (chosen, but the read failed and live answered). A skip a leg declined also names its `declineCode` (`served_copy_filter_comparison`, `served_copy_result_order_comparison`, ...), and a string comparison a stored table does not reproduce names its `comparison`: the `field` it compares, how that field compares at its source (`compare`) and `why` (`strings_unread`: its comparison could not be read; `collation_mismatch`: it compares under a collation the stored table does not keep; `caller_collate`: the query's own SQL sets one). `notConsidered` lists nearby tables this query cannot use (a sibling's, or an extension's), which is where moving the query or an annotation would help. Each is decided per query; the source's other queries still read the table.
23
23
 
24
24
  **A 403 is not a live answer.** A 403 with `reason: INHERITED_FILTER_UNVERIFIED` ("could not be verified here … This is not a permission rule") is neither a materialization reason nor a gate's denial. A `where:` the source inherits could not be verified to read the fields it was written against, which is a problem in the model's own text. Supplying givens will not help: the model's author fixes the model (`malloy-source-unreachable` covers it).
25
25
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-model
3
3
  description: Build Malloy semantic models with base source and joined source files. Use when creating or modifying .malloy files, user asks to "create a malloy model", "add dimensions", "add measures", "create a source", or any Malloy model authoring task.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
 
7
7
  <!--
@@ -298,7 +298,7 @@ Each extension replaces the base's `false` on the lock route with its own rule.
298
298
  - **A gate inherited through `->` filters the derivation's input.** In `source: shares is sales -> { group_by: region, category; aggregate: total, share is total / all(total) }` over a source gated `region = $REGION`, the gate filters `sales`'s rows before the derivation runs, so `all()`, `exclude()`, window functions, `calculate:`, a top-N `limit` and a rename onto the gate's field name all see only the caller's rows, and the derivation need not keep the gate's column. A chain applies it at the innermost base. A gate declared on the derived source itself filters that source's output, after its query has run over every base row; declare it there only when that is the intent. A base that hides the gate's column (`sales extend { except: region } -> { … }`) leaves the gate nothing to filter, and every query is denied.
299
299
  - **A derivation that drops a column the gate reads fails CLOSED.** `extend { except: org_id }`, or an `accept:` that omits it, leaves the grafted filter unable to compile, so the request is denied rather than served ungated. The one hole to know: dropping the gated column and then `rename:`-ing a _different_ column onto that exact name grafts successfully and binds the gate to the wrong column. Narrow, but real, so don't recycle a gated column's name. If a derivation's own projection needs to drop the column a row-level term would read, use a source-level term (`'literal' in/= $GIVEN`) instead, since it never depends on any projected column.
300
300
  - **The quoted-string and file-level forms are refused at load and no longer exist.** A quoted expression on the `source:` line, in either quote, a file-level `##(…) "<expr>"` applying to every source in the file, and the earlier `internal dimension: authorized is <expr>` form are all retired; the load names the rewrite. Every `.malloy` file in a package compiles at load and any failure aborts the package, so a retired-form gate anywhere in the package is refused. Only a declaring file _outside_ the package escapes that: it loads and denies every request instead, with no compile-time hint. See your deployment's reference documentation.
301
- - **A gated source can be materialized, but the gating column freezes.** `#(materialize)`, database or `storage=`, is admitted when the gate is provably the entry point's own row filter (a `storage=` table holds every caller's rows, ungated, in the destination), and a `#(rollup)` only where its gate holds on the rollup's rows. The gate still runs live on every query, so rows come back filtered - but the column it filters ON is frozen at build time, so a row whose access decision changes keeps being served under the old decision until the next rebuild. Pair `#(materialize)` on a gated source with a freshness window (`fallback="live"`), which is the only control that bounds that - and read `skill:malloy-materialization` for where that window binds.
301
+ - **A gated source can be materialized, but the gating column freezes.** `#(materialize)` is admitted when the gate is provably the entry point's own row filter (its table holds every caller's rows, ungated, in the warehouse), and a `#(rollup)` only where its gate holds on the rollup's rows. The gate still runs live on every query, so rows come back filtered - but the column it filters ON is frozen at build time, so a row whose access decision changes keeps being served under the old decision until the next rebuild. Pair `#(materialize)` on a gated source with a freshness window (`fallback="live"`), which is the only control that bounds that - and read `skill:malloy-materialization` for where that window binds.
302
302
 
303
303
  > **Trust caveat.** Givens are **caller-asserted**, anyone who can reach the query API can claim a favorable given, e.g. `{"ROLE":"admin"}`. Neither annotation is a real boundary unless it sits behind a trusted tier that sets givens from its own verified context, never directly from an untrusted caller. Neither is, on its own, end-user authentication. Publisher is a microservice that runs locally with the user's own permissions or inside their cloud behind that gateway, so say so whenever you describe what a gate protects.
304
304
  >
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-model-as-you-go
3
3
  description: 'After answering a data question, write down what the answer assumed so the next reader can trust the number. A field with a #(doc) in the model when you can edit it, an extend in the notebook when you can only author reports, or a stated assumption plus a Malloy snippet when you can only chat. Use after every answered question that rested on a judgment call, and whenever a question is asked against tables that have no model yet.'
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
 
7
7
  <!--
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-modeling
3
3
  description: Build semantic models with Malloy for the Malloy Publisher. Read this skill whenever the user asks about modeling data or specifically mentions Malloy.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!--
7
7
  Copyright (c) Credible Data Inc.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-notebooks
3
3
  description: "Renamed to malloy-reports. A notebook is now a report with layout=linear: a .malloy file with an ## artifact tag, written at the package root. Load malloy-reports instead when the user asks for a notebook, a data story, or a report that reads top to bottom."
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
 
7
7
  <!--
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-phrase-detection
3
3
  description: How to phrase search_text on a get_context call so retrieval returns the fields you need instead of a truncated catalog. Covers target-type classification and decomposition patterns.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!-- Copyright (c) Credible Data Inc. SPDX-License-Identifier: MIT -->
7
7
 
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-powerbi-review
3
3
  description: Move a Power BI semantic model (TMDL, PBIP, or .pbix) onto Malloy - read their model, transpile its DAX, and prove the numbers match. Use when Power BI artifacts are present, when a user wants to migrate or switch off Power BI, and whenever a specific DAX measure has to become Malloy - CALCULATE, ALL/ALLSELECTED/ALLEXCEPT, RANKX and top-N, time intelligence, USERELATIONSHIP, calculation groups, what-if parameters, or an RLS role. Carries a worked, executed transpile per construct and states what each port costs. Works with or without a database connection.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!--
7
7
  Copyright (c) Credible Data Inc.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-publish
3
3
  description: Package Malloy models for serving by Malloy Publisher. Use when user asks to "publish", "package", "deploy", or wants to share models with others.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!--
7
7
  Copyright (c) Credible Data Inc.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-queries
3
3
  description: Read before writing or debugging a Malloy query. Dates, aggregates vs dimensions, joins, filters, strings, window functions, chart annotations, and the compile errors a SQL habit produces.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!--
7
7
  Copyright (c) Credible Data Inc.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-reports
3
3
  description: "Build or modify a Malloy Publisher report: a .malloy file with an ## artifact tag, written at the package root unless asked otherwise, laid out as a grid (a dashboard, scanned at a glance) or linear (a notebook or data story, read top to bottom), with filter controls rendered from givens and # drill click-through. Use when the user asks for a dashboard, a notebook, a report, a data story, a filterable view, or drill-through between views, and no code is wanted."
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
 
7
7
  <!--
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-review
3
3
  description: Malloy semantic-model code review. Invoke when the user asks to review, audit, or critique a `.malloy` file, a folder of Malloy models, or a GitHub PR that touches Malloy. Enforces project modeling standards and emits a navigable review file.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!--
7
7
  Copyright (c) Credible Data Inc.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-run-workflow
3
3
  description: Use a workflow or skill set a Malloy package declares, by name. Use only when the user names a package workflow or skill set, for example "run the weekly-report workflow on storefront" or "use the analyst skill set in this package". Fetches the definition with get_workflow or the set with get_skill_set, installs the skill sets, and runs the workflow's instructions when asked to run it.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!--
7
7
  Copyright (c) Credible Data Inc.
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: malloy-source-unreachable
3
3
  description: Work out why a source is missing from get_context, or why a query against it was refused with a 404 or a 403, and what to do next. Use when a source you expect is absent from discovery, when execute_query answers "No queryable source", when a query that used to work stops working, or when deciding whether a package's curation is hiding something you need.
4
- version: 0.1.67
4
+ version: 0.2.0
5
5
  ---
6
6
  <!-- Copyright (c) Credible Data Inc. SPDX-License-Identifier: MIT -->
7
7
 
@@ -1,85 +0,0 @@
1
- <!--
2
- Copyright (c) Credible Data Inc.
3
- SPDX-License-Identifier: MIT
4
- -->
5
-
6
- # The storage tier: `storage=`, and how a stored table is served
7
-
8
- By default a materialized source is built **in its own connection** (database): the warehouse runs the build and the table lands beside the data. `#(materialize) storage="<destination>"` builds it into a **storage destination** the environment declares instead - today a DuckLake catalog over local or object storage - and serves it from there, so a query served from the table never runs in the warehouse at all.
9
-
10
- ```malloy
11
- #(materialize) name="daily_orders" storage="lake"
12
- source: daily_orders is orders -> { group_by: order_date; aggregate: total is amount.sum() }
13
- ```
14
-
15
- - `storage=` names a **storage destination**, never a connection. Destinations are declared on the environment (`storageDestinations: [{ "name": "lake", "type": "ducklake", "ducklakeConnection": { "catalog": {...}, "storage": {...} } }]`, by config or by environment PATCH); a build naming one the environment does not hold fails the run with a `DestinationNotFoundError`. Reads of the environment report a destination's name and type only, never its config.
16
- - The build is a native **query passthrough**: the source warehouse (Postgres, BigQuery or Snowflake) computes the source and only the result crosses into the store, through DuckDB. A source on any other connection, the package's DuckDB sandbox (`duckdb.sql(...)`, `duckdb.table(...)`) and an environment DuckDB connection included, is refused at load: it is not built, it is answered live, and the route's `*-not-built` warning (reason `storage_source_unsupported`) names the connection. Drop `storage=` to build it in its own connection, or move the source to a warehouse connection. A DuckLake source builds only into its own catalog. A source with a row-level gate of its own (`#(authorize)`, `#(access_filter)`) is admitted here as on the database tier, and its table puts every caller's rows, ungated, at rest in the destination, where anyone with direct access to it reads them: say so before choosing this tier. An inherited gate, or one reached through a join, is refused (`reference/access-filter.md`).
17
- - **A source already in the destination's own catalog is the exception to the passthrough** (the gate rules above still apply): a DuckLake connection whose catalog is the destination's, matched not by name but by the catalog database's `host`, `port` and `databaseName` (a `connectionString` config never matches), its metadata schema, and its data path when both configs state one (`docs/ducklake.md`). Its build runs inside the catalog with no passthrough. That session can write the catalog, so it runs only SQL Malloy generated: a source with `.sql()` or a `sql_*` expression anywhere beneath it is refused, as is a table read from a file or URL: refused at load (`materialize-not-built`, reason `storage_source_unsupported`) and answered live, never left to fail its build. On a connection configured `managed` this holds without `storage=` too, since a managed catalog's tables are always built inside it. It uses the DuckDB dialect, so `refresh="incremental"` is refused on it, as on any DuckDB source.
18
- - The tier is always on: a `storage=` source is built into its destination and served from it, never built in the database tier instead. The former `PERSIST_STORAGE_MODE` switch was removed; a server that still sets it warns at startup that it is ignored. A `storage=` source that "did nothing" was not built (no run, or a server in simulation), refused (its `*-not-built` warning), or not served (its serve verdict); see the main skill's **Why does this answer live?**
19
- - **Hidden columns are stored.** A `storage=` table holds every column its source declares, `private:` and `internal:` ones included (a renamed one under the name its query gives it; an `except:`-ed one not at all, unless another source with identical SQL shares the table and stores it), and the served copy hides them again: a measure over a hidden column is answered from the table, and a caller is refused a hidden column in live's words. The values are at rest in the destination, readable by anyone with direct access to it, never through Publisher. To keep a value out of the destination, leave it out of the source's query, do not just hide it. `#(carries)` checks what a caller can reach, not what a table stores.
20
- - A package may name several destinations; each source routes to its own.
21
- - `partition=` is not supported: a stored table is written unpartitioned, and a package whose `#(materialize)` carries `partition=` fails the publish and the load (`materialize-retired-key`). Remove the key; it was a layout only, so the cost is scan time and no answer changes.
22
-
23
- ## Collation: the destination compares bytes
24
-
25
- A storage destination compares strings **byte for byte**: `'a' = 'A'` is false there, and strings order by their bytes. The source warehouse may not: a Postgres column under a case-insensitive or locale collation, a BigQuery column with a collation, a DuckDB instance with a `default_collation`. A stored table can only answer what it compares as live does, so Publisher judges every string comparison on the destination side against the source side:
26
-
27
- | How the source compares a string column live | Downstream of a stored copy, it may be |
28
- |---|---|
29
- | byte order (a binary collation: Postgres `C` / `POSIX` / `C.UTF-8`, BigQuery or DuckDB with no collation) | grouped, filtered and ordered |
30
- | deterministic, but not byte order (a Postgres ICU or libc locale collation) | grouped and compared by equality, **not ordered** |
31
- | nondeterministic (case- or accent-insensitive) | neither: answered live |
32
- | not known (the connection cannot report collation, or its read did not complete) | neither, until it is known |
33
-
34
- What it means:
35
-
36
- - **A query over a stored table** that groups, filters or orders a string the destination would compare unlike live is answered live for that query only; its path report names the skip. The source's other queries still read the table.
37
- - **A chained build** (a `storage=` extension with its own `#(materialize)` over a parent stored there, or a legacy `#@ persist` chain) runs in the destination, so each string it groups, filters or orders must be one its **upstream's table records as compared like live**, in the column contract the upstream's build wrote (`compare`). Otherwise it is refused at plan, `upstream_table_unusable`, "it groups or compares 'x', which the table of its upstream 'y' records as compared by … only", and the message ends with what to do: drop `storage=` here and on the upstreams it reads so the chain builds in the warehouse, or, where the upstream's warehouse reports collations, make its read find byte order and rebuild the upstream: on Postgres, give the column the `C` collation (on the table's column, or a `COLLATE "C"` in the upstream's SQL); on DuckDB, compare it as bytes (no `default_collation` on the instance and no `COLLATE` in any table, view or macro it holds, the upstream's build included, since even a binary one reads as unknown); on BigQuery, remove the collation from the tables the upstream's build reads, and any `COLLATE` from its SQL (a collated dataset elsewhere in the project can also leave it unknown). In a legacy `#@ persist` chain, a string it compares that Publisher could not trace to a stored upstream's column (through a named base or an inline extend) is refused too; the remedies are the named-base rule in `reference/chaining.md`.
38
- - **An upstream's string columns are the thing to read before chaining.** A column whose source collates by locale can be grouped downstream but not ordered; one whose collation is case-insensitive can be neither. Collation is read only on DuckDB, Postgres and BigQuery: a Snowflake, MySQL or Trino column's collation is not known, so a chained build that compares a string from one is refused. An upstream whose contract says its catalog read did not complete fails the downstream's build `upstream_contract_unread` (retryable: rebuild that upstream, the main skill's ladder). On BigQuery an `.sql()` source's strings are read column by column from a dry run of its SQL; when they cannot be (setup SQL on the connection, a failed dry run, a referenced table holding a collated column, ...), the package's `stored-strings-compare-unknown` warning names the table, the columns and the fix.
39
- - **The database tier keeps the warehouse's own collation.** When a chain over strings cannot satisfy the destination, build that chain in the warehouse (no `storage=` on the downstream or on the upstreams it reads, since a database table cannot read a `storage=` one) rather than reshaping the model. That is an annotation change, so it belongs in the first tier of `reference/estimating.md`.
40
-
41
- In simulation, each string column's collation is read off the build SQL (`WHERE false`), as a real build's contract capture reads it, and recorded on the predicted contract (fact `collation`, `basis: exact`, `method: build_sql`), so a collation refusal or a `NOT_SERVED` skip shows on the local server before anything is built. On a dialect whose collations are not read (Snowflake, MySQL, Trino and others), or a column whose read did not answer, the fact is `not_knowable_locally`, and a database string column whose read failed is recorded as compared by nothing (`compare: none, compareFrom: unread`), never as if it had been read.
42
-
43
- ## Where a given may sit
44
-
45
- A materialized table is built once, with no caller present, so a `given` has to be somewhere the build never reads it.
46
-
47
- - **In the materialized source's own `where:` - honoured per caller.** `#(materialize) storage="lake"` on `fact is raw extend { where: org_id = $ORG_ID }` leaves the term out of the build, stores every caller's rows in one table, and re-applies the term per caller at read. One table serves every tenant, and a term a caller writes on an extension of it still scopes what is read. A dimension of its own that reads a given is not stored; the served copy computes it at read.
48
- - **Inherited from a base - refused, answered live.** `#(materialize)` on `r is scoped extend { ... }`, where `scoped is raw extend { where: org_id = $ORG_ID }`, is not built: only the materialized source's own declaration is re-applied over its table at read. It is refused with a `materialize-not-built` warning and answers live, correctly but at live speed. The same holds for a given-reading dimension a base declares. To serve it from a table, move the given-reading `where:` onto the materialized source itself, and let extensions that materialize nothing read its table. An extension that declares its own `#(materialize)` over such a parent is refused too (`upstream_table_unusable`), and its queries are answered from the parent's table.
49
- - **Inside a persisted view's or named query's result - refused.** A view or query whose result reads a given differs per caller, so it is not built (`reads_given`, `persist-view-not-built` / `persist-query-not-built`).
50
-
51
- A `#(access_filter)` gate is the same shape with a different source of truth; see `reference/access-filter.md`.
52
-
53
- ## Shaping a rollup for its reads
54
-
55
- A stored rollup pays at build time so that reads are cheap; the grain and the inputs decide whether they are.
56
-
57
- - **Grain to the reads, not to the data.** Group by exactly the columns the queries filter or group by. Every extra dimension multiplies the row count, and a rollup that approaches the fact table's size saves nothing.
58
- - **A source's own filters shrink its table.** The `where:` a materialized source already declares is applied by the build. A term that reads a given is left out of the build and re-applied at read, and a rolling time window is re-applied at every read.
59
- - **A distinct count needs its field in the grain.** `#(rollup)` stores `count(x)` only when `x` is a grain entry (`grain=["region", "customer_id"]` for `count(customer_id)`); the rollup keeps one row per value of `x`, and a coarser query counts the stored values, exactly. With `x` outside the grain the load fails (`rollup-not-mergeable`). Size the grain before adding `x`: a high-cardinality `x` can make the rollup nearly as large as the fact, so check its rollup reduction and flag it under 10x (`reference/estimating.md`).
60
- - **An average is a sum and a count, rolled up, and a measure over them.** Put `#(rollup)` on the sum and the count at the grain the reads need, and declare `avg is total / nullif(n, 0)` with no line of its own: it is served from any rollup that stores both. A measure with an aggregate of its own (`total / count()`) or a filter on a dimension is not, without a `#(rollup)` line of its own; one with `all()` or `exclude()` cannot be rolled up. Their queries answer live with `MISSING_FIELD`. Publisher 0.18.9 and earlier serve the declared average only with its own `#(rollup)` line at the parts' grain, so when the path report skips the rollup with `MISSING_FIELD` for it, add that line.
61
- - **Give a ratio both halves.** A percentage whose numerator is a rollup and whose denominator is a count over the fact table still scans the fact per query. Put `#(rollup)` on the denominator's existing measure at the same grain first.
62
-
63
- Three more shapings change the model, so each is a tier-2 change (`reference/estimating.md`), proposed only after the annotations above fall short, as its own diff with its own approval: adding a `where:` to bake a filter into a source, a new source holding the denominator at its own grain, and `except:`-ing columns no reader uses from a wide stored copy.
64
-
65
- ## How a stored table is served
66
-
67
- A query against a package with bound tables is compiled over the **served copy**: your own files, held in memory, with each materialized source's definition replaced by its stored table under the same name. Its `extend` blocks, annotations and every other line are your text, so an extension, a join to it, a view, a named query or a source in a file that imports it reads the stored table with no change to how it is written. A reader whose query or joins reach a source that is not materialized there - a warehouse table, or a stored source whose table is stale past its freshness window - is served **live** instead.
68
-
69
- Routing is decided per query, not per source, so one source can serve some queries from its table and others live:
70
-
71
- - **A join to a source not stored with it** serves live for the queries that traverse it; queries on the fact's own fields still route to the table. A join between two sources stored in one destination routes both legs.
72
- - **A nested column** (`nest:`, a repeated record) a destination cannot hold as one is left out of the stored source, so every query that traverses it answers live while the scalar columns serve from storage. The source looks fully materialized and is, for its flat fields.
73
- - **The served copy reads the author's own text** over the stored table (its views, joins, measures and filters as written), so nothing is thinned: a source whose re-root does not compile is left as written and answers live, with a `served-copy-not-served` warning, and the model's other stored sources still serve.
74
- - A **stale** table (past its freshness window, with `fallback` `live` or `fail`) leaves the serving set, and a run-time store failure under `fallback: live` degrades that query to live.
75
-
76
- What the server reports:
77
-
78
- - `QueryResult.servedFrom`: `storage` when the tier answered, `database` when a table in the source's own database did, `live_fallback` when the tier was bound but a run-time store failure degraded the query to a live recompute, and empty when no table answered (no binding, or an ineligible query; the path report says which).
79
- - The package's `storageServeBindings`, in its serving state at `GET /api/v0/environments/{env}/packages/{pkg}/status` (an older server: its entry in `GET /api/v0/status`, or the package read), lists the stored tables the package is currently bound to, with each entry's origin. `manifestEntryCount` does not count them.
80
- - `publisher_query_route_total{leg, outcome, reason}` counts each leg the router considered (`used`, `skipped` with the path report's reason, `fallback` when a stored run failed and live answered), and each query's path report names the table that answered (`servedBy.via: served_copy`) or why each one was skipped.
81
- - A query's full result carries the SQL it ran; served from the store, its `FROM` names the destination and the physical table.
82
-
83
- ## Rollups use the same tier
84
-
85
- `#(rollup) grain=["category", "order_day"]` on a **measure** stores a rollup Publisher derives at that grain and routes to it when a query groups by a subset of the grain; queries do not change. Write one line per grain. It builds through the same plan, manifest and scheduler as `#(materialize)`, inherits the base source's freshness, and refuses a gated source unless its gate holds on the rollup's rows (`reference/access-filter.md`). A rollup on a measure the published surface hides is not built; the package loads and warns. A hidden (`private` or `internal`) grain dimension is stored and stays hidden; a `where:` of the source's own that reads a given over grain dimensions is left out of the build and re-applied per caller at read; and a query that sets its own `timezone:` but reads no date or timestamp is answered from the rollup. See `docs/preaggregation.md` for grain choice.