dabla commented on code in PR #76342:
URL: https://github.com/apache/airflow/pull/76342#discussion_r4648222143


##########
providers/apache/iceberg/src/airflow/providers/apache/iceberg/hooks/iceberg.py:
##########
@@ -165,6 +167,52 @@ def table_exists(self, table_name: str) -> bool:
         """Check whether a table exists in the catalog."""
         return self.catalog.table_exists(table_name)
 
+    def append(
+        self,
+        table_name: str,
+        records: list[dict[str, Any]] | pa.Table,
+        *,
+        retries: int = 8,
+    ) -> None:
+        """
+        Append rows to an Iceberg table.
+
+        ``records`` may be a list of dicts or a ``pyarrow.Table``. Dict keys 
that
+        are not in the table schema are dropped (same behaviour as
+        ``pa.Table.from_pylist(..., schema=table.schema().as_arrow())``).
+        Do not pass a ``RecordBatchReader``: it is consumed on the first 
attempt,
+        so a retry after ``CommitFailedException`` would append no rows.
+
+        On ``CommitFailedException`` the table is reloaded from the catalog and
+        the write is retried up to ``retries`` times. That covers a stale table
+        handle held across another writer's commit (pyiceberg's in-transaction
+        retry does not help that case, and is off when the table property
+        ``commit.retry.num-retries`` is ``0``).
+
+        :param table_name: Fully-qualified table name (``namespace.table``).
+        :param records: Rows to append.
+        :param retries: Total attempts including the first (must be >= 1).
+        """
+        if retries < 1:
+            raise ValueError("retries must be at least 1")
+
+        last_error: CommitFailedException | None = None
+        for _ in range(retries):

Review Comment:
   **[warning]** The retry loop stacks on pyiceberg's own retry, has no wait, 
and rewrites the data files on every attempt.
   
   Measured with every commit failing with `CommitFailedException` and the 
default `retries=8`:
   
   | | pyiceberg 0.8.0 | pyiceberg 0.12.0 |
   |---|---|---|
   | commit attempts | 8, back to back | 40 (pyiceberg retries 4 times per 
`table.append`, with backoff and a refresh, from `commit.retry.num-retries`) |
   | Parquet data files left in the warehouse | 8 | 8 |
   
   Three things follow:
   
   - On current pyiceberg the two loops multiply. `commit_transaction` already 
refreshes the table and rebuilds the snapshot between its attempts, so the 
outer loop mainly repeats the full data write.
   - On the versions without that retry there is no wait between attempts, so a 
writer that lost the race retries straight into the same contention.
   - Every failed attempt leaves its data file behind. With a large `pa.Table` 
and eight attempts that is eight copies of the payload for the user to clean up 
with orphan-file removal. The docs should at least say so.
   
   The docstring's reason, "a stale table handle held across another writer's 
commit", does not describe this code: the table is loaded inside the loop, so 
the hook never holds a handle across attempts. The window is only the duration 
of one write.
   
   Suggestion: keep the outer loop small (2 or 3 attempts), add a backoff and a 
warning log per retry, and name the parameter for what it counts 
(`max_attempts`, since `retries=1` means no retry at all). Or leave retrying to 
pyiceberg and the task's own `retries`, and only document the table properties.



##########
providers/apache/iceberg/src/airflow/providers/apache/iceberg/hooks/iceberg.py:
##########
@@ -165,6 +167,52 @@ def table_exists(self, table_name: str) -> bool:
         """Check whether a table exists in the catalog."""
         return self.catalog.table_exists(table_name)
 
+    def append(
+        self,
+        table_name: str,
+        records: list[dict[str, Any]] | pa.Table,
+        *,
+        retries: int = 8,
+    ) -> None:
+        """
+        Append rows to an Iceberg table.
+
+        ``records`` may be a list of dicts or a ``pyarrow.Table``. Dict keys 
that
+        are not in the table schema are dropped (same behaviour as
+        ``pa.Table.from_pylist(..., schema=table.schema().as_arrow())``).
+        Do not pass a ``RecordBatchReader``: it is consumed on the first 
attempt,
+        so a retry after ``CommitFailedException`` would append no rows.
+
+        On ``CommitFailedException`` the table is reloaded from the catalog and
+        the write is retried up to ``retries`` times. That covers a stale table
+        handle held across another writer's commit (pyiceberg's in-transaction
+        retry does not help that case, and is off when the table property
+        ``commit.retry.num-retries`` is ``0``).
+
+        :param table_name: Fully-qualified table name (``namespace.table``).
+        :param records: Rows to append.
+        :param retries: Total attempts including the first (must be >= 1).
+        """
+        if retries < 1:
+            raise ValueError("retries must be at least 1")
+
+        last_error: CommitFailedException | None = None
+        for _ in range(retries):
+            table = self.load_table(table_name)
+            arrow_schema = table.schema().as_arrow()
+            if isinstance(records, pa.Table):
+                arrow = records.select(
+                    [name for name in records.column_names if name in 
arrow_schema.names]
+                ).cast(arrow_schema)

Review Comment:
   **[warning]** The `pa.Table` branch does not align the schema the way the 
`list[dict]` branch does.
   
   `Table.cast` requires the same field names in the same order, so after the 
`select` only tables that already match are accepted. Same table as above, 
pyarrow 16.1.0 and 26.0.1:
   
   | Input | `list[dict]` | `pa.Table` |
   |---|---|---|
   | columns in another order | written | `ValueError: Target schema's field 
names are not matching the table's field names: ['name', 'id'], ['id', 'name']` 
|
   | optional column `name` left out | written as null | same `ValueError` |
   | extra column | dropped | dropped |
   
   The PR description says both inputs are schema-aligned. Either build the 
aligned table by name (select the schema's fields in schema order, add nulls 
for missing optional ones) or narrow the docstring to "a `pa.Table` must match 
the table schema apart from extra columns".
   
   The unit tests cannot see this: `table.schema()` and `table.append` are 
mocked, and the `pa.Table` test passes columns that are already in schema 
order. One test against a real catalog (`SqlCatalog` on SQLite in `tmp_path`, 
as in the demo repository linked from the issue) would cover this and comment 
[4].



##########
providers/apache/iceberg/src/airflow/providers/apache/iceberg/hooks/iceberg.py:
##########
@@ -165,6 +167,52 @@ def table_exists(self, table_name: str) -> bool:
         """Check whether a table exists in the catalog."""
         return self.catalog.table_exists(table_name)
 
+    def append(
+        self,
+        table_name: str,
+        records: list[dict[str, Any]] | pa.Table,
+        *,
+        retries: int = 8,
+    ) -> None:
+        """
+        Append rows to an Iceberg table.
+
+        ``records`` may be a list of dicts or a ``pyarrow.Table``. Dict keys 
that
+        are not in the table schema are dropped (same behaviour as
+        ``pa.Table.from_pylist(..., schema=table.schema().as_arrow())``).

Review Comment:
   **[warning]** Dropping unknown keys silently turns a typo into a column of 
nulls.
   
   I ran this method's body against a SQLite catalog with a table `id: required 
long, name: optional string`. `append("demo.events", [{"id": 2, "nmae": "b"}])` 
succeeds and writes `{"id": 2, "name": None}`: no error, no log line. For a 
write path that is data loss the task reports as success ("Errors should never 
pass silently", [PEP 20](https://peps.python.org/pep-0020/)).
   
   Could unknown keys raise by default, with an explicit opt-in to drop them 
(and a log line naming the dropped keys when they are dropped)? A caller who 
wants the lenient behaviour then asks for it.



##########
providers/apache/iceberg/src/airflow/providers/apache/iceberg/hooks/iceberg.py:
##########
@@ -165,6 +167,52 @@ def table_exists(self, table_name: str) -> bool:
         """Check whether a table exists in the catalog."""
         return self.catalog.table_exists(table_name)
 
+    def append(
+        self,
+        table_name: str,
+        records: list[dict[str, Any]] | pa.Table,
+        *,
+        retries: int = 8,
+    ) -> None:
+        """
+        Append rows to an Iceberg table.
+
+        ``records`` may be a list of dicts or a ``pyarrow.Table``. Dict keys 
that
+        are not in the table schema are dropped (same behaviour as
+        ``pa.Table.from_pylist(..., schema=table.schema().as_arrow())``).
+        Do not pass a ``RecordBatchReader``: it is consumed on the first 
attempt,
+        so a retry after ``CommitFailedException`` would append no rows.
+
+        On ``CommitFailedException`` the table is reloaded from the catalog and
+        the write is retried up to ``retries`` times. That covers a stale table
+        handle held across another writer's commit (pyiceberg's in-transaction
+        retry does not help that case, and is off when the table property
+        ``commit.retry.num-retries`` is ``0``).
+
+        :param table_name: Fully-qualified table name (``namespace.table``).
+        :param records: Rows to append.
+        :param retries: Total attempts including the first (must be >= 1).
+        """
+        if retries < 1:
+            raise ValueError("retries must be at least 1")
+
+        last_error: CommitFailedException | None = None
+        for _ in range(retries):
+            table = self.load_table(table_name)
+            arrow_schema = table.schema().as_arrow()
+            if isinstance(records, pa.Table):
+                arrow = records.select(
+                    [name for name in records.column_names if name in 
arrow_schema.names]
+                ).cast(arrow_schema)
+            else:
+                arrow = pa.Table.from_pylist(records, schema=arrow_schema)

Review Comment:
   **[warning]** At the declared minimum versions a row without a required 
field is written with a made-up value.
   
   With `pyiceberg==0.8.0` and `pyarrow==16.1.0` (both floors in 
`pyproject.toml`), `append("demo.events", [{"name": "c"}])` on a table where 
`id` is `required long` succeeds and the scan returns `{"id": 0, "name": "c"}`. 
With pyarrow 26.0.1 the same call raises `ArrowInvalid: Column 'id' is declared 
non-nullable but contains nulls`.
   
   Since the method builds the Arrow table itself, it should check the rows 
against the required fields before `from_pylist` (or validate the built table), 
so the result does not depend on the installed pyarrow.



##########
providers/apache/iceberg/docs/connections.rst:
##########
@@ -66,6 +66,24 @@ Extra (Optional)
     For AWS/GCP/Azure deployments, prefer using IAM roles or environment-based
     credentials and pass only the ``warehouse`` path in extra.
 
+Appending rows

Review Comment:
   **[nit]** A usage section on the connection page is hard to find, and the 
class docstring still describes a read-only hook.
   
   "Appending rows" sits between the connection extras and "Migration from 
1.x". The class docstring of `IcebergHook` still reads "Provides catalog-level 
operations (list namespaces, list tables, load schemas)". Please mention the 
write there, and say in this section that the method is meant for small 
batches: the rows are held in memory and written again on every retry.



##########
providers/apache/iceberg/src/airflow/providers/apache/iceberg/hooks/iceberg.py:
##########
@@ -165,6 +167,52 @@ def table_exists(self, table_name: str) -> bool:
         """Check whether a table exists in the catalog."""
         return self.catalog.table_exists(table_name)
 
+    def append(
+        self,
+        table_name: str,
+        records: list[dict[str, Any]] | pa.Table,
+        *,
+        retries: int = 8,
+    ) -> None:
+        """
+        Append rows to an Iceberg table.
+
+        ``records`` may be a list of dicts or a ``pyarrow.Table``. Dict keys 
that
+        are not in the table schema are dropped (same behaviour as
+        ``pa.Table.from_pylist(..., schema=table.schema().as_arrow())``).
+        Do not pass a ``RecordBatchReader``: it is consumed on the first 
attempt,
+        so a retry after ``CommitFailedException`` would append no rows.
+
+        On ``CommitFailedException`` the table is reloaded from the catalog and
+        the write is retried up to ``retries`` times. That covers a stale table
+        handle held across another writer's commit (pyiceberg's in-transaction
+        retry does not help that case, and is off when the table property
+        ``commit.retry.num-retries`` is ``0``).
+
+        :param table_name: Fully-qualified table name (``namespace.table``).
+        :param records: Rows to append.
+        :param retries: Total attempts including the first (must be >= 1).
+        """
+        if retries < 1:
+            raise ValueError("retries must be at least 1")
+
+        last_error: CommitFailedException | None = None
+        for _ in range(retries):
+            table = self.load_table(table_name)
+            arrow_schema = table.schema().as_arrow()
+            if isinstance(records, pa.Table):
+                arrow = records.select(
+                    [name for name in records.column_names if name in 
arrow_schema.names]
+                ).cast(arrow_schema)
+            else:
+                arrow = pa.Table.from_pylist(records, schema=arrow_schema)
+            try:
+                table.append(arrow)
+                return
+            except CommitFailedException as error:
+                last_error = error
+        raise RuntimeError(f"append to {table_name} failed after {retries} 
attempts") from last_error

Review Comment:
   **[nit]** Re-raise the `CommitFailedException` instead of wrapping it in 
`RuntimeError`.
   
   A caller that wants to handle a write conflict (skip, reschedule, alert) has 
to catch `RuntimeError` and inspect `__cause__`. Letting the last 
`CommitFailedException` propagate keeps the type the docstring talks about; the 
attempt count fits in a log line.



##########
providers/apache/iceberg/tests/unit/apache/iceberg/hooks/test_iceberg.py:
##########
@@ -469,6 +471,94 @@ def test_get_snapshots_respects_limit(self):
         mock_arrow.slice.assert_called_once_with(offset=15, length=5)
 
 
+class TestIcebergHookAppend:
+    """Unit tests for IcebergHook.append (mocked catalog)."""
+
+    def test_append_dicts_aligns_schema_and_writes(self):
+        """list[dict] rows drop unknown keys and are written as a pyarrow 
Table."""
+        mock_schema = MagicMock()

Review Comment:
   **[nit]** `mock_schema = MagicMock()` has no spec, here and in the four 
tests below.
   
   The file's own helpers use `MagicMock(spec=Table)` and 
`MagicMock(spec=RestCatalog)`, and `AGENTS.md` asks for `spec`/`autospec`. 
`MagicMock(spec=Schema)` in a small `_make_mock_schema(arrow_schema)` helper 
would also remove the five copies of the same three lines.



-- 
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]

Reply via email to