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(firehydrant): add schedule, milestone, task and escalation tables (#107404)

Tom Owers3dba0fb74180
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 53b978b28dce..2e833b223335 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3163,13 +3163,13 @@ Today (24): `alerts`, `change_events`, `changes`, `checklist_templates`, `custom
Diffed against: <https://raw.githubusercontent.com/firehydrant/firehydrant-typescript-sdk/main/openapi.yaml>
-- [ ] `/v1/incidents/{incident_id}/milestones` — the incident state-transition history that every MTTx and lifecycle calculation is built from (high)
+- [x] `/v1/incidents/{incident_id}/milestones` — the incident state-transition history that every MTTx and lifecycle calculation is built from (high)
- [ ] `/v1/incidents/{incident_id}/events` — the full incident timeline; incidents alone give no in-incident activity (high)
- [ ] `/v1/incidents/{incident_id}/role_assignments` — membership table joining incidents to users and the already-synced incident_roles (high)
- [ ] `/v1/metrics/mttx` — FireHydrant's headline reliability metric (MTTA/MTTR/MTTM) with no equivalent in the current tables (high)
-- [ ] `/v1/schedules` — org-wide on-call schedules; signals_on_call is synced but the schedule definitions it references are not (high)
-- [ ] `/v1/teams/{team_id}/escalation_policies` — lookup resolving how alerts route per team, joining teams already synced (high)
-- [ ] `/v1/incidents/{incident_id}/tasks` — task_lists is synced but not the actual tasks executed on incidents (high)
+- [x] `/v1/schedules` — org-wide on-call schedules; signals_on_call is synced but the schedule definitions it references are not (high)
+- [x] `/v1/teams/{team_id}/escalation_policies` — lookup resolving how alerts route per team, joining teams already synced (high)
+- [x] `/v1/incidents/{incident_id}/tasks` — task_lists is synced but not the actual tasks executed on incidents (high)
- [ ] `/v1/change_types` — lookup table resolving the change type carried on the synced changes and change_events rows (medium)
- [ ] `/v1/lifecycles/phases and /v1/lifecycles/measurement_definitions` — lookup tables that give milestones and lifecycle measurements their names and ordering (medium)
- [ ] `/v1/ticketing/tickets (plus /v1/ticketing/priorities, /v1/ticketing/ticket_tags)` — follow-up work tracked off incidents, entirely absent today (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.md
index 5dfaa8f4d43c..7a9ccd7436e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/api_inventory.md
@@ -37,6 +37,25 @@ Source: <https://docs.firehydrant.com/reference/firehydrant-api> and the officia
| scheduled_maintenances | `/v1/scheduled_maintenances` | id | created_at |
| task_lists | `/v1/task_lists` | id | created_at |
| checklist_templates | `/v1/checklist_templates` | id | created_at |
+| schedules | `/v1/schedules` | id | — (no created_at) |
+
+## Fan-out endpoints implemented
+
+Walked once per parent row, through the shared dependent-resource helper. The parent id is injected
+into each child row and forms part of the primary key, because FireHydrant only documents the child
+ids as unique within their parent.
+
+| Schema name | Path | Parent | Primary key | Partition key |
+| ------------------------ | ----------------------------------------- | --------- | --------------- | ------------- |
+| incident_milestones | `/v1/incidents/{incident_id}/milestones` | incidents | incident_id, id | created_at |
+| incident_tasks | `/v1/incidents/{incident_id}/tasks` | incidents | incident_id, id | created_at |
+| team_escalation_policies | `/v1/teams/{team_id}/escalation_policies` | teams | team_id, id | — |
+
+`/v1/incidents/{incident_id}/milestones` is the one paginated endpoint whose spec entry lists no
+`page` / `per_page` params, though it returns the same paginated envelope as its siblings. The spec
+also leaves the escalation policies response body empty, as it does for 100+ other FireHydrant
+endpoints; transport reads the standard `data` envelope either way and degrades to zero rows if the
+endpoint answers differently.
## Future enhancements
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.py
index fd4eea37393b..ec39ccbf91fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/canonical_descriptions.py
@@ -238,4 +238,51 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_at": "The time the checklist template was created.",
},
},
+ "schedules": {
+ "description": "On-call schedules known to FireHydrant, as pulled from the connected external on-call providers.",
+ "docs_url": "https://docs.firehydrant.com/reference/list_schedules",
+ "columns": {
+ "id": "UUID of the schedule.",
+ "name": "Name of the schedule.",
+ "integration": "The external provider the schedule was pulled from.",
+ "discarded": "Whether the schedule has been discarded.",
+ },
+ },
+ "incident_milestones": {
+ "description": "Lifecycle milestones reached on each incident, with the time spent in each one.",
+ "docs_url": "https://docs.firehydrant.com/reference/list_incident_milestones",
+ "columns": {
+ "id": "UUID of the milestone.",
+ "incident_id": "UUID of the incident the milestone belongs to.",
+ "type": "The milestone's type, one of the milestones configured for the incident.",
+ "duration": "How long the incident spent in this milestone, in ISO 8601 duration format. Null while the milestone is the incident's current one.",
+ "occurred_at": "The time the incident reached this milestone.",
+ "created_at": "The time the milestone record was created.",
+ "updated_at": "The time the milestone record was last changed.",
+ },
+ },
+ "incident_tasks": {
+ "description": "Tasks created on incidents, including who they are assigned to and whether they are done.",
+ "docs_url": "https://docs.firehydrant.com/reference/list_incident_tasks",
+ "columns": {
+ "id": "UUID of the task.",
+ "incident_id": "UUID of the incident the task belongs to.",
+ "title": "Title of the task.",
+ "description": "Description of what the task is for.",
+ "state": "State of the task: open, in_progress, cancelled or done.",
+ "assignee": "The user the task is assigned to.",
+ "created_by": "The user who created the task.",
+ "created_at": "The time the task was created.",
+ "updated_at": "The time the task was last changed.",
+ "due_at": "The time the task is due.",
+ },
+ },
+ "team_escalation_policies": {
+ "description": "Signals escalation policies per team, describing how an alert is routed and escalated.",
+ "docs_url": "https://docs.firehydrant.com/reference/list_team_escalation_policies",
+ "columns": {
+ "id": "UUID of the escalation policy.",
+ "team_id": "UUID of the team the escalation policy belongs to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.py
index ed92cba0b21b..e1e0e57c7d85 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/firehydrant.py
@@ -1,18 +1,28 @@
import dataclasses
-from typing import Any, Optional
+from typing import Any, Optional, cast
+
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from 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 (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponseCursorPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.settings import FIREHYDRANT_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.firehydrant.settings import (
+ FIREHYDRANT_ENDPOINTS,
+ PAGE_SIZE,
+)
# FireHydrant accounts are region-pinned: US accounts live on api.firehydrant.io, EU accounts on the
# data-residency host. The stored API key only authenticates against its own region's host.
@@ -21,16 +31,16 @@ BASE_URLS: dict[str, str] = {
"eu": "https://api.eu.firehydrant.io",
}
DEFAULT_REGION = "us"
-# FireHydrant caps per_page at 200. 100 keeps each response comfortably small while halving the
-# request count versus the default page size.
-PAGE_SIZE = 100
+@frozen
class FireHydrantResumeConfig:
- # The next 1-indexed page to fetch. FireHydrant paginates with `page` / `per_page` query params and
- # returns a `pagination.next` page number (or null) in each response body.
- next_page: int
+ # Opaque framework checkpoint: `{"cursor": <next page>}` for a top-level endpoint (FireHydrant
+ # paginates with `page` / `per_page` and returns `pagination.next`, or null on the last page), or
+ # the fan-out manager's `{"completed": [...], "current": ..., "child_state": {...}}` for an
+ # endpoint walked per parent — round-tripped into `initial_paginator_state` on resume.
+ # Defaulted so state written in an older shape resumes from the start instead of failing.
+ paginator_state: dict[str, Any] = dataclasses.field(default_factory=dict)
def _get_headers(api_key: str) -> dict[str, str]:
@@ -71,6 +81,21 @@ def validate_credentials(api_key: str, region: str | None = None) -> tuple[bool,
return False, f"FireHydrant API returned an unexpected status: {status}"
+def _client_config(api_key: str, region: str | None) -> ClientConfig:
+ return {
+ "base_url": base_url_for_region(region),
+ # Auth (Bearer) is supplied via the framework auth config so the token is redacted from
+ # logs; only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ # FireHydrant returns the next page number in `pagination.next` (null on the last page);
+ # inject it as the `page` query param. Termination is `pagination.next` being falsy —
+ # endpoints returning a single unpaginated response carry no `pagination`, so they stop
+ # after one page.
+ "paginator": JSONResponseCursorPaginator(cursor_path="pagination.next", cursor_param="page"),
+ }
+
+
def firehydrant_source(
api_key: str,
endpoint: str,
@@ -81,54 +106,75 @@ def firehydrant_source(
) -> SourceResponse:
config = FIREHYDRANT_ENDPOINTS[endpoint]
- rest_config: RESTAPIConfig = {
- "client": {
- "base_url": base_url_for_region(region),
- # Auth (Bearer) is supplied via the framework auth config so the token is redacted from
- # logs; only the non-secret Accept header is set here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "bearer", "token": api_key},
- # FireHydrant returns the next page number in `pagination.next` (null on the last page);
- # inject it as the `page` query param. Termination is `pagination.next` being falsy —
- # endpoints returning a single unpaginated response carry no `pagination`, so they stop
- # after one page.
- "paginator": JSONResponseCursorPaginator(cursor_path="pagination.next", cursor_param="page"),
- },
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": {"per_page": PAGE_SIZE},
- # Paginated endpoints wrap rows in a top-level `data` array. A missing/empty `data`
- # key degrades to zero rows (not required) so an endpoint with nothing to return
- # ends cleanly rather than raising.
- "data_selector": "data",
- },
- }
- ],
- }
-
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
- if resume is not None:
- initial_paginator_state = {"cursor": resume.next_page}
+ if resume is not None and resume.paginator_state:
+ initial_paginator_state = resume.paginator_state
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields the
- # last page (merge dedupes on the primary key) rather than skipping it.
- if state and state.get("cursor") is not None:
- resumable_source_manager.save_state(FireHydrantResumeConfig(next_page=int(state["cursor"])))
-
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- None,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ # Persist only when there is somewhere left to resume to; save AFTER a page is yielded so a
+ # crash re-yields the last page (merge dedupes on the primary key) rather than skipping it.
+ if state:
+ resumable_source_manager.save_state(FireHydrantResumeConfig(paginator_state=dict(state)))
+
+ resource: Resource
+ if config.fanout is not None:
+ # Neither parent nor child offers a server-side time filter, so every sync walks the parent
+ # list and re-fetches the child per parent; that is inherent to the API.
+ resource = cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=cast(Any, FIREHYDRANT_ENDPOINTS),
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_key, region),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ page_size_param="per_page",
+ # A response that drops the `data` envelope is a shape change, not an empty page:
+ # tolerating it would silently replace the whole table with no rows.
+ parent_endpoint_extra={
+ "data_selector": "data",
+ "data_selector_required": True,
+ "data_selector_empty_ok": True,
+ },
+ child_endpoint_extra={
+ "data_selector": "data",
+ "data_selector_required": True,
+ "data_selector_empty_ok": True,
+ },
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ else:
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key, region),
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": {"per_page": PAGE_SIZE},
+ # Paginated endpoints wrap rows in a top-level `data` array. A missing/empty
+ # `data` key degrades to zero rows (not required) so an endpoint with nothing
+ # to return ends cleanly rather than raising.
+ "data_selector": "data",
+ },
+ }
+ ],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
return SourceResponse(
name=endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py
index f66ccfe81d97..3babaae1e394 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py
@@ -1,10 +1,19 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField
+# FireHydrant caps per_page at 200. 100 keeps each response comfortably small while halving the
+# request count versus the default page size.
+PAGE_SIZE = 100
+
-@dataclass
+@frozen
class FireHydrantEndpointConfig:
path: str
# Field to partition by. Must be a STABLE creation timestamp (never updated_at), and only set
@@ -13,6 +22,11 @@ class FireHydrantEndpointConfig:
primary_keys: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
should_sync_default: bool = True
+ # Set when the endpoint is scoped to a parent resource and has to be walked once per parent row.
+ fanout: Optional[DependentEndpointConfig] = None
+ page_size: int = PAGE_SIZE
+ # Read by the shared fan-out builder; every FireHydrant endpoint is full refresh, so it stays None.
+ default_incremental_field: Optional[str] = None
# Endpoint catalog. Paths are the FireHydrant v1 REST collection endpoints (verified against the
@@ -51,6 +65,48 @@ FIREHYDRANT_ENDPOINTS: dict[str, FireHydrantEndpointConfig] = {
"scheduled_maintenances": FireHydrantEndpointConfig(path="/v1/scheduled_maintenances", partition_key="created_at"),
"task_lists": FireHydrantEndpointConfig(path="/v1/task_lists", partition_key="created_at"),
"checklist_templates": FireHydrantEndpointConfig(path="/v1/checklist_templates", partition_key="created_at"),
+ # ScheduleEntity carries only id/name/integration/discarded, so there is nothing to partition on.
+ "schedules": FireHydrantEndpointConfig(path="/v1/schedules"),
+ "incident_milestones": FireHydrantEndpointConfig(
+ path="/v1/incidents/{incident_id}/milestones",
+ partition_key="created_at",
+ # Milestone ids are only documented per incident, and this table aggregates every incident's
+ # milestones, so the parent incident is part of the key to keep it unique table-wide.
+ primary_keys=["incident_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="incidents",
+ resolve_param="incident_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "incident_id"},
+ ),
+ ),
+ "incident_tasks": FireHydrantEndpointConfig(
+ path="/v1/incidents/{incident_id}/tasks",
+ partition_key="created_at",
+ primary_keys=["incident_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="incidents",
+ resolve_param="incident_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "incident_id"},
+ ),
+ ),
+ # The spec documents the request but leaves the response body empty, as it does for 100+ other
+ # FireHydrant endpoints (signals_on_call included). Transport reads the standard `data` envelope
+ # and fails loud if this endpoint turns out to answer differently.
+ "team_escalation_policies": FireHydrantEndpointConfig(
+ path="/v1/teams/{team_id}/escalation_policies",
+ primary_keys=["team_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="teams",
+ resolve_param="team_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "team_id"},
+ ),
+ ),
}
ENDPOINTS = tuple(FIREHYDRANT_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.py
index 079aa7034de5..48ebdb743b2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/tests/test_firehydrant.py
@@ -1,6 +1,7 @@
import json
from typing import Any
+import pytest
from unittest import mock
import requests
@@ -93,7 +94,7 @@ class TestPagination:
assert params[1]["per_page"] == PAGE_SIZE
# Checkpoint saved once, pointing at the next page; the final (next=None) page saves nothing.
manager.save_state.assert_called_once()
- assert manager.save_state.call_args.args[0] == FireHydrantResumeConfig(next_page=2)
+ assert manager.save_state.call_args.args[0] == FireHydrantResumeConfig(paginator_state={"cursor": 2})
@mock.patch(CLIENT_SESSION_PATCH)
def test_single_unpaginated_response_terminates(self, MockSession) -> None:
@@ -126,7 +127,7 @@ class TestPagination:
_rows(firehydrant_source("fhb_test", "services", team_id=1, job_id="j", resumable_source_manager=manager))
# State saved only when a next page exists — not after the final page.
- assert [c.args[0].next_page for c in manager.save_state.call_args_list] == [2, 3]
+ assert [c.args[0].paginator_state["cursor"] for c in manager.save_state.call_args_list] == [2, 3]
@mock.patch(CLIENT_SESSION_PATCH)
def test_region_routes_requests_to_eu_host(self, MockSession) -> None:
@@ -150,7 +151,7 @@ class TestPagination:
session = MockSession.return_value
params, _urls = _wire(session, [_response([{"id": "b"}], next_page=None)])
- manager = _make_manager(FireHydrantResumeConfig(next_page=2))
+ manager = _make_manager(FireHydrantResumeConfig(paginator_state={"cursor": 2}))
rows = _rows(
firehydrant_source("fhb_test", "services", team_id=1, job_id="j", resumable_source_manager=manager)
)
@@ -179,6 +180,126 @@ class TestPagination:
assert [r["id"] for r in rows] == ["ok"]
+class TestFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_child_endpoint_once_per_parent(self, MockSession) -> None:
+ session = MockSession.return_value
+ params, urls = _wire(
+ session,
+ [
+ _response([{"id": "inc1"}, {"id": "inc2"}], next_page=None),
+ _response([{"id": "m1"}], next_page=None),
+ _response([{"id": "m2"}], next_page=None),
+ ],
+ )
+
+ rows = _rows(
+ firehydrant_source(
+ "fhb_test", "incident_milestones", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+
+ assert urls == [
+ "https://api.firehydrant.io/v1/incidents",
+ "https://api.firehydrant.io/v1/incidents/inc1/milestones",
+ "https://api.firehydrant.io/v1/incidents/inc2/milestones",
+ ]
+ # The parent id is injected and renamed to `incident_id`, which the primary key depends on
+ # (milestone ids are only unique within their incident).
+ assert rows == [
+ {"id": "m1", "incident_id": "inc1"},
+ {"id": "m2", "incident_id": "inc2"},
+ ]
+ # The resolved param binds the path only; leaking it into the query string would make every
+ # child request carry a filter FireHydrant never documented.
+ assert "incident_id" not in params[1]
+ assert params[1]["per_page"] == PAGE_SIZE
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_parents_already_synced(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "t1"}, {"id": "t2"}], next_page=None),
+ _response([{"id": "task2"}], next_page=None),
+ ],
+ )
+
+ manager = _make_manager(
+ FireHydrantResumeConfig(
+ paginator_state={
+ "completed": ["/v1/teams/t1/escalation_policies"],
+ "current": None,
+ "child_state": None,
+ }
+ )
+ )
+ rows = _rows(
+ firehydrant_source(
+ "fhb_test", "team_escalation_policies", team_id=1, job_id="j", resumable_source_manager=manager
+ )
+ )
+
+ # Only the unfinished parent is re-fetched, so a resumed fan-out doesn't replay the whole
+ # parent list's children.
+ assert session.send.call_count == 2
+ assert rows == [{"id": "task2", "team_id": "t2"}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_checkpoint_records_completed_parents(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "inc1"}], next_page=None),
+ _response([{"id": "task1"}], next_page=None),
+ ],
+ )
+
+ manager = _make_manager()
+ _rows(firehydrant_source("fhb_test", "incident_tasks", team_id=1, job_id="j", resumable_source_manager=manager))
+
+ assert manager.save_state.call_args.args[0].paginator_state["completed"] == ["/v1/incidents/inc1/tasks"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_response_without_the_data_envelope_fails_loud(self, MockSession) -> None:
+ # A shape change has to stop the sync. Reading it as an empty page would replace the whole
+ # table with no rows, and nothing downstream would report that.
+ session = MockSession.return_value
+ renamed_envelope = Response()
+ renamed_envelope.status_code = 200
+ renamed_envelope._content = json.dumps({"escalation_policies": [{"id": "ep1"}]}).encode()
+ _wire(session, [_response([{"id": "t1"}], next_page=None), renamed_envelope])
+
+ with pytest.raises(ValueError, match="data_selector"):
+ _rows(
+ firehydrant_source(
+ "fhb_test",
+ "team_escalation_policies",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ )
+ )
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_child_body_is_zero_rows(self, MockSession) -> None:
+ # An empty container carries no rows and no alternative shape, so it must not fail loud.
+ session = MockSession.return_value
+ empty = Response()
+ empty.status_code = 200
+ empty._content = b"{}"
+ _wire(session, [_response([{"id": "t1"}], next_page=None), empty])
+
+ rows = _rows(
+ firehydrant_source(
+ "fhb_test", "team_escalation_policies", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+ )
+ assert rows == []
+
+
class TestSourceResponse:
@parameterized.expand(list(ENDPOINTS))
def test_source_response_matches_endpoint_config(self, endpoint: str) -> None: