rahulsmahadev commented on code in PR #4419:
URL: https://github.com/apache/iceberg-python/pull/4419#discussion_r4790991248


##########
pyiceberg/io/pyarrow.py:
##########
@@ -1314,6 +1334,176 @@ def pyarrow_to_schema(
         )
 
 
+def _has_any_field_ids(schema: pa.Schema) -> bool:
+    """Return whether any field in the schema, including nested ones, has a 
field ID."""
+    return any(_field_has_any_ids(field) for field in schema)
+
+
+def _field_has_any_ids(field: pa.Field) -> bool:
+    if _get_field_id(field) is not None:
+        return True
+    arrow_type = field.type
+    if pa.types.is_struct(arrow_type):
+        return any(_field_has_any_ids(arrow_type.field(i)) for i in 
range(arrow_type.num_fields))
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        return _field_has_any_ids(arrow_type.value_field)
+    elif isinstance(arrow_type, pa.MapType):
+        return _field_has_any_ids(arrow_type.key_field) or 
_field_has_any_ids(arrow_type.item_field)
+    return False
+
+
+def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema:
+    """Drop fields without a field ID, so only the columns with IDs are read.
+
+    A list is dropped when its element has no ID. A map is kept when its key or
+    value has an ID, including when only one side has one, matching Java's
+    PruneColumns.map; key and value are later matched by position. A struct
+    whose children all get dropped is dropped as well.
+    """
+    fields = [pruned for field in schema if (pruned := 
_prune_field_without_id(field)) is not None]
+    # Placeholders let _ConvertToIceberg convert a kept map whose key or value 
has no ID.
+    # Projection matches map key and value by position, not by these IDs.
+    ids = itertools.count(-1, -1)
+    fields = [_assign_missing_field_ids(field, ids) for field in fields]
+    return pa.schema(fields, metadata=schema.metadata)
+
+
+def _prune_field_without_id(field: pa.Field) -> pa.Field | None:
+    if _get_field_id(field) is None:
+        return None
+    pruned_type = _prune_type_without_ids(field.type)
+    if pruned_type is None:
+        return None
+    return field.with_type(pruned_type)
+
+
+def _prune_type_without_ids(arrow_type: pa.DataType) -> pa.DataType | None:
+    if pa.types.is_struct(arrow_type):
+        children = [arrow_type.field(i) for i in range(arrow_type.num_fields)]
+        pruned_children = [pruned for child in children if (pruned := 
_prune_field_without_id(child)) is not None]
+        return pa.struct(pruned_children) if pruned_children else None
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        element_field = _prune_field_without_id(arrow_type.value_field)
+        if element_field is None:
+            return None
+        if isinstance(arrow_type, pa.LargeListType):
+            return pa.large_list(element_field)
+        if isinstance(arrow_type, pa.FixedSizeListType):
+            return pa.list_(element_field, arrow_type.list_size)
+        return pa.list_(element_field)
+    elif isinstance(arrow_type, pa.MapType):
+        # Like Java's PruneColumns.map: keep the whole map when either child 
has any ID.
+        # TypeWithSchemaVisitor (and ArrowAccessor) later match key and value 
by position.
+        if not _field_has_any_ids(arrow_type.key_field) and not 
_field_has_any_ids(arrow_type.item_field):
+            return None
+        key_field = _keep_map_child(arrow_type.key_field)

Review Comment:
   When the key is a struct with an ID but some of its fields have none, a 
filtered scan aborts the Python process; main returns the rows:
   
   ```python
   # foo: map<struct<x: int, y: string>, int>, with IDs on foo, its key and x 
only
   tbl.scan(row_filter=NotNull("foo")).to_arrow()
   # main (with a name mapping): 2 rows; here: "Invalid: Map array keys array 
should have no nulls", then the process aborts
   ```
   
   One option would be to drop the map, as 0b2bc7af did, when its key is not a 
primitive and `_prune_type_without_ids` would remove some of the key's fields.



##########
pyiceberg/io/pyarrow.py:
##########
@@ -1884,8 +2074,13 @@ def _task_to_record_batches(
             downcast_ns_timestamp_to_us if downcast_ns_timestamp_to_us is not 
None else format_version <= 2
         )
         file_schema = pyarrow_to_schema(
-            physical_schema, name_mapping, 
downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, 
format_version=format_version
+            physical_schema,
+            name_mapping,
+            downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us,
+            format_version=format_version,
+            prune_fields_without_ids=True,
         )
+        file_schema = _align_map_key_value_ids(file_schema, table_schema)

Review Comment:
   `table_schema` is the current schema, so after the map is dropped, a 
time-travel read of an older snapshot can't replace the placeholder IDs:
   
   ```python
   # foo: map<string, int> with IDs on foo and its key only; then 
update_schema().delete_column("foo")
   tbl.scan(snapshot_id=old).to_arrow()
   # main (with a name mapping): [[('k', 1)], [], None]; here: ValueError: 
Could not find field with id: 4
   ```
   
   ```suggestion
           file_schema = _align_map_key_value_ids(file_schema, projected_schema)
   ```



##########
pyiceberg/io/pyarrow.py:
##########
@@ -1314,6 +1334,176 @@ def pyarrow_to_schema(
         )
 
 
+def _has_any_field_ids(schema: pa.Schema) -> bool:
+    """Return whether any field in the schema, including nested ones, has a 
field ID."""
+    return any(_field_has_any_ids(field) for field in schema)
+
+
+def _field_has_any_ids(field: pa.Field) -> bool:
+    if _get_field_id(field) is not None:
+        return True
+    arrow_type = field.type
+    if pa.types.is_struct(arrow_type):
+        return any(_field_has_any_ids(arrow_type.field(i)) for i in 
range(arrow_type.num_fields))
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        return _field_has_any_ids(arrow_type.value_field)
+    elif isinstance(arrow_type, pa.MapType):
+        return _field_has_any_ids(arrow_type.key_field) or 
_field_has_any_ids(arrow_type.item_field)
+    return False
+
+
+def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema:
+    """Drop fields without a field ID, so only the columns with IDs are read.
+
+    A list is dropped when its element has no ID. A map is kept when its key or
+    value has an ID, including when only one side has one, matching Java's
+    PruneColumns.map; key and value are later matched by position. A struct
+    whose children all get dropped is dropped as well.
+    """
+    fields = [pruned for field in schema if (pruned := 
_prune_field_without_id(field)) is not None]
+    # Placeholders let _ConvertToIceberg convert a kept map whose key or value 
has no ID.
+    # Projection matches map key and value by position, not by these IDs.
+    ids = itertools.count(-1, -1)
+    fields = [_assign_missing_field_ids(field, ids) for field in fields]
+    return pa.schema(fields, metadata=schema.metadata)
+
+
+def _prune_field_without_id(field: pa.Field) -> pa.Field | None:
+    if _get_field_id(field) is None:
+        return None
+    pruned_type = _prune_type_without_ids(field.type)
+    if pruned_type is None:
+        return None
+    return field.with_type(pruned_type)
+
+
+def _prune_type_without_ids(arrow_type: pa.DataType) -> pa.DataType | None:
+    if pa.types.is_struct(arrow_type):
+        children = [arrow_type.field(i) for i in range(arrow_type.num_fields)]
+        pruned_children = [pruned for child in children if (pruned := 
_prune_field_without_id(child)) is not None]
+        return pa.struct(pruned_children) if pruned_children else None
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        element_field = _prune_field_without_id(arrow_type.value_field)
+        if element_field is None:
+            return None
+        if isinstance(arrow_type, pa.LargeListType):
+            return pa.large_list(element_field)
+        if isinstance(arrow_type, pa.FixedSizeListType):
+            return pa.list_(element_field, arrow_type.list_size)
+        return pa.list_(element_field)
+    elif isinstance(arrow_type, pa.MapType):
+        # Like Java's PruneColumns.map: keep the whole map when either child 
has any ID.
+        # TypeWithSchemaVisitor (and ArrowAccessor) later match key and value 
by position.
+        if not _field_has_any_ids(arrow_type.key_field) and not 
_field_has_any_ids(arrow_type.item_field):
+            return None
+        key_field = _keep_map_child(arrow_type.key_field)
+        value_field = _keep_map_child(arrow_type.item_field)
+        return pa.map_(key_field, value_field, 
keys_sorted=arrow_type.keys_sorted)
+    return arrow_type
+
+
+def _keep_map_child(field: pa.Field) -> pa.Field:
+    """Keep a map key or value so the map can be matched by position.
+
+    If this side has an ID, still prune nested fields without one. If pruning
+    would drop the type, or this side itself has no ID, leave the field as-is;
+    missing IDs are filled in after the map is kept.
+    """
+    if _get_field_id(field) is None:
+        return field
+    pruned_type = _prune_type_without_ids(field.type)
+    if pruned_type is None:
+        return field
+    return field.with_type(pruned_type)
+
+
+def _assign_missing_field_ids(field: pa.Field, ids: Iterator[int]) -> pa.Field:
+    """Assign placeholder field IDs to any field that does not already have 
one."""
+    metadata = dict(field.metadata or {})
+    if _get_field_id(field) is None:
+        metadata[PYARROW_PARQUET_FIELD_ID_KEY] = str(next(ids)).encode()
+    new_type = _assign_missing_type_ids(field.type, ids)
+    return pa.field(field.name, new_type, nullable=field.nullable, 
metadata=metadata or None)
+
+
+def _assign_missing_type_ids(arrow_type: pa.DataType, ids: Iterator[int]) -> 
pa.DataType:
+    if pa.types.is_struct(arrow_type):
+        children = [_assign_missing_field_ids(arrow_type.field(i), ids) for i 
in range(arrow_type.num_fields)]
+        return pa.struct(children)
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        element_field = _assign_missing_field_ids(arrow_type.value_field, ids)
+        if isinstance(arrow_type, pa.LargeListType):
+            return pa.large_list(element_field)
+        if isinstance(arrow_type, pa.FixedSizeListType):
+            return pa.list_(element_field, arrow_type.list_size)
+        return pa.list_(element_field)
+    elif isinstance(arrow_type, pa.MapType):
+        key_field = _assign_missing_field_ids(arrow_type.key_field, ids)
+        value_field = _assign_missing_field_ids(arrow_type.item_field, ids)
+        return pa.map_(key_field, value_field, 
keys_sorted=arrow_type.keys_sorted)
+    return arrow_type
+
+
+def _align_map_key_value_ids(file_schema: Schema, table_schema: Schema) -> 
Schema:
+    """Match file map key/value IDs to the table schema by position.
+
+    Java's TypeWithSchemaVisitor pairs a file map's key and value with the 
table
+    map's key and value by position, not by field ID. After pruning, a file map
+    may have a placeholder ID on the side that had no field ID; rewriting those
+    IDs here lets projection and filters find the table fields on the file 
schema.
+    """
+    aligned = _align_iceberg_type(file_schema.as_struct(), 
table_schema.as_struct())
+    if not isinstance(aligned, StructType) or aligned == 
file_schema.as_struct():
+        return file_schema
+    return Schema(
+        *aligned.fields,
+        schema_id=file_schema.schema_id,
+        identifier_field_ids=list(file_schema.identifier_field_ids),
+    )
+
+
+def _align_iceberg_type(file_type: IcebergType, table_type: IcebergType) -> 
IcebergType:
+    if isinstance(file_type, MapType) and isinstance(table_type, MapType):
+        return MapType(
+            key_id=table_type.key_id,
+            key_type=_align_iceberg_type(file_type.key_type, 
table_type.key_type),
+            value_id=table_type.value_id,
+            value_type=_align_iceberg_type(file_type.value_type, 
table_type.value_type),
+            value_required=file_type.value_required,
+        )
+    if isinstance(file_type, ListType) and isinstance(table_type, ListType):
+        return ListType(
+            element_id=file_type.element_id,

Review Comment:
   When the kept side is a list without IDs, like the value of `map<string, 
list<int>>` with IDs on the map and its key only, the element keeps its 
placeholder and the read fails with `ValueError: Could not find field with id: 
5`, where main reads it with a name mapping. Taking the table's element ID for 
a placeholder fixes it:
   
   ```suggestion
               element_id=table_type.element_id if file_type.element_id < 0 
else file_type.element_id,
   ```



##########
pyiceberg/io/pyarrow.py:
##########
@@ -1314,6 +1334,176 @@ def pyarrow_to_schema(
         )
 
 
+def _has_any_field_ids(schema: pa.Schema) -> bool:
+    """Return whether any field in the schema, including nested ones, has a 
field ID."""
+    return any(_field_has_any_ids(field) for field in schema)
+
+
+def _field_has_any_ids(field: pa.Field) -> bool:
+    if _get_field_id(field) is not None:
+        return True
+    arrow_type = field.type
+    if pa.types.is_struct(arrow_type):
+        return any(_field_has_any_ids(arrow_type.field(i)) for i in 
range(arrow_type.num_fields))
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        return _field_has_any_ids(arrow_type.value_field)
+    elif isinstance(arrow_type, pa.MapType):
+        return _field_has_any_ids(arrow_type.key_field) or 
_field_has_any_ids(arrow_type.item_field)
+    return False
+
+
+def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema:
+    """Drop fields without a field ID, so only the columns with IDs are read.
+
+    A list is dropped when its element has no ID. A map is kept when its key or
+    value has an ID, including when only one side has one, matching Java's
+    PruneColumns.map; key and value are later matched by position. A struct
+    whose children all get dropped is dropped as well.
+    """
+    fields = [pruned for field in schema if (pruned := 
_prune_field_without_id(field)) is not None]
+    # Placeholders let _ConvertToIceberg convert a kept map whose key or value 
has no ID.
+    # Projection matches map key and value by position, not by these IDs.
+    ids = itertools.count(-1, -1)
+    fields = [_assign_missing_field_ids(field, ids) for field in fields]
+    return pa.schema(fields, metadata=schema.metadata)
+
+
+def _prune_field_without_id(field: pa.Field) -> pa.Field | None:
+    if _get_field_id(field) is None:
+        return None
+    pruned_type = _prune_type_without_ids(field.type)
+    if pruned_type is None:
+        return None
+    return field.with_type(pruned_type)
+
+
+def _prune_type_without_ids(arrow_type: pa.DataType) -> pa.DataType | None:
+    if pa.types.is_struct(arrow_type):
+        children = [arrow_type.field(i) for i in range(arrow_type.num_fields)]
+        pruned_children = [pruned for child in children if (pruned := 
_prune_field_without_id(child)) is not None]
+        return pa.struct(pruned_children) if pruned_children else None
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        element_field = _prune_field_without_id(arrow_type.value_field)
+        if element_field is None:
+            return None
+        if isinstance(arrow_type, pa.LargeListType):
+            return pa.large_list(element_field)
+        if isinstance(arrow_type, pa.FixedSizeListType):
+            return pa.list_(element_field, arrow_type.list_size)
+        return pa.list_(element_field)
+    elif isinstance(arrow_type, pa.MapType):
+        # Like Java's PruneColumns.map: keep the whole map when either child 
has any ID.
+        # TypeWithSchemaVisitor (and ArrowAccessor) later match key and value 
by position.
+        if not _field_has_any_ids(arrow_type.key_field) and not 
_field_has_any_ids(arrow_type.item_field):
+            return None
+        key_field = _keep_map_child(arrow_type.key_field)
+        value_field = _keep_map_child(arrow_type.item_field)
+        return pa.map_(key_field, value_field, 
keys_sorted=arrow_type.keys_sorted)
+    return arrow_type
+
+
+def _keep_map_child(field: pa.Field) -> pa.Field:
+    """Keep a map key or value so the map can be matched by position.
+
+    If this side has an ID, still prune nested fields without one. If pruning
+    would drop the type, or this side itself has no ID, leave the field as-is;
+    missing IDs are filled in after the map is kept.
+    """
+    if _get_field_id(field) is None:
+        return field
+    pruned_type = _prune_type_without_ids(field.type)
+    if pruned_type is None:
+        return field
+    return field.with_type(pruned_type)
+
+
+def _assign_missing_field_ids(field: pa.Field, ids: Iterator[int]) -> pa.Field:
+    """Assign placeholder field IDs to any field that does not already have 
one."""
+    metadata = dict(field.metadata or {})
+    if _get_field_id(field) is None:
+        metadata[PYARROW_PARQUET_FIELD_ID_KEY] = str(next(ids)).encode()
+    new_type = _assign_missing_type_ids(field.type, ids)
+    return pa.field(field.name, new_type, nullable=field.nullable, 
metadata=metadata or None)
+
+
+def _assign_missing_type_ids(arrow_type: pa.DataType, ids: Iterator[int]) -> 
pa.DataType:
+    if pa.types.is_struct(arrow_type):
+        children = [_assign_missing_field_ids(arrow_type.field(i), ids) for i 
in range(arrow_type.num_fields)]
+        return pa.struct(children)
+    elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, 
pa.FixedSizeListType)):
+        element_field = _assign_missing_field_ids(arrow_type.value_field, ids)
+        if isinstance(arrow_type, pa.LargeListType):
+            return pa.large_list(element_field)
+        if isinstance(arrow_type, pa.FixedSizeListType):
+            return pa.list_(element_field, arrow_type.list_size)
+        return pa.list_(element_field)
+    elif isinstance(arrow_type, pa.MapType):
+        key_field = _assign_missing_field_ids(arrow_type.key_field, ids)
+        value_field = _assign_missing_field_ids(arrow_type.item_field, ids)
+        return pa.map_(key_field, value_field, 
keys_sorted=arrow_type.keys_sorted)
+    return arrow_type
+
+
+def _align_map_key_value_ids(file_schema: Schema, table_schema: Schema) -> 
Schema:
+    """Match file map key/value IDs to the table schema by position.
+
+    Java's TypeWithSchemaVisitor pairs a file map's key and value with the 
table
+    map's key and value by position, not by field ID. After pruning, a file map
+    may have a placeholder ID on the side that had no field ID; rewriting those
+    IDs here lets projection and filters find the table fields on the file 
schema.
+    """
+    aligned = _align_iceberg_type(file_schema.as_struct(), 
table_schema.as_struct())
+    if not isinstance(aligned, StructType) or aligned == 
file_schema.as_struct():
+        return file_schema
+    return Schema(
+        *aligned.fields,
+        schema_id=file_schema.schema_id,
+        identifier_field_ids=list(file_schema.identifier_field_ids),
+    )
+
+
+def _align_iceberg_type(file_type: IcebergType, table_type: IcebergType) -> 
IcebergType:
+    if isinstance(file_type, MapType) and isinstance(table_type, MapType):
+        return MapType(
+            key_id=table_type.key_id,

Review Comment:
   This also replaces IDs the file has. For a file with IDs on every field 
whose map key and value IDs (30, 40) aren't the table's (3, 4), main reads the 
map as null, while here it is read by position, and with a string value under 
an int column the scan now raises `ResolveError: Cannot promote an string to 
int`. Replacing only placeholders keeps such files as before, as the 
description says:
   
   ```suggestion
               key_id=table_type.key_id if file_type.key_id < 0 else 
file_type.key_id,
   ```
   
   and the same for `value_id`.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to