mz_adapter/coord/appends.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//! Logic and types for all appends executed by the [`Coordinator`].
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::{Arc, LazyLock};
16use std::time::{Duration, Instant};
17
18use derivative::Derivative;
19use futures::future::{BoxFuture, FutureExt};
20use mz_adapter_types::connection::ConnectionId;
21use mz_catalog::builtin::{BuiltinTable, MZ_SESSIONS};
22use mz_expr::CollectionPlan;
23use mz_ore::metrics::MetricsFutureExt;
24use mz_ore::task;
25use mz_ore::tracing::OpenTelemetryContext;
26use mz_ore::{assert_none, instrument};
27use mz_repr::{CatalogItemId, Timestamp};
28use mz_sql::names::ResolvedIds;
29use mz_sql::plan::{ExplainPlanPlan, ExplainTimestampPlan, Explainee, ExplaineeStatement, Plan};
30use mz_sql::session::metadata::SessionMetadata;
31use mz_storage_client::client::TableData;
32use mz_timestamp_oracle::WriteTimestamp;
33use smallvec::SmallVec;
34use tokio::sync::{Notify, OwnedMutexGuard, OwnedSemaphorePermit, Semaphore, oneshot};
35use tracing::{Instrument, Span, debug_span, info, warn};
36
37use crate::catalog::{BuiltinTableUpdate, Catalog};
38use crate::coord::{Coordinator, Message, PendingTxn, PlanValidity};
39use crate::session::{GroupCommitWriteLocks, Session, WriteLocks};
40use crate::util::{CompletedClientTransmitter, ResultExt};
41use crate::{AdapterError, ExecuteContext};
42
43/// Tables that we emit updates for when starting a new session.
44pub(crate) static REQUIRED_BUILTIN_TABLES: &[&LazyLock<BuiltinTable>] = &[&MZ_SESSIONS];
45
46/// An operation that was deferred waiting on a resource to be available.
47///
48/// For example when inserting into a table we defer on acquiring [`WriteLocks`].
49#[derive(Debug)]
50pub enum DeferredOp {
51 /// A plan, e.g. ReadThenWrite, that needs locks before sequencing.
52 Plan(DeferredPlan),
53 /// Inserts into a collection.
54 Write(DeferredWrite),
55}
56
57impl DeferredOp {
58 /// Certain operations, e.g. "blind writes"/`INSERT` statements, can be optimistically retried
59 /// because we can share a write lock between multiple operations. In this case we wait to
60 /// acquire the locks until [`group_commit`], where writes are groupped by collection and
61 /// comitted at a single timestamp.
62 ///
63 /// Other operations, e.g. read-then-write plans/`UPDATE` statements, must uniquely hold their
64 /// write locks and thus we should acquire the locks in [`try_deferred`] to prevent multiple
65 /// queued plans attempting to get retried at the same time, when we know only one can proceed.
66 ///
67 /// [`try_deferred`]: crate::coord::Coordinator::try_deferred
68 /// [`group_commit`]: crate::coord::Coordinator::group_commit
69 pub(crate) fn can_be_optimistically_retried(&self) -> bool {
70 match self {
71 DeferredOp::Plan(_) => false,
72 DeferredOp::Write(_) => true,
73 }
74 }
75
76 /// Returns an Iterator of all the required locks for current operation.
77 pub fn required_locks(&self) -> impl Iterator<Item = CatalogItemId> + '_ {
78 match self {
79 DeferredOp::Plan(plan) => {
80 let iter = plan.requires_locks.iter().copied();
81 itertools::Either::Left(iter)
82 }
83 DeferredOp::Write(write) => {
84 let iter = write.writes.keys().copied();
85 itertools::Either::Right(iter)
86 }
87 }
88 }
89
90 /// Returns the [`ConnectionId`] associated with this deferred op.
91 pub fn conn_id(&self) -> &ConnectionId {
92 match self {
93 DeferredOp::Plan(plan) => plan.ctx.session().conn_id(),
94 DeferredOp::Write(write) => write.pending_txn.ctx.session().conn_id(),
95 }
96 }
97
98 /// Consumes the [`DeferredOp`], returning the inner [`ExecuteContext`].
99 pub fn into_ctx(self) -> ExecuteContext {
100 match self {
101 DeferredOp::Plan(plan) => plan.ctx,
102 DeferredOp::Write(write) => write.pending_txn.ctx,
103 }
104 }
105}
106
107/// Describes a plan that is awaiting [`WriteLocks`].
108#[derive(Derivative)]
109#[derivative(Debug)]
110pub struct DeferredPlan {
111 #[derivative(Debug = "ignore")]
112 pub ctx: ExecuteContext,
113 pub plan: Plan,
114 pub validity: PlanValidity,
115 pub requires_locks: BTreeSet<CatalogItemId>,
116 pub resolved_ids: ResolvedIds,
117 pub sql_impl_resolved_ids: ResolvedIds,
118}
119
120#[derive(Debug)]
121pub struct DeferredWrite {
122 pub span: Span,
123 pub writes: BTreeMap<CatalogItemId, SmallVec<[TableData; 1]>>,
124 pub pending_txn: PendingTxn,
125}
126
127/// Describes what action triggered an update to a builtin table.
128#[derive(Debug)]
129pub(crate) enum BuiltinTableUpdateSource {
130 /// Internal update, notify the caller when it's complete.
131 Internal(oneshot::Sender<()>),
132 /// Update was triggered by some background process, such as periodic heartbeats from COMPUTE.
133 Background(oneshot::Sender<()>),
134}
135
136/// Where to deliver the result of a [`PendingWriteTxn::User`] write.
137#[derive(Debug)]
138pub(crate) enum UserWriteResponder {
139 /// Session-bound write. The coordinator retires the session's
140 /// `ExecuteContext` once the write commits.
141 Session(PendingTxn),
142}
143
144/// A pending write transaction that will be committing during the next group commit.
145#[derive(Debug)]
146pub(crate) enum PendingWriteTxn {
147 /// Write to a user table. The write timestamp is picked by the oracle
148 /// during group commit. The write lock is either handed off from the
149 /// submitting session (via `write_locks: Some(..)`) or acquired during
150 /// group commit (`write_locks: None`).
151 User {
152 span: Span,
153 /// List of all write operations within the transaction.
154 writes: BTreeMap<CatalogItemId, SmallVec<[TableData; 1]>>,
155 /// If they exist, should contain locks for each [`CatalogItemId`] in `writes`.
156 write_locks: Option<WriteLocks>,
157 /// Where to deliver the result once the write commits.
158 responder: UserWriteResponder,
159 },
160 /// Write to a system table.
161 System {
162 updates: Vec<BuiltinTableUpdate>,
163 source: BuiltinTableUpdateSource,
164 },
165}
166
167impl PendingWriteTxn {
168 fn is_internal_system(&self) -> bool {
169 match self {
170 PendingWriteTxn::System {
171 source: BuiltinTableUpdateSource::Internal(_),
172 ..
173 } => true,
174 _ => false,
175 }
176 }
177}
178
179impl Coordinator {
180 /// Send a message to the Coordinate to start a group commit.
181 pub(crate) fn trigger_group_commit(&mut self) {
182 self.group_commit_tx.notify();
183 // Avoid excessive `Message::GroupCommitInitiate` by resetting the periodic table
184 // advancement. The group commit triggered by the message above will already advance all
185 // tables.
186 self.advance_timelines_interval.reset();
187 }
188
189 /// Tries to execute a previously [`DeferredOp`] that requires write locks.
190 ///
191 /// If we can't acquire all of the write locks then we'll defer the plan again and wait for
192 /// the necessary locks to become available.
193 pub(crate) async fn try_deferred(
194 &mut self,
195 conn_id: ConnectionId,
196 acquired_lock: Option<(CatalogItemId, tokio::sync::OwnedMutexGuard<()>)>,
197 ) {
198 // Try getting the deferred op, it may have already been canceled.
199 let Some(op) = self.deferred_write_ops.remove(&conn_id) else {
200 tracing::warn!(%conn_id, "no deferred op found, it must have been canceled?");
201 return;
202 };
203 tracing::info!(%conn_id, "trying deferred plan");
204
205 // If we pre-acquired a lock, try to acquire the rest.
206 let write_locks = match acquired_lock {
207 Some((acquired_gid, acquired_lock)) => {
208 let mut write_locks = WriteLocks::builder(op.required_locks());
209
210 // Insert the one lock we already acquired into the our builder.
211 write_locks.insert_lock(acquired_gid, acquired_lock);
212
213 // Acquire the rest of our locks, filtering out the one we already have.
214 for gid in op.required_locks().filter(|gid| *gid != acquired_gid) {
215 if let Some(lock) = self.try_grant_object_write_lock(gid) {
216 write_locks.insert_lock(gid, lock);
217 }
218 }
219
220 // If we failed to acquire any locks, spawn a task that waits for them to become available.
221 let locks = match write_locks.all_or_nothing(op.conn_id()) {
222 Ok(locks) => locks,
223 Err(failed_to_acquire) => {
224 let acquire_future = self
225 .grant_object_write_lock(failed_to_acquire)
226 .map(Option::Some);
227 self.defer_op(acquire_future, op);
228 return;
229 }
230 };
231
232 Some(locks)
233 }
234 None => None,
235 };
236
237 match op {
238 DeferredOp::Plan(mut deferred) => {
239 if let Err(e) = deferred.validity.check(self.catalog()) {
240 deferred.ctx.retire(Err(e))
241 } else {
242 // If we pre-acquired our locks, grant them to the session.
243 if let Some(locks) = write_locks {
244 let conn_id = deferred.ctx.session().conn_id().clone();
245 if let Err(existing) =
246 deferred.ctx.session_mut().try_grant_write_locks(locks)
247 {
248 tracing::error!(
249 %conn_id,
250 ?existing,
251 "session already write locks granted?",
252 );
253 return deferred.ctx.retire(Err(AdapterError::WrongSetOfLocks));
254 }
255 };
256
257 // Note: This plan is not guaranteed to run, it may get deferred again.
258 self.sequence_plan(
259 deferred.ctx,
260 deferred.plan,
261 deferred.resolved_ids,
262 deferred.sql_impl_resolved_ids,
263 )
264 .await;
265 }
266 }
267 DeferredOp::Write(DeferredWrite {
268 span,
269 writes,
270 pending_txn,
271 }) => {
272 self.submit_write(PendingWriteTxn::User {
273 span,
274 writes,
275 write_locks,
276 responder: UserWriteResponder::Session(pending_txn),
277 });
278 }
279 }
280 }
281
282 /// Attempts to commit all pending write transactions in a group commit. If the timestamp
283 /// chosen for the writes is not ahead of `now()`, then we can execute and commit the writes
284 /// immediately. Otherwise we must wait for `now()` to advance past the timestamp chosen for the
285 /// writes.
286 #[instrument(level = "debug")]
287 pub(crate) async fn try_group_commit(&mut self, permit: Option<GroupCommitPermit>) {
288 let timestamp = self.peek_local_write_ts().await;
289 let now = Timestamp::from((self.catalog().config().now)());
290
291 // HACK: This is a special case to allow writes to the mz_sessions table to proceed even
292 // if the timestamp oracle is ahead of the current walltime. We do this because there are
293 // some tests that mock the walltime, so it doesn't automatically advance, and updating
294 // those tests to advance the walltime while creating a connection is too much.
295 //
296 // TODO(parkmycar): Get rid of the check below when refactoring group commits.
297 let contains_internal_system_write = self
298 .pending_writes
299 .iter()
300 .any(|write| write.is_internal_system());
301
302 if timestamp > now && !contains_internal_system_write {
303 // Cap retry time to 1s. In cases where the system clock has retreated by
304 // some large amount of time, this prevents against then waiting for that
305 // large amount of time in case the system clock then advances back to near
306 // what it was.
307 let remaining_ms = std::cmp::min(timestamp.saturating_sub(now), 1_000.into());
308 let internal_cmd_tx = self.internal_cmd_tx.clone();
309 task::spawn(
310 || "group_commit_initiate",
311 async move {
312 tokio::time::sleep(Duration::from_millis(remaining_ms.into())).await;
313 // It is not an error for this task to be running after `internal_cmd_rx` is dropped.
314 let result =
315 internal_cmd_tx.send(Message::GroupCommitInitiate(Span::current(), permit));
316 if let Err(e) = result {
317 warn!("internal_cmd_rx dropped before we could send: {:?}", e);
318 }
319 }
320 .instrument(Span::current()),
321 );
322 } else {
323 self.group_commit(permit).await;
324 }
325 }
326
327 /// Tries to commit all pending writes transactions at the same timestamp.
328 ///
329 /// If the caller of this function has the `write_lock` acquired, then they can optionally pass
330 /// it in to this method. If the caller does not have the `write_lock` acquired and the
331 /// `write_lock` is currently locked by another operation, then only writes to system tables
332 /// and table advancements will be applied. If the caller does not have the `write_lock`
333 /// acquired and the `write_lock` is not currently locked by another operation, then group
334 /// commit will acquire it and all writes will be applied.
335 ///
336 /// All applicable pending writes will be combined into a single Append command and sent to
337 /// STORAGE as a single batch. All applicable writes will happen at the same timestamp and all
338 /// involved tables will be advanced to some timestamp larger than the timestamp of the write.
339 ///
340 /// Returns the timestamp of the write.
341 #[instrument(name = "coord::group_commit")]
342 pub(crate) async fn group_commit(&mut self, permit: Option<GroupCommitPermit>) -> Timestamp {
343 let mut validated_writes = Vec::new();
344 let mut deferred_writes = Vec::new();
345 let mut group_write_locks = GroupCommitWriteLocks::default();
346
347 // TODO(parkmycar): Refactor away this allocation. Currently `drain(..)` requires holding
348 // a mutable borrow on the Coordinator and so does trying to grant a write lock.
349 let pending_writes: Vec<_> = self.pending_writes.drain(..).collect();
350
351 // Validate, merge, and possibly acquire write locks for as many pending writes as possible.
352 for pending_write in pending_writes {
353 match pending_write {
354 // We always allow system writes to proceed.
355 PendingWriteTxn::System { .. } => validated_writes.push(pending_write),
356 // We have a set of locks! Validate they're correct (expected).
357 PendingWriteTxn::User {
358 span,
359 write_locks: Some(write_locks),
360 writes,
361 responder: UserWriteResponder::Session(pending_txn),
362 } => match write_locks.validate(writes.keys().copied()) {
363 Ok(validated_locks) => {
364 // Merge all of our write locks together since we can allow concurrent
365 // writes at the same timestamp.
366 group_write_locks.merge(validated_locks);
367
368 let validated_write = PendingWriteTxn::User {
369 span,
370 writes,
371 write_locks: None,
372 responder: UserWriteResponder::Session(pending_txn),
373 };
374 validated_writes.push(validated_write);
375 }
376 // This is very unexpected since callers of this method should be validating.
377 //
378 // We cannot allow these write to occur since if the correct set of locks was
379 // not taken we could violate serializability.
380 Err(missing) => {
381 let writes: Vec<_> = writes.keys().collect();
382 panic!(
383 "got to group commit with partial set of locks!\nmissing: {:?}, writes: {:?}, txn: {:?}",
384 missing, writes, pending_txn,
385 );
386 }
387 },
388 // If we don't have any locks, try to acquire them, otherwise defer the write.
389 PendingWriteTxn::User {
390 span,
391 writes,
392 write_locks: None,
393 responder: UserWriteResponder::Session(pending_txn),
394 } => {
395 let missing = group_write_locks.missing_locks(writes.keys().copied());
396
397 if missing.is_empty() {
398 // We have all the locks! Queue the pending write.
399 let validated_write = PendingWriteTxn::User {
400 span,
401 writes,
402 write_locks: None,
403 responder: UserWriteResponder::Session(pending_txn),
404 };
405 validated_writes.push(validated_write);
406 } else {
407 // Try to acquire the locks we're missing.
408 let mut just_in_time_locks = WriteLocks::builder(missing.clone());
409 for collection in missing {
410 if let Some(lock) = self.try_grant_object_write_lock(collection) {
411 just_in_time_locks.insert_lock(collection, lock);
412 }
413 }
414
415 match just_in_time_locks.all_or_nothing(pending_txn.ctx.session().conn_id())
416 {
417 // We acquired all of the locks! Proceed with the write.
418 Ok(locks) => {
419 group_write_locks.merge(locks);
420 let validated_write = PendingWriteTxn::User {
421 span,
422 writes,
423 write_locks: None,
424 responder: UserWriteResponder::Session(pending_txn),
425 };
426 validated_writes.push(validated_write);
427 }
428 // Darn. We couldn't acquire the locks, defer the write.
429 Err(missing) => {
430 let acquire_future =
431 self.grant_object_write_lock(missing).map(Option::Some);
432 let write = DeferredWrite {
433 span,
434 writes,
435 pending_txn,
436 };
437 deferred_writes.push((acquire_future, write));
438 }
439 }
440 }
441 }
442 }
443 }
444
445 // Queue all of our deferred ops.
446 for (acquire_future, write) in deferred_writes {
447 self.defer_op(acquire_future, DeferredOp::Write(write));
448 }
449
450 // The value returned here still might be ahead of `now()` if `now()` has gone backwards at
451 // any point during this method or if this was triggered from DDL. We will still commit the
452 // write without waiting for `now()` to advance. This is ok because the next batch of writes
453 // will trigger the wait loop in `try_group_commit()` if `now()` hasn't advanced past the
454 // global timeline, preventing an unbounded advancing of the global timeline ahead of
455 // `now()`. Additionally DDL is infrequent enough and takes long enough that we don't think
456 // it's practical for continuous DDL to advance the global timestamp in an unbounded manner.
457 let WriteTimestamp {
458 timestamp,
459 advance_to,
460 } = self.get_local_write_ts().await;
461
462 // Advance the catalog shard's upper to keep it in sync with the oracle
463 // timestamp. This ensures that reads of mz_catalog_raw at the oracle's
464 // read_ts do not block waiting for the catalog shard's upper to advance.
465 let catalog_upper_start = Instant::now();
466 self.catalog
467 .advance_upper(advance_to)
468 .await
469 .unwrap_or_terminate("unable to advance catalog upper");
470 self.metrics
471 .group_commit_catalog_upper_seconds
472 .observe(catalog_upper_start.elapsed().as_secs_f64());
473
474 let mut appends: BTreeMap<CatalogItemId, SmallVec<[TableData; 1]>> = BTreeMap::new();
475 let mut responses = Vec::with_capacity(validated_writes.len());
476 let mut notifies = Vec::new();
477
478 for validated_write_txn in validated_writes {
479 match validated_write_txn {
480 PendingWriteTxn::User {
481 span: _,
482 writes,
483 write_locks,
484 responder:
485 UserWriteResponder::Session(PendingTxn {
486 ctx,
487 response,
488 action,
489 }),
490 } => {
491 assert_none!(write_locks, "should have merged together all locks above");
492 for (id, table_data) in writes {
493 // If the table that some write was targeting has been deleted while the
494 // write was waiting, then the write will be ignored and we respond to the
495 // client that the write was successful. This is only possible if the write
496 // and the delete were concurrent. Therefore, we are free to order the
497 // write before the delete without violating any consistency guarantees.
498 if self.catalog().try_get_entry(&id).is_some() {
499 appends.entry(id).or_default().extend(table_data);
500 }
501 }
502 if let Some(id) = ctx.extra().contents() {
503 self.set_statement_execution_timestamp(id, timestamp);
504 }
505
506 responses.push(CompletedClientTransmitter::new(ctx, response, action));
507 }
508 PendingWriteTxn::System { updates, source } => {
509 for update in updates {
510 appends.entry(update.id).or_default().push(update.data);
511 }
512 // Once the write completes we notify any waiters.
513 match source {
514 BuiltinTableUpdateSource::Internal(tx)
515 | BuiltinTableUpdateSource::Background(tx) => notifies.push(tx),
516 }
517 }
518 }
519 }
520
521 // Consolidate all Rows for a given table. We do not consolidate the
522 // staged batches, that's up to whoever staged them.
523 let mut all_appends = Vec::with_capacity(appends.len());
524 for (item_id, table_data) in appends.into_iter() {
525 let mut all_rows = Vec::new();
526 let mut all_data = Vec::new();
527 for data in table_data {
528 match data {
529 TableData::Rows(rows) => all_rows.extend(rows),
530 TableData::Batches(_) => all_data.push(data),
531 }
532 }
533 differential_dataflow::consolidation::consolidate(&mut all_rows);
534 all_data.push(TableData::Rows(all_rows));
535
536 // TODO(parkmycar): Use SmallVec throughout.
537 all_appends.push((item_id, all_data));
538 }
539
540 let appends: Vec<_> = all_appends
541 .into_iter()
542 .map(|(id, updates)| {
543 let gid = self.catalog().get_entry(&id).latest_global_id();
544 (gid, updates)
545 })
546 .collect();
547
548 // Log non-empty user appends.
549 let modified_tables: Vec<_> = appends
550 .iter()
551 .filter_map(|(id, updates)| {
552 if id.is_user() && !updates.iter().all(|u| u.is_empty()) {
553 Some(id)
554 } else {
555 None
556 }
557 })
558 .collect();
559 if !modified_tables.is_empty() {
560 info!(
561 "Appending to tables, {modified_tables:?}, at {timestamp}, advancing to {advance_to}"
562 );
563 }
564
565 // Instrument our table writes since they can block the coordinator.
566 let histogram = self.metrics.append_table_duration_seconds.clone();
567
568 // NOTE: It is important that we append, even when there are no actual
569 // appends. This makes sure we periodically bump the upper of all
570 // tables, which is required to make them readable at the latest oracle
571 // read ts.
572
573 let append_fut = self
574 .controller
575 .storage
576 .append_table(timestamp, advance_to, appends)
577 .expect("invalid updates")
578 .wall_time()
579 .observe(histogram);
580
581 // Spawn a task to do the table writes.
582 let internal_cmd_tx = self.internal_cmd_tx.clone();
583 let apply_write_fut = self.apply_local_write(timestamp);
584
585 let span = debug_span!(parent: None, "group_commit_apply");
586 OpenTelemetryContext::obtain().attach_as_parent_to(&span);
587 task::spawn(
588 || "group_commit_apply",
589 async move {
590 // Wait for the writes to complete.
591 match append_fut
592 .instrument(debug_span!("group_commit_apply::append_fut"))
593 .await
594 {
595 Ok(append_result) => {
596 append_result.unwrap_or_terminate("cannot fail to apply appends")
597 }
598 Err(_) => warn!("Writer terminated with writes in indefinite state"),
599 };
600
601 // Apply the write by marking the timestamp as complete on the timeline.
602 apply_write_fut
603 .instrument(debug_span!("group_commit_apply::append_write_fut"))
604 .await;
605
606 // Notify the external clients of the result.
607 for response in responses {
608 let (mut ctx, result) = response.finalize();
609 ctx.session_mut().apply_write(timestamp);
610 ctx.retire(result);
611 }
612
613 // IMPORTANT: Make sure we hold the permit and write locks
614 // until here, to prevent other writes from going through while
615 // we haven't yet applied the write at the timestamp oracle.
616 drop(permit);
617 drop(group_write_locks);
618
619 // Advance other timelines.
620 if let Err(e) = internal_cmd_tx.send(Message::AdvanceTimelines) {
621 warn!("Server closed with non-advanced timelines, {e}");
622 }
623
624 for notify in notifies {
625 // We don't care if the listeners have gone away.
626 let _ = notify.send(());
627 }
628 }
629 .instrument(span),
630 );
631
632 timestamp
633 }
634
635 /// Submit a write to be executed during the next group commit and trigger a group commit.
636 pub(crate) fn submit_write(&mut self, pending_write_txn: PendingWriteTxn) {
637 if self.controller.read_only() {
638 panic!(
639 "attempting table write in read-only mode: {:?}",
640 pending_write_txn
641 );
642 }
643 self.pending_writes.push(pending_write_txn);
644 self.trigger_group_commit();
645 }
646
647 /// Append some [`BuiltinTableUpdate`]s, with various degrees of waiting and blocking.
648 pub(crate) fn builtin_table_update<'a>(&'a mut self) -> BuiltinTableAppend<'a> {
649 BuiltinTableAppend { coord: self }
650 }
651
652 pub(crate) fn defer_op<F>(&mut self, acquire_future: F, op: DeferredOp)
653 where
654 F: Future<Output = Option<(CatalogItemId, tokio::sync::OwnedMutexGuard<()>)>>
655 + Send
656 + 'static,
657 {
658 let conn_id = op.conn_id().clone();
659
660 // Track all of our deferred ops.
661 let is_optimistic = op.can_be_optimistically_retried();
662 self.deferred_write_ops.insert(conn_id.clone(), op);
663
664 let internal_cmd_tx = self.internal_cmd_tx.clone();
665 let conn_id_ = conn_id.clone();
666 mz_ore::task::spawn(|| format!("defer op {conn_id_}"), async move {
667 tracing::info!(%conn_id, "deferring plan");
668 // Once we can acquire the first failed lock, try running the deferred plan.
669 //
670 // Note: This does not guarantee the plan will be able to run, there might be
671 // other locks that we later fail to get.
672 let acquired_lock = acquire_future.await;
673
674 // Some operations, e.g. blind INSERTs, can be optimistically retried, meaning we
675 // can run multiple at once. In those cases we don't hold the lock so we retry all
676 // blind writes for a single object.
677 let acquired_lock = match (acquired_lock, is_optimistic) {
678 (Some(_lock), true) => None,
679 (Some(lock), false) => Some(lock),
680 (None, _) => None,
681 };
682
683 // If this send fails then the Coordinator is shutting down.
684 let _ = internal_cmd_tx.send(Message::TryDeferred {
685 conn_id,
686 acquired_lock,
687 });
688 });
689 }
690
691 /// Returns a future that waits until it can get an exclusive lock on the specified collection.
692 pub(crate) fn grant_object_write_lock(
693 &mut self,
694 object_id: CatalogItemId,
695 ) -> impl Future<Output = (CatalogItemId, OwnedMutexGuard<()>)> + 'static {
696 let write_lock_handle = self
697 .write_locks
698 .entry(object_id)
699 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())));
700 let write_lock_handle = Arc::clone(write_lock_handle);
701
702 write_lock_handle
703 .lock_owned()
704 .map(move |guard| (object_id, guard))
705 }
706
707 /// Lazily creates the lock for the provided `object_id`, and grants it if possible, returns
708 /// `None` if the lock is already held.
709 pub(crate) fn try_grant_object_write_lock(
710 &mut self,
711 object_id: CatalogItemId,
712 ) -> Option<OwnedMutexGuard<()>> {
713 let write_lock_handle = self
714 .write_locks
715 .entry(object_id)
716 .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())));
717 let write_lock_handle = Arc::clone(write_lock_handle);
718
719 write_lock_handle.try_lock_owned().ok()
720 }
721}
722
723/// Helper struct to run a builtin table append.
724pub struct BuiltinTableAppend<'a> {
725 coord: &'a mut Coordinator,
726}
727
728/// `Future` that notifies when a builtin table write has completed.
729///
730/// Note: builtin table writes need to talk to persist, which can take 100s of milliseconds. This
731/// type allows you to execute a builtin table write, e.g. via [`BuiltinTableAppend::execute`], and
732/// wait for it to complete, while other long running tasks are concurrently executing.
733pub type BuiltinTableAppendNotify = Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>;
734
735impl<'a> BuiltinTableAppend<'a> {
736 /// Submit a write to a system table to be executed during the next group commit. This method
737 /// __does not__ trigger a group commit.
738 ///
739 /// This is useful for non-critical writes like metric updates because it allows us to piggy
740 /// back off the next group commit instead of triggering a potentially expensive group commit.
741 ///
742 /// Note: __do not__ call this for DDL which needs the system tables updated immediately.
743 ///
744 /// Note: When in read-only mode, this will buffer the update and return
745 /// immediately.
746 pub fn background(self, mut updates: Vec<BuiltinTableUpdate>) -> BuiltinTableAppendNotify {
747 if self.coord.controller.read_only() {
748 self.coord
749 .buffered_builtin_table_updates
750 .as_mut()
751 .expect("in read-only mode")
752 .append(&mut updates);
753
754 return Box::pin(futures::future::ready(()));
755 }
756
757 let (tx, rx) = oneshot::channel();
758 self.coord.pending_writes.push(PendingWriteTxn::System {
759 updates,
760 source: BuiltinTableUpdateSource::Background(tx),
761 });
762
763 Box::pin(rx.map(|_| ()))
764 }
765
766 /// Submits a write to be executed during the next group commit __and__ triggers a group commit.
767 ///
768 /// Returns a `Future` that resolves when the write has completed, does not block the
769 /// Coordinator.
770 ///
771 /// Note: When in read-only mode, this will buffer the update and the
772 /// returned future will resolve immediately, without the update actually
773 /// having been written.
774 pub fn defer(self, mut updates: Vec<BuiltinTableUpdate>) -> BuiltinTableAppendNotify {
775 if self.coord.controller.read_only() {
776 self.coord
777 .buffered_builtin_table_updates
778 .as_mut()
779 .expect("in read-only mode")
780 .append(&mut updates);
781
782 return Box::pin(futures::future::ready(()));
783 }
784
785 let (tx, rx) = oneshot::channel();
786 self.coord.pending_writes.push(PendingWriteTxn::System {
787 updates,
788 source: BuiltinTableUpdateSource::Internal(tx),
789 });
790 self.coord.trigger_group_commit();
791
792 Box::pin(rx.map(|_| ()))
793 }
794
795 /// Submit a write to a system table.
796 ///
797 /// This method will block the Coordinator on acquiring a write timestamp from the timestamp
798 /// oracle, and then returns a `Future` that will complete once the write has been applied and
799 /// the write timestamp.
800 ///
801 /// Note: When in read-only mode, this will buffer the update, the
802 /// returned future will resolve immediately, without the update actually
803 /// having been written, and no timestamp is returned.
804 pub async fn execute(
805 self,
806 mut updates: Vec<BuiltinTableUpdate>,
807 ) -> (BuiltinTableAppendNotify, Option<Timestamp>) {
808 if self.coord.controller.read_only() {
809 self.coord
810 .buffered_builtin_table_updates
811 .as_mut()
812 .expect("in read-only mode")
813 .append(&mut updates);
814
815 return (Box::pin(futures::future::ready(())), None);
816 }
817
818 let (tx, rx) = oneshot::channel();
819
820 // Most DDL queries cause writes to system tables. Unlike writes to user tables, system
821 // table writes do not wait for a group commit, they explicitly trigger one. There is a
822 // possibility that if a user is executing DDL at a rate faster than 1 query per
823 // millisecond, then the global timeline will unboundedly advance past the system clock.
824 // This can cause future queries to block, but will not affect correctness. Since this
825 // rate of DDL is unlikely, we allow DDL to explicitly trigger group commit.
826 self.coord.pending_writes.push(PendingWriteTxn::System {
827 updates,
828 source: BuiltinTableUpdateSource::Internal(tx),
829 });
830 let write_ts = self.coord.group_commit(None).await;
831
832 // Avoid excessive group commits by resetting the periodic table advancement timer. The
833 // group commit triggered by above will already advance all tables.
834 self.coord.advance_timelines_interval.reset();
835
836 (Box::pin(rx.map(|_| ())), Some(write_ts))
837 }
838
839 /// Submit a write to a system table, blocking until complete.
840 ///
841 /// Note: if possible you should use the `execute(...)` method, which returns a `Future` that
842 /// can be `await`-ed concurrently with other tasks.
843 ///
844 /// Note: When in read-only mode, this will buffer the update and the
845 /// returned future will resolve immediately, without the update actually
846 /// having been written.
847 pub async fn blocking(self, updates: Vec<BuiltinTableUpdate>) {
848 let (notify, _) = self.execute(updates).await;
849 notify.await;
850 }
851}
852
853/// Returns two sides of a "channel" that can be used to notify the coordinator when we want a
854/// group commit to be run.
855pub fn notifier() -> (GroupCommitNotifier, GroupCommitWaiter) {
856 let notify = Arc::new(Notify::new());
857 let in_progress = Arc::new(Semaphore::new(1));
858
859 let notifier = GroupCommitNotifier {
860 notify: Arc::clone(¬ify),
861 };
862 let waiter = GroupCommitWaiter {
863 notify,
864 in_progress,
865 };
866
867 (notifier, waiter)
868}
869
870/// A handle that allows us to notify the coordinator that a group commit should be run at some
871/// point in the future.
872#[derive(Debug, Clone)]
873pub struct GroupCommitNotifier {
874 /// Tracks if there are any outstanding group commits.
875 notify: Arc<Notify>,
876}
877
878impl GroupCommitNotifier {
879 /// Notifies the [`GroupCommitWaiter`] that we'd like a group commit to be run.
880 pub fn notify(&self) {
881 self.notify.notify_one()
882 }
883}
884
885/// A handle that returns a future when a group commit needs to be run, and one is not currently
886/// being run.
887#[derive(Debug)]
888pub struct GroupCommitWaiter {
889 /// Tracks if there are any outstanding group commits.
890 notify: Arc<Notify>,
891 /// Distributes permits which tracks in progress group commits.
892 in_progress: Arc<Semaphore>,
893}
894static_assertions::assert_not_impl_all!(GroupCommitWaiter: Clone);
895
896impl GroupCommitWaiter {
897 /// Returns a permit for a group commit, once a permit is available _and_ there someone
898 /// requested a group commit to be run.
899 ///
900 /// # Cancel Safety
901 ///
902 /// * Waiting on the returned Future is cancel safe because we acquire an in-progress permit
903 /// before waiting for notifications. If the Future gets dropped after acquiring a permit but
904 /// before a group commit is queued, we'll release the permit which can be acquired by the
905 /// next caller.
906 ///
907 pub async fn ready(&self) -> GroupCommitPermit {
908 let permit = Semaphore::acquire_owned(Arc::clone(&self.in_progress))
909 .await
910 .expect("semaphore should not close");
911
912 // Note: We must wait for notifies _after_ waiting for a permit to be acquired for cancel
913 // safety.
914 self.notify.notified().await;
915
916 GroupCommitPermit {
917 _permit: Some(permit),
918 }
919 }
920}
921
922/// A permit to run a group commit, this must be kept alive for the entire duration of the commit.
923///
924/// Note: We sometimes want to throttle how many group commits are running at once, which this
925/// permit allows us to do.
926#[derive(Debug)]
927pub struct GroupCommitPermit {
928 /// Permit that is preventing other group commits from running.
929 ///
930 /// Only `None` if the permit has been moved into a tokio task for waiting.
931 _permit: Option<OwnedSemaphorePermit>,
932}
933
934/// When we start a [`Session`] we need to update some builtin tables, but we don't want to wait for
935/// these writes to complete for two reasons:
936///
937/// 1. Doing a write can take a relatively long time.
938/// 2. Decoupling the write from the session start allows us to batch multiple writes together, if
939/// sessions are being created with a high frequency.
940///
941/// So, as an optimization we do not wait for these writes to complete. But if a [`Session`] tries
942/// to query any of these builtin objects, we need to block that query on the writes completing to
943/// maintain linearizability.
944///
945/// Warning: this already clears the wait flag (i.e., it calls `clear_builtin_table_updates`).
946///
947/// TODO(peek-seq): After we delete the old peek sequencing, we can remove the first component of
948/// the return tuple.
949pub(crate) fn waiting_on_startup_appends(
950 catalog: &Catalog,
951 session: &mut Session,
952 plan: &Plan,
953) -> Option<(BTreeSet<CatalogItemId>, BoxFuture<'static, ()>)> {
954 // TODO(parkmycar): We need to check transitive uses here too if we ever move the
955 // referenced builtin tables out of mz_internal, or we allow creating views on
956 // mz_internal objects.
957 let depends_on = match plan {
958 Plan::Select(plan) => plan.source.depends_on(),
959 Plan::ReadThenWrite(plan) => plan.selection.depends_on(),
960 Plan::ShowColumns(plan) => plan.select_plan.source.depends_on(),
961 Plan::Subscribe(plan) => plan.from.depends_on(),
962 Plan::ExplainPlan(ExplainPlanPlan {
963 explainee: Explainee::Statement(ExplaineeStatement::Select { plan, .. }),
964 ..
965 }) => plan.source.depends_on(),
966 Plan::ExplainTimestamp(ExplainTimestampPlan { raw_plan, .. }) => raw_plan.depends_on(),
967 Plan::CreateConnection(_)
968 | Plan::CreateDatabase(_)
969 | Plan::CreateSchema(_)
970 | Plan::CreateRole(_)
971 | Plan::CreateNetworkPolicy(_)
972 | Plan::CreateCluster(_)
973 | Plan::CreateClusterReplica(_)
974 | Plan::CreateSource(_)
975 | Plan::CreateSources(_)
976 | Plan::CreateSecret(_)
977 | Plan::CreateSink(_)
978 | Plan::CreateTable(_)
979 | Plan::CreateView(_)
980 | Plan::CreateMaterializedView(_)
981 | Plan::CreateIndex(_)
982 | Plan::CreateType(_)
983 | Plan::Comment(_)
984 | Plan::DiscardTemp
985 | Plan::DiscardAll
986 | Plan::DropObjects(_)
987 | Plan::DropOwned(_)
988 | Plan::EmptyQuery
989 | Plan::ShowAllVariables
990 | Plan::ShowCreate(_)
991 | Plan::ShowVariable(_)
992 | Plan::InspectShard(_)
993 | Plan::SetVariable(_)
994 | Plan::ResetVariable(_)
995 | Plan::SetTransaction(_)
996 | Plan::StartTransaction(_)
997 | Plan::CommitTransaction(_)
998 | Plan::AbortTransaction(_)
999 | Plan::CopyFrom(_)
1000 | Plan::CopyTo(_)
1001 | Plan::ExplainPlan(_)
1002 | Plan::ExplainPushdown(_)
1003 | Plan::ExplainSinkSchema(_)
1004 | Plan::Insert(_)
1005 | Plan::AlterNetworkPolicy(_)
1006 | Plan::AlterNoop(_)
1007 | Plan::AlterClusterRename(_)
1008 | Plan::AlterClusterSwap(_)
1009 | Plan::AlterClusterReplicaRename(_)
1010 | Plan::AlterCluster(_)
1011 | Plan::AlterConnection(_)
1012 | Plan::AlterSource(_)
1013 | Plan::AlterSetCluster(_)
1014 | Plan::AlterItemRename(_)
1015 | Plan::AlterRetainHistory(_)
1016 | Plan::AlterSourceTimestampInterval(_)
1017 | Plan::AlterSchemaRename(_)
1018 | Plan::AlterSchemaSwap(_)
1019 | Plan::AlterSecret(_)
1020 | Plan::AlterSink(_)
1021 | Plan::AlterSystemSet(_)
1022 | Plan::AlterSystemReset(_)
1023 | Plan::AlterSystemResetAll(_)
1024 | Plan::AlterRole(_)
1025 | Plan::AlterOwner(_)
1026 | Plan::AlterTableAddColumn(_)
1027 | Plan::AlterMaterializedViewApplyReplacement(_)
1028 | Plan::Declare(_)
1029 | Plan::Fetch(_)
1030 | Plan::Close(_)
1031 | Plan::Prepare(_)
1032 | Plan::Execute(_)
1033 | Plan::Deallocate(_)
1034 | Plan::Raise(_)
1035 | Plan::GrantRole(_)
1036 | Plan::RevokeRole(_)
1037 | Plan::GrantPrivileges(_)
1038 | Plan::RevokePrivileges(_)
1039 | Plan::AlterDefaultPrivileges(_)
1040 | Plan::ReassignOwned(_)
1041 | Plan::ValidateConnection(_)
1042 | Plan::SideEffectingFunc(_) => BTreeSet::default(),
1043 };
1044 let depends_on_required_id = REQUIRED_BUILTIN_TABLES
1045 .iter()
1046 .map(|table| catalog.resolve_builtin_table(&**table))
1047 .any(|id| {
1048 catalog
1049 .get_global_ids(&id)
1050 .any(|gid| depends_on.contains(&gid))
1051 });
1052
1053 // If our plan does not depend on any required ID, then we don't need to
1054 // wait for any builtin writes to occur.
1055 if !depends_on_required_id {
1056 return None;
1057 }
1058
1059 // Even if we depend on a builtin table, there's no need to wait if the
1060 // writes have already completed.
1061 //
1062 // TODO(parkmycar): As an optimization we should add a `Notify` type to
1063 // `mz_ore` that allows peeking. If the builtin table writes have already
1064 // completed then there is no need to defer this plan.
1065 match session.clear_builtin_table_updates() {
1066 Some(wait_future) => {
1067 let depends_on = depends_on
1068 .into_iter()
1069 .map(|gid| catalog.get_entry_by_global_id(&gid).id())
1070 .collect();
1071 Some((depends_on, wait_future.boxed()))
1072 }
1073 None => None,
1074 }
1075}