Skip to content

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

chore(warehouse_sources): split the fan-out resource builder into helpers (#99746)

posthog[bot]39f5e89a8c6d
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.py
index 526f7fd46dde..83a2bcccf036 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
@@ -94,113 +94,113 @@ def rename_parent_fields(parent_name: str, renames: dict[str, str]) -> Callable[
return _mapper
-def build_dependent_resource(
- *,
- endpoint_configs: Mapping[str, FanoutEndpointLike],
- child_endpoint: str,
- fanout: DependentEndpointConfig,
- client_config: ClientConfig,
- path_format_values: dict[str, str],
- team_id: int,
- job_id: str,
- db_incremental_field_last_value: Any,
- should_use_incremental_field: bool = False,
- incremental_field: str | None = None,
- incremental_config_factory: Callable[[str], IncrementalConfig | None] | None = None,
- parent_endpoint_extra: Endpoint | None = None,
- child_endpoint_extra: Endpoint | None = None,
- child_params_extra: dict[str, Any] | None = None,
- parent_data_map: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
- 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,
- parent_snapshot_at: datetime | None = None,
-) -> Iterable[Any]:
- parent_config = endpoint_configs[fanout.parent_name]
- child_config = endpoint_configs[child_endpoint]
+def _format_path(path: str, path_format_values: Mapping[str, str]) -> str:
+ for key, value in path_format_values.items():
+ path = path.replace(f"{{{key}}}", value)
+ return path
- warehouse_parent = fanout.parent_source == "warehouse" and use_warehouse_parent
+def _build_parent_resource(
+ *,
+ fanout: DependentEndpointConfig,
+ parent_config: FanoutEndpointLike,
+ path_format_values: Mapping[str, str],
+ page_size_param: str | None,
+ parent_endpoint_extra: Endpoint | None,
+ parent_data_map: Callable[[dict[str, Any]], dict[str, Any]] | None,
+) -> EndpointResource:
# 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}
- parent_params.update(fanout.parent_params)
+ params: dict[str, Any] = {} if page_size_param is None else {page_size_param: parent_config.page_size}
+ params.update(fanout.parent_params)
- parent_path = parent_config.path
- for key, value in path_format_values.items():
- parent_path = parent_path.replace(f"{{{key}}}", value)
-
- parent_endpoint_config: Endpoint = {
- "path": parent_path,
- "params": parent_params,
+ endpoint: Endpoint = {
+ "path": _format_path(parent_config.path, path_format_values),
+ "params": params,
}
if parent_endpoint_extra:
if "params" in parent_endpoint_extra:
raise ValueError(
"Do not pass 'params' in parent_endpoint_extra. Use fanout.parent_params or page_size_param instead."
)
- parent_endpoint_config.update(parent_endpoint_extra)
+ endpoint.update(parent_endpoint_extra)
parent_resource: EndpointResource = {
"name": fanout.parent_name,
"table_name": fanout.parent_name,
"write_disposition": "replace",
- "endpoint": parent_endpoint_config,
+ "endpoint": endpoint,
"table_format": "delta",
}
-
if parent_data_map is not None:
# Parent transforms run before the child transformer reads the page, so a resolve_field
# the parent rows do not carry can be derived here. `process_parent_data_item` binds the
# path with `str.format`, which applies no escaping, so a vendor whose ids can contain
# `/` must percent-encode them through this hook.
parent_resource["data_map"] = parent_data_map
+ return parent_resource
- 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,
- row_filter=fanout.parent_row_filter,
- )
- 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["parent_source"] = "warehouse"
- 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,
- schema_name=child_endpoint,
- row_filter=fanout.parent_row_filter,
- )
+def _attach_warehouse_parent(
+ parent_resource: EndpointResource,
+ *,
+ fanout: DependentEndpointConfig,
+ page_size: int,
+ team_id: int,
+ source_id: str | None,
+ child_endpoint: str,
+) -> bool:
+ """Point the parent resource at the parent's Delta table. False means stay on the API."""
+ 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,
+ row_filter=fanout.parent_row_filter,
+ )
+ if parent_table is None:
+ # Drop back to the API parent entirely, including the child's snapshot-only 404
+ # handling, so the child syncs exactly the way it does without this feature.
+ return False
+
+ parent_resource["parent_source"] = "warehouse"
+ parent_resource["data_iterator"] = lambda: iter_parent_pages_from_warehouse(
+ table=parent_table,
+ parent_name=fanout.parent_name,
+ columns=parent_columns,
+ page_size=page_size,
+ schema_name=child_endpoint,
+ row_filter=fanout.parent_row_filter,
+ )
+ return True
- child_path = child_config.path
- for key, value in path_format_values.items():
- child_path = child_path.replace(f"{{{key}}}", value)
- child_params: dict[str, Any] = {
+def _build_child_endpoint(
+ *,
+ fanout: DependentEndpointConfig,
+ child_config: FanoutEndpointLike,
+ path_format_values: Mapping[str, str],
+ page_size_param: str | None,
+ child_params_extra: dict[str, Any] | None,
+ child_endpoint_extra: Endpoint | None,
+ warehouse_parent: bool,
+) -> Endpoint:
+ params: dict[str, Any] = {
fanout.resolve_param: {
"type": "resolve",
"resource": fanout.parent_name,
@@ -208,7 +208,7 @@ def build_dependent_resource(
},
}
if page_size_param is not None:
- child_params[page_size_param] = child_config.page_size
+ params[page_size_param] = child_config.page_size
# The resolve param binds child requests to their parent row. A config that reuses that key
# would clobber the binding, so reject it loudly rather than silently dropping the value.
if fanout.resolve_param in fanout.child_params:
@@ -216,29 +216,42 @@ def build_dependent_resource(
f"child_params must not include the resolve param '{fanout.resolve_param}'; "
"it is managed by build_dependent_resource."
)
- child_params.update(fanout.child_params)
+ params.update(fanout.child_params)
if child_params_extra:
- child_params.update(child_params_extra)
- child_endpoint_config: Endpoint = {
- "path": child_path,
- "params": child_params,
+ params.update(child_params_extra)
+
+ endpoint: Endpoint = {
+ "path": _format_path(child_config.path, path_format_values),
+ "params": params,
}
if fanout.child_response_actions:
- child_endpoint_config["response_actions"] = fanout.child_response_actions
+ endpoint["response_actions"] = fanout.child_response_actions
if child_endpoint_extra:
if "params" in child_endpoint_extra:
raise ValueError(
"Do not pass 'params' in child_endpoint_extra. "
"The child resolve/page-size params are managed by build_dependent_resource."
)
- child_endpoint_config.update(child_endpoint_extra)
+ endpoint.update(child_endpoint_extra)
- if warehouse_parent and "response_actions" not in child_endpoint_config:
+ if warehouse_parent and "response_actions" not in endpoint:
# 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"}]
+ endpoint["response_actions"] = [{"status_code": 404, "action": "ignore"}]
+ return endpoint
+
+def _build_child_resource(
+ *,
+ child_endpoint: str,
+ child_config: FanoutEndpointLike,
+ child_endpoint_config: Endpoint,
+ fanout: DependentEndpointConfig,
+ should_use_incremental_field: bool,
+ incremental_field: str | None,
+ incremental_config_factory: Callable[[str], IncrementalConfig | None] | None,
+) -> EndpointResource:
use_merge = should_use_incremental_field and bool(child_config.incremental_fields)
if use_merge:
if incremental_config_factory is None:
@@ -250,7 +263,7 @@ def build_dependent_resource(
if incremental is not None:
child_endpoint_config["incremental"] = incremental
- child_resource: EndpointResource = {
+ return {
"name": child_endpoint,
"table_name": child_endpoint,
"write_disposition": ({"disposition": "merge", "strategy": "upsert"} if use_merge else "replace"),
@@ -259,6 +272,92 @@ def build_dependent_resource(
"table_format": "delta",
}
+
+def _cap_at_parent_snapshot(
+ child: Any,
+ *,
+ child_endpoint: str,
+ child_config: FanoutEndpointLike,
+ incremental_field: str | None,
+ parent_snapshot_at: datetime,
+) -> Any:
+ # `getattr` because a source that never merges can omit the field entirely, and the read
+ # has to stay off the path those sources take.
+ cursor_field = incremental_field or getattr(child_config, "default_incremental_field", None)
+ if not cursor_field:
+ raise ValueError(
+ f"'{child_endpoint}' asks for a parent snapshot cap but declares no incremental field to "
+ "cap on; capping nothing would let its watermark run past the snapshot"
+ )
+ return child.add_filter(_not_newer_than(cursor_field, parent_snapshot_at))
+
+
+def build_dependent_resource(
+ *,
+ endpoint_configs: Mapping[str, FanoutEndpointLike],
+ child_endpoint: str,
+ fanout: DependentEndpointConfig,
+ client_config: ClientConfig,
+ path_format_values: dict[str, str],
+ team_id: int,
+ job_id: str,
+ db_incremental_field_last_value: Any,
+ should_use_incremental_field: bool = False,
+ incremental_field: str | None = None,
+ incremental_config_factory: Callable[[str], IncrementalConfig | None] | None = None,
+ parent_endpoint_extra: Endpoint | None = None,
+ child_endpoint_extra: Endpoint | None = None,
+ child_params_extra: dict[str, Any] | None = None,
+ parent_data_map: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
+ 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,
+ parent_snapshot_at: datetime | None = None,
+) -> Iterable[Any]:
+ parent_config = endpoint_configs[fanout.parent_name]
+ child_config = endpoint_configs[child_endpoint]
+
+ parent_resource = _build_parent_resource(
+ fanout=fanout,
+ parent_config=parent_config,
+ path_format_values=path_format_values,
+ page_size_param=page_size_param,
+ parent_endpoint_extra=parent_endpoint_extra,
+ parent_data_map=parent_data_map,
+ )
+
+ warehouse_parent = fanout.parent_source == "warehouse" and use_warehouse_parent
+ if warehouse_parent:
+ warehouse_parent = _attach_warehouse_parent(
+ parent_resource,
+ fanout=fanout,
+ page_size=parent_config.page_size,
+ team_id=team_id,
+ source_id=source_id,
+ child_endpoint=child_endpoint,
+ )
+
+ child_endpoint_config = _build_child_endpoint(
+ fanout=fanout,
+ child_config=child_config,
+ path_format_values=path_format_values,
+ page_size_param=page_size_param,
+ child_params_extra=child_params_extra,
+ child_endpoint_extra=child_endpoint_extra,
+ warehouse_parent=warehouse_parent,
+ )
+ child_resource = _build_child_resource(
+ child_endpoint=child_endpoint,
+ child_config=child_config,
+ child_endpoint_config=child_endpoint_config,
+ fanout=fanout,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ incremental_config_factory=incremental_config_factory,
+ )
+
config: RESTAPIConfig = {
"client": client_config,
"resource_defaults": {},
@@ -281,15 +380,13 @@ def build_dependent_resource(
# to be unresolvable, and a caller reading its own config would still see "warehouse" and cap a
# live API response, dropping rows that path had no reason to hold back.
if warehouse_parent and parent_snapshot_at is not None:
- # `getattr` because a source that never merges can omit the field entirely, and the read
- # has to stay off the path those sources take.
- cursor_field = incremental_field or getattr(child_config, "default_incremental_field", None)
- if not cursor_field:
- raise ValueError(
- f"'{child_endpoint}' asks for a parent snapshot cap but declares no incremental field to "
- "cap on; capping nothing would let its watermark run past the snapshot"
- )
- child = child.add_filter(_not_newer_than(cursor_field, parent_snapshot_at))
+ child = _cap_at_parent_snapshot(
+ child,
+ child_endpoint=child_endpoint,
+ child_config=child_config,
+ incremental_field=incremental_field,
+ parent_snapshot_at=parent_snapshot_at,
+ )
return child
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.py
index 638456278f37..f55ebcceaeb0 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
@@ -1,6 +1,6 @@
from collections.abc import Callable, Iterator
from dataclasses import dataclass, replace
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, cast
import pytest
@@ -35,6 +35,7 @@ def _stub_child_resource() -> Mock:
stub = Mock()
stub.name = "children"
stub.add_map.return_value = stub
+ stub.add_filter.return_value = stub
return stub
@@ -302,11 +303,13 @@ def test_build_dependent_resource_threads_resume_state(mock_rest_api_resources)
assert kwargs["initial_paginator_state"] == initial_state
[email protected]("extra_kwarg", ["parent_endpoint_extra", "child_endpoint_extra"])
@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:
+def test_build_dependent_resource_rejects_params_in_endpoint_extras(mock_rest_api_resources, extra_kwarg) -> None:
mock_rest_api_resources.return_value = [_stub_child_resource()]
+ endpoint_extra: dict[str, Any] = {extra_kwarg: {"params": {"limit": 1}}}
- with pytest.raises(ValueError, match="Do not pass 'params' in child_endpoint_extra"):
+ with pytest.raises(ValueError, match=f"Do not pass 'params' in {extra_kwarg}"):
build_dependent_resource(
endpoint_configs=_build_endpoint_configs(),
child_endpoint="children",
@@ -321,7 +324,7 @@ def test_build_dependent_resource_rejects_params_in_endpoint_extras(mock_rest_ap
team_id=1,
job_id="job-1",
db_incremental_field_last_value=None,
- child_endpoint_extra={"params": {"limit": 1}},
+ **endpoint_extra,
)
@@ -754,6 +757,230 @@ def test_warehouse_parent_drives_child_without_parent_http(mock_reader, _mock_re
]
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
+def test_path_format_values_bind_both_the_parent_and_the_child_path(mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [_stub_child_resource()]
+ endpoint_configs = _build_endpoint_configs()
+ endpoint_configs["parents"].path = "/orgs/{org_id}/parents"
+ endpoint_configs["children"].path = "/orgs/{org_id}/parents/{parent_id}/children"
+
+ build_dependent_resource(
+ endpoint_configs=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={"org_id": "acme"},
+ team_id=1,
+ job_id="job-1",
+ db_incremental_field_last_value=None,
+ )
+
+ config = mock_rest_api_resources.call_args.args[0]
+ assert config["resources"][0]["endpoint"]["path"] == "/orgs/acme/parents"
+ # {parent_id} stays a template: the child transformer binds it per parent row, not here.
+ assert config["resources"][1]["endpoint"]["path"] == "/orgs/acme/parents/{parent_id}/children"
+
+
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
+def test_parent_data_map_reaches_the_parent_resource(mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [_stub_child_resource()]
+ derive_resolve_field = Mock()
+
+ 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_data_map=derive_resolve_field,
+ )
+
+ config = mock_rest_api_resources.call_args.args[0]
+ assert config["resources"][0]["data_map"] is derive_resolve_field
+ assert "data_map" not in config["resources"][1]
+
+
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
+def test_child_params_extra_win_over_fanout_child_params(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=DependentEndpointConfig(
+ parent_name="parents",
+ resolve_param="parent_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ child_params={"full": "true", "expand": "none"},
+ ),
+ client_config={"base_url": "https://example.com"},
+ path_format_values={},
+ team_id=1,
+ job_id="job-1",
+ db_incremental_field_last_value=None,
+ child_params_extra={"expand": "items", "since": "2026-01-01"},
+ )
+
+ child_params = mock_rest_api_resources.call_args.args[0]["resources"][1]["endpoint"]["params"]
+ assert child_params == {
+ "parent_id": {"type": "resolve", "resource": "parents", "field": "id"},
+ "limit": 7,
+ "full": "true",
+ # The per-run value has to beat the static config value, or a caller cannot narrow a request.
+ "expand": "items",
+ "since": "2026-01-01",
+ }
+
+
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
+def test_incremental_config_is_bound_to_the_child_request(mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [_stub_child_resource()]
+ endpoint_configs = _build_endpoint_configs()
+ endpoint_configs["children"].incremental_fields = [{"field": "created_at"}]
+ endpoint_configs["children"].default_incremental_field = "created_at"
+ cursor_paths: list[str] = []
+
+ def factory(cursor_path: str) -> dict[str, Any]:
+ cursor_paths.append(cursor_path)
+ return {"cursor_path": cursor_path, "start_param": "since"}
+
+ build_dependent_resource(
+ endpoint_configs=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="2026-01-01T00:00:00Z",
+ should_use_incremental_field=True,
+ incremental_config_factory=cast(Any, factory),
+ )
+
+ assert cursor_paths == ["created_at"]
+ child_resource = mock_rest_api_resources.call_args.args[0]["resources"][1]
+ assert child_resource["endpoint"]["incremental"] == {"cursor_path": "created_at", "start_param": "since"}
+ assert child_resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources")
+def test_incremental_fanout_without_a_factory_is_rejected(mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [_stub_child_resource()]
+ endpoint_configs = _build_endpoint_configs()
+ endpoint_configs["children"].incremental_fields = [{"field": "created_at"}]
+
+ with pytest.raises(ValueError, match="incremental_config_factory is required"):
+ build_dependent_resource(
+ endpoint_configs=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,
+ should_use_incremental_field=True,
+ )
+
+
+_SNAPSHOT_AT = datetime(2026, 3, 1, tzinfo=UTC)
+
+
+def _build_with_snapshot_cap(endpoint_configs: dict[str, _EndpointConfig], **kwargs: Any) -> Any:
+ return build_dependent_resource(
+ endpoint_configs=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,
+ parent_snapshot_at=_SNAPSHOT_AT,
+ **kwargs,
+ )
+
+
+@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),
+)
+def test_warehouse_parent_caps_child_rows_at_the_snapshot(_mock_resolve, mock_rest_api_resources) -> None:
+ stub = _stub_child_resource()
+ mock_rest_api_resources.return_value = [stub]
+ endpoint_configs = _build_endpoint_configs()
+ endpoint_configs["children"].default_incremental_field = "updated_at"
+
+ _build_with_snapshot_cap(endpoint_configs)
+
+ keep = stub.add_filter.call_args.args[0]
+ # A row the snapshot could not account for would push the watermark past the snapshot.
+ assert keep({"updated_at": "2026-02-01T00:00:00Z"}) is True
+ assert keep({"updated_at": "2026-04-01T00:00:00Z"}) is False
+ # No cursor value is no recency signal, so the row is kept, as the parent row filter does.
+ assert keep({}) is True
+
+
+@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),
+)
+def test_snapshot_cap_without_a_cursor_field_is_rejected(_mock_resolve, mock_rest_api_resources) -> None:
+ mock_rest_api_resources.return_value = [_stub_child_resource()]
+
+ with pytest.raises(ValueError, match="declares no incremental field to cap on"):
+ _build_with_snapshot_cap(_build_endpoint_configs())
+
+
+@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_api_parent_fallback_leaves_the_child_uncapped(mock_rest_api_resources, mock_resolve) -> None:
+ # The cap exists to match a stale snapshot. The API parent is not stale, so capping it here
+ # would drop rows that path has every reason to sync.
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (
+ WarehouseParentTableNotFoundError,
+ )
+
+ mock_resolve.side_effect = WarehouseParentTableNotFoundError("table gone")
+ stub = _stub_child_resource()
+ mock_rest_api_resources.return_value = [stub]
+ endpoint_configs = _build_endpoint_configs()
+ endpoint_configs["children"].default_incremental_field = "updated_at"
+
+ _build_with_snapshot_cap(endpoint_configs)
+
+ stub.add_filter.assert_not_called()
+
+
class _ConfigWithFanout:
def __init__(self, fanout: DependentEndpointConfig | None) -> None:
self.fanout = fanout