:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Octolens source (#77098)
Tom Owers72fb762f94a4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 477d8d0e5bd3..59256081a31e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -432,6 +432,7 @@ the row lists both.| news_api | HTTP | requests | ✅ || newsdata | HTTP | requests | ✅ || npm_registry | HTTP | requests | ✅ |+| octolens | HTTP (POST body cursor) | requests + `rest_source.RESTClient` | ✅ || okendo | HTTP (cursor pagination) | requests + `rest_source.RESTClient` | ✅ || okta | HTTP | requests | ✅ || nocrm | HTTP | requests | ✅ |@@ -1167,7 +1168,6 @@ doesn't conflict with concurrent PRs.- nuntly- nutshell- nylas-- octolens- odoo- oecd- onedrivediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/octolens.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/octolens.pyindex 6ad20caafabb..d629011c76c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/octolens.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/octolens.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass OctolensSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/canonical_descriptions.pynew file mode 100644index 000000000000..fd976b613af3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/canonical_descriptions.py@@ -0,0 +1,97 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "mentions": {+ "description": "Posts Octolens collected from social, community and developer platforms because they matched one of the workspace's monitored keywords, each scored by the AI for relevance and sentiment.",+ "docs_url": "https://octolens.com/docs/api-reference/mentions/list-mentions",+ "columns": {+ "id": "Internal numeric post id.",+ "sourceId": "Stable composite key for the mention across the collection pipeline, for example `reddit_t3_1abc234`.",+ "url": "Canonical URL of the original post.",+ "title": "Post title. Null on platforms that have no titles, such as X posts.",+ "body": "Post body or content. May be empty or null for posts with no text.",+ "source": "Platform the mention was collected from, for example `reddit`, `twitter` or `linkedin`. Historical rows may be uppercase.",+ "timestamp": "When the mention was posted, as `YYYY-MM-DD HH:MM:SS.SSS` in UTC with no offset suffix.",+ "author": "Handle or username of the author. Null if not captured.",+ "authorName": "Display name of the author, when it differs from the handle.",+ "authorAvatar": "URL of the author's avatar image.",+ "authorUrl": "URL of the author's profile page.",+ "authorFollowers": "Author's follower count at collection time.",+ "relevance": "AI relevance verdict, either `relevant` or `not_relevant`. Unscored posts collapse to `not_relevant`.",+ "relevanceScore": "Raw internal relevance score: 0 is high, 1 is medium, 2 is low. `relevance` is derived from this.",+ "relevanceComment": "Free-text justification the AI produced for its relevance verdict.",+ "sentiment": "AI sentiment classification: `Positive`, `Neutral` or `Negative`. Null until the mention has been scored.",+ "language": "ISO 639-1 language code detected by the pipeline.",+ "tags": "AI-assigned topic tags applied to the mention, for example `buy_intent`, `bug_report` or `pricing`.",+ "keywords": "Monitored keywords this mention matched, each with its id and display text.",+ "keywordId": "First matched keyword id, denormalized so callers do not have to scan `keywords`.",+ "engaged": "Whether a workspace member marked this mention as engaged with, for example replied to or liked on the platform.",+ "feedbackRelevant": "Relevance feedback a member left on this mention: 1 for thumbs up, -1 for thumbs down, 0 for none.",+ "imageUrl": "URL of a preview image attached to the post, when present.",+ },+ },+ "keywords": {+ "description": "Phrases the workspace monitors. Each keyword drives collection on the platforms it is enabled for and carries the matching rules and exclusions applied before a post becomes a mention.",+ "docs_url": "https://octolens.com/docs/api-reference/keywords/list-keywords",+ "columns": {+ "id": "Stable numeric keyword id.",+ "keyword": "The phrase being tracked.",+ "context": "Short sentence disambiguating the keyword for AI relevance scoring.",+ "additionalTerms": "Comma-separated terms that must appear alongside the main keyword.",+ "additionalTermsAndOr": "How `additionalTerms` combine: true means any one must appear, false means all must appear.",+ "caseSensitive": "Whether matching is case-sensitive.",+ "symbolSensitive": "Exact match in the UI. When true, the words of a multi-word keyword must appear together.",+ "platforms": "Platforms this keyword is monitored on.",+ "excludeWords": "Comma-separated words that disqualify a post if present.",+ "wildcardExcludeWords": "Comma-separated wildcard exclusion patterns, where `*` matches a prefix or suffix.",+ "excludeAuthors": "Comma-separated author handles whose posts are filtered out.",+ "tag": "Classification of the keyword: `own_brand`, `competitor` or `industry_term`. Null for legacy keywords.",+ "paused": "When true, data collection is paused for this keyword.",+ "isSubReddit": "When true, the keyword is a subreddit to monitor rather than a free-text phrase.",+ },+ },+ "feeds": {+ "description": "Saved filters over the mentions stream. A feed combines a filter definition with the notification destinations attached to it.",+ "docs_url": "https://octolens.com/docs/api-reference/feeds/list-feeds",+ "columns": {+ "id": "Feed id.",+ "name": "Display name shown in the app and included in notifications.",+ "icon": "Icon identifier used for display.",+ "simpleFilters": "Flat filter definition, as field to values pairs.",+ "advancedFilters": "Grouped filter definition with AND/OR operators.",+ "isDefault": "Whether this feed is pinned as the workspace's default view.",+ "destinations": "Notification destinations attached to the feed. An empty array means the feed sends nothing.",+ "createdAt": "When the feed was created.",+ "updatedAt": "When the feed was last updated.",+ },+ },+ "notifications": {+ "description": "Delivery rules. Mentions matching the linked feed's filters are sent to the notification's configured email, Slack or webhook destinations.",+ "docs_url": "https://octolens.com/docs/api/v2/overview",+ "columns": {+ "id": "Notification id.",+ "name": "Display name shown in the app and included in deliveries.",+ "enabled": "When false, the notification is paused and nothing is delivered.",+ "feedId": "The feed whose filters decide which mentions trigger this notification.",+ "feedName": "Display name of the linked feed.",+ "destinations": "Configured delivery destinations, at most one per type of `EMAIL`, `SLACK` or `WEBHOOK`.",+ "createdAt": "When the notification was created.",+ "updatedAt": "When the notification was last updated.",+ },+ },+ "org_members": {+ "description": "People who belong to the authenticated Octolens workspace.",+ "docs_url": "https://octolens.com/docs/api/v2/overview",+ "columns": {+ "id": "Membership id. This is not the user id.",+ "userId": "User id of the member.",+ "email": "Primary email on the member's profile.",+ "firstName": "First name, if set on the profile.",+ "lastName": "Last name, if set on the profile.",+ "role": "Role within the workspace, either `admin` or `member`.",+ "createdAt": "When the member joined the workspace.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/octolens.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/octolens.pynew file mode 100644index 000000000000..75ad3a293880--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/octolens.py@@ -0,0 +1,181 @@+import dataclasses+from typing import Any, Optional++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.settings import (+ OCTOLENS_ENDPOINTS,+ OctolensEndpointConfig,+)++OCTOLENS_BASE_URL = "https://app.octolens.com"+# Documented maximum page size on the mentions feed (1-100, default 20).+PAGE_SIZE = 100+# Cheap credential introspection endpoint: returns the workspace the key is bound to plus its+# effective scopes. Every read-capable key can call it, so it validates the key without needing+# access to any particular table.+AUTH_PROBE_PATH = "/auth"+++class OctolensResumeConfig:+ cursor: str+++def _api_path(api_version: str, path: str) -> str:+ return f"/api/{api_version}{path}"+++def _mentions_body() -> dict[str, Any]:+ # No `filters.startDate`: it filters on the mention's post time, which says nothing about when+ # Octolens collected or last changed the row, so watermarking on it would drop late-collected+ # historical mentions and every later edit to an already-synced row. See settings.py.+ return {+ "limit": PAGE_SIZE,+ # Defaults to false, which silently drops low-relevance mentions. A warehouse copy should+ # mirror everything Octolens collected, so opt in.+ "includeAll": True,+ }+++def _paginator(config: OctolensEndpointConfig) -> BasePaginator:+ if not config.paginated:+ return SinglePagePaginator()+ # The cursor rides in the POST body alongside the filters, not the query string.+ return JSONResponseCursorPaginator(+ cursor_path="pagination.nextCursor", cursor_param="cursor", param_location="json"+ )+++def _resource(config: OctolensEndpointConfig, api_version: str) -> EndpointResource:+ endpoint: Endpoint = {+ "path": _api_path(api_version, config.path),+ "method": config.method,+ "data_selector": config.data_selector,+ "paginator": _paginator(config),+ }+ if config.method == "post":+ endpoint["json"] = _mentions_body()++ return {+ "name": config.name,+ "table_name": config.name,+ "table_format": "delta",+ # Every Octolens table is full refresh — the API exposes no update-aware cursor.+ "write_disposition": "replace",+ "endpoint": endpoint,+ }+++def octolens_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[OctolensResumeConfig],+) -> SourceResponse:+ config = OCTOLENS_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": OCTOLENS_BASE_URL,+ "headers": {"Content-Type": "application/json", "Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ },+ "resource_defaults": {},+ "resources": [_resource(config, api_version)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if config.paginated and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"cursor": resume.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Fires AFTER a page is yielded, so a crash re-fetches the page we were about to read rather+ # than skipping it — completeness over an occasional replayed row.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(OctolensResumeConfig(cursor=str(state["cursor"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint if config.paginated else None,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_key,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def check_access(api_key: str, api_version: str) -> tuple[int, Optional[str]]:+ """Probe the credential-introspection endpoint and report `(status, message)`.++ Status mimics HTTP semantics: 200 = key is genuine, 401 = bad/expired key, 403 = valid key+ without the scope, 0 = could not reach or parse Octolens.+ """+ session = make_tracked_session(redact_values=(api_key,))+ try:+ response = session.get(+ f"{OCTOLENS_BASE_URL}{_api_path(api_version, AUTH_PROBE_PATH)}",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=15,+ )+ except Exception as e: # noqa: BLE001 — a credential probe must never raise out of validation+ return 0, f"Could not connect to Octolens: {e}"++ if response.status_code in (401, 403):+ return response.status_code, _error_message(response)++ if not 200 <= response.status_code < 300:+ return response.status_code, _error_message(response) or f"Octolens returned HTTP {response.status_code}"++ try:+ body = response.json()+ except ValueError:+ # A 200 that isn't JSON (a proxy or maintenance page) is not a valid Octolens response.+ return 0, "Octolens returned a non-JSON response"++ if not isinstance(body, dict) or not body.get("organizationId"):+ return 0, "Octolens did not return a workspace for this API key"++ return 200, None+++def _error_message(response: Any) -> Optional[str]:+ """Pull `error.message` out of Octolens' error envelope, which every non-2xx response shares."""+ try:+ body = response.json()+ except ValueError:+ return None+ if not isinstance(body, dict):+ return None+ error = body.get("error")+ if not isinstance(error, dict):+ return None+ message = error.get("message")+ return str(message) if message else Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/settings.pynew file mode 100644index 000000000000..f046c68f21c4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/settings.py@@ -0,0 +1,53 @@+from dataclasses import dataclass+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class OctolensEndpointConfig:+ name: str+ """Table name we expose to the user (snake_case)."""+ path: str+ """Path under `/api/<version>`, e.g. `/mentions`."""+ primary_key: list[str]+ method: Literal["get", "post"] = "get"+ data_selector: str = "data"+ paginated: bool = False+ """True only for the cursor-paginated mentions feed. The dimension endpoints document no+ pagination parameters and return the full collection in one response."""+ partition_key: Optional[str] = None+ """A STABLE creation-time field to partition on. `None` disables partitioning."""+++OCTOLENS_ENDPOINTS: dict[str, OctolensEndpointConfig] = {+ "mentions": OctolensEndpointConfig(+ name="mentions",+ path="/mentions",+ primary_key=["sourceId"],+ method="post",+ paginated=True,+ partition_key="timestamp",+ ),+ "keywords": OctolensEndpointConfig(name="keywords", path="/keywords", primary_key=["id"]),+ "feeds": OctolensEndpointConfig(name="feeds", path="/feeds", primary_key=["id"]),+ "notifications": OctolensEndpointConfig(name="notifications", path="/notifications", primary_key=["id"]),+ "org_members": OctolensEndpointConfig(name="org_members", path="/org/members", primary_key=["id"]),+}++ENDPOINTS = tuple(OCTOLENS_ENDPOINTS.keys())++# Every table is full refresh.+#+# The only date filter Octolens offers is `filters.startDate` on the mentions feed, and it filters on+# `timestamp` — the time the mention was *posted*, not the time Octolens collected or last changed the+# row. Mention rows are mutable after that post time: `sentiment` is null until scoring finishes, and+# `engaged`/`feedbackRelevant` change as people act on a mention. Octolens also backfills historical+# mentions for a keyword long after the fact. Watermarking on `timestamp` would therefore permanently+# exclude both late-collected old mentions and every later edit to a row already synced, so the feed is+# resynced in full until Octolens exposes an update-aware cursor (an `updatedAt` field or a+# collected-at filter) we can safely watermark on.+#+# The other four endpoints expose no date filter and no pagination, so they full-refresh in a single+# request each regardless.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in OCTOLENS_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/source.pyindex 429d1c6e245e..795496c95eff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/source.py@@ -1,21 +1,49 @@-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.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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.octolens import (OctolensSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.octolens import (+ OctolensResumeConfig,+ check_access,+ octolens_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ OCTOLENS_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OctolensSource(SimpleSource[OctolensSourceConfig]):+class OctolensSource(ResumableSource[OctolensSourceConfig, OctolensResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # `v2` is the `/api/v2` URL segment, threaded into the request layer via resolve_api_version.+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://octolens.com/docs/api/v2/overview"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OCTOLENS@@ -26,8 +54,89 @@ class OctolensSource(SimpleSource[OctolensSourceConfig]):name=SchemaExternalDataSourceType.OCTOLENS,category=DataWarehouseSourceCategory.ANALYTICS,label="Octolens",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Octolens API key to pull your brand and keyword mentions into the PostHog Data warehouse.++Create a key under **Settings → API** in Octolens. A key with the `read` scope is enough for every table this source syncs.""",iconPath="/static/services/octolens.png",+ docsUrl="https://posthog.com/docs/cdp/sources/octolens",keywords=["social listening", "mentions", "brand monitoring"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: OctolensSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: OctolensSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if schema_name is not None and schema_name not in OCTOLENS_ENDPOINTS:+ return False, f"Unknown Octolens schema '{schema_name}'"++ status, message = check_access(config.api_key, self.resolve_api_version(api_version))++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid or expired Octolens API key"+ if status == 403:+ # A key that cannot introspect itself has no usable scope at all, so this is a hard+ # failure rather than the usual "accept a partially scoped key at source-create".+ return False, message or "Your Octolens API key does not have the required read scope"++ return False, message or "Could not validate Octolens credentials"++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Octolens API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error": "Your Octolens API key does not have the required permissions. Please create a key with the read scope and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OctolensResumeConfig]:+ return ResumableSourceManager[OctolensResumeConfig](inputs, OctolensResumeConfig)++ def source_for_pipeline(+ self,+ config: OctolensSourceConfig,+ resumable_source_manager: ResumableSourceManager[OctolensResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return octolens_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/tests/test_octolens.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/tests/test_octolens.pynew file mode 100644index 000000000000..10ef34fd9a41--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/tests/test_octolens.py@@ -0,0 +1,349 @@+import json+from collections.abc import Iterable+from typing import Any, Optional, cast++import pytest+from unittest import mock++import requests+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.octolens import (+ OCTOLENS_BASE_URL,+ PAGE_SIZE,+ OctolensResumeConfig,+ _resource,+ check_access,+ octolens_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.settings import (+ ENDPOINTS,+ OCTOLENS_ENDPOINTS,+)++# 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"+# check_access builds its own tracked session in the octolens module.+OCTOLENS_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.octolens.octolens.make_tracked_session"+)+++def _response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _mentions_page(items: list[dict[str, Any]], next_cursor: Optional[str] = None) -> Response:+ return _response({"data": items, "pagination": {"nextCursor": next_cursor}})+++def _make_manager(resume_state: OctolensResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and snapshot each request AT SEND TIME.++ ``request.json`` is one dict mutated in place across pages, so inspecting it afterwards shows+ only the final state — copy it when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append(+ {+ "url": request.url,+ "method": request.method,+ "json": dict(request.json or {}),+ "params": dict(request.params or {}),+ "auth": request.auth,+ }+ )+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in cast(Iterable[Any], source_response.items()) for row in page]+++def _source(+ endpoint: str = "mentions",+ manager: Optional[mock.MagicMock] = None,+ *,+ api_key: str = "dummy-key",+ api_version: str = "v2",+):+ return octolens_source(+ api_key=api_key,+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ api_version=api_version,+ resumable_source_manager=manager if manager is not None else _make_manager(),+ )+++class TestMentionsPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_cursor_rides_in_the_post_body_until_exhausted(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _mentions_page([{"sourceId": "reddit_1"}], next_cursor="c1"),+ _mentions_page([{"sourceId": "reddit_2"}], next_cursor=None),+ ],+ )++ rows = _rows(_source("mentions"))++ assert rows == [{"sourceId": "reddit_1"}, {"sourceId": "reddit_2"}]+ assert snapshots[0]["method"] == "POST"+ assert snapshots[0]["url"] == f"{OCTOLENS_BASE_URL}/api/v2/mentions"+ assert "cursor" not in snapshots[0]["json"]+ assert snapshots[1]["json"]["cursor"] == "c1"+ # The cursor must not leak into the query string — the API only reads it from the body.+ assert snapshots[1]["params"] == {}+ assert snapshots[0]["json"]["limit"] == PAGE_SIZE++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_include_all_opts_into_low_relevance_mentions(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_mentions_page([])])++ _rows(_source("mentions"))++ assert snapshots[0]["json"]["includeAll"] is True++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_bearer_token_authenticates_the_request(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_mentions_page([])])++ _rows(_source("mentions", api_key="secret-key"))++ request = requests.Request(method="POST", url="https://example.com").prepare()+ snapshots[0]["auth"](request)+ assert request.headers["Authorization"] == "Bearer secret-key"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_api_version_selects_the_url_path_segment(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_mentions_page([])])++ _rows(_source("mentions", api_version="v3"))++ assert snapshots[0]["url"] == f"{OCTOLENS_BASE_URL}/api/v3/mentions"+++class TestMentionsFullRefresh:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_never_sends_a_date_filter(self, MockSession) -> None:+ """`filters.startDate` filters on post time, which is not an update-aware cursor.++ Mention rows mutate after they are posted (`sentiment` fills in once scoring finishes,+ `engaged`/`feedbackRelevant` change as people act on them) and Octolens backfills historical+ mentions, so a post-time watermark would permanently drop both. The feed resyncs in full.+ """+ session = MockSession.return_value+ snapshots = _wire(session, [_mentions_page([])])++ _rows(_source("mentions"))++ assert "filters" not in snapshots[0]["json"]+ assert "startDate" not in json.dumps(snapshots[0]["json"])++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_every_endpoint_replaces_rather_than_merges(self, MockSession) -> None:+ for endpoint in ENDPOINTS:+ resource = _resource(OCTOLENS_ENDPOINTS[endpoint], "v2")+ assert resource["write_disposition"] == "replace"+++class TestResume:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_state_is_saved_after_each_yielded_page(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _mentions_page([{"sourceId": "a"}], next_cursor="c1"),+ _mentions_page([{"sourceId": "b"}], next_cursor=None),+ ],+ )+ manager = _make_manager()++ _rows(_source("mentions", manager))++ manager.save_state.assert_called_once_with(OctolensResumeConfig(cursor="c1"))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_the_saved_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_mentions_page([{"sourceId": "z"}])])+ manager = _make_manager(OctolensResumeConfig(cursor="resume-cursor"))++ rows = _rows(_source("mentions", manager))++ assert rows == [{"sourceId": "z"}]+ assert snapshots[0]["json"]["cursor"] == "resume-cursor"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unpaginated_endpoints_never_checkpoint(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"data": [{"id": 1}]})])+ manager = _make_manager(OctolensResumeConfig(cursor="stale-mentions-cursor"))++ _rows(_source("keywords", manager))++ manager.save_state.assert_not_called()+ manager.load_state.assert_not_called()+++class TestDimensionEndpoints:+ @pytest.mark.parametrize(+ "endpoint, path",+ [+ ("keywords", "/api/v2/keywords"),+ ("feeds", "/api/v2/feeds"),+ ("notifications", "/api/v2/notifications"),+ ("org_members", "/api/v2/org/members"),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_single_get_request_per_endpoint(self, MockSession, endpoint: str, path: str) -> None:+ session = MockSession.return_value+ # A stray cursor in the body must not make these endpoints page — they are not paginated.+ snapshots = _wire(session, [_response({"data": [{"id": 1}], "pagination": {"nextCursor": "c1"}})])++ rows = _rows(_source(endpoint))++ assert rows == [{"id": 1}]+ assert session.send.call_count == 1+ assert snapshots[0]["method"] == "GET"+ assert snapshots[0]["url"] == f"{OCTOLENS_BASE_URL}{path}"+ assert snapshots[0]["json"] == {}+++class TestSourceResponseShape:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_mentions_partitioned_on_the_stable_post_timestamp(self, MockSession) -> None:+ response = _source("mentions")+ assert response.name == "mentions"+ assert response.primary_keys == ["sourceId"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["timestamp"]++ @pytest.mark.parametrize("endpoint", ["keywords", "feeds", "notifications", "org_members"])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_dimension_tables_are_unpartitioned_with_id_keys(self, MockSession, endpoint: str) -> None:+ response = _source(endpoint)+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is None++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_every_declared_endpoint_is_buildable(self, MockSession) -> None:+ for endpoint in ENDPOINTS:+ assert _source(endpoint).primary_keys+++class TestHttpErrors:+ @pytest.mark.parametrize("status_code", [401, 403])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_failures_raise_a_matchable_error(self, MockSession, status_code: int) -> None:+ session = MockSession.return_value+ _wire(session, [_response({"error": {"code": "UNAUTHORIZED"}}, status_code=status_code)])++ with pytest.raises(requests.HTTPError) as exc:+ _rows(_source("mentions"))+ assert f"{status_code} Client Error" in str(exc.value)+++class FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, raise_json: bool = False) -> None:+ self.status_code = status_code+ self._json = json_data if json_data is not None else {}+ self._raise_json = raise_json++ def json(self) -> Any:+ if self._raise_json:+ raise ValueError("no json")+ return self._json+++class TestCheckAccess:+ @pytest.mark.parametrize(+ "response, expected_status",+ [+ (FakeResponse(json_data={"organizationId": "org_1", "scopes": ["read"]}), 200),+ (FakeResponse(status_code=401, json_data={"error": {"message": "Invalid key"}}), 401),+ (FakeResponse(status_code=403, json_data={"error": {"message": "Insufficient scope"}}), 403),+ (FakeResponse(status_code=500), 500),+ # A 200 that isn't JSON, or one without a workspace, is not a validated key.+ (FakeResponse(raise_json=True), 0),+ (FakeResponse(json_data={"scopes": ["read"]}), 0),+ ],+ )+ def test_status_mapping(self, response: FakeResponse, expected_status: int) -> None:+ session = mock.MagicMock()+ session.get.return_value = response+ with mock.patch(OCTOLENS_SESSION_PATCH, return_value=session):+ status, _message = check_access("k", "v2")+ assert status == expected_status++ @pytest.mark.parametrize("status_code, expected", [(401, "Invalid key"), (500, "Boom")])+ def test_surfaces_the_error_envelope_message(self, status_code: int, expected: str) -> None:+ session = mock.MagicMock()+ session.get.return_value = FakeResponse(status_code=status_code, json_data={"error": {"message": expected}})+ with mock.patch(OCTOLENS_SESSION_PATCH, return_value=session):+ _status, message = check_access("k", "v2")+ assert message == expected++ @pytest.mark.parametrize(+ "response",+ [+ # Not JSON at all (a proxy or maintenance page fronting the error).+ FakeResponse(status_code=500, raise_json=True),+ # JSON, but not the documented error envelope.+ FakeResponse(status_code=500, json_data=["unexpected"]),+ FakeResponse(status_code=500, json_data={"error": "just a string"}),+ FakeResponse(status_code=500, json_data={"error": {"code": "boom"}}),+ ],+ )+ def test_falls_back_to_the_status_code_when_there_is_no_envelope_message(self, response: FakeResponse) -> None:+ session = mock.MagicMock()+ session.get.return_value = response+ with mock.patch(OCTOLENS_SESSION_PATCH, return_value=session):+ status, message = check_access("k", "v2")+ assert status == 500+ assert message == "Octolens returned HTTP 500"++ def test_probes_the_versioned_auth_endpoint_with_a_bearer_token(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = FakeResponse(json_data={"organizationId": "org_1"})+ with mock.patch(OCTOLENS_SESSION_PATCH, return_value=session):+ check_access("k", "v2")+ call = session.get.call_args+ assert call.args[0] == f"{OCTOLENS_BASE_URL}/api/v2/auth"+ assert call.kwargs["headers"]["Authorization"] == "Bearer k"++ def test_connection_error_reports_unvalidated(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = Exception("boom")+ with mock.patch(OCTOLENS_SESSION_PATCH, return_value=session):+ status, message = check_access("k", "v2")+ assert status == 0+ assert message is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/tests/test_octolens_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/tests/test_octolens_source.pynew file mode 100644index 000000000000..8d0db61c1f8e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/octolens/tests/test_octolens_source.py@@ -0,0 +1,149 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.octolens import (+ OctolensSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.octolens import OctolensResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.octolens.source import OctolensSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.octolens.source"+++class TestOctolensSource:+ def setup_method(self) -> None:+ self.source = OctolensSource()+ self.team_id = 123+ self.config = OctolensSourceConfig(api_key="octolens-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.OCTOLENS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Octolens"+ assert config.label == "Octolens"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/octolens.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_a_required_secret(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_table_advertises_incremental(self) -> None:+ """Octolens exposes no update-aware cursor, so nothing may advertise incremental.++ The only date filter is `filters.startDate` on the mentions feed, and it filters on the+ mention's post time — mention rows keep changing after that (scoring backfills `sentiment`,+ `engaged`/`feedbackRelevant` follow user actions) and historical mentions are collected late,+ so a post-time watermark would silently drop rows and updates.+ """+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)++ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ @pytest.mark.parametrize(+ "names, expected",+ [(["mentions"], {"mentions"}), (["keywords", "feeds"], {"keywords", "feeds"}), (["nope"], set())],+ )+ def test_get_schemas_filtered_by_names(self, names: list[str], expected: set[str]) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)+ assert {s.name for s in schemas} == expected++ def test_canonical_descriptions_cover_every_shipped_table(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://app.octolens.com/api/v2/mentions",+ "403 Client Error: Forbidden for url: https://app.octolens.com/api/v2/keywords",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "unrelated_error",+ [+ "429 Client Error: Too Many Requests for url: https://app.octolens.com/api/v2/mentions",+ "500 Server Error for url: https://app.octolens.com/api/v2/mentions",+ ],+ )+ def test_non_retryable_errors_ignore_throttling_and_server_errors(self, unrelated_error: str) -> None:+ assert not any(key in unrelated_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "status, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid or expired Octolens API key"),+ (403, False, "boom"),+ (0, False, "boom"),+ ],+ )+ @mock.patch(f"{SOURCE_MODULE}.check_access")+ def test_validate_credentials(+ self, mock_check: mock.MagicMock, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ mock_check.return_value = (status, "boom")+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert message == expected_message++ @mock.patch(f"{SOURCE_MODULE}.check_access")+ def test_validate_credentials_probes_the_resolved_api_version(self, mock_check: mock.MagicMock) -> None:+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id)+ mock_check.assert_called_once_with("octolens-key", "v2")++ @mock.patch(f"{SOURCE_MODULE}.check_access")+ def test_validate_credentials_rejects_unknown_schema_without_probing(self, mock_check: mock.MagicMock) -> None:+ is_valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="not_a_table")+ assert is_valid is False+ assert message == "Unknown Octolens schema 'not_a_table'"+ mock_check.assert_not_called()++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OctolensResumeConfig++ @mock.patch(f"{SOURCE_MODULE}.octolens_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_octolens_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "mentions"+ inputs.team_id = 123+ inputs.job_id = "job-1"+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_octolens_source.call_args.kwargs+ assert kwargs["api_key"] == "octolens-key"+ assert kwargs["endpoint"] == "mentions"+ assert kwargs["team_id"] == 123+ assert kwargs["job_id"] == "job-1"+ # An unset pin resolves to the source's default version rather than reaching the request layer as None.+ assert kwargs["api_version"] == "v2"+ assert kwargs["resumable_source_manager"] is manager+ # Every table is full refresh, so no watermark can reach the request body.+ assert "db_incremental_field_last_value" not in kwargs+ assert "should_use_incremental_field" not in kwargs