: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 harvey import source (#69632)
Tom Owers10696cca6f04
diff --git a/frontend/public/services/harvey.svg b/frontend/public/services/harvey.svgnew file mode 100644index 000000000000..10fb9b28df3d--- /dev/null+++ b/frontend/public/services/harvey.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="282 198.143 109.714 109.714" width="110" height="110">+<path fill="#0F0E0D" d="M391.714 301H343.714L357.429 287.286V258.486H316.286V287.286L330 301H282L295.714 287.286V218.714L282 205H330L316.286 218.714V244.771H357.429V218.714L343.714 205H391.714L378 218.714V287.286L391.714 301Z"></path>+</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 9ce609abbd13..ada3a7bb0300 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -195,6 +195,7 @@ the row lists both.| gridly | HTTP | requests | ✅ || guardian | HTTP | requests | ✅ || guru | HTTP | requests | ✅ |+| harvey | HTTP | requests | ✅ || height | HTTP | requests | ✅ || hellobaton | HTTP | requests | ✅ || hibob | HTTP | requests | ✅ |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 a7dd6f459b87..9f2592a7da03 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@@ -1668,7 +1668,8 @@ class HarnessSourceConfig(config.Config):@config.configclass HarveySourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu", "au"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/canonical_descriptions.pynew file mode 100644index 000000000000..f3c0d9eb794f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/canonical_descriptions.py@@ -0,0 +1,101 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "audit_logs": {+ "description": "Immutable audit trail of every action taken in the Harvey workspace - logins, admin changes, user activity, and API access.",+ "docs_url": "https://developers.harvey.ai/guides/audit_logs",+ "columns": {+ "id": "Unique identifier for the log entry (UUID).",+ "timestamp": "Date when the event occurred.",+ "type": "Event type identifying the action performed, e.g. auth:login or admin:add_users. New types may be added over time.",+ "user": "Email of the user who triggered the event.",+ "ip": "IP address of the actor.",+ "user_agent": "User agent of the actor who triggered the event.",+ "data": "Optional metadata for certain event types, JSON-encoded.",+ },+ },+ "usage_history": {+ "description": "Usage events describing how users interact with Harvey - product surface, action, client matter attribution - without prompt or response text.",+ "docs_url": "https://developers.harvey.ai/guides/usage_history",+ "columns": {+ "unique_usage_id": "Unique identifier for the usage event (UUID).",+ "utc_time": "Time the event occurred, in UTC.",+ "user": "Email of the user who performed the action.",+ "action": "Action performed, e.g. CREATE.",+ "access_point": "Where the action originated, e.g. WEB.",+ "product_surface_area": "Harvey product surface used, e.g. ASSISTANT, VAULT, PLAYBOOK, WORKFLOW, WORD, OUTLOOK, DRAFT.",+ "subsurface": "More specific surface within the product area, e.g. ASSISTANT_THREAD, REVIEW_TABLE.",+ "cm_id": "Client matter number the event is attributed to.",+ "parent_thread_id": "Identifier of the parent assistant thread, when applicable.",+ "source": "Source of the event.",+ "space_name": "Name of the shared space involved, when applicable.",+ "playbook_name": "Name of the playbook used, when applicable.",+ "review_table_name": "Name of the Vault review table involved, when applicable.",+ "vault_project_name": "Name of the Vault project involved, when applicable.",+ "workflow_name": "Name of the workflow used, when applicable.",+ "metadata": "Event-type-specific metadata (e.g. num_columns, num_files), JSON-encoded.",+ },+ },+ "query_history": {+ "description": "Query events including the full prompt and response text, feedback, and a deep link into Harvey, alongside the usage attribution fields.",+ "docs_url": "https://developers.harvey.ai/guides/usage_history",+ "columns": {+ "unique_usage_id": "Unique identifier for the query event (UUID).",+ "utc_time": "Time the event occurred, in UTC.",+ "user": "Email of the user who performed the action.",+ "query": "Full prompt text submitted by the user.",+ "response": "Full response text returned by Harvey. May be 'NA' for some event types.",+ "link": "Direct URL to the query within Harvey.",+ "feedback_comments": "Free-text feedback the user left on the response, when any.",+ "feedback_sentiments": "Feedback sentiment the user left on the response, when any.",+ "action": "Action performed, e.g. CREATE.",+ "access_point": "Where the action originated, e.g. WEB.",+ "product_surface_area": "Harvey product surface used, e.g. ASSISTANT, VAULT, PLAYBOOK, WORKFLOW, WORD, OUTLOOK, DRAFT.",+ "subsurface": "More specific surface within the product area, e.g. ASSISTANT_THREAD, REVIEW_TABLE.",+ "cm_id": "Client matter number the event is attributed to.",+ "parent_thread_id": "Identifier of the parent assistant thread, when applicable.",+ "source": "Source of the event.",+ "space_name": "Name of the shared space involved, when applicable.",+ "playbook_name": "Name of the playbook used, when applicable.",+ "review_table_name": "Name of the Vault review table involved, when applicable.",+ "vault_project_name": "Name of the Vault project involved, when applicable.",+ "workflow_name": "Name of the workflow used, when applicable.",+ "metadata": "Event-type-specific metadata, JSON-encoded.",+ },+ },+ "client_matters": {+ "description": "All client matters in the workspace (including deleted ones) with usage statistics.",+ "docs_url": "https://developers.harvey.ai/guides/client_matters",+ "columns": {+ "id": "Unique identifier for the client matter (UUID).",+ "name": "Client matter number, e.g. 1234-5678.",+ "description": "Description of the client matter.",+ "user_email": "Email of the user who created the client matter.",+ "user_count": "Count of unique users associated with the client matter.",+ "total_events": "Count of queries associated with the client matter.",+ "created_at": "When the client matter was created.",+ "deleted_at": "When the client matter was deleted, if it has been.",+ },+ },+ "vault_projects": {+ "description": "Vault projects and knowledge bases in the workspace, with file counts, sizes, and sharing details.",+ "docs_url": "https://developers.harvey.ai/guides/vault",+ "columns": {+ "id": "Unique identifier for the project (UUID).",+ "name": "Name of the project.",+ "client_matter_id": "Client matter the project is attached to, when any (UUID).",+ "created_at": "When the project was created.",+ "updated_at": "When the project's metadata was last updated.",+ "project_updated_at": "When the project's content was last updated.",+ "project_retained_at": "Retention timestamp for the project, when set.",+ "creator_email": "Email of the user who created the project.",+ "is_knowledge_base_project": "Whether the project is designated as a knowledge base.",+ "files_count": "Number of files in the project.",+ "size_bytes": "Total size of the project's files in bytes.",+ "query_count": "Number of queries run against the project.",+ "sharing": "User and workspace sharing details, JSON-encoded.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/harvey.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/harvey.pynew file mode 100644index 000000000000..fbf8412619fd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/harvey.py@@ -0,0 +1,418 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, time+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 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.harvey.settings import (+ AUDIT_LOGS_PAGE_SIZE,+ HARVEY_BASE_URLS,+ HARVEY_ENDPOINTS,+ HISTORY_WINDOW_SECONDS,+ MAX_LOOKBACK_DAYS,+ VAULT_PROJECTS_PAGE_SIZE,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 6++HISTORY_PATHS: dict[str, str] = {+ "usage_history": "/api/v2/history/usage",+ "query_history": "/api/v2/history/query",+}+++class HarveyRetryableError(Exception):+ pass+++class HarveyResumeConfig:+ # audit_logs: last processed log ID - pagination resumes from it (`from` is exclusive)+ last_audit_log_id: str | None = None+ # usage_history / query_history: epoch start of the next time window to fetch+ window_start: int | None = None+ # vault_projects: next page number to fetch+ next_page: int | None = None+++def get_base_url(region: str | None) -> str:+ return HARVEY_BASE_URLS.get((region or "us").lower(), HARVEY_BASE_URLS["us"])+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _make_session(api_key: str, capture: bool = True) -> requests.Session:+ # `redact_values` masks the bearer token from any captured request samples or logged errors,+ # so the credential never leaks into warehouse job telemetry. `capture=False` additionally+ # excludes the response body from HTTP sample capture, for endpoints whose bodies carry+ # arbitrary user content the name-based scrubbers can't recognise.+ return make_tracked_session(redact_values=(api_key,), capture=capture)+++def _endpoint_captures_samples(endpoint: str) -> bool:+ # Default off for anything unmapped - capture is opt-in per endpoint.+ config = HARVEY_ENDPOINTS.get(endpoint)+ return config.capture_http_samples if config is not None else False+++def validate_credentials(api_key: str, region: str | None) -> bool:+ url = f"{get_base_url(region)}/api/whoami"+ try:+ response = _make_session(api_key).get(url, headers=_get_headers(api_key), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _probe_url(base_url: str, endpoint: str) -> str:+ now = int(datetime.now(UTC).timestamp())+ if endpoint == "audit_logs":+ return f"{base_url}/api/v1/logs/audit/latest"+ if endpoint in HISTORY_PATHS:+ return f"{base_url}{HISTORY_PATHS[endpoint]}?{urlencode({'start_time': now - 3600, 'end_time': now})}"+ if endpoint == "vault_projects":+ return f"{base_url}/api/v1/vault/workspace/projects?{urlencode({'page': 1, 'per_page': 1})}"+ return f"{base_url}/api/v1/client_matters"+++def check_endpoint_access(api_key: str, region: str | None, endpoint: str) -> str | None:+ """Return None when the token can reach the endpoint, or a short reason when it can't.++ Harvey API tokens carry a per-endpoint permissions list, so a valid token can still be+ denied on individual endpoints. Only a definitive denial (401/403) counts as missing+ access - throttles, 5xx, and network blips are treated as reachable.+ """+ url = _probe_url(get_base_url(region), endpoint)+ try:+ # The query_history probe fetches a live window of prompt/response text, so honour the+ # endpoint's capture flag here too - the probe body is as sensitive as the export body.+ session = _make_session(api_key, capture=_endpoint_captures_samples(endpoint))+ response = session.get(url, headers=_get_headers(api_key), timeout=30)+ except Exception:+ return None+ if response.status_code in (401, 403):+ return "Your API token does not have permission for this endpoint. Enable it in the token's permissions list in Harvey workspace settings (Settings → API Tokens)."+ return None+++@retry(+ retry=retry_if_exception_type(+ (+ HarveyRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ # Harvey's per-minute rate limit windows reset each minute, so back off past a full+ # window before giving up on a 429.+ wait=wait_exponential_jitter(initial=2, max=70),+ reraise=True,+)+def _fetch_json(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise HarveyRetryableError(f"Harvey API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected from the seed endpoints (no logs at/after the watermark) and is+ # handled by callers; anything else is a genuine failure. The response body is+ # deliberately left out of the log - it can contain confidential query content.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Harvey API error: status={response.status_code}, url={url}")+ response.raise_for_status()++ return response.json()+++def _parse_datetime(value: Any) -> datetime | None:+ """Parse Harvey's timestamp strings (ISO 8601 or 'YYYY-MM-DD HH:MM:SS') as UTC."""+ if isinstance(value, datetime):+ return value if value.tzinfo else value.replace(tzinfo=UTC)+ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value)+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def _to_epoch(value: Any) -> int:+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return int(dt.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, time.min, tzinfo=UTC).timestamp())+ if isinstance(value, int | float):+ return int(value)+ if isinstance(value, str):+ parsed = _parse_datetime(value)+ if parsed is not None:+ return int(parsed.timestamp())+ raise ValueError(f"Cannot convert incremental field value to epoch: {value!r}")+++def _lookback_floor_epoch(now_epoch: int) -> int:+ return now_epoch - MAX_LOOKBACK_DAYS * 24 * 60 * 60+++def _normalize_audit_log(log: dict[str, Any]) -> dict[str, Any]:+ # Parse the ISO timestamp so the column lands as a real datetime (needed for the+ # incremental watermark and datetime partitioning). Nested `data` stays a dict - the+ # pipeline JSON-encodes nested objects.+ parsed = _parse_datetime(log.get("timestamp"))+ if parsed is not None:+ log["timestamp"] = parsed+ return log+++def _normalize_history_event(event: dict[str, Any]) -> dict[str, Any]:+ parsed = _parse_datetime(event.get("utc_time"))+ if parsed is not None:+ event["utc_time"] = parsed+ return event+++def _seed_audit_cursor(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ logger: FilteringBoundLogger,+ db_incremental_field_last_value: Any,+) -> dict[str, Any] | None:+ """Find the audit log to start paginating from, or None when there is nothing to sync.++ Incremental syncs seed via GET /logs/audit/search?time=<watermark epoch>, which returns+ the first log at or after that time. Full syncs (and watermarks older than the search+ endpoint's 1-year limit) start from GET /logs/audit/earliest - re-pulled rows are+ deduped on the `id` primary key at merge.+ """+ if db_incremental_field_last_value is not None:+ epoch = _to_epoch(db_incremental_field_last_value)+ now_epoch = int(datetime.now(UTC).timestamp())+ # A future watermark (bad source clock) would 400 - cap it at now.+ epoch = min(epoch, now_epoch)+ if epoch >= _lookback_floor_epoch(now_epoch):+ url = f"{base_url}/api/v1/logs/audit/search?{urlencode({'time': epoch})}"+ try:+ data = _fetch_json(session, url, headers, logger)+ return data.get("log")+ except requests.HTTPError as exc:+ if exc.response is not None and exc.response.status_code == 404:+ # No log at or after the watermark - fully caught up.+ return None+ raise+ logger.debug("Harvey: incremental watermark is older than the 1-year search limit, restarting from earliest")++ url = f"{base_url}/api/v1/logs/audit/earliest"+ try:+ data = _fetch_json(session, url, headers, logger)+ except requests.HTTPError as exc:+ if exc.response is not None and exc.response.status_code == 404:+ # Workspace has no audit logs yet.+ return None+ raise+ return data.get("log")+++def _get_audit_log_rows(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HarveyResumeConfig],+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if resume is not None and resume.last_audit_log_id:+ from_id = resume.last_audit_log_id+ logger.debug(f"Harvey: resuming audit logs from id={from_id}")+ else:+ seed = _seed_audit_cursor(session, headers, base_url, logger, db_incremental_field_last_value)+ if seed is None:+ return+ # `from` is exclusive, so the seed log itself has to be yielded here.+ yield [_normalize_audit_log(dict(seed))]+ from_id = seed["id"]+ resumable_source_manager.save_state(HarveyResumeConfig(last_audit_log_id=from_id))++ while True:+ url = f"{base_url}/api/v1/logs/audit?{urlencode({'from': from_id, 'take': AUDIT_LOGS_PAGE_SIZE})}"+ logs = _fetch_json(session, url, headers, logger)+ if not logs:+ break++ yield [_normalize_audit_log(log) for log in logs]++ from_id = logs[-1]["id"]+ # Save AFTER yielding so a crash re-yields the last batch instead of skipping it -+ # audit logs are immutable and merge dedupes on the primary key.+ resumable_source_manager.save_state(HarveyResumeConfig(last_audit_log_id=from_id))++ if len(logs) < AUDIT_LOGS_PAGE_SIZE:+ break+++def _get_history_rows(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ path: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HarveyResumeConfig],+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ now_epoch = int(datetime.now(UTC).timestamp())+ floor = _lookback_floor_epoch(now_epoch)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.window_start is not None:+ window_start = resume.window_start+ logger.debug(f"Harvey: resuming history export from window_start={window_start}")+ elif db_incremental_field_last_value is not None:+ # The API rejects start times older than 1 year, so clamp the watermark to the floor.+ window_start = max(_to_epoch(db_incremental_field_last_value), floor)+ else:+ window_start = floor++ while window_start < now_epoch:+ window_end = min(window_start + HISTORY_WINDOW_SECONDS, now_epoch)+ url = f"{base_url}{path}?{urlencode({'start_time': window_start, 'end_time': window_end})}"+ data = _fetch_json(session, url, headers, logger)++ events = data.get("events") or []+ if events:+ yield [_normalize_history_event(event) for event in events]++ # Save AFTER yielding; boundary events re-pulled by the next window are deduped on+ # `unique_usage_id` at merge.+ resumable_source_manager.save_state(HarveyResumeConfig(window_start=window_end))+ window_start = window_end+++def _get_client_matter_rows(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ # Single unpaginated response containing every client matter (including deleted ones).+ matters = _fetch_json(session, f"{base_url}/api/v1/client_matters", headers, logger)+ if matters:+ yield matters+++def _get_vault_project_rows(+ session: requests.Session,+ headers: dict[str, str],+ base_url: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HarveyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.next_page if resume is not None and resume.next_page else 1++ while True:+ # Sort by name: the default `date` sort orders by content-update time, which+ # reshuffles rows mid-pagination as projects change.+ params = {"page": page, "per_page": VAULT_PROJECTS_PAGE_SIZE, "sort_by": "name", "sort_order": "asc"}+ url = f"{base_url}/api/v1/vault/workspace/projects?{urlencode(params)}"+ data = _fetch_json(session, url, headers, logger)++ content = (data.get("response") or {}).get("content") or {}+ projects = content.get("projects") or []+ if not projects:+ break++ yield projects++ pagination = content.get("pagination") or {}+ total_pages = pagination.get("total_pages")+ if total_pages is not None and page >= total_pages:+ break++ page += 1+ resumable_source_manager.save_state(HarveyResumeConfig(next_page=page))+++def get_rows(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HarveyResumeConfig],+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ base_url = get_base_url(region)+ headers = _get_headers(api_key)+ # One session reused across every page so urllib3 keeps the connection alive. Endpoints whose+ # bodies carry arbitrary user content (e.g. query_history) opt out of HTTP sample capture.+ session = _make_session(api_key, capture=_endpoint_captures_samples(endpoint))++ if endpoint == "audit_logs":+ yield from _get_audit_log_rows(+ session, headers, base_url, logger, resumable_source_manager, db_incremental_field_last_value+ )+ elif endpoint in HISTORY_PATHS:+ yield from _get_history_rows(+ session,+ headers,+ base_url,+ HISTORY_PATHS[endpoint],+ logger,+ resumable_source_manager,+ db_incremental_field_last_value,+ )+ elif endpoint == "client_matters":+ yield from _get_client_matter_rows(session, headers, base_url, logger)+ elif endpoint == "vault_projects":+ yield from _get_vault_project_rows(session, headers, base_url, logger, resumable_source_manager)+ else:+ raise ValueError(f"Unknown Harvey endpoint: {endpoint}")+++def harvey_source(+ api_key: str,+ region: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[HarveyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = HARVEY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ region=region,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value if should_use_incremental_field else None,+ ),+ 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,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/settings.pynew file mode 100644index 000000000000..993a15b28f2d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/settings.py@@ -0,0 +1,104 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++HARVEY_BASE_URLS: dict[str, str] = {+ "us": "https://api.harvey.ai",+ "eu": "https://eu.api.harvey.ai",+ "au": "https://au.api.harvey.ai",+}++AUDIT_LOGS_PAGE_SIZE = 1000 # `take` max on GET /api/v1/logs/audit+# The history export APIs cap a single request at a 30-day range and recommend pulling one+# day at a time; responses are unpaginated, so smaller windows also bound response size.+HISTORY_WINDOW_SECONDS = 24 * 60 * 60+# Both the history export APIs and the audit log search endpoint only accept timestamps up+# to 1 year old. Stay a day under the limit so a request built "now" can't drift past it.+MAX_LOOKBACK_DAYS = 364+VAULT_PROJECTS_PAGE_SIZE = 100 # `per_page` max on GET /api/v1/vault/workspace/projects+++@dataclass+class HarveyEndpointConfig:+ name: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable datetime field used for partitioning (never an update-tracking field)+ partition_key: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ should_sync_default: bool = True+ # HTTP sample capture is off by default. Harvey serves legal/business data, and most endpoints+ # return free-text names, descriptions, or audit metadata the name-based sample scrubbers can't+ # recognise, so capturing bodies would leak that content into job telemetry. Opt an endpoint+ # back in only when its responses carry no user-controlled content.+ capture_http_samples: bool = False+++HARVEY_ENDPOINTS: dict[str, HarveyEndpointConfig] = {+ # Immutable workspace audit trail. Paginated forward in time by log ID+ # (GET /api/v1/logs/audit?from=<id>&take=1000); incremental syncs seed the cursor+ # server-side via GET /api/v1/logs/audit/search?time=<epoch>.+ "audit_logs": HarveyEndpointConfig(+ name="audit_logs",+ primary_keys=["id"],+ partition_key="timestamp",+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Usage events (no prompt/response text). Windowed server-side via start_time/end_time.+ "usage_history": HarveyEndpointConfig(+ name="usage_history",+ primary_keys=["unique_usage_id"],+ partition_key="utc_time",+ incremental_fields=[+ {+ "label": "utc_time",+ "type": IncrementalFieldType.DateTime,+ "field": "utc_time",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ # Structured usage metrics only (counts, timestamps, model ids) - no free-text or+ # prompt/response content - so this endpoint opts into HTTP sample capture.+ capture_http_samples=True,+ ),+ # Usage events including the full prompt/response text, feedback, and deep link.+ "query_history": HarveyEndpointConfig(+ name="query_history",+ primary_keys=["unique_usage_id"],+ partition_key="utc_time",+ incremental_fields=[+ {+ "label": "utc_time",+ "type": IncrementalFieldType.DateTime,+ "field": "utc_time",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ # Bodies carry confidential prompt/response text; relies on the capture-off default.+ ),+ # Unpaginated full list with no server-side time filter - full refresh only.+ "client_matters": HarveyEndpointConfig(+ name="client_matters",+ primary_keys=["id"],+ # A matter's description is free-text that can carry confidential client content;+ # relies on the capture-off default.+ ),+ # Page-number pagination. Rows are mutable (file counts, sharing, update timestamps),+ # so full refresh keeps the table current.+ "vault_projects": HarveyEndpointConfig(+ name="vault_projects",+ primary_keys=["id"],+ ),+}++ENDPOINTS = tuple(HARVEY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in HARVEY_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/source.pyindex c5f7fa267df0..c15f5e35ba64 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/source.py@@ -1,31 +1,191 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HarveySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.harvey import (+ HarveyResumeConfig,+ check_endpoint_access,+ harvey_source,+ validate_credentials as validate_harvey_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.settings import (+ ENDPOINTS,+ HARVEY_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class HarveySource(SimpleSource[HarveySourceConfig]):+class HarveySource(ResumableSource[HarveySourceConfig, HarveyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HARVEY+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` selects the host the stored API token is sent to. Retargeting it must re-require the+ # secret so a preserved token can't be aimed at a different regional endpoint without re-entry.+ return ["region"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.HARVEY,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Harvey",- iconPath="/static/services/harvey.png",+ caption="""Enter your Harvey API token to pull audit logs, usage and query history, client matters, and Vault project metadata into the PostHog Data warehouse.++Create an API token in Harvey workspace settings under **API Tokens** (if you don't see that section, ask your Harvey Customer Success Manager to enable API access).++Each token carries a per-endpoint permissions list — grant access for the endpoints you want to sync: audit logs, history exports, client matters, and Vault.+""",+ iconPath="/static/services/harvey.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/harvey",keywords=["legal", "ai", "audit logs", "usage"],- fields=cast(list[FieldType], []),+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (api.harvey.ai)", value="us"),+ SourceFieldSelectConfigOption(label="EU (eu.api.harvey.ai)", value="eu"),+ SourceFieldSelectConfigOption(label="AU (au.api.harvey.ai)", value="au"),+ ],+ ),+ ],+ ),unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # requests raises "401 Client Error: Unauthorized for url: <regional host>/..." -+ # match the stable status text so all three regional hosts are covered.+ return {+ "401 Client Error: Unauthorized for url": "Your Harvey API token is invalid or has been revoked. Create a new token in Harvey workspace settings (Settings → API Tokens), then reconnect.",+ "403 Client Error: Forbidden for url": "Your Harvey API token does not have permission for this endpoint. Enable it in the token's permissions list in Harvey workspace settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: HarveySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Audit logs are immutable, so append-only is the only incremental mode we offer.+ append_only_endpoints = {"audit_logs"}++ def _description(endpoint: str) -> str | None:+ if endpoint in ("usage_history", "query_history"):+ return "Only syncs the last year on initial sync (Harvey API limit)"+ if endpoint in ("client_matters", "vault_projects"):+ return "Full refresh only"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental and endpoint not in append_only_endpoints,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=HARVEY_ENDPOINTS[endpoint].should_sync_default,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) 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: HarveySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not validate_harvey_credentials(config.api_key, config.region):+ return False, "Invalid Harvey API token"++ # Harvey tokens have per-endpoint permissions; when asked about a specific schema,+ # confirm the token can actually reach that endpoint.+ if schema_name is not None and schema_name in HARVEY_ENDPOINTS:+ reason = check_endpoint_access(config.api_key, config.region, schema_name)+ if reason is not None:+ return False, reason++ return True, None++ def get_endpoint_permissions(+ self, config: HarveySourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ return {+ endpoint: check_endpoint_access(config.api_key, config.region, endpoint)+ if endpoint in HARVEY_ENDPOINTS+ else None+ for endpoint in endpoints+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HarveyResumeConfig]:+ return ResumableSourceManager[HarveyResumeConfig](inputs, HarveyResumeConfig)++ def source_for_pipeline(+ self,+ config: HarveySourceConfig,+ resumable_source_manager: ResumableSourceManager[HarveyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return harvey_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.pynew file mode 100644index 000000000000..9734e5559d98--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey.py@@ -0,0 +1,700 @@+import json+from collections.abc import Callable+from datetime import UTC, date, datetime+from typing import Any, cast+from urllib.parse import parse_qs, urlparse++import pytest+from freezegun import freeze_time+from unittest import mock++from parameterized import parameterized+from requests import HTTPError, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.harvey import (+ HarveyResumeConfig,+ HarveyRetryableError,+ _fetch_json,+ _parse_datetime,+ _to_epoch,+ check_endpoint_access,+ get_base_url,+ get_rows,+ harvey_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.settings import (+ AUDIT_LOGS_PAGE_SIZE,+ MAX_LOOKBACK_DAYS,+)++NOW = datetime(2026, 7, 1, 12, 0, 0, tzinfo=UTC)+NOW_EPOCH = int(NOW.timestamp())++HARVEY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.harvey.harvey"++# The undecorated function behind tenacity's retry wrapper, so failure-path tests don't sit+# through the backoff schedule. mypy can't see tenacity's `__wrapped__`, hence the cast.+_fetch_json_unretried = cast(Any, _fetch_json).__wrapped__+++class _FakeManager:+ def __init__(self, resume: HarveyResumeConfig | None = None) -> None:+ self._resume = resume+ self.saved: list[HarveyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume is not None++ def load_state(self) -> HarveyResumeConfig | None:+ return self._resume++ def save_state(self, data: HarveyResumeConfig) -> None:+ self.saved.append(data)+++def _response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ resp.url = "https://api.harvey.ai/api/test"+ return resp+++def _session_with(responses: list[Response]) -> mock.MagicMock:+ session = mock.MagicMock()+ session.get.side_effect = responses+ return session+++def _requested_urls(session: mock.MagicMock) -> list[str]:+ return [call.args[0] for call in session.get.call_args_list]+++def _query_params(url: str) -> dict[str, str]:+ return {key: values[0] for key, values in parse_qs(urlparse(url).query).items()}+++def _audit_log(log_id: str, timestamp: str = "2026-06-01T10:00:00+00:00") -> dict[str, Any]:+ return {+ "id": log_id,+ "timestamp": timestamp,+ "type": "auth:login",+ "user": "[email protected]",+ "ip": "203.0.113.10",+ "user_agent": "curl/8.0",+ "data": {},+ }+++def _history_event(usage_id: str, utc_time: str = "2026-07-01 10:30:00") -> dict[str, Any]:+ return {+ "unique_usage_id": usage_id,+ "utc_time": utc_time,+ "user": "[email protected]",+ "product_surface_area": "ASSISTANT",+ "metadata": {},+ }+++class TestHelpers:+ @parameterized.expand(+ [+ ("us", "us", "https://api.harvey.ai"),+ ("eu", "eu", "https://eu.api.harvey.ai"),+ ("au", "au", "https://au.api.harvey.ai"),+ ("uppercase", "US", "https://api.harvey.ai"),+ ("none", None, "https://api.harvey.ai"),+ ("unknown", "unknown", "https://api.harvey.ai"),+ ]+ )+ def test_get_base_url(self, _name: str, region: str | None, expected: str) -> None:+ assert get_base_url(region) == expected++ @parameterized.expand(+ [+ ("iso_offset", "2026-06-01T10:00:00+00:00", datetime(2026, 6, 1, 10, 0, 0, tzinfo=UTC)),+ ("iso_z", "2026-06-01T10:00:00Z", datetime(2026, 6, 1, 10, 0, 0, tzinfo=UTC)),+ ("space_separated", "2026-02-22 14:01:23", datetime(2026, 2, 22, 14, 1, 23, tzinfo=UTC)),+ ("naive_datetime", datetime(2026, 6, 1, 10, 0, 0), datetime(2026, 6, 1, 10, 0, 0, tzinfo=UTC)),+ ("unparseable_string", "not a timestamp", None),+ ("none", None, None),+ ("int", 12345, None),+ ]+ )+ def test_parse_datetime(self, _name: str, value: Any, expected: datetime | None) -> None:+ assert _parse_datetime(value) == expected++ @parameterized.expand(+ [+ ("aware_datetime", datetime(2026, 7, 1, 12, 0, 0, tzinfo=UTC), NOW_EPOCH),+ ("naive_datetime", datetime(2026, 7, 1, 12, 0, 0), NOW_EPOCH),+ ("date", date(2026, 7, 1), NOW_EPOCH - 12 * 60 * 60),+ ("int", NOW_EPOCH, NOW_EPOCH),+ ("float", float(NOW_EPOCH), NOW_EPOCH),+ ("iso_string", "2026-07-01T12:00:00+00:00", NOW_EPOCH),+ ]+ )+ def test_to_epoch(self, _name: str, value: Any, expected: int) -> None:+ assert _to_epoch(value) == expected++ def test_to_epoch_rejects_unparseable_values(self) -> None:+ with pytest.raises(ValueError):+ _to_epoch("not a timestamp")++ @parameterized.expand([("throttle", 429), ("server_error", 500), ("unavailable", 503)])+ def test_fetch_json_raises_retryable_on_throttle_and_server_errors(self, _name: str, status_code: int) -> None:+ session = _session_with([_response({}, status_code=status_code)])+ with pytest.raises(HarveyRetryableError):+ _fetch_json_unretried(session, "https://api.harvey.ai/api/test", {}, mock.MagicMock())++ def test_fetch_json_raises_http_error_on_client_errors(self) -> None:+ session = _session_with([_response({"error": "Unauthorized"}, status_code=401)])+ with pytest.raises(HTTPError):+ _fetch_json_unretried(session, "https://api.harvey.ai/api/test", {}, mock.MagicMock())+++class TestValidateCredentials:+ @parameterized.expand(+ [("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)],+ )+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ session = _session_with([_response({}, status_code=status_code)])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ assert validate_credentials("token", "us") is expected++ assert _requested_urls(session) == ["https://api.harvey.ai/api/whoami"]++ def test_uses_regional_base_url(self) -> None:+ session = _session_with([_response({})])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ validate_credentials("token", "eu")++ assert _requested_urls(session) == ["https://eu.api.harvey.ai/api/whoami"]++ def test_network_error_is_invalid(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = ConnectionError("boom")+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ assert validate_credentials("token", "us") is False+++class TestCheckEndpointAccess:+ @parameterized.expand(+ [+ ("audit_logs", "audit_logs", "/api/v1/logs/audit/latest"),+ ("usage_history", "usage_history", "/api/v2/history/usage"),+ ("query_history", "query_history", "/api/v2/history/query"),+ ("client_matters", "client_matters", "/api/v1/client_matters"),+ ("vault_projects", "vault_projects", "/api/v1/vault/workspace/projects"),+ ]+ )+ def test_probes_the_right_endpoint(self, _name: str, endpoint: str, expected_path: str) -> None:+ session = _session_with([_response({})])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ assert check_endpoint_access("token", "us", endpoint) is None++ assert expected_path in _requested_urls(session)[0]++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])+ def test_denial_returns_reason(self, _name: str, status_code: int) -> None:+ session = _session_with([_response({}, status_code=status_code)])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ reason = check_endpoint_access("token", "us", "audit_logs")++ assert reason is not None+ assert "permission" in reason++ @parameterized.expand([("not_found", 404), ("throttle", 429), ("server_error", 500)])+ def test_non_denial_statuses_are_reachable(self, _name: str, status_code: int) -> None:+ session = _session_with([_response({}, status_code=status_code)])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ assert check_endpoint_access("token", "us", "audit_logs") is None++ def test_network_error_is_reachable(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = ConnectionError("boom")+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ assert check_endpoint_access("token", "us", "audit_logs") is None+++class TestSessionRedaction:+ # A dropped `redact_values` would copy the bearer token into captured request samples and logged+ # errors, leaking the credential into warehouse job telemetry. Every request-issuing entry point+ # must build its session with the token registered for redaction.+ @parameterized.expand(+ [+ ("validate_credentials", lambda: validate_credentials("token", "us")),+ ("check_endpoint_access", lambda: check_endpoint_access("token", "us", "audit_logs")),+ (+ "get_rows",+ lambda: list(+ get_rows(+ api_key="token",+ region="us",+ endpoint="client_matters",+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]+ )+ ),+ ),+ ]+ )+ def test_tracked_session_redacts_api_token(self, _name: str, run: Callable[[], Any]) -> None:+ session = _session_with([_response({})])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session) as mock_session:+ run()++ assert mock_session.call_args.kwargs["redact_values"] == ("token",)+++class TestHttpSampleCapture:+ # Capture is off by default (Harvey serves confidential legal/business data); only endpoints+ # returning purely structured metrics opt back in. usage_history is the lone opt-in; every other+ # endpoint returns free-text names, descriptions, audit metadata, or prompt/response content that+ # would leak past the scrubbers, so their sessions must be built with capture=False. A regression+ # here (flipping the default back on or dropping the per-endpoint flag) would re-introduce the leak.+ @parameterized.expand(+ [+ # History endpoints resume at `now` so the window loop makes no request - the session is+ # still built up front, which is where the capture flag is decided.+ ("query_history", "query_history", HarveyResumeConfig(window_start=NOW_EPOCH), [], False),+ ("usage_history", "usage_history", HarveyResumeConfig(window_start=NOW_EPOCH), [], True),+ ("client_matters", "client_matters", None, [_response([])], False),+ ("audit_logs", "audit_logs", HarveyResumeConfig(last_audit_log_id="log-1"), [_response([])], False),+ (+ "vault_projects",+ "vault_projects",+ HarveyResumeConfig(next_page=1),+ [_response({"response": {"content": {"projects": []}}})],+ False,+ ),+ ]+ )+ def test_get_rows_capture_flag(+ self,+ _name: str,+ endpoint: str,+ resume: HarveyResumeConfig | None,+ responses: list[Response],+ expected_capture: bool,+ ) -> None:+ session = _session_with(responses)+ with (+ freeze_time(NOW),+ mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session) as mock_session,+ ):+ list(+ get_rows(+ api_key="token",+ region="us",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeManager(resume=resume), # type: ignore[arg-type]+ )+ )++ assert mock_session.call_args.kwargs["capture"] is expected_capture++ @parameterized.expand(+ [+ ("usage_history", "usage_history", True),+ ("query_history", "query_history", False),+ ("audit_logs", "audit_logs", False),+ ]+ )+ def test_check_endpoint_access_capture_flag(self, _name: str, endpoint: str, expected_capture: bool) -> None:+ session = _session_with([_response({})])+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session) as mock_session:+ check_endpoint_access("token", "us", endpoint)++ assert mock_session.call_args.kwargs["capture"] is expected_capture+++class TestAuditLogRows:+ def _get_batches(+ self,+ responses: list[Response],+ manager: _FakeManager,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ session = _session_with(responses)+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ api_key="token",+ region="us",+ endpoint="audit_logs",+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ return batches, session++ def test_full_sync_seeds_from_earliest(self) -> None:+ manager = _FakeManager()+ batches, session = self._get_batches(+ [+ _response({"log": _audit_log("log-a")}),+ _response([_audit_log("log-b"), _audit_log("log-c")]),+ ],+ manager,+ )++ # The seed log is yielded on its own (the `from` param is exclusive), then the page.+ assert [[log["id"] for log in batch] for batch in batches] == [["log-a"], ["log-b", "log-c"]]++ urls = _requested_urls(session)+ assert urls[0] == "https://api.harvey.ai/api/v1/logs/audit/earliest"+ assert _query_params(urls[1]) == {"from": "log-a", "take": str(AUDIT_LOGS_PAGE_SIZE)}++ # State is saved after each yielded batch, bookmarking the last processed id.+ assert [state.last_audit_log_id for state in manager.saved] == ["log-a", "log-c"]++ def test_full_sync_no_logs(self) -> None:+ manager = _FakeManager()+ batches, session = self._get_batches([_response({"error": "Not found"}, status_code=404)], manager)++ assert batches == []+ assert manager.saved == []++ def test_full_page_keeps_paginating(self) -> None:+ full_page = [_audit_log(f"log-{i}") for i in range(AUDIT_LOGS_PAGE_SIZE)]+ manager = _FakeManager()+ batches, session = self._get_batches(+ [+ _response({"log": _audit_log("log-seed")}),+ _response(full_page),+ _response([]),+ ],+ manager,+ )++ assert len(batches) == 2+ urls = _requested_urls(session)+ assert _query_params(urls[2])["from"] == f"log-{AUDIT_LOGS_PAGE_SIZE - 1}"++ @freeze_time(NOW)+ def test_incremental_seeds_from_search(self) -> None:+ last_value = datetime(2026, 6, 30, 9, 0, 0, tzinfo=UTC)+ manager = _FakeManager()+ batches, session = self._get_batches(+ [+ _response({"log": _audit_log("log-a")}),+ _response([_audit_log("log-b")]),+ ],+ manager,+ db_incremental_field_last_value=last_value,+ )++ urls = _requested_urls(session)+ assert urls[0].startswith("https://api.harvey.ai/api/v1/logs/audit/search?")+ assert _query_params(urls[0]) == {"time": str(int(last_value.timestamp()))}+ assert [[log["id"] for log in batch] for batch in batches] == [["log-a"], ["log-b"]]++ @freeze_time(NOW)+ def test_incremental_caught_up(self) -> None:+ # No log at or after the watermark - the search endpoint 404s.+ manager = _FakeManager()+ batches, _ = self._get_batches(+ [_response({"error": "Not found"}, status_code=404)],+ manager,+ db_incremental_field_last_value=NOW,+ )++ assert batches == []++ @freeze_time(NOW)+ def test_incremental_watermark_older_than_search_limit_falls_back_to_earliest(self) -> None:+ stale_watermark = datetime(2024, 1, 1, tzinfo=UTC)+ manager = _FakeManager()+ _, session = self._get_batches(+ [+ _response({"log": _audit_log("log-a")}),+ _response([]),+ ],+ manager,+ db_incremental_field_last_value=stale_watermark,+ )++ assert _requested_urls(session)[0] == "https://api.harvey.ai/api/v1/logs/audit/earliest"++ def test_resume_skips_seeding(self) -> None:+ manager = _FakeManager(resume=HarveyResumeConfig(last_audit_log_id="log-x"))+ batches, session = self._get_batches([_response([_audit_log("log-y")])], manager)++ urls = _requested_urls(session)+ assert _query_params(urls[0])["from"] == "log-x"+ assert [[log["id"] for log in batch] for batch in batches] == [["log-y"]]++ def test_timestamps_are_parsed_to_datetimes(self) -> None:+ manager = _FakeManager()+ batches, _ = self._get_batches(+ [+ _response({"log": _audit_log("log-a", timestamp="2026-06-01T10:00:00Z")}),+ _response([]),+ ],+ manager,+ )++ assert batches[0][0]["timestamp"] == datetime(2026, 6, 1, 10, 0, 0, tzinfo=UTC)+++class TestHistoryRows:+ def _get_batches(+ self,+ responses: list[Response],+ manager: _FakeManager,+ endpoint: str = "usage_history",+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ session = _session_with(responses)+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ api_key="token",+ region="us",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+ return batches, session++ @parameterized.expand(+ [+ ("usage_history", "usage_history", "/api/v2/history/usage"),+ ("query_history", "query_history", "/api/v2/history/query"),+ ]+ )+ @freeze_time(NOW)+ def test_incremental_fetches_windows_up_to_now(self, _name: str, endpoint: str, expected_path: str) -> None:+ last_value = datetime(2026, 7, 1, 10, 0, 0, tzinfo=UTC)+ manager = _FakeManager()+ batches, session = self._get_batches(+ [_response({"events": [_history_event("usage-1")]})],+ manager,+ endpoint=endpoint,+ db_incremental_field_last_value=last_value,+ )++ urls = _requested_urls(session)+ assert expected_path in urls[0]+ assert _query_params(urls[0]) == {+ "start_time": str(int(last_value.timestamp())),+ "end_time": str(NOW_EPOCH),+ }+ assert [[event["unique_usage_id"] for event in batch] for batch in batches] == [["usage-1"]]+ # utc_time is parsed so the incremental watermark and partitioning see a datetime.+ assert batches[0][0]["utc_time"] == datetime(2026, 7, 1, 10, 30, 0, tzinfo=UTC)+ assert [state.window_start for state in manager.saved] == [NOW_EPOCH]++ @freeze_time(NOW)+ def test_walks_multiple_windows_and_saves_state_after_each(self) -> None:+ # 2.5 windows back from now: expect 3 requests covering contiguous ranges.+ last_value = NOW_EPOCH - int(2.5 * 24 * 60 * 60)+ manager = _FakeManager()+ batches, session = self._get_batches(+ [+ _response({"events": [_history_event("usage-1", utc_time="2026-06-29 03:00:00")]}),+ _response({"events": []}),+ _response({"events": [_history_event("usage-2", utc_time="2026-07-01 11:00:00")]}),+ ],+ manager,+ db_incremental_field_last_value=last_value,+ )++ params = [_query_params(url) for url in _requested_urls(session)]+ day = 24 * 60 * 60+ assert [(p["start_time"], p["end_time"]) for p in params] == [+ (str(last_value), str(last_value + day)),+ (str(last_value + day), str(last_value + 2 * day)),+ (str(last_value + 2 * day), str(NOW_EPOCH)),+ ]+ # The empty middle window yields nothing but still advances the saved cursor.+ assert len(batches) == 2+ assert [state.window_start for state in manager.saved] == [+ last_value + day,+ last_value + 2 * day,+ NOW_EPOCH,+ ]++ @freeze_time(NOW)+ def test_full_sync_starts_at_lookback_floor(self) -> None:+ manager = _FakeManager()+ # Widen the window so the full backfill is a single request.+ with mock.patch(f"{HARVEY_MODULE}.HISTORY_WINDOW_SECONDS", 400 * 24 * 60 * 60):+ _, session = self._get_batches([_response({"events": []})], manager)++ params = _query_params(_requested_urls(session)[0])+ assert params["start_time"] == str(NOW_EPOCH - MAX_LOOKBACK_DAYS * 24 * 60 * 60)+ assert params["end_time"] == str(NOW_EPOCH)++ @freeze_time(NOW)+ def test_incremental_caught_up_makes_no_requests(self) -> None:+ manager = _FakeManager()+ batches, session = self._get_batches([], manager, db_incremental_field_last_value=NOW)++ assert batches == []+ assert session.get.call_count == 0++ @freeze_time(NOW)+ def test_resume_starts_at_saved_window(self) -> None:+ window_start = NOW_EPOCH - 3600+ manager = _FakeManager(resume=HarveyResumeConfig(window_start=window_start))+ _, session = self._get_batches([_response({"events": []})], manager)++ assert _query_params(_requested_urls(session)[0])["start_time"] == str(window_start)++ @freeze_time(NOW)+ def test_incremental_watermark_older_than_api_limit_is_clamped(self) -> None:+ manager = _FakeManager()+ with mock.patch(f"{HARVEY_MODULE}.HISTORY_WINDOW_SECONDS", 400 * 24 * 60 * 60):+ _, session = self._get_batches(+ [_response({"events": []})],+ manager,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )++ params = _query_params(_requested_urls(session)[0])+ assert params["start_time"] == str(NOW_EPOCH - MAX_LOOKBACK_DAYS * 24 * 60 * 60)+++class TestClientMatterRows:+ def _get_batches(self, responses: list[Response]) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ session = _session_with(responses)+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ api_key="token",+ region="us",+ endpoint="client_matters",+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]+ )+ )+ return batches, session++ def test_single_unpaginated_fetch(self) -> None:+ matters = [+ {"id": "cm-1", "name": "1234-5678", "user_count": 3},+ {"id": "cm-2", "name": "8765-4321", "user_count": 1},+ ]+ batches, session = self._get_batches([_response(matters)])++ assert batches == [matters]+ assert _requested_urls(session) == ["https://api.harvey.ai/api/v1/client_matters"]++ def test_empty_list_yields_nothing(self) -> None:+ batches, _ = self._get_batches([_response([])])+ assert batches == []+++class TestVaultProjectRows:+ def _vault_page(self, project_ids: list[str], page: int, total_pages: int) -> Response:+ return _response(+ {+ "response": {+ "content": {+ "projects": [{"id": project_id, "name": project_id} for project_id in project_ids],+ "pagination": {"page": page, "per_page": 100, "total": 0, "total_pages": total_pages},+ }+ }+ }+ )++ def _get_batches(+ self, responses: list[Response], manager: _FakeManager+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:+ session = _session_with(responses)+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ api_key="token",+ region="us",+ endpoint="vault_projects",+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )+ return batches, session++ def test_single_page(self) -> None:+ manager = _FakeManager()+ batches, session = self._get_batches([self._vault_page(["proj-1", "proj-2"], page=1, total_pages=1)], manager)++ assert [[p["id"] for p in batch] for batch in batches] == [["proj-1", "proj-2"]]+ params = _query_params(_requested_urls(session)[0])+ # Name sort keeps pagination stable; the default date sort reshuffles mid-walk.+ assert params["sort_by"] == "name"+ assert params["sort_order"] == "asc"+ assert manager.saved == []++ def test_multiple_pages_save_state_between_pages(self) -> None:+ manager = _FakeManager()+ batches, session = self._get_batches(+ [+ self._vault_page(["proj-1"], page=1, total_pages=2),+ self._vault_page(["proj-2"], page=2, total_pages=2),+ ],+ manager,+ )++ assert len(batches) == 2+ assert _query_params(_requested_urls(session)[1])["page"] == "2"+ assert [state.next_page for state in manager.saved] == [2]++ def test_resume_starts_at_saved_page(self) -> None:+ manager = _FakeManager(resume=HarveyResumeConfig(next_page=3))+ _, session = self._get_batches([self._vault_page([], page=3, total_pages=5)], manager)++ assert _query_params(_requested_urls(session)[0])["page"] == "3"++ def test_empty_page_stops(self) -> None:+ manager = _FakeManager()+ batches, _ = self._get_batches([self._vault_page([], page=1, total_pages=0)], manager)+ assert batches == []+++class TestHarveySourceResponse:+ @parameterized.expand(+ [+ ("audit_logs", "audit_logs", ["id"], ["timestamp"]),+ ("usage_history", "usage_history", ["unique_usage_id"], ["utc_time"]),+ ("query_history", "query_history", ["unique_usage_id"], ["utc_time"]),+ ("client_matters", "client_matters", ["id"], None),+ ("vault_projects", "vault_projects", ["id"], None),+ ]+ )+ def test_source_response_shape(+ self, _name: str, endpoint: str, primary_keys: list[str], partition_keys: list[str] | None+ ) -> None:+ response = harvey_source(+ api_key="token",+ region="us",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]+ )++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == partition_keys+ assert response.partition_mode == ("datetime" if partition_keys else None)+ assert response.sort_mode == "asc"++ def test_unknown_endpoint_raises(self) -> None:+ with mock.patch(f"{HARVEY_MODULE}.make_tracked_session", return_value=mock.MagicMock()):+ with pytest.raises(ValueError):+ list(+ get_rows(+ api_key="token",+ region="us",+ endpoint="nonexistent",+ logger=mock.MagicMock(),+ resumable_source_manager=_FakeManager(), # type: ignore[arg-type]+ )+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey_source.pynew file mode 100644index 000000000000..74bdae9fb328--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/harvey/tests/test_harvey_source.py@@ -0,0 +1,222 @@+from typing import Any++from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HarveySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.harvey import HarveyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source import HarveySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "audit_logs",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "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-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestHarveySource:+ def setup_method(self) -> None:+ self.source = HarveySource()+ self.team_id = 123+ self.config = HarveySourceConfig(api_key="test-token", region="us")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.HARVEY++ def test_connection_host_fields_includes_region(self) -> None:+ # `region` selects the host the stored API token is sent to, so editing it must re-require the secret.+ assert self.source.connection_host_fields == ["region"]++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static endpoint catalog, so the public docs can render it.+ assert self.source.lists_tables_without_credentials is True++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Harvey"+ assert config.label == "Harvey"+ assert config.unreleasedSource is True+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/harvey.svg"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/harvey"++ api_key_field, region_field = config.fields+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.name == "region"+ assert region_field.required is True+ assert region_field.defaultValue == "us"+ assert [option.value for option in region_field.options] == ["us", "eu", "au"]++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url"),+ ("forbidden", "403 Client Error: Forbidden for url"),+ ]+ )+ def test_non_retryable_errors(self, _name: str, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ # Audit logs are immutable, so only append is offered.+ ("audit_logs", "audit_logs", False, True, "timestamp"),+ ("usage_history", "usage_history", True, True, "utc_time"),+ ("query_history", "query_history", True, True, "utc_time"),+ ("client_matters", "client_matters", False, False, None),+ ("vault_projects", "vault_projects", False, False, None),+ ]+ )+ def test_get_schemas_sync_modes(+ self,+ _name: str,+ endpoint: str,+ supports_incremental: bool,+ supports_append: bool,+ incremental_field: str | None,+ ) -> None:+ (schema,) = self.source.get_schemas(self.config, self.team_id, names=[endpoint])++ assert schema.supports_incremental is supports_incremental+ assert schema.supports_append is supports_append+ if incremental_field is None:+ assert schema.incremental_fields == []+ else:+ assert [f["field"] for f in schema.incremental_fields] == [incremental_field]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.validate_harvey_credentials"+ )+ def test_validate_credentials_success(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = True++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is True+ assert error_message is None+ mock_validate.assert_called_once_with("test-token", "us")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.validate_harvey_credentials"+ )+ def test_validate_credentials_failure(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = False++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Invalid Harvey API token"++ @parameterized.expand(+ [+ ("has_access", None, True),+ ("no_access", "Your API token does not have permission for this endpoint.", False),+ ]+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.check_endpoint_access")+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.validate_harvey_credentials"+ )+ def test_validate_credentials_with_schema_name_checks_endpoint_access(+ self,+ _name: str,+ access_reason: str | None,+ expected_valid: bool,+ mock_validate: mock.MagicMock,+ mock_access: mock.MagicMock,+ ) -> None:+ mock_validate.return_value = True+ mock_access.return_value = access_reason++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, schema_name="audit_logs")++ assert is_valid is expected_valid+ assert error_message == access_reason+ mock_access.assert_called_once_with("test-token", "us", "audit_logs")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.check_endpoint_access")+ def test_get_endpoint_permissions(self, mock_access: mock.MagicMock) -> None:+ mock_access.side_effect = lambda api_key, region, endpoint: (+ "missing permission" if endpoint == "vault_projects" else None+ )++ permissions = self.source.get_endpoint_permissions(+ self.config, self.team_id, ["audit_logs", "vault_projects", "unknown_endpoint"]+ )++ assert permissions == {+ "audit_logs": None,+ "vault_projects": "missing permission",+ "unknown_endpoint": None,+ }++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is HarveyResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.harvey_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="usage_history")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="test-token",+ region="us",+ endpoint="usage_history",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.harvey.source.harvey_source")+ def test_source_for_pipeline_strips_last_value_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_known_endpoints(self) -> None:+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS