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.

perf(weekly-digest): batch the ClickHouse lookups and the send client (#104659)

Rafael Audibertc4a694d5022a
diff --git a/posthog/session_recordings/queries/session_replay_events.py b/posthog/session_recordings/queries/session_replay_events.py
index 78aeab6a20ba..9598c087213b 100644
--- a/posthog/session_recordings/queries/session_replay_events.py
+++ b/posthog/session_recordings/queries/session_replay_events.py
@@ -835,17 +835,18 @@ class SessionReplayEvents:
return query
@staticmethod
- def count_soon_to_expire_sessions_query(
- format: Optional[str] = None,
- ):
- """
- Helper function to build a query for counting all sessions that are about to expire
+ def count_soon_to_expire_sessions_by_team_query() -> str:
+ """Count the sessions about to expire for every team in a [team_id_start, team_id_end) range.
+
+ Parameters: team_id_start, team_id_end, python_now, ttl_threshold.
+ Teams without expiring sessions return no row.
"""
- query = """
+ return """
WITH
expiring_sessions
AS (
SELECT
+ team_id,
session_id,
min(min_first_timestamp) as start_time,
max(retention_period_days) as retention_period_days,
@@ -854,24 +855,21 @@ class SessionReplayEvents:
FROM
session_replay_events
PREWHERE
- team_id = %(team_id)s
+ team_id >= %(team_id_start)s
+ AND team_id < %(team_id_end)s
AND min_first_timestamp <= %(python_now)s
GROUP BY
- session_id
+ team_id, session_id
HAVING
expiry_time >= %(python_now)s
AND recording_ttl <= %(ttl_threshold)s
- ORDER BY recording_ttl ASC
)
SELECT
+ team_id,
count(session_id) as recording_count
FROM expiring_sessions
- {optional_format_clause}
+ GROUP BY team_id
"""
- query = query.format(
- optional_format_clause=(f"FORMAT {format}" if format else ""),
- )
- return query
def get_person_emails_for_session_ids(
diff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.py
index d974cda0f3f4..08f2919d5dc2 100644
--- a/posthog/temporal/tests/weekly_digest/test_activities.py
+++ b/posthog/temporal/tests/weekly_digest/test_activities.py
@@ -1,5 +1,6 @@
import json
import inspect
+import dataclasses
from collections.abc import Callable, Iterator
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -24,10 +25,13 @@ from posthog.models.product_intent.product_intent import ProductIntent
from posthog.models.team import Team
from posthog.models.user import User
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
+from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.session_recordings.session_recording_playlist_api import PLAYLIST_COUNT_REDIS_PREFIX
from posthog.temporal.weekly_digest.activities import (
+ DIGEST_PAYLOAD_SIZE_LIMIT,
NEW_ERROR_ISSUES_PER_TEAM_LIMIT,
ActivityCancelled,
+ UploadDeadlineExceeded,
_cut_team_id_ranges,
_query_team_usage_trends,
_redis_url,
@@ -375,13 +379,58 @@ def test_generate_filter_lookup_orders_filters_by_cached_recording_count(team, r
@pytest.mark.django_db
-def test_generate_recording_lookup_stores_the_count_for_each_team(team, redis_servers, common_input, digest):
- with patch("posthog.temporal.weekly_digest.activities.sync_execute", return_value=[(10,)]) as sync_execute:
- run_sync(generate_recording_lookup, batch_input(team, digest, common_input))
+def test_generate_recording_lookup_counts_expiring_sessions_per_team(
+ organization, team, redis_servers, common_input, digest
+):
+ other_team = _make_team(organization, "other team")
+ quiet_team = _make_team(organization, "quiet team")
+ now = datetime.now(UTC)
+ # 30-day retention: sessions started 25 days ago expire in 5 days, inside the 10-day threshold.
+ for session_id in ("expiring-1", "expiring-2"):
+ produce_replay_summary(
+ team_id=team.id,
+ session_id=session_id,
+ first_timestamp=now - timedelta(days=25),
+ last_timestamp=now - timedelta(days=25),
+ retention_period_days=30,
+ ensure_analytics_event_in_session=False,
+ )
+ # Started 5 days ago, so it has 25 days left and is not about to expire.
+ produce_replay_summary(
+ team_id=team.id,
+ session_id="fresh",
+ first_timestamp=now - timedelta(days=5),
+ last_timestamp=now - timedelta(days=5),
+ retention_period_days=30,
+ ensure_analytics_event_in_session=False,
+ )
+ # Left over from an earlier attempt of the same digest; the quiet team has no sessions.
+ redis_servers.digest.set(
+ team_data_key(digest.key, TeamDataKey.EXPIRING_RECORDINGS, quiet_team.id), json.dumps({"recording_count": 9})
+ )
+ produce_replay_summary(
+ team_id=other_team.id,
+ session_id="other-expiring",
+ first_timestamp=now - timedelta(days=25),
+ last_timestamp=now - timedelta(days=25),
+ retention_period_days=30,
+ ensure_analytics_event_in_session=False,
+ )
- assert sync_execute.call_args.args[1]["team_id"] == team.id
- stored = json.loads(redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id)))
- assert stored == {"recording_count": 10}
+ run_sync(
+ generate_recording_lookup,
+ GenerateDigestDataBatchInput(
+ team_id_range=TeamIdRange(start=team.id, end=quiet_team.id + 1), digest=digest, common=common_input
+ ),
+ )
+
+ def stored_count(for_team: Team) -> dict | None:
+ raw = redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.EXPIRING_RECORDINGS, for_team.id))
+ return json.loads(raw) if raw else None
+
+ assert stored_count(team) == {"recording_count": 2}
+ assert stored_count(other_team) == {"recording_count": 1}
+ assert stored_count(quiet_team) is None
def _make_team(organization: Organization, name: str) -> Team:
@@ -580,12 +629,16 @@ def test_send_weekly_digest_batch_emails_subscribed_members_once(
run_sync(send_weekly_digest_batch, _send_input(organization, digest, common_input, dry_run=dry_run))
assert ph_client.capture.call_count == expected_captures
+ assert ph_client.shutdown.called
record = MessagingRecord.objects.get(campaign_key=digest.key)
# A dry run must not stamp the record, or the real run that follows would skip the organization.
assert (record.sent_at is not None) is (not dry_run)
if expected_captures == 0:
return
+ method_names = [name for name, _, _ in ph_client.method_calls]
+ assert method_names.index("capture") < method_names.index("flush")
+
capture = ph_client.capture.call_args.kwargs
assert capture["distinct_id"] == subscribed.distinct_id
assert capture["event"] == "transactional email"
@@ -625,7 +678,80 @@ def test_send_weekly_digest_batch_stops_sending_once_the_activity_is_cancelled(
)
assert ph_client.capture.call_count == 1
- assert MessagingRecord.objects.get(campaign_key=digest.key).sent_at is not None
+ # A queued event is unconfirmed until a drain finishes, so the cancelled attempt leaves the record unsent.
+ assert MessagingRecord.objects.get(campaign_key=digest.key).sent_at is None
+
+
+ "drop,expected_captures",
+ [
+ ("failed_upload", 1),
+ ("queue_full", 1),
+ ("oversized", 0),
+ ],
+)
+def test_send_weekly_digest_batch_leaves_organization_unsent_when_an_event_is_dropped(
+ drop, expected_captures, organization, team, redis_servers, common_input, digest
+):
+ subscribed = create_user(organization, "[email protected]")
+ redis_servers.digest.set(org_digest_key(digest.key, organization.id), _org_digest_json(organization, team))
+ redis_servers.digest.sadd(user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, subscribed.id), team.id)
+ ph_client = MagicMock()
+
+ def make_client(**kwargs: Any) -> MagicMock:
+ if drop == "failed_upload":
+ # The SDK reports a failed upload through on_error while flush drains the queue.
+ def flush(**_: Any) -> None:
+ kwargs["on_error"](
+ RuntimeError("upload failed"), [{"properties": {"organization_id": str(organization.id)}}]
+ )
+
+ ph_client.flush.side_effect = flush
+ elif drop == "queue_full":
+ ph_client.capture.return_value = None
+ return ph_client
+
+ with (
+ patch("posthog.temporal.weekly_digest.activities.get_ph_client", side_effect=make_client),
+ patch(
+ "posthog.temporal.weekly_digest.activities.DIGEST_PAYLOAD_SIZE_LIMIT",
+ 100 if drop == "oversized" else DIGEST_PAYLOAD_SIZE_LIMIT,
+ ),
+ ):
+ run_sync(send_weekly_digest_batch, _send_input(organization, digest, common_input, dry_run=False))
+
+ assert ph_client.capture.call_count == expected_captures
+ assert ph_client.shutdown.called
+ record = MessagingRecord.objects.get(campaign_key=digest.key)
+ assert record.sent_at is None
+
+
+def test_send_weekly_digest_batch_leaves_organization_unsent_when_the_attempt_runs_out_of_time(
+ activity_environment, organization, team, redis_servers, common_input, digest
+):
+ subscribed = create_user(organization, "[email protected]")
+ redis_servers.digest.set(org_digest_key(digest.key, organization.id), _org_digest_json(organization, team))
+ redis_servers.digest.sadd(user_data_key(digest.key, UserDataKey.NOTIFY_TEAMS, subscribed.id), team.id)
+ ph_client = MagicMock()
+ activity_environment.info = dataclasses.replace(
+ activity_environment.info,
+ started_time=datetime.now(UTC) - timedelta(minutes=30),
+ start_to_close_timeout=timedelta(minutes=30),
+ )
+
+ with (
+ patch("posthog.temporal.weekly_digest.activities.get_ph_client", return_value=ph_client),
+ pytest.raises(UploadDeadlineExceeded),
+ ):
+ activity_environment.run(
+ send_weekly_digest_batch_body, _send_input(organization, digest, common_input, dry_run=False)
+ )
+
+ assert ph_client.capture.call_count == 1
+ assert ph_client.shutdown.called
+ assert MessagingRecord.objects.get(campaign_key=digest.key).sent_at is None
@pytest.mark.parametrize(
@@ -680,7 +806,7 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):
)
flush_persons_and_events()
- result = _query_team_usage_trends(team.id, period_start, period_end)
+ result = _query_team_usage_trends(team, period_start, period_end)
assert result is not None
events, users = result.metrics
@@ -688,6 +814,36 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):
assert (users.label, users.current, users.previous) == ("Active users", 2, 1)
+def test_generate_usage_trends_lookup_queries_only_teams_with_events(
+ organization, team, redis_servers, common_input, digest
+):
+ idle_team = _make_team(organization, "idle team")
+ _create_event(team=team, event="$pageview", distinct_id="a", timestamp=digest.period_end - timedelta(days=1))
+ _create_event(team=idle_team, event="$pageview", distinct_id="b", timestamp=digest.period_start - timedelta(days=1))
+ flush_persons_and_events()
+ # Left over from an earlier attempt of the same digest; the idle team has no events this week.
+ redis_servers.digest.set(team_data_key(digest.key, TeamDataKey.USAGE_TRENDS, idle_team.id), '{"metrics": []}')
+
+ with patch(
+ "posthog.temporal.weekly_digest.activities._query_team_usage_trends", wraps=_query_team_usage_trends
+ ) as query_team_usage_trends:
+ run_sync(
+ generate_usage_trends_lookup,
+ GenerateDigestDataBatchInput(
+ team_id_range=TeamIdRange(start=team.id, end=idle_team.id + 1), digest=digest, common=common_input
+ ),
+ )
+
+ assert [call.args[0].id for call in query_team_usage_trends.call_args_list] == [team.id]
+ stored = json.loads(redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.USAGE_TRENDS, team.id)))
+ assert [(metric["label"], metric["current"]) for metric in stored["metrics"]] == [
+ ("Events", 1),
+ ("Active users", 1),
+ ]
+ assert redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.USAGE_TRENDS, idle_team.id)) is None
+
+
@pytest.mark.django_db
@pytest.mark.parametrize(
"side_effects,should_raise",
@@ -706,7 +862,10 @@ def test_generate_usage_trends_lookup_raises_only_when_every_team_fails(
team_id_range=TeamIdRange(start=team.id, end=second_team.id + 1), digest=digest, common=common_input
)
- with patch("posthog.temporal.weekly_digest.activities._query_team_usage_trends", side_effect=side_effects):
+ with (
+ patch("posthog.temporal.weekly_digest.activities._active_team_ids", return_value={team.id, second_team.id}),
+ patch("posthog.temporal.weekly_digest.activities._query_team_usage_trends", side_effect=side_effects),
+ ):
if should_raise:
with pytest.raises(RuntimeError):
run_sync(generate_usage_trends_lookup, input_data)
diff --git a/posthog/temporal/weekly_digest/README.md b/posthog/temporal/weekly_digest/README.md
index 8f9099a8494e..3da5be5f5aec 100644
--- a/posthog/temporal/weekly_digest/README.md
+++ b/posthog/temporal/weekly_digest/README.md
@@ -31,8 +31,8 @@ Data is stored with keys prefixed by `{digest_key}` (e.g., `weekly-digest-2024-0
Generated via `team_data_key(digest_key, TeamDataKey.*, team_id)`.
Each Postgres-backed generator reads a team id range with two queries, one for the eligible teams and one for the data, and writes its keys in one Redis pipeline.
-The ClickHouse-backed generators (usage trends, expiring recordings) still query per team.
A team with no data of a kind gets no key for it; organization aggregation substitutes an empty default for a missing key.
+The two ClickHouse-backed generators work per range too: expiring recordings are counted for the whole range in one grouped query, and usage trends first find the teams with events in the window in one query, then run the per-team HogQL query for those teams only.
| `TeamDataKey` enum | Key Pattern | Contents |
| ----------------------- | ---------------------------------------------- | ---------------------------------- |
@@ -106,7 +106,9 @@ Generated via `user_data_key(digest_key, UserDataKey.*, user_id)`:
│ a. Load user's notification team set │
│ b. Load user's product suggestion │
│ c. Create UserSpecificDigest via org_digest.for_user() │
-│ d. Render payload and send via PostHog capture event │
+│ d. Render payload and queue it as a PostHog capture event │
+│ 3. Flush queued events, then stamp the org's MessagingRecord as sent │
+│ (a dropped, oversized, or undrained event leaves the org unsent) │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
diff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.py
index 8ec519565ad7..3883b2a6bc77 100644
--- a/posthog/temporal/weekly_digest/activities.py
+++ b/posthog/temporal/weekly_digest/activities.py
@@ -1,3 +1,6 @@
+import json
+import math
+import time
from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence
from datetime import UTC, datetime
@@ -11,6 +14,7 @@ from django.utils import timezone
import redis
from posthoganalytics import Posthog
+from posthoganalytics.consumer import MAX_MSG_SIZE
from pydantic import ValidationError
from structlog.contextvars import bind_contextvars
from structlog.typing import FilteringBoundLogger
@@ -405,44 +409,36 @@ def _generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:
logger = _bind_batch_logger(input)
logger.info("Generating Replay recording count batch")
- recording_count = 0
- team_count = 0
+ eligible_team_ids = _eligible_team_ids(input)
+ tag_queries(product=Product.INTERNAL, feature=Feature.DIGEST)
+ rows = sync_execute(
+ SessionReplayEvents.count_soon_to_expire_sessions_by_team_query(),
+ {
+ "team_id_start": input.team_id_range.start,
+ "team_id_end": input.team_id_range.end,
+ "python_now": datetime.now(UTC),
+ "ttl_threshold": TTL_THRESHOLD,
+ },
+ workload=Workload.OFFLINE,
+ )
- ch_query: str = SessionReplayEvents.count_soon_to_expire_sessions_query()
+ # Teams without expiring recordings get no key; aggregation defaults the count to zero.
+ payload_by_team: dict[int, str] = {}
+ recording_count = 0
+ for team_id, count in rows:
+ if team_id not in eligible_team_ids:
+ continue
+ expiring_recordings = RecordingCount(recording_count=int(count))
+ payload_by_team[team_id] = expiring_recordings.model_dump_json()
+ recording_count += expiring_recordings.recording_count
with _digest_redis(input.common) as r:
- for team in _teams_in_range(input):
- try:
- tag_queries(product=Product.INTERNAL, feature=Feature.DIGEST, team_id=team.id)
- rows = sync_execute(
- ch_query,
- {
- "team_id": team.id,
- "python_now": datetime.now(UTC),
- "ttl_threshold": TTL_THRESHOLD,
- },
- workload=Workload.OFFLINE,
- team_id=team.id,
- )
- expiring_recordings = RecordingCount(recording_count=int(rows[0][0]) if rows else 0)
-
- key = team_data_key(input.digest.key, TeamDataKey.EXPIRING_RECORDINGS, team.id)
- r.setex(key, input.common.redis_ttl, expiring_recordings.model_dump_json())
-
- team_count += 1
- recording_count += expiring_recordings.recording_count
- except Exception as e:
- logger.warning(
- f"Failed to generate Replay recording count for team {team.id}, skipping...",
- error=str(e),
- team_id=team.id,
- )
- continue
+ _store_team_data(r, input, TeamDataKey.EXPIRING_RECORDINGS, payload_by_team, eligible_team_ids)
logger.info(
"Finished generating Replay recording count batch",
recording_count=recording_count,
- team_count=team_count,
+ team_count=len(payload_by_team),
)
@@ -506,9 +502,34 @@ def _usage_trend_metric(label: str, current: int, previous: int) -> UsageTrendMe
)
-def _query_team_usage_trends(team_id: int, period_start: datetime, period_end: datetime) -> UsageTrends | None:
+# Teams with no events in the current window produce no usage section, so one range-wide query finds
+# the teams worth a per-team HogQL query. HogQL cannot express this: it guards every table by team.
+ACTIVE_TEAMS_QUERY = """
+SELECT team_id
+FROM events
+WHERE team_id >= %(team_id_start)s AND team_id < %(team_id_end)s
+ AND timestamp >= %(period_start)s AND timestamp < %(period_end)s
+GROUP BY team_id
+"""
+
+
+def _active_team_ids(input: GenerateDigestDataBatchInput) -> set[int]:
+ tag_queries(product=Product.INTERNAL, feature=Feature.DIGEST)
+ rows = sync_execute(
+ ACTIVE_TEAMS_QUERY,
+ {
+ "team_id_start": input.team_id_range.start,
+ "team_id_end": input.team_id_range.end,
+ "period_start": input.digest.period_start,
+ "period_end": input.digest.period_end,
+ },
+ workload=Workload.OFFLINE,
+ )
+ return {int(team_id) for (team_id,) in rows}
+
+
+def _query_team_usage_trends(team: Team, period_start: datetime, period_end: datetime) -> UsageTrends | None:
"""Run the per-team usage snapshot on the offline cluster. Returns None for inactive teams."""
- team = Team.objects.get(pk=team_id)
window = period_end - period_start
response = execute_hogql_query(
query=USAGE_TRENDS_QUERY,
@@ -545,30 +566,31 @@ def _generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> None:
logger = _bind_batch_logger(input)
logger.info("Generating usage trends batch")
- team_count = 0
attempted = 0
error_count = 0
- with _digest_redis(input.common) as r:
- for team in _teams_in_range(input):
- attempted += 1
- try:
- usage_trends = _query_team_usage_trends(team.id, input.digest.period_start, input.digest.period_end)
- except Exception as e:
- error_count += 1
- logger.warning(
- f"Failed to generate usage trends for team {team.id}, skipping...",
- error=str(e),
- team_id=team.id,
- )
- continue
+ eligible_team_ids = _eligible_team_ids(input)
+ active_team_ids = _active_team_ids(input) & eligible_team_ids
+ # execute_hogql_query reads several team columns, so load the active teams in full rather than
+ # through the trimmed digest queryset.
+ active_teams = Team.objects.filter(id__in=active_team_ids).order_by("id")
- if usage_trends is None:
- continue
+ payload_by_team: dict[int, str] = {}
+ for team in active_teams:
+ attempted += 1
+ try:
+ usage_trends = _query_team_usage_trends(team, input.digest.period_start, input.digest.period_end)
+ except Exception as e:
+ error_count += 1
+ logger.warning(
+ f"Failed to generate usage trends for team {team.id}, skipping...",
+ error=str(e),
+ team_id=team.id,
+ )
+ continue
- key = team_data_key(input.digest.key, TeamDataKey.USAGE_TRENDS, team.id)
- r.setex(key, input.common.redis_ttl, usage_trends.model_dump_json())
- team_count += 1
+ if usage_trends is not None:
+ payload_by_team[team.id] = usage_trends.model_dump_json()
# A malformed query (or an offline-cluster outage) fails for every team, which would
# otherwise look identical to "no active teams" and silently ship an empty section for
@@ -576,7 +598,10 @@ def _generate_usage_trends_lookup(input: GenerateDigestDataBatchInput) -> None:
if attempted > 0 and error_count == attempted:
raise RuntimeError(f"Usage trends query failed for all {attempted} teams in batch")
- logger.info("Finished generating usage trends batch", team_count=team_count, error_count=error_count)
+ with _digest_redis(input.common) as r:
+ _store_team_data(r, input, TeamDataKey.USAGE_TRENDS, payload_by_team, eligible_team_ids)
+
+ logger.info("Finished generating usage trends batch", team_count=len(payload_by_team), error_count=error_count)
@activity.defn(name="generate-usage-trends-lookup")
@@ -865,18 +890,54 @@ def generate_organization_digest_batch(input: GenerateOrganizationDigestInput) -
RECORD_BATCH_SIZE = 100
DIGEST_ITEM_COUNT_THRESHOLD = 4
+# The SDK queue holds 10,000 events. Draining well below that keeps `capture` from dropping events on a
+# full queue, and bounds how many unconfirmed events an abandoned attempt leaves behind.
+DRAIN_EVENT_COUNT = 500
+# The SDK consumer drops an event above MAX_MSG_SIZE without calling on_error. The margin covers the fields
+# the SDK adds around the properties.
+DIGEST_PAYLOAD_SIZE_LIMIT = MAX_MSG_SIZE - 16 * 1024
+UPLOAD_CLEANUP_SECONDS = 120
+DRAIN_SLICE_SECONDS = 5
-# A BaseException, so that the per-organization `except Exception` handler cannot swallow it.
+# These derive from BaseException, so that the per-organization `except Exception` handler cannot swallow them.
class ActivityCancelled(BaseException):
pass
+class UploadDeadlineExceeded(BaseException):
+ pass
+
+
def _raise_if_cancelled() -> None:
if activity.in_activity() and activity.is_cancelled():
raise ActivityCancelled
+def _upload_deadline() -> float:
+ if not activity.in_activity():
+ return math.inf
+ info = activity.info()
+ if info.start_to_close_timeout is None:
+ return math.inf
+ remaining = info.started_time + info.start_to_close_timeout - datetime.now(UTC)
+ return time.monotonic() + remaining.total_seconds() - UPLOAD_CLEANUP_SECONDS
+
+
+def _drain(ph_client: Posthog, deadline: float) -> bool:
+ # `flush` returns silently with events still queued once its budget runs out. A slice that returns
+ # before its budget ends has emptied the queue, and short slices let a cancellation stop the wait.
+ while True:
+ _raise_if_cancelled()
+ budget = min(DRAIN_SLICE_SECONDS, deadline - time.monotonic())
+ if budget <= 0:
+ return False
+ started = time.monotonic()
+ ph_client.flush(timeout_seconds=budget)
+ if time.monotonic() - started < budget:
+ return True
+
+
def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
bind_contextvars(digest_key=input.digest.key, batch_start=input.batch[0], batch_end=input.batch[1])
logger = LOGGER.bind()
@@ -886,14 +947,40 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
empty_org_digest_count = 0
empty_user_digest_count = 0
+ # The SDK marks a batch done whether or not its upload succeeded, so this callback and the value
+ # `capture` returns are the only delivery signals. Every event carries organization_id in its payload.
+ failed_organization_ids: set[str] = set()
+
+ def on_upload_error(error: Exception, items: list[dict[str, Any]]) -> None:
+ failed_organization_ids.update(str(item.get("properties", {}).get("organization_id")) for item in items)
+ logger.warning("Failed to upload digest events", error=str(error), event_count=len(items))
+
# Only US deployment forwards email events to customer.io
- ph_client: Posthog = get_ph_client(region="US", sync_mode=True)
+ ph_client: Posthog | None = get_ph_client(region="US", on_error=on_upload_error)
if not ph_client and not input.dry_run:
logger.error("Failed to set up Posthog client")
return
- messaging_record_batch: list[MessagingRecord] = []
+ messaging_record_batch: list[tuple[str, MessagingRecord]] = []
+ deadline = _upload_deadline()
+ queued_event_count = 0
+
+ def drain() -> None:
+ nonlocal queued_event_count
+ if ph_client is not None and not _drain(ph_client, deadline):
+ raise UploadDeadlineExceeded
+ queued_event_count = 0
+
+ def record_sent(records: list[tuple[str, MessagingRecord]]) -> None:
+ # An organization whose events failed to upload keeps sent_at empty, so the next attempt resends it.
+ drain()
+ delivered = [record for organization_id, record in records if organization_id not in failed_organization_ids]
+ if len(delivered) < len(records):
+ logger.warning(
+ "Leaving organizations unsent after failed uploads", organization_count=len(records) - len(delivered)
+ )
+ MessagingRecord.objects.bulk_update(delivered, ["sent_at"])
try:
with _digest_redis(input.common) as r:
@@ -973,9 +1060,17 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
digest=payload,
user_email=user.email,
)
- else:
+ elif len(json.dumps(payload, default=str).encode()) > DIGEST_PAYLOAD_SIZE_LIMIT:
+ logger.error(
+ "Digest exceeds the event size limit, leaving the organization unsent",
+ organization_id=organization.id,
+ user_id=user.id,
+ )
+ failed_organization_ids.add(str(organization.id))
+ continue
+ elif ph_client is not None:
partial = True
- ph_client.capture(
+ queued = ph_client.capture(
distinct_id=user.distinct_id,
event="transactional email",
properties=payload,
@@ -984,6 +1079,11 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
"instance": settings.SITE_URL,
},
)
+ if queued is None:
+ failed_organization_ids.add(str(organization.id))
+ queued_event_count += 1
+ if queued_event_count >= DRAIN_EVENT_COUNT:
+ drain()
sent_digest_count += 1
except Exception as e:
@@ -996,16 +1096,18 @@ def _send_weekly_digest_batch(input: SendWeeklyDigestBatchInput) -> None:
finally:
if not input.dry_run and partial:
messaging_record.sent_at = timezone.now()
- messaging_record_batch.append(messaging_record)
+ messaging_record_batch.append((str(organization.id), messaging_record))
if len(messaging_record_batch) >= RECORD_BATCH_SIZE:
- MessagingRecord.objects.bulk_update(messaging_record_batch, ["sent_at"])
+ record_sent(messaging_record_batch)
messaging_record_batch = []
+
+ if len(messaging_record_batch) > 0:
+ record_sent(messaging_record_batch)
+
finally:
- # Sync mode sends each capture before `capture` returns, so a record in the batch belongs to an
- # organization that reached PostHog. Saving it on cancellation too keeps the retry from resending it.
- if messaging_record_batch:
- MessagingRecord.objects.bulk_update(messaging_record_batch, ["sent_at"])
+ if ph_client is not None:
+ ph_client.shutdown()
logger.info(
"Finished sending weekly digest batch",