: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(error-tracking): stage digest org list in object storage, discover once (#76900)
Aleksander Błaszkiewicza0c87c639bf2
diff --git a/products/error_tracking/backend/temporal/weekly_digest/__init__.py b/products/error_tracking/backend/temporal/weekly_digest/__init__.pyindex 0e82c05ffa7c..c2fd8cbcfcdb 100644--- a/products/error_tracking/backend/temporal/weekly_digest/__init__.py+++ b/products/error_tracking/backend/temporal/weekly_digest/__init__.py@@ -1,5 +1,7 @@from products.error_tracking.backend.temporal.weekly_digest.activities import (+ cleanup_digest_orgs_activity,get_digest_orgs_activity,+ load_page_orgs_activity,send_org_digest_activity,)from products.error_tracking.backend.temporal.weekly_digest.workflow import (@@ -8,13 +10,20 @@ from products.error_tracking.backend.temporal.weekly_digest.workflow import ()WORKFLOWS = [ErrorTrackingWeeklyDigestWorkflow, ErrorTrackingWeeklyDigestPageWorkflow]-ACTIVITIES = [get_digest_orgs_activity, send_org_digest_activity]+ACTIVITIES = [+ get_digest_orgs_activity,+ load_page_orgs_activity,+ send_org_digest_activity,+ cleanup_digest_orgs_activity,+]__all__ = ["ACTIVITIES","WORKFLOWS","ErrorTrackingWeeklyDigestPageWorkflow","ErrorTrackingWeeklyDigestWorkflow",+ "cleanup_digest_orgs_activity","get_digest_orgs_activity",+ "load_page_orgs_activity","send_org_digest_activity",]diff --git a/products/error_tracking/backend/temporal/weekly_digest/activities.py b/products/error_tracking/backend/temporal/weekly_digest/activities.pyindex 342c535fef3c..1ea5d78c7fe0 100644--- a/products/error_tracking/backend/temporal/weekly_digest/activities.py+++ b/products/error_tracking/backend/temporal/weekly_digest/activities.py@@ -1,3 +1,5 @@+import json+from django.conf import settingsfrom django.db import close_old_connectionsfrom django.utils import timezone@@ -9,13 +11,17 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.cloud_utils import is_cloudfrom posthog.models import Organization, OrganizationMembership, Teamfrom posthog.models.messaging import MessagingRecord+from posthog.storage import object_storagefrom posthog.tasks.email import NotificationSetting, should_send_notificationfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.user_permissions import UserPermissionsfrom products.error_tracking.backend import weekly_digestfrom products.error_tracking.backend.temporal.weekly_digest.types import (+ CleanupDigestOrgsInputs,GetDigestOrgsInputs,+ GetDigestOrgsResult,+ LoadPageOrgsInputs,SendOrgDigestInputs,SendOrgDigestResult,)@@ -23,39 +29,63 @@ from products.error_tracking.backend.temporal.weekly_digest.types import (logger = structlog.get_logger(__name__)-def _get_digest_orgs(inputs: GetDigestOrgsInputs) -> list[str]:- """Resolve one keyset page of org ids for this run.+def _get_digest_orgs(inputs: GetDigestOrgsInputs) -> GetDigestOrgsResult:+ """Resolve the full sorted set of org ids for this run and stash it in object storage.An explicit ``org_ids`` (manual targeted runs) bypasses discovery; scheduled runs- discover every org with exceptions.+ discover every org with exceptions. Discovery's exception-count scan runs once per+ run instead of once per page; page children read their slice back via+ ``load_page_orgs_activity``, so the full list never rides through a Temporal payload.- The candidate set is sorted and sliced to (``after``, ``after`` + ``limit``] so the- workflow can page with only a cursor. Recomputing candidates each page is safe: an- org shifting in or out between pages is either <= cursor (already processed) or- > cursor (still pending), never both.+ Writing before returning makes retries idempotent: a retry overwrites the same key+ with a fresh list and the count always describes the object that was just written."""# Checked before org_ids so a targeted manual run can't route around the cloud gate. Returning- # no orgs is what keeps the send activity from being scheduled at all.+ # no orgs is what keeps the page children from being scheduled at all.if not is_cloud():logger.info("Skipping Error Tracking weekly digest outside PostHog Cloud")- return []+ return GetDigestOrgsResult(total_orgs=0)if inputs.org_ids is not None:- candidates = sorted(str(org_id) for org_id in inputs.org_ids)+ org_ids = sorted(str(org_id) for org_id in inputs.org_ids)else:- candidates = sorted(str(org_id) for org_id in weekly_digest.get_org_ids_with_exceptions())+ org_ids = sorted(str(org_id) for org_id in weekly_digest.get_org_ids_with_exceptions())- if inputs.after is not None:- candidates = [org_id for org_id in candidates if org_id > inputs.after]- return candidates[: inputs.limit]+ if org_ids:+ object_storage.write(inputs.storage_key, json.dumps(org_ids))+ return GetDigestOrgsResult(total_orgs=len(org_ids))@activity.defn-def get_digest_orgs_activity(inputs: GetDigestOrgsInputs) -> list[str]:+def get_digest_orgs_activity(inputs: GetDigestOrgsInputs) -> GetDigestOrgsResult:close_old_connections()return _get_digest_orgs(inputs)+def _load_page_orgs(inputs: LoadPageOrgsInputs) -> list[str]:+ """Read one page's org ids back from the list discovery stored.++ A missing object raises (activity retries): the parent always writes before starting+ children, so absence means storage trouble, not an empty page.+ """+ content = object_storage.read(inputs.storage_key)+ if content is None:+ raise ApplicationError(f"Digest org list not found in object storage at {inputs.storage_key}")+ org_ids = json.loads(content)+ start = (inputs.page_number - 1) * inputs.page_size+ return org_ids[start : start + inputs.page_size]+++def load_page_orgs_activity(inputs: LoadPageOrgsInputs) -> list[str]:+ return _load_page_orgs(inputs)+++def cleanup_digest_orgs_activity(inputs: CleanupDigestOrgsInputs) -> None:+ object_storage.delete(inputs.storage_key)++def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigestResult:"""Send one combined weekly error tracking digest per user in an org via the delivery workflow.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.pyindex 532a65750b93..491dc7031fac 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@@ -29,9 +29,16 @@ from products.error_tracking.backend.models import (ErrorTrackingIssueFingerprintV2,sync_issues_to_clickhouse,)-from products.error_tracking.backend.temporal.weekly_digest.activities import _get_digest_orgs, _send_org_digest+from products.error_tracking.backend.temporal.weekly_digest.activities import (+ _get_digest_orgs,+ _load_page_orgs,+ _send_org_digest,+)from products.error_tracking.backend.temporal.weekly_digest.types import (+ CleanupDigestOrgsInputs,GetDigestOrgsInputs,+ GetDigestOrgsResult,+ LoadPageOrgsInputs,SendOrgDigestInputs,SendOrgDigestResult,WeeklyDigestInputs,@@ -50,6 +57,7 @@ from ee.models.rbac.access_control import AccessControl_WEBHOOK_POST = "products.error_tracking.backend.weekly_digest.requests.post"_BUILD_TEAM_DIGEST_DATA = "products.error_tracking.backend.weekly_digest.build_team_digest_data"_IS_CLOUD = "products.error_tracking.backend.temporal.weekly_digest.activities.is_cloud"+_OBJECT_STORAGE = "products.error_tracking.backend.temporal.weekly_digest.activities.object_storage"def _days_ago(n: int) -> str:@@ -58,30 +66,35 @@ def _days_ago(n: int) -> str:@override_settings(CLOUD_DEPLOYMENT="US")class TestGetDigestOrgs(SimpleTestCase):- def test_explicit_org_ids_bypass_discovery(self):- with patch("products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions") as mock_discover:- assert _get_digest_orgs(GetDigestOrgsInputs(org_ids=["org-x"])) == ["org-x"]+ def test_explicit_org_ids_bypass_discovery_and_are_stored_sorted(self):+ with (+ patch("products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions") as mock_discover,+ patch(_OBJECT_STORAGE) as mock_storage,+ ):+ result = _get_digest_orgs(GetDigestOrgsInputs(storage_key="k", org_ids=["org-b", "org-a"]))+ assert result == GetDigestOrgsResult(total_orgs=2)mock_discover.assert_not_called()+ # Sorted before storing: page slicing downstream assumes a stable order.+ mock_storage.write.assert_called_once_with("k", json.dumps(["org-a", "org-b"]))- def test_cloud_scheduled_run_returns_all_orgs_with_exceptions(self):- with patch(- "products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions",- return_value=["org-a", "org-b"],+ def test_cloud_scheduled_run_stores_all_orgs_with_exceptions(self):+ with (+ patch(+ "products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions",+ return_value=["org-b", "org-a"],+ ),+ patch(_OBJECT_STORAGE) as mock_storage,):- assert _get_digest_orgs(GetDigestOrgsInputs()) == ["org-a", "org-b"]+ assert _get_digest_orgs(GetDigestOrgsInputs(storage_key="k")) == GetDigestOrgsResult(total_orgs=2)+ mock_storage.write.assert_called_once_with("k", json.dumps(["org-a", "org-b"]))- @parameterized.expand(- [- ("first_page", None, 2, ["org-a", "org-b"]),- ("cursor_is_exclusive", "org-b", 2, ["org-c"]),- ("cursor_between_ids_skips_nothing", "org-aa", 2, ["org-b", "org-c"]),- ("past_the_end", "org-z", 2, []),- ]- )- def test_keyset_page_bounds(self, _name, after, limit, expected):- # Unsorted input: paging correctness depends on the activity sorting before slicing.- inputs = GetDigestOrgsInputs(org_ids=["org-c", "org-a", "org-b"], after=after, limit=limit)- assert _get_digest_orgs(inputs) == expected+ def test_no_orgs_stores_nothing(self):+ with (+ patch("products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions", return_value=[]),+ patch(_OBJECT_STORAGE) as mock_storage,+ ):+ assert _get_digest_orgs(GetDigestOrgsInputs(storage_key="k")) == GetDigestOrgsResult(total_orgs=0)+ mock_storage.write.assert_not_called()@parameterized.expand([("scheduled", None), ("targeted_manual_run", ["org-x"])])def test_self_hosted_run_is_a_noop(self, _name, org_ids):@@ -89,9 +102,38 @@ class TestGetDigestOrgs(SimpleTestCase):with (patch(_IS_CLOUD, return_value=False),patch("products.error_tracking.backend.weekly_digest.get_org_ids_with_exceptions") as mock_discover,+ patch(_OBJECT_STORAGE) as mock_storage,):- assert _get_digest_orgs(GetDigestOrgsInputs(org_ids=org_ids)) == []+ assert _get_digest_orgs(GetDigestOrgsInputs(storage_key="k", org_ids=org_ids)) == GetDigestOrgsResult(+ total_orgs=0+ )mock_discover.assert_not_called()+ mock_storage.write.assert_not_called()+++class TestLoadPageOrgs(SimpleTestCase):+ @parameterized.expand(+ [+ ("first_page", 1, ["org-0", "org-1"]),+ ("middle_page", 2, ["org-2", "org-3"]),+ ("last_partial_page", 3, ["org-4"]),+ ("past_the_end", 4, []),+ ]+ )+ def test_page_slicing(self, _name, page_number, expected):+ # Off-by-one here silently drops or double-sends whole orgs; pages must tile the+ # stored list exactly.+ stored = json.dumps([f"org-{i}" for i in range(5)])+ with patch(_OBJECT_STORAGE) as mock_storage:+ mock_storage.read.return_value = stored+ inputs = LoadPageOrgsInputs(storage_key="k", page_number=page_number, page_size=2)+ assert _load_page_orgs(inputs) == expected++ def test_missing_object_raises_for_retry(self):+ with patch(_OBJECT_STORAGE) as mock_storage:+ mock_storage.read.return_value = None+ with pytest.raises(ApplicationError):+ _load_page_orgs(LoadPageOrgsInputs(storage_key="k", page_number=1, page_size=2))# send_digest_to_workflow refuses to send outside Cloud, so the send path needs cloud mode.@@ -393,6 +435,46 @@ class _FanOutTracker:inputs_seen: list[SendOrgDigestInputs] = dataclasses.field(default_factory=list)+def _storage_stubs(+ org_ids: list[str],+ cleanup_keys: list[str] | None = None,+ load_calls: list[LoadPageOrgsInputs] | None = None,+ fail_page: int | None = None,+ fail_cleanup: bool = False,+):+ # In-memory stand-in for object storage, keyed by storage_key rather than closing over+ # the org list, so a page reading a key discovery never wrote — or reading one cleanup+ # already deleted — fails here the way it would against S3.+ store: dict[str, list[str]] = {}++ @activity.defn(name="get_digest_orgs_activity")+ async def _get_orgs(inputs: GetDigestOrgsInputs) -> GetDigestOrgsResult:+ if org_ids:+ store[inputs.storage_key] = sorted(org_ids)+ return GetDigestOrgsResult(total_orgs=len(org_ids))++ @activity.defn(name="load_page_orgs_activity")+ async def _load_page(inputs: LoadPageOrgsInputs) -> list[str]:+ if load_calls is not None:+ load_calls.append(inputs)+ if inputs.page_number == fail_page:+ raise ApplicationError(f"object storage unavailable for page {fail_page}", non_retryable=True)+ if inputs.storage_key not in store:+ raise ApplicationError(f"Digest org list not found in object storage at {inputs.storage_key}")+ start = (inputs.page_number - 1) * inputs.page_size+ return store[inputs.storage_key][start : start + inputs.page_size]++ @activity.defn(name="cleanup_digest_orgs_activity")+ async def _cleanup(inputs: CleanupDigestOrgsInputs) -> None:+ if fail_cleanup:+ raise ApplicationError("object storage unavailable for cleanup", non_retryable=True)+ store.pop(inputs.storage_key, None)+ if cleanup_keys is not None:+ cleanup_keys.append(inputs.storage_key)++ return [_get_orgs, _load_page, _cleanup]++class TestErrorTrackingWeeklyDigestWorkflow:async def _execute(self, workflow_inputs, activities, max_concurrent_activities: int = 16):task_queue = str(uuid.uuid4())@@ -414,16 +496,16 @@ class TestErrorTrackingWeeklyDigestWorkflow:@pytest.mark.asyncioasync def test_completes_without_fanout_when_no_orgs(self):- @activity.defn(name="get_digest_orgs_activity")- async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:- return []+ cleanup_keys: list[str] = []@activity.defn(name="send_org_digest_activity")async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:raise AssertionError("should not fan out when there are no orgs")- result = await self._execute(WeeklyDigestInputs(), [_get_orgs, _send])+ result = await self._execute(WeeklyDigestInputs(), [*_storage_stubs([], cleanup_keys), _send])assert result == WeeklyDigestResult(orgs=0, orgs_failed=0, sent=0)+ # Nothing was stored, so there must be nothing to clean up.+ assert cleanup_keys == []@pytest.mark.asyncioasync def test_fans_out_with_concurrency_cap_and_plumbs_inputs(self):@@ -431,10 +513,6 @@ class TestErrorTrackingWeeklyDigestWorkflow:tracker = _FanOutTracker()state_lock = asyncio.Lock()- @activity.defn(name="get_digest_orgs_activity")- async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:- return org_ids-@activity.defn(name="send_org_digest_activity")async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:async with state_lock:@@ -450,7 +528,7 @@ class TestErrorTrackingWeeklyDigestWorkflow:result = await self._execute(WeeklyDigestInputs(dry_run=True, max_concurrent=3, max_attempts=4),- [_get_orgs, _send],+ [*_storage_stubs(org_ids), _send],max_concurrent_activities=len(org_ids),)@@ -468,10 +546,6 @@ class TestErrorTrackingWeeklyDigestWorkflow:sent_orgs: set[str] = set()inputs_seen: list[SendOrgDigestInputs] = []- @activity.defn(name="get_digest_orgs_activity")- async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:- return org_ids-@activity.defn(name="send_org_digest_activity")async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:inputs_seen.append(inputs)@@ -483,7 +557,7 @@ class TestErrorTrackingWeeklyDigestWorkflow:# No input at all — the shape of a manual Temporal UI run. It must fall back to# defaults, and those defaults must be a dry run.with pytest.raises(Exception) as exc_info:- await self._execute(None, [_get_orgs, _send])+ await self._execute(None, [*_storage_stubs(org_ids), _send])# Workflow raises ApplicationError(type=FAILED_ORGS_ERROR_TYPE). Temporal wraps it# in WorkflowFailureError; the cause carries the ApplicationError.@@ -500,40 +574,39 @@ class TestErrorTrackingWeeklyDigestWorkflow:@pytest.mark.asyncioasync 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] = []+ cleanup_keys: list[str] = []+ load_calls: list[LoadPageOrgsInputs] = []seen: list[str] = []- @activity.defn(name="get_digest_orgs_activity")- async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:- cursors_seen.append(inputs.after)- candidates = org_ids if inputs.after is None else [o for o in org_ids if o > inputs.after]- return candidates[: inputs.limit]-@activity.defn(name="send_org_digest_activity")async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:seen.append(inputs.org_id)return SendOrgDigestResult(sent=1, teams_built=1)- result = await self._execute(WeeklyDigestInputs(page_size=10), [_get_orgs, _send])+ result = await self._execute(+ WeeklyDigestInputs(page_size=10), [*_storage_stubs(org_ids, cleanup_keys, load_calls), _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 page children.- assert cursors_seen == [None, org_ids[9], org_ids[19]]+ # Every org is processed exactly once across the page children (25 orgs at+ # page_size 10 = pages of 10/10/5), and the stored list is cleaned up after.assert Counter(seen) == Counter(org_ids)assert result == WeeklyDigestResult(orgs=25, orgs_failed=0, sent=25)+ assert len(cleanup_keys) == 1+ # Each child must request its own page at the parent's page_size: a child that+ # ignores page_size pulls the whole list into one activity payload, which is the+ # payload-cap failure the storage handoff exists to avoid.+ assert sorted((call.page_number, call.page_size) for call in load_calls) == [(1, 10), (2, 10), (3, 10)]+ # The key written, read, and deleted must all be the same one.+ assert {call.storage_key for call in load_calls} == set(cleanup_keys)@pytest.mark.asyncioasync 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.+ # Exact multiple of page_size: page math must not add an empty trailing page+ # or drop failures or totals.org_ids = sorted(f"org-{i}" for i in range(20))+ load_calls: list[LoadPageOrgsInputs] = []seen: list[str] = []- @activity.defn(name="get_digest_orgs_activity")- async def _get_orgs(inputs: GetDigestOrgsInputs) -> list[str]:- candidates = org_ids if inputs.after is None else [o for o in org_ids if o > inputs.after]- return candidates[: inputs.limit]-@activity.defn(name="send_org_digest_activity")async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:seen.append(inputs.org_id)@@ -542,10 +615,69 @@ class TestErrorTrackingWeeklyDigestWorkflow:return SendOrgDigestResult(sent=1, teams_built=1)with pytest.raises(Exception) as exc_info:- await self._execute(WeeklyDigestInputs(page_size=10), [_get_orgs, _send])+ await self._execute(+ WeeklyDigestInputs(page_size=10), [*_storage_stubs(org_ids, load_calls=load_calls), _send]+ )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: every page drains and the# parent reports the failure once at the end.assert Counter(seen) == Counter(org_ids)+ # 20 orgs at page_size 10 is exactly two pages. A ceil that rounds up unconditionally+ # would add a third child that loads nothing.+ assert sorted(call.page_number for call in load_calls) == [1, 2]++ @pytest.mark.asyncio+ async def test_page_that_cannot_load_its_orgs_is_attributed_as_a_whole_page(self):+ # A child that never gets its org ids reports nothing back, so the parent has to+ # attribute the page from its own math. Counting it as one org would tell an+ # operator a storage outage cost 1 org when it cost the whole page.+ org_ids = sorted(f"org-{i}" for i in range(25))+ sent_orgs: list[str] = []++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ sent_orgs.append(inputs.org_id)+ return SendOrgDigestResult(sent=1, teams_built=1)++ with pytest.raises(Exception) as exc_info:+ await self._execute(WeeklyDigestInputs(page_size=10), [*_storage_stubs(org_ids, fail_page=1), _send])++ cause = exc_info.value.__cause__+ assert cause is not None and getattr(cause, "type", None) == FAILED_ORGS_ERROR_TYPE+ assert "10/25 orgs" in str(cause)+ # The other pages still drain: only page 1's orgs go unsent.+ assert Counter(sent_orgs) == Counter(org_ids[10:])++ @pytest.mark.asyncio+ async def test_cleanup_failure_does_not_fail_an_otherwise_successful_run(self):+ # Cleanup runs after every digest has already gone out, so a storage hiccup there+ # must stay best-effort: failing the run would page someone over a leftover object.+ org_ids = sorted(f"org-{i}" for i in range(5))++ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ return SendOrgDigestResult(sent=1, teams_built=1)++ result = await self._execute(+ WeeklyDigestInputs(page_size=10), [*_storage_stubs(org_ids, fail_cleanup=True), _send]+ )++ assert result == WeeklyDigestResult(orgs=5, orgs_failed=0, sent=5)++ @pytest.mark.asyncio+ @pytest.mark.parametrize("page_size", [0, -5])+ async def test_non_positive_page_size_fails_the_run(self, page_size):+ # 0 used to raise ZeroDivisionError from the page arithmetic, which Temporal retries+ # as a workflow task forever rather than failing; a negative value produced an empty+ # page range and reported a successful run that sent nothing.+ @activity.defn(name="send_org_digest_activity")+ async def _send(inputs: SendOrgDigestInputs) -> SendOrgDigestResult:+ raise AssertionError("should not fan out for an invalid page_size")++ with pytest.raises(Exception) as exc_info:+ await self._execute(WeeklyDigestInputs(page_size=page_size), [*_storage_stubs(["org-a"]), _send])++ cause = exc_info.value.__cause__+ assert cause is not None and "page_size" in str(cause)diff --git a/products/error_tracking/backend/temporal/weekly_digest/types.py b/products/error_tracking/backend/temporal/weekly_digest/types.pyindex bd052786e0ab..f8bdbe1e5ab1 100644--- a/products/error_tracking/backend/temporal/weekly_digest/types.py+++ b/products/error_tracking/backend/temporal/weekly_digest/types.py@@ -10,35 +10,50 @@ class WeeklyDigestInputs:# targeted manual runs.dry_run: bool = Trueorg_ids: list[str] | None = None- # How many per-org activities run at once (bounds ClickHouse load and webhook rate).+ # How many per-org activities run at once within each page (bounds ClickHouse load+ # and webhook rate per page).max_concurrent: int = 10# 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 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.+ # Orgs handled per page child workflow. Bounds each page's history and the size of+ # the org-id slice its load activity returns (~40KB per 1000 orgs).page_size: int = 1000- # 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)class GetDigestOrgsInputs:+ # Object storage key the discovered org ids are written to. Discovery returns only this+ # key and a count, keeping the discovered org list out of workflow history no matter how+ # many orgs it finds. A targeted manual run still passes its org_ids through directly.+ storage_key: strorg_ids: list[str] | None = None- # Keyset page bounds: return at most ``limit`` org ids, sorted, strictly greater- # than ``after``. The candidate set is recomputed each call; sorting makes paging- # stable so an org can never be returned in two pages.- after: str | None = None- limit: int = 1000++[email protected](frozen=True)+class GetDigestOrgsResult:+ total_orgs: int++[email protected](frozen=True)+class CleanupDigestOrgsInputs:+ storage_key: str++[email protected](frozen=True)+class LoadPageOrgsInputs:+ storage_key: str+ # 1-based page number into the stored sorted org list; the activity returns the+ # [page_size * (page_number - 1), page_size * page_number) slice.+ page_number: int+ page_size: int@dataclasses.dataclass(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]+ storage_key: str+ page_number: int+ page_size: intdry_run: bool = Truemax_concurrent: int = 10max_attempts: int = 6diff --git a/products/error_tracking/backend/temporal/weekly_digest/workflow.py b/products/error_tracking/backend/temporal/weekly_digest/workflow.pyindex 6e51c0d838a5..34142b9c17a0 100644--- a/products/error_tracking/backend/temporal/weekly_digest/workflow.py+++ b/products/error_tracking/backend/temporal/weekly_digest/workflow.py@@ -9,11 +9,15 @@ from posthog.temporal.common.base import PostHogWorkflowwith workflow.unsafe.imports_passed_through():from products.error_tracking.backend.temporal.weekly_digest.activities import (+ cleanup_digest_orgs_activity,get_digest_orgs_activity,+ load_page_orgs_activity,send_org_digest_activity,)from products.error_tracking.backend.temporal.weekly_digest.types import (+ CleanupDigestOrgsInputs,GetDigestOrgsInputs,+ LoadPageOrgsInputs,SendOrgDigestInputs,SendOrgDigestResult,WeeklyDigestInputs,@@ -26,9 +30,17 @@ PAGE_WORKFLOW_NAME = "error-tracking-weekly-digest-page"FAILED_ORGS_ERROR_TYPE = "ErrorTrackingWeeklyDigestOrgsFailed"+DIGEST_ORGS_STORAGE_PREFIX = "error_tracking/weekly_digest"+GET_ORGS_RETRY_POLICY = common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=30))GET_ORGS_TIMEOUT = timedelta(minutes=5)+LOAD_PAGE_RETRY_POLICY = common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5))+LOAD_PAGE_TIMEOUT = timedelta(minutes=1)++CLEANUP_RETRY_POLICY = common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5))+CLEANUP_TIMEOUT = timedelta(minutes=1)+SEND_ORG_START_TO_CLOSE_TIMEOUT = timedelta(minutes=30)SEND_ORG_HEARTBEAT_TIMEOUT = timedelta(minutes=5)SEND_ORG_INITIAL_RETRY_INTERVAL = timedelta(seconds=1)@@ -101,24 +113,34 @@ async def _send_orgs(org_ids: list[str], dry_run: bool, max_concurrent: int, max@workflow.defn(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."""+ """Processes one page of orgs, read back from the list discovery stored in object+ storage. 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.runasync 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)+ org_ids = await workflow.execute_activity(+ load_page_orgs_activity,+ LoadPageOrgsInputs(+ storage_key=inputs.storage_key, page_number=inputs.page_number, page_size=inputs.page_size+ ),+ start_to_close_timeout=LOAD_PAGE_TIMEOUT,+ retry_policy=LOAD_PAGE_RETRY_POLICY,+ )+ outcome = await _send_orgs(org_ids, inputs.dry_run, inputs.max_concurrent, inputs.max_attempts)+ return WeeklyDigestResult(orgs=len(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.+ """Discovers orgs once, stores the list in object storage, and fans every page out as+ a child workflow immediately.- 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.+ Only a storage key and a count ride through workflow history, so history and payload+ sizes stay flat regardless of org count. All children start at once, so the worker+ fleet's activity-slot capacity is the intended global throttle."""inputs_cls = WeeklyDigestInputs@@ -129,50 +151,73 @@ class ErrorTrackingWeeklyDigestWorkflow(PostHogWorkflow):if inputs is None:inputs = WeeklyDigestInputs()- 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,- )+ # Checked before discovery so a bad value can't orphan a staged list. Zero would+ # raise ZeroDivisionError from the page arithmetic below, which Temporal retries as+ # a workflow task forever instead of failing; a negative value yields an empty page+ # range and reports a successful run that sent nothing.+ if inputs.page_size < 1:+ raise ApplicationError(f"page_size must be at least 1, got {inputs.page_size}", non_retryable=True)++ info = workflow.info()+ # run_id-scoped so a re-run of the same workflow id can never read a stale list.+ storage_key = f"{DIGEST_ORGS_STORAGE_PREFIX}/{info.workflow_id}/{info.run_id}/orgs.json"++ discovery = await workflow.execute_activity(+ get_digest_orgs_activity,+ GetDigestOrgsInputs(storage_key=storage_key, org_ids=inputs.org_ids),+ start_to_close_timeout=GET_ORGS_TIMEOUT,+ retry_policy=GET_ORGS_RETRY_POLICY,+ )- 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,+ page_count = -(-discovery.total_orgs // inputs.page_size)+ page_sizes = [+ min(inputs.page_size, discovery.total_orgs - (page_number - 1) * inputs.page_size)+ for page_number in range(1, page_count + 1)+ ]++ async def run_page(page_number: int) -> WeeklyDigestResult:+ return await workflow.execute_child_workflow(+ ErrorTrackingWeeklyDigestPageWorkflow.run,+ WeeklyDigestPageInputs(+ storage_key=storage_key,+ page_number=page_number,+ page_size=inputs.page_size,+ dry_run=inputs.dry_run,+ max_concurrent=inputs.max_concurrent,+ max_attempts=inputs.max_attempts,+ ),+ id=f"{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,)- 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)+ results = await asyncio.gather(+ *(run_page(page_number) for page_number in range(1, page_count + 1)), return_exceptions=True+ )++ if discovery.total_orgs:+ # Best-effort: a leftover object costs pennies and the bucket can carry a+ # lifecycle rule; failing the whole run over cleanup would be backwards.+ try:+ await workflow.execute_activity(+ cleanup_digest_orgs_activity,+ CleanupDigestOrgsInputs(storage_key=storage_key),+ start_to_close_timeout=CLEANUP_TIMEOUT,+ retry_policy=CLEANUP_RETRY_POLICY,+ )+ except Exception as error:+ workflow.logger.warning(+ "Error Tracking weekly digest org list cleanup failed",+ extra={"storage_key": storage_key, "error": str(error)},+ )orgs = 0orgs_failed = 0sent = 0- for page, result in zip(pages, results):- orgs += len(page)+ for page_size, result in zip(page_sizes, results):+ orgs += page_size# Same as _send_orgs: a captured CancelledError is the run being cancelled,# not a failed page.if isinstance(result, asyncio.CancelledError):@@ -180,10 +225,10 @@ class ErrorTrackingWeeklyDigestWorkflow(PostHogWorkflow):if isinstance(result, BaseException):# The child only propagates unexpected failures (per-org errors are counted# inside it), so attribute the whole page.- orgs_failed += len(page)+ orgs_failed += page_sizeworkflow.logger.error("Error Tracking weekly digest page failed",- extra={"page_size": len(page), "error": str(result)},+ extra={"page_size": page_size, "error": str(result)},)continueorgs_failed += result.orgs_failed