Skip to main content

mz_adapter/
frontend_read_then_write.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Frontend sequencing for read-then-write operations.
11//!
12//! This module implements INSERT [...] SELECT FROM [...], DELETE and UPDATE
13//! operations using a subscribe with optimistic concurrency control (OCC),
14//! sequenced from the session task rather than the Coordinator.
15//!
16//! The motivation is correctness with concurrent writers, including writers in
17//! different `environmentd` processes, which the coordinator's in-process write
18//! locks cannot provide. The OCC path also fixes a serializability defect of the
19//! lock path, which reads at one timestamp and commits at a later one while
20//! locking only the selection's direct dependency items. See the design doc,
21//! `doc/developer/design/20260210_incremental_occ_read_then_write.md`, and the
22//! comment on the retry arm in `run_occ_loop`. Relieving the coordinator loop is
23//! a side benefit, and only sequencing moves off it. The subscribe's data path
24//! still runs through the coordinator.
25//!
26//! ## Whether the write reads persisted state
27//!
28//! Two predicates answer that one question, and they have to agree. Before
29//! anything runs, `SessionClient::try_read_then_write` decides it
30//! syntactically, from `depends_on()` on the planned selection, because inside
31//! a transaction a read-dependent write has to be refused while refusing is
32//! still possible. Once the dataflow runs, the subscribe answers it
33//! dynamically: the channel closes on its own only once the sink's output
34//! frontier reaches the empty antichain, which means the selection can never
35//! change again.
36//!
37//! Reading nothing persisted is the common case for a clean close, not the
38//! guarantee. An input whose frontier seals closes cleanly too, despite reading
39//! persisted state, for example a `REFRESH AT` materialized view past its last
40//! refresh, whose write frontier advances to the empty antichain. What holds in
41//! either case is the property the write side actually needs: past the close,
42//! the consolidated diffs are frontier-independent. The syntactic predicate is
43//! correspondingly stricter than the dynamic one, since it refuses a sealed-MV
44//! `INSERT ... SELECT` in a transaction that would technically be bufferable.
45//!
46//! The two answers are used for different things, and that separation matters.
47//!
48//! The syntactic answer decides whether the statement can belong to a
49//! transaction. A selection that reads nothing produces diffs that are valid at
50//! any timestamp, so they are staged as session write ops and land when the
51//! transaction commits, which is what makes the statement atomic with whatever
52//! surrounds it. A selection that reads persisted state cannot belong to a
53//! transaction, and we refuse it in an explicit one. An extended-protocol
54//! pipeline is an implicit transaction, so it must not quietly join one either:
55//! it ends its own transaction instead of spanning the rest of the pipeline,
56//! which is how PostgreSQL treats statements that cannot run in a transaction
57//! block. It is durable once it reports success, and a later failure in the
58//! pipeline does not undo it.
59//!
60//! The dynamic answer only decides how the write is submitted, a timestamped
61//! write from inside the loop or a blind submission after it. It cannot decide
62//! transaction membership, because it is a property of the inputs rather than
63//! of the statement. A sealed input closes the subscribe cleanly, so an
64//! `INSERT ... SELECT` over a `REFRESH AT` materialized view past its last
65//! refresh takes the blind exit while still reading persisted state. Its diffs
66//! really are frontier-independent and staging them would be safe, and we still
67//! do not stage them. Otherwise whether a statement's rows survive a failure
68//! later in the pipeline would depend on whether one of its inputs happened to
69//! pass its last refresh, which no one reading the statement could predict.
70//!
71//! Staging is also what earns the right to span a pipeline in the first place.
72//! `TransactionStatus::may_span_pipeline` lets an implicit transaction stay open
73//! only for writes, precisely because they are merely staged. A statement that
74//! committed on its own has no business claiming it.
75//!
76//! Disagreement is caught on both sides, and only one side can still refuse.
77//! `PeekClient::read_then_write` re-checks the syntactic predicate before running a
78//! dataflow, which catches a caller that skipped the gate. If the syntactic
79//! predicate were laxer than the dynamic one, that check would pass and a write
80//! meant for staging would commit on its own, so the loop asserts wherever the
81//! two answers can be compared. The `Committed` arm catches a write timestamp
82//! for a statement we meant to stage, and the zero-row arm catches a read
83//! timestamp for one. Neither can undo anything by then, the write is already
84//! durable in the first case and there was never anything to write in the
85//! second, so all they do is make the disagreement loud.
86//!
87//! ## The frontier certifies, the oracle chooses
88//!
89//! The target `T` comes from the oracle, and a progress message at `F` only
90//! certifies completeness below `F`, so it gates the write rather than choosing
91//! its timestamp. The design doc's "The OCC loop" says why. Three invariants
92//! hold for every write this path makes:
93//!
94//! * `F >= T` before it submits, so the payload is a complete view of `T - 1`.
95//! * The payload is every diff below `T`, strictly. A diff at `T` is concurrent
96//!   with the write and waits for a later target.
97//! * `T > as_of`, so the snapshot, which arrives at `as_of`, is in the payload.
98//!
99//! NOTE: `F >= T` does not make the two equal, because `F` is a minimum over the
100//! selection's inputs. Where `F` runs above `T`, a selection that reads the
101//! target table makes the compare-and-append refuse, and retrying higher is the
102//! design rather than a failure.
103//!
104//! ## A zero-row answer
105//!
106//! A write linearizes itself, because group commit advances the oracle before it
107//! acknowledges. An answer of "no rows" performs no write, so the loop reports
108//! the timestamp its view is complete through and the caller waits for the
109//! oracle to reach it. A selection empty at `as_of` is complete through `as_of`,
110//! which the caller put behind the oracle before the subscribe started, so that
111//! answer waits for nothing, while reporting the frontier the subscribe observed
112//! would cost a group commit every time. The design doc's "Linearization" argues
113//! why the lower timestamp is not the weaker guarantee.
114
115use std::collections::BTreeMap;
116use std::collections::BTreeSet;
117use std::num::{NonZeroI64, NonZeroUsize};
118use std::sync::atomic::{AtomicBool, Ordering};
119use std::sync::{Arc, Mutex};
120use std::time::Duration;
121
122use bytesize::ByteSize;
123use differential_dataflow::consolidation;
124use mz_catalog::memory::error::ErrorKind;
125use mz_catalog::memory::objects::CatalogItem;
126use mz_cluster_client::ReplicaId;
127use mz_compute_types::ComputeInstanceId;
128use mz_expr::Eval;
129use mz_expr::row::RowCollection;
130use mz_expr::{CollectionPlan, Id, LocalId, MirRelationExpr, MirScalarExpr, RowSetFinishing};
131use mz_ore::cast::CastFrom;
132use mz_ore::{soft_assert_or_log, soft_panic_or_log};
133use mz_repr::optimize::OverrideFrom;
134use mz_repr::{CatalogItemId, Diff, GlobalId, RelationDesc, Row, RowArena, Timestamp};
135use mz_sql::catalog::CatalogError;
136use mz_sql::plan::{self, MutationKind, QueryWhen};
137use mz_sql::session::metadata::SessionMetadata;
138use mz_sql::session::vars::IsolationLevel;
139use mz_storage_client::client::TableData;
140use mz_storage_types::sources::Timeline;
141use mz_timestamp_oracle::TimestampOracle;
142use prometheus::Histogram;
143use timely::progress::Antichain;
144use tokio::sync::mpsc;
145use uuid::Uuid;
146
147use crate::active_compute_sink::ActiveSubscribeOwner;
148use crate::catalog::Catalog;
149use crate::command::{Command, ExecuteResponse, WriteAttemptKind};
150use crate::coord::appends::WriteResult;
151use crate::coord::read_then_write::{DependencyPolicy, validate_read_then_write_dependencies};
152use crate::coord::timestamp_selection::TimestampProvider;
153use crate::coord::{Coordinator, TargetCluster};
154use crate::error::AdapterError;
155use crate::metrics::{OCC_CALLER_BACKGROUND, OCC_CALLER_SESSION};
156use crate::optimize::Optimize;
157use crate::optimize::dataflows::{ComputeInstanceSnapshot, EvalTime, ExprPrep, ExprPrepOneShot};
158use crate::peek_client::CoordinatorClient;
159use crate::session::{Session, TransactionOps, WriteOp};
160use crate::statement_logging::{StatementLifecycleEvent, StatementLoggingId};
161use crate::{PeekClient, PeekResponseUnary, TimelineContext, optimize};
162
163/// Reason a frontend write attempt is being torn down early.
164#[derive(Clone, Copy)]
165pub(crate) enum WriteCancellation {
166    Canceled,
167    StatementTimeout,
168}
169
170impl From<WriteCancellation> for AdapterError {
171    fn from(cancellation: WriteCancellation) -> Self {
172        match cancellation {
173            WriteCancellation::Canceled => AdapterError::Canceled,
174            WriteCancellation::StatementTimeout => AdapterError::StatementTimeout,
175        }
176    }
177}
178
179/// State shared between an in-flight frontend write attempt and its
180/// cancellation wrapper,
181/// `SessionClient::try_read_then_write_with_cancel`.
182///
183/// The contract: `write_submitted` is true from just before the
184/// `AttemptWrite` command is sent until the attempt resolves as definitively
185/// not committed. While it is true, cancellation and statement timeout must
186/// not synthesize an error but await the definitive write result instead,
187/// because the write may already be durable.
188///
189/// The wrapper and the attempt it wraps are polled by the same task, so the
190/// mutex and the atomic are here to satisfy `Send`, not to arbitrate between
191/// concurrent writers. There is one writer for each field.
192pub(crate) struct WriteAttemptState {
193    write_submitted: AtomicBool,
194    /// Set at most once, by the cancellation wrapper.
195    cancellation: Mutex<Option<WriteCancellation>>,
196}
197
198impl WriteAttemptState {
199    pub(crate) fn new() -> Self {
200        Self {
201            write_submitted: AtomicBool::new(false),
202            cancellation: Mutex::new(None),
203        }
204    }
205
206    pub(crate) fn mark_write_submitted(&self) {
207        self.write_submitted.store(true, Ordering::Release);
208    }
209
210    /// Marks the submitted write as definitively not committed.
211    ///
212    /// NOTE: This must only be called for outcomes where the write is known
213    /// to not have landed (`TimestampPassed`). Terminal outcomes leave
214    /// `write_submitted` set so a concurrent cancellation path can never
215    /// fabricate an error for a write that may have committed.
216    fn mark_write_resolved(&self) {
217        self.write_submitted.store(false, Ordering::Release);
218    }
219
220    pub(crate) fn write_submitted(&self) -> bool {
221        self.write_submitted.load(Ordering::Acquire)
222    }
223
224    /// Records why the attempt is being torn down. The first reason recorded
225    /// is the one the attempt reports.
226    pub(crate) fn request(&self, cancellation: WriteCancellation) {
227        self.cancellation
228            .lock()
229            .expect("cancellation lock poisoned")
230            .get_or_insert(cancellation);
231    }
232
233    fn requested_error(&self) -> Option<AdapterError> {
234        self.cancellation
235            .lock()
236            .expect("cancellation lock poisoned")
237            .map(AdapterError::from)
238    }
239}
240
241/// Which kind of caller is driving a read-then-write.
242///
243/// Dependency rules, replica selection, and write cancellation follow from the
244/// caller kind.
245#[derive(Clone, Copy)]
246enum RtwCaller {
247    /// A user statement. Cancelled with its connection, and restricted to
248    /// reading user tables.
249    Session,
250    /// Coordinator-owned maintenance, pinned to one replica.
251    ///
252    /// The caller must build the statement itself rather than accept one from a
253    /// user, and must tolerate reading a log relation that is sealed empty,
254    /// which is how a replica with introspection disabled presents one.
255    Background { replica_id: ReplicaId },
256}
257
258impl RtwCaller {
259    fn is_background(&self) -> bool {
260        matches!(self, RtwCaller::Background { .. })
261    }
262
263    /// Which relations the selection may read.
264    fn dependency_policy(&self) -> DependencyPolicy {
265        match self {
266            RtwCaller::Session => DependencyPolicy::UserDml,
267            RtwCaller::Background { .. } => DependencyPolicy::SystemReads,
268        }
269    }
270
271    /// The replica a background caller pins its subscribe to, overriding the
272    /// session's replica selection.
273    fn replica_override(&self) -> Option<ReplicaId> {
274        match self {
275            RtwCaller::Background { replica_id } => Some(*replica_id),
276            RtwCaller::Session => None,
277        }
278    }
279
280    /// Who owns the subscribe, which decides whether it is cancelled with a
281    /// connection and whether it counts against one.
282    fn subscribe_owner(
283        &self,
284        conn_id: &mz_adapter_types::connection::ConnectionId,
285        session_uuid: Uuid,
286    ) -> ActiveSubscribeOwner {
287        match self {
288            RtwCaller::Session => ActiveSubscribeOwner::Session {
289                conn_id: conn_id.clone(),
290                session_uuid,
291            },
292            RtwCaller::Background { .. } => ActiveSubscribeOwner::Background,
293        }
294    }
295
296    /// The connection a pending write is cancelled with, if any.
297    fn write_conn_id(
298        &self,
299        conn_id: &mz_adapter_types::connection::ConnectionId,
300    ) -> Option<mz_adapter_types::connection::ConnectionId> {
301        match self {
302            RtwCaller::Session => Some(conn_id.clone()),
303            RtwCaller::Background { .. } => None,
304        }
305    }
306}
307
308/// What the OCC loop produced.
309enum OccOutcome {
310    /// The write is durable at `write_ts`.
311    Committed {
312        response: ExecuteResponse,
313        write_ts: Timestamp,
314    },
315    /// The selection was empty, so there was nothing to write.
316    ///
317    /// `empty_as_of` is the timestamp the emptiness holds at, and the caller must
318    /// bring the oracle's read timestamp up to it before responding. `None` when
319    /// the subscribe ran to completion, where the emptiness holds at every
320    /// timestamp. See the module docs for why the choice of timestamp matters.
321    NoRowsMatched {
322        response: ExecuteResponse,
323        empty_as_of: Option<Timestamp>,
324    },
325    /// Diffs no frontier can change, from a subscribe that ran to completion.
326    /// The close says the selection can never change again, not that it reads
327    /// nothing persisted, and either way the caller chooses whether to submit
328    /// them now or buffer them into the transaction.
329    Blind {
330        response: ExecuteResponse,
331        diffs: Vec<(Row, Diff)>,
332    },
333}
334
335/// What the coordinator's answer to a submitted write means for the statement.
336enum WriteOutcome {
337    /// The write is durable at this timestamp.
338    Committed(Timestamp),
339    /// The write did not land, and resubmitting these diffs cannot change
340    /// that. This is the error to report.
341    Failed(AdapterError),
342    /// Another writer advanced the target's upper past the timestamp we asked
343    /// for. The diffs still describe the mutation, so the OCC loop can
344    /// resubmit them once the subscribe has caught up.
345    Conflict { next_eligible_timestamp: Timestamp },
346}
347
348/// Maps a [`WriteResult`] to the outcome the statement reports, or to the one
349/// conflict the OCC loop can retry.
350fn classify_write_result(
351    result: WriteResult,
352    target_id: CatalogItemId,
353    attempt_state: &WriteAttemptState,
354) -> WriteOutcome {
355    match result {
356        WriteResult::Success { timestamp } => WriteOutcome::Committed(timestamp),
357        WriteResult::TimestampPassed {
358            next_eligible_timestamp,
359            ..
360        } => WriteOutcome::Conflict {
361            next_eligible_timestamp,
362        },
363        WriteResult::Canceled => WriteOutcome::Failed(
364            attempt_state
365                .requested_error()
366                .unwrap_or(AdapterError::Canceled),
367        ),
368        WriteResult::TimestampTooFarAhead {
369            target_timestamp,
370            limit,
371        } => WriteOutcome::Failed(AdapterError::ReadThenWriteTimestampTooFarAhead {
372            target_timestamp,
373            limit,
374        }),
375        WriteResult::ReadOnly => WriteOutcome::Failed(AdapterError::ReadOnly),
376        WriteResult::TargetChanged => {
377            // A concurrent DDL gave the table a new generation after we
378            // computed these diffs against the old one. The same error the
379            // coordinator raises when a dependency changes underneath a
380            // statement, so clients see one retryable outcome for both.
381            WriteOutcome::Failed(AdapterError::ConcurrentDependencyMutation {
382                dependency_id: target_id.to_string(),
383            })
384        }
385        WriteResult::Indeterminate => WriteOutcome::Failed(AdapterError::Internal(
386            "write outcome is indeterminate because the group committer shut down".into(),
387        )),
388    }
389}
390
391/// Ends the implicit transaction that a statement which cannot run in a
392/// transaction block opened for itself.
393///
394/// A read-then-write that reads persisted state is refused inside a transaction,
395/// so it must not quietly become part of one. Clearing the ops it staged leaves
396/// [`crate::session::TransactionStatus::may_span_pipeline`] false, so pgwire
397/// commits the implicit transaction rather than letting the rest of an
398/// extended-protocol pipeline join it. The write is already durable at this
399/// point, and the caller has established there is nothing else staged to lose.
400fn end_own_transaction(session: &mut Session, stages_rows: bool) {
401    if !stages_rows {
402        session.clear_transaction_ops();
403    }
404}
405
406/// Checks that a read-then-write may read what its selection depends on.
407///
408/// An invalid selection is invalid wherever the statement runs, so a caller with
409/// something contextual to report, such as the transaction state, must ask this
410/// first. Reporting the transaction for a statement that can never work suggests
411/// it would work outside one.
412///
413/// `catalog` must be the snapshot the plan was built against. A missing item
414/// means the caller mixed snapshots, which is reported as a catalog error rather
415/// than treated as a dropped dependency.
416pub(crate) fn validate_selection_dependencies(
417    catalog: &Catalog,
418    depends_on: &BTreeSet<GlobalId>,
419    policy: DependencyPolicy,
420) -> Result<(), AdapterError> {
421    let dependency_ids = depends_on
422        .iter()
423        .copied()
424        .map(|gid| {
425            catalog.try_resolve_item_id(&gid).ok_or_else(|| {
426                AdapterError::Catalog(mz_catalog::memory::error::Error {
427                    kind: ErrorKind::Sql(CatalogError::UnknownItem(gid.to_string())),
428                })
429            })
430        })
431        .collect::<Result<Vec<_>, _>>()?;
432    let max_rw_dependencies = mz_adapter_types::dyncfgs::READ_THEN_WRITE_MAX_DEPENDENCIES
433        .get(catalog.system_config().dyncfgs());
434    validate_read_then_write_dependencies(catalog, dependency_ids, max_rw_dependencies, policy)
435}
436
437/// Validates a read-then-write and resolves the context the rest of the
438/// pipeline runs against.
439///
440/// Rejects `mz_now()` in the selection, the assignments or the returning
441/// clause. `optimize_mir_read_then_write` relies on that rejection by name
442/// when it prepares unmaterializable functions one-shot. Also enforces the
443/// dependency cap, resolves the target cluster and requires it to have a
444/// live replica, honors the session's replica pin, computes the read side's
445/// `TimelineContext`, and fetches the target table's descriptor.
446///
447/// `catalog` must be the snapshot the plan was built against. One snapshot
448/// serves planning, validation and optimization, so items the plan names
449/// cannot disappear from it, and the missing-entry branches below are
450/// failsafes rather than a live concurrent-DDL path.
451///
452/// `dependency_policy` decides which relations the selection may read. Both
453/// policies reject `mz_now()` anywhere in the transitive dependencies.
454fn validate_read_then_write(
455    catalog: &Arc<Catalog>,
456    session: &Session,
457    plan: &plan::ReadThenWritePlan,
458    target_cluster: TargetCluster,
459    dependency_policy: DependencyPolicy,
460) -> Result<ValidationResult, AdapterError> {
461    if contains_mz_now(plan) {
462        return Err(AdapterError::Unsupported(
463            "calls to mz_now in write statements",
464        ));
465    }
466
467    // One walk of the selection serves both the dependency check and the
468    // timeline validation below.
469    let depends_on = plan.selection.depends_on();
470
471    validate_selection_dependencies(catalog, &depends_on, dependency_policy)?;
472
473    let cluster = catalog.resolve_target_cluster(target_cluster, session)?;
474    let cluster_id = cluster.id;
475
476    if cluster.replicas().next().is_none() {
477        return Err(AdapterError::NoClusterReplicasAvailable {
478            name: cluster.name.clone(),
479            is_managed: cluster.is_managed(),
480        });
481    }
482
483    let replica_id = session
484        .vars()
485        .cluster_replica()
486        .map(|name| {
487            cluster
488                .replica_id(name)
489                .ok_or(AdapterError::UnknownClusterReplica {
490                    cluster_name: cluster.name.clone(),
491                    replica_name: name.to_string(),
492                })
493        })
494        .transpose()?;
495
496    let timeline = catalog.validate_timeline_context(depends_on.iter().copied())?;
497
498    // The loop waits for the subscribe's frontier to reach a target timestamp
499    // taken from the `EpochMilliseconds` oracle, and it is the target table's
500    // upper the write then competes for. A selection in another timeline
501    // counts something else, transactions rather than milliseconds for a CDCv2
502    // source, so its frontier is not comparable with that target and the
503    // statement would burn until `statement_timeout`. Refuse it up front
504    // instead.
505    //
506    // Only `INSERT ... SELECT` reaches this. A DELETE or UPDATE selection
507    // includes the target table, so a foreign timeline already fails above
508    // as a mixed-timeline query.
509    if let TimelineContext::TimelineDependent(t) = &timeline {
510        if t != &Timeline::EpochMilliseconds {
511            return Err(AdapterError::Unsupported(
512                "read-then-write on a selection outside the EpochMilliseconds timeline",
513            ));
514        }
515    }
516
517    // Get the table descriptor for constraint validation. As above, a
518    // missing entry would mean the snapshot contract was broken.
519    let table_desc = match catalog.try_get_entry(&plan.id) {
520        Some(entry) => entry
521            .relation_desc_latest()
522            .expect("table has desc")
523            .into_owned(),
524        None => {
525            return Err(AdapterError::Catalog(mz_catalog::memory::error::Error {
526                kind: ErrorKind::Sql(CatalogError::UnknownItem(plan.id.to_string())),
527            }));
528        }
529    };
530
531    Ok(ValidationResult {
532        cluster_id,
533        replica_id,
534        timeline,
535        depends_on,
536        table_desc,
537    })
538}
539
540/// Builds the response for a write that is about to be submitted.
541///
542/// This runs before the write, so the result-size checks in here reject the
543/// statement without having written anything.
544fn build_success_response(
545    kind: &MutationKind,
546    returning: &[MirScalarExpr],
547    diffs: &[(Row, Diff)],
548    max_result_size: u64,
549    max_query_result_size: u64,
550    row_set_finishing_seconds: &Histogram,
551) -> Result<ExecuteResponse, AdapterError> {
552    if returning.is_empty() {
553        // For UPDATE each changed row produces a retraction (-1) and an
554        // insertion (+1), so we divide by 2 below.
555        let row_count = diffs
556            .iter()
557            .map(|(_, diff)| diff.into_inner().unsigned_abs())
558            .sum::<u64>();
559        let row_count = usize::try_from(row_count).expect("positive row count must fit in usize");
560
561        return Ok(match kind {
562            MutationKind::Delete => ExecuteResponse::Deleted(row_count),
563            MutationKind::Update => ExecuteResponse::Updated(row_count / 2),
564            MutationKind::Insert => ExecuteResponse::Inserted(row_count),
565        });
566    }
567
568    let mut returning_rows = Vec::new();
569    let mut arena = RowArena::new();
570    // RETURNING expressions are evaluated row-by-row in this loop, so an
571    // expression like `RETURNING repeat('x', 10_000_000)` will allocate
572    // unbounded data unless we bail mid-loop. The post-loop
573    // `RowSetFinishing::finish` below would also reject this, but only
574    // after we've materialized everything. The early-bail caps the
575    // temporary allocation. We pick the lower of the two configured caps,
576    // whichever fires first wins.
577    let mut projected_byte_size: u64 = 0;
578    let early_cap = std::cmp::min(max_result_size, max_query_result_size);
579
580    for (row, diff) in diffs {
581        let include = match kind {
582            MutationKind::Delete => diff.is_negative(),
583            MutationKind::Update | MutationKind::Insert => diff.is_positive(),
584        };
585
586        if !include {
587            continue;
588        }
589
590        let mut returning_row = Row::with_capacity(returning.len());
591        let mut packer = returning_row.packer();
592        let datums: Vec<_> = row.iter().collect();
593
594        for expr in returning {
595            match expr.eval(&datums, &arena) {
596                Ok(datum) => packer.push(datum),
597                Err(err) => return Err(err.into()),
598            }
599        }
600        arena.clear();
601
602        let multiplicity = NonZeroUsize::try_from(
603            NonZeroI64::try_from(diff.into_inner().abs()).expect("diff is non-zero"),
604        )
605        .map_err(AdapterError::from)?;
606
607        let row_bytes = u64::cast_from(returning_row.byte_len())
608            .saturating_mul(u64::cast_from(multiplicity.get()));
609        projected_byte_size = projected_byte_size.saturating_add(row_bytes);
610        if projected_byte_size > early_cap {
611            return Err(AdapterError::ResultSize(format!(
612                "result exceeds max size of {}",
613                ByteSize::b(early_cap)
614            )));
615        }
616
617        returning_rows.push((returning_row, multiplicity));
618    }
619
620    // Run the canonical finish to enforce both caps with full precision
621    // (including the sorted-view memory overhead) and to register the
622    // row-set-finishing duration histogram.
623    let finishing = RowSetFinishing {
624        order_by: Vec::new(),
625        limit: None,
626        offset: 0,
627        project: (0..returning.len()).collect(),
628    };
629    match finishing.finish(
630        RowCollection::new(returning_rows, &finishing.order_by),
631        max_result_size,
632        Some(max_query_result_size),
633        row_set_finishing_seconds,
634    ) {
635        Ok((rows, _size_bytes)) => Ok(ExecuteResponse::SendingRowsImmediate {
636            rows: Box::new(rows),
637        }),
638        Err(e) => Err(AdapterError::ResultSize(e)),
639    }
640}
641
642/// Whether a read-then-write mentions `mz_now()` anywhere.
643///
644/// Read time and write time differ on this path, so `mz_now()` has no single
645/// answer and is refused in every position.
646pub(crate) fn contains_mz_now(plan: &plan::ReadThenWritePlan) -> bool {
647    plan.selection.contains_temporal()
648        || plan.assignments.values().any(|e| e.contains_temporal())
649        || plan.returning.iter().any(|e| e.contains_temporal())
650}
651
652/// The timeline whose oracle governs a read-then-write with the given read-side
653/// [`TimelineContext`].
654///
655/// The write target is always a table on `EpochMilliseconds`, so a read side
656/// that pins no timeline (`TimestampDependent`) still maps to
657/// `EpochMilliseconds`. `None` only for timestamp-independent selections, which
658/// need no oracle at all.
659fn governing_timeline(timeline: &TimelineContext) -> Option<Timeline> {
660    <Coordinator as TimestampProvider>::get_timeline(timeline)
661}
662
663/// A handle to an internal subscribe, meaning one that writes no
664/// `mz_subscriptions` row. A `Drop` impl ensures the subscribe's dataflow is
665/// cleaned up when dropped.
666struct SubscribeHandle {
667    rx: mpsc::UnboundedReceiver<PeekResponseUnary>,
668    sink_id: GlobalId,
669    /// Wrapped in `Option` so we can move it out in `Drop`.
670    client: Option<CoordinatorClient>,
671}
672
673impl SubscribeHandle {
674    /// Receive the next message from the subscribe, waiting if necessary.
675    pub async fn recv(&mut self) -> Option<PeekResponseUnary> {
676        self.rx.recv().await
677    }
678
679    /// Try to receive a message without waiting.
680    pub fn try_recv(&mut self) -> Result<PeekResponseUnary, mpsc::error::TryRecvError> {
681        self.rx.try_recv()
682    }
683}
684
685impl Drop for SubscribeHandle {
686    fn drop(&mut self) {
687        if let Some(client) = self.client.take() {
688            // Fire-and-forget: if the coordinator is gone, the subscribe will
689            // be cleaned up when the process exits anyway.
690            client.try_send(Command::DropInternalSubscribe {
691                sink_id: self.sink_id,
692            });
693        }
694    }
695}
696
697impl PeekClient {
698    /// Executes a read-then-write for a statement of `session`.
699    ///
700    /// The caller owns the end-of-execution logging for
701    /// `statement_logging_id` and verified and planned the portal against
702    /// `catalog`, which stays in force through optimization and write-target
703    /// generation capture.
704    pub(crate) async fn session_read_then_write(
705        &mut self,
706        session: &mut Session,
707        plan: plan::ReadThenWritePlan,
708        target_cluster: TargetCluster,
709        catalog: &Arc<Catalog>,
710        statement_logging_id: Option<StatementLoggingId>,
711        attempt_state: Arc<WriteAttemptState>,
712    ) -> Result<ExecuteResponse, AdapterError> {
713        self.read_then_write(
714            session,
715            plan,
716            target_cluster,
717            catalog,
718            statement_logging_id,
719            attempt_state,
720            RtwCaller::Session,
721        )
722        .await
723    }
724
725    /// Executes a coordinator-owned read-then-write against system relations,
726    /// pinned to `replica_id`.
727    ///
728    /// See `RtwCaller::Background` for what the caller takes on by using this.
729    pub(crate) async fn background_read_then_write(
730        &mut self,
731        session: &mut Session,
732        plan: plan::ReadThenWritePlan,
733        cluster_id: ComputeInstanceId,
734        replica_id: ReplicaId,
735        catalog: &Arc<Catalog>,
736    ) -> Result<ExecuteResponse, AdapterError> {
737        let is_system_table = matches!(plan.id, CatalogItemId::System(_))
738            && catalog
739                .try_get_entry(&plan.id)
740                .is_some_and(|entry| matches!(entry.item(), CatalogItem::Table(_)));
741        if !is_system_table {
742            soft_panic_or_log!(
743                "background read-then-write target {} is not a system table",
744                plan.id
745            );
746            return Err(AdapterError::Internal(
747                "background read-then-write target is not a system table".into(),
748            ));
749        }
750
751        self.read_then_write(
752            session,
753            plan,
754            TargetCluster::Transaction(cluster_id),
755            catalog,
756            None,
757            // Nothing cancels a background write, so this state only ever
758            // records that a write was submitted.
759            Arc::new(WriteAttemptState::new()),
760            RtwCaller::Background { replica_id },
761        )
762        .await
763    }
764
765    #[allow(clippy::too_many_arguments)]
766    async fn read_then_write(
767        &mut self,
768        session: &mut Session,
769        mut plan: plan::ReadThenWritePlan,
770        target_cluster: TargetCluster,
771        catalog: &Arc<Catalog>,
772        statement_logging_id: Option<StatementLoggingId>,
773        attempt_state: Arc<WriteAttemptState>,
774        caller: RtwCaller,
775    ) -> Result<ExecuteResponse, AdapterError> {
776        // The OCC dataflow emits raw diffs and does not apply top-level
777        // finishing. Silently dropping a LIMIT, OFFSET, projection or ordering
778        // can change the rows written, so this stage requires trivial finishing.
779        if !plan.finishing.is_trivial(plan.selection.arity()) {
780            soft_panic_or_log!("frontend read-then-write received nontrivial row-set finishing");
781            return Err(AdapterError::Internal(
782                "frontend read-then-write requires trivial row-set finishing".into(),
783            ));
784        }
785
786        // A transaction that has taken a timestamped read, was opened READ
787        // ONLY, or is committed to some other kind of operation cannot take a
788        // write. Check up front because the marker op below rejects only
789        // some of those states and reports different errors.
790        //
791        // Both this and the marker op require an open transaction. The
792        // frontends start one before they execute anything, and a `Failed`
793        // transaction only ever admits COMMIT/ROLLBACK, so DML never arrives
794        // in a state where these panic.
795        if !session.transaction().allows_writes() {
796            return Err(AdapterError::ReadOnlyTransaction);
797        }
798
799        let validation_result = validate_read_then_write(
800            catalog,
801            session,
802            &plan,
803            target_cluster,
804            caller.dependency_policy(),
805        )?;
806
807        let ValidationResult {
808            cluster_id,
809            mut replica_id,
810            timeline,
811            depends_on,
812            table_desc,
813        } = validation_result;
814        if let Some(pinned) = caller.replica_override() {
815            replica_id = Some(pinned);
816        }
817
818        // A write that reads no persisted state may join a surrounding
819        // transaction. Its rows do not come from a snapshot, so staging them
820        // and letting the transaction flush them keeps them atomic with
821        // everything else the transaction does.
822        //
823        // A write that does read persisted state may not. We refuse it in an
824        // explicit transaction, and an extended-protocol pipeline is an
825        // implicit transaction, so it must not silently span one either. It
826        // runs as its own transaction instead, which is how PostgreSQL treats
827        // statements that cannot run in a transaction block.
828        let stages_rows = depends_on.is_empty();
829
830        // Snapshot this before the marker op below, which makes the predicate
831        // true unconditionally.
832        let in_transaction = session
833            .transaction()
834            .may_share_transaction_with_other_statements();
835
836        if !stages_rows && in_transaction {
837            // Defense in depth for the gate in
838            // `SessionClient::try_read_then_write`. Rejecting here,
839            // before we run a dataflow, is the last point where refusing is
840            // still possible: past the OCC loop the write may already be
841            // durable.
842            soft_panic_or_log!(
843                "read-dependent read-then-write reached the OCC path inside a transaction"
844            );
845            return Err(AdapterError::Internal(
846                "read-then-write cannot be run inside a transaction block".into(),
847            ));
848        }
849
850        // Mark this as a write transaction in the session state machine, so
851        // auto-commit treats the statement as a write. The rows follow once we
852        // know them.
853        session.add_transaction_ops(TransactionOps::Writes(vec![]))?;
854
855        // Prepare expressions (resolve unmaterializable functions like
856        // current_user())
857        let style = ExprPrepOneShot {
858            logical_time: EvalTime::NotAvailable, // We already errored out on mz_now above.
859            session,
860            catalog_state: catalog.state(),
861        };
862        for expr in plan
863            .assignments
864            .values_mut()
865            .chain(plan.returning.iter_mut())
866        {
867            style.prep_scalar_expr(expr)?;
868        }
869
870        let (mut optimizer, global_mir_plan) =
871            self.optimize_mir_read_then_write(catalog, session, &plan, cluster_id)?;
872
873        // Acquire the OCC semaphore permit *before* acquiring read holds in
874        // `determine_timestamp`. Under contention, waiters will
875        // otherwise sit on read holds on the RTW's read dependencies for the
876        // entire time they are queued, pinning compaction on those
877        // collections. Waiting on the permit first keeps queued operations
878        // hold-free. Once we have a permit we proceed to acquire the read holds
879        // needed for the rest of the operation.
880        //
881        // The cost of this ordering is that a permit held by a long-running
882        // operation stalls every read-then-write in the process, including ones
883        // on unrelated tables. We accept that because the
884        // statement timeout in
885        // `SessionClient::try_read_then_write_with_cancel` covers the
886        // permit wait, so the stall is bounded for everyone but a session that
887        // disabled its own timeout.
888        //
889        // The semaphore is owned by the coordinator and outlives every
890        // session task, so `acquire_owned` cannot return `Err` in practice.
891        //
892        // Background maintenance skips the queue entirely. It is single-flight
893        // by construction, one sweep at a time and one mutation at a time, so it
894        // adds at most one concurrent read-then-write. Taking a permit instead
895        // would let it hold one for as long as a subscribe on a loaded user
896        // replica takes to hydrate, and with `max_concurrent_occ_writes` set low
897        // that stalls user DML behind a background sampler. The bound above does
898        // not apply to it either: it has no statement timeout, only its own much
899        // longer one.
900        let permit = if caller.is_background() {
901            None
902        } else {
903            Some(
904                Arc::clone(&self.occ_write_semaphore)
905                    .acquire_owned()
906                    .await
907                    .expect("semaphore is never closed during coordinator lifetime"),
908            )
909        };
910
911        // Determine timestamp and acquire read holds.
912        let oracle_read_ts = self.oracle_read_ts(&timeline).await?;
913
914        // Real-time recency, on the same terms as the frontend peek path. The
915        // coordinator round trip polls the selection's upstream sources, so we
916        // only pay it when the session actually asked for recency.
917        let vars = session.vars();
918        let real_time_recency_ts: Option<Timestamp> = if vars.real_time_recency()
919            && vars.transaction_isolation() == &IsolationLevel::StrictSerializable
920            && !session.contains_read_timestamp()
921        {
922            let real_time_recency_timeout = *vars.real_time_recency_timeout();
923            self.call_coordinator(|tx| Command::DetermineRealTimeRecentTimestamp {
924                source_ids: depends_on.iter().copied().collect(),
925                real_time_recency_timeout,
926                tx,
927            })
928            .await??
929        } else {
930            None
931        };
932
933        let bundle = global_mir_plan.id_bundle(cluster_id);
934        let (determination, read_holds) = self
935            .determine_timestamp(
936                session,
937                &bundle,
938                &QueryWhen::FreshestTableWrite,
939                cluster_id,
940                &timeline,
941                oracle_read_ts,
942                real_time_recency_ts,
943            )
944            .await?;
945
946        let as_of = determination.timestamp_context.timestamp_or_default();
947
948        let global_mir_plan = global_mir_plan.resolve(Antichain::from_elem(as_of));
949        let global_lir_plan = optimizer.catch_unwind_optimize(global_mir_plan)?;
950
951        // Log optimization finished
952        if let Some(logging_id) = statement_logging_id {
953            self.log_lifecycle_event(logging_id, StatementLifecycleEvent::OptimizationFinished);
954        }
955
956        let sink_id = global_lir_plan.sink_id();
957        let target_id = plan.id;
958        let target_global_id = catalog.get_entry(&target_id).latest_global_id();
959        let kind = plan.kind.clone();
960        let returning = plan.returning.clone();
961
962        let (df_desc, df_meta) = global_lir_plan.unapply();
963
964        if !caller.is_background() {
965            crate::query_policy::check_query_policies(catalog, session, cluster_id, &df_desc)?;
966        }
967
968        crate::coord::sequencer::emit_optimizer_notices(
969            &**catalog,
970            session,
971            &df_meta.optimizer_notices,
972        );
973        if session.vars().emit_timestamp_notice() {
974            self.add_timestamp_notice(session, cluster_id, bundle, determination)
975                .await?;
976        }
977
978        let arity = df_desc
979            .sink_exports
980            .values()
981            .next()
982            .expect("has sink")
983            .from_desc
984            .arity();
985
986        let conn_id = session.conn_id().clone();
987        let session_uuid = session.uuid();
988        let start_time = (self.statement_logging_frontend.now)();
989        let max_result_size = catalog.system_config().max_result_size();
990        let max_query_result_size = session.vars().max_query_result_size();
991        let row_set_finishing_seconds = session.metrics().row_set_finishing_seconds().clone();
992        let max_occ_retries = usize::cast_from(catalog.system_config().max_occ_retries());
993
994        // Linearize the read BEFORE subscribing or writing: block until
995        // the oracle for this query's timeline has advanced to `as_of`.
996        //
997        // Ordering is load-bearing: this leaves the oracle at or above `as_of`,
998        // which is what makes the loop's target clear `as_of` and so include the
999        // snapshot. A far-future `as_of` parks here until the clock arrives,
1000        // bounded by `statement_timeout`.
1001        self.ensure_read_linearized(&timeline, as_of).await?;
1002
1003        // The loop takes its write target from this oracle, and reaching one takes
1004        // `&mut self`, which the loop does not have. `None` for a
1005        // timestamp-independent selection, which reads at `Timestamp::maximum()`
1006        // and so always leaves through the blind path rather than reaching a write.
1007        let write_oracle = match governing_timeline(&timeline) {
1008            Some(tl) => Some(Arc::clone(self.ensure_oracle(tl).await?)),
1009            None => None,
1010        };
1011
1012        let subscribe_handle = self
1013            .create_internal_subscribe(
1014                Box::new(df_desc),
1015                cluster_id,
1016                replica_id,
1017                depends_on.clone(),
1018                as_of,
1019                arity,
1020                sink_id,
1021                caller.subscribe_owner(&conn_id, session_uuid),
1022                start_time,
1023                read_holds,
1024            )
1025            .await?;
1026
1027        let (retry_count, result) = self
1028            .run_occ_loop(
1029                subscribe_handle,
1030                target_id,
1031                target_global_id,
1032                kind,
1033                returning,
1034                max_result_size,
1035                max_query_result_size,
1036                row_set_finishing_seconds,
1037                max_occ_retries,
1038                table_desc,
1039                caller.write_conn_id(&conn_id),
1040                statement_logging_id,
1041                as_of,
1042                write_oracle,
1043                &attempt_state,
1044            )
1045            .await;
1046
1047        let caller_label = match caller {
1048            RtwCaller::Session => OCC_CALLER_SESSION,
1049            RtwCaller::Background { .. } => OCC_CALLER_BACKGROUND,
1050        };
1051        self.coordinator_client()
1052            .metrics()
1053            .occ_retry_count
1054            .with_label_values(&[caller_label])
1055            .observe(f64::from(u32::try_from(retry_count).unwrap_or(u32::MAX)));
1056
1057        // Finish the operation, including a blind write's submission, before
1058        // releasing the OCC permit. Holding it for the entire operation is what
1059        // bounds concurrency. An early drop would let a waiter start its
1060        // subscribe while we are still consolidating diffs, retrying, or
1061        // waiting for our write to commit.
1062        //
1063        // The zero-row linearization wait below is the one exception, and hands
1064        // the permit back before it parks.
1065        let mut permit = permit;
1066        let response = match result {
1067            Ok(OccOutcome::Committed { response, write_ts }) => {
1068                // A committed write timestamp for a statement we meant to
1069                // stage means the two predicates disagreed: the syntactic one
1070                // said it reads nothing, the subscribe then read persisted
1071                // state. The write is already durable, so there is nothing to
1072                // refuse, and `apply_write` still has to run to keep the
1073                // session's read timestamps ahead of it.
1074                soft_assert_or_log!(
1075                    !stages_rows,
1076                    "read-then-write committed a write it meant to stage"
1077                );
1078                session.apply_write(write_ts);
1079                end_own_transaction(session, stages_rows);
1080                Ok(response)
1081            }
1082            Ok(OccOutcome::NoRowsMatched {
1083                response,
1084                empty_as_of,
1085            }) => {
1086                // An `empty_as_of` for a statement we meant to stage is the
1087                // same predicate disagreement the `Committed` arm guards
1088                // against: the syntactic answer said it reads nothing, the
1089                // subscribe then read persisted state. Nothing is durable here,
1090                // so there is nothing to undo, but the disagreement itself is
1091                // the bug and it would otherwise park silently.
1092                soft_assert_or_log!(
1093                    !(stages_rows && empty_as_of.is_some()),
1094                    "read-then-write observed a read timestamp for a statement \
1095                     it meant to stage"
1096                );
1097                end_own_transaction(session, stages_rows);
1098                match empty_as_of {
1099                    Some(empty_as_of) => {
1100                        // The wait is a no-op where the oracle is already past
1101                        // `empty_as_of`, which is the common `WHERE <no match>`,
1102                        // and otherwise costs the group commit that
1103                        // `ensure_read_linearized` asks for. Either way the
1104                        // subscribe handle is gone, so the permit guards nothing
1105                        // and holding it would throttle unrelated writes.
1106                        drop(permit.take());
1107                        self.ensure_read_linearized(&timeline, empty_as_of)
1108                            .await
1109                            .map(|()| response)
1110                    }
1111                    None => Ok(response),
1112                }
1113            }
1114            Ok(OccOutcome::Blind { response, diffs }) if stages_rows => {
1115                // Staging rather than writing here is what makes the statement
1116                // atomic with its transaction. An extended-protocol pipeline is
1117                // an implicit transaction, and it may still fail after us, so a
1118                // write of our own would survive a rollback that discards
1119                // everything around it.
1120                //
1121                // NOTE: A staged session write carries no target-generation
1122                // guard the way the immediate path's `target_global_id` does. A
1123                // `WriteOp` only names the `CatalogItemId`, and commit staging
1124                // resolves whatever global id is current then. What keeps it
1125                // safe is a check at the far end: group commit compares the
1126                // arity of the rows each staged write carries against the
1127                // target's latest `RelationDesc` and rolls the transaction back
1128                // with `ConcurrentDependencyMutation` instead of encoding old
1129                // rows against a new schema. So an `ALTER TABLE ... ADD COLUMN`
1130                // landing between here and the commit becomes the same
1131                // retryable failure the immediate path reports as
1132                // `TargetChanged`. The comparison reads one row per staged
1133                // write and looks only at arity, so it stands in for the
1134                // descriptor rather than pinning it.
1135                //
1136                // Missing the pin is true of every staged write. The arity
1137                // check is not: rows staged as a batch, which is how `COPY
1138                // FROM` arrives, carry their schema into persist instead.
1139                session
1140                    .add_transaction_ops(TransactionOps::Writes(vec![WriteOp {
1141                        id: target_id,
1142                        rows: TableData::Rows(diffs),
1143                    }]))
1144                    .map(|()| response)
1145            }
1146            Ok(OccOutcome::Blind { response, diffs }) => {
1147                if caller.is_background() {
1148                    return Err(AdapterError::Internal(
1149                        "background read-then-write unexpectedly had no persisted dependency"
1150                            .into(),
1151                    ));
1152                }
1153                // The subscribe closed on its own even though the selection
1154                // reads persisted state, so the input is sealed and the diffs
1155                // are frontier-independent after all. Staging them would be
1156                // safe for that reason, and we still do not, because it would
1157                // make a statement's transaction semantics depend on whether an
1158                // input happens to be past its last refresh. What the statement
1159                // reads decides, so this commits as its own transaction like
1160                // any other read-dependent write.
1161                match self
1162                    .submit_blind_write(
1163                        conn_id,
1164                        target_id,
1165                        target_global_id,
1166                        diffs,
1167                        statement_logging_id,
1168                        &attempt_state,
1169                    )
1170                    .await
1171                {
1172                    Ok(write_ts) => {
1173                        session.apply_write(write_ts);
1174                        end_own_transaction(session, stages_rows);
1175                        Ok(response)
1176                    }
1177                    Err(err) => Err(err),
1178                }
1179            }
1180            Err(err) => Err(err),
1181        };
1182
1183        drop(permit);
1184
1185        response
1186    }
1187
1188    /// Builds the subscribe optimizer and the unresolved global MIR plan for a
1189    /// read-then-write.
1190    ///
1191    /// The optimized expression is the selection with the mutation already
1192    /// applied, so the subscribe's sink emits ready-to-write table diffs rather
1193    /// than query results. `finishing` and `returning` are deliberately not part
1194    /// of the dataflow, and unmaterializable functions are prepared one-shot.
1195    fn optimize_mir_read_then_write(
1196        &self,
1197        catalog: &Arc<Catalog>,
1198        session: &dyn SessionMetadata,
1199        plan: &plan::ReadThenWritePlan,
1200        cluster_id: ComputeInstanceId,
1201    ) -> Result<
1202        (
1203            optimize::subscribe::Optimizer,
1204            optimize::subscribe::GlobalMirPlan<optimize::subscribe::Unresolved>,
1205        ),
1206        AdapterError,
1207    > {
1208        // `finishing` is unused: the OCC path emits raw diffs and
1209        // `apply_mutation_to_mir` handles update projection.
1210        let plan::ReadThenWritePlan {
1211            id: _,
1212            selection,
1213            finishing: _,
1214            assignments,
1215            kind,
1216            returning: _,
1217        } = plan;
1218
1219        let expr = selection.clone().lower(catalog.system_config(), None)?;
1220        let mut expr = apply_mutation_to_mir(expr, kind, assignments);
1221
1222        // Resolve unmaterializable functions (now(), current_user, ...) before
1223        // the subscribe optimizer sees them: it uses `ExprPrepMaintained`,
1224        // which rejects them, but our subscribe is a one-shot read so we can
1225        // resolve them to constants. `mz_now()` is rejected upstream by
1226        // `validate_read_then_write`.
1227        let style = ExprPrepOneShot {
1228            logical_time: EvalTime::NotAvailable,
1229            session,
1230            catalog_state: catalog.state(),
1231        };
1232        expr.try_visit_scalars_mut(&mut |s| style.prep_scalar_expr(s))?;
1233
1234        let compute_instance = ComputeInstanceSnapshot::new_without_collections(cluster_id);
1235        let (_, view_id) = self.transient_id_gen.allocate_id();
1236        let (_, sink_id) = self.transient_id_gen.allocate_id();
1237        let debug_name = format!("frontend-read-then-write-subscribe-{}", sink_id);
1238        let optimizer_config = optimize::OptimizerConfig::from(catalog.system_config())
1239            .override_from(&catalog.get_cluster(cluster_id).config.features())
1240            .override_from(
1241                &catalog
1242                    .state()
1243                    .cluster_scoped_optimizer_overrides(cluster_id),
1244            );
1245
1246        let mut optimizer = optimize::subscribe::Optimizer::new(
1247            Arc::<Catalog>::clone(catalog),
1248            compute_instance,
1249            view_id,
1250            sink_id,
1251            true, // with_snapshot
1252            None, // up_to
1253            debug_name,
1254            optimizer_config,
1255            self.optimizer_metrics.clone(),
1256        );
1257
1258        let expr_typ = expr.typ();
1259        let sql_typ = mz_repr::SqlRelationType::from_repr(&expr_typ);
1260        let column_names: Vec<String> = (0..sql_typ.column_types.len())
1261            .map(|i| format!("column{}", i))
1262            .collect();
1263        let relation_desc = RelationDesc::new(sql_typ, column_names.iter().map(|s| s.as_str()));
1264
1265        // MIR ⇒ MIR optimization (global). The mutation is already applied in
1266        // MIR, so we hand the expression to the subscribe optimizer directly
1267        // instead of going through the `SubscribePlan` path, which expects HIR.
1268        // An empty `output` makes the sink emit raw diffs.
1269        // `optimize_query` is not an `Optimize` impl, so wrap it by hand.
1270        let global_mir_plan = mz_transform::catch_unwind_optimize(|| {
1271            optimizer.optimize_query(expr, relation_desc, vec![])
1272        })?;
1273
1274        Ok((optimizer, global_mir_plan))
1275    }
1276
1277    /// The governing oracle's read timestamp, used as a lower bound for
1278    /// timestamp selection. `None` when the selection needs no oracle.
1279    async fn oracle_read_ts(
1280        &mut self,
1281        timeline: &TimelineContext,
1282    ) -> Result<Option<Timestamp>, AdapterError> {
1283        match governing_timeline(timeline) {
1284            Some(timeline) => {
1285                let oracle = self.ensure_oracle(timeline).await?;
1286                Ok(Some(oracle.read_ts().await))
1287            }
1288            None => Ok(None),
1289        }
1290    }
1291
1292    /// Block until the oracle for this query's timeline has advanced to
1293    /// `as_of`. Returns immediately if it already has.
1294    ///
1295    /// This implements the strict-serializable read guarantee for RTW:
1296    /// once this returns, any session observing the oracle sees a read
1297    /// timestamp at least as large as `as_of`, so reads at `as_of` (and
1298    /// writes derived from them) cannot appear to "go backwards" relative
1299    /// to subsequent queries.
1300    async fn ensure_read_linearized(
1301        &mut self,
1302        timeline: &TimelineContext,
1303        as_of: Timestamp,
1304    ) -> Result<(), AdapterError> {
1305        // Linearization must target the oracle future readers of the target
1306        // table will consult, which is why this uses `governing_timeline` and
1307        // not `TimelineContext::timeline()`. The latter answers "is there a
1308        // source-forced timeline?" and would skip linearization entirely for a
1309        // read side that pins none.
1310        let tl = match governing_timeline(timeline) {
1311            Some(tl) => tl,
1312            None => return Ok(()),
1313        };
1314
1315        // Cloned before `ensure_oracle` borrows `self` for the rest of this
1316        // function. The handle is an `Arc` internally, so this is cheap.
1317        let group_commit_notifier = self.group_commit_notifier.clone();
1318        let oracle = self.ensure_oracle(tl).await?;
1319
1320        // The oracle advances only when a group commit applies, and an empty
1321        // group commit is already the periodic keepalive. So when we have
1322        // nothing to write ourselves, waiting for the next tick costs up to a
1323        // full `default_timestamp_interval`. We ask for that commit instead of
1324        // waiting for it, which also spares the oracle the ~1ms poll below
1325        // running for the whole interval.
1326        //
1327        // Once per wait rather than once per poll. The committer never
1328        // allocates a write timestamp above wall clock, so a far-future `as_of`
1329        // cannot be reached by asking, and nudging per iteration would spin for
1330        // as long as such a statement legitimately parks. That case pays one
1331        // empty commit, which is what the keepalive would have done anyway.
1332        let mut nudged = false;
1333
1334        loop {
1335            let oracle_ts = oracle.read_ts().await;
1336            if as_of <= oracle_ts {
1337                return Ok(());
1338            }
1339
1340            if !nudged {
1341                group_commit_notifier.notify();
1342                nudged = true;
1343            }
1344
1345            // Sleep for roughly the difference between as_of and the current
1346            // oracle timestamp. Since timestamps are epoch milliseconds, the
1347            // difference is the approximate wall-clock time we need to wait.
1348            // Cap at 1s to avoid very long sleeps if clocks are skewed,
1349            // matching the cap in `message_linearize_reads`.
1350            let wait_ms = u64::from(as_of.saturating_sub(oracle_ts));
1351            let wait = Duration::from_millis(wait_ms).min(Duration::from_secs(1));
1352            tokio::time::sleep(wait).await;
1353        }
1354    }
1355
1356    /// Submits frontier-independent diffs to group commit, which picks the
1357    /// write timestamp, and returns the timestamp the write committed at.
1358    ///
1359    /// Only valid for diffs that do not depend on an observed read frontier:
1360    /// the write lands at a timestamp this caller does not choose.
1361    async fn submit_blind_write(
1362        &self,
1363        conn_id: mz_adapter_types::connection::ConnectionId,
1364        target_id: CatalogItemId,
1365        target_global_id: GlobalId,
1366        diffs: Vec<(Row, Diff)>,
1367        statement_logging_id: Option<StatementLoggingId>,
1368        attempt_state: &WriteAttemptState,
1369    ) -> Result<Timestamp, AdapterError> {
1370        attempt_state.mark_write_submitted();
1371        let result = self
1372            .call_coordinator(|tx| Command::AttemptWrite {
1373                attempt: WriteAttemptKind::Session {
1374                    conn_id,
1375                    write_ts: None,
1376                },
1377                target_id,
1378                target_global_id,
1379                diffs,
1380                tx,
1381            })
1382            .await?;
1383
1384        // Every outcome here terminates the attempt, so `write_submitted`
1385        // stays set per its contract.
1386        match classify_write_result(result, target_id, attempt_state) {
1387            WriteOutcome::Committed(timestamp) => {
1388                if let Some(id) = statement_logging_id {
1389                    self.log_set_timestamp(id, timestamp);
1390                }
1391                Ok(timestamp)
1392            }
1393            WriteOutcome::Failed(err) => Err(err),
1394            WriteOutcome::Conflict { .. } => {
1395                // Unreachable: a write that requests no timestamp cannot have
1396                // one pass. Group commit resolves it through
1397                // `UserWriteResponder::Internal`, which only reports a conflict
1398                // to a write that asked for a specific timestamp.
1399                soft_panic_or_log!("blind read-then-write unexpectedly got TimestampPassed");
1400                Err(AdapterError::Internal(
1401                    "blind write unexpectedly got TimestampPassed".into(),
1402                ))
1403            }
1404        }
1405    }
1406
1407    /// Creates an internal subscribe, meaning one that writes no
1408    /// `mz_subscriptions` row. Returns a [`SubscribeHandle`] that ensures
1409    /// cleanup on drop.
1410    async fn create_internal_subscribe(
1411        &self,
1412        df_desc: Box<optimize::LirDataflowDescription>,
1413        cluster_id: ComputeInstanceId,
1414        replica_id: Option<ReplicaId>,
1415        depends_on: BTreeSet<GlobalId>,
1416        as_of: Timestamp,
1417        arity: usize,
1418        sink_id: GlobalId,
1419        owner: ActiveSubscribeOwner,
1420        start_time: mz_ore::now::EpochMillis,
1421        read_holds: crate::ReadHolds,
1422    ) -> Result<SubscribeHandle, AdapterError> {
1423        let rx: mpsc::UnboundedReceiver<PeekResponseUnary> = self
1424            .call_coordinator(|tx| Command::CreateInternalSubscribe {
1425                df_desc,
1426                cluster_id,
1427                replica_id,
1428                depends_on,
1429                as_of,
1430                arity,
1431                sink_id,
1432                owner,
1433                start_time,
1434                read_holds,
1435                tx,
1436            })
1437            .await??;
1438
1439        Ok(SubscribeHandle {
1440            rx,
1441            sink_id,
1442            client: Some(self.coordinator_client().clone()),
1443        })
1444    }
1445
1446    /// Run the OCC loop: drain the subscribe at `as_of`, apply the
1447    /// mutation, and submit the resulting diffs as a write.
1448    ///
1449    /// Semantically a SELECT at `target - 1` followed by an INSERT at `target`.
1450    /// `write_oracle` chooses `target`, the subscribe's frontier certifies the
1451    /// payload is complete below it, and a target the target table has moved
1452    /// past comes back as `WriteResult::TimestampPassed`, whose next eligible
1453    /// timestamp the loop adopts. At most `max_occ_retries` attempts.
1454    ///
1455    /// A subscribe that ends on its own has diffs no frontier can change, and
1456    /// those are returned as [`OccOutcome::Blind`] rather than written.
1457    ///
1458    /// Contract on the caller, both ends of the read: the oracle's read
1459    /// timestamp must be at or above `as_of` on entry, and an
1460    /// [`OccOutcome::NoRowsMatched`] must be linearized against its
1461    /// `empty_as_of` before the response goes out.
1462    ///
1463    /// `write_oracle` is `None` only for a timestamp-independent selection. Such
1464    /// a statement reads at `Timestamp::maximum()`, so it observes no progress
1465    /// past its `as_of` and always leaves through the blind path.
1466    ///
1467    /// Returns `(retry_count, result)` so the caller can record OCC retry
1468    /// metrics regardless of whether the operation succeeded or failed.
1469    async fn run_occ_loop(
1470        &self,
1471        mut subscribe_handle: SubscribeHandle,
1472        target_id: CatalogItemId,
1473        target_global_id: GlobalId,
1474        kind: MutationKind,
1475        returning: Vec<MirScalarExpr>,
1476        max_result_size: u64,
1477        max_query_result_size: u64,
1478        row_set_finishing_seconds: Histogram,
1479        max_occ_retries: usize,
1480        table_desc: RelationDesc,
1481        write_conn_id: Option<mz_adapter_types::connection::ConnectionId>,
1482        statement_logging_id: Option<StatementLoggingId>,
1483        as_of: Timestamp,
1484        write_oracle: Option<Arc<dyn TimestampOracle<Timestamp> + Send + Sync>>,
1485        attempt_state: &WriteAttemptState,
1486    ) -> (usize, Result<OccOutcome, AdapterError>) {
1487        let mut state = OccState::new();
1488
1489        // The timestamp the next attempt writes at, chosen when we are first
1490        // ready to attempt one and replaced only by a conflict. `None` until
1491        // then.
1492        let mut write_target: Option<Timestamp> = None;
1493
1494        // The smallest timestamp an attempt may target. `as_of` itself is out,
1495        // since the payload has to contain the snapshot the subscribe emits
1496        // there.
1497        //
1498        // `as_of` is `Timestamp::MAX` for a selection with no timestamp at all,
1499        // which is the selection whose subscribe closes on its own and leaves
1500        // through the blind path rather than a write. There is no timestamp
1501        // above `MAX`, so saturating keeps this total instead of asserting a
1502        // property of a value the write path never uses.
1503        let min_target = as_of.try_step_forward().unwrap_or(as_of);
1504
1505        // Retry invariant: the payload is the selection consolidated at
1506        // `target - 1`, and the diffs at or above `target` are concurrent with
1507        // the write, so a retry folds them in only once it raises the target.
1508        let result = loop {
1509            if let Some(error) = attempt_state.requested_error() {
1510                break Err(error);
1511            }
1512
1513            // Before a target is chosen, `min_target` is a lower bound on it, so
1514            // folding there consolidates the snapshot without admitting a diff a
1515            // write would have to treat as concurrent.
1516            let fold_target = write_target.unwrap_or(min_target);
1517
1518            // Already certified for the target we hold? Write. Otherwise wait for
1519            // the next subscribe message. Waiting first would hang after a
1520            // conflict, since an input settled until its next refresh sends
1521            // nothing further and does not close the channel either.
1522            //
1523            // Termination: the write arm awaits a round trip and only a conflict
1524            // returns to this one, raising `retry_count` towards
1525            // `max_occ_retries`, so neither arm spins.
1526            let attempt_write = match write_target {
1527                Some(target) if state.current_upper.is_some_and(|upper| upper >= target) => true,
1528                _ => {
1529                    let msg = match subscribe_handle.recv().await {
1530                        Some(msg) => msg,
1531                        None => {
1532                            // The channel closed cleanly, which says the
1533                            // selection can never change again, so these diffs
1534                            // are frontier-independent. It does not say the
1535                            // selection reads nothing persisted, a sealed
1536                            // `REFRESH AT` MV closes cleanly too. Either way no
1537                            // target separates them, and the caller decides
1538                            // where they go.
1539                            state.fold_all();
1540                            if state.payload.is_empty() {
1541                                break Ok(OccOutcome::NoRowsMatched {
1542                                    response: build_no_rows_response(&kind),
1543                                    empty_as_of: None,
1544                                });
1545                            }
1546                            let success_response = match build_success_response(
1547                                &kind,
1548                                &returning,
1549                                &state.payload,
1550                                max_result_size,
1551                                max_query_result_size,
1552                                &row_set_finishing_seconds,
1553                            ) {
1554                                Ok(response) => response,
1555                                Err(e) => break Err(e),
1556                            };
1557
1558                            break Ok(OccOutcome::Blind {
1559                                response: success_response,
1560                                diffs: std::mem::take(&mut state.payload),
1561                            });
1562                        }
1563                    };
1564
1565                    match process_message(
1566                        msg,
1567                        &mut state,
1568                        as_of,
1569                        fold_target,
1570                        max_result_size,
1571                        &table_desc,
1572                    ) {
1573                        ProcessResult::Continue { ready_to_write } => ready_to_write,
1574                        ProcessResult::NoRowsMatched { empty_as_of } => {
1575                            break Ok(OccOutcome::NoRowsMatched {
1576                                response: build_no_rows_response(&kind),
1577                                empty_as_of: Some(empty_as_of),
1578                            });
1579                        }
1580                        ProcessResult::Error(e) => break Err(e),
1581                    }
1582                }
1583            };
1584
1585            if !attempt_write {
1586                continue;
1587            }
1588
1589            // Drain buffered messages before attempting the write.
1590            let drain_err = loop {
1591                match subscribe_handle.try_recv() {
1592                    Ok(msg) => {
1593                        match process_message(
1594                            msg,
1595                            &mut state,
1596                            as_of,
1597                            fold_target,
1598                            max_result_size,
1599                            &table_desc,
1600                        ) {
1601                            ProcessResult::Continue { .. } => {}
1602                            ProcessResult::NoRowsMatched { empty_as_of } => {
1603                                break Some(Ok(OccOutcome::NoRowsMatched {
1604                                    response: build_no_rows_response(&kind),
1605                                    empty_as_of: Some(empty_as_of),
1606                                }));
1607                            }
1608                            ProcessResult::Error(e) => {
1609                                break Some(Err(e));
1610                            }
1611                        }
1612                    }
1613                    Err(mpsc::error::TryRecvError::Empty) => break None,
1614                    // The subscribe can finish (coordinator drops the sender
1615                    // after `process_response` returns true) between our last
1616                    // recv() and this drain. This is benign, all buffered
1617                    // messages have already been consumed via the Ok(msg) arm
1618                    // above.
1619                    Err(mpsc::error::TryRecvError::Disconnected) => break None,
1620                }
1621            };
1622            if let Some(result) = drain_err {
1623                break result;
1624            }
1625
1626            let upper = state
1627                .current_upper
1628                .expect("a write attempt requires an observed frontier");
1629
1630            let target = match write_target {
1631                Some(target) => target,
1632                None => {
1633                    let Some(oracle) = &write_oracle else {
1634                        // Invariant: a statement with no governing timeline
1635                        // reads at `as_of == Timestamp::maximum()`, so it
1636                        // observes no progress past its `as_of` and leaves
1637                        // through the blind arm above rather than reaching a
1638                        // write.
1639                        soft_panic_or_log!(
1640                            "read-then-write reached a write attempt with no governing timeline"
1641                        );
1642                        break Err(AdapterError::Internal(
1643                            "read-then-write has no oracle to take a write timestamp from".into(),
1644                        ));
1645                    };
1646
1647                    // One step above the oracle's write timestamp is the smallest
1648                    // value `commit_timestamped` accepts.
1649                    let peek_write_ts = oracle.peek_write_ts().await;
1650                    let Some(chosen) = peek_write_ts.try_step_forward() else {
1651                        // A timeline that reached `Timestamp::MAX` is a broken
1652                        // environment, not anything this statement did.
1653                        soft_panic_or_log!(
1654                            "read-then-write cannot target a timestamp above the write \
1655                             timeline's timestamp {peek_write_ts}"
1656                        );
1657                        break Err(AdapterError::Internal(format!(
1658                            "write timeline exhausted at timestamp {peek_write_ts}"
1659                        )));
1660                    };
1661
1662                    // Unreachable while the oracle's read timestamp is at or
1663                    // above `as_of` on entry, and the clamp keeps the payload
1664                    // rule rather than only reporting the violation.
1665                    if chosen < min_target {
1666                        soft_panic_or_log!(
1667                            "read-then-write target {chosen} does not clear the as_of {as_of}, \
1668                             so the payload would miss the snapshot"
1669                        );
1670                    }
1671                    let chosen = std::cmp::max(chosen, min_target);
1672
1673                    write_target = Some(chosen);
1674                    chosen
1675                }
1676            };
1677
1678            // Fold in what the drain picked up, plus anything a target raised
1679            // by the last conflict now admits.
1680            state.fold_below(target);
1681
1682            // A write at `target` needs every diff below it, which is what
1683            // progress at or above `target` certifies. Waiting for the next
1684            // message is bounded by `statement_timeout`, like every wait here.
1685            if upper < target {
1686                continue;
1687            }
1688
1689            if state.payload.is_empty() {
1690                // Everything below `target` cancelled out, so there is nothing to
1691                // write and the answer holds as of `target - 1`. Diffs pending at
1692                // or above `target` are concurrent with the write this would have
1693                // been and do not enter it.
1694                break Ok(OccOutcome::NoRowsMatched {
1695                    response: build_no_rows_response(&kind),
1696                    empty_as_of: Some(empty_as_of(target)),
1697                });
1698            }
1699
1700            let success_response = match build_success_response(
1701                &kind,
1702                &returning,
1703                &state.payload,
1704                max_result_size,
1705                max_query_result_size,
1706                &row_set_finishing_seconds,
1707            ) {
1708                Ok(response) => response,
1709                Err(e) => break Err(e),
1710            };
1711
1712            // Submit write.
1713            //
1714            // TODO(aljoscha): Store `Arc<Row>` in the payload if this shows up
1715            // in profiles. Every attempt clones every row, and we retry up to
1716            // `max_occ_retries` times.
1717            attempt_state.mark_write_submitted();
1718            let result = match self
1719                .call_coordinator(|tx| Command::AttemptWrite {
1720                    attempt: match write_conn_id.clone() {
1721                        Some(conn_id) => WriteAttemptKind::Session {
1722                            conn_id,
1723                            write_ts: Some(target),
1724                        },
1725                        None => WriteAttemptKind::Background { write_ts: target },
1726                    },
1727                    target_id,
1728                    target_global_id,
1729                    diffs: state.payload.clone(),
1730                    tx,
1731                })
1732                .await
1733            {
1734                Ok(result) => result,
1735                Err(error) => break Err(error),
1736            };
1737
1738            match classify_write_result(result, target_id, attempt_state) {
1739                WriteOutcome::Committed(timestamp) => {
1740                    if let Some(id) = statement_logging_id {
1741                        self.log_set_timestamp(id, timestamp);
1742                    }
1743                    // N.B. subscribe_handle is dropped here, which fires off
1744                    // the cleanup message.
1745                    break Ok(OccOutcome::Committed {
1746                        response: success_response,
1747                        write_ts: timestamp,
1748                    });
1749                }
1750                WriteOutcome::Failed(err) => break Err(err),
1751                WriteOutcome::Conflict {
1752                    next_eligible_timestamp,
1753                } => {
1754                    // The write definitively did not land, so the attempt is
1755                    // resolved. Clearing `write_submitted` lets a cancel or
1756                    // statement timeout that fires during the upcoming
1757                    // subscribe wait resolve promptly instead of awaiting a
1758                    // write result.
1759                    attempt_state.mark_write_resolved();
1760                    // Adopt the timestamp the committer reported as next
1761                    // eligible. The accumulated diffs say nothing about it
1762                    // yet, and they do not have to: the readiness check above
1763                    // holds the next attempt until the subscribe has certified
1764                    // everything below the new target, and the fold then moves
1765                    // the diffs in between into the payload.
1766                    write_target = Some(next_eligible_timestamp);
1767                    state.retry_count += 1;
1768                    // Cancellation wins over the retry budget: if both apply,
1769                    // the user asked us to stop and that is the more truthful
1770                    // answer.
1771                    if let Some(error) = attempt_state.requested_error() {
1772                        break Err(error);
1773                    }
1774                    if state.retry_count > max_occ_retries {
1775                        // Contention is a user-visible condition, not an
1776                        // internal invariant violation, and every attempt was
1777                        // refused before anything was appended, so the
1778                        // statement is retryable.
1779                        break Err(AdapterError::ReadThenWriteContention);
1780                    }
1781                    tracing::debug!(
1782                        retry_count = state.retry_count,
1783                        write_ts = %target,
1784                        next_eligible_timestamp = %next_eligible_timestamp,
1785                        "OCC write conflict, retrying"
1786                    );
1787                    continue;
1788                }
1789            }
1790        };
1791
1792        (state.retry_count, result)
1793    }
1794}
1795
1796/// Result of validating a read-then-write operation.
1797struct ValidationResult {
1798    cluster_id: ComputeInstanceId,
1799    replica_id: Option<ReplicaId>,
1800    timeline: TimelineContext,
1801    depends_on: BTreeSet<GlobalId>,
1802    /// The table descriptor, used for constraint validation.
1803    table_desc: RelationDesc,
1804}
1805
1806/// Accumulated state for the OCC loop in `run_occ_loop`.
1807///
1808/// Every diff the subscribe ever sent is kept, split at [`Self::split`]. The
1809/// split only rises, so each diff crosses it once.
1810struct OccState {
1811    /// Consolidated net diffs from strictly below [`Self::split`].
1812    payload: Vec<(Row, Diff)>,
1813    /// Diffs at or above [`Self::split`], consolidated by `(row, timestamp)`.
1814    pending: Vec<(Row, Timestamp, Diff)>,
1815    /// Where the last fold split the diffs, `None` before the first one.
1816    split: Option<Timestamp>,
1817    /// Timestamp of the last progress message, which certifies that no diff
1818    /// will arrive below it.
1819    current_upper: Option<Timestamp>,
1820    retry_count: usize,
1821    /// Row bytes held in `payload` and `pending` together, which is what the
1822    /// `max_result_size` check measures. `pending` is consolidated by
1823    /// `(row, timestamp)`, so a row touched at several timestamps occupies
1824    /// several entries until a rising split folds them together, and the count
1825    /// can exceed the size of the payload that eventually goes out.
1826    byte_size: u64,
1827}
1828
1829impl OccState {
1830    fn new() -> Self {
1831        Self {
1832            payload: Vec::new(),
1833            pending: Vec::new(),
1834            split: None,
1835            current_upper: None,
1836            retry_count: 0,
1837            byte_size: 0,
1838        }
1839    }
1840
1841    /// Raises the split to `split`, moving the diffs below it into the payload.
1842    ///
1843    /// Lowering it is a bug: the payload is consolidated and never re-split, so
1844    /// the diffs above a lowered split would stay in it. We clamp to the old
1845    /// split, which keeps the payload's contract intact.
1846    fn fold_below(&mut self, split: Timestamp) {
1847        let split = match self.split {
1848            Some(previous) if split < previous => {
1849                soft_panic_or_log!(
1850                    "read-then-write folded at {split}, below its previous split {previous}"
1851                );
1852                previous
1853            }
1854            _ => split,
1855        };
1856        self.split = Some(split);
1857        self.fold(Some(split));
1858    }
1859
1860    /// Moves every accumulated diff into the payload, whatever its timestamp.
1861    ///
1862    /// Only valid once the subscribe has run to completion, where the diffs are
1863    /// frontier-independent and no split separates them.
1864    fn fold_all(&mut self) {
1865        self.fold(None);
1866    }
1867
1868    /// Moves the diffs below `split`, or all of them when it is `None`, into the
1869    /// payload, consolidates both halves, and recomputes `byte_size`.
1870    fn fold(&mut self, split: Option<Timestamp>) {
1871        for (row, ts, diff) in std::mem::take(&mut self.pending) {
1872            match split {
1873                Some(split) if ts >= split => self.pending.push((row, ts, diff)),
1874                _ => self.payload.push((row, diff)),
1875            }
1876        }
1877        consolidation::consolidate(&mut self.payload);
1878        consolidation::consolidate_updates(&mut self.pending);
1879        self.byte_size = self
1880            .payload
1881            .iter()
1882            .map(|(row, _)| u64::cast_from(row.byte_len()))
1883            .chain(
1884                self.pending
1885                    .iter()
1886                    .map(|(row, _, _)| u64::cast_from(row.byte_len())),
1887            )
1888            .sum();
1889    }
1890
1891    /// Whether nothing has been accumulated on either side of the split.
1892    fn is_empty(&self) -> bool {
1893        self.payload.is_empty() && self.pending.is_empty()
1894    }
1895}
1896
1897/// Result of processing a single subscribe message in the OCC loop.
1898enum ProcessResult {
1899    Continue {
1900        ready_to_write: bool,
1901    },
1902    /// The consolidated selection is empty, as of the timestamp reported. See
1903    /// [`OccOutcome::NoRowsMatched`].
1904    NoRowsMatched {
1905        empty_as_of: Timestamp,
1906    },
1907    Error(AdapterError),
1908}
1909
1910/// Process one subscribe message, updating `state` in place.
1911///
1912/// Data rows are accumulated into `state` (with per-row constraint and
1913/// max-result-size checks). Progress messages fold everything below
1914/// `fold_target` into the payload and can promote the accumulated diffs to
1915/// "ready to write".
1916///
1917/// `fold_target` must not exceed the timestamp the next write attempt uses, or
1918/// the payload takes in a diff that is concurrent with that write.
1919fn process_message(
1920    response: PeekResponseUnary,
1921    state: &mut OccState,
1922    as_of: Timestamp,
1923    fold_target: Timestamp,
1924    max_result_size: u64,
1925    table_desc: &RelationDesc,
1926) -> ProcessResult {
1927    match response {
1928        PeekResponseUnary::Rows(mut rows) => {
1929            let mut saw_progress = false;
1930
1931            while let Some(row) = rows.next() {
1932                let mut datums = row.iter();
1933
1934                // Extract mz_timestamp (SubscribeOutput::Diffs format:
1935                // mz_timestamp, mz_progressed, mz_diff, ...data columns...).
1936                //
1937                // Format drift would mean we'd silently commit an incorrect
1938                // write, so surface every shape mismatch as an internal
1939                // error rather than panicking the process.
1940                let Some(ts_datum) = datums.next() else {
1941                    return ProcessResult::Error(AdapterError::Internal(
1942                        "missing mz_timestamp in subscribe output".into(),
1943                    ));
1944                };
1945                let ts = match ts_datum {
1946                    mz_repr::Datum::Numeric(n) => match n.0.try_into() {
1947                        Ok(ts_u64) => Timestamp::new(ts_u64),
1948                        Err(_) => {
1949                            return ProcessResult::Error(AdapterError::Internal(format!(
1950                                "mz_timestamp in subscribe output is not a valid u64: {n}"
1951                            )));
1952                        }
1953                    },
1954                    other => {
1955                        return ProcessResult::Error(AdapterError::Internal(format!(
1956                            "unexpected mz_timestamp datum: {other:?}"
1957                        )));
1958                    }
1959                };
1960
1961                let Some(progressed_datum) = datums.next() else {
1962                    return ProcessResult::Error(AdapterError::Internal(
1963                        "missing mz_progressed in subscribe output".into(),
1964                    ));
1965                };
1966                let is_progress = matches!(progressed_datum, mz_repr::Datum::True);
1967
1968                if is_progress {
1969                    state.current_upper = Some(ts);
1970                    saw_progress = true;
1971
1972                    // Fold and consolidate incrementally on each progress
1973                    // message. This keeps memory bounded by the consolidated
1974                    // size and makes the byte_size check below accurate (except
1975                    // for rows received between two progress messages, which is
1976                    // a small window).
1977                    state.fold_below(fold_target);
1978
1979                    // NOTE: The first progress message is always at `as_of`,
1980                    // emitted by `ActiveSubscribe::initialize` before any data
1981                    // batch, so the accumulation is empty there whatever the
1982                    // snapshot holds. Later progress is gated on `batch.upper >
1983                    // as_of` (see `crate::active_compute_sink`), so `ts > as_of`
1984                    // is what distinguishes a real answer from that first one.
1985                    //
1986                    // Nothing accumulated at all, so no write is coming and the
1987                    // loop would otherwise wait for diffs that will not arrive.
1988                    // Our view is complete below `ts` and the payload covers
1989                    // below `fold_target`, so the emptiness holds as of one below
1990                    // the earlier of the two.
1991                    if ts > as_of && state.is_empty() {
1992                        return ProcessResult::NoRowsMatched {
1993                            empty_as_of: empty_as_of(std::cmp::min(ts, fold_target)),
1994                        };
1995                    }
1996                } else {
1997                    let Some(diff_datum) = datums.next() else {
1998                        return ProcessResult::Error(AdapterError::Internal(
1999                            "missing mz_diff in subscribe output".into(),
2000                        ));
2001                    };
2002                    let diff = match diff_datum {
2003                        mz_repr::Datum::Int64(d) => Diff::from(d),
2004                        other => {
2005                            return ProcessResult::Error(AdapterError::Internal(format!(
2006                                "unexpected mz_diff datum while processing read-then-write: {other:?}"
2007                            )));
2008                        }
2009                    };
2010
2011                    let data_row = Row::pack(datums);
2012
2013                    // Validate constraints for rows being added (positive diff)
2014                    if diff.is_positive() {
2015                        for (idx, datum) in data_row.iter().enumerate() {
2016                            if let Err(e) = table_desc.constraints_met(idx, &datum) {
2017                                return ProcessResult::Error(e.into());
2018                            }
2019                        }
2020                    }
2021
2022                    state.byte_size = state
2023                        .byte_size
2024                        .saturating_add(u64::cast_from(data_row.byte_len()));
2025                    if state.byte_size > max_result_size {
2026                        return ProcessResult::Error(AdapterError::ResultSize(format!(
2027                            "result exceeds max size of {}",
2028                            ByteSize::b(max_result_size)
2029                        )));
2030                    }
2031                    state.pending.push((data_row, ts, diff));
2032                }
2033            }
2034
2035            // The complement of the zero-row exit above: something accumulated
2036            // means a write is coming, nothing at all means there is none.
2037            let ready_to_write = saw_progress && !state.is_empty();
2038            ProcessResult::Continue { ready_to_write }
2039        }
2040        PeekResponseUnary::Error(e) => {
2041            ProcessResult::Error(AdapterError::Unstructured(anyhow::anyhow!(e)))
2042        }
2043        // `Unstructured` would misclassify an ordinary concurrent DDL race
2044        // as an internal error (XX000).
2045        PeekResponseUnary::DependencyDropped(dep) => {
2046            ProcessResult::Error(dep.to_concurrent_dependency_drop())
2047        }
2048        PeekResponseUnary::Canceled => ProcessResult::Error(AdapterError::Canceled),
2049    }
2050}
2051
2052/// The timestamp an answer holds as of, given a view complete strictly below
2053/// `complete_below`.
2054///
2055/// Both callers derive `complete_below` from a timestamp strictly above the
2056/// subscribe's `as_of`, so it is never `Timestamp::MIN` and the saturating
2057/// fallback is unreachable.
2058fn empty_as_of(complete_below: Timestamp) -> Timestamp {
2059    complete_below.step_back().unwrap_or(complete_below)
2060}
2061
2062/// Build the response returned when no rows matched the selection.
2063///
2064/// TODO: Return an empty result set for zero-row `INSERT ... RETURNING`, as
2065/// Postgres does, instead of a plain row count.
2066fn build_no_rows_response(kind: &MutationKind) -> ExecuteResponse {
2067    match kind {
2068        MutationKind::Delete => ExecuteResponse::Deleted(0),
2069        MutationKind::Update => ExecuteResponse::Updated(0),
2070        MutationKind::Insert => ExecuteResponse::Inserted(0),
2071    }
2072}
2073
2074/// Transform a MIR expression to produce the appropriate diffs for a mutation.
2075///
2076/// - DELETE: Negates the expression to produce `(row, -1)` diffs
2077/// - UPDATE: Unions negated old rows with mapped new rows to produce both
2078///   `(old_row, -1)` and `(new_row, +1)` diffs
2079fn apply_mutation_to_mir(
2080    expr: MirRelationExpr,
2081    kind: &MutationKind,
2082    assignments: &BTreeMap<usize, MirScalarExpr>,
2083) -> MirRelationExpr {
2084    match kind {
2085        MutationKind::Delete => MirRelationExpr::Negate {
2086            input: Box::new(expr),
2087        },
2088        MutationKind::Update => {
2089            let arity = expr.arity();
2090
2091            // Find a fresh LocalId that won't conflict with any in the expression.
2092            //
2093            // Invariant: `Let` and `LetRec` are the only MIR nodes that *bind*
2094            // LocalIds. `Get` references them but does not introduce new ones.
2095            // So scanning just those two node kinds and picking `max + 1` is
2096            // guaranteed to produce an id unused by the subtree.
2097            let mut max_id = 0_u64;
2098            expr.visit_pre(|e| match e {
2099                MirRelationExpr::Let { id, .. } => {
2100                    max_id = std::cmp::max(max_id, id.into());
2101                }
2102                MirRelationExpr::LetRec { ids, .. } => {
2103                    for id in ids {
2104                        max_id = std::cmp::max(max_id, id.into());
2105                    }
2106                }
2107                _ => {}
2108            });
2109            let binding_id = LocalId::new(max_id + 1);
2110
2111            let get_binding = MirRelationExpr::Get {
2112                id: Id::Local(binding_id),
2113                typ: expr.typ(),
2114                access_strategy: mz_expr::AccessStrategy::UnknownOrLocal,
2115            };
2116
2117            let map_scalars: Vec<MirScalarExpr> = (0..arity)
2118                .map(|i| {
2119                    assignments
2120                        .get(&i)
2121                        .cloned()
2122                        .unwrap_or_else(|| MirScalarExpr::column(i))
2123                })
2124                .collect();
2125
2126            let new_rows = get_binding
2127                .clone()
2128                .map(map_scalars)
2129                .project((arity..2 * arity).collect());
2130
2131            let old_rows = MirRelationExpr::Negate {
2132                input: Box::new(get_binding),
2133            };
2134
2135            let body = new_rows.union(old_rows);
2136
2137            MirRelationExpr::Let {
2138                id: binding_id,
2139                value: Box::new(expr),
2140                body: Box::new(body),
2141            }
2142        }
2143        // INSERT: rows pass through unchanged, the subscribe emits them with
2144        // diff +1.
2145        MutationKind::Insert => expr,
2146    }
2147}
2148
2149#[cfg(test)]
2150mod tests {
2151    use mz_repr::adt::numeric;
2152    use mz_repr::{Datum, IntoRowIterator};
2153
2154    use super::*;
2155
2156    fn row(value: i64) -> Row {
2157        Row::pack_slice(&[Datum::Int64(value)])
2158    }
2159
2160    /// A progress message in the subscribe's `SubscribeOutput::Diffs` shape:
2161    /// `mz_timestamp, mz_progressed, mz_diff, data...`.
2162    fn progress(ts: u64) -> PeekResponseUnary {
2163        let mut row = Row::default();
2164        let mut packer = row.packer();
2165        packer.push(Datum::from(numeric::Numeric::from(ts)));
2166        packer.push(Datum::True);
2167        packer.push(Datum::Null);
2168        PeekResponseUnary::Rows(Box::new(row.into_row_iter()))
2169    }
2170
2171    /// Accumulates `(row value, timestamp, diff)` triples the way
2172    /// `process_message` does, without going through a subscribe.
2173    fn accumulate(diffs: impl IntoIterator<Item = (i64, u64, i64)>) -> OccState {
2174        let mut state = OccState::new();
2175        for (value, ts, diff) in diffs {
2176            state
2177                .pending
2178                .push((row(value), Timestamp::new(ts), Diff::from(diff)));
2179        }
2180        state
2181    }
2182
2183    /// The target is the boundary the write turns on, so the off-by-one is the
2184    /// whole point: a diff at exactly the target is concurrent with the write
2185    /// and must not be in its payload.
2186    #[mz_ore::test]
2187    fn test_fold_below_splits_at_the_target() {
2188        let mut state = accumulate([(1, 9, 1), (2, 10, 1), (3, 11, 1)]);
2189        state.fold_below(Timestamp::new(10));
2190
2191        assert_eq!(state.payload, vec![(row(1), Diff::ONE)]);
2192        assert_eq!(
2193            state.pending,
2194            vec![
2195                (row(2), Timestamp::new(10), Diff::ONE),
2196                (row(3), Timestamp::new(11), Diff::ONE),
2197            ]
2198        );
2199    }
2200
2201    /// A retry raises the target, which is what admits the diffs that were
2202    /// concurrent with the attempt that lost.
2203    #[mz_ore::test]
2204    fn test_fold_below_moves_each_diff_once() {
2205        let mut state = accumulate([(1, 9, 1), (2, 10, 1), (3, 11, 1)]);
2206
2207        state.fold_below(Timestamp::new(10));
2208        assert_eq!(state.payload, vec![(row(1), Diff::ONE)]);
2209
2210        state.fold_below(Timestamp::new(11));
2211        assert_eq!(
2212            state.payload,
2213            vec![(row(1), Diff::ONE), (row(2), Diff::ONE)]
2214        );
2215        assert_eq!(state.pending, vec![(row(3), Timestamp::new(11), Diff::ONE)]);
2216
2217        state.fold_below(Timestamp::new(12));
2218        assert_eq!(
2219            state.payload,
2220            vec![
2221                (row(1), Diff::ONE),
2222                (row(2), Diff::ONE),
2223                (row(3), Diff::ONE),
2224            ]
2225        );
2226        assert!(state.pending.is_empty());
2227    }
2228
2229    /// A row inserted and retracted below the target leaves nothing behind,
2230    /// which is what makes the payload the net change rather than a log.
2231    #[mz_ore::test]
2232    fn test_fold_below_cancels_opposite_diffs() {
2233        let mut state = accumulate([(1, 9, 1), (1, 10, -1), (2, 9, 1)]);
2234        state.fold_below(Timestamp::new(11));
2235
2236        assert_eq!(state.payload, vec![(row(2), Diff::ONE)]);
2237        assert!(state.pending.is_empty());
2238        assert!(!state.is_empty());
2239    }
2240
2241    /// The same rows stay pending or move to the payload depending on the
2242    /// target, so a size check that saw only one half would let a statement
2243    /// past `max_result_size` by picking the other one.
2244    #[mz_ore::test]
2245    fn test_byte_size_counts_payload_and_pending() {
2246        let row_bytes = u64::cast_from(row(1).byte_len());
2247
2248        let mut state = accumulate([(1, 9, 1), (2, 10, 1), (3, 11, 1)]);
2249        state.fold_below(Timestamp::new(10));
2250        assert_eq!(state.payload.len(), 1);
2251        assert_eq!(state.pending.len(), 2);
2252        assert_eq!(state.byte_size, 3 * row_bytes);
2253
2254        state.fold_below(Timestamp::new(12));
2255        assert!(state.pending.is_empty());
2256        assert_eq!(state.byte_size, 3 * row_bytes);
2257    }
2258
2259    /// A subscribe that ran to completion has no target to split on, and
2260    /// cancellation still applies.
2261    #[mz_ore::test]
2262    fn test_fold_all_takes_every_timestamp() {
2263        let mut state = accumulate([(1, 9, 1), (1, 10, -1), (2, u64::MAX, 1)]);
2264        state.fold_all();
2265
2266        assert_eq!(state.payload, vec![(row(2), Diff::ONE)]);
2267        assert!(state.pending.is_empty());
2268    }
2269
2270    /// A zero-row answer holds as of the timestamp the answer was reached at,
2271    /// never an input's frontier. The caller waits for the oracle to reach
2272    /// whatever it gets, and an input settled until its next refresh reports a
2273    /// frontier days out, so reporting that would spend the statement's timeout
2274    /// on an answer of "0 rows".
2275    #[mz_ore::test]
2276    fn test_zero_rows_report_the_answer_not_the_frontier() {
2277        let as_of = Timestamp::new(10);
2278        let desc = RelationDesc::empty();
2279
2280        // First pass, where the fold target is `as_of + 1`. The answer holds at
2281        // `as_of`, which the caller linearized before the subscribe started, so
2282        // it costs no wait however far out the frontier is.
2283        let mut state = OccState::new();
2284        match process_message(
2285            progress(u64::MAX / 2),
2286            &mut state,
2287            as_of,
2288            as_of.step_forward(),
2289            u64::MAX,
2290            &desc,
2291        ) {
2292            ProcessResult::NoRowsMatched { empty_as_of } => assert_eq!(empty_as_of, as_of),
2293            _ => panic!("an empty selection past `as_of` must report no rows matched"),
2294        }
2295
2296        // A target raised by a conflict, with the frontier past it. The answer
2297        // holds at one below the target, the same timestamp a write there would
2298        // have been read at.
2299        let fold_target = Timestamp::new(20);
2300        let mut state = OccState::new();
2301        match process_message(
2302            progress(u64::MAX / 2),
2303            &mut state,
2304            as_of,
2305            fold_target,
2306            u64::MAX,
2307            &desc,
2308        ) {
2309            ProcessResult::NoRowsMatched { empty_as_of } => {
2310                assert_eq!(empty_as_of, Timestamp::new(19))
2311            }
2312            _ => panic!("an empty selection past `as_of` must report no rows matched"),
2313        }
2314
2315        // A frontier below the target certifies less, so the answer holds one
2316        // below the frontier instead.
2317        let mut state = OccState::new();
2318        match process_message(
2319            progress(15),
2320            &mut state,
2321            as_of,
2322            fold_target,
2323            u64::MAX,
2324            &desc,
2325        ) {
2326            ProcessResult::NoRowsMatched { empty_as_of } => {
2327                assert_eq!(empty_as_of, Timestamp::new(14))
2328            }
2329            _ => panic!("an empty selection past `as_of` must report no rows matched"),
2330        }
2331    }
2332
2333    /// Diffs waiting above the target mean a write is still coming, so the
2334    /// answer is not "no rows" yet even with an empty payload.
2335    #[mz_ore::test]
2336    fn test_pending_diffs_are_not_a_zero_row_answer() {
2337        let as_of = Timestamp::new(10);
2338        let desc = RelationDesc::empty();
2339
2340        let mut state = accumulate([(1, 30, 1)]);
2341        match process_message(
2342            progress(20),
2343            &mut state,
2344            as_of,
2345            as_of.step_forward(),
2346            u64::MAX,
2347            &desc,
2348        ) {
2349            ProcessResult::Continue { ready_to_write } => assert!(ready_to_write),
2350            _ => panic!("a selection with diffs above the target must not report no rows"),
2351        }
2352    }
2353}