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(warehouse-sources): disqualify retention-clamped parents from warehouse fan-out (#85599)

Daniel RCd347ef95de9f
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.md
index a30395c232f2..8e684bcde955 100644
--- a/.agents/skills/implementing-warehouse-sources/SKILL.md
+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md
@@ -625,13 +625,13 @@ Fan-out = iterate a parent resource, then query child endpoints per parent.
### Reading the fan-out parent from the warehouse (`parent_source="warehouse"`)
> [!IMPORTANT]
-> **Not generally available — do not opt new sources in.** The flag is off everywhere and Sentry is the only source wired up, pending validation against real syncs.
+> **Not generally available — do not opt new sources in.** The flag is limited to dogfood rollouts and the only wired caller is Sentry's `issue_tag_values` custom iterator, gated on an incremental watermark.
> This section is here because the shared fan-out builder carries the machinery either way, so anyone changing fan-out internals needs to know the constraints. Treat the caveats below (windowed parents, ordered parents, non-REST callers) as unproven outside Sentry, and ask the data warehouse team before opting another source in.
By default a fan-out child re-fetches its parent endpoint on every sync — syncing `issue_hashes` re-pulls all of `issues` even when the `issues` schema already synced.
A child endpoint opts into warehouse parent reuse with `parent_source="warehouse"` on its `DependentEndpointConfig`:
the child then streams parent rows from the parent schema's already-synced Delta table (`iter_parent_pages_from_warehouse` in `common/rest_source/warehouse_parent.py`) instead of hitting the parent API.
-Reference implementation: Sentry (`issue_events` / `issue_hashes` via the config flag, `issue_tag_values` via the custom iterator calling the reader directly).
+Reference implementation: Sentry's `issue_tag_values` custom iterator calling the reader directly, warehouse-mode only when an incremental watermark bounds the scan.
Requirements and behavior:
@@ -646,7 +646,11 @@ Requirements and behavior:
- **Stale parents 404.** The warehouse snapshot can contain parents deleted upstream since the parent's last sync; the builder adds a `404 → ignore` response action on the child (custom iterators must skip 404s themselves — see Sentry's `_skip_rows_on_stale_issue_404`).
- **Freshness**: children fan out over the parent's last synced snapshot. Parents created after the parent's last sync appear once the parent re-syncs — same staleness class as independent schedules.
- **Column names**: the reader takes API field names (e.g. `lastSeen`), maps them to the snake_case physical Delta columns, and re-keys rows back to API names. Request only the columns the fan-out needs (`resolve_field` + `include_from_parent`).
-- **The warehouse read must reproduce the API path's effective row set, not just its columns.** The vendor's list endpoint usually windows what it returns (server-side defaults, retention), while an incremental parent table accumulates every row ever seen — an unbounded scan therefore fans out over parents the API path never would. This is measured, not hypothetical: unbounded Sentry children produced 2–4x the rows and 2–6x the run time of the API path on aged snapshots, plus a stale-404 rate that grew with snapshot age. Set `parent_row_filter` on the `DependentEndpointConfig` (`ParentRowFilter(field=..., not_older_than=...)`) to floor the scan; the predicate is pushed into the parquet read, keeps NULL rows, adapts to string or timestamp physical columns, and an unfilterable table falls back to the API path via the eager resolve validation. Leave it unset only when the parent API genuinely returns the full collection. Before opting a source in, establish what the API path's effective window actually is — it is usually invisible in our code because the vendor applies it server-side.
+- **The warehouse read must reproduce the API path's effective row set, and if it can't, the parent is disqualified.** The vendor's list endpoint usually bounds what it returns server-side, while an incremental parent table accumulates every row ever seen — an unbounded scan fans out over parents the API path never would, multiplying child rows, billed volume, and run time on aged snapshots. Classify the parent into one of three cases before opting it in:
+ - The parent API genuinely returns the full collection → no filter needed; ideal candidate.
+ - The bound is knowable and expressible → set `parent_row_filter` on the `DependentEndpointConfig` (`ParentRowFilter(field=..., not_older_than=..., not_before=...)`); the predicate is pushed into the parquet read, keeps NULL rows, adapts to string or timestamp physical columns, and an unfilterable table falls back to the API path via eager resolve validation. A per-run watermark (`not_before`) is the safest bound, because it is self-consistent with what the child already processed.
+ - The bound depends on state you cannot know → **do not opt the parent in.** The classic shape is a listing clamped by the customer's plan (event retention, seat tier, feature entitlements): per-account, applied silently server-side, exposed by no API, and overriding any explicit range you send. No snapshot filter can reproduce a bound like that.
+ The effective bound is usually invisible in our code, so classify empirically: run the listing against a real account with and without explicit bounds, compare counts, and check whether items outside the suspected bound still serve their child endpoints.
- **Windowed parents must stay windowed.** If the source currently bounds its parent walk by the child watermark (e.g. Github's `_fan_out_get_rows`), a full warehouse read would _increase_ child fan-out — filter the warehouse read to the same window instead.
- **Non-REST sources** (e.g. Stripe's SDK loop) can call `iter_parent_pages_from_warehouse` directly; project any fields their skip-checks inspect (e.g. customer `balance`). Resolve the table with `resolve_parent_table_ref(..., required_columns=[...])` eagerly in `source_for_pipeline` (sync context) — it does an ORM read, and the pipeline's iterator executor threads are the wrong place for ad-hoc DB connections. It also pins the parent's Delta version, so a parent that re-syncs mid-fan-out can't shift the rows underneath the child; pass the returned ref to the reader instead of re-deriving a URI.
- **Catch `WarehouseParentTableNotFoundError` around that resolve call and take the API path.** A schema row can claim a completed sync while its table is unreadable (purged, renamed, or missing the fan-out columns), and the reader is a generator, so anything it validated lazily would raise deep inside the pipeline where no fallback is left. That is why `required_columns` is validated eagerly during resolution. When falling back, also turn off any behavior that only makes sense for a warehouse snapshot (the child's stale-parent `404 → ignore`, and resume checkpoints the warehouse scan skips), so the run matches the feature-off path exactly.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
index 9c3e1a833622..8bda69699624 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
@@ -4,6 +4,7 @@ import graphlib # type: ignore[import,unused-ignore]
from collections.abc import Callable, Iterator
from typing import Any, Optional, cast
+import structlog
from dateutil import parser
from .config_setup import (
@@ -23,6 +24,8 @@ from .rest_client import DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_BACKOFF_MAX_SECON
from .typing import ClientConfig, Endpoint, EndpointResource, HTTPMethodBasic, ResolvedParam, RESTAPIConfig
from .utils import exclude_keys # noqa: F401
+logger = structlog.get_logger(__name__)
+
def convert_types(
data: Iterator[Any] | list[Any], types: Optional[dict[str, dict[str, Any]]]
@@ -150,6 +153,7 @@ def _make_paginate_dependent_resource(
``{"completed": [child_path, ...], "current": child_path | None, "child_state": {...} | None}``.
"""
# Closure state persists across parent-page invocations within a single run.
+ parent_rows_consumed = 0
seed: dict[str, Any] = dict(initial_state) if initial_state else {}
completed: set[str] = set(seed.get("completed") or [])
current_path: Optional[str] = seed.get("current")
@@ -169,9 +173,11 @@ def _make_paginate_dependent_resource(
hooks: Optional[dict[str, Any]],
columns_config: Optional[Any] = None,
) -> Iterator[list[Any]]:
- nonlocal current_path, current_child_state
+ nonlocal current_path, current_child_state, parent_rows_consumed
effective_columns_config = columns_config if columns_config is not None else default_columns_config
+ page_rows = 0
+
if incremental_object:
params = _set_incremental_params(
params,
@@ -187,6 +193,9 @@ def _make_paginate_dependent_resource(
if resume_hook is not None and formatted_path in completed:
continue
+ page_rows += 1
+ parent_rows_consumed += 1
+
# Resume this parent's child cursor only if it's the one we were mid-way through.
child_initial = (
current_child_state if (resume_hook is not None and current_path == formatted_path) else None
@@ -237,6 +246,15 @@ def _make_paginate_dependent_resource(
current_child_state = None
checkpoint(None, None)
+ # Counted after the page so parents a resume skips don't inflate it. A running total,
+ # since there's no end-of-parent signal: the last line of a run carries the fan-out's
+ # size, for either parent kind, which the API path never surfaced anywhere.
+ logger.info(
+ "data_imports.fanout_parent_rows_consumed",
+ page_rows=page_rows,
+ rows_total=parent_rows_consumed,
+ )
+
return paginate_dependent_resource
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
index a5aa9c3df056..0643ee5420cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py
@@ -414,12 +414,10 @@ def _issues_parent_row_filter(cutoff_last_seen: datetime | None) -> ParentRowFil
reader applies, so an incremental run stops reading issues it would only discard. The
per-row check stays the authority, and the floor is never tighter than it.
- The window half is the same constant `issue_events` and `issue_hashes` use, so all three
- children fan out over one row set instead of each bounding the parent differently. It does
- drop issues this iterator used to yield, in the two cases where the per-row check bounded
- nothing: a full refresh (no cutoff at all) and a watermark older than the window. Those are
- issues Sentry's own listing no longer returns, so the API path never fanned out over them
- either.
+ The window half caps a watermark older than the window from widening the scan back out.
+ The no-watermark case never reaches this filter: `sentry_source` sends full refreshes down
+ the API parent path, because Sentry clamps its listing to the org's plan retention and a
+ snapshot floor cannot reproduce that bound — see SENTRY_FANOUT_PARENT_WINDOW.
"""
return dataclasses.replace(ISSUES_PARENT_ROW_FILTER, not_before=cutoff_last_seen)
@@ -1275,7 +1273,12 @@ def sentry_source(
headers = _auth_headers(auth_token)
incremental_last_seen_max = db_incremental_field_last_value if should_use_incremental_field else None
issues_table: ParentTableRef | None = None
- if use_warehouse_parent:
+ # Warehouse reuse only with a watermark: the per-row cutoff then bounds the fan-out to
+ # issues newer than the last run, the regime whose volume matched the API path in
+ # production. Without one (a full refresh), the only available floor is our window
+ # constant, and Sentry clamps its own listing to the org plan retention below it --
+ # see SENTRY_FANOUT_PARENT_WINDOW -- so the API path is the only faithful parent.
+ if use_warehouse_parent and _parse_datetime_value(incremental_last_seen_max) is not None:
if team_id is None or not source_id:
raise ValueError("team_id and source_id are required when reading the issues parent from the warehouse")
# noqa reason: keeps deltalake/pyarrow off the import path of this module (imported
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py
index ea2cfbb3dead..7fd5b8efa242 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/settings.py
@@ -33,10 +33,14 @@ REQUIRED_SENTRY_SCOPES = (
# carry a floor rather than the 1970 sentinel the issue endpoints tolerate.
SENTRY_RETENTION_DAYS = 90
-# The issues API windows its listing while the synced `issues` table accumulates every issue
-# ever seen, so a warehouse fan-out must floor the scan or it fans out over issues the API
-# path never would. Same floor as the tag-values iterator's per-row cutoff.
-ISSUES_PARENT_ROW_FILTER = ParentRowFilter(field="lastSeen", not_older_than=timedelta(days=SENTRY_RETENTION_DAYS))
+# The issues listing only returns issues whose events still exist in Sentry's event store,
+# and events are kept for the org's plan retention (30 or 90 days) — a per-customer bound
+# that is unqueryable and clamps any wider request. A snapshot scan cannot reproduce it, so
+# issue_events and issue_hashes stay on parent_source="api", and issue_tag_values reads the
+# warehouse only when an incremental watermark bounds the scan, with this window as the cap.
+SENTRY_FANOUT_PARENT_WINDOW = timedelta(days=90)
+
+ISSUES_PARENT_ROW_FILTER = ParentRowFilter(field="lastSeen", not_older_than=SENTRY_FANOUT_PARENT_WINDOW)
# `dataset` values accepted by /trace-items/attributes/.
TRACE_ITEM_DATASETS = ("logs", "preprod", "processing_errors", "spans", "tracemetrics")
@@ -265,8 +269,9 @@ SENTRY_ENDPOINTS: dict[str, SentryEndpointConfig] = {
parent_params={"query": "", "sort": "date"},
# full=true makes Sentry return complete event bodies (incl. stacktrace entries).
child_params={"full": "true"},
- parent_source="warehouse",
- parent_row_filter=ISSUES_PARENT_ROW_FILTER,
+ # Not "warehouse": the issues listing is clamped by per-org event retention, which a
+ # snapshot scan cannot reproduce — see SENTRY_FANOUT_PARENT_WINDOW.
+ parent_source="api",
),
),
"issue_hashes": SentryEndpointConfig(
@@ -285,8 +290,8 @@ SENTRY_ENDPOINTS: dict[str, SentryEndpointConfig] = {
# this per-issue fetch, which 404s. That's expected churn, not a broken sync — treat
# it as "no hashes for this issue" instead of failing the whole schema.
child_response_actions=[{"status_code": 404, "action": "ignore"}],
- parent_source="warehouse",
- parent_row_filter=ISSUES_PARENT_ROW_FILTER,
+ # Not "warehouse": same per-org retention clamp as issue_events.
+ parent_source="api",
),
),
"issue_tag_values": SentryEndpointConfig(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py
index 05d8d5d37da4..ab9f0cb7baff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/tests/test_sentry.py
@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sen
from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.settings import (
REQUIRED_SENTRY_SCOPES,
SENTRY_ENDPOINTS,
+ SENTRY_FANOUT_PARENT_WINDOW,
SENTRY_RETENTION_DAYS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.source import SentrySource
@@ -960,6 +961,8 @@ class TestIssueTagValuesResumable:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
resumable_source_manager=manager,
)
@@ -970,10 +973,10 @@ class TestIssueTagValuesResumable:
@parameterized.expand(
[
- # An incremental run floors at its watermark, which is tighter than the window.
- ("incremental_run", "2026-08-01T00:00:00Z", datetime(2026, 8, 1, tzinfo=UTC)),
- # A full refresh has no watermark, so only Sentry's list window bounds the scan.
- ("full_refresh", None, None),
+ # A watermark inside the window is the tighter floor, so the scan stops there.
+ ("watermark_inside_window", timedelta(days=2), timedelta(days=2)),
+ # A watermark older than the window can't widen it back out.
+ ("watermark_older_than_window", timedelta(days=120), None),
]
)
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.make_tracked_session")
@@ -986,11 +989,12 @@ class TestIssueTagValuesResumable:
return_value=iter([[{"id": "100", "lastSeen": "2026-08-17T00:00:00Z"}]]),
)
def test_warehouse_scan_is_floored_by_the_watermark_and_the_list_window(
- self, _name, watermark, expected_floor, mock_reader, _mock_resolve, mock_get
+ self, _name, watermark_ago, expected_floor_ago, mock_reader, _mock_resolve, mock_get
) -> None:
# Without a floor the scan reads every issue ever synced and discards most of them
- # per row, which is the fan-out inflation the config-driven children already fixed.
+ # per row, which is the fan-out inflation the retention findings traced.
mock_get.return_value.get.side_effect = lambda url, **kwargs: _response([])
+ watermark = (datetime.now(UTC) - watermark_ago).isoformat()
resp = sentry_source(
auth_token="token",
@@ -1001,17 +1005,42 @@ class TestIssueTagValuesResumable:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
- should_use_incremental_field=watermark is not None,
+ should_use_incremental_field=True,
db_incremental_field_last_value=watermark,
)
list(cast(Any, resp.items()))
row_filter = mock_reader.call_args.kwargs["row_filter"]
assert row_filter.field == "lastSeen"
- floor = row_filter.floor(datetime.now(UTC))
- if expected_floor is None:
- expected_floor = datetime.now(UTC) - timedelta(days=SENTRY_RETENTION_DAYS)
- assert abs(floor - expected_floor) < timedelta(seconds=5)
+ now = datetime.now(UTC)
+ expected_floor = now - (expected_floor_ago if expected_floor_ago is not None else SENTRY_FANOUT_PARENT_WINDOW)
+ assert abs(row_filter.floor(now) - expected_floor) < timedelta(seconds=5)
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.make_tracked_session")
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.try_resolve_parent_table"
+ )
+ def test_full_refresh_takes_the_api_parent_even_with_the_flag_on(self, mock_resolve, mock_get) -> None:
+ # No watermark means the only floor is our window constant, and Sentry clamps its own
+ # listing to the org's plan retention below it, so the snapshot can't reproduce the
+ # API's row set. The run must not even resolve the warehouse table.
+ mock_get.return_value.get.side_effect = lambda url, **kwargs: _response([])
+
+ resp = sentry_source(
+ auth_token="token",
+ organization_slug="acme",
+ api_base_url="https://sentry.io",
+ endpoint="issue_tag_values",
+ team_id=123,
+ job_id="job-id",
+ source_id="source-1",
+ use_warehouse_parent=True,
+ )
+ list(cast(Any, resp.items()))
+
+ mock_resolve.assert_not_called()
+ issues_urls = [c.args[0] for c in mock_get.return_value.get.call_args_list if c.args[0].endswith("/issues/")]
+ assert issues_urls, "expected the API issues listing to drive the fan-out"
@parameterized.expand(
[
@@ -1057,6 +1086,8 @@ class TestIssueTagValuesResumable:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=use_warehouse_parent,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
resumable_source_manager=manager,
)
@@ -1867,8 +1898,8 @@ class TestSentryCustomIteratorEndpoints:
class TestWarehouseParentReuse:
@parameterized.expand(
[
- ("issue_events", ["issues"]),
- ("issue_hashes", ["issues"]),
+ ("issue_events", []),
+ ("issue_hashes", []),
("issue_tag_values", ["issues"]),
("issues", []),
("projects", []),
@@ -1906,6 +1937,8 @@ class TestWarehouseParentReuse:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
)
rows = list(cast(Any, resp.items()))
@@ -1942,6 +1975,8 @@ class TestWarehouseParentReuse:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
)
rows = list(cast(Any, resp.items()))
@@ -1953,7 +1988,7 @@ class TestWarehouseParentReuse:
columns=["id", "lastSeen"],
page_size=100,
schema_name="issue_tag_values",
- row_filter=_issues_parent_row_filter(None),
+ row_filter=_issues_parent_row_filter(datetime(2020, 1, 1, tzinfo=UTC)),
)
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.make_tracked_session")
@@ -2040,6 +2075,8 @@ class TestWarehouseParentReuse:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
)
rows = list(cast(Any, resp.items()))
@@ -2081,6 +2118,8 @@ class TestWarehouseParentReuse:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
)
rows = list(cast(Any, resp.items()))
@@ -2099,6 +2138,8 @@ class TestWarehouseParentReuse:
job_id="job-id",
source_id="source-1",
use_warehouse_parent=True,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01T00:00:00Z",
)
kwargs = mock_build.call_args.kwargs
@@ -2106,16 +2147,14 @@ class TestWarehouseParentReuse:
assert kwargs["use_warehouse_parent"] is True
-def test_every_warehouse_fanout_child_bounds_its_parent_scan():
- # The issues API windows its listing server-side, so an unbounded snapshot scan fans out
- # over issues the API path never would. Any endpoint opting into the warehouse parent
- # must carry the floor.
- warehouse_children = {
- name: config.fanout
+def test_no_sentry_endpoint_reads_its_parent_from_the_warehouse():
+ # Sentry's issue listing is clamped by per-org event retention, a bound a snapshot scan
+ # cannot reproduce, so config-driven warehouse fan-out shipped 3-5x row inflation on
+ # aged orgs. Re-enabling parent_source="warehouse" here needs a parity story first —
+ # see SENTRY_FANOUT_PARENT_WINDOW in settings.
+ warehouse_children = [
+ name
for name, config in SENTRY_ENDPOINTS.items()
if config.fanout is not None and config.fanout.parent_source == "warehouse"
- }
- assert warehouse_children, "expected Sentry to have warehouse-mode fan-out children"
- for name, fanout in warehouse_children.items():
- assert fanout.parent_row_filter is not None, f"{name} reads its parent unbounded"
- assert fanout.parent_row_filter.field == "lastSeen"
+ ]
+ assert warehouse_children == []