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): support Mention API version 1.21 (#80093)

Tom Owersf282b2e30054
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index d73950fa8a61..37abe3f6cab3 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -45,7 +45,7 @@ Add it when any of these hold:
## Adding a new version, step by step
-1. **Read the vendor's changelog** (the source's `api_docs_url`) and list what changed between the currently supported version(s) and the new one: renamed/removed fields, changed pagination, new required headers, changed webhook payloads. Verification is docs-only — there are no stored credentials and no live-sync harness, so the docs are the sole source of truth for what each version serves. This is also the evidence the gate above runs on.
+1. **Read the vendor's changelog** (the source's `api_docs_url`) and list what changed between the currently supported version(s) and the new one: renamed/removed fields, changed pagination, new required headers, changed webhook payloads, or a field the source reads becoming opt-in behind a new query parameter (a field returned by default in the old version now empty unless requested — restore it by adding that parameter on the new version's request path). Verification is docs-only — there are no stored credentials and no live-sync harness, so the docs are the sole source of truth for what each version serves. This is also the evidence the gate above runs on.
2. **Declare the version** (only once the gate says the version has to exist): add the new label to `supported_versions` and flip `default_version` to it — new sources always start on the newest stable version. A pinned row's **sync** path is unaffected by a default flip (that is the point of pinning), but two things still follow the new default: discovery/`get_schemas` if the pin isn't threaded there (step 3), and any row whose `api_version` is NULL. Reference the request layer's version constants instead of duplicating string literals.
3. **Dispatch on `SourceInputs.api_version`** at the request layer:
- Keep it minimal. If the version is just a header/URL segment and response shapes are compatible, thread the version string down to where the client/URL is built (see Stripe: `StripeSource.source_for_pipeline` passes `self.resolve_api_version(inputs.api_version)` → `stripe_source(...)` → `StripeClient(stripe_version=...)`). Resolve through `resolve_api_version` at the source class — never hardcode a fallback version in the request layer.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.py
index 88a3eab62a47..94b34b42a256 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/mention.py
@@ -14,8 +14,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mention.se
MENTION_HOST = "https://api.mention.net"
MENTION_BASE_URL = f"{MENTION_HOST}/api"
-# Pinned API version, sent on every request as recommended by the Mention docs.
-API_VERSION = "1.19"
+# Vendor API versions, sent verbatim on every request via the Accept-Version header
+# (https://dev.mention.com/current/src/Changelog.html). Since 1.21 the alert resource returns an
+# empty `stats` field unless a `stats` query parameter lists the counters to include; 1.19 returns
+# them by default, so the alerts list request restores the documented counters under 1.21.
+API_VERSION_1_19 = "1.19"
+API_VERSION_1_21 = "1.21"
+SUPPORTED_API_VERSIONS = (API_VERSION_1_19, API_VERSION_1_21)
+DEFAULT_API_VERSION = API_VERSION_1_21
+# Versions that return the alert `stats` object without an explicit request for it.
+_STATS_BY_DEFAULT_VERSIONS = frozenset({API_VERSION_1_19})
+# Counters the Mention changelog documents for the 1.21 `stats` query parameter; they map to the
+# "mentions per folder and unread mention totals" the alerts schema exposes.
+ALERT_STATS_PARAM = "mention_folders.inbox.total,unread_mentions.total"
# Mentions accept up to limit=1000; 100 keeps pages small while staying well inside the documented
# 3600 list calls per alert per 24h quota.
PAGE_SIZE = 100
@@ -40,18 +51,30 @@ class MentionResumeConfig:
next_url: str | None = None
-def _headers(access_token: str) -> dict[str, str]:
+def _headers(access_token: str, api_version: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {access_token}",
"Accept": "application/json",
- "Accept-Version": API_VERSION,
+ "Accept-Version": api_version,
}
-def _list_url(path: str, limit: int | None = PAGE_SIZE) -> str:
- if limit is None:
+def _list_url(path: str, limit: int | None = PAGE_SIZE, extra_params: dict[str, str] | None = None) -> str:
+ params: dict[str, str | int] = {}
+ if limit is not None:
+ params["limit"] = limit
+ if extra_params:
+ params.update(extra_params)
+ if not params:
return f"{MENTION_BASE_URL}{path}"
- return f"{MENTION_BASE_URL}{path}?{urlencode({'limit': limit})}"
+ # ``safe=","`` keeps the comma-separated ``stats`` value readable rather than percent-encoded.
+ return f"{MENTION_BASE_URL}{path}?{urlencode(params, safe=',')}"
+
+
+def _alerts_list_url(account_id: str, api_version: str) -> str:
+ # 1.21 empties the alert `stats` field unless the counters are requested explicitly.
+ extra = None if api_version in _STATS_BY_DEFAULT_VERSIONS else {"stats": ALERT_STATS_PARAM}
+ return _list_url(f"/accounts/{account_id}/alerts", extra_params=extra)
def _more_url(payload: dict[str, Any]) -> Optional[str]:
@@ -151,13 +174,14 @@ def _alert_rows(
logger: FilteringBoundLogger,
resume: MentionResumeConfig | None,
resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
if resume and resume.next_url:
url: Optional[str] = resume.next_url
logger.debug(f"Mention: resuming alerts from cursor {url}")
else:
account_id = str(_get_account(session, logger)["id"])
- url = _list_url(f"/accounts/{account_id}/alerts")
+ url = _alerts_list_url(account_id, api_version)
while url:
payload = _fetch_page(session, url, logger)
@@ -254,14 +278,15 @@ def get_rows(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
- session = make_tracked_session(headers=_headers(access_token), redact_values=(access_token,))
+ session = make_tracked_session(headers=_headers(access_token, api_version), redact_values=(access_token,))
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if endpoint == "accounts":
yield from _account_rows(session, logger)
elif endpoint == "alerts":
- yield from _alert_rows(session, logger, resume, resumable_source_manager)
+ yield from _alert_rows(session, logger, resume, resumable_source_manager, api_version)
elif endpoint == "alert_tags":
yield from _alert_tag_rows(session, logger, resume, resumable_source_manager)
elif endpoint == "mentions":
@@ -275,6 +300,7 @@ def mention_source(
endpoint: str,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
+ api_version: str,
) -> SourceResponse:
config = MENTION_ENDPOINTS[endpoint]
@@ -285,6 +311,7 @@ def mention_source(
endpoint=endpoint,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ api_version=api_version,
),
primary_keys=config.primary_keys,
partition_count=1,
@@ -292,13 +319,15 @@ def mention_source(
)
-def check_access(access_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+def check_access(
+ access_token: str, path: str = DEFAULT_PROBE_PATH, api_version: str = DEFAULT_API_VERSION
+) -> tuple[int, Optional[str]]:
"""Probe a single endpoint to validate the access token.
Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
connection problem, other HTTP status otherwise.
"""
- session = make_tracked_session(headers=_headers(access_token), redact_values=(access_token,))
+ session = make_tracked_session(headers=_headers(access_token, api_version), redact_values=(access_token,))
try:
response = session.get(f"{MENTION_BASE_URL}{path}", timeout=15)
except Exception as e:
@@ -313,8 +342,8 @@ def check_access(access_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int
return 200, None
-def validate_credentials(access_token: str) -> tuple[bool, str | None]:
- status, message = check_access(access_token)
+def validate_credentials(access_token: str, api_version: str = DEFAULT_API_VERSION) -> tuple[bool, str | None]:
+ status, message = check_access(access_token, api_version=api_version)
if status == 200:
return True, None
if status in (401, 403):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py
index 01e5e0f3de98..7691ab9e90f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/source.py
@@ -21,6 +21,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
MentionSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mention.mention import (
+ DEFAULT_API_VERSION,
+ SUPPORTED_API_VERSIONS,
MentionResumeConfig,
mention_source,
validate_credentials,
@@ -35,8 +37,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class MentionSource(ResumableSource[MentionSourceConfig, MentionResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- supported_versions = ("1.19",)
- default_version = "1.19"
+ supported_versions = SUPPORTED_API_VERSIONS
+ default_version = DEFAULT_API_VERSION
api_docs_url = "https://dev.mention.com/"
@property
@@ -119,7 +121,7 @@ You can create an access token by registering an API application at [dev.mention
api_version: str | None = None,
) -> tuple[bool, str | None]:
# The access token is account-wide, so a single probe validates access to every schema.
- return validate_credentials(config.access_token)
+ return validate_credentials(config.access_token, api_version=self.resolve_api_version(api_version))
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MentionResumeConfig]:
return ResumableSourceManager[MentionResumeConfig](inputs, MentionResumeConfig)
@@ -138,4 +140,5 @@ You can create an access token by registering an API application at [dev.mention
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.py
index 124e9ce79707..235705d2c757 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention.py
@@ -53,6 +53,7 @@ class TestGetRows:
monkeypatch: Any,
pages: Mapping[str, Any],
endpoint: str,
+ api_version: str = mention.API_VERSION_1_19,
) -> list[dict]:
def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:
assert url in pages, f"unexpected request to {url}"
@@ -67,6 +68,7 @@ class TestGetRows:
endpoint=endpoint,
logger=MagicMock(),
resumable_source_manager=manager, # type: ignore[arg-type]
+ api_version=api_version,
):
rows.extend(batch)
return rows
@@ -169,6 +171,58 @@ class TestGetRows:
self._collect(_FakeResumableManager(), monkeypatch, {}, "nope")
+class TestApiVersioning:
+ @staticmethod
+ def _run(pages: Mapping[str, Any], endpoint: str, api_version: str) -> tuple[dict[str, str], list[str]]:
+ requested_urls: list[str] = []
+ captured: dict[str, dict[str, str]] = {}
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> dict[str, Any]:
+ requested_urls.append(url)
+ assert url in pages, f"unexpected request to {url}"
+ return pages[url]
+
+ def fake_session(**kwargs: Any) -> MagicMock:
+ captured["headers"] = kwargs["headers"]
+ return MagicMock()
+
+ with (
+ patch.object(mention, "_fetch_page", fake_fetch),
+ patch.object(mention, "make_tracked_session", fake_session),
+ ):
+ for _ in get_rows(
+ access_token="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ api_version=api_version,
+ ):
+ pass
+ return captured["headers"], requested_urls
+
+ @parameterized.expand([(v,) for v in mention.SUPPORTED_API_VERSIONS])
+ def test_pinned_version_reaches_accept_version_header(self, api_version: str) -> None:
+ # A pinned source must send its version; otherwise the sync silently tracks the app's
+ # configured version — the drift the pinning framework exists to prevent.
+ headers, _ = self._run({ME_URL: ME_PAYLOAD}, "accounts", api_version)
+ assert headers["Accept-Version"] == api_version
+
+ @parameterized.expand(
+ [
+ (mention.API_VERSION_1_19, f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"),
+ (
+ mention.API_VERSION_1_21,
+ f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100&stats={mention.ALERT_STATS_PARAM}",
+ ),
+ ]
+ )
+ def test_alerts_request_asks_for_stats_only_from_1_21(self, api_version: str, alerts_url: str) -> None:
+ # 1.21 empties the alert `stats` field unless the counters are requested explicitly; 1.19
+ # returns them by default, so only the newer version appends the `stats` query parameter.
+ _, requested_urls = self._run({ME_URL: ME_PAYLOAD, alerts_url: {"alerts": [{"id": 1}]}}, "alerts", api_version)
+ assert requested_urls[-1] == alerts_url
+
+
class TestFetchPage:
def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
response = MagicMock()
@@ -297,6 +351,7 @@ class TestMentionSourceResponse:
endpoint=endpoint,
logger=MagicMock(),
resumable_source_manager=MagicMock(),
+ api_version=mention.DEFAULT_API_VERSION,
)
assert response.name == endpoint
assert response.primary_keys == MENTION_ENDPOINTS[endpoint].primary_keys
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.py
index 52c37aac4a31..499e832c6088 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/tests/test_mention_source.py
@@ -24,6 +24,11 @@ class TestMentionSource:
def test_source_type(self) -> None:
assert self.source.source_type == ExternalDataSourceType.MENTION
+ def test_new_sources_default_to_latest_version(self) -> None:
+ # New sources are stamped with default_version; it must be the newest supported label.
+ assert self.source.supported_versions == ("1.19", "1.21")
+ assert self.source.default_version == "1.21"
+
def test_get_source_config(self) -> None:
config = self.source.get_source_config
assert config.name.value == "Mention"
@@ -95,7 +100,7 @@ class TestMentionSource:
mock_validate.return_value = (False, "Invalid Mention access token")
result = self.source.validate_credentials(self.config, self.team_id)
assert result == (False, "Invalid Mention access token")
- mock_validate.assert_called_once_with("tok")
+ mock_validate.assert_called_once_with("tok", api_version="1.21")
def test_get_resumable_source_manager_binds_resume_config(self) -> None:
manager = self.source.get_resumable_source_manager(mock.MagicMock())
@@ -106,6 +111,7 @@ class TestMentionSource:
def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
inputs = mock.MagicMock()
inputs.schema_name = "mentions"
+ inputs.api_version = "1.21"
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -115,6 +121,8 @@ class TestMentionSource:
assert kwargs["access_token"] == "tok"
assert kwargs["endpoint"] == "mentions"
assert kwargs["resumable_source_manager"] is manager
+ # The resolved source pin is threaded to the request layer so it drives the Accept-Version header.
+ assert kwargs["api_version"] == "1.21"
def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
inputs = mock.MagicMock()