: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): spread scout run starts with a per-config delay in the child (#116574)
posthog[bot]179dd008c97b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex f13969ff56e6..a52975447c29 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11575,9 +11575,9 @@ snapshots:scenes-app-inbox-scoutconfigform--structured-output--light:hash: v1.k794b7964.8fd03bb1e0bcf6bfd12d4e1998b5c748a628d77305ed3ecd4f65c06dfb912859.47heuQ1PD7usF5OCbISOMs8eLB0VYyCdqi4LsN8OUb4scenes-app-inbox-scoutconfigform--weekly-schedule--dark:- hash: v1.k794b7964.19a81863734b43a19a43c3377dfcaaefdc267077a1a047305d99d81a693a5c7f.Lxu9-YhxbDgAogm9XF5HAxAE8gbU8obJT6GmnW70Yys+ hash: v1.k794b7964.aa7da945516a905ecf22b1032b498239a19af44e75b3c476417096c620952730.lUIjdBY7-uy4Oiuhvn1aBXxW_qjoliRsX0Kj1yQd6aYscenes-app-inbox-scoutconfigform--weekly-schedule--light:- hash: v1.k794b7964.df6a52c606df65aff4b0739de4647dea8f2d85ca10c2809eb623c0bde7dcf3aa.HIt7xQ0EWAkyBron_PV0TJUam5y6sO0_oF07KM0lnTQ+ hash: v1.k794b7964.504737de87284126ec0dc3dc0ec444f6a2637aa6caf79659061e904ff6be2be3.rlZQm2FDzS0j_cYW8xKRw6DgnBmxX2-WQiBETvCl5qcscenes-app-inbox-scoutdetailview--scout-page--dark:hash: v1.k794b7964.7994cd307f5adb384df6008caa4d535248e8e10ba5505840e7b2661704cfa054.HD73lbCqzK0mXr4mcQ7lZJdj5J5aGTd_5LtbP3TDbLUscenes-app-inbox-scoutdetailview--scout-page--light:diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 4685ef3f3be4..6e54180684eb 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -178,6 +178,7 @@ class TestSignalsProductModuleIntegrity:"stamp_dispatched_signals_scout_runs_activity","run_due_signal_report_checks_activity","evaluate_signals_scout_precheck_activity",+ "check_signals_scout_config_runnable_activity","run_signals_scout_activity","cancel_failed_scout_trial_activity","load_scout_trial_evaluation_activity",diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex fdad165bd259..07bf5ed1bf68 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -191,6 +191,10 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eThe 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.+ `child_start_delay: true` in the flag payload moves the spread into each child: the coordinator starts every child of the tick at once (in chunks of `CHILD_START_CHUNK_SIZE`), stamps them in one call, and exits, and each child sleeps a stable per-config delay (`_start_delay_seconds`, a digest fraction of the smear) before its pre-check.+ A cron scout's delay is capped at `CRON_START_DELAY_CAP_SECONDS`, a config with no previous run gets none, and a child checks its config again after the sleep and skips with `config_disabled` when it is gone or disabled.+ With the key on, the tick cap stays under `CHILD_START_DELAY_MAX_RUNS_PER_TICK`, because Temporal limits the pending children of one workflow.+ Workflow durations then include the sleep, so read the start rate from `signals_scout_run_started`, not from the dispatch counters.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/limits.py b/products/signals/backend/scout_harness/limits.pyindex 87e7140bb15e..11dfa0c1849b 100644--- a/products/signals/backend/scout_harness/limits.py+++ b/products/signals/backend/scout_harness/limits.py@@ -129,6 +129,16 @@ DUE_GRACE_SECONDS = 60DISPATCH_SMEAR_SECONDS = 600DISPATCH_BATCH_INTERVAL_SECONDS = 60+# The smear stays this far under one tick, so the runs of one tick never start in the next tick.+# This is also below the shortest scout interval.+MAX_DISPATCH_SMEAR_SECONDS = COORDINATOR_INTERVAL_MINUTES * 60 - 180+# A cron scout starts at most this long after its cron time, whatever the smear is.+CRON_START_DELAY_CAP_SECONDS = 20 * 60+# With child start delays, the coordinator starts every child of the tick before it closes. Temporal+# limits the pending child executions of one workflow (2,000 by default), so the tick cap stays under it.+CHILD_START_DELAY_MAX_RUNS_PER_TICK = 1500+# The coordinator starts children in groups of this size, so each workflow task stays small.+CHILD_START_CHUNK_SIZE = 200def dispatch_ticks_per_interval(run_interval_minutes: int) -> int:diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex 93719c86dfd9..c0ad568b022e 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -28,7 +28,11 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom products.signals.backend.models import SignalScoutRun-from products.signals.backend.scout_harness.limits import COORDINATOR_INTERVAL_MINUTES, MAX_ENABLED_SCOUTS_PER_TEAM+from products.signals.backend.scout_harness.limits import (+ COORDINATOR_INTERVAL_MINUTES,+ MAX_DISPATCH_SMEAR_SECONDS,+ MAX_ENABLED_SCOUTS_PER_TEAM,+)logger = structlog.get_logger(__name__)@@ -609,12 +613,28 @@ DISPATCH_SMEAR_SECONDS_KEY = "dispatch_smear_seconds"def _resolve_dispatch_smear_seconds(payload: dict | None, default: int) -> int:+ """The smear window from the flag, else `default`, capped at `MAX_DISPATCH_SMEAR_SECONDS`.++ The cap keeps the runs of one tick out of the next tick.+ """if payload is None:- return default+ return min(default, MAX_DISPATCH_SMEAR_SECONDS)override = payload.get(DISPATCH_SMEAR_SECONDS_KEY)if isinstance(override, int) and not isinstance(override, bool) and override >= 0:- return override- return default+ return min(override, MAX_DISPATCH_SMEAR_SECONDS)+ return min(default, MAX_DISPATCH_SMEAR_SECONDS)+++# Flag payload key that moves the smear from the coordinator into each child. On, the coordinator+# starts every child of the tick at once, and each child sleeps a stable per-config delay inside the+# smear window before it starts work. Off, the coordinator dispatches in paced batches. Absent or+# malformed → off.+CHILD_START_DELAY_KEY = "child_start_delay"+++def _resolve_child_start_delay(payload: dict | None) -> bool:+ """Whether children carry their own start delay. Only a literal `true` turns it on."""+ return payload is not None and payload.get(CHILD_START_DELAY_KEY) is True# Flag payload key toggling slot-aligned dispatch anchors (the coordinator's `_slot_anchor`). On,diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex 3f470f29a131..dd257bfc4c71 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -14,6 +14,7 @@ from products.signals.backend.temporal.agentic.scout_rubrics import (from products.signals.backend.temporal.agentic.scout_scheduler import (RunSignalsScoutWorkflow,cancel_failed_scout_trial_activity,+ check_signals_scout_config_runnable_activity,evaluate_signals_scout_precheck_activity,resume_signals_scout_workflow_step,run_signals_scout_activity,@@ -192,6 +193,7 @@ ACTIVITIES = [run_signal_semantic_search_activity,run_signals_scout_activity,evaluate_signals_scout_precheck_activity,+ check_signals_scout_config_runnable_activity,cancel_failed_scout_trial_activity,plan_scout_suggestion_runs_activity,resume_signals_scout_workflow_step,diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 80b29c0bf839..4cc9d75295cd 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -52,7 +52,10 @@ from products.signals.backend.scout_harness.lazy_seed import ()from products.signals.backend.scout_harness.limits import (AUTO_PAUSE_PROBE_INTERVAL_S,+ CHILD_START_CHUNK_SIZE,+ CHILD_START_DELAY_MAX_RUNS_PER_TICK,COORDINATOR_INTERVAL_MINUTES,+ CRON_START_DELAY_CAP_SECONDS,DISPATCH_BATCH_INTERVAL_SECONDS,DISPATCH_SMEAR_SECONDS,DUE_GRACE_SECONDS,@@ -73,6 +76,7 @@ from products.signals.backend.scout_harness.team_limits import (_parse_background,_parse_enrollment,_read_flag_payload,+ _resolve_child_start_delay,_resolve_dispatch_smear_seconds,_resolve_global_max_runs_per_tick,_resolve_max_runs_per_day,@@ -111,12 +115,14 @@ BACKGROUND_TICK_EVENT = "signals_scout_background_tick"BACKGROUND_TICK_DISTINCT_ID = "internal_signals_scout_coordinator"-@dataclass+@dataclass(frozen=True)class PlannedRun:"""One unit of fan-out: a single (team, skill) pair the coordinator will trigger."""team_id: intskill_name: str+ # How long the child sleeps before it starts work. See `_start_delay_seconds`.+ start_delay_seconds: int = 0@dataclass@@ -130,6 +136,8 @@ class FetchEnabledRunsInput:class FetchEnabledRunsOutput:planned_runs: list[PlannedRun]dispatch_smear_seconds: int = 0+ # On, the coordinator starts every child at once and each child sleeps its own start delay.+ child_start_delay: bool = False@frozen@@ -220,12 +228,24 @@ async def fetch_enabled_signals_scout_runs_activity(# 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)+ child_start_delay = _resolve_child_start_delay(payload)+ if child_start_delay:+ # Every child of the tick is pending while the coordinator starts them, and Temporal+ # limits the pending children of one workflow.+ global_max_runs_per_tick = min(global_max_runs_per_tick, CHILD_START_DELAY_MAX_RUNS_PER_TICK)planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)(- enrollment, team_configs, default_team_config, global_max_runs_per_tick, background+ enrollment,+ team_configs,+ default_team_config,+ global_max_runs_per_tick,+ background,+ start_delay_spread_seconds=smear_seconds if child_start_delay else 0,)logger.info("signals_scout coordinator: planned runs", count=len(planned))increment_coordinator_tick(len(planned))- return FetchEnabledRunsOutput(planned_runs=planned, dispatch_smear_seconds=smear_seconds)+ return FetchEnabledRunsOutput(+ planned_runs=planned, dispatch_smear_seconds=smear_seconds, child_start_delay=child_start_delay+ )@activity.defn@@ -272,6 +292,31 @@ def _dispatch_slot(config_pk: str, run_interval_minutes: int) -> int:return int.from_bytes(digest[:8], "big") % ticks_per_interval+def _start_delay_seconds(config_pk: str, spread_seconds: int) -> int:+ """The config's stable start delay inside a spread window of `spread_seconds`.++ A fraction of the spread rather than a modulo, so a spread change scales every offset in+ proportion: no offset moves by more than the change, and the order of scouts stays the same.+ The salt keeps the offset independent of the slot from `_dispatch_slot`.+ """+ digest = hashlib.sha256(f"{config_pk}:start-delay".encode(), usedforsecurity=False).digest()+ fraction = int.from_bytes(digest[:8], "big") / 2**64+ return int(fraction * max(0, spread_seconds))+++def _config_start_delay_seconds(config: SignalScoutConfig, spread_seconds: int) -> int:+ """The start delay for one scheduled run of `config`.++ A config with no previous run starts at once, so the first result of a new scout is not held+ back. A cron scout uses a smaller spread, so it starts soon after its cron time.+ """+ if spread_seconds <= 0 or config.last_run_at is None:+ return 0+ if config.run_cron_schedule:+ spread_seconds = min(spread_seconds, CRON_START_DELAY_CAP_SECONDS)+ return _start_delay_seconds(str(config.pk), spread_seconds)++def _slot_anchor(config_pk: str, run_interval_minutes: int, dispatched_at: datetime) -> datetime:"""The schedule anchor to stamp: the config's own slot, at or before this tick.@@ -479,12 +524,13 @@ def _engaged_team_ids(since_by_team: dict[int, datetime]) -> set[int]:return {team_id for team_id, engaged_at in latest.items() if engaged_at > since_by_team[team_id]}-@dataclass+@dataclass(frozen=True)class _DueRun:overdue_s: floatconfig_pk: strteam_id: intskill_name: str+ start_delay_s: int = 0@dataclass(frozen=True)@@ -503,6 +549,7 @@ def _collect_planned_runs(default_team_config: dict | None = None,max_runs_per_tick: int | None = None,background: BackgroundEnrollment | None = None,+ start_delay_spread_seconds: int = 0,) -> list[PlannedRun]:"""Sync DB scan. Runs in a worker thread via Django's per-thread connection mgmt.@@ -512,6 +559,9 @@ def _collect_planned_runs(Background configs are dispatched only through `_collect_background_runs`, never through theparticipating-team loop, so the consent check and the background kill switch gate every one.++ `start_delay_spread_seconds` is the window the start delays of the planned runs spread across.+ 0 gives every run no delay."""now = timezone.now()team_configs = _canonicalize_team_config_keys(team_configs or {})@@ -601,7 +651,15 @@ def _collect_planned_runs(overdue_s = _overdue_seconds(config, now, team.timezone_info)if overdue_s is None:continue- due.append(_DueRun(overdue_s, str(config.pk), team.id, config.skill_name))+ due.append(+ _DueRun(+ overdue_s,+ str(config.pk),+ team.id,+ config.skill_name,+ _config_start_delay_seconds(config, start_delay_spread_seconds),+ )+ )due.extend(_collect_probe_runs(paused_by_team.get(team.id, []), live_skills, now))if skipped_without_consent:@@ -614,7 +672,12 @@ def _collect_planned_runs(runs_last_24h: int | None = Noneif background is not None and background.enabled:background_due = _collect_background_runs(- background, background_team_ids, team_configs, default_team_config, now+ background,+ background_team_ids,+ team_configs,+ default_team_config,+ now,+ start_delay_spread_seconds=start_delay_spread_seconds,)admitted = [d.run for d in background_due]if background.budget is not None and background_due:@@ -635,7 +698,9 @@ def _collect_planned_runs(selected = _allocate_tick_budget(due, team_configs, default_team_config, runs_today, max_runs_per_tick)if background is not None and background.enabled:_capture_background_tick(background_due, selected, background.budget, runs_last_24h)- planned = [PlannedRun(team_id=d.team_id, skill_name=d.skill_name) for d in selected]+ planned = [+ PlannedRun(team_id=d.team_id, skill_name=d.skill_name, start_delay_seconds=d.start_delay_s) for d in selected+ ]# Stable order for predictable child-workflow ids within the tick.planned.sort(key=lambda p: (p.team_id, p.skill_name))return planned@@ -1171,6 +1236,8 @@ def _collect_background_runs(team_configs: dict[int, dict],default_team_config: dict,now: datetime,+ *,+ start_delay_spread_seconds: int = 0,) -> list[_BackgroundDueRun]:"""Due runs for background configs on listed teams whose organization approved AI data processing.@@ -1229,7 +1296,19 @@ def _collect_background_runs(config.run_interval_minutes, config.background_backoff_level)overdue_s = _overdue_seconds(config, now, config.team.timezone_info, interval_minutes=interval_minutes)- runs = [] if overdue_s is None else [_DueRun(overdue_s, str(config.pk), config.team_id, config.skill_name)]+ runs = (+ []+ if overdue_s is None+ else [+ _DueRun(+ overdue_s,+ str(config.pk),+ config.team_id,+ config.skill_name,+ _config_start_delay_seconds(config, start_delay_spread_seconds),+ )+ ]+ )for run in runs:due.append(_BackgroundDueRun(@@ -1309,6 +1388,11 @@ class SignalsScoutCoordinatorWorkflow:a `workflow.patched()` gate (see `.claude/rules/temporal-workflow-versioning.md`) — thischange itself is gated on `FetchEnabledRunsOutput.dispatch_smear_seconds` defaulting to 0.+ With `child_start_delay` on in the flag payload, the coordinator instead starts every child at+ once and exits. Each child sleeps its own stable start delay (`_start_delay_seconds`), so the+ spread no longer depends on this workflow's sleep loop. Remove the batch loop only after that+ path has been on everywhere for longer than one coordinator execution.+The schedule advances only after dispatch (not during planning) so a fan-out failurere-dispatches next tick rather than silently suppressing a scout for a full interval, andis stamped per batch so a coordinator that dies mid-smear leaves only its undispatched@@ -1356,6 +1440,9 @@ class SignalsScoutCoordinatorWorkflow:# new child ids and double-launch.tick_id = workflow.info().workflow_idtick_started_at = workflow.info().start_time+ if workflow.patched("scout-child-start-delay") and fetch_result.child_start_delay:+ return await _dispatch_with_child_start_delays(planned_runs, tick_id, tick_started_at)+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)@@ -1403,6 +1490,54 @@ class SignalsScoutCoordinatorWorkflow:)+async def _dispatch_with_child_start_delays(+ planned_runs: list[PlannedRun], tick_id: str, tick_started_at: datetime+) -> CoordinatorWorkflowOutput:+ """Start every planned child at once, stamp them, and return.++ Each child sleeps its own `start_delay_seconds` before it starts work, so the spread no longer+ depends on how long this workflow stays alive. Children start in chunks, so each workflow task+ stays small. A hard start error does not stop the other starts: every child that started is+ stamped first, and then the error is raised.+ """+ indexed = list(enumerate(planned_runs))+ dispatched: list[PlannedRun] = []+ started = 0+ skipped = 0+ errors: list[BaseException] = []+ for offset in range(0, len(indexed), CHILD_START_CHUNK_SIZE):+ chunk = indexed[offset : offset + CHILD_START_CHUNK_SIZE]+ outcomes = await asyncio.gather(+ *(_start_child(planned=planned, tick_id=tick_id, idx=idx) for idx, planned in chunk),+ return_exceptions=True,+ )+ for (_, planned), outcome in zip(chunk, outcomes):+ if isinstance(outcome, BaseException):+ errors.append(outcome)+ continue+ if outcome:+ started += 1+ else:+ skipped += 1+ dispatched.append(planned)++ if dispatched:+ await workflow.execute_activity(+ stamp_dispatched_signals_scout_runs_activity,+ StampDispatchedRunsInput(+ dispatched_runs=dispatched,+ dispatched_at=tick_started_at,+ started_count=started,+ deduped_count=skipped,+ ),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=5),+ )+ if errors:+ raise errors[0]+ return CoordinatorWorkflowOutput(planned_count=len(planned_runs), started_count=started, skipped_count=skipped)++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.@@ -1436,6 +1571,7 @@ async def _start_child(*, planned: PlannedRun, tick_id: str, idx: int) -> bool:RunSignalsScoutInput(team_id=planned.team_id,skill_name=planned.skill_name,+ start_delay_seconds=planned.start_delay_seconds,),id=child_id,id_reuse_policy=WorkflowIDReusePolicy.REJECT_DUPLICATE,diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.pyindex 1e5ef9d77de5..2fe2d91533ea 100644--- a/products/signals/backend/temporal/agentic/scout_scheduler.py+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, castfrom django.conf import settingsfrom django.db import InterfaceError, OperationalError+from django.db.models import Qimport structlogimport temporalio@@ -25,6 +26,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.cdp.backend.workflow_step_resume import WorkflowStepResumeStatus, emit_workflow_step_resumefrom products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate+from products.signals.backend.models import SignalScoutConfigfrom products.signals.backend.quota import (capture_signal_report_quota_paused,notify_scout_quota_paused,@@ -75,6 +77,9 @@ class RunSignalsScoutInput:precheck_rows: str | None = None# Which pre-check started the run (`config` or `skill_default`), stamped on the run row.precheck_query_source: str | None = None+ # Seconds a coordinator dispatch sleeps before it starts work, to spread the run starts of one+ # tick. 0 for every other trigger, so those runs start at once.+ start_delay_seconds: int = 0@frozen@@ -149,6 +154,35 @@ async def evaluate_signals_scout_precheck_activity(input: RunSignalsScoutInput))+def _scout_config_runnable(team_id: int, skill_name: str) -> bool:+ """Whether the coordinator would still dispatch this scout: enabled, or paused by the failure+ breaker, which the coordinator probes."""+ return (+ SignalScoutConfig.objects.for_team(team_id)+ .filter(skill_name=skill_name)+ .filter(+ Q(enabled=True)+ | Q(+ status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,+ pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,+ )+ )+ .exists()+ )+++@close_db_connections+async def check_signals_scout_config_runnable_activity(input: RunSignalsScoutInput) -> bool:+ """Check the config again after the start delay. A person can disable or delete it while the child sleeps."""+ runnable = await database_sync_to_async(_scout_config_runnable, thread_sensitive=False)(+ input.team_id, input.skill_name+ )+ if not runnable:+ metrics.increment_scout_run("config_disabled")+ return runnable++@temporalio.activity.defn@close_db_connectionsasync def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsScoutOutput:@@ -324,6 +358,17 @@ class RunSignalsScoutWorkflow:managed_resume = bool(input.workflow_origin_key) and temporalio.workflow.patched("scout-workflow-step-resume")if managed_resume:input = replace(input, workflow_managed_resume=True)+ if temporalio.workflow.patched("scout-start-delay") and input.start_delay_seconds > 0:+ if not await self._sleep_start_delay(input):+ return RunSignalsScoutOutput(+ run_id=None,+ task_run_id=None,+ status=None,+ runtime_s=0.0,+ skill_name=input.skill_name,+ skill_version=input.skill_version or 0,+ skip_reason="config_disabled",+ )if input.triggered_by == TRIGGERED_BY_SCHEDULE and temporalio.workflow.patched("scout-precheck"):precheck = await self._evaluate_precheck(input)if not precheck.should_run:@@ -384,6 +429,21 @@ class RunSignalsScoutWorkflow:await self._resume_step(input, output)return output+ async def _sleep_start_delay(self, input: RunSignalsScoutInput) -> bool:+ """Sleep the start delay, then return whether the config can still run.++ The wake time goes on the memo, so a sleeping child does not look stuck in the Temporal UI.+ """+ delay = timedelta(seconds=input.start_delay_seconds)+ temporalio.workflow.upsert_memo({"scout_starts_at": (temporalio.workflow.now() + delay).isoformat()})+ await temporalio.workflow.sleep(delay, summary="Spread the scout run starts of one tick")+ return await temporalio.workflow.execute_activity(+ check_signals_scout_config_runnable_activity,+ input,+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+async def _evaluate_precheck(self, input: RunSignalsScoutInput) -> EvaluateScoutPrecheckOutput:try:return await temporalio.workflow.execute_activity(diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex be8a59ad49b4..7384cb806cc4 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -35,8 +35,11 @@ from products.signals.backend.scout_harness.config_registry import register_missfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, sync_canonical_skillsfrom products.signals.backend.scout_harness.limits import (AUTO_PAUSE_PROBE_INTERVAL_S,+ CHILD_START_CHUNK_SIZE,+ CRON_START_DELAY_CAP_SECONDS,DISPATCH_BATCH_INTERVAL_SECONDS,DISPATCH_SMEAR_SECONDS,+ MAX_DISPATCH_SMEAR_SECONDS,MAX_ENABLED_SCOUTS_PER_TEAM,)@@ -84,12 +87,14 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (_breaker_paused_configs_by_team,_collect_planned_runs,_collect_probe_runs,+ _config_start_delay_seconds,_dispatch_batches,_dispatch_slot,_DueRun,_overdue_seconds,_slot_anchor,_stamp_dispatched_runs,+ _start_delay_seconds,fetch_enabled_signals_scout_runs_activity,run_due_signal_report_checks_activity,stamp_dispatched_signals_scout_runs_activity,@@ -497,6 +502,8 @@ def test_resolve_global_max_runs_per_tick(payload, expected):({"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+ # A window as long as the tick would start this tick's runs in the next one.+ ({"dispatch_smear_seconds": 1800}, MAX_DISPATCH_SMEAR_SECONDS),],)def test_resolve_dispatch_smear_seconds(payload, expected):@@ -2997,3 +3004,106 @@ async def test_hard_dispatch_error_does_not_stamp():run_due_signal_report_checks_activity,fetch_enabled_signals_scout_runs_activity,]+++def test_start_delay_is_stable_bounded_and_scales_with_the_spread():+ pks = [f"00000000-0000-4000-8000-{index:012d}" for index in range(2000)]+ spread = 1500++ delays = [_start_delay_seconds(pk, spread) for pk in pks]++ assert delays == [_start_delay_seconds(pk, spread) for pk in pks]+ assert all(0 <= delay < spread for delay in delays)+ # Roughly uniform: no minute of the window holds a burst.+ per_minute = [0] * (spread // 60)+ for delay in delays:+ per_minute[delay // 60] += 1+ assert max(per_minute) < 3 * len(pks) / len(per_minute)++ # A spread change keeps the order of scouts and moves none by more than the change.+ wider = [_start_delay_seconds(pk, spread + 300) for pk in pks]+ in_old_order = [after for _, after in sorted(zip(delays, wider))]+ assert in_old_order == sorted(in_old_order)+ assert all(0 <= after - before <= 300 for before, after in zip(delays, wider))+++ [+ ("interval scout spreads over the whole window", None, _TICK_STARTED_AT, 1500, 1500),+ ("cron scout spreads over its smaller cap", "0 9 * * *", _TICK_STARTED_AT, 1500, CRON_START_DELAY_CAP_SECONDS),+ ("first run starts at once", None, None, 1500, 0),+ ("no spread starts at once", None, _TICK_STARTED_AT, 0, 0),+ ]+)+def test_config_start_delay_seconds(_name, cron, last_run_at, spread, expected_cap):+ config = SignalScoutConfig(+ pk=_SLOT_TEST_PKS[0], skill_name="signals-scout-a", run_cron_schedule=cron, last_run_at=last_run_at+ )++ delay = _config_start_delay_seconds(config, spread)++ assert delay == _start_delay_seconds(_SLOT_TEST_PKS[0], expected_cap)++[email protected]("fail_team_id", [None, 3])+async def test_child_start_delay_starts_every_child_at_once_and_stamps_them(fail_team_id):+ # Catches the coordinator falling back to the paced loop when the flag is on, a child started+ # without its delay, and a hard start error leaving the children that did start unstamped,+ # which would dispatch them again next tick while they still sleep.+ planned = [+ PlannedRun(team_id=team_id, skill_name=f"signals-scout-{team_id}", start_delay_seconds=team_id * 60)+ for team_id in range(CHILD_START_CHUNK_SIZE + 5)+ ]+ started_inputs: list[Any] = []+ stamps: list[StampDispatchedRunsInput] = []++ async def fake_start_child(_workflow_run, run_input, **kwargs):+ if run_input.team_id == fail_team_id:+ raise RuntimeError("start failed")+ started_inputs.append(run_input)+ return AsyncMock()++ async def fake_execute_activity(activity, activity_input, **kwargs):+ if activity is stamp_dispatched_signals_scout_runs_activity:+ stamps.append(activity_input)+ return None+ return FetchEnabledRunsOutput(planned_runs=planned, dispatch_smear_seconds=600, child_start_delay=True)++ coordinator = SignalsScoutCoordinatorWorkflow()+ with (+ _patch_check_gate(),+ 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.start_child_workflow",+ side_effect=fake_start_child,+ ),+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.sleep",+ new_callable=AsyncMock,+ ) as sleep_mock,+ ):+ if fail_team_id is None:+ output = await coordinator.run(CoordinatorWorkflowInput())+ assert output == CoordinatorWorkflowOutput(+ planned_count=len(planned), started_count=len(planned), skipped_count=0+ )+ else:+ with pytest.raises(RuntimeError):+ await coordinator.run(CoordinatorWorkflowInput())++ sleep_mock.assert_not_awaited()+ expected = [run for run in planned if run.team_id != fail_team_id]+ assert {(i.team_id, i.start_delay_seconds) for i in started_inputs} == {+ (run.team_id, run.start_delay_seconds) for run in expected+ }+ assert len(stamps) == 1+ assert stamps[0].dispatched_runs == expected+ assert stamps[0].dispatched_at == _TICK_STARTED_ATdiff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 739972a538a9..d06d983adc5c 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -109,6 +109,7 @@ from products.signals.backend.temporal.agentic.scout_scheduler import (RunSignalsScoutOutput,RunSignalsScoutWorkflow,cancel_failed_scout_trial_activity,+ check_signals_scout_config_runnable_activity,evaluate_signals_scout_precheck_activity,run_signals_scout_activity,start_trial_signals_scout_run,@@ -4087,3 +4088,68 @@ class TestScoutRunTokenCosts(BaseTest):def test_background_backoff_props(managed_by, backoff, level, expected):config = SignalScoutConfig(managed_by=managed_by, run_interval_minutes=10080, background_backoff_level=level)assert _background_backoff_props(config, backoff) == expected+++ "start_delay_seconds,runnable,expected_sleep,runs",+ [+ (0, True, None, True),+ (420, True, 420, True),+ (420, False, 420, False),+ ],+)+async def test_workflow_sleeps_its_start_delay_and_skips_a_config_disabled_meanwhile(+ start_delay_seconds, runnable, expected_sleep, runs+):+ output = RunSignalsScoutOutput(+ run_id="abc", task_run_id="def", status="completed", runtime_s=1.0, skill_name="s", skill_version=1+ )+ events: list[object] = []++ async def execute_activity(activity_function, input=None, **kwargs):+ events.append(activity_function)+ if activity_function is check_signals_scout_config_runnable_activity:+ return runnable+ if activity_function is evaluate_signals_scout_precheck_activity:+ return EvaluateScoutPrecheckOutput(should_run=True)+ return output++ async def sleep(duration, **kwargs):+ events.append(duration)++ with (+ patch(+ "products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.patched", return_value=True+ ),+ patch(+ "products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.execute_activity",+ side_effect=execute_activity,+ ),+ patch("products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.sleep", side_effect=sleep),+ patch(+ "products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.now",+ return_value=datetime(2026, 10, 13, 9, 0, tzinfo=UTC),+ ),+ patch("products.signals.backend.temporal.agentic.scout_scheduler.temporalio.workflow.upsert_memo"),+ ):+ result = await RunSignalsScoutWorkflow().run(+ RunSignalsScoutInput(team_id=7, skill_name="s", start_delay_seconds=start_delay_seconds)+ )++ if expected_sleep is None:+ assert events == [evaluate_signals_scout_precheck_activity, run_signals_scout_activity]+ elif runs:+ # The sleep comes first, so the pre-check and the run read fresh data after it.+ assert events == [+ timedelta(seconds=expected_sleep),+ check_signals_scout_config_runnable_activity,+ evaluate_signals_scout_precheck_activity,+ run_signals_scout_activity,+ ]+ else:+ assert events == [timedelta(seconds=expected_sleep), check_signals_scout_config_runnable_activity]+ if runs:+ assert result == output+ else:+ assert result.skip_reason == "config_disabled"diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsxindex abfaa4bb6e04..0599d4d82ecc 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutConfigControls.tsx@@ -210,7 +210,9 @@ export function ScoutConfigForm({<div className="flex items-center justify-between gap-4"><div className="flex flex-col min-w-0"><span className="text-xs text-default">Run time</span>- <span className="text-[11.5px] text-muted">Uses the project timezone ({projectTimezone})</span>+ <span className="text-[11.5px] text-muted">+ Uses the project timezone ({projectTimezone}). Starts within 20 minutes of this time.+ </span></div><LemonInputkey={config.run_cron_schedule ?? 'unset'}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsxindex 0aa3af981ae3..edc390c24303 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutCreateModal.tsx@@ -319,7 +319,10 @@ export function ScoutCreateModal({) : null}{scheduleMode === SCOUT_DAILY_AT_SCHEDULE_MODE ||scheduleMode === SCOUT_WEEKLY_ON_SCHEDULE_MODE ? (- <LemonField.Pure label="Run time" help={`Uses the project timezone (${projectTimezone})`}>+ <LemonField.Pure+ label="Run time"+ help={`Uses the project timezone (${projectTimezone}). Starts within 20 minutes of this time.`}+ ><LemonInputtype="time"step={60}diff --git a/products/signals/skills/authoring-scouts/SKILL.md b/products/signals/skills/authoring-scouts/SKILL.mdindex def1393ac6da..170c08217eae 100644--- a/products/signals/skills/authoring-scouts/SKILL.md+++ b/products/signals/skills/authoring-scouts/SKILL.md@@ -140,6 +140,12 @@ For an **existing scout**, tune with `posthog:scout-config-update` (find the `idWhen set it takes precedence over `run_interval_minutes`, so a "slow it down" edit on a cron scout has to change or clear the cron (set `null` to return to the rolling interval).A new or edited schedule anchors on the edit time and waits for its next slot rather than catching up on a past one.Reach for it when the run should land at a wall-clock time: a digest before standup, a weekday-only watch.+- A scheduled run starts inside a window, not at an exact minute.+ Each scout has a fixed offset in that window, so its cadence does not change from run to run.+ A cron scout starts within 20 minutes of its cron time, so a `0 9 * * *` scout starts at the same minute between 9:00 and 9:20 every day.+ An interval scout starts within the same 30-minute coordinator tick, and `last_run_at` records the tick, not the start.+ A scout's first run, a manual run, a workflow run, and a report-check run start at once.+ When you explain or write a schedule, describe the time as a window.- `enabled` — `false` pauses the scout entirely (coordinator skips it).- `precheck_query` — defaults to null: a HogQL `SELECT` that a scheduled run evaluates before it starts, with `{since}`, `{now}`, and `{interval_minutes}` placeholders.No rows, or one row with one false value (such as a zero `count()`), skips the run before it creates a run row or a sandbox. Any other result starts the run, and the rows enter the run prompt. A query error also starts the run.