:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): scan synced tickets for zendesk ticket comments (#87807)
Daniel RC03cde8e3ecb4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/datetime_utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/datetime_utils.pyindex 061f4187b056..9ea79308b9eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/datetime_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/datetime_utils.py@@ -1,6 +1,8 @@from datetime import UTC, date, datetimefrom typing import Any+from dateutil import parser as dateutil_parser+def coerce_datetime_to_utc(value: Any) -> datetime | None:"""Normalize a date/datetime-like value to a timezone-aware UTC datetime.@@ -17,3 +19,18 @@ def coerce_datetime_to_utc(value: Any) -> datetime | None:if value.tzinfo is None:return value.replace(tzinfo=UTC)return value.astimezone(UTC)+++def parse_datetime_value(value: Any) -> datetime | None:+ """Same as `coerce_datetime_to_utc`, but also parses a datetime written as a string.++ An incremental watermark reaches a source as whatever the pipeline persisted, which is a+ string for some sources and a datetime for others, so a caller that has to compare one+ against a real datetime cannot assume either.+ """+ if isinstance(value, str):+ try:+ value = dateutil_parser.parse(value)+ except (ValueError, TypeError, OverflowError):+ return None+ return coerce_datetime_to_utc(value)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.pyindex afc8991357c7..09eb797bba56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/fanout.py@@ -1,9 +1,11 @@from collections.abc import Callable, Iterable, Mappingfrom dataclasses import dataclass, field+from datetime import datetimefrom typing import Any, Literal, Protocolimport structlog+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resources,@@ -102,6 +104,7 @@ def build_dependent_resource(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]@@ -251,4 +254,34 @@ def build_dependent_resource(initial_paginator_state=initial_paginator_state,)child_dlt_resource = next(r for r in resources if getattr(r, "name", None) == child_endpoint)- return child_dlt_resource.add_map(rename_parent_fields(fanout.parent_name, fanout.parent_field_renames))+ child = child_dlt_resource.add_map(rename_parent_fields(fanout.parent_name, fanout.parent_field_renames))++ # Capping belongs here rather than in the caller because only this function knows whether the+ # run ended up on the warehouse parent: `warehouse_parent` is false when the table turned out+ # 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))+ return child+++def _not_newer_than(field: str, snapshot_at: datetime) -> Callable[[dict[str, Any]], bool]:+ """Keep rows the parent snapshot could already account for.++ A row without the field carries no recency signal and is kept, matching how the parent row+ filter treats NULLs.+ """++ def _keep(row: dict[str, Any]) -> bool:+ value = parse_datetime_value(row.get(field))+ return value is None or value <= snapshot_at++ return _keepdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.pyindex 2604622b879f..83ccf18518ab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/tests/test_warehouse_parent.py@@ -167,6 +167,56 @@ def test_resolve_pins_to_last_completed_snapshot_while_parent_is_syncing(tmp_patassert pinned.version == v0+class TestParentSnapshotCoversThrough(APIBaseTest):+ def _schema_with_completed_job(self) -> tuple[Any, Any, Any, Any]:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Sentry",+ job_inputs={"auth_token": "token", "organization_slug": "acme"},+ )+ schema = ExternalDataSchema.objects.create(name="issues", team=self.team, source=source)+ now = datetime.now(UTC)+ started_at, finished_at = now - timedelta(hours=3), now - timedelta(hours=1)+ job = ExternalDataJob.objects.create(+ team=self.team,+ pipeline=source,+ schema=schema,+ status="Completed",+ workflow_id="wf-0",+ finished_at=finished_at,+ )+ ExternalDataJob.objects.filter(id=job.id).update(created_at=started_at)+ return source, schema, started_at, finished_at++ def test_coverage_is_when_the_sync_started_not_when_it_finished(self) -> None:+ source, _schema, started_at, finished_at = self._schema_with_completed_job()++ covers_through = warehouse_parent.parent_snapshot_covers_through(self.team.pk, str(source.pk), "issues")++ assert covers_through is not None+ assert abs(covers_through - started_at) < timedelta(seconds=1)+ assert covers_through < finished_at++ def test_none_without_a_completed_sync(self) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Sentry",+ job_inputs={"auth_token": "token", "organization_slug": "acme"},+ )+ ExternalDataSchema.objects.create(name="issues", team=self.team, source=source)++ assert warehouse_parent.parent_snapshot_covers_through(self.team.pk, str(source.pk), "issues") is None++ def test_none_when_the_parent_schema_does_not_exist(self) -> None:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Sentry",+ job_inputs={"auth_token": "token", "organization_slug": "acme"},+ )++ assert warehouse_parent.parent_snapshot_covers_through(self.team.pk, str(source.pk), "issues") is None++class TestSnapshotPinAsOf(APIBaseTest):def _schema_with_jobs(self, statuses: list[str], finished_at_hours_ago: float = 1.0) -> tuple[Any, dict[int, Any]]:"""Jobs in the given order, oldest first, all finishing `finished_at_hours_ago` back."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.pyindex fd545fc8baee..38878fcb8c5e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/warehouse_parent.py@@ -236,6 +236,44 @@ def try_resolve_parent_table(return None+def parent_snapshot_covers_through(team_id: int, source_id: str, parent_name: str) -> dt.datetime | None:+ """How far the parent's data is guaranteed complete, or None if it has never completed a sync.++ A child that derives its next scan floor from its own rows has to cap what it emits at this+ value, or the floor advances past parent changes the snapshot could not show it yet and they+ are never scanned again.++ This is when the parent's last completed sync *started*, not when it finished. A sync reads+ each row at some point between those two, so a row read early carries the state it had then,+ and a parent change landing later in the same sync may be missing from the snapshot entirely.+ Only changes from before the sync started are guaranteed to be in it. `finished_at` is the+ right stamp for picking a Delta version (see `_snapshot_pin_as_of`) and the wrong one for+ coverage; they are different quantities.++ Call this BEFORE resolving the table, never after. A sync completing between the two reads+ then leaves the cap on the older job while the pinned snapshot holds the newer one, which errs+ toward emitting too little. Reversing the order errs toward emitting rows the snapshot never+ covered, which is the bug this exists to prevent.+ """+ try:+ parent_schema = get_schema_if_exists(parent_name, team_id, uuid.UUID(source_id))+ except (ValueError, AttributeError):+ return None+ if parent_schema is None:+ return None+ return (+ ExternalDataJob.objects.filter(+ team_id=team_id,+ schema_id=parent_schema.id,+ status=ExternalDataJob.Status.COMPLETED,+ finished_at__isnull=False,+ )+ .order_by("-finished_at")+ .values_list("created_at", flat=True)+ .first()+ )++def _snapshot_pin_as_of(team_id: int, parent_schema_id: uuid.UUID) -> dt.datetime | None:"""The timestamp to time-travel the parent table to, or None to read its latest version.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.pyindex d10d9118be99..b174b6d3abfc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/settings.py@@ -1,7 +1,7 @@"""Zendesk source settings and constants"""from dataclasses import dataclass, field-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (@@ -163,10 +163,11 @@ class ZendeskEndpointConfig:params: dict[str, Any] = field(default_factory=dict)-# Parent that drives the `ticket_comments` fan-out. It is deliberately kept out of-# `ZENDESK_ENDPOINTS` so it never becomes a schema of its own — tickets already sync through the-# cursor incremental export.-TICKET_COMMENTS_PARENT_NAME = "tickets_for_comments"+# Parent that drives the `ticket_comments` fan-out. The name is the `tickets` schema's, because+# that is how `_warehouse_parent_reuse_available` finds the parent to read from. The path is the+# API-fallback walk, and stays on the plain list endpoint so a fallback run produces the row set it+# has always produced.+TICKET_COMMENTS_PARENT_NAME = "tickets"TICKET_COMMENTS_PARENT = ZendeskEndpointConfig(name=TICKET_COMMENTS_PARENT_NAME,path="/api/v2/tickets",@@ -174,6 +175,22 @@ TICKET_COMMENTS_PARENT = ZendeskEndpointConfig(primary_key=["id"],)+# A ticket's `updated_at` moves whenever a comment is added, redacted, or made private. Comments+# carry no modification timestamp of their own, so this is the only field a scan can use to find+# the tickets whose comments may have changed.+TICKET_COMMENTS_PARENT_FILTER_FIELD = "updated_at"++# Absorbs the offset between a comment's `created_at`, which is the child's watermark, and the+# ticket `updated_at` the scan compares it against, so a comment written moments before the last+# run finished is not stranded below the next run's floor.+TICKET_COMMENTS_PARENT_LOOKBACK = timedelta(hours=1)++# Zendesk archives a closed ticket around 120 days after it closes, and an archived ticket drops+# out of `/api/v2/tickets` while staying in the incremental export the `tickets` schema syncs.+# Scanning further back than that covers tickets the API path would never visit, which multiplies+# the fan-out instead of shrinking it, so a run that far behind takes the API path.+TICKET_COMMENTS_PARENT_MAX_CATCHUP = timedelta(days=120)+# Parent endpoints referenced by `ZendeskEndpointConfig.fanout`, looked up by `fanout.parent_name`.FANOUT_PARENTS: dict[str, ZendeskEndpointConfig] = {TICKET_COMMENTS_PARENT_NAME: TICKET_COMMENTS_PARENT}@@ -222,6 +239,10 @@ ZENDESK_ENDPOINTS: dict[str, ZendeskEndpointConfig] = {resolve_field="id",include_from_parent=["id"],parent_field_renames={"id": "ticket_id"},+ # The row filter is per-run rather than static, so it is applied in `zendesk.py` where+ # the watermark is known. Without one this scan would fan out over every ticket ever+ # exported, so that code also drops the run to the API path when it cannot build one.+ parent_source="warehouse",),),"group_memberships": ZendeskEndpointConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.pyindex 134090806e22..5450299b02ea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/source.py@@ -14,6 +14,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.canCanonicalDescriptions,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ required_parents_from_endpoint_configs,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesk import (@@ -61,6 +64,9 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):"401 Client Error": "Zendesk authentication failed. Please check your API token and subdomain.",}+ def get_required_parent_schemas(self, schema_name: str) -> list[str]:+ return required_parents_from_endpoint_configs(ZENDESK_ENDPOINTS, schema_name)+def get_schemas(self,config: ZendeskSourceConfig,@@ -168,6 +174,8 @@ class ZendeskSource(SimpleSource[ZendeskSourceConfig]):if inputs.should_use_incremental_fieldelse None,incremental_field_name=inputs.incremental_field,+ source_id=inputs.source_id,+ use_warehouse_parent=inputs.fanout_warehouse_reuse,)# The original nine endpoints aren't in the declarative catalog; they keep the `id`# primary key and ascending sort they have always used.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.pyindex 92ba0d92c4c7..84305e2c82a1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/tests/test_zendesk.py@@ -12,6 +12,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resJSONLinkPaginator,SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ParentRowFilter+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ ParentTableRef,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputsfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.zendesk import (ZendeskSourceConfig,@@ -21,6 +25,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.seFANOUT_PARENTS,INCREMENTAL_ENDPOINTS,INCREMENTAL_FIELDS,+ TICKET_COMMENTS_PARENT_LOOKBACK,+ TICKET_COMMENTS_PARENT_MAX_CATCHUP,TICKET_COMMENTS_PARENT_NAME,ZENDESK_ENDPOINTS,)@@ -537,15 +543,23 @@ class TestToZendeskIso8601:assert to_zendesk_iso8601(value) == expected+_UNSET = object()++class _FakeResource:def __init__(self, name: str) -> None:self.name = nameself.maps: list[Any] = []+ self.filters: list[Any] = []def add_map(self, fn: Any) -> "_FakeResource":self.maps.append(fn)return self+ def add_filter(self, fn: Any) -> "_FakeResource":+ self.filters.append(fn)+ return self+class TestZendeskTicketCommentsFanout:def _build(self, should_use_incremental_field: bool = False) -> tuple[_FakeResource, list[Any]]:@@ -607,6 +621,161 @@ class TestZendeskTicketCommentsFanout:assert row == {"ticket_id": 42, "id": 7, "body": "hi"}+class TestZendeskTicketCommentsWarehouseParent:+ def _build(+ self,+ watermark: Any,+ use_warehouse_parent: bool = True,+ snapshot_at: Any = _UNSET,+ ) -> tuple[Any, _FakeResource]:+ child = _FakeResource("ticket_comments")+ if snapshot_at is _UNSET:+ snapshot_at = datetime.now(UTC)+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources",+ return_value=[_FakeResource("tickets"), child],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.zendesk.parent_snapshot_covers_through",+ return_value=snapshot_at,+ ),+ 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/tickets", version=3),+ ) as mock_resolve,+ ):+ zendesk_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint="ticket_comments",+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=watermark,+ should_use_incremental_field=True,+ source_id="source-1",+ use_warehouse_parent=use_warehouse_parent,+ )+ return mock_resolve, child++ def _resolve(self, watermark: Any, use_warehouse_parent: bool = True, snapshot_at: Any = _UNSET) -> Any:+ return self._build(watermark, use_warehouse_parent, snapshot_at)[0]++ def test_scans_tickets_bounded_by_the_child_watermark(self) -> None:+ watermark = datetime.now(UTC) - timedelta(hours=6)++ resolve = self._resolve(watermark)++ assert resolve.call_args.args[2] == "tickets"+ assert resolve.call_args.kwargs["required_columns"] == ["id"]+ assert resolve.call_args.kwargs["row_filter"] == ParentRowFilter(+ field="updated_at",+ not_before=watermark - TICKET_COMMENTS_PARENT_LOOKBACK,+ )++ def test_clamps_a_watermark_that_sits_ahead_of_now(self) -> None:+ resolve = self._resolve(datetime.now(UTC) + timedelta(days=1))++ assert resolve.call_args.kwargs["row_filter"].not_before <= datetime.now(UTC) - TICKET_COMMENTS_PARENT_LOOKBACK++ @pytest.mark.parametrize(+ "watermark_factory",+ [+ pytest.param(lambda: None, id="no_watermark"),+ pytest.param(lambda: "still syncing", id="unparseable_watermark"),+ pytest.param(+ lambda: datetime.now(UTC) - TICKET_COMMENTS_PARENT_MAX_CATCHUP - timedelta(days=1),+ id="older_than_the_archive_window",+ ),+ ],+ )+ def test_takes_the_api_path_when_no_safe_floor_exists(self, watermark_factory: Any) -> None:+ assert self._resolve(watermark_factory()).call_count == 0++ def test_drops_comments_newer_than_the_parent_snapshot(self) -> None:+ snapshot_at = datetime.now(UTC) - timedelta(hours=6)+ _, child = self._build(datetime.now(UTC) - timedelta(hours=7), snapshot_at=snapshot_at)++ keep = child.filters[0]++ assert keep({"created_at": (snapshot_at - timedelta(minutes=1)).isoformat()}) is True+ assert keep({"created_at": (snapshot_at + timedelta(minutes=1)).isoformat()}) is False+ assert keep({"created_at": None}) is True++ def test_emits_every_comment_on_the_api_path(self) -> None:+ _, child = self._build(datetime.now(UTC) - timedelta(hours=6), use_warehouse_parent=False)++ assert child.filters == []++ def test_takes_the_api_path_without_a_completed_parent_sync(self) -> None:+ assert self._resolve(datetime.now(UTC) - timedelta(hours=6), snapshot_at=None).call_count == 0++ def test_no_cap_when_the_parent_table_cannot_be_resolved(self) -> None:+ child = _FakeResource("ticket_comments")+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources",+ return_value=[_FakeResource("tickets"), child],+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.zendesk.parent_snapshot_covers_through",+ return_value=datetime.now(UTC) - timedelta(hours=6),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent.try_resolve_parent_table",+ return_value=None,+ ),+ ):+ zendesk_source(+ subdomain="nibbles",+ api_key="token",+ email_address="[email protected]",+ endpoint="ticket_comments",+ team_id=1,+ job_id="job-1",+ db_incremental_field_last_value=datetime.now(UTC) - timedelta(hours=7),+ should_use_incremental_field=True,+ source_id="source-1",+ use_warehouse_parent=True,+ )++ assert child.filters == []++ def test_takes_the_api_path_when_reuse_is_not_enabled_for_the_run(self) -> None:+ watermark = datetime.now(UTC) - timedelta(hours=6)++ assert self._resolve(watermark, use_warehouse_parent=False).call_count == 0+++class TestZendeskRequiredParentSchemas:+ @pytest.mark.parametrize(+ "schema_name,expected",+ [+ pytest.param("ticket_comments", ["tickets"], id="the_fanout_child"),+ pytest.param("tickets", [], id="the_parent_itself"),+ pytest.param("ticket_audits", [], id="a_plain_list_endpoint"),+ pytest.param("users", [], id="an_original_export_endpoint"),+ ],+ )+ def test_required_parent_schemas(self, schema_name: str, expected: list[str]) -> None:+ assert ZendeskSource().get_required_parent_schemas(schema_name) == expected++ def test_source_for_pipeline_forwards_the_source_and_the_reuse_decision(self) -> None:+ config = ZendeskSourceConfig(subdomain="nibbles", api_key="token", email_address="[email protected]")+ inputs = _source_inputs("ticket_comments")+ inputs.fanout_warehouse_reuse = True++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.source.zendesk_source",+ return_value=SimpleNamespace(name="ticket_comments", column_hints=None),+ ) as mock_source:+ ZendeskSource().source_for_pipeline(config, inputs)++ assert mock_source.call_args.kwargs["source_id"] == "source-1"+ assert mock_source.call_args.kwargs["use_warehouse_parent"] is True++class TestZendeskSchemas:def _schemas(self) -> dict[str, Any]:config = ZendeskSourceConfig(subdomain="nibbles", api_key="token", email_address="[email protected]")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.pyindex d3741797e65e..1de88eb57b2b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zendesk/zendesk.py@@ -1,5 +1,6 @@import reimport base64+import dataclassesfrom collections.abc import Callablefrom datetime import UTC, datetimefrom typing import Any, Optional, cast@@ -7,12 +8,14 @@ from typing import Any, Optional, castfrom requests import Request, Responsefrom products.warehouse_sources.backend.models.external_table_definitions import get_dlt_mapping_for_external_table+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,build_dependent_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (@@ -26,9 +29,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resEndpoint,EndpointResource,IncrementalConfig,+ ParentRowFilter,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.warehouse_parent import (+ parent_snapshot_covers_through,)from products.warehouse_sources.backend.temporal.data_imports.sources.zendesk.settings import (FANOUT_PARENTS,+ TICKET_COMMENTS_PARENT_FILTER_FIELD,+ TICKET_COMMENTS_PARENT_LOOKBACK,+ TICKET_COMMENTS_PARENT_MAX_CATCHUP,ZENDESK_ENDPOINTS,ZendeskEndpointConfig,)@@ -66,6 +76,36 @@ def zendesk_incremental_window(start_param: str, cursor_path: str) -> Incrementa}+def _bounded_fanout(fanout: DependentEndpointConfig, db_incremental_field_last_value: Any) -> DependentEndpointConfig:+ """Bound a warehouse parent scan to the tickets whose comments may have changed.++ The floor is the child's own watermark, so the scan covers exactly what the previous run did+ not: a comment added, redacted, or made private since then moved its ticket's `updated_at`.++ Two cases have no floor that is both safe and complete, and both take the parent-API path the+ feature already falls back to. Without a watermark there is nothing to scan from. With a+ watermark older than Zendesk's archive delay, a scan wide enough to cover the gap reaches+ tickets `/api/v2/tickets` no longer lists, so it would fan out wider than the API path rather+ than narrower.+ """+ if fanout.parent_source != "warehouse":+ return fanout++ now = datetime.now(UTC)+ watermark = parse_datetime_value(db_incremental_field_last_value)+ if watermark is None or watermark < now - TICKET_COMMENTS_PARENT_MAX_CATCHUP:+ return dataclasses.replace(fanout, parent_source="api")++ return dataclasses.replace(+ fanout,+ parent_row_filter=ParentRowFilter(+ field=TICKET_COMMENTS_PARENT_FILTER_FIELD,+ # A watermark ahead of now would floor the scan in the future and read nothing.+ not_before=min(watermark, now) - TICKET_COMMENTS_PARENT_LOOKBACK,+ ),+ )++def _fanout_incremental_config(config: ZendeskEndpointConfig) -> Callable[[str], IncrementalConfig | None]:"""Build the child's request window, or report that the endpoint has none.@@ -504,16 +544,33 @@ def zendesk_fanout_source(db_incremental_field_last_value: Optional[Any],should_use_incremental_field: bool = False,incremental_field_name: str | None = None,+ source_id: str | None = None,+ use_warehouse_parent: bool = False,) -> Resource:"""Fan out over a parent list endpoint, then page the child endpoint per parent row."""assert config.fanout is not None- parent = FANOUT_PARENTS[config.fanout.parent_name]+ fanout = _bounded_fanout(config.fanout, db_incremental_field_last_value)++ # How far the tickets snapshot is guaranteed complete. The comments fanned out below are+ # fetched live, so emitting one past this point would carry this schema's watermark over+ # ticket changes the snapshot could not show it, and the next run's floor would skip them for+ # good. Capping defers those comments by one run instead, so nothing is lost. Read before+ # `build_dependent_resource` pins the table, never after — see the helper's docstring. Without+ # a completed parent sync there is no cap, so the run takes the API path, whose listing is+ # live and needs none.+ snapshot_at: datetime | None = None+ if fanout.parent_source == "warehouse" and use_warehouse_parent:+ snapshot_at = parent_snapshot_covers_through(team_id, source_id or "", fanout.parent_name)+ if snapshot_at is None:+ fanout = dataclasses.replace(fanout, parent_source="api")++ parent = FANOUT_PARENTS[fanout.parent_name]return cast(Resource,build_dependent_resource(endpoint_configs={config.name: config, parent.name: parent},child_endpoint=config.name,- fanout=config.fanout,+ fanout=fanout,client_config=client_config,path_format_values={},team_id=team_id,@@ -531,6 +588,9 @@ def zendesk_fanout_source("paginator": paginator_for(config),"data_selector": config.data_selector,},+ source_id=source_id,+ use_warehouse_parent=use_warehouse_parent,+ parent_snapshot_at=snapshot_at,),)@@ -545,6 +605,8 @@ def zendesk_source(db_incremental_field_last_value: Optional[Any],should_use_incremental_field: bool = False,incremental_field_name: str | None = None,+ source_id: str | None = None,+ use_warehouse_parent: bool = False,):client_config = zendesk_client_config(subdomain, api_key, email_address)@@ -558,6 +620,8 @@ def zendesk_source(db_incremental_field_last_value,should_use_incremental_field,incremental_field_name,+ source_id=source_id,+ use_warehouse_parent=use_warehouse_parent,)config: RESTAPIConfig = {