: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 cody import source (#70709)
Tom Owers7e18c00c112d
diff --git a/frontend/public/services/cody.svg b/frontend/public/services/cody.svgnew file mode 100644index 000000000000..01cf65c6e86c--- /dev/null+++ b/frontend/public/services/cody.svg@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<svg viewBox="0 0 195 176" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path fill-rule="evenodd" clip-rule="evenodd" d="M141.819 -8.93872e-07C152.834 -4.002e-07 161.763 9.02087 161.763 20.1487L161.763 55.9685C161.763 67.0964 152.834 76.1172 141.819 76.1172C130.805 76.1172 121.876 67.0963 121.876 55.9685L121.876 20.1487C121.876 9.02087 130.805 -1.38754e-06 141.819 -8.93872e-07Z" fill="#FF5543"/>+ <path fill-rule="evenodd" clip-rule="evenodd" d="M15.5111 47.0133C15.5111 35.8855 24.44 26.8646 35.4543 26.8646H70.9088C81.9231 26.8646 90.8519 35.8855 90.8519 47.0133C90.8519 58.1411 81.9231 67.162 70.9088 67.162H35.4543C24.44 67.162 15.5111 58.1411 15.5111 47.0133Z" fill="#A112FF"/>+ <path fill-rule="evenodd" clip-rule="evenodd" d="M189.482 105.669C196.58 112.482 196.868 123.818 190.125 130.989L183.85 137.662C134.75 189.88 51.971 188.579 4.50166 134.844C-2.01751 127.464 -1.38097 116.142 5.92343 109.556C13.2278 102.97 24.434 103.613 30.9532 110.993C64.6181 149.101 123.324 150.024 158.146 112.991L164.42 106.318C171.164 99.1472 182.384 98.8565 189.482 105.669Z" fill="#00CBEC"/>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a300d329900b..000c9e720ce8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -111,6 +111,7 @@ the row lists both.| coassemble | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || codefresh | HTTP | requests | ✅ |+| cody | HTTP (CSV reports) | requests | ✅ || cohere | HTTP | requests | ✅ || coin_api | HTTP | requests | ✅ || coingecko | HTTP | requests | ✅ |@@ -575,7 +576,6 @@ doesn't conflict with concurrent PRs.- cockroachdb- codacy- codecov-- cody- confluent_cloud- constant_contact- copperdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/canonical_descriptions.pynew file mode 100644index 000000000000..cf58693b55ce--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/canonical_descriptions.py@@ -0,0 +1,31 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://sourcegraph.com/docs/analytics/api"++# Table-level descriptions only: Sourcegraph doesn't publish the CSV column schema for these+# reports, so column descriptions are left to the LLM enrichment pass (which receives the+# docs_url below) rather than curated from guesses.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "usage_by_user": {+ "description": "All-time Sourcegraph and Cody usage totals per user, including searches, chats, code completions, and completion acceptance rates.",+ "docs_url": _DOCS_URL,+ },+ "usage_by_user_month": {+ "description": "Monthly Sourcegraph and Cody usage totals per user, one row per user per calendar month of activity.",+ "docs_url": _DOCS_URL,+ },+ "usage_by_user_day": {+ "description": "Daily Sourcegraph and Cody usage totals per user, one row per user per day of activity.",+ "docs_url": _DOCS_URL,+ },+ "usage_by_user_day_client_language": {+ "description": "Daily Sourcegraph and Cody usage per user, split by client/editor and programming language. The most detailed usage report the Analytics API offers.",+ "docs_url": _DOCS_URL,+ },+ "credits": {+ "description": "Credit bucket allocations and consumption for the Sourcegraph instance, filtered by each bucket's active period.",+ "docs_url": _DOCS_URL,+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/cody.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/cody.pynew file mode 100644index 000000000000..ce8b14392419--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/cody.py@@ -0,0 +1,307 @@+import io+import re+import csv+import dataclasses+from collections.abc import Iterable, Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cody.settings import (+ CODY_ENDPOINTS,+ REPORTS_PATH,+ CodyEndpointConfig,+)+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++CODY_BASE_URL = "https://analytics.sourcegraph.com"+# Sourcegraph Analytics is fed by telemetry V2, which first shipped in Sourcegraph 5.2 (late+# 2023) — no instance has analytics data before then, so windowed backfills start here.+WINDOW_ORIGIN = date(2023, 1, 1)+REQUEST_TIMEOUT_SECONDS = 300+MAX_RETRY_ATTEMPTS = 5+# Yield rows in chunks so huge reports don't build one giant list.+CHUNK_SIZE = 5000+++class CodyRetryableError(Exception):+ pass+++class CodyCredentialsError(Exception):+ """A credential check failed for a reason we can explain to the user (bad token, bad instance URL)."""++ pass+++class CodyResumeConfig:+ # ISO date (YYYY-MM-DD) of the first day of the calendar-month window to resume from.+ window_start: str+++def _make_session(access_token: str) -> requests.Session:+ # Redirects are pinned off so the token can't be replayed to a cross-host redirect target;+ # urllib3 retries are disabled so tenacity (on `_fetch`) is the single retry layer.+ return make_tracked_session(+ headers={"Authorization": f"Bearer {access_token}"},+ redact_values=(access_token,),+ allow_redirects=False,+ retry=Retry(total=0),+ )+++def normalize_instance_url(instance_url: str) -> str:+ """The API expects a bare host (`example.sourcegraphcloud.com`); tolerate pasted URLs."""+ host = re.sub(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", "", instance_url.strip())+ return host.split("/")[0]+++def _normalize_header(header: str) -> str:+ """CSV headers like 'Completion Acceptance Rate (CAR%)' become stable snake_case columns."""+ return re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()+++def _build_url(+ config: CodyEndpointConfig,+ instance_url: str,+ start: Optional[date] = None,+ end: Optional[date] = None,+) -> str:+ params: dict[str, str] = {"instanceURL": normalize_instance_url(instance_url)}+ if config.granularity is not None:+ params["granularity"] = config.granularity+ if start is not None:+ params["startDate"] = start.isoformat()+ if end is not None:+ params["endDate"] = end.isoformat()+ return f"{CODY_BASE_URL}{config.path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type(+ (+ CodyRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> requests.Response:+ # Streamed so report bodies of any size never get buffered whole — `_parse_csv_rows`+ # consumes the body incrementally and memory stays bounded by the chunk size.+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)++ if response.status_code == 429 or response.status_code >= 500:+ response.close()+ raise CodyRetryableError(f"Sourcegraph Analytics API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(+ f"Sourcegraph Analytics API error: status={response.status_code}, body={response.text[:500]}, url={url}"+ )+ response.raise_for_status()++ return response+++def _parse_csv_rows(lines: Iterable[str], logger: FilteringBoundLogger | None = None) -> Iterator[dict[str, Any]]:+ reader = csv.reader(lines)+ headers: list[str] | None = None+ for row in reader:+ if headers is None:+ headers = [_normalize_header(header) for header in row]+ continue+ if not any(cell.strip() for cell in row):+ continue+ # zip would silently truncate a short row, leaving columns absent for that row —+ # drop the malformed row instead so the failure is explicit.+ if len(row) != len(headers):+ if logger is not None:+ logger.warning(+ "Cody CSV row length mismatch; skipping row",+ expected=len(headers),+ got=len(row),+ )+ continue+ yield dict(zip(headers, row))+++def _rows_from_response(response: requests.Response, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:+ """Parse rows out of a report response, handling both CSV and JSON bodies.++ The reports endpoint is documented as CSV; the credits endpoint's format isn't documented,+ so sniff the content type rather than assuming.+ """+ content_type = response.headers.get("Content-Type", "")+ if "json" in content_type:+ # Credit buckets are a small payload; buffering the JSON body is fine.+ payload = response.json()+ if isinstance(payload, list):+ rows = payload+ elif isinstance(payload, dict):+ # A wrapped shape like {"buckets": [...]} — take the first list value, else the dict itself.+ rows = next((value for value in payload.values() if isinstance(value, list)), [payload])+ else:+ rows = []+ for row in rows:+ if isinstance(row, dict):+ yield row+ return++ # Stream-parse the CSV instead of materializing `response.text`, so an arbitrarily large+ # report can't exhaust worker memory. `.raw` bypasses requests' content decoding, so turn+ # it back on for gzipped responses; newline="" lets the csv module handle quoted newlines.+ response.raw.decode_content = True+ yield from _parse_csv_rows(io.TextIOWrapper(response.raw, encoding="utf-8", newline=""), logger)+++def validate_credentials(access_token: str, instance_url: str) -> bool:+ """Confirm the token and instance URL with a cheap one-day, per-user report probe.++ Returns ``True`` when the probe succeeds. Raises ``CodyCredentialsError`` with a+ user-facing message when the API rejects the token or the instance isn't accessible,+ ``CodyRetryableError`` on rate-limit / 5xx responses, and lets transport errors propagate+ so the caller can tell a transient failure apart from a bad credential.+ """+ today = datetime.now(UTC).date()+ config = CodyEndpointConfig(name="probe", path=REPORTS_PATH, granularity="by_user")+ # Stream and close without reading the body: validation only inspects the status code, so a+ # large per-user report never gets buffered into the API worker.+ response = _make_session(access_token).get(+ _build_url(config, instance_url, start=today, end=today),+ timeout=30,+ stream=True,+ )+ response.close()+ if response.status_code == 429 or response.status_code >= 500:+ raise CodyRetryableError(f"Sourcegraph Analytics API error (retryable): status={response.status_code}")+ if response.status_code == 200:+ return True+ if response.status_code == 401:+ raise CodyCredentialsError(+ "Sourcegraph rejected the access token. Create a new token at "+ "analytics.sourcegraph.com under Access tokens, then reconnect."+ )+ if response.status_code in (403, 404):+ raise CodyCredentialsError(+ "Sourcegraph denied access to that instance's analytics. Check the instance URL "+ "(e.g. example.sourcegraphcloud.com) and that your Sourcegraph account has access "+ "to Sourcegraph Analytics for it."+ )+ raise CodyCredentialsError(+ f"Sourcegraph Analytics returned an unexpected response (HTTP {response.status_code}) while "+ "validating credentials. If your instance URL and access token look correct, please try "+ "again shortly or contact support."+ )+++def _chunk_rows(rows: Iterator[dict[str, Any]]) -> Iterator[list[dict[str, Any]]]:+ chunk: list[dict[str, Any]] = []+ for row in rows:+ chunk.append(row)+ if len(chunk) >= CHUNK_SIZE:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def _month_windows(start: date, today: date) -> Iterator[tuple[date, date]]:+ """Calendar-month windows from `start` through `today` (inclusive bounds, last one clipped)."""+ window_start = start+ while window_start <= today:+ if window_start.month == 12:+ next_month = date(window_start.year + 1, 1, 1)+ else:+ next_month = date(window_start.year, window_start.month + 1, 1)+ yield window_start, min(next_month - timedelta(days=1), today)+ window_start = next_month+++def _get_rows(+ session: requests.Session,+ config: CodyEndpointConfig,+ instance_url: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Single all-time request for aggregate reports and credits. Small tables, no checkpointing:+ a worker restart simply re-fetches."""+ response = _fetch(session, _build_url(config, instance_url), logger)+ yield from _chunk_rows(_rows_from_response(response, logger))+++def _get_windowed_rows(+ session: requests.Session,+ config: CodyEndpointConfig,+ instance_url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Walk the day-grain reports in calendar-month windows, checkpointing after each window.++ startDate/endDate filter server-side, so each window is an independent fetch and a resumed+ job picks up at the checkpointed window instead of re-downloading the whole history."""+ today = datetime.now(UTC).date()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None:+ start = date.fromisoformat(resume.window_start)+ logger.debug(f"Cody: resuming {config.name} from window_start={start.isoformat()}")+ else:+ start = WINDOW_ORIGIN++ for window_start, window_end in _month_windows(start, today):+ response = _fetch(session, _build_url(config, instance_url, start=window_start, end=window_end), logger)+ yield from _chunk_rows(_rows_from_response(response, logger))++ # Checkpoint AFTER the window's rows are yielded, so a crash re-fetches the current+ # window rather than skipping it.+ next_window = window_end + timedelta(days=1)+ if next_window <= today:+ resumable_source_manager.save_state(CodyResumeConfig(window_start=next_window.isoformat()))++ # The walk finished cleanly, so drop the checkpoint. Otherwise a later attempt in the same+ # job (e.g. a retry that re-runs extract after the previous one completed) would resume from+ # the final window and skip everything before it.+ resumable_source_manager.clear_state()+++def cody_source(+ access_token: str,+ instance_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CodyResumeConfig],+) -> SourceResponse:+ config = CODY_ENDPOINTS.get(endpoint)+ if config is None:+ raise ValueError(f"Unknown Cody endpoint: {endpoint}")++ def get_rows() -> Iterator[list[dict[str, Any]]]:+ session = _make_session(access_token)++ if config.windowed:+ yield from _get_windowed_rows(session, config, instance_url, logger, resumable_source_manager)+ else:+ yield from _get_rows(session, config, instance_url, logger)++ return SourceResponse(+ name=endpoint,+ # The CSV column names aren't published and can't be verified without an Enterprise+ # token, so no primary keys are declared — every endpoint is full refresh (replace).+ items=get_rows,+ primary_keys=None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/settings.pynew file mode 100644index 000000000000..a52a2a4601b2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/settings.py@@ -0,0 +1,69 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++REPORTS_PATH = "/api/reports/by-user-client-date"+CREDITS_PATH = "/api/credits"+++@dataclass+class CodyEndpointConfig:+ name: str+ path: str+ # Value for the reports endpoint's `granularity` query param; None for non-report endpoints.+ granularity: Optional[str] = None+ # Whether syncs chunk the fetch into calendar-month startDate/endDate windows. Only valid for+ # day-grain granularities — windowing an aggregate report (e.g. by_user) would turn its+ # all-time totals into per-window totals and change the table's meaning.+ windowed: bool = False+ # The Analytics API filters server-side on startDate/endDate, but the CSV column names+ # (including the date column an incremental cursor would track) aren't documented, so every+ # endpoint ships full refresh until the response schema can be verified against a live token.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ description: Optional[str] = None+ should_sync_default: bool = True+++CODY_ENDPOINTS: dict[str, CodyEndpointConfig] = {+ "usage_by_user": CodyEndpointConfig(+ name="usage_by_user",+ path=REPORTS_PATH,+ granularity="by_user",+ description="All-time usage totals per user (searches, chats, completions, acceptance rates). Full refresh only",+ should_sync_default=False,+ ),+ "usage_by_user_month": CodyEndpointConfig(+ name="usage_by_user_month",+ path=REPORTS_PATH,+ granularity="by_user_month",+ description="Monthly usage totals per user. Full refresh only",+ should_sync_default=False,+ ),+ "usage_by_user_day": CodyEndpointConfig(+ name="usage_by_user_day",+ path=REPORTS_PATH,+ granularity="by_user_day",+ windowed=True,+ description="Daily usage totals per user. Full refresh only",+ should_sync_default=False,+ ),+ "usage_by_user_day_client_language": CodyEndpointConfig(+ name="usage_by_user_day_client_language",+ path=REPORTS_PATH,+ granularity="by_user_day_client_language",+ windowed=True,+ description="Daily usage per user, split by client/editor and programming language (the most detailed report). Full refresh only",+ ),+ "credits": CodyEndpointConfig(+ name="credits",+ path=CREDITS_PATH,+ description="Credit bucket allocations and consumption for the instance. Full refresh only",+ ),+}++ENDPOINTS = tuple(CODY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CODY_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/source.pyindex bfca485b6097..9e11380ff643 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/source.py@@ -1,31 +1,168 @@-from typing import cast+from typing import Optional, cast++import requestsfrom 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.cody.cody import (+ CODY_BASE_URL,+ CodyCredentialsError,+ CodyResumeConfig,+ CodyRetryableError,+ cody_source,+ validate_credentials as validate_cody_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cody.settings import (+ CODY_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CodySource(SimpleSource[CodySourceConfig]):+class CodySource(ResumableSource[CodySourceConfig, CodyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CODY+ @property+ def connection_host_fields(self) -> list[str]:+ # instance_url selects which instance's analytics the stored token is used against;+ # changing it must require re-entering the secret so a preserved token can't be+ # retargeted at another instance.+ return ["instance_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CODY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cody",- iconPath="/static/services/cody.png",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Sourcegraph Analytics access token to pull Cody and Sourcegraph usage reports into the PostHog Data warehouse.++Sourcegraph Analytics is available to Sourcegraph Enterprise customers. Create an access token at [analytics.sourcegraph.com/access-tokens](https://analytics.sourcegraph.com/access-tokens). The instance URL is your Sourcegraph instance's host, e.g. `example.sourcegraphcloud.com`.+""",+ iconPath="/static/services/cody.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/cody",keywords=["ai coding assistant", "developer analytics", "sourcegraph", "usage"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="instance_url",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="example.sourcegraphcloud.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cody.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked access token surfaces as a requests HTTPError when `_fetch`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Match the stable status text and base host, not the per-request path.+ f"401 Client Error: Unauthorized for url: {CODY_BASE_URL}": "Your Sourcegraph Analytics access token is invalid or has expired. Create a new token at analytics.sourcegraph.com under Access tokens, then reconnect.",+ f"403 Client Error: Forbidden for url: {CODY_BASE_URL}": "Your Sourcegraph account does not have access to this instance's analytics. Check the instance URL and that your account is linked to the instance's usage metrics.",+ }++ def get_schemas(+ self,+ config: CodySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=CODY_ENDPOINTS[endpoint].should_sync_default,+ description=CODY_ENDPOINTS[endpoint].description,+ )+ 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: CodySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ # validate_cody_credentials returns True or raises — it never returns False — so an+ # unexpected status surfaces its real cause instead of a conflated credential error.+ validate_cody_credentials(config.access_token, config.instance_url)+ return True, None+ except CodyCredentialsError as e:+ return False, str(e)+ except (CodyRetryableError, requests.RequestException):+ # A rate-limit, 5xx, or network blip isn't a bad credential — don't mislabel it.+ return (+ False,+ "Could not reach Sourcegraph Analytics to validate credentials. This may be a temporary rate-limit or network issue — please try again.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CodyResumeConfig]:+ return ResumableSourceManager[CodyResumeConfig](inputs, CodyResumeConfig)++ def source_for_pipeline(+ self,+ config: CodySourceConfig,+ resumable_source_manager: ResumableSourceManager[CodyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return cody_source(+ access_token=config.access_token,+ instance_url=config.instance_url,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.pynew file mode 100644index 000000000000..8966a54e67e3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody.py@@ -0,0 +1,327 @@+import io+from collections.abc import Iterable, Iterator+from datetime import date+from typing import Any, cast+from urllib.parse import parse_qs, urlparse++import pytest+from freezegun import freeze_time+from unittest import mock++import urllib3+import requests+from parameterized import parameterized+from tenacity import wait_none++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cody import cody+from products.warehouse_sources.backend.temporal.data_imports.sources.cody.cody import (+ CodyCredentialsError,+ CodyResumeConfig,+ CodyRetryableError,+ _month_windows,+ _parse_csv_rows,+ _rows_from_response,+ cody_source,+ normalize_instance_url,+ validate_credentials,+)++CSV_BODY = "User Email,Chats,Completion Acceptance Rate (CAR%)\[email protected],12,0.5\[email protected],3,0.25\n"++[email protected](autouse=True)+def _instant_retries():+ fetch: Any = cody._fetch # the tenacity wrapper's `retry` attribute isn't in the Callable type+ original_wait = fetch.retry.wait+ fetch.retry.wait = wait_none()+ yield+ fetch.retry.wait = original_wait+++def _response(+ status_code: int = 200,+ text: str = "",+ content_type: str = "text/csv",+ json_data: Any = None,+) -> requests.Response:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status_code+ response.ok = status_code < 400+ response.text = text+ response.headers = {"Content-Type": content_type}+ response.json.return_value = json_data+ # The CSV path stream-parses `response.raw`; a real urllib3 response over the body keeps+ # the `decode_content` + TextIOWrapper plumbing honest.+ response.raw = urllib3.response.HTTPResponse(body=io.BytesIO(text.encode("utf-8")), preload_content=False)+ typed = cast(requests.Response, response)+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: Error for url: {cody.CODY_BASE_URL}/x", response=typed+ )+ return typed+++def _manager(resume_state: CodyResumeConfig | None = None) -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _batches(source: SourceResponse) -> Iterator[list[dict[str, Any]]]:+ return iter(cast(Iterable[list[dict[str, Any]]], source.items()))+++def _requested_urls(session: mock.Mock) -> list[str]:+ return [call.args[0] for call in session.get.call_args_list]+++class TestCodyTransport:+ @parameterized.expand(+ [+ # (start, today, expected inclusive windows)+ (date(2023, 1, 1), date(2023, 1, 15), [(date(2023, 1, 1), date(2023, 1, 15))]),+ (date(2023, 1, 1), date(2023, 1, 31), [(date(2023, 1, 1), date(2023, 1, 31))]),+ (+ date(2023, 1, 1),+ date(2023, 3, 2),+ [+ (date(2023, 1, 1), date(2023, 1, 31)),+ (date(2023, 2, 1), date(2023, 2, 28)),+ (date(2023, 3, 1), date(2023, 3, 2)),+ ],+ ),+ (+ date(2023, 12, 1),+ date(2024, 1, 5),+ [(date(2023, 12, 1), date(2023, 12, 31)), (date(2024, 1, 1), date(2024, 1, 5))],+ ),+ ]+ )+ def test_month_windows_cover_range_without_gaps(self, start, today, expected):+ windows = list(_month_windows(start, today))++ assert windows == expected+ for (_, prev_end), (next_start, _) in zip(windows, windows[1:]):+ assert (next_start - prev_end).days == 1 # inclusive bounds — no gap, no overlap++ @parameterized.expand(+ [+ ("example.sourcegraphcloud.com", "example.sourcegraphcloud.com"),+ ("https://example.sourcegraphcloud.com", "example.sourcegraphcloud.com"),+ ("https://example.sourcegraphcloud.com/", "example.sourcegraphcloud.com"),+ ("http://example.com/some/path", "example.com"),+ (" example.com ", "example.com"),+ ]+ )+ def test_normalize_instance_url_strips_scheme_and_path(self, raw, expected):+ assert normalize_instance_url(raw) == expected++ def test_parse_csv_rows_normalizes_headers(self):+ rows = list(_parse_csv_rows(io.StringIO(CSV_BODY)))++ assert rows == [+ {"user_email": "[email protected]", "chats": "12", "completion_acceptance_rate_car": "0.5"},+ {"user_email": "[email protected]", "chats": "3", "completion_acceptance_rate_car": "0.25"},+ ]++ def test_parse_csv_rows_skips_malformed_and_blank_rows(self):+ # A short row zipped against the headers would silently drop trailing columns for+ # that row — it must be skipped, not half-parsed.+ text = "a,b\n1\n\n2,3\n"+ logger = mock.Mock()++ rows = list(_parse_csv_rows(io.StringIO(text), logger))++ assert rows == [{"a": "2", "b": "3"}]+ logger.warning.assert_called_once()++ @parameterized.expand(+ [+ # The credits endpoint's format isn't documented — both JSON shapes and CSV must parse.+ ("application/json", None, [{"id": "b1"}, {"id": "b2"}], [{"id": "b1"}, {"id": "b2"}]),+ ("application/json; charset=utf-8", None, {"buckets": [{"id": "b1"}]}, [{"id": "b1"}]),+ ("application/json", None, {"id": "b1"}, [{"id": "b1"}]),+ ("text/csv", "id,amount\nb1,10\n", None, [{"id": "b1", "amount": "10"}]),+ ]+ )+ def test_rows_from_response_sniffs_json_and_csv(self, content_type, text, json_data, expected):+ response = _response(200, text=text or "", content_type=content_type, json_data=json_data)++ assert list(_rows_from_response(response, mock.Mock())) == expected++ def test_validate_credentials_probes_one_day_by_user_report(self):+ session = mock.Mock()+ session.get.return_value = _response(200, text=CSV_BODY)++ with (+ freeze_time("2025-06-15"),+ mock.patch.object(cody, "make_tracked_session", return_value=session),+ ):+ assert validate_credentials("token", "example.com") is True++ url = session.get.call_args.args[0]+ assert "granularity=by_user" in url+ assert "startDate=2025-06-15" in url and "endDate=2025-06-15" in url+ assert "instanceURL=example.com" in url+ # Probe must stream and never read the body — a large per-user report can't be buffered.+ assert session.get.call_args.kwargs["stream"] is True+ session.get.return_value.close.assert_called_once()++ @parameterized.expand([(401,), (403,), (404,), (400,)])+ def test_validate_credentials_raises_user_facing_error(self, status_code):+ session = mock.Mock()+ session.get.return_value = _response(status_code)++ with mock.patch.object(cody, "make_tracked_session", return_value=session):+ with pytest.raises(CodyCredentialsError):+ validate_credentials("token", "example.com")++ @parameterized.expand([(429,), (500,), (503,)])+ def test_validate_credentials_raises_retryable_on_transient_status(self, status_code):+ # A rate limit or 5xx must not be conflated with a bad credential.+ session = mock.Mock()+ session.get.return_value = _response(status_code)++ with mock.patch.object(cody, "make_tracked_session", return_value=session):+ with pytest.raises(CodyRetryableError):+ validate_credentials("token", "example.com")++ def test_session_masks_token_and_sends_bearer_auth(self):+ # The tracked transport logs and samples requests; without redaction the raw token+ # would leak into HTTP telemetry.+ with mock.patch.object(cody, "make_tracked_session") as make_session:+ cody._make_session("sgat_token")++ kwargs = make_session.call_args.kwargs+ assert kwargs["headers"]["Authorization"] == "Bearer sgat_token"+ assert "sgat_token" in kwargs["redact_values"]+ assert kwargs["allow_redirects"] is False++ @parameterized.expand([(429,), (500,), (503,)])+ def test_fetch_retries_transient_errors(self, status_code):+ session = mock.Mock()+ session.get.side_effect = [_response(status_code), _response(200, text=CSV_BODY)]++ result = cody._fetch(session, f"{cody.CODY_BASE_URL}/api/credits", mock.Mock())++ assert result.status_code == 200+ assert session.get.call_count == 2++ def test_fetch_raises_on_client_error_without_retry(self):+ session = mock.Mock()+ session.get.return_value = _response(401)++ with pytest.raises(requests.HTTPError):+ cody._fetch(session, f"{cody.CODY_BASE_URL}/api/credits", mock.Mock())++ assert session.get.call_count == 1++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown Cody endpoint"):+ cody_source("token", "example.com", "audit_logs", mock.Mock(), _manager())++ @parameterized.expand([(endpoint,) for endpoint in cody.CODY_ENDPOINTS])+ def test_source_response_shape(self, endpoint):+ response = cody_source("token", "example.com", endpoint, mock.Mock(), _manager())++ assert response.name == endpoint+ assert response.primary_keys is None+ assert response.sort_mode == "asc"++ @parameterized.expand(+ [+ ("usage_by_user", "by_user"),+ ("usage_by_user_month", "by_user_month"),+ ]+ )+ def test_aggregate_reports_fetch_all_time_in_one_request(self, endpoint, granularity):+ # Windowing an aggregate report would change per-user totals to per-window totals,+ # so these must go out as a single request with no date bounds.+ manager = _manager()+ session = mock.Mock()+ session.get.return_value = _response(200, text=CSV_BODY)++ with mock.patch.object(cody, "make_tracked_session", return_value=session):+ batches = list(_batches(cody_source("token", "example.com", endpoint, mock.Mock(), manager)))++ assert [len(batch) for batch in batches] == [2]+ params = parse_qs(urlparse(session.get.call_args.args[0]).query)+ assert params == {"instanceURL": ["example.com"], "granularity": [granularity]}+ manager.save_state.assert_not_called()++ def test_credits_requests_without_granularity(self):+ session = mock.Mock()+ session.get.return_value = _response(200, text="id,amount\nb1,10\n")++ with mock.patch.object(cody, "make_tracked_session", return_value=session):+ batches = list(_batches(cody_source("token", "example.com", "credits", mock.Mock(), _manager())))++ assert batches == [[{"id": "b1", "amount": "10"}]]+ url = session.get.call_args.args[0]+ assert url.startswith(f"{cody.CODY_BASE_URL}/api/credits?")+ assert "granularity" not in url+ # Reports must stay streamed — buffering the whole body lets a huge report OOM the worker.+ assert session.get.call_args.kwargs["stream"] is True++ def test_windowed_endpoint_walks_months_from_origin_and_checkpoints(self):+ manager = _manager()+ session = mock.Mock()+ # A fresh response per window — each one's raw stream is consumed exactly once.+ session.get.side_effect = lambda *args, **kwargs: _response(200, text=CSV_BODY)++ with (+ freeze_time("2023-03-15"),+ mock.patch.object(cody, "make_tracked_session", return_value=session),+ ):+ batches = list(_batches(cody_source("token", "example.com", "usage_by_user_day", mock.Mock(), manager)))++ urls = _requested_urls(session)+ assert len(urls) == 3 # Jan, Feb, and the clipped March window+ assert "startDate=2023-01-01" in urls[0] and "endDate=2023-01-31" in urls[0]+ assert "startDate=2023-02-01" in urls[1] and "endDate=2023-02-28" in urls[1]+ assert "startDate=2023-03-01" in urls[2] and "endDate=2023-03-15" in urls[2]+ assert all("granularity=by_user_day" in url for url in urls)+ assert len(batches) == 3++ # A checkpoint lands after each fully-yielded window except the final one, and the+ # completed walk clears state so a same-job retry restarts from the origin.+ saved = [call.args[0].window_start for call in manager.save_state.call_args_list]+ assert saved == ["2023-02-01", "2023-03-01"]+ manager.clear_state.assert_called_once()++ def test_windowed_endpoint_resumes_from_saved_window(self):+ manager = _manager(CodyResumeConfig(window_start="2023-03-01"))+ session = mock.Mock()+ session.get.return_value = _response(200, text=CSV_BODY)++ with (+ freeze_time("2023-03-15"),+ mock.patch.object(cody, "make_tracked_session", return_value=session),+ ):+ list(_batches(cody_source("token", "example.com", "usage_by_user_day", mock.Mock(), manager)))++ urls = _requested_urls(session)+ assert len(urls) == 1 # earlier windows are not re-fetched+ assert "startDate=2023-03-01" in urls[0] and "endDate=2023-03-15" in urls[0]++ def test_windowed_endpoint_checkpoints_only_after_rows_are_consumed(self):+ manager = _manager()+ session = mock.Mock()+ session.get.side_effect = lambda *args, **kwargs: _response(200, text=CSV_BODY)++ with (+ freeze_time("2023-02-10"),+ mock.patch.object(cody, "make_tracked_session", return_value=session),+ ):+ iterator = _batches(cody_source("token", "example.com", "usage_by_user_day", mock.Mock(), manager))++ next(iterator)+ # The generator is suspended at the yield — nothing saved until the consumer has+ # taken the batch, so a crash mid-batch re-fetches the window instead of skipping it.+ assert manager.save_state.call_count == 0++ list(iterator)++ assert [call.args[0].window_start for call in manager.save_state.call_args_list] == ["2023-02-01"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody_source.pynew file mode 100644index 000000000000..020916a35a42--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cody/tests/test_cody_source.py@@ -0,0 +1,166 @@+from typing import Any++from unittest import mock++import requests+from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ SourceFieldInputConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.cody.cody import (+ CodyCredentialsError,+ CodyResumeConfig,+ CodyRetryableError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cody.source import CodySource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CodySourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++ALL_ENDPOINTS = [+ "usage_by_user",+ "usage_by_user_month",+ "usage_by_user_day",+ "usage_by_user_day_client_language",+ "credits",+]+++def _make_inputs(**overrides) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "usage_by_user_day_client_language",+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": mock.Mock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestCodySource:+ def setup_method(self):+ self.source = CodySource()+ self.config = CodySourceConfig(instance_url="example.sourcegraphcloud.com", access_token="token")+ self.team_id = 123++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CODY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name == SchemaExternalDataSourceType.CODY+ assert config.label == "Cody"+ assert len(config.fields) == 2+ instance_url, access_token = config.fields+ assert isinstance(instance_url, SourceFieldInputConfig)+ assert instance_url.name == "instance_url"+ assert instance_url.required is True+ assert instance_url.secret is False+ assert isinstance(access_token, SourceFieldInputConfig)+ assert access_token.name == "access_token"+ assert access_token.required is True+ assert access_token.secret is True+ # The docs slug is derived from docsUrl; a mismatch 404s the public doc.+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cody"++ def test_instance_url_requires_reentering_secret_on_change(self):+ # Retargeting the instance without re-entering the token would let a preserved+ # credential be pointed at another instance's analytics.+ assert self.source.connection_host_fields == ["instance_url"]++ def test_get_schemas_returns_all_endpoints_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert [s.name for s in schemas] == ALL_ENDPOINTS+ # The CSV column schema is unpublished, so no endpoint may advertise incremental or+ # append sync — a declared-but-wrong cursor field would corrupt the watermark.+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_default_on_tables(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["usage_by_user_day_client_language"].should_sync_default is True+ assert schemas["credits"].should_sync_default is True+ # Coarser rollups are derivable from the detailed report, so they start disabled.+ assert schemas["usage_by_user"].should_sync_default is False+ assert schemas["usage_by_user_month"].should_sync_default is False+ assert schemas["usage_by_user_day"].should_sync_default is False++ def test_get_schemas_filters_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["credits"])++ assert [s.name for s in schemas] == ["credits"]++ def test_get_documented_tables_lists_endpoints_without_credentials(self):+ # lists_tables_without_credentials=True drives the public docs' Supported tables section.+ tables = self.source.get_documented_tables()++ assert [t["name"] for t in tables] == ALL_ENDPOINTS+ assert all(t["description"] for t in tables)++ def test_validate_credentials_success(self):+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cody.source.validate_cody_credentials",+ return_value=True,+ ) as validate:+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)++ validate.assert_called_once_with("token", "example.sourcegraphcloud.com")++ @parameterized.expand(+ [+ (CodyCredentialsError("Sourcegraph rejected the access token."), "Sourcegraph rejected the access token."),+ (CodyRetryableError("status=503"), "Could not reach Sourcegraph Analytics"),+ (requests.ConnectionError("boom"), "Could not reach Sourcegraph Analytics"),+ ]+ )+ def test_validate_credentials_failure_messages(self, raised, expected_prefix):+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cody.source.validate_cody_credentials",+ side_effect=raised,+ ):+ valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert valid is False+ assert message is not None and message.startswith(expected_prefix)++ @parameterized.expand([("401 Client Error",), ("403 Client Error",)])+ def test_non_retryable_errors_cover_credential_failures(self, status):+ keys = self.source.get_non_retryable_errors()+ assert any(key.startswith(status) and "analytics.sourcegraph.com" in key for key in keys)++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert manager._data_class is CodyResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self):+ inputs = _make_inputs()+ manager = mock.Mock()++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cody.source.cody_source"+ ) as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ access_token="token",+ instance_url="example.sourcegraphcloud.com",+ endpoint="usage_by_user_day_client_language",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )diff --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 fef71da83789..ec7ed0c4d844 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@@ -922,7 +922,8 @@ class CodefreshSourceConfig(config.Config):@config.configclass CodySourceConfig(config.Config):- pass+ instance_url: str+ access_token: str@config.config