Skip to content

: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.

feat(warehouse-sources): add the clari activity table (#102927)

Tom Owersf11ec679df99
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 922452148868..16d48917d3c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1538,12 +1538,12 @@ Note: Static endpoint config, no dynamic table discovery. Excluded settings, bra
## Clari — gaps
-Today (2): `audit_events`, `forecast`
+Today (3): `activity`, `audit_events`, `forecast`
Diffed against: <https://developer.clari.com/default/documentation/external_spec>
-- [ ] `/opportunity` — opportunity-level revenue records - the core analytical object behind every forecast number (high)
-- [ ] `/export/activity` — rep activity export (calls, emails, meetings) driving engagement-vs-outcome analysis (high)
+- [ ] `/opportunity` — skipped: `oppId` is a required query parameter (max 100 per call) and the API publishes no endpoint that lists opportunity IDs, so there is nothing to enumerate into a table. It is a point lookup for IDs a caller already holds, not a collection. The only place the API surfaces opportunity IDs is the `opportunities[]` array on activity export rows, which covers just the opportunities touched by an activity in the exported window.
+- [x] `/export/activity` — rep activity export (meetings, emails, attachments) driving engagement-vs-outcome analysis (high) — added as `activity`, incremental on the epoch-millisecond `date` field via the export's `startDate`.
Note: The public Clari API v5 spec is small: forecast export, export jobs, audit events, opportunity, activity export, admin limits, plus write-only ingest endpoints. /admin/limits was excluded as quota config and /ingest/\* as write plumbing, so opportunity and activity are the only real gaps. Clari Copilot (formerly Wingman) has a separate API host not covered by this spec.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/canonical_descriptions.py
index 088fbeed6e24..76a2b30be9c7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/canonical_descriptions.py
@@ -10,6 +10,21 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "activity": {
+ "description": "Rep activity indexed by Clari from connected inboxes and calendars, mapped to the accounts and opportunities it relates to.",
+ "docs_url": "https://developer.clari.com/",
+ "columns": {
+ "activityId": "Unique identifier for the activity record.",
+ "activityType": "Type of activity: MEETING, EMAIL_SENT, EMAIL_RECEIVED, ATTACHMENT_SENT or ATTACHMENT_RECEIVED.",
+ "subject": "Subject line of the activity.",
+ "date": "Time the activity occurred or is scheduled for, as a Unix timestamp in milliseconds.",
+ "activityOwnerId": "Salesforce ID of the user whose inbox or calendar the activity was indexed from.",
+ "activityOrganiserId": "Salesforce ID of the user who organised or created the activity.",
+ "accounts": "Accounts the activity is mapped to, each with accountId, accountName and accountOwnerId.",
+ "opportunities": "Opportunities the activity is mapped to, each with opportunityId, opportunityName and opportunityOwnerId.",
+ "participants": "People on the activity, each with name, email, sfdcUserId and whether they are internal.",
+ },
+ },
"audit_events": {
"description": "An audit log of user and system actions taken in Clari, such as forecast edits and submissions.",
"docs_url": "https://developer.clari.com/",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py
index bb115efca517..573595b304f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/clari.py
@@ -1,7 +1,6 @@
import time
-import dataclasses
-from collections.abc import Iterator
-from datetime import UTC, date, datetime
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from urllib.parse import quote, urlencode
@@ -9,7 +8,13 @@ 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.sources.clari.settings import CLARI_BASE_URL
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.clari.settings import (
+ ACTIVITY_INITIAL_LOOKBACK_DAYS,
+ ACTIVITY_TYPES,
+ CLARI_BASE_URL,
+)
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.common.typings import SourceResponse
@@ -28,11 +33,11 @@ class ClariRetryableError(Exception):
pass
+@frozen
class ClariResumeConfig:
- # Forecast: the in-flight export job to re-poll instead of creating a new
- # one (exports are quota-limited to ~1000 per rolling 30 days). Audit
- # events: the nextLink URL of the next unfetched page.
+ # Forecast and activity: the in-flight export job to re-poll instead of
+ # creating a new one (exports are quota-limited). Audit events: the
+ # nextLink URL of the next unfetched page.
job_id: Optional[str] = None
next_link: Optional[str] = None
@@ -50,6 +55,23 @@ def _format_timestamp(value: Any) -> str:
return str(value)
+def _to_datetime(value: Any) -> Optional[datetime]:
+ """Coerce an incremental watermark to UTC. Activity `date` values are epoch milliseconds."""
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime(value.year, value.month, value.day, tzinfo=UTC)
+ if isinstance(value, int | float):
+ return datetime.fromtimestamp(value / 1000, tz=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ return None
+
+
def validate_credentials(api_key: str) -> bool:
"""Confirm the API key works with a cheap audit-events probe."""
try:
@@ -121,7 +143,7 @@ def _extract_result_rows(data: Any) -> list[dict[str, Any]]:
if isinstance(data, list):
return [row for row in data if isinstance(row, dict)]
if isinstance(data, dict):
- for key in ("data", "rows", "records", "results"):
+ for key in ("data", "rows", "records", "results", "activities"):
value = data.get(key)
if isinstance(value, list):
return [row for row in value if isinstance(row, dict)]
@@ -129,29 +151,23 @@ def _extract_result_rows(data: Any) -> list[dict[str, Any]]:
return []
-def get_forecast(
- api_key: str,
- forecast_id: str,
+def _run_export_job(
+ fetch: Callable[..., requests.Response],
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[ClariResumeConfig],
-) -> Iterator[list[dict[str, Any]]]:
- session = _get_session(api_key)
- fetch = _make_fetcher(session, logger)
-
+ create_url: str,
+ create_body: dict[str, Any],
+) -> Any:
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
job_id = resume_config.job_id if resume_config is not None else None
if job_id:
- logger.debug(f"Clari: re-polling existing forecast export job {job_id}")
+ logger.debug(f"Clari: re-polling existing export job {job_id}")
if not job_id:
- create_body = fetch(
- "POST",
- f"{CLARI_BASE_URL}/export/forecast/{quote(forecast_id)}",
- json_body={"exportFormat": "JSON"},
- ).json()
- job_id = create_body.get("jobId") or (create_body.get("job") or {}).get("id")
+ created = fetch("POST", create_url, json_body=create_body).json()
+ job_id = created.get("jobId") or (created.get("job") or {}).get("id")
if not job_id:
- raise ValueError(f"Clari export job creation returned no jobId: {create_body}")
+ raise ValueError(f"Clari export job creation returned no jobId: {created}")
# Persist immediately — exports are quota-limited, so a retried
# activity must re-poll this job rather than create another.
resumable_source_manager.save_state(ClariResumeConfig(job_id=job_id))
@@ -167,13 +183,65 @@ def get_forecast(
if status in ("FAILED", "CANCELLED", "ABORTED"):
# Don't re-poll a dead job on retry.
resumable_source_manager.save_state(ClariResumeConfig(job_id=None))
- raise ValueError(f"Clari forecast export job {job_id} ended with status {status}")
+ raise ValueError(f"Clari export job {job_id} ended with status {status}")
time.sleep(EXPORT_POLL_INTERVAL_SECONDS)
else:
- raise ClariRetryableError(f"Clari forecast export job {job_id} still {status} after polling budget")
+ raise ClariRetryableError(f"Clari export job {job_id} still {status} after polling budget")
+
+ return fetch("GET", f"{CLARI_BASE_URL}/export/jobs/{quote(job_id)}/results").json()
+
- results = fetch("GET", f"{CLARI_BASE_URL}/export/jobs/{quote(job_id)}/results").json()
+def get_forecast(
+ api_key: str,
+ forecast_id: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClariResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ session = _get_session(api_key)
+ fetch = _make_fetcher(session, logger)
+
+ results = _run_export_job(
+ fetch,
+ logger,
+ resumable_source_manager,
+ create_url=f"{CLARI_BASE_URL}/export/forecast/{quote(forecast_id)}",
+ create_body={"exportFormat": "JSON"},
+ )
+ rows = _extract_result_rows(results)
+ if rows:
+ yield rows
+
+
+def get_activity(
+ api_key: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClariResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ session = _get_session(api_key)
+ fetch = _make_fetcher(session, logger)
+
+ end_date = datetime.now(tz=UTC)
+ start_date = _to_datetime(db_incremental_field_last_value) if should_use_incremental_field else None
+ if start_date is None:
+ start_date = end_date - timedelta(days=ACTIVITY_INITIAL_LOOKBACK_DAYS)
+
+ results = _run_export_job(
+ fetch,
+ logger,
+ resumable_source_manager,
+ create_url=f"{CLARI_BASE_URL}/export/activity",
+ create_body={
+ "activityTypes": list(ACTIVITY_TYPES),
+ # The export reads the date and ignores the time, so the window is day-granular
+ # and an incremental run re-exports the watermark's own day. Merge dedupes it.
+ "startDate": _format_timestamp(start_date),
+ "endDate": _format_timestamp(end_date),
+ "exportFormat": "JSON",
+ },
+ )
rows = _extract_result_rows(results)
if rows:
yield rows
@@ -188,6 +256,24 @@ def clari_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
+ if endpoint == "activity":
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_activity(
+ api_key=api_key,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=["activityId"],
+ partition_count=1,
+ partition_size=1,
+ # Export ordering is undocumented, so only commit the watermark
+ # once a sync completes.
+ sort_mode="desc",
+ )
+
if endpoint == "audit_events":
return SourceResponse(
name=endpoint,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/settings.py
index fad951dcd833..781bacfbff38 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/settings.py
@@ -2,11 +2,27 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
CLARI_BASE_URL = "https://api.clari.com/v4"
-ENDPOINTS = ("audit_events", "forecast")
+ENDPOINTS = ("activity", "audit_events", "forecast")
-# Audit events accept a server-side dateFrom filter; the forecast export is a
-# quarter-scoped snapshot with no cursor, so it is full refresh only.
+# The export filters to the activity types it is given, so ask for every supported type
+# rather than relying on an unset default.
+ACTIVITY_TYPES = ("MEETING", "EMAIL_SENT", "EMAIL_RECEIVED", "ATTACHMENT_SENT", "ATTACHMENT_RECEIVED")
+
+# The activity export requires a start date and a first sync has no watermark to derive one from.
+ACTIVITY_INITIAL_LOOKBACK_DAYS = 365
+
+# Audit events accept a server-side dateFrom filter and the activity export accepts a
+# startDate; the forecast export is a quarter-scoped snapshot with no cursor, so it is
+# full refresh only.
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "activity": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Integer,
+ "field": "date",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
"audit_events": [
{
"label": "eventTimestamp",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/source.py
index e79dd2288b54..7ab0ac1565b4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/source.py
@@ -57,7 +57,7 @@ class ClariSource(ResumableSource[ClariSourceConfig, ClariResumeConfig]):
label="Clari",
caption="""Connect your Clari account to pull your revenue data into the PostHog Data warehouse.
-Generate an API key in Clari under your account's API settings. The forecast ID is in the URL when viewing a forecast tab in Clari (e.g. `app.clari.com/forecast/<forecast-id>`). Note: Clari retains audit events for ~30 days and caps forecast exports at roughly 1,000 per rolling 30 days, so avoid very frequent syncs of the forecast table.""",
+Generate an API key in Clari under your account's API settings. The forecast ID is in the URL when viewing a forecast tab in Clari (e.g. `app.clari.com/forecast/<forecast-id>`). Note: Clari retains audit events for ~30 days and limits bulk exports per rolling 30 days, so avoid very frequent syncs of the forecast and activity tables. The first activity sync covers the past year.""",
iconPath="/static/services/clari.png",
docsUrl="https://posthog.com/docs/cdp/sources/clari",
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/tests/test_clari.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/tests/test_clari.py
index d0323b306a02..ae3500f60443 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clari/tests/test_clari.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clari/tests/test_clari.py
@@ -10,11 +10,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clari.clar
ClariRetryableError,
_extract_result_rows,
_format_timestamp,
+ _to_datetime,
clari_source,
+ get_activity,
get_audit_events,
get_forecast,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clari.settings import (
+ ACTIVITY_INITIAL_LOOKBACK_DAYS,
+)
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.clari.clari"
@@ -56,6 +61,8 @@ class TestExtractResultRows:
([{"a": 1}, "junk"], [{"a": 1}]),
({"data": [{"a": 1}]}, [{"a": 1}]),
({"rows": [{"a": 1}]}, [{"a": 1}]),
+ ({"activities": [{"a": 1}]}, [{"a": 1}]),
+ ({"activities": []}, []),
({"unknown_key": "x"}, [{"unknown_key": "x"}]),
("junk", []),
],
@@ -64,6 +71,23 @@ class TestExtractResultRows:
assert _extract_result_rows(data) == expected
+class TestToDatetime:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (1702906200000, datetime(2023, 12, 18, 13, 30, tzinfo=UTC)),
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ (datetime(2024, 1, 2, 3, 4, 5), datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ (date(2024, 1, 2), datetime(2024, 1, 2, tzinfo=UTC)),
+ ("2024-01-02T03:04:05Z", datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)),
+ ("not a date", None),
+ (None, None),
+ ],
+ )
+ def test_converts_watermarks(self, value, expected):
+ assert _to_datetime(value) == expected
+
+
class TestValidateCredentials:
@pytest.mark.parametrize(
"status_code, expected",
@@ -209,6 +233,67 @@ class TestGetForecast:
list(get_forecast("key", "fc-1", mock.MagicMock(), _make_manager()))
+class TestGetActivity:
+ def _run(self, mock_session, mock_sleep, **kwargs) -> list[list[dict[str, Any]]]:
+ mock_session.return_value.request.side_effect = [
+ _response({"jobId": "job-a"}),
+ _response({"job": {"id": "job-a", "status": "DONE"}}),
+ _response({"activities": [{"activityId": "act-1", "activityType": "MEETING"}]}),
+ ]
+ return list(get_activity("key", mock.MagicMock(), _make_manager(), **kwargs))
+
+ def _create_body(self, mock_session) -> dict[str, Any]:
+ return mock_session.return_value.request.call_args_list[0].kwargs["json"]
+
+ @mock.patch(f"{_MODULE}.time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_exports_every_activity_type_and_reads_the_activities_key(self, mock_session, mock_sleep):
+ batches = self._run(mock_session, mock_sleep)
+
+ assert batches == [[{"activityId": "act-1", "activityType": "MEETING"}]]
+ create_call = mock_session.return_value.request.call_args_list[0]
+ assert create_call.args == ("POST", "https://api.clari.com/v4/export/activity")
+ assert self._create_body(mock_session)["activityTypes"] == [
+ "MEETING",
+ "EMAIL_SENT",
+ "EMAIL_RECEIVED",
+ "ATTACHMENT_SENT",
+ "ATTACHMENT_RECEIVED",
+ ]
+
+ @mock.patch(f"{_MODULE}.time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_full_refresh_exports_the_initial_lookback_window(self, mock_session, mock_sleep):
+ self._run(mock_session, mock_sleep, should_use_incremental_field=False, db_incremental_field_last_value=123)
+
+ body = self._create_body(mock_session)
+ start = datetime.strptime(body["startDate"], "%Y-%m-%dT%H:%M:%SZ")
+ end = datetime.strptime(body["endDate"], "%Y-%m-%dT%H:%M:%SZ")
+ assert (end - start).days == ACTIVITY_INITIAL_LOOKBACK_DAYS
+
+ @mock.patch(f"{_MODULE}.time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_incremental_starts_from_the_epoch_millisecond_watermark(self, mock_session, mock_sleep):
+ self._run(
+ mock_session,
+ mock_sleep,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1702906200000,
+ )
+
+ assert self._create_body(mock_session)["startDate"] == "2023-12-18T13:30:00Z"
+
+ @mock.patch(f"{_MODULE}.time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_first_incremental_sync_falls_back_to_the_lookback_window(self, mock_session, mock_sleep):
+ self._run(mock_session, mock_sleep, should_use_incremental_field=True, db_incremental_field_last_value=None)
+
+ body = self._create_body(mock_session)
+ start = datetime.strptime(body["startDate"], "%Y-%m-%dT%H:%M:%SZ")
+ end = datetime.strptime(body["endDate"], "%Y-%m-%dT%H:%M:%SZ")
+ assert (end - start).days == ACTIVITY_INITIAL_LOOKBACK_DAYS
+
+
class TestClariSourceResponse:
def test_audit_events_metadata(self):
response = clari_source("key", "fc-1", "audit_events", mock.MagicMock(), _make_manager())
@@ -222,6 +307,14 @@ class TestClariSourceResponse:
assert not response.has_duplicate_primary_keys
validate_incremental_sync(True, response)
+ def test_activity_metadata(self):
+ response = clari_source("key", "fc-1", "activity", mock.MagicMock(), _make_manager())
+
+ assert response.name == "activity"
+ assert response.primary_keys == ["activityId"]
+ assert response.sort_mode == "desc"
+ validate_incremental_sync(True, response)
+
def test_forecast_metadata(self):
response = clari_source("key", "fc-1", "forecast", mock.MagicMock(), _make_manager())