You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iceberg.apache.org by gi...@apache.org on 2026/09/17 08:16:37 UTC
(iceberg-rust) branch gh-readonly-queue/main/pr-2773-8193cce4b3cfe4608738cdf36e0ddf74a15a415b created (now 8030cf444)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-2773-8193cce4b3cfe4608738cdf36e0ddf74a15a415b
in repository https://gitbox.apache.org/repos/asf/iceberg-rust.git
at 8030cf444 feat(spec): add unknown primitive type support (#2773)
This branch includes the following new commits:
new 8030cf444 feat(spec): add unknown primitive type support (#2773)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(iceberg-rust) 01/01: feat(spec): add unknown primitive type support (#2773)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-2773-8193cce4b3cfe4608738cdf36e0ddf74a15a415b
in repository https://gitbox.apache.org/repos/asf/iceberg-rust.git
commit 8030cf44445b3f957e367515e9d3c5eeb00f104d
Author: Manu Zhang <Ow...@gmail.com>
AuthorDate: Thu Sep 17 08:16:13 2026 +0000
feat(spec): add unknown primitive type support (#2773)
* feat(spec): add unknown primitive type support
Co-authored-by: Codex <co...@openai.com>
* fix(arrow): validate row ID synthesis inputs
* fix(spec): centralize unknown field validation
* fix(spec): address unknown type review feedback
* fix(spec): address remaining review feedback
* fix(spec): centralize dropped partition source handling
* fix(inspect): recover historical partition bounds
* fix(spec): validate default partition sources on metadata load
* Revert "fix(inspect): recover historical partition bounds"
This reverts commit 6403d4898edd03b433c64965b1ed7195686a0330.
---------
Co-authored-by: Codex <co...@openai.com>
---
crates/catalog/glue/src/schema.rs | 6 ++
crates/catalog/hms/src/schema.rs | 6 ++
crates/iceberg/public-api.txt | 1 +
crates/iceberg/src/arrow/schema.rs | 11 ++
crates/iceberg/src/arrow/value.rs | 24 ++++-
crates/iceberg/src/avro/schema.rs | 106 ++++++++++++++++----
crates/iceberg/src/inspect/manifests.rs | 61 ++++++++----
crates/iceberg/src/scan/mod.rs | 35 +++++--
crates/iceberg/src/scan/task.rs | 9 +-
crates/iceberg/src/spec/datatypes.rs | 24 ++++-
crates/iceberg/src/spec/partition.rs | 124 +++++++++++++++++------
crates/iceberg/src/spec/schema/mod.rs | 160 ++++++++++++++++++++++++++++++
crates/iceberg/src/spec/table_metadata.rs | 86 +++++++++++++++-
crates/iceberg/src/spec/values/datum.rs | 6 ++
crates/iceberg/src/spec/values/literal.rs | 27 +++--
crates/iceberg/src/spec/values/tests.rs | 17 ++++
16 files changed, 599 insertions(+), 104 deletions(-)
diff --git a/crates/catalog/glue/src/schema.rs b/crates/catalog/glue/src/schema.rs
index 6a33a9cba..6116fc224 100644
--- a/crates/catalog/glue/src/schema.rs
+++ b/crates/catalog/glue/src/schema.rs
@@ -149,6 +149,12 @@ impl SchemaVisitor for GlueSchemaBuilder {
fn primitive(&mut self, p: &PrimitiveType) -> Result<Self::T> {
let glue_type = match p {
+ PrimitiveType::Unknown => {
+ return Err(Error::new(
+ ErrorKind::FeatureUnsupported,
+ format!("Conversion from {p:?} is not supported"),
+ ));
+ }
PrimitiveType::Boolean => "boolean".to_string(),
PrimitiveType::Int => "int".to_string(),
PrimitiveType::Long => "bigint".to_string(),
diff --git a/crates/catalog/hms/src/schema.rs b/crates/catalog/hms/src/schema.rs
index e21a75f97..f04ee11c1 100644
--- a/crates/catalog/hms/src/schema.rs
+++ b/crates/catalog/hms/src/schema.rs
@@ -100,6 +100,12 @@ impl SchemaVisitor for HiveSchemaBuilder {
fn primitive(&mut self, p: &PrimitiveType) -> Result<String> {
let hive_type = match p {
+ PrimitiveType::Unknown => {
+ return Err(Error::new(
+ ErrorKind::FeatureUnsupported,
+ format!("Conversion from {p:?} is not supported"),
+ ));
+ }
PrimitiveType::Boolean => "boolean".to_string(),
PrimitiveType::Int => "int".to_string(),
PrimitiveType::Long => "bigint".to_string(),
diff --git a/crates/iceberg/public-api.txt b/crates/iceberg/public-api.txt
index 7d03d6b1f..a917d28f5 100644
--- a/crates/iceberg/public-api.txt
+++ b/crates/iceberg/public-api.txt
@@ -1664,6 +1664,7 @@ pub iceberg::spec::PrimitiveType::Timestamp
pub iceberg::spec::PrimitiveType::TimestampNs
pub iceberg::spec::PrimitiveType::Timestamptz
pub iceberg::spec::PrimitiveType::TimestamptzNs
+pub iceberg::spec::PrimitiveType::Unknown
pub iceberg::spec::PrimitiveType::Uuid
impl iceberg::spec::PrimitiveType
pub fn iceberg::spec::PrimitiveType::compatible(&self, literal: &iceberg::spec::PrimitiveLiteral) -> bool
diff --git a/crates/iceberg/src/arrow/schema.rs b/crates/iceberg/src/arrow/schema.rs
index 349ada859..4ef7b2943 100644
--- a/crates/iceberg/src/arrow/schema.rs
+++ b/crates/iceberg/src/arrow/schema.rs
@@ -191,6 +191,7 @@ fn visit_type<V: ArrowSchemaVisitor>(r#type: &DataType, visitor: &mut V) -> Resu
| DataType::Utf8
| DataType::LargeUtf8
| DataType::Utf8View
+ | DataType::Null
| DataType::Binary
| DataType::LargeBinary
| DataType::BinaryView
@@ -509,6 +510,7 @@ impl ArrowSchemaVisitor for ArrowSchemaConverter {
fn primitive(&mut self, p: &DataType) -> Result<Self::T> {
match p {
+ DataType::Null => Ok(Type::Primitive(PrimitiveType::Unknown)),
DataType::Boolean => Ok(Type::Primitive(PrimitiveType::Boolean)),
DataType::Int8 | DataType::Int16 | DataType::Int32 => {
Ok(Type::Primitive(PrimitiveType::Int))
@@ -697,6 +699,7 @@ impl SchemaVisitor for ToArrowSchemaConverter {
fn primitive(&mut self, p: &PrimitiveType) -> Result<ArrowSchemaOrFieldOrType> {
match p {
+ PrimitiveType::Unknown => Ok(ArrowSchemaOrFieldOrType::Type(DataType::Null)),
PrimitiveType::Boolean => Ok(ArrowSchemaOrFieldOrType::Type(DataType::Boolean)),
PrimitiveType::Int => Ok(ArrowSchemaOrFieldOrType::Type(DataType::Int32)),
PrimitiveType::Long => Ok(ArrowSchemaOrFieldOrType::Type(DataType::Int64)),
@@ -1209,6 +1212,7 @@ pub(crate) fn primitive_type_to_arrow_type_with_ree(primitive_type: &PrimitiveTy
};
match primitive_type {
+ PrimitiveType::Unknown => make_ree(DataType::Null),
PrimitiveType::Boolean => make_ree(DataType::Boolean),
PrimitiveType::Int => make_ree(DataType::Int32),
PrimitiveType::Long => make_ree(DataType::Int64),
@@ -2227,6 +2231,13 @@ mod tests {
assert_eq!(iceberg_type, arrow_type_to_type(&arrow_type).unwrap());
}
+ {
+ let arrow_type = DataType::Null;
+ let iceberg_type = Type::Primitive(PrimitiveType::Unknown);
+ assert_eq!(arrow_type, type_to_arrow_type(&iceberg_type).unwrap());
+ assert_eq!(iceberg_type, arrow_type_to_type(&arrow_type).unwrap());
+ }
+
// test struct type
{
// no metadata will cause error
diff --git a/crates/iceberg/src/arrow/value.rs b/crates/iceberg/src/arrow/value.rs
index ff28052fc..ad2a7f647 100644
--- a/crates/iceberg/src/arrow/value.rs
+++ b/crates/iceberg/src/arrow/value.rs
@@ -206,6 +206,7 @@ impl SchemaWithPartnerVisitor<ArrayRef> for ArrowArrayToIcebergStructConverter {
fn primitive(&mut self, p: &PrimitiveType, partner: &ArrayRef) -> Result<Vec<Option<Literal>>> {
match p {
+ PrimitiveType::Unknown => Ok(vec![None; partner.len()]),
PrimitiveType::Boolean => {
let array = partner
.as_any()
@@ -636,6 +637,7 @@ pub(crate) fn create_primitive_array_single_element(
prim_lit: Option<&PrimitiveLiteral>,
) -> Result<ArrayRef> {
match (data_type, prim_lit) {
+ (DataType::Null, None) => Ok(Arc::new(arrow_array::NullArray::new(1))),
(DataType::Boolean, Some(PrimitiveLiteral::Boolean(v))) => {
Ok(Arc::new(BooleanArray::from(vec![*v])))
}
@@ -963,7 +965,7 @@ pub(crate) fn create_primitive_array_repeated(
Some(NullBuffer::new_null(num_rows)),
))
}
- (DataType::Null, _) => Arc::new(arrow_array::NullArray::new(num_rows)),
+ (DataType::Null, None) => Arc::new(arrow_array::NullArray::new(num_rows)),
// --- Catch-all null arm: use arrow-rs new_null_array for any remaining DataType ---
(dt, None) => new_null_array(dt, num_rows),
@@ -1886,6 +1888,26 @@ mod test {
}
}
+ #[test]
+ fn test_create_null_array_rejects_non_null_literal() {
+ let literal = Some(PrimitiveLiteral::Int(1));
+
+ assert!(create_primitive_array_single_element(&DataType::Null, literal.as_ref()).is_err());
+ assert!(create_primitive_array_repeated(&DataType::Null, literal.as_ref(), 2).is_err());
+ assert_eq!(
+ create_primitive_array_single_element(&DataType::Null, None)
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ create_primitive_array_repeated(&DataType::Null, None, 2)
+ .unwrap()
+ .len(),
+ 2
+ );
+ }
+
#[test]
fn test_create_decimal_array_repeated_respects_precision() {
// Ensure repeated arrays also respect target precision, not Arrow's default.
diff --git a/crates/iceberg/src/avro/schema.rs b/crates/iceberg/src/avro/schema.rs
index 528b89b7c..a67e4ed71 100644
--- a/crates/iceberg/src/avro/schema.rs
+++ b/crates/iceberg/src/avro/schema.rs
@@ -75,7 +75,13 @@ impl SchemaVisitor for SchemaToAvroSchema {
}
if !field.required {
- field_schema = avro_optional(field_schema)?;
+ if is_avro_null(&field_schema) {
+ // Unknown maps directly to Avro null. Wrapping it as optional would create
+ // an invalid union with duplicate null variants.
+ field_schema = AvroSchema::Null;
+ } else {
+ field_schema = avro_optional(field_schema)?;
+ }
}
let default = if let Some(literal) = &field.initial_default {
@@ -127,7 +133,13 @@ impl SchemaVisitor for SchemaToAvroSchema {
}
if !list.element_field.required {
- field_schema = avro_optional(field_schema)?;
+ if is_avro_null(&field_schema) {
+ // Unknown maps directly to Avro null. Wrapping it as optional would create
+ // an invalid union with duplicate null variants.
+ field_schema = AvroSchema::Null;
+ } else {
+ field_schema = avro_optional(field_schema)?;
+ }
}
Ok(Either::Left(AvroSchema::Array(ArraySchema {
@@ -148,7 +160,13 @@ impl SchemaVisitor for SchemaToAvroSchema {
let key_field_schema = key_value.unwrap_left();
let mut value_field_schema = value.unwrap_left();
if !map.value_field.required {
- value_field_schema = avro_optional(value_field_schema)?;
+ if is_avro_null(&value_field_schema) {
+ // Unknown maps directly to Avro null. Wrapping it as optional would create
+ // an invalid union with duplicate null variants.
+ value_field_schema = AvroSchema::Null;
+ } else {
+ value_field_schema = avro_optional(value_field_schema)?;
+ }
}
if matches!(key_field_schema, AvroSchema::String) {
@@ -222,6 +240,7 @@ impl SchemaVisitor for SchemaToAvroSchema {
fn primitive(&mut self, p: &PrimitiveType) -> Result<AvroSchemaOrField> {
let avro_schema = match p {
+ PrimitiveType::Unknown => AvroSchema::Null,
PrimitiveType::Boolean => AvroSchema::Boolean,
PrimitiveType::Int => AvroSchema::Int,
PrimitiveType::Long => AvroSchema::Long,
@@ -324,6 +343,14 @@ fn is_avro_optional(avro_schema: &AvroSchema) -> bool {
}
}
+fn is_avro_null(avro_schema: &AvroSchema) -> bool {
+ matches!(avro_schema, AvroSchema::Null)
+}
+
+fn unwrap_or_unknown(field_type: Option<Type>) -> Type {
+ field_type.unwrap_or(Type::Primitive(PrimitiveType::Unknown))
+}
+
/// Post order avro schema visitor.
pub(crate) trait AvroSchemaVisitor {
type T;
@@ -447,10 +474,10 @@ impl AvroSchemaVisitor for AvroSchemaToSchema {
let field_id =
Self::get_element_id_from_attributes(&avro_field.custom_attributes, FIELD_ID_PROP)?;
- let optional = is_avro_optional(&avro_field.schema);
+ let optional = is_avro_optional(&avro_field.schema) || is_avro_null(&avro_field.schema);
- let mut field =
- NestedField::new(field_id, &avro_field.name, field_type.unwrap(), !optional);
+ let field_type = unwrap_or_unknown(field_type);
+ let mut field = NestedField::new(field_id, &avro_field.name, field_type, !optional);
if let Some(doc) = &avro_field.doc {
field = field.with_doc(doc);
@@ -482,7 +509,7 @@ impl AvroSchemaVisitor for AvroSchemaToSchema {
}
if options.len() == 1 {
- Ok(Some(options.remove(0).unwrap()))
+ Ok(Some(unwrap_or_unknown(options.remove(0))))
} else {
Ok(Some(options.remove(1).unwrap()))
}
@@ -490,10 +517,11 @@ impl AvroSchemaVisitor for AvroSchemaToSchema {
fn array(&mut self, array: &ArraySchema, item: Option<Type>) -> Result<Self::T> {
let element_field_id = Self::get_element_id_from_attributes(&array.attributes, ELEMENT_ID)?;
+ let item = unwrap_or_unknown(item);
let element_field = NestedField::list_element(
element_field_id,
- item.unwrap(),
- !is_avro_optional(&array.items),
+ item,
+ !is_avro_optional(&array.items) && !is_avro_null(&array.items),
)
.into();
Ok(Some(Type::List(ListType { element_field })))
@@ -504,10 +532,11 @@ impl AvroSchemaVisitor for AvroSchemaToSchema {
let key_field =
NestedField::map_key_element(key_field_id, Type::Primitive(PrimitiveType::String));
let value_field_id = Self::get_element_id_from_attributes(&map.attributes, VALUE_ID)?;
+ let value = unwrap_or_unknown(value);
let value_field = NestedField::map_value_element(
value_field_id,
- value.unwrap(),
- !is_avro_optional(&map.types),
+ value,
+ !is_avro_optional(&map.types) && !is_avro_null(&map.types),
);
Ok(Some(Type::Map(MapType {
key_field: key_field.into(),
@@ -557,12 +586,7 @@ impl AvroSchemaVisitor for AvroSchemaToSchema {
"Can't convert avro map schema, missing key schema.",
)
})?;
- let value = value.ok_or_else(|| {
- Error::new(
- ErrorKind::DataInvalid,
- "Can't convert avro map schema, missing value schema.",
- )
- })?;
+ let value = unwrap_or_unknown(value);
let key_id = Self::get_element_id_from_attributes(
&array.fields[0].custom_attributes,
FIELD_ID_PROP,
@@ -575,7 +599,7 @@ impl AvroSchemaVisitor for AvroSchemaToSchema {
let value_field = NestedField::map_value_element(
value_id,
value,
- !is_avro_optional(&array.fields[1].schema),
+ !is_avro_optional(&array.fields[1].schema) && !is_avro_null(&array.fields[1].schema),
);
Ok(Some(Type::Map(MapType {
key_field: key_field.into(),
@@ -659,6 +683,52 @@ mod tests {
assert_eq!(iceberg_schema, converted_avro_converted_iceberg_schema);
}
+ #[test]
+ fn test_unknown_type_schema_conversion() {
+ let schema = Schema::builder()
+ .with_fields(vec![
+ NestedField::optional(1, "empty", PrimitiveType::Unknown.into()).into(),
+ NestedField::required(
+ 2,
+ "unknowns",
+ Type::List(ListType::new(
+ NestedField::list_element(3, PrimitiveType::Unknown.into(), false).into(),
+ )),
+ )
+ .into(),
+ NestedField::required(
+ 4,
+ "unknown_values",
+ Type::Map(MapType::optional(
+ 5,
+ PrimitiveType::String.into(),
+ 6,
+ PrimitiveType::Unknown.into(),
+ )),
+ )
+ .into(),
+ ])
+ .build()
+ .unwrap();
+
+ let avro_schema = schema_to_avro_schema("table", &schema).unwrap();
+ let AvroSchema::Record(record) = &avro_schema else {
+ panic!("expected avro record schema");
+ };
+ assert!(is_avro_null(&record.fields[0].schema));
+ assert_eq!(record.fields[0].default, Some(Value::Null));
+ let AvroSchema::Array(array) = &record.fields[1].schema else {
+ panic!("expected Avro array schema");
+ };
+ assert!(is_avro_null(&array.items));
+ let AvroSchema::Map(map) = &record.fields[2].schema else {
+ panic!("expected Avro map schema");
+ };
+ assert!(is_avro_null(&map.types));
+
+ assert_eq!(schema, avro_schema_to_schema(&avro_schema).unwrap());
+ }
+
#[test]
fn test_manifest_file_v1_schema() {
let fields = vec![
diff --git a/crates/iceberg/src/inspect/manifests.rs b/crates/iceberg/src/inspect/manifests.rs
index 38351a8c5..9e0f7f224 100644
--- a/crates/iceberg/src/inspect/manifests.rs
+++ b/crates/iceberg/src/inspect/manifests.rs
@@ -260,22 +260,22 @@ impl<'a> ManifestsTable<'a> {
.unwrap()
.append_option(summary.contains_nan);
- partition_summaries_builder
- .field_builder::<StringBuilder>(2)
- .unwrap()
- .append_option(summary.lower_bound.as_ref().map(|v| {
- Datum::try_from_bytes(v, field.field_type.as_primitive_type().unwrap().clone())
- .unwrap()
- .to_string()
- }));
- partition_summaries_builder
- .field_builder::<StringBuilder>(3)
- .unwrap()
- .append_option(summary.upper_bound.as_ref().map(|v| {
- Datum::try_from_bytes(v, field.field_type.as_primitive_type().unwrap().clone())
- .unwrap()
- .to_string()
- }));
+ let field_type = field.field_type.as_primitive_type().unwrap();
+ for (index, bound) in [(2, &summary.lower_bound), (3, &summary.upper_bound)] {
+ // Bounds cannot be decoded when the source column's type is unknown.
+ let bound = bound
+ .as_ref()
+ .filter(|_| *field_type != PrimitiveType::Unknown)
+ .map(|v| {
+ Datum::try_from_bytes(v, field_type.clone())
+ .unwrap()
+ .to_string()
+ });
+ partition_summaries_builder
+ .field_builder::<StringBuilder>(index)
+ .unwrap()
+ .append_option(bound);
+ }
partition_summaries_builder.append(true);
}
builder.append(true);
@@ -286,6 +286,7 @@ impl<'a> ManifestsTable<'a> {
mod tests {
use std::sync::Arc;
+ use arrow_array::{Array, ListArray, StructArray};
use expect_test::expect;
use futures::TryStreamExt;
@@ -418,9 +419,29 @@ mod tests {
let metadata: TableMetadata = serde_json::from_value(metadata).unwrap();
let table = fixture.table.clone().with_metadata(Arc::new(metadata));
- match table.inspect().manifests().scan().await {
- Err(err) => assert!(err.to_string().contains("No column with source column id")),
- Ok(_) => panic!("expected scan to fail for a dropped partition source column"),
- }
+ let batches: Vec<_> = table
+ .inspect()
+ .manifests()
+ .scan()
+ .await
+ .unwrap()
+ .try_collect()
+ .await
+ .unwrap();
+ assert_eq!(batches.len(), 1);
+ assert_eq!(batches[0].num_rows(), 1);
+ let summaries = batches[0]
+ .column_by_name("partition_summaries")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<ListArray>()
+ .unwrap();
+ let summary = summaries.value(0);
+ let summary = summary.as_any().downcast_ref::<StructArray>().unwrap();
+ assert_eq!(summary.len(), 1);
+ assert!(summary.column_by_name("contains_null").unwrap().is_valid(0));
+ assert!(summary.column_by_name("contains_nan").unwrap().is_valid(0));
+ assert!(summary.column_by_name("lower_bound").unwrap().is_null(0));
+ assert!(summary.column_by_name("upper_bound").unwrap().is_null(0));
}
}
diff --git a/crates/iceberg/src/scan/mod.rs b/crates/iceberg/src/scan/mod.rs
index 081d64273..fd833d9b3 100644
--- a/crates/iceberg/src/scan/mod.rs
+++ b/crates/iceberg/src/scan/mod.rs
@@ -2284,10 +2284,15 @@ pub mod tests {
}
#[tokio::test]
- async fn test_filtered_scan_rejects_dropped_partition_source_column() {
+ async fn test_filtered_scan_with_dropped_partition_source_column() {
let mut fixture = TableTestFixture::new();
fixture.setup_manifest_files().await;
+ // Baseline: the same filtered scan against the table before evolution.
+ let baseline = scan_y_gte_5(&fixture.table).await;
+ assert!(!baseline.is_empty());
+ assert!(baseline.iter().all(|y| *y >= 5));
+
// Evolve the table so that the manifests reference a historical spec whose source
// column is no longer in the current schema: make an unpartitioned spec the
// default, then drop the original spec's source column from the schema.
@@ -2337,23 +2342,37 @@ pub mod tests {
.metadata;
let table = fixture.table.clone().with_metadata(Arc::new(metadata));
+ // Planning and reading must succeed, and the results must match the table before
+ // evolution: no rows wrongly pruned and none returned unfiltered.
+ let evolved = scan_y_gte_5(&table).await;
+ assert_eq!(evolved, baseline);
+ }
+
+ async fn scan_y_gte_5(table: &Table) -> Vec<i64> {
let table_scan = table
.scan()
.select(["y"])
.with_filter(Reference::new("y").greater_than_or_equal_to(Datum::long(5)))
.build()
.unwrap();
-
- let err = table_scan
- .plan_files()
+ let batches: Vec<_> = table_scan
+ .to_arrow()
.await
.unwrap()
- .try_collect::<Vec<_>>()
+ .try_collect()
.await
- .unwrap_err();
+ .unwrap();
- assert_eq!(err.kind(), ErrorKind::Unexpected);
- assert!(err.message().contains("No column with source column id 1"));
+ let mut values: Vec<i64> = batches
+ .iter()
+ .flat_map(|batch| {
+ let col = batch.column_by_name("y").unwrap();
+ let arr = col.as_any().downcast_ref::<Int64Array>().unwrap();
+ (0..arr.len()).map(|i| arr.value(i)).collect::<Vec<_>>()
+ })
+ .collect();
+ values.sort_unstable();
+ values
}
#[tokio::test]
diff --git a/crates/iceberg/src/scan/task.rs b/crates/iceberg/src/scan/task.rs
index 5fd0f81bb..531f40556 100644
--- a/crates/iceberg/src/scan/task.rs
+++ b/crates/iceberg/src/scan/task.rs
@@ -689,7 +689,7 @@ mod tests {
}
#[test]
- fn test_file_scan_task_builder_rejects_dropped_partition_source_column() {
+ fn test_file_scan_task_builder_accepts_dropped_partition_source_column() {
let (_historical_schema, partition_spec) =
schema_and_spec(PrimitiveType::Long, Transform::Identity);
let current_schema = Arc::new(
@@ -703,15 +703,12 @@ mod tests {
.unwrap(),
);
- let err = build_file_scan_task(
+ build_file_scan_task(
current_schema,
Some(Struct::from_iter([Some(Literal::long(42))])),
Some(partition_spec),
)
- .unwrap_err();
-
- assert_eq!(err.kind(), ErrorKind::Unexpected);
- assert!(err.message().contains("No column with source column id 1"));
+ .unwrap();
}
#[test]
diff --git a/crates/iceberg/src/spec/datatypes.rs b/crates/iceberg/src/spec/datatypes.rs
index e53f856c0..8c4029f7b 100644
--- a/crates/iceberg/src/spec/datatypes.rs
+++ b/crates/iceberg/src/spec/datatypes.rs
@@ -133,8 +133,8 @@ impl Type {
/// Minimum [`FormatVersion`] required to support this type, **without** taking
/// nested field types into account.
///
- /// `TimestampNs` / `TimestamptzNs` / `Variant` require [`FormatVersion::V3`]; every
- /// other type is valid from [`FormatVersion::V1`]. Mirrors Java's
+ /// `Unknown` / `TimestampNs` / `TimestamptzNs` / `Variant` require
+ /// [`FormatVersion::V3`]; every other type is valid from [`FormatVersion::V1`]. Mirrors Java's
/// `Schema.MIN_FORMAT_VERSIONS` (a shallow lookup keyed by type id), so it
/// intentionally does not recurse: callers needing the floor for a whole schema
/// iterate its flattened fields (see [`Schema::calc_min_compatible_format`]).
@@ -142,7 +142,9 @@ impl Type {
/// [`Schema::calc_min_compatible_format`]: crate::spec::Schema::calc_min_compatible_format
pub(crate) fn min_format_version(&self) -> FormatVersion {
match self {
- Type::Primitive(PrimitiveType::TimestampNs | PrimitiveType::TimestamptzNs)
+ Type::Primitive(
+ PrimitiveType::Unknown | PrimitiveType::TimestampNs | PrimitiveType::TimestamptzNs,
+ )
| Type::Variant(_) => FormatVersion::V3,
_ => FormatVersion::V1,
}
@@ -273,6 +275,8 @@ pub enum PrimitiveType {
Fixed(u64),
/// Arbitrary-length byte array.
Binary,
+ /// Default / null column type used when a more specific type is not known.
+ Unknown,
}
impl PrimitiveType {
@@ -390,6 +394,7 @@ where S: Serializer {
impl fmt::Display for PrimitiveType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
+ PrimitiveType::Unknown => write!(f, "unknown"),
PrimitiveType::Boolean => write!(f, "boolean"),
PrimitiveType::Int => write!(f, "int"),
PrimitiveType::Long => write!(f, "long"),
@@ -596,12 +601,12 @@ impl TryFrom<SerdeNestedField> for NestedField {
fn try_from(value: SerdeNestedField) -> Result<Self> {
let initial_default = value
.initial_default
- .map(|x| Literal::try_from_json(x, &value.field_type))
+ .map(|default| Literal::try_from_json(default, &value.field_type))
.transpose()?
.flatten();
let write_default = value
.write_default
- .map(|x| Literal::try_from_json(x, &value.field_type))
+ .map(|default| Literal::try_from_json(default, &value.field_type))
.transpose()?
.flatten();
@@ -940,6 +945,7 @@ mod tests {
{
"type": "struct",
"fields": [
+ {"id": 17, "name": "unknown_field", "required": false, "type": "unknown"},
{"id": 1, "name": "bool_field", "required": true, "type": "boolean"},
{"id": 2, "name": "int_field", "required": true, "type": "int"},
{"id": 3, "name": "long_field", "required": true, "type": "long"},
@@ -964,6 +970,12 @@ mod tests {
record,
Type::Struct(StructType {
fields: vec![
+ NestedField::optional(
+ 17,
+ "unknown_field",
+ Type::Primitive(PrimitiveType::Unknown),
+ )
+ .into(),
NestedField::required(1, "bool_field", Type::Primitive(PrimitiveType::Boolean))
.into(),
NestedField::required(2, "int_field", Type::Primitive(PrimitiveType::Int))
@@ -1345,6 +1357,8 @@ mod tests {
for (ty, literal) in pairs {
assert!(ty.compatible(&literal));
}
+
+ assert!(!PrimitiveType::Unknown.compatible(&PrimitiveLiteral::Int(1)));
}
#[test]
diff --git a/crates/iceberg/src/spec/partition.rs b/crates/iceberg/src/spec/partition.rs
index 0fe573923..c79eaae63 100644
--- a/crates/iceberg/src/spec/partition.rs
+++ b/crates/iceberg/src/spec/partition.rs
@@ -25,7 +25,7 @@ use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;
use super::transform::Transform;
-use super::{NestedField, Schema, SchemaRef, StructType};
+use super::{NestedField, PrimitiveType, Schema, SchemaRef, StructType};
use crate::spec::Struct;
use crate::{Error, ErrorKind, Result};
@@ -103,8 +103,32 @@ impl PartitionSpec {
}
/// Returns the partition type of this partition spec.
+ /// If a source column is absent, preserves fixed transform result types and uses
+ /// unknown for result types that depend on the source type.
pub fn partition_type(&self, schema: &Schema) -> Result<StructType> {
- PartitionSpecBuilder::partition_type(&self.fields, schema)
+ let mut struct_fields = Vec::with_capacity(self.fields.len());
+ for partition_field in &self.fields {
+ let res_type = match schema.field_by_id(partition_field.source_id) {
+ Some(field) => partition_field.transform.result_type(&field.field_type)?,
+ // Historical specs may reference dropped source columns. Retain every
+ // field's position and any result type that is independent of its source.
+ None => match partition_field.transform {
+ Transform::Bucket(_) | Transform::Year | Transform::Month | Transform::Hour => {
+ PrimitiveType::Int.into()
+ }
+ Transform::Day => PrimitiveType::Date.into(),
+ Transform::Unknown => PrimitiveType::String.into(),
+ Transform::Identity | Transform::Truncate(_) | Transform::Void => {
+ PrimitiveType::Unknown.into()
+ }
+ },
+ };
+ struct_fields.push(
+ NestedField::optional(partition_field.field_id, &partition_field.name, res_type)
+ .into(),
+ );
+ }
+ Ok(StructType::new(struct_fields))
}
/// Convert to unbound partition spec
@@ -566,32 +590,6 @@ impl PartitionSpecBuilder {
Ok(bound_fields)
}
- /// Returns the partition type of this partition spec.
- fn partition_type(fields: &Vec<PartitionField>, schema: &Schema) -> Result<StructType> {
- let mut struct_fields = Vec::with_capacity(fields.len());
- for partition_field in fields {
- let field = schema
- .field_by_id(partition_field.source_id)
- .ok_or_else(|| {
- Error::new(
- // This should never occur as check_transform_compatibility
- // already ensures that the source field exists in the schema
- ErrorKind::Unexpected,
- format!(
- "No column with source column id {} in schema {:?}",
- partition_field.source_id, schema
- ),
- )
- })?;
- let res_type = partition_field.transform.result_type(&field.field_type)?;
- let field =
- NestedField::optional(partition_field.field_id, &partition_field.name, res_type)
- .into();
- struct_fields.push(field);
- }
- Ok(StructType::new(struct_fields))
- }
-
/// Ensure that the partition name is unique among columns in the schema.
/// Duplicate names are allowed if:
/// 1. The column is sourced from the column with the same name.
@@ -1055,7 +1053,7 @@ mod tests {
}
#[test]
- fn test_partition_error() {
+ fn test_partition_type_with_dropped_source_column() {
let spec = r#"
{
"spec-id": 1,
@@ -1087,7 +1085,73 @@ mod tests {
.build()
.unwrap();
- assert!(partition_spec.partition_type(&schema).is_err());
+ assert_eq!(
+ partition_spec.partition_type(&schema).unwrap(),
+ StructType::new(vec![
+ NestedField::optional(1000, "ts_day", PrimitiveType::Date.into()).into(),
+ NestedField::optional(1001, "id_bucket", PrimitiveType::Int.into()).into(),
+ NestedField::optional(1002, "id_truncate", PrimitiveType::String.into()).into(),
+ ])
+ );
+
+ // Dropping all sources must retain every partition field in its original position.
+ let empty_schema = Schema::builder().build().unwrap();
+ assert_eq!(
+ partition_spec.partition_type(&empty_schema).unwrap(),
+ StructType::new(vec![
+ NestedField::optional(1000, "ts_day", PrimitiveType::Date.into()).into(),
+ NestedField::optional(1001, "id_bucket", PrimitiveType::Int.into()).into(),
+ NestedField::optional(1002, "id_truncate", PrimitiveType::Unknown.into()).into(),
+ ])
+ );
+
+ // Missing sources must not suppress validation of transforms on remaining sources.
+ let incompatible_schema = Schema::builder()
+ .with_fields(vec![
+ NestedField::required(1, "id", PrimitiveType::Boolean.into()).into(),
+ ])
+ .build()
+ .unwrap();
+ let err = partition_spec
+ .partition_type(&incompatible_schema)
+ .unwrap_err();
+ assert_eq!(err.kind(), ErrorKind::DataInvalid);
+ assert_eq!(
+ err.message(),
+ "boolean is not a valid input type of bucket transform"
+ );
+ }
+
+ #[test]
+ fn test_partition_type_without_source_type() {
+ let schema = Schema::builder().build().unwrap();
+ for (transform, expected_type) in [
+ (Transform::Identity, PrimitiveType::Unknown),
+ (Transform::Truncate(4), PrimitiveType::Unknown),
+ (Transform::Void, PrimitiveType::Unknown),
+ (Transform::Bucket(16), PrimitiveType::Int),
+ (Transform::Year, PrimitiveType::Int),
+ (Transform::Month, PrimitiveType::Int),
+ (Transform::Day, PrimitiveType::Date),
+ (Transform::Hour, PrimitiveType::Int),
+ (Transform::Unknown, PrimitiveType::String),
+ ] {
+ let spec = PartitionSpec {
+ spec_id: 0,
+ fields: vec![PartitionField {
+ source_id: 1,
+ field_id: 1000,
+ name: "partition".to_string(),
+ transform,
+ }],
+ };
+ assert_eq!(
+ spec.partition_type(&schema).unwrap(),
+ StructType::new(vec![
+ NestedField::optional(1000, "partition", expected_type.into()).into(),
+ ])
+ );
+ }
}
#[test]
diff --git a/crates/iceberg/src/spec/schema/mod.rs b/crates/iceberg/src/spec/schema/mod.rs
index 35af6f0f8..a0197b82c 100644
--- a/crates/iceberg/src/spec/schema/mod.rs
+++ b/crates/iceberg/src/spec/schema/mod.rs
@@ -647,6 +647,17 @@ mod tests {
]);
assert_eq!(variant.calc_min_compatible_format(), FormatVersion::V3);
+ // Unknown is a v3-only primitive type.
+ let unknown = schema_with(vec![
+ NestedField::optional(1, "u", Primitive(PrimitiveType::Unknown)).into(),
+ ]);
+ assert_eq!(unknown.calc_min_compatible_format(), FormatVersion::V3);
+ assert!(
+ unknown
+ .check_format_compatibility(FormatVersion::V2)
+ .is_err()
+ );
+
// A v3-only type nested inside a list inside a struct → V3 (flattened fields).
let nested = schema_with(vec![
NestedField::required(
@@ -1475,4 +1486,153 @@ table {
.is_err()
);
}
+
+ #[test]
+ fn test_unknown_type_deserialization_rejects_non_null_default() {
+ let field_json = serde_json::json!({
+ "id": 1,
+ "name": "empty",
+ "required": false,
+ "type": "unknown",
+ "initial-default": 1
+ });
+
+ let error = serde_json::from_value::<NestedField>(field_json.clone()).unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("Unknown type only supports null default values"),
+ "unexpected error: {error}"
+ );
+
+ let schema_json = serde_json::json!({
+ "type": "struct",
+ "schema-id": 1,
+ "fields": [field_json]
+ });
+ assert!(serde_json::from_value::<Schema>(schema_json).is_err());
+ }
+
+ #[test]
+ fn test_unknown_type_deserialization_accepts_null_defaults() {
+ let schema_json = serde_json::json!({
+ "type": "struct",
+ "schema-id": 1,
+ "fields": [
+ {
+ "id": 1,
+ "name": "empty",
+ "required": false,
+ "type": "unknown",
+ "initial-default": null,
+ "write-default": null
+ }
+ ]
+ });
+
+ serde_json::from_value::<Schema>(schema_json).unwrap();
+ }
+
+ #[test]
+ fn test_unknown_type_accepts_null_container_defaults() {
+ let cases = [
+ (
+ "struct",
+ Struct(StructType::new(vec![
+ NestedField::optional(2, "empty", Primitive(PrimitiveType::Unknown)).into(),
+ ])),
+ Literal::Struct(crate::spec::Struct::from_iter([None])),
+ ),
+ (
+ "list",
+ List(ListType::new(
+ NestedField::list_element(2, Primitive(PrimitiveType::Unknown), false).into(),
+ )),
+ Literal::List(vec![None]),
+ ),
+ (
+ "map",
+ Map(MapType::optional(
+ 2,
+ Primitive(PrimitiveType::String),
+ 3,
+ Primitive(PrimitiveType::Unknown),
+ )),
+ Literal::Map(MapValue::from([(Literal::string("key"), None)])),
+ ),
+ ];
+
+ for (name, field_type, default) in cases {
+ let schema = Schema::builder()
+ .with_schema_id(1)
+ .with_fields(vec![
+ NestedField::optional(1, name, field_type)
+ .with_write_default(default)
+ .into(),
+ ])
+ .build()
+ .unwrap();
+ serde_json::to_value(schema).unwrap();
+ }
+ }
+
+ #[test]
+ fn test_unknown_type_deserialization_rejects_non_null_container_defaults() {
+ let cases = [
+ (
+ "struct",
+ serde_json::json!({
+ "type": "struct",
+ "fields": [{
+ "id": 2,
+ "name": "empty",
+ "required": false,
+ "type": "unknown"
+ }]
+ }),
+ serde_json::json!({"2": 1}),
+ ),
+ (
+ "list",
+ serde_json::json!({
+ "type": "list",
+ "element-id": 2,
+ "element-required": false,
+ "element": "unknown"
+ }),
+ serde_json::json!([1]),
+ ),
+ (
+ "map",
+ serde_json::json!({
+ "type": "map",
+ "key-id": 2,
+ "key": "string",
+ "value-id": 3,
+ "value-required": false,
+ "value": "unknown"
+ }),
+ serde_json::json!({"keys": ["key"], "values": [1]}),
+ ),
+ ];
+
+ for (name, field_type, default) in cases {
+ let schema_json = serde_json::json!({
+ "type": "struct",
+ "schema-id": 1,
+ "fields": [{
+ "id": 1,
+ "name": name,
+ "required": false,
+ "type": field_type,
+ "initial-default": default
+ }]
+ });
+
+ assert!(
+ serde_json::from_value::<Schema>(schema_json).is_err(),
+ "non-null unknown default in {name} should be rejected"
+ );
+ }
+ }
}
diff --git a/crates/iceberg/src/spec/table_metadata.rs b/crates/iceberg/src/spec/table_metadata.rs
index 2b9d1d140..84bb97a32 100644
--- a/crates/iceberg/src/spec/table_metadata.rs
+++ b/crates/iceberg/src/spec/table_metadata.rs
@@ -35,7 +35,7 @@ pub use super::table_metadata_builder::{TableMetadataBuildResult, TableMetadataB
use super::{
DEFAULT_PARTITION_SPEC_ID, PartitionSpecRef, PartitionStatisticsFile, Schema, SchemaId,
SchemaRef, SnapshotRef, SnapshotRetention, SortOrder, SortOrderRef, StatisticsFile, StructType,
- TableProperties,
+ TableProperties, Transform,
};
use crate::catalog::{METADATA_FOLDER_NAME, MetadataLocation};
use crate::compression::CompressionCodec;
@@ -565,8 +565,26 @@ impl TableMetadata {
Ok(self)
}
- /// If the default partition spec is not present in specs, add it
+ /// Validate active default-spec sources and add the spec if it is not present.
fn try_normalize_partition_spec(&mut self) -> Result<()> {
+ for field in self.default_spec.fields() {
+ // Historical specs may reference dropped columns, but active default-spec
+ // fields need a source for new writes. Void fields do not read their source.
+ if field.transform != Transform::Void
+ && self.current_schema().field_by_id(field.source_id).is_none()
+ {
+ return Err(Error::new(
+ ErrorKind::DataInvalid,
+ format!(
+ "Default partition spec {} references missing source field {} in current schema {}",
+ self.default_spec.spec_id(),
+ field.source_id,
+ self.current_schema_id
+ ),
+ ));
+ }
+ }
+
if self
.partition_spec_by_id(self.default_spec.spec_id())
.is_none()
@@ -3546,6 +3564,70 @@ mod tests {
assert_eq!(FormatVersion::V2, FormatVersion::V2);
}
+ #[test]
+ fn test_deserialize_default_partition_spec_with_dropped_source() {
+ for version in [1, 2, 3] {
+ for transform in ["identity", "truncate[4]", "bucket[16]"] {
+ let mut metadata = serde_json::json!({
+ "format-version": version,
+ "table-uuid": "9c12d441-03fe-4693-9a96-a0705ddf69c1",
+ "location": "s3://bucket/table",
+ "last-sequence-number": 0,
+ "last-updated-ms": 1602638573590_i64,
+ "last-column-id": 2,
+ "current-schema-id": 1,
+ "schemas": [
+ {
+ "schema-id": 0,
+ "type": "struct",
+ "fields": [
+ {"id": 1, "name": "x", "required": false, "type": "long"},
+ {"id": 2, "name": "y", "required": false, "type": "long"}
+ ]
+ },
+ {
+ "schema-id": 1,
+ "type": "struct",
+ "fields": [
+ {"id": 2, "name": "y", "required": false, "type": "long"}
+ ]
+ }
+ ],
+ "default-spec-id": 0,
+ "partition-specs": [{"spec-id": 0, "fields": [{
+ "source-id": 1, "field-id": 1000, "name": "x_partition",
+ "transform": transform
+ }]}],
+ "last-partition-id": 1000,
+ "default-sort-order-id": 0,
+ "sort-orders": [{"order-id": 0, "fields": []}],
+ "next-row-id": 0
+ });
+
+ // Retaining the source in history does not make it writable using
+ // the current schema and default spec.
+ let err = serde_json::from_value::<TableMetadata>(metadata.clone()).unwrap_err();
+ assert!(err.to_string().contains(
+ "Default partition spec 0 references missing source field 1 in current schema 1"
+ ));
+
+ // The same spec is allowed once it becomes historical.
+ metadata["partition-specs"]
+ .as_array_mut()
+ .unwrap()
+ .push(serde_json::json!({"spec-id": 1, "fields": []}));
+ metadata["default-spec-id"] = serde_json::json!(1);
+ serde_json::from_value::<TableMetadata>(metadata.clone()).unwrap();
+
+ // A voided field does not require its dropped source, even in the default spec.
+ metadata["default-spec-id"] = serde_json::json!(0);
+ metadata["partition-specs"][0]["fields"][0]["transform"] =
+ serde_json::json!("void");
+ serde_json::from_value::<TableMetadata>(metadata).unwrap();
+ }
+ }
+ }
+
#[test]
fn test_default_partition_spec() {
let default_spec_id = 1234;
diff --git a/crates/iceberg/src/spec/values/datum.rs b/crates/iceberg/src/spec/values/datum.rs
index d5eccd832..289002906 100644
--- a/crates/iceberg/src/spec/values/datum.rs
+++ b/crates/iceberg/src/spec/values/datum.rs
@@ -368,6 +368,12 @@ impl Datum {
/// See [this spec](https://iceberg.apache.org/spec/#binary-single-value-serialization) for reference.
pub fn try_from_bytes(bytes: &[u8], data_type: PrimitiveType) -> Result<Self> {
let literal = match data_type {
+ PrimitiveType::Unknown => {
+ return Err(Error::new(
+ ErrorKind::FeatureUnsupported,
+ "Cannot create datum for unknown type from bytes",
+ ));
+ }
PrimitiveType::Boolean => {
if bytes.len() == 1 && bytes[0] == 0u8 {
PrimitiveLiteral::Boolean(false)
diff --git a/crates/iceberg/src/spec/values/literal.rs b/crates/iceberg/src/spec/values/literal.rs
index 194b1c3b9..63d6c1aee 100644
--- a/crates/iceberg/src/spec/values/literal.rs
+++ b/crates/iceberg/src/spec/values/literal.rs
@@ -547,6 +547,10 @@ impl Literal {
decimal_mantissa(&rescaled),
))))
}
+ (PrimitiveType::Unknown, value) if !value.is_null() => Err(Error::new(
+ ErrorKind::DataInvalid,
+ "Unknown type only supports null default values",
+ )),
(_, JsonValue::Null) => Ok(None),
(i, j) => Err(Error::new(
ErrorKind::DataInvalid,
@@ -555,20 +559,15 @@ impl Literal {
},
Type::Struct(schema) => {
if let JsonValue::Object(mut object) = value {
- Ok(Some(Literal::Struct(Struct::from_iter(
- schema.fields().iter().map(|field| {
- object.remove(&field.id.to_string()).and_then(|value| {
- Literal::try_from_json(value, &field.field_type)
- .and_then(|value| {
- value.ok_or(Error::new(
- ErrorKind::DataInvalid,
- "Key of map cannot be null",
- ))
- })
- .ok()
- })
- }),
- ))))
+ let values = schema
+ .fields()
+ .iter()
+ .map(|field| match object.remove(&field.id.to_string()) {
+ Some(value) => Literal::try_from_json(value, &field.field_type),
+ None => Ok(None),
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Ok(Some(Literal::Struct(Struct::from_iter(values))))
} else {
Err(Error::new(
ErrorKind::DataInvalid,
diff --git a/crates/iceberg/src/spec/values/tests.rs b/crates/iceberg/src/spec/values/tests.rs
index 1d716a48d..97b2f6b32 100644
--- a/crates/iceberg/src/spec/values/tests.rs
+++ b/crates/iceberg/src/spec/values/tests.rs
@@ -342,6 +342,23 @@ fn json_fixed() {
);
}
+#[test]
+fn json_unknown_only_accepts_null() {
+ let unknown = Primitive(PrimitiveType::Unknown);
+
+ assert_eq!(
+ Literal::try_from_json(JsonValue::Null, &unknown).unwrap(),
+ None
+ );
+ let error = Literal::try_from_json(serde_json::json!(1), &unknown).unwrap_err();
+ assert_eq!(error.kind(), ErrorKind::DataInvalid);
+ assert!(
+ error
+ .message()
+ .contains("Unknown type only supports null default values")
+ );
+}
+
#[test]
fn test_should_parse_json_binary_if_hex_uses_uppercase_digits() {
let result = Literal::try_from_json(