: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): implement devin_ai import source (#67808)
Tom Owersc506e46f3015
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 2bdb890832fe..b21865329092 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -122,6 +122,7 @@ the row lists both.| datadog | HTTP | requests | ✅ || deel | HTTP | requests | ✅ || delighted | HTTP | requests | ✅ |+| devin_ai | HTTP | requests | ✅ || ding_connect | HTTP | requests | ✅ || dixa | HTTP | requests | ✅ || docuseal | HTTP | requests | ✅ |@@ -395,7 +396,6 @@ doesn't conflict with concurrent PRs.- db2- dbt- deputy-- devin_ai- display_video_360- dockerhub- docusigndiff --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.pynew file mode 100644index 000000000000..fec76926ff4b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/canonical_descriptions.py@@ -0,0 +1,86 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the Devin (Cognition AI) v3 API reference (https://docs.devin.ai/api-reference).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sessions": {+ "description": "A Devin agent session — one run of the autonomous engineer against a task, including its status, consumed ACUs, and any pull requests it opened.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/sessions/organizations-sessions",+ "columns": {+ "session_id": "Unique identifier for the session.",+ "url": "Link to view the session in the Devin web app.",+ "status": "High-level session state (new, claimed, running, exit, error, suspended, resuming).",+ "status_detail": "Finer-grained status such as working, waiting_for_user, waiting_for_approval, or a suspension reason.",+ "org_id": "Identifier of the organization the session belongs to.",+ "created_at": "Unix timestamp (seconds) when the session was created.",+ "updated_at": "Unix timestamp (seconds) when the session was last updated.",+ "acus_consumed": "Number of Agent Compute Units consumed by the session.",+ "tags": "User-assigned tags on the session.",+ "pull_requests": "Pull requests opened by the session, each with a pr_url and pr_state.",+ "category": "Session category (populated on get/list endpoints).",+ "subcategory": "Session subcategory.",+ "structured_output": "Structured output produced by the session, if any.",+ "origin": "Where the session was started (webapp, slack, teams, api, linear, jira, automation, cli, desktop, code_scan, other).",+ "is_archived": "Whether the session has been archived.",+ "title": "Session title.",+ "user_id": "Identifier of the user who created the session.",+ "service_user_id": "Identifier of the service user that created the session, if API-initiated.",+ "playbook_id": "Identifier of the playbook the session was launched with, if any.",+ "parent_session_id": "Identifier of the parent session, if this is a child session.",+ "child_session_ids": "Identifiers of any child sessions spawned by this session.",+ },+ },+ "playbooks": {+ "description": "A reusable Devin playbook — a saved set of instructions that can be attached to sessions.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/playbooks/organizations-playbooks",+ "columns": {+ "playbook_id": "Unique identifier for the playbook.",+ "title": "Playbook title.",+ "body": "Playbook instructions.",+ "macro": "Macro (slash command) that invokes the playbook, if set.",+ "created_by": "Identifier of the user who created the playbook.",+ "updated_by": "Identifier of the user who last updated the playbook.",+ "created_at": "Unix timestamp (seconds) when the playbook was created.",+ "updated_at": "Unix timestamp (seconds) when the playbook was last updated.",+ "access_type": "Scope of the playbook (org or enterprise).",+ "org_id": "Identifier of the organization the playbook belongs to.",+ "structured_output_schema": "Schema describing the structured output the playbook produces, if any.",+ },+ },+ "knowledge_notes": {+ "description": "An org-level knowledge note that Devin can reference while working.",+ "docs_url": "https://docs.devin.ai/api-reference/v3/notes/organizations-knowledge-notes",+ "columns": {+ "note_id": "Unique identifier for the note.",+ "name": "Note name.",+ "body": "Note contents.",+ "trigger": "Condition that surfaces the note to Devin.",+ "is_enabled": "Whether the note is active.",+ "created_at": "Unix timestamp (seconds) when the note was created.",+ "updated_at": "Unix timestamp (seconds) when the note was last updated.",+ "access_type": "Scope of the note (org or enterprise).",+ "org_id": "Identifier of the organization the note belongs to.",+ "folder_id": "Identifier of the folder containing the note, if any.",+ "folder_path": "Path of the folder containing the note.",+ "macro": "Macro (slash command) that references the note, if set.",+ "pinned_repo": "Repository the note is pinned to, if any.",+ },+ },+ "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",+ "columns": {+ "secret_id": "Unique identifier for the secret.",+ "key": "Name/key of the secret.",+ "note": "User note describing the secret.",+ "is_sensitive": "Whether the secret is marked sensitive.",+ "created_by": "Identifier of the user who created the secret.",+ "created_at": "Unix timestamp (seconds) when the secret was created.",+ "updated_at": "Unix timestamp (seconds) when the secret was last updated.",+ "updated_by": "Identifier of the user who last updated the secret.",+ "secret_type": "Type of secret (cookie, key-value, totp).",+ "access_type": "Scope of the secret (org or personal).",+ },+ },+}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.pynew file mode 100644index 000000000000..8c2c0a727d2e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/devin_ai.py@@ -0,0 +1,164 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import DEVIN_AI_ENDPOINTS++DEVIN_AI_BASE_URL = "https://api.devin.ai"+# v3 cursor pagination caps `first` at 200.+PAGE_SIZE = 200+++class DevinAIRetryableError(Exception):+ pass+++class DevinAIResumeConfig:+ # Opaque cursor from the previous page's `end_cursor`, passed back as `after`. None starts at page 1.+ after: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++# Devin org IDs look like `org-<slug>`. Constrain to the characters an ID can legitimately contain so a+# malformed value can't inject `/` or `?` and route the stored API key at a different Devin API path.+_ORG_ID_RE = re.compile(r"[a-zA-Z0-9._-]+")+++def _validate_org_id(org_id: str) -> str:+ org = org_id.strip()+ if not _ORG_ID_RE.fullmatch(org):+ raise ValueError(f"Invalid Devin organization ID: {org_id}")+ return org+++def _endpoint_path(endpoint: str, org_id: str) -> str:+ return DEVIN_AI_ENDPOINTS[endpoint].path.format(org_id=_validate_org_id(org_id))+++@retry(+ retry=retry_if_exception_type(+ (+ DevinAIRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> dict:+ response = session.get(url, params=params, headers=headers, timeout=60)++ # 429 (rate limit) and 5xx are transient — retry with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise DevinAIRetryableError(f"Devin API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Devin API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++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)}"+ response = make_tracked_session().get(url, params={"first": 1}, headers=_get_headers(api_key), timeout=10)+ return response.status_code+++def get_rows(+ api_key: str,+ org_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DevinAIResumeConfig],+) -> Iterator[Any]:+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()++ url = f"{DEVIN_AI_BASE_URL}{_endpoint_path(endpoint, org_id)}"++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after = resume.after if resume else None+ if after:+ logger.debug(f"Devin: resuming {endpoint} from cursor: {after}")++ # Yield one full page at a time and only save state at the page boundary, after the page has been+ # yielded. The pipeline batches internally, so a source-level batcher would only double-buffer and,+ # because it spans pages, would force a mid-page save that drops the un-yielded tail on crash-resume.+ while True:+ params: dict[str, Any] = {"first": PAGE_SIZE}+ if after:+ params["after"] = after++ data = _fetch_page(session, url, params, headers, logger)++ items = data.get("items", [])+ if items:+ yield items++ next_cursor = data.get("end_cursor")+ if not data.get("has_next_page") or not next_cursor:+ break++ after = next_cursor+ # Save state AFTER yielding the page so a crash re-fetches this page (merge dedupes on the+ # primary key) rather than skipping it.+ resumable_source_manager.save_state(DevinAIResumeConfig(after=next_cursor))+++def devin_ai_source(+ api_key: str,+ org_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DevinAIResumeConfig],+) -> SourceResponse:+ endpoint_config = DEVIN_AI_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ org_id=org_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ 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,+ )+++def validate_credentials(api_key: str, org_id: str, endpoint: str = "sessions") -> int:+ """Probe the given endpoint and return its HTTP status code (or raise on transport failure)."""+ return get_status_code(api_key, org_id, endpoint)diff --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.pynew file mode 100644index 000000000000..47c13b4cbdbf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/settings.py@@ -0,0 +1,62 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++# Devin (Cognition AI) v3 API. Every org-level list endpoint shares the same shape:+# GET https://api.devin.ai/v3/organizations/{org_id}/<resource>+# cursor pagination via `first` (<=200) / `after`, response envelope+# {"items": [...], "end_cursor": str | None, "has_next_page": bool, "total": int | None}+# Timestamps (`created_at` / `updated_at`) are integer Unix seconds.+#+# 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+# watermark, so every endpoint ships full-refresh-only for now. Cursor pagination still makes the sync+# resumable across heartbeat timeouts. Enabling incremental on sessions is a follow-up once the filter+# and ordering are curl-verified.+++@dataclass+class DevinAIEndpointConfig:+ name: str+ # Path template under the API root; `{org_id}` is filled from the source config.+ 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+++DEVIN_AI_ENDPOINTS: dict[str, DevinAIEndpointConfig] = {+ "sessions": DevinAIEndpointConfig(+ name="sessions",+ path="/v3/organizations/{org_id}/sessions",+ primary_keys=["session_id"],+ ),+ "playbooks": DevinAIEndpointConfig(+ name="playbooks",+ path="/v3/organizations/{org_id}/playbooks",+ primary_keys=["playbook_id"],+ ),+ "knowledge_notes": DevinAIEndpointConfig(+ name="knowledge_notes",+ path="/v3/organizations/{org_id}/knowledge/notes",+ primary_keys=["note_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(+ name="secrets",+ path="/v3/organizations/{org_id}/secrets",+ primary_keys=["secret_id"],+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(DEVIN_AI_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DEVIN_AI_ENDPOINTS.items()+}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 d17a2786fd2b..9baa36ed2cb3 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@@ -1,30 +1,176 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.devin_ai import (+ DevinAIResumeConfig,+ devin_ai_source,+ validate_credentials as validate_devin_ai_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import (+ DEVIN_AI_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DevinAISourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DevinAISource(SimpleSource[DevinAISourceConfig]):+class DevinAISource(ResumableSource[DevinAISourceConfig, DevinAIResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DEVINAI+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored API key is sent against whatever `org_id` is configured, so changing it retargets+ # the saved credential at a different Devin organization — force secret re-entry on a change.+ return ["org_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DEVIN_AI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Devin AI",+ releaseStatus=ReleaseStatus.ALPHA,+ 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+- `ManageAccountKnowledge` — Playbooks and Knowledge notes+- `ManageOrgSecrets` — Secrets (metadata only; values are never synced)++Your organization ID is the `org-...` identifier shown in your Devin organization settings.""",iconPath="/static/services/devin_ai.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/devin-ai",+ keywords=["devin", "cognition", "cognition ai"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="cog_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="org_id",+ label="Organization ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="org-...",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A revoked/invalid key or a key missing the endpoint's RBAC permission surfaces as a+ # requests HTTPError from `raise_for_status()`. Retrying can't fix a credential problem, so+ # stop the sync. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.devin.ai": "Your Devin API key is invalid or has been revoked. Create a new service user API key in your Devin organization settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.devin.ai": "Your Devin service user is missing the organization permission needed to sync this data. Grant the required permission in your Devin organization settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: DevinAISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Devin's v3 list endpoints expose no verified server-side timestamp filter, so every table is+ # full refresh only (see settings.py). Cursor pagination still makes each sync resumable.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=DEVIN_AI_ENDPOINTS[endpoint].primary_keys,+ should_sync_default=DEVIN_AI_ENDPOINTS[endpoint].should_sync_default,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: DevinAISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # Probe the specific table when checking a schema; otherwise probe Sessions as a cheap token check.+ endpoint = schema_name if schema_name in DEVIN_AI_ENDPOINTS else "sessions"+ try:+ status = validate_devin_ai_credentials(config.api_key, config.org_id, endpoint)+ except Exception:+ return False, "Could not reach the Devin API. Check your network connection and try again."++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Devin API key. Check your service user key and organization ID, then reconnect."+ if status == 403:+ # A valid key may legitimately lack the scope for some tables. Accept it at source-create so+ # the user can still sync the tables they do have access to; only fail the per-schema check.+ if schema_name is None:+ return True, None+ return (+ False,+ f"Your Devin service user is missing the organization permission required to sync '{schema_name}'.",+ )+ if status == 404:+ return False, "Organization not found. Check that your Devin organization ID is correct."+ return False, f"Unexpected response from the Devin API (status {status})."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DevinAIResumeConfig]:+ return ResumableSourceManager[DevinAIResumeConfig](inputs, DevinAIResumeConfig)++ def source_for_pipeline(+ self,+ config: DevinAISourceConfig,+ resumable_source_manager: ResumableSourceManager[DevinAIResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return devin_ai_source(+ api_key=config.api_key,+ org_id=config.org_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..883479b6c5ad--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai.py@@ -0,0 +1,236 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai import devin_ai+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.devin_ai import (+ DEVIN_AI_BASE_URL,+ PAGE_SIZE,+ DevinAIResumeConfig,+ _endpoint_path,+ devin_ai_source,+ get_rows,+ get_status_code,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import DEVIN_AI_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: DevinAIResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[DevinAIResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> DevinAIResumeConfig | None:+ return self._state++ def save_state(self, data: DevinAIResumeConfig) -> None:+ self.saved.append(data)+++def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, pages: list[dict]) -> list[dict]:+ """Feed successive `pages` from _fetch_page and return the flattened rows."""+ calls: list[dict[str, Any]] = []++ def fake_fetch(session: Any, url: str, params: dict[str, Any], headers: dict[str, str], logger: Any) -> dict:+ calls.append({"url": url, "params": params})+ return pages[len(calls) - 1]++ monkeypatch.setattr(devin_ai, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for page in get_rows(+ api_key="cog_test",+ org_id="org-abc",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ # get_rows yields one page's items as a list[dict]; the pipeline batches internally.+ rows.extend(page)+ manager.calls = calls # type: ignore[attr-defined]+ return rows+++class TestEndpointPath:+ @parameterized.expand(+ [+ ("sessions", "/v3/organizations/org-abc/sessions"),+ ("playbooks", "/v3/organizations/org-abc/playbooks"),+ ("knowledge_notes", "/v3/organizations/org-abc/knowledge/notes"),+ ("secrets", "/v3/organizations/org-abc/secrets"),+ ]+ )+ def test_org_id_is_interpolated_into_path(self, endpoint: str, expected: str) -> None:+ assert _endpoint_path(endpoint, "org-abc") == expected++ @parameterized.expand(+ [+ ("path_traversal", "org-abc/../billing"),+ ("query_injection", "org-abc?first=1"),+ ("slash", "org/abc"),+ ("empty", ""),+ ("whitespace_only", " "),+ ]+ )+ def test_malicious_org_id_is_rejected(self, _name: str, org_id: str) -> None:+ # A malformed org_id must not be able to inject `/` or `?` to route the stored key elsewhere.+ with pytest.raises(ValueError):+ _endpoint_path("sessions", org_id)+++class TestGetRows:+ def test_yields_items_as_dicts(self, monkeypatch: Any) -> None:+ pages = [{"items": [{"session_id": "s1"}, {"session_id": "s2"}], "has_next_page": False, "end_cursor": None}]+ rows = _collect(_FakeResumableManager(), monkeypatch, "sessions", pages)+ assert rows == [{"session_id": "s1"}, {"session_id": "s2"}]++ def test_first_page_has_no_after_and_uses_page_size(self, monkeypatch: Any) -> None:+ pages = [{"items": [{"session_id": "s1"}], "has_next_page": False, "end_cursor": None}]+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, "sessions", pages)+ first_call = manager.calls[0] # type: ignore[attr-defined]+ assert first_call["params"] == {"first": PAGE_SIZE}++ def test_follows_cursor_pagination(self, monkeypatch: Any) -> None:+ pages = [+ {"items": [{"session_id": "s1"}], "has_next_page": True, "end_cursor": "cur1"},+ {"items": [{"session_id": "s2"}], "has_next_page": False, "end_cursor": None},+ ]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "sessions", pages)+ assert rows == [{"session_id": "s1"}, {"session_id": "s2"}]+ # Second request must carry the cursor from the first page's end_cursor.+ assert manager.calls[1]["params"] == {"first": PAGE_SIZE, "after": "cur1"} # type: ignore[attr-defined]++ def test_stops_when_has_next_page_false_even_if_cursor_present(self, monkeypatch: Any) -> None:+ # A defensive guard: if the API returns a cursor but has_next_page is false, we must not loop.+ pages = [{"items": [{"session_id": "s1"}], "has_next_page": False, "end_cursor": "cur1"}]+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, "sessions", pages)+ assert rows == [{"session_id": "s1"}]+ assert len(manager.calls) == 1 # type: ignore[attr-defined]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ pages = [{"items": [{"session_id": "s3"}], "has_next_page": False, "end_cursor": None}]+ manager = _FakeResumableManager(DevinAIResumeConfig(after="saved_cursor"))+ rows = _collect(manager, monkeypatch, "sessions", pages)+ assert rows == [{"session_id": "s3"}]+ assert manager.calls[0]["params"] == {"first": PAGE_SIZE, "after": "saved_cursor"} # type: ignore[attr-defined]++ def test_saves_next_cursor_at_page_boundary_only(self, monkeypatch: Any) -> None:+ # State is saved once per completed page that has a successor, after the page is yielded — so a+ # crash re-fetches the last page (merge dedupes) rather than skipping its tail.+ pages = [+ {"items": [{"session_id": "s1"}], "has_next_page": True, "end_cursor": "cur1"},+ {"items": [{"session_id": "s2"}], "has_next_page": True, "end_cursor": "cur2"},+ {"items": [{"session_id": "s3"}], "has_next_page": False, "end_cursor": None},+ ]+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, "sessions", pages)+ # No save after the final page (nothing left to resume into).+ assert manager.saved == [DevinAIResumeConfig(after="cur1"), DevinAIResumeConfig(after="cur2")]+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 500),+ ("bad_gateway", 502),+ ]+ )+ def test_retryable_status_codes_are_retried(self, _name: str, status_code: int) -> None:+ retryable = MagicMock()+ retryable.status_code = status_code+ retryable.ok = False++ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"items": []}++ session = MagicMock()+ session.get.side_effect = [retryable, good]++ with patch.object(devin_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = devin_ai._fetch_page(session, f"{DEVIN_AI_BASE_URL}/x", {}, {}, MagicMock())++ assert result == {"items": []}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("chunked_encoding", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ]+ )+ def test_transient_transport_errors_are_retried(self, _name: str, transient_error: Exception) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"items": []}++ session = MagicMock()+ session.get.side_effect = [transient_error, good]++ with patch.object(devin_ai._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = devin_ai._fetch_page(session, f"{DEVIN_AI_BASE_URL}/x", {}, {}, MagicMock())++ assert result == {"items": []}+ assert session.get.call_count == 2++ def test_client_error_raises_immediately(self) -> None:+ forbidden = MagicMock()+ forbidden.status_code = 403+ forbidden.ok = False+ forbidden.raise_for_status.side_effect = requests.HTTPError("403 Client Error", response=forbidden)++ session = MagicMock()+ session.get.return_value = forbidden++ with pytest.raises(requests.HTTPError):+ devin_ai._fetch_page(session, f"{DEVIN_AI_BASE_URL}/x", {}, {}, MagicMock())++ assert session.get.call_count == 1+++class TestGetStatusCode:+ def test_returns_status_and_probes_with_first_one(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response++ with patch.object(devin_ai, "make_tracked_session", return_value=session):+ status = get_status_code("cog_test", "org-abc", "sessions")++ assert status == 200+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"first": 1}+ assert kwargs["headers"]["Authorization"] == "Bearer cog_test"+++class TestDevinAISource:+ @parameterized.expand(list(DEVIN_AI_ENDPOINTS.keys()))+ def test_source_response_uses_endpoint_primary_keys_and_stable_partition(self, endpoint: str) -> None:+ response = devin_ai_source(+ api_key="cog_test",+ org_id="org-abc",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ cfg = DEVIN_AI_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == cfg.primary_keys+ # created_at is a stable field — never updated_at — so partitions don't rewrite each sync.+ assert response.partition_keys == ["created_at"]+ assert response.partition_mode == "datetime"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.pynew file mode 100644index 000000000000..3863c49f157a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/devin_ai/tests/test_devin_ai_source.py@@ -0,0 +1,168 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.devin_ai import DevinAIResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.settings import (+ DEVIN_AI_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.devin_ai.source import DevinAISource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "cog_test", org_id: str = "org-abc") -> Any:+ return source_module.DevinAISourceConfig(api_key=api_key, org_id=org_id)+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert DevinAISource().source_type == ExternalDataSourceType.DEVINAI++ def test_config_declares_api_key_and_org_id_fields(self) -> None:+ fields = DevinAISource().get_source_config.fields+ names = {f.name for f in fields}+ assert names == {"api_key", "org_id"}+ api_key_field = next(f for f in fields if f.name == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.secret is True+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — required so the public docs render the table list.+ assert DevinAISource.lists_tables_without_credentials is True++ def test_connection_host_fields_force_secret_reentry_on_org_change(self) -> None:+ # Changing org_id retargets the stored API key at a different Devin org, so it must count as a+ # host field — editing it forces the user to re-enter the key.+ assert DevinAISource().connection_host_fields == ["org_id"]+++class TestGetSchemas:+ def test_returns_all_endpoints_full_refresh_only(self) -> None:+ schemas = DevinAISource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # No verified server-side timestamp filter, so nothing advertises incremental/append.+ 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:+ 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++ def test_names_filter_restricts_output(self) -> None:+ schemas = DevinAISource().get_schemas(_config(), team_id=1, names=["sessions"])+ assert [s.name for s in schemas] == ["sessions"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = DevinAISource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ sessions = next(t for t in tables if t["name"] == "sessions")+ assert sessions["primary_keys"] == ["session_id"]+ assert "Full refresh" in sessions["sync_methods"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("forbidden_at_create_is_accepted", 403, None, True),+ ("forbidden_for_schema_is_rejected", 403, "sessions", False),+ ("org_not_found", 404, None, False),+ ("unexpected", 500, None, False),+ ]+ )+ def test_status_code_mapping(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ with patch.object(source_module, "validate_devin_ai_credentials", return_value=status):+ ok, _err = DevinAISource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok++ def test_probes_requested_schema_endpoint(self) -> None:+ with patch.object(source_module, "validate_devin_ai_credentials", return_value=200) as mock_validate:+ DevinAISource().validate_credentials(_config(), team_id=1, schema_name="playbooks")+ assert mock_validate.call_args.args[2] == "playbooks"++ def test_unknown_schema_falls_back_to_sessions_probe(self) -> None:+ with patch.object(source_module, "validate_devin_ai_credentials", return_value=200) as mock_validate:+ DevinAISource().validate_credentials(_config(), team_id=1, schema_name="not_a_table")+ assert mock_validate.call_args.args[2] == "sessions"++ def test_transport_failure_is_not_fatal_message(self) -> None:+ with patch.object(source_module, "validate_devin_ai_credentials", side_effect=Exception("boom")):+ ok, err = DevinAISource().validate_credentials(_config(), team_id=1)+ assert ok is False+ assert err is not None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.devin.ai/v3/organizations/org-abc/sessions?first=200",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.devin.ai/v3/organizations/org-abc/secrets"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = DevinAISource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.devin.ai/v3/organizations/org-abc/sessions",+ ),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.devin.ai/v3/organizations/org-abc/sessions",+ ),+ ("read_timeout", "HTTPSConnectionPool(host='api.devin.ai', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_stay_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = DevinAISource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock()+ manager = DevinAISource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)++ def test_source_for_pipeline_plumbs_config_through(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "sessions"+ manager = MagicMock()+ with patch.object(source_module, "devin_ai_source") as mock_source:+ DevinAISource().source_for_pipeline(_config(api_key="cog_k", org_id="org-x"), manager, inputs)+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "cog_k"+ assert kwargs["org_id"] == "org-x"+ assert kwargs["endpoint"] == "sessions"+ assert kwargs["resumable_source_manager"] is manager+++class TestCanonicalDescriptions:+ def test_every_endpoint_has_a_canonical_description(self) -> None:+ descriptions = DevinAISource().get_canonical_descriptions()+ for endpoint in DEVIN_AI_ENDPOINTS:+ assert endpoint in descriptions+ entry = descriptions[endpoint]+ # Primary key columns must be documented so enrichment doesn't fall back to the LLM for them.+ for pk in DEVIN_AI_ENDPOINTS[endpoint].primary_keys:+ assert pk in entry["columns"]+++def test_resume_config_default_is_none() -> None:+ assert DevinAIResumeConfig().after is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex f66742ca5de5..a731795f239e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -948,7 +948,8 @@ class DeputySourceConfig(config.Config):@config.configclass DevinAISourceConfig(config.Config):- pass+ api_key: str+ org_id: str@config.config