: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): support BuildBetter API version v3 (#113233)
Tom Owers7acc9b27f9e0
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.mdindex 020347717179..dfb21029ad0c 100644--- a/.agents/skills/warehouse-source-new-version/SKILL.md+++ b/.agents/skills/warehouse-source-new-version/SKILL.md@@ -107,6 +107,8 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP- A version bump can change the auth scheme, not just the wire format. Then the source config needs both credential shapes as optional fields, auth construction dispatches on the resolved version, and `validate_credentials` enforces the pair that version needs — form-level `required` can't express "depends on the pin".- A new version can page a horizon the old one returned whole (a fixed record cap plus `next`/`prev` links). For a snapshot-polling source, keep one request per sync rather than following the links — vendors bill each page — and state the resulting horizon in each table's description, since it can be shorter than the old version's.- A version that drops the sort parameters the old request path used to order rows by the incremental field (for example a fixed newest-first order) breaks the per-batch watermark checkpoint that `sort_mode="asc"` implies. Report `sort_mode="desc"` for those endpoints under the new pin, so the pipeline persists the watermark only when a sync completes, and stop sending the sort params the new version rejects.+- When the new version's list endpoint cannot filter on the table's existing incremental field (it filters only on a different timestamp, or not at all), make those tables full refresh under the new pin by returning version-specific incremental fields from `get_schemas`. Filtering on a substitute timestamp silently skips rows that change or arrive late.+- A partial move that changes the resource's id scheme (internal integer → public UUID) breaks joins between the moved tables and the tables left on the legacy wire, which still carry the old foreign key. Say so in the PR and treat the repin as lossy.- A version that changes the pagination _mechanism_ (e.g. offset→cursor, or one opaque cursor param for another, since a token one generation issued means nothing to the other) also changes the resumable checkpoint's persisted shape. Add a new defaulted field to the resume-config dataclass rather than repurposing the existing one — so state persisted under the old version still decodes — and make the seed and save-checkpoint logic dispatch on the resolved version. Reusing one field across incompatible mechanisms corrupts in-flight resumes of the other version. When a table stays on its old wire under the new pin, key the check on the wire that issued the cursor, not on the pin.- Other products can read a synced table's columns by name, e.g. a signal emitter registered on `(source_type, table)` in `products/signals/backend/emission/registry.py`. Grep for the source type outside its directory before a new version renames or nests a column such a reader uses, and keep that column under its old name on the new version's rows.- When the vendor renames a collection between versions, keep the schema/table name set identical across versions and put the rename in a per-version path on the endpoint config — otherwise discovery diffs orphan the table on repin.diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 1391d22360b9..6d7b0aa88bc8 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -336,7 +336,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/bugherd.py1 products/warehouse_sources/backend/temporal/data_imports/sources/bugherd/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.py1 products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/buildkite.py1 products/warehouse_sources/backend/temporal/data_imports/sources/buildkite/settings.pydiff --git a/products/warehouse_sources/backend/migrations/0178_pin_unpinned_buildbetter_sources_to_v1.py b/products/warehouse_sources/backend/migrations/0178_pin_unpinned_buildbetter_sources_to_v1.pynew file mode 100644index 000000000000..53d19d478c6a--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0178_pin_unpinned_buildbetter_sources_to_v1.py@@ -0,0 +1,35 @@+from django.db import migrations+from django.db.models import Q++# BuildBetter's default version moves from `v1` (GraphQL) to `v3` (REST for interviews, attendees+# and transcripts). The versions are not request-identical: `v3` keys interviews by public UUID+# instead of the GraphQL bigint id. An unpinned source resolves to the default, so it would move to+# `v3` silently and merge UUID-keyed rows into tables built from bigint ids. Every unpinned source+# was created when `v1` was the only version, so this pins it to `v1` explicitly.+#+# Rows already pinned to `v1` stay on `v1`: the vendor deprecated GraphQL without a sunset date, and+# moving to `v3` changes primary keys, so that move is a manual re-sync, not a scripted repin.+BUILDBETTER_SOURCE_TYPE = "BuildBetter"+LEGACY_VERSION = "v1"+++def pin_unpinned_buildbetter_sources_to_v1(apps, schema_editor):+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")++ # Only the source-level pin is touched. Schema-level `ExternalDataSchema.api_version` overrides+ # are user-managed and are left alone. Matching only NULL/empty pins keeps this idempotent.+ ExternalDataSource.objects.filter(+ Q(api_version__isnull=True) | Q(api_version=""), source_type=BUILDBETTER_SOURCE_TYPE+ ).update(api_version=LEGACY_VERSION)+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources", "0177_repin_hookdeck_api_version"),+ ]++ operations = [+ # Reverse is a no-op: once pinned, these rows are indistinguishable from sources pinned to+ # `v1` by the create path, so clearing them would move legitimate `v1` pins to the default.+ migrations.RunPython(pin_unpinned_buildbetter_sources_to_v1, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex ef3396355239..2a95875ff7eb 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0177_repin_hookdeck_api_version+0178_pin_unpinned_buildbetter_sources_to_v1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.pyindex b93e78e893a0..238b6c67837a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.py@@ -1,5 +1,6 @@import reimport dataclasses+from collections.abc import Callable, Iteratorfrom typing import Anyimport requests@@ -13,9 +14,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildbette)from products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.settings import (BUILDBETTER_API_URL,+ BUILDBETTER_API_VERSION_V3,BUILDBETTER_ENDPOINTS,+ BUILDBETTER_REST_API_URL,+ BUILDBETTER_REST_PAGE_SIZE,+ BUILDBETTER_V3_REST_PRIMARY_KEYS,+ CREATED_AT,+ INTERVIEW_CREATED_AT,+ INTERVIEW_ID,+ INTERVIEW_UPDATED_AT,+ SENTENCE_INDEX,+ SPEAKER,+ UPDATED_AT,BuildBetterEndpointConfig,BuildBetterNestedConfig,+ uses_rest_api,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -34,9 +47,20 @@ class BuildBetterMissingFieldError(Exception):super().__init__(field_name)[email protected](frozen=True)class BuildBetterResumeConfig:- offset: int+ offset: int = 0+ # The REST API pages by page number rather than offset+ page: int | None = None+++def _make_session(api_key: str) -> requests.Session:+ return make_tracked_session(+ headers={+ "X-Buildbetter-API-Key": api_key,+ "Content-Type": "application/json",+ }+ )def _resolve_endpoint(endpoint_name: str) -> tuple[BuildBetterEndpointConfig, str]:@@ -192,12 +216,7 @@ def _make_paginated_request(graphql_query_name = endpoint_config.graphql_query_name or endpoint_namepage_size = endpoint_config.page_size- sess = make_tracked_session(- headers={- "X-Buildbetter-API-Key": api_key,- "Content-Type": "application/json",- }- )+ sess = _make_session(api_key)variables = _initial_variables(endpoint_name=endpoint_name,@@ -238,9 +257,112 @@ def _make_paginated_request(sess.close()+@retry(+ retry=retry_if_exception_type(BuildBetterRetryableError),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _rest_get(+ sess: requests.Session, path: str, params: dict[str, Any] | None = None, missing_ok: bool = False+) -> dict | None:+ response = sess.get(f"{BUILDBETTER_REST_API_URL}{path}", params=params, timeout=60)++ _raise_for_retryable_status(response)+ # A recording deleted between the list read and its detail read returns 404+ if missing_ok and response.status_code == 404:+ return None+ response.raise_for_status()++ return response.json()+++def _recording_parent_columns(recording: dict) -> dict[str, Any]:+ return {+ INTERVIEW_ID: recording.get("id"),+ INTERVIEW_CREATED_AT: recording.get(CREATED_AT),+ INTERVIEW_UPDATED_AT: recording.get(UPDATED_AT),+ }+++def _rest_attendee_rows(sess: requests.Session, recording: dict) -> list[dict]:+ detail = _rest_get(sess, f"/recordings/{recording['id']}", missing_ok=True)+ if detail is None:+ return []++ parent_columns = _recording_parent_columns(recording)+ return [+ parent_columns | {SPEAKER: participant.get("speaker"), "person": participant.get("person")}+ for participant in detail.get("participants") or []+ ]+++def _rest_sentence_rows(sess: requests.Session, recording: dict) -> list[dict]:+ transcript = _rest_get(sess, f"/recordings/{recording['id']}/transcript", {"type": "utterance"}, missing_ok=True)+ if transcript is None:+ return []++ parent_columns = _recording_parent_columns(recording)+ return [+ parent_columns+ | {+ "text": utterance.get("text"),+ SPEAKER: utterance.get("speaker"),+ "start_sec": utterance.get("startSec"),+ "end_sec": utterance.get("endSec"),+ SENTENCE_INDEX: index,+ }+ for index, utterance in enumerate(transcript.get("utterances") or [])+ ]+++_REST_CHILD_ROWS: dict[str, Callable[[requests.Session, dict], list[dict]]] = {+ "interview_attendees": _rest_attendee_rows,+ "interview_sentences": _rest_sentence_rows,+}+++def _make_rest_paginated_request(+ api_key: str,+ endpoint_name: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BuildBetterResumeConfig],+) -> Iterator[list[dict]]:+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume_config.page if resume_config is not None and resume_config.page is not None else 1+ if page > 1:+ logger.debug(f"BuildBetter: resuming {endpoint_name} from page {page}")++ child_rows = _REST_CHILD_ROWS.get(endpoint_name)+ sess = _make_session(api_key)++ try:+ while True:+ payload = _rest_get(sess, "/recordings", {"page": page, "limit": BUILDBETTER_REST_PAGE_SIZE}) or {}+ recordings = payload.get("recordings") or []++ if child_rows is None:+ rows = recordings+ else:+ rows = [row for recording in recordings for row in child_rows(sess, recording)]++ has_more = bool(recordings) and bool(payload.get("has_more"))+ if has_more:+ resumable_source_manager.save_state(BuildBetterResumeConfig(page=page + 1))+ if rows:+ yield rows++ if not has_more:+ break+ page += 1+ finally:+ sess.close()++def buildbetter_source(api_key: str,endpoint_name: str,+ api_version: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[BuildBetterResumeConfig],incremental_field: str | None = None,@@ -250,7 +372,18 @@ def buildbetter_source(if not endpoint_config:raise ValueError(f"Unknown BuildBetter endpoint: {endpoint_name}")+ use_rest = uses_rest_api(endpoint_name, api_version)+def get_rows():+ if use_rest:+ yield from _make_rest_paginated_request(+ api_key=api_key,+ endpoint_name=endpoint_name,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ )+ return+if incremental_field and incremental_field_last_value:logger.debug(f"BuildBetter: incremental sync for {endpoint_name} on {incremental_field} since {incremental_field_last_value}"@@ -267,24 +400,27 @@ def buildbetter_source(return SourceResponse(items=get_rows,- primary_keys=endpoint_config.primary_keys,+ primary_keys=BUILDBETTER_V3_REST_PRIMARY_KEYS[endpoint_name] if use_rest else endpoint_config.primary_keys,name=endpoint_name,partition_count=endpoint_config.partition_count,partition_size=endpoint_config.partition_size,partition_mode=endpoint_config.partition_mode,partition_format=endpoint_config.partition_format,partition_keys=endpoint_config.partition_keys,+ on_complete=resumable_source_manager.clear_state if use_rest else None,)-def validate_credentials(api_key: str) -> tuple[bool, str | None]:+def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:try:- sess = make_tracked_session(- headers={- "X-Buildbetter-API-Key": api_key,- "Content-Type": "application/json",- }- )+ sess = _make_session(api_key)+ if api_version == BUILDBETTER_API_VERSION_V3:+ response = sess.get(f"{BUILDBETTER_REST_API_URL}/recordings", params={"page": 1, "limit": 1}, timeout=10)+ response.raise_for_status()+ if "recordings" in response.json():+ return True, None+ return False, "Could not verify BuildBetter credentials"+response = sess.post(BUILDBETTER_API_URL,json={"query": VIEWER_QUERY},diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/canonical_descriptions.pyindex af5814ac61eb..767da3527791 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/canonical_descriptions.py@@ -18,6 +18,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"id": "Unique identifier of the interview.","external_id": "Identifier of the interview in the source system it was imported from.","name": "Name or title of the interview.",+ "display_name": "Name of the interview as shown in BuildBetter.","original_name": "Original name of the interview before any renaming.","short_summary": "Short AI-generated summary of the interview.","summary": "Full AI-generated summary of the interview.",@@ -39,6 +40,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"summary_state": "Processing state of the AI summaries.","attendees": "People who attended the interview.","tags": "Tags applied to the interview.",+ "metadata": "Metadata records linked to the interview, grouped by the source that supplied them.",},},"interview_attendees": {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/settings.pyindex 8c9bad5bf069..411941910001 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/settings.py@@ -19,10 +19,18 @@ SENTENCE_INDEX = "sentence_index"TOPIC_ID = "topic_id"TAG_ID = "tag_id"TYPE_ID = "type_id"+SPEAKER = "speaker"++BUILDBETTER_API_VERSION_V1 = "v1"+BUILDBETTER_API_VERSION_V3 = "v3"BUILDBETTER_API_URL = "https://api.buildbetter.app/v1/graphql"BUILDBETTER_DEFAULT_PAGE_SIZE = 1000+BUILDBETTER_REST_API_URL = "https://api.buildbetter.app/v3/rest"+# The recordings list caps `limit` at 100+BUILDBETTER_REST_PAGE_SIZE = 100+def _incremental_datetime_field(name: str) -> list[IncrementalField]:return [@@ -196,3 +204,24 @@ ENDPOINTS = tuple(BUILDBETTER_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in BUILDBETTER_ENDPOINTS.items()}++# Tables the v3 pin reads from the REST API, with their primary keys there. REST identifies a+# recording by its public UUID and a participant by its speaker number. BuildBetter has no REST+# endpoints for the other tables, so they stay on GraphQL under every version.+BUILDBETTER_V3_REST_PRIMARY_KEYS: dict[str, list[str]] = {+ "interviews": [ID],+ "interview_attendees": [INTERVIEW_ID, SPEAKER],+ "interview_sentences": [INTERVIEW_ID, SENTENCE_INDEX],+}+++def uses_rest_api(endpoint_name: str, api_version: str) -> bool:+ if api_version not in (BUILDBETTER_API_VERSION_V1, BUILDBETTER_API_VERSION_V3):+ raise ValueError(f"Unsupported BuildBetter API version: {api_version}")+ return api_version == BUILDBETTER_API_VERSION_V3 and endpoint_name in BUILDBETTER_V3_REST_PRIMARY_KEYS+++def incremental_fields_for_version(api_version: str) -> dict[str, list[IncrementalField]]:+ # The REST recordings list filters only on `recorded_at`, which misses recordings imported or+ # transcribed after the fact, so the REST tables are full refresh.+ return {name: [] if uses_rest_api(name, api_version) else fields for name, fields in INCREMENTAL_FIELDS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/source.pyindex 37628161b4e4..ccd5391395c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/source.py@@ -13,10 +13,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildbettevalidate_credentials as validate_buildbetter_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.settings import (+ BUILDBETTER_API_VERSION_V1,+ BUILDBETTER_API_VERSION_V3,ENDPOINTS,- INCREMENTAL_FIELDS,+ incremental_fields_for_version,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ FieldType,+ ResumableSource,+ VersionDeprecation,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)@@ -36,9 +42,13 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass BuildBetterSource(ResumableSource[BuildBetterSourceConfig, BuildBetterResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docs- supported_versions = ("v1",)- default_version = "v1"- api_docs_url = "https://docs.buildbetter.app/"+ # `v1` reads every table from the GraphQL API. `v3` reads interviews, attendees and transcripts+ # from the REST API, the only data REST serves so far, and keeps the other tables on GraphQL.+ supported_versions = (BUILDBETTER_API_VERSION_V1, BUILDBETTER_API_VERSION_V3)+ default_version = BUILDBETTER_API_VERSION_V3+ api_docs_url = "https://docs.buildbetter.ai/pages/api/index"+ # BuildBetter deprecates GraphQL for customer integrations but publishes no sunset date+ deprecated_versions = (VersionDeprecation(version=BUILDBETTER_API_VERSION_V1, sunset_at=None),)@propertydef source_type(self) -> ExternalDataSourceType:@@ -75,7 +85,9 @@ class BuildBetterSource(ResumableSource[BuildBetterSourceConfig, BuildBetterResuforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(+ ENDPOINTS, incremental_fields_for_version(self.resolve_api_version(api_version)), names+ )def validate_credentials(self,@@ -84,7 +96,7 @@ class BuildBetterSource(ResumableSource[BuildBetterSourceConfig, BuildBetterResuschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- return validate_buildbetter_credentials(config.api_key)+ return validate_buildbetter_credentials(config.api_key, self.resolve_api_version(api_version))def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BuildBetterResumeConfig]:return ResumableSourceManager[BuildBetterResumeConfig](inputs, BuildBetterResumeConfig)@@ -102,6 +114,7 @@ class BuildBetterSource(ResumableSource[BuildBetterSourceConfig, BuildBetterResureturn buildbetter_source(api_key=config.api_key,endpoint_name=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),logger=inputs.logger,resumable_source_manager=resumable_source_manager,incremental_field=inputs.incremental_field if inputs.should_use_incremental_field else None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/test_buildbetter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/test_buildbetter.pyindex c740287b390c..bf63477d50fc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/test_buildbetter.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/test_buildbetter.py@@ -10,8 +10,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildbetteBuildBetterResumeConfig,_make_paginated_request,buildbetter_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.settings import (+ BUILDBETTER_API_URL,+ BUILDBETTER_ENDPOINTS,+ BUILDBETTER_REST_API_URL,)-from products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.settings import BUILDBETTER_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.source import BuildBetterSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -35,6 +40,27 @@ def _interview_payload(ids: list[str]) -> dict:return {"data": {"interview": [{"id": i} for i in ids]}}+def _recording(recording_id: str) -> dict:+ return {+ "id": recording_id,+ "display_name": "Renewal discussion",+ "source": "upload",+ "recorded_at": "2026-07-28T15:00:00.000Z",+ "created_at": "2026-07-28T15:05:00.000Z",+ "updated_at": "2026-07-28T15:12:00.000Z",+ "metadata": [],+ }+++def _recordings_page(ids: list[str], has_more: bool = False) -> dict:+ return {"recordings": [_recording(i) for i in ids], "page": 1, "limit": 100, "has_more": has_more}+++REST_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.buildbetter.make_tracked_session"+)++class TestMakePaginatedRequest:@parameterized.expand([@@ -500,29 +526,192 @@ class TestNestedEndpoints:]-class TestBuildbetterSource:- def test_source_threads_resumable_manager_through(self) -> None:+class TestRestEndpoints:+ @parameterized.expand(+ [+ (+ "interview_attendees",+ "interview_attendees",+ {+ "id": "rec-1",+ "participants": [+ {"speaker": 0, "person": {"id": "per-1", "firstName": "Pat", "email": "[email protected]"}},+ {"speaker": 1, "person": {"id": "per-2", "firstName": "Alex", "email": "[email protected]"}},+ ],+ },+ [+ {"speaker": 0, "person": {"id": "per-1", "firstName": "Pat", "email": "[email protected]"}},+ {"speaker": 1, "person": {"id": "per-2", "firstName": "Alex", "email": "[email protected]"}},+ ],+ ),+ (+ "interview_sentences",+ "interview_sentences",+ {+ "type": "utterance",+ "recordingId": "rec-1",+ "utterances": [+ {"recordingId": "rec-1", "startSec": 0, "endSec": 2.5, "speaker": 0, "text": "First"},+ {"recordingId": "rec-1", "startSec": 2.5, "endSec": 4, "speaker": 1, "text": "Second"},+ ],+ },+ [+ {"text": "First", "speaker": 0, "start_sec": 0, "end_sec": 2.5, "sentence_index": 0},+ {"text": "Second", "speaker": 1, "start_sec": 2.5, "end_sec": 4, "sentence_index": 1},+ ],+ ),+ ]+ )+ def test_flattens_recording_children_with_parent_columns(+ self, _name: str, endpoint_name: str, child_payload: dict, expected_child_rows: list[dict]+ ) -> None:manager = _make_manager(can_resume=False)- logger = MagicMock()- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.buildbetter.make_tracked_session"- ) as session_cls:+ with patch(REST_PATCH) as session_cls:session = session_cls.return_value- session.post.return_value = _make_response(_interview_payload(["x"]))+ session.get.side_effect = [+ _make_response(_recordings_page(["rec-1", "rec-gone"])),+ _make_response(child_payload),+ # A recording deleted after the list read is skipped rather than failing the sync+ _make_response({"message": "Not Found"}, status_code=404),+ ]++ response = buildbetter_source(+ api_key="key",+ endpoint_name=endpoint_name,+ api_version="v3",+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ batches = list(cast(Iterable[Any], response.items()))++ parent_columns = {+ "interview_id": "rec-1",+ "interview_created_at": "2026-07-28T15:05:00.000Z",+ "interview_updated_at": "2026-07-28T15:12:00.000Z",+ }+ assert batches == [[parent_columns | row for row in expected_child_rows]]+ primary_keys = response.primary_keys+ assert primary_keys+ for row in batches[0]:+ assert all(row.get(key) is not None for key in primary_keys)++ @parameterized.expand(+ [+ ("fresh_run", False, None, 1),+ ("resume", True, BuildBetterResumeConfig(page=3), 3),+ # A checkpoint written by the GraphQL path carries no page, so REST starts over+ ("graphql_checkpoint", True, BuildBetterResumeConfig(offset=200), 1),+ ]+ )+ def test_pages_recordings_and_checkpoints_the_next_page(+ self, _name: str, can_resume: bool, state: BuildBetterResumeConfig | None, first_page: int+ ) -> None:+ manager = _make_manager(can_resume=can_resume, state=state)++ with patch(REST_PATCH) as session_cls:+ session = session_cls.return_value+ session.get.side_effect = [+ _make_response(_recordings_page(["a"], has_more=True)),+ _make_response(_recordings_page(["b"], has_more=False)),+ ]response = buildbetter_source(api_key="key",endpoint_name="interviews",- logger=logger,+ api_version="v3",+ logger=MagicMock(),resumable_source_manager=manager,)batches = list(cast(Iterable[Any], response.items()))- assert batches == [[{"id": "x"}]]- assert response.primary_keys == ["id"]+ assert batches == [[_recording("a")], [_recording("b")]]+ assert [call.kwargs["params"]["page"] for call in session.get.call_args_list] == [first_page, first_page + 1]+ assert [call.args[0].page for call in manager.save_state.call_args_list] == [first_page + 1]+ assert response.on_complete == manager.clear_state+++class TestBuildbetterSource:+ @parameterized.expand(+ [+ ("v1_interviews", "v1", "interviews", BUILDBETTER_API_URL, ["id"]),+ ("v1_attendees", "v1", "interview_attendees", BUILDBETTER_API_URL, ["interview_id", "id"]),+ ("v3_interviews", "v3", "interviews", f"{BUILDBETTER_REST_API_URL}/recordings", ["id"]),+ (+ "v3_attendees",+ "v3",+ "interview_attendees",+ f"{BUILDBETTER_REST_API_URL}/recordings",+ ["interview_id", "speaker"],+ ),+ # REST serves no signals, so v3 keeps them on GraphQL+ ("v3_extractions", "v3", "extractions", BUILDBETTER_API_URL, ["id"]),+ ]+ )+ def test_routes_each_version_to_its_api(+ self, _name: str, api_version: str, endpoint_name: str, expected_url: str, expected_primary_keys: list[str]+ ) -> None:+ manager = _make_manager(can_resume=False)+ query_name = BUILDBETTER_ENDPOINTS[endpoint_name].graphql_query_name++ with patch(REST_PATCH) as session_cls:+ session = session_cls.return_value+ session.post.return_value = _make_response({"data": {query_name: []}})+ session.get.return_value = _make_response(_recordings_page([]))++ response = buildbetter_source(+ api_key="key",+ endpoint_name=endpoint_name,+ api_version=api_version,+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ list(cast(Iterable[Any], response.items()))++ requested_urls = [call.args[0] for call in session.post.call_args_list + session.get.call_args_list]+ assert requested_urls == [expected_url]+ assert response.primary_keys == expected_primary_keysmanager.can_resume.assert_called_once()+ def test_unknown_version_is_rejected(self) -> None:+ with pytest.raises(ValueError, match="Unsupported BuildBetter API version"):+ buildbetter_source(+ api_key="key",+ endpoint_name="interviews",+ api_version="v2",+ logger=MagicMock(),+ resumable_source_manager=_make_manager(),+ )++ @parameterized.expand(+ [+ ("v1", "v1", {"interviews", "interview_attendees", "interview_sentences", "extractions"}),+ ("v3", "v3", {"extractions"}),+ ]+ )+ def test_incremental_tables_per_version(self, _name: str, api_version: str, expected_incremental: set[str]) -> None:+ schemas = BuildBetterSource().get_schemas(MagicMock(), team_id=1, api_version=api_version)+ checked = {"interviews", "interview_attendees", "interview_sentences", "extractions"}++ assert {schema.name for schema in schemas if schema.supports_incremental} & checked == expected_incremental++ @parameterized.expand(+ [+ ("v1", "v1", "post", BUILDBETTER_API_URL, {"data": {"interview": [{"id": 1}]}}),+ ("v3", "v3", "get", f"{BUILDBETTER_REST_API_URL}/recordings", _recordings_page(["rec-1"])),+ ]+ )+ def test_validate_credentials_probes_the_pinned_api(+ self, _name: str, api_version: str, method: str, expected_url: str, payload: dict+ ) -> None:+ with patch(REST_PATCH) as session_cls:+ session = session_cls.return_value+ getattr(session, method).return_value = _make_response(payload)++ assert validate_credentials("key", api_version) == (True, None)++ assert getattr(session, method).call_args.args[0] == expected_url+class TestBuildBetterSourceNonRetryableErrors:def setup_method(self) -> None: