Repository navigation
Conversation
Nearly all of the slow coordinator messages tracked in our metrics
funnel into `catalog_transact*`, which runs inline on the coordinator
main loop. `mz_catalog_transact_seconds` shows the spikes but wraps the
whole call, so we cannot tell where the time goes: preparatory work,
the timestamp-oracle round trip, the durable persist commit, staging
builtin-table writes, or waiting on the group committer.
- Add `mz_catalog_transact_phase_seconds{phase}` with phases `prep`,
`write_ts`, `transact`, `stage_builtin`, `finalize`,
`table_updates_wait`, and `side_effects`.
- Convert the durable catalog latency metrics for commit, sync, and
snapshot from avg-only `Counter`s to histograms (same names, now
exposed as `_bucket`/`_sum`/`_count`), so p99 spikes in the
persist-backed paths become visible.
The `transact` phase minus the durable sync and commit histograms
attributes the in-memory work.
Part of https://linear.app/materializeinc/issue/SQL-584
ggevay
left a comment
There was a problem hiding this comment.
Claude and me wrote some comments.
| )), | ||
| catalog_transact_phase_seconds: registry.register(metric!( | ||
| name: "mz_catalog_transact_phase_seconds", | ||
| help: "Wall time of the individual phases of a coordinator catalog transaction, to attribute where transact time is spent.", |
There was a problem hiding this comment.
Maybe mention that the phases don't add up to catalog_transact_seconds, because of overlaps (side_effects/table_updates_wait are joined, and transact contains the durable sync+commit.).
There was a problem hiding this comment.
Done, added to the help text: phases overlap and do not sum to mz_catalog_transact_seconds, and transact includes the durable sync and commit.
| buckets: histogram_seconds_buckets(0.000_128, 32.0), | ||
| )), | ||
| apply_catalog_implications_seconds: registry.register(metric!( | ||
| name: "mz_apply_catalog_implications_seconds", |
There was a problem hiding this comment.
Wondering if we'd like to merge apply_catalog_implications_seconds into catalog_transact_phase_seconds (with its own label). I don't think we have Grafana panels on apply_catalog_implications_seconds yet.
There was a problem hiding this comment.
Leaving apply_catalog_implications_seconds separate on purpose. apply_catalog_implications is reachable from other places in the future, notably applying implications derived from following another writer's catalog changes, which is the shape SQL-585 needs. Folding it into a metric named for the transact path would misname it the moment that lands.
| "coordinator inconsistency detected" | ||
| ); | ||
|
|
||
| let side_effects_seconds = self |
There was a problem hiding this comment.
Anchored here because GitHub will not let me comment outside the diff. This is about the soft_assert_eq_no_log!(self.check_consistency(), ...) just above (line 123-126), and the identical one at line 211-214.
check_consistency sits inside catalog_transact_seconds and inside no phase. In prod that is fine, MZ_SOFT_ASSERTIONS is not set for any environment and on optimized builds the block is one relaxed atomic load and a branch.
But the likely use of these metrics is someone debugging a catalog transaction stall locally, and a local rig easily has soft assertions on without the person having thought about it. run.py always sets MZ_SOFT_ASSERTIONS=1 for sqllogictest, bin/ci-builder forwards the var, and it is a common thing to leave exported in a shell. With them on the work is real: check_cluster_statuses (coord/consistency.rs:148-176) is O(total clusters x replicas) per transaction regardless of what the transaction touched, and the catalog-side sweeps in CatalogState::check_consistency are O(catalog size). On a catalog resembling a real user's it can plausibly dominate, and the person chasing the stall then sees an inflated wrapper metric with a large remainder and no phase explaining it.
Cheap to cover: take an Instant before the macro and observe after, unconditionally. Nothing goes inside soft_assert_eq_no_log!, since an observation written there would vanish exactly where soft asserts are off and be inert where they are on. In prod the phase then reads about zero, which is itself the signal that it is not your problem.
There was a problem hiding this comment.
Done, timed unconditionally with an Instant outside the macro, in both wrappers, under a consistency_check phase. Comment records why it reads about zero in production and why nothing goes inside the macro.
| .metrics | ||
| .catalog_transact_phase_seconds | ||
| .with_label_values(&["side_effects"]); | ||
| let table_updates_wait = self |
There was a problem hiding this comment.
table_updates_wait is recorded from two call sites whose semantics differ, pooled under one label.
Here in catalog_transact_with_side_effects the group commit has already been running concurrently with apply_catalog_implications (line 112-115, awaited sequentially before this join), so the wrapper is first polled late and this records the residual wait. In catalog_transact_with_context (line 184-187) the wrapper is polled right after catalog_transact_inner returns, so it records the full remaining wait.
For the "what blocks the coordinator main loop" question both are the right number, so I would not change the measurement. But consider adding a method label to mz_catalog_transact_phase_seconds, matching the one mz_catalog_transact_seconds already carries. That keeps the two populations separable, and it would also let the DDL-transaction path share this phase vocabulary without pooling into the same series. See my comment at line 344.
There was a problem hiding this comment.
Agreed on the diagnosis, took a cheaper fix than the method label: the two sites now carry distinct phases, table_updates_wait in catalog_transact_with_context and table_updates_residual_wait here, with your reasoning as the comment. That encodes exactly the difference you identified without doubling the series count on a 19-bucket histogram, and without threading a method name through catalog_transact_inner.
For the DDL-transaction path I used the same approach rather than a shared vocabulary plus method, see the reply on your other comment.
There was a problem hiding this comment.
Distinct labels work for me, and I agree that beats a second dimension here.
One nit on the same lines: the binding is still let table_updates_wait = ... while the label is now table_updates_residual_wait, and the comment directly above it says "Distinct from table_updates_wait in catalog_transact_with_context". So the comment and the identifier on the next line read as contradicting each other. Renaming the binding to match the label would settle it.
|
|
||
| phase_seconds | ||
| .with_label_values(&["prep"]) | ||
| .observe(phase_start.elapsed().as_secs_f64()); |
There was a problem hiding this comment.
prep is dropped on the error path. validate_resource_limits(...)? on line 484 returns before this observe, so a transaction rejected on resource limits contributes nothing to prep even though it burned the whole op scan on the main loop.
Same shape as the existing catalog_transact_seconds wrappers, which also skip on ?, so low stakes unless resource-limit rejection ever becomes hot. If you want to close it:
let validate_res = self.validate_resource_limits(&ops, conn_id.unwrap_or(&SYSTEM_CONN_ID));
phase_seconds
.with_label_values(&["prep"])
.observe(phase_start.elapsed().as_secs_f64());
validate_res?;There was a problem hiding this comment.
Fixed, using your snippet.
| .get_catalog_write_ts() | ||
| .wall_time() | ||
| .observe(phase_seconds.with_label_values(&["write_ts"])) | ||
| .await; |
There was a problem hiding this comment.
nit: in read-only-controllers mode this is not purely the oracle round trip. get_catalog_write_ts (timeline.rs:170-175) joins peek_local_write_ts with catalog().current_upper() on that branch, so the phase also covers a persist upper fetch there. Only affects read-only replicas. Worth a word in the PR description, which describes write_ts as just the timestamp-oracle round trip.
There was a problem hiding this comment.
This branch is unreachable from here, so leaving the description as is. catalog_transact_inner returns Err(AdapterError::ReadOnly) at its top when self.controller.read_only(), before it ever reaches get_catalog_write_ts. The controller's read_only is set once at construction from the same read_only_controllers flag that get_catalog_write_ts branches on (coord.rs:4844/4863) and is never mutated afterwards, only read (controller/src/lib.rs:317,580). So read_only_controllers == true implies we returned early, and the write_ts phase on this path is only ever the oracle round trip.
Worth flagging if that ever changes: an in-process read-only to read-write promotion would make both the early return and this phase's meaning wrong at the same time.
| ops, | ||
| ) | ||
| .wall_time() | ||
| .observe(phase_seconds.with_label_values(&["transact"])) |
There was a problem hiding this comment.
The transact phase contains four sync observations and one commit, so the subtraction the description suggests needs care. I think this is worth writing down somewhere more durable than the PR description.
Per Catalog::transact:
storage.transaction()->transaction_unchecked->snapshot()->with_snapshot->with_trace->sync_to_current_upper->sync(persist.rs:725)storage.transaction()->ensure_not_out_of_sync->sync(persist.rs:1775)tx.commit->commit_transaction_inner->compare_and_append->sync(persist.rs:415)tx.commit->sync_updates->sync(durable/transaction.rs:2779)
So sync_count is roughly 4 * transact_count, while commit_count == transact_count.
The subtraction is correct in rate-of-sum space:
rate(mz_catalog_transact_phase_seconds_sum{phase="transact"}[5m])
- rate(mz_catalog_sync_latency_seconds_sum[5m])
- rate(mz_catalog_transaction_commit_latency_seconds_sum[5m])
but the intuitive per-transaction form is wrong, because sync's mean is taken over 4x as many observations:
# WRONG
rate(transact_sum[5m])/rate(transact_count[5m])
- rate(sync_sum[5m])/rate(sync_count[5m])
You have to divide the sync sum by the transact count.
The good news from the same trace, and the thing that makes the subtraction valid at all: at steady state every sync observation comes from inside Catalog::transact. The only other callers are bootstrap, preflight, debug, and tests, and there is no timer-driven catalog sync in the coordinator.
Where to write this down
The PR description alone is discoverable only by archaeology, and the person who needs this is whoever builds a panel in a year. Suggest splitting it three ways:
Here, as a code comment. This is the part I care most about, because it is a fact about Catalog::transact's structure that a later edit can silently invalidate. Something like:
// NOTE: This phase contains every durable `sync` and `commit` on the catalog
// path, which is what makes `transact` minus those two histograms a valid
// estimate of the in-memory work. More than one sync happens per transaction,
// so that subtraction is only valid on rates of `_sum`, never on
// per-observation means.Deliberately "more than one" rather than "exactly four". The count can drift as the durable path changes, but the caution stays true either way, and the invariant that actually matters, that every sync is inside this phase, is the one a future edit could break.
In the help text, one clause noting that transact includes the durable sync and commit. That string is what Grafana's metric browser and doc/user/data/metrics.yml surface, so it reaches the panel builder directly. It pairs with the non-additivity note I suggested on the metric definition. Worth keeping to a clause, since # HELP goes out on every scrape.
In the PR description, the PromQL above, for whoever builds the panel first.
There was a problem hiding this comment.
Adopted the three-way split, with one correction: the invariant this rests on does not hold.
sync and commit observations also come from durable allocate_id, which opens its own transaction (transaction_unchecked -> snapshot -> ... -> sync) and commits through the same commit_transaction that observes the commit histogram. At runtime that fires from allocate_storage_usage_id (message_handler.rs:323, once per storage-usage cycle) and allocate_user_ids (coord.rs:4177, on ID pool refill). So commit_count == transact_count is not true, and the subtraction over-subtracts, enough to go negative during a refill burst on an otherwise quiet catalog.
The code comment says this instead:
// NOTE: This phase contains every durable `sync` and `commit` a catalog
// transaction performs, which is what makes `transact` minus those two
// histograms an estimate of the in-memory work. Two caveats. More than
// one sync happens per transaction, so the subtraction is only valid on
// rates of `_sum`, never on per-observation means. And durable
// `allocate_id` (user ID pool refills, storage usage batch IDs) observes
// into the same histograms from outside any catalog transaction, so the
// estimate is biased low while allocation is active.Kept your "more than one" phrasing rather than "exactly four", for the reason you gave. The PromQL is in the PR description with the same caveat attached.
|
|
||
| phase_seconds | ||
| .with_label_values(&["finalize"]) | ||
| .observe(finalize_start.elapsed().as_secs_f64()); |
There was a problem hiding this comment.
nit: finalize also covers restart_webhook_sources (line 559-561), not only "config fanout + audit events" as the PR description puts it. Cosmetic, just so the description matches what the label actually measures.
There was a problem hiding this comment.
Fixed in the PR description.
|
|
||
| event!(Level::TRACE, ops = format!("{:?}", ops)); | ||
|
|
||
| let phase_seconds = self.metrics.catalog_transact_phase_seconds.clone(); |
There was a problem hiding this comment.
Anchored here because the code this is about is not in the diff. This instrumentation covers catalog_transact_inner, but the sibling DDL-transaction path bypasses it entirely.
catalog_transact_with_ddl_transaction gets no phase coverage at all
The per-statement dry-run path (ddl.rs:243-320) runs inline on the coordinator loop and is counted by catalog_transact_seconds{method="catalog_transact_with_ddl_transaction"}, but none of the seven new phases fire there. The eventual COMMIT does route through catalog_transact_with_side_effects into catalog_transact_inner (sequencer/inner.rs:2250-2264), so that half is covered. Every statement before the COMMIT is not.
That matters because DDL transactions do show up in the slow-message population, and there are concrete costs sitting in that window:
ddl.rs:279,txn_snapshot.clone()is a deep clone of the whole durableSnapshot. That type (durable/objects.rs:1303-1334) is#[derive(Clone)]over about 24 plainBTreeMaps of proto values, so this is O(catalog size) with real allocation, once per statement.ddl.rs:277and:283rebuild and re-clonecombined_opsevery statement, andvalidate_resource_limits(ddl.rs:1156-1179) is still a plainfor op in opsscan over the accumulated vector. adapter/ddl-perf: eliminate O(n^2) operation replay in DDL transactions #35303 removed the O(N^2) op replay, but this O(N^2) clone-and-count is still there.
Explicitly not a concern, so nobody else chases it like I nearly did: txn_state.clone() on the very next line is cheap, CatalogState keeps its large collections in imbl::OrdMap.
The history here is interesting, and I think it argues for instrumenting rather than skipping ahead to a fix. The snapshot round trip exists because of #35303, which traded O(N^2) op replay for an O(catalog) snapshot export and restore per statement. The follow-through that would make that cheap is yours and it never landed: 868be3967f on aljoscha/envd-specsheet-experiments replaces the proto Snapshot cache with a rust-typed MemorySnapshot of imbl::OrdMap fields, and cfae53b930 on aljoscha/envd-ddl-scalability swaps TransactionOps::DDL { snapshot } for durable_data, making each statement O(|pending|) instead of O(catalog). That commit message quotes a flamegraph putting about 22% of coordinator CPU on the per-entry proto deserialization at 30k catalog entries.
So there is a strong prior on where the time goes, and a flamegraph behind it, but no production metric confirming it. Which is exactly what this PR exists to provide.
Suggested shape, as a follow-up rather than growing this PR: reuse prep for ddl.rs:277-285 and write_ts for ddl.rs:288, both unchanged in meaning, add a dry_run for transact_incremental_dry_run, and ideally split the snapshot clone onto its own label since it is the prime suspect. Combined with the method label I suggest at line 133, both paths could share one vocabulary without pooling into the same series.
There was a problem hiding this comment.
Good catch, and thanks for the archaeology. Two parts:
Instrumentation, now in this PR. The per-statement path is covered under its own labels: ddl_txn_snapshot_clone (the prime suspect, on its own as you suggested), ddl_txn_prep (combined-ops build plus validate_resource_limits, observed before the ?), ddl_txn_write_ts, and ddl_txn_dry_run. I gave them a separate namespace rather than reusing prep/write_ts with a method label: the work differs from a real transaction's phases and it is billed once per statement rather than once per transaction, so pooling would blur both populations. Your "no free lunch on a shared vocabulary" point stands, this just resolves it in the label name instead of a second dimension.
Also recorded the txn_state.clone() non-issue as a comment at the site, since you nearly chased it and so will the next person:
// NOTE: `txn_snapshot` is a deep clone of the durable `Snapshot`, which is
// O(catalog size) in allocations, once per statement. `txn_state` next to
// it is cheap, `CatalogState` holds its large collections in `imbl` maps.The fix, as a follow-up. SQL-586, with the O(N^2) validate_resource_limits rescan folded in, and gated on reading the new phase metrics first so we confirm in production what the flamegraph showed locally.
- Note the non-additivity of the phases in the metric help text, and that `transact` includes the durable sync and commit. - Record `prep` before propagating a resource-limit rejection, so a rejected transaction still accounts for the op scan it burned. - Give the two `table_updates` wait sites distinct labels. In `catalog_transact_with_side_effects` the group commit already ran concurrently with the implications, so that site only sees a residual wait, while `catalog_transact_with_context` sees the full one. - Time `check_consistency`, which sits in no phase. It reads about zero in production but is O(catalog size) with soft assertions on, which is the common state of a local rig debugging a stall. - Record what makes the in-memory estimate valid, and where it is not: more than one durable sync happens per transaction, so the subtraction only holds on rates of `_sum`, and durable `allocate_id` contributes to the same histograms from outside any transaction. - Cover the per-statement DDL transaction path, which ran uninstrumented on the loop, under its own labels. The deep `Snapshot` clone gets its own phase, it is O(catalog size) once per statement.
|
Thanks for the fixes, LGTM, just one more very minor thing |
… panels The Areas table now carries the top-50 networking dashboard the release bot links (axhjnp) alongside the original (bHQE8bN4k), and the datasource table gains a canary-environments column: Sandbox in all three production regions, Analytics in us-east-1 and eu-west-1. The bot's eu-west-1 links omit Analytics, so the text says to add it by hand. The dead-panel note becomes a table giving, for each panel, the metric, when it went empty and the change behind it: the stash deletion in #26647, the catalog latency histograms from #37926 (read _sum and _count), the autospill backend removal, the legacy-upsert-only and backpressure-only metrics, the kubelet volume stats that stopped on 2026-06-26, and the v2_ prefix on the exporter's envd_up series. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Motivation
Nearly all of the slow coordinator messages we track in
mz_slow_message_handlingfunnel intocatalog_transact*, which runs inline on the coordinator main loop, and Grafana showsmz_catalog_transact_secondsspiking in those cases. But that metric wraps the whole call, so we cannot tell where the time goes: preparatory work, the timestamp-oracle round trip, the durable persist commit, staging builtin-table writes, or waiting on the group committer. This attribution decides how we tackle the rest of the milestone.Fixes SQL-584
Description
Adds
mz_catalog_transact_phase_seconds{phase}. For a catalog transaction:prep(op scan + resource-limit validation),write_ts(timestamp-oracle round trip),transact(all ofCatalog::transact),stage_builtin(builtin-table staging incl. row consolidation),finalize(config fanout, webhook-source restarts, audit events),consistency_check, and the concurrently-joined tailsside_effectsandtable_updates_wait/table_updates_residual_wait. The two wait labels are deliberately distinct: incatalog_transact_with_side_effectsthe group commit has already been running alongside the catalog implications, so that site sees only a residual wait, whilecatalog_transact_with_contextsees the full one.Also covers the per-statement DDL-transaction path, which ran entirely uninstrumented on the loop, under its own labels (
ddl_txn_snapshot_clone,ddl_txn_prep,ddl_txn_write_ts,ddl_txn_dry_run). The deep durableSnapshotclone gets its own phase because it is O(catalog size) once per statement and the prime suspect there. Follow-up for the fix: SQL-586.Converts the durable catalog latency metrics
mz_catalog_transaction_commit_latency_seconds,mz_catalog_sync_latency_seconds, andmz_catalog_snapshot_latency_secondsfrom avg-onlyCounters to histograms. They were invisible at p99 by construction. Metric names are unchanged, but Prometheus now exposes them as_bucket/_sum/_count, so existing dashboard queries need_sumappended (and gainhistogram_quantile).doc/user/data/metrics.ymlregenerated viabin/gen-metrics-catalog.Estimating the in-memory work
The phases overlap and do not sum to
mz_catalog_transact_seconds.transactcontains every durable sync and commit a transaction performs, so subtracting those two histograms estimates the in-memory portion:Two caveats, both also recorded at the call site. More than one sync happens per transaction, so this is only valid on rates of
_sum, never on per-observation means (sync's mean is taken over several times as many observations). And durableallocate_idobserves into the same histograms from outside any catalog transaction (user ID pool refills, storage usage batch IDs), so the estimate is biased low while allocation is active.Verification
Metrics-only change, no behavior change.
cargo check,cargo clippy,bin/fmt, and the metrics-catalog lint pass locally. Attribution will be validated by watching the new phase histograms alongsidemz_catalog_transact_secondson the environmentd health dashboard.