1use std::cmp::Ordering;
86use std::collections::{BTreeSet, VecDeque};
87use std::convert::Infallible;
88use std::future::Future;
89use std::time::Instant;
90use std::{cell::RefCell, rc::Rc, sync::Arc};
91
92use anyhow::{Context, anyhow};
93use arrow::array::{ArrayRef, Int32Array, Int64Array, RecordBatch};
94use arrow::datatypes::{DataType, Field, Schema as ArrowSchema};
95use differential_dataflow::trace::Span;
96use differential_dataflow::trace::implementations::ord_neu::OrdValBatch;
97use differential_dataflow::trace::implementations::spine_fueled::SpineBatch;
98use differential_dataflow::trace::implementations::{BatchContainer, Layout};
99use differential_dataflow::{Hashable, VecCollection};
100use futures::StreamExt;
101use iceberg::ErrorKind;
102use iceberg::arrow::{
103 arrow_schema_to_schema, arrow_schema_to_schema_auto_assign_ids, schema_to_arrow_schema,
104};
105use iceberg::spec::{
106 DataFile, FormatVersion, NestedField, NestedFieldRef, PrimitiveType, Snapshot, StructType,
107 Type, read_data_files_from_avro, write_data_files_to_avro,
108};
109use iceberg::spec::{Schema, SchemaRef};
110use iceberg::table::Table;
111use iceberg::transaction::{RowDeltaAction, TransactionAction};
112use iceberg::writer::base_writer::data_file_writer::DataFileWriterBuilder;
113use iceberg::writer::base_writer::equality_delete_writer::{
114 EqualityDeleteFileWriterBuilder, EqualityDeleteWriterConfig,
115};
116use iceberg::writer::base_writer::position_delete_writer::{
117 PositionDeleteFileWriterBuilder, PositionDeleteWriterConfig,
118};
119use iceberg::writer::combined_writer::delta_writer::DeltaWriterBuilder;
120use iceberg::writer::file_writer::ParquetWriterBuilder;
121use iceberg::writer::file_writer::location_generator::{
122 DefaultFileNameGenerator, DefaultLocationGenerator,
123};
124use iceberg::writer::file_writer::rolling_writer::RollingFileWriterBuilder;
125use iceberg::writer::{IcebergWriter, IcebergWriterBuilder};
126use iceberg::{Catalog, NamespaceIdent, TableCommit, TableCreation, TableIdent};
127use itertools::Itertools;
128use mz_arrow_util::builder::{ARROW_EXTENSION_NAME_KEY, ArrowBuilder};
129use mz_interchange::avro::DiffPair;
130use mz_interchange::envelopes::for_each_diff_pair_async;
131use mz_ore::cast::CastFrom;
132use mz_ore::error::ErrorExt;
133use mz_ore::future::InTask;
134use mz_ore::result::ResultExt;
135use mz_ore::retry::{Retry, RetryResult};
136use mz_persist_client::Diagnostics;
137use mz_persist_client::write::WriteHandle;
138use mz_persist_types::codec_impls::UnitSchema;
139use mz_repr::{Diff, GlobalId, Row, Timestamp};
140use mz_row_spine::ArcBatch;
141use mz_storage_types::StorageDiff;
142use mz_storage_types::configuration::StorageConfiguration;
143use mz_storage_types::controller::CollectionMetadata;
144use mz_storage_types::errors::DataflowError;
145use mz_storage_types::sinks::{
146 IcebergSinkConnection, SinkEnvelope, StorageSinkDesc, iceberg_type_overrides,
147};
148use mz_storage_types::sources::SourceData;
149use mz_timely_util::antichain::AntichainExt;
150use mz_timely_util::builder_async::{Event, OperatorBuilder, PressOnDropButton};
151use parquet::arrow::PARQUET_FIELD_ID_META_KEY;
152use parquet::file::properties::WriterProperties;
153use serde::{Deserialize, Serialize};
154use timely::PartialOrder;
155use timely::container::CapacityContainerBuilder;
156use timely::dataflow::StreamVec;
157use timely::dataflow::channels::pact::{Exchange, Pipeline};
158use timely::dataflow::operators::vec::{Broadcast, Map, ToStream};
159use timely::dataflow::operators::{CapabilitySet, Concatenate};
160use timely::progress::{Antichain, Timestamp as _};
161use tracing::{debug, info};
162
163use crate::healthcheck::{HealthStatusMessage, HealthStatusUpdate, StatusNamespace};
164use crate::metrics::sink::iceberg::IcebergSinkMetrics;
165use crate::render::sinks::{PkViolationWarner, SinkBatchStream, SinkRender};
166use crate::statistics::SinkStatistics;
167use crate::storage_state::StorageState;
168
169const DEFAULT_ARRAY_BUILDER_ITEM_CAPACITY: usize = 1024;
172const DEFAULT_ARRAY_BUILDER_DATA_CAPACITY: usize = 1024;
176
177const PARQUET_FILE_PREFIX: &str = "mz_data";
179const INITIAL_DESCRIPTIONS_TO_MINT: u64 = 3;
182
183struct WriterContext {
186 arrow_schema: Arc<ArrowSchema>,
188 current_schema: Arc<Schema>,
190 file_io: iceberg::io::FileIO,
192 location_generator: DefaultLocationGenerator,
194 file_name_generator: DefaultFileNameGenerator,
196 writer_properties: WriterProperties,
197}
198
199trait EnvelopeHandler: Send {
201 fn new(
203 ctx: WriterContext,
204 connection: &IcebergSinkConnection,
205 materialize_arrow_schema: &Arc<ArrowSchema>,
206 ) -> anyhow::Result<Self>
207 where
208 Self: Sized;
209
210 async fn create_writer(&self, is_snapshot: bool) -> anyhow::Result<Box<dyn IcebergWriter>>;
216
217 fn row_to_batch(&self, diff_pair: DiffPair<Row>, ts: Timestamp) -> anyhow::Result<RecordBatch>;
218}
219
220struct UpsertEnvelopeHandler {
221 ctx: WriterContext,
222 equality_ids: Vec<i32>,
224 pos_schema: Arc<Schema>,
226 eq_schema: Arc<Schema>,
228 eq_config: EqualityDeleteWriterConfig,
230 schema_with_op: Arc<ArrowSchema>,
234}
235
236impl EnvelopeHandler for UpsertEnvelopeHandler {
237 fn new(
238 ctx: WriterContext,
239 connection: &IcebergSinkConnection,
240 materialize_arrow_schema: &Arc<ArrowSchema>,
241 ) -> anyhow::Result<Self> {
242 let Some((_, equality_indices)) = &connection.key_desc_and_indices else {
243 return Err(StallingError::MissingKey.into());
244 };
245
246 let equality_ids = equality_ids_for_indices(
247 ctx.current_schema.as_ref(),
248 materialize_arrow_schema.as_ref(),
249 equality_indices,
250 )?;
251
252 let pos_arrow_schema = PositionDeleteWriterConfig::arrow_schema();
253 let pos_schema = Arc::new(
254 arrow_schema_to_schema(&pos_arrow_schema)
255 .context("Failed to convert position delete Arrow schema to Iceberg schema")?,
256 );
257
258 let eq_config =
259 EqualityDeleteWriterConfig::new(equality_ids.clone(), Arc::clone(&ctx.current_schema))
260 .context("Failed to create EqualityDeleteWriterConfig")?;
261 let eq_schema = Arc::new(
262 arrow_schema_to_schema(eq_config.projected_arrow_schema_ref())
263 .context("Failed to convert equality delete Arrow schema to Iceberg schema")?,
264 );
265
266 let schema_with_op = Arc::new(build_schema_with_op_column(&ctx.arrow_schema));
267
268 Ok(Self {
269 ctx,
270 equality_ids,
271 pos_schema,
272 eq_schema,
273 eq_config,
274 schema_with_op,
275 })
276 }
277
278 async fn create_writer(&self, is_snapshot: bool) -> anyhow::Result<Box<dyn IcebergWriter>> {
279 let data_parquet_writer = ParquetWriterBuilder::new(
280 self.ctx.writer_properties.clone(),
281 Arc::clone(&self.ctx.current_schema),
282 )
283 .with_arrow_schema(Arc::clone(&self.ctx.arrow_schema))
284 .context("Arrow schema validation failed")?;
285 let data_rolling_writer = RollingFileWriterBuilder::new_with_default_file_size(
286 data_parquet_writer,
287 Arc::clone(&self.ctx.current_schema),
288 self.ctx.file_io.clone(),
289 self.ctx.location_generator.clone(),
290 self.ctx.file_name_generator.clone(),
291 );
292 let data_writer_builder = DataFileWriterBuilder::new(data_rolling_writer);
293
294 let pos_config = PositionDeleteWriterConfig::new(None, 0, None);
295 let pos_parquet_writer = ParquetWriterBuilder::new(
296 self.ctx.writer_properties.clone(),
297 Arc::clone(&self.pos_schema),
298 );
299 let pos_rolling_writer = RollingFileWriterBuilder::new_with_default_file_size(
300 pos_parquet_writer,
301 Arc::clone(&self.ctx.current_schema),
302 self.ctx.file_io.clone(),
303 self.ctx.location_generator.clone(),
304 self.ctx.file_name_generator.clone(),
305 );
306 let pos_delete_writer_builder =
307 PositionDeleteFileWriterBuilder::new(pos_rolling_writer, pos_config);
308
309 let eq_parquet_writer = ParquetWriterBuilder::new(
310 self.ctx.writer_properties.clone(),
311 Arc::clone(&self.eq_schema),
312 );
313 let eq_rolling_writer = RollingFileWriterBuilder::new_with_default_file_size(
314 eq_parquet_writer,
315 Arc::clone(&self.ctx.current_schema),
316 self.ctx.file_io.clone(),
317 self.ctx.location_generator.clone(),
318 self.ctx.file_name_generator.clone(),
319 );
320 let eq_delete_writer_builder =
321 EqualityDeleteFileWriterBuilder::new(eq_rolling_writer, self.eq_config.clone());
322
323 let mut builder = DeltaWriterBuilder::new(
324 data_writer_builder,
325 pos_delete_writer_builder,
326 eq_delete_writer_builder,
327 self.equality_ids.clone(),
328 );
329
330 builder = if is_snapshot {
331 builder.with_max_seen_rows(0)
333 } else {
334 builder.with_max_seen_rows(usize::MAX)
346 };
347
348 Ok(Box::new(
349 builder
350 .build(None)
351 .await
352 .context("Failed to create DeltaWriter")?,
353 ))
354 }
355
356 fn row_to_batch(
359 &self,
360 diff_pair: DiffPair<Row>,
361 _ts: Timestamp,
362 ) -> anyhow::Result<RecordBatch> {
363 let mut builder = ArrowBuilder::new_with_schema(
364 Arc::clone(&self.ctx.arrow_schema),
365 DEFAULT_ARRAY_BUILDER_ITEM_CAPACITY,
366 DEFAULT_ARRAY_BUILDER_DATA_CAPACITY,
367 )
368 .context("Failed to create builder")?;
369
370 let mut op_values = Vec::new();
371
372 if let Some(before) = diff_pair.before {
373 builder
374 .add_row(&before)
375 .context("Failed to add delete row to builder")?;
376 op_values.push(-1i32);
377 }
378 if let Some(after) = diff_pair.after {
379 builder
380 .add_row(&after)
381 .context("Failed to add insert row to builder")?;
382 op_values.push(1i32);
383 }
384
385 let batch = builder
386 .to_record_batch()
387 .context("Failed to create record batch")?;
388
389 let mut columns: Vec<ArrayRef> = batch.columns().to_vec();
390 columns.push(Arc::new(Int32Array::from(op_values)));
391
392 RecordBatch::try_new(Arc::clone(&self.schema_with_op), columns)
393 .context("Failed to create batch with op column")
394 }
395}
396
397struct AppendEnvelopeHandler {
398 ctx: WriterContext,
399 user_schema_for_append: Arc<ArrowSchema>,
402}
403
404impl EnvelopeHandler for AppendEnvelopeHandler {
405 fn new(
406 ctx: WriterContext,
407 _connection: &IcebergSinkConnection,
408 _materialize_arrow_schema: &Arc<ArrowSchema>,
409 ) -> anyhow::Result<Self> {
410 let n = ctx.arrow_schema.fields().len().saturating_sub(2);
413 let user_schema_for_append =
414 Arc::new(ArrowSchema::new(ctx.arrow_schema.fields()[..n].to_vec()));
415
416 Ok(Self {
417 ctx,
418 user_schema_for_append,
419 })
420 }
421
422 async fn create_writer(&self, _is_snapshot: bool) -> anyhow::Result<Box<dyn IcebergWriter>> {
423 let data_parquet_writer = ParquetWriterBuilder::new(
424 self.ctx.writer_properties.clone(),
425 Arc::clone(&self.ctx.current_schema),
426 )
427 .with_arrow_schema(Arc::clone(&self.ctx.arrow_schema))
428 .context("Arrow schema validation failed")?;
429 let data_rolling_writer = RollingFileWriterBuilder::new_with_default_file_size(
430 data_parquet_writer,
431 Arc::clone(&self.ctx.current_schema),
432 self.ctx.file_io.clone(),
433 self.ctx.location_generator.clone(),
434 self.ctx.file_name_generator.clone(),
435 );
436 Ok(Box::new(
437 DataFileWriterBuilder::new(data_rolling_writer)
438 .build(None)
439 .await
440 .context("Failed to create DataFileWriter")?,
441 ))
442 }
443
444 fn row_to_batch(&self, diff_pair: DiffPair<Row>, ts: Timestamp) -> anyhow::Result<RecordBatch> {
447 let mut builder = ArrowBuilder::new_with_schema(
448 Arc::clone(&self.user_schema_for_append),
449 DEFAULT_ARRAY_BUILDER_ITEM_CAPACITY,
450 DEFAULT_ARRAY_BUILDER_DATA_CAPACITY,
451 )
452 .context("Failed to create builder")?;
453
454 let mut diff_values: Vec<i32> = Vec::new();
455 let ts_i64 = i64::try_from(u64::from(ts)).unwrap_or(i64::MAX);
456
457 if let Some(before) = diff_pair.before {
458 builder
459 .add_row(&before)
460 .context("Failed to add before row to builder")?;
461 diff_values.push(-1i32);
462 }
463 if let Some(after) = diff_pair.after {
464 builder
465 .add_row(&after)
466 .context("Failed to add after row to builder")?;
467 diff_values.push(1i32);
468 }
469
470 let n = diff_values.len();
471 let batch = builder
472 .to_record_batch()
473 .context("Failed to create record batch")?;
474
475 let mut columns: Vec<ArrayRef> = batch.columns().to_vec();
476 columns.push(Arc::new(Int32Array::from(diff_values)));
477 columns.push(Arc::new(Int64Array::from(vec![ts_i64; n])));
478
479 RecordBatch::try_new(Arc::clone(&self.ctx.arrow_schema), columns)
480 .context("Failed to create append record batch")
481 }
482}
483
484fn add_field_ids_to_arrow_schema(schema: ArrowSchema) -> ArrowSchema {
489 let mut next_field_id = 1i32;
490 let fields: Vec<Field> = schema
491 .fields()
492 .iter()
493 .map(|field| add_field_ids_recursive(field, &mut next_field_id))
494 .collect();
495 ArrowSchema::new(fields).with_metadata(schema.metadata().clone())
496}
497
498fn add_field_ids_recursive(field: &Field, next_id: &mut i32) -> Field {
500 let current_id = *next_id;
501 *next_id += 1;
502
503 let mut metadata = field.metadata().clone();
504 metadata.insert(
505 PARQUET_FIELD_ID_META_KEY.to_string(),
506 current_id.to_string(),
507 );
508
509 let new_data_type = add_field_ids_to_datatype(field.data_type(), next_id);
510
511 Field::new(field.name(), new_data_type, field.is_nullable()).with_metadata(metadata)
512}
513
514fn add_field_ids_to_datatype(data_type: &DataType, next_id: &mut i32) -> DataType {
516 match data_type {
517 DataType::Struct(fields) => {
518 let new_fields: Vec<Field> = fields
519 .iter()
520 .map(|f| add_field_ids_recursive(f, next_id))
521 .collect();
522 DataType::Struct(new_fields.into())
523 }
524 DataType::List(element_field) => {
525 let new_element = add_field_ids_recursive(element_field, next_id);
526 DataType::List(Arc::new(new_element))
527 }
528 DataType::LargeList(element_field) => {
529 let new_element = add_field_ids_recursive(element_field, next_id);
530 DataType::LargeList(Arc::new(new_element))
531 }
532 DataType::Map(entries_field, sorted) => {
533 let new_entries = add_field_ids_recursive(entries_field, next_id);
534 DataType::Map(Arc::new(new_entries), *sorted)
535 }
536 _ => data_type.clone(),
537 }
538}
539
540fn merge_materialize_metadata_into_iceberg_schema(
545 materialize_arrow_schema: &ArrowSchema,
546 iceberg_schema: &Schema,
547) -> anyhow::Result<ArrowSchema> {
548 let iceberg_arrow_schema = schema_to_arrow_schema(iceberg_schema)
550 .context("Failed to convert Iceberg schema to Arrow schema")?;
551
552 let fields: Vec<Field> = iceberg_arrow_schema
554 .fields()
555 .iter()
556 .map(|iceberg_field| {
557 let mz_field = materialize_arrow_schema
559 .field_with_name(iceberg_field.name())
560 .with_context(|| {
561 format!(
562 "Field '{}' not found in Materialize schema",
563 iceberg_field.name()
564 )
565 })?;
566
567 merge_field_metadata_recursive(iceberg_field, Some(mz_field))
568 })
569 .collect::<anyhow::Result<Vec<_>>>()?;
570
571 Ok(ArrowSchema::new(fields).with_metadata(iceberg_arrow_schema.metadata().clone()))
572}
573
574fn merge_field_metadata_recursive(
576 iceberg_field: &Field,
577 mz_field: Option<&Field>,
578) -> anyhow::Result<Field> {
579 let mut metadata = iceberg_field.metadata().clone();
581
582 if let Some(mz_f) = mz_field {
584 if let Some(extension_name) = mz_f.metadata().get(ARROW_EXTENSION_NAME_KEY) {
585 metadata.insert(ARROW_EXTENSION_NAME_KEY.to_string(), extension_name.clone());
586 }
587 }
588
589 let new_data_type = match iceberg_field.data_type() {
591 DataType::Struct(iceberg_fields) => {
592 let mz_struct_fields = match mz_field {
593 Some(f) => match f.data_type() {
594 DataType::Struct(fields) => Some(fields),
595 other => anyhow::bail!(
596 "Type mismatch for field '{}': Iceberg schema has Struct, but Materialize schema has {:?}",
597 iceberg_field.name(),
598 other
599 ),
600 },
601 None => None,
602 };
603
604 let new_fields: Vec<Field> = iceberg_fields
605 .iter()
606 .map(|iceberg_inner| {
607 let mz_inner = mz_struct_fields.and_then(|fields| {
608 fields.iter().find(|f| f.name() == iceberg_inner.name())
609 });
610 merge_field_metadata_recursive(iceberg_inner, mz_inner.map(|f| f.as_ref()))
611 })
612 .collect::<anyhow::Result<Vec<_>>>()?;
613
614 DataType::Struct(new_fields.into())
615 }
616 DataType::List(iceberg_element) => {
617 let mz_element = match mz_field {
618 Some(f) => match f.data_type() {
619 DataType::List(element) => Some(element.as_ref()),
620 other => anyhow::bail!(
621 "Type mismatch for field '{}': Iceberg schema has List, but Materialize schema has {:?}",
622 iceberg_field.name(),
623 other
624 ),
625 },
626 None => None,
627 };
628 let new_element = merge_field_metadata_recursive(iceberg_element, mz_element)?;
629 DataType::List(Arc::new(new_element))
630 }
631 DataType::LargeList(iceberg_element) => {
632 let mz_element = match mz_field {
633 Some(f) => match f.data_type() {
634 DataType::LargeList(element) => Some(element.as_ref()),
635 other => anyhow::bail!(
636 "Type mismatch for field '{}': Iceberg schema has LargeList, but Materialize schema has {:?}",
637 iceberg_field.name(),
638 other
639 ),
640 },
641 None => None,
642 };
643 let new_element = merge_field_metadata_recursive(iceberg_element, mz_element)?;
644 DataType::LargeList(Arc::new(new_element))
645 }
646 DataType::Map(iceberg_entries, sorted) => {
647 let mz_entries = match mz_field {
648 Some(f) => match f.data_type() {
649 DataType::Map(entries, _) => Some(entries.as_ref()),
650 other => anyhow::bail!(
651 "Type mismatch for field '{}': Iceberg schema has Map, but Materialize schema has {:?}",
652 iceberg_field.name(),
653 other
654 ),
655 },
656 None => None,
657 };
658 let new_entries = match mz_entries {
663 Some(mz_entries) => merge_map_entries_metadata(iceberg_entries, mz_entries)?,
664 None => iceberg_entries.as_ref().clone(),
665 };
666 DataType::Map(Arc::new(new_entries), *sorted)
667 }
668 other => other.clone(),
669 };
670
671 Ok(Field::new(
672 iceberg_field.name(),
673 new_data_type,
674 iceberg_field.is_nullable(),
675 )
676 .with_metadata(metadata))
677}
678
679fn merge_map_entries_metadata(
701 iceberg_entries: &Field,
702 mz_entries: &Field,
703) -> anyhow::Result<Field> {
704 let mut metadata = iceberg_entries.metadata().clone();
705 if let Some(extension_name) = mz_entries.metadata().get(ARROW_EXTENSION_NAME_KEY) {
706 metadata.insert(ARROW_EXTENSION_NAME_KEY.to_string(), extension_name.clone());
707 }
708
709 let iceberg_fields = match iceberg_entries.data_type() {
710 DataType::Struct(fields) => fields,
711 other => anyhow::bail!(
712 "Iceberg map entries field '{}' is not a Struct: {:?}",
713 iceberg_entries.name(),
714 other
715 ),
716 };
717 let mz_fields = match mz_entries.data_type() {
718 DataType::Struct(fields) => fields,
719 other => anyhow::bail!(
720 "Materialize map entries field '{}' is not a Struct: {:?}",
721 mz_entries.name(),
722 other
723 ),
724 };
725
726 let new_fields: Vec<Field> = iceberg_fields
727 .iter()
728 .enumerate()
729 .map(|(idx, iceberg_inner)| {
730 let mz_inner = mz_fields.get(idx).map(|f| f.as_ref());
731 merge_field_metadata_recursive(iceberg_inner, mz_inner)
732 })
733 .collect::<anyhow::Result<Vec<_>>>()?;
734
735 Ok(Field::new(
736 iceberg_entries.name(),
737 DataType::Struct(new_fields.into()),
738 iceberg_entries.is_nullable(),
739 )
740 .with_metadata(metadata))
741}
742
743async fn reload_table(
744 catalog: &dyn Catalog,
745 namespace: String,
746 table_name: String,
747 current_table: &Table,
748) -> anyhow::Result<Table> {
749 let namespace_ident = NamespaceIdent::new(namespace.clone());
750 let table_ident = TableIdent::new(namespace_ident, table_name.clone());
751 let current_schema = current_table.metadata().current_schema_id();
752 let current_partition_spec = current_table.metadata().default_partition_spec_id();
753
754 match catalog.load_table(&table_ident).await {
755 Ok(table) => {
756 let reloaded_schema = table.metadata().current_schema_id();
757 let reloaded_partition_spec = table.metadata().default_partition_spec_id();
758 if reloaded_schema != current_schema {
759 return Err(anyhow::anyhow!(
760 "Iceberg table '{}' schema changed during operation but schema evolution isn't supported, expected schema ID {}, got {}",
761 table_name,
762 current_schema,
763 reloaded_schema
764 ));
765 }
766
767 if reloaded_partition_spec != current_partition_spec {
768 return Err(anyhow::anyhow!(
769 "Iceberg table '{}' partition spec changed during operation but partition spec evolution isn't supported, expected partition spec ID {}, got {}",
770 table_name,
771 current_partition_spec,
772 reloaded_partition_spec
773 ));
774 }
775
776 Ok(table)
777 }
778 Err(err) => Err(err).context("Failed to reload Iceberg table"),
779 }
780}
781
782enum CommitError {
784 Local(iceberg::Error),
787 Request(iceberg::Error),
790}
791
792async fn do_commit(
803 table: &Table,
804 catalog: &dyn Catalog,
805 snapshot_properties: Vec<(String, String)>,
806 data_files: Vec<DataFile>,
807 delete_files: Vec<DataFile>,
808) -> Result<Table, CommitError> {
809 let mut action = RowDeltaAction::new()
810 .set_snapshot_properties(snapshot_properties.into_iter().collect())
811 .with_check_duplicate(false);
812
813 if !data_files.is_empty() || !delete_files.is_empty() {
814 action = action
815 .add_data_files(data_files)
816 .add_delete_files(delete_files);
817 }
818
819 let mut action_commit = Arc::new(action)
825 .commit(table)
826 .await
827 .map_err(CommitError::Local)?;
828
829 let table_commit = TableCommit::builder()
835 .ident(table.identifier().clone())
836 .updates(action_commit.take_updates())
837 .requirements(action_commit.take_requirements())
838 .build();
839
840 catalog
841 .update_table(table_commit)
842 .await
843 .map_err(CommitError::Request)
844}
845
846async fn try_commit_batch(
848 table: Table,
849 snapshot_properties: Vec<(String, String)>,
850 data_files: Vec<DataFile>,
851 delete_files: Vec<DataFile>,
852 catalog: &dyn Catalog,
853 conn_namespace: &str,
854 conn_table: &str,
855 sink_id: GlobalId,
856 sink_version: u64,
857 batch_lower: &Antichain<Timestamp>,
858 batch_upper: &Antichain<Timestamp>,
859 metrics: &IcebergSinkMetrics,
860) -> (Table, RetryResult<(), anyhow::Error>) {
861 let table = match reload_table(
865 catalog,
866 conn_namespace.to_string(),
867 conn_table.to_string(),
868 &table,
869 )
870 .await
871 {
872 Ok(table) => table,
873 Err(e) => {
874 return (table, RetryResult::RetryableErr(anyhow!(e)));
876 }
877 };
878
879 let mut snapshots: Vec<_> = table.metadata().snapshots().cloned().collect();
880 let last = match retrieve_upper_from_snapshots(&mut snapshots) {
881 Ok(last) => last,
882 Err(e) => return (table, RetryResult::RetryableErr(e.into())),
883 };
884 if let Some((last_frontier, last_id, last_version)) = last {
885 if last_id == sink_id && last_version == sink_version && last_frontier == *batch_upper {
887 info!(
890 namespace = %conn_namespace,
891 table = %conn_table,
892 lower = %batch_lower.pretty(),
893 upper = %batch_upper.pretty(),
894 "found iceberg commit from previous attempt, treating as success"
895 );
896 return (table, RetryResult::Ok(()));
897 }
898
899 if last_version > sink_version {
900 return (
902 table,
903 RetryResult::FatalErr(
904 StallingError::FencedAtCommit {
905 table: conn_table.to_string(),
906 writer_version: last_version,
907 sink_version,
908 }
909 .into(),
910 ),
911 );
912 }
913
914 if PartialOrder::less_equal(batch_upper, &last_frontier)
915 || PartialOrder::less_than(batch_lower, &last_frontier)
916 {
917 return (
919 table,
920 RetryResult::FatalErr(anyhow!(
921 "Iceberg table '{}' has been modified by another writer. \
922 Current frontier: {:?}, last frontier: {:?}.",
923 conn_table,
924 batch_upper,
925 last_frontier,
926 )),
927 );
928 }
929 }
930
931 match do_commit(
932 &table,
933 catalog,
934 snapshot_properties,
935 data_files,
936 delete_files,
937 )
938 .await
939 {
940 Ok(new_table) => (new_table, RetryResult::Ok(())),
941 Err(CommitError::Local(e)) => {
942 metrics.commit_failures.inc();
945 (
946 table,
947 RetryResult::RetryableErr(anyhow!("Failed to build iceberg table commit: {}", e)),
948 )
949 }
950 Err(CommitError::Request(e)) => match e.kind() {
951 ErrorKind::CatalogCommitConflicts => {
952 metrics.commit_conflicts.inc();
955 (table, RetryResult::RetryableErr(anyhow!(e)))
956 }
957 ErrorKind::Unexpected => {
958 metrics.commit_failures.inc();
961 (table, RetryResult::RetryableErr(anyhow!(e)))
962 }
963 _ => {
964 metrics.commit_failures.inc();
966 (table, RetryResult::FatalErr(anyhow!(e)))
967 }
968 },
969 }
970}
971
972fn schema_mismatch(current: &Schema, expected: &Schema) -> Option<String> {
992 struct_mismatch(None, current.as_struct(), expected.as_struct())
993}
994
995fn struct_mismatch(
996 parent: Option<&str>,
997 current: &StructType,
998 expected: &StructType,
999) -> Option<String> {
1000 let (current, expected) = (current.fields(), expected.fields());
1001 let names = |fields: &[NestedFieldRef]| -> BTreeSet<String> {
1004 fields.iter().map(|field| field.name.clone()).collect()
1005 };
1006 let (current_names, expected_names) = (names(current), names(expected));
1007 if let Some(missing) = expected
1008 .iter()
1009 .find(|field| !current_names.contains(&field.name))
1010 {
1011 return Some(format!(
1012 "the table is missing `{}`",
1013 field_path(parent, &missing.name)
1014 ));
1015 }
1016 if let Some(extra) = current
1017 .iter()
1018 .find(|field| !expected_names.contains(&field.name))
1019 {
1020 return Some(format!(
1021 "the table has an extra field `{}`",
1022 field_path(parent, &extra.name)
1023 ));
1024 }
1025 std::iter::zip(current, expected).find_map(|(current_field, expected_field)| {
1028 field_mismatch(parent, current_field, expected_field)
1029 })
1030}
1031
1032fn field_mismatch(
1033 parent: Option<&str>,
1034 current: &NestedField,
1035 expected: &NestedField,
1036) -> Option<String> {
1037 let path = field_path(parent, &expected.name);
1038 if current.name != expected.name {
1039 return Some(format!(
1040 "the table has `{}` where `{path}` is expected",
1041 field_path(parent, ¤t.name)
1042 ));
1043 }
1044 if current.required != expected.required {
1045 let nullability = |required| if required { "required" } else { "optional" };
1046 return Some(format!(
1047 "`{path}` is {} in the table but {} in the sink",
1048 nullability(current.required),
1049 nullability(expected.required)
1050 ));
1051 }
1052 match (&*current.field_type, &*expected.field_type) {
1053 (Type::Primitive(PrimitiveType::Fixed(16)), Type::Primitive(PrimitiveType::String)) => None,
1055 (Type::Struct(current_struct), Type::Struct(expected_struct)) => {
1056 struct_mismatch(Some(&path), current_struct, expected_struct)
1057 }
1058 (Type::List(current_list), Type::List(expected_list)) => field_mismatch(
1059 Some(&path),
1060 ¤t_list.element_field,
1061 &expected_list.element_field,
1062 ),
1063 (Type::Map(current_map), Type::Map(expected_map)) => {
1064 let parent = Some(path.as_str());
1065 field_mismatch(parent, ¤t_map.key_field, &expected_map.key_field).or_else(|| {
1066 field_mismatch(parent, ¤t_map.value_field, &expected_map.value_field)
1067 })
1068 }
1069 (current_type, expected_type) if current_type == expected_type => None,
1070 (current_type, expected_type) => Some(format!(
1071 "`{path}` has type {} in the table but {} in the sink",
1072 type_name(current_type),
1073 type_name(expected_type)
1074 )),
1075 }
1076}
1077
1078fn field_path(parent: Option<&str>, name: &str) -> String {
1079 match parent {
1080 Some(parent) => format!("{parent}.{name}"),
1081 None => name.to_string(),
1082 }
1083}
1084
1085fn type_name(ty: &Type) -> String {
1088 match ty {
1089 Type::Primitive(primitive) => primitive.to_string(),
1090 Type::Struct(_) => "struct".to_string(),
1091 Type::List(_) => "list".to_string(),
1092 Type::Map(_) => "map".to_string(),
1093 }
1094}
1095
1096#[derive(Debug, thiserror::Error)]
1098enum StallingError {
1099 #[error("Iceberg table '{table_name}' schema does not match expected schema: {mismatch}")]
1100 SchemaMismatch {
1101 table_name: String,
1102 mismatch: String,
1103 },
1104 #[error("{0}")]
1105 Overcompacted(String),
1106 #[error(
1107 "Fenced off by newer sink version: resume_version {resume_version}, sink_version {sink_version}"
1108 )]
1109 FencedAtStartup {
1110 resume_version: u64,
1111 sink_version: u64,
1112 },
1113 #[error(
1114 "Iceberg table '{table}' has been modified by another writer with version \
1115 {writer_version}. Current sink version: {sink_version}. Frontiers may be out of sync, \
1116 aborting to avoid data loss."
1117 )]
1118 FencedAtCommit {
1119 table: String,
1120 writer_version: u64,
1121 sink_version: u64,
1122 },
1123 #[error(
1124 "Iceberg table is in an inconsistent state: snapshot {snapshot_id} has operation \
1125 '{operation}' but is missing 'mz-frontier' property. Schema or partition spec evolution \
1126 is not supported."
1127 )]
1128 MissingFrontier { snapshot_id: i64, operation: String },
1129 #[error("Failed to parse {property} from snapshot properties")]
1130 InvalidSnapshotProperty {
1131 property: &'static str,
1132 #[source]
1133 source: anyhow::Error,
1134 },
1135 #[error(transparent)]
1136 InvalidSchema(anyhow::Error),
1137 #[error("Iceberg sink requires key columns for equality deletes")]
1138 MissingKey,
1139}
1140
1141fn error_status(error: &anyhow::Error) -> HealthStatusMessage {
1143 let message = format!("{}", error.display_with_causes());
1144 let update = if error.is::<StallingError>() {
1145 HealthStatusUpdate::suspending(message, None)
1146 } else {
1147 HealthStatusUpdate::halting(message, None)
1148 };
1149 HealthStatusMessage {
1150 id: None,
1151 update,
1152 namespace: StatusNamespace::Iceberg,
1153 }
1154}
1155
1156async fn load_or_create_table(
1158 catalog: &dyn Catalog,
1159 namespace: String,
1160 table_name: String,
1161 schema: &Schema,
1162) -> anyhow::Result<iceberg::table::Table> {
1163 let namespace_ident = NamespaceIdent::new(namespace.clone());
1164 let table_ident = TableIdent::new(namespace_ident.clone(), table_name.clone());
1165
1166 match catalog.load_table(&table_ident).await {
1168 Ok(table) => {
1169 let current_schema = table.metadata().current_schema();
1172 if let Some(mismatch) = schema_mismatch(current_schema, schema) {
1173 return Err(StallingError::SchemaMismatch {
1174 table_name,
1175 mismatch,
1176 }
1177 .into());
1178 }
1179 Ok(table)
1180 }
1181 Err(err) => {
1182 if matches!(err.kind(), ErrorKind::TableNotFound { .. })
1183 || err
1184 .message()
1185 .contains("Tried to load a table that does not exist")
1186 {
1187 let table_creation = TableCreation::builder()
1191 .name(table_name.clone())
1192 .schema(schema.clone())
1193 .build();
1197
1198 catalog
1199 .create_table(&namespace_ident, table_creation)
1200 .await
1201 .with_context(|| {
1202 format!(
1203 "Failed to create Iceberg table '{}' in namespace '{}'",
1204 table_name, namespace
1205 )
1206 })
1207 } else {
1208 Err(err).context("Failed to load Iceberg table")
1210 }
1211 }
1212 }
1213}
1214
1215fn retrieve_upper_from_snapshots(
1222 snapshots: &mut [Arc<Snapshot>],
1223) -> Result<Option<(Antichain<Timestamp>, GlobalId, u64)>, StallingError> {
1224 fn invalid_property<E: Into<anyhow::Error>>(
1225 property: &'static str,
1226 ) -> impl FnOnce(E) -> StallingError {
1227 move |source| StallingError::InvalidSnapshotProperty {
1228 property,
1229 source: source.into(),
1230 }
1231 }
1232
1233 snapshots.sort_by(|a, b| Ord::cmp(&b.sequence_number(), &a.sequence_number()));
1234
1235 for snapshot in snapshots {
1236 let props = &snapshot.summary().additional_properties;
1237 if let (Some(frontier_json), Some(sink_id_str), Some(sink_version_str)) = (
1238 props.get("mz-frontier"),
1239 props.get("mz-sink-id"),
1240 props.get("mz-sink-version"),
1241 ) {
1242 let frontier: Vec<Timestamp> =
1243 serde_json::from_str(frontier_json).map_err(invalid_property("mz-frontier"))?;
1244 let frontier = Antichain::from_iter(frontier);
1245
1246 let sink_id = sink_id_str
1247 .parse::<GlobalId>()
1248 .map_err(invalid_property("mz-sink-id"))?;
1249
1250 let sink_version = sink_version_str
1251 .parse::<u64>()
1252 .map_err(invalid_property("mz-sink-version"))?;
1253
1254 return Ok(Some((frontier, sink_id, sink_version)));
1255 }
1256 if snapshot.summary().operation.as_str() != "replace" {
1257 return Err(StallingError::MissingFrontier {
1262 snapshot_id: snapshot.snapshot_id(),
1263 operation: snapshot.summary().operation.as_str().to_string(),
1264 });
1265 }
1266 }
1267
1268 Ok(None)
1269}
1270
1271fn relation_desc_to_iceberg_schema(
1281 desc: &mz_repr::RelationDesc,
1282) -> anyhow::Result<(ArrowSchema, SchemaRef)> {
1283 let arrow_schema =
1284 mz_arrow_util::builder::desc_to_schema_with_overrides(desc, iceberg_type_overrides)
1285 .context("Failed to convert RelationDesc to Iceberg-compatible Arrow schema")?;
1286
1287 let arrow_schema_with_ids = add_field_ids_to_arrow_schema(arrow_schema);
1288
1289 let iceberg_schema = arrow_schema_to_schema_auto_assign_ids(&arrow_schema_with_ids)
1290 .context("Failed to convert Arrow schema to Iceberg schema")?;
1291
1292 Ok((arrow_schema_with_ids, Arc::new(iceberg_schema)))
1293}
1294
1295fn equality_ids_for_indices(
1300 current_schema: &Schema,
1301 materialize_arrow_schema: &ArrowSchema,
1302 equality_indices: &[usize],
1303) -> anyhow::Result<Vec<i32>> {
1304 let top_level_fields = current_schema.as_struct();
1305
1306 equality_indices
1307 .iter()
1308 .map(|index| {
1309 let mz_field = materialize_arrow_schema
1310 .fields()
1311 .get(*index)
1312 .with_context(|| format!("Equality delete key index {index} is out of bounds"))?;
1313 let field_name = mz_field.name();
1314 let iceberg_field = top_level_fields
1315 .field_by_name(field_name)
1316 .with_context(|| {
1317 format!(
1318 "Equality delete key column '{}' not found in Iceberg table schema",
1319 field_name
1320 )
1321 })?;
1322 Ok(iceberg_field.id)
1323 })
1324 .collect()
1325}
1326
1327fn build_schema_with_op_column(schema: &ArrowSchema) -> ArrowSchema {
1329 let mut fields: Vec<Arc<Field>> = schema.fields().iter().cloned().collect();
1330 fields.push(Arc::new(Field::new("__op", DataType::Int32, false)));
1331 ArrowSchema::new(fields)
1332}
1333
1334#[allow(clippy::disallowed_types)]
1339fn build_schema_with_append_columns(schema: &ArrowSchema) -> ArrowSchema {
1340 use mz_storage_types::sinks::{ICEBERG_APPEND_DIFF_COLUMN, ICEBERG_APPEND_TIMESTAMP_COLUMN};
1341 let mut fields: Vec<Arc<Field>> = schema.fields().iter().cloned().collect();
1342 fields.push(Arc::new(Field::new(
1343 ICEBERG_APPEND_DIFF_COLUMN,
1344 DataType::Int32,
1345 false,
1346 )));
1347 fields.push(Arc::new(Field::new(
1348 ICEBERG_APPEND_TIMESTAMP_COLUMN,
1349 DataType::Int64,
1350 false,
1351 )));
1352
1353 add_field_ids_to_arrow_schema(ArrowSchema::new(fields).with_metadata(schema.metadata().clone()))
1354}
1355
1356fn mint_batch_descriptions<'scope>(
1361 name: String,
1362 sink_id: GlobalId,
1363 input: SinkBatchStream<'scope>,
1364 sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
1365 connection: IcebergSinkConnection,
1366 storage_configuration: StorageConfiguration,
1367 initial_schema: SchemaRef,
1368) -> (
1369 StreamVec<'scope, Timestamp, (Antichain<Timestamp>, Antichain<Timestamp>)>,
1370 StreamVec<'scope, Timestamp, Infallible>,
1371 StreamVec<'scope, Timestamp, HealthStatusMessage>,
1372 PressOnDropButton,
1373) {
1374 let scope = input.scope();
1375 let name_for_error = name.clone();
1376 let name_for_logging = name.clone();
1377 let mut builder = OperatorBuilder::new(name, scope.clone());
1378 let sink_version = sink.version;
1379
1380 let hashed_id = sink_id.hashed();
1381 let is_active_worker = usize::cast_from(hashed_id) % scope.peers() == scope.index();
1382 let (_, table_ready_stream) = builder.new_output::<CapacityContainerBuilder<Vec<_>>>();
1383 let (batch_desc_output, batch_desc_stream) =
1384 builder.new_output::<CapacityContainerBuilder<Vec<_>>>();
1385 let mut input = builder.new_input_for(input, Pipeline, &batch_desc_output);
1386
1387 let as_of = sink.as_of.clone();
1388 let commit_interval = sink
1389 .commit_interval
1390 .expect("the planner should have enforced this")
1391 .clone();
1392
1393 let (button, errors): (_, StreamVec<'scope, Timestamp, Rc<anyhow::Error>>) =
1394 builder.build_fallible(move |caps| {
1395 Box::pin(async move {
1396 let [table_ready_capset, capset]: &mut [_; 2] = caps.try_into().unwrap();
1397
1398 if !is_active_worker {
1399 return Ok(());
1401 }
1402
1403 fail::fail_point!("iceberg_sink_creation_error", |_| Err(anyhow::anyhow!(
1404 "synthetic error"
1405 )));
1406
1407 let table_ident = TableIdent::new(
1408 NamespaceIdent::new(connection.namespace.clone()),
1409 connection.table.clone(),
1410 );
1411 let catalog = connection
1412 .catalog_connection
1413 .connect(&storage_configuration, InTask::Yes, Some(&table_ident))
1414 .await
1415 .with_context(|| {
1416 format!(
1417 "Failed to connect to Iceberg catalog '{}' for table '{}.{}'",
1418 connection.catalog_connection.uri, connection.namespace, connection.table
1419 )
1420 })?;
1421
1422 let table = load_or_create_table(
1423 catalog.as_ref(),
1424 connection.namespace.clone(),
1425 connection.table.clone(),
1426 initial_schema.as_ref(),
1427 )
1428 .await?;
1429 debug!(
1430 ?sink_id,
1431 %name_for_logging,
1432 namespace = %connection.namespace,
1433 table = %connection.table,
1434 "iceberg mint loaded/created table"
1435 );
1436
1437 *table_ready_capset = CapabilitySet::new();
1438
1439 let mut snapshots: Vec<_> = table.metadata().snapshots().cloned().collect();
1440 let resume = retrieve_upper_from_snapshots(&mut snapshots)?;
1441 let (resume_upper, resume_version) = match resume {
1442 Some((f, _, v)) => (f, v),
1443 None => (Antichain::from_elem(Timestamp::minimum()), 0),
1444 };
1445 debug!(
1446 ?sink_id,
1447 %name_for_logging,
1448 resume_upper = %resume_upper.pretty(),
1449 resume_version,
1450 as_of = %as_of.pretty(),
1451 "iceberg mint resume position loaded"
1452 );
1453
1454 let overcompacted =
1456 *resume_upper != [Timestamp::minimum()] &&
1458 PartialOrder::less_than(&resume_upper, &as_of);
1460
1461 if overcompacted {
1462 let err = super::overcompacted_error(
1465 &name_for_error,
1466 &as_of,
1467 &resume_upper,
1468 "drop the Iceberg table and recreate the sink",
1469 );
1470 return Err(StallingError::Overcompacted(err).into());
1471 };
1472
1473 if resume_version > sink_version {
1474 return Err(StallingError::FencedAtStartup {
1475 resume_version,
1476 sink_version,
1477 }
1478 .into());
1479 }
1480
1481 let mut initialized = false;
1482 let mut observed_frontier;
1483 let mut minted_batches = VecDeque::new();
1488
1489 let catchup_start = if *resume_upper == [Timestamp::minimum()] {
1492 let batch_upper = Antichain::from_elem(
1494 as_of.as_option().expect("as_of not empty").step_forward());
1495 let batch = (as_of.clone(), batch_upper.clone());
1496 minted_batches.push_back(batch.clone());
1497 batch_desc_output.give(&capset[0], batch);
1498 capset.downgrade(batch_upper.clone());
1499
1500 batch_upper
1502 } else {
1503 resume_upper.clone()
1505 };
1506
1507 loop {
1508 if let Some(event) = input.next().await {
1509 match event {
1510 Event::Data(_, _) => continue,
1511 Event::Progress(frontier) => {
1512 observed_frontier = frontier;
1513 }
1514 }
1515 } else {
1516 return Ok(());
1517 }
1518
1519 if !initialized {
1520 if observed_frontier.is_empty() {
1521 if catchup_start.is_empty() {
1528 return Ok(());
1531 }
1532 debug!(
1533 ?sink_id,
1534 %name_for_logging,
1535 batch_lower = %catchup_start.pretty(),
1536 "iceberg mint input closed before initialization; minting final batch"
1537 );
1538 let batch = (catchup_start.clone(), Antichain::new());
1539 batch_desc_output.give(&capset[0], batch);
1540 return Ok(());
1541 }
1542
1543 if !PartialOrder::less_than(&catchup_start, &observed_frontier)
1546 {
1547 continue;
1548 }
1549
1550 let mut batch_descriptions = vec![];
1551 let mut current_upper = observed_frontier.clone();
1552 let current_upper_ts = observed_frontier.as_option().expect("frontier not empty").clone();
1553 debug!(
1554 ?sink_id,
1555 %name_for_logging,
1556 batch_lower = %catchup_start.pretty(),
1557 current_upper = %current_upper.pretty(),
1558 "iceberg mint initializing (catch-up batch)"
1559 );
1560 debug!(
1561 "{}: creating catch-up batch [{}, {})",
1562 name_for_logging,
1563 catchup_start.pretty(),
1564 current_upper.pretty()
1565 );
1566 batch_descriptions.push((catchup_start.clone(), current_upper.clone()));
1567
1568 for i in 1..INITIAL_DESCRIPTIONS_TO_MINT {
1570 let duration_millis = commit_interval.as_millis()
1571 .checked_mul(u128::from(i))
1572 .expect("commit interval multiplication overflow");
1573 let duration_ts = Timestamp::new(
1574 u64::try_from(duration_millis)
1575 .expect("commit interval too large for u64"),
1576 );
1577 let desired_batch_upper = Antichain::from_elem(
1578 current_upper_ts.step_forward_by(&duration_ts),
1579 );
1580
1581 let batch_description =
1582 (current_upper.clone(), desired_batch_upper.clone());
1583 debug!(
1584 "{}: minting future batch {}/{} [{}, {})",
1585 name_for_logging,
1586 i,
1587 INITIAL_DESCRIPTIONS_TO_MINT,
1588 current_upper.pretty(),
1589 desired_batch_upper.pretty()
1590 );
1591 current_upper = batch_description.1.clone();
1592 batch_descriptions.push(batch_description);
1593 }
1594
1595 minted_batches.extend(batch_descriptions.clone());
1596
1597 for desc in batch_descriptions {
1598 batch_desc_output.give(&capset[0], desc);
1599 }
1600
1601 capset.downgrade(current_upper);
1602
1603 initialized = true;
1604 } else {
1605 if observed_frontier.is_empty() {
1606 return Ok(());
1608 }
1609 while let Some(oldest_desc) = minted_batches.front() {
1612 let oldest_upper = &oldest_desc.1;
1613 if !PartialOrder::less_equal(oldest_upper, &observed_frontier) {
1614 break;
1615 }
1616
1617 let newest_upper = minted_batches.back().unwrap().1.clone();
1618 let new_lower = newest_upper.clone();
1619 let duration_ts = Timestamp::new(commit_interval.as_millis()
1620 .try_into()
1621 .expect("commit interval too large for u64"));
1622 let new_upper = Antichain::from_elem(newest_upper
1623 .as_option()
1624 .unwrap()
1625 .step_forward_by(&duration_ts));
1626
1627 let new_batch_description = (new_lower.clone(), new_upper.clone());
1628 minted_batches.pop_front();
1629 minted_batches.push_back(new_batch_description.clone());
1630
1631 batch_desc_output.give(&capset[0], new_batch_description);
1632
1633 capset.downgrade(new_upper);
1634 }
1635 }
1636 }
1637 })
1638 });
1639
1640 let statuses = errors.map(|error| error_status(&error));
1641 (
1642 batch_desc_stream,
1643 table_ready_stream,
1644 statuses,
1645 button.press_on_drop(),
1646 )
1647}
1648
1649#[derive(Clone, Debug, Serialize, Deserialize)]
1650#[serde(try_from = "AvroDataFile", into = "AvroDataFile")]
1651struct SerializableDataFile {
1652 pub data_file: DataFile,
1653 pub schema: Schema,
1654}
1655
1656#[derive(Clone, Debug, Serialize, Deserialize)]
1664struct AvroDataFile {
1665 pub data_file: Vec<u8>,
1666 pub schema: Vec<u8>,
1668}
1669
1670impl From<SerializableDataFile> for AvroDataFile {
1671 fn from(value: SerializableDataFile) -> Self {
1672 let mut data_file = Vec::new();
1673 write_data_files_to_avro(
1674 &mut data_file,
1675 [value.data_file],
1676 &StructType::new(vec![]),
1677 FormatVersion::V2,
1678 )
1679 .expect("serialization into buffer");
1680 let schema = serde_json::to_vec(&value.schema).expect("schema serialization");
1681 AvroDataFile { data_file, schema }
1682 }
1683}
1684
1685impl TryFrom<AvroDataFile> for SerializableDataFile {
1686 type Error = String;
1687
1688 fn try_from(value: AvroDataFile) -> Result<Self, Self::Error> {
1689 let schema: Schema = serde_json::from_slice(&value.schema)
1690 .map_err(|e| format!("Failed to deserialize schema: {}", e))?;
1691 let data_files = read_data_files_from_avro(
1692 &mut &*value.data_file,
1693 &schema,
1694 0,
1695 &StructType::new(vec![]),
1696 FormatVersion::V2,
1697 )
1698 .map_err_to_string_with_causes()?;
1699 let Some(data_file) = data_files.into_iter().next() else {
1700 return Err("No DataFile found in Avro data".into());
1701 };
1702 Ok(SerializableDataFile { data_file, schema })
1703 }
1704}
1705
1706#[derive(Clone, Debug, Serialize, Deserialize)]
1708struct BoundedDataFile {
1709 pub data_file: SerializableDataFile,
1710 pub batch_desc: (Antichain<Timestamp>, Antichain<Timestamp>),
1711}
1712
1713impl BoundedDataFile {
1714 pub fn new(
1715 file: DataFile,
1716 schema: Schema,
1717 batch_desc: (Antichain<Timestamp>, Antichain<Timestamp>),
1718 ) -> Self {
1719 Self {
1720 data_file: SerializableDataFile {
1721 data_file: file,
1722 schema,
1723 },
1724 batch_desc,
1725 }
1726 }
1727
1728 pub fn batch_desc(&self) -> &(Antichain<Timestamp>, Antichain<Timestamp>) {
1729 &self.batch_desc
1730 }
1731
1732 pub fn data_file(&self) -> &DataFile {
1733 &self.data_file.data_file
1734 }
1735
1736 pub fn into_data_file(self) -> DataFile {
1737 self.data_file.data_file
1738 }
1739}
1740
1741#[derive(Clone, Debug, Default)]
1743struct BoundedDataFileSet {
1744 pub data_files: Vec<BoundedDataFile>,
1745}
1746
1747fn data_file_location(configured_path: Option<&str>, location: &str) -> String {
1757 if let Some(path) = configured_path {
1764 return path.trim_end_matches('/').to_string();
1765 }
1766
1767 let corrected_location = match location.rsplit_once("/metadata/") {
1771 Some((a, b)) if b.ends_with(".metadata.json") => a,
1772 _ => location,
1773 };
1774 format!("{}/data", corrected_location.trim_end_matches('/'))
1777}
1778
1779fn write_data_files<'scope, H: EnvelopeHandler + 'static>(
1785 name: String,
1786 input: SinkBatchStream<'scope>,
1787 batch_desc_input: StreamVec<'scope, Timestamp, (Antichain<Timestamp>, Antichain<Timestamp>)>,
1788 table_ready_stream: StreamVec<'scope, Timestamp, Infallible>,
1789 sink_id: GlobalId,
1790 from_id: GlobalId,
1791 key_is_synthetic: bool,
1792 as_of: Antichain<Timestamp>,
1793 connection: IcebergSinkConnection,
1794 storage_configuration: StorageConfiguration,
1795 materialize_arrow_schema: Arc<ArrowSchema>,
1796 metrics: Arc<IcebergSinkMetrics>,
1797 statistics: SinkStatistics,
1798) -> (
1799 StreamVec<'scope, Timestamp, BoundedDataFile>,
1800 StreamVec<'scope, Timestamp, HealthStatusMessage>,
1801 PressOnDropButton,
1802) {
1803 let scope = input.scope();
1804 let name_for_logging = name.clone();
1805 let mut builder = OperatorBuilder::new(name, scope.clone());
1806
1807 let (output, output_stream) = builder.new_output::<CapacityContainerBuilder<_>>();
1808
1809 let mut table_ready_input = builder.new_disconnected_input(table_ready_stream, Pipeline);
1810 let mut batch_desc_input =
1811 builder.new_input_for(batch_desc_input.broadcast(), Pipeline, &output);
1812 let mut input = builder.new_disconnected_input(input, Pipeline);
1813
1814 let (button, errors): (_, StreamVec<'scope, Timestamp, Rc<anyhow::Error>>) = builder
1815 .build_fallible(move |caps| {
1816 Box::pin(async move {
1817 let [capset]: &mut [_; 1] = caps.try_into().unwrap();
1818 let namespace_ident = NamespaceIdent::new(connection.namespace.clone());
1819 let table_ident = TableIdent::new(namespace_ident, connection.table.clone());
1820 let catalog = connection
1821 .catalog_connection
1822 .connect(&storage_configuration, InTask::Yes, Some(&table_ident))
1823 .await
1824 .with_context(|| {
1825 format!(
1826 "Failed to connect to Iceberg catalog '{}' for table '{}.{}'",
1827 connection.catalog_connection.uri,
1828 connection.namespace,
1829 connection.table
1830 )
1831 })?;
1832
1833 while let Some(_) = table_ready_input.next().await {
1834 }
1836 let table = catalog.load_table(&table_ident).await.with_context(|| {
1837 format!(
1838 "Failed to load Iceberg table '{}.{}' in write_data_files operator",
1839 connection.namespace, connection.table
1840 )
1841 })?;
1842
1843 let table_metadata = table.metadata().clone();
1844 let current_schema = Arc::clone(table_metadata.current_schema());
1845
1846 let arrow_schema = Arc::new(
1850 merge_materialize_metadata_into_iceberg_schema(
1851 materialize_arrow_schema.as_ref(),
1852 current_schema.as_ref(),
1853 )
1854 .context("Failed to merge Materialize metadata into Iceberg schema")
1855 .map_err(StallingError::InvalidSchema)?,
1856 );
1857
1858 let properties = table_metadata.properties();
1868 let configured_path = properties
1869 .get("write.data.path")
1870 .or_else(|| properties.get("write.folder-storage.path"));
1871 let data_location = data_file_location(
1872 configured_path.map(String::as_str),
1873 table_metadata.location(),
1874 );
1875 debug!(%data_location, "iceberg sink data file location");
1876 let location_generator =
1877 DefaultLocationGenerator::with_data_location(data_location);
1878
1879 let unique_suffix = format!("-{}", uuid::Uuid::new_v4());
1881 let file_name_generator = DefaultFileNameGenerator::new(
1882 PARQUET_FILE_PREFIX.to_string(),
1883 Some(unique_suffix),
1884 iceberg::spec::DataFileFormat::Parquet,
1885 );
1886
1887 let file_io = table.file_io().clone();
1888
1889 let writer_properties = WriterProperties::new();
1890
1891 let ctx = WriterContext {
1892 arrow_schema,
1893 current_schema: Arc::clone(¤t_schema),
1894 file_io,
1895 location_generator,
1896 file_name_generator,
1897 writer_properties,
1898 };
1899 let handler = H::new(ctx, &connection, &materialize_arrow_schema)?;
1900 let mut pk_warner =
1901 (!key_is_synthetic).then(|| PkViolationWarner::new(sink_id, from_id));
1902
1903 let mut stashed_rows: VecDeque<Span<Timestamp, ArcBatch<OrdValBatch<_>>>> =
1907 VecDeque::new();
1908
1909 let mut in_flight_batches: VecDeque<(
1913 (Antichain<Timestamp>, Antichain<Timestamp>),
1914 Box<dyn IcebergWriter>,
1915 )> = VecDeque::new();
1916
1917 let mut last_batch_desc: Option<BatchDescription> = None;
1921 let mut last_input_bounds: Option<(Antichain<Timestamp>, Antichain<Timestamp>)> =
1922 None;
1923
1924 let mut batch_description_frontier = Antichain::from_elem(Timestamp::minimum());
1925 let mut input_frontier = Antichain::from_elem(Timestamp::minimum());
1926
1927 while !(batch_description_frontier.is_empty() && input_frontier.is_empty()) {
1928 tokio::select! {
1929 _ = batch_desc_input.ready() => {},
1930 _ = input.ready() => {}
1931 }
1932
1933 while let Some(event) = batch_desc_input.next_sync() {
1937 match event {
1938 Event::Data(_cap, data) => {
1939 for batch_desc in data {
1940 let (lower, upper) = &batch_desc;
1941
1942 if let Some((prev_lower, prev_upper)) = last_batch_desc.as_ref()
1943 {
1944 if prev_upper != lower {
1945 anyhow::bail!(
1946 "batch descriptions must arrive in order, non-overlapping, \
1947 and without gaps: previous [{}, {}), new [{}, {})",
1948 prev_lower.pretty(),
1949 prev_upper.pretty(),
1950 lower.pretty(),
1951 upper.pretty(),
1952 );
1953 }
1954 }
1955 last_batch_desc = Some(batch_desc.clone());
1956
1957 let is_snapshot = lower == &as_of;
1959 debug!(
1960 "{}: received batch description [{}, {}), snapshot={}",
1961 name_for_logging,
1962 lower.pretty(),
1963 upper.pretty(),
1964 is_snapshot
1965 );
1966 let batch_writer = handler.create_writer(is_snapshot).await?;
1967 in_flight_batches.push_back((batch_desc.clone(), batch_writer));
1968 }
1969 }
1970 Event::Progress(frontier) => {
1971 batch_description_frontier = frontier;
1972 }
1973 }
1974 }
1975
1976 while let Some(event) = input.next_sync() {
1978 match event {
1979 Event::Data(_cap, data) => {
1980 for rows in &data {
1981 if let Some((prev_lower, prev_upper)) =
1982 last_input_bounds.as_ref()
1983 {
1984 if !PartialOrder::less_equal(prev_upper, rows.lower()) {
1988 anyhow::bail!(
1989 "input batches must arrive in order and \
1990 non-overlapping: previous [{}, {}), new [{}, {})",
1991 prev_lower.pretty(),
1992 prev_upper.pretty(),
1993 rows.lower().pretty(),
1994 rows.upper().pretty(),
1995 );
1996 }
1997 }
1998 last_input_bounds =
1999 Some((rows.lower().clone(), rows.upper().clone()));
2000
2001 stashed_rows.push_back(rows.clone());
2002 }
2003 }
2004 Event::Progress(frontier) => {
2005 input_frontier = frontier;
2006 }
2007 }
2008 }
2009
2010 metrics.stashed_rows.set(u64::cast_from(
2011 stashed_rows
2012 .iter()
2013 .map(|rows| rows.inner.as_ref().map_or(0, |b| b.len()))
2014 .sum::<usize>(),
2015 ));
2016
2017 let mut staged_messages_since_flush: u64 = 0;
2022
2023 let write_rows = async |rows: &Span<Timestamp, ArcBatch<OrdValBatch<_>>>,
2025 (lower, upper): BatchDescription,
2026 batch_writer: &mut Box<dyn IcebergWriter>|
2027 -> Result<(), anyhow::Error> {
2028 let Some(rows) = &rows.inner else {
2030 return Ok(());
2031 };
2032 for_each_diff_pair_async(
2033 rows,
2034 Some(lower),
2035 Some(upper),
2036 async |key, time, diff_pair| -> Result<(), anyhow::Error> {
2037 if let Some(warner) = pk_warner.as_mut() {
2038 warner.observe(key, time);
2039 }
2040
2041 let record_batch = handler
2042 .row_to_batch(diff_pair, time)
2043 .context("failed to convert row to recordbatch")?;
2044 staged_messages_since_flush +=
2045 u64::cast_from(record_batch.num_rows());
2046 batch_writer
2047 .write(record_batch)
2048 .await
2049 .context("failed to write recordbatch")?;
2050 if staged_messages_since_flush >= 10_000 {
2051 statistics.inc_messages_staged_by(staged_messages_since_flush);
2052 staged_messages_since_flush = 0;
2053 }
2054 Ok(())
2055 },
2056 )
2057 .await?;
2058 if let Some(warner) = pk_warner.as_mut() {
2062 warner.flush();
2063 }
2064 Ok(())
2065 };
2066
2067 let close_batch = async |batch_desc: BatchDescription,
2069 batch_writer: &mut Box<dyn IcebergWriter>|
2070 -> Result<(), anyhow::Error> {
2071 let close_started_at = Instant::now();
2072 let data_files = batch_writer.close().await;
2073 metrics
2074 .writer_close_duration_seconds
2075 .observe(close_started_at.elapsed().as_secs_f64());
2076 let data_files = data_files.context("Failed to close batch writer")?;
2077 debug!(
2078 "{}: closed batch [{}, {}), wrote {} files",
2079 name_for_logging,
2080 batch_desc.0.pretty(),
2081 batch_desc.1.pretty(),
2082 data_files.len()
2083 );
2084 for data_file in data_files {
2085 match data_file.content_type() {
2086 iceberg::spec::DataContentType::Data => {
2087 metrics.data_files_written.inc();
2088 }
2089 iceberg::spec::DataContentType::PositionDeletes
2090 | iceberg::spec::DataContentType::EqualityDeletes => {
2091 metrics.delete_files_written.inc();
2092 }
2093 }
2094 statistics.inc_bytes_staged_by(data_file.file_size_in_bytes());
2095 let file = BoundedDataFile::new(
2096 data_file,
2097 current_schema.as_ref().clone(),
2098 batch_desc.clone(),
2099 );
2100 output.give(&capset[0], file);
2101 }
2102
2103 capset.downgrade(batch_desc.1.clone());
2106 Ok(())
2107 };
2108
2109 with_ready_batches(
2111 input_frontier.clone(),
2112 &mut stashed_rows,
2113 batch_description_frontier.clone(),
2114 &mut in_flight_batches,
2115 write_rows,
2116 close_batch,
2117 )
2118 .await?;
2119
2120 if staged_messages_since_flush > 0 {
2121 statistics.inc_messages_staged_by(staged_messages_since_flush);
2122 }
2123 metrics.stashed_rows.set(u64::cast_from(
2124 stashed_rows
2125 .iter()
2126 .map(|rows| rows.inner.as_ref().map_or(0, |b| b.len()))
2127 .sum::<usize>(),
2128 ));
2129 }
2130 Ok(())
2131 })
2132 });
2133
2134 let statuses = errors.map(|error| error_status(&error));
2135 (output_stream, statuses, button.press_on_drop())
2136}
2137
2138type BatchDescription = (Antichain<Timestamp>, Antichain<Timestamp>);
2140
2141async fn with_ready_batches<L: Layout, W, Write, Close>(
2153 input_frontier: Antichain<Timestamp>,
2154 input_batches: &mut VecDeque<Span<Timestamp, ArcBatch<OrdValBatch<L>>>>,
2155 output_frontier: Antichain<Timestamp>,
2156 output_batches: &mut VecDeque<(BatchDescription, W)>,
2157 mut write_rows: Write,
2158 mut close_batch: Close,
2159) -> Result<(), anyhow::Error>
2160where
2161 L::TimeContainer: BatchContainer<Owned = Timestamp>,
2162 Write: AsyncFnMut(
2163 &Span<Timestamp, ArcBatch<OrdValBatch<L>>>,
2164 BatchDescription,
2165 &mut W,
2166 ) -> Result<(), anyhow::Error>,
2167 Close: AsyncFnMut(BatchDescription, &mut W) -> Result<(), anyhow::Error>,
2168{
2169 loop {
2170 {
2171 let output_lower = output_batches
2174 .front()
2175 .map_or(&output_frontier, |((lower, _), _)| lower);
2176 while input_batches
2177 .pop_front_if(|rows| PartialOrder::less_equal(rows.upper(), output_lower))
2178 .is_some()
2179 {}
2180 }
2181
2182 {
2183 let input_lower = input_batches
2186 .front()
2187 .map_or(&input_frontier, |rows| rows.lower());
2188 while let Some((batch_desc, mut batch_writer)) =
2189 output_batches.pop_front_if(|((_, batch_upper), _)| {
2190 PartialOrder::less_equal(batch_upper, input_lower)
2191 })
2192 {
2193 close_batch(batch_desc, &mut batch_writer).await?;
2194 }
2195 }
2196
2197 let Some((batch_desc, batch_writer)) = output_batches.front_mut() else {
2198 break;
2200 };
2201
2202 let Some(rows) = input_batches.front() else {
2203 break;
2205 };
2206
2207 write_rows(rows, batch_desc.clone(), batch_writer).await?;
2215 let output_upper = batch_desc.1.clone();
2216 let rows_upper = rows.upper();
2217 if PartialOrder::less_equal(&output_upper, rows_upper) {
2218 let (batch_desc, mut batch_writer) =
2220 output_batches.pop_front().expect("already checked front");
2221 close_batch(batch_desc, &mut batch_writer).await?;
2222 }
2223 if PartialOrder::less_equal(rows_upper, &output_upper) {
2224 input_batches.pop_front();
2226 }
2227
2228 }
2232
2233 Ok(())
2234}
2235
2236#[cfg(test)]
2237mod tests {
2238 use iceberg::spec::{ListType, MapType, PrimitiveType, Type};
2239 use iceberg::writer::file_writer::location_generator::LocationGenerator;
2240 use mz_repr::SqlScalarType;
2241 use mz_storage_types::sinks::ICEBERG_UINT64_DECIMAL_PRECISION;
2242
2243 use super::*;
2244
2245 #[mz_ore::test]
2246 fn error_status_suspends_only_stalling_errors() {
2247 use crate::healthcheck::StallAction;
2248
2249 let wrapped = Err::<(), anyhow::Error>(StallingError::MissingKey.into())
2250 .context("failed to commit batch")
2251 .unwrap_err();
2252 assert_eq!(
2253 error_status(&wrapped).update.stall_action(),
2254 StallAction::Suspend
2255 );
2256 assert_eq!(
2257 error_status(&anyhow!("catalog unreachable"))
2258 .update
2259 .stall_action(),
2260 StallAction::Restart
2261 );
2262 }
2263
2264 fn manifest_uri(configured_path: Option<&str>, location: &str) -> String {
2266 let data_location = data_file_location(configured_path, location);
2267 DefaultLocationGenerator::with_data_location(data_location)
2268 .generate_location(None, "part-00000.parquet")
2269 }
2270
2271 fn assert_addresses_one_object(uri: &str) {
2275 let path = uri
2276 .split_once("://")
2277 .map(|(_scheme, path)| path)
2278 .unwrap_or(uri);
2279 assert!(
2280 !path.contains("//"),
2281 "URI has an empty path segment, so it does not name the object written: {uri}"
2282 );
2283 }
2284
2285 #[mz_ore::test]
2286 fn test_data_file_location_trims_configured_path() {
2287 assert_eq!(
2289 manifest_uri(Some("s3://bucket/tbl/data"), "s3://bucket/tbl"),
2290 "s3://bucket/tbl/data/part-00000.parquet"
2291 );
2292
2293 for configured in [
2295 "s3://bucket/tbl/data/",
2296 "s3://bucket/tbl/data//",
2297 "s3://bucket/tbl/data///",
2298 ] {
2299 let uri = manifest_uri(Some(configured), "s3://bucket/tbl");
2300 assert_addresses_one_object(&uri);
2301 assert_eq!(uri, "s3://bucket/tbl/data/part-00000.parquet");
2302 }
2303 }
2304
2305 #[mz_ore::test]
2306 fn test_data_file_location_trims_table_location() {
2307 assert_eq!(
2309 manifest_uri(None, "s3://bucket/tbl"),
2310 "s3://bucket/tbl/data/part-00000.parquet"
2311 );
2312
2313 let uri = manifest_uri(None, "s3://bucket/tbl/");
2316 assert_addresses_one_object(&uri);
2317 assert_eq!(uri, "s3://bucket/tbl/data/part-00000.parquet");
2318 }
2319
2320 #[mz_ore::test]
2321 fn test_data_file_location_corrects_s3_tables_metadata_path() {
2322 assert_eq!(
2325 data_file_location(None, "s3://bucket/tbl/metadata/00001-abc.metadata.json"),
2326 "s3://bucket/tbl/data"
2327 );
2328
2329 assert_eq!(
2331 data_file_location(None, "s3://bucket/metadata/tbl"),
2332 "s3://bucket/metadata/tbl/data"
2333 );
2334 }
2335
2336 #[mz_ore::test]
2337 fn test_iceberg_type_overrides() {
2338 let result = iceberg_type_overrides(&SqlScalarType::UInt16);
2340 assert_eq!(result.unwrap().0, DataType::Int32);
2341
2342 let result = iceberg_type_overrides(&SqlScalarType::UInt32);
2344 assert_eq!(result.unwrap().0, DataType::Int64);
2345
2346 let result = iceberg_type_overrides(&SqlScalarType::UInt64);
2348 assert_eq!(
2349 result.unwrap().0,
2350 DataType::Decimal128(ICEBERG_UINT64_DECIMAL_PRECISION, 0)
2351 );
2352
2353 let result = iceberg_type_overrides(&SqlScalarType::MzTimestamp);
2355 assert_eq!(
2356 result.unwrap().0,
2357 DataType::Decimal128(ICEBERG_UINT64_DECIMAL_PRECISION, 0)
2358 );
2359
2360 let result = iceberg_type_overrides(&SqlScalarType::Interval);
2362 assert_eq!(result.unwrap().0, DataType::LargeUtf8);
2363
2364 let result = iceberg_type_overrides(&SqlScalarType::Uuid);
2366 assert_eq!(result.unwrap().0, DataType::Utf8);
2367
2368 assert!(iceberg_type_overrides(&SqlScalarType::Int32).is_none());
2370 assert!(iceberg_type_overrides(&SqlScalarType::String).is_none());
2371 assert!(iceberg_type_overrides(&SqlScalarType::Bool).is_none());
2372 }
2373
2374 #[mz_ore::test]
2375 fn test_iceberg_schema_with_nested_uint64() {
2376 let desc = mz_repr::RelationDesc::builder()
2379 .with_column(
2380 "items",
2381 SqlScalarType::List {
2382 element_type: Box::new(SqlScalarType::UInt64),
2383 custom_id: None,
2384 }
2385 .nullable(true),
2386 )
2387 .finish();
2388
2389 let schema =
2390 mz_arrow_util::builder::desc_to_schema_with_overrides(&desc, iceberg_type_overrides)
2391 .expect("schema conversion should succeed");
2392
2393 if let DataType::List(field) = schema.field(0).data_type() {
2395 assert_eq!(
2396 field.data_type(),
2397 &DataType::Decimal128(ICEBERG_UINT64_DECIMAL_PRECISION, 0)
2398 );
2399 } else {
2400 panic!("Expected List type");
2401 }
2402 }
2403
2404 #[mz_ore::test]
2405 fn test_iceberg_interval_override() {
2406 let result = iceberg_type_overrides(&SqlScalarType::Interval);
2408 assert_eq!(result.unwrap().0, DataType::LargeUtf8);
2409
2410 let desc = mz_repr::RelationDesc::builder()
2412 .with_column("id", SqlScalarType::Int32.nullable(false))
2413 .with_column("dur", SqlScalarType::Interval.nullable(true))
2414 .finish();
2415
2416 let (arrow_schema, iceberg_schema) =
2417 relation_desc_to_iceberg_schema(&desc).expect("schema conversion should succeed");
2418
2419 assert_eq!(arrow_schema.field(1).data_type(), &DataType::LargeUtf8);
2421
2422 let field = iceberg_schema
2424 .as_struct()
2425 .field_by_name("dur")
2426 .expect("field should exist");
2427 assert_eq!(*field.field_type, Type::Primitive(PrimitiveType::String));
2428 }
2429
2430 #[mz_ore::test]
2433 fn test_iceberg_uuid_override() {
2434 let result = iceberg_type_overrides(&SqlScalarType::Uuid);
2435 assert_eq!(result.unwrap().0, DataType::Utf8);
2436
2437 let desc = mz_repr::RelationDesc::builder()
2438 .with_column("id", SqlScalarType::Int32.nullable(false))
2439 .with_column("u", SqlScalarType::Uuid.nullable(true))
2440 .finish();
2441
2442 let (arrow_schema, iceberg_schema) =
2443 relation_desc_to_iceberg_schema(&desc).expect("schema conversion should succeed");
2444
2445 assert_eq!(arrow_schema.field(1).data_type(), &DataType::Utf8);
2446
2447 let field = iceberg_schema
2448 .as_struct()
2449 .field_by_name("u")
2450 .expect("field should exist");
2451 assert_eq!(*field.field_type, Type::Primitive(PrimitiveType::String));
2452 assert_ne!(
2453 *field.field_type,
2454 Type::Primitive(PrimitiveType::Fixed(16)),
2455 "uuid must not fall back to the default FixedSizeBinary(16) mapping"
2456 );
2457 }
2458
2459 fn with_field_type(schema: &Schema, name: &str, ty: Type) -> Schema {
2462 let fields = schema.as_struct().fields().iter().map(|f| {
2463 let mut field = (**f).clone();
2464 if field.name == name {
2465 field.field_type = Box::new(ty.clone());
2466 }
2467 Arc::new(field)
2468 });
2469 Schema::builder()
2470 .with_fields(fields)
2471 .build()
2472 .expect("valid schema")
2473 }
2474
2475 #[mz_ore::test]
2478 fn test_schema_mismatch_accepts_legacy_uuid() {
2479 let desc = mz_repr::RelationDesc::builder()
2480 .with_column("id", SqlScalarType::Int32.nullable(false))
2481 .with_column("u", SqlScalarType::Uuid.nullable(true))
2482 .finish();
2483 let (_, expected) =
2484 relation_desc_to_iceberg_schema(&desc).expect("schema conversion should succeed");
2485
2486 assert_eq!(schema_mismatch(&expected, &expected), None);
2487
2488 let legacy = with_field_type(&expected, "u", Type::Primitive(PrimitiveType::Fixed(16)));
2490 assert_eq!(schema_mismatch(&legacy, &expected), None);
2491
2492 assert!(schema_mismatch(&expected, &legacy).is_some());
2495
2496 let wrong_type = with_field_type(&expected, "u", Type::Primitive(PrimitiveType::Long));
2498 assert!(schema_mismatch(&wrong_type, &expected).is_some());
2499
2500 let truncated = Schema::builder()
2502 .with_fields(expected.as_struct().fields().iter().take(1).cloned())
2503 .build()
2504 .expect("valid schema");
2505 assert!(schema_mismatch(&truncated, &expected).is_some());
2506 }
2507
2508 #[mz_ore::test]
2511 fn test_schema_mismatch_accepts_legacy_uuid_in_list() {
2512 let desc = mz_repr::RelationDesc::builder()
2513 .with_column("id", SqlScalarType::Int32.nullable(false))
2514 .with_column(
2515 "us",
2516 SqlScalarType::List {
2517 element_type: Box::new(SqlScalarType::Uuid),
2518 custom_id: None,
2519 }
2520 .nullable(true),
2521 )
2522 .finish();
2523 let (_, expected) =
2524 relation_desc_to_iceberg_schema(&desc).expect("schema conversion should succeed");
2525
2526 let Type::List(list) = &*expected
2527 .as_struct()
2528 .field_by_name("us")
2529 .expect("field should exist")
2530 .field_type
2531 else {
2532 panic!("expected a list type");
2533 };
2534 let mut legacy_element = (*list.element_field).clone();
2535 legacy_element.field_type = Box::new(Type::Primitive(PrimitiveType::Fixed(16)));
2536 let legacy = with_field_type(
2537 &expected,
2538 "us",
2539 Type::List(ListType {
2540 element_field: Arc::new(legacy_element),
2541 }),
2542 );
2543
2544 assert_eq!(schema_mismatch(&legacy, &expected), None);
2545 }
2546
2547 #[allow(clippy::disallowed_methods)]
2553 #[allow(clippy::match_wildcard_for_single_variants)]
2554 fn with_catalog_field_ids(schema: &Schema) -> Schema {
2555 fn renumber_fields(fields: &[Arc<NestedField>], next: &mut i32) -> Vec<Arc<NestedField>> {
2556 let ids: Vec<i32> = fields
2557 .iter()
2558 .map(|_| {
2559 let id = *next;
2560 *next += 1;
2561 id
2562 })
2563 .collect();
2564 fields
2565 .iter()
2566 .zip(ids)
2567 .map(|(f, id)| {
2568 let mut field = (**f).clone();
2569 field.id = id;
2570 field.field_type = Box::new(renumber_type(&field.field_type, next));
2571 Arc::new(field)
2572 })
2573 .collect()
2574 }
2575 fn renumber_type(ty: &Type, next: &mut i32) -> Type {
2576 match ty {
2577 Type::Struct(s) => Type::Struct(StructType::new(renumber_fields(s.fields(), next))),
2578 Type::List(l) => {
2579 let mut element = (*l.element_field).clone();
2580 element.id = *next;
2581 *next += 1;
2582 element.field_type = Box::new(renumber_type(&element.field_type, next));
2583 Type::List(ListType {
2584 element_field: Arc::new(element),
2585 })
2586 }
2587 Type::Map(m) => {
2588 let mut key = (*m.key_field).clone();
2589 key.id = *next;
2590 *next += 1;
2591 let mut value = (*m.value_field).clone();
2592 value.id = *next;
2593 *next += 1;
2594 key.field_type = Box::new(renumber_type(&key.field_type, next));
2595 value.field_type = Box::new(renumber_type(&value.field_type, next));
2596 Type::Map(MapType::new(Arc::new(key), Arc::new(value)))
2597 }
2598 primitive => primitive.clone(),
2599 }
2600 }
2601 let mut next = 1;
2602 Schema::builder()
2603 .with_fields(renumber_fields(schema.as_struct().fields(), &mut next))
2604 .build()
2605 .expect("valid schema")
2606 }
2607
2608 fn with_array_element_type(schema: &Schema, name: &str, ty: Type) -> Schema {
2611 let fields = schema.as_struct().fields().iter().map(|f| {
2612 if f.name != name {
2613 return Arc::clone(f);
2614 }
2615 let Type::Struct(array) = &*f.field_type else {
2616 panic!("{name} should be an array struct");
2617 };
2618 let inner = array.fields().iter().map(|inner| {
2619 let mut inner = (**inner).clone();
2620 if inner.name == "items" {
2621 let Type::List(list) = &*inner.field_type else {
2622 panic!("items should be a list");
2623 };
2624 let mut element = (*list.element_field).clone();
2625 element.field_type = Box::new(ty.clone());
2626 inner.field_type = Box::new(Type::List(ListType {
2627 element_field: Arc::new(element),
2628 }));
2629 }
2630 Arc::new(inner)
2631 });
2632 let mut field = (**f).clone();
2633 field.field_type = Box::new(Type::Struct(StructType::new(inner.collect())));
2634 Arc::new(field)
2635 });
2636 Schema::builder()
2637 .with_fields(fields)
2638 .build()
2639 .expect("valid schema")
2640 }
2641
2642 fn with_field_required(schema: &Schema, name: &str, required: bool) -> Schema {
2644 let fields = schema.as_struct().fields().iter().map(|f| {
2645 let mut field = (**f).clone();
2646 if field.name == name {
2647 field.required = required;
2648 }
2649 Arc::new(field)
2650 });
2651 Schema::builder()
2652 .with_fields(fields)
2653 .build()
2654 .expect("valid schema")
2655 }
2656
2657 #[mz_ore::test]
2667 fn test_schema_mismatch_accepts_catalog_assigned_field_ids() {
2668 let desc = mz_repr::RelationDesc::builder()
2669 .with_column("id", SqlScalarType::Int64.nullable(true))
2670 .with_column(
2671 "a",
2672 SqlScalarType::Array(Box::new(SqlScalarType::Int64)).nullable(true),
2673 )
2674 .with_column("w", SqlScalarType::Int64.nullable(true))
2675 .finish();
2676 let arrow_schema =
2677 mz_arrow_util::builder::desc_to_schema_with_overrides(&desc, iceberg_type_overrides)
2678 .expect("schema conversion should succeed");
2679
2680 let arrow_schema_with_ids = add_field_ids_to_arrow_schema(arrow_schema);
2681 let expected = arrow_schema_to_schema(&arrow_schema_with_ids)
2682 .expect("schema conversion should succeed");
2683 let catalog = with_catalog_field_ids(&expected);
2684
2685 let id_of = |schema: &Schema, name: &str| {
2687 schema
2688 .field_by_name(name)
2689 .unwrap_or_else(|| panic!("field {name} should exist"))
2690 .id
2691 };
2692 assert_eq!(id_of(&catalog, "id"), id_of(&expected, "id"));
2693 assert_ne!(id_of(&catalog, "a.items"), id_of(&expected, "a.items"));
2694 assert_ne!(id_of(&catalog, "w"), id_of(&expected, "w"));
2695
2696 let wrong_type = with_field_type(&catalog, "w", Type::Primitive(PrimitiveType::String));
2698 assert!(schema_mismatch(&wrong_type, &expected).is_some());
2699 let wrong_element =
2701 with_array_element_type(&catalog, "a", Type::Primitive(PrimitiveType::String));
2702 assert!(schema_mismatch(&wrong_element, &expected).is_some());
2703 let wrong_required = with_field_required(&catalog, "w", true);
2705 assert!(schema_mismatch(&wrong_required, &expected).is_some());
2706
2707 let flat = mz_repr::RelationDesc::builder()
2710 .with_column("id", SqlScalarType::Int64.nullable(true))
2711 .with_column("w", SqlScalarType::Int64.nullable(true))
2712 .finish();
2713 let (_, flat_expected) =
2714 relation_desc_to_iceberg_schema(&flat).expect("schema conversion should succeed");
2715 assert_eq!(
2716 schema_mismatch(&with_catalog_field_ids(&flat_expected), &flat_expected),
2717 None
2718 );
2719
2720 assert_eq!(
2723 schema_mismatch(&catalog, &expected),
2724 None,
2725 "a table that differs from the expected schema only in field ids must be accepted"
2726 );
2727 }
2728
2729 #[mz_ore::test]
2730 fn test_schema_mismatch_names_the_first_differing_field() {
2731 let desc = mz_repr::RelationDesc::builder()
2732 .with_column("id", SqlScalarType::Int64.nullable(true))
2733 .with_column(
2734 "a",
2735 SqlScalarType::Array(Box::new(SqlScalarType::Int64)).nullable(true),
2736 )
2737 .with_column("w", SqlScalarType::Int64.nullable(true))
2738 .finish();
2739 let (_, expected) =
2740 relation_desc_to_iceberg_schema(&desc).expect("schema conversion should succeed");
2741
2742 let wrong_type = with_field_type(&expected, "w", Type::Primitive(PrimitiveType::String));
2743 assert_eq!(
2744 schema_mismatch(&wrong_type, &expected).as_deref(),
2745 Some("`w` has type string in the table but long in the sink")
2746 );
2747
2748 let wrong_element =
2749 with_array_element_type(&expected, "a", Type::Primitive(PrimitiveType::String));
2750 let mismatch = schema_mismatch(&wrong_element, &expected).expect("schemas differ");
2751 assert!(
2752 mismatch.starts_with("`a.")
2753 && mismatch.ends_with("has type string in the table but long in the sink"),
2754 "nested mismatch should name the path into the array: {mismatch}"
2755 );
2756
2757 let wrong_required = with_field_required(&expected, "w", true);
2758 assert_eq!(
2759 schema_mismatch(&wrong_required, &expected).as_deref(),
2760 Some("`w` is required in the table but optional in the sink")
2761 );
2762
2763 let truncated = Schema::builder()
2764 .with_fields(expected.as_struct().fields().iter().take(1).cloned())
2765 .build()
2766 .expect("valid schema");
2767 assert_eq!(
2768 schema_mismatch(&truncated, &expected).as_deref(),
2769 Some("the table is missing `a`")
2770 );
2771 assert_eq!(
2772 schema_mismatch(&expected, &truncated).as_deref(),
2773 Some("the table has an extra field `a`")
2774 );
2775
2776 let mut wide = mz_repr::RelationDesc::builder();
2779 for i in 0..500 {
2780 wide = wide.with_column(format!("column_{i}"), SqlScalarType::Int64.nullable(true));
2781 }
2782 let (_, wide_expected) = relation_desc_to_iceberg_schema(&wide.finish())
2783 .expect("schema conversion should succeed");
2784 let wide_current = with_field_type(
2785 &wide_expected,
2786 "column_499",
2787 Type::Primitive(PrimitiveType::String),
2788 );
2789 assert_eq!(
2790 schema_mismatch(&wide_current, &wide_expected).as_deref(),
2791 Some("`column_499` has type string in the table but long in the sink")
2792 );
2793 }
2794
2795 #[mz_ore::test]
2796 fn test_schema_mismatch_names_an_added_or_removed_field() {
2797 let schema = |columns: &[&str]| {
2798 let mut desc = mz_repr::RelationDesc::builder();
2799 for column in columns {
2800 desc = desc.with_column(*column, SqlScalarType::String.nullable(true));
2801 }
2802 let (_, schema) = relation_desc_to_iceberg_schema(&desc.finish())
2803 .expect("schema conversion should succeed");
2804 schema
2805 };
2806 let before = schema(&["name", "address"]);
2807 let after = schema(&["id", "name", "address"]);
2808
2809 assert_eq!(
2810 schema_mismatch(&before, &after).as_deref(),
2811 Some("the table is missing `id`")
2812 );
2813 assert_eq!(
2814 schema_mismatch(&after, &before).as_deref(),
2815 Some("the table has an extra field `id`")
2816 );
2817 assert_eq!(
2818 schema_mismatch(&schema(&["address", "name"]), &before).as_deref(),
2819 Some("the table has `address` where `name` is expected")
2820 );
2821 }
2822
2823 #[mz_ore::test]
2824 fn test_iceberg_range_schema() {
2825 let desc = mz_repr::RelationDesc::builder()
2827 .with_column("id", SqlScalarType::Int32.nullable(false))
2828 .with_column(
2829 "r",
2830 SqlScalarType::Range {
2831 element_type: Box::new(SqlScalarType::Int32),
2832 }
2833 .nullable(true),
2834 )
2835 .finish();
2836
2837 let (_arrow_schema, iceberg_schema) =
2838 relation_desc_to_iceberg_schema(&desc).expect("schema conversion should succeed");
2839
2840 let field = iceberg_schema
2842 .as_struct()
2843 .field_by_name("r")
2844 .expect("field should exist");
2845 assert!(
2846 matches!(&*field.field_type, Type::Struct(_)),
2847 "range should be struct, got: {:?}",
2848 field.field_type
2849 );
2850 }
2851
2852 #[mz_ore::test]
2853 fn equality_ids_follow_iceberg_field_ids() {
2854 let map_entries = Field::new(
2855 "entries",
2856 DataType::Struct(
2857 vec![
2858 Field::new("key", DataType::Utf8, false),
2859 Field::new("value", DataType::Utf8, true),
2860 ]
2861 .into(),
2862 ),
2863 false,
2864 );
2865 let materialize_arrow_schema = ArrowSchema::new(vec![
2866 Field::new("attrs", DataType::Map(Arc::new(map_entries), false), true),
2867 Field::new("key_col", DataType::Int32, false),
2868 ]);
2869 let materialize_arrow_schema = add_field_ids_to_arrow_schema(materialize_arrow_schema);
2870 let iceberg_schema = arrow_schema_to_schema(&materialize_arrow_schema)
2871 .expect("schema conversion should succeed");
2872
2873 let equality_ids =
2874 equality_ids_for_indices(&iceberg_schema, &materialize_arrow_schema, &[1])
2875 .expect("field lookup should succeed");
2876
2877 let expected_id = iceberg_schema
2878 .as_struct()
2879 .field_by_name("key_col")
2880 .expect("top-level field should exist")
2881 .id;
2882 assert_eq!(equality_ids, vec![expected_id]);
2883 assert_ne!(expected_id, 2);
2884 }
2885
2886 #[mz_ore::test]
2891 #[allow(clippy::disallowed_types)]
2892 fn merge_map_entries_preserves_value_extension_metadata() {
2893 use std::collections::HashMap;
2894
2895 let mz_value_metadata = HashMap::from([(
2896 ARROW_EXTENSION_NAME_KEY.to_string(),
2897 "materialize.v1.string".to_string(),
2898 )]);
2899 let mz_entries = Field::new(
2900 "entries",
2901 DataType::Struct(
2902 vec![
2903 Field::new("keys", DataType::Utf8, false),
2904 Field::new("values", DataType::Utf8, true).with_metadata(mz_value_metadata),
2905 ]
2906 .into(),
2907 ),
2908 false,
2909 );
2910 let mz_map = Field::new("m", DataType::Map(Arc::new(mz_entries), false), true)
2911 .with_metadata(HashMap::from([(
2912 ARROW_EXTENSION_NAME_KEY.to_string(),
2913 "materialize.v1.map".to_string(),
2914 )]));
2915
2916 let iceberg_entries = Field::new(
2917 "key_value",
2918 DataType::Struct(
2919 vec![
2920 Field::new("key", DataType::Utf8, false),
2921 Field::new("value", DataType::Utf8, true),
2922 ]
2923 .into(),
2924 ),
2925 false,
2926 );
2927 let iceberg_map = Field::new("m", DataType::Map(Arc::new(iceberg_entries), false), true);
2928
2929 let merged = merge_field_metadata_recursive(&iceberg_map, Some(&mz_map))
2930 .expect("merge should succeed");
2931
2932 let entries = match merged.data_type() {
2933 DataType::Map(entries, _) => entries.as_ref(),
2934 other => panic!("expected Map, got {other:?}"),
2935 };
2936 let entry_fields = match entries.data_type() {
2937 DataType::Struct(fields) => fields,
2938 other => panic!("expected Struct, got {other:?}"),
2939 };
2940 assert_eq!(entry_fields[0].name(), "key");
2942 assert_eq!(entry_fields[1].name(), "value");
2943 assert_eq!(
2946 entry_fields[1].metadata().get(ARROW_EXTENSION_NAME_KEY),
2947 Some(&"materialize.v1.string".to_string()),
2948 );
2949 }
2950
2951 mod with_ready_batches {
2952 use differential_dataflow::trace::Description;
2953 use differential_dataflow::trace::implementations::Vector;
2954
2955 use super::*;
2956
2957 type TestBatch = OrdValBatch<Vector<((u64, u64), Timestamp, Diff)>>;
2958
2959 fn frontier(t: Option<u64>) -> Antichain<Timestamp> {
2961 t.map_or_else(Antichain::new, |t| Antichain::from_elem(Timestamp::new(t)))
2962 }
2963
2964 fn span(lower: u64, upper: Option<u64>) -> BatchDescription {
2966 (frontier(Some(lower)), frontier(upper))
2967 }
2968
2969 fn input(lower: u64, upper: Option<u64>) -> Span<Timestamp, ArcBatch<TestBatch>> {
2972 let (lower, upper) = span(lower, upper);
2973 let since = Antichain::from_elem(Timestamp::MIN);
2974 Span::new(Description::new(lower, upper, since), None)
2975 }
2976
2977 #[derive(Debug, PartialEq)]
2978 enum Call {
2979 Write(BatchDescription, BatchDescription),
2981 Close(BatchDescription),
2982 }
2983
2984 async fn run(
2987 input_frontier: Antichain<Timestamp>,
2988 input_batches: &mut VecDeque<Span<Timestamp, ArcBatch<TestBatch>>>,
2989 output_frontier: Antichain<Timestamp>,
2990 output_batches: &mut VecDeque<(BatchDescription, ())>,
2991 ) -> Vec<Call> {
2992 let calls = RefCell::new(vec![]);
2993 with_ready_batches(
2994 input_frontier,
2995 input_batches,
2996 output_frontier,
2997 output_batches,
2998 async |rows: &Span<Timestamp, ArcBatch<TestBatch>>, desc, _writer: &mut ()| {
2999 let bounds = (rows.lower().clone(), rows.upper().clone());
3000 calls.borrow_mut().push(Call::Write(bounds, desc));
3001 Ok(())
3002 },
3003 async |desc, _writer: &mut ()| {
3004 calls.borrow_mut().push(Call::Close(desc));
3005 Ok(())
3006 },
3007 )
3008 .await
3009 .expect("test callbacks never fail");
3010 calls.into_inner()
3011 }
3012
3013 #[mz_ore::test(tokio::test)]
3014 async fn input_batch_spanning_multiple_output_batches() {
3015 let mut inputs = VecDeque::from([input(0, Some(30))]);
3016 let mut outputs = VecDeque::from([
3017 (span(0, Some(10)), ()),
3018 (span(10, Some(20)), ()),
3019 (span(20, Some(30)), ()),
3020 ]);
3021
3022 let calls = run(
3023 frontier(Some(30)),
3024 &mut inputs,
3025 frontier(Some(30)),
3026 &mut outputs,
3027 )
3028 .await;
3029
3030 assert_eq!(
3033 calls,
3034 vec![
3035 Call::Write(span(0, Some(30)), span(0, Some(10))),
3036 Call::Close(span(0, Some(10))),
3037 Call::Write(span(0, Some(30)), span(10, Some(20))),
3038 Call::Close(span(10, Some(20))),
3039 Call::Write(span(0, Some(30)), span(20, Some(30))),
3040 Call::Close(span(20, Some(30))),
3041 ]
3042 );
3043 assert!(inputs.is_empty());
3044 assert!(outputs.is_empty());
3045 }
3046
3047 #[mz_ore::test(tokio::test)]
3048 async fn output_batch_spanning_multiple_input_batches() {
3049 let mut inputs =
3050 VecDeque::from([input(0, Some(10)), input(10, Some(20)), input(20, Some(30))]);
3051 let mut outputs = VecDeque::from([(span(0, Some(30)), ())]);
3052
3053 let calls = run(
3054 frontier(Some(30)),
3055 &mut inputs,
3056 frontier(Some(30)),
3057 &mut outputs,
3058 )
3059 .await;
3060
3061 assert_eq!(
3062 calls,
3063 vec![
3064 Call::Write(span(0, Some(10)), span(0, Some(30))),
3065 Call::Write(span(10, Some(20)), span(0, Some(30))),
3066 Call::Write(span(20, Some(30)), span(0, Some(30))),
3067 Call::Close(span(0, Some(30))),
3068 ]
3069 );
3070 assert!(inputs.is_empty());
3071 assert!(outputs.is_empty());
3072 }
3073
3074 #[mz_ore::test(tokio::test)]
3075 async fn input_batch_retained_for_future_output_batches() {
3076 let mut inputs = VecDeque::from([input(0, Some(30))]);
3077 let mut outputs = VecDeque::from([(span(0, Some(10)), ())]);
3078
3079 let calls = run(
3080 frontier(Some(30)),
3081 &mut inputs,
3082 frontier(Some(10)),
3083 &mut outputs,
3084 )
3085 .await;
3086
3087 assert_eq!(
3090 calls,
3091 vec![
3092 Call::Write(span(0, Some(30)), span(0, Some(10))),
3093 Call::Close(span(0, Some(10))),
3094 ]
3095 );
3096 assert_eq!(inputs.len(), 1);
3097 assert!(outputs.is_empty());
3098 }
3099
3100 #[mz_ore::test(tokio::test)]
3101 async fn already_committed_input_batches_dropped_unwritten() {
3102 let mut inputs = VecDeque::from([input(0, Some(10)), input(10, Some(20))]);
3103 let mut outputs = VecDeque::from([(span(20, Some(30)), ())]);
3104
3105 let calls = run(
3106 frontier(Some(20)),
3107 &mut inputs,
3108 frontier(Some(30)),
3109 &mut outputs,
3110 )
3111 .await;
3112
3113 assert_eq!(calls, vec![]);
3117 assert!(inputs.is_empty());
3118 assert_eq!(outputs.len(), 1);
3119 }
3120
3121 #[mz_ore::test(tokio::test)]
3122 async fn output_batch_closes_empty_once_input_frontier_passes() {
3123 let mut outputs = VecDeque::from([(span(0, Some(10)), ())]);
3124
3125 let calls = run(
3128 frontier(Some(5)),
3129 &mut VecDeque::new(),
3130 frontier(Some(10)),
3131 &mut outputs,
3132 )
3133 .await;
3134 assert_eq!(calls, vec![]);
3135 assert_eq!(outputs.len(), 1);
3136
3137 let calls = run(
3140 frontier(Some(10)),
3141 &mut VecDeque::new(),
3142 frontier(Some(10)),
3143 &mut outputs,
3144 )
3145 .await;
3146 assert_eq!(calls, vec![Call::Close(span(0, Some(10)))]);
3147 assert!(outputs.is_empty());
3148 }
3149
3150 #[mz_ore::test(tokio::test)]
3151 async fn final_output_batch_with_empty_upper() {
3152 let mut inputs = VecDeque::from([input(20, Some(30))]);
3153 let mut outputs = VecDeque::from([(span(20, None), ())]);
3154
3155 let calls = run(
3159 frontier(Some(30)),
3160 &mut inputs,
3161 frontier(None),
3162 &mut outputs,
3163 )
3164 .await;
3165 assert_eq!(calls, vec![Call::Write(span(20, Some(30)), span(20, None))]);
3166 assert!(inputs.is_empty());
3167 assert_eq!(outputs.len(), 1);
3168
3169 let calls = run(frontier(None), &mut inputs, frontier(None), &mut outputs).await;
3170 assert_eq!(calls, vec![Call::Close(span(20, None))]);
3171 assert!(outputs.is_empty());
3172 }
3173 }
3174}
3175
3176fn commit_to_iceberg<'scope>(
3180 name: String,
3181 sink_id: GlobalId,
3182 sink_version: u64,
3183 batch_input: StreamVec<'scope, Timestamp, BoundedDataFile>,
3184 batch_desc_input: StreamVec<'scope, Timestamp, (Antichain<Timestamp>, Antichain<Timestamp>)>,
3185 table_ready_stream: StreamVec<'scope, Timestamp, Infallible>,
3186 write_frontier: Rc<RefCell<Antichain<Timestamp>>>,
3187 connection: IcebergSinkConnection,
3188 storage_configuration: StorageConfiguration,
3189 write_handle: impl Future<
3190 Output = anyhow::Result<WriteHandle<SourceData, (), Timestamp, StorageDiff>>,
3191 > + 'static,
3192 metrics: Arc<IcebergSinkMetrics>,
3193 statistics: SinkStatistics,
3194) -> (
3195 StreamVec<'scope, Timestamp, HealthStatusMessage>,
3196 PressOnDropButton,
3197) {
3198 let scope = batch_input.scope();
3199 let mut builder = OperatorBuilder::new(name, scope.clone());
3200
3201 let hashed_id = sink_id.hashed();
3202 let is_active_worker = usize::cast_from(hashed_id) % scope.peers() == scope.index();
3203 let name_for_logging = format!("{sink_id}-commit-to-iceberg");
3204
3205 let mut input = builder.new_disconnected_input(batch_input, Exchange::new(move |_| hashed_id));
3206 let mut batch_desc_input =
3207 builder.new_disconnected_input(batch_desc_input, Exchange::new(move |_| hashed_id));
3208 let mut table_ready_input = builder.new_disconnected_input(table_ready_stream, Pipeline);
3209
3210 let (button, errors) = builder.build_fallible(move |_caps| {
3211 Box::pin(async move {
3212 if !is_active_worker {
3213 write_frontier.borrow_mut().clear();
3214 return Ok(());
3215 }
3216
3217 let namespace_ident = NamespaceIdent::new(connection.namespace.clone());
3218 let table_ident = TableIdent::new(namespace_ident, connection.table.clone());
3219 let catalog = connection
3220 .catalog_connection
3221 .connect(&storage_configuration, InTask::Yes, Some(&table_ident))
3222 .await
3223 .with_context(|| {
3224 format!(
3225 "Failed to connect to Iceberg catalog '{}' for table '{}.{}'",
3226 connection.catalog_connection.uri, connection.namespace, connection.table
3227 )
3228 })?;
3229
3230 let mut write_handle = write_handle.await?;
3231
3232 while let Some(_) = table_ready_input.next().await {
3233 }
3235 let mut table = catalog.load_table(&table_ident).await.with_context(|| {
3236 format!(
3237 "Failed to load Iceberg table '{}.{}' in commit_to_iceberg operator",
3238 connection.namespace, connection.table
3239 )
3240 })?;
3241
3242 #[allow(clippy::disallowed_types)]
3243 let mut batch_descriptions: std::collections::HashMap<
3244 (Antichain<Timestamp>, Antichain<Timestamp>),
3245 BoundedDataFileSet,
3246 > = std::collections::HashMap::new();
3247
3248 let mut batch_description_frontier = Antichain::from_elem(Timestamp::minimum());
3249 let mut input_frontier = Antichain::from_elem(Timestamp::minimum());
3250
3251 while !(batch_description_frontier.is_empty() && input_frontier.is_empty()) {
3252 tokio::select! {
3253 _ = batch_desc_input.ready() => {},
3254 _ = input.ready() => {}
3255 }
3256
3257 while let Some(event) = batch_desc_input.next_sync() {
3258 match event {
3259 Event::Data(_cap, data) => {
3260 for batch_desc in data {
3261 let prev = batch_descriptions
3262 .insert(batch_desc, BoundedDataFileSet { data_files: vec![] });
3263 if let Some(prev) = prev {
3264 anyhow::bail!(
3265 "Duplicate batch description received \
3266 in commit operator: {:?}",
3267 prev
3268 );
3269 }
3270 }
3271 }
3272 Event::Progress(frontier) => {
3273 batch_description_frontier = frontier;
3274 }
3275 }
3276 }
3277
3278 let ready_events = std::iter::from_fn(|| input.next_sync()).collect_vec();
3279 for event in ready_events {
3280 match event {
3281 Event::Data(_cap, data) => {
3282 for bounded_data_file in data {
3283 let entry = batch_descriptions
3284 .entry(bounded_data_file.batch_desc().clone())
3285 .or_default();
3286 entry.data_files.push(bounded_data_file);
3287 }
3288 }
3289 Event::Progress(frontier) => {
3290 input_frontier = frontier;
3291 }
3292 }
3293 }
3294
3295 let mut done_batches: Vec<_> = batch_descriptions
3301 .keys()
3302 .filter(|(lower, _upper)| PartialOrder::less_than(lower, &input_frontier))
3303 .cloned()
3304 .collect();
3305
3306 done_batches.sort_by(|a, b| {
3308 if PartialOrder::less_than(a, b) {
3309 Ordering::Less
3310 } else if PartialOrder::less_than(b, a) {
3311 Ordering::Greater
3312 } else {
3313 Ordering::Equal
3314 }
3315 });
3316
3317 for batch in done_batches {
3318 let file_set = batch_descriptions.remove(&batch).unwrap();
3319
3320 let mut data_files = vec![];
3321 let mut delete_files = vec![];
3322 let mut total_messages: u64 = 0;
3324 let mut total_bytes: u64 = 0;
3325 for file in file_set.data_files {
3326 total_messages += file.data_file().record_count();
3327 total_bytes += file.data_file().file_size_in_bytes();
3328 match file.data_file().content_type() {
3329 iceberg::spec::DataContentType::Data => {
3330 data_files.push(file.into_data_file());
3331 }
3332 iceberg::spec::DataContentType::PositionDeletes
3333 | iceberg::spec::DataContentType::EqualityDeletes => {
3334 delete_files.push(file.into_data_file());
3335 }
3336 }
3337 }
3338
3339 debug!(
3340 ?sink_id,
3341 %name_for_logging,
3342 lower = %batch.0.pretty(),
3343 upper = %batch.1.pretty(),
3344 data_files = data_files.len(),
3345 delete_files = delete_files.len(),
3346 total_messages,
3347 total_bytes,
3348 "iceberg commit applying batch"
3349 );
3350
3351 let instant = Instant::now();
3352
3353 let frontier = batch.1.clone();
3354 let frontier_json = serde_json::to_string(&frontier.elements())
3355 .context("Failed to serialize frontier to JSON")?;
3356 let snapshot_properties = vec![
3357 ("mz-sink-id".to_string(), sink_id.to_string()),
3358 ("mz-frontier".to_string(), frontier_json),
3359 ("mz-sink-version".to_string(), sink_version.to_string()),
3360 ];
3361
3362 let (table_state, commit_result) = Retry::default()
3363 .max_tries(5)
3364 .retry_async_with_state(table, |_, table| {
3365 let snapshot_properties = snapshot_properties.clone();
3366 let data_files = data_files.clone();
3367 let delete_files = delete_files.clone();
3368 let metrics = Arc::clone(&metrics);
3369 let catalog = Arc::clone(&catalog);
3370 let conn_namespace = connection.namespace.clone();
3371 let conn_table = connection.table.clone();
3372 let batch_lower = batch.0.clone();
3373 let batch_upper = batch.1.clone();
3374 async move {
3375 try_commit_batch(
3376 table,
3377 snapshot_properties,
3378 data_files,
3379 delete_files,
3380 catalog.as_ref(),
3381 &conn_namespace,
3382 &conn_table,
3383 sink_id,
3384 sink_version,
3385 &batch_lower,
3386 &batch_upper,
3387 &metrics,
3388 )
3389 .await
3390 }
3391 })
3392 .await;
3393 let commit_result = commit_result.with_context(|| {
3394 format!(
3395 "failed to commit batch to Iceberg table '{}.{}'",
3396 connection.namespace, connection.table
3397 )
3398 });
3399 table = table_state;
3400 let duration = instant.elapsed();
3401 metrics
3402 .commit_duration_seconds
3403 .observe(duration.as_secs_f64());
3404 commit_result?;
3405
3406 debug!(
3407 ?sink_id,
3408 %name_for_logging,
3409 lower = %batch.0.pretty(),
3410 upper = %batch.1.pretty(),
3411 total_messages,
3412 total_bytes,
3413 ?duration,
3414 "iceberg commit applied batch"
3415 );
3416
3417 metrics.snapshots_committed.inc();
3418 statistics.inc_messages_committed_by(total_messages);
3419 statistics.inc_bytes_committed_by(total_bytes);
3420
3421 let mut expect_upper = write_handle.shared_upper();
3422 loop {
3423 if PartialOrder::less_equal(&frontier, &expect_upper) {
3424 break;
3426 }
3427
3428 const EMPTY: &[((SourceData, ()), Timestamp, StorageDiff)] = &[];
3429 match write_handle
3430 .compare_and_append(EMPTY, expect_upper, frontier.clone())
3431 .await
3432 .expect("valid usage")
3433 {
3434 Ok(()) => break,
3435 Err(mismatch) => {
3436 expect_upper = mismatch.current;
3437 }
3438 }
3439 }
3440 write_frontier.borrow_mut().clone_from(&frontier);
3441 }
3442 }
3443
3444 Ok(())
3445 })
3446 });
3447
3448 let statuses = errors.map(|error| error_status(&error));
3449
3450 (statuses, button.press_on_drop())
3451}
3452
3453impl<'scope> SinkRender<'scope> for IcebergSinkConnection {
3454 fn get_key_indices(&self) -> Option<&[usize]> {
3455 self.key_desc_and_indices
3456 .as_ref()
3457 .map(|(_, indices)| indices.as_slice())
3458 }
3459
3460 fn get_relation_key_indices(&self) -> Option<&[usize]> {
3461 self.relation_key_indices.as_deref()
3462 }
3463
3464 fn render_sink(
3465 &self,
3466 storage_state: &mut StorageState,
3467 sink: &StorageSinkDesc<CollectionMetadata, Timestamp>,
3468 sink_id: GlobalId,
3469 batches: SinkBatchStream<'scope>,
3470 key_is_synthetic: bool,
3471 _err_collection: VecCollection<'scope, Timestamp, DataflowError, Diff>,
3472 ) -> (
3473 StreamVec<'scope, Timestamp, HealthStatusMessage>,
3474 Vec<PressOnDropButton>,
3475 ) {
3476 let scope = batches.scope();
3477
3478 let write_handle = {
3479 let persist = Arc::clone(&storage_state.persist_clients);
3480 let shard_meta = sink.to_storage_metadata.clone();
3481 async move {
3482 let client = persist.open(shard_meta.persist_location).await?;
3483 let handle = client
3484 .open_writer(
3485 shard_meta.data_shard,
3486 Arc::new(shard_meta.relation_desc),
3487 Arc::new(UnitSchema),
3488 Diagnostics::from_purpose("sink handle"),
3489 )
3490 .await?;
3491 Ok(handle)
3492 }
3493 };
3494
3495 let write_frontier = Rc::new(RefCell::new(Antichain::from_elem(Timestamp::minimum())));
3496 storage_state
3497 .sink_write_frontiers
3498 .insert(sink_id, Rc::clone(&write_frontier));
3499
3500 let (arrow_schema_with_ids, iceberg_schema) =
3501 match (|| -> Result<(ArrowSchema, Arc<Schema>), anyhow::Error> {
3502 let (arrow_schema_with_ids, iceberg_schema) =
3503 relation_desc_to_iceberg_schema(&sink.from_desc)?;
3504
3505 Ok(if sink.envelope == SinkEnvelope::Append {
3506 let extended_arrow = build_schema_with_append_columns(&arrow_schema_with_ids);
3511 let extended_iceberg = Arc::new(
3512 arrow_schema_to_schema_auto_assign_ids(&extended_arrow)
3513 .context("Failed to build Iceberg schema with append columns")?,
3514 );
3515
3516 (extended_arrow, extended_iceberg)
3517 } else {
3518 (arrow_schema_with_ids, iceberg_schema)
3519 })
3520 })() {
3521 Ok(schemas) => schemas,
3522 Err(err) => {
3523 let err = StallingError::InvalidSchema(err).into();
3525 let error_stream = std::iter::once(error_status(&err)).to_stream(scope);
3526 return (error_stream, vec![]);
3527 }
3528 };
3529
3530 let metrics = Arc::new(
3531 storage_state
3532 .metrics
3533 .get_iceberg_sink_metrics(sink_id, scope.index()),
3534 );
3535
3536 let statistics = storage_state
3537 .aggregated_statistics
3538 .get_sink(&sink_id)
3539 .expect("statistics initialized")
3540 .clone();
3541
3542 let connection_for_minter = self.clone();
3543 let (batch_descriptions, table_ready, mint_status, mint_button) = mint_batch_descriptions(
3544 format!("{sink_id}-iceberg-mint"),
3545 sink_id,
3546 batches.clone(),
3547 sink,
3548 connection_for_minter,
3549 storage_state.storage_configuration.clone(),
3550 Arc::clone(&iceberg_schema),
3551 );
3552
3553 let connection_for_writer = self.clone();
3554 let (datafiles, write_status, write_button) = match sink.envelope {
3555 SinkEnvelope::Upsert => write_data_files::<UpsertEnvelopeHandler>(
3556 format!("{sink_id}-write-data-files"),
3557 batches,
3558 batch_descriptions.clone(),
3559 table_ready.clone(),
3560 sink_id,
3561 sink.from,
3562 key_is_synthetic,
3563 sink.as_of.clone(),
3564 connection_for_writer,
3565 storage_state.storage_configuration.clone(),
3566 Arc::new(arrow_schema_with_ids.clone()),
3567 Arc::clone(&metrics),
3568 statistics.clone(),
3569 ),
3570 SinkEnvelope::Append => write_data_files::<AppendEnvelopeHandler>(
3571 format!("{sink_id}-write-data-files"),
3572 batches,
3573 batch_descriptions.clone(),
3574 table_ready.clone(),
3575 sink_id,
3576 sink.from,
3577 key_is_synthetic,
3578 sink.as_of.clone(),
3579 connection_for_writer,
3580 storage_state.storage_configuration.clone(),
3581 Arc::new(arrow_schema_with_ids.clone()),
3582 Arc::clone(&metrics),
3583 statistics.clone(),
3584 ),
3585 SinkEnvelope::Debezium => {
3586 unreachable!("Iceberg sink only supports Upsert and Append envelopes")
3587 }
3588 };
3589
3590 let connection_for_committer = self.clone();
3591 let (commit_status, commit_button) = commit_to_iceberg(
3592 format!("{sink_id}-commit-to-iceberg"),
3593 sink_id,
3594 sink.version,
3595 datafiles,
3596 batch_descriptions,
3597 table_ready,
3598 Rc::clone(&write_frontier),
3599 connection_for_committer,
3600 storage_state.storage_configuration.clone(),
3601 write_handle,
3602 Arc::clone(&metrics),
3603 statistics,
3604 );
3605
3606 let running_status = Some(HealthStatusMessage {
3607 id: None,
3608 update: HealthStatusUpdate::running(),
3609 namespace: StatusNamespace::Iceberg,
3610 })
3611 .to_stream(scope);
3612
3613 let statuses =
3614 scope.concatenate([running_status, mint_status, write_status, commit_status]);
3615
3616 (statuses, vec![mint_button, write_button, commit_button])
3617 }
3618}