: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 5 missing tables to the Cursor source (#120030)
Tom Owers447088334d0e
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 aa9fb4c43a61..75690baa1a73 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@@ -3460,11 +3460,11 @@ Diffed against: <https://cursor.com/docs/account/teams/analytics-api.md>- [x] `GET /analytics/team/agent-edits` — agent edit volume - the primary productivity measure for agent usage (high)- [x] `GET /analytics/team/tabs` — tab-completion acceptance metrics, the other half of core usage (high)- [x] `GET /analytics/by-user/{agent-edits,tabs,models,top-file-extensions}` — per-user breakdowns joining directly to the members table we already sync (high)-- [ ] `GET /teams/groups and /teams/groups/{id}/members` — billing-group lookup and membership resolving the group IDs on member and spend rows (medium)+- [x] `GET /teams/groups and /teams/groups/{id}/members` — billing-group lookup and membership resolving the group IDs on member and spend rows (medium). Shipped as `billing_groups` and `billing_group_members`, both from `GET /teams/groups`, which returns each group's current and former members inline. `/teams/groups/{id}/members` has only POST and DELETE (full refresh)- [x] `GET /analytics/team/top-file-extensions` — language/file-type breakdown of AI usage (medium)-- [ ] `GET /analytics/team/bugbot and /analytics/team/bugbot-reviews` — code-review volume and per-review analytics for the Bugbot product (medium)-- [ ] `GET /analytics/team/conversation-insights` — aggregated conversation topics and outcomes (medium)-- [ ] `GET /teams/audit-logs` — admin action history for access and compliance reporting (medium)+- [x] `GET /analytics/team/bugbot and /analytics/team/bugbot-reviews` — code-review volume and per-review analytics for the Bugbot product (medium). Shipped as `bugbot_reviews` (incremental on `timestamp`). `/analytics/team/bugbot` was not added: its per-PR review and issue counts cover only the requested range, so a row changes with the sync window and cannot merge across windows+- [x] `GET /analytics/team/conversation-insights` — aggregated conversation topics and outcomes (medium). Shipped as `conversation_insights`, one row per day per slice value from each slice's `timeSeries` (incremental on `date`). The range totals (`distribution`, `topValues`, `subcategories`) are left out because they change with the window+- [x] `GET /teams/audit-logs` — admin action history for access and compliance reporting (medium). Shipped as `audit_logs` (incremental on `timestamp`, 30-day `startTime`/`endTime` windows)Note: PostHog covers the four Admin API data endpoints (members, daily-usage-data, spend, filtered-usage-events) plus the agent-edits, tabs, dau, models and top-file-extensions team metrics, their four by-user breakdowns, and both AI Code Tracking grains (commits and changes). The adoption metrics (bugbot, conversation insights, leaderboard, mcp, commands, plans, skills, ask-mode, client-versions), the team groups and audit-log endpoints, and the Cloud Agents API are still unmapped. Admin API endpoints verified at https://cursor.com/docs/account/teams/admin-api.md and AI code tracking at https://cursor.com/docs/account/teams/ai-code-tracking-api.md. Repo blocklists and spend-limit endpoints excluded as configuration. Correcting the original sweep: every Analytics API and AI Code Tracking endpoint is a plain GET with query params, not a POST with a body, and the Analytics API caps a range at 30 inclusive calendar days.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.pyindex a6d7b01277dc..6a99292676d5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/canonical_descriptions.py@@ -260,4 +260,78 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"metadata": "Per-file breakdown of the change. The file name is omitted when the team has privacy mode on.",},},+ "audit_logs": {+ "description": "Audit log events for your Cursor team: logins, member changes, and settings changes.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "event_id": "Unique identifier for the audit log event.",+ "timestamp": "When the event happened.",+ "ip_address": "IP address the action came from.",+ "user_email": "Email address of the user who performed the action.",+ "event_type": "Type of the event, for example login or add_user.",+ "application_type": "Surface that produced the event: grok_bot, cursor, or empty when unknown.",+ "event_data": "Fields specific to the event type.",+ },+ },+ "billing_groups": {+ "description": "Billing groups of your Cursor team with their spend for the current billing cycle.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "id": "Encoded billing group ID, with the group_ prefix.",+ "name": "Name of the billing group. Members in no group are in the reserved Unassigned group.",+ "type": "Group type, BILLING for billing groups.",+ "directoryGroupId": "ID of the directory group that the billing group syncs from, if any.",+ "memberCount": "Number of members in the group.",+ "spendCents": "Spend of the group in the billing cycle, in cents.",+ "dailySpend": "Spend of the group per day of the billing cycle, in cents.",+ "createdAt": "When the group was created.",+ "updatedAt": "When the group was last updated.",+ "billingCycleStart": "Start of the billing cycle that the spend covers.",+ "billingCycleEnd": "End of the billing cycle that the spend covers.",+ },+ },+ "billing_group_members": {+ "description": "Current and former members of each Cursor billing group, with their spend for the current billing cycle.",+ "docs_url": "https://cursor.com/docs/account/teams/admin-api",+ "columns": {+ "groupId": "Encoded ID of the billing group.",+ "groupName": "Name of the billing group.",+ "userId": "Public (encoded) Cursor user ID of the member.",+ "name": "Display name of the member.",+ "email": "Email address of the member.",+ "joinedAt": "When the member joined the group.",+ "leftAt": "When the member left the group, empty for current members.",+ "isCurrentMember": "Whether the user is a member of the group now.",+ "spendCents": "Spend of the member in the group during the billing cycle, in cents.",+ "billingCycleStart": "Start of the billing cycle that the spend covers.",+ "billingCycleEnd": "End of the billing cycle that the spend covers.",+ },+ },+ "bugbot_reviews": {+ "description": "Completed Bugbot reviews, one row per review, including posted and dry-run reviews.",+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",+ "columns": {+ "request_id": "Unique identifier for the review.",+ "timestamp": "When the review ran.",+ "repo": "Repository in host/owner/repo form.",+ "repo_node_id": "Node ID of the repository in the source control provider.",+ "pr_number": "Pull request or merge request number.",+ "commit_sha": "Commit that the review covered.",+ "bugs_found": "Number of findings in the review.",+ "cost_cents": "Billed cost of the review in cents, empty when the review is not billed separately.",+ "dry_run": "Whether the review was a dry run that posted nothing.",+ "publication_status": "Whether the review was posted or was a dry run.",+ "bugs": "Findings of the review, with severity and resolution status.",+ },+ },+ "conversation_insights": {+ "description": "Daily counts of team conversations in Cursor, grouped by intent, complexity, category, guidance level, and work type.",+ "docs_url": "https://cursor.com/docs/account/teams/analytics-api",+ "columns": {+ "date": "Day the counts are for.",+ "slice": "Insight dimension: intents, complexity, categories, guidanceLevels, or workTypes.",+ "value": "Value within the dimension, for example Write Code or high.",+ "count": "Number of conversations or conversation segments with this value on the day.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.pyindex d6f02a2fb48f..4739a209f8d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/cursor.py@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.cursor.settings import (+ CONVERSATION_INSIGHT_SLICES,CURSOR_ENDPOINTS,MAX_WINDOW_DAYS,CursorEndpointConfig,@@ -285,6 +286,68 @@ def _get_members_rows(yield rows+_normalize_billing_group = _make_iso_normalizer("createdAt", "updatedAt", "billingCycleStart", "billingCycleEnd")+_normalize_billing_group_member = _make_iso_normalizer("joinedAt", "leftAt", "billingCycleStart", "billingCycleEnd")+++def _all_billing_groups(data: dict[str, Any]) -> list[dict[str, Any]]:+ # Members in no group sit in a reserved `Unassigned` group the API returns apart from the rest.+ unassigned = data.get("unassignedGroup")+ return [*(data.get("groups") or []), *([unassigned] if isinstance(unassigned, dict) else [])]+++def _billing_group_rows(data: dict[str, Any]) -> list[dict[str, Any]]:+ cycle = data.get("billingCycle") or {}+ # Members land in billing_group_members, so leave the unbounded member lists out of the group row.+ return [+ _normalize_billing_group(+ {+ **{key: value for key, value in group.items() if key not in ("currentMembers", "formerMembers")},+ "billingCycleStart": cycle.get("cycleStart"),+ "billingCycleEnd": cycle.get("cycleEnd"),+ }+ )+ for group in _all_billing_groups(data)+ ]+++def _billing_group_member_rows(data: dict[str, Any]) -> list[dict[str, Any]]:+ cycle = data.get("billingCycle") or {}+ return [+ _normalize_billing_group_member(+ {+ **member,+ "groupId": group.get("id"),+ "groupName": group.get("name"),+ "isCurrentMember": is_current,+ "billingCycleStart": cycle.get("cycleStart"),+ "billingCycleEnd": cycle.get("cycleEnd"),+ }+ )+ for group in _all_billing_groups(data)+ for members_key, is_current in (("currentMembers", True), ("formerMembers", False))+ for member in group.get(members_key) or []+ ]+++_BILLING_GROUP_ROW_BUILDERS: dict[str, Callable[[dict[str, Any]], list[dict[str, Any]]]] = {+ "billing_groups": _billing_group_rows,+ "billing_group_members": _billing_group_member_rows,+}+++def _get_billing_group_rows(+ session: requests.Session,+ config: CursorEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ # The group listing carries every group's members inline, so both tables read the same response.+ data = _fetch(session, config.method, f"{CURSOR_BASE_URL}{config.path}", logger)+ rows = _BILLING_GROUP_ROW_BUILDERS[config.name](data)+ if rows:+ yield rows++def _get_spend_rows(session: requests.Session,config: CursorEndpointConfig,@@ -337,6 +400,9 @@ _WINDOWED_NORMALIZERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {"by_user_models": _make_iso_normalizer("date"),"ai_code_commits": _make_iso_normalizer("commitTs", "createdAt"),"ai_code_changes": _make_iso_normalizer("createdAt"),+ "audit_logs": _make_iso_normalizer("timestamp"),+ "bugbot_reviews": _make_iso_normalizer("timestamp"),+ "conversation_insights": _make_iso_normalizer("date"),}@@ -361,8 +427,41 @@ _ROW_EXPANDERS: dict[str, Callable[[dict[str, Any]], list[dict[str, Any]]]] = {}+def _conversation_insight_rows(payload: Any) -> list[dict[str, Any]]:+ """Flatten each slice's daily time series into one row per day per slice value.++ The distribution and top-value lists are totals over the requested range, so they change with+ the window and cannot merge across syncs. The daily points can.+ """+ if not isinstance(payload, dict):+ return []+ rows = []+ for slice_name, value_key in CONVERSATION_INSIGHT_SLICES.items():+ slice_data = payload.get(slice_name)+ if not isinstance(slice_data, dict):+ continue+ for point in slice_data.get("timeSeries") or []:+ rows.append(+ {+ "date": point.get("date"),+ "slice": slice_name,+ "value": point.get(value_key),+ "count": point.get("count"),+ }+ )+ return rows+++_PAYLOAD_EXTRACTORS: dict[str, Callable[[Any], list[dict[str, Any]]]] = {+ "conversation_insights": _conversation_insight_rows,+}++def _extract_rows(config: CursorEndpointConfig, data: dict[str, Any]) -> list[dict[str, Any]]:payload = data.get(config.data_key)+ extract = _PAYLOAD_EXTRACTORS.get(config.name)+ if extract:+ return extract(payload)expand = _ROW_EXPANDERS.get(config.name)if not config.by_user:rows = payload or []@@ -397,10 +496,12 @@ def _page_item_count(config: CursorEndpointConfig, data: dict[str, Any], rows: ldef _window_request_params(config: CursorEndpointConfig, window_start: int, window_end: int, page: int) -> dict[str, Any]:+ start_param, end_param = config.date_param_namesif config.date_param_format == "iso_date":- params: dict[str, Any] = {"startDate": _to_iso_date(window_start), "endDate": _to_iso_date(window_end)}+ params: dict[str, Any] = {start_param: _to_iso_date(window_start), end_param: _to_iso_date(window_end)}else:- params = {"startDate": window_start, "endDate": window_end}+ params = {start_param: window_start, end_param: window_end}+ params |= config.extra_paramsif config.paginated:params |= {"page": page, "pageSize": config.page_size}return params@@ -537,6 +638,8 @@ def cursor_source(if endpoint == "members":yield from _get_members_rows(session, config, logger)+ elif endpoint in _BILLING_GROUP_ROW_BUILDERS:+ yield from _get_billing_group_rows(session, config, logger)elif endpoint == "spend":yield from _get_spend_rows(session, config, logger, resumable_source_manager)else:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.pyindex eb14f6789f9c..18daacce4bbd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/settings.py@@ -11,6 +11,15 @@ MAX_WINDOW_DAYS = 30# truncated to a date. 29 is the largest window that always fits.ANALYTICS_MAX_WINDOW_DAYS = 29+# Conversation Insights slice name -> the key that holds the slice value in each time-series point.+CONVERSATION_INSIGHT_SLICES: dict[str, str] = {+ "intents": "intent",+ "complexity": "complexity",+ "categories": "category",+ "guidanceLevels": "guidanceLevel",+ "workTypes": "workType",+}+def _datetime_field(name: str) -> IncrementalField:return {@@ -37,6 +46,9 @@ class CursorEndpointConfig:# the Admin API takes a JSON body with epoch-ms dates.query_params: bool = Falsedate_param_format: Literal["epoch_ms", "iso_date"] = "epoch_ms"+ date_param_names: tuple[str, str] = ("startDate", "endDate")+ # Fixed query params the endpoint requires on every request.+ extra_params: dict[str, str] = field(default_factory=dict)# Response `data` is an object keyed by user email instead of a list of rows.by_user: bool = Falsepaginated: bool = True@@ -275,6 +287,76 @@ CURSOR_ENDPOINTS: dict[str, CursorEndpointConfig] = {should_sync_default=False,description="Individual accepted AI changes with the lines added and deleted, the model, and the files each change touched. Needs a Cursor Enterprise plan with AI code tracking enabled. Only syncs the last 365 days on initial sync",),+ "audit_logs": CursorEndpointConfig(+ name="audit_logs",+ path="/teams/audit-logs",+ method="GET",+ query_params=True,+ date_param_names=("startTime", "endTime"),+ data_key="events",+ primary_keys=["event_id"],+ windowed=True,+ page_size=500,+ partition_key="timestamp",+ incremental_fields=[_datetime_field("timestamp")],+ should_sync_default=False,+ description="Audit log events for your team, such as logins, member changes, and settings changes. Only syncs the last 365 days on initial sync",+ ),+ "billing_groups": CursorEndpointConfig(+ name="billing_groups",+ path="/teams/groups",+ method="GET",+ data_key="groups",+ primary_keys=["id"],+ paginated=False,+ should_sync_default=False,+ description="Billing groups with their spend for the current billing cycle, including the reserved Unassigned group. Needs a Cursor Enterprise plan. Full refresh only",+ ),+ "billing_group_members": CursorEndpointConfig(+ name="billing_group_members",+ path="/teams/groups",+ method="GET",+ data_key="groups",+ # A member can leave a group and join it again, so the join time is in the key.+ primary_keys=["groupId", "userId", "joinedAt"],+ paginated=False,+ should_sync_default=False,+ description="Current and former members of each billing group, with their spend for the current billing cycle. Needs a Cursor Enterprise plan. Full refresh only",+ ),+ "bugbot_reviews": CursorEndpointConfig(+ name="bugbot_reviews",+ path="/analytics/team/bugbot-reviews",+ method="GET",+ query_params=True,+ date_param_format="iso_date",+ data_key="data",+ primary_keys=["request_id"],+ windowed=True,+ window_days=ANALYTICS_MAX_WINDOW_DAYS,+ page_size=250,+ partition_key="timestamp",+ incremental_fields=[_datetime_field("timestamp")],+ should_sync_default=False,+ description="One row per completed Bugbot review, with the reviewed commit, the findings, and the billed cost. Needs a Cursor Enterprise plan and an API key with read access. Only syncs the last 365 days on initial sync",+ ),+ "conversation_insights": CursorEndpointConfig(+ name="conversation_insights",+ path="/analytics/team/conversation-insights",+ method="GET",+ query_params=True,+ date_param_format="iso_date",+ data_key="data",+ extra_params={"include": ",".join(CONVERSATION_INSIGHT_SLICES)},+ # One row per day per slice value, expanded from each slice's time series.+ primary_keys=["date", "slice", "value"],+ windowed=True,+ window_days=ANALYTICS_MAX_WINDOW_DAYS,+ paginated=False,+ partition_key="date",+ incremental_fields=[_datetime_field("date")],+ should_sync_default=False,+ description="Daily team conversation counts by intent, complexity, category, guidance level, and work type. Needs a Cursor Enterprise plan with Conversation Insights turned on. Only syncs the last 365 days on initial sync",+ ),}ENDPOINTS = tuple(CURSOR_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.pyindex c90dfd3837f0..32e360c4f58f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cursor/tests/test_cursor.py@@ -233,7 +233,7 @@ class TestCursorTransport:assert _resolve_friendly_error(excinfo.value) == expecteddef test_unknown_endpoint_raises(self):- result = _driver().run("audit_logs", [])+ result = _driver().run("not_a_table", [])assert isinstance(result.raised, ValueError)assert "Unknown Cursor endpoint" in str(result.raised)@@ -392,6 +392,8 @@ class TestCursorTransport:("by_user_agent_edits", {"data": {}, "pagination": {"hasNextPage": False}}, True),("ai_code_commits", {"items": [], "totalCount": 0}, True),("ai_code_changes", {"items": [], "totalCount": 0}, True),+ ("bugbot_reviews", {"data": [], "pagination": {"hasNextPage": False}}, True),+ ("conversation_insights", {"data": {}}, False),])def test_analytics_endpoints_send_calendar_dates_as_query_params(self, endpoint, payload, paginated):@@ -497,3 +499,145 @@ class TestCursorTransport:assert session.request.call_count == 2assert session.request.call_args_list[1].kwargs["json"]["page"] == 2++ @parameterized.expand(+ [+ # The Admin API names the audit log range startTime/endTime. Sent as startDate/endDate,+ # the range is ignored and every window returns the default last 7 days.+ (+ "audit_logs",+ {"events": [], "pagination": {"hasNextPage": False}},+ {"startTime": "1699568000000", "endTime": "1700000000000", "pageSize": "500", "startDate": None},+ ),+ # `include` is required, and the slices it names are the ones the rows are built from.+ (+ "conversation_insights",+ {"data": {}},+ {"include": "intents,complexity,categories,guidanceLevels,workTypes", "page": None},+ ),+ ]+ )+ def test_endpoint_specific_query_params(self, endpoint, payload, expected_params):+ now_ms = 1_700_000_000_000+ watermark = datetime.fromtimestamp((now_ms - 5 * DAY_MS) / 1000, tz=UTC)+ with mock.patch.object(cursor, "_now_ms", return_value=now_ms):+ result = _driver().run(+ endpoint,+ [ScriptedResponse(json=payload)],+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )++ assert result.raised is None+ assert {name: result.requests[0].param(name) for name in expected_params} == expected_params++ def test_audit_logs_walk_every_page_of_a_window(self):+ now_ms = 1_700_000_000_000+ pages = [+ ScriptedResponse(+ json={+ "events": [{"event_id": "evt-1", "timestamp": "2023-11-13T08:00:00.000Z"}],+ "pagination": {"hasNextPage": True},+ }+ ),+ ScriptedResponse(+ json={+ "events": [{"event_id": "evt-2", "timestamp": "2023-11-14T09:30:00.000Z"}],+ "pagination": {"hasNextPage": False},+ }+ ),+ ]+ with mock.patch.object(cursor, "_now_ms", return_value=now_ms):+ result = _driver().run(+ "audit_logs",+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.fromtimestamp((now_ms - DAY_MS) / 1000, tz=UTC),+ )++ assert result.raised is None+ assert result.paths == ["/teams/audit-logs", "/teams/audit-logs"]+ assert result.params("page") == ["1", "2"]+ assert [row["event_id"] for row in result.rows] == ["evt-1", "evt-2"]+ assert result.rows[1]["timestamp"] == datetime(2023, 11, 14, 9, 30, tzinfo=UTC)++ @parameterized.expand(+ [+ (+ "groups_and_unassigned",+ {+ "groups": [+ {+ "id": "group_eng",+ "name": "Engineering",+ "spendCents": 1200,+ "createdAt": "2025-01-02T00:00:00.000Z",+ "currentMembers": [+ {"userId": "user_a", "joinedAt": "2025-01-03T00:00:00.000Z", "leftAt": None}+ ],+ "formerMembers": [+ {+ "userId": "user_b",+ "joinedAt": "2025-01-01T00:00:00.000Z",+ "leftAt": "2025-01-05T00:00:00.000Z",+ }+ ],+ }+ ],+ "unassignedGroup": {+ "id": "group_unassigned",+ "name": "Unassigned",+ "currentMembers": [{"userId": "user_c", "joinedAt": "2025-01-04T00:00:00.000Z"}],+ },+ "billingCycle": {"cycleStart": "2025-01-01T00:00:00.000Z", "cycleEnd": "2025-02-01T00:00:00.000Z"},+ },+ ["group_eng", "group_unassigned"],+ [("group_eng", "user_a", True), ("group_eng", "user_b", False), ("group_unassigned", "user_c", True)],+ ),+ ("unassigned_group_null", {"groups": [], "unassignedGroup": None}, [], []),+ ("empty_body", {}, [], []),+ ]+ )+ def test_billing_group_tables_read_one_listing(self, _name, body, expected_group_ids, expected_members):+ groups_result = _driver().run("billing_groups", [ScriptedResponse(json=body)])+ members_result = _driver().run("billing_group_members", [ScriptedResponse(json=body)])++ assert groups_result.raised is None and members_result.raised is None+ assert groups_result.paths == members_result.paths == ["/teams/groups"]+ assert [row["id"] for row in groups_result.rows] == expected_group_ids+ # Members get their own table, so the unbounded member lists stay out of the group rows.+ assert all("currentMembers" not in row and "formerMembers" not in row for row in groups_result.rows)+ assert [+ (row["groupId"], row["userId"], row["isCurrentMember"]) for row in members_result.rows+ ] == expected_members+ if expected_members:+ cycle_start = datetime(2025, 1, 1, tzinfo=UTC)+ assert all(row["billingCycleStart"] == cycle_start for row in groups_result.rows + members_result.rows)+ assert members_result.rows[1]["leftAt"] == datetime(2025, 1, 5, tzinfo=UTC)++ def test_conversation_insights_rows_come_from_the_daily_series_only(self):+ data = {+ "data": {+ # Range totals change with the window, so they must not become rows.+ "intents": {+ "distribution": [{"intent": "Ask", "count": 7}],+ "topValues": [{"intent": "Ask", "count": 7}],+ "timeSeries": [+ {"date": "2026-03-01", "intent": "Ask", "count": 2},+ {"date": "2026-03-02", "intent": "Write Code", "count": 6},+ ],+ "subcategories": {"askMode": [{"subcategory": "error_fix", "count": 4}]},+ },+ "workTypes": {"timeSeries": [{"date": "2026-03-01", "workType": "bug", "count": 2}]},+ "complexity": {"distribution": [{"complexity": "high", "count": 1}]},+ "categories": None,+ }+ }++ rows = _extract_rows(CURSOR_ENDPOINTS["conversation_insights"], data)++ assert rows == [+ {"date": "2026-03-01", "slice": "intents", "value": "Ask", "count": 2},+ {"date": "2026-03-02", "slice": "intents", "value": "Write Code", "count": 6},+ {"date": "2026-03-01", "slice": "workTypes", "value": "bug", "count": 2},+ ]