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(data-warehouse): add mention authors, tasks and daily stats tables (#115045)

Tom Owers5e654c0a6860
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 77b864726ef7..c9d791aa3f0b 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
@@ -5516,14 +5516,14 @@ Note: Mem0 publishes a real OpenAPI spec (33 paths, linked from https://docs.mem
## Mention — gaps
-Today (4): `accounts`, `alert_tags`, `alerts`, `mentions`
+Today (7): `accounts`, `alert_authors`, `alert_daily_stats`, `alert_tags`, `alert_tasks`, `alerts`, `mentions`
Diffed against: <https://dev.mention.com/current/>
-- [ ] `GET /accounts/{account_id}/stats` — Per-alert statistics with country, tone, weekday and influencer breakdowns - the product's headline metric (high)
-- [ ] `GET /accounts/{account_id}/alerts/{alert_id}/authors` — Author/influencer breakdown per alert, with scores; a key analytical dimension over mentions (high)
-- [ ] `GET /accounts/{account_id}/alerts/{alert_id}/tasks` — Task assignments on mentions - the workflow state layered over the mentions we already sync (medium)
-- [ ] `GET /accounts/{account_id}/alerts/{alert_id}/mentions/{mention_id}/children` — Child/duplicate mentions, needed to deduplicate or measure syndication reach (medium)
+- [x] `GET /accounts/{account_id}/stats` — Per-alert statistics with country, tone, weekday and influencer breakdowns - the product's headline metric (high)
+- [x] `GET /accounts/{account_id}/alerts/{alert_id}/authors` — Author/influencer breakdown per alert, with scores; a key analytical dimension over mentions (high)
+- [x] `GET /accounts/{account_id}/alerts/{alert_id}/tasks` — Task assignments on mentions - the workflow state layered over the mentions we already sync (medium)
+- [ ] `GET /accounts/{account_id}/alerts/{alert_id}/mentions/{mention_id}/children` — Child/duplicate mentions, needed to deduplicate or measure syndication reach (medium) — not built: it needs one request per mention on top of the full mentions walk, and each `mentions` row already carries its first page of children plus the `total` count
- [ ] `GET /accounts/{account_id}/alerts/{alert_id}/shares` — Alert share membership, showing who has access to each alert (low)
Note: The reference is a static HTML tree; the full endpoint list is readable from the index page's link set. MENTION_ENDPOINTS is a static dict with no dynamic discovery, and all four tables are full-refresh.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.py
index e034acb42324..dc76279a7ef8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/canonical_descriptions.py
@@ -83,4 +83,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"metadata": "Source-specific metadata, such as tweet and Twitter user ids.",
},
},
+ "alert_authors": {
+ "description": "Authors (influencers) who published mentions found by each alert, with their influence scores. One row per author per alert.",
+ "docs_url": "https://dev.mention.com/current/src/account/alert/author/GetAuthors.html",
+ "columns": {
+ "alert_id": "Identifier of the alert the author was found by (added by PostHog during sync).",
+ "id": "Identifier of the author.",
+ "type": "Kind of author, such as people.",
+ "name": "Display name of the author.",
+ "avatar": "URL of the author's avatar image.",
+ "influencer_score": "Influence score of the author.",
+ "main_author": "Primary social profile of the author: network, URL, score, follower, following and post counts, and topics.",
+ "twitter_authors": "Twitter profiles linked to the author.",
+ "instagram_authors": "Instagram profiles linked to the author.",
+ "facebook_authors": "Facebook profiles linked to the author.",
+ "linkedin_authors": "LinkedIn profiles linked to the author.",
+ "permissions": "Actions the connected account can take on the author, such as following or messaging.",
+ },
+ },
+ "alert_tasks": {
+ "description": "Tasks assigned to team members on the mentions of each alert. One row per task per alert.",
+ "docs_url": "https://dev.mention.com/current/src/account/alert/GetTasks.html",
+ "columns": {
+ "alert_id": "Identifier of the alert the task's mention belongs to (added by PostHog during sync).",
+ "id": "Identifier of the task.",
+ "assigned_to_account": "Account the task is assigned to.",
+ "assigned_by_account": "Account that assigned the task.",
+ "type": "Kind of task, such as read.",
+ "done": "Whether the task is completed.",
+ "permissions": "Actions the connected account can take on the task, such as marking it done or deleting it.",
+ "mention": "The mention the task was created on.",
+ "created_at": "When the task was created.",
+ "updated_at": "When the task was last updated.",
+ },
+ },
+ "alert_daily_stats": {
+ "description": "Daily mention statistics per alert over the trailing year: mention volume, sentiment, and reach. One row per alert per day, bucketed in UTC by the day Mention fetched each mention.",
+ "docs_url": "https://dev.mention.com/current/src/account/stats/GetStats.html",
+ "columns": {
+ "alert_id": "Identifier of the alert the statistics belong to.",
+ "date": "Day the statistics cover (UTC).",
+ "mentions": "Number of mentions the alert found on that day.",
+ "negative_mentions": "Number of mentions with a negative tone on that day.",
+ "neutral_mentions": "Number of mentions with a neutral tone on that day.",
+ "positive_mentions": "Number of mentions with a positive tone on that day.",
+ "direct_reach": "Direct reach of the day's mentions, as sum, max, and avg.",
+ "cumulative_reach": "Cumulative reach of the day's mentions, as sum, max, and avg.",
+ "domain_reach": "Domain reach of the day's mentions, as sum, max, and avg.",
+ },
+ },
}
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 94b34b42a256..3caea3f576c7 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
@@ -1,5 +1,6 @@
import dataclasses
from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlencode, urljoin
@@ -7,6 +8,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
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
@@ -31,6 +34,10 @@ ALERT_STATS_PARAM = "mention_folders.inbox.total,unread_mentions.total"
# 3600 list calls per alert per 24h quota.
PAGE_SIZE = 100
REQUEST_TIMEOUT_SECONDS = 60
+# Trailing window requested from the stats endpoint. Stats are bucketed by the day Mention fetched
+# each mention, so recent days keep changing and the table is rebuilt on every sync.
+STATS_LOOKBACK_DAYS = 365
+STATS_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.0"
# Cheap endpoint used to confirm an access token is genuine. The token is account-wide, so one
# probe validates access to every list endpoint.
DEFAULT_PROBE_PATH = "/accounts/me"
@@ -273,6 +280,130 @@ def _alert_tag_rows(
resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids))
+def _paginated_alert_fan_out_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resume: MentionResumeConfig | None,
+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
+ path: str,
+ key: str,
+) -> Iterator[list[dict[str, Any]]]:
+ account_id = str(_get_account(session, logger)["id"])
+ alert_ids, next_url = _fan_out_alert_ids(session, account_id, logger, resume)
+
+ while alert_ids:
+ alert_id = alert_ids[0]
+ url: Optional[str] = next_url or _list_url(f"/accounts/{account_id}/alerts/{alert_id}/{path}")
+
+ while url:
+ payload = _fetch_page(session, url, logger)
+ rows = _rows_from_payload(payload, key, url)
+ for row in rows:
+ row["alert_id"] = alert_id
+
+ more = _more_url(payload) if rows else None
+ if more:
+ resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids, next_url=more))
+ else:
+ resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids[1:]))
+
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+ url = more
+
+ alert_ids = alert_ids[1:]
+ next_url = None
+
+
+@frozen
+class StatsWindow:
+ start: str
+ end: str
+
+
+def _stats_window(now: datetime) -> StatsWindow:
+ start = (now - timedelta(days=STATS_LOOKBACK_DAYS)).replace(hour=0, minute=0, second=0, microsecond=0)
+ return StatsWindow(start=start.strftime(STATS_DATE_FORMAT), end=now.strftime(STATS_DATE_FORMAT))
+
+
+def _stats_url(account_id: str, alert_id: str, window: StatsWindow) -> str:
+ params = {
+ "alerts[]": alert_id,
+ "from": window.start,
+ "to": window.end,
+ "timezone": "UTC",
+ "interval": "P1D",
+ "tones_per_interval_stats": "true",
+ "reach_per_interval_stats": "true",
+ }
+ return f"{MENTION_BASE_URL}/accounts/{account_id}/stats?{urlencode(params)}"
+
+
+def _series(alert_stats: dict[str, Any], name: str) -> dict[str, Any]:
+ series = alert_stats.get(name)
+ data = series.get("data") if isinstance(series, dict) else None
+ return data if isinstance(data, dict) else {}
+
+
+def _daily_stats_rows(alert_id: str, alert_stats: dict[str, Any]) -> list[dict[str, Any]]:
+ mentions = _series(alert_stats, "mentions_per_interval")
+ tones = _series(alert_stats, "tones_per_interval")
+ reach = {
+ column: _series(alert_stats, f"{column}_per_interval")
+ for column in ("direct_reach", "cumulative_reach", "domain_reach")
+ }
+
+ rows: list[dict[str, Any]] = []
+ for date in sorted({*mentions, *tones, *(d for series in reach.values() for d in series)}):
+ day_tones = tones.get(date)
+ day_tones = day_tones if isinstance(day_tones, dict) else {}
+ rows.append(
+ {
+ "alert_id": alert_id,
+ "date": date,
+ "mentions": mentions.get(date),
+ # Tone keys are "-1", "0" and "1"; named columns are easier to query.
+ "negative_mentions": day_tones.get("-1"),
+ "neutral_mentions": day_tones.get("0"),
+ "positive_mentions": day_tones.get("1"),
+ **{column: series.get(date) for column, series in reach.items()},
+ }
+ )
+ return rows
+
+
+def _alert_daily_stats_rows(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ resume: MentionResumeConfig | None,
+ resumable_source_manager: ResumableSourceManager[MentionResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ account_id = str(_get_account(session, logger)["id"])
+ alert_ids, _ = _fan_out_alert_ids(session, account_id, logger, resume)
+ window = _stats_window(datetime.now(UTC))
+
+ while alert_ids:
+ alert_id = alert_ids[0]
+ url = _stats_url(account_id, alert_id, window)
+ payload = _fetch_page(session, url, logger)
+ if payload.get("partial"):
+ # Mention is still generating the stats and asks callers to try again later.
+ raise MentionRetryableError(f"Mention returned partial stats for alert {alert_id}")
+
+ stats = payload.get("stats")
+ alert_stats = stats.get(alert_id) if isinstance(stats, dict) else None
+ rows = _daily_stats_rows(alert_id, alert_stats) if isinstance(alert_stats, dict) else []
+
+ alert_ids = alert_ids[1:]
+ resumable_source_manager.save_state(MentionResumeConfig(alert_ids=alert_ids))
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+
+
def get_rows(
access_token: str,
endpoint: str,
@@ -291,6 +422,16 @@ def get_rows(
yield from _alert_tag_rows(session, logger, resume, resumable_source_manager)
elif endpoint == "mentions":
yield from _mention_rows(session, logger, resume, resumable_source_manager)
+ elif endpoint == "alert_authors":
+ yield from _paginated_alert_fan_out_rows(
+ session, logger, resume, resumable_source_manager, path="authors", key="authors"
+ )
+ elif endpoint == "alert_tasks":
+ yield from _paginated_alert_fan_out_rows(
+ session, logger, resume, resumable_source_manager, path="tasks", key="tasks"
+ )
+ elif endpoint == "alert_daily_stats":
+ yield from _alert_daily_stats_rows(session, logger, resume, resumable_source_manager)
else:
raise ValueError(f"Unknown Mention endpoint '{endpoint}'")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.py
index f8b1d9d0acd0..f691439a16dd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mention/settings.py
@@ -20,6 +20,10 @@ MENTION_ENDPOINTS: dict[str, MentionEndpointConfig] = {
# Mentions fan out per alert and each row natively carries `alert_id`; the composite key keeps
# the same content matched by two alerts as two distinct rows.
"mentions": MentionEndpointConfig(name="mentions", primary_keys=["alert_id", "id"]),
+ "alert_authors": MentionEndpointConfig(name="alert_authors", primary_keys=["alert_id", "id"]),
+ "alert_tasks": MentionEndpointConfig(name="alert_tasks", primary_keys=["alert_id", "id"]),
+ # One row per alert per day of the trailing stats window.
+ "alert_daily_stats": MentionEndpointConfig(name="alert_daily_stats", primary_keys=["alert_id", "date"]),
}
ENDPOINTS = tuple(MENTION_ENDPOINTS.keys())
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 c9c7256c4287..43e7e4f2f9f2 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
@@ -51,7 +51,7 @@ class MentionSource(ResumableSource[MentionSourceConfig, MentionResumeConfig]):
label="Mention",
releaseStatus=ReleaseStatus.ALPHA,
keywords=["social listening", "media monitoring", "brand monitoring"],
- caption="""Enter your Mention API access token to pull your monitored accounts, alerts, mentions, and tags into the PostHog Data warehouse.
+ caption="""Enter your Mention API access token to pull your monitored accounts, alerts, mentions, tags, authors, tasks, and daily alert statistics into the PostHog Data warehouse.
You can create an access token by registering an API application at [dev.mention.com](https://dev.mention.com). Note that Mention API access is a paid add-on to Mention plans.
""",
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 2dd8785b057b..35181732f6b3 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
@@ -35,6 +35,7 @@ class _FakeResumableManager:
def __init__(self, state: MentionResumeConfig | None = None) -> None:
self._state = state
self.saved: list[MentionResumeConfig] = []
+ self.safe_points = 0
def can_resume(self) -> bool:
return self._state is not None
@@ -45,6 +46,9 @@ class _FakeResumableManager:
def save_state(self, data: MentionResumeConfig) -> None:
self.saved.append(data)
+ def safe_point(self) -> None:
+ self.safe_points += 1
+
class TestGetRows:
@staticmethod
@@ -148,6 +152,111 @@ class TestGetRows:
assert rows == [{"id": 46468, "name": "space", "alert_id": "11"}]
assert [s.alert_ids for s in manager.saved] == [[]]
+ @parameterized.expand([("alert_authors", "authors"), ("alert_tasks", "tasks")])
+ def test_paginated_fan_out_walks_each_alert_and_stages_state(self, endpoint: str, path: str) -> None:
+ manager = _FakeResumableManager()
+ alerts_url = f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"
+ first_11 = f"{MENTION_BASE_URL}/accounts/acc1/alerts/11/{path}?limit=100"
+ more_href = f"/api/accounts/acc1/alerts/11/{path}?limit=100&before_id=140548"
+ second_11 = f"{MENTION_HOST}{more_href}"
+ first_22 = f"{MENTION_BASE_URL}/accounts/acc1/alerts/22/{path}?limit=100"
+ pages = {
+ ME_URL: ME_PAYLOAD,
+ alerts_url: {"alerts": [{"alert": {"id": 11}}, {"alert": {"id": 22}}]},
+ first_11: {path: [{"id": "a"}], "_links": {"more": {"href": more_href}}},
+ second_11: {path: [{"id": "b"}], "_links": {}},
+ first_22: {path: [], "_links": {}},
+ }
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ rows = self._collect(manager, monkeypatch, pages, endpoint)
+ assert rows == [{"id": "a", "alert_id": "11"}, {"id": "b", "alert_id": "11"}]
+ assert [(s.alert_ids, s.next_url) for s in manager.saved] == [
+ (["11", "22"], second_11),
+ (["22"], None),
+ ([], None),
+ ]
+ # The empty alert yields nothing, so it must hand the worker a safe point instead.
+ assert manager.safe_points == 1
+
+ def test_paginated_fan_out_resumes_mid_alert_from_cursor(self, monkeypatch: Any) -> None:
+ cursor = f"{MENTION_HOST}/api/accounts/acc1/alerts/22/tasks?limit=100&before_id=140548"
+ manager = _FakeResumableManager(MentionResumeConfig(alert_ids=["22", "33"], next_url=cursor))
+ first_33 = f"{MENTION_BASE_URL}/accounts/acc1/alerts/33/tasks?limit=100"
+ pages = {
+ ME_URL: ME_PAYLOAD,
+ cursor: {"tasks": [{"id": "t1"}], "_links": {}},
+ first_33: {"tasks": [{"id": "t2"}], "_links": {}},
+ }
+ rows = self._collect(manager, monkeypatch, pages, "alert_tasks")
+ assert rows == [{"id": "t1", "alert_id": "22"}, {"id": "t2", "alert_id": "33"}]
+
+ def test_alert_daily_stats_reshapes_series_into_daily_rows(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ window = mention.StatsWindow(start="2025-01-01T00:00:00.0", end="2026-01-01T12:00:00.0")
+ monkeypatch.setattr(mention, "_stats_window", lambda now: window)
+ alerts_url = f"{MENTION_BASE_URL}/accounts/acc1/alerts?limit=100"
+ stats_url = (
+ f"{MENTION_BASE_URL}/accounts/acc1/stats?alerts%5B%5D=11&from=2025-01-01T00%3A00%3A00.0"
+ "&to=2026-01-01T12%3A00%3A00.0&timezone=UTC&interval=P1D"
+ "&tones_per_interval_stats=true&reach_per_interval_stats=true"
+ )
+ reach = {"sum": 507, "max": 267, "avg": 48.5}
+ pages = {
+ ME_URL: ME_PAYLOAD,
+ alerts_url: {"alerts": [{"alert": {"id": 11}}]},
+ stats_url: {
+ "stats": {
+ "11": {
+ "mentions_per_interval": {"data": {"2025-06-02": 5, "2025-06-01": 322}, "total": 327},
+ "tones_per_interval": {"data": {"2025-06-01": {"-1": 7, "0": 267, "1": 48}}},
+ "direct_reach_per_interval": {"data": {"2025-06-01": reach}},
+ "week_days_total": {"data": {"1": [3, 36]}, "total": 39},
+ }
+ },
+ "from": window.start,
+ "to": window.end,
+ },
+ }
+ rows = self._collect(manager, monkeypatch, pages, "alert_daily_stats")
+ assert rows == [
+ {
+ "alert_id": "11",
+ "date": "2025-06-01",
+ "mentions": 322,
+ "negative_mentions": 7,
+ "neutral_mentions": 267,
+ "positive_mentions": 48,
+ "direct_reach": reach,
+ "cumulative_reach": None,
+ "domain_reach": None,
+ },
+ {
+ "alert_id": "11",
+ "date": "2025-06-02",
+ "mentions": 5,
+ "negative_mentions": None,
+ "neutral_mentions": None,
+ "positive_mentions": None,
+ "direct_reach": None,
+ "cumulative_reach": None,
+ "domain_reach": None,
+ },
+ ]
+ assert [s.alert_ids for s in manager.saved] == [[]]
+
+ def test_alert_daily_stats_partial_response_is_retryable(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(MentionResumeConfig(alert_ids=["11"]))
+ monkeypatch.setattr(mention, "_stats_window", lambda now: mention.StatsWindow(start="f", end="t"))
+ stats_url = (
+ f"{MENTION_BASE_URL}/accounts/acc1/stats?alerts%5B%5D=11&from=f&to=t&timezone=UTC&interval=P1D"
+ "&tones_per_interval_stats=true&reach_per_interval_stats=true"
+ )
+ pages = {ME_URL: ME_PAYLOAD, stats_url: {"stats": {"11": {}}, "partial": True}}
+ with pytest.raises(MentionRetryableError, match="partial stats"):
+ self._collect(manager, monkeypatch, pages, "alert_daily_stats")
+ # The alert stays queued so the retried sync fetches its stats again.
+ assert manager.saved == []
+
def test_unknown_endpoint_raises(self, monkeypatch: Any) -> None:
with pytest.raises(ValueError, match="Unknown Mention endpoint 'nope'"):
self._collect(_FakeResumableManager(), monkeypatch, {}, "nope")