: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): reuse synced parent tables for fan-out endpoints (#72929)
Daniel RCde878063a905
diff --git a/.agents/skills/implementing-warehouse-sources/SKILL.md b/.agents/skills/implementing-warehouse-sources/SKILL.mdindex 9e9e07a31fc5..6af3f95cdbce 100644--- a/.agents/skills/implementing-warehouse-sources/SKILL.md+++ b/.agents/skills/implementing-warehouse-sources/SKILL.md@@ -622,6 +622,34 @@ Fan-out = iterate a parent resource, then query child endpoints per parent.**Custom iterator only when fan-out is 2+ levels deep.** Reuse the same pagination/retry helpers as elsewhere.+### 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.+> 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).++Requirements and behavior:++- **The parent must be a selectable schema of the same source** — it has to produce its own Delta table.+- **Soft dependency — the child falls back to the parent API.** Declare the parents by overriding `get_required_parent_schemas` on the source (wire it to `required_parents_from_endpoint_configs(ENDPOINTS, schema_name)`; add explicit entries for custom-iterator endpoints). That override is the only declaration: nothing surfaces the relationship through the API, so don't add a schema-payload field for it while the feature is unvalidated.+ Nothing in the API constrains the selection either: a child can be enabled without its parent, and a parent can be disabled or deleted while children sync. `_warehouse_parent_reuse_available` in `import_data_activity_sync` decides per run — a parent that is missing, disabled, not yet initially synced, or on any sync type other than merge or full refresh sends that run down the legacy parent-API path, so enabling the flag can never break a schema that syncs today. A parent that is merely mid-sync does not force the fallback, because `resolve_parent_table_ref` pins the read to the parent's last completed snapshot via Delta time travel.+ Never enable a parent as a side effect of enabling a child: parent syncs count toward the customer's billed rows.+- **Feature-flagged.** The whole path is gated by the `warehouse-fanout-parent-reuse` flag (`is_fanout_warehouse_reuse_enabled`); with the flag off, opted-in endpoints silently keep the legacy parent-API path, so rollback is a flag flip.+- **Strictly streaming — never materialize the parent table.** The reader scans one projected batch at a time with column projection pushed down to the parquet read. Do not add `to_table`, global sorts, or seen-set dedupe to it — parents can be arbitrarily large, and the whole pipeline exists to avoid full-dataset memory. If a caller's semantics depend on parent order (the API returned sorted rows), rework them into per-row filters over the unordered stream (see Sentry's `issue_tag_values` cutoff handling) instead of sorting.+- **The usable sync types are an allow-list, not a deny-list.** Only merge and full refresh hold one row per key; append accumulates a row per sync and CDC keeps change history, so streaming either would fan the child out once per duplicate, and dedupe would need unbounded state. A new sync type has to opt in deliberately in `_parent_unusable_reason`.+- **Values carry Delta physical types, not the API's JSON types.** A timestamp comes back as a datetime rather than an ISO string, a nested object as a dict. Because the API fallback engages per run, projecting such a field through `include_from_parent` makes the child's column type flip between runs and trips the merge's type-drift guards. Only project fields whose physical type matches what the API returned (an id string is safe), or normalize in the caller.+- **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`).+- **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.+## OAuth configurationBefore implementing OAuth, **check if the integration already exists** — search `posthog/models/integration.py` loosely for the service name before concluding it's new.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.pyindex 3974aeea8ce5..f80c4c07cf00 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/maintenance.py@@ -1,5 +1,6 @@import jsonimport asyncio+import datetime as dtfrom typing import TYPE_CHECKING, Anyfrom django.conf import settings@@ -56,6 +57,11 @@ DEFAULT_COMPACT_TARGET_SIZE_BYTES = 100 * 1024 * 1024# can't be avoided at any reasonable bin size still surfaces to error tracking instead of looping.COMPACT_OFFSET_OVERFLOW_RETRIES = 3+# How long a tombstoned file survives before vacuum may delete it. Readers that pin an older+# table version must stay inside this window — see MAX_SNAPSHOT_ROLLBACK in the fan-out+# warehouse-parent reader, which derives its bound from this value.+VACUUM_RETENTION = dt.timedelta(hours=24)+class DeltaMaintenance:"""Compaction, vacuuming, and the vacuum-watermark cadence for one schema's Delta table.@@ -77,7 +83,11 @@ class DeltaMaintenance:# conflict checker as merge/optimize.compact — see execute_with_conflict_retry.vacuum_stats = await execute_with_conflict_retry(table,- lambda: table.vacuum(retention_hours=24, enforce_retention_duration=False, dry_run=False),+ lambda: table.vacuum(+ retention_hours=int(VACUUM_RETENTION.total_seconds() // 3600),+ enforce_retention_duration=False,+ dry_run=False,+ ),"vacuum_table",self._logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.pyindex 8e287d12fa8c..7812f3af134e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/table.py@@ -68,6 +68,16 @@ async def _purge_s3_prefix_once(s3: Any, uri: str) -> None:await s3._rm(uri, recursive=True)+def build_delta_table_uri(folder_path: str, resource_name: str) -> str:+ """Canonical S3 URI of a schema's Delta table.++ The writer (`DeltaTableRef`) and readers (e.g. the fan-out warehouse parent reader)+ must agree byte-for-byte on where a table lives; both derive it here.+ """+ normalized_name = NamingConvention.normalize_identifier(resource_name)+ return f"{settings.BUCKET_URL}/{folder_path}/{normalized_name}"++def delta_storage_options() -> dict[str, str]:"""delta-rs storage options for the data-warehouse bucket, independent of any import job — so aread path (e.g. the person-property backfill) can open a Delta table without constructing a full@@ -150,9 +160,8 @@ class DeltaTableRef:return delta_storage_options()async def _get_delta_table_uri(self) -> str:- normalized_resource_name = NamingConvention.normalize_identifier(self._resource_name)folder_path = await database_sync_to_async_pool(self._job.folder_path)()- return f"{settings.BUCKET_URL}/{folder_path}/{normalized_resource_name}"+ return build_delta_table_uri(folder_path, self._resource_name)async def get_table_uri(self) -> str:"""Public accessor for the live Delta table S3 URI (used by the in-place repartitioner)."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex e64cfed52ef7..29e4b6b5b19d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py@@ -222,6 +222,18 @@ class _BaseSource(ABC, Generic[ConfigType]):return set()+ def get_required_parent_schemas(self, schema_name: str) -> list[str]:+ """Sibling schemas `schema_name` reads from the warehouse instead of re-fetching.++ Non-empty only for fan-out children that read their parent from the warehouse+ (`DependentEndpointConfig.parent_source == "warehouse"`). Nothing requires these to+ be enabled: `import_data_activity_sync` checks them per run and falls back to the+ parent API when they aren't usable. Sources built on the shared REST fan-out wire+ this to `required_parents_from_endpoint_configs`.+ """++ return []+def get_canonical_descriptions(self) -> CanonicalDescriptions:"""Curated, documentation-sourced descriptions for this source's well-known tables/endpoints.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/fanout_reuse_flag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/fanout_reuse_flag.pynew file mode 100644index 000000000000..cf5ef7ce3b49--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/fanout_reuse_flag.py@@ -0,0 +1,40 @@+import posthoganalytics++from posthog.exceptions_capture import capture_exception+from posthog.models.team.team import Team++FANOUT_WAREHOUSE_REUSE_FLAG = "warehouse-fanout-parent-reuse"+++def is_fanout_warehouse_reuse_enabled(team_id: int) -> bool:+ """Gate for reading fan-out parents from the warehouse instead of the parent API.++ Fails closed: any error means "off", which keeps the legacy parent-API path.+ Lives in a leaf module (no deltalake/pyarrow) so callers can import it without pulling+ the Delta reader stack into their import graph.+ """+ try:+ team = Team.objects.only("uuid", "organization_id").get(id=team_id)+ except Team.DoesNotExist:+ return False+ except Exception as e:+ capture_exception(e)+ return False++ try:+ return bool(+ posthoganalytics.feature_enabled(+ FANOUT_WAREHOUSE_REUSE_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+ except Exception as e:+ capture_exception(e)+ return Falsediff --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__.pyindex 60418eaa3013..3cfc68ffe3c6 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@@ -302,7 +302,9 @@ def create_resources(hooks = create_response_hooks(endpoint_config.get("response_actions"))- resource_kwargs = exclude_keys(endpoint_resource, {"endpoint", "include_from_parent", "data_map"})+ resource_kwargs = exclude_keys(+ endpoint_resource, {"endpoint", "include_from_parent", "data_map", "data_iterator"}+ )columns_config = endpoint_resource.get("columns")@@ -320,7 +322,18 @@ def create_resources()}- if resolved_params is None:+ data_iterator = endpoint_resource.get("data_iterator")+ if data_iterator is not None:+ # Iterator-backed resource: pages come from the callable (e.g. an already-synced+ # warehouse parent table) instead of HTTP pagination. Downstream dependents consume+ # it via ``data_from`` exactly like an HTTP-backed parent.+ resources[resource_name] = Resource(+ data_iterator,+ name=resource_name,+ hints=hints,+ )++ elif resolved_params is None:def paginate_resource(method: HTTPMethodBasic,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.pyindex a49e3ac458ce..08344fbfdea3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py@@ -1,6 +1,8 @@from collections.abc import Callable, Iterable, Mappingfrom dataclasses import dataclass, field-from typing import Any, Protocol+from typing import Any, Literal, Protocol++import structlogfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -14,6 +16,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resResponseAction,)+logger = structlog.get_logger(__name__)+class FanoutEndpointLike(Protocol):name: str@@ -36,6 +40,24 @@ class DependentEndpointConfig:# 404 for a parent row deleted/merged between the parent listing and this child fetch)# without failing the whole fan-out — see resource.py's response_actions "ignore" handling.child_response_actions: list[ResponseAction] = field(default_factory=list)+ # "api" re-fetches the parent endpoint each child sync (legacy behavior). "warehouse"+ # drives the child from the parent schema's already-synced Delta table when that table is+ # usable, and falls back to "api" for the run when it isn't — see+ # `_warehouse_parent_reuse_available` in `import_data_activity_sync`.+ parent_source: Literal["api", "warehouse"] = "api"+++def required_parents_from_endpoint_configs(endpoint_configs: Mapping[str, Any], schema_name: str) -> list[str]:+ """Parents a schema reads from the warehouse when they're available, from its fan-out config.++ Generic wiring for `get_required_parent_schemas` overrides: returns the parent for+ endpoints whose fan-out reads the parent from the warehouse, `[]` otherwise.+ """+ config = endpoint_configs.get(schema_name)+ fanout = getattr(config, "fanout", None)+ if fanout is not None and fanout.parent_source == "warehouse":+ return [fanout.parent_name]+ return []def rename_parent_fields(parent_name: str, renames: dict[str, str]) -> Callable[[dict[str, Any]], dict[str, Any]]:@@ -72,10 +94,14 @@ def build_dependent_resource(page_size_param: str | None = "limit",resume_hook: Callable[[dict[str, Any] | None], None] | None = None,initial_paginator_state: dict[str, Any] | None = None,+ source_id: str | None = None,+ use_warehouse_parent: bool = False,) -> Iterable[Any]:parent_config = endpoint_configs[fanout.parent_name]child_config = endpoint_configs[child_endpoint]+ warehouse_parent = fanout.parent_source == "warehouse" and use_warehouse_parent+# page_size_param=None is for APIs whose list endpoints take no page-size param at all# (unpaginated, full-collection responses) — sending one would be an undocumented param.parent_params: dict[str, Any] = {} if page_size_param is None else {page_size_param: parent_config.page_size}@@ -104,6 +130,40 @@ def build_dependent_resource("table_format": "delta",}+ if warehouse_parent:+ if not source_id:+ raise ValueError("source_id is required when a fan-out reads its parent from the warehouse")+ # noqa reason: keeps deltalake/pyarrow off the import path of every source module —+ # the reader stack loads only when a warehouse-parent fan-out actually runs.+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import ( # noqa: PLC0415+ iter_parent_pages_from_warehouse,+ try_resolve_parent_table,+ )++ # Resolve the parent's table now, while we're in sync source-build context — the+ # iterator itself runs later on executor threads where ad-hoc ORM reads are fragile.+ # This also pins the Delta version the whole fan-out reads, and validates the columns+ # while a fallback is still possible.+ parent_columns = list(dict.fromkeys([fanout.resolve_field, *fanout.include_from_parent]))+ parent_table = try_resolve_parent_table(+ team_id=team_id,+ source_id=source_id,+ parent_name=fanout.parent_name,+ required_columns=parent_columns,+ schema_name=child_endpoint,+ )+ if parent_table is None:+ # Drop back to the API parent entirely, including the snapshot-only 404 handling+ # below, so the child syncs exactly the way it does without this feature.+ warehouse_parent = False+ else:+ parent_resource["data_iterator"] = lambda: iter_parent_pages_from_warehouse(+ table=parent_table,+ parent_name=fanout.parent_name,+ columns=parent_columns,+ page_size=parent_config.page_size,+ )+child_path = child_config.pathfor key, value in path_format_values.items():child_path = child_path.replace(f"{{{key}}}", value)@@ -141,6 +201,12 @@ def build_dependent_resource()child_endpoint_config.update(child_endpoint_extra)+ if warehouse_parent and "response_actions" not in child_endpoint_config:+ # The warehouse snapshot can contain parents deleted upstream since the parent's+ # last sync (incremental parents accumulate); their child fetch 404s. A fresh API+ # parent pull would simply not list them, so treat 404 as an empty child.+ child_endpoint_config["response_actions"] = [{"status_code": 404, "action": "ignore"}]+use_merge = should_use_incremental_field and bool(child_config.incremental_fields)if use_merge:if incremental_config_factory is None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.pyindex 623ab30b5ef1..8ab552d36418 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_fanout.py@@ -10,9 +10,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (DependentEndpointConfig,build_dependent_resource,+ required_parents_from_endpoint_configs,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginatorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResolvedParam+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ ParentTableRef,+)+++def _stub_child_resource() -> Mock:+ """Stand-in for the dlt resource `build_dependent_resource` looks up by name and maps."""+ stub = Mock()+ stub.name = "children"+ stub.add_map.return_value = stub+ return stub@dataclass@@ -51,26 +63,23 @@ def _build_endpoint_configs() -> dict[str, _EndpointConfig]:@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_uses_custom_page_size_param(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []- try:- build_dependent_resource(- endpoint_configs=_build_endpoint_configs(),- child_endpoint="children",- fanout=DependentEndpointConfig(- parent_name="parents",- resolve_param="parent_id",- resolve_field="id",- include_from_parent=["id"],- ),- client_config={"base_url": "https://example.com"},- path_format_values={},- team_id=1,- job_id="job-1",- db_incremental_field_last_value=None,- page_size_param="page_size",- )- except StopIteration:- pass+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ ),+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ page_size_param="page_size",+ )config = mock_rest_api_resources.call_args.args[0]parent_resource = config["resources"][0]@@ -83,27 +92,24 @@ def test_build_dependent_resource_uses_custom_page_size_param(mock_rest_api_reso@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_forwards_endpoint_extras(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []- try:- build_dependent_resource(- endpoint_configs=_build_endpoint_configs(),- child_endpoint="children",- fanout=DependentEndpointConfig(- parent_name="parents",- resolve_param="parent_id",- resolve_field="id",- include_from_parent=["id"],- ),- client_config={"base_url": "https://example.com"},- path_format_values={},- team_id=1,- job_id="job-1",- db_incremental_field_last_value=None,- parent_endpoint_extra={"data_selector": "items", "paginator": _DummyPaginator()},- child_endpoint_extra={"data_selector": "items", "paginator": _DummyPaginator()},- )- except StopIteration:- pass+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ ),+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ parent_endpoint_extra={"data_selector": "items", "paginator": _DummyPaginator()},+ child_endpoint_extra={"data_selector": "items", "paginator": _DummyPaginator()},+ )config = mock_rest_api_resources.call_args.args[0]parent_endpoint = config["resources"][0]["endpoint"]@@ -116,25 +122,22 @@ def test_build_dependent_resource_forwards_endpoint_extras(mock_rest_api_resourc@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_backwards_compatible_defaults(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []- try:- build_dependent_resource(- endpoint_configs=_build_endpoint_configs(),- child_endpoint="children",- fanout=DependentEndpointConfig(- parent_name="parents",- resolve_param="parent_id",- resolve_field="id",- include_from_parent=["id"],- ),- client_config={"base_url": "https://example.com"},- path_format_values={},- team_id=1,- job_id="job-1",- db_incremental_field_last_value=None,- )- except StopIteration:- pass+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ ),+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ )config = mock_rest_api_resources.call_args.args[0]parent_resource = config["resources"][0]@@ -150,26 +153,23 @@ def test_build_dependent_resource_backwards_compatible_defaults(mock_rest_api_re@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_merges_fanout_child_params(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []- try:- build_dependent_resource(- endpoint_configs=_build_endpoint_configs(),- child_endpoint="children",- fanout=DependentEndpointConfig(- parent_name="parents",- resolve_param="parent_id",- resolve_field="id",- include_from_parent=["id"],- child_params={"full": "true"},- ),- client_config={"base_url": "https://example.com"},- path_format_values={},- team_id=1,- job_id="job-1",- db_incremental_field_last_value=None,- )- except StopIteration:- pass+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ child_params={"full": "true"},+ ),+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ )config = mock_rest_api_resources.call_args.args[0]parent_params = config["resources"][0]["endpoint"]["params"]@@ -184,26 +184,23 @@ def test_build_dependent_resource_merges_fanout_child_params(mock_rest_api_resou@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_forwards_child_response_actions(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []- try:- build_dependent_resource(- endpoint_configs=_build_endpoint_configs(),- child_endpoint="children",- fanout=DependentEndpointConfig(- parent_name="parents",- resolve_param="parent_id",- resolve_field="id",- include_from_parent=["id"],- child_response_actions=[{"status_code": 404, "action": "ignore"}],- ),- client_config={"base_url": "https://example.com"},- path_format_values={},- team_id=1,- job_id="job-1",- db_incremental_field_last_value=None,- )- except StopIteration:- pass+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ )config = mock_rest_api_resources.call_args.args[0]parent_resource = config["resources"][0]@@ -215,7 +212,7 @@ def test_build_dependent_resource_forwards_child_response_actions(mock_rest_api_@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_rejects_child_params_clobbering_resolve(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []+ mock_rest_api_resources.return_value = [_stub_child_resource()]with pytest.raises(ValueError, match="must not include the resolve param 'parent_id'"):build_dependent_resource(@@ -238,29 +235,26 @@ def test_build_dependent_resource_rejects_child_params_clobbering_resolve(mock_r@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_threads_resume_state(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []+ mock_rest_api_resources.return_value = [_stub_child_resource()]resume_hook = Mock()initial_state = {"completed": ["/parents/a/children"], "current": None, "child_state": None}- try:- build_dependent_resource(- endpoint_configs=_build_endpoint_configs(),- child_endpoint="children",- fanout=DependentEndpointConfig(- parent_name="parents",- resolve_param="parent_id",- resolve_field="id",- include_from_parent=["id"],- ),- client_config={"base_url": "https://example.com"},- path_format_values={},- team_id=1,- job_id="job-1",- db_incremental_field_last_value=None,- resume_hook=resume_hook,- initial_paginator_state=initial_state,- )- except StopIteration:- pass+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ ),+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ resume_hook=resume_hook,+ initial_paginator_state=initial_state,+ )kwargs = mock_rest_api_resources.call_args.kwargsassert kwargs["resume_hook"] is resume_hook@@ -269,7 +263,7 @@ def test_build_dependent_resource_threads_resume_state(mock_rest_api_resources)@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")def test_build_dependent_resource_rejects_params_in_endpoint_extras(mock_rest_api_resources) -> None:- mock_rest_api_resources.return_value = []+ mock_rest_api_resources.return_value = [_stub_child_resource()]with pytest.raises(ValueError, match="Do not pass 'params' in child_endpoint_extra"):build_dependent_resource(@@ -458,3 +452,207 @@ def test_dependent_resume_disabled_without_hook_processes_all() -> None:)rows = _drive(_dependent_fn(client, resume_hook=None))assert [r["id"] for r in rows] == ["a1", "b1"]+++_WAREHOUSE_FANOUT = DependentEndpointConfig(+ parent_name="parents",+ resolve_param="parent_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "parent_id"},+ parent_source="warehouse",+)+++@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")+@patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_1_x_y/parents", version=7),+)+@patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse"+)+def test_warehouse_parent_builds_data_iterator_and_404_ignore(+ mock_reader, mock_resolve, mock_rest_api_resources+) -> None:+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ mock_reader.return_value = iter([[{"id": "p1"}]])+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=_WAREHOUSE_FANOUT,+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ source_id="source-1",+ use_warehouse_parent=True,+ )++ # The URI and columns are resolved eagerly at build time (sync context), not lazily on+ # iteration — a lazy check would raise past the fall-back-to-the-API branch.+ mock_resolve.assert_called_once_with(1, "source-1", "parents", required_columns=["id"])++ config = mock_rest_api_resources.call_args.args[0]+ parent_resource = config["resources"][0]+ child_resource = config["resources"][1]++ pages = list(parent_resource["data_iterator"]())+ assert pages == [[{"id": "p1"}]]+ mock_reader.assert_called_once_with(+ table=ParentTableRef(uri="s3://bucket/team_1_x_y/parents", version=7),+ parent_name="parents",+ columns=["id"],+ page_size=3,+ )+ assert child_resource["endpoint"]["response_actions"] == [{"status_code": 404, "action": "ignore"}]+++@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")+def test_warehouse_parent_config_stays_on_api_path_when_not_enabled(mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=_WAREHOUSE_FANOUT,+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ source_id="source-1",+ use_warehouse_parent=False,+ )++ config = mock_rest_api_resources.call_args.args[0]+ parent_resource = config["resources"][0]+ child_resource = config["resources"][1]+ assert "data_iterator" not in parent_resource+ assert parent_resource["endpoint"]["params"]["limit"] == 3+ assert "response_actions" not in child_resource["endpoint"]+++@patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.resolve_parent_table_ref"+)+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")+def test_unreadable_parent_table_falls_back_to_the_api_path(mock_rest_api_resources, mock_resolve) -> None:+ # The schema row can say the parent synced while its table is gone (purged) or missing the+ # fan-out columns. Failing here would break a child that syncs fine off the parent API.+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ WarehouseParentTableNotFoundError,+ )++ mock_resolve.side_effect = WarehouseParentTableNotFoundError("table gone")+ mock_rest_api_resources.return_value = [_stub_child_resource()]+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=_WAREHOUSE_FANOUT,+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ source_id="source-1",+ use_warehouse_parent=True,+ )++ config = mock_rest_api_resources.call_args.args[0]+ parent_resource = config["resources"][0]+ assert "data_iterator" not in parent_resource+ assert parent_resource["endpoint"]["params"]["limit"] == 3+ # The snapshot-only 404 handling goes with it: a fresh API parent doesn't list stale rows.+ assert "response_actions" not in config["resources"][1]["endpoint"]+++def test_warehouse_parent_requires_source_id() -> None:+ with pytest.raises(ValueError, match="source_id is required"):+ build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=_WAREHOUSE_FANOUT,+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ use_warehouse_parent=True,+ )+++class _FakeChildOnlyClient:+ """Fails the test if any request goes to the parent listing path."""++ def __init__(self) -> None:+ self.requested_paths: list[str] = []++ def paginate(self, *, method, path, params, paginator, data_selector, hooks, **kwargs):+ self.requested_paths.append(path)+ assert path != "/parents", "warehouse-parent fan-out must not fetch the parent endpoint"+ parent_id = path.split("/")[2]+ yield [{"id": f"child-of-{parent_id}"}]+++@patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_1_x_y/parents", version=7),+)+@patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse"+)+def test_warehouse_parent_drives_child_without_parent_http(mock_reader, _mock_resolve) -> None:+ mock_reader.return_value = iter([[{"id": "p1"}, {"id": "p2"}], [{"id": "p3"}]])+ fake_client = _FakeChildOnlyClient()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.RESTClient",+ return_value=fake_client,+ ):+ resource = build_dependent_resource(+ endpoint_configs=_build_endpoint_configs(),+ child_endpoint="children",+ fanout=_WAREHOUSE_FANOUT,+ client_config={"base_url": "https://example.com"},+ path_format_values={},+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=None,+ source_id="source-1",+ use_warehouse_parent=True,+ )+ rows = [row for page in resource for row in page]++ # One child fetch per warehouse parent row, parent id injected and renamed.+ assert rows == [+ {"id": "child-of-p1", "parent_id": "p1"},+ {"id": "child-of-p2", "parent_id": "p2"},+ {"id": "child-of-p3", "parent_id": "p3"},+ ]+ assert fake_client.requested_paths == [+ "/parents/p1/children",+ "/parents/p2/children",+ "/parents/p3/children",+ ]+++class _ConfigWithFanout:+ def __init__(self, fanout: DependentEndpointConfig | None) -> None:+ self.fanout = fanout+++def test_required_parents_from_endpoint_configs() -> None:+ configs = {+ "children": _ConfigWithFanout(_WAREHOUSE_FANOUT),+ "api_children": _ConfigWithFanout(+ DependentEndpointConfig(+ parent_name="parents", resolve_param="parent_id", resolve_field="id", include_from_parent=[]+ )+ ),+ "parents": _ConfigWithFanout(None),+ }+ assert required_parents_from_endpoint_configs(configs, "children") == ["parents"]+ assert required_parents_from_endpoint_configs(configs, "api_children") == []+ assert required_parents_from_endpoint_configs(configs, "parents") == []+ assert required_parents_from_endpoint_configs(configs, "unknown") == []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.pynew file mode 100644index 000000000000..aec03a5514ce--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py@@ -0,0 +1,248 @@+from datetime import UTC, datetime, timedelta+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from posthog.test.base import APIBaseTest+from unittest.mock import patch++import pyarrow as pa+import deltalake+from parameterized import parameterized++from products.warehouse_sources.backend.facade.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import warehouse_parent+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ ParentTableRef,+ WarehouseParentTableNotFoundError,+ iter_parent_pages_from_warehouse,+ resolve_parent_table_ref,+)+++def _write_parent_table(tmp_path: Path) -> str:+ uri = str(tmp_path / "issues")+ # Physical columns are snake_case — the Delta writer normalizes API field names.+ table = pa.table(+ {+ "id": ["1", "2", "3"],+ "last_seen": ["2026-03-01", "2026-03-03", "2026-03-02"],+ "title": ["a", "b", "c"],+ }+ )+ deltalake.write_deltalake(uri, table)+ return uri+++def _patched_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_from_warehouse(table=ref, parent_name="issues", **kwargs))+++def _patched_resolve(uri: str, snapshot_timestamp=None):+ parent_schema = SimpleNamespace(+ id="parent-id", normalized_s3_folder_name="issues", folder_path=lambda: "team_1_sentry_x"+ )+ with (+ patch.object(warehouse_parent, "get_schema_if_exists", return_value=parent_schema),+ patch.object(warehouse_parent, "build_delta_table_uri", return_value=uri),+ patch.object(warehouse_parent, "delta_storage_options", return_value={}),+ patch.object(warehouse_parent, "_snapshot_pin_as_of", return_value=snapshot_timestamp),+ ):+ return resolve_parent_table_ref(1, "00000000-0000-0000-0000-000000000000", "issues")+++def test_resolve_parent_table_ref_raises_when_parent_schema_missing() -> None:+ with patch.object(warehouse_parent, "get_schema_if_exists", return_value=None):+ with pytest.raises(WarehouseParentTableNotFoundError, match="does not exist for source"):+ resolve_parent_table_ref(1, "00000000-0000-0000-0000-000000000000", "issues")+++ "unexpected_error",+ [RuntimeError("s3 connection reset"), ValueError("badly formed hexadecimal UUID string")],+)+def test_resolve_wraps_unexpected_errors_so_callers_can_fall_back(unexpected_error: Exception) -> None:+ # Callers catch only WarehouseParentTableNotFoundError as the fall-back-to-the-API+ # signal; any other exception class escaping resolve fails the whole run instead.+ with patch.object(warehouse_parent, "get_schema_if_exists", side_effect=unexpected_error):+ with pytest.raises(WarehouseParentTableNotFoundError, match="could not be resolved") as exc_info:+ resolve_parent_table_ref(1, "00000000-0000-0000-0000-000000000000", "issues")++ assert exc_info.value.__cause__ is unexpected_error+++def test_reader_floors_page_size_to_one(tmp_path: Path) -> None:+ uri = _write_parent_table(tmp_path)++ pages = _patched_reader(uri, columns=["id"], page_size=0)++ assert [len(page) for page in pages] == [1, 1, 1]+++def test_reader_caps_page_size(tmp_path: Path) -> None:+ uri = _write_parent_table(tmp_path)++ with patch.object(warehouse_parent, "MAX_PARENT_PAGE_SIZE", 2):+ pages = _patched_reader(uri, columns=["id"], page_size=10_000_000)++ assert [len(page) for page in pages] == [2, 1]+++def test_reader_pages_and_rekeys_to_api_field_names(tmp_path: Path) -> None:+ uri = _write_parent_table(tmp_path)++ pages = _patched_reader(uri, columns=["id", "lastSeen"], page_size=2)++ assert [len(page) for page in pages] == [2, 1]+ rows = [row for page in pages for row in page]+ # Keys come back as the API field names, values from the snake_case physical columns,+ # and only the requested columns are present.+ assert {row["id"]: row["lastSeen"] for row in rows} == {+ "1": "2026-03-01",+ "2": "2026-03-03",+ "3": "2026-03-02",+ }+ assert all(set(row) == {"id", "lastSeen"} for row in rows)+++def test_resolve_raises_when_parent_has_no_synced_table(tmp_path: Path) -> None:+ with pytest.raises(WarehouseParentTableNotFoundError, match="no synced table"):+ _patched_resolve(str(tmp_path / "does_not_exist"))+++def test_resolve_pins_to_last_completed_snapshot_while_parent_is_syncing(tmp_path: Path) -> None:+ uri = _write_parent_table(tmp_path)+ v0_table = deltalake.DeltaTable(uri)+ v0 = v0_table.version()+ v0_timestamp = datetime.fromtimestamp(v0_table.history()[0]["timestamp"] / 1000, tz=UTC)++ # An in-flight full refresh has already committed a partial overwrite on top of v0.+ deltalake.write_deltalake(uri, pa.table({"id": ["partial"], "last_seen": ["x"], "title": ["y"]}), mode="overwrite")++ pinned = _patched_resolve(uri, snapshot_timestamp=v0_timestamp)++ assert pinned.version == v0+++class TestSnapshotPinAsOf(APIBaseTest):+ def _schema_with_jobs(self, statuses: list[str], finished_at_hours_ago: float = 1.0) -> tuple[Any, dict[int, Any]]:+ """Jobs in the given order, oldest first, all finishing `finished_at_hours_ago` back."""+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Sentry",+ job_inputs={"auth_token": "token", "organization_slug": "acme"},+ )+ schema = ExternalDataSchema.objects.create(name="issues", team=self.team, source=source)+ now = datetime.now(UTC)+ finished_at_by_index: dict[int, Any] = {}+ for job_index, job_status in enumerate(statuses):+ created_at = now - timedelta(hours=finished_at_hours_ago, minutes=10 * (len(statuses) - job_index))+ finished_at = now - timedelta(hours=finished_at_hours_ago, minutes=len(statuses) - job_index)+ job = ExternalDataJob.objects.create(+ team=self.team,+ pipeline=source,+ schema=schema,+ status=job_status,+ workflow_id=f"wf-{job_index}",+ finished_at=finished_at,+ )+ # auto_now_add ignores a passed created_at; the newest-job ordering needs it real.+ ExternalDataJob.objects.filter(id=job.id).update(created_at=created_at)+ finished_at_by_index[job_index] = finished_at+ return schema, finished_at_by_index++ @parameterized.expand(+ [+ # A COMPLETED newest job means the latest version is a finished snapshot (plus+ # maintenance commits, which must not be pinned away): no rollback.+ ("no_jobs", [], None),+ ("newest_completed", ["Completed"], None),+ ("completed_after_failure", ["Failed", "Completed"], None),+ # A newest job that is running or died mid-write may have left a torn latest+ # version: roll back to the last completed job's finish time.+ ("newest_running", ["Completed", "Running"], 0),+ ("newest_failed", ["Completed", "Failed"], 0),+ ("newest_billing_limited_after_two", ["Completed", "Completed", "BillingLimitReached"], 1),+ ]+ )+ def test_rolls_back_only_when_the_newest_job_is_not_completed(+ self, _name, statuses, expected_completed_index+ ) -> None:+ schema, finished_at_by_index = self._schema_with_jobs(statuses)++ result = warehouse_parent._snapshot_pin_as_of(self.team.pk, schema.id)++ if expected_completed_index is None:+ assert result is None+ else:+ assert result == finished_at_by_index[expected_completed_index]++ def test_raises_when_rollback_is_needed_but_no_job_ever_completed(self) -> None:+ schema, _ = self._schema_with_jobs(["Failed"])++ with pytest.raises(WarehouseParentTableNotFoundError, match="no completed job"):+ warehouse_parent._snapshot_pin_as_of(self.team.pk, schema.id)++ def test_refuses_a_rollback_older_than_the_vacuum_window(self) -> None:+ # A parent that fails every attempt would otherwise pin children to an ever-older+ # snapshot whose files its retries eventually tombstone and vacuum, and that missing+ # -file error lands inside the reader, past the caller's fallback.+ schema, _ = self._schema_with_jobs(["Completed", "Failed"], finished_at_hours_ago=30)++ with pytest.raises(WarehouseParentTableNotFoundError, match="beyond the window"):+ warehouse_parent._snapshot_pin_as_of(self.team.pk, schema.id)++ def test_ignores_completed_jobs_predating_the_finished_at_column(self) -> None:+ # Postgres sorts NULLs first on a descending order_by, so a legacy NULL row would+ # otherwise mask every newer completed job and disable the feature for old sources.+ schema, finished_at_by_index = self._schema_with_jobs(["Completed", "Completed", "Running"])+ oldest_job = ExternalDataJob.objects.filter(team_id=self.team.pk, schema_id=schema.id).earliest("created_at")+ ExternalDataJob.objects.filter(id=oldest_job.id).update(finished_at=None)++ result = warehouse_parent._snapshot_pin_as_of(self.team.pk, schema.id)++ assert result == finished_at_by_index[1]+++def test_reader_stays_on_the_pinned_version_when_the_parent_re_syncs(tmp_path: Path) -> None:+ uri = _write_parent_table(tmp_path)+ pinned = _patched_resolve(uri)++ # The parent's next full refresh overwrites the table while the child is still fanning out.+ deltalake.write_deltalake(+ uri,+ pa.table({"id": ["9"], "last_seen": ["2026-04-01"], "title": ["z"]}),+ mode="overwrite",+ )++ with patch.object(warehouse_parent, "delta_storage_options", return_value={}):+ pages = list(iter_parent_pages_from_warehouse(table=pinned, parent_name="issues", columns=["id"], page_size=10))++ assert sorted(row["id"] for page in pages for row in page) == ["1", "2", "3"]+++def test_reader_raises_when_requested_columns_missing(tmp_path: Path) -> None:+ uri = _write_parent_table(tmp_path)++ # A partial miss must fail loudly upfront too — a silently dropped column would surface+ # later as an opaque resolve error mid-sync.+ with pytest.raises(+ WarehouseParentTableNotFoundError, match=r"missing requested column\(s\) \['definitely_missing'\]"+ ):+ _patched_reader(uri, columns=["id", "definitely_missing"], page_size=10)+++def test_reader_streams_multiple_fragments(tmp_path: Path) -> None:+ uri = str(tmp_path / "issues")+ # Two separate Delta commits produce multiple parquet fragments — the streamed scan+ # must walk them all without materializing the table.+ deltalake.write_deltalake(uri, pa.table({"id": ["1", "2"], "last_seen": ["a", "b"]}))+ deltalake.write_deltalake(uri, pa.table({"id": ["3"], "last_seen": ["c"]}), mode="append")++ pages = _patched_reader(uri, columns=["id"], page_size=2)++ rows = sorted(row["id"] for page in pages for row in page)+ assert rows == ["1", "2", "3"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.pyindex 6368cd854b6c..191c89c09acf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/typing.py@@ -1,4 +1,4 @@-from collections.abc import Callable+from collections.abc import Callable, Iteratorfrom dataclasses import dataclass, fieldfrom typing import Any, Literal, NotRequired, Optional, TypedDict@@ -300,6 +300,10 @@ class EndpointResourceBase(ResourceBase, total=False):# a row the selector can't express (e.g. flattening JSON:API ``attributes`` into the row root).# Wired through to ``Resource.add_map``; must be dict -> dict (1:1).data_map: Optional[Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]]+ # When set, the resource's pages come from this callable instead of HTTP pagination —+ # ``endpoint`` is kept only for dependency-graph bookkeeping. Used to drive a fan-out+ # child from an already-synced warehouse parent table.+ data_iterator: Optional[Callable[[], Iterator[list[dict[str, Any]]]]]class EndpointResource(EndpointResourceBase, total=False):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.pynew file mode 100644index 000000000000..7ebe7c32ec08--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py@@ -0,0 +1,286 @@+import uuid+import datetime as dt+from collections.abc import Iterator+from dataclasses import dataclass+from typing import Any++import deltalake+import structlog++from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob+from products.warehouse_sources.backend.models.external_data_schema import get_schema_if_exists+from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (+ pyarrow_schema_from_arrow_exportable,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import VACUUM_RETENTION+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import (+ build_delta_table_uri,+ delta_storage_options,+)++# Upper bound on rows held in memory per page. Source configs drive page_size for API paging+# semantics; a misconfigured or future large value must not turn into a whole-table page.+MAX_PARENT_PAGE_SIZE = 5000++# How far back a snapshot pin may reach. Derived from the writer's vacuum retention, with+# margin, so a pinned version's files can't have been tombstoned and vacuumed out from under+# an in-flight fan-out. Vacuum keys deletion off tombstone age, and a file live at the pinned+# version can only be tombstoned after that version, so any pin inside the window is safe.+MAX_SNAPSHOT_ROLLBACK = VACUUM_RETENTION - dt.timedelta(hours=4)++logger = structlog.get_logger(__name__)+++class WarehouseParentTableNotFoundError(Exception):+ """The fan-out parent schema has no readable Delta table to fan out over.++ The run-time check in `import_data_activity_sync` only sees Postgres, so the table can+ still be missing, purged, or short a column. Callers of `resolve_parent_table_ref` catch+ this and fall back to the parent API for that run, which is why the check is eager.+ """+++@dataclass(frozen=True)+class ParentTableRef:+ """A parent Delta table pinned to one version, so the whole fan-out reads one snapshot."""++ uri: str+ version: int+++def _physical_columns_by_api_name(+ delta_table: "deltalake.DeltaTable", parent_name: str, columns: list[str]+) -> dict[str, str]:+ """Map API field names to the snake_case identifiers the Delta writer stored them under."""+ physical_schema_names = set(pyarrow_schema_from_arrow_exportable(delta_table.schema()).names)++ physical_by_api_name: dict[str, str] = {}+ missing_columns: list[str] = []+ for api_name in columns:+ physical = NamingConvention.normalize_identifier(api_name)+ if physical in physical_schema_names:+ physical_by_api_name[api_name] = physical+ else:+ missing_columns.append(api_name)++ if missing_columns:+ raise WarehouseParentTableNotFoundError(+ f"Parent table '{parent_name}' is missing requested column(s) {missing_columns} — "+ f"re-sync the parent schema so the fan-out fields are present"+ )+ return physical_by_api_name+++def resolve_parent_table_ref(+ team_id: int, source_id: str, parent_name: str, required_columns: list[str] | None = None+) -> ParentTableRef:+ """Locate the parent schema row, derive its Delta table URI, and pin the current version.++ Does a Django ORM read — call it from sync context at source-build time (e.g. inside+ `source_for_pipeline`), NOT lazily from the pipeline's iterator executor threads, whose+ ad-hoc DB connections are exactly the pooler-drop failure mode `ExternalDataSchema.save`+ documents. The storage leaf comes from `normalized_s3_folder_name`, the same property the+ writer resolves, so legacy-migrated rows land on the same table either side.++ The version is pinned here rather than at first read: the read is lazy and can start minutes+ into the pipeline, by which time a full-refresh parent may be mid-rewrite (overwrite + appends+ across several commits). Pinning means later parent commits are invisible to this run — the+ child fans out over one complete snapshot instead of a torn one.++ A parent whose newest job is not COMPLETED doesn't block the child: the pin rolls back+ to the version as of the parent's last completed job (Delta time travel), which is a+ complete snapshot by definition. That covers a writer that is mid-sync and one that+ failed mid-write, whose torn overwrite+appends would otherwise be the table's latest+ version with no RUNNING row to betray it. A rollback target older than+ `MAX_SNAPSHOT_ROLLBACK` is refused instead, keeping the pin inside the window where its+ files are safe from vacuum. What remains is clock skew: the rollback compares Postgres+ `finished_at` against Delta commit timestamps stamped by (possibly different) worker+ clocks, so backward skew exceeding the final-commit-to-`finished_at` gap could pull an+ in-flight commit under the pin. That surfaces as a retryable read failure, not corrupt+ data.++ Only ever raises WarehouseParentTableNotFoundError: callers treat it as the+ fall-back-to-the-API signal, so an unexpected error here (S3, a corrupt Delta log, a+ malformed source_id) must become that signal too, not fail the run past their handler.+ """+ try:+ parent_schema = get_schema_if_exists(parent_name, team_id, uuid.UUID(source_id))+ if parent_schema is None:+ raise WarehouseParentTableNotFoundError(+ f"Parent schema '{parent_name}' does not exist for source {source_id}"+ )+ uri = build_delta_table_uri(parent_schema.folder_path(), parent_schema.normalized_s3_folder_name)++ storage_options = delta_storage_options()+ if not deltalake.DeltaTable.is_deltatable(uri, storage_options=storage_options):+ raise WarehouseParentTableNotFoundError(+ f"Parent schema '{parent_name}' has no synced table yet — complete its initial sync first"+ )+ delta_table = deltalake.DeltaTable(uri, storage_options=storage_options)++ as_of = _snapshot_pin_as_of(team_id, parent_schema.id)+ if as_of is not None:+ delta_table.load_as_version(as_of)+ if required_columns:+ # Validate eagerly: the reader is a generator, so a missing column would otherwise+ # surface deep inside the pipeline, past the caller's fall-back-to-the-API branch.+ _physical_columns_by_api_name(delta_table, parent_name, required_columns)+ return ParentTableRef(uri=uri, version=delta_table.version())+ except WarehouseParentTableNotFoundError:+ raise+ except Exception as e:+ raise WarehouseParentTableNotFoundError(f"Parent table '{parent_name}' could not be resolved: {e}") from e+++def try_resolve_parent_table(+ *,+ team_id: int,+ source_id: str,+ parent_name: str,+ required_columns: list[str],+ schema_name: str,+) -> ParentTableRef | None:+ """Resolve the parent table, or None when this run must read the parent from the API.++ The fallback branch every caller needs, in one place: `resolve_parent_table_ref` raises+ only `WarehouseParentTableNotFoundError`, so None covers a missing, unreadable, or+ too-stale parent table. Callers must treat None as "use the API parent", including any+ behavior that only makes sense over a warehouse snapshot.+ """+ try:+ return resolve_parent_table_ref(team_id, source_id, parent_name, required_columns=required_columns)+ except WarehouseParentTableNotFoundError:+ # Same event name as the run-time gate's fallback log, so one stream covers every+ # fallback class.+ logger.warning(+ "data_imports.fanout_parent_unusable",+ schema=schema_name,+ parent=parent_name,+ reason="table_unreadable",+ exc_info=True,+ )+ return None+++def _snapshot_pin_as_of(team_id: int, parent_schema_id: uuid.UUID) -> dt.datetime | None:+ """The timestamp to time-travel the parent table to, or None to read its latest version.++ Raises rather than returning a pin that can't be trusted, so the caller falls back to the+ parent API.++ None means "read the latest version", which is right when the parent's newest job+ COMPLETED: commits after it are maintenance (compaction), and pinning behind a compaction+ can point at files a later vacuum removed. A newest job that is RUNNING or terminally+ failed may instead have left a torn overwrite+appends as the latest version, so the read+ rolls back to the last completed snapshot. The completed-job timestamp deliberately comes+ from Postgres, not the Delta log: `finished_at` is stamped strictly after the job's final+ commit, so every commit at or before it belongs to a finished run.++ The COMPLETED-newest case is not airtight — `update_external_job_status` documents a+ lock-takeover where a zombie loader keeps writing after its job was force-failed and a+ newer job completed, so a writer can still be live. That yields one torn parent list and+ self-heals on the next run, which is why it doesn't force a rollback here.++ A rollback target older than MAX_SNAPSHOT_ROLLBACK is refused. A parent that fails every+ attempt would otherwise pin children to an ever-older snapshot while its retries keep+ tombstoning and vacuuming those files, and the resulting missing-file error surfaces+ inside the reader's generator, past the caller's fallback.+ """+ newest_job_status = (+ ExternalDataJob.objects.filter(team_id=team_id, schema_id=parent_schema_id)+ .order_by("-created_at")+ .values_list("status", flat=True)+ .first()+ )+ if newest_job_status is None or newest_job_status == ExternalDataJob.Status.COMPLETED:+ return None+ last_completed = (+ ExternalDataJob.objects.filter(+ team_id=team_id,+ schema_id=parent_schema_id,+ status=ExternalDataJob.Status.COMPLETED,+ # Postgres sorts NULLs first on a descending order_by, and jobs predating the+ # `finished_at` column still carry NULL — without this, `.first()` returns one of+ # those and hides every newer completed job.+ finished_at__isnull=False,+ )+ .order_by("-finished_at")+ .values_list("finished_at", flat=True)+ .first()+ )+ if last_completed is None:+ # No completed job to pin to (e.g. purged history) while the latest version can't be+ # trusted — let the caller fall back to the API.+ raise WarehouseParentTableNotFoundError("Parent schema has no completed job to snapshot from")+ if dt.datetime.now(dt.UTC) - last_completed > MAX_SNAPSHOT_ROLLBACK:+ raise WarehouseParentTableNotFoundError(+ f"Parent schema's last completed sync finished {last_completed.isoformat()}, "+ f"beyond the window where its files are guaranteed to survive vacuum"+ )+ return last_completed+++def iter_parent_pages_from_warehouse(+ *,+ table: ParentTableRef,+ parent_name: str,+ columns: list[str],+ page_size: int,+ schema_name: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ """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+ (`list[dict]` keyed by the parent API's field names), so a child resource can be driven by+ this iterator instead of re-pulling the parent endpoint. Values are NOT identical to the+ API's: they carry the Delta column's physical type, so a timestamp comes back as a+ datetime rather than the API's ISO string, and a nested object as a dict. Only project+ `include_from_parent` fields whose physical type matches what the API returned, or the+ child table's column type will flip between runs as the API fallback engages.++ Reads the version pinned by `resolve_parent_table_ref`, so a parent re-syncing during the+ (potentially long) fan-out can't shift the rows underneath it.++ `columns` are API field names (e.g. ``lastSeen``); the Delta writer stores snake_case+ identifiers, so each is normalized to locate the physical column and rows are re-keyed+ back to the API names.++ Strictly streaming: the scan holds one projected batch in memory at a time, with column+ projection pushed down to the parquet read. No sorting, no dedupe state — rows are+ assumed unique per parent, which holds for merge/full-refresh parents by construction;+ append-mode parents accumulate duplicates, so the run-time check in+ `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.+ """+ 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())+ physical_by_api_name = _physical_columns_by_api_name(delta_table, parent_name, columns)++ projected = list(dict.fromkeys(physical_by_api_name.values()))+ dataset = delta_table.to_pyarrow_dataset()++ rows_streamed = 0+ page: list[dict[str, Any]] = []+ for batch in dataset.to_batches(columns=projected, batch_size=page_size):+ for row in batch.to_pylist():+ 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++ # The snapshot only grows for an incremental parent, while the vendor's own listing drops+ # rows past its retention. This count against the child's stale-parent skips is how we tell+ # whether the fan-out set has drifted above what the API would return — see the reuse+ # follow-up in the plan.+ logger.info(+ "data_imports.fanout_parent_rows_streamed",+ schema=schema_name,+ parent=parent_name,+ rows=rows_streamed,+ version=table.version,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_fanout_reuse_flag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_fanout_reuse_flag.pynew file mode 100644index 000000000000..a40146d44a68--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_fanout_reuse_flag.py@@ -0,0 +1,28 @@+import pytest+from unittest.mock import patch++from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_reuse_flag import (+ is_fanout_warehouse_reuse_enabled,+)+++class TestFanoutReuseFlagFailsClosed:+ # Fail-closed is the contract every consumer relies on: a falsy result keeps the legacy+ # parent-API path. If the try/except narrows, a flag-service blip becomes failed sync runs.++ def test_flag_service_error_returns_false(self):+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_reuse_flag.Team"+ ) as team_cls,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_reuse_flag.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flags endpoint down"),+ ),+ ):+ team_cls.objects.get.return_value.uuid = "u"+ assert is_fanout_warehouse_reuse_enabled(1) is False++ @pytest.mark.django_db+ def test_missing_team_returns_false(self):+ assert is_fanout_warehouse_reuse_enabled(999999999) is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex 8e54ffdaadc1..0c5492594459 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py@@ -103,3 +103,7 @@ class SourceInputs:# Effective vendor API version: the source instance's pin resolved through the source's# `default_version`. Sources with a versioned vendor API thread it to their request layer.api_version: Optional[str] = None+ # True when this schema is a fan-out child whose parent should be read from the warehouse+ # (flag on + parents verified synced). Evaluated once by the run-time gate in+ # `import_data_activity_sync` so sources don't re-evaluate the feature flag per run.+ fanout_warehouse_reuse: bool = Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/sentry.pyindex 6c21a3921f5b..848f8679e2e1 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@@ -2,9 +2,14 @@ import reimport dataclassesfrom collections.abc import Callable, Iterable, Iteratorfrom datetime import UTC, datetime, timedelta-from typing import Any, Optional, cast+from typing import TYPE_CHECKING, Any, Optional, castfrom urllib.parse import quote, urljoin, urlparse+if TYPE_CHECKING:+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ ParentTableRef,+ )+import structlogfrom dateutil import parser as dateutil_parserfrom requests import Request, Response@@ -78,6 +83,10 @@ class SentryResumeConfig:issue_id: Optional[str] = Nonetag_key: Optional[str] = Nonevalues_next_url: Optional[str] = None+ # Which issue ordering the fan-out checkpoint above is a position in: None for the API's+ # `sort=date` listing, or the pinned Delta version when the parent came from the warehouse.+ # Resuming across a change here would fast-forward past issues the new order never reached.+ parent_version: Optional[int] = None# Sentry exposes an org URL as `https://<org>.sentry.io/` in its UI and as@@ -368,43 +377,127 @@ def _parse_datetime_value(value: Any) -> datetime | None:# ---------------------------------------------------------------------------+def _skip_rows_on_stale_issue_404(+ rows: Iterator[dict[str, Any]], organization_slug: str, issue_id: str, stale_issues: set[str]+) -> Iterator[dict[str, Any]]:+ """Swallow a 404 raised while iterating a warehouse-snapshot issue's sub-resource.++ Records the issue in `stale_issues` so the caller can report how much of the snapshot the+ vendor no longer has — the drift measure the reuse follow-up needs.+ """+ try:+ yield from rows+ except HTTPError as exc:+ response = exc.response+ if response is not None and response.status_code == 404:+ stale_issues.add(issue_id)+ logger.info(+ "sentry_source.stale_warehouse_issue_skipped",+ organization_slug=organization_slug,+ issue_id=issue_id,+ )+ return+ raise+++def _issues_parent_columns(cutoff_last_seen: Any) -> list[str]:+ # lastSeen is only projected when an incremental cutoff needs it — a parent whose column+ # selection dropped it can still drive full-refresh children.+ return ["id", "lastSeen"] if cutoff_last_seen is not None else ["id"]+++def _usable_resume_state(+ manager: Optional[ResumableSourceManager[SentryResumeConfig]], parent_version: int | None+) -> Optional[SentryResumeConfig]:+ """The issue_tag_values checkpoint, when this run iterates issues the way it was written.++ A checkpoint is a position in an iteration order, so it only means anything to a run+ walking the same order: the API's `sort=date` listing, or one pinned Delta version.+ Applying one across that boundary fast-forwards past issues the new order never reached+ while the watermark still advances, so the rows are lost until a reset. The full triple+ has to be present — anything partial is treated as absent rather than applied to the+ wrong (issue, tag) pair.++ Callers must also `clear_state()` when this returns None with state still stored: the+ pipeline reads `can_resume()` itself to pick replace-vs-append for chunk 0, so a source+ restarting from the top while that says "resuming" appends a full re-read.+ """+ if manager is None or not manager.can_resume():+ return None+ loaded = manager.load_state()+ if loaded is None or not (loaded.issue_id and loaded.tag_key and loaded.values_next_url):+ return None+ if loaded.parent_version != parent_version:+ return None+ return loaded++def _iter_issue_tag_values_rows(base_api_url: str,headers: dict[str, str],organization_slug: str,resumable_source_manager: Optional[ResumableSourceManager[SentryResumeConfig]] = None,incremental_last_seen_max: Any = None,+ issues_table: Optional["ParentTableRef"] = None,) -> Iterator[dict[str, Any]]:cutoff_last_seen = _parse_datetime_value(incremental_last_seen_max)+ use_warehouse_parent = issues_table is not None++ issues: Iterator[dict[str, Any]]+ if issues_table is not None:+ # noqa reason: keeps deltalake/pyarrow off the import path of this module (imported+ # by the API process for schema discovery) — the reader loads only when syncing.+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import ( # noqa: PLC0415+ iter_parent_pages_from_warehouse,+ )++ # Streamed scan — the reader must never materialize the table. The incremental+ # early-break below becomes a per-row filter in this mode (same issue set, no+ # ordering requirement). Duplicate rows can't occur: append-mode parents take the+ # API path instead of this one.+ issues = (+ row+ for page in iter_parent_pages_from_warehouse(+ table=issues_table,+ parent_name="issues",+ columns=_issues_parent_columns(cutoff_last_seen),+ page_size=100,+ schema_name="issue_tag_values",+ )+ for row in page+ )+ else:+ issues = _iter_endpoint_rows(+ base_api_url=base_api_url,+ path=f"/organizations/{organization_slug}/issues/",+ headers=headers,+ params={"limit": 100, "query": "", "sort": "date"},+ )- # Resume state only honours the fan-out fields; the flat-endpoint- # ``next_url`` is meaningless here. We require the full (issue_id, tag_key,- # values_next_url) triple to be present — anything partial is treated as- # absent and falls through to a fresh run so we don't apply a stale URL to- # the wrong (issue, tag) pair.+ # A pinned Delta version enumerates its files in a fixed order, so a warehouse run+ # resumes like an API run — but only against a checkpoint written over the same pin.+ parent_version = issues_table.version if issues_table is not None else Noneresume_issue_id: str | None = Noneresume_tag_key: str | None = Noneresume_values_next_url: str | None = None- if resumable_source_manager is not None and resumable_source_manager.can_resume():- loaded = resumable_source_manager.load_state()- if loaded is not None and loaded.issue_id and loaded.tag_key and loaded.values_next_url:- resume_issue_id = loaded.issue_id- resume_tag_key = loaded.tag_key- resume_values_next_url = loaded.values_next_url-- issues = _iter_endpoint_rows(- base_api_url=base_api_url,- path=f"/organizations/{organization_slug}/issues/",- headers=headers,- params={"limit": 100, "query": "", "sort": "date"},- )+ loaded = _usable_resume_state(resumable_source_manager, parent_version)+ if loaded is not None:+ resume_issue_id = loaded.issue_id+ resume_tag_key = loaded.tag_key+ resume_values_next_url = loaded.values_next_url+ stale_issues: set[str] = set()skipped_for_resume = 0for issue in issues:if cutoff_last_seen is not None:issue_last_seen = _parse_datetime_value(issue.get("lastSeen"))if issue_last_seen is not None and issue_last_seen <= cutoff_last_seen:+ # API mode returns issues sorted by date desc, so the first stale issue ends+ # the scan. The warehouse scan is unordered (streaming, no global sort), so+ # stale issues are filtered per row instead — same selected set either way.+ if use_warehouse_parent:+ continuebreakissue_id = str(issue["id"])@@ -441,6 +534,11 @@ def _iter_issue_tag_values_rows(params={"limit": 100},max_pages=_MAX_PAGES_PER_PARENT,)+ if use_warehouse_parent:+ # The warehouse snapshot can contain issues deleted upstream since the issues+ # schema last synced; their tags endpoint 404s. A fresh API parent pull would+ # simply not list them, so skip instead of failing the sync.+ tags = _skip_rows_on_stale_issue_404(tags, organization_slug, issue_id, stale_issues)for tag in tags:tag_key = tag.get("key") or tag.get("id")if not isinstance(tag_key, str) or not tag_key:@@ -507,6 +605,17 @@ def _iter_issue_tag_values_rows(status_code=response.status_code,)break+ # Warehouse-snapshot parents can be deleted upstream mid-list; their+ # values endpoint 404s. Skip the tag, same as the stale-issue skip above.+ if use_warehouse_parent and response.status_code == 404:+ stale_issues.add(issue_id)+ logger.info(+ "sentry_source.stale_warehouse_issue_skipped",+ organization_slug=organization_slug,+ issue_id=issue_id,+ tag_key=tag_key,+ )+ break# Other client errors (401, etc.) still propagate to the job-level handler.raise@@ -546,13 +655,17 @@ def _iter_issue_tag_values_rows(# Checkpoint the URL of the NEXT values page — it has not been# fetched yet, so resume can pick it up directly without- # re-processing any rows that were already yielded.+ # re-processing any rows that were already yielded. `parent_version`+ # stamps which issue ordering the position belongs to, so a later+ # attempt reading a different parent ignores it (see+ # `_usable_resume_state`).if next_url and resumable_source_manager is not None:resumable_source_manager.save_state(SentryResumeConfig(issue_id=issue_id,tag_key=tag_key,values_next_url=urljoin(f"{base_api_url}/", next_url),+ parent_version=parent_version,))@@ -566,6 +679,16 @@ def _iter_issue_tag_values_rows(resume_tag_key = Noneresume_values_next_url = None+ if use_warehouse_parent:+ # Stale issues are ones the snapshot still lists but Sentry has dropped, each costing+ # a wasted request per sync. Against the reader's row count this is the drift measure+ # for deciding whether the snapshot needs a freshness filter — see the plan follow-up.+ logger.info(+ "sentry_source.warehouse_parent_stale_issues",+ organization_slug=organization_slug,+ stale_issues=len(stale_issues),+ )+# ---------------------------------------------------------------------------# Endpoints whose payload needs reshaping before it can be a table@@ -1120,6 +1243,8 @@ def sentry_source(should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,+ source_id: str | None = None,+ use_warehouse_parent: bool = False,) -> SourceResponse:endpoint_config = SENTRY_ENDPOINTS[endpoint]normalized_base_url = _validated_api_base_url(api_base_url)@@ -1129,6 +1254,33 @@ def sentry_source(# which can't be expressed as a single parent→child dependency.if endpoint == "issue_tag_values":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:+ 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+ # by the API process for schema discovery) — the reader stack loads only when syncing.+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import ( # noqa: PLC0415+ try_resolve_parent_table,+ )++ # Resolved here, in sync source-build context, never inside the iterator: its body+ # runs on the pipeline's executor threads, where ad-hoc ORM reads hit the+ # pooler-drop failure mode resolve_parent_table_ref documents.+ issues_table = try_resolve_parent_table(+ team_id=team_id,+ source_id=source_id,+ parent_name="issues",+ required_columns=_issues_parent_columns(_parse_datetime_value(incremental_last_seen_max)),+ schema_name="issue_tag_values",+ )+ if resumable_source_manager is not None and resumable_source_manager.can_resume():+ # The pipeline reads this same Redis state to pick replace-vs-append for chunk 0,+ # so state the iterator will refuse has to go now, before it decides. Same+ # predicate as the iterator's, so the two can't disagree.+ if _usable_resume_state(resumable_source_manager, issues_table.version if issues_table else None) is None:+ resumable_source_manager.clear_state()return _make_source_response(endpoint_config,lambda: _iter_issue_tag_values_rows(@@ -1136,7 +1288,8 @@ def sentry_source(headers=headers,organization_slug=organization_slug,resumable_source_manager=resumable_source_manager,- incremental_last_seen_max=db_incremental_field_last_value if should_use_incremental_field else None,+ incremental_last_seen_max=incremental_last_seen_max,+ issues_table=issues_table,),)@@ -1173,6 +1326,8 @@ def sentry_source(should_use_incremental_field=should_use_incremental_field,incremental_field=incremental_field,incremental_config_factory=_sentry_incremental_window,+ source_id=source_id,+ use_warehouse_parent=use_warehouse_parent,page_size_param=endpoint_config.page_size_param,),)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.pyindex bb05941e086b..3d9447e7c891 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@@ -258,6 +258,7 @@ 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",),),"issue_hashes": SentryEndpointConfig(@@ -276,6 +277,7 @@ 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",),),"issue_tag_values": SentryEndpointConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.pyindex 1bd194ec422f..1c42fd2789ac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sentry/source.py@@ -16,6 +16,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ required_parents_from_endpoint_configs,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse@@ -33,6 +36,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.sentry.setENDPOINTS,INCREMENTAL_FIELDS,REQUIRED_SENTRY_SCOPES,+ SENTRY_ENDPOINTS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -138,6 +142,13 @@ class SentrySource(ResumableSource[SentrySourceConfig, SentryResumeConfig]):# Close's equivalent case.return {"Max retries exceeded with url"}+ def get_required_parent_schemas(self, schema_name: str) -> list[str]:+ # issue_tag_values fans out over issues through its custom two-level iterator, so it+ # carries no DependentEndpointConfig to derive the dependency from.+ if schema_name == "issue_tag_values":+ return ["issues"]+ return required_parents_from_endpoint_configs(SENTRY_ENDPOINTS, schema_name)+def get_schemas(self,config: SentrySourceConfig,@@ -206,4 +217,6 @@ class SentrySource(ResumableSource[SentrySourceConfig, SentryResumeConfig]):if inputs.should_use_incremental_fieldelse None,incremental_field=inputs.incremental_field,+ source_id=inputs.source_id,+ use_warehouse_parent=inputs.fanout_warehouse_reuse,)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.pyindex 1497d25c8633..3d6ccf21c635 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@@ -8,6 +8,10 @@ from parameterized import parameterizedfrom requests.exceptions import HTTPError, JSONDecodeErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ ParentTableRef,+ WarehouseParentTableNotFoundError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sentry import SentrySourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry import (@@ -916,6 +920,102 @@ class TestIssueTagValuesResumable:values_next_url="https://sentry.io/api/0/organizations/acme/issues/100/tags/browser/values/?cursor=0:100:2",)+ @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.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse",+ return_value=iter([[{"id": "100"}]]),+ )+ def test_warehouse_mode_stamps_the_checkpoint_with_the_pinned_version(+ self, _mock_reader, _mock_resolve, mock_get+ ) -> None:+ # A checkpoint is a position in an iteration order, so it has to record which one:+ # without the pin, a later attempt reading a different parent would fast-forward past+ # issues its own order never reached, and the watermark would still advance.+ next_values_link = (+ "<https://sentry.io/api/0/organizations/acme/issues/100/tags/browser/values/?cursor=0:100:2>; "+ 'rel="next"; results="true"'+ )++ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/issues/100/tags/"):+ return _response([{"key": "browser"}])+ if url.endswith("/organizations/acme/issues/100/tags/browser/values/"):+ return _response([{"value": "Chrome"}], link_header=next_values_link)+ return _response([])++ mock_get.return_value.get.side_effect = side_effect+ manager = _make_fake_manager(can_resume=False)++ 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,+ resumable_source_manager=manager,+ )++ rows = list(cast(Any, resp.items()))+ assert len(rows) == 1+ saved_state = cast(Mock, manager.save_state).call_args_list[0].args[0]+ assert saved_state.parent_version == 3++ @parameterized.expand(+ [+ # Written over the API listing, read by a warehouse run.+ ("api_checkpoint_in_warehouse_run", None, True),+ # Written over a different pinned version than this run resolved (parent re-synced).+ ("other_version_checkpoint", 2, True),+ # Written over a warehouse scan, read by a run that fell back to the API.+ ("warehouse_checkpoint_in_api_run", 3, False),+ ]+ )+ @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.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse",+ return_value=iter([[{"id": "100"}]]),+ )+ def test_checkpoint_from_a_different_issue_order_is_refused_and_cleared(+ self, _name, stored_parent_version, use_warehouse_parent, _mock_reader, _mock_resolve, mock_get+ ) -> None:+ # Applying it would skip issues the new order never reached; leaving it in Redis would+ # make the pipeline append chunk 0 onto the previous attempt's rows.+ mock_get.return_value.get.side_effect = lambda url, **kwargs: _response([])+ manager = _make_fake_manager(+ can_resume=True,+ state=SentryResumeConfig(+ issue_id="999",+ tag_key="browser",+ values_next_url="https://x",+ parent_version=stored_parent_version,+ ),+ )++ 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=use_warehouse_parent,+ resumable_source_manager=manager,+ )++ cast(Mock, manager.clear_state).assert_called_once()+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.make_tracked_session")def test_resume_fetches_saved_values_url_and_skips_earlier_pairs(self, mock_get) -> None:seen_urls: list[str] = []@@ -1716,3 +1816,243 @@ class TestSentryCustomIteratorEndpoints:assert abs(since - floor) < 60else:assert abs(since - recent) < 60+++class TestWarehouseParentReuse:+ @parameterized.expand(+ [+ ("issue_events", ["issues"]),+ ("issue_hashes", ["issues"]),+ ("issue_tag_values", ["issues"]),+ ("issues", []),+ ("projects", []),+ ("project_events", []),+ ]+ )+ def test_get_required_parent_schemas(self, endpoint: str, expected: list[str]) -> None:+ assert SentrySource().get_required_parent_schemas(endpoint) == expected++ @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.resolve_parent_table_ref",+ side_effect=WarehouseParentTableNotFoundError("issues table is gone"),+ )+ def test_issue_tag_values_falls_back_to_the_api_when_the_table_is_unreadable(self, _mock_resolve, mock_get) -> None:+ # issues reports a completed sync but its table can't be read, so the iterator has to+ # walk the issues endpoint exactly as it does with the feature off.+ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/issues/"):+ return _response([{"id": "100", "lastSeen": "2026-03-05T12:00:00Z"}])+ if url.endswith("/organizations/acme/issues/100/tags/"):+ return _response([{"key": "browser"}])+ if url.endswith("/organizations/acme/issues/100/tags/browser/values/"):+ return _response([{"value": "Chrome", "timesSeen": 1}])+ return _response([])++ mock_get.return_value.get.side_effect = side_effect++ 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,+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [{"value": "Chrome", "timesSeen": 1, "issue_id": "100", "tag_key": "browser"}]++ @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.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse"+ )+ def test_issue_tag_values_reads_issues_from_warehouse(self, mock_reader, _mock_resolve, mock_get) -> None:+ mock_reader.return_value = iter([[{"id": "100", "lastSeen": "2026-03-05T12:00:00Z"}]])++ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/issues/"):+ raise AssertionError("warehouse-parent issue_tag_values must not fetch the issues endpoint")+ if url.endswith("/organizations/acme/issues/100/tags/"):+ return _response([{"key": "browser"}])+ if url.endswith("/organizations/acme/issues/100/tags/browser/values/"):+ return _response([{"value": "Chrome", "timesSeen": 1}])+ return _response([])++ mock_get.return_value.get.side_effect = side_effect++ 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,+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [{"value": "Chrome", "timesSeen": 1, "issue_id": "100", "tag_key": "browser"}]+ mock_reader.assert_called_once_with(+ table=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ parent_name="issues",+ columns=["id"],+ page_size=100,+ schema_name="issue_tag_values",+ )++ @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.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse"+ )+ def test_issue_tag_values_warehouse_cutoff_filters_instead_of_breaking(+ self, mock_reader, _mock_resolve, mock_get+ ) -> None:+ cutoff = datetime(2026, 3, 3, 0, 0, 0, tzinfo=UTC)+ # Unordered warehouse scan: a stale issue arrives BEFORE a fresh one. API mode breaks+ # on the first stale row (sorted input); warehouse mode must filter and keep scanning.+ mock_reader.return_value = iter(+ [+ [+ {"id": "100", "lastSeen": "2026-03-01T00:00:00Z"},+ {"id": "200", "lastSeen": "2026-03-05T00:00:00Z"},+ ]+ ]+ )++ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/issues/100/tags/"):+ raise AssertionError("stale issue must be filtered out, not fanned out")+ if url.endswith("/organizations/acme/issues/200/tags/"):+ return _response([{"key": "browser"}])+ if url.endswith("/organizations/acme/issues/200/tags/browser/values/"):+ return _response([{"value": "Chrome", "lastSeen": "2026-03-05T00:00:00Z"}])+ return _response([])++ mock_get.return_value.get.side_effect = side_effect++ 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,+ should_use_incremental_field=True,+ db_incremental_field_last_value=cutoff,+ incremental_field="lastSeen",+ )++ rows = list(cast(Any, resp.items()))+ assert [row["issue_id"] for row in rows] == ["200"]++ @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.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse"+ )+ def test_issue_tag_values_warehouse_skips_issue_deleted_upstream(+ self, mock_reader, _mock_resolve, mock_get+ ) -> None:+ mock_reader.return_value = iter([[{"id": "100", "lastSeen": None}, {"id": "200", "lastSeen": None}]])++ def side_effect(url, headers=None, params=None, timeout=None):+ if url.endswith("/organizations/acme/issues/100/tags/"):+ return _response([], status_code=404)+ if url.endswith("/organizations/acme/issues/200/tags/"):+ return _response([{"key": "browser"}])+ if url.endswith("/organizations/acme/issues/200/tags/browser/values/"):+ return _response([{"value": "Chrome"}])+ return _response([])++ mock_get.return_value.get.side_effect = side_effect++ 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,+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [{"value": "Chrome", "issue_id": "200", "tag_key": "browser"}]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.resolve_parent_table_ref",+ return_value=ParentTableRef(uri="s3://bucket/team_123_sentry_x/issues", version=3),+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.iter_parent_pages_from_warehouse"+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry._request_with_retry")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.make_tracked_session")+ def test_issue_tag_values_warehouse_skips_tag_when_values_endpoint_404s(+ self, mock_get, mock_request, mock_reader, _mock_resolve+ ) -> None:+ # An issue deleted upstream between the tags listing and the values fetch 404s only on+ # the values endpoint — the sync must skip that tag, not fail.+ mock_reader.return_value = iter([[{"id": "100"}, {"id": "200"}]])++ def request_side_effect(url, headers=None, params=None):+ if url.endswith("/tags/"):+ return _response([{"key": "browser"}])+ if "/issues/100/tags/browser/values/" in url:+ return _response([], status_code=404)+ if "/issues/200/tags/browser/values/" in url:+ return _response([{"value": "Chrome"}])+ return _response([])++ mock_request.side_effect = request_side_effect++ 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,+ )++ rows = list(cast(Any, resp.items()))+ assert rows == [{"value": "Chrome", "issue_id": "200", "tag_key": "browser"}]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.sentry.sentry.build_dependent_resource")+ def test_fanout_endpoint_threads_warehouse_flag(self, mock_build) -> None:+ mock_build.return_value = iter([])++ sentry_source(+ auth_token="token",+ organization_slug="acme",+ api_base_url="https://sentry.io",+ endpoint="issue_hashes",+ team_id=123,+ job_id="job-id",+ source_id="source-1",+ use_warehouse_parent=True,+ )++ kwargs = mock_build.call_args.kwargs+ assert kwargs["source_id"] == "source-1"+ assert kwargs["use_warehouse_parent"] is Truediff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex d9c56ecbe10f..ccf3633ac8f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -27,6 +27,7 @@ from products.warehouse_sources.backend.models.external_data_job import Externalfrom products.warehouse_sources.backend.models.external_data_schema import (ExternalDataSchema,apply_incremental_lookback,+ get_schema_if_exists,process_incremental_value,)from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource@@ -49,10 +50,14 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources.backend.temporal.data_imports.row_tracking import setup_row_trackingfrom products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ AnySource,ResumableSource,SimpleSource,error_message_matches,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.fanout_reuse_flag import (+ is_fanout_warehouse_reuse_enabled,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_context import bind_job_contextfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClientNonRetryableError,@@ -107,6 +112,62 @@ def _get_external_data_schema(schema_id: uuid.UUID, team_id: int) -> ExternalDat)+def _parent_unusable_reason(parent: ExternalDataSchema | None) -> str | None:+ """Why a fan-out child can't read this parent from the warehouse, or None when it can."""+ if parent is None:+ return "missing"+ if not parent.should_sync:+ return "disabled"+ if not (parent.is_incremental or parent.sync_type == ExternalDataSchema.SyncType.FULL_REFRESH):+ # An allow-list, not a deny-list: only merge and full-refresh parents hold one row per+ # key. Append accumulates a row per sync, and CDC keeps change history, so the reader —+ # which streams the table as-is, with no dedupe state — would fan the child out once+ # per duplicate. New sync types have to opt in here deliberately.+ return "unsupported_sync_type"+ if not parent.initial_sync_complete:+ return "no_initial_sync"+ return None+++async def _warehouse_parent_reuse_available(+ source: AnySource,+ schema: ExternalDataSchema,+ source_id: uuid.UUID,+ team_id: int,+ logger: FilteringBoundLogger,+) -> bool:+ """Whether this run reads its fan-out parents from the warehouse instead of the parent API.++ Reuse is an optimization, never a requirement: any parent the child can't read falls the+ whole run back to the legacy parent-API path, so enabling the flag can't break a schema+ that syncs today. Sources consume the result via `SourceInputs.fanout_warehouse_reuse`;+ this is the single feature-flag evaluation for the run.++ A parent that is mid-sync doesn't force the fallback: `resolve_parent_table_ref` pins the+ read to the parent's last completed snapshot (Delta time travel), so a concurrent rewrite+ can't hand the child a torn table.+ """+ required_parents = source.get_required_parent_schemas(schema.name)+ if not required_parents:+ return False+ if not await database_sync_to_async_pool(is_fanout_warehouse_reuse_enabled)(team_id):+ return False++ for parent_name in required_parents:+ parent = await database_sync_to_async_pool(get_schema_if_exists)(parent_name, team_id, source_id)+ unusable_reason = _parent_unusable_reason(parent)+ if unusable_reason is not None:+ await logger.ainfo(+ "data_imports.fanout_parent_unusable",+ schema=schema.name,+ parent=parent_name,+ reason=unusable_reason,+ )+ return False++ return True++@activity.defnasync def import_data_activity_sync(inputs: ImportDataActivityInputs) -> PipelineResult:bind_contextvars(team_id=inputs.team_id)@@ -235,6 +296,20 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:if SourceRegistry.is_registered(source_type):new_source = SourceRegistry.get_source(source_type)+ fanout_warehouse_reuse = await _warehouse_parent_reuse_available(+ new_source, schema, inputs.source_id, inputs.team_id, logger+ )+ # INFO so it's visible without DEBUG: confirms which parent-source path a fan-out+ # child took, and doubles as rollout-adoption telemetry. Only fan-out children+ # (schemas with required parents) log it; every other schema stays quiet.+ if new_source.get_required_parent_schemas(schema.name):+ await logger.ainfo(+ "data_imports.fanout_parent_source",+ schema=schema.name,+ parent_source="warehouse" if fanout_warehouse_reuse else "api",+ source_type=source_type,+ )+source_inputs = SourceInputs(schema_name=schema.name,schema_id=str(schema.id),@@ -258,6 +333,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:s3_folder_name=schema.resolved_s3_folder_name,# A schema-level override (user-managed) wins over the source pin.api_version=new_source.resolve_api_version(schema.api_version or model.pipeline.api_version),+ fanout_warehouse_reuse=fanout_warehouse_reuse,)try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 146a95c4243d..441949a58c0e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -90,6 +90,7 @@ def _make_source(error: Exception, non_retryable: dict[str, str | None]):source = mock.MagicMock(spec=SimpleSource)source.parse_config.return_value = {}source.get_non_retryable_errors.return_value = non_retryable+ source.get_required_parent_schemas.return_value = []source.source_for_pipeline.side_effect = errorreturn source@@ -603,3 +604,135 @@ async def test_pinned_api_version_is_resolved_into_source_inputs(schema_override_, source_inputs = source.source_for_pipeline.call_args.argsassert source_inputs.api_version == expected+++def _fanout_child_schema() -> mock.MagicMock:+ schema = mock.MagicMock()+ schema.name = "issue_events"+ return schema+++def _fanout_source() -> mock.MagicMock:+ source = mock.MagicMock(spec=SimpleSource)+ source.get_required_parent_schemas.return_value = ["issues"]+ return source+++def _parent(+ should_sync: bool,+ initial_sync_complete: bool,+ sync_type: str = ExternalDataSchema.SyncType.INCREMENTAL,+) -> mock.MagicMock:+ parent = mock.MagicMock()+ parent.should_sync = should_sync+ parent.initial_sync_complete = initial_sync_complete+ parent.sync_type = sync_type+ parent.is_incremental = sync_type == ExternalDataSchema.SyncType.INCREMENTAL+ return parent+++ "parent",+ [None, "disabled", "never_synced", "append_mode", "cdc_mode"],+)+async def test_unusable_parent_falls_back_to_the_api_path(parent):+ # A child enabled without its parent is a config that syncs today, so turning the flag on+ # must leave it working: fall back to the parent API instead of failing the run. Append and+ # CDC parents hold more than one row per key, so the reader must not stream them either.+ parent_obj = None+ if parent == "disabled":+ parent_obj = _parent(should_sync=False, initial_sync_complete=True)+ elif parent == "never_synced":+ parent_obj = _parent(should_sync=True, initial_sync_complete=False)+ elif parent == "append_mode":+ parent_obj = _parent(should_sync=True, initial_sync_complete=True, sync_type=ExternalDataSchema.SyncType.APPEND)+ elif parent == "cdc_mode":+ parent_obj = _parent(should_sync=True, initial_sync_complete=True, sync_type=ExternalDataSchema.SyncType.CDC)++ with (+ mock.patch.object(module, "database_sync_to_async_pool", new=_passthrough),+ mock.patch.object(module, "is_fanout_warehouse_reuse_enabled", return_value=True),+ mock.patch.object(module, "get_schema_if_exists", return_value=parent_obj),+ ):+ result = await module._warehouse_parent_reuse_available(+ _fanout_source(), _fanout_child_schema(), uuid.uuid4(), 1, mock.AsyncMock()+ )++ assert result is False+++ "sync_type",+ [ExternalDataSchema.SyncType.INCREMENTAL, ExternalDataSchema.SyncType.FULL_REFRESH],+)+async def test_synced_parent_uses_the_warehouse_path(sync_type):+ # Merge and full-refresh parents both hold one row per key, so both drive the reader.+ with (+ mock.patch.object(module, "database_sync_to_async_pool", new=_passthrough),+ mock.patch.object(module, "is_fanout_warehouse_reuse_enabled", return_value=True),+ mock.patch.object(+ module,+ "get_schema_if_exists",+ return_value=_parent(should_sync=True, initial_sync_complete=True, sync_type=sync_type),+ ),+ ):+ result = await module._warehouse_parent_reuse_available(+ _fanout_source(), _fanout_child_schema(), uuid.uuid4(), 1, mock.AsyncMock()+ )++ assert result is True+++async def test_fanout_gate_result_threaded_into_source_inputs():+ # The gate's decision must reach the source via SourceInputs — if this wiring drops,+ # every child silently falls back to re-pulling the parent API with the flag on.+ source = mock.MagicMock(spec=SimpleSource)+ source.parse_config.return_value = {}+ source.get_required_parent_schemas.return_value = ["issues"]+ source.source_for_pipeline.return_value = mock.MagicMock()+ source.resolve_api_version = lambda p: p or "v1"+ schema = _incremental_schema(is_incremental=False, lookback_seconds=None)++ with (+ _patched_activity_reaching_run(source, schema),+ mock.patch.object(module, "is_fanout_warehouse_reuse_enabled", return_value=True),+ mock.patch.object(+ module, "get_schema_if_exists", return_value=_parent(should_sync=True, initial_sync_complete=True)+ ),+ ):+ await import_data_activity_sync(_inputs_no_reset())++ _, source_inputs = source.source_for_pipeline.call_args.args+ assert source_inputs.fanout_warehouse_reuse is True+++async def test_parent_gate_inert_when_flag_disabled():+ with (+ mock.patch.object(module, "database_sync_to_async_pool", new=_passthrough),+ mock.patch.object(module, "is_fanout_warehouse_reuse_enabled", return_value=False),+ mock.patch.object(module, "get_schema_if_exists") as schema_lookup,+ ):+ result = await module._warehouse_parent_reuse_available(+ _fanout_source(), _fanout_child_schema(), uuid.uuid4(), 1, mock.AsyncMock()+ )++ assert result is False+ schema_lookup.assert_not_called()+++async def test_parent_gate_inert_for_sources_without_requirements():+ source = mock.MagicMock(spec=SimpleSource)+ source.get_required_parent_schemas.return_value = []++ with mock.patch.object(module, "is_fanout_warehouse_reuse_enabled") as flag_check:+ result = await module._warehouse_parent_reuse_available(+ source, _fanout_child_schema(), uuid.uuid4(), 1, mock.AsyncMock()+ )++ assert result is False+ flag_check.assert_not_called()diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py b/products/warehouse_sources/backend/tests/api/test_external_data_schema.pyindex 91c354c9df92..d1654890721c 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_schema.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_schema.py@@ -1,4 +1,5 @@import uuid+import contextlibfrom datetime import timedeltafrom typing import Any@@ -14,7 +15,7 @@ import pytest_asynciofrom asgiref.sync import sync_to_asyncfrom parameterized import parameterizedfrom rest_framework import status-from temporalio.service import RPCError+from temporalio.service import RPCError, RPCStatusCodefrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_team@@ -2992,7 +2993,7 @@ class TestCancelExternalDataSchema(APIBaseTest):"products.warehouse_sources.backend.presentation.views.external_data_schema.cancel_external_data_workflow")def test_cancel_v3_succeeds_when_cancel_rpc_fails(self, _case, rpc_status_name, mock_cancel, _mock_finish):- from temporalio.service import RPCError, RPCStatusCode+ from temporalio.service import RPCErrorfrom products.warehouse_sources.backend.facade.models import ExternalDataJob@@ -3041,7 +3042,7 @@ class TestCancelExternalDataSchema(APIBaseTest):# A workflow that was terminated (not cancelled) never runs the cleanup that writes the# terminal status, so the cancel RPC comes back NOT_FOUND. Without recovery the job and# schema would stay stuck on Running forever and the schema could never be synced again.- from temporalio.service import RPCError, RPCStatusCode+ from temporalio.service import RPCErrorfrom products.warehouse_sources.backend.facade.models import ExternalDataJob@@ -3066,7 +3067,7 @@ class TestCancelExternalDataSchema(APIBaseTest):def test_cancel_legacy_pipeline_returns_400_on_transient_rpc_error(self, mock_cancel):# A transient RPC failure against a possibly-live workflow must not mark the job Failed -# the workflow still owns the terminal status, so leave it Running and surface the error.- from temporalio.service import RPCError, RPCStatusCode+ from temporalio.service import RPCErrorfrom products.warehouse_sources.backend.facade.models import ExternalDataJob@@ -3769,3 +3770,109 @@ class TestExternalDataSchemaApiVersionOverride(APIBaseTest):"sunset_at": None,"default_version": StripeSource.default_version,}+++class TestFanoutParentSelection(APIBaseTest):+ """Fan-out parents and children are selected independently.++ Warehouse parent reuse is an optimization the run-time gate applies when it can, so the+ API constrains nothing here: no selection is refused and no parent is enabled as a side+ effect. Deliberately not in TestExternalDataSchema: its autouse fixture needs a live+ Temporal server, while every Temporal touchpoint here is behind a mock.+ """++ def _create_sentry_fanout_pair(self, parent_sync_type, child_should_sync=False, parent_should_sync=False):+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=ExternalDataSourceType.SENTRY,+ job_inputs={"auth_token": "token", "organization_slug": "acme"},+ )+ parent = ExternalDataSchema.objects.create(+ name="issues",+ team=self.team,+ source=source,+ should_sync=parent_should_sync,+ sync_type=parent_sync_type,+ )+ child = ExternalDataSchema.objects.create(+ name="issue_events",+ team=self.team,+ source=source,+ should_sync=child_should_sync,+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,+ )+ return source, parent, child++ def _temporal_patches(self):+ return (+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.external_data_workflow_exists",+ return_value=False,+ ),+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.sync_external_data_job_workflow"+ ),+ mock.patch("products.data_warehouse.backend.facade.api.external_data_workflow_exists", return_value=False),+ mock.patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow"),+ mock.patch(+ "products.warehouse_sources.backend.presentation.views.external_data_schema.pause_external_data_schedule"+ ),+ mock.patch("products.data_warehouse.backend.facade.api.pause_external_data_schedule"),+ )++ def _patch_schema(self, schema_id, data):+ with contextlib.ExitStack() as stack:+ for p in self._temporal_patches():+ stack.enter_context(p)+ return self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema_id}",+ data=data,+ )++ @parameterized.expand(+ [+ ("unconfigured_parent", None, False),+ ("disabled_parent", ExternalDataSchema.SyncType.INCREMENTAL, False),+ ("append_parent", ExternalDataSchema.SyncType.APPEND, True),+ ("enabled_parent", ExternalDataSchema.SyncType.INCREMENTAL, True),+ ]+ )+ def test_enabling_child_never_blocks_on_or_touches_its_parent(self, _name, parent_sync_type, parent_should_sync):+ # These are the configurations teams already run, so enabling the child has to keep+ # working. The parent must come out byte-identical either way: enabling one bills its+ # rows, and even a redundant write would churn its Temporal schedule.+ _, parent, child = self._create_sentry_fanout_pair(+ parent_sync_type=parent_sync_type, parent_should_sync=parent_should_sync+ )+ parent_updated_at = parent.updated_at++ response = self._patch_schema(child.id, {"should_sync": True})++ assert response.status_code == 200, response.json()+ child.refresh_from_db()+ assert child.should_sync is True+ parent.refresh_from_db()+ assert parent.should_sync is parent_should_sync+ assert parent.updated_at == parent_updated_at++ @parameterized.expand([("disable",), ("delete",)])+ def test_parent_stays_editable_while_a_child_syncs_from_it(self, action):+ # The child degrades to the parent-API path instead of stranding, so neither write is+ # protected against.+ _, parent, _child = self._create_sentry_fanout_pair(+ parent_sync_type=ExternalDataSchema.SyncType.INCREMENTAL,+ parent_should_sync=True,+ child_should_sync=True,+ )++ if action == "disable":+ response = self._patch_schema(parent.id, {"should_sync": False})+ assert response.status_code == 200, response.json()+ parent.refresh_from_db()+ assert parent.should_sync is False+ else:+ with contextlib.ExitStack() as stack:+ for p in self._temporal_patches():+ stack.enter_context(p)+ response = self.client.delete(f"/api/environments/{self.team.pk}/external_data_schemas/{parent.id}")+ assert response.status_code == 204diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex f00dbb1b95e9..61052287c8bb 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -13264,3 +13264,62 @@ class TestGithubMultiRepoPatch(APIBaseTest):removed_webhook_row.refresh_from_db()assert removed_webhook_row.deleted is True or removed_webhook_row.should_sync is False+++class TestFanoutParentCreation(APIBaseTest):+ """Source creation places no fan-out constraint on the schema selection: any combination of+ parent and child creates, and the run-time gate decides per run whether the child can read+ its parent from the warehouse."""++ def _post_sentry_source(self, schemas: list[dict]):+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.sentry.source.SentrySource.validate_credentials",+ return_value=(True, None),+ ):+ return self.client.post(+ f"/api/environments/{self.team.pk}/external_data_sources/",+ data={+ "source_type": "Sentry",+ "created_via": "web",+ "payload": {+ "auth_token": "token",+ "organization_slug": "acme",+ "schemas": schemas,+ },+ },+ )++ def test_create_accepts_child_when_parent_also_selected(self):+ response = self._post_sentry_source(+ [+ {"name": "issues", "should_sync": True, "sync_type": "full_refresh"},+ {"name": "issue_events", "should_sync": True, "sync_type": "full_refresh"},+ ]+ )++ assert response.status_code == 201, response.json()+ source = ExternalDataSource.objects.get(team_id=self.team.pk)+ should_sync_by_name = {+ schema.name: schema.should_sync+ for schema in ExternalDataSchema.objects.filter(team_id=self.team.pk, source_id=source.id)+ }+ assert should_sync_by_name["issues"] is True+ assert should_sync_by_name["issue_events"] is True++ @parameterized.expand(+ [+ ("unconfigured_parent", {"name": "issues", "should_sync": False}),+ ("missing_parent", None),+ ]+ )+ def test_create_accepts_child_without_a_usable_parent(self, _name, parent_entry):+ # Selecting only the child is a supported setup: it syncs off the parent API, exactly as+ # it does today. Refusing it here would force the customer to pay for parent rows.+ schemas = [{"name": "issue_events", "should_sync": True, "sync_type": "full_refresh"}]+ if parent_entry is not None:+ schemas.insert(0, parent_entry)++ response = self._post_sentry_source(schemas)++ assert response.status_code == 201, response.json()+ assert ExternalDataSchema.objects.get(team_id=self.team.pk, name="issue_events").should_sync is True