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.

fix(signals): smear scout fan-out across the coordinator tick (#86710)

Alessandro Pogliaghi7347a079f5d7
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index bc352c799cd8..176923845b8d 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -41,7 +41,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
The stop switch on the waste axis (the failure breaker below covers the failure axis). `sweep_inactive_scouts()` judges **consumption, not emission**: a scout counts as consumed only when a **person** acted on a report it wrote or edited in the `TOUCHED_REPORT_LOOKBACK` — a log artefact attributed to a user (pipeline writers append log artefacts of their own, so unattributed ones don't count), a `SignalReportAction` row (the light interactions the inbox UI records server-side: opening a report's detail view via the `viewed` endpoint, rating it with the thumbs via `feedback` — reading counts on purpose, since that is how digest-style reports are consumed), or the report recently reaching `resolved`/`deleted` (`resolved` deliberately includes the GitHub webhook's resolve-on-merge, so a PR merged on GitHub with no in-app action still counts; `suppressed` is deliberately excluded because the same webhook suppresses on close-unmerged with no human involved).
The two `pause_reason`s behave differently: `ignored` (the scout holds at least one report older than `ESTABLISHED_REPORT_AGE` and none of its reports show consumption) warns and then pauses after `WARNING_GRACE`; `no_output` (silent, with no judgeable report evidence) only ever warns, because a watch scout's silence can be its job. A scout with output but nothing judgeable on the report side — findings-only, Slack-routed (consumption happens in Slack where no evidence flows back), or every report younger than `ESTABLISHED_REPORT_AGE` — is left alone.
It speaks the scout lifecycle vocabulary rather than keeping fields of its own: the warning is `status=pending_pause` (still scheduled), the pause is `status=paused_by_system` (syncing `enabled=False`), both through `transition_status_by_system`. The helper's ownership rule is writer-scoped: the sweep owns both of its reasons (so it can reclassify its own warning in either direction — `no_output` becomes `ignored` when report evidence establishes, restarting the grace clock, and `ignored` downgrades to `no_output` when its evidence ages out of the lookback, so a pause never lands on stale grounds), and neither the sweep nor the failure breaker can touch the other's pauses.
- Driven by the daily `pause_inactive_signal_scouts` Celery task rather than the coordinator tick, which stays short-lived and bounded. A dry-run scout, one inside `in_cold_start_grace()`, one that has barely run (`MIN_RUNS_IN_WINDOW`), and one flagged `auto_pause_exempt` (watchdogs whose value is staying quiet) are all left alone; new warnings are capped per sweep (`MAX_WARNS_PER_SWEEP`), which also bounds later pauses, since a pause only ever follows a warning by `WARNING_GRACE`.
+ Driven by the daily `pause_inactive_signal_scouts` Celery task rather than the coordinator tick, which stays bounded. A dry-run scout, one inside `in_cold_start_grace()`, one that has barely run (`MIN_RUNS_IN_WINDOW`), and one flagged `auto_pause_exempt` (watchdogs whose value is staying quiet) are all left alone; new warnings are capped per sweep (`MAX_WARNS_PER_SWEEP`), which also bounds later pauses, since a pause only ever follows a warning by `WARNING_GRACE`.
Unlike the failure breaker there is no probe — an inactivity pause never runs again on its own. Re-enabling through the config API resumes the scout and re-anchors its grace window, so the sweep waits a full fresh `COLD_START_GRACE` and re-derives its verdict before judging it again (permanent immunity stays the explicit `auto_pause_exempt` field, never a resume side effect); that resume also emits `signals_scout_auto_pause_reverted`, the sweep's false-positive metric (the warn and pause emit `signals_scout_auto_pause_warned` / `signals_scout_auto_paused`).
- `limits.py`
Runtime ceilings as module constants: `DEFAULT_MAX_RUNTIME_S` (per-run budget), `ACTIVITY_SLACK_S`, and `WORKFLOW_HARD_CEILING_S` (`= DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow's `start_to_close_timeout`).
@@ -121,6 +121,9 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
Anchoring on the grid also returns a run deferred by a per-team cap or a missed tick to the slot it was meant to have, instead of re-anchoring wherever it happened to land.
`slot_aligned_dispatch: false` in the flag payload reverts to wall-clock stamping.
Cron scouts and breaker-paused lanes under probe keep the wall clock, because their `last_run_at` is a croniter reference and a probe cooldown clock respectively, not a schedule anchor.
+ The tick's fan-out is paced rather than emitted in one burst: planned runs are strided into batches dispatched `DISPATCH_BATCH_INTERVAL_SECONDS` apart across a `DISPATCH_SMEAR_SECONDS` window (flag-tunable via `dispatch_smear_seconds`, `0` disables), each stamped right after its own dispatch.
+ Every batch stamps with the tick's own start time, so pacing moves neither a slot anchor nor a cron reference.
+ The coordinator is therefore alive for a chunk of each tick rather than for seconds: the schedule caps its `execution_timeout` at one interval, and any later edit to `SignalsScoutCoordinatorWorkflow.run` needs a `workflow.patched()` gate for executions in flight across the deploy.
A lane paused by the failure-streak breaker (`status=paused_by_system`, `pause_reason=repeated_failures`) is excluded by the `enabled=True` dispatch filter like any other pause; the coordinator additionally dispatches one probe per `AUTO_PAUSE_PROBE_INTERVAL_S` to such lanes (`_collect_probe_runs`).
- **Models** — `SignalScoutConfig`, `SignalScoutRun`, `SignalScratchpad`, `SignalScoutNote`, `SignalProjectProfile` in `../models.py`.
- **Source variant** — `SignalSourceConfig.SourceProduct.SIGNALS_SCOUT` paired with `SourceType.CROSS_SOURCE_ISSUE`.
diff --git a/products/signals/backend/scout_harness/inactivity.py b/products/signals/backend/scout_harness/inactivity.py
index 0e7ce6f2ba81..0f27ba40058c 100644
--- a/products/signals/backend/scout_harness/inactivity.py
+++ b/products/signals/backend/scout_harness/inactivity.py
@@ -3,7 +3,7 @@
`SignalScoutConfig.enabled` only ever moves by hand, so a scout nobody is getting value from
keeps spending sandbox runs on its cadence indefinitely. This module is the missing stop: once a
day (`tasks.pause_inactive_signal_scouts`, deliberately not the 30-minute coordinator tick, which
-is kept short-lived and bounded) it decides whether each enabled scout is still earning its runs.
+is kept bounded) it decides whether each enabled scout is still earning its runs.
The sweep judges **consumption, not emission**. Emitting a report is not evidence anyone wanted
it; a scout that files report after report nobody acts on is the expensive failure mode (a full
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index 37dabdb6abee..b4811d3418d5 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -88,6 +88,9 @@ COORDINATOR_INTERVAL_MINUTES = 30
# else stamp jitter makes it skip every other tick (a 60-min scout runs every 2h).
DUE_GRACE_SECONDS = 60
+DISPATCH_SMEAR_SECONDS = 600
+DISPATCH_BATCH_INTERVAL_SECONDS = 60
+
def dispatch_ticks_per_interval(run_interval_minutes: int) -> int:
"""The scout's dispatch period, as a count of coordinator ticks.
diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.py
index c62a321107c3..bd1e91aa8766 100644
--- a/products/signals/backend/scout_harness/team_limits.py
+++ b/products/signals/backend/scout_harness/team_limits.py
@@ -323,6 +323,18 @@ def _resolve_global_max_runs_per_tick(payload: dict | None, default: int) -> int
return default
+DISPATCH_SMEAR_SECONDS_KEY = "dispatch_smear_seconds"
+
+
+def _resolve_dispatch_smear_seconds(payload: dict | None, default: int) -> int:
+ if payload is None:
+ return default
+ override = payload.get(DISPATCH_SMEAR_SECONDS_KEY)
+ if isinstance(override, int) and not isinstance(override, bool) and override >= 0:
+ return override
+ return default
+
+
# Flag payload key toggling slot-aligned dispatch anchors (the coordinator's `_slot_anchor`). On,
# a dispatched scout's `last_run_at` is stamped at its own stable slot on the tick grid, so tick
# latency stops pushing whole cohorts onto later ticks and merging them into ever larger waves.
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 6484b3f021e9..a9e099726ab6 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -545,7 +545,7 @@ def pause_inactive_signal_scouts() -> None:
"""Daily sweep: warn, then auto-pause scouts nothing comes of.
Runs here rather than on the coordinator's 30-minute tick — that tick is deliberately
- short-lived and bounded, and inactivity doesn't change by the half hour. See
+ bounded, and inactivity doesn't change by the half hour. See
`scout_harness/inactivity.py` for what counts as productive.
"""
outcome = sweep_inactive_scouts()
diff --git a/products/signals/backend/temporal/agentic/schedule.py b/products/signals/backend/temporal/agentic/schedule.py
index 26dfc038b868..a651fc72cdaa 100644
--- a/products/signals/backend/temporal/agentic/schedule.py
+++ b/products/signals/backend/temporal/agentic/schedule.py
@@ -34,8 +34,10 @@ async def create_signals_scout_coordinator_schedule(client: Client) -> None:
The coordinator runs on the existing signals task queue (currently
`VIDEO_EXPORT_TASK_QUEUE`, shared with the rest of the signals temporal worker).
`ScheduleOverlapPolicy.SKIP` is a defense-in-depth guard against pathologically
- slow ticks; the coordinator itself dispatches children fire-and-forget so its
- lifetime is normally seconds and overlap should never fire in practice.
+ slow ticks. The coordinator paces its fan-out across a smear window well under the tick,
+ and `execution_timeout` caps it at one whole interval, so a tick that somehow burns its
+ activity retry budget is killed rather than left running to starve the next tick under
+ `SKIP` — its undispatched scouts stay unstamped and re-dispatch on that next tick.
"""
schedule = Schedule(
action=ScheduleActionStartWorkflow(
@@ -43,6 +45,7 @@ async def create_signals_scout_coordinator_schedule(client: Client) -> None:
asdict(CoordinatorWorkflowInput()),
id=SIGNALS_SCOUT_COORDINATOR_SCHEDULE_ID,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
+ execution_timeout=timedelta(minutes=COORDINATOR_INTERVAL_MINUTES),
),
spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=COORDINATOR_INTERVAL_MINUTES))]),
policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index 1ada13e71fba..ab909c6a69e2 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -16,6 +16,7 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.dataclasses import frozen
from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
@@ -26,6 +27,8 @@ from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skil
from products.signals.backend.scout_harness.limits import (
AUTO_PAUSE_PROBE_INTERVAL_S,
COORDINATOR_INTERVAL_MINUTES,
+ DISPATCH_BATCH_INTERVAL_SECONDS,
+ DISPATCH_SMEAR_SECONDS,
DUE_GRACE_SECONDS,
dispatch_ticks_per_interval,
)
@@ -40,6 +43,7 @@ from products.signals.backend.scout_harness.team_limits import (
_default_team_config,
_parse_enrollment,
_read_flag_payload,
+ _resolve_dispatch_smear_seconds,
_resolve_global_max_runs_per_tick,
_resolve_max_runs_per_day,
_resolve_max_runs_per_tick,
@@ -79,16 +83,19 @@ class FetchEnabledRunsInput:
pass
-@dataclass
+@frozen
class FetchEnabledRunsOutput:
planned_runs: list[PlannedRun]
+ dispatch_smear_seconds: int = 0
-@dataclass
+@frozen
class StampDispatchedRunsInput:
- """The (team, skill) runs whose child workflow was dispatched this tick."""
+ """The (team, skill) runs whose child workflow was dispatched this tick, and the tick's own
+ start time to anchor their stamps on (`None` falls back to the wall clock)."""
dispatched_runs: list[PlannedRun]
+ dispatched_at: datetime | None = None
@dataclass
@@ -128,24 +135,27 @@ async def fetch_enabled_signals_scout_runs_activity(
# snapshot, falling back to the code constant. `MAX_RUNS_PER_TICK` is read at call time so
# tests patching the module global still take effect.
global_max_runs_per_tick = _resolve_global_max_runs_per_tick(payload, MAX_RUNS_PER_TICK)
+ smear_seconds = _resolve_dispatch_smear_seconds(payload, DISPATCH_SMEAR_SECONDS)
planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)(
enrollment, team_configs, default_team_config, global_max_runs_per_tick
)
logger.info("signals_scout coordinator: planned runs", count=len(planned))
- return FetchEnabledRunsOutput(planned_runs=planned)
+ return FetchEnabledRunsOutput(planned_runs=planned, dispatch_smear_seconds=smear_seconds)
@activity.defn
async def stamp_dispatched_signals_scout_runs_activity(
stamp_input: StampDispatchedRunsInput,
) -> None:
- """Advance `last_run_at` for the configs whose child workflow was dispatched this tick.
+ """Advance `last_run_at` for the configs whose child workflow was dispatched this batch.
Split out of planning so the schedule only advances for scouts a child was actually
launched for: if fan-out fails (or the coordinator dies) before dispatch, the config
stays unstamped and re-dispatches next tick instead of being silently suppressed for a
full interval. The trade is a rare double-run if this stamp fails after children started
— far less harmful than a day of suppression, and bounded by the activity retry policy.
+ Called once per dispatch batch, so a coordinator that dies mid-smear leaves only its
+ undispatched batches unstamped rather than the whole tick.
"""
async with Heartbeater():
# Same off-the-DB-pool read as planning: the SDK call can block on a cold cache, and
@@ -153,7 +163,7 @@ async def stamp_dispatched_signals_scout_runs_activity(
payload = await asyncio.to_thread(_read_flag_payload)
slot_aligned = _resolve_slot_aligned_dispatch(payload)
await database_sync_to_async(_stamp_dispatched_runs, thread_sensitive=False)(
- stamp_input.dispatched_runs, slot_aligned=slot_aligned
+ stamp_input.dispatched_runs, slot_aligned=slot_aligned, dispatched_at=stamp_input.dispatched_at
)
@@ -202,10 +212,16 @@ def _slot_anchor(config_pk: str, run_interval_minutes: int, dispatched_at: datet
return datetime.fromtimestamp(snapped_index * TICK_SECONDS, tz=UTC)
-def _stamp_dispatched_runs(dispatched_runs: list[PlannedRun], *, slot_aligned: bool = True) -> None:
+def _stamp_dispatched_runs(
+ dispatched_runs: list[PlannedRun], *, slot_aligned: bool = True, dispatched_at: datetime | None = None
+) -> None:
"""Sync bulk stamp. `.update()` bypasses save(), so this per-tick write never hits the
activity log.
+ `dispatched_at` is the tick's start time, not the moment this batch happens to run: a late
+ batch would otherwise floor to the next tick index (re-anchoring those scouts by a whole
+ period) and push a cron scout's croniter reference past an occurrence it should still serve.
+
Rolling-interval scouts are stamped with their slot anchor (see `_slot_anchor`). Anchors differ
per config, so they are applied through a single `CASE` expression rather than one `.update()`
per anchor: at the global tick cap a per-anchor loop would be up to `MAX_RUNS_PER_TICK`
@@ -222,7 +238,7 @@ def _stamp_dispatched_runs(dispatched_runs: list[PlannedRun], *, slot_aligned: b
"""
if not dispatched_runs:
return
- now = timezone.now()
+ now = dispatched_at or timezone.now()
predicate = Q()
for run in dispatched_runs:
predicate |= Q(team_id=run.team_id, skill_name=run.skill_name)
@@ -606,15 +622,22 @@ class SignalsScoutCoordinatorWorkflow:
"""Coordinator: scans dogfood teams, fans out per-(team, skill) child runs for due scouts.
Dispatch is fire-and-forget: each child is started with `ParentClosePolicy.ABANDON`
- so it outlives this workflow, and the coordinator returns right after the last
- `start_child_workflow` call plus one fast bookkeeping activity that advances
- `last_run_at` for the children it dispatched. This keeps the coordinator's lifetime to
- seconds regardless of how many children are dispatched, so the schedule's `SKIP` overlap
- policy never collapses ticks at scale. Temporal's task queue + worker concurrency
- handles the throttling — if workers are saturated, the children just queue.
+ so it outlives this workflow. Temporal's task queue + worker concurrency handles the
+ throttling — if workers are saturated, the children just queue.
+
+ The fan-out is paced rather than emitted in one burst: the planned runs are split into
+ batches dispatched `DISPATCH_BATCH_INTERVAL_SECONDS` apart across a `dispatch_smear_seconds`
+ window, so the fleet's runs are created over minutes instead of landing in the single minute
+ of the tick. The window is bounded well under the tick and the schedule caps the workflow's
+ execution at one tick interval, so `SKIP` still never collapses ticks; a coordinator is now
+ alive for a meaningful fraction of every tick, though, so any later edit to this method needs
+ a `workflow.patched()` gate (see `.claude/rules/temporal-workflow-versioning.md`) — this
+ change itself is gated on `FetchEnabledRunsOutput.dispatch_smear_seconds` defaulting to 0.
The schedule advances only after dispatch (not during planning) so a fan-out failure
- re-dispatches next tick rather than silently suppressing a scout for a full interval.
+ re-dispatches next tick rather than silently suppressing a scout for a full interval, and
+ is stamped per batch so a coordinator that dies mid-smear leaves only its undispatched
+ batches unstamped.
Idempotency: child workflow IDs are deterministic per `(team_id, skill_name, tick_id)`,
so a retried coordinator can't double-launch within a single tick. A separate
@@ -649,27 +672,37 @@ class SignalsScoutCoordinatorWorkflow:
# dedupe a retry without re-launching. `run_id` would break that: a retry would mint
# new child ids and double-launch.
tick_id = workflow.info().workflow_id
+ tick_started_at = workflow.info().start_time
+ smear_seconds = max(0, fetch_result.dispatch_smear_seconds)
+ smear_deadline = tick_started_at + timedelta(seconds=smear_seconds)
+ batches = _dispatch_batches(planned_runs, smear_seconds)
+
started = 0
skipped = 0
- dispatched: list[PlannedRun] = []
- for idx, planned in enumerate(planned_runs):
- if await _start_child(planned=planned, tick_id=tick_id, idx=idx):
- started += 1
- else:
- skipped += 1
- # Both branches mean a child for this (team, skill, tick) now exists (started, or
- # dedupe-skipped because a retry already started it) — so its schedule should
- # advance. A hard `start_child` error raises out of `_start_child` before reaching
- # here, leaving that config unstamped to re-dispatch next tick.
- dispatched.append(planned)
-
- # Stamp only after dispatch, so a fan-out failure can't suppress a scout for a day.
- await workflow.execute_activity(
- stamp_dispatched_signals_scout_runs_activity,
- StampDispatchedRunsInput(dispatched_runs=dispatched),
- start_to_close_timeout=timedelta(minutes=1),
- retry_policy=RetryPolicy(maximum_attempts=5),
- )
+ for batch_number, batch in enumerate(batches, start=1):
+ dispatched: list[PlannedRun] = []
+ for idx, planned in batch:
+ if await _start_child(planned=planned, tick_id=tick_id, idx=idx):
+ started += 1
+ else:
+ skipped += 1
+ # Both branches mean a child for this (team, skill, tick) now exists (started, or
+ # dedupe-skipped because a retry already started it) — so its schedule should
+ # advance. A hard `start_child` error raises out of `_start_child` before reaching
+ # here, leaving that config unstamped to re-dispatch next tick.
+ dispatched.append(planned)
+
+ # Stamp only after dispatch, so a fan-out failure can't suppress a scout for a day.
+ await workflow.execute_activity(
+ stamp_dispatched_signals_scout_runs_activity,
+ StampDispatchedRunsInput(dispatched_runs=dispatched, dispatched_at=tick_started_at),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=5),
+ )
+
+ if batch_number < len(batches) and workflow.now() < smear_deadline:
+ await workflow.sleep(timedelta(seconds=DISPATCH_BATCH_INTERVAL_SECONDS))
+
return CoordinatorWorkflowOutput(
planned_count=len(planned_runs),
started_count=started,
@@ -677,6 +710,21 @@ class SignalsScoutCoordinatorWorkflow:
)
+def _dispatch_batches(planned_runs: list[PlannedRun], smear_seconds: int) -> list[list[tuple[int, PlannedRun]]]:
+ """Split the tick's planned runs into the batches to dispatch one `DISPATCH_BATCH_INTERVAL_SECONDS`
+ apart, each entry carrying its index in the full planned list so child ids stay stable.
+
+ Strided rather than sliced contiguously: `planned_runs` is sorted by `(team_id, skill_name)`,
+ so contiguous batches would put a whole team in one batch and make how late a team dispatches
+ a permanent function of its id. A stride of 1 (`smear_seconds=0`, which is also what an
+ in-flight coordinator replaying a pre-smear history resolves to) yields today's single batch
+ in today's order.
+ """
+ indexed = list(enumerate(planned_runs))
+ num_batches = max(1, min(smear_seconds // DISPATCH_BATCH_INTERVAL_SECONDS, len(indexed)))
+ return [indexed[offset::num_batches] for offset in range(num_batches)]
+
+
async def _start_child(*, planned: PlannedRun, tick_id: str, idx: int) -> bool:
"""Fire-and-forget child dispatch. Returns True if started, False if dedupe-skipped.
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index fdab0f104b76..e589f94e96a8 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -25,7 +25,11 @@ from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.config_registry import register_missing_configs
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, sync_canonical_skills
-from products.signals.backend.scout_harness.limits import AUTO_PAUSE_PROBE_INTERVAL_S
+from products.signals.backend.scout_harness.limits import (
+ AUTO_PAUSE_PROBE_INTERVAL_S,
+ DISPATCH_BATCH_INTERVAL_SECONDS,
+ DISPATCH_SMEAR_SECONDS,
+)
# The flag-payload read + per-team cap resolution live in `scout_harness/team_limits.py`; helpers
# defined there are imported and patched there (see `_PAYLOAD_PATH` / `_IS_CLOUD_PATH`).
@@ -37,6 +41,7 @@ from products.signals.backend.scout_harness.team_limits import (
_enrolled_team_ids,
_parse_enrollment,
_read_flag_payload,
+ _resolve_dispatch_smear_seconds,
_resolve_enrolled,
_resolve_github_read_access,
_resolve_global_max_runs_per_tick,
@@ -52,12 +57,14 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (
CoordinatorWorkflowInput,
CoordinatorWorkflowOutput,
FetchEnabledRunsInput,
+ FetchEnabledRunsOutput,
PlannedRun,
SignalsScoutCoordinatorWorkflow,
StampDispatchedRunsInput,
_allocate_tick_budget,
_breaker_paused_configs_by_team,
_collect_probe_runs,
+ _dispatch_batches,
_dispatch_slot,
_DueRun,
_overdue_seconds,
@@ -74,6 +81,11 @@ _IS_CLOUD_PATH = "products.signals.backend.scout_harness.team_limits.is_cloud"
# distinguishable from one that snapped to a slot.
_DISPATCHED_AT = datetime(2026, 8, 8, 16, 31, 12, tzinfo=UTC)
+# When the tick that planned the dispatch started. Distinct from `_DISPATCHED_AT` so a stamp
+# anchored on the tick is distinguishable from one that read the clock when its batch ran, and
+# off the tick grid too so it can never coincide with a slot anchor.
+_TICK_STARTED_AT = datetime(2026, 8, 8, 16, 30, 7, tzinfo=UTC)
+
# Config ids drawn once and pinned, so slot spread and stability are asserted against fixed input
# rather than a fresh sample per run.
_SLOT_TEST_PKS = [
@@ -450,6 +462,24 @@ def test_resolve_global_max_runs_per_tick(payload, expected):
assert _resolve_global_max_runs_per_tick(payload, MAX_RUNS_PER_TICK) == expected
+# `dispatch_smear_seconds: 0` is the no-deploy kill switch for paced fan-out, so a key that
+# silently fails to resolve would leave no way to turn smearing off during an incident.
+ "payload,expected",
+ [
+ (None, DISPATCH_SMEAR_SECONDS), # no payload → code default
+ ({}, DISPATCH_SMEAR_SECONDS), # absent key → code default
+ ({"dispatch_smear_seconds": 0}, 0), # the kill switch: back to a single burst
+ ({"dispatch_smear_seconds": 300}, 300), # narrow the window
+ ({"dispatch_smear_seconds": -60}, DISPATCH_SMEAR_SECONDS), # negative → default
+ ({"dispatch_smear_seconds": "0"}, DISPATCH_SMEAR_SECONDS), # wrong type → default
+ ({"dispatch_smear_seconds": False}, DISPATCH_SMEAR_SECONDS), # bool is not a valid int here
+ ],
+)
+def test_resolve_dispatch_smear_seconds(payload, expected):
+ assert _resolve_dispatch_smear_seconds(payload, DISPATCH_SMEAR_SECONDS) == expected
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_disabled_config_is_skipped(ateam):
@@ -938,6 +968,9 @@ async def test_stamp_activity_advances_dispatched_configs_to_their_slot_anchor(a
],
)
async def test_stamp_activity_keeps_the_wall_clock_for_cron_and_probed_configs(ateam, config_kwargs):
+ # `dispatched_at` is the tick's start time, and it has to reach the write: a batch dispatched
+ # minutes into the smear would otherwise push a cron scout's croniter reference past the next
+ # occurrence, silently costing it that run.
await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")
config = await database_sync_to_async(_create_config)(
ateam, "signals-scout-foo", run_interval_minutes=1440, **config_kwargs
@@ -947,11 +980,14 @@ async def test_stamp_activity_keeps_the_wall_clock_for_cron_and_probed_configs(a
env = ActivityEnvironment()
await env.run(
stamp_dispatched_signals_scout_runs_activity,
- StampDispatchedRunsInput(dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")]),
+ StampDispatchedRunsInput(
+ dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")],
+ dispatched_at=_TICK_STARTED_AT,
+ ),
)
refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)
- assert refreshed.last_run_at == _DISPATCHED_AT
+ assert refreshed.last_run_at == _TICK_STARTED_AT
@pytest.mark.asyncio
@@ -1689,15 +1725,18 @@ async def test_payload_enrolled_unseeded_team_is_seeded_by_tick(ateam):
# dispatch counts (started vs already-running skip), not completion outcomes.
+def _fake_info(workflow_id: str = "tick-1"):
+ return type("Info", (), {"workflow_id": workflow_id, "start_time": _TICK_STARTED_AT})()
+
+
@pytest.mark.asyncio
async def test_workflow_returns_zero_counts_when_no_planned_runs():
coordinator = SignalsScoutCoordinatorWorkflow()
- fake_fetch_result = type("R", (), {"planned_runs": []})()
with patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
new_callable=AsyncMock,
- return_value=fake_fetch_result,
+ return_value=FetchEnabledRunsOutput(planned_runs=[]),
):
output = await coordinator.run(CoordinatorWorkflowInput())
@@ -1706,12 +1745,15 @@ async def test_workflow_returns_zero_counts_when_no_planned_runs():
@pytest.mark.asyncio
async def test_workflow_dispatches_children_fire_and_forget():
+ # `dispatch_smear_seconds` left at its default, which is also what an in-flight coordinator
+ # replaying a pre-smear history decodes it to: one batch, one stamp, no timers, original
+ # order. That default is the whole replay gate — a non-zero one would fail those replays,
+ # and a wedged coordinator starves every later tick under `ScheduleOverlapPolicy.SKIP`.
planned = [
PlannedRun(team_id=1, skill_name="signals-scout-a"),
PlannedRun(team_id=1, skill_name="signals-scout-b"),
PlannedRun(team_id=2, skill_name="signals-scout-c"),
]
- fake_fetch_result = type("R", (), {"planned_runs": planned})()
# Second dispatch raises WorkflowAlreadyStartedError → counted as skipped, others as started.
dispatch_outcomes: list[BaseException | None] = [
@@ -1720,6 +1762,7 @@ async def test_workflow_dispatches_children_fire_and_forget():
None,
]
dispatch_calls: list[tuple[int, str]] = []
+ stamp_calls: list[StampDispatchedRunsInput] = []
async def fake_start_child(_workflow_run, run_input, **kwargs):
idx = len(dispatch_calls)
@@ -1729,16 +1772,21 @@ async def test_workflow_dispatches_children_fire_and_forget():
raise outcome
return AsyncMock()
+ async def fake_execute_activity(activity, activity_input, **kwargs):
+ if activity is stamp_dispatched_signals_scout_runs_activity:
+ stamp_calls.append(activity_input)
+ return None
+ return FetchEnabledRunsOutput(planned_runs=planned)
+
coordinator = SignalsScoutCoordinatorWorkflow()
with (
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
- new_callable=AsyncMock,
- return_value=fake_fetch_result,
+ side_effect=fake_execute_activity,
),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.info",
- return_value=type("Info", (), {"workflow_id": "tick-1"})(),
+ return_value=_fake_info(),
),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.logger",
@@ -1747,6 +1795,10 @@ async def test_workflow_dispatches_children_fire_and_forget():
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.start_child_workflow",
side_effect=fake_start_child,
),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.sleep",
+ new_callable=AsyncMock,
+ ) as sleep_mock,
):
output = await coordinator.run(CoordinatorWorkflowInput())
@@ -1758,6 +1810,132 @@ async def test_workflow_dispatches_children_fire_and_forget():
(1, "signals-scout-b"),
(2, "signals-scout-c"),
]
+ sleep_mock.assert_not_awaited()
+ assert [call.dispatched_runs for call in stamp_calls] == [planned]
+
+
+async def test_smeared_fan_out_paces_batches_and_stamps_each_one():
+ # Catches the fan-out reverting to a single burst, a batching bug dropping or double-dispatching
+ # a scout, and a batch left unstamped before the coordinator sleeps — the last one re-runs those
+ # scouts next tick, which is the crash window per-batch stamping exists to keep small.
+ planned = [PlannedRun(team_id=team_id, skill_name=f"signals-scout-{team_id}") for team_id in range(9)]
+ smear_seconds = 3 * DISPATCH_BATCH_INTERVAL_SECONDS
+
+ events: list[tuple[str, Any]] = []
+
+ async def fake_start_child(_workflow_run, run_input, **kwargs):
+ events.append(("start", run_input.team_id))
+ return AsyncMock()
+
+ async def fake_execute_activity(activity, activity_input, **kwargs):
+ if activity is stamp_dispatched_signals_scout_runs_activity:
+ events.append(("stamp", activity_input))
+ return None
+ return FetchEnabledRunsOutput(planned_runs=planned, dispatch_smear_seconds=smear_seconds)
+
+ async def fake_sleep(duration):
+ events.append(("sleep", duration))
+
+ coordinator = SignalsScoutCoordinatorWorkflow()
+ with (
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
+ side_effect=fake_execute_activity,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.info",
+ return_value=_fake_info(),
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.now",
+ return_value=_TICK_STARTED_AT,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.start_child_workflow",
+ side_effect=fake_start_child,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.sleep",
+ side_effect=fake_sleep,
+ ),
+ ):
+ output = await coordinator.run(CoordinatorWorkflowInput())
+
+ assert output == CoordinatorWorkflowOutput(planned_count=9, started_count=9, skipped_count=0)
+
+ stamps = [payload for kind, payload in events if kind == "stamp"]
+ assert len(stamps) == 3
+ # Every planned run dispatched exactly once, and every dispatched run stamped.
+ assert sorted(run.team_id for stamp in stamps for run in stamp.dispatched_runs) == list(range(9))
+ assert [kind for kind, _ in events].count("start") == 9
+ # The tick's own start time, not the moment each batch ran: a batch stamped minutes late
+ # would re-anchor its scouts and could skip a cron scout's next occurrence.
+ assert {stamp.dispatched_at for stamp in stamps} == {_TICK_STARTED_AT}
+
+ kinds = [kind for kind, _ in events]
+ assert kinds.count("sleep") == 2, "a sleep between batches, and none after the last"
+ # Each batch is fully stamped before the coordinator sleeps on it.
+ for index, kind in enumerate(kinds):
+ if kind == "sleep":
+ assert kinds[index - 1] == "stamp"
+
+
+async def test_smeared_fan_out_stops_sleeping_once_the_window_is_spent():
+ # A tick that burns its window on slow activities must dispatch the remainder back to back
+ # rather than run past the tick, where `ScheduleOverlapPolicy.SKIP` would drop the next one.
+ planned = [PlannedRun(team_id=team_id, skill_name=f"signals-scout-{team_id}") for team_id in range(9)]
+ smear_seconds = 3 * DISPATCH_BATCH_INTERVAL_SECONDS
+ sleeps: list[timedelta] = []
+
+ async def fake_execute_activity(activity, activity_input, **kwargs):
+ if activity is stamp_dispatched_signals_scout_runs_activity:
+ return None
+ return FetchEnabledRunsOutput(planned_runs=planned, dispatch_smear_seconds=smear_seconds)
+
+ coordinator = SignalsScoutCoordinatorWorkflow()
+ with (
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
+ side_effect=fake_execute_activity,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.info",
+ return_value=_fake_info(),
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.now",
+ return_value=_TICK_STARTED_AT + timedelta(seconds=smear_seconds),
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.start_child_workflow",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.sleep",
+ side_effect=lambda duration: sleeps.append(duration),
+ ),
+ ):
+ output = await coordinator.run(CoordinatorWorkflowInput())
+
+ assert output.started_count == 9
+ assert sleeps == []
+
+
+ [
+ ("no smear collapses to one batch in planned order", 0, [[0, 1, 2, 3, 4]]),
+ ("strided so one team is never confined to one batch", 120, [[0, 2, 4], [1, 3]]),
+ ("fewer runs than batches never stretches", 600, [[0], [1], [2], [3], [4]]),
+ ]
+)
+def test_dispatch_batches(_name, smear_seconds, expected_indices):
+ planned = [PlannedRun(team_id=team_id, skill_name="signals-scout-a") for team_id in range(5)]
+
+ batches = _dispatch_batches(planned, smear_seconds)
+
+ assert [[idx for idx, _ in batch] for batch in batches] == expected_indices
@pytest.mark.asyncio
@@ -1765,12 +1943,11 @@ async def test_hard_dispatch_error_does_not_stamp():
# A non-dedupe start_child error must abort before the stamp activity, so the affected
# configs stay unstamped and re-dispatch next tick instead of being suppressed.
planned = [PlannedRun(team_id=1, skill_name="signals-scout-a")]
- fake_fetch_result = type("R", (), {"planned_runs": planned})()
execute_activity_calls: list[Any] = []
async def fake_execute_activity(activity, *args, **kwargs):
execute_activity_calls.append(activity)
- return fake_fetch_result
+ return FetchEnabledRunsOutput(planned_runs=planned)
async def fake_start_child(_workflow_run, run_input, **kwargs):
raise RuntimeError("temporal unavailable")
@@ -1783,7 +1960,7 @@ async def test_hard_dispatch_error_does_not_stamp():
),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.info",
- return_value=type("Info", (), {"workflow_id": "tick-1"})(),
+ return_value=_fake_info(),
),
patch(
"products.signals.backend.temporal.agentic.scout_coordinator.workflow.start_child_workflow",