: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 2 missing tables to the Bloomerang source (#120139)
Tom Owersaf1cc28d8c57
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.mdindex 3557e09f93d0..c3aad6fcbe5f 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@@ -1737,8 +1737,8 @@ Diffed against: <https://bloomerang-api-documentation.s3.us-west-2.amazonaws.com- [x] `Addresses (GET /v2/addresses)` — resolve AddressIds beyond the primary address for geographic and household analysis (high)- [x] `Email addresses (GET /v2/emails)` — resolve EmailIds beyond the primary email for contact coverage and donor matching (high)- [x] `Phones (GET /v2/phones)` — resolve PhoneIds beyond the primary phone for contact coverage and outreach analysis (high)-- [ ] `Relationships (GET /v2/constituent/{id}/relationships)` — analyze donor relationships, employers, and connections that affect fundraising (medium)-- [ ] `Pledge payment failures (GET /v2/pledge/{id}/paymentFailures)` — measure failed pledge payments and identify donations at risk (medium)+- [x] `Relationships (GET /v2/constituent/{id}/relationships)` — analyze donor relationships, employers, and connections that affect fundraising (medium)+- [x] `Pledge payment failures (GET /v2/pledge/{id}/paymentFailures)` — measure failed pledge payments and identify donations at risk (medium)- [x] `Notes (GET /v2/notes)` — analyze donor notes alongside transactions and interactions (medium)- [x] `Tasks (GET /v2/tasks)` — measure fundraising follow-up activity, completion, and outstanding work (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.pyindex 7bdef3db2188..56a77fa83594 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.py@@ -1,3 +1,4 @@+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional@@ -7,15 +8,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerangBLOOMERANG_ENDPOINTS,PAGE_SIZE,BloomerangEndpointConfig,+ BloomerangFanoutConfig,)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.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (+ create_response_hooks,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (OffsetPaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom 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_probe@@ -26,8 +33,15 @@ BASE_URL = "https://api.bloomerang.co/v2"@frozenclass BloomerangResumeConfig:- # Next `skip` value to resume from. Matches OffsetPaginator's own resume-state shape.+ # Next `skip` value to resume from. Matches OffsetPaginator's own resume-state shape. For a+ # fan-out table it is the `skip` of the parent page.next_offset: int+ # Fan-out tables only: the first parent on that parent page that is not fully read.+ parent_index: int = 0+++# A constituent or pledge can be deleted between the parent listing and the child request.+_IGNORE_NOT_FOUND = create_response_hooks([{"status_code": 404, "action": "ignore"}], resource_name="bloomerang")def _flatten_audit_trail(item: dict[str, Any]) -> dict[str, Any]:@@ -76,6 +90,17 @@ def _build_params(return params+def _paginator() -> OffsetPaginator:+ return OffsetPaginator(+ limit=PAGE_SIZE,+ offset_param="skip",+ limit_param="take",+ # TotalFiltered reflects whatever filters we send (e.g. lastModified); it equals the+ # unfiltered Total when we send none.+ total_path="TotalFiltered",+ )++def _client_config(api_key: str) -> ClientConfig:return {"base_url": BASE_URL,@@ -89,17 +114,112 @@ def _client_config(api_key: str) -> ClientConfig:# cross-origin redirect, so a hostile redirect could otherwise harvest it — disable# redirects for production syncs the same way the credential probe below already does."allow_redirects": False,- "paginator": OffsetPaginator(- limit=PAGE_SIZE,- offset_param="skip",- limit_param="take",- # TotalFiltered reflects whatever filters we send (e.g. lastModified); it equals the- # unfiltered Total when we send none.- total_path="TotalFiltered",- ),+ "paginator": _paginator(),}+def _rest_client(api_key: str) -> RESTClient:+ return RESTClient(+ base_url=BASE_URL,+ headers={"Accept": "application/json"},+ auth=APIKeyAuth(api_key=api_key, name="X-Api-Key", location="header"),+ # Same reasons as `_client_config`: donor PII stays out of samples, and no redirects.+ session=make_tracked_session(redact_values=(api_key,), capture=False),+ allow_redirects=False,+ )+++def _parent_ids(row: dict[str, Any], fanout: BloomerangFanoutConfig) -> list[int]:+ if fanout.designation_type is None:+ ids = [row.get("Id")]+ else:+ ids = [+ designation.get("Id")+ for designation in row.get("Designations") or []+ if isinstance(designation, dict) and designation.get("Type") == fanout.designation_type+ ]+ return [parent_id for parent_id in ids if isinstance(parent_id, int)]+++def _fanout_rows(+ client: RESTClient,+ config: BloomerangEndpointConfig,+ fanout: BloomerangFanoutConfig,+ resumable_source_manager: ResumableSourceManager[BloomerangResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Read the child endpoint for each parent, one parent page at a time.++ The resume state is a position in the parent list, not the framework's fan-out state, which+ keeps a list of every finished parent and grows with the size of the donor database.+ """+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.next_offset if resume else 0+ first_parent = resume.parent_index if resume else 0+ child_has_more_pages = False++ def track_child_page(_state: Optional[dict[str, Any]], has_next_page: bool) -> None:+ nonlocal child_has_more_pages+ child_has_more_pages = has_next_page++ for parent_page in client.paginate(+ path=fanout.parent_path,+ params=dict(fanout.parent_params),+ paginator=_paginator(),+ data_selector="Results",+ data_selector_required=True,+ initial_paginator_state={"offset": offset} if resume else None,+ ):+ resumable_source_manager.safe_point()+ parent_ids = [+ parent_id for row in parent_page if isinstance(row, dict) for parent_id in _parent_ids(row, fanout)+ ]+ for index in range(first_parent, len(parent_ids)):+ parent_id = parent_ids[index]+ after_parent = (+ BloomerangResumeConfig(next_offset=offset, parent_index=index + 1)+ if index + 1 < len(parent_ids)+ else BloomerangResumeConfig(next_offset=offset + PAGE_SIZE)+ )+ yielded = False+ for child_page in client.paginate(+ path=config.path.replace("{id}", str(parent_id)),+ paginator=_paginator(),+ data_selector="Results",+ data_selector_required=True,+ hooks=_IGNORE_NOT_FOUND,+ page_state_hook=track_child_page,+ ):+ rows = [{**row, fanout.parent_id_column: parent_id} for row in child_page if isinstance(row, dict)]+ if not rows:+ continue+ # A parent with child pages still to read is read again from its first page.+ resumable_source_manager.save_state(+ BloomerangResumeConfig(next_offset=offset, parent_index=index)+ if child_has_more_pages+ else after_parent+ )+ yield rows+ yielded = True+ if not yielded:+ resumable_source_manager.safe_point()+ first_parent = 0+ offset += PAGE_SIZE+++def _source_response(config: BloomerangEndpointConfig, items: Callable[[], Any]) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )++def bloomerang_source(api_key: str,endpoint: str,@@ -110,6 +230,11 @@ def bloomerang_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = BLOOMERANG_ENDPOINTS[endpoint]+ fanout = config.fanout+ if fanout is not None:+ client = _rest_client(api_key)+ return _source_response(config, lambda: _fanout_rows(client, config, fanout, resumable_source_manager))+is_incremental = config.supports_incremental and should_use_incremental_fieldrest_config: RESTAPIConfig = {@@ -156,17 +281,7 @@ def bloomerang_source(if config.has_audit_trail:resource = resource.add_map(_flatten_audit_trail)- return SourceResponse(- name=endpoint,- items=lambda: resource,- primary_keys=config.primary_keys,- partition_count=1,- partition_size=1,- partition_mode="datetime" if config.partition_key else None,- partition_format="month" if config.partition_key else None,- partition_keys=[config.partition_key] if config.partition_key else None,- sort_mode="asc",- )+ return _source_response(config, lambda: resource)def validate_credentials(api_key: str) -> tuple[bool, int | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.pyindex 11646dd9e506..8770b022f19d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.py@@ -223,4 +223,31 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"LastModifiedDate": "When the task was last modified.",},},+ "Relationships": {+ "description": "A link between two constituents, such as spouse, employer, or board member, listed once for each constituent on it.",+ "docs_url": _DOCS_URL,+ "columns": {+ "ConstituentId": "ID of the constituent whose relationships list returned this row.",+ "Id": "Unique identifier for the relationship used by the API.",+ "AccountId1": "ID of the first constituent in the relationship.",+ "AccountId2": "ID of the second constituent in the relationship.",+ "RelationshipRole1": "Role of the first constituent in the relationship.",+ "RelationshipRole2": "Role of the second constituent in the relationship.",+ "Note": "Free-form note on the relationship.",+ },+ },+ "PledgePaymentFailures": {+ "description": "A failed payment against a pledge installment.",+ "docs_url": _DOCS_URL,+ "columns": {+ "Id": "Unique identifier for the pledge payment failure.",+ "PledgeId": "Designation ID of the pledge the failed payment was for.",+ "InstallmentId": "ID of the pledge installment the failed payment was for.",+ "Date": "Date the payment failed.",+ "Amount": "Amount of the failed payment.",+ "Reason": "Reason the payment failed.",+ "IsResolved": "Whether the payment failure has been resolved.",+ "IsSuppressed": "Whether the payment failure has been suppressed.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.pyindex 877b783727d3..9bee25e04ea5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.py@@ -23,6 +23,19 @@ def _last_modified_incremental_fields() -> list[IncrementalField]:]+@frozen+class BloomerangFanoutConfig:+ """A child table read once for each row of a parent list endpoint."""++ parent_path: str+ parent_params: dict[str, str]+ # Column that carries the parent id on each child row.+ parent_id_column: str+ # When set, the child is read once for each embedded designation of this type, not once for each+ # parent row. Pledges are designations inside transactions and have no list endpoint of their own.+ designation_type: Optional[str] = None++@frozenclass BloomerangEndpointConfig:name: str@@ -45,6 +58,7 @@ class BloomerangEndpointConfig:primary_keys: list[str] = field(default_factory=lambda: ["Id"])# Stable creation-time column to partition by. None when the endpoint has no AuditTrail.partition_key: Optional[str] = "CreatedDate"+ fanout: Optional[BloomerangFanoutConfig] = NoneBLOOMERANG_ENDPOINTS: dict[str, BloomerangEndpointConfig] = {@@ -159,6 +173,38 @@ BLOOMERANG_ENDPOINTS: dict[str, BloomerangEndpointConfig] = {# The API doesn't document which statuses an unfiltered request returns, so ask for all of them.extra_params={"status": "Active|Complete|Archived"},),+ "Relationships": BloomerangEndpointConfig(+ name="Relationships",+ path="constituent/{id}/relationships",+ # Rows carry no AuditTrail, so the `lastModified` filter has no cursor column to advance.+ supports_incremental=False,+ supports_sort=False,+ has_audit_trail=False,+ # A relationship links two constituents and is listed under each of them.+ primary_keys=["ConstituentId", "Id"],+ partition_key=None,+ fanout=BloomerangFanoutConfig(+ parent_path="constituents",+ parent_params={"orderBy": "Id", "orderDirection": "Asc"},+ parent_id_column="ConstituentId",+ ),+ ),+ "PledgePaymentFailures": BloomerangEndpointConfig(+ name="PledgePaymentFailures",+ path="pledge/{id}/paymentFailures",+ supports_incremental=False,+ supports_sort=False,+ has_audit_trail=False,+ primary_keys=["PledgeId", "Id"],+ partition_key="Date",+ fanout=BloomerangFanoutConfig(+ parent_path="transactions",+ # /transactions takes no `orderBy=Id`.+ parent_params={"type": "Pledge", "orderBy": "CreatedDate", "orderDirection": "Asc"},+ parent_id_column="PledgeId",+ designation_type="Pledge",+ ),+ ),}ENDPOINTS = tuple(BLOOMERANG_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.pyindex 8d9d0716efb6..1104f55aceeb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py@@ -127,7 +127,7 @@ class BloomerangSource(ResumableSource[BloomerangSourceConfig, BloomerangResumeCcategory=DataWarehouseSourceCategory.CRM,keywords=["donor", "nonprofit", "fundraising"],releaseStatus=ReleaseStatus.ALPHA,- caption="""Enter your Bloomerang private API key to pull your donor database into the PostHog Data warehouse, including constituents, households, addresses, emails, phones, notes, tasks, transactions, refunds, soft credits, interactions, appeals, campaigns, and funds.+ caption="""Enter your Bloomerang private API key to pull your donor database into the PostHog Data warehouse, including constituents, relationships, households, addresses, emails, phones, notes, tasks, transactions, refunds, soft credits, pledge payment failures, interactions, appeals, campaigns, and funds.Generate a private API key under **Settings → User Settings → API Keys** in your Bloomerang account. This key grants full read/write access to your Bloomerang data, so keep it secret.""",iconPath="/static/services/bloomerang.png",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.pyindex 1f2580f2a5b8..f4dffbfe806b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.py@@ -212,6 +212,81 @@ class TestBloomerangSourceTransport:assert result.rows[0]["LastModifiedDate"] == "2026-01-02T00:00:00Z"assert "AuditTrail" not in result.rows[0]+ def test_relationships_fan_out_reads_every_child_page_and_skips_missing_parents(self) -> None:+ child_first_page = [{"Id": i, "AccountId1": 102} for i in range(1, 51)]+ result = self._driver().run(+ "Relationships",+ [+ _response([{"Id": 101}, {"Id": 102}, {"Id": 103}], total_filtered=3),+ ScriptedResponse(status=404),+ _response(child_first_page, total_filtered=51),+ _response([{"Id": 51, "AccountId1": 102}], total_filtered=51),+ _response([], total_filtered=0),+ ],+ )++ assert result.raised is None+ assert result.paths == [+ "/v2/constituents",+ "/v2/constituent/101/relationships",+ "/v2/constituent/102/relationships",+ "/v2/constituent/102/relationships",+ "/v2/constituent/103/relationships",+ ]+ assert result.requests[0].param("orderBy") == "Id"+ assert [row["Id"] for row in result.rows] == list(range(1, 52))+ assert {row["ConstituentId"] for row in result.rows} == {102}+ # While constituent 102 has a child page left, a resume reads it again from its first page.+ assert result.saved_states == [+ BloomerangResumeConfig(next_offset=0, parent_index=1),+ BloomerangResumeConfig(next_offset=0, parent_index=2),+ ]++ def test_pledge_payment_failures_fan_out_over_pledge_designations_only(self) -> None:+ result = self._driver().run(+ "PledgePaymentFailures",+ [+ _response(+ [+ {"Id": 1, "Designations": [{"Id": 11, "Type": "Pledge"}, {"Id": 12, "Type": "Donation"}]},+ {"Id": 2, "Designations": [{"Id": 21, "Type": "Pledge"}]},+ {"Id": 3, "Designations": None},+ ],+ total_filtered=3,+ ),+ _response([{"Id": 900, "Date": "2026-01-05", "Amount": 25.0}], total_filtered=1),+ _response([{"Id": 901, "Date": "2026-02-05", "Amount": 10.0}], total_filtered=1),+ ],+ )++ assert result.raised is None+ assert result.paths == [+ "/v2/transactions",+ "/v2/pledge/11/paymentFailures",+ "/v2/pledge/21/paymentFailures",+ ]+ assert result.requests[0].param("type") == "Pledge"+ assert [(row["PledgeId"], row["Id"]) for row in result.rows] == [(11, 900), (21, 901)]+ assert result.saved_states == [+ BloomerangResumeConfig(next_offset=0, parent_index=1),+ BloomerangResumeConfig(next_offset=50, parent_index=0),+ ]++ def test_fan_out_resumes_at_saved_parent_page_and_parent(self) -> None:+ result = self._driver().run(+ "Relationships",+ [+ _response([{"Id": 151}, {"Id": 152}], total_filtered=52),+ _response([{"Id": 7}], total_filtered=1),+ ],+ resume_state=BloomerangResumeConfig(next_offset=50, parent_index=1),+ )++ assert result.raised is None+ assert result.paths == ["/v2/constituents", "/v2/constituent/152/relationships"]+ assert result.params("skip") == ["50", "0"]+ assert result.rows == [{"Id": 7, "ConstituentId": 152}]+@parameterized.expand([("Constituents", "merge"),