Skip to content

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

feat(data-warehouse): add fan-out support to custom REST source (#62115)

Marcus Hoff2655ab90933
diff --git a/posthog/temporal/data_imports/sources/custom/source.py b/posthog/temporal/data_imports/sources/custom/source.py
index 7e7775693353..9ae29429fafc 100644
--- a/posthog/temporal/data_imports/sources/custom/source.py
+++ b/posthog/temporal/data_imports/sources/custom/source.py
@@ -1,7 +1,11 @@
+import copy
import json
-from typing import Any, Literal, Optional, cast
+import graphlib
+from typing import Any, Literal, NamedTuple, Optional, cast
from urllib.parse import urlparse
+import structlog
+from jsonpath_ng.exceptions import JSONPathError
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
from requests import Response
from urllib3.util.retry import Retry
@@ -20,10 +24,18 @@ from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleS
from posthog.temporal.data_imports.sources.common.http import make_tracked_session
from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
-from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource
+from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resources
from posthog.temporal.data_imports.sources.common.rest_source.auth import auth_secret_values
-from posthog.temporal.data_imports.sources.common.rest_source.config_setup import create_auth
-from posthog.temporal.data_imports.sources.common.rest_source.utils import resolve_request_url
+from posthog.temporal.data_imports.sources.common.rest_source.config_setup import (
+ build_resource_dependency_graph,
+ create_auth,
+)
+from posthog.temporal.data_imports.sources.common.rest_source.typing import (
+ EndpointResource,
+ EndpointResourceBase,
+ ResolvedParam,
+)
+from posthog.temporal.data_imports.sources.common.rest_source.utils import exclude_keys, resolve_request_url
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import CustomSourceConfig
from posthog.temporal.data_imports.util import NonRetryableException
@@ -34,6 +46,8 @@ from products.data_warehouse.backend.types import ExternalDataSourceType, Increm
# the dedicated secret `auth_*` config fields so the API layer can redact them.
INLINE_SECRET_KEYS = ("token", "api_key", "password")
+logger = structlog.get_logger(__name__)
+
# Outbound create-time probe tunables. The probe runs inline on the API request
# thread, the same as business_knowledge's URL fetch, so it borrows that feature's
# limits (products/business_knowledge/backend/constants.py): short connect/read
@@ -139,12 +153,16 @@ class _Manifest(BaseModel):
return self
-def validate_manifest(manifest: Any) -> None:
- """Validate the structural shape of a user-provided REST API manifest.
+def validate_manifest_structure(manifest: Any) -> None:
+ """Validate only the structural shape of a manifest, via the
+ :class:`_Manifest` schema.
- Delegates to the :class:`_Manifest` schema. The safety of any URLs in
- the manifest is checked separately by :func:`validate_manifest_urls`,
- which needs the team_id for cloud-vs-self-hosted handling.
+ This is the validation level used on sync and schema-listing reads of
+ already-stored manifests: it must stay permissive enough that tightening
+ the rules can never brick a deployed source's syncs. Graph-level fan-out
+ errors are checked separately by :func:`_validate_resource_graph` on the
+ API validation paths (`validate_credentials`), and per-schema at sync time
+ by :func:`_fanout_chain`.
"""
if not isinstance(manifest, dict):
raise ManifestValidationError("Manifest must be a JSON object")
@@ -154,6 +172,86 @@ def validate_manifest(manifest: Any) -> None:
raise ManifestValidationError(_format_validation_errors(exc)) from exc
+def _validate_resource_graph(manifest: dict[str, Any]) -> dict[str, Optional[ResolvedParam]]:
+ """Surface parent/child fan-out errors at create-time instead of first sync.
+
+ Reuses the REST engine's own :func:`build_resource_dependency_graph` so the
+ rules can't drift from what the engine enforces at runtime: a child's
+ ``type: "resolve"`` param must reference a resource that exists, must be
+ bound in the path (``/forms/{form_id}/responses`` — query-param resolve is
+ not supported by the engine), at most one resolve param per resource, and no
+ dependency cycles (forced by ``static_order``). The graph builder mutates the
+ resources it inspects (binds path params), so it runs on a deep copy and
+ never touches the stored manifest.
+
+ On top of the engine's rules, nesting is capped at one level: a parent must
+ itself be top-level. The engine supports deeper chains, but each extra level
+ multiplies the per-sync request volume by the parent's row count and every
+ ancestor full-scans on every run — and no shipped fan-out source (PostHog
+ built-ins, or any of Airbyte's declarative connectors) uses more than one
+ level. Starting strict is deliberately cheap to relax later; loosening the
+ cap is backwards-compatible, tightening it would break stored manifests.
+
+ Returns the engine's parent-resolution map (resource name -> resolve param,
+ ``None`` for top-level resources) so callers that need it — the probe's
+ child filter — don't rebuild the graph.
+ """
+ try:
+ graph, resource_map, resolved = _build_resource_graph(manifest)
+ list(graph.static_order())
+ except KeyError as exc:
+ # A resolve param missing "resource"/"field" raises KeyError from deep
+ # inside the engine — surface it as a validation error, not a 500.
+ raise ManifestValidationError(f"A resolve param is missing the required key {exc}") from exc
+ except JSONPathError as exc:
+ # The resolve param's "field" is a JSONPath, compiled inside the engine;
+ # a malformed expression raises a bare-Exception subclass.
+ raise ManifestValidationError(f"A resolve param's field is not a valid JSONPath: {exc}") from exc
+ except graphlib.CycleError as exc:
+ # str(CycleError) is the raw args tuple — render the cycle readably.
+ cycle = exc.args[1] if len(exc.args) > 1 else []
+ rendered = " -> ".join(str(name) for name in cycle)
+ raise ManifestValidationError(f"Resources form a dependency cycle: {rendered}") from exc
+ except (ValueError, NotImplementedError) as exc:
+ raise ManifestValidationError(str(exc)) from exc
+
+ client = manifest.get("client")
+ base_url = client.get("base_url") if isinstance(client, dict) else None
+ for name, resolved_param in resolved.items():
+ if resolved_param is None:
+ continue
+ parent = resolved_param.resolve_config["resource"]
+ if resolved.get(parent) is not None:
+ raise ManifestValidationError(
+ f"Resource {name!r} depends on {parent!r}, which itself depends on another resource — "
+ "a resource can only depend on a top-level resource (one level of nesting)"
+ )
+ # The parent placeholder is filled with uncontrolled upstream data at
+ # sync time, then the engine resolves the path against base_url. A
+ # placeholder positioned where it can supply the URL's authority lets that
+ # parent value redirect the authenticated request — and its credential —
+ # off base_url: a leading placeholder (`{form_id}/...`) can be a full
+ # `https://attacker/...`, and a literal scheme prefix (`https:{form_id}`)
+ # lets `//attacker/...` take over the authority. Neither the create-time
+ # host validator nor the update retarget guard can see this — they only
+ # ever inspect the literal placeholder. The path comes from `resource_map`
+ # (defaults merged, scalar params already bound), so only the resolve
+ # placeholder survives in the same string the request is built from.
+ endpoint = resource_map[name].get("endpoint")
+ path = endpoint.get("path", "") if isinstance(endpoint, dict) else ""
+ if (
+ isinstance(path, str)
+ and isinstance(base_url, str)
+ and _placeholder_escapes_base(path, resolved_param.param_name, base_url)
+ ):
+ raise ManifestValidationError(
+ f"Resource {name!r}: the parent placeholder {{{resolved_param.param_name}}} must sit within the path "
+ "of the base URL (e.g. /forms/{form_id}/responses) — it must not start the path or follow a scheme "
+ "like 'https:', so the bound parent value can't redirect the request off the manifest's base URL"
+ )
+ return resolved
+
+
def _format_validation_errors(exc: ValidationError) -> str:
"""Render Pydantic's validation errors as a single user-facing string."""
messages: list[str] = []
@@ -297,6 +395,43 @@ def _url_hostname(url: str) -> str | None:
return urlparse(normalized).hostname
+# Probe values substituted for a fan-out child's resolve placeholder to test
+# whether uncontrolled parent data bound there could move the request — and the
+# credential — off base_url's host. Each models a different escape technique: a
+# full absolute URL (placeholder is the first/only path segment), an
+# authority-only value (a literal ``scheme:`` prefix lets ``//host`` take over),
+# and a bare host (placeholder sits in the authority of a ``scheme://`` prefix).
+# The ``.invalid`` TLD never resolves and this is a pure string check — no I/O.
+_PLACEHOLDER_ESCAPE_SENTINELS = ("https://sentinel.invalid/x", "//sentinel.invalid/x", "sentinel.invalid")
+
+
+def _placeholder_escapes_base(path: str, param_name: str, base_url: str) -> bool:
+ """True if binding the resolve placeholder ``{param_name}`` in ``path`` could
+ move the request to a host other than ``base_url``'s.
+
+ The placeholder is filled with uncontrolled upstream data at sync time, then
+ the engine resolves the path against ``base_url`` exactly as
+ :func:`resolve_request_url` does. We substitute attacker-shaped sentinels for
+ the placeholder and check whether any resolves to a different host — catching
+ not just a leading placeholder (``{form_id}/responses``) but a literal
+ ``scheme:`` prefix that lets the bound value supply the authority
+ (``https:{form_id}/responses`` with ``form_id="//attacker/x"`` resolves to the
+ attacker host). A position that keeps the placeholder strictly inside the path
+ (``/forms/{form_id}/responses``) leaves the host unchanged and passes.
+ """
+ base_host = _url_hostname(base_url)
+ if not base_host:
+ # A base_url with no host is rejected separately by validate_manifest_urls;
+ # don't raise a confusing placeholder error for it here.
+ return False
+ placeholder = "{" + param_name + "}"
+ for sentinel in _PLACEHOLDER_ESCAPE_SENTINELS:
+ probed = path.replace(placeholder, sentinel)
+ if _url_hostname(resolve_request_url(base_url, probed)) != base_host:
+ return True
+ return False
+
+
@SourceRegistry.register
class CustomSource(SimpleSource[CustomSourceConfig]):
"""User-defined REST API source.
@@ -391,7 +526,12 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
manifest = json.loads(config.manifest_json)
except json.JSONDecodeError as exc:
raise ManifestValidationError(f"Manifest is not valid JSON: {exc.msg} (line {exc.lineno}, col {exc.colno})")
- validate_manifest(manifest)
+ # Structural validation only — no resource-graph checks. This runs on
+ # every sync and schema listing of already-stored manifests, so a
+ # graph problem on one resource must not take down the source's other
+ # schemas (graph rules are enforced on the API validation paths in
+ # `validate_credentials`, and per-schema at sync time in `_fanout_chain`).
+ validate_manifest_structure(manifest)
_inject_auth_secrets(manifest, config)
return manifest
@@ -400,6 +540,14 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
) -> tuple[bool, str | None]:
try:
manifest = self._assemble_manifest(config)
+ # Graph-level fan-out rules apply on every validation path —
+ # including updates that don't touch the manifest and schema-scoped
+ # read checks. Builder-authored manifests are always graph-valid,
+ # so a stored manifest tripping this means hand-authored JSON that
+ # never synced; failing the API call with a pointed message is
+ # preferable to carrying a permanent leniency mode. The returned
+ # map feeds the probe's child filter below.
+ resolved = _validate_resource_graph(manifest)
except ManifestValidationError as exc:
return False, str(exc)
@@ -438,7 +586,14 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
allow_redirects=False,
)
- for resource in manifest["resources"][:PROBE_MAX_RESOURCES]:
+ # Fan-out child resources bind a parent row's field into their path
+ # (`/forms/{form_id}/responses`), so they can't be reached without first
+ # fetching a parent — skip them. Auth is shared across resources, so the
+ # top-level resources still validate the credential. The engine's own
+ # dependency map (not a local copy of its resolve-param detection) tells
+ # us which resources are children.
+ probeable = [resource for resource in manifest["resources"] if resolved.get(resource.get("name")) is None]
+ for resource in probeable[:PROBE_MAX_RESOURCES]:
endpoint = resource.get("endpoint", {})
method = (endpoint.get("method") or "GET").upper()
path = endpoint.get("path", "")
@@ -512,33 +667,44 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
if not ok:
raise ManifestValidationError(err or "Manifest URL validation failed")
- chosen = next(
- (r for r in manifest["resources"] if isinstance(r, dict) and r.get("name") == inputs.schema_name),
- None,
+ # The resources to run for this schema: the chosen resource plus,
+ # when it's a fan-out child, its ancestor chain (root first) — see
+ # `_fanout_chain` for the full rationale. Ancestors are stripped of
+ # incremental config so the run's high-watermark — which belongs to
+ # the chosen resource — can't be misapplied to a parent and silently
+ # drop parent rows (and with them their children); they full-scan
+ # every run, matching the built-in fan-out sources (Typeform/Sentry).
+ chain = _fanout_chain(manifest, inputs.schema_name)
+ chosen = chain.child
+ engine_resources = [
+ *(_without_incremental_config(r) for r in chain.ancestors),
+ _strip_engine_unsupported_incremental_keys(chain.child),
+ ]
+ engine_manifest = cast(RESTAPIConfig, {**manifest, "resources": engine_resources})
+
+ # Inside the try block: the engine raises deterministic ValueErrors at
+ # build time for config problems the create-time checks can't see
+ # (e.g. `include_from_parent` on a resource with no resolve param).
+ resources = rest_api_resources(
+ engine_manifest,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ db_incremental_field_last_value=(
+ inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
+ ),
)
- if chosen is None:
- raise ValueError(f"Resource {inputs.schema_name!r} not found in config")
except ValueError as exc:
- # A malformed manifest or a missing resource is a permanent,
- # deterministic failure — retrying the sync cannot fix it. Raise
- # NonRetryableException (the only type Temporal treats as
- # non-retryable for this activity) so the job fails fast instead of
- # burning the whole retry budget on an error that will always recur.
+ # A malformed manifest, a missing resource, or a broken parent
+ # reference is a permanent, deterministic failure — retrying the sync
+ # cannot fix it. Raise NonRetryableException (the only type Temporal
+ # treats as non-retryable for this activity) so the job fails fast
+ # instead of burning the whole retry budget on an error that will
+ # always recur.
raise NonRetryableException(str(exc)) from exc
- single_resource_manifest = cast(
- RESTAPIConfig,
- {**manifest, "resources": [_strip_engine_unsupported_incremental_keys(chosen)]},
- )
-
- resource = rest_api_resource(
- single_resource_manifest,
- team_id=inputs.team_id,
- job_id=inputs.job_id,
- db_incremental_field_last_value=(
- inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None
- ),
- )
+ resource = next((r for r in resources if getattr(r, "name", None) == inputs.schema_name), None)
+ if resource is None:
+ raise NonRetryableException(f"Resource {inputs.schema_name!r} was not produced by the REST engine")
primary_key = chosen.get("primary_key")
primary_keys: list[str] | None
@@ -563,7 +729,12 @@ class CustomSource(SimpleSource[CustomSourceConfig]):
# finish within one worker window. A proper fix would slice the cursor into
# windows with per-window state (cf. Airbyte's DatetimeBasedCursor), which
# the generic engine doesn't support today.
- sort_mode: SortMode = "desc" if chosen.get("sort_mode") == "desc" else "asc"
+ #
+ # Fan-out children always get the deferred-commit ("desc") behavior: their
+ # rows arrive grouped per parent, never globally cursor-ascending, so an
+ # "asc" per-batch commit after an interruption would set the watermark past
+ # later parents' older rows and permanently skip them.
+ sort_mode: SortMode = "desc" if (chain.is_fanout_child or chosen.get("sort_mode") == "desc") else "asc"
return SourceResponse(
name=inputs.schema_name,
@@ -666,10 +837,114 @@ def _strip_engine_unsupported_incremental_keys(resource: dict[str, Any]) -> dict
incremental = endpoint.get("incremental")
if not isinstance(incremental, dict) or not _ENGINE_UNSUPPORTED_INCREMENTAL_KEYS.intersection(incremental):
return resource
- cleaned = {k: v for k, v in incremental.items() if k not in _ENGINE_UNSUPPORTED_INCREMENTAL_KEYS}
+ cleaned = exclude_keys(incremental, _ENGINE_UNSUPPORTED_INCREMENTAL_KEYS)
return {**resource, "endpoint": {**endpoint, "incremental": cleaned}}
+def _build_resource_graph(
+ manifest: dict[str, Any],
+) -> tuple[Any, dict[str, EndpointResource], dict[str, Optional[ResolvedParam]]]:
+ """Run the REST engine's dependency-graph builder on a deep copy of the
+ manifest. The builder binds path params in place, so it must never see the
+ stored manifest's resources — hence the copy.
+ """
+ return build_resource_dependency_graph(
+ cast(EndpointResourceBase, copy.deepcopy(manifest.get("resource_defaults") or {})),
+ cast("list[str | EndpointResource]", copy.deepcopy(manifest["resources"])),
+ )
+
+
+class FanoutChain(NamedTuple):
+ """The resources a schema's sync hands the engine: the chosen resource plus
+ its fan-out ancestors (root first). The single source of truth for whether
+ the chosen resource is a fan-out child — callers must not re-derive that
+ from names or chain length."""
+
+ ancestors: list[dict[str, Any]]
+ child: dict[str, Any]
+
+ @property
+ def is_fanout_child(self) -> bool:
+ return bool(self.ancestors)
+
+
+def _fanout_chain(manifest: dict[str, Any], chosen_name: str) -> FanoutChain:
+ """The :class:`FanoutChain` for ``chosen_name``: its fan-out ancestors
+ (root first) plus ``chosen`` itself; a top-level resource has no ancestors.
+
+ We pass this subset, not the whole manifest, on purpose. The engine is lazy —
+ resources it builds but we never iterate issue no requests — but it still
+ runs ``setup_incremental_object`` for every resource it's given at build time,
+ so an unrelated resource's config error would otherwise sink this schema's
+ sync. Subsetting also lets the caller full-scan the ancestors (via
+ ``_without_incremental_config``) so the child's high-watermark isn't
+ misapplied to a parent. The parent graph comes from the engine's own
+ ``build_resource_dependency_graph``, so resolve-param detection isn't
+ re-implemented here.
+
+ Raises ``ValueError`` when ``chosen_name`` isn't in the manifest.
+ """
+ by_name: dict[str, dict[str, Any]] = {
+ r["name"]: r for r in manifest["resources"] if isinstance(r, dict) and isinstance(r.get("name"), str)
+ }
+ chosen = by_name.get(chosen_name)
+ if chosen is None:
+ raise ValueError(f"Resource {chosen_name!r} not found in config")
+ try:
+ _, _, resolved = _build_resource_graph(manifest)
+ except (ValueError, NotImplementedError, KeyError, JSONPathError) as exc:
+ # Graph rules are enforced at create/update time, but a stored manifest
+ # can predate them. A graph error on an UNRELATED resource must not sink
+ # this schema's sync — fall back to handing the engine just the chosen
+ # resource (the pre-fan-out behavior). If the chosen resource itself is
+ # the broken one, the engine rejects it at build time with the
+ # underlying error, which the caller converts to a non-retryable failure.
+ # Logged so the size of the predates-the-rules population is measurable;
+ # once this stops firing in production the fallback can be deleted.
+ logger.warning(
+ "custom_source_fanout_graph_fallback",
+ schema_name=chosen_name,
+ error=str(exc),
+ )
+ return FanoutChain(ancestors=[], child=chosen)
+ ancestor_names: list[str] = []
+ seen: set[str] = {chosen_name}
+ current = chosen_name
+ while (resolved_param := resolved.get(current)) is not None:
+ parent_name = resolved_param.resolve_config["resource"]
+ if parent_name in seen:
+ # The graph builder itself doesn't reject cycles (only the
+ # create-time `static_order` check does), so a stored manifest can
+ # still carry one — fail loudly rather than loop or truncate.
+ raise ValueError(f"Resource {chosen_name!r} is part of a dependency cycle")
+ ancestor_names.append(parent_name)
+ seen.add(parent_name)
+ current = parent_name
+ return FanoutChain(ancestors=[by_name[name] for name in reversed(ancestor_names)], child=chosen)
+
+
+def _without_incremental_config(resource: dict[str, Any]) -> dict[str, Any]:
+ """Return a copy of ``resource`` with every incremental form removed.
+
+ The engine builds an incremental tracker from EITHER ``endpoint.incremental``
+ OR a params-style ``{"type": "incremental", ...}`` spec (see the engine's
+ ``setup_incremental_object``) — both must go, or the run's high-watermark
+ would still be injected into this resource's start param.
+ """
+ endpoint = resource.get("endpoint")
+ if not isinstance(endpoint, dict):
+ return resource
+ cleaned = exclude_keys(endpoint, {"incremental"})
+ params = cleaned.get("params")
+ if isinstance(params, dict):
+ cleaned["params"] = {
+ key: value
+ for key, value in params.items()
+ if not (isinstance(value, dict) and value.get("type") == "incremental")
+ }
+ return {**resource, "endpoint": cleaned}
+
+
def _schema_from_resource(resource: dict[str, Any]) -> SourceSchema:
name = resource["name"]
endpoint = resource.get("endpoint", {})
diff --git a/posthog/temporal/data_imports/sources/custom/test_custom_source.py b/posthog/temporal/data_imports/sources/custom/test_custom_source.py
index 90ec70705655..442304998a36 100644
--- a/posthog/temporal/data_imports/sources/custom/test_custom_source.py
+++ b/posthog/temporal/data_imports/sources/custom/test_custom_source.py
@@ -1,12 +1,14 @@
import io
import gzip
import json
+from typing import Any, cast
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from requests import Response
from urllib3.response import HTTPResponse
from posthog.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth, BearerTokenAuth, HttpBasicAuth
@@ -15,10 +17,13 @@ from posthog.temporal.data_imports.sources.custom.source import (
PROBE_ERROR_SNIPPET_BYTES,
PROBE_MAX_RESOURCES,
CustomSource,
+ FanoutChain,
ManifestValidationError,
+ _fanout_chain,
_read_capped_text,
+ _validate_resource_graph,
manifest_request_hosts,
- validate_manifest,
+ validate_manifest_structure,
validate_manifest_urls,
)
from posthog.temporal.data_imports.sources.generated_configs import CustomSourceConfig
@@ -27,6 +32,15 @@ from posthog.temporal.data_imports.util import NonRetryableException
from products.data_warehouse.backend.types import IncrementalFieldType
+def validate_manifest(manifest: Any) -> None:
+ # Full-validation composite (structure + graph). Production runs the two
+ # levels separately — permissive structural checks on stored-manifest
+ # reads, graph rules on the API validation paths — so the composite lives
+ # here with the tests that use it.
+ validate_manifest_structure(manifest)
+ _validate_resource_graph(manifest)
+
+
def _minimal_manifest(base_url: str = "https://api.example.com") -> dict:
"""A structurally valid manifest. Auth carries no inline credential — the
secret lives in the separate auth_* config fields."""
@@ -709,8 +723,9 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
@parameterized.expand(
[("default_asc", None, "asc"), ("explicit_asc", "asc", "asc"), ("explicit_desc", "desc", "desc")]
)
- @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
- def test_sort_mode_threaded_to_source_response(self, _name, declared, expected, _mock_resource):
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_sort_mode_threaded_to_source_response(self, _name, declared, expected, mock_resources):
+ mock_resources.return_value = [_fake_resource("users")]
manifest = _minimal_manifest()
if declared is not None:
manifest["resources"][0]["sort_mode"] = declared
@@ -734,12 +749,13 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
("opted_in_none", True, None, None),
]
)
- @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
def test_incremental_last_value_threaded_to_rest_engine(
- self, _name, should_use_incremental, last_value, expected, mock_resource
+ self, _name, should_use_incremental, last_value, expected, mock_resources
):
# The high-watermark must only reach the REST engine when the schema is
# configured for incremental sync — otherwise a full refresh would skip rows.
+ mock_resources.return_value = [_fake_resource("users")]
source = CustomSource()
config = CustomSourceConfig(manifest_json=json.dumps(_minimal_manifest()))
inputs = MagicMock(
@@ -751,7 +767,7 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
)
source.source_for_pipeline(config, inputs)
- assert mock_resource.call_args.kwargs["db_incremental_field_last_value"] == expected
+ assert mock_resources.call_args.kwargs["db_incremental_field_last_value"] == expected
@parameterized.expand(
[
@@ -764,11 +780,12 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
("page_number", {"type": "page_number", "page_param": "page"}),
]
)
- @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
- def test_paginator_config_threaded_to_rest_engine(self, _name, paginator_config, mock_resource):
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_paginator_config_threaded_to_rest_engine(self, _name, paginator_config, mock_resources):
# Every PaginatorType the REST engine knows about must round-trip through
# the custom source — paginator config is passed through untouched and the
# REST engine selects the paginator at sync time.
+ mock_resources.return_value = [_fake_resource("users")]
manifest = _minimal_manifest()
manifest["client"]["paginator"] = paginator_config
@@ -783,14 +800,15 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
)
source.source_for_pipeline(config, inputs)
- threaded_config = mock_resource.call_args.args[0]
+ threaded_config = mock_resources.call_args.args[0]
assert threaded_config["client"]["paginator"] == paginator_config
- @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resource")
- def test_cursor_type_stripped_before_rest_engine(self, mock_resource):
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_cursor_type_stripped_before_rest_engine(self, mock_resources):
# cursor_type informs schema field typing but is not a valid kwarg for the
# engine's Incremental(**config) — it must be removed before the manifest
- # reaches rest_api_resource, while the other incremental keys survive.
+ # reaches the REST engine, while the other incremental keys survive.
+ mock_resources.return_value = [_fake_resource("users")]
manifest = _minimal_manifest()
manifest["resources"][0]["endpoint"]["incremental"] = {
"cursor_path": "updated_at",
@@ -809,5 +827,541 @@ class TestCustomSourceSourceForPipeline(SimpleTestCase):
)
source.source_for_pipeline(config, inputs)
- threaded_incremental = mock_resource.call_args.args[0]["resources"][0]["endpoint"]["incremental"]
+ threaded_incremental = mock_resources.call_args.args[0]["resources"][0]["endpoint"]["incremental"]
assert threaded_incremental == {"cursor_path": "updated_at", "start_param": "since"}
+
+
+def _fanout_manifest() -> dict:
+ """A parent (`forms`) + fan-out child (`responses`) that binds the parent's
+ `id` into its path via a `type: "resolve"` param."""
+ return {
+ "client": {"base_url": "https://api.example.com", "auth": {"type": "bearer"}},
+ "resources": [
+ {"name": "forms", "primary_key": "id", "endpoint": {"path": "/forms", "data_selector": "items"}},
+ {
+ "name": "responses",
+ "primary_key": "token",
+ "endpoint": {
+ "path": "/forms/{form_id}/responses",
+ "data_selector": "items",
+ "params": {"form_id": {"type": "resolve", "resource": "forms", "field": "id"}},
+ },
+ },
+ ],
+ }
+
+
+def _fake_resource(name: str) -> MagicMock:
+ # MagicMock(name=...) sets the mock's repr, not a `.name` attribute, so the
+ # source's `r.name == chosen_name` lookup needs the attribute set explicitly.
+ resource = MagicMock()
+ resource.name = name
+ return resource
+
+
+def _break_unknown_parent(m: dict) -> None:
+ m["resources"][1]["endpoint"]["params"]["form_id"]["resource"] = "nonexistent"
+
+
+def _break_resolve_not_in_path(m: dict) -> None:
+ # Resolve param with no matching `{placeholder}` — the engine can only inject into the path.
+ m["resources"][1]["endpoint"]["path"] = "/responses"
+
+
+def _break_cycle(m: dict) -> None:
+ # Make `forms` depend on `responses`, closing a loop.
+ m["resources"][0]["endpoint"]["path"] = "/forms/{response_token}"
+ m["resources"][0]["endpoint"]["params"] = {
+ "response_token": {"type": "resolve", "resource": "responses", "field": "token"}
+ }
+
+
+def _break_multiple_resolve_params(m: dict) -> None:
+ m["resources"][1]["endpoint"]["path"] = "/forms/{form_id}/responses/{other_id}"
+ m["resources"][1]["endpoint"]["params"]["other_id"] = {"type": "resolve", "resource": "forms", "field": "id"}
+
+
+def _break_missing_resolve_field(m: dict) -> None:
+ # The engine raises KeyError (not ValueError) for this shape — it must still
+ # surface as a clean validation error, not a 500.
+ del m["resources"][1]["endpoint"]["params"]["form_id"]["field"]
+
+
+def _break_missing_resolve_resource(m: dict) -> None:
+ del m["resources"][1]["endpoint"]["params"]["form_id"]["resource"]
+
+
+def _break_invalid_resolve_field_jsonpath(m: dict) -> None:
+ # The resolve field is a JSONPath; a malformed one raises a bare-Exception
+ # subclass (JsonPathParserError) from inside the engine.
+ m["resources"][1]["endpoint"]["params"]["form_id"]["field"] = "user..["
+
+
+def _break_path_starting_with_placeholder(m: dict) -> None:
+ # A child path that BEGINS with the parent placeholder lets an absolute URL
+ # in the parent's field move the authenticated request off base_url.
+ m["resources"][1]["endpoint"]["path"] = "{form_id}/responses"
+
+
+def _break_leading_slash_placeholder(m: dict) -> None:
+ # A leading slash is NOT a defense: the engine strips leading slashes before
+ # joining onto base_url, so `/{form_id}/...` still resolves to whatever host
+ # the bound parent value carries.
+ m["resources"][1]["endpoint"]["path"] = "/{form_id}/responses"
+
+
+def _break_scheme_prefixed_placeholder(m: dict) -> None:
+ # A literal scheme prefix lets the placeholder supply the URL's authority:
+ # `https:{form_id}/...` with `form_id="//attacker/x"` formats to
+ # `https://attacker/x/...`, an absolute URL off base_url. The placeholder is
+ # not the first path segment, so a position-only guard misses it.
+ m["resources"][1]["endpoint"]["path"] = "https:{form_id}/responses"
+
+
+def _add_nested_child(m: dict) -> None:
+ # Grandchild: nesting is capped at one level — a parent must be top-level.
+ m["resources"].append(
+ {
+ "name": "answers",
+ "primary_key": "id",
+ "endpoint": {
+ "path": "/responses/{response_token}/answers",
+ "params": {"response_token": {"type": "resolve", "resource": "responses", "field": "token"}},
+ },
+ }
+ )
+
+
+class TestCustomSourceFanoutValidation(SimpleTestCase):
+ def test_accepts_valid_fanout(self):
+ validate_manifest(_fanout_manifest())
+
+ @parameterized.expand(
+ [
+ ("unknown_parent", _break_unknown_parent),
+ ("resolve_param_not_bound_in_path", _break_resolve_not_in_path),
+ ("cycle", _break_cycle),
+ ("multiple_resolve_params", _break_multiple_resolve_params),
+ ("missing_resolve_field", _break_missing_resolve_field),
+ ("missing_resolve_resource", _break_missing_resolve_resource),
+ ("invalid_resolve_field_jsonpath", _break_invalid_resolve_field_jsonpath),
+ ("nested_child", _add_nested_child),
+ ("path_starting_with_placeholder", _break_path_starting_with_placeholder),
+ ("leading_slash_placeholder", _break_leading_slash_placeholder),
+ ("scheme_prefixed_placeholder", _break_scheme_prefixed_placeholder),
+ ]
+ )
+ def test_rejects_invalid_fanout(self, _name, break_manifest):
+ # Every fan-out misconfiguration the engine's dependency graph rejects must
+ # surface at manifest-validation time, not first sync.
+ manifest = _fanout_manifest()
+ break_manifest(manifest)
+ with self.assertRaises(ManifestValidationError):
+ validate_manifest(manifest)
+
+ @parameterized.expand(
+ [
+ # str(graphlib.CycleError) is its raw args tuple — the user-facing
+ # message must render the cycle, not the tuple repr.
+ ("cycle", _break_cycle, ["dependency cycle"]),
+ # The nesting cap must name the offending resources.
+ ("nested_child", _add_nested_child, ["'answers'", "'responses'", "one level of nesting"]),
+ # The placeholder-authority guard must name the resource and point at
+ # the scheme-prefix escape, not just the leading-segment case.
+ ("scheme_prefixed_placeholder", _break_scheme_prefixed_placeholder, ["'responses'", "scheme", "redirect"]),
+ ]
+ )
+ def test_rejection_message_is_readable(self, _name, break_manifest, expected_fragments):
+ manifest = _fanout_manifest()
+ break_manifest(manifest)
+ with self.assertRaises(ManifestValidationError) as ctx:
+ validate_manifest(manifest)
+ message = str(ctx.exception)
+ assert not message.startswith("(")
+ for fragment in expected_fragments:
+ assert fragment in message
+
+ @parameterized.expand(
+ [
+ # Graph rules apply on every validation path — create/update ...
+ ("create_or_update", {}),
+ # ... and schema-scoped read checks against stored config alike.
+ # Builder-authored manifests are always graph-valid, so a stored
+ # manifest tripping this was hand-authored JSON that never synced.
+ ("schema_scoped_read_check", {"schema_name": "forms"}),
+ ]
+ )
+ def test_validate_credentials_rejects_broken_graph(self, _name, kwargs):
+ manifest = _fanout_manifest()
+ _break_unknown_parent(manifest)
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999, **kwargs)
+ assert ok is False
+ assert err is not None and "nonexistent" in err
+
+
+class TestFanoutChain(SimpleTestCase):
+ def test_top_level_resource_has_no_ancestors(self):
+ manifest = _fanout_manifest()
+ chain = _fanout_chain(manifest, "forms")
+ assert chain == FanoutChain(ancestors=[], child=manifest["resources"][0])
+ assert chain.is_fanout_child is False
+
+ def test_child_chain_is_parent_first(self):
+ manifest = _fanout_manifest()
+ parent, child = manifest["resources"]
+ chain = _fanout_chain(manifest, "responses")
+ assert chain == FanoutChain(ancestors=[parent], child=child)
+ assert chain.is_fanout_child is True
+
+ def test_multi_level_chain(self):
+ # Create-time validation rejects nesting beyond one level, but the sync
+ # path must still walk a deeper chain correctly if a stored manifest
+ # carries one (e.g. written before the cap existed).
+ manifest = _fanout_manifest()
+ _add_nested_child(manifest)
+ forms, responses, answers = manifest["resources"]
+ assert _fanout_chain(manifest, "answers") == FanoutChain(ancestors=[forms, responses], child=answers)
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.logger")
+ def test_falls_back_to_chosen_when_unrelated_resource_breaks_the_graph(self, mock_logger):
+ # A stored manifest can predate the create-time graph rules. A graph
+ # error on a sibling must not sink this schema — the chain degrades to
+ # the pre-fan-out single-resource behavior, and the degradation is
+ # logged so the affected population stays measurable.
+ manifest = _fanout_manifest()
+ _break_unknown_parent(manifest)
+ manifest["resources"].append(
+ {"name": "users", "primary_key": "id", "endpoint": {"path": "/users", "data_selector": "items"}}
+ )
+ assert _fanout_chain(manifest, "users") == FanoutChain(ancestors=[], child=manifest["resources"][2])
+ mock_logger.warning.assert_called_once()
+ assert mock_logger.warning.call_args.args[0] == "custom_source_fanout_graph_fallback"
+ assert mock_logger.warning.call_args.kwargs["schema_name"] == "users"
+
+ def test_raises_for_chosen_resource_in_a_cycle(self):
+ # The graph builder itself doesn't reject cycles (only create-time
+ # static_order does) — the walk must fail loudly, not loop or truncate.
+ manifest = _fanout_manifest()
+ _break_cycle(manifest)
+ with self.assertRaises(ValueError):
+ _fanout_chain(manifest, "responses")
+
+
+class TestCustomSourceFanoutPipeline(SimpleTestCase):
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_child_schema_runs_parent_and_child(self, mock_resources):
+ # Selecting the child must hand the engine BOTH resources (parent first)
+ # and return only the child resource — the parent is fetched transiently.
+ mock_resources.return_value = [_fake_resource("forms"), _fake_resource("responses")]
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_fanout_manifest()))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ response = source.source_for_pipeline(config, inputs)
+
+ threaded_resources = mock_resources.call_args.args[0]["resources"]
+ assert [r["name"] for r in threaded_resources] == ["forms", "responses"]
+ assert cast(Any, response.items()).name == "responses"
+ assert response.primary_keys == ["token"]
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_top_level_schema_runs_only_that_resource(self, mock_resources):
+ # A parent selected on its own is a one-element chain — only that resource
+ # reaches the engine (no ancestors), and it's returned by name.
+ mock_resources.return_value = [_fake_resource("forms")]
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_fanout_manifest()))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="forms",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ response = source.source_for_pipeline(config, inputs)
+
+ assert [r["name"] for r in mock_resources.call_args.args[0]["resources"]] == ["forms"]
+ assert cast(Any, response.items()).name == "forms"
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_fanout_strips_incremental_from_parent_but_keeps_child(self, mock_resources):
+ # The run's high-watermark belongs to the child; applying it to the parent
+ # would silently drop parents (and their children). Parent must full-scan.
+ mock_resources.return_value = [_fake_resource("forms"), _fake_resource("responses")]
+ manifest = _fanout_manifest()
+ manifest["resources"][0]["endpoint"]["incremental"] = {"cursor_path": "updated_at", "start_param": "since"}
+ manifest["resources"][1]["endpoint"]["incremental"] = {"cursor_path": "submitted_at", "start_param": "since"}
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+ source.source_for_pipeline(config, inputs)
+
+ parent_cfg, child_cfg = mock_resources.call_args.args[0]["resources"]
+ assert "incremental" not in parent_cfg["endpoint"]
+ assert child_cfg["endpoint"]["incremental"] == {"cursor_path": "submitted_at", "start_param": "since"}
+ assert mock_resources.call_args.kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_fanout_strips_cursor_type_from_child(self, mock_resources):
+ # cursor_type is a schema-typing hint the engine's Incremental(**config)
+ # rejects — it must be removed before the child reaches the engine.
+ mock_resources.return_value = [_fake_resource("forms"), _fake_resource("responses")]
+ manifest = _fanout_manifest()
+ manifest["resources"][1]["endpoint"]["incremental"] = {
+ "cursor_path": "submitted_at",
+ "start_param": "since",
+ "cursor_type": "datetime",
+ }
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ source.source_for_pipeline(config, inputs)
+
+ _parent_cfg, child_cfg = mock_resources.call_args.args[0]["resources"]
+ assert child_cfg["endpoint"]["incremental"] == {"cursor_path": "submitted_at", "start_param": "since"}
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_fanout_strips_params_style_incremental_from_parent(self, mock_resources):
+ # The engine also builds an incremental tracker from a params-style
+ # {"type": "incremental"} spec — it must be stripped from ancestors too,
+ # or the child's watermark would be injected as the parent's start param.
+ mock_resources.return_value = [_fake_resource("forms"), _fake_resource("responses")]
+ manifest = _fanout_manifest()
+ manifest["resources"][0]["endpoint"]["params"] = {
+ "since": {"type": "incremental", "cursor_path": "updated_at"},
+ "status": "active",
+ }
+ manifest["resources"][1]["endpoint"]["incremental"] = {"cursor_path": "submitted_at", "start_param": "since"}
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2024-01-01T00:00:00Z",
+ )
+ source.source_for_pipeline(config, inputs)
+
+ parent_cfg, _child_cfg = mock_resources.call_args.args[0]["resources"]
+ # Static params survive; only the incremental spec is removed.
+ assert parent_cfg["endpoint"]["params"] == {"status": "active"}
+
+ @parameterized.expand(
+ [
+ # Child with no declared sort_mode -> forced "desc".
+ ("child_default", "responses", None, "desc"),
+ # Child that explicitly declares "asc" -> STILL forced "desc". This is
+ # the override that matters: per-batch asc commits on a child would
+ # advance the watermark past later parents' older rows and skip them.
+ ("child_overrides_declared_asc", "responses", "asc", "desc"),
+ # Top-level resource keeps its declaration (default "asc").
+ ("parent_keeps_declared", "forms", None, "asc"),
+ ]
+ )
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_fanout_child_forces_deferred_watermark_sort_mode(
+ self, _name, schema_name, declared_sort_mode, expected, mock_resources
+ ):
+ # Fan-out child rows arrive grouped per parent, never globally
+ # cursor-ascending, so the "asc" per-batch watermark commit would skip
+ # later parents' older rows after an interruption — children must always
+ # use the deferred-commit ("desc") behavior.
+ mock_resources.return_value = [_fake_resource("forms"), _fake_resource("responses")]
+ manifest = _fanout_manifest()
+ if declared_sort_mode is not None:
+ next(r for r in manifest["resources"] if r["name"] == schema_name)["sort_mode"] = declared_sort_mode
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name=schema_name,
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ response = source.source_for_pipeline(config, inputs)
+ assert response.sort_mode == expected
+
+ def test_engine_config_error_raises_non_retryable(self):
+ # include_from_parent without a resolve param passes create-time graph
+ # validation but is rejected by the engine at build time — a deterministic
+ # config error that must not burn the Temporal retry budget.
+ manifest = _minimal_manifest()
+ manifest["resources"][0]["include_from_parent"] = ["id"]
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="users",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ with self.assertRaises(NonRetryableException):
+ source.source_for_pipeline(config, inputs)
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.rest_api_resources")
+ def test_broken_sibling_does_not_sink_healthy_schema_sync(self, mock_resources):
+ # A stored manifest can carry a graph-broken resource from before the
+ # create-time rules existed — its healthy schemas must keep syncing.
+ mock_resources.return_value = [_fake_resource("forms")]
+ manifest = _fanout_manifest()
+ _break_unknown_parent(manifest)
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="forms",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ response = source.source_for_pipeline(config, inputs)
+
+ assert [r["name"] for r in mock_resources.call_args.args[0]["resources"]] == ["forms"]
+ assert cast(Any, response.items()).name == "forms"
+
+ def test_broken_sibling_fails_child_schema_fast(self):
+ # Accepted trade-off: a child schema can't be built without the graph,
+ # so when an UNRELATED resource breaks the graph, the fallback hands the
+ # engine just the child, whose orphaned resolve param the engine rejects
+ # at build time — a loud, non-retryable failure rather than wrong data.
+ # (Top-level siblings keep syncing; see
+ # test_broken_sibling_does_not_sink_healthy_schema_sync.)
+ manifest = _fanout_manifest()
+ manifest["resources"].append(
+ {
+ "name": "broken",
+ "primary_key": "id",
+ "endpoint": {
+ "path": "/broken/{x}",
+ "params": {"x": {"type": "resolve", "resource": "nonexistent", "field": "id"}},
+ },
+ }
+ )
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ with self.assertRaises(NonRetryableException):
+ source.source_for_pipeline(config, inputs)
+
+ @patch("posthog.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session")
+ def test_fanout_runs_through_real_engine(self, mock_make_session):
+ # End-to-end through the real REST engine (only the HTTP session is
+ # mocked): the parent is fetched once, the child is requested per parent
+ # row, and `include_from_parent` carries the parent id onto each child row.
+ def _response(body: dict) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+ session = mock_make_session.return_value
+ session.headers = {}
+ session.prepare_request.side_effect = lambda request: request
+ session.send.side_effect = [
+ _response({"items": [{"id": "f1"}, {"id": "f2"}]}), # GET /forms
+ _response({"items": [{"token": "r1"}, {"token": "r2"}]}), # GET /forms/f1/responses
+ _response({"items": [{"token": "r3"}]}), # GET /forms/f2/responses
+ ]
+
+ manifest = _fanout_manifest()
+ for resource in manifest["resources"]:
+ resource["endpoint"]["paginator"] = {"type": "single_page"}
+ manifest["resources"][1]["include_from_parent"] = ["id"]
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ inputs = MagicMock(
+ team_id=999,
+ schema_name="responses",
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ response = source.source_for_pipeline(config, inputs)
+
+ rows = [row for page in cast(Any, response.items()) for row in page]
+ assert [row["token"] for row in rows] == ["r1", "r2", "r3"]
+ # include_from_parent injects the parent id as `_<parent>_<field>`.
+ assert [row["_forms_id"] for row in rows] == ["f1", "f1", "f2"]
+ requested_paths = [call.args[0].url for call in session.prepare_request.call_args_list]
+ assert requested_paths == [
+ "https://api.example.com/forms",
+ "https://api.example.com/forms/f1/responses",
+ "https://api.example.com/forms/f2/responses",
+ ]
+
+
+class TestCustomSourceFanoutSchemasAndProbe(SimpleTestCase):
+ def test_child_resource_is_its_own_schema(self):
+ manifest = _fanout_manifest()
+ manifest["resources"][1]["endpoint"]["incremental"] = {"cursor_path": "submitted_at", "start_param": "since"}
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ schemas = {s.name: s for s in source.get_schemas(config, team_id=999)}
+
+ assert set(schemas) == {"forms", "responses"}
+ assert schemas["responses"].supports_incremental is True
+ assert [f["field"] for f in schemas["responses"].incremental_fields] == ["submitted_at"]
+
+ def test_broken_graph_does_not_break_schema_listing(self):
+ # Schema listing runs on stored manifests; a graph error (which the
+ # create-time validation now rejects, but older manifests may carry)
+ # must not make it raise.
+ manifest = _fanout_manifest()
+ _break_unknown_parent(manifest)
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(manifest))
+ schemas = {s.name for s in source.get_schemas(config, team_id=999)}
+ assert schemas == {"forms", "responses"}
+
+ @patch("posthog.temporal.data_imports.sources.custom.source.make_tracked_session")
+ def test_probe_skips_fanout_child(self, mock_session):
+ # The child can't be probed without a parent row, so only the parent is hit.
+ mock_session.return_value.request.return_value = MagicMock(status_code=200, text="{}")
+
+ source = CustomSource()
+ config = CustomSourceConfig(manifest_json=json.dumps(_fanout_manifest()), auth_token="abc")
+ ok, err = source.validate_credentials(config, team_id=999)
+ assert ok, err
+
+ probed_urls = [call.args[1] for call in mock_session.return_value.request.call_args_list]
+ assert probed_urls == ["https://api.example.com/forms"]
diff --git a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
index 4b5e7df1e7eb..f47cccaec550 100644
--- a/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/CustomSourceManifestBuilder.tsx
@@ -13,6 +13,8 @@ import {
type AuthType,
CURSOR_TYPES,
type CursorType,
+ eligibleParentStreams,
+ EMPTY_PARENT_FIELDS,
type HeaderEntry,
type ManifestState,
type Paginator,
@@ -133,6 +135,7 @@ export function CustomSourceManifestBuilder({
index={index}
stream={stream}
canRemove={manifestState.streams.length > 1}
+ parentOptions={eligibleParentStreams(manifestState.streams, index)}
onUpdate={(patch) => updateStream(index, patch)}
onUpdatePaginator={(paginator) => updatePaginator(index, paginator)}
onRemove={() => removeStream(index)}
@@ -292,6 +295,7 @@ function StreamCard({
index,
stream,
canRemove,
+ parentOptions,
onUpdate,
onUpdatePaginator,
onRemove,
@@ -299,6 +303,7 @@ function StreamCard({
index: number
stream: StreamForm
canRemove: boolean
+ parentOptions: string[]
onUpdate: (patch: Partial<StreamForm>) => void
onUpdatePaginator: (paginator: Paginator) => void
onRemove: () => void
@@ -359,12 +364,121 @@ function StreamCard({
<code>items</code>, <code>results.data</code>).
</p>
</LemonField.Pure>
+ {/* Only show the dependency section when there's an eligible parent to
+ pick, or an existing dependency to edit / warn about (a stale parent
+ from raw-authored JSON still needs its warning). A single-stream
+ manifest has neither, so the section would just be an inert box. */}
+ {(parentOptions.length > 0 || stream.parent_stream.trim().length > 0) && (
+ <ParentSection stream={stream} parentOptions={parentOptions} onUpdate={onUpdate} />
+ )}
<PaginatorSection paginator={stream.paginator} onUpdate={onUpdatePaginator} />
<IncrementalSection stream={stream} onUpdate={onUpdate} />
</div>
)
}
+function ParentSection({
+ stream,
+ parentOptions,
+ onUpdate,
+}: {
+ stream: StreamForm
+ parentOptions: string[]
+ onUpdate: (patch: Partial<StreamForm>) => void
+}): JSX.Element {
+ const hasParent = stream.parent_stream.trim().length > 0
+ const pathParam = stream.parent_path_param.trim()
+ const parentField = stream.parent_resolve_field.trim()
+ // A parent name can go stale when the manifest was authored elsewhere (raw
+ // JSON) — the select would render the raw value with no visible error, and
+ // saving fails with an engine message that doesn't point here.
+ const parentMissing = hasParent && !parentOptions.includes(stream.parent_stream)
+ // The REST engine can only inject a resolved value into the URL path, so the
+ // path must contain the placeholder — warn early instead of failing at sync.
+ const pathMissingPlaceholder = hasParent && pathParam.length > 0 && !stream.path.includes(`{${pathParam}}`)
+ return (
+ <div className="rounded border border-border p-3 space-y-2">
+ <LemonField.Pure label="Depends on parent stream">
+ <LemonSelect
+ value={hasParent ? stream.parent_stream : ''}
+ onChange={(value) =>
+ value ? onUpdate({ parent_stream: value }) : onUpdate({ ...EMPTY_PARENT_FIELDS })
+ }
+ options={[
+ { value: '', label: 'None (top-level stream)' },
+ ...parentOptions.map((name) => ({ value: name, label: name })),
+ ]}
+ />
+ </LemonField.Pure>
+ {hasParent && (
+ <>
+ <p className="m-0 text-xs text-secondary">
+ PostHog fetches the parent stream first, then calls this stream once per parent row — binding
+ the chosen parent field into the path placeholder (e.g.{' '}
+ <code>/forms/{'{form_id}'}/responses</code>).
+ </p>
+ <div className="grid grid-cols-2 gap-2">
+ <LemonField.Pure label="Parent field">
+ <LemonInput
+ placeholder="id"
+ value={stream.parent_resolve_field}
+ onChange={(value) => onUpdate({ parent_resolve_field: value })}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Path placeholder">
+ <LemonInput
+ placeholder="form_id"
+ value={stream.parent_path_param}
+ onChange={(value) => onUpdate({ parent_path_param: value })}
+ />
+ </LemonField.Pure>
+ </div>
+ <LemonField.Pure label="Include parent fields">
+ <LemonInput
+ placeholder="id, name"
+ value={stream.include_from_parent}
+ onChange={(value) => onUpdate({ include_from_parent: value })}
+ />
+ <p className="m-0 mt-1 text-xs text-secondary">
+ Optional comma-separated parent fields copied onto each row, as{' '}
+ <code>_{stream.parent_stream || 'parent'}_&lt;field&gt;</code>.
+ </p>
+ </LemonField.Pure>
+ </>
+ )}
+ {/* One persistently-mounted live region so screen readers announce
+ validation messages as they appear — a region that enters the DOM
+ already populated (e.g. mounted inside the hasParent gate) is
+ skipped by several readers. empty:hidden keeps it from adding
+ spacing when there's nothing to say. */}
+ <div aria-live="polite" className="empty:hidden space-y-2">
+ {parentMissing && (
+ <p className="m-0 text-xs text-danger">
+ Stream <code>{stream.parent_stream}</code> doesn't exist or can't be this stream's parent — pick
+ another parent or set to none.
+ </p>
+ )}
+ {hasParent && !parentField && (
+ <p className="m-0 text-xs text-danger">
+ Set the parent field — the dependency is incomplete without it and saving fails.
+ </p>
+ )}
+ {hasParent && !pathParam && (
+ <p className="m-0 text-xs text-danger">
+ Set the path placeholder — the dependency is incomplete without it and saving fails.
+ </p>
+ )}
+ {pathMissingPlaceholder && (
+ <p className="m-0 text-xs text-danger">
+ Add <code>{`{${pathParam}}`}</code> to the path above — the parent field is injected there, and
+ the sync fails without it.
+ </p>
+ )}
+ </div>
+ </div>
+ )
+}
+
function PaginatorSection({
paginator,
onUpdate,
@@ -542,6 +656,11 @@ function IncrementalSection({
value={stream.sort_mode}
onChange={(value) => onUpdate({ sort_mode: value as SortMode })}
options={SORT_MODE_OPTIONS}
+ disabledReason={
+ stream.parent_stream.trim()
+ ? 'Streams with a parent always defer the incremental cursor commit to the end of the run — rows arrive grouped by parent, not in cursor order.'
+ : undefined
+ }
/>
</LemonField.Pure>
</div>
diff --git a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
index e22879dd5bb8..b7061011a6f4 100644
--- a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifest.test.ts
@@ -1,4 +1,13 @@
-import { buildManifest, extractAuthSecrets, ManifestState, parseManifestIntoState } from '../customSourceManifest'
+import {
+ buildManifest,
+ eligibleParentStreams,
+ extractAuthSecrets,
+ ManifestState,
+ parseManifestIntoState,
+ removeStreamFromList,
+ StreamForm,
+ updateStreamInList,
+} from '../customSourceManifest'
const baseState = (): ManifestState => ({
base_url: 'https://api.example.com',
@@ -24,6 +33,11 @@ const baseState = (): ManifestState => ({
cursor_path: '',
cursor_type: 'datetime',
start_param: '',
+ parent_stream: '',
+ parent_resolve_field: '',
+ parent_path_param: '',
+ include_from_parent: '',
+ passthrough_params: {},
},
],
})
@@ -259,6 +273,11 @@ describe('parseManifestIntoState', () => {
cursor_path: 'updated_at',
cursor_type: 'datetime',
start_param: 'since',
+ parent_stream: '',
+ parent_resolve_field: '',
+ parent_path_param: '',
+ include_from_parent: '',
+ passthrough_params: {},
},
]
@@ -399,6 +418,11 @@ describe('parseManifestIntoState', () => {
cursor_path: 'updated_at',
cursor_type: 'timestamp',
start_param: 'since',
+ parent_stream: '',
+ parent_resolve_field: '',
+ parent_path_param: '',
+ include_from_parent: '',
+ passthrough_params: {},
},
]
@@ -408,6 +432,168 @@ describe('parseManifestIntoState', () => {
})
})
+// Spreads the base stream so new StreamForm fields only need a default in
+// baseState(), not in every fixture.
+const makeStream = (overrides: Partial<StreamForm>): StreamForm => ({
+ ...baseState().streams[0],
+ ...overrides,
+})
+
+describe('fan-out (parent/child)', () => {
+ const childState = (): ManifestState => {
+ const state = baseState()
+ state.streams = [
+ makeStream({
+ id: 'stream-forms',
+ name: 'forms',
+ path: '/forms',
+ data_selector: 'items',
+ }),
+ makeStream({
+ id: 'stream-responses',
+ name: 'responses',
+ path: '/forms/{form_id}/responses',
+ data_selector: 'items',
+ primary_key: 'token',
+ parent_stream: 'forms',
+ parent_resolve_field: 'id',
+ parent_path_param: 'form_id',
+ include_from_parent: 'id, title',
+ }),
+ ]
+ return state
+ }
+
+ it('emits a resolve param binding the parent field into the path placeholder', () => {
+ const manifest = buildManifest(childState()) as any
+ expect(manifest.resources[1].endpoint.params).toEqual({
+ form_id: { type: 'resolve', resource: 'forms', field: 'id' },
+ })
+ })
+
+ it('emits include_from_parent as a list when fields are provided', () => {
+ const manifest = buildManifest(childState()) as any
+ expect(manifest.resources[1].include_from_parent).toEqual(['id', 'title'])
+ })
+
+ it('still emits the resolve param when the dependency is half-filled, so the backend rejects it loudly', () => {
+ // Silently dropping a half-filled dependency would sync the stream as an
+ // unrelated top-level endpoint — wrong data with no error anywhere.
+ const state = childState()
+ state.streams[1].parent_path_param = '' // missing placeholder name
+ const manifest = buildManifest(state) as any
+ expect(manifest.resources[1].endpoint.params).toEqual({
+ '': { type: 'resolve', resource: 'forms', field: 'id' },
+ })
+ })
+
+ it('omits include_from_parent when no parent fields are listed', () => {
+ const state = childState()
+ state.streams[1].include_from_parent = ''
+ const manifest = buildManifest(state) as any
+ expect('params' in manifest.resources[1].endpoint).toBe(true)
+ expect('include_from_parent' in manifest.resources[1]).toBe(false)
+ })
+
+ it('keeps the top-level parent stream free of a resolve param', () => {
+ const manifest = buildManifest(childState()) as any
+ expect('params' in manifest.resources[0].endpoint).toBe(false)
+ })
+
+ it('offers only top-level streams as parents — one level of nesting, no cycles', () => {
+ const state = childState()
+ state.streams.push({
+ ...state.streams[0],
+ id: 'stream-users',
+ name: 'users',
+ path: '/users',
+ })
+ // The child stream may pick either top-level stream, but not itself.
+ expect(eligibleParentStreams(state.streams, 1)).toEqual(['forms', 'users'])
+ // A top-level stream can't pick the child (it has a parent) — so mutual
+ // cycles and grandchildren are unbuildable.
+ expect(eligibleParentStreams(state.streams, 0)).toEqual(['users'])
+ expect(eligibleParentStreams(state.streams, 2)).toEqual(['forms'])
+ })
+
+ it('renaming a parent stream follows through to its children', () => {
+ const streams = updateStreamInList(childState().streams, 0, { name: 'surveys' })
+ expect(streams[0].name).toBe('surveys')
+ expect(streams[1].parent_stream).toBe('surveys')
+ })
+
+ it('removing a parent stream clears its children back to top-level', () => {
+ const streams = removeStreamFromList(childState().streams, 0)
+ expect(streams).toHaveLength(1)
+ expect(streams[0].parent_stream).toBe('')
+ expect(streams[0].parent_resolve_field).toBe('')
+ expect(streams[0].parent_path_param).toBe('')
+ expect(streams[0].include_from_parent).toBe('')
+ })
+
+ it('keeps children attached when a duplicate-named stream is removed', () => {
+ // A sibling still carries the removed name, so the child's parent
+ // reference remains satisfiable and must not be cleared.
+ const state = childState()
+ state.streams.push(makeStream({ id: 'stream-forms-2', name: 'forms', path: '/forms-v2' }))
+ const streams = removeStreamFromList(state.streams, 0)
+ expect(streams.find((s) => s.name === 'responses')?.parent_stream).toBe('forms')
+ })
+
+ it('rename to a colliding name still cascades — the backend rejects the duplicate at save', () => {
+ const state = childState()
+ state.streams.push(makeStream({ id: 'stream-surveys', name: 'surveys', path: '/surveys' }))
+ const streams = updateStreamInList(state.streams, 0, { name: 'surveys' })
+ expect(streams[1].parent_stream).toBe('surveys')
+ })
+
+ it('keeps the first resolve param as the dependency when a manifest carries two', () => {
+ // The backend rejects multi-resolve manifests, but the parse path can
+ // still be handed one (raw JSON authoring) — the first becomes the
+ // editable dependency, the rest ride along in passthrough_params so a
+ // builder edit re-emits (and the backend re-rejects) them honestly.
+ const manifest = buildManifest(childState()) as any
+ manifest.resources[1].endpoint.params.other_id = { type: 'resolve', resource: 'forms', field: 'id' }
+ const child = parseManifestIntoState(JSON.stringify(manifest)).streams[1]
+ expect(child.parent_path_param).toBe('form_id')
+ expect(child.passthrough_params).toEqual({ other_id: { type: 'resolve', resource: 'forms', field: 'id' } })
+ })
+
+ it('preserves raw-authored static params through a builder round-trip', () => {
+ // The builder has no UI for static query params, but editing a stream
+ // must not silently drop ones authored in raw JSON.
+ const manifest = buildManifest(childState()) as any
+ manifest.resources[1].endpoint.params.status = 'active'
+ const rebuilt = buildManifest(parseManifestIntoState(JSON.stringify(manifest))) as any
+ expect(rebuilt.resources[1].endpoint.params).toEqual({
+ status: 'active',
+ form_id: { type: 'resolve', resource: 'forms', field: 'id' },
+ })
+ })
+
+ it('preserves a top-level stream’s static params even with no parent dependency', () => {
+ const manifest = buildManifest(childState()) as any
+ manifest.resources[0].endpoint.params = { limit: 100 }
+ const rebuilt = buildManifest(parseManifestIntoState(JSON.stringify(manifest))) as any
+ expect(rebuilt.resources[0].endpoint.params).toEqual({ limit: 100 })
+ })
+
+ it('hydrates the parent dependency back out on parse', () => {
+ const state = parseManifestIntoState(JSON.stringify(buildManifest(childState())))
+ const child = state.streams[1]
+ expect(child.parent_stream).toBe('forms')
+ expect(child.parent_resolve_field).toBe('id')
+ expect(child.parent_path_param).toBe('form_id')
+ expect(child.include_from_parent).toBe('id, title')
+ })
+
+ it('round-trips a fan-out manifest through build → parse → build without drift', () => {
+ const firstJson = JSON.stringify(buildManifest(childState()))
+ const secondJson = JSON.stringify(buildManifest(parseManifestIntoState(firstJson)))
+ expect(secondJson).toBe(firstJson)
+ })
+})
+
describe('extractAuthSecrets', () => {
it('returns only the bearer token for bearer auth', () => {
const state = baseState()
diff --git a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.ts b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.ts
index 065dfe9ca606..6fc542c60135 100644
--- a/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/__tests__/customSourceManifestBuilderLogic.test.ts
@@ -139,6 +139,20 @@ describe('customSourceManifestBuilderLogic', () => {
expect(logic.values.manifestState.streams).toHaveLength(1)
})
+ it('cascades a parent rename to dependent streams through the reducer', () => {
+ // The cascade behavior itself is unit-tested on the pure helpers;
+ // this pins that the reducer is actually wired to them.
+ logic.actions.updateStream(0, { name: 'forms' })
+ logic.actions.addStream()
+ logic.actions.updateStream(1, { name: 'responses', parent_stream: 'forms' })
+
+ logic.actions.updateStream(0, { name: 'surveys' })
+ expect(logic.values.manifestState.streams[1].parent_stream).toBe('surveys')
+
+ logic.actions.removeStream(0)
+ expect(logic.values.manifestState.streams[0].parent_stream).toBe('')
+ })
+
it('updates a stream paginator by index', () => {
logic.actions.updatePaginator(0, { type: 'cursor', cursor_path: 'meta.next', cursor_param: 'after' })
expect(logic.values.manifestState.streams[0].paginator).toEqual({
diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
index bb9961711dde..5f54cefe53cc 100644
--- a/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifest.ts
@@ -86,6 +86,20 @@ export interface StreamForm {
cursor_path: string
cursor_type: CursorType
start_param: string
+ // Fan-out (parent/child): when `parent_stream` is set, PostHog fetches that
+ // stream first and calls this one once per parent row, injecting
+ // `parent_resolve_field` into the `{parent_path_param}` placeholder in the
+ // path. `include_from_parent` lists parent fields copied onto each child row.
+ // Empty `parent_stream` means a top-level stream.
+ parent_stream: string
+ parent_resolve_field: string
+ parent_path_param: string
+ include_from_parent: string
+ // Raw-authored `endpoint.params` entries the builder has no UI for (static
+ // query params, the engine's incremental specs, extra resolve params).
+ // Carried verbatim through parse → build so editing a stream in the builder
+ // never silently drops a query param the manifest author wrote by hand.
+ passthrough_params: Record<string, unknown>
}
export interface ManifestState {
@@ -111,6 +125,17 @@ export function emptyHeader(): HeaderEntry {
return { id: nextHeaderId(), key: '', value: '' }
}
+// The cleared (top-level) state of every parent-dependency field. Single
+// source for the three places that reset a dependency — emptyStream, removing
+// a parent stream, and the builder's "None" selection — so a new parent field
+// only needs a default here.
+export const EMPTY_PARENT_FIELDS = {
+ parent_stream: '',
+ parent_resolve_field: '',
+ parent_path_param: '',
+ include_from_parent: '',
+} satisfies Partial<StreamForm>
+
export function emptyStream(): StreamForm {
return {
id: nextStreamId(),
@@ -125,7 +150,64 @@ export function emptyStream(): StreamForm {
cursor_path: '',
cursor_type: 'datetime',
start_param: '',
+ passthrough_params: {},
+ ...EMPTY_PARENT_FIELDS,
+ }
+}
+
+function splitCsv(value: string): string[] {
+ return value
+ .split(',')
+ .map((part) => part.trim())
+ .filter(Boolean)
+}
+
+/**
+ * Names of the streams that `streams[index]` may depend on: named, not itself,
+ * and top-level — nesting is capped at one level (a stream that already has a
+ * parent can't be a parent itself), mirroring the backend validation. This also
+ * makes cycles structurally impossible to build in the UI.
+ */
+export function eligibleParentStreams(streams: StreamForm[], index: number): string[] {
+ return streams
+ .filter(
+ (other, otherIndex) =>
+ otherIndex !== index && other.name.trim().length > 0 && other.parent_stream.trim().length === 0
+ )
+ .map((other) => other.name)
+}
+
+/**
+ * Applies a patch to one stream. Renaming a stream follows through to children
+ * that reference it via `parent_stream` — otherwise their dependency would
+ * dangle silently and only fail at save time.
+ */
+export function updateStreamInList(streams: StreamForm[], index: number, patch: Partial<StreamForm>): StreamForm[] {
+ const oldName = streams[index]?.name
+ const updated = streams.map((stream, i) => (i === index ? { ...stream, ...patch } : stream))
+ const newName = patch.name
+ if (newName === undefined || !oldName || newName === oldName) {
+ return updated
}
+ return updated.map((stream, i) =>
+ i !== index && stream.parent_stream === oldName ? { ...stream, parent_stream: newName } : stream
+ )
+}
+
+/**
+ * Removes a stream. Children that depended on it have the parent dependency
+ * cleared (back to top-level) so they don't reference a stream that no longer
+ * exists.
+ */
+export function removeStreamFromList(streams: StreamForm[], index: number): StreamForm[] {
+ const removedName = streams[index]?.name
+ const remaining = streams.filter((_, i) => i !== index)
+ if (!removedName || remaining.some((stream) => stream.name === removedName)) {
+ return remaining
+ }
+ return remaining.map((stream) =>
+ stream.parent_stream === removedName ? { ...stream, ...EMPTY_PARENT_FIELDS } : stream
+ )
}
export function defaultState(): ManifestState {
@@ -201,10 +283,26 @@ export function buildManifest(state: ManifestState): Record<string, unknown> {
}
endpoint.incremental = incremental
}
- const primaryKeys = stream.primary_key
- .split(',')
- .map((part) => part.trim())
- .filter(Boolean)
+ // Fan-out: bind the parent's field into the path placeholder via a
+ // `resolve` param, merged onto the raw-authored params the builder has
+ // no UI for. The dependency is emitted whenever a parent is selected,
+ // even half-filled: an incomplete dependency must fail backend validation
+ // loudly (the builder UI flags the missing pieces inline) rather than be
+ // silently dropped — that would sync this stream as an unrelated
+ // top-level endpoint.
+ const parentStream = stream.parent_stream.trim()
+ const params: Record<string, unknown> = { ...stream.passthrough_params }
+ if (parentStream) {
+ params[stream.parent_path_param.trim()] = {
+ type: 'resolve',
+ resource: parentStream,
+ field: stream.parent_resolve_field.trim(),
+ }
+ }
+ if (Object.keys(params).length > 0) {
+ endpoint.params = params
+ }
+ const primaryKeys = splitCsv(stream.primary_key)
const resource: Record<string, unknown> = {
name: stream.name,
// Fall back to 'id' when the field is cleared — an empty primary_key
@@ -212,6 +310,10 @@ export function buildManifest(state: ManifestState): Record<string, unknown> {
primary_key: primaryKeys.length === 0 ? 'id' : primaryKeys.length === 1 ? primaryKeys[0] : primaryKeys,
endpoint,
}
+ const includeFromParent = splitCsv(stream.include_from_parent)
+ if (parentStream && includeFromParent.length > 0) {
+ resource.include_from_parent = includeFromParent
+ }
// sort_mode only affects incremental resume safety. Emit only when the
// user explicitly opts into descending order — backend default is asc.
if (stream.sort_mode === 'desc') {
@@ -344,6 +446,29 @@ function parseStream(resource: unknown): StreamForm {
const cursorTypeRaw = asString(incremental.cursor_type, 'datetime')
const cursorType: CursorType = isMember(CURSOR_TYPES, cursorTypeRaw) ? cursorTypeRaw : 'datetime'
const primaryKey = r.primary_key
+ // Recover a fan-out dependency from the first `resolve` param: its key is the
+ // path placeholder, and it names the parent stream + the parent field bound in.
+ // Every other params entry (static query params, incremental specs, extra
+ // resolve params on a malformed manifest) is preserved verbatim so a builder
+ // edit can't silently drop it.
+ const params = asObject(endpoint.params)
+ let parentStream = ''
+ let parentResolveField = ''
+ let parentPathParam = ''
+ const passthroughParams: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(params)) {
+ const spec = asObject(value)
+ if (spec.type === 'resolve' && !parentPathParam) {
+ parentPathParam = key
+ parentStream = asString(spec.resource)
+ parentResolveField = asString(spec.field)
+ } else {
+ passthroughParams[key] = value
+ }
+ }
+ const includeFromParent = Array.isArray(r.include_from_parent)
+ ? (r.include_from_parent as unknown[]).map((field) => String(field)).join(', ')
+ : ''
return {
id: nextStreamId(),
name: asString(r.name),
@@ -357,5 +482,10 @@ function parseStream(resource: unknown): StreamForm {
cursor_path: asString(incremental.cursor_path),
cursor_type: cursorType,
start_param: asString(incremental.start_param),
+ parent_stream: parentStream,
+ parent_resolve_field: parentResolveField,
+ parent_path_param: parentPathParam,
+ include_from_parent: includeFromParent,
+ passthrough_params: passthroughParams,
}
}
diff --git a/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts b/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts
index 3ac90dc02f89..9a4a1207ba20 100644
--- a/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts
+++ b/products/data_warehouse/frontend/shared/components/forms/customSourceManifestBuilderLogic.ts
@@ -21,7 +21,9 @@ import {
type ManifestState,
type Paginator,
parseManifestIntoState,
+ removeStreamFromList,
type StreamForm,
+ updateStreamInList,
} from './customSourceManifest'
import type { customSourceManifestBuilderLogicType } from './customSourceManifestBuilderLogicType'
@@ -80,9 +82,11 @@ export const customSourceManifestBuilderLogic = kea<customSourceManifestBuilderL
{
setManifestState: (_, { state }) => state,
updateState: (state, { patch }) => ({ ...state, ...patch }),
+ // Rename/remove cascade to dependent child streams lives in the
+ // pure helpers so it stays unit-testable.
updateStream: (state, { index, patch }) => ({
...state,
- streams: state.streams.map((stream, i) => (i === index ? { ...stream, ...patch } : stream)),
+ streams: updateStreamInList(state.streams, index, patch),
}),
updatePaginator: (state, { index, paginator }) => ({
...state,
@@ -91,7 +95,7 @@ export const customSourceManifestBuilderLogic = kea<customSourceManifestBuilderL
addStream: (state) => ({ ...state, streams: [...state.streams, emptyStream()] }),
removeStream: (state, { index }) => ({
...state,
- streams: state.streams.filter((_, i) => i !== index),
+ streams: removeStreamFromList(state.streams, index),
}),
addHeader: (state) => ({ ...state, headers: [...state.headers, emptyHeader()] }),
removeHeader: (state, { index }) => ({