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(buildbetter): sync attendees, transcripts, topics and documents (#100156)

Tom Owers8b7fcf102a03
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 b7dc6aeb425d..fd1b12750977 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
@@ -1048,14 +1048,14 @@ Note: Pulled the raw API Blueprint (384KB) behind the Apiary docs. It self-decla
## BuildBetter — gaps
-Today (4): `companies`, `extractions`, `interviews`, `persons`
+Today (8): `companies`, `documents`, `extraction_topics`, `extractions`, `interview_attendees`, `interview_sentences`, `interviews`, `persons`
Diffed against: <https://docs.buildbetter.ai/pages/api/data-access.md>
-- [ ] `document` — Documents are named as one of the three core data models alongside calls and signals, and are the AI-generated output most teams want to analyze (high)
-- [ ] `interview.attendees (attendee/person join)` — membership table linking interviews we already sync to persons we already sync — currently no way to join calls to participants (high)
-- [ ] `interview.sentences / transcript_segments (REST /recordings/{id}/transcript)` — sentence-level transcript rows with speaker and timing; the raw text behind every call (high)
-- [ ] `extraction.topics (topic)` — lookup table resolving the topic IDs attached to extractions we already sync (high)
+- [x] `document` — Documents are named as one of the three core data models alongside calls and signals, and are the AI-generated output most teams want to analyze (high)
+- [x] `interview.attendees (attendee/person join)` — membership table linking interviews we already sync to persons we already sync — currently no way to join calls to participants (high)
+- [x] `interview.sentences / transcript_segments (REST /recordings/{id}/transcript)` — sentence-level transcript rows with speaker and timing; the raw text behind every call (high)
+- [x] `extraction.topics (topic)` — lookup table resolving the topic IDs attached to extractions we already sync (high)
- [ ] `extraction.types / interview.type (call and signal type)` — lookup tables resolving the type IDs carried on interviews and extractions (high)
- [ ] `tag (interview tags)` — lookup for the tag references on calls, needed for any segmentation by tag (medium)
- [ ] `recordings` — REST recording resource with public UUID, duration, source, and transcript_status — the supported successor to the interview asset fields (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/buildbetter.py
index d185121197cf..106bf6f8d4f6 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.buildbette
BUILDBETTER_API_URL,
BUILDBETTER_ENDPOINTS,
BuildBetterEndpointConfig,
+ BuildBetterNestedConfig,
)
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.resumable import ResumableSourceManager
@@ -109,8 +110,43 @@ def _execute_query(
return payload
+def _flatten_nested_rows(nested: BuildBetterNestedConfig, parent_rows: list[dict]) -> list[dict]:
+ rows: list[dict] = []
+ for parent in parent_rows:
+ parent_columns = {column: parent.get(parent_field) for parent_field, column in nested.parent_columns.items()}
+ for index, child in enumerate(parent.get(nested.nested_field) or []):
+ row = dict(child)
+ if nested.unwrap_field:
+ inner = row.pop(nested.unwrap_field, None)
+ if not inner:
+ # Without the wrapped record the row has no key columns to merge on
+ continue
+ row = {f"{nested.unwrap_prefix}{key}": value for key, value in inner.items()} | row
+ if nested.index_column:
+ row[nested.index_column] = index
+ rows.append(parent_columns | row)
+ return rows
+
+
+def _filter_field(endpoint_config: BuildBetterEndpointConfig, incremental_field: str) -> str:
+ """Map a row's incremental column back to the field the filter applies to.
+
+ A nested table's rows carry the parent's timestamps under a prefixed column name, but the
+ `where` clause filters the parent query, which knows them by their own names.
+ """
+ nested = endpoint_config.nested
+ if nested is None:
+ return incremental_field
+
+ for parent_field, column in nested.parent_columns.items():
+ if column == incremental_field:
+ return parent_field
+ return incremental_field
+
+
def _initial_variables(
endpoint_name: str,
+ endpoint_config: BuildBetterEndpointConfig,
page_size: int,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[BuildBetterResumeConfig],
@@ -128,7 +164,7 @@ def _initial_variables(
}
if incremental_field and incremental_field_last_value:
- variables["where"] = {incremental_field: {"_gt": incremental_field_last_value}}
+ variables["where"] = {_filter_field(endpoint_config, incremental_field): {"_gt": incremental_field_last_value}}
return variables
@@ -158,6 +194,7 @@ def _make_paginated_request(
variables = _initial_variables(
endpoint_name=endpoint_name,
+ endpoint_config=endpoint_config,
page_size=page_size,
logger=logger,
resumable_source_manager=resumable_source_manager,
@@ -181,7 +218,9 @@ def _make_paginated_request(
if not data:
break
- yield data
+ rows = _flatten_nested_rows(endpoint_config.nested, data) if endpoint_config.nested else data
+ if rows:
+ yield rows
if len(data) < page_size:
break
@@ -221,7 +260,7 @@ def buildbetter_source(
return SourceResponse(
items=get_rows,
- primary_keys=[endpoint_config.primary_key],
+ primary_keys=endpoint_config.primary_keys,
name=endpoint_name,
partition_count=endpoint_config.partition_count,
partition_size=endpoint_config.partition_size,
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.py
index cfff4caaed33..9eefa9150abf 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
@@ -41,6 +41,32 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"tags": "Tags applied to the interview.",
},
},
+ "interview_attendees": {
+ "description": "A person who attended an interview, linking an interview to the person who took part in it.",
+ "docs_url": "https://docs.buildbetter.ai/pages/api/data-access.md",
+ "columns": {
+ "interview_id": "Identifier of the interview the person attended.",
+ "interview_created_at": "Time at which the interview record was created.",
+ "interview_updated_at": "Time at which the interview record was last updated.",
+ "id": "Unique identifier of the attendee record.",
+ "speaker": "Speaker label the attendee was assigned in the transcript.",
+ "person": "The person who attended, with their name, email and title.",
+ },
+ },
+ "interview_sentences": {
+ "description": "A single sentence of an interview transcript, with its speaker and timing.",
+ "docs_url": "https://docs.buildbetter.ai/pages/api/data-access.md",
+ "columns": {
+ "interview_id": "Identifier of the interview the sentence was spoken in.",
+ "interview_created_at": "Time at which the interview record was created.",
+ "interview_updated_at": "Time at which the interview record was last updated.",
+ "sentence_index": "Position of the sentence in the transcript, ordered by start time.",
+ "text": "Transcribed text of the sentence.",
+ "speaker": "Speaker the sentence is attributed to.",
+ "start_sec": "Start time of the sentence within the recording, in seconds.",
+ "end_sec": "End time of the sentence within the recording, in seconds.",
+ },
+ },
"extractions": {
"description": "An AI-extracted insight from an interview — a quote with sentiment, topics, and context.",
"docs_url": "https://docs.buildbetter.app/",
@@ -62,6 +88,32 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"keywords": "Keywords associated with the extraction.",
},
},
+ "extraction_topics": {
+ "description": "A topic assigned to an extraction, resolving the topics attached to an AI-extracted insight.",
+ "docs_url": "https://docs.buildbetter.ai/pages/api/data-access.md",
+ "columns": {
+ "extraction_id": "Identifier of the extraction the topic is assigned to.",
+ "extraction_created_at": "Time at which the extraction was created.",
+ "topic_id": "Unique identifier of the topic.",
+ "topic_text": "Text of the topic.",
+ },
+ },
+ "documents": {
+ "description": "An AI-generated document in BuildBetter, produced from calls or folders.",
+ "docs_url": "https://docs.buildbetter.ai/pages/api/data-access.md",
+ "columns": {
+ "id": "Unique identifier of the document.",
+ "name": "Name of the document.",
+ "status": "Generation status of the document: waiting, processing, completed or error.",
+ "content": "Generated content of the document.",
+ "permission": "Access permission level for the document: private or public.",
+ "created_at": "Time at which the document was created.",
+ "updated_at": "Time at which the document was last updated.",
+ "creator": "User who created the document.",
+ "template": "Template the document was generated from, if any.",
+ "input_data": "Calls or folders the document was generated from.",
+ },
+ },
"persons": {
"description": "A person tracked in BuildBetter — an interview participant or customer contact.",
"docs_url": "https://docs.buildbetter.app/",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/queries.py b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/queries.py
index 4b191bcf5456..16491fc28c5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/queries.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/buildbetter/queries.py
@@ -173,11 +173,117 @@ query PaginatedCompanies($limit: Int!, $offset: Int!, $where: company_bool_exp)
}
}"""
+INTERVIEW_ATTENDEES_QUERY = """
+query PaginatedInterviewAttendees($limit: Int!, $offset: Int!, $where: interview_bool_exp) {
+ interview(limit: $limit, offset: $offset, order_by: {updated_at: asc}, where: $where) {
+ id
+ created_at
+ updated_at
+ attendees {
+ id
+ speaker
+ person {
+ id
+ first_name
+ last_name
+ email
+ title
+ avatar_url
+ }
+ }
+ }
+}"""
+
+INTERVIEW_SENTENCES_QUERY = """
+query PaginatedInterviewSentences($limit: Int!, $offset: Int!, $where: interview_bool_exp) {
+ interview(limit: $limit, offset: $offset, order_by: {updated_at: asc}, where: $where) {
+ id
+ created_at
+ updated_at
+ sentences(order_by: {start_sec: asc}) {
+ text
+ speaker
+ start_sec
+ end_sec
+ }
+ }
+}"""
+
+EXTRACTION_TOPICS_QUERY = """
+query PaginatedExtractionTopics($limit: Int!, $offset: Int!, $where: extraction_bool_exp) {
+ extraction(limit: $limit, offset: $offset, order_by: {created_at: asc}, where: $where) {
+ id
+ created_at
+ topics {
+ topic {
+ id
+ text
+ }
+ }
+ }
+}"""
+
+# Document relations that the docs describe but the account's schema (role-dependent) may not
+# expose. Kept separate so they can be dropped when the API reports the field is unknown.
+DOCUMENT_PERMISSION_FIELD = """
+ permission"""
+
+DOCUMENT_TEMPLATE_FIELD = """
+ template {
+ id
+ name
+ description
+ }"""
+
+DOCUMENT_INPUT_DATA_FIELD = """
+ input_data {
+ call {
+ id
+ name
+ created_at
+ }
+ folder {
+ id
+ name
+ }
+ }"""
+
+DOCUMENTS_QUERY = (
+ """
+query PaginatedDocuments($limit: Int!, $offset: Int!, $where: document_bool_exp) {
+ document(limit: $limit, offset: $offset, order_by: {updated_at: asc}, where: $where) {
+ id
+ name
+ status
+ content
+ created_at
+ updated_at
+ creator {
+ id
+ person {
+ id
+ first_name
+ last_name
+ email
+ }
+ }"""
+ + DOCUMENT_PERMISSION_FIELD
+ + DOCUMENT_TEMPLATE_FIELD
+ + DOCUMENT_INPUT_DATA_FIELD
+ + """
+ }
+}"""
+)
+
VIEWER_QUERY = "{ interview(limit: 1) { id } }"
QUERIES: dict[str, str] = {
"interviews": INTERVIEWS_QUERY,
+ "interview_attendees": INTERVIEW_ATTENDEES_QUERY,
+ "interview_sentences": INTERVIEW_SENTENCES_QUERY,
"extractions": EXTRACTIONS_QUERY,
+ "extraction_topics": EXTRACTION_TOPICS_QUERY,
+ "documents": DOCUMENTS_QUERY,
"persons": PERSONS_QUERY,
"companies": COMPANIES_QUERY,
}
@@ -185,4 +291,9 @@ QUERIES: dict[str, str] = {
# endpoint -> {field name -> exact query block to drop when the account's schema lacks the field}
OPTIONAL_QUERY_FIELDS: dict[str, dict[str, str]] = {
"interviews": {"monologues": INTERVIEW_MONOLOGUES_FIELD},
+ "documents": {
+ "permission": DOCUMENT_PERMISSION_FIELD,
+ "template": DOCUMENT_TEMPLATE_FIELD,
+ "input_data": DOCUMENT_INPUT_DATA_FIELD,
+ },
}
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.py
index ad32616c9a49..db2d4d68fdf3 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
@@ -10,34 +10,58 @@ UPDATED_AT = "updated_at"
CREATED_AT = "created_at"
ID = "id"
+INTERVIEW_ID = "interview_id"
+INTERVIEW_CREATED_AT = "interview_created_at"
+INTERVIEW_UPDATED_AT = "interview_updated_at"
+EXTRACTION_ID = "extraction_id"
+EXTRACTION_CREATED_AT = "extraction_created_at"
+SENTENCE_INDEX = "sentence_index"
+TOPIC_ID = "topic_id"
+
BUILDBETTER_API_URL = "https://api.buildbetter.app/v1/graphql"
BUILDBETTER_DEFAULT_PAGE_SIZE = 1000
-INCREMENTAL_UPDATED_AT: list[IncrementalField] = [
- {
- "label": UPDATED_AT,
- "type": IncrementalFieldType.DateTime,
- "field": UPDATED_AT,
- "field_type": IncrementalFieldType.DateTime,
- },
-]
-
-INCREMENTAL_CREATED_AT: list[IncrementalField] = [
- {
- "label": CREATED_AT,
- "type": IncrementalFieldType.DateTime,
- "field": CREATED_AT,
- "field_type": IncrementalFieldType.DateTime,
- },
-]
-
-
-@dataclass
+
+def _incremental_datetime_field(name: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+INCREMENTAL_UPDATED_AT = _incremental_datetime_field(UPDATED_AT)
+INCREMENTAL_CREATED_AT = _incremental_datetime_field(CREATED_AT)
+INCREMENTAL_INTERVIEW_UPDATED_AT = _incremental_datetime_field(INTERVIEW_UPDATED_AT)
+INCREMENTAL_EXTRACTION_CREATED_AT = _incremental_datetime_field(EXTRACTION_CREATED_AT)
+
+
+@dataclass(frozen=True)
+class BuildBetterNestedConfig:
+ """A table built from a nested relation of a parent query, one row per nested item.
+
+ BuildBetter exposes attendees, transcript sentences and extraction topics only as relations
+ of `interview` / `extraction`, so these tables page their parent query and flatten the
+ relation, carrying the parent's identifier and timestamps onto every row.
+ """
+
+ nested_field: str
+ parent_columns: dict[str, str]
+ unwrap_field: str | None = None
+ unwrap_prefix: str = ""
+ index_column: str | None = None
+
+
+@dataclass(frozen=True)
class BuildBetterEndpointConfig:
incremental_fields: list[IncrementalField]
graphql_query_name: str | None = None
page_size: int = BUILDBETTER_DEFAULT_PAGE_SIZE
- primary_key: str = ID
+ primary_keys: list[str] = field(default_factory=lambda: [ID])
+ nested: BuildBetterNestedConfig | None = None
partition_count: int = 1
partition_size: int = 1
partition_mode: PartitionMode | None = "datetime"
@@ -45,6 +69,12 @@ class BuildBetterEndpointConfig:
partition_keys: list[str] | None = field(default_factory=lambda: [CREATED_AT])
+INTERVIEW_PARENT_COLUMNS = {
+ ID: INTERVIEW_ID,
+ CREATED_AT: INTERVIEW_CREATED_AT,
+ UPDATED_AT: INTERVIEW_UPDATED_AT,
+}
+
BUILDBETTER_ENDPOINTS: dict[str, BuildBetterEndpointConfig] = {
"interviews": BuildBetterEndpointConfig(
graphql_query_name="interview",
@@ -52,11 +82,55 @@ BUILDBETTER_ENDPOINTS: dict[str, BuildBetterEndpointConfig] = {
page_size=100,
partition_keys=[CREATED_AT],
),
+ "interview_attendees": BuildBetterEndpointConfig(
+ graphql_query_name="interview",
+ incremental_fields=INCREMENTAL_INTERVIEW_UPDATED_AT,
+ page_size=100,
+ primary_keys=[INTERVIEW_ID, ID],
+ nested=BuildBetterNestedConfig(
+ nested_field="attendees",
+ parent_columns=INTERVIEW_PARENT_COLUMNS,
+ ),
+ partition_keys=[INTERVIEW_CREATED_AT],
+ ),
+ "interview_sentences": BuildBetterEndpointConfig(
+ graphql_query_name="interview",
+ incremental_fields=INCREMENTAL_INTERVIEW_UPDATED_AT,
+ page_size=25,
+ # The API exposes no sentence identifier, so a sentence is keyed by its position in the
+ # transcript, which the query orders by start time.
+ primary_keys=[INTERVIEW_ID, SENTENCE_INDEX],
+ nested=BuildBetterNestedConfig(
+ nested_field="sentences",
+ parent_columns=INTERVIEW_PARENT_COLUMNS,
+ index_column=SENTENCE_INDEX,
+ ),
+ partition_keys=[INTERVIEW_CREATED_AT],
+ ),
"extractions": BuildBetterEndpointConfig(
graphql_query_name="extraction",
incremental_fields=INCREMENTAL_CREATED_AT,
partition_keys=[CREATED_AT],
),
+ "extraction_topics": BuildBetterEndpointConfig(
+ graphql_query_name="extraction",
+ incremental_fields=INCREMENTAL_EXTRACTION_CREATED_AT,
+ page_size=500,
+ primary_keys=[EXTRACTION_ID, TOPIC_ID],
+ nested=BuildBetterNestedConfig(
+ nested_field="topics",
+ parent_columns={ID: EXTRACTION_ID, CREATED_AT: EXTRACTION_CREATED_AT},
+ unwrap_field="topic",
+ unwrap_prefix="topic_",
+ ),
+ partition_keys=[EXTRACTION_CREATED_AT],
+ ),
+ "documents": BuildBetterEndpointConfig(
+ graphql_query_name="document",
+ incremental_fields=INCREMENTAL_UPDATED_AT,
+ page_size=100,
+ partition_keys=[CREATED_AT],
+ ),
"persons": BuildBetterEndpointConfig(
graphql_query_name="person",
incremental_fields=INCREMENTAL_UPDATED_AT,
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.py
index 175bf5066293..96c9e7b1a708 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
@@ -117,7 +117,7 @@ class BuildBetterSource(ResumableSource[BuildBetterSourceConfig, BuildBetterResu
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="BuildBetter",
releaseStatus=ReleaseStatus.GA,
- caption="Connect your BuildBetter workspace to sync interviews, extractions, persons, and companies.",
+ caption="Connect your BuildBetter workspace to sync interviews, transcripts, extractions, documents, persons, and companies.",
iconPath="/static/services/buildbetter.png",
fields=cast(
list[FieldType],
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.py
index 54b718f940ce..eb7cd6cd4bd7 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
@@ -193,29 +193,228 @@ class TestMakePaginatedRequest:
)
)
- def test_incremental_filter_passes_where_clause(self) -> None:
+ @parameterized.expand(
+ [
+ ("top_level", "interviews", "updated_at", "updated_at"),
+ # A nested table's rows carry the parent timestamp under a prefixed column, but the
+ # filter has to name the field the parent query knows
+ ("nested_interview", "interview_attendees", "interview_updated_at", "updated_at"),
+ ("nested_extraction", "extraction_topics", "extraction_created_at", "created_at"),
+ ]
+ )
+ def test_incremental_filter_passes_where_clause(
+ self, _name: str, endpoint_name: str, incremental_field: str, expected_filter_field: str
+ ) -> None:
manager = _make_manager(can_resume=False)
logger = MagicMock()
+ query_name = BUILDBETTER_ENDPOINTS[endpoint_name].graphql_query_name
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.buildbetter.buildbetter.make_tracked_session"
) as session_cls:
session = session_cls.return_value
- session.post.return_value = _make_response({"data": {"interview": []}})
+ session.post.return_value = _make_response({"data": {query_name: []}})
list(
_make_paginated_request(
api_key="key",
- endpoint_name="interviews",
+ endpoint_name=endpoint_name,
logger=logger,
resumable_source_manager=manager,
- incremental_field="updated_at",
+ incremental_field=incremental_field,
incremental_field_last_value="2026-01-01",
)
)
call = session.post.call_args_list[0]
- assert call.kwargs["json"]["variables"]["where"] == {"updated_at": {"_gt": "2026-01-01"}}
+ assert call.kwargs["json"]["variables"]["where"] == {expected_filter_field: {"_gt": "2026-01-01"}}
+
+
+class TestNestedEndpoints:
+ @parameterized.expand(
+ [
+ (
+ "interview_attendees",
+ "interview_attendees",
+ {
+ "interview": [
+ {
+ "id": 1,
+ "created_at": "2026-01-01",
+ "updated_at": "2026-01-02",
+ "attendees": [
+ {"id": 10, "speaker": "Speaker 1", "person": {"id": 100, "email": "[email protected]"}},
+ {"id": 11, "speaker": "Speaker 2", "person": None},
+ ],
+ }
+ ]
+ },
+ [
+ {
+ "interview_id": 1,
+ "interview_created_at": "2026-01-01",
+ "interview_updated_at": "2026-01-02",
+ "id": 10,
+ "speaker": "Speaker 1",
+ "person": {"id": 100, "email": "[email protected]"},
+ },
+ {
+ "interview_id": 1,
+ "interview_created_at": "2026-01-01",
+ "interview_updated_at": "2026-01-02",
+ "id": 11,
+ "speaker": "Speaker 2",
+ "person": None,
+ },
+ ],
+ ),
+ (
+ "interview_sentences",
+ "interview_sentences",
+ {
+ "interview": [
+ {
+ "id": 2,
+ "created_at": "2026-01-01",
+ "updated_at": "2026-01-02",
+ "sentences": [
+ {"text": "First", "speaker": "Speaker 1", "start_sec": 0, "end_sec": 2},
+ {"text": "Second", "speaker": "Speaker 2", "start_sec": 2, "end_sec": 4},
+ ],
+ }
+ ]
+ },
+ [
+ {
+ "interview_id": 2,
+ "interview_created_at": "2026-01-01",
+ "interview_updated_at": "2026-01-02",
+ "text": "First",
+ "speaker": "Speaker 1",
+ "start_sec": 0,
+ "end_sec": 2,
+ "sentence_index": 0,
+ },
+ {
+ "interview_id": 2,
+ "interview_created_at": "2026-01-01",
+ "interview_updated_at": "2026-01-02",
+ "text": "Second",
+ "speaker": "Speaker 2",
+ "start_sec": 2,
+ "end_sec": 4,
+ "sentence_index": 1,
+ },
+ ],
+ ),
+ (
+ "extraction_topics",
+ "extraction_topics",
+ {
+ "extraction": [
+ {
+ "id": 3,
+ "created_at": "2026-01-03",
+ "topics": [{"topic": {"id": 7, "text": "Pricing"}}],
+ },
+ {"id": 4, "created_at": "2026-01-04", "topics": []},
+ # A topic reference the API resolves to nothing has no key columns
+ {"id": 5, "created_at": "2026-01-05", "topics": [{"topic": None}]},
+ ]
+ },
+ [
+ {
+ "extraction_id": 3,
+ "extraction_created_at": "2026-01-03",
+ "topic_id": 7,
+ "topic_text": "Pricing",
+ },
+ ],
+ ),
+ ]
+ )
+ def test_flattens_nested_rows_with_parent_columns(
+ self, _name: str, endpoint_name: str, payload: dict, expected_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:
+ session = session_cls.return_value
+ session.post.return_value = _make_response({"data": payload})
+
+ batches = list(
+ _make_paginated_request(
+ api_key="key",
+ endpoint_name=endpoint_name,
+ logger=logger,
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert batches == [expected_rows]
+ # Every row has to carry its whole primary key, otherwise merges collapse or duplicate rows
+ for row in expected_rows:
+ assert all(key in row for key in BUILDBETTER_ENDPOINTS[endpoint_name].primary_keys)
+
+ def test_page_without_nested_rows_keeps_paginating(self) -> None:
+ page_size = BUILDBETTER_ENDPOINTS["interview_sentences"].page_size
+ empty_page = {
+ "data": {
+ "interview": [
+ {"id": i, "created_at": "c", "updated_at": "u", "sentences": []} for i in range(page_size)
+ ]
+ }
+ }
+ tail_page = {
+ "data": {
+ "interview": [
+ {
+ "id": 99,
+ "created_at": "c",
+ "updated_at": "u",
+ "sentences": [{"text": "Hello", "speaker": "Speaker 1", "start_sec": 0, "end_sec": 1}],
+ }
+ ]
+ }
+ }
+
+ 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:
+ session = session_cls.return_value
+ session.post.side_effect = [_make_response(empty_page), _make_response(tail_page)]
+
+ batches = list(
+ _make_paginated_request(
+ api_key="key",
+ endpoint_name="interview_sentences",
+ logger=logger,
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert session.post.call_count == 2
+ assert session.post.call_args_list[1].kwargs["json"]["variables"]["offset"] == page_size
+ assert batches == [
+ [
+ {
+ "interview_id": 99,
+ "interview_created_at": "c",
+ "interview_updated_at": "u",
+ "text": "Hello",
+ "speaker": "Speaker 1",
+ "start_sec": 0,
+ "end_sec": 1,
+ "sentence_index": 0,
+ }
+ ]
+ ]
class TestBuildbetterSource: