: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): add devin ai session and consumption tables (#105173)
Tom Owerscc683355b087
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 6934c500ab34..9dcde3a0875b 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@@ -2441,14 +2441,14 @@ Note: The downloadable spec (Descope_API.yaml, 474 paths, 318 under /mgmt) is a## DevinAI — **thin**-Today (4): `knowledge_notes`, `playbooks`, `secrets`, `sessions`+Today (9): `consumption_daily`, `consumption_daily_users`, `knowledge_notes`, `members`, `playbooks`, `secrets`, `session_insights`, `session_messages`, `sessions`Diffed against: <https://docs.devin.ai/llms.txt>-- [ ] `/v3/organizations/{org_id}/members/users (and /members/{id})` — lookup table resolving the user IDs on every session; without it sessions cannot be attributed to people (high)-- [ ] `/v3/organizations/{org_id}/consumption/daily (+ /daily/users, /daily/sessions, /daily/service-users, /consumption/cycles)` — ACU consumption per day, user and session — the headline cost metric for Devin (high)-- [ ] `/v3/organizations/{org_id}/sessions/{session_id}/messages` — the conversation transcript inside a session; sessions alone carry no content (high)-- [ ] `/v3/organizations/{org_id}/sessions/insights (and /sessions/{id}/insights)` — per-session outcome and quality insights, the vendor's own success measure (high)+- [x] `/v3/organizations/{org_id}/members/users (and /members/{id})` — lookup table resolving the user IDs on every session; without it sessions cannot be attributed to people (high) — already synced as `members`, off the v3beta1 org-scoped users listing, which is the only org-scoped path this listing has. `/members/{id}` is a single-record lookup of the same rows.+- [x] `/v3/organizations/{org_id}/consumption/daily (+ /daily/users, /daily/sessions, /daily/service-users, /consumption/cycles)` — ACU consumption per day, user and session — the headline cost metric for Devin (high) — added as `consumption_daily` and `consumption_daily_users`. `/daily/sessions/{id}` is redundant: every session row already carries `acus_consumed`. `/daily/service-users/{id}` has no org-scoped service-user listing to fan out from, and `/consumption/cycles` only exists at enterprise scope — both need an enterprise service user this source does not hold.+- [x] `/v3/organizations/{org_id}/sessions/{session_id}/messages` — the conversation transcript inside a session; sessions alone carry no content (high) — added as `session_messages`, fanned out over `sessions`. Off by default: it costs one request per session in the org's history.+- [x] `/v3/organizations/{org_id}/sessions/insights (and /sessions/{id}/insights)` — per-session outcome and quality insights, the vendor's own success measure (high) — added as `session_insights`. `/sessions/{id}/insights` returns the same record one session at a time, so the list endpoint covers it.- [ ] `/v3/organizations/{org_id}/pr-reviews` — PR review activity and outcomes, a primary Devin use case not represented at all today (high)- [ ] `/v3/organizations/{org_id}/audit-logs (and enterprise audit logs)` — who did what in the org — standard governance table (medium)- [ ] `/v3/organizations/{org_id}/metrics/sessions, /metrics/prs, /metrics/usage, /metrics/dau|wau|mau, /metrics/sessions-by-category` — pre-aggregated adoption and throughput metrics that avoid recomputing them from raw sessions (medium)@@ -2458,7 +2458,7 @@ Diffed against: <https://docs.devin.ai/llms.txt>- [ ] `/v3/organizations/{org_id}/guardrail-violations` — policy violations raised during sessions — compliance reporting (medium)- [ ] `/v3/organizations/{org_id}/knowledge/folders` — folder lookup that gives the synced knowledge notes their hierarchy (low)-Note: docs.devin.ai/llms.txt enumerates every v1/v2/v3 API reference page; v3 alone spans sessions, consumption, metrics, users, repositories, pr-reviews, audit-logs, code-scans, guardrails and more, so 4 synced tables (one of which, secrets, is plumbing) is a small fraction.+Note: docs.devin.ai/llms.txt enumerates every v1/v2/v3 API reference page; v3 alone spans sessions, consumption, metrics, users, repositories, pr-reviews, audit-logs, code-scans, guardrails and more, so 9 synced tables (one of which, secrets, is plumbing) is still a small fraction.## DigitalOcean — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/canonical_descriptions.pyindex 1afde0b288b6..c027524cba20 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/canonical_descriptions.py@@ -77,6 +77,57 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"role_assignments": "Roles assigned directly to the member, each with a role (role_id, role_name, role_type) and the org it applies to.",},},+ "session_insights": {+ "description": "Devin's own read on a completed session: the same session record plus message counts, a size band, and the AI-generated analysis of how the run went.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/sessions/organizations-sessions-insights",+ "columns": {+ "session_id": "Unique identifier for the session. Joins to the sessions table.",+ "num_user_messages": "Number of user messages sent during the session.",+ "num_devin_messages": "Number of Devin messages sent during the session.",+ "session_size": "Session size classification based on ACU usage and message count (xs, s, m, l, xl).",+ "analysis": "AI-generated analysis of the session. Null until analysis completes.",+ "analysis_status": "State of the most recent analysis run (started, completed, failed). Null if analysis was never run.",+ "status": "High-level session state (new, claimed, running, exit, error, suspended, resuming).",+ "acus_consumed": "Number of Agent Compute Units consumed by the session.",+ "created_at": "Unix timestamp (seconds) when the session was created.",+ "updated_at": "Unix timestamp (seconds) when the session was last updated.",+ "user_id": "Identifier of the user who created the session.",+ "org_id": "Identifier of the organization the session belongs to.",+ },+ },+ "session_messages": {+ "description": "A single message in a Devin session's conversation, from either the user or Devin. Messages are returned in chronological order.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/sessions/get-organizations-session-messages",+ "columns": {+ "session_id": "Identifier of the session the message belongs to. Joins to the sessions table.",+ "event_id": "Identifier of the message within its session.",+ "source": "Who sent the message (devin or user).",+ "message": "Text of the message.",+ "created_at": "Unix timestamp (seconds) when the message was sent.",+ "username": "Display name of the user who sent the message, if available.",+ "user_id": "Identifier of the user who sent the message, if available.",+ "origin": "Surface the message came from, if available.",+ },+ },+ "consumption_daily": {+ "description": "Agent Compute Units the organization consumed on one day. Days run midnight to midnight Pacific, which is the boundary Devin bills on.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/consumption/organizations-consumption-daily",+ "columns": {+ "date": "Unix timestamp (seconds) of the day the consumption falls in.",+ "acus": "Total Agent Compute Units consumed on that day.",+ "acus_by_product": "The day's ACUs split by product (devin, cascade, terminal, review).",+ },+ },+ "consumption_daily_users": {+ "description": "Agent Compute Units one organization member consumed on one day. The per-person split of consumption_daily, so spend can be attributed to people.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/consumption/organizations-consumption-daily-users",+ "columns": {+ "user_id": "Identifier of the member the consumption belongs to. Joins to the members table.",+ "date": "Unix timestamp (seconds) of the day the consumption falls in.",+ "acus": "Agent Compute Units the member consumed on that day.",+ "acus_by_product": "The day's ACUs split by product (devin, cascade, terminal, review).",+ },+ },"secrets": {"description": "Metadata for an org-level secret available to Devin sessions. Secret values are never returned by the API and are not synced.","docs_url": "https://docs.devin.ai/api-reference/v3/secrets/organizations-secrets",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/devin_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/devin_ai.pyindex 5b15987d8859..edab2b9c30aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/devin_ai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/devin_ai.py@@ -1,6 +1,7 @@import reimport dataclasses-from typing import Any, Optional+from collections.abc import Iterable+from typing import Any, Optional, castfrom requests import Request, Response@@ -9,14 +10,22 @@ 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.paginators import BasePaginator+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 ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import DEVIN_AI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import (+ DEVIN_AI_ENDPOINTS,+ DevinAIEndpointConfig,+)DEVIN_AI_BASE_URL = "https://api.devin.ai"-# v3 cursor pagination caps `first` at 200.-PAGE_SIZE = 200@dataclasses.dataclass@@ -48,6 +57,11 @@ def _endpoint_path(endpoint: str, org_id: str) -> str:return DEVIN_AI_ENDPOINTS[endpoint].path.format(org_id=_validate_org_id(org_id))+def _probe_endpoint(endpoint: str) -> str:+ # A fan-out child's path needs a parent id, so it can't be probed directly.+ return DEVIN_AI_ENDPOINTS[endpoint].probe_endpoint or endpoint++class DevinCursorPaginator(BasePaginator):"""Cursor paginator for Devin's v3 list envelope.@@ -106,35 +120,63 @@ class DevinCursorPaginator(BasePaginator):return "DevinCursorPaginator()"-def devin_ai_source(+def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": DEVIN_AI_BASE_URL,+ # Only the non-secret Accept header goes here; the Bearer token is supplied via the+ # framework `auth` config so its value is redacted from logs.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ }+++def _paginator(config: DevinAIEndpointConfig) -> BasePaginator:+ return DevinCursorPaginator() if config.paginated else SinglePagePaginator()+++def _list_params(config: DevinAIEndpointConfig) -> dict[str, Any]:+ return {"first": config.page_size} if config.paginated else {}+++def _source_response(+ config: DevinAIEndpointConfig,+ items_fn: Any,+ column_hints: Any = None,+) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=column_hints,+ )+++def _top_level_source(api_key: str,org_id: str,- endpoint: str,+ config: DevinAIEndpointConfig,team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[DevinAIResumeConfig],- db_incremental_field_last_value: Optional[Any] = None,+ db_incremental_field_last_value: Optional[Any],) -> SourceResponse:- endpoint_config = DEVIN_AI_ENDPOINTS[endpoint]-rest_config: RESTAPIConfig = {- "client": {- "base_url": DEVIN_AI_BASE_URL,- # Only the non-secret Accept header goes here; the Bearer token is supplied via the- # framework `auth` config so its value is redacted from logs.- "headers": {"Accept": "application/json"},- "auth": {"type": "bearer", "token": api_key},- },+ "client": _client_config(api_key),"resources": [{- "name": endpoint,+ "name": config.name,"endpoint": {# `_endpoint_path` validates org_id so a malformed value can't inject `/` or `?`# and retarget the stored key at a different Devin API path.- "path": _endpoint_path(endpoint, org_id),- "params": {"first": PAGE_SIZE},- "data_selector": "items",- "paginator": DevinCursorPaginator(),+ "path": _endpoint_path(config.name, org_id),+ "params": _list_params(config),+ "data_selector": config.data_selector,+ "paginator": _paginator(config),},}],@@ -161,24 +203,79 @@ def devin_ai_source(initial_paginator_state=initial_paginator_state,)- return SourceResponse(- name=endpoint,- items=lambda: resource,- primary_keys=endpoint_config.primary_keys,- partition_count=1,- partition_size=1,- partition_mode="datetime" if endpoint_config.partition_key else None,- partition_format="week" if endpoint_config.partition_key else None,- partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,- column_hints=resource.column_hints,+ return _source_response(config, lambda: resource, column_hints=resource.column_hints)+++def _fanout_source(+ api_key: str,+ org_id: str,+ config: DevinAIEndpointConfig,+ team_id: int,+ job_id: str,+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ # Fan-out endpoints don't resume: a retry re-syncs from scratch and the merge dedupes.+ assert config.fanout is not None+ parent_config = DEVIN_AI_ENDPOINTS[config.fanout.parent_name]+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=DEVIN_AI_ENDPOINTS,+ child_endpoint=config.name,+ # Parent and child disagree on whether they take a page-size param, so each carries its+ # own rather than sharing one through `page_size_param`.+ fanout=dataclasses.replace(config.fanout, parent_params=_list_params(parent_config)),+ client_config=_client_config(api_key),+ path_format_values={"org_id": _validate_org_id(org_id)},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ page_size_param=None,+ parent_endpoint_extra={+ "paginator": _paginator(parent_config),+ "data_selector": parent_config.data_selector,+ },+ child_endpoint_extra={+ "paginator": _paginator(config),+ "data_selector": config.data_selector,+ },+ child_params_extra=_list_params(config),+ ),+ )+ return _source_response(config, lambda: dependent_resource)+++def devin_ai_source(+ api_key: str,+ org_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[DevinAIResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = DEVIN_AI_ENDPOINTS[endpoint]++ if endpoint_config.fanout is not None:+ return _fanout_source(api_key, org_id, endpoint_config, team_id, job_id, db_incremental_field_last_value)+ return _top_level_source(+ api_key,+ org_id,+ endpoint_config,+ team_id,+ job_id,+ resumable_source_manager,+ db_incremental_field_last_value,)def get_status_code(api_key: str, org_id: str, endpoint: str) -> int:"""Cheap single-page probe used by credential validation. Returns the HTTP status code."""- url = f"{DEVIN_AI_BASE_URL}{_endpoint_path(endpoint, org_id)}"+ config = DEVIN_AI_ENDPOINTS[_probe_endpoint(endpoint)]+ url = f"{DEVIN_AI_BASE_URL}{_endpoint_path(config.name, org_id)}"+ params = {"first": 1} if config.paginated else {}session = make_tracked_session(redact_values=(api_key,))- response = session.get(url, params={"first": 1}, headers=_get_headers(api_key), timeout=10)+ response = session.get(url, params=params, headers=_get_headers(api_key), timeout=10)return response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/settings.pyindex 49dc0dc39e99..985cf7ea57d6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/settings.py@@ -1,6 +1,9 @@from dataclasses import dataclass, fieldfrom typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField# Devin (Cognition AI) v3 API. Every org-level list endpoint shares the same shape:@@ -11,6 +14,10 @@ from products.warehouse_sources.backend.types import IncrementalField# {"items": [...], "end_cursor": str | None, "has_next_page": bool, "total": int | None}# Timestamps (`created_at` / `updated_at`) are integer Unix seconds.#+# The consumption endpoints are the exception: they answer with a single unpaginated+# {"total_acus": float, "consumption_by_date": [...]} object, so they select a different key and+# take no page-size param.+## The v3 sessions endpoint documents server-side `created_after` / `updated_after` filters that could# power incremental sync, but we can't verify against the live API (no credentials), and the default# result ordering is undocumented. Declaring incremental with the wrong sort assumption corrupts the@@ -18,17 +25,33 @@ from products.warehouse_sources.backend.types import IncrementalField# resumable across heartbeat timeouts. Enabling incremental on sessions is a follow-up once the filter# and ordering are curl-verified.+# v3 cursor pagination caps `first` at 200.+PAGE_SIZE = 200+-@dataclass+@dataclass(frozen=True)class DevinAIEndpointConfig:name: str- # Path template under the API root; `{org_id}` is filled from the source config.+ # Path template under the API root; `{org_id}` is filled from the source config. A fan-out child+ # keeps its parent placeholder (e.g. `{devin_id}`) for the fan-out helper to bind per parent row.path: str# Field to partition Delta files by. Must be a STABLE field (created_at, never updated_at).partition_key: Optional[str] = "created_at"primary_keys: list[str] = field(default_factory=lambda: ["id"])incremental_fields: list[IncrementalField] = field(default_factory=list)should_sync_default: bool = True+ # Key in the response body holding the rows.+ data_selector: str = "items"+ # False for the consumption endpoints, which return their whole collection in one response.+ paginated: bool = True+ page_size: int = PAGE_SIZE+ # Endpoint to probe when validating credentials for this table. A fan-out child needs a parent id+ # in its path, so it delegates to the org-level endpoint gated by the same permission.+ probe_endpoint: Optional[str] = None+ # Path fan-out driven by the shared rest_source helper (parent id fills a {placeholder}).+ fanout: Optional[DependentEndpointConfig] = None+ # Full refresh only — kept so the config satisfies the fan-out helper's protocol.+ default_incremental_field: Optional[str] = NoneDEVIN_AI_ENDPOINTS: dict[str, DevinAIEndpointConfig] = {@@ -37,6 +60,32 @@ DEVIN_AI_ENDPOINTS: dict[str, DevinAIEndpointConfig] = {path="/v3/organizations/{org_id}/sessions",primary_keys=["session_id"],),+ # Same session records as `sessions` plus Devin's own quality read on each run: message counts,+ # session size band, and the generated analysis with its status.+ "session_insights": DevinAIEndpointConfig(+ name="session_insights",+ path="/v3/organizations/{org_id}/sessions/insights",+ primary_keys=["session_id"],+ ),+ # The conversation inside a session, one request per session. Off by default because the request+ # count grows with the org's whole session history, and most orgs only want the session rows.+ "session_messages": DevinAIEndpointConfig(+ name="session_messages",+ path="/v3/organizations/{org_id}/sessions/{devin_id}/messages",+ # event_id is documented as the message id, with no promise of uniqueness beyond its session,+ # so the parent session scopes the key.+ primary_keys=["session_id", "event_id"],+ should_sync_default=False,+ probe_endpoint="sessions",+ fanout=DependentEndpointConfig(+ parent_name="sessions",+ resolve_param="devin_id",+ resolve_field="session_id",+ # Message rows carry no session id, so copy the parent's down as `session_id`.+ include_from_parent=["session_id"],+ parent_field_renames={"session_id": "session_id"},+ ),+ ),"playbooks": DevinAIEndpointConfig(name="playbooks",path="/v3/organizations/{org_id}/playbooks",@@ -59,6 +108,33 @@ DEVIN_AI_ENDPOINTS: dict[str, DevinAIEndpointConfig] = {partition_key=None,primary_keys=["user_id"],),+ # Org-wide ACU spend per day. One row per day, so full refresh stays cheap.+ "consumption_daily": DevinAIEndpointConfig(+ name="consumption_daily",+ path="/v3/organizations/{org_id}/consumption/daily",+ partition_key="date",+ primary_keys=["date"],+ data_selector="consumption_by_date",+ paginated=False,+ ),+ # The same daily spend split per member, so ACUs can be attributed to a person.+ "consumption_daily_users": DevinAIEndpointConfig(+ name="consumption_daily_users",+ path="/v3/organizations/{org_id}/consumption/daily/users/{user_id}",+ partition_key="date",+ primary_keys=["user_id", "date"],+ data_selector="consumption_by_date",+ paginated=False,+ probe_endpoint="consumption_daily",+ fanout=DependentEndpointConfig(+ parent_name="members",+ resolve_param="user_id",+ resolve_field="user_id",+ # Consumption rows are just date + ACUs, so the member they belong to comes from the parent.+ include_from_parent=["user_id"],+ parent_field_renames={"user_id": "user_id"},+ ),+ ),# Org secrets expose metadata only (key names, type, audit fields) — never the secret values.# Off by default so a user opts in rather than silently syncing secret metadata."secrets": DevinAIEndpointConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/source.pyindex 1845cf1795f1..9be6403db355 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/source.py@@ -59,9 +59,10 @@ class DevinAISource(ResumableSource[DevinAISourceConfig, DevinAIResumeConfig]):caption="""Enter your Devin service user API key and organization ID to sync your Devin data into the PostHog Data warehouse.Create a service user API key (prefixed `cog_`) in your [Devin organization settings](https://app.devin.ai/settings). The service user needs the following organization-level permissions:-- `ViewOrgSessions` — Sessions+- `ViewOrgSessions` — Sessions, session insights and session messages+- `ViewOrgConsumption` — Daily ACU consumption, per org and per user- `ManageAccountKnowledge` — Playbooks and Knowledge notes-- `ViewOrgMembership` — Members+- `ViewOrgMembership` — Members, and the per-user consumption that fans out from them- `ManageOrgSecrets` — Secrets (metadata only; values are never synced)Your organization ID is the `org-...` identifier shown in your Devin organization settings.""",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai.pyindex 3baf2c509e23..138fce29a46a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai.py@@ -8,13 +8,15 @@ from parameterized import parameterizedfrom requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.devin_ai import (- PAGE_SIZE,DevinAIResumeConfig,_endpoint_path,devin_ai_source,get_status_code,)-from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import DEVIN_AI_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import (+ DEVIN_AI_ENDPOINTS,+ PAGE_SIZE,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -36,6 +38,14 @@ def _response(return resp+def _consumption_response(rows: list[dict[str, Any]], *, total_acus: float = 0.0) -> Response:+ # The consumption endpoints answer with one unpaginated object, not the cursor envelope.+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps({"total_acus": total_acus, "consumption_by_date": rows}).encode()+ return resp++def _make_manager(resume_state: DevinAIResumeConfig | None = None) -> mock.MagicMock:manager = mock.MagicMock()manager.can_resume.return_value = resume_state is not None@@ -61,6 +71,21 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,return param_snapshots+def _wire_urls(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:+ """Like `_wire`, but capture each request's URL too so fan-out tests can tell a parent request+ from a per-parent child request."""+ session.headers = {}+ captured: list[tuple[str, dict[str, Any]]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ captured.append((request.url or "", dict(request.params or {})))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return captured++def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]@@ -83,6 +108,8 @@ class TestEndpointPath:("playbooks", "/v3/organizations/org-abc/playbooks"),("knowledge_notes", "/v3/organizations/org-abc/knowledge/notes"),("secrets", "/v3/organizations/org-abc/secrets"),+ ("session_insights", "/v3/organizations/org-abc/sessions/insights"),+ ("consumption_daily", "/v3/organizations/org-abc/consumption/daily"),# Members must stay on the org-scoped users listing: the v2 members endpoint only accepts# enterprise-admin personal API keys, which this source never stores.("members", "/v3beta1/organizations/org-abc/members/users"),@@ -212,9 +239,37 @@ class TestGetStatusCode:assert kwargs["params"] == {"first": 1}assert kwargs["headers"]["Authorization"] == "Bearer cog_test"+ @parameterized.expand(+ [+ # A fan-out child's own path needs a parent id, so probing it directly would send a URL+ # with an unbound `{devin_id}` / `{user_id}` placeholder. Each delegates to the org-level+ # endpoint gated by the same permission instead.+ ("session_messages", "https://api.devin.ai/v3/organizations/org-abc/sessions", {"first": 1}),+ (+ "consumption_daily_users",+ "https://api.devin.ai/v3/organizations/org-abc/consumption/daily",+ {},+ ),+ ]+ )+ def test_fanout_child_probes_its_org_level_endpoint(+ self, endpoint: str, expected_url: str, expected_params: dict[str, Any]+ ) -> None:+ response = mock.MagicMock()+ response.status_code = 200+ session = mock.MagicMock()+ session.get.return_value = response++ with mock.patch(DEVIN_SESSION_PATCH, return_value=session):+ get_status_code("cog_test", "org-abc", endpoint)++ args, kwargs = session.get.call_args+ assert args[0] == expected_url+ assert kwargs["params"] == expected_params+class TestDevinAISource:- @parameterized.expand(["sessions", "playbooks", "knowledge_notes", "secrets"])+ @parameterized.expand(["sessions", "session_insights", "playbooks", "knowledge_notes", "secrets"])@mock.patch(CLIENT_SESSION_PATCH)def test_source_response_uses_endpoint_primary_keys_and_stable_partition(self, endpoint: str, MockSession) -> None:response = _source(endpoint, _make_manager())@@ -225,6 +280,26 @@ class TestDevinAISource:assert response.partition_keys == ["created_at"]assert response.partition_mode == "datetime"+ @parameterized.expand(+ [+ ("session_messages", ["session_id", "event_id"]),+ ("consumption_daily", ["date"]),+ ("consumption_daily_users", ["user_id", "date"]),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fan_out_and_consumption_tables_keep_their_keys_and_partitioning(+ self, endpoint: str, expected_keys: list[str], MockSession+ ) -> None:+ # The fan-out and single-page branches build their SourceResponse separately from the+ # top-level one, so each has to carry the composite key that keeps rows from colliding+ # across parents, and a partition key that doesn't move once written.+ response = _source(endpoint, _make_manager())+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ assert response.partition_mode == "datetime"+ assert response.partition_keys == (["date"] if endpoint.startswith("consumption") else ["created_at"])+@mock.patch(CLIENT_SESSION_PATCH)def test_members_source_response_dedupes_on_user_id_and_has_no_partition(self, MockSession) -> None:response = _source("members", _make_manager())@@ -303,3 +378,97 @@ class TestMembersJoin:assert params[1] == {"first": PAGE_SIZE, "after": "cur1"}email_by_user_id = {row["user_id"]: row["email"] for row in rows}assert email_by_user_id["email|bbb222"] == "[email protected]"+++class TestConsumption:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_daily_selects_rows_from_the_consumption_envelope_in_one_request(self, MockSession) -> None:+ session = MockSession.return_value+ # The consumption body nests its rows under `consumption_by_date`, and carries no cursor —+ # selecting `items` or paginating it would sync nothing and loop respectively.+ params = _wire(+ session,+ [+ _consumption_response(+ [+ {"date": 1750000000, "acus": 12.5, "acus_by_product": {"devin": 12.5}},+ {"date": 1750086400, "acus": 3.0, "acus_by_product": {"devin": 3.0}},+ ],+ total_acus=15.5,+ )+ ],+ )++ rows = _rows(_source("consumption_daily", _make_manager()))++ assert [row["date"] for row in rows] == [1750000000, 1750086400]+ assert rows[0]["acus"] == 12.5+ assert session.send.call_count == 1+ # The endpoint takes no page-size param; sending one would be undocumented.+ assert params[0] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_daily_users_fans_out_over_members_and_stamps_the_member_on_each_row(self, MockSession) -> None:+ session = MockSession.return_value+ # Per-user consumption rows are just date + ACUs, so without the parent's user_id copied down+ # the table would be unattributable — and every member's rows would collide on `date`.+ reqs = _wire_urls(+ session,+ [+ _response([{"user_id": "email|aaa111"}, {"user_id": "email|bbb222"}]),+ _consumption_response([{"date": 1750000000, "acus": 4.0, "acus_by_product": {"devin": 4.0}}]),+ _consumption_response([{"date": 1750000000, "acus": 7.0, "acus_by_product": {"devin": 7.0}}]),+ ],+ )++ rows = _rows(_source("consumption_daily_users", _make_manager()))++ assert {(row["user_id"], row["acus"]) for row in rows} == {("email|aaa111", 4.0), ("email|bbb222", 7.0)}+ child_urls = [url for url, _params in reqs if "/consumption/daily/users/" in url]+ assert {url.rsplit("/", 1)[1] for url in child_urls} == {"email|aaa111", "email|bbb222"}+ parent = next(params for url, params in reqs if url.endswith("/members/users"))+ assert parent["first"] == PAGE_SIZE+++class TestSessionMessagesFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_messages_are_fetched_per_session_and_carry_their_session_id(self, MockSession) -> None:+ session = MockSession.return_value+ # Message rows carry no session id of their own, so the parent's has to be copied down —+ # otherwise the (session_id, event_id) primary key can't be formed.+ reqs = _wire_urls(+ session,+ [+ _response([{"session_id": "devin-1"}, {"session_id": "devin-2"}]),+ _response([{"event_id": "e1", "source": "user", "message": "hi", "created_at": 1750000000}]),+ _response([{"event_id": "e1", "source": "devin", "message": "on it", "created_at": 1750000100}]),+ ],+ )++ rows = _rows(_source("session_messages", _make_manager()))++ assert {(row["session_id"], row["event_id"]) for row in rows} == {("devin-1", "e1"), ("devin-2", "e1")}+ # The un-renamed parent-prefixed key must not survive into the table.+ assert all("_sessions_session_id" not in row for row in rows)+ child = [(url, params) for url, params in reqs if url.endswith("/messages")]+ assert {url.split("/sessions/")[1].split("/")[0] for url, _params in child} == {"devin-1", "devin-2"}+ # The messages endpoint cursor-paginates like the rest of v3, so it takes a page size.+ assert all(params["first"] == PAGE_SIZE for _url, params in child)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_a_session_with_more_messages_than_one_page_is_fully_walked(self, MockSession) -> None:+ session = MockSession.return_value+ reqs = _wire_urls(+ session,+ [+ _response([{"session_id": "devin-1"}]),+ _response([{"event_id": "e1"}], has_next_page=True, end_cursor="cur1"),+ _response([{"event_id": "e2"}], has_next_page=False, end_cursor=None),+ ],+ )++ rows = _rows(_source("session_messages", _make_manager()))++ assert [row["event_id"] for row in rows] == ["e1", "e2"]+ child = [params for url, params in reqs if url.endswith("/messages")]+ assert child[1]["after"] == "cur1"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai_source.pyindex 8266367f68b4..07d38112417c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai_source.py@@ -36,10 +36,20 @@ class TestGetSchemas:assert all(s.supports_incremental is False for s in schemas)assert all(s.supports_append is False for s in schemas)- def test_secrets_off_by_default_others_on(self) -> None:+ @parameterized.expand(+ [+ # Secret metadata is opt-in, and session_messages costs one request per session in the+ # org's whole history — neither should turn on for a user who just wanted sessions.+ ("secrets", False),+ ("session_messages", False),+ ("sessions", True),+ ("session_insights", True),+ ("consumption_daily", True),+ ]+ )+ def test_costly_and_sensitive_tables_are_opt_in(self, endpoint: str, expected_default: bool) -> None:schemas = {s.name: s for s in DevinAISource().get_schemas(_config(), team_id=1)}- assert schemas["secrets"].should_sync_default is False- assert schemas["sessions"].should_sync_default is True+ assert schemas[endpoint].should_sync_default is expected_defaultdef test_members_table_is_discovered_full_refresh_with_user_id_key(self) -> None:# The set-equality assertions above compare get_schemas against the same dict the schemas come