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(error-tracking): fan weekly digest pages out as concurrent child workflows (#76669)

Aleksander Błaszkiewicz326da8820ef3
diff --git a/products/error_tracking/backend/temporal/weekly_digest/__init__.py b/products/error_tracking/backend/temporal/weekly_digest/__init__.py
index f90679245eb5..0e82c05ffa7c 100644
--- a/products/error_tracking/backend/temporal/weekly_digest/__init__.py
+++ b/products/error_tracking/backend/temporal/weekly_digest/__init__.py
@@ -2,14 +2,18 @@ from products.error_tracking.backend.temporal.weekly_digest.activities import (
get_digest_orgs_activity,
send_org_digest_activity,
)
-from products.error_tracking.backend.temporal.weekly_digest.workflow import ErrorTrackingWeeklyDigestWorkflow
+from products.error_tracking.backend.temporal.weekly_digest.workflow import (
+ ErrorTrackingWeeklyDigestPageWorkflow,
+ ErrorTrackingWeeklyDigestWorkflow,
+)
-WORKFLOWS = [ErrorTrackingWeeklyDigestWorkflow]
+WORKFLOWS = [ErrorTrackingWeeklyDigestWorkflow, ErrorTrackingWeeklyDigestPageWorkflow]
ACTIVITIES = [get_digest_orgs_activity, send_org_digest_activity]
__all__ = [
"ACTIVITIES",
"WORKFLOWS",
+ "ErrorTrackingWeeklyDigestPageWorkflow",
"ErrorTrackingWeeklyDigestWorkflow",
"get_digest_orgs_activity",
"send_org_digest_activity",
diff --git a/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py b/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py
index d4ce19075d4e..532a65750b93 100644
--- a/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py
+++ b/products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py
@@ -39,6 +39,7 @@ from products.error_tracking.backend.temporal.weekly_digest.types import (
)
from products.error_tracking.backend.temporal.weekly_digest.workflow import (
FAILED_ORGS_ERROR_TYPE,
+ ErrorTrackingWeeklyDigestPageWorkflow,
ErrorTrackingWeeklyDigestWorkflow,
)
from products.error_tracking.backend.weekly_digest import build_team_digest_data
@@ -399,7 +400,7 @@ class TestErrorTrackingWeeklyDigestWorkflow:
async with Worker(
env.client,
task_queue=task_queue,
- workflows=[ErrorTrackingWeeklyDigestWorkflow],
+ workflows=[ErrorTrackingWeeklyDigestWorkflow, ErrorTrackingWeeklyDigestPageWorkflow],
activities=activities,
workflow_runner=UnsandboxedWorkflowRunner(),
max_concurrent_activities=max_concurrent_activities,
@@ -497,7 +498,7 @@ class TestErrorTrackingWeeklyDigestWorkflow:
assert all(i.dry_run for i in inputs_seen)
@pytest.mark.asyncio
- async def test_pages_through_all_orgs_via_continue_as_new(self):
+ async def test_pages_through_all_orgs_via_child_workflows(self):
org_ids = sorted(f"org-{i}" for i in range(25))
cursors_seen: list[str | None] = []
seen: list[str] = []
@@ -516,15 +517,15 @@ class TestErrorTrackingWeeklyDigestWorkflow:
result = await self._execute(WeeklyDigestInputs(page_size=10), [_get_orgs, _send])
# One discovery call per page, each carrying the previous page's last org id as
- # the cursor; every org is processed exactly once across the continued executions.
+ # the cursor; every org is processed exactly once across the page children.
assert cursors_seen == [None, org_ids[9], org_ids[19]]
assert Counter(seen) == Counter(org_ids)
assert result == WeeklyDigestResult(orgs=25, orgs_failed=0, sent=25)
@pytest.mark.asyncio
- async def test_failure_in_early_page_is_carried_to_the_final_execution(self):
- # Exact multiple of page_size: the chain must end via the empty trailing page
- # without dropping carried failures or totals.
+ async def test_failure_in_early_page_is_reported_by_the_parent(self):
+ # Exact multiple of page_size: the run must end via the empty trailing page
+ # without dropping failures or totals.
org_ids = sorted(f"org-{i}" for i in range(20))
seen: list[str] = []
@@ -545,6 +546,6 @@ class TestErrorTrackingWeeklyDigestWorkflow:
cause = exc_info.value.__cause__
assert cause is not None and getattr(cause, "type", None) == FAILED_ORGS_ERROR_TYPE
- # A failure in page 1 must not stop later pages: the chain drains fully and
- # only the final execution reports the carried failure.
+ # A failure in page 1 must not stop later pages: every page drains and the
+ # parent reports the failure once at the end.
assert Counter(seen) == Counter(org_ids)
diff --git a/products/error_tracking/backend/temporal/weekly_digest/types.py b/products/error_tracking/backend/temporal/weekly_digest/types.py
index 1ee900177900..bd052786e0ab 100644
--- a/products/error_tracking/backend/temporal/weekly_digest/types.py
+++ b/products/error_tracking/backend/temporal/weekly_digest/types.py
@@ -15,18 +15,14 @@ class WeeklyDigestInputs:
# Total executions per org activity: initial run + 5 retries. The final attempt sends
# partial digests instead of deferring recipients whose teams failed to build.
max_attempts: int = 6
- # Orgs handled per workflow execution. Each page runs in its own execution (chained via
- # continue_as_new) so history stays bounded no matter how many orgs are discovered.
+ # Orgs handled per page. Per-org activity history lives in the page child workflows;
+ # the parent still records ~80KB per page (discovery result + child input), so it
+ # holds to roughly 600k orgs before nearing Temporal's 50MB history cap.
page_size: int = 1000
- # Continue-as-new carried state — never set by callers. cursor is the last org id of
- # the previous page (keyset paging: only this ~40-byte cursor rides between executions,
- # never the org list, so org count can't approach the 2 MiB payload cap); the carried_*
- # counters accumulate across the chain so the final execution can report and fail on
- # the whole run.
- cursor: str | None = None
- carried_orgs: int = 0
- carried_orgs_failed: int = 0
- carried_sent: int = 0
+ # Pages processed concurrently as child workflows. The global org-activity target is
+ # max_concurrent_pages * max_concurrent — keep it at or below the worker fleet's
+ # activity-slot capacity (35 in prod) or the extra pages just queue.
+ max_concurrent_pages: int = 3
@dataclasses.dataclass(frozen=True)
@@ -39,6 +35,15 @@ class GetDigestOrgsInputs:
limit: int = 1000
[email protected](frozen=True)
+class WeeklyDigestPageInputs:
+ # ~40 bytes per org id: a 1000-org page rides well under the 2 MiB payload cap.
+ org_ids: list[str]
+ dry_run: bool = True
+ max_concurrent: int = 10
+ max_attempts: int = 6
+
+
@dataclasses.dataclass(frozen=True)
class SendOrgDigestInputs:
org_id: str
diff --git a/products/error_tracking/backend/temporal/weekly_digest/workflow.py b/products/error_tracking/backend/temporal/weekly_digest/workflow.py
index 411b84408f1c..6e51c0d838a5 100644
--- a/products/error_tracking/backend/temporal/weekly_digest/workflow.py
+++ b/products/error_tracking/backend/temporal/weekly_digest/workflow.py
@@ -17,10 +17,12 @@ with workflow.unsafe.imports_passed_through():
SendOrgDigestInputs,
SendOrgDigestResult,
WeeklyDigestInputs,
+ WeeklyDigestPageInputs,
WeeklyDigestResult,
)
WORKFLOW_NAME = "error-tracking-weekly-digest"
+PAGE_WORKFLOW_NAME = "error-tracking-weekly-digest-page"
FAILED_ORGS_ERROR_TYPE = "ErrorTrackingWeeklyDigestOrgsFailed"
@@ -43,8 +45,82 @@ def _sent_from_error(error: BaseException) -> int:
return details[0] if details and isinstance(details[0], int) else 0
[email protected](frozen=True, kw_only=True)
+class _PageOutcome:
+ sent: int
+ orgs_failed: int
+
+
+async def _send_orgs(org_ids: list[str], dry_run: bool, max_concurrent: int, max_attempts: int) -> _PageOutcome:
+ """Run the per-org digest activities for one page, ``max_concurrent`` at a time.
+
+ Must be called from within a workflow.
+ """
+ # Keep up to max_concurrent per-org activities in flight at all times: the semaphore
+ # releases the moment one finishes, so the next org starts immediately rather than
+ # waiting for a whole wave to drain.
+ semaphore = asyncio.Semaphore(max_concurrent)
+
+ async def send_org(org_id: str) -> SendOrgDigestResult:
+ async with semaphore:
+ return await workflow.execute_activity(
+ send_org_digest_activity,
+ SendOrgDigestInputs(org_id=org_id, dry_run=dry_run, max_attempts=max_attempts),
+ start_to_close_timeout=SEND_ORG_START_TO_CLOSE_TIMEOUT,
+ heartbeat_timeout=SEND_ORG_HEARTBEAT_TIMEOUT,
+ retry_policy=common.RetryPolicy(
+ # Must match SendOrgDigestInputs.max_attempts — final-attempt detection
+ # inside the activity depends on the two agreeing.
+ maximum_attempts=max_attempts,
+ initial_interval=SEND_ORG_INITIAL_RETRY_INTERVAL,
+ backoff_coefficient=2.0,
+ maximum_interval=SEND_ORG_MAXIMUM_RETRY_INTERVAL,
+ ),
+ )
+
+ results = await asyncio.gather(*(send_org(org_id) for org_id in org_ids), return_exceptions=True)
+
+ sent = 0
+ orgs_failed = 0
+ for org_id, result in zip(org_ids, results):
+ # Workflow cancellation lands here as a captured CancelledError; counting it as an
+ # org failure would keep the run going instead of honoring the cancel.
+ if isinstance(result, asyncio.CancelledError):
+ raise result
+ if isinstance(result, BaseException):
+ orgs_failed += 1
+ sent += _sent_from_error(result)
+ workflow.logger.error(
+ "Error Tracking weekly digest org failed after retries",
+ extra={"org_id": org_id, "error": str(result)},
+ )
+ continue
+ sent += result.sent
+ return _PageOutcome(sent=sent, orgs_failed=orgs_failed)
+
+
[email protected](name=PAGE_WORKFLOW_NAME)
+class ErrorTrackingWeeklyDigestPageWorkflow(PostHogWorkflow):
+ """Processes one page of orgs. Returns counts instead of raising on org failures so the
+ parent can aggregate across pages and fail the run exactly once."""
+
+ inputs_cls = WeeklyDigestPageInputs
+
+ @workflow.run
+ async def run(self, inputs: WeeklyDigestPageInputs) -> WeeklyDigestResult:
+ outcome = await _send_orgs(inputs.org_ids, inputs.dry_run, inputs.max_concurrent, inputs.max_attempts)
+ return WeeklyDigestResult(orgs=len(inputs.org_ids), orgs_failed=outcome.orgs_failed, sent=outcome.sent)
+
+
@workflow.defn(name=WORKFLOW_NAME)
class ErrorTrackingWeeklyDigestWorkflow(PostHogWorkflow):
+ """Fans pages of orgs out as child workflows, ``max_concurrent_pages`` at a time.
+
+ Overlapping pages keeps activity slots busy while a page drains its slowest orgs —
+ with sequential pages, each page's tail (one slow org retrying) idles the whole
+ fleet until the next page starts.
+ """
+
inputs_cls = WeeklyDigestInputs
inputs_optional = True
@@ -53,72 +129,66 @@ class ErrorTrackingWeeklyDigestWorkflow(PostHogWorkflow):
if inputs is None:
inputs = WeeklyDigestInputs()
- # One keyset page per execution: only the ~40-byte cursor rides through
- # continue_as_new, so neither history nor payload size grows with org count.
- page = await workflow.execute_activity(
- get_digest_orgs_activity,
- GetDigestOrgsInputs(org_ids=inputs.org_ids, after=inputs.cursor, limit=inputs.page_size),
- start_to_close_timeout=GET_ORGS_TIMEOUT,
- retry_policy=GET_ORGS_RETRY_POLICY,
- )
-
- # Keep up to max_concurrent per-org activities in flight at all times: the semaphore
- # releases the moment one finishes, so the next org starts immediately rather than
- # waiting for a whole wave to drain.
- semaphore = asyncio.Semaphore(inputs.max_concurrent)
-
- async def send_org(org_id: str) -> SendOrgDigestResult:
- async with semaphore:
- return await workflow.execute_activity(
- send_org_digest_activity,
- SendOrgDigestInputs(org_id=org_id, dry_run=inputs.dry_run, max_attempts=inputs.max_attempts),
- start_to_close_timeout=SEND_ORG_START_TO_CLOSE_TIMEOUT,
- heartbeat_timeout=SEND_ORG_HEARTBEAT_TIMEOUT,
- retry_policy=common.RetryPolicy(
- # Must match SendOrgDigestInputs.max_attempts — final-attempt detection
- # inside the activity depends on the two agreeing.
- maximum_attempts=inputs.max_attempts,
- initial_interval=SEND_ORG_INITIAL_RETRY_INTERVAL,
- backoff_coefficient=2.0,
- maximum_interval=SEND_ORG_MAXIMUM_RETRY_INTERVAL,
+ window = asyncio.Semaphore(inputs.max_concurrent_pages)
+
+ async def run_page(org_ids: list[str], page_number: int) -> WeeklyDigestResult:
+ async with window:
+ return await workflow.execute_child_workflow(
+ ErrorTrackingWeeklyDigestPageWorkflow.run,
+ WeeklyDigestPageInputs(
+ org_ids=org_ids,
+ dry_run=inputs.dry_run,
+ max_concurrent=inputs.max_concurrent,
+ max_attempts=inputs.max_attempts,
),
+ id=f"{workflow.info().workflow_id}-page-{page_number}",
+ # Explicitly the default: terminating the parent must stop all page
+ # children too, so killing the parent is a reliable stop-everything
+ # switch and no abandoned child keeps sending digests.
+ parent_close_policy=workflow.ParentClosePolicy.TERMINATE,
)
- results = await asyncio.gather(*(send_org(org_id) for org_id in page), return_exceptions=True)
-
- sent = inputs.carried_sent
- orgs_failed = inputs.carried_orgs_failed
- for org_id, result in zip(page, results):
+ cursor: str | None = None
+ pages: list[list[str]] = []
+ page_tasks: list[asyncio.Task[WeeklyDigestResult]] = []
+ while True:
+ page = await workflow.execute_activity(
+ get_digest_orgs_activity,
+ GetDigestOrgsInputs(org_ids=inputs.org_ids, after=cursor, limit=inputs.page_size),
+ start_to_close_timeout=GET_ORGS_TIMEOUT,
+ retry_policy=GET_ORGS_RETRY_POLICY,
+ )
+ if not page:
+ break
+ pages.append(page)
+ page_tasks.append(asyncio.create_task(run_page(page, page_number=len(pages))))
+ if len(page) < inputs.page_size:
+ break
+ cursor = page[-1]
+
+ results = await asyncio.gather(*page_tasks, return_exceptions=True)
+
+ orgs = 0
+ orgs_failed = 0
+ sent = 0
+ for page, result in zip(pages, results):
+ orgs += len(page)
+ # Same as _send_orgs: a captured CancelledError is the run being cancelled,
+ # not a failed page.
+ if isinstance(result, asyncio.CancelledError):
+ raise result
if isinstance(result, BaseException):
- orgs_failed += 1
- sent += _sent_from_error(result)
+ # The child only propagates unexpected failures (per-org errors are counted
+ # inside it), so attribute the whole page.
+ orgs_failed += len(page)
workflow.logger.error(
- "Error Tracking weekly digest org failed after retries",
- extra={"org_id": org_id, "error": str(result)},
+ "Error Tracking weekly digest page failed",
+ extra={"page_size": len(page), "error": str(result)},
)
continue
+ orgs_failed += result.orgs_failed
sent += result.sent
- orgs = inputs.carried_orgs + len(page)
-
- # A full page may hide more orgs behind it; only a short page proves the set is
- # drained. An exact-multiple total costs one extra execution that gets an empty
- # page and finishes with the carried totals.
- if page and len(page) == inputs.page_size:
- workflow.logger.info(
- "Error Tracking weekly digest page complete, continuing as new",
- extra={"orgs_so_far": orgs, "cursor": page[-1], "orgs_failed": orgs_failed, "sent": sent},
- )
- workflow.continue_as_new(
- dataclasses.replace(
- inputs,
- cursor=page[-1],
- carried_orgs=orgs,
- carried_orgs_failed=orgs_failed,
- carried_sent=sent,
- )
- )
-
if not orgs:
workflow.logger.info("No orgs for Error Tracking weekly digest")