Skip to main content

mz_adapter/coord/sequencer/inner/
copy_from.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
10use std::str::FromStr;
11use std::sync::Arc;
12
13use mz_adapter_types::connection::ConnectionId;
14use mz_ore::cast::CastInto;
15use mz_persist_client::Diagnostics;
16use mz_persist_client::batch::ProtoBatch;
17use mz_persist_types::codec_impls::UnitSchema;
18use mz_pgcopy::CopyFormatParams;
19use mz_repr::{CatalogItemId, ColumnIndex, Datum, RelationDesc, Row, RowArena};
20use mz_sql::catalog::SessionCatalog;
21use mz_sql::plan::{self, CopyFromFilter, CopyFromSource, HirScalarExpr};
22use mz_sql::session::metadata::SessionMetadata;
23use mz_storage_client::client::TableData;
24use mz_storage_types::StorageDiff;
25use mz_storage_types::oneshot_sources::{ContentShape, OneshotIngestionRequest};
26use mz_storage_types::sources::SourceData;
27use smallvec::SmallVec;
28use timely::progress::Antichain;
29use tokio::sync::{mpsc, oneshot};
30use url::Url;
31use uuid::Uuid;
32
33use crate::command::CopyFromStdinWriter;
34use crate::coord::sequencer::inner::return_if_err;
35use crate::coord::{ActiveCopyFrom, Coordinator, TargetCluster};
36use crate::optimize;
37use crate::optimize::dataflows::{EvalTime, ExprPrep, ExprPrepOneShot};
38use crate::session::{Session, TransactionOps, WriteOp};
39use crate::{AdapterError, ExecuteContext, ExecuteResponse};
40
41/// Finalize persist batches periodically during COPY FROM STDIN to avoid
42/// unbounded in-memory growth in a single giant batch.
43const COPY_FROM_STDIN_MAX_BATCH_BYTES: usize = 32 * 1024 * 1024;
44
45/// Cap on the number of parallel decode workers spawned per COPY FROM STDIN.
46/// A single network-bound stream sees marginal gains past a handful of
47/// decoders, and capping bounds how much of the blocking pool any one COPY can
48/// occupy while actively decoding.
49const COPY_FROM_STDIN_MAX_WORKERS: usize = 8;
50
51impl Coordinator {
52    pub(crate) async fn sequence_copy_from(
53        &mut self,
54        mut ctx: ExecuteContext,
55        plan: plan::CopyFromPlan,
56        target_cluster: TargetCluster,
57    ) {
58        if ctx
59            .session()
60            .vars()
61            .transaction_isolation()
62            .is_bounded_staleness()
63        {
64            return ctx.retire(Err(AdapterError::BoundedStalenessReadOnly));
65        }
66
67        // STDIN is sequenced by handing control back to pgwire, which drives the
68        // CopyData/CopyDone exchange. URL/S3 sources stage a one-shot ingestion
69        // server-side and fall through to the rest of this function.
70        if let CopyFromSource::Stdin = plan.source {
71            // The statement-logging obligation moves into the response, pgwire carries it onward.
72            // `ctx` stays intact so `retire` can wait out any response barriers safely.
73            let ctx_extra = std::mem::take(ctx.extra_mut());
74            ctx.retire(Ok(ExecuteResponse::CopyFrom {
75                target_id: plan.target_id,
76                target_name: plan.target_name,
77                columns: plan.columns,
78                params: plan.params,
79                ctx_extra,
80            }));
81            return;
82        }
83
84        let plan::CopyFromPlan {
85            target_name: _,
86            target_id,
87            source,
88            columns: _,
89            source_desc,
90            mfp,
91            params,
92            filter,
93        } = plan;
94
95        let eval_uri = |from: HirScalarExpr| -> Result<String, AdapterError> {
96            let style = ExprPrepOneShot {
97                logical_time: EvalTime::NotAvailable,
98                session: ctx.session(),
99                catalog_state: self.catalog().state(),
100            };
101            let mut from = from.lower_uncorrelated(self.catalog().state().system_config())?;
102            style.prep_scalar_expr(&mut from)?;
103
104            // TODO(cf3): Add structured errors for the below uses of `coord_bail!`
105            // and AdapterError::Unstructured.
106            let temp_storage = RowArena::new();
107            let eval_result = from.eval_constant_foldable(&temp_storage)?;
108            let eval_string = match eval_result {
109                Datum::Null => coord_bail!("COPY FROM target value cannot be NULL"),
110                Datum::String(url_str) => url_str,
111                other => coord_bail!("programming error! COPY FROM target cannot be {other}"),
112            };
113
114            Ok(eval_string.to_string())
115        };
116
117        // We check in planning that we're copying into a Table, but be defensive.
118        let Some(entry) = self.catalog().try_get_entry(&target_id) else {
119            return ctx.retire(Err(AdapterError::ConcurrentDependencyDrop {
120                dependency_kind: "table",
121                dependency_id: target_id.to_string(),
122            }));
123        };
124        let Some(dest_table) = entry.table() else {
125            let typ = entry.item().typ();
126            let msg = format!("programming error: expected a Table found {typ:?}");
127            return ctx.retire(Err(AdapterError::Unstructured(anyhow::anyhow!(msg))));
128        };
129
130        // Generate a unique UUID for our ingestion.
131        let ingestion_id = Uuid::new_v4();
132        let collection_id = dest_table.global_id_writes();
133
134        let format = match params {
135            CopyFormatParams::Csv(csv) => {
136                mz_storage_types::oneshot_sources::ContentFormat::Csv(csv.to_owned())
137            }
138            CopyFormatParams::Parquet => mz_storage_types::oneshot_sources::ContentFormat::Parquet,
139            CopyFormatParams::Text(_) | CopyFormatParams::Binary => {
140                mz_ore::soft_panic_or_log!("unsupported formats should be rejected in planning");
141                ctx.retire(Err(AdapterError::Unsupported("COPY FROM URL/S3 format")));
142                return;
143            }
144        };
145
146        let source = match source {
147            CopyFromSource::Url(from_expr) => {
148                let url = return_if_err!(eval_uri(from_expr), ctx);
149                // TODO(cf2): Structured errors.
150                let result = Url::parse(&url)
151                    .map_err(|err| AdapterError::Unstructured(anyhow::anyhow!("{err}")));
152                let url = return_if_err!(result, ctx);
153
154                // Only allow http(s) schemes. Technically we would fail later, as the current
155                // crate (reqwest) doesn't support other schemes.
156                // Prefer to fail early and explicitly in case the downstream ever changes.
157                // DNS resolution for hostnames is performed at execution time to avoid stalls
158                // during sequencing; IP-literal hosts are validated here because reqwest's
159                // custom DNS resolver is only invoked for hostnames.
160                match url.scheme() {
161                    "http" | "https" => {}
162                    other => {
163                        return ctx.retire(Err(AdapterError::Unstructured(anyhow::anyhow!(
164                            "only 'http://' and 'https://' urls are supported as COPY FROM \
165                             target, got '{other}://'"
166                        ))));
167                    }
168                }
169                let enforce_external_addresses =
170                    mz_storage_types::dyncfgs::ENFORCE_EXTERNAL_ADDRESSES
171                        .get(self.controller.storage.config().config_set());
172                if enforce_external_addresses {
173                    if let Err(err) = mz_ore::netio::ensure_url_ip_global(&url) {
174                        return ctx
175                            .retire(Err(AdapterError::Unstructured(anyhow::anyhow!("{err}"))));
176                    }
177                }
178                mz_storage_types::oneshot_sources::ContentSource::Http {
179                    url: mz_ore::url::SensitiveUrl(url),
180                }
181            }
182            CopyFromSource::AwsS3 {
183                uri,
184                connection,
185                connection_id,
186            } => {
187                let uri = return_if_err!(eval_uri(uri), ctx);
188
189                // Validate the URI is an S3 URI, with a bucket name. We rely on validating here
190                // and expect it in clusterd.
191                //
192                // TODO(cf2): Structured errors.
193                let result = http::Uri::from_str(&uri)
194                    .map_err(|err| {
195                        AdapterError::Unstructured(anyhow::anyhow!("expected S3 uri: {err}"))
196                    })
197                    .and_then(|uri| {
198                        if uri.scheme_str() != Some("s3") && uri.scheme_str() != Some("gs") {
199                            coord_bail!("only 's3://...' and 'gs://...' urls are supported as COPY FROM target");
200                        }
201                        Ok(uri)
202                    })
203                    .and_then(|uri| {
204                        if uri.host().is_none() {
205                            coord_bail!("missing bucket name from 's3://...' url");
206                        }
207                        Ok(uri)
208                    });
209                let uri = return_if_err!(result, ctx);
210
211                mz_storage_types::oneshot_sources::ContentSource::AwsS3 {
212                    connection,
213                    connection_id,
214                    uri: uri.to_string(),
215                }
216            }
217            CopyFromSource::Stdin => {
218                unreachable!("STDIN handled by the early return above")
219            }
220        };
221
222        let filter = match filter {
223            None => mz_storage_types::oneshot_sources::ContentFilter::None,
224            Some(CopyFromFilter::Files(files)) => {
225                mz_storage_types::oneshot_sources::ContentFilter::Files(files)
226            }
227            Some(CopyFromFilter::Pattern(pattern)) => {
228                mz_storage_types::oneshot_sources::ContentFilter::Pattern(pattern)
229            }
230        };
231
232        let source_mfp = mfp
233            .into_plan()
234            .map_err(|s| AdapterError::internal("copy_from", s))
235            .and_then(|mfp| {
236                mfp.into_nontemporal().map_err(|_| {
237                    AdapterError::internal("copy_from", "temporal MFP not allowed in copy from")
238                })
239            });
240        let source_mfp = return_if_err!(source_mfp, ctx);
241
242        let shape = ContentShape {
243            source_desc,
244            source_mfp,
245        };
246
247        let request = OneshotIngestionRequest {
248            source,
249            format,
250            filter,
251            shape,
252        };
253
254        let target_cluster = match self
255            .catalog()
256            .resolve_target_cluster(target_cluster, ctx.session())
257        {
258            Ok(cluster) => cluster,
259            Err(err) => {
260                return ctx.retire(Err(err));
261            }
262        };
263        let cluster_id = target_cluster.id;
264
265        // When we finish staging the Batches in Persist, we'll send a command
266        // to the Coordinator.
267        let command_tx = self.internal_cmd_tx.clone();
268        let conn_id = ctx.session().conn_id().clone();
269        let closure = Box::new(move |batches| {
270            let _ = command_tx.send(crate::coord::Message::StagedBatches {
271                conn_id,
272                table_id: target_id,
273                batches,
274            });
275        });
276        // Stash the execute context so we can cancel the COPY.
277        let conn_id = ctx.session().conn_id().clone();
278        self.active_copies.insert(
279            conn_id,
280            ActiveCopyFrom {
281                ingestion_id,
282                cluster_id,
283                table_id: target_id,
284                ctx,
285            },
286        );
287
288        let _result = self
289            .controller
290            .storage
291            .create_oneshot_ingestion(ingestion_id, collection_id, cluster_id, request, closure)
292            .await;
293    }
294
295    /// Sets up a streaming COPY FROM STDIN operation.
296    ///
297    /// Spawns N parallel background batch builder tasks that each receive
298    /// raw byte chunks, decode them, apply column defaults/reordering,
299    /// and build persist batches. Returns a [`CopyFromStdinWriter`] for
300    /// pgwire to distribute raw byte chunks across the workers.
301    pub(crate) fn setup_copy_from_stdin(
302        &self,
303        session: &Session,
304        target_id: CatalogItemId,
305        target_name: String,
306        columns: Vec<ColumnIndex>,
307        row_desc: RelationDesc,
308        params: CopyFormatParams<'static>,
309    ) -> Result<CopyFromStdinWriter, AdapterError> {
310        // Look up the table and its persist shard metadata.
311        let Some(entry) = self.catalog().try_get_entry(&target_id) else {
312            return Err(AdapterError::ConcurrentDependencyDrop {
313                dependency_kind: "table",
314                dependency_id: target_id.to_string(),
315            });
316        };
317        let Some(dest_table) = entry.table() else {
318            let typ = entry.item().typ();
319            return Err(AdapterError::Unstructured(anyhow::anyhow!(
320                "programming error: expected a Table found {typ:?}"
321            )));
322        };
323        let collection_id = dest_table.global_id_writes();
324
325        let collection_meta = self
326            .controller
327            .storage
328            .collection_metadata(collection_id)
329            .map_err(|e| AdapterError::Unstructured(anyhow::anyhow!("{e}")))?;
330        let shard_id = collection_meta.data_shard;
331        let collection_desc = collection_meta.relation_desc.clone();
332
333        // Pre-compute the column transformation.
334        let pcx = session.pcx().clone();
335        let session_meta = session.meta();
336        let catalog = self.catalog().clone();
337        let conn_catalog = catalog.for_session(session);
338        let catalog_state = conn_catalog.state();
339        let optimizer_config = optimize::OptimizerConfig::from(conn_catalog.system_vars());
340
341        // Determine if we need column rewriting (defaults/reordering).
342        let target_desc = catalog
343            .try_get_entry(&target_id)
344            .expect("table must exist")
345            .relation_desc_latest()
346            .expect("table has desc")
347            .into_owned();
348        let all_columns_in_order = columns.len() == target_desc.arity()
349            && columns.iter().enumerate().all(|(i, c)| c.to_raw() == i);
350
351        // If we need column rewriting, pre-compute the transform by running
352        // plan_copy_from with a single dummy row through the optimizer.
353        let column_transform = if all_columns_in_order {
354            None
355        } else {
356            let dummy_datums: Vec<Datum> = columns.iter().map(|_| Datum::Null).collect();
357            let dummy_row = Row::pack(&dummy_datums);
358
359            let prep = ExprPrepOneShot {
360                logical_time: EvalTime::NotAvailable,
361                session: &session_meta,
362                catalog_state,
363            };
364            let mut optimizer =
365                optimize::view::Optimizer::new_with_prep(optimizer_config.clone(), None, prep)
366                    .without_fold_constants_limit();
367
368            let hir = mz_sql::plan::plan_copy_from(
369                &pcx,
370                &conn_catalog,
371                target_id,
372                target_name.clone(),
373                columns.clone(),
374                vec![dummy_row],
375            )?;
376            let mir = optimize::Optimize::optimize(&mut optimizer, hir)?;
377            let mir_expr = mir.into_inner();
378            // Constant folding leaves some defaults alone, such as a jq call.
379            let Some((result_ref, _)) = mir_expr.as_const() else {
380                return Err(AdapterError::Unsupported(
381                    "column defaults that do not reduce to a constant in COPY FROM STDIN",
382                ));
383            };
384            let result_rows = result_ref
385                .clone()
386                .map_err(|e| AdapterError::Unstructured(anyhow::anyhow!("eval error: {e}")))?;
387
388            let (full_row, _) = result_rows.into_iter().next().expect("should have one row");
389            let full_datums: Vec<Datum> = full_row.unpack();
390
391            let col_to_source: std::collections::BTreeMap<ColumnIndex, usize> =
392                columns.iter().enumerate().map(|(a, b)| (*b, a)).collect();
393
394            let mut sources: Vec<ColumnSource> = Vec::with_capacity(target_desc.arity());
395            let mut default_datums: Vec<Datum> = Vec::new();
396
397            for i in 0..target_desc.arity() {
398                let col_idx = ColumnIndex::from_raw(i);
399                if let Some(&src_idx) = col_to_source.get(&col_idx) {
400                    sources.push(ColumnSource::Input(src_idx));
401                } else {
402                    sources.push(ColumnSource::Default(default_datums.len()));
403                    default_datums.push(full_datums[i]);
404                }
405            }
406
407            let defaults_row = Row::pack(&default_datums);
408
409            Some(ColumnTransform {
410                sources,
411                defaults_row,
412            })
413        };
414
415        // Compute column types for decoding (same logic as pgwire used to do).
416        let column_types: Arc<[mz_pgrepr::Type]> = row_desc
417            .typ()
418            .column_types
419            .iter()
420            .map(|x| &x.scalar_type)
421            .map(mz_pgrepr::Type::from)
422            .collect::<Vec<_>>()
423            .into();
424
425        // Determine number of parallel workers, capped so that a single COPY
426        // cannot reserve an unbounded share of the shared blocking pool.
427        let num_workers = std::cmp::min(
428            std::thread::available_parallelism()
429                .map(|n| n.get())
430                .unwrap_or(1),
431            COPY_FROM_STDIN_MAX_WORKERS,
432        );
433        tracing::info!(
434            %target_id, num_workers,
435            "starting parallel COPY FROM STDIN batch builders"
436        );
437
438        // Shared state across workers.
439        let column_transform = Arc::new(column_transform);
440        let target_desc = Arc::new(target_desc);
441        let collection_desc = Arc::new(collection_desc);
442        let persist_client = self.persist_client.clone();
443
444        // Create per-worker channels and spawn one async task per worker. Each
445        // worker offloads the CPU-intensive processing of a chunk (decode plus
446        // the per-row transform/constraint-check/columnar encode) to the
447        // blocking pool for the duration of that chunk (see
448        // `copy_from_stdin_batch_builder`), so workers run in parallel while
449        // doing CPU work but hold no thread while idle between chunks.
450        let mut batch_txs = Vec::with_capacity(num_workers);
451        let mut worker_handles = Vec::with_capacity(num_workers);
452
453        // When COPY FROM uses CSV with HEADER, only the very first chunk in
454        // the stream contains the real header line. The pgwire handler splits
455        // data into ~32MB chunks distributed round-robin across workers, so
456        // subsequent chunks' first rows are data, not headers. We must only
457        // skip the header on the first chunk of worker 0.
458        let first_chunk_has_header = params.requires_header();
459        let mut worker_params = params;
460        if let CopyFormatParams::Csv(ref mut csv) = worker_params {
461            csv.header = false;
462        }
463
464        for worker_id in 0..num_workers {
465            // Keep in-flight buffering tight: at most one chunk queued per
466            // worker in addition to the currently-processed chunk.
467            let (batch_tx, batch_rx) = mpsc::channel::<Vec<u8>>(1);
468            batch_txs.push(batch_tx);
469
470            let persist_client = persist_client.clone();
471            let column_types = Arc::clone(&column_types);
472            let column_transform = Arc::clone(&column_transform);
473            let target_desc = Arc::clone(&target_desc);
474            let collection_desc = Arc::clone(&collection_desc);
475            let params = worker_params.clone();
476            // Only worker 0 receives the first chunk (round-robin), so only
477            // it needs to skip the CSV header on its first chunk.
478            let skip_header_on_first_chunk = worker_id == 0 && first_chunk_has_header;
479
480            let handle = mz_ore::task::spawn(
481                || format!("copy_from_stdin_worker:{target_id}:{worker_id}"),
482                Self::copy_from_stdin_batch_builder(
483                    persist_client,
484                    shard_id,
485                    collection_id,
486                    collection_desc,
487                    target_desc,
488                    column_transform,
489                    column_types,
490                    params,
491                    skip_header_on_first_chunk,
492                    batch_rx,
493                ),
494            );
495            worker_handles.push(handle);
496        }
497
498        // Spawn a collector task that waits for all workers.
499        let (completion_tx, completion_rx) = oneshot::channel();
500        mz_ore::task::spawn(
501            || format!("copy_from_stdin_collector:{target_id}"),
502            async move {
503                let mut all_batches = Vec::with_capacity(num_workers);
504                let mut total_rows: u64 = 0;
505
506                for handle in worker_handles {
507                    match handle.await {
508                        Ok((proto_batches, count)) => {
509                            all_batches.extend(proto_batches);
510                            total_rows += count;
511                        }
512                        Err(e) => {
513                            let _ = completion_tx.send(Err(e));
514                            return;
515                        }
516                    }
517                }
518
519                let _ = completion_tx.send(Ok((all_batches, total_rows)));
520            },
521        );
522
523        Ok(CopyFromStdinWriter {
524            batch_txs,
525            completion_rx,
526        })
527    }
528
529    /// Background task: receives raw byte chunks, decodes rows, and builds
530    /// persist batches. One instance runs per parallel worker.
531    async fn copy_from_stdin_batch_builder(
532        persist_client: mz_persist_client::PersistClient,
533        shard_id: mz_persist_client::ShardId,
534        collection_id: mz_repr::GlobalId,
535        collection_desc: Arc<RelationDesc>,
536        target_desc: Arc<RelationDesc>,
537        column_transform: Arc<Option<ColumnTransform>>,
538        column_types: Arc<[mz_pgrepr::Type]>,
539        params: CopyFormatParams<'static>,
540        skip_header_on_first_chunk: bool,
541        mut batch_rx: mpsc::Receiver<Vec<u8>>,
542    ) -> Result<(Vec<ProtoBatch>, u64), AdapterError> {
543        let persist_diagnostics = Diagnostics {
544            shard_name: collection_id.to_string(),
545            handle_purpose: "CopyFromStdin::batch_builder".to_string(),
546        };
547        let write_handle = persist_client
548            .open_writer::<SourceData, (), mz_repr::Timestamp, StorageDiff>(
549                shard_id,
550                collection_desc,
551                Arc::new(UnitSchema),
552                persist_diagnostics,
553            )
554            .await
555            .map_err(|e| AdapterError::Unstructured(anyhow::anyhow!("persist open: {e}")))?;
556
557        // Build a batch at the minimum timestamp. The coordinator will
558        // re-timestamp it during commit.
559        let lower = mz_repr::Timestamp::MIN;
560        let upper = Antichain::from_elem(lower.step_forward());
561        let mut batch_builder = write_handle.rewritable_builder(Antichain::from_elem(lower));
562        let mut row_count: u64 = 0;
563        let mut row_count_in_batch: u64 = 0;
564        let mut batch_bytes: usize = 0;
565        let mut proto_batches = Vec::new();
566
567        let rt = tokio::runtime::Handle::current();
568        let mut is_first_chunk = true;
569        while let Some(raw_bytes) = batch_rx.recv().await {
570            // For the first chunk of worker 0, re-enable header skipping so the
571            // real CSV header line is skipped.
572            let chunk_params = if is_first_chunk && skip_header_on_first_chunk {
573                let mut p = params.clone();
574                if let CopyFormatParams::Csv(ref mut csv) = p {
575                    csv.header = true;
576                }
577                p
578            } else {
579                params.clone()
580            };
581            is_first_chunk = false;
582            let raw_len = raw_bytes.len();
583
584            // Offload the entire CPU-bound per-chunk pipeline -- decode, column
585            // transform, constraint checks, and the columnar persist encode
586            // (`BatchBuilder::add` -> `PartBuilder::push`) -- to the blocking
587            // pool. There is no yield point in the row loop until a batch fills
588            // (`add` only awaits `flush_part`, and only once an *encoded* part
589            // reaches `blob_target_size`, far beyond the 32 MiB *raw* batch
590            // boundary), so left on the async runtime each chunk's rows would
591            // run as one uninterrupted burst on a shared runtime worker thread,
592            // starving other connections. The blocking thread is held only
593            // while a chunk is in flight and released back to the pool between
594            // chunks (during `recv().await`), so idle workers still hold no
595            // thread. `block_on` is invoked once per chunk -- not per row -- to
596            // drive the row loop and the rare `flush_part` it may await.
597            let chunk_column_types = Arc::clone(&column_types);
598            let chunk_transform = Arc::clone(&column_transform);
599            let chunk_target_desc = Arc::clone(&target_desc);
600            let chunk_rt = rt.clone();
601            let (returned_builder, added_rows) = mz_ore::task::spawn_blocking(
602                || "copy_from_stdin_process_chunk",
603                move || {
604                    let rows = mz_pgcopy::decode_copy_format(
605                        &raw_bytes,
606                        &chunk_column_types,
607                        chunk_params,
608                    )
609                    .map_err(|e| AdapterError::CopyFormatError(e.to_string()))?;
610
611                    chunk_rt.block_on(async move {
612                        let mut added: u64 = 0;
613                        for row in rows {
614                            // Apply column transform if needed (add defaults, reorder).
615                            let full_row = if let Some(ref transform) = *chunk_transform {
616                                transform.apply(&row)
617                            } else {
618                                row
619                            };
620
621                            // Check constraints.
622                            for (i, datum) in full_row.iter().enumerate() {
623                                chunk_target_desc.constraints_met(i, &datum).map_err(|e| {
624                                    AdapterError::Unstructured(anyhow::anyhow!(
625                                        "constraint violation: {e}"
626                                    ))
627                                })?;
628                            }
629
630                            let data = SourceData(Ok(full_row));
631                            batch_builder
632                                .add(&data, &(), &lower, &1)
633                                .await
634                                .map_err(|e| {
635                                    AdapterError::Unstructured(anyhow::anyhow!("persist add: {e}"))
636                                })?;
637                            added += 1;
638                        }
639                        Ok::<_, AdapterError>((batch_builder, added))
640                    })
641                },
642            )
643            .await?;
644            batch_builder = returned_builder;
645            row_count += added_rows;
646            row_count_in_batch += added_rows;
647
648            batch_bytes = batch_bytes.saturating_add(raw_len);
649            if batch_bytes >= COPY_FROM_STDIN_MAX_BATCH_BYTES {
650                let batch = batch_builder.finish(upper.clone()).await.map_err(|e| {
651                    AdapterError::Unstructured(anyhow::anyhow!("persist finish: {e}"))
652                })?;
653                proto_batches.push(batch.into_transmittable_batch());
654
655                batch_builder = write_handle.rewritable_builder(Antichain::from_elem(lower));
656                row_count_in_batch = 0;
657                batch_bytes = 0;
658            }
659        }
660
661        if row_count_in_batch > 0 || proto_batches.is_empty() {
662            let batch = batch_builder
663                .finish(upper)
664                .await
665                .map_err(|e| AdapterError::Unstructured(anyhow::anyhow!("persist finish: {e}")))?;
666            proto_batches.push(batch.into_transmittable_batch());
667        }
668
669        Ok((proto_batches, row_count))
670    }
671
672    pub(crate) fn commit_staged_batches(
673        &mut self,
674        conn_id: ConnectionId,
675        table_id: CatalogItemId,
676        batches: Vec<Result<ProtoBatch, String>>,
677    ) {
678        let Some(active_copy) = self.active_copies.remove(&conn_id) else {
679            // Getting a successful response for a cancel COPY FROM is unexpected.
680            tracing::warn!(%conn_id, ?batches, "got response for canceled COPY FROM");
681            return;
682        };
683
684        let ActiveCopyFrom {
685            ingestion_id,
686            cluster_id: _,
687            table_id: _,
688            mut ctx,
689        } = active_copy;
690        tracing::info!(%ingestion_id, num_batches = ?batches.len(), "received batches to append");
691
692        let mut all_batches = SmallVec::with_capacity(batches.len());
693        let mut all_errors = SmallVec::<[String; 1]>::with_capacity(batches.len());
694        let mut row_count = 0u64;
695
696        for maybe_batch in batches {
697            match maybe_batch {
698                Ok(batch) => {
699                    let count = batch.batch.as_ref().map(|b| b.len).unwrap_or(0);
700                    all_batches.push(batch);
701                    row_count = row_count.saturating_add(count);
702                }
703                Err(err) => all_errors.push(err),
704            }
705        }
706
707        // If we got any errors we need to fail the whole operation.
708        if let Some(error) = all_errors.pop() {
709            tracing::warn!(?error, ?all_errors, "failed COPY FROM");
710
711            // TODO(cf1): Cleanup the existing ProtoBatches to prevent leaking them.
712            // TODO(cf2): Carry structured errors all the way through.
713
714            ctx.retire(Err(AdapterError::Unstructured(anyhow::anyhow!(
715                "COPY FROM: {error}"
716            ))));
717
718            return;
719        }
720
721        // Stage a WriteOp, then when the Session is retired we complete the
722        // transaction, which handles advancing the timestamps of the staged batches and waiting for
723        // everything to complete before sending a response to the client.
724        let stage_write = ctx
725            .session_mut()
726            .add_transaction_ops(TransactionOps::Writes(vec![WriteOp {
727                id: table_id,
728                rows: TableData::Batches(all_batches),
729            }]));
730
731        if let Err(err) = stage_write {
732            ctx.retire(Err(err));
733        } else {
734            ctx.retire(Ok(ExecuteResponse::Copied(row_count.cast_into())));
735        }
736    }
737
738    /// Cancel any active `COPY FROM` statements/oneshot ingestions.
739    #[mz_ore::instrument(level = "debug")]
740    pub(crate) fn cancel_pending_copy(&mut self, conn_id: &ConnectionId) {
741        if let Some(ActiveCopyFrom {
742            ingestion_id,
743            cluster_id: _,
744            table_id: _,
745            ctx,
746        }) = self.active_copies.remove(conn_id)
747        {
748            let cancel_result = self
749                .controller
750                .storage
751                .cancel_oneshot_ingestion(ingestion_id);
752            if let Err(err) = cancel_result {
753                tracing::error!(?err, "failed to cancel OneshotIngestion");
754            }
755
756            ctx.retire(Err(AdapterError::Canceled));
757        }
758    }
759}
760
761/// Describes how to transform a partial row (with only specified columns)
762/// into a full row matching the table schema.
763struct ColumnTransform {
764    /// For each column in the target table, where to get the value.
765    sources: Vec<ColumnSource>,
766    /// Pre-computed default values for columns not in the COPY column list.
767    /// Packed as a Row; indexed by the `Default(idx)` variant.
768    defaults_row: Row,
769}
770
771enum ColumnSource {
772    /// Take the value from the input row at this position.
773    Input(usize),
774    /// Use the pre-computed default at this index in `defaults_row`.
775    Default(usize),
776}
777
778impl ColumnTransform {
779    /// Apply the transform to produce a full row from a partial input row.
780    fn apply(&self, input: &Row) -> Row {
781        let input_datums: Vec<Datum> = input.unpack();
782        let default_datums: Vec<Datum> = self.defaults_row.unpack();
783        let mut output_datums = Vec::with_capacity(self.sources.len());
784        for source in &self.sources {
785            match source {
786                ColumnSource::Input(idx) => output_datums.push(input_datums[*idx]),
787                ColumnSource::Default(idx) => output_datums.push(default_datums[*idx]),
788            }
789        }
790        Row::pack(&output_datums)
791    }
792}