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.

feat(warehouse-sources): let a fan-out parent scan report and resume a position (#87283)

Daniel RC3e308ff2a8f8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py
index 83ccf18518ab..dc4230e9215e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py
@@ -16,8 +16,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ParentRowFilter
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (
ParentTableRef,
+ ScanPosition,
WarehouseParentTableNotFoundError,
iter_parent_pages_from_warehouse,
+ iter_parent_pages_with_positions,
resolve_parent_table_ref,
)
@@ -44,6 +46,25 @@ def _patched_reader(uri: str, version: int | None = None, **kwargs):
)
+def _patched_positioned_reader(uri: str, version: int | None = None, **kwargs):
+ ref = ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version() if version is None else version)
+ with patch.object(warehouse_parent, "delta_storage_options", return_value={}):
+ return list(
+ iter_parent_pages_with_positions(table=ref, parent_name="issues", schema_name="issue_tag_values", **kwargs)
+ )
+
+
+def _write_multi_fragment_table(tmp_path: Path, fragments: int = 3, rows_per_fragment: int = 4) -> str:
+ """One Delta table of `fragments` parquet files. Note the scan walks them in sorted-path
+ order, and Delta names files by uuid — so fragment 0 is not necessarily the first written."""
+ uri = str(tmp_path / "issues_fragmented")
+ for fragment in range(fragments):
+ ids = [f"f{fragment}r{row}" for row in range(rows_per_fragment)]
+ table = pa.table({"id": ids, "last_seen": ["2026-03-01"] * rows_per_fragment})
+ deltalake.write_deltalake(uri, table, mode="overwrite" if fragment == 0 else "append")
+ return uri
+
+
def _patched_resolve(uri: str, snapshot_timestamp=None, row_filter=None):
parent_schema = SimpleNamespace(
id="parent-id", normalized_s3_folder_name="issues", folder_path=lambda: "team_1_sentry_x"
@@ -457,3 +478,183 @@ def test_parent_row_filter_rejects_a_filter_with_no_floor() -> None:
# Silently scanning everything is the failure this whole field exists to prevent.
with pytest.raises(ValueError, match="not_older_than"):
ParentRowFilter(field="lastSeen")
+
+
+def test_positioned_pages_never_span_fragments(tmp_path: Path) -> None:
+ # A page that spanned two files would make `position_after` name a row in the wrong one,
+ # so a resumed fan-out would re-fetch or skip parents.
+ uri = _write_multi_fragment_table(tmp_path, fragments=3, rows_per_fragment=4)
+
+ pages = _patched_positioned_reader(uri, columns=["id"], page_size=10)
+
+ assert [(page.fragment_index, page.row_offset, len(page.rows)) for page in pages] == [
+ (0, 0, 4),
+ (1, 0, 4),
+ (2, 0, 4),
+ ]
+
+
+def test_resume_from_a_position_yields_exactly_the_unconsumed_rows(tmp_path: Path) -> None:
+ uri = _write_multi_fragment_table(tmp_path, fragments=3, rows_per_fragment=4)
+ version = deltalake.DeltaTable(uri).version()
+ everything = [
+ row["id"] for page in _patched_positioned_reader(uri, columns=["id"], page_size=10) for row in page.rows
+ ]
+
+ # Stop mid-fragment: consumed fragment 0 entirely, then two rows of fragment 1.
+ resumed = _patched_positioned_reader(
+ uri,
+ columns=["id"],
+ page_size=10,
+ start_position=ScanPosition(fragment_index=1, row_offset=2, table_uri=uri, version=version),
+ )
+
+ assert [row["id"] for page in resumed for row in page.rows] == everything[6:]
+
+
[email protected]("page_size", [1, 2, 3, 5])
+def test_position_after_a_row_resumes_at_the_next_row(tmp_path: Path, page_size: int) -> None:
+ # The contract a resumable fan-out relies on: checkpoint after finishing a parent, restart,
+ # and the very next row is the one that never got processed — no gap, no repeat.
+ uri = _write_multi_fragment_table(tmp_path, fragments=2, rows_per_fragment=5)
+ version = deltalake.DeltaTable(uri).version()
+ pages = _patched_positioned_reader(uri, columns=["id"], page_size=page_size)
+ flat = [row["id"] for page in pages for row in page.rows]
+
+ for stop_after, expected_remaining in enumerate(range(len(flat) - 1, -1, -1)):
+ consumed = 0
+ position = None
+ for page in pages:
+ for index in range(len(page.rows)):
+ if consumed == stop_after:
+ position = page.position_after(index, table=ParentTableRef(uri=uri, version=version))
+ break
+ consumed += 1
+ if position is not None:
+ break
+ assert position is not None
+ resumed = _patched_positioned_reader(uri, columns=["id"], page_size=page_size, start_position=position)
+ assert [row["id"] for page in resumed for row in page.rows] == flat[stop_after + 1 :]
+ assert len([row for page in resumed for row in page.rows]) == expected_remaining
+
+
+def test_fragment_indexes_survive_a_filter_pruning_files(tmp_path: Path) -> None:
+ # Indexes come from the full file list, so a filter that eliminates a whole fragment must
+ # not renumber the ones after it — otherwise a stored position points at the wrong file
+ # the moment the filter's floor moves.
+ uri = str(tmp_path / "issues_pruned")
+ now = datetime.now(UTC)
+ deltalake.write_deltalake(
+ uri,
+ pa.table(
+ {"id": ["old1", "old2"], "last_seen": [(now - timedelta(days=300)).strftime("%Y-%m-%dT%H:%M:%S")] * 2}
+ ),
+ )
+ deltalake.write_deltalake(
+ uri,
+ pa.table({"id": ["new1", "new2"], "last_seen": [(now - timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%S")] * 2}),
+ mode="append",
+ )
+
+ unfiltered = _patched_positioned_reader(uri, columns=["id"], page_size=10)
+ index_of_new_rows = next(page.fragment_index for page in unfiltered if page.rows[0]["id"].startswith("new"))
+
+ pages = _patched_positioned_reader(uri, columns=["id"], page_size=10, row_filter=_LAST_SEEN_FLOOR)
+
+ assert [row["id"] for page in pages for row in page.rows] == ["new1", "new2"]
+ # The surviving fragment keeps the index it has in the unfiltered list, rather than being
+ # renumbered to 0 because the older file was pruned away.
+ assert [page.fragment_index for page in pages] == [index_of_new_rows]
+
+
+def test_a_pinned_version_keeps_its_positions_through_a_compaction(tmp_path: Path) -> None:
+ # Positions are only meaningful because a pinned version's file list is immutable. Delta
+ # compaction rewrites many files into one at a NEW version, so a scan that followed the
+ # latest version would find its coordinates renumbered underneath it mid-fan-out.
+ uri = _write_multi_fragment_table(tmp_path, fragments=4, rows_per_fragment=3)
+ pinned = deltalake.DeltaTable(uri).version()
+ before = [row["id"] for page in _patched_positioned_reader(uri, columns=["id"], page_size=10) for row in page.rows]
+
+ deltalake.DeltaTable(uri).optimize.compact()
+
+ assert deltalake.DeltaTable(uri).version() > pinned
+ resumed = _patched_positioned_reader(
+ uri,
+ version=pinned,
+ columns=["id"],
+ page_size=10,
+ start_position=ScanPosition(fragment_index=2, row_offset=0, table_uri=uri, version=pinned),
+ )
+ assert [row["id"] for page in resumed for row in page.rows] == before[6:]
+
+
+def test_scan_position_matches_only_its_own_table_version_and_filter() -> None:
+ # The guard a caller uses before trusting stored state: offsets count emitted rows, so a
+ # different table, version or moved filter floor makes the same offset a different row.
+ table = ParentTableRef(uri="s3://bucket/table", version=7)
+ position = ScanPosition(
+ fragment_index=0,
+ row_offset=3,
+ table_uri="s3://bucket/table",
+ version=7,
+ filter_fingerprint="last_seen>=2026-05-01",
+ )
+
+ assert position.matches(table, "last_seen>=2026-05-01")
+ assert not position.matches(table, "last_seen>=2026-06-01")
+ assert not position.matches(ParentTableRef(uri="s3://bucket/table", version=8), "last_seen>=2026-05-01")
+ assert not position.matches(table, None)
+ # Delta versions restart at 0 when a table is recreated, so a position from a different
+ # table at the same version number must not pass — it would skip fragments in a table the
+ # scan has never read.
+ assert not position.matches(ParentTableRef(uri="s3://bucket/rebuilt", version=7), "last_seen>=2026-05-01")
+
+
+def test_position_after_stamps_the_table_identity_it_was_given(tmp_path: Path) -> None:
+ # The guard in `matches` is only worth anything if the positions the scan hands out carry
+ # the identity to check. A checkpoint that recorded version alone would pass validation
+ # against a rebuilt table sitting at the same version number.
+ uri = _write_multi_fragment_table(tmp_path, fragments=2, rows_per_fragment=3)
+ ref = ParentTableRef(uri=uri, version=deltalake.DeltaTable(uri).version())
+ page = _patched_positioned_reader(uri, columns=["id"], page_size=10)[0]
+
+ position = page.position_after(0, table=ref)
+
+ assert position.table_uri == uri
+ assert position.version == ref.version
+ assert position.matches(ref, None)
+ assert not position.matches(ParentTableRef(uri=str(tmp_path / "rebuilt"), version=ref.version), None)
+
+
+def test_the_plain_reader_reraises_even_if_the_scan_swallows_the_exception() -> None:
+ # The wrapper hands the consumer's exception to the scan so the outcome is classified
+ # correctly. A scan that swallowed it and kept yielding would leave the consumer's error
+ # lost, so the wrapper re-raises rather than trusting the scan to do it.
+ def _swallowing_scan(**_kwargs):
+ try:
+ yield warehouse_parent.ParentPage(rows=[{"id": "1"}], fragment_index=0, row_offset=0)
+ except BaseException:
+ yield warehouse_parent.ParentPage(rows=[{"id": "2"}], fragment_index=0, row_offset=1)
+
+ with patch.object(warehouse_parent, "iter_parent_pages_with_positions", _swallowing_scan):
+ pages = warehouse_parent.iter_parent_pages_from_warehouse(
+ table=ParentTableRef(uri="s3://bucket/table", version=1),
+ parent_name="issues",
+ columns=["id"],
+ page_size=10,
+ schema_name="issue_hashes",
+ )
+ next(pages)
+ with pytest.raises(RuntimeError, match="consumer blew up"):
+ pages.throw(RuntimeError("consumer blew up"))
+
+
+def test_plain_reader_still_yields_bare_pages(tmp_path: Path) -> None:
+ # The pre-existing callers take `list[dict]`; the positioned generator is additive.
+ uri = _write_multi_fragment_table(tmp_path, fragments=2, rows_per_fragment=3)
+
+ pages = _patched_reader(uri, columns=["id"], page_size=10)
+ positioned = _patched_positioned_reader(uri, columns=["id"], page_size=10)
+
+ assert [[row["id"] for row in page] for page in pages] == [[row["id"] for row in page.rows] for page in positioned]
+ assert sorted(row["id"] for page in pages for row in page) == ["f0r0", "f0r1", "f0r2", "f1r0", "f1r1", "f1r2"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py
index 38878fcb8c5e..c1ba5157f383 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py
@@ -54,6 +54,68 @@ class ParentTableRef:
version: int
+@frozen
+class ScanPosition:
+ """Where a parent scan had got to, as a coordinate a later scan can resume from.
+
+ A pinned Delta version is a fixed list of parquet files, and row order inside one file is
+ fixed, so (file, row offset) names the same row on every re-scan — without sorting rows,
+ holding a seen-set, or materializing the table.
+
+ `row_offset` counts rows the scan *emitted* from that fragment, so it is relative to the
+ table, version and filter in force. All three are recorded here, and `matches` is the
+ guard a caller uses before trusting a stored position.
+
+ `table_uri` is not redundant with `version`: Delta versions are small integers that
+ restart at 0 whenever a table is recreated, which the reset paths in the loader do
+ routinely, so a position saved against an old table would otherwise match a rebuilt one
+ at the same number and skip fragments the scan has never read.
+ """
+
+ fragment_index: int
+ row_offset: int
+ table_uri: str
+ version: int
+ filter_fingerprint: str | None = None
+
+ def matches(self, table: "ParentTableRef", row_filter_fingerprint: str | None) -> bool:
+ return (
+ self.table_uri == table.uri
+ and self.version == table.version
+ and self.filter_fingerprint == row_filter_fingerprint
+ )
+
+
+@frozen
+class ParentPage:
+ """One page of parent rows, tagged with where it started.
+
+ A page never spans fragments, so the position after consuming row `i` is
+ `(fragment_index, row_offset + i + 1)` — the granularity a fan-out needs to checkpoint
+ after a parent's children are fully yielded, rather than re-fanning it on resume.
+ """
+
+ rows: list[dict[str, Any]]
+ fragment_index: int
+ row_offset: int
+
+ def position_after(
+ self, row_index: int, table: "ParentTableRef", filter_fingerprint: str | None = None
+ ) -> ScanPosition:
+ """The position to resume from after fully consuming this page's row `row_index`.
+
+ Takes the table ref rather than a bare version so a caller cannot record a position
+ without the identity that makes it safe to reuse.
+ """
+ return ScanPosition(
+ fragment_index=self.fragment_index,
+ row_offset=self.row_offset + row_index + 1,
+ table_uri=table.uri,
+ version=table.version,
+ filter_fingerprint=filter_fingerprint,
+ )
+
+
def _physical_columns_by_api_name(
delta_table: "deltalake.DeltaTable", parent_name: str, columns: list[str]
) -> dict[str, str]:
@@ -84,6 +146,10 @@ class _ResolvedRowFilter:
scan_filter: pc.Expression | None
row_passes: Callable[[dict[str, Any]], bool]
physical_column: str
+ # Identifies the floor this filter resolved to, for `ScanPosition` validity. A relative
+ # bound (`not_older_than`) resolves against `now()`, so the same offset names a different
+ # row on the next run; comparing fingerprints is what catches that.
+ fingerprint: str
def _row_filter_scan_and_predicate(
@@ -131,7 +197,12 @@ def _row_filter_scan_and_predicate(
value = row.get(physical)
return value is None or value >= floor
- return _ResolvedRowFilter(scan_filter=scan_filter, row_passes=_passes_floor, physical_column=physical)
+ return _ResolvedRowFilter(
+ scan_filter=scan_filter,
+ row_passes=_passes_floor,
+ physical_column=physical,
+ fingerprint=f"{physical}>={floor!r}",
+ )
def resolve_parent_table_ref(
@@ -341,6 +412,36 @@ def iter_parent_pages_from_warehouse(
schema_name: str,
row_filter: ParentRowFilter | None = None,
) -> Generator[list[dict[str, Any]]]:
+ """Yield fan-out parent rows as plain pages. See `iter_parent_pages_with_positions`."""
+ pages = iter_parent_pages_with_positions(
+ table=table,
+ parent_name=parent_name,
+ columns=columns,
+ page_size=page_size,
+ schema_name=schema_name,
+ row_filter=row_filter,
+ )
+ try:
+ for page in pages:
+ yield page.rows
+ except BaseException as exc:
+ # Hand the consumer's exception (GeneratorExit included) to the scan underneath, so it
+ # classifies the outcome it logs exactly as it would for a direct caller. Without this
+ # the wrapper closes the scan silently and every crash reads as a clean early stop.
+ pages.throw(exc)
+ raise
+
+
+def iter_parent_pages_with_positions(
+ *,
+ table: ParentTableRef,
+ parent_name: str,
+ columns: list[str],
+ page_size: int,
+ schema_name: str,
+ row_filter: ParentRowFilter | None = None,
+ start_position: ScanPosition | None = None,
+) -> Generator[ParentPage]:
"""Yield fan-out parent rows from the parent schema's already-synced Delta table.
Pages are shaped like the REST parent pages the dependent-resource machinery consumes
@@ -365,6 +466,14 @@ def iter_parent_pages_from_warehouse(
`import_data_activity_sync` sends them down the parent-API path instead of here. Do not
add whole-table materialization (`to_table`, global sorts, seen-sets) — parents can be
arbitrarily large.
+
+ Pages carry their start coordinate and never span fragments, so a resumable caller can
+ checkpoint a `ScanPosition` and pass it back as `start_position` to pick up where it
+ stopped. Fragments are walked in sorted-path order — a metadata sort over the file list,
+ not a sort of rows — and enumerated independently of the filter, so an index means the
+ same file whether or not pushdown pruned it. A `start_position` from a different table,
+ version or filter is the caller's to reject (`ScanPosition.matches`); passing a stale one
+ skips the wrong rows rather than raising.
"""
page_size = max(1, min(page_size, MAX_PARENT_PAGE_SIZE))
delta_table = deltalake.DeltaTable(table.uri, version=table.version, storage_options=delta_storage_options())
@@ -383,21 +492,45 @@ def iter_parent_pages_from_warehouse(
dataset = delta_table.to_pyarrow_dataset()
+ # Enumerated here rather than through `dataset.get_fragments(filter=...)` so an index
+ # always names the same file: pushdown may prune fragments, and a pruned-away file must
+ # not shift the ones after it. Sorting is over paths — file metadata, never rows.
+ fragments = sorted(dataset.get_fragments(), key=lambda fragment: fragment.path)
+
rows_streamed = 0
outcome = "failed"
try:
- page: list[dict[str, Any]] = []
- for batch in dataset.to_batches(columns=projected, batch_size=page_size, filter=scan_filter):
- for row in batch.to_pylist():
- if resolved_row_filter is not None and not resolved_row_filter.row_passes(row):
- continue
- page.append({api_name: row.get(physical) for api_name, physical in physical_by_api_name.items()})
- rows_streamed += 1
- if len(page) >= page_size:
- yield page
- page = []
- if page:
- yield page
+ for fragment_index, fragment in enumerate(fragments):
+ if start_position is not None and fragment_index < start_position.fragment_index:
+ continue
+ # Rows this fragment already emitted under the same version and filter; the scan
+ # re-reads and discards them, which is what keeps the coordinate free of any
+ # per-row bookkeeping in the table itself.
+ skip_rows = (
+ start_position.row_offset
+ if start_position is not None and fragment_index == start_position.fragment_index
+ else 0
+ )
+ emitted = 0
+ # Flushed per fragment so a page never spans two of them, which is what lets a
+ # caller derive the position of any row from its page's start.
+ page: list[dict[str, Any]] = []
+ page_start = skip_rows
+ for batch in fragment.to_batches(columns=projected, batch_size=page_size, filter=scan_filter):
+ for row in batch.to_pylist():
+ if resolved_row_filter is not None and not resolved_row_filter.row_passes(row):
+ continue
+ emitted += 1
+ if emitted <= skip_rows:
+ continue
+ page.append({api_name: row.get(physical) for api_name, physical in physical_by_api_name.items()})
+ rows_streamed += 1
+ if len(page) >= page_size:
+ yield ParentPage(rows=page, fragment_index=fragment_index, row_offset=page_start)
+ page_start += len(page)
+ page = []
+ if page:
+ yield ParentPage(rows=page, fragment_index=fragment_index, row_offset=page_start)
outcome = "completed"
except GeneratorExit:
outcome = "stopped"