: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
fix(signals): throttle weekly repository-activity rebuild fan-out (#92034)
posthog[bot]8c5c8549eeb4
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 2f1b755fb092..f068b97fd6be 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -2,6 +2,7 @@ from datetime import timedeltafrom decimal import Decimalfrom django.core.cache import cache+from django.db.models import Qfrom django.utils import timezoneimport structlog@@ -484,6 +485,12 @@ def sync_pending_signals_refund_credits() -> None:_ACTIVITY_ROW_MAX_IDLE = timedelta(days=90)+# Every rebuild boots a Modal sandbox, so the weekly warm-up releases rebuilds in small batches+# spaced this far apart rather than all at once. A single burst of the whole fan-out trips+# Modal's API rate limit once enough repositories are warm. N repositories fully release in about+# (N / _REFRESH_BATCH_SIZE) * _REFRESH_BATCH_INTERVAL_SECONDS, well within the weekly cadence.+_REFRESH_BATCH_SIZE = 10+_REFRESH_BATCH_INTERVAL_SECONDS = 60# Backstop for a worker dying without releasing the rebuild lock; above the task's# time_limit so a live rebuild is never treated as abandoned._REBUILD_LOCK_TTL_SECONDS = 30 * 60@@ -593,23 +600,43 @@ def pause_inactive_signal_scouts() -> None:name="products.signals.backend.tasks.refresh_signal_repository_activity",ignore_result=True,max_retries=0,+ # The chain holds each countdown message in one worker's memory for the whole interval.+ # Ack it only after the batch schedules the next one, so a worker restart (deploy,+ # scale-down, OOM) redelivers the message and resumes the walk instead of dropping it.+ acks_late=True,+ reject_on_worker_lost=True,)@skip_team_scope_audit-def refresh_signal_repository_activity() -> None:- """Weekly (Monday) warm-up: enqueue a rebuild for every recently-used repository map."""+def refresh_signal_repository_activity(after_team_id: int | None = None, after_repository: str | None = None) -> None:+ """Weekly (Monday) warm-up: enqueue a rebuild for every recently-used repository map.++ Releases rebuilds in batches of ``_REFRESH_BATCH_SIZE``. Each batch re-schedules the next+ after ``_REFRESH_BATCH_INTERVAL_SECONDS`` via a stable (team_id, repository) cursor, so the+ fan-out spreads over the window instead of bursting past Modal's sandbox-creation rate limit.+ """now = timezone.now()- SignalRepositoryAreaActivity.objects.unscoped().filter(- last_used_at__lt=now - _ACTIVITY_ROW_MAX_IDLE- ).delete() # nosemgrep: idor-lookup-without-team (system Celery sweeper, no user input; unscoped is the sanctioned cross-team access)-- repositories = list(- SignalRepositoryAreaActivity.objects.unscoped() # nosemgrep: idor-lookup-without-team (system Celery sweeper, no user input; unscoped is the sanctioned cross-team access)- .filter(last_used_at__gte=now - ACTIVITY_KEEP_WARM_WINDOW)- .values_list("team_id", "repository")- .distinct()- .order_by("team_id", "repository")+ first_batch = after_team_id is None and after_repository is None+ if first_batch:+ SignalRepositoryAreaActivity.objects.unscoped().filter(+ last_used_at__lt=now - _ACTIVITY_ROW_MAX_IDLE+ ).delete() # nosemgrep: idor-lookup-without-team (system Celery sweeper, no user input; unscoped is the sanctioned cross-team access)++ warm = SignalRepositoryAreaActivity.objects.unscoped().filter( # nosemgrep: idor-lookup-without-team (system Celery sweeper, no user input; unscoped is the sanctioned cross-team access)+ last_used_at__gte=now - ACTIVITY_KEEP_WARM_WINDOW)- for team_id, repository in repositories:+ if after_team_id is not None and after_repository is not None:+ warm = warm.filter(Q(team_id__gt=after_team_id) | Q(team_id=after_team_id, repository__gt=after_repository))+ batch = list(+ warm.values_list("team_id", "repository").distinct().order_by("team_id", "repository")[:_REFRESH_BATCH_SIZE]+ )+ if not batch:+ return+ for team_id, repository in batch:rebuild_signal_repository_activity.delay(team_id=team_id, repository=repository, force=True)- if repositories:- logger.info("signals repository activity refresh enqueued rebuilds", count=len(repositories))+ logger.info("signals repository activity refresh enqueued rebuilds", count=len(batch))+ if len(batch) == _REFRESH_BATCH_SIZE:+ last_team_id, last_repository = batch[-1]+ refresh_signal_repository_activity.apply_async(+ kwargs={"after_team_id": last_team_id, "after_repository": last_repository},+ countdown=_REFRESH_BATCH_INTERVAL_SECONDS,+ )diff --git a/products/signals/backend/test/test_repo_activity.py b/products/signals/backend/test/test_repo_activity.pyindex d4aac1502603..e26341e9be1e 100644--- a/products/signals/backend/test/test_repo_activity.py+++ b/products/signals/backend/test/test_repo_activity.py@@ -242,3 +242,45 @@ class TestWeeklyRefreshTask:assert enqueued == {(team.id, "acme/app"), (team.id, "acme/other")}with team_scope(team.id, canonical=True):assert not SignalRepositoryAreaActivity.objects.filter(id=idle.id).exists()++ def test_releases_repositories_in_chained_batches_without_gaps_or_repeats(self, team, organization):+ # A run larger than one batch must reach every warm repository exactly once, across+ # teams, by following the (team_id, repository) cursor its follow-up batches carry.+ now = timezone.now()+ other_team = Team.objects.create(organization=organization, name="test-repo-activity-team-2")+ expected = [+ (team.id, "acme/a"),+ (team.id, "acme/b"),+ (team.id, "acme/c"),+ (other_team.id, "z/one"),+ ]+ for owner_id, repository in expected:+ with team_scope(owner_id, canonical=True):+ SignalRepositoryAreaActivity.objects.create(+ team_id=owner_id, repository=repository, area="a/one", last_used_at=now+ )++ released: list[tuple[int, str]] = []++ def drive(**kwargs: object) -> None:+ with (+ patch("products.signals.backend.tasks._REFRESH_BATCH_SIZE", 2),+ patch("products.signals.backend.tasks.rebuild_signal_repository_activity.delay") as delay,+ patch("products.signals.backend.tasks.refresh_signal_repository_activity.apply_async") as chain,+ ):+ refresh_signal_repository_activity(**kwargs)+ released.extend((c.kwargs["team_id"], c.kwargs["repository"]) for c in delay.call_args_list)+ if chain.call_args_list:+ assert chain.call_args.kwargs["countdown"] > 0+ drive(**chain.call_args.kwargs["kwargs"])++ drive()++ assert released == expected++ def test_chain_survives_worker_restart_via_late_ack(self):+ # The batch chain holds a countdown message between batches; without late ack a worker+ # restart drops it and every repository after the cursor stays stale.+ task = refresh_signal_repository_activity+ assert task.acks_late is True+ assert task.reject_on_worker_lost is True