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(data-warehouse): remove three s3 reads from the batch path (#113089)

Tom Owers343654e55287
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py
index 1c746d69a92e..d3be830e0453 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_writer.py
@@ -45,6 +45,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.del
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import (
DeltaWriter,
+ _committed_file_count_change,
+ _committed_version,
_deltalite_write_stats,
_merge_predicate_ops,
commit_covers_batch,
@@ -1184,6 +1186,20 @@ class TestDeltaliteWritePath:
stats.helper = lambda: None # callable attribute must be ignored
assert _deltalite_write_stats(stats) == {"version": 7, "rows_inserted": 2, "files_added": 1}
+ def test_unreadable_post_commit_stats_are_ignored(self):
+ class UnreadableStats:
+ @property
+ def version(self) -> int:
+ raise RuntimeError("stats unavailable")
+
+ @property
+ def files_added(self) -> int:
+ raise RuntimeError("stats unavailable")
+
+ stats = UnreadableStats()
+ assert _committed_version(stats) is None
+ assert _committed_file_count_change(stats) is None
+
@pytest.mark.asyncio
async def test_writes_via_deltalite_when_enabled(self):
logger = make_logger() # captured so we can inspect the structured log without hitting the typed attr
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
index 9b20e5a228d7..0c3857d0be21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py
@@ -114,11 +114,26 @@ def _delta_table_identity(delta_table: deltalake.DeltaTable, table_ref: "DeltaTa
def _committed_version(stats: Any) -> int | None:
- """The table version a deltalite ``UpsertStats`` reports, or None from a double without one."""
- version = getattr(stats, "version", None)
+ """The table version a deltalite ``UpsertStats`` reports, or None when it cannot be read."""
+ try:
+ version = getattr(stats, "version", None)
+ except Exception: # noqa: BLE001 - stats are read after the write has committed
+ return None
return version if isinstance(version, int) else None
+def _committed_file_count_change(stats: Any) -> int | None:
+ """Files a deltalite commit added minus files it removed, or None when the stats cannot say."""
+ try:
+ added = getattr(stats, "files_added", None)
+ removed = getattr(stats, "files_removed", None)
+ except Exception: # noqa: BLE001 - stats are read after the write has committed
+ return None
+ if not isinstance(added, int) or not isinstance(removed, int):
+ return None
+ return added - removed
+
+
def _commit_metadata_layouts(commit: dict[str, Any]) -> list[dict[str, Any]]:
"""The places a commit's custom metadata can live: inlined onto the commit dict (delta-rs 1.x)
or nested under `userMetadata` as a dict or a JSON string (older/other layouts)."""
@@ -182,6 +197,14 @@ class DeltaWriter:
def __init__(self, table: "DeltaTableRef") -> None:
self._table = table
self._logger = table.logger
+ self._deltalite_file_count_change: int | None = None
+
+ @property
+ def deltalite_file_count_change(self) -> int | None:
+ """The change in the table's file count from the deltalite commit of the last `write`, or
+ None when deltalite did not commit that write. The handle `write` returns is one commit
+ behind after a deltalite commit, so this is what its file list is off by."""
+ return self._deltalite_file_count_change
async def _dedupe_incremental_batch(
self, data: pa.Table, primary_keys: Sequence[Any], use_partitioning: bool
@@ -309,6 +332,7 @@ class DeltaWriter:
# here: that costs a log listing per batch, and most batches never read the handle's version
# or file list again. The ref refreshes it on the next `get_delta_table` call instead.
self._table.note_deltalite_commit(_committed_version(stats))
+ self._deltalite_file_count_change = _committed_file_count_change(stats)
# NOTHING past this point may raise into the caller: an exception here would leave
# `deltalite_wrote` unset and either fail/retry the sync or re-run the delta-rs MERGE on top of
@@ -371,6 +395,7 @@ class DeltaWriter:
# share we can actually attribute.
report_phase("merge")
report_buffer_bytes(data.nbytes)
+ self._deltalite_file_count_change = None
# Guard against delta-rs aborting the worker on misaligned decimal buffers (see
# realign_decimal_buffers). Sub-tables derived below via filter()/take() are
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 568b924e8b1a..5800cdef3820 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -93,7 +93,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
ExportSignalMessage,
SyncTypeLiteral,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import read_parquet
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import (
+ read_parquet,
+ read_parquet_first_values,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
release_v3_pipeline_lock,
)
@@ -406,6 +409,26 @@ async def _handle_partial_data_loading(
)
+def _file_count_after_write(
+ delta_table: deltalake.DeltaTable, delta_table_ref: DeltaTableRef, deltalite_file_count_change: int | None
+) -> int | None:
+ """The table's file count after the write, from memory, or None when the handle cannot give it.
+
+ A handle at the newest known version has the count. A handle one commit behind is behind by the
+ deltalite commit of this write, whose added and removed files give the difference. Any other
+ distance means a commit this process did not make, so the caller must read the log.
+ """
+ try:
+ commits_behind = delta_table_ref.latest_known_version(delta_table) - delta_table.version()
+ except Exception:
+ return None
+ if commits_behind == 0:
+ return len(delta_table.file_uris())
+ if commits_behind == 1 and isinstance(deltalite_file_count_change, int):
+ return len(delta_table.file_uris()) + deltalite_file_count_change
+ return None
+
+
def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessage) -> PostLoadResult:
"""Run post-load operations for a final batch whose data was already written to Delta Lake.
@@ -443,12 +466,12 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessag
)
return PostLoadResult(queryable_folder=None)
- pa_table = read_parquet(export_signal.s3_path)
+ # The batch only decides which string columns hold JSON, and the first non-null value of a
+ # column decides that. The rows are already in the table, so they are not read again.
internal_schema = HogQLSchema()
internal_schema.add_pyarrow_schema(pyarrow_schema_from_arrow_exportable(delta_table.schema()))
- internal_schema.add_pyarrow_table(pa_table)
+ internal_schema.add_pyarrow_table(read_parquet_first_values(export_signal.s3_path))
table_schema_dict = internal_schema.to_hogql_types()
- del pa_table
post_load_result = await run_post_load_operations(
job=job,
@@ -1193,6 +1216,7 @@ def _process_message_reported(
primary_keys = export_signal.primary_keys
cdc_write_mode = export_signal.cdc_write_mode
+ deltalite_file_count_change: int | None = None
# Tag every delta commit with (run_uuid, batch_index) so that a redelivery after a writer
# crash can detect "already committed" even when the Redis dedup flag is missing. A set
@@ -1287,7 +1311,8 @@ def _process_message_reported(
with DELTA_WRITE_DURATION_SECONDS.labels(
team_id=team_id_str, schema_id=schema_id_str, write_type=write_type
).time():
- delta_table = async_to_sync(DeltaWriter(delta_table_ref).write)(
+ delta_writer = DeltaWriter(delta_table_ref)
+ delta_table = async_to_sync(delta_writer.write)(
data=pa_table,
write_type=write_type,
should_overwrite_table=should_overwrite_table,
@@ -1295,6 +1320,7 @@ def _process_message_reported(
progress_callback=progress_callback,
commit_metadata=commit_metadata,
)
+ deltalite_file_count_change = delta_writer.deltalite_file_count_change
DELTA_ROWS_WRITTEN_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc(pa_table.num_rows)
@@ -1308,14 +1334,23 @@ def _process_message_reported(
# but listing every file costs O(files in table), which is the very thing it measures. Sample
# it instead: the trend is what matters, and the version is cheap enough to log every batch.
sample_file_count = export_signal.batch_index % FILE_COUNT_LOG_SAMPLE_EVERY == 0
+ file_count = (
+ _file_count_after_write(delta_table, delta_table_ref, deltalite_file_count_change)
+ if sample_file_count
+ else None
+ )
# The handle `write` returns can be one deltalite commit behind the log. Column names and
# types cannot differ across that commit, so the schema below reads it as is; a file list
- # can, so the readers of one go through the ref, which catches the handle up first.
- if sample_file_count or _partial_data_loading_applies(export_signal, schema):
+ # can, so the readers of one go through the ref, which catches the handle up first. The
+ # sampled count needs that read only when the commit's own numbers cannot give it: batch 0
+ # is a sample, so the read would otherwise cost each run a log listing.
+ if (sample_file_count and file_count is None) or _partial_data_loading_applies(export_signal, schema):
current_delta_table = async_to_sync(delta_table_ref.get_delta_table)()
if current_delta_table is not None:
delta_table = current_delta_table
+ if sample_file_count and file_count is None:
+ file_count = len(delta_table.file_uris())
internal_schema = HogQLSchema()
# Build from the Delta table schema first to cover all columns from
@@ -1328,7 +1363,7 @@ def _process_message_reported(
batch_index=export_signal.batch_index,
batch_count=len(members),
delta_version=delta_table_ref.latest_known_version(delta_table),
- file_count=len(delta_table.file_uris()) if sample_file_count else None,
+ file_count=file_count,
)
async_to_sync(_handle_partial_data_loading)(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index 2f70a5007475..f43614b3dad7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -8,6 +8,7 @@ import pytest
from unittest.mock import ANY, AsyncMock, MagicMock, patch
import pyarrow as pa
+from asgiref.sync import async_to_sync
from deltalake import DeltaTable, write_deltalake
from parameterized import parameterized
from temporalio.exceptions import WorkflowAlreadyStartedError
@@ -24,7 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.con
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (
make_local_table_ref,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import commit_covers_batch
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import (
+ DeltaWriter,
+ commit_covers_batch,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.post_load_phases import (
SUMMARY_EVENT,
post_load_phase,
@@ -32,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.pos
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (
_apply_partitioning,
_enrich_cdc_rows,
+ _file_count_after_write,
_get_write_type,
_mark_job_completed,
_promote_staged_cursor,
@@ -90,8 +95,8 @@ def _schema(**overrides: Any) -> MagicMock:
return schema
-_COL_ID = pa.field("id", pa.int64())
-_COL_PARTITION = pa.field(PARTITION_KEY, pa.string())
+_COL_ID: pa.Field[pa.DataType] = pa.field("id", pa.int64())
+_COL_PARTITION: pa.Field[pa.DataType] = pa.field(PARTITION_KEY, pa.string())
class TestApplyPartitioning:
@@ -503,7 +508,7 @@ class TestMarkJobCompleted:
class TestRedeliveredFinalBatchPostLoad:
@parameterized.expand([("companion", "scd2_append"), ("consolidated", "incremental_merge"), ("snapshot", None)])
@patch(f"{_PROCESSOR}.run_post_load_operations", new_callable=AsyncMock, return_value=_POST_LOAD_RESULT)
- @patch(f"{_PROCESSOR}.read_parquet", return_value=pa.table({"id": [1]}))
+ @patch(f"{_PROCESSOR}.read_parquet_first_values", return_value=pa.table({"id": [1], "payload": ['{"a": 1}']}))
@patch(f"{_PROCESSOR}.DeltaTableRef")
@patch(f"{_PROCESSOR}.ExternalDataJob")
def test_forwards_the_batch_write_mode(
@@ -519,7 +524,7 @@ class TestRedeliveredFinalBatchPostLoad:
# write (register the _cdc table, leave schema.table alone) or a snapshot to seed the
# companion from. Dropping it here let a redelivered streaming batch re-seed the companion,
# wiping its SCD2 history, and point schema.table at the companion's folder.
- delta_table = MagicMock(schema=MagicMock(return_value=pa.schema([_COL_ID])))
+ delta_table = MagicMock(schema=MagicMock(return_value=pa.schema([_COL_ID, pa.field("payload", pa.string())])))
mock_job_model.objects.prefetch_related.return_value.aget = AsyncMock(return_value=MagicMock())
mock_helper_cls.return_value.get_delta_table = AsyncMock(return_value=delta_table)
@@ -530,6 +535,11 @@ class TestRedeliveredFinalBatchPostLoad:
assert mock_post_load.await_args is not None
assert mock_post_load.await_args.kwargs["cdc_write_mode"] == cdc_write_mode
+ # The table schema alone types the column as a plain string; the batch's first value says JSON.
+ assert mock_post_load.await_args.kwargs["table_schema_dict"] == {
+ "id": "IntegerDatabaseField",
+ "payload": "StringJSONDatabaseField",
+ }
class TestPostWriteHandleReads:
@@ -537,7 +547,18 @@ class TestPostWriteHandleReads:
# types survive that lag, a file list does not: partial data loading must read its file list
# through the ref, which catches the handle up, and a plain batch must not pay that read.
- @parameterized.expand([("plain_batch", False, 1), ("partial_data_loading", True, 2)])
+ @parameterized.expand(
+ [
+ ("plain_batch", 1, False, 1, 1, 1, None),
+ ("partial_data_loading", 1, True, 1, 1, 2, None),
+ # Batch 0 is a file-count sample and is the only batch of most runs.
+ ("sampled_batch_after_a_deltalite_commit", 0, False, 1, 1, 1, 3),
+ ("sampled_batch_on_a_current_handle", 0, False, 0, None, 1, 2),
+ ("sampled_batch_behind_by_a_foreign_commit", 0, False, 2, 1, 2, 5),
+ ("sampled_batch_with_no_commit_stats", 0, False, 1, None, 2, 5),
+ ]
+ )
+ @patch(f"{_PROCESSOR}.logger")
@patch(f"{_PROCESSOR}.posthoganalytics")
@patch(f"{_PROCESSOR}.mark_batch_as_processed")
@patch(f"{_PROCESSOR}._handle_partial_data_loading", new_callable=AsyncMock)
@@ -550,8 +571,12 @@ class TestPostWriteHandleReads:
def test_file_list_readers_go_through_the_ref(
self,
_case: str,
+ batch_index: int,
is_first_ever_sync: bool,
+ commits_behind: int,
+ deltalite_file_count_change: int | None,
expected_handle_reads: int,
+ expected_file_count: int | None,
mock_job_model: MagicMock,
mock_helper_cls: MagicMock,
mock_writer_cls: MagicMock,
@@ -561,23 +586,64 @@ class TestPostWriteHandleReads:
mock_partial: AsyncMock,
_mark: MagicMock,
_analytics: MagicMock,
+ mock_logger: MagicMock,
) -> None:
returned = MagicMock()
returned.schema.return_value = pa.schema([_COL_ID])
+ returned.version.return_value = 7
+ returned.file_uris.return_value = ["a", "b"]
current = MagicMock()
current.schema.return_value = pa.schema([_COL_ID])
- current.file_uris.return_value = []
+ current.file_uris.return_value = ["a", "b", "c", "d", "e"]
helper = mock_helper_cls.return_value
helper.get_delta_table = AsyncMock(return_value=current)
+ helper.latest_known_version.return_value = 7 + commits_behind
mock_writer_cls.return_value.write = AsyncMock(return_value=returned)
+ mock_writer_cls.return_value.deltalite_file_count_change = deltalite_file_count_change
mock_job_model.objects.prefetch_related.return_value.get.return_value = MagicMock()
- process_message(_message(batch_index=1, is_first_ever_sync=is_first_ever_sync))
+ process_message(_message(batch_index=batch_index, is_first_ever_sync=is_first_ever_sync))
# One read opens the table before the write; only a file-list reader adds a second.
assert helper.get_delta_table.await_count == expected_handle_reads
assert mock_partial.await_args is not None
- assert mock_partial.await_args.kwargs["delta_table"] is (current if is_first_ever_sync else returned)
+ assert mock_partial.await_args.kwargs["delta_table"] is (current if expected_handle_reads == 2 else returned)
+ written = [call for call in mock_logger.debug.call_args_list if call.args[0] == "batch_written_to_delta_lake"]
+ assert len(written) == 1
+ assert written[0].kwargs["file_count"] == expected_file_count
+
+
+class TestFileCountAfterWrite:
+ def test_the_count_from_memory_is_the_count_in_the_log(self, tmp_path: Path) -> None:
+ # The sampled file count comes from the handle `write` returns plus the commit's own numbers,
+ # with no read of the log. If the handle's lag or the upsert stats stop meaning what the
+ # arithmetic assumes, the log line goes wrong without an error.
+ path = str(tmp_path / "table")
+ seed = pa.table({"id": pa.array([1, 2, 101], pa.int64()), PARTITION_KEY: ["a", "a", "b"], "v": ["x", "y", "z"]})
+ write_deltalake(path, seed, partition_by=PARTITION_KEY)
+ ref = make_local_table_ref(path)
+ writer = DeltaWriter(ref)
+ handle_lags: set[int] = set()
+
+ writes: list[tuple[list[int], list[str], Any, list[str] | None]] = [
+ ([1], ["a"], "incremental", ["id"]),
+ ([500], ["c"], "incremental", ["id"]),
+ ([1, 101, 500, 900], ["a", "b", "c", "d"], "incremental", ["id"]),
+ ([7], ["a"], "append", None),
+ ]
+ for ids, partitions, write_type, primary_keys in writes:
+ batch = pa.table({"id": pa.array(ids, pa.int64()), PARTITION_KEY: partitions, "v": ["new"] * len(ids)})
+ returned = async_to_sync(writer.write)(
+ data=batch, write_type=write_type, should_overwrite_table=False, primary_keys=primary_keys
+ )
+ handle_lags.add(ref.latest_known_version(returned) - returned.version())
+
+ file_count = _file_count_after_write(returned, ref, writer.deltalite_file_count_change)
+
+ assert file_count == len(DeltaTable(path).file_uris())
+
+ # Both a current handle and one that a deltalite commit left behind were read.
+ assert handle_lags == {0, 1}
class TestFinalDataBatch:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/__init__.py
index 2b65a017f8bc..9a2cb24e4288 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/__init__.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.reader import (
list_parquet_files,
read_parquet,
+ read_parquet_first_values,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import S3BatchWriter
@@ -23,5 +24,6 @@ __all__ = [
"get_date_partition",
"list_parquet_files",
"read_parquet",
+ "read_parquet_first_values",
"strip_s3_protocol",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py
index bff78c8407b4..4e354ef8f3f6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/reader.py
@@ -1,8 +1,10 @@
import threading
+from collections.abc import Callable
from typing import Any
import pyarrow as pa
import structlog
+import pyarrow.compute as pc
import pyarrow.parquet as pq
from products.data_warehouse.backend.facade.api import get_s3_client
@@ -41,14 +43,69 @@ def _read_table(s3: Any, path: str) -> pa.Table:
return pq.read_table(f)
-def read_parquet(s3_path: str) -> pa.Table:
+def _first_non_null(column: pa.ChunkedArray) -> Any:
+ for chunk in column.chunks:
+ if chunk.null_count == len(chunk):
+ continue
+ index = pc.index(chunk.is_valid(), True).as_py()
+ if index != -1:
+ return chunk[index].as_py()
+ return None
+
+
+def _all_null_columns(row_group: pq.RowGroupMetaData) -> set[str]:
+ """Top-level columns that the row group statistics show as null in each row."""
+ all_null: set[str] = set()
+ seen: set[str] = set()
+ for index in range(row_group.num_columns):
+ column = row_group.column(index)
+ path = column.path_in_schema
+ if path in seen:
+ # A nested leaf can share a dotted path with a top-level column. Read both.
+ all_null.discard(path)
+ continue
+ seen.add(path)
+ statistics = column.statistics
+ if statistics is not None and statistics.null_count == row_group.num_rows:
+ all_null.add(path)
+ return all_null
+
+
+def _read_first_values(s3: Any, path: str) -> pa.Table:
+ with s3.open(path, "rb") as f:
+ parquet_file = pq.ParquetFile(f)
+ schema = parquet_file.schema_arrow
+ pending = [field.name for field in schema if pa.types.is_string(field.type)]
+ first_values: dict[str, Any] = {}
+ for index in range(parquet_file.num_row_groups):
+ if not pending:
+ break
+ all_null = _all_null_columns(parquet_file.metadata.row_group(index))
+ columns = [name for name in pending if name not in all_null]
+ if not columns:
+ continue
+ row_group = parquet_file.read_row_group(index, columns=columns)
+ for name in columns:
+ value = _first_non_null(row_group.column(name))
+ if value is not None:
+ first_values[name] = value
+ pending.remove(name)
+ return pa.table(
+ [
+ pa.array([first_values[field.name]], type=field.type)
+ if field.name in first_values
+ else pa.nulls(1, type=field.type)
+ for field in schema
+ ],
+ schema=schema,
+ )
+
+
+def _with_shared_s3(read: Callable[[Any, str], pa.Table], s3_path: str) -> pa.Table:
s3_path_without_protocol = strip_s3_protocol(s3_path)
-
- logger.debug("reading_parquet", s3_path=s3_path)
-
s3 = _get_shared_s3()
try:
- table = _read_table(s3, s3_path_without_protocol)
+ return read(s3, s3_path_without_protocol)
except RuntimeError as e:
# The RuntimeError s3fs raises here is a session whose event loop is gone. A fresh client is
# the fix, and a single retry keeps a genuine fault from looping.
@@ -56,13 +113,32 @@ def read_parquet(s3_path: str) -> pa.Table:
raise
logger.warning("parquet_read_client_rebuilt", s3_path=s3_path, error=str(e))
_discard_shared_s3(s3)
- table = _read_table(_get_shared_s3(), s3_path_without_protocol)
+ return read(_get_shared_s3(), s3_path_without_protocol)
+
+
+def read_parquet(s3_path: str) -> pa.Table:
+ logger.debug("reading_parquet", s3_path=s3_path)
+
+ table = _with_shared_s3(_read_table, s3_path)
logger.debug("parquet_read_success", s3_path=s3_path, row_count=table.num_rows)
return table
+def read_parquet_first_values(s3_path: str) -> pa.Table:
+ """One row with the file's schema: the first non-null value of each string column, null elsewhere.
+
+ For a caller that only needs to tell a JSON string column from a plain one, which is decided by
+ the first non-null value. Reads the footer, then the string columns of each row group until each
+ has a value, and skips a column chunk that the statistics show as all null. The rows of the file
+ are not loaded.
+ """
+ logger.debug("reading_parquet_first_values", s3_path=s3_path)
+
+ return _with_shared_s3(_read_first_values, s3_path)
+
+
def list_parquet_files(data_folder: str) -> list[str]:
s3 = _get_shared_s3()
folder_without_protocol = strip_s3_protocol(data_folder)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.py
index 50ffb8fcd52e..a2c26bd24a38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_reader.py
@@ -4,7 +4,11 @@ import pytest
from unittest.mock import MagicMock, patch
import pyarrow as pa
+import pyarrow.parquet as pq
+from fsspec.implementations.memory import MemoryFileSystem
+from parameterized import parameterized
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import reader
_READER = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.reader"
@@ -67,3 +71,54 @@ class TestReadParquetClientReuse:
mock_get_client.assert_called_once()
assert reader._shared_s3 is mock_get_client.return_value
+
+
+def _hogql_types(table: pa.Table) -> dict[str, str]:
+ schema = HogQLSchema()
+ schema.add_pyarrow_table(table)
+ return schema.to_hogql_types()
+
+
+class TestReadParquetFirstValues:
+ # A redelivered final batch types its string columns from this read. A column typed as a plain
+ # string where the full batch gives JSON changes how every later query reads that column.
+
+ @parameterized.expand(
+ [
+ ("json_in_the_first_row", ['{"a": 1}', "x", "y", "z"], "StringJSONDatabaseField"),
+ ("json_array", ["[1, 2]", None, None, None], "StringJSONDatabaseField"),
+ ("plain_string_before_json", ["plain", '{"a": 1}', None, None], "StringDatabaseField"),
+ ("json_after_nulls_in_a_later_row_group", [None, None, None, '{"a": 1}'], "StringJSONDatabaseField"),
+ ("json_after_a_null_in_the_same_row_group", [None, '{"a": 1}', "x", "y"], "StringJSONDatabaseField"),
+ ("all_null", [None, None, None, None], "StringDatabaseField"),
+ ("no_rows", [], "StringDatabaseField"),
+ ]
+ )
+ @patch(f"{_READER}.get_s3_client")
+ def test_types_each_column_as_the_full_batch_does(
+ self, _name: str, payload: list[str | None], expected_payload_type: str, mock_get_client: MagicMock
+ ) -> None:
+ rows = len(payload)
+ table = pa.table(
+ {
+ "id": pa.array(range(rows), pa.int64()),
+ "payload": pa.array(payload, pa.string()),
+ "other": pa.array(["plain"] * rows, pa.string()),
+ "raw": pa.array([b"{"] * rows, pa.binary()),
+ "seen_at": pa.array([None] * rows, pa.timestamp("us")),
+ "tags": pa.array([["{"]] * rows, pa.list_(pa.string())),
+ "a.b": pa.array(['{"a": 1}'] * rows, pa.string()),
+ "a": pa.array([{"b": None}] * rows, pa.struct([("b", pa.string())])),
+ }
+ )
+ store = MemoryFileSystem()
+ with store.open("bucket/first-values.parquet", "wb") as f:
+ pq.write_table(table, f, row_group_size=2)
+ mock_get_client.return_value = store
+
+ first_values = reader.read_parquet_first_values("s3://bucket/first-values.parquet")
+
+ assert first_values.num_rows == 1
+ assert first_values.schema.equals(table.schema)
+ assert _hogql_types(first_values) == _hogql_types(table)
+ assert _hogql_types(first_values)["payload"] == expected_payload_type
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
index a4b8b5a0c9b9..b96e5d3f6385 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py
@@ -7,12 +7,14 @@ from unittest.mock import MagicMock, patch
import pyarrow as pa
import botocore.exceptions
+from fsspec.implementations.memory import MemoryFileSystem
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.ops import (
ObjectStorePermissionDeniedError,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import (
+ ParquetCompression,
S3BatchWriter,
_write_parquet_to_s3,
build_schema_dict,
@@ -119,38 +121,37 @@ class TestBuildSchemaDict:
class TestBatchByteSize:
@parameterized.expand(
[
- # s3fs spells the key in lowercase; reading S3's `Size` here recorded 0 bytes on every queue row.
- ("s3fs_lowercase_size", {"size": 2048}, 2048),
- ("raw_s3_head_shape", {"Size": 512}, 512),
- ("numeric_string", {"size": "64"}, 64),
- ("no_size_key", {"type": "file"}, 0),
- ("not_a_dict", None, 0),
+ ("one_row", 1, "zstd"),
+ ("empty_table", 0, "zstd"),
+ # Several megabytes that do not compress, so the parquet writer makes many writes.
+ ("many_writes", 400_000, "none"),
]
)
- @patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer._write_parquet_to_s3"
- )
@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.ensure_bucket")
@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.get_s3_client")
- def test_byte_size_comes_from_the_written_object(
+ def test_byte_size_counted_while_writing_is_the_size_of_the_stored_object(
self,
_name: str,
- file_info: dict | None,
- expected: int,
+ rows: int,
+ compression: ParquetCompression,
mock_get_s3_client,
_mock_ensure_bucket,
- _mock_write,
) -> None:
- mock_get_s3_client.return_value.info.return_value = file_info
-
+ # The size is on each queue row and sets how many batches the loader joins into one write.
+ # A count that differs from the object, or a zero, changes that plan without an error.
+ store = MemoryFileSystem()
+ mock_get_s3_client.return_value = store
job = MagicMock()
job.team_id = 1
job.created_at = datetime(2026, 8, 5, tzinfo=UTC)
- writer = S3BatchWriter(MagicMock(), job, schema_id="schema-1", run_uuid="run-1")
+ writer = S3BatchWriter(MagicMock(), job, schema_id="schema-1", run_uuid=f"run-{_name}", compression=compression)
+ table = pa.table({"id": pa.array(range(rows), pa.int64()), "v": [f"{i:x}" * 3 for i in range(rows)]})
- result = writer.write_batch(pa.table({"id": [1]}), 0)
+ result = writer.write_batch(table, 0)
- assert result.byte_size == expected
+ stored_size = store.info(result.s3_path.split("://", 1)[-1])["size"]
+ assert result.byte_size == stored_size
+ assert result.byte_size > 0
class TestWriteBatchPermissionDenied:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
index 76a9f52cc4cd..1f41bcc9d247 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py
@@ -63,22 +63,6 @@ def build_schema_dict(schema: pa.Schema) -> dict:
}
-def _object_size(file_info: object) -> int:
- # s3fs reports the object size under the lowercase `size` key. S3's own HeadObject shape
- # uses `Size`, so both are accepted rather than trusting one client's spelling.
- if not isinstance(file_info, dict):
- return 0
- for key in ("size", "Size"):
- value = file_info.get(key)
- if value is None:
- continue
- try:
- return int(value)
- except (TypeError, ValueError):
- continue
- return 0
-
-
def _is_transient_s3_write_error(exc: BaseException) -> bool:
# s3fs translates most S3-side write failures (IncompleteBody, InternalError,
# SlowDown/ServiceUnavailable, ...) into a plain OSError. PermissionError,
@@ -109,9 +93,16 @@ def _is_transient_s3_write_error(exc: BaseException) -> bool:
)
def _write_parquet_to_s3(
s3: s3fs.S3FileSystem, s3_path: str, pa_table: pa.Table, compression: ParquetCompression
-) -> None:
+) -> int:
+ """Write the table and return the size of the object in bytes.
+
+ The file position after the last write is the object size: the parquet writer only appends, and
+ s3fs uploads each byte it accepted, in one PUT or in parts. Reading the size back from S3 would
+ cost one HEAD for each batch.
+ """
with s3.open(s3_path, "wb") as f:
pq.write_table(pa_table, f, compression=compression)
+ return int(f.tell())
class S3BatchWriter:
@@ -164,7 +155,7 @@ class S3BatchWriter:
write_start = time.perf_counter()
try:
s3_path_without_protocol = strip_s3_protocol(s3_path)
- _write_parquet_to_s3(self._s3, s3_path_without_protocol, pa_table, self._compression)
+ byte_size = _write_parquet_to_s3(self._s3, s3_path_without_protocol, pa_table, self._compression)
except Exception as e:
if activity.in_activity():
get_s3_write_errors_metric(type(e).__name__).add(1)
@@ -180,8 +171,6 @@ class S3BatchWriter:
if activity.in_activity():
get_s3_write_duration_metric().record(write_duration)
- byte_size = _object_size(self._s3.info(s3_path_without_protocol))
-
if self._schema is None:
self._schema = pa_table.schema
else: