: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(data-warehouse): add flexmail contact sub-resource tables (#107705)
Tom Owersdb25ab458c51
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 3d2ee15c888d..76d5cf6da738 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -571,8 +571,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py1 products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.py1 products/warehouse_sources/backend/temporal/data_imports/sources/float_app/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/flowlu/flowlu.pydiff --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.mdindex 2a37ba05d3bb..dbb2a6932206 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@@ -3241,18 +3241,18 @@ Note: No OpenAPI file is published; the resource list came from the Docusaurus s## Flexmail — gaps-Today (7): `contacts`, `custom_fields`, `interests`, `opt_in_forms`, `preferences`, `segments`, `sources`+Today (9): `contact_interest_subscriptions`, `contact_sources`, `contacts`, `custom_fields`, `interests`, `opt_in_forms`, `preferences`, `segments`, `sources`Diffed against: <https://api.flexmail.eu/documentation/openapi.php>-- [ ] `/contacts/{id}/interest-subscriptions` — membership table joining synced contacts to synced interests - the only way to segment by interest (high)-- [ ] `/contacts/{id}/preferences` — membership table joining contacts to the synced preferences (consent/topic opt-ins) (high)-- [ ] `/contacts/{id}/sources` — attribution rows linking each contact to the synced sources that acquired them (high)-- [ ] `/interest-labels` — lookup resolving the label IDs carried on interest rows (medium)-- [ ] `/contacts/{id}/interest-labels` — per-contact interest labels, a second targeting dimension not derivable from the synced tables (medium)+- [x] `/contacts/{id}/interest-subscriptions` — membership table joining synced contacts to synced interests - the only way to segment by interest (high)+- [ ] `/contacts/{id}/preferences` — membership table joining contacts to the synced preferences (consent/topic opt-ins) (high) — skipped: marked `deprecated` in the spec; the whole Preferences resource is superseded by Interests+- [x] `/contacts/{id}/sources` — attribution rows linking each contact to the synced sources that acquired them (high)+- [ ] `/interest-labels` — lookup resolving the label IDs carried on interest rows (medium) — skipped: marked `deprecated` in the spec; superseded by Interests+- [ ] `/contacts/{id}/interest-labels` — per-contact interest labels, a second targeting dimension not derivable from the synced tables (medium) — skipped: marked `deprecated` in the spec; superseded by Interests- [ ] `/account-contact-languages` — lookup resolving the language code on contact rows (low)-Note: The Flexmail public API is contact-management only - it exposes no campaigns, mailings, sends, opens or clicks - so the synced set already covers every top-level collection. The genuine gaps are all per-contact sub-resources, which need a contact-ID-driven fan-out rather than a plain list endpoint. Webhooks and webhook-events are excluded as plumbing.+Note: The Flexmail public API is contact-management only - it exposes no campaigns, mailings, sends, opens or clicks - so the synced set already covers every top-level collection. The remaining gaps are the two deprecated resources (preferences and interest labels, both superseded by Interests) and the contact-languages lookup. Webhooks and webhook-events are excluded as plumbing.## FloatApp — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.pyindex 7daa92462e3c..33b94f783436 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/canonical_descriptions.py@@ -17,6 +17,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"custom_fields": "The contact's values for the account's custom fields, keyed by custom field placeholder.",},},+ "contact_interest_subscriptions": {+ "description": "One row per contact and interest the contact is subscribed to, joining the contacts table to the interests table.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/contacts/-id-/interest-subscriptions",+ "columns": {+ "contact_id": "Identifier of the contact the subscription belongs to.",+ "interest_id": "Identifier of the interest the contact is subscribed to.",+ },+ },+ "contact_sources": {+ "description": "One row per contact and source, recording where the contact's data originated. Every Flexmail contact has at least one source.",+ "docs_url": "https://api.flexmail.eu/documentation/#get-/contacts/-id-/sources",+ "columns": {+ "contact_id": "Identifier of the contact the source belongs to.",+ "id": "Unique identifier of the source.",+ "name": "The name of the source.",+ },+ },"custom_fields": {"description": "A custom field configured for contacts in your Flexmail account (free text, multiple choice, numeric, or date).","docs_url": "https://api.flexmail.eu/documentation/#get-/custom-fields",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.pyindex 8d2400228c48..23171ffe1789 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py@@ -9,35 +9,50 @@ collection, so a missing selector legitimately means zero rows) and every row catop-level ``total``; the segments, opt-in forms and custom fields collections return their wholeresult set in one response.-Every table is full refresh only — no list endpoint exposes a server-side timestamp filter, so there-is no incremental cursor to advance.+Two tables are per-contact sub-resources (``/contacts/{id}/sources`` and+``/contacts/{id}/interest-subscriptions``) and are fetched once per contact, with the contact's id+carried onto every row so the table can be joined back to ``contacts``.++Every table is full refresh only — no endpoint exposes a server-side timestamp filter, so there is+no incremental cursor to advance.Built on the shared ``rest_source`` framework: framework ``http_basic`` auth carries the credentials(and redacts the token from errors/logs), a built-in ``OffsetPaginator`` reproduces the-``limit``/``offset`` + ``total`` termination with resume, and a ``data_map`` strips each row's-``_links``.+``limit``/``offset`` + ``total`` termination with resume, ``build_dependent_resource`` drives the+per-contact fan-out, and a ``data_map`` strips each row's ``_links``."""-import dataclasses+from collections.abc import Callable, Iterable, Iteratorfrom typing import Any, Optionalfrom requests.auth import HTTPBasicAuth+from posthog.dataclasses import frozen+from 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 (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,OffsetPaginator,SinglePagePaginator,)-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.rest_source.typing import (+ ClientConfig,+ Endpoint,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.settings import FLEXMAIL_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.flexmail.settings import (+ FLEXMAIL_ENDPOINTS,+ FlexmailEndpointConfig,+)FLEXMAIL_BASE_URL = "https://api.flexmail.eu"# List endpoints accept a `limit` of up to 500; the largest page minimises round trips against the@@ -52,17 +67,22 @@ DEFAULT_PROBE_PATH = "/sources"_DATA_SELECTOR = "_embedded.item"+@frozenclass FlexmailResumeConfig:# Offset of the next page to fetch. Flexmail paginates with `limit`/`offset` query params, so a# crashed full-refresh sync resumes from the page after the last one yielded; merge dedupes the# re-pulled page on `id`. `0` means start from the first page.offset: int = 0+ # Fan-out endpoints resume on the shape `build_dependent_resource` checkpoints: which contacts+ # finished and where the current one stopped.+ fanout_state: Optional[dict[str, Any]] = None-def _strip_links(item: dict[str, Any]) -> dict[str, Any]:- # Per-item `_links` are HAL navigation, not data.- return {k: v for k, v in item.items() if k != "_links"}+def _strip_hal_navigation(item: dict[str, Any]) -> dict[str, Any]:+ # Per-item `_links` are HAL navigation, not data. `_embedded` on a sub-resource row repeats a+ # row of the parent collection we already sync (an interest subscription embeds its interest),+ # so it is navigation too.+ return {k: v for k, v in item.items() if k not in ("_links", "_embedded")}def _client_config(account_id: str, personal_access_token: str) -> ClientConfig:@@ -79,65 +99,136 @@ def _client_config(account_id: str, personal_access_token: str) -> ClientConfig:}-def flexmail_source(- account_id: str,- personal_access_token: str,- endpoint: str,- team_id: int,- job_id: str,- resumable_source_manager: ResumableSourceManager[FlexmailResumeConfig],-) -> SourceResponse:- config = FLEXMAIL_ENDPOINTS[endpoint]-- paginator: BasePaginator+def _paginator(config: FlexmailEndpointConfig) -> BasePaginator:if config.paginated:# `total` is the row count; the paginator stops once offset >= total (or on a short/empty# page), matching the hand-rolled `next_offset >= total` termination.- paginator = OffsetPaginator(limit=PAGE_SIZE, offset_param="offset", limit_param="limit", total_path="total")- else:- # Segments, opt-in forms and custom fields return the whole collection in one response.- paginator = SinglePagePaginator()+ return OffsetPaginator(limit=PAGE_SIZE, offset_param="offset", limit_param="limit", total_path="total")+ # Segments, opt-in forms, custom fields and a contact's interest subscriptions return the whole+ # collection in one response.+ return SinglePagePaginator()+++def _endpoint_extra(config: FlexmailEndpointConfig) -> Endpoint:+ # Each resource carries its own paginator: a fan-out pairs a paginated parent with a child that+ # may not be paginated at all.+ return {"paginator": _paginator(config), "data_selector": _DATA_SELECTOR}++def _flat_resource(+ *,+ config: FlexmailEndpointConfig,+ client_config: ClientConfig,+ team_id: int,+ job_id: str,+ resume_hook: Callable[[Optional[dict[str, Any]]], None],+ initial_paginator_state: Optional[dict[str, Any]],+) -> Iterable[list[dict[str, Any]]]:rest_config: RESTAPIConfig = {- "client": {**_client_config(account_id, personal_access_token), "paginator": paginator},+ "client": {**client_config, "paginator": _paginator(config)},"resources": [{- "name": endpoint,+ "name": config.name,"endpoint": {"path": config.path, "data_selector": _DATA_SELECTOR},- "data_map": _strip_links,+ "data_map": _strip_hal_navigation,}],}-- 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 and resume.offset:- initial_paginator_state = {"offset": resume.offset}-- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Save AFTER a page is yielded so a crash re-fetches the last page (merge dedupes on `id`)- # rather than skipping it. SinglePagePaginator never yields resume state, so unpaginated- # endpoints never checkpoint.- if state and state.get("offset") is not None:- resumable_source_manager.save_state(FlexmailResumeConfig(offset=int(state["offset"])))-- resource = rest_api_resource(+ return rest_api_resource(rest_config,team_id,job_id,None,- resume_hook=save_checkpoint,+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+++def _fanout_resource(+ *,+ config: FlexmailEndpointConfig,+ client_config: ClientConfig,+ team_id: int,+ job_id: str,+ resume_hook: Callable[[Optional[dict[str, Any]]], None],+ initial_paginator_state: Optional[dict[str, Any]],+) -> Iterable[list[dict[str, Any]]]:+ assert config.fanout is not None+ return build_dependent_resource(+ endpoint_configs=FLEXMAIL_ENDPOINTS,+ child_endpoint=config.name,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra=_endpoint_extra(FLEXMAIL_ENDPOINTS[config.fanout.parent_name]),+ child_endpoint_extra=_endpoint_extra(config),+ # Both paginators send their own page size, so the builder must not add one.+ page_size_param=None,+ resume_hook=resume_hook,initial_paginator_state=initial_paginator_state,)++def flexmail_source(+ account_id: str,+ personal_access_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FlexmailResumeConfig],+) -> SourceResponse:+ config = FLEXMAIL_ENDPOINTS[endpoint]+ client_config = _client_config(account_id, personal_access_token)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Save AFTER a page is yielded so a crash re-fetches the last page (merge dedupes on the+ # primary key) rather than skipping it. SinglePagePaginator never yields resume state, so+ # unpaginated endpoints never checkpoint.+ if not state:+ return+ if config.fanout is not None:+ resumable_source_manager.save_state(FlexmailResumeConfig(fanout_state=state))+ return+ if state.get("offset") is not None:+ resumable_source_manager.save_state(FlexmailResumeConfig(offset=int(state["offset"])))++ def build_resource() -> Iterable[list[dict[str, Any]]]:+ if config.fanout is not None:+ return _fanout_resource(+ config=config,+ client_config=client_config,+ team_id=team_id,+ job_id=job_id,+ resume_hook=save_checkpoint,+ initial_paginator_state=resume.fanout_state if resume else None,+ )+ initial_paginator_state = {"offset": resume.offset} if resume and resume.offset else None+ return _flat_resource(+ config=config,+ client_config=client_config,+ team_id=team_id,+ job_id=job_id,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ def items() -> Iterator[list[dict[str, Any]]]:+ # The fan-out builder has no resource-level `data_map` seam, so sub-resource rows are+ # cleaned here instead.+ for batch in build_resource():+ yield [_strip_hal_navigation(row) for row in batch] if config.fanout is not None else batch+return SourceResponse(name=endpoint,- items=lambda: resource,+ items=items,primary_keys=config.primary_keys,partition_count=1,partition_size=1,- column_hints=resource.column_hints,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.pyindex 39f7bfed86bf..dd944af754eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/settings.py@@ -1,30 +1,81 @@-from dataclasses import dataclass, field+from dataclasses import field+from typing import Optional+from posthog.dataclasses import frozen-@dataclass+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField+++@frozenclass FlexmailEndpointConfig:+ # `name` repeats the FLEXMAIL_ENDPOINTS key because `build_dependent_resource` reads it off+ # the config rather than the mapping key.+ name: strpath: str# `paginated` marks endpoints that accept `limit`/`offset` and wrap results in the HAL# collection envelope (`total`/`limit`/`offset`); the rest return the full collection at once.paginated: bool = True# Flexmail identifiers are account-unique (integers or UUIDs depending on the resource), so- # `id` is a safe primary key for every endpoint.+ # `id` is a safe primary key for every top-level endpoint. A per-contact sub-resource repeats+ # the same sub-resource id once per contact, so it keys on the contact as well.primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Set on endpoints fetched once per row of a parent endpoint.+ fanout: Optional[DependentEndpointConfig] = None+ # Nothing here is incremental: no Flexmail list endpoint exposes a server-side timestamp+ # filter. Both fields exist for `build_dependent_resource`'s endpoint-config protocol.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Never read: every paginator here sends its own `limit`, so the fan-out builder is told to+ # add no page-size param. Present for the same protocol.+ page_size: int = 0+++# Both per-contact sub-resources are addressed the same way, and the config is frozen, so one+# instance serves both. A contact deleted between the contact listing and the sub-resource fetch+# answers 404 — skip that contact rather than failing the whole table.+CONTACT_FANOUT = DependentEndpointConfig(+ parent_name="contacts",+ resolve_param="id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "contact_id"},+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+)-# Flexmail REST API (https://api.flexmail.eu) list endpoints. All are full-refresh only: no list-# endpoint accepts a server-side timestamp filter (contacts only filter on `email`, custom fields-# on `type`/`language`), so there is no incremental cursor to advance. Contact sub-resources-# (interest subscriptions, preferences, sources per contact) are deliberately not fanned out —-# at 60 requests/minute per account, one request per contact is impractical for real accounts.+# Flexmail REST API (https://api.flexmail.eu) endpoints. All are full-refresh only: no endpoint+# accepts a server-side timestamp filter (contacts only filter on `email`/`interest`, custom+# fields on `type`/`language`), so there is no incremental cursor to advance.+#+# The two `contact_*` tables fan out one request per contact: a sync costs the contact listing+# plus one request per contact, against a 60 requests/minute per-account rate limit. They are+# separately selectable schemas, and joining contacts to their sources or interests is not+# possible from any other endpoint, so the cost is the user's call to make.FLEXMAIL_ENDPOINTS: dict[str, FlexmailEndpointConfig] = {- "contacts": FlexmailEndpointConfig(path="/contacts"),- "custom_fields": FlexmailEndpointConfig(path="/custom-fields", paginated=False),- "interests": FlexmailEndpointConfig(path="/interests"),- "opt_in_forms": FlexmailEndpointConfig(path="/opt-in-forms", paginated=False),- "preferences": FlexmailEndpointConfig(path="/preferences"),- "segments": FlexmailEndpointConfig(path="/segments", paginated=False),- "sources": FlexmailEndpointConfig(path="/sources"),+ "contact_interest_subscriptions": FlexmailEndpointConfig(+ name="contact_interest_subscriptions",+ path="/contacts/{id}/interest-subscriptions",+ # Takes no `limit`/`offset`; answers with the contact's whole subscription collection.+ paginated=False,+ primary_keys=["contact_id", "interest_id"],+ fanout=CONTACT_FANOUT,+ ),+ "contact_sources": FlexmailEndpointConfig(+ name="contact_sources",+ path="/contacts/{id}/sources",+ primary_keys=["contact_id", "id"],+ fanout=CONTACT_FANOUT,+ ),+ "contacts": FlexmailEndpointConfig(name="contacts", path="/contacts"),+ "custom_fields": FlexmailEndpointConfig(name="custom_fields", path="/custom-fields", paginated=False),+ "interests": FlexmailEndpointConfig(name="interests", path="/interests"),+ "opt_in_forms": FlexmailEndpointConfig(name="opt_in_forms", path="/opt-in-forms", paginated=False),+ "preferences": FlexmailEndpointConfig(name="preferences", path="/preferences"),+ "segments": FlexmailEndpointConfig(name="segments", path="/segments", paginated=False),+ "sources": FlexmailEndpointConfig(name="sources", path="/sources"),}ENDPOINTS = tuple(FLEXMAIL_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.pyindex 150be02f58cf..25a1d6d977f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/tests/test_flexmail.py@@ -290,15 +290,133 @@ class TestValidateCredentials:assert kwargs["auth"] == HTTPBasicAuth("12345", "flexmail-token")+class TestContactFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_contacts_and_carries_the_contact_id(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _envelope([{"id": 29}, {"id": 30}], total=2),+ _envelope(+ [{"id": 4, "name": "newsletter signup form", "_links": {"self": {"href": "/sources/4"}}}], total=1+ ),+ _envelope([{"id": 7, "name": "import"}], total=1),+ ],+ )++ rows = _rows(_source("contact_sources"))++ # A contact's source rows are indistinguishable from the account-wide `sources` table+ # without the contact id, so the join column has to survive onto every row.+ assert rows == [+ {"contact_id": 29, "id": 4, "name": "newsletter signup form"},+ {"contact_id": 30, "id": 7, "name": "import"},+ ]+ assert [p.get("offset") for p in params] == [0, 0, 0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_walks_offset_pages_within_one_contact(self, MockSession) -> None:+ session = MockSession.return_value+ first_page = [{"id": i} for i in range(PAGE_SIZE)]+ params = _wire(+ session,+ [+ _envelope([{"id": 29}], total=1),+ _envelope(first_page, total=PAGE_SIZE + 1),+ _envelope([{"id": 999}], total=PAGE_SIZE + 1, offset=PAGE_SIZE),+ ],+ )++ rows = _rows(_source("contact_sources"))++ assert len(rows) == PAGE_SIZE + 1+ assert all(row["contact_id"] == 29 for row in rows)+ assert [p["offset"] for p in params[1:]] == [0, PAGE_SIZE]++ @mock.patch(SLEEP_PATCH)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_skips_a_contact_deleted_since_the_listing(self, MockSession, _sleep) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _envelope([{"id": 29}, {"id": 30}], total=2),+ _json_response({"title": "Not Found"}, status_code=404),+ _envelope([{"id": 7, "name": "import"}], total=1),+ ],+ )++ rows = _rows(_source("contact_sources"))++ assert rows == [{"contact_id": 30, "id": 7, "name": "import"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_interest_subscriptions_fetch_once_per_contact_without_pagination_params(self, MockSession) -> None:+ session = MockSession.return_value+ subscription = {+ "interest_id": "1f0b2e6c-0000-4000-8000-000000000001",+ "_links": {"self": {"href": "/contacts/29/interest-subscriptions/1f0b"}},+ # The embedded interest repeats a row of the `interests` table we already sync.+ "_embedded": {"interest": {"id": "1f0b2e6c-0000-4000-8000-000000000001", "name": "Programming"}},+ }+ params = _wire(+ session,+ [+ _envelope([{"id": 29}], total=1),+ _json_response({"total": 1, "_embedded": {"item": [subscription]}}),+ ],+ )++ rows = _rows(_source("contact_interest_subscriptions"))++ assert rows == [{"contact_id": 29, "interest_id": "1f0b2e6c-0000-4000-8000-000000000001"}]+ assert session.send.call_count == 2+ assert "offset" not in params[1] and "limit" not in params[1]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_without_refetching_a_finished_contact(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _envelope([{"id": 29}, {"id": 30}], total=2),+ _envelope([{"id": 7, "name": "import"}], total=1),+ ],+ )++ manager = _make_manager(FlexmailResumeConfig(fanout_state={"completed": ["/contacts/29/sources"]}))+ rows = _rows(_source("contact_sources", manager))++ assert rows == [{"contact_id": 30, "id": 7, "name": "import"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoints_which_contacts_finished(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _envelope([{"id": 29}], total=1),+ _envelope([{"id": 7, "name": "import"}], total=1),+ ],+ )++ manager = _make_manager()+ _rows(_source("contact_sources", manager))++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved, "the fan-out must checkpoint its progress through the contact list"+ assert saved[-1].fanout_state is not None+ assert "/contacts/29/sources" in saved[-1].fanout_state["completed"]++class TestFlexmailSourceResponse:@parameterized.expand([(e,) for e in ENDPOINTS])def test_source_response_shape(self, endpoint: str) -> None:response = _source(endpoint)assert response.name == endpoint- assert response.primary_keys == ["id"]+ # Wired from the endpoint config, not hardcoded: a fan-out table keyed on the bare+ # sub-resource id would seed a duplicate row per contact.+ assert response.primary_keys == FLEXMAIL_ENDPOINTS[endpoint].primary_keys# No stable creation timestamp exists on most resources, so we don't partition.assert response.partition_mode is None-- def test_every_endpoint_uses_id_primary_key(self) -> None:- assert all(config.primary_keys == ["id"] for config in FLEXMAIL_ENDPOINTS.values())- assert set(FLEXMAIL_ENDPOINTS) == set(ENDPOINTS)