Repository navigation
compute: derive time dependence from the imports a dataflow reads - #38260
Conversation
|
I wonder why we have unused inputs at all? Is this another bug that we're working around here? |
|
Real gap rather than an inherent one, and worth fixing separately. Imports are collected eagerly when the dataflow is built, before the global MIR // Here, we import all indexes that belong to all imported collections. Later,
// `prune_and_annotate_dataflow_index_imports` runs at the end of the MIR
// pipeline, and removes unneeded index imports based on the optimized plan.That pruning exists and So yes, I'd call the missing prune a second bug, and it costs more than the
I'd still want this change on top of the prune, because the two are not the same I kept the prune out of this PR because SQL-635 is a hang and I wanted the fix |
264d784 to
7688aa6
Compare
A dataflow's imports are collected before optimization finishes, so a collection the optimizer folds to a constant afterwards leaves imports in the description that nothing reads. `determine_time_dependence` counted those anyway and reported wall-clock dependence, which earns the dataflow a dataflow expiration. Expiration pins the output frontier at the expiration time, and a constant export's true frontier is the empty antichain, so the pin holds the reported frontier days short of the truth for as long as the replica lives. It also makes every worker warn "frontier not less than expiration" on every such dataflow, which is the log spam in SQL-635. Whoever reads that frontier is then told the collection is frozen until the expiration rather than complete. A subscribe over it never ends. The frontend read-then-write path, which takes the empty antichain as "this selection can never change again" and otherwise writes at the frontier it last observed, either parks until the oracle reaches the expiration or commits its write there. With `compute_replica_expiration_offset` set to three days, `UPDATE a SET c0 = TRUE WHERE TRUE = a.c0` hangs until `statement_timeout`, because assigning `true` to rows filtered on `c0 = true` cancels against its own retractions and folds the selection to a constant late enough that the table is already an import. The same fold with a row left to write is worse: the write commits three days ahead of wall clock and takes the timeline's oracle with it, after which no session can even open. So count only the imports the exports read. `used_import_ids` answers that from the same walk rendering already does per export, and it is what `doc/developer/design/20240919_dataflow_expiration.md` asks for: a dataflow whose inputs' upper is the empty antichain does not expire. Where the imports are read, the answer is unchanged, and the change can only ever remove an expiration, never add or tighten one. Tests: an integration test covering all three statements, the parking one, the writing one, and a plain subscribe that has to end, each of which fails without this. Its `EXPLAIN` assertions pin the premise that the fold happens in the global pipeline rather than locally, so the case cannot go vacuous unnoticed. Unit tests cover the new helper, including that an imported index is reported by index id. Closes: SQL-635
7688aa6 to
e4b1cf0
Compare
### Motivation Closes: [SQL-635](https://linear.app/materializeinc/issue/SQL-635) Stacked on #38260, which must merge first. The base branch carries its commit; this PR is the three on top. My change uses `DataflowDescription::used_import_ids`, which #38260 introduces, so the dependency is real rather than presentational. Source imports are collected before the global MIR pipeline runs, from the plans as they were written. `prune_and_annotate_dataflow_index_imports` tightens the index imports at the end of the pipeline, and `DataflowBuilder::import_into_dataflow` says that deferral is by design, but `source_imports` never had a counterpart: the three passes that touch it after optimization only annotate. So a transform that drops the last `Get` of an imported collection leaves the import behind, and that costs three things, not one: * `render.rs` builds a `persist_source` for every entry, so a dangling one decodes a shard into a stream nobody consumes, on every worker. * `ComputeController::create_dataflow` acquires a read hold per imported source, so a dangling one pins that collection's `since` for the lifetime of the dataflow. * The dataflow reports wall-clock dependence its exports do not have, which earns it a replica expiration. That pins the output frontier at the expiration time, so a collection that can never change again reports as merely frozen, days out, and nothing downstream learns it is final. #38260 fixes the third at the consumer. Review concluded the discrepancy it reads around should not exist in the first place, so this restores the invariant at the producer, and keeps a derived-from-the-read-set answer for the one consumer whose wrong answer hangs an environment. ### Description * `prune_dataflow_source_imports` runs at the end of `optimize_dataflow`, beside the index prune, and drops the source imports no export reads. Read holds and persist sources are read off the import list directly, so the prune is what reclaims them. * `ComputeController::create_dataflow` computes `used_import_ids` once and uses it twice: `determine_time_dependence` counts through it rather than over the raw import list, and a check reports a list the prune left loose. Three non-obvious decisions: **The dangerous consumer does not depend on the prune having run.** `determine_time_dependence` takes the read set and filters both import loops through it. With the prune in place the two sets agree and the filter is a no-op, but a path that ever slipped past the prune would otherwise pin a frontier silently, which is the shape [SQL-635](https://linear.app/materializeinc/issue/SQL-635) presented as. The prune reclaims the read hold and the persist source; the read set makes the frontier answer correct by construction. **The tightness check logs in production.** `soft_assert_or_log!`, not `soft_assert_no_log!`. The walk is paid for above either way, so reporting a loose list costs only the comparison, and a debug-only assertion would buy a failing test while leaving production silent. **An export-less description gets its own check.** `EXPLAIN` builds a peek description without its index export (the conditional `export_index` in `optimize::peek`, which carries a standing TODO). Such a description has no answer to "what do the exports read", so the prune leaves its imports alone and the import check would fail it for the wrong reason. Stating the two invariants separately keeps both messages accurate. The consequence of the prune's exemption is that `EXPLAIN` of a one-shot `SELECT` still lists imports the real dataflow would prune; `EXPLAIN` of a materialized view, index, or subscribe is unaffected, since those always export. A note on one-sidedness: `depends_on` cannot tell which index on a collection a plan will use, so the export walk reports every index imported on a collection it reaches. That makes `used` a superset on the index side, so the check can miss a loose list but never invent one, which is the direction you want for something that logs in production. Pruning index imports needs the exact usage information `collect_index_reqs` collects, which is why the two prunes are not unified. ### Verification * New unit tests for the prune in `mz_transform::dataflow`: the import no export reads is dropped, a constant export drops every import, and an export-less description is left alone. * Two `EXPLAIN MATERIALIZED VIEW` goldens in `test/sqllogictest/explain/materialized_view.slt`, each pinning that a folded import stops showing up as a source, and each paired with an `EXPLAIN LOCALLY OPTIMIZED PLAN` golden asserting the table is still read at that stage. Without that pairing the case goes vacuous: the first draft of this test passed with and without the fix, because the shape folded during local optimization and the table was never imported at all. * `test/sqllogictest/explain/` passes 872/872, with no firing of either new assertion. That is the coverage that matters for the export-less check, which is a new way to fail. The two goldens fold through different transforms on purpose. The first needs the optimizer to recognize a mapped literal as the column it was filtered on; the second folds a view on an unsatisfiable predicate and collapses a join by inlining it. A change to either piece of reasoning leaves the other golden standing. With the prune removed, both fail because the boundary check fires first: ``` dataflow materialize.public.mv_join imports collections no export reads: imports [User(1)], read {} ``` Reaching this state at all requires a fold only the dataflow-level pipeline can see. A view that folds to a constant locally is inlined as a constant and never imports its inputs, so `LIMIT 0` behind a view does not qualify; nor does a contradictory range split across a view boundary, which inlines but does not fold. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_018eEZgU1VhJF9jgnjhCHGYc --------- Co-authored-by: Claude <[email protected]>
…8320) Part of: [SQL-641](https://linear.app/materializeinc/issue/SQL-641) Safeguard for the write timestamp the frontend OCC read-then-write path chooses. Independent of #38260. #38322 stacks on this and makes the far-future case work rather than merely be refused. ## The hole `GroupCommitter::commit_timestamped` documented an obligation it never discharged: ``` /// * The wall-clock throttle. `target_timestamp` is the caller's to choose, /// and it must not run the write timeline ahead of the clock. ``` Nothing checked it. Every other write allocates from the oracle, `GREATEST(write_ts + 1, now())`, so it cannot jump. A caller-chosen target can, and the oracle is monotone and durable: * Under the default **strict serializable**, every later write and read on the timeline blocks until the wall clock catches up. * Under **serializable** it is worse. Those reads never consult the oracle (`needs_linearized_read_ts` is false for them), so they pick a timestamp near the clock and an acknowledged write stays invisible. * It **survives restart** through the catalog shard's upper, which boot re-applies to the oracle. The startup sleep that once waited for the clock is gone. The frontend path produces such a target today, no bug involved: it writes at the frontier its subscribe observed, and a selection over a `REFRESH` materialized view settles until its next refresh. With `REFRESH EVERY '15 seconds'` that is a ~6s oracle jump. With a coarser interval it is a stalled environment. ## What this does **Enforces the bound where it is stated.** A target above `write_ts_upper_bound(now)` is refused before the append, and the session turns `WriteResult::TimestampTooFarAhead` into a statement error. The ceiling is the same `now + 2 * 5000ms` that `check_runaway_write_ts` already measured against, now named. A backstop, not the fix: the worst outcome becomes one failed statement instead of a stalled timeline, for any caller of the timestamped-write API. **Leaves the detector logging.** `check_runaway_write_ts` stays an `error!`. With the refusal above in place, every way left to reach it is a runaway this process inherited, a durable one re-applied at boot or a backwards clock step, and the group committer's throttle is written to wait those out. Failing there would turn a stalled timeline into a crash loop, which is the opposite of what the boot check below decides. **Reports the restart channel.** Boot logs an error when the catalog upper is already past the bound. It does not refuse to start: the timeline is stalled either way, and a process that will not boot turns that into an outage plus a crash loop. ## Tests `test_far_future_write_timestamp_is_refused` builds a genuinely far-future target from a materialized view with two refreshes, one seconds out so the view becomes readable, one in the year 3000 so the target is deterministic rather than racing a refresh interval. It asserts the refusal, that the oracle did not move (checked before reading the target back, since a read cannot be served once the oracle is out there), and that the timeline still takes a write and a read. The error is `FEATURE_NOT_SUPPORTED` here because retrying does not help while the frontier stays out there. #38322 changes the producer set to "the oracle itself ran away" and moves it to `INTERNAL_ERROR` with a hint that matches.
Fixes the hang and the log spam in SQL-635, which are one cause.
What goes wrong
A dataflow's imports are collected before optimization finishes, so a collection
the optimizer folds to a constant afterwards leaves imports in the description
that nothing reads.
ComputeController::determine_time_dependencecounted thoseanyway, reported wall-clock dependence, and that is what earns a dataflow a
dataflow expiration.
Expiration holds the output frontier at the expiration time so nothing
downstream believes data at or after it. A constant export's true frontier is
the empty antichain, so the hold reports it as merely frozen until the
expiration, days out, for as long as the replica lives. Every worker also warns
frontier not less than expirationfor each such sink, which is the log spam inthe issue.
Whoever reads that frontier is told the collection is frozen rather than
complete:
SUBSCRIBEover such a selection never ends.selection can never change again" and otherwise writes at the frontier it last
observed. So the reported
UPDATE a SET c0 = TRUE WHERE TRUE = a.c0parks inensure_read_linearizeduntil the oracle reaches the expiration and dies onstatement_timeout. Assigningtrueto rows filtered onc0 = truecancelsagainst its own retractions, and that fold happens in the global pipeline,
late enough that the table is already an import.
INSERT INTO dst WITH x AS (SELECT c0 FROM a WHERE TRUE = c0) ((SELECT true AS c0 FROM x) EXCEPT ALL (SELECT c0 FROM x)) UNION ALL (VALUES (true))committing at a timestamp 259,199,635 ms (three days) ahead of wall clock and
taking the timeline's oracle with it. After that, writes, strict-serializable
reads, and opening a new session all hang.
WHERE c0works andWHERE TRUE = c0hangs for exactly this reason: only thelatter folds.
The fix
Count only the imports the exports read.
DataflowDescription::used_import_idsanswers that with the walk rendering already does per export, over each index
export's
on_idand each sink export'sfrom, anddetermine_time_dependencefilters its two import loops through it.This is what
doc/developer/design/20240919_dataflow_expiration.mdasks for. Adataflow whose inputs' upper is the empty antichain must not expire, and a
dataflow that reads no import at all is that case. The design doc states the
rule as
time_dependence == None, and reading it literally off the import listis what produced the bug.
Where the imports are read, the answer is unchanged. The set can only shrink, so
the change can only ever remove an expiration, never add one or make one more
aggressive.
Note this is not specific to read-then-write. Any dataflow with an import
optimization left unread was affected, and
compute_replica_expiration_offsetdefaults to
3din CI's mzcompose configuration.Tests
test_replica_expiration_spares_folded_selectionsinsrc/environmentd/tests/read_then_write.rsruns the three statements aboveagainst a replica with a three-day expiration offset: the writing one, checking
the oracle stayed near wall clock before it reads anything back, the parking
one, and a plain
COPY (SUBSCRIBE ...)that has to end, bounded by a thread anda channel because a subscribe is exempt from
statement_timeout. Each of thethree fails without the fix. Its two
EXPLAINassertions pin the premise, thatthe fold happens in the global pipeline and not locally, so the test cannot go
vacuous unnoticed if that moves.
Four unit tests in
src/compute-types/src/dataflows.rscover the new helper,including that an imported index is reported by index id rather than by the id
of the collection it indexes.
Left alone deliberately
read hold that pins the table's
sinceat the dataflow'sas_of. Pruning itin the optimizer would fix the accounting at its root, but it reaches read
holds,
as_ofselection, and adapter dependency tracking.REFRESH EVERYmaterialized view's upper, still yields a far-future write timestamp on the
OCC path. That is pre-existing and orthogonal to this issue, and it deserves
its own.
check_runaway_write_tsalready logs an error in that case, which ishow it showed up here too.
Closes: SQL-635