Skip to content

fix: preserve Arrow field metadata in element_at, GetStructField, and CreateNamedStruct - #7774

Open
samarkumar4355 wants to merge 1 commit into
apache:mainfrom
samarkumar4355:fix/issue-7769-preserve-field-metadata
Open

samarkumar4355 wants to merge 1 commit into
apache:mainfrom
samarkumar4355:fix/issue-7769-preserve-field-metadata

Conversation

@samarkumar4355

Copy link
Copy Markdown

Which issue does this PR close?

Closes #7769

Rationale for this change

ListExtract, SparkMapExtract, GetStructField, and CreateNamedStruct were dropping Arrow field metadata (including Arrow extension types such as VariantType) because they relied on DataFusion's default PhysicalExpr::return_field / ScalarUDFImpl::return_field_from_args or rebuilt Field::new(...) from data_type + nullable. Additionally, PhysicalPlanner::create_scalar_function_expr reconstructed arg_fields and the output Field from DataTypes, stripping metadata for scalar UDFs like map_extract.

What changes are included in this PR?

  • ListExtract (native/spark-expr/src/array_funcs/list_extract.rs): Updated child_field to use return_field and overrode PhysicalExpr::return_field to preserve the inner element field's metadata.
  • SparkMapExtract (native/spark-expr/src/map_funcs/map_extract.rs): Overrode ScalarUDFImpl::return_field_from_args to preserve the map value field's metadata.
  • GetStructField (native/spark-expr/src/struct_funcs/get_struct_field.rs): Updated child_field to use return_field and overrode PhysicalExpr::return_field to preserve the child struct field's metadata.
  • CreateNamedStruct (native/spark-expr/src/struct_funcs/create_named_struct.rs): Updated fields() to use expr.return_field(schema)? with .with_name(name) instead of Field::new(...).
  • PhysicalPlanner::create_scalar_function_expr (native/core/src/execution/planner.rs): Propagated input return_fields into arg_fields and preserved the FieldRef returned by return_field_from_args on ScalarFunctionExpr.

(Note: Under ANSI mode with nullable array/map operands, CometElementAt.needsNullGuard wraps ListExtract/map_extract in CaseWhenExpr, which still uses the default return_field. Leaving CaseWhenExpr out of this PR to keep scope focused; happy to follow up if desired.)

How are these changes tested?

Added unit tests covering all 4 expressions and end-to-end planner integration (map_extract_preserves_field_metadata_through_planner).

Before fix (4 reproduction tests failing with empty metadata {})
running 4 tests
test struct_funcs::get_struct_field::tests::get_struct_field_preserves_field_metadata ... FAILED
test map_funcs::map_extract::tests::map_extract_preserves_field_metadata ... FAILED
test struct_funcs::create_named_struct::test::test_create_struct_preserves_field_metadata ... FAILED
test array_funcs::list_extract::test::test_list_extract_preserves_field_metadata ... FAILED

test result: FAILED. 0 passed; 4 failed; 0 ignored; 0 measured; 1395 filtered out
After fix (all unit tests, planner tests, fmt, and clippy passing)
  • cargo test -p datafusion-comet-spark-expr --lib preserves_field_metadata: 4 passed; 0 failed
  • cargo test -p datafusion-comet --lib preserves_field_metadata: 3 passed; 0 failed
  • cargo test -p datafusion-comet --lib execution::planner::tests: 81 passed; 0 failed
  • cargo fmt --check: passed
  • cargo clippy -p datafusion-comet-spark-expr -p datafusion-comet --tests: passed

@samarkumar4355 samarkumar4355 changed the title fix: preserve Arrow field metadata in ListExtract, SparkMapExtract, G… fix: preserve Arrow field metadata in element_at, GetStructField, and CreateNamedStruct Nov 27, 2026

@comphead comphead left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return_field overrides on ListExtract, GetStructField and SparkMapExtract and the with_name rebuild in CreateNamedStruct are the right shape and use DataFusion's return_field and return_field_from_args as the metadata carrier. Three things need work. The child_field changes in ListExtract and GetStructField add per-batch work and are not needed. The planner change reaches every scalar function and is also not needed for map_extract. And #7769 names GetArrayStructFields, which this PR does not touch and does not test, yet the PR closes the issue. By my reading its item field already keeps metadata through data_type (child_field returns fields[ordinal]), so a test that pins this would let the issue close, otherwise it should stay open. Rust unit tests are the right place for these, since CometExecRule.tryConvertToComet falls back for any operator whose output or children contain VariantType, so no SQL file test can reach this metadata. CI here is only the fork status, so I did not see the tests run.

fn child_field(&self, input_schema: &Schema) -> DataFusionResult<FieldRef> {
match self.child.data_type(input_schema)? {
DataType::List(field) | DataType::LargeList(field) => Ok(field),
match self.child.return_field(input_schema)?.data_type() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

child_field now calls self.child.return_field(...) only to read the data type. The item field with its metadata already sits inside DataType::List(field), so self.child.data_type(input_schema) returned the same FieldRef before this change and the new return_field override is the only change needed. This also costs time on every batch. evaluate calls self.data_type(&batch.schema()), which now reaches the child's return_field, and the default PhysicalExpr::return_field does format!("{self}") and allocates a Field. Could child_field go back to data_type?

fn child_field(&self, input_schema: &Schema) -> DataFusionResult<Arc<Field>> {
match self.child.data_type(input_schema)? {
fn child_field(&self, input_schema: &Schema) -> DataFusionResult<FieldRef> {
match self.child.return_field(input_schema)?.data_type() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as in ListExtract::child_field. DataType::Struct(fields) already carries each field with its metadata, so self.child.data_type(input_schema) gave the same field. Only the return_field override is needed.

let nullable = expr.nullable(schema)?;
Ok(Field::new(name, data_type, nullable))
})
.map(|(expr, name)| Ok(expr.return_field(schema)?.as_ref().clone().with_name(name)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fields is also called from evaluate (line 80), so every batch now calls return_field on every child. For a Column that is a schema lookup, but a child that relies on the default PhysicalExpr::return_field formats the expression and allocates a field on each batch. Separately, this copies the child's whole metadata map into the struct field, not only the ARROW:extension:* keys. A source column that carries PARQUET:field_id (Iceberg or field-id Parquet reads) now gives a DataType::Struct whose child field differs from one built over a different source column. Field equality includes metadata and arrow's zip requires equal data types, so I wonder whether a CASE WHEN or IF over two such named_struct values can now fail. I did not run this. Could you add a test with field-id metadata on the child and decide whether only the extension keys should be carried?

Comment thread native/core/src/execution/planner.rs Outdated
Comment on lines +2272 to +2287
let arg_fields: Vec<_> = input_expr_fields
.iter()
.zip(&coerced_types)
.enumerate()
.map(|(i, dt)| Arc::new(Field::new(format!("arg{i}"), dt.clone(), true)))
.map(|(i, (f, dt))| {
if f.data_type() == dt {
Arc::new(
f.as_ref()
.clone()
.with_name(format!("arg{i}"))
.with_nullable(true),
)
} else {
Arc::new(Field::new(format!("arg{i}"), dt.clone(), true))
}
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Propagating the argument fields (input_expr_fields, this rebuild, and the matching one in the fields_with_udf branch) is not needed for map_extract. SparkMapExtract::return_field_from_args reads the value field out of map_field.data_type(), and its coerce_types returns the map type unchanged, so the metadata already reached it through the old Field::new("argN", dt, true) fields. What was lost was the FieldRef it returned, and keeping that (return_field below) is the fix. As written this applies to every scalar function in the planner. For example spark_array_slice::return_field_from_args returns Arc::clone(&args.arg_fields[0]), so a derived column now takes the input column's top-level metadata, including PARQUET:field_id. I did not run this. Could the argument plumbing be dropped and only the returned FieldRef kept? That also removes the duplicated clone().with_name(format!("arg{i}")).with_nullable(true) blocks.

}

#[test]
fn map_extract_preserves_field_metadata_through_planner() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The composed CreateNamedStruct half of this test repeats get_struct_field_preserves_field_metadata, test_list_extract_preserves_field_metadata and test_create_struct_preserves_field_metadata with about 100 lines of extra setup. The part the unit tests cannot cover is the planner path for map_extract, meaning the FieldRef kept from return_field_from_args with both values of null_short_circuit. Could this shrink to map_extract alone?

@samarkumar4355
samarkumar4355 force-pushed the fix/issue-7769-preserve-field-metadata branch from 26bcc7a to 505f46a Compare December 1, 2026 22:10
@samarkumar4355

Copy link
Copy Markdown
Author

@comphead,
ListExtract and GetStructField use data_type() again to locate the nested fields.
Their return_field() overrides preserve the metadata on those fields.

CreateNamedStruct filters child metadata to ARROW:extension:* and reuses the filtered fields across batches with the same schema. The regression verifies that zip accepts structs built from columns with different Parquet field IDs and that the extension metadata survives.

The planner builds argN fields from the argument types and carries the UDF’s returned field into ScalarFunctionExpr.
The focused map_extract test uses an ANSI cast to cover both the direct path and the NullShortCircuit wrapper.

The GetArrayStructFields test verifies extension metadata on the list element in both the declared output field and the evaluated array.

@james-willis

Copy link
Copy Markdown
Contributor

Thanks for taking this on. I want to raise a policy point because DataFusion settled the same question upstream in the last two weeks and I'd like Comet to land on the same rule rather than carry its own.

DataFusion handles struct arms that differ only in nested metadata at the coercion layer, not at the constructor. apache/datafusion#27536 (in DataFusion 57) reconciles struct child fields during type coercion with coerced_fields_metadata, merging metadata by field name (earlier input wins per key, extension name and parameters kept together, differing extension names a planning error), then casts the arms to the merged type. apache/datafusion#27502 builds on that: named_struct keeps each child field whole and make_array merges its item field with coerced_fields_metadata. No DataFusion constructor filters metadata keys, so PARQUET:field_id and friends stay on struct children there (maybe this should be changed in datafusion!).

Comet has its own version of that coercion step: create_case_when and create_if_expr in case_when.rs run merge_branch_types over the arm types and coerce_branch casts any arm whose type differs from the merged one. As far as I can tell, that already makes CASE WHEN p THEN struct(a) ELSE struct(b) END work for columns with different field ids, because the ELSE arm is cast to the THEN arm's struct type before zip sees it. The regression test here calls zip on the two evaluated structs directly, which is a path a planned query doesn't take. So I'd suggest CreateNamedStruct keep the child fields whole, as in your first revision but without the retain, matching named_struct.

What merge_branch_types does not yet do is merge nested metadata the way #27536 does (it keeps the left arm's field as is). I'll file an issue to switch it to coerced_fields_metadata once #7249 brings DataFusion 56 in, which is also what #7763 depends on. It covers the CaseWhenExpr half you mention in the description, so the ANSI null guard around element_at is handled there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:expressions Expression evaluation bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

element_at, struct field access and struct() drop the field metadata of their inputs, including Arrow extension types

3 participants