: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): stop scout dispatch waves merging into one tick (#80256)
Andrew Maguire7da1c4690c65
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex e13725dc9af9..78934a7b9878 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -114,7 +114,12 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e## Where the rest of the system meets this directory- **Coordinator** — `temporal/agentic/scout_coordinator.py` and `scout_scheduler.py`.- Polls every `COORDINATOR_INTERVAL_MINUTES = 30`; dispatches each scout whose per-scout schedule (`run_interval_minutes`, default every 24 hours, or an optional project-local cron `run_cron_schedule` that takes precedence) is due, most-overdue first, hard cap `MAX_RUNS_PER_TICK = 50` per tick, `ScheduleOverlapPolicy.SKIP` to drop ticks rather than queue them.+ Polls every `COORDINATOR_INTERVAL_MINUTES = 30`; dispatches each scout whose per-scout schedule (`run_interval_minutes`, default every 24 hours, or an optional project-local cron `run_cron_schedule` that takes precedence) is due, most-overdue first, hard cap `MAX_RUNS_PER_TICK` per tick (flag-tunable via `max_runs_per_tick_global`), `ScheduleOverlapPolicy.SKIP` to drop ticks rather than queue them.+ A dispatched rolling-interval scout has its `last_run_at` stamped at its own stable slot on the tick grid (`_slot_anchor`, keyed on a digest of the config id), not at the post-fan-out wall clock.+ That is what keeps dispatch spread across the day: a wall-clock anchor accumulated each tick's planning and fan-out latency, so a cohort eventually slipped onto the next tick and merged into that tick's cohort, and every merge made the resulting wave slower to fan out and more likely to slip again.+ 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.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/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex 67599506890a..c62a321107c3 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -323,6 +323,25 @@ def _resolve_global_max_runs_per_tick(payload: dict | None, default: int) -> intreturn 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.+# Set `false` to fall back to stamping the wall clock, which is the only way back to the previous+# behaviour without a deploy. Absent / malformed → on.+SLOT_ALIGNED_DISPATCH_KEY = "slot_aligned_dispatch"+++def _resolve_slot_aligned_dispatch(payload: dict | None) -> bool:+ """Whether the coordinator stamps slot-aligned dispatch anchors. Only a literal boolean is+ honored, so a typo'd override can't silently flip the fleet's dispatch spread either way."""+ if payload is None:+ return True+ override = payload.get(SLOT_ALIGNED_DISPATCH_KEY)+ if isinstance(override, bool):+ return override+ return True++def _resolve_github_read_access(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> bool:"""Whether report-channel scouts on this team get the `gh` evidence prompt guidance,most-specific layer first: `team_configs[team_id]` → `default_team_config` → on. Only adiff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex ad8e8710a633..75650ffc7729 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -2,10 +2,12 @@ from __future__ import annotationsimport jsonimport asyncio+import hashlibfrom dataclasses import dataclass-from datetime import datetime, timedelta, tzinfo+from datetime import UTC, datetime, timedelta, tzinfo+from uuid import UUID-from django.db.models import Q+from django.db.models import Case, DateTimeField, Q, Value, Whenfrom django.utils import timezoneimport structlog@@ -36,6 +38,7 @@ from products.signals.backend.scout_harness.team_limits import (_resolve_global_max_runs_per_tick,_resolve_max_runs_per_day,_resolve_max_runs_per_tick,+ _resolve_slot_aligned_dispatch,_resolve_withheld_skills,_runs_today_by_team,_team_configs,@@ -58,6 +61,8 @@ COORDINATOR_INTERVAL_MINUTES = 30# else stamp jitter makes it skip every other tick (a 60-min scout runs every 2h).DUE_GRACE_SECONDS = 60+TICK_SECONDS = COORDINATOR_INTERVAL_MINUTES * 60+@dataclassclass PlannedRun:@@ -143,19 +148,121 @@ async def stamp_dispatched_signals_scout_runs_activity(— far less harmful than a day of suppression, and bounded by the activity retry policy."""async with Heartbeater():- await database_sync_to_async(_stamp_dispatched_runs, thread_sensitive=False)(stamp_input.dispatched_runs)+ # Same off-the-DB-pool read as planning: the SDK call can block on a cold cache, and+ # `database_sync_to_async`'s pool is sized for DB-bound work.+ 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+ )+++def _dispatch_slot(config_pk: str, run_interval_minutes: int) -> int:+ """The config's stable slot within its interval, as a count of coordinator ticks.+ Derived from a digest of the config's primary key so it never moves: the same scout keeps the+ same slot across restarts, redeploys, and re-enrolments, and the fleet's slots are spread by+ the digest's uniformity rather than by whenever each scout happened to be enabled.+ """+ ticks_per_interval = _ticks_per_interval(run_interval_minutes)+ digest = hashlib.sha256(str(config_pk).encode("utf-8"), usedforsecurity=False).digest()+ return int.from_bytes(digest[:8], "big") % ticks_per_interval+++def _ticks_per_interval(run_interval_minutes: int) -> int:+ """The scout's dispatch period, as a count of coordinator ticks.-def _stamp_dispatched_runs(dispatched_runs: list[PlannedRun]) -> None:+ This has to be the cadence the grid actually produces, or the anchor pulls the scout onto a+ schedule its owner did not configure: an anchor period shorter than the real cadence snaps+ every dispatch back far enough that the scout comes due again early, forever. So it accounts+ for both effects the grid applies. A scout comes due `DUE_GRACE_SECONDS` short of its interval,+ and is then dispatched at the first tick at or after that, which is why the interval is+ rounded up rather than down and why the grace is subtracted before rounding.++ `run_interval_minutes` is validated to 30..43200 with no multiple-of-30 constraint, so an+ interval that lands off the grid is allowed even though the fleet does not use one today.+ """+ due_after_seconds = run_interval_minutes * 60 - DUE_GRACE_SECONDS+ return max(1, -(-due_after_seconds // TICK_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.++ Stamping `timezone.now()` here instead made `last_run_at` absorb the tick's planning and+ fan-out latency, so the next due time crept later every run. Once that creep passed+ `DUE_GRACE_SECONDS` a scout missed its usual tick and re-anchored on the next one, merging its+ cohort into that tick's cohort. The bigger merged wave then took longer to fan out, which made+ the next slip more likely, so waves only ever grew.++ Snapping back to the config's own slot removes both halves of that. Latency never accumulates,+ because the anchor is a grid point rather than a measured time. A run deferred past its slot by+ a per-team cap or a missed tick anchors on the slot it was meant to have, so cohorts drift back+ together on the grid instead of ratcheting forward off it.++ The snapped anchor always lands in `(this tick - period, this tick]`, where the period is the+ scout's cadence from `_ticks_per_interval`. Once a scout is dispatched on its own slot the+ anchor is exactly that tick, so its cadence is the configured one forever after.++ Before then the anchor can sit up to one period back, which shortens that single gap and costs+ the scout ONE EXTRA RUN. The shift is permanent rather than repaid: the scout keeps its new+ phase and its normal cadence from there, so it never skips a later run to make up for the early+ one. Each scout pays it once, when it first lands on its slot, and again after an interval edit+ (which changes its period, and so its slot). Accepted deliberately: it buys a de-merge that+ needs no migration and no backfill command, and the extra runs spread across every tick in the+ period rather than landing in the wave this is meant to break up.+ """+ ticks_per_interval = _ticks_per_interval(run_interval_minutes)+ slot = _dispatch_slot(config_pk, run_interval_minutes)+ tick_index = int(dispatched_at.timestamp()) // TICK_SECONDS+ snapped_index = tick_index - ((tick_index - slot) % ticks_per_interval)+ return datetime.fromtimestamp(snapped_index * TICK_SECONDS, tz=UTC)+++def _stamp_dispatched_runs(dispatched_runs: list[PlannedRun], *, slot_aligned: bool = True) -> None:"""Sync bulk stamp. `.update()` bypasses save(), so this per-tick write never hits the- activity log."""+ activity log.++ 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`+ sequential round trips inside an activity whose timeout is a minute, and a timeout there lands+ after the children have already launched. Two kinds of config are stamped with the wall clock+ instead:++ - A cron scout, because `_overdue_seconds` feeds `last_run_at` to croniter as the reference for+ the next slot. Cron slots are already absolute, so that path never had the drift, and moving+ the reference backwards could re-select the slot this dispatch just fulfilled.+ - A disabled config, which here is a lane the failure breaker paused and the coordinator is+ probing. Its `last_run_at` is the probe cooldown clock rather than a schedule anchor, so+ backdating it would shorten the cooldown the breaker is counting.+ """if not dispatched_runs:returnnow = timezone.now()predicate = Q()for run in dispatched_runs:predicate |= Q(team_id=run.team_id, skill_name=run.skill_name)- SignalScoutConfig.all_teams.filter(predicate).update(last_run_at=now)+ dispatched = SignalScoutConfig.all_teams.filter(predicate)+ if not slot_aligned:+ dispatched.update(last_run_at=now)+ return++ pks_by_anchor: dict[datetime, list[UUID]] = {}+ for pk, enabled, cron_schedule, interval_minutes in dispatched.values_list(+ "pk", "enabled", "run_cron_schedule", "run_interval_minutes"+ ):+ anchor = _slot_anchor(str(pk), interval_minutes, now) if enabled and not cron_schedule else now+ pks_by_anchor.setdefault(anchor, []).append(pk)+ if not pks_by_anchor:+ return+ dispatched.update(+ last_run_at=Case(+ *(When(pk__in=pks, then=Value(anchor)) for anchor, pks in pks_by_anchor.items()),+ default=Value(now),+ output_field=DateTimeField(),+ )+ )@dataclass@@ -443,11 +550,17 @@ def _collect_probe_runs(paused_configs: list[SignalScoutConfig], live_skills: sefor config in paused_configs:if config.skill_name not in live_skills:continue- # `last_run_at` is stamped on every dispatch, including the failed run that tripped the- # breaker, so the first probe lands one full cooldown after the trip. A null (possible- # only through manual row surgery) probes immediately rather than never.+ # The cooldown runs from the later of the lane's last dispatch and the moment it was+ # paused. `last_run_at` alone is not enough: the run that trips the breaker was dispatched+ # while the lane was still enabled, so it was stamped with a slot anchor that can sit up to+ # a full period before the trip, and the cooldown would then read as already elapsed and+ # probe on the next tick. `status_changed_at` alone is not enough either, because a failed+ # probe leaves the status untouched and only `last_run_at` advances to restart the+ # cooldown. Neither set (possible only through manual row surgery) probes immediately+ # rather than never.+ cooldown_anchors = [moment for moment in (config.last_run_at, config.status_changed_at) if moment is not None]cooldown_elapsed_s = (- (now - config.last_run_at).total_seconds() if config.last_run_at else float(AUTO_PAUSE_PROBE_INTERVAL_S)+ (now - max(cooldown_anchors)).total_seconds() if cooldown_anchors else float(AUTO_PAUSE_PROBE_INTERVAL_S))overdue_s = cooldown_elapsed_s - AUTO_PAUSE_PROBE_INTERVAL_Sif overdue_s < 0:diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex 646ececf9caa..fdab0f104b76 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -1,11 +1,12 @@from __future__ import annotationsimport random-from datetime import datetime, timedelta+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom zoneinfo import ZoneInfoimport pytest+from freezegun import freeze_timefrom unittest.mock import AsyncMock, patchfrom django.test import override_settings@@ -40,10 +41,13 @@ from products.signals.backend.scout_harness.team_limits import (_resolve_github_read_access,_resolve_global_max_runs_per_tick,_resolve_max_runs_per_day,+ _resolve_slot_aligned_dispatch,_resolve_withheld_skills,_team_configs,)from products.signals.backend.temporal.agentic.scout_coordinator import (+ COORDINATOR_INTERVAL_MINUTES,+ DUE_GRACE_SECONDS,MAX_RUNS_PER_TICK,CoordinatorWorkflowInput,CoordinatorWorkflowOutput,@@ -54,8 +58,10 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (_allocate_tick_budget,_breaker_paused_configs_by_team,_collect_probe_runs,+ _dispatch_slot,_DueRun,_overdue_seconds,+ _slot_anchor,fetch_enabled_signals_scout_runs_activity,stamp_dispatched_signals_scout_runs_activity,)@@ -64,6 +70,23 @@ from products.skills.backend.models.skills import LLMSkill_PAYLOAD_PATH = "products.signals.backend.scout_harness.team_limits.posthoganalytics.get_feature_flag_payload"_IS_CLOUD_PATH = "products.signals.backend.scout_harness.team_limits.is_cloud"+# A dispatch instant deliberately off the tick grid, so a stamp that reaches the wall clock is+# distinguishable from one that snapped to a slot.+_DISPATCHED_AT = datetime(2026, 8, 8, 16, 31, 12, 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 = [+ "97599cd0-c5d8-457d-ac65-139f71a1eb41",+ "cbbfeb14-54e5-4dc3-b5cc-5f6341e40e36",+ "c01ddd7f-dffa-44f8-88fc-a99c7d8b8302",+ "2d3aee44-2ea5-4e35-bd94-125664596ff4",+ "f6011ab7-2cf9-4488-9bb8-81fbc47e94fb",+ "fcb15539-9802-4a2d-99aa-09fd0103ac53",+ "9fc3e630-5d1a-4836-b102-ca8e7a4633ee",+ "53892108-7c13-4518-bc63-f3e82903ae05",+]+# Enrollment is driven by the `signals-scout` flag payload allowlist. These async tests commit# (no transaction rollback across the worker thread), so leftover teams from other modules can# leak in. Enroll only the teams this module created to keep the scan deterministic.@@ -565,6 +588,29 @@ class TestFailureStreakProbeCollection:assert [p.skill_name for p in probes] == (["signals-scout-general"] if expect_probe else [])+ def test_a_lane_paused_after_a_backdated_stamp_still_serves_its_full_cooldown(self) -> None:+ # The run that trips the breaker is dispatched while the lane is still enabled, so it is+ # stamped with a slot anchor that can sit up to a full period before the trip. Reading the+ # cooldown off `last_run_at` alone then makes a lane paused seconds ago look a day cold,+ # and it probes on the very next tick instead of serving the cooldown.+ now = timezone.now()+ team = Team.objects.create(organization=Organization.objects.create(name="probe-org"), name="probe-team")+ with team_scope(team.id, canonical=True):+ _create_config(+ team,+ "signals-scout-general",+ status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,+ pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,+ consecutive_failure_count=5,+ last_run_at=now - timedelta(seconds=AUTO_PAUSE_PROBE_INTERVAL_S + 3600),+ status_changed_at=now - timedelta(minutes=5),+ )++ paused_by_team = _breaker_paused_configs_by_team()+ probes = _collect_probe_runs(paused_by_team.get(team.id, []), {"signals-scout-general"}, now)++ assert probes == []+@pytest.mark.asyncio@pytest.mark.django_db@@ -751,6 +797,89 @@ async def test_due_check_grace_boundary(ateam, seconds_short, expected_skill_namassert [p.skill_name for p in planned] == expected_skill_names+def _ceil_to_tick(moment: datetime) -> datetime:+ tick = timedelta(minutes=COORDINATOR_INTERVAL_MINUTES)+ ticks = -(-int(moment.timestamp()) // int(tick.total_seconds()))+ return datetime.fromtimestamp(ticks * tick.total_seconds(), tz=UTC)+++class TestSlotAlignedDispatchAnchors:+ # Dispatch used to anchor on the post-fan-out wall clock, which made `last_run_at` absorb each+ # tick's latency: once the creep passed `DUE_GRACE_SECONDS` a cohort missed its usual tick and+ # re-anchored on the next one, merging into that tick's cohort, and the larger wave then made+ # the next slip more likely. These pin the two properties that replace it — anchors land on the+ # tick grid, and a cohort sharing a tick is spread over the interval rather than kept together.++ @parameterized.expand([(1440,), (720,), (60,), (45,), (15,)])+ def test_anchor_is_a_grid_point_no_more_than_one_interval_behind_the_tick(self, interval: int) -> None:+ # The bound is what makes the next due time land in `(this tick, this tick + interval]`: an+ # anchor in the future would stall the scout, one further back would re-dispatch it at once.+ tick_start = datetime(2026, 8, 8, 16, 30, tzinfo=UTC)+ for config_pk in _SLOT_TEST_PKS:+ anchor = _slot_anchor(config_pk, interval, tick_start + timedelta(seconds=97))+ assert anchor <= tick_start+ assert tick_start - anchor < timedelta(minutes=interval)+ assert int(anchor.timestamp()) % (COORDINATOR_INTERVAL_MINUTES * 60) == 0++ @parameterized.expand(+ [(30, 30), (31, 30), (45, 60), (60, 60), (61, 60), (75, 90), (100, 120), (720, 720), (1440, 1440)]+ )+ def test_steady_state_cadence_matches_the_tick_grid(self, interval: int, expected_gap: int) -> None:+ # The slot period has to equal the gap the grid actually produces, or the anchor drags the+ # scout onto a shorter schedule than its owner configured, every dispatch, forever. Two+ # ways to get it wrong, both caught here: rounding the interval down (a 75-minute scout+ # dispatches hourly) and ignoring DUE_GRACE_SECONDS (a 31-minute scout comes due at 30+ # minutes exactly, so its period is one tick, not two).+ config_pk = _SLOT_TEST_PKS[0]+ dispatched_at = _slot_anchor(config_pk, interval, datetime(2026, 8, 8, 16, 30, tzinfo=UTC))+ for _ in range(4):+ due_at = dispatched_at + timedelta(minutes=interval, seconds=-DUE_GRACE_SECONDS)+ next_tick = _ceil_to_tick(due_at)+ assert next_tick - dispatched_at == timedelta(minutes=expected_gap)+ dispatched_at = _slot_anchor(config_pk, interval, next_tick)++ def test_slot_does_not_move_between_processes(self) -> None:+ # Pinned rather than recomputed: a switch to the builtin `hash()` would still be stable+ # within one worker and reshuffle the whole fleet on every restart.+ assert _dispatch_slot("97599cd0-c5d8-457d-ac65-139f71a1eb41", 1440) == 28++ def test_a_cohort_sharing_one_tick_is_spread_across_the_interval(self) -> None:+ dispatched_at = datetime(2026, 8, 8, 16, 31, 12, tzinfo=UTC)+ anchors = {_slot_anchor(config_pk, 1440, dispatched_at) for config_pk in _SLOT_TEST_PKS}+ assert len(anchors) > len(_SLOT_TEST_PKS) / 2++ def test_dispatch_at_its_own_slot_re_anchors_on_that_slot(self) -> None:+ # The steady state, and the property the ratchet lacked: a scout dispatched at its slot+ # anchors exactly there however long planning and fan-out took, so nothing accumulates.+ config_pk = _SLOT_TEST_PKS[0]+ slot_start = _slot_anchor(config_pk, 1440, datetime(2026, 8, 8, 16, 30, tzinfo=UTC))+ assert _slot_anchor(config_pk, 1440, slot_start + timedelta(days=1, seconds=214)) == slot_start + timedelta(+ days=1+ )++ def test_a_deferred_dispatch_anchors_back_on_the_slot_it_missed(self) -> None:+ # A run held back by a per-team cap or a missed tick used to re-anchor wherever it landed,+ # which is how cohorts merged; it now returns to its own slot.+ config_pk = _SLOT_TEST_PKS[0]+ slot_start = _slot_anchor(config_pk, 1440, datetime(2026, 8, 8, 16, 30, tzinfo=UTC))+ assert _slot_anchor(config_pk, 1440, slot_start + timedelta(hours=3)) == slot_start+++ "payload,expected",+ [+ (None, True),+ ({}, True),+ ({"slot_aligned_dispatch": False}, False),+ ({"slot_aligned_dispatch": True}, True),+ ({"slot_aligned_dispatch": "false"}, True), # not a literal bool → the default posture+ ({"slot_aligned_dispatch": 0}, True),+ ],+)+def test_resolve_slot_aligned_dispatch(payload, expected):+ assert _resolve_slot_aligned_dispatch(payload) is expected++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_overdue_config_is_planned_without_stamping(ateam):@@ -772,22 +901,79 @@ async def test_overdue_config_is_planned_without_stamping(ateam):@pytest.mark.asyncio@pytest.mark.django_db-async def test_stamp_activity_advances_dispatched_configs(ateam):+async def test_stamp_activity_advances_dispatched_configs_to_their_slot_anchor(ateam):+ # The stamp must advance the schedule, and must land on the config's slot rather than the wall+ # clock: stamping `now()` let fan-out latency accumulate on `last_run_at` until whole cohorts+ # slipped onto a later tick and merged there.await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")- old = timezone.now() - timedelta(minutes=2000)+ old = _DISPATCHED_AT - timedelta(minutes=2000)config = await database_sync_to_async(_create_config)(ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440, last_run_at=old)- before = timezone.now()- env = ActivityEnvironment()- await env.run(- stamp_dispatched_signals_scout_runs_activity,- StampDispatchedRunsInput(dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")]),+ with freeze_time(_DISPATCHED_AT):+ env = ActivityEnvironment()+ await env.run(+ stamp_dispatched_signals_scout_runs_activity,+ StampDispatchedRunsInput(dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")]),+ )++ refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)+ assert refreshed.last_run_at == _slot_anchor(str(config.pk), 1440, _DISPATCHED_AT)+ assert refreshed.last_run_at != _DISPATCHED_AT+ assert refreshed.last_run_at > old+++ "config_kwargs",+ [+ # A cron scout's `last_run_at` is the reference croniter picks the next slot from, so+ # moving it back could re-select the slot this dispatch just fulfilled and double the run.+ {"enabled": True, "run_cron_schedule": "30 16 * * *"},+ # A disabled config here is a lane the failure breaker paused and the coordinator is+ # probing; its `last_run_at` is the probe cooldown clock, which backdating would shorten.+ {"enabled": False},+ ],+)+async def test_stamp_activity_keeps_the_wall_clock_for_cron_and_probed_configs(ateam, config_kwargs):+ 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+ )++ with freeze_time(_DISPATCHED_AT):+ env = ActivityEnvironment()+ await env.run(+ stamp_dispatched_signals_scout_runs_activity,+ StampDispatchedRunsInput(dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")]),+ )++ refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)+ assert refreshed.last_run_at == _DISPATCHED_AT+++async def test_stamp_activity_falls_back_to_the_wall_clock_when_slot_alignment_is_off(ateam):+ # `slot_aligned_dispatch: false` is the only way back to the previous stamping behaviour+ # without a deploy, so it has to reach the write.+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")+ config = await database_sync_to_async(_create_config)(+ ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440)+ payload = {**_allowlist_payload(), "slot_aligned_dispatch": False}++ with freeze_time(_DISPATCHED_AT), patch(_PAYLOAD_PATH, side_effect=lambda *a, **k: payload):+ env = ActivityEnvironment()+ await env.run(+ stamp_dispatched_signals_scout_runs_activity,+ StampDispatchedRunsInput(dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")]),+ )refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)- assert refreshed.last_run_at is not None and refreshed.last_run_at >= before+ assert refreshed.last_run_at == _DISPATCHED_AT@pytest.mark.asyncio