: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 3 missing tables to the Roark source (#116577)
Tom Owersa901e35bb176
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 e2b09f5a68c6..cad3c59a3f96 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@@ -10253,10 +10253,10 @@ Today (12): `agent`, `agent_endpoint`, `call`, `chat`, `issue`, `knowledge_base`Diffed against: <https://docs.roark.ai/llms.txt>-- [ ] `call/list-call-metrics (GET /calls/{id}/metrics)` — the scored per-call metric values - the product's headline output and the only numeric quality data (high)-- [ ] `metric-collection-job/get-metric-values-produced-by-a-metric-collection-job` — metric values per collection job, giving metric history over time rather than only the latest run (high)+- [x] `call/list-call-metrics (GET /calls/{id}/metrics)` — the scored per-call metric values - the product's headline output and the only numeric quality data (high)+- [x] `metric-collection-job/get-metric-values-produced-by-a-metric-collection-job` — metric values per collection job, giving metric history over time rather than only the latest run (high)- [ ] `call/list-call-evaluation-runs` — pass/fail evaluation results per call, the row grain quality dashboards are built on (high)-- [ ] `call/get-call-transcript` — turn-level transcript for the calls already synced; enables text and duration analysis (high)+- [x] `call/get-call-transcript` — turn-level transcript for the calls already synced; enables text and duration analysis (high)- [ ] `call/list-call-sentiment-runs` — sentiment scores and key phrases per call, a standard breakdown dimension (high)- [ ] `chat/list-chat-metrics` — the chat-channel equivalent of call metrics; chats are synced but their scores are not (medium)- [ ] `chat/get-chat-transcript` — message-level content under the chats already synced (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/canonical_descriptions.pyindex 4103d8f8d305..64d895d7691a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/canonical_descriptions.py@@ -229,4 +229,51 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updatedAt": "Timestamp when the knowledge base was last updated.",},},+ "call_metric": {+ "description": "The latest metric values of a call, one row per metric definition. Only successfully computed values are included.",+ "docs_url": "https://docs.roark.ai/api-reference/call/list-call-metrics",+ "columns": {+ "callId": "Identifier of the call the metric was computed on.",+ "metricDefinitionId": "Unique identifier of the metric definition.",+ "slug": "Stable slug of the metric.",+ "metricId": "Alias of `slug`, kept for backwards compatibility.",+ "name": "Name of the metric.",+ "description": "Description of what the metric measures.",+ "type": "Type of value the metric produces: COUNT, NUMERIC, BOOLEAN, SCALE, TEXT, CLASSIFICATION, or OFFSET.",+ "scope": "Whether the metric is GLOBAL or PER_PARTICIPANT.",+ "unit": "Unit of the metric (name and symbol), when it has one.",+ "values": "The metric value entries: one per participant for PER_PARTICIPANT metrics, or one per segment. Each entry carries the value, capture status, context, confidence, reasoning, and the time it was computed.",+ },+ },+ "call_transcript": {+ "description": "The transcript of a call, one row per transcript entry, from the best available transcription source.",+ "docs_url": "https://docs.roark.ai/api-reference/call/get-call-transcript",+ "columns": {+ "callId": "Identifier of the call the entry belongs to.",+ "entryIndex": "Zero-based position of the entry in the transcript.",+ "transcriptionSource": "Transcription source of the transcript: ROARK_POST_CALL, SIMULATION_AGENT_REALTIME, or CUSTOMER_AGENT_REALTIME.",+ "participantId": "Identifier of the conversation participant who produced the entry.",+ "participant": "The participant who produced the entry, with its type and its agent or customer identifier.",+ "role": "Role derived from the participant type: AGENT or CUSTOMER.",+ "text": "Transcript text of the entry.",+ "startOffsetMs": "Start of the entry, in milliseconds from the start of the conversation.",+ "endOffsetMs": "End of the entry, in milliseconds from the start of the conversation.",+ },+ },+ "metric_collection_job_metric_value": {+ "description": "The metric values that a metric collection job produced, one row per metric definition per job. Unlike call metrics, this keeps the values of earlier jobs after a metric is recomputed.",+ "docs_url": "https://docs.roark.ai/api-reference/metric-collection-job/get-metric-values-produced-by-a-metric-collection-job",+ "columns": {+ "jobId": "Identifier of the metric collection job that produced the values.",+ "metricDefinitionId": "Unique identifier of the metric definition.",+ "slug": "Stable slug of the metric.",+ "metricId": "Alias of `slug`, kept for backwards compatibility.",+ "name": "Name of the metric.",+ "description": "Description of what the metric measures.",+ "type": "Type of value the metric produces: COUNT, NUMERIC, BOOLEAN, SCALE, TEXT, CLASSIFICATION, or OFFSET.",+ "scope": "Whether the metric is GLOBAL or PER_PARTICIPANT.",+ "unit": "Unit of the metric (name and symbol), when it has one.",+ "values": "The metric value entries the job produced. Each entry carries the `callId` or `chatId` it was computed on, the value, capture status, context, confidence, reasoning, and the time it was computed.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/roark.py b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/roark.pyindex 9edbcce6853b..f02c30ec5873 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/roark.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/roark.py@@ -8,11 +8,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,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,SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,Endpoint,EndpointResource,)@@ -27,7 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.roark.settROARK_BASE_URL = "https://api.roark.ai/v1"[email protected](frozen=True)class RoarkResumeConfig:# Cursor (`after`) pointing at the next page to fetch for the cursor-paginated endpoints. `None`# means "start at the first page". Saved after a page is yielded so a crash resumes from the next@@ -35,6 +39,8 @@ class RoarkResumeConfig:after: str | None = None# Offset of the next page to fetch for the offset-paginated endpoints.offset: int | None = None+ # Child paths already fetched, for the endpoints that make one request per parent row.+ completed: list[str] | None = Noneclass RoarkCursorPaginator(BasePaginator):@@ -148,6 +154,86 @@ def _base_params(config: RoarkEndpointConfig) -> dict[str, Any]:return params+def _explode_transcript(item: dict[str, Any]) -> list[dict[str, Any]]:+ """Reshape one call transcript into one row per entry, in spoken order."""+ participants = {p.get("id"): p for p in item.get("participants") or [] if isinstance(p, dict)}+ return [+ {+ **entry,+ "callId": item.get("callId"),+ "entryIndex": index,+ "transcriptionSource": item.get("transcriptionSource"),+ "participant": participants.get(entry.get("participantId")),+ }+ for index, entry in enumerate(item.get("entries") or [])+ if isinstance(entry, dict)+ ]+++def _source_response(config: RoarkEndpointConfig, resource: Any) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ sort_mode=config.sort_mode,+ 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,+ column_hints=resource.column_hints,+ )+++def _fanout_source(+ config: RoarkEndpointConfig,+ api_key: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[RoarkResumeConfig],+) -> SourceResponse:+ assert config.fanout is not None+ parent_config = ROARK_ENDPOINTS[config.fanout.parent_name]++ client_config: ClientConfig = {+ "base_url": ROARK_BASE_URL,+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ }++ initial_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.completed:+ initial_state = {"completed": resume.completed, "current": None, "child_state": None}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Every child endpoint is a single page, so the completed parents are the whole state.+ if state is not None:+ resumable_source_manager.save_state(RoarkResumeConfig(completed=state.get("completed")))++ resource: Any = build_dependent_resource(+ endpoint_configs=ROARK_ENDPOINTS,+ child_endpoint=config.name,+ fanout=dataclasses.replace(config.fanout, parent_params=_base_params(parent_config)),+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra={"paginator": RoarkCursorPaginator(), "data_selector": "data"},+ child_endpoint_extra={"paginator": SinglePagePaginator(), "data_selector": "data"},+ # The parent params carry the page size, and the child endpoints accept none.+ page_size_param=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ )+ if config.name == "call_transcript":+ resource = resource.add_map(_explode_transcript)++ return _source_response(config, resource)++def roark_source(api_key: str,endpoint: str,@@ -158,6 +244,9 @@ def roark_source() -> SourceResponse:config = ROARK_ENDPOINTS[endpoint]+ if config.fanout is not None:+ return _fanout_source(config, api_key, team_id, job_id, resumable_source_manager)+paginator: BasePaginatordata_selector: Optional[str]data_map = None@@ -224,18 +313,7 @@ def roark_source(initial_paginator_state=initial_paginator_state,)- return SourceResponse(- name=endpoint,- items=lambda: resource,- primary_keys=config.primary_keys,- sort_mode=config.sort_mode,- 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,- column_hints=resource.column_hints,- )+ return _source_response(config, resource)def validate_credentials(api_key: str) -> bool:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/settings.pyindex 803ef2c5816d..267814eafc54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/settings.py@@ -1,7 +1,12 @@from dataclasses import dataclass, fieldfrom typing import Literal, Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseActionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField# Roark exposes no server-side timestamp filter on any list endpoint (only client-side `sortBy`# ordering plus an opaque `after` cursor), so every table syncs as a full refresh. Incremental sync@@ -9,7 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typPaginationMode = Literal["cursor", "offset", "none"]-@dataclass+@dataclass(frozen=True)class RoarkEndpointConfig:name: strpath: str@@ -29,6 +34,36 @@ class RoarkEndpointConfig:# `issue` is fixed newest-first by the API and can't be reordered.sort_mode: SortMode = "asc"should_sync_default: bool = True+ # Set on a child endpoint that is fetched once per row of a parent endpoint.+ fanout: Optional[DependentEndpointConfig] = None++ # The shared fan-out helper reads these three members from every endpoint config.+ @property+ def page_size(self) -> int:+ return self.max_page_size++ @property+ def incremental_fields(self) -> list[IncrementalField]:+ return []++ @property+ def default_incremental_field(self) -> Optional[str]:+ return None+++# A parent row deleted between the parent listing and the child request answers 404; skip it.+_SKIP_MISSING_PARENT: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]+++def _per_call() -> DependentEndpointConfig:+ return DependentEndpointConfig(+ parent_name="call",+ resolve_param="callId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "callId"},+ child_response_actions=_SKIP_MISSING_PARENT,+ )ROARK_ENDPOINTS: dict[str, RoarkEndpointConfig] = {@@ -115,6 +150,45 @@ ROARK_ENDPOINTS: dict[str, RoarkEndpointConfig] = {pagination="cursor",partition_key="createdAt",),+ # The three endpoints below make one request per parent row on every sync, so they are off by+ # default. None of them is paginated, and none has a server-side time filter.+ "call_metric": RoarkEndpointConfig(+ name="call_metric",+ path="/call/{callId}/metrics",+ pagination="none",+ max_page_size=0,+ # One row per metric definition per call; the scored values stay nested under `values`+ # because `value` is a number, a boolean or a string depending on the metric type.+ primary_keys=["callId", "metricDefinitionId"],+ should_sync_default=False,+ fanout=_per_call(),+ ),+ "call_transcript": RoarkEndpointConfig(+ name="call_transcript",+ path="/call/{callId}/transcript",+ pagination="none",+ max_page_size=0,+ # Transcript entries carry no id, so a row is keyed on its position in the call.+ primary_keys=["callId", "entryIndex"],+ should_sync_default=False,+ fanout=_per_call(),+ ),+ "metric_collection_job_metric_value": RoarkEndpointConfig(+ name="metric_collection_job_metric_value",+ path="/metric/collection-jobs/{jobId}/metric-values",+ pagination="none",+ max_page_size=0,+ primary_keys=["jobId", "metricDefinitionId"],+ should_sync_default=False,+ fanout=DependentEndpointConfig(+ parent_name="metric_collection_job",+ resolve_param="jobId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "jobId"},+ child_response_actions=_SKIP_MISSING_PARENT,+ ),+ ),}ENDPOINTS = tuple(ROARK_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/tests/test_roark.py b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/tests/test_roark.pyindex cb4c3196bf50..e02a9ba2c5eb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/roark/tests/test_roark.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/roark/tests/test_roark.py@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.roark import RoarkSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.roark.roark import (RoarkResumeConfig,+ _explode_transcript,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.roark.settings import ENDPOINTS, ROARK_ENDPOINTS@@ -109,6 +110,122 @@ class TestUnpaginated:assert [r["id"] for r in result.rows] == ["1", "2"]+class TestFanout:+ @parameterized.expand(+ [+ ("call_metric", "/v1/call", "callId", "/v1/call/{}/metrics", {"limit": "100", "sortBy": "createdAt"}),+ (+ "metric_collection_job_metric_value",+ "/v1/metric/collection-jobs",+ "jobId",+ "/v1/metric/collection-jobs/{}/metric-values",+ {"limit": "50", "sortBy": None},+ ),+ ]+ )+ def test_fetches_each_parent_and_skips_missing_ones(+ self, endpoint: str, parent_path: str, parent_column: str, child_path: str, parent_params: dict[str, str | None]+ ) -> None:+ metric = {"metricDefinitionId": "m1", "values": [{"value": 0.5, "captureStatus": "SUCCESS"}]}+ result = _driver().run(+ endpoint,+ [+ _cursor_page([{"id": "p1"}, {"id": "p2"}], has_more=True, next_cursor="c1"),+ _resp({"data": [metric, {"metricDefinitionId": "m2", "values": []}]}),+ _resp({"message": "Not found"}, status=404),+ _cursor_page([{"id": "p3"}], has_more=False),+ _resp({"data": []}),+ ],+ )++ assert result.raised is None+ assert result.rows == [+ {**metric, parent_column: "p1"},+ {"metricDefinitionId": "m2", "values": [], parent_column: "p1"},+ ]+ assert result.paths == [+ parent_path,+ child_path.format("p1"),+ child_path.format("p2"),+ parent_path,+ child_path.format("p3"),+ ]+ for name, value in parent_params.items():+ assert result.requests[0].param(name) == value+ assert result.requests[3].param("after") == "c1"+ # The child endpoints document no page size, so none is sent.+ assert result.requests[1].param("limit") is None+ # Saved child paths are relative to the base URL, which already carries `/v1`.+ assert result.saved_states[-1] == RoarkResumeConfig(+ completed=[child_path.format(p).removeprefix("/v1") for p in ("p1", "p2", "p3")]+ )++ def test_transcript_yields_one_row_per_entry(self) -> None:+ entries: list[dict[str, Any]] = [+ {"participantId": "pa", "role": "AGENT", "text": "Hello", "startOffsetMs": 0, "endOffsetMs": 900},+ {"participantId": None, "role": None, "text": "(noise)", "startOffsetMs": 900, "endOffsetMs": 1200},+ ]+ agent = {"id": "pa", "type": "AGENT", "agentId": "agent-1"}+ result = _driver().run(+ "call_transcript",+ [+ _cursor_page([{"id": "c1"}, {"id": "c2"}, {"id": "c3"}], has_more=False),+ _resp(+ {"data": {"transcriptionSource": "ROARK_POST_CALL", "participants": [agent], "entries": entries}}+ ),+ # A call with no transcript answers with a null source and no entries.+ _resp({"data": {"transcriptionSource": None, "participants": [], "entries": []}}),+ _resp({"data": {"transcriptionSource": "ROARK_POST_CALL", "participants": [], "entries": entries[:1]}}),+ ],+ )++ assert result.raised is None+ assert result.rows == [+ {+ **entries[0],+ "callId": "c1",+ "entryIndex": 0,+ "transcriptionSource": "ROARK_POST_CALL",+ "participant": agent,+ },+ {+ **entries[1],+ "callId": "c1",+ "entryIndex": 1,+ "transcriptionSource": "ROARK_POST_CALL",+ "participant": None,+ },+ {+ **entries[0],+ "callId": "c3",+ "entryIndex": 0,+ "transcriptionSource": "ROARK_POST_CALL",+ "participant": None,+ },+ ]++ def test_transcript_skips_malformed_entries(self) -> None:+ rows = _explode_transcript(+ {"callId": "c1", "participants": [None], "entries": [None, {"participantId": "pa", "text": "Hi"}]}+ )++ assert [(row["callId"], row["entryIndex"], row["text"]) for row in rows] == [("c1", 1, "Hi")]++ def test_resume_skips_completed_parents(self) -> None:+ result = _driver().run(+ "call_metric",+ [+ _cursor_page([{"id": "p1"}, {"id": "p2"}], has_more=False),+ _resp({"data": [{"metricDefinitionId": "m1", "values": []}]}),+ ],+ resume_state=RoarkResumeConfig(completed=["/call/p1/metrics"]),+ )++ assert result.raised is None+ assert [row["callId"] for row in result.rows] == ["p2"]+ assert result.paths == ["/v1/call", "/v1/call/p2/metrics"]++class TestRetryAndFailLoud:@parameterized.expand([("throttled", 429), ("server_error", 500), ("unavailable", 503)])def test_retryable_status_is_reissued_then_recovers(self, _name: str, status: int) -> None: