Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(postgres): align read schema to the columns actually returned (#81894)

Tom Owerse4f5877579d4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
index f5f9ee0cd511..fa5ee5f8f0d6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/arrow_utils.py
@@ -580,6 +580,23 @@ def table_from_py_list(table_data: list[Any], schema: Optional[pa.Schema] = None
return table_from_iterator(iter(table_data), schema=schema)
+def restrict_schema_to_columns(schema: pa.Schema, column_names: Sequence[str]) -> pa.Schema:
+ """Drop fields from `schema` that aren't among `column_names`.
+
+ `pa.Table.from_pydict` raises an opaque KeyError ("The passed mapping doesn't contain the
+ following field(s) of the schema: ...") when the provided schema declares a column the row
+ mapping lacks. A SQL source builds its Arrow schema from columns discovered during setup, but
+ the streaming read can return a strict subset — e.g. a column dropped at the source, or the
+ table recreated with a narrower shape, between discovery and the read. Restricting the schema
+ to the columns the query actually returned lets the batch build; extra columns present in the
+ rows but not the schema are still handled by `_process_batch`, which appends them.
+ """
+ present = set(column_names)
+ if all(name in present for name in schema.names):
+ return schema
+ return pa.schema([field for field in schema if field.name in present])
+
+
def build_pyarrow_decimal_type(precision: int, scale: int) -> pa.Decimal128Type | pa.Decimal256Type:
if precision <= 38:
return pa.decimal128(precision, scale)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
index 80891e4651f7..0f326aa5f0e6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_utils.py
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
observe_and_project_table,
observed_schema_metadata_columns,
raise_on_nullability_drift,
+ restrict_schema_to_columns,
source_uses_delta_write_column_selection,
table_from_py_list,
)
@@ -339,6 +340,31 @@ def test_table_from_py_list_schema_missing_temporal_column(value, expected_type)
assert table.column("ts").to_pylist() == [value]
+def test_restrict_schema_to_columns_drops_fields_absent_from_the_read():
+ # A SQL source's discovered schema can declare a column the streaming read no longer returns
+ # (dropped at the source, or the table recreated with a narrower shape, between discovery and
+ # the read). `from_pydict` crashes with an opaque KeyError in that case, so the read path first
+ # restricts the schema to the columns it actually got back.
+ schema = pa.schema(
+ cast(Any, [pa.field("id", pa.int64()), pa.field("name", pa.string()), pa.field("dropped", pa.string())])
+ )
+ rows = [{"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
+
+ with pytest.raises(KeyError):
+ table_from_py_list(rows, schema)
+
+ restricted = restrict_schema_to_columns(schema, ["id", "name"])
+ assert restricted.names == ["id", "name"]
+ assert restricted.field("id").type == pa.int64()
+
+ table = table_from_py_list(rows, restricted)
+ assert table.schema.names == ["id", "name"]
+ assert table.column("id").to_pylist() == [1, 2]
+
+ # When every schema field is present the schema is returned unchanged (common case).
+ assert restrict_schema_to_columns(restricted, ["id", "name"]) is restricted
+
+
@pytest.mark.parametrize(
"error_msg, large_type, values",
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py
index 9dbf3cedc262..c133f2102223 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/partitioned_tables.py
@@ -14,6 +14,7 @@ from structlog.types import FilteringBoundLogger
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
QueryTimeoutException,
+ restrict_schema_to_columns,
table_from_iterator,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import (
@@ -440,12 +441,13 @@ def iterate_date_windows(
logger.debug(f"window query lo={lo} hi={hi}: {query.as_string()}")
cur.execute(query)
columns = [c.name for c in cur.description or []]
+ window_schema = restrict_schema_to_columns(arrow_schema, columns)
while True:
rows = cur.fetchmany(chunk_size)
if not rows:
break
rows_this_window += len(rows)
- yield table_from_iterator((dict(zip(columns, r)) for r in rows), arrow_schema)
+ yield table_from_iterator((dict(zip(columns, r)) for r in rows), window_schema)
except psycopg.errors.QueryCanceled:
qc_retries += 1
if qc_retries > WINDOW_MAX_QUERY_CANCELED_RETRIES or window <= min_window:
@@ -626,12 +628,13 @@ def iterate_partitions(
logger.debug(f"partition query {child.schema}.{child.name}: {query.as_string()}")
cur.execute(query)
columns = [c.name for c in cur.description or []]
+ partition_schema = restrict_schema_to_columns(arrow_schema, columns)
while True:
rows = cur.fetchmany(chunk_size)
if not rows:
break
rows_this_partition += len(rows)
- yield table_from_iterator((dict(zip(columns, r)) for r in rows), arrow_schema)
+ yield table_from_iterator((dict(zip(columns, r)) for r in rows), partition_schema)
elapsed = clock() - p_start
total_rows += rows_this_partition
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 771c475dd0af..df8f29b480ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -45,6 +45,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
QueryTimeoutException,
TemporaryFileSizeExceedsLimitException,
build_pyarrow_decimal_type,
+ restrict_schema_to_columns,
table_from_iterator,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import (
@@ -3524,7 +3525,10 @@ def postgres_source(
offset += len(rows)
- yield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)
+ yield table_from_iterator(
+ (dict(zip(column_names, row)) for row in rows),
+ restrict_schema_to_columns(arrow_schema, column_names),
+ )
successive_errors = 0
successive_conn_errors = 0
@@ -3723,6 +3727,7 @@ def postgres_source(
cursor.execute(query)
column_names = [column.name for column in cursor.description or []]
+ read_schema = restrict_schema_to_columns(arrow_schema, column_names)
while True:
rows = cursor.fetchmany(chunk_size)
@@ -3731,7 +3736,7 @@ def postgres_source(
dicts = [dict(zip(column_names, row)) for row in rows]
del rows
- yield table_from_iterator(iter(dicts), arrow_schema)
+ yield table_from_iterator(iter(dicts), read_schema)
offset += len(dicts)
return
except psycopg.errors.SerializationFailure as e: