You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@fluss.apache.org by "zuston (via GitHub)" <gi...@apache.org> on 2026/08/10 14:20:41 UTC

[PR] [rust] add support of iceberg format key encoder [fluss]

zuston opened a new pull request, #3934:
URL: https://github.com/apache/fluss/pull/3934

   ### Purpose
   
   add support of iceberg format key encoder
   
   ### Brief change log
   
   
   ### Tests
   
   <!-- List UT and IT cases to verify this change -->
   
   ### API and Format
   
   <!-- Does this change affect API or storage format -->
   
   ### Documentation
   
   <!-- Does this change introduce a new feature -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [rust] add support of iceberg format key encoder [fluss]

Posted by "zuston (via GitHub)" <gi...@apache.org>.
zuston commented on code in PR #3934:
URL: https://github.com/apache/fluss/pull/3934#discussion_r3758782303


##########
fluss-rust/crates/fluss/src/row/encode/iceberg_key_encoder.rs:
##########
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::Bytes;
+
+use crate::error::Error::IllegalArgument;
+use crate::error::Result;
+use crate::metadata::RowType;
+use crate::row::binary::{BinaryWriter, IcebergBinaryRowWriter, ValueWriter};
+use crate::row::encode::KeyEncoder;
+use crate::row::field_getter::FieldGetter;
+use crate::row::{Datum, InternalRow};
+
+/// Rust port of Java's `org.apache.fluss.row.encode.iceberg.IcebergKeyEncoder`.
+///
+/// Iceberg currently supports exactly one bucket key field. The field is
+/// encoded with Iceberg's single-value binary representation before being
+/// passed to the Iceberg bucketing function.
+pub struct IcebergKeyEncoder {
+    field_getter: FieldGetter,
+    field_encoder: ValueWriter,
+    writer: IcebergBinaryRowWriter,
+}
+
+impl IcebergKeyEncoder {
+    /// Construct an Iceberg key encoder for the single key in `keys`.
+    pub fn new(row_type: &RowType, keys: &[String]) -> Result<Self> {
+        if keys.len() != 1 {
+            return Err(IllegalArgument {
+                message: format!(
+                    "Key fields must have exactly one field for iceberg format, but got: {keys:?}"
+                ),
+            });
+        }
+
+        let key = &keys[0];
+        let index = row_type
+            .get_field_index(key)
+            .ok_or_else(|| IllegalArgument {
+                message: format!("Field {key:?} not found in input row type {row_type:?}"),
+            })?;
+        let data_type = row_type.fields()[index].data_type();
+
+        Ok(Self {
+            field_getter: FieldGetter::create(data_type, index),
+            field_encoder: IcebergBinaryRowWriter::create_value_writer(data_type)?,
+            writer: IcebergBinaryRowWriter::new(),
+        })
+    }
+}
+
+impl KeyEncoder for IcebergKeyEncoder {
+    fn encode_key(&mut self, row: &dyn InternalRow) -> Result<Bytes> {
+        self.writer.reset();
+
+        let datum = self.field_getter.get_field(row)?;
+        if datum == Datum::Null {
+            return Err(IllegalArgument {
+                message: "Iceberg key columns do not support null values".to_string(),
+            });
+        }
+        self.field_encoder
+            .write_value(&mut self.writer, 0, &datum)?;
+
+        Ok(self.writer.to_bytes())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::metadata::{DataType, DataTypes};
+    use crate::row::{Date, Decimal, GenericRow, Time, TimestampNtz};
+
+    fn encode(data_type: DataType, datum: Datum<'static>) -> Bytes {
+        let row_type = RowType::with_data_types_and_field_names(vec![data_type], vec!["key"]);
+        let mut encoder = IcebergKeyEncoder::new(&row_type, &["key".to_string()]).unwrap();
+        encoder
+            .encode_key(&GenericRow::from_data(vec![datum]))
+            .unwrap()
+    }
+
+    #[test]
+    fn rejects_key_counts_other_than_one() {
+        let row_type = RowType::with_data_types_and_field_names(
+            vec![DataTypes::int(), DataTypes::string()],
+            vec!["id", "name"],
+        );
+
+        for keys in [Vec::new(), vec!["id".to_string(), "name".to_string()]] {
+            let error = match IcebergKeyEncoder::new(&row_type, &keys) {
+                Ok(_) => panic!("expected IllegalArgument"),
+                Err(error) => error,
+            };
+            assert!(
+                error
+                    .to_string()
+                    .contains("Key fields must have exactly one field for iceberg format")
+            );
+        }
+    }
+
+    #[test]
+    fn rejects_missing_key_field() {
+        let row_type = RowType::with_data_types_and_field_names(vec![DataTypes::int()], vec!["id"]);
+        let error = match IcebergKeyEncoder::new(&row_type, &["missing".to_string()]) {
+            Ok(_) => panic!("expected IllegalArgument"),
+            Err(error) => error,
+        };
+        assert!(error.to_string().contains("not found in input row type"));
+    }
+
+    #[test]
+    fn encodes_values_with_iceberg_binary_layout() {

Review Comment:
   really insightful comment! updated  



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [rust] add support of iceberg format key encoder [fluss]

Posted by "zuston (via GitHub)" <gi...@apache.org>.
zuston commented on code in PR #3934:
URL: https://github.com/apache/fluss/pull/3934#discussion_r3758728021


##########
fluss-rust/crates/fluss/src/row/encode/mod.rs:
##########
@@ -111,9 +113,9 @@ impl KeyEncoderFactory {
             Some(DataLakeFormat::Lance) => Ok(Box::new(CompactedKeyEncoder::create_key_encoder(
                 row_type, key_fields,
             )?)),
-            Some(DataLakeFormat::Iceberg) => Err(Error::UnsupportedOperation {
-                message: "KeyEncoder for Iceberg format is not yet implemented".to_string(),
-            }),
+            Some(DataLakeFormat::Iceberg) => {

Review Comment:
   added



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [rust] add support of iceberg format key encoder [fluss]

Posted by "fresh-borzoni (via GitHub)" <gi...@apache.org>.
fresh-borzoni merged PR #3934:
URL: https://github.com/apache/fluss/pull/3934


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [rust] add support of iceberg format key encoder [fluss]

Posted by "fresh-borzoni (via GitHub)" <gi...@apache.org>.
fresh-borzoni commented on code in PR #3934:
URL: https://github.com/apache/fluss/pull/3934#discussion_r3754684755


##########
fluss-rust/crates/fluss/src/row/encode/mod.rs:
##########
@@ -111,9 +113,9 @@ impl KeyEncoderFactory {
             Some(DataLakeFormat::Lance) => Ok(Box::new(CompactedKeyEncoder::create_key_encoder(
                 row_type, key_fields,
             )?)),
-            Some(DataLakeFormat::Iceberg) => Err(Error::UnsupportedOperation {
-                message: "KeyEncoder for Iceberg format is not yet implemented".to_string(),
-            }),
+            Some(DataLakeFormat::Iceberg) => {

Review Comment:
   It seems append-only Iceberg tables bucket through here too.  Can you add an append IT then?



##########
fluss-rust/crates/fluss/src/row/encode/iceberg_key_encoder.rs:
##########
@@ -0,0 +1,210 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use bytes::Bytes;
+
+use crate::error::Error::IllegalArgument;
+use crate::error::Result;
+use crate::metadata::RowType;
+use crate::row::binary::{BinaryWriter, IcebergBinaryRowWriter, ValueWriter};
+use crate::row::encode::KeyEncoder;
+use crate::row::field_getter::FieldGetter;
+use crate::row::{Datum, InternalRow};
+
+/// Rust port of Java's `org.apache.fluss.row.encode.iceberg.IcebergKeyEncoder`.
+///
+/// Iceberg currently supports exactly one bucket key field. The field is
+/// encoded with Iceberg's single-value binary representation before being
+/// passed to the Iceberg bucketing function.
+pub struct IcebergKeyEncoder {
+    field_getter: FieldGetter,
+    field_encoder: ValueWriter,
+    writer: IcebergBinaryRowWriter,
+}
+
+impl IcebergKeyEncoder {
+    /// Construct an Iceberg key encoder for the single key in `keys`.
+    pub fn new(row_type: &RowType, keys: &[String]) -> Result<Self> {
+        if keys.len() != 1 {
+            return Err(IllegalArgument {
+                message: format!(
+                    "Key fields must have exactly one field for iceberg format, but got: {keys:?}"
+                ),
+            });
+        }
+
+        let key = &keys[0];
+        let index = row_type
+            .get_field_index(key)
+            .ok_or_else(|| IllegalArgument {
+                message: format!("Field {key:?} not found in input row type {row_type:?}"),
+            })?;
+        let data_type = row_type.fields()[index].data_type();
+
+        Ok(Self {
+            field_getter: FieldGetter::create(data_type, index),
+            field_encoder: IcebergBinaryRowWriter::create_value_writer(data_type)?,
+            writer: IcebergBinaryRowWriter::new(),
+        })
+    }
+}
+
+impl KeyEncoder for IcebergKeyEncoder {
+    fn encode_key(&mut self, row: &dyn InternalRow) -> Result<Bytes> {
+        self.writer.reset();
+
+        let datum = self.field_getter.get_field(row)?;
+        if datum == Datum::Null {
+            return Err(IllegalArgument {
+                message: "Iceberg key columns do not support null values".to_string(),
+            });
+        }
+        self.field_encoder
+            .write_value(&mut self.writer, 0, &datum)?;
+
+        Ok(self.writer.to_bytes())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::metadata::{DataType, DataTypes};
+    use crate::row::{Date, Decimal, GenericRow, Time, TimestampNtz};
+
+    fn encode(data_type: DataType, datum: Datum<'static>) -> Bytes {
+        let row_type = RowType::with_data_types_and_field_names(vec![data_type], vec!["key"]);
+        let mut encoder = IcebergKeyEncoder::new(&row_type, &["key".to_string()]).unwrap();
+        encoder
+            .encode_key(&GenericRow::from_data(vec![datum]))
+            .unwrap()
+    }
+
+    #[test]
+    fn rejects_key_counts_other_than_one() {
+        let row_type = RowType::with_data_types_and_field_names(
+            vec![DataTypes::int(), DataTypes::string()],
+            vec!["id", "name"],
+        );
+
+        for keys in [Vec::new(), vec!["id".to_string(), "name".to_string()]] {
+            let error = match IcebergKeyEncoder::new(&row_type, &keys) {
+                Ok(_) => panic!("expected IllegalArgument"),
+                Err(error) => error,
+            };
+            assert!(
+                error
+                    .to_string()
+                    .contains("Key fields must have exactly one field for iceberg format")
+            );
+        }
+    }
+
+    #[test]
+    fn rejects_missing_key_field() {
+        let row_type = RowType::with_data_types_and_field_names(vec![DataTypes::int()], vec!["id"]);
+        let error = match IcebergKeyEncoder::new(&row_type, &["missing".to_string()]) {
+            Ok(_) => panic!("expected IllegalArgument"),
+            Err(error) => error,
+        };
+        assert!(error.to_string().contains("not found in input row type"));
+    }
+
+    #[test]
+    fn encodes_values_with_iceberg_binary_layout() {

Review Comment:
   These check the bytes against values copied from our Java code, not from Iceberg — and the IT can't help since write and read share the encoder.
   
   Could you assert Iceberg's Appendix B hash vectors instead?  Run them through IcebergBucketingFunction with num_buckets = i32::MAX so the modulo cancels and you get the raw hash back. Negative ones need hash & i32::MAX accordingly.
   
   Let me know if you need more clarifications.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [rust] add support of iceberg format key encoder [fluss]

Posted by "zuston (via GitHub)" <gi...@apache.org>.
zuston commented on PR #3934:
URL: https://github.com/apache/fluss/pull/3934#issuecomment-5241588135

   could you help review this? @fresh-borzoni 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@fluss.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org