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): let scout failure breaker ride out platform outages (#81569)

Andrew Maguire2d47995c2416
diff --git a/products/signals/backend/management/commands/run_signals_scout.py b/products/signals/backend/management/commands/run_signals_scout.py
index 842a59431f7b..04969a0c71e0 100644
--- a/products/signals/backend/management/commands/run_signals_scout.py
+++ b/products/signals/backend/management/commands/run_signals_scout.py
@@ -35,6 +35,7 @@ class Command(BaseCommand):
skill_version=options["skill_version"],
repository=options["repository"],
verbose=options["verbose"],
+ triggered_by="manual",
)
except SkillNotFoundError as exc:
raise CommandError(str(exc))
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index abc20a28dfaa..3fb8fda0b2df 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1431,8 +1431,9 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
# run, so it is excluded from activity logging (see field_exclusions below).
last_run_at = models.DateTimeField(null=True, blank=True)
# Failure-streak circuit breaker over this lane's run outcomes, maintained by the runner:
- # bumped on a failed run, zeroed on a successful one. At `FAILURE_STREAK_PAUSE_THRESHOLD`
- # the runner pauses the lane (`transition_status_by_system`, `repeated_failures`) and the
+ # bumped on a failed run, zeroed on a successful one. At the threshold
+ # `failure_streak_pause_threshold` derives from this lane's own schedule, the runner pauses it
+ # (`transition_status_by_system`, `repeated_failures`) and the
# coordinator holds it to one probe per `AUTO_PAUSE_PROBE_INTERVAL_S`. Without it a lane
# that can never succeed re-dispatches forever, taking a full-length sandbox lease per
# interval to produce nothing. Written on every run, so it is excluded from activity
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 78934a7b9878..b4b7909e0c9b 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -45,7 +45,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
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, re-anchors its grace window, and marks it `auto_pause_exempt` so the sweep never overrules a person twice; 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`).
- Also the failure-streak circuit breaker's two knobs: `FAILURE_STREAK_PAUSE_THRESHOLD` (consecutive failed runs before the breaker pauses the lane) and `AUTO_PAUSE_PROBE_INTERVAL_S` (how long a paused lane holds before the coordinator dispatches one probe).
+ Also the failure-streak circuit breaker's knobs: `failure_streak_pause_threshold(runs_in_tolerance_window)` — consecutive failed runs before the breaker pauses the lane, derived per-lane so the same wall-clock tolerance holds at every cadence (one failure past the runs the schedule fits into `FAILURE_STREAK_MIN_SPAN_MINUTES` of continuous failure, `FAILURE_STREAK_MIN_RUNS` floor, capped at `FAILURE_STREAK_MAX_RUNS` + 1), with `interval_runs_in_tolerance_window` sizing the evenly spaced case — and `AUTO_PAUSE_PROBE_INTERVAL_S` (how long a paused lane holds before the coordinator dispatches one probe).
- `team_limits.py`
Single source of truth for a team's effective scout caps + metadata, resolved from the `signals-scout` flag payload in one read. The same three-layer cap resolution (`team_configs[team]` → `default_team_config` → code constant) the coordinator enforces at dispatch, plus enrollment (`_parse_enrollment` → `guaranteed_team_ids` / `skip_team_ids`, with a cloud/dev-gated fallback) and the editorial banner string. `guaranteed_team_ids` may contain the `"*"` wildcard (`ENROLL_ALL_TOKEN`): with it, enrollment inverts from an explicit allowlist to "every team that has enabled scout configs" — the self-serve gate, where the product-autonomy- gated UI creates the configs; explicit ids alongside `"*"` are still force-provisioned and `skip_team_ids` still hard-excludes. The global per-tick ceiling is flag-tunable too (`_resolve_global_max_runs_per_tick` ← `max_runs_per_tick_global`, default `MAX_RUNS_PER_TICK`).
Kept free of the temporalio stack so it stays cheap to import on the API path; both the coordinator and the metadata endpoint import from here so the reported caps never drift from what dispatch allows. `resolve_team_metadata()` backs the metadata viewset;
@@ -73,7 +73,8 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
`SignalScoutRun` is now a thin bridge to a Tasks `TaskRun` — run status / timing / error live on `task_run`, not on the bridge row. Single-flight is a best-effort app-layer guard:
`_has_running_run` skips dispatch when a prior run for the same `(team, skill_name)` has `task_run.status = IN_PROGRESS`. The old `WHERE status='running'` partial unique index was dropped in the bridge simplification; `_self_heal_stale_runs` now reaps the orphan case at the app layer (failing any `QUEUED`/`IN_PROGRESS` run older than `STALE_RUN_CUTOFF_S` before the guard), so a worker crash no longer wedges a lane permanently. A `task_run.status`-based DB constraint is still a possible follow-up for stronger single-flight guarantees.
- A `(team, skill)` lane that never succeeds is its own failure mode, distinct from the orphan case above: every dispatch is well-formed, takes a sandbox lease for the full runtime cap, produces nothing, and books a `failed` run — indefinitely, since the lane stays due every tick and nothing reconciles "this has never worked".
- The runner maintains a failure-streak circuit breaker for it: `consecutive_failure_count` on the config row is bumped on a failed run and zeroed on a successful one, and at `FAILURE_STREAK_PAUSE_THRESHOLD` the runner pauses the lane through `SignalScoutConfig.transition_status_by_system` (`status=paused_by_system`, `pause_reason=repeated_failures`, which also syncs `enabled=False` like any pause).
+ The runner maintains a failure-streak circuit breaker for it: `consecutive_failure_count` on the config row is bumped on a failed run and zeroed on a successful one, and at the lane's threshold the runner pauses it through `SignalScoutConfig.transition_status_by_system` (`status=paused_by_system`, `pause_reason=repeated_failures`, which also syncs `enabled=False` like any pause).
+ The threshold is per-lane, not fleet-wide: `failure_streak_pause_threshold` sets it one failure past the runs the lane's own schedule fits into `FAILURE_STREAK_MIN_SPAN_MINUTES` of continuous failure (`_failure_streak_runs_in_window` — the fullest window of occurrences across a year-long sample when a cron is set, widened by two hours of DST slack since project-local wall-clock schedules pack extra runs into the spring-forward night (Antarctica/Troll jumps two hours), else the evenly spaced count off the tick-quantized `run_interval_minutes`, the cadence dispatch actually produces), so the streak has to outlast the same wall clock whatever the schedule. Only scheduled runs feed the streak — a manual "run now" is off-schedule, so its failures must not count against a schedule-sized threshold (a burst of retries would pause a daily lane in minutes), while a manual success still clears the streak and can resume a paused lane. A single count could not: at the tightest cadences it trips healthy scouts partway through a platform outage, and at the default daily one it would have to grow into weeks of lease burn to buy tolerance those lanes never needed (an outage costs a daily lane at most one run). Counting occurrences rather than reading one gap is what keeps a bursty cron honest — `0,30 0 * * *` has a 30-minute gap but only runs twice a day, so gap-sizing would hand it a lane-that-runs-all-day budget. The resolved threshold rides on `signals_scout_config_auto_paused` next to the count and the lane's schedule, so a trip is readable without re-deriving it.
The breaker is half-open on purpose — a pause is not a tombstone, so the coordinator dispatches one probe per `AUTO_PAUSE_PROBE_INTERVAL_S` to lanes paused with `repeated_failures` (`_collect_probe_runs`, cooldown anchored on `last_run_at` so a failed probe restarts it with no extra bookkeeping); a probe that succeeds resumes the lane through the same helper and normal cadence returns with nobody intervening.
The helper's reason-scoped ownership rule keeps it honest: the breaker may only resume its own `repeated_failures` pauses and can never touch `paused_by_user`, so an operator switching a scout off always wins.
The streak is read-only on the config serializers (`scout-configs-list`); any config edit resets it, a resume (human `enabled=true` or a successful probe) always starts it clean, and the trip emits `signals_scout_config_auto_paused` once.
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index d7788b47c74c..37dabdb6abee 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -35,9 +35,93 @@ STALE_RUN_CUTOFF_S = 2 * WORKFLOW_HARD_CEILING_S
# scout that has never once succeeded: every dispatch takes a fresh sandbox lease for the
# full runtime cap, produces nothing, and books a `failed` run — so a permanently broken
# (team, skill) lane costs a lease per interval forever. Five in a row is well past any
-# plausible run of bad luck (a flaky sandbox spawn, one upstream provider error) while still
-# tripping within hours on the tight cadences, not days.
-FAILURE_STREAK_PAUSE_THRESHOLD = 5
+# plausible run of bad luck (a flaky sandbox spawn, one upstream provider error), and on the
+# default daily cadence it is also the whole story: a multi-hour platform outage can cost
+# such a lane at most one run, so nothing wider buys it outage tolerance — it only buys a
+# permanently broken lane more leases before the breaker notices.
+FAILURE_STREAK_MIN_RUNS = 5
+
+# A lane on a tight cadence is the case the run count alone gets wrong: an outage fails
+# every run fleet-wide, so at one run an hour five failures land inside an outage most of a
+# workday shorter than the 24h probe cooldown the pause then costs — the healthy scouts the
+# breaker exists to leave alone are exactly the ones it trips first. So the streak also has
+# to span this much wall clock before it counts as a wedge, which is what
+# `failure_streak_pause_threshold` converts into a per-lane run count.
+FAILURE_STREAK_MIN_SPAN_MINUTES = 12 * 60
+
+# Cap on the runs-in-window the threshold scales on, so a lane that runs constantly can never
+# turn the span into an unbounded lease budget. The 30-minute floor on `run_interval_minutes`
+# (and on the minimum gap between cron occurrences) puts the densest real lane exactly here;
+# the derived threshold tops out one past it.
+FAILURE_STREAK_MAX_RUNS = 24
+
+
+def failure_streak_pause_threshold(runs_in_tolerance_window: int) -> int:
+ """Consecutive failures this lane has to reach before the breaker pauses it.
+
+ Deliberately not a fleet-wide number: the same count means hours on an hourly scout and
+ weeks on a monthly one, so one constant either trips healthy tight lanes during an outage
+ or lets broken slow lanes burn leases for months.
+
+ Callers pass how many runs the lane's schedule actually fits inside
+ `FAILURE_STREAK_MIN_SPAN_MINUTES` — the most an outage of that length can consume. The
+ threshold sits one failure past that: a streak that merely equals the window's worth is
+ still consistent with a tolerated outage (an hourly lane books 12 failures inside 12 hours),
+ so only the next failure beyond it demonstrates a wedge rather than "the platform was
+ down". Deliberately not derived from one gap between runs: a bursty schedule can pair a
+ tight gap with only a couple of runs a day, and sizing off the gap would hand it the
+ tolerance of a lane that runs all day, i.e. weeks of lease burn.
+ """
+ return max(FAILURE_STREAK_MIN_RUNS, min(FAILURE_STREAK_MAX_RUNS, runs_in_tolerance_window) + 1)
+
+
+# The coordinator's tick grid, which quantizes every rolling interval: a lane comes due
+# `DUE_GRACE_SECONDS` short of its interval and is dispatched at the first tick at or after
+# that, so an off-grid interval runs at the next whole-tick cadence. The grid lives here
+# rather than in the coordinator so the failure breaker can size a lane off the cadence
+# dispatch actually produces; the coordinator imports it back from here.
+#
+# Tick cadence: per-scout schedules are enforced via the coordinator's due-check, so this is
+# just the polling granularity — the floor on how often any scout can run.
+COORDINATOR_INTERVAL_MINUTES = 30
+# Slack on the due-check so a scout that's a few seconds short at a tick still counts as due —
+# else stamp jitter makes it skip every other tick (a 60-min scout runs every 2h).
+DUE_GRACE_SECONDS = 60
+
+
+def dispatch_ticks_per_interval(run_interval_minutes: int) -> int:
+ """The scout's dispatch period, as a count of coordinator ticks.
+
+ 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 // (COORDINATOR_INTERVAL_MINUTES * 60)))
+
+
+def interval_runs_in_tolerance_window(interval_minutes: int) -> int:
+ """Runs a rolling-interval lane fits in the tolerance window — the evenly spaced case.
+
+ Sized off the cadence the tick grid actually produces, not the raw column: an off-grid
+ interval (say 32 minutes) is dispatched at the next whole tick, so the raw value would
+ credit the lane with runs it never books and hand a wedged lane a wider threshold than
+ its real cadence earns.
+
+ Cron lanes count occurrences instead (`runner._failure_streak_runs_in_window`), since
+ their gaps are uneven and no single one stands for the window's worth of runs.
+ """
+ if interval_minutes <= 0:
+ return 1
+ effective_minutes = dispatch_ticks_per_interval(interval_minutes) * COORDINATOR_INTERVAL_MINUTES
+ return -(-FAILURE_STREAK_MIN_SPAN_MINUTES // effective_minutes) # ceil
+
# Cooldown a paused lane holds before the coordinator dispatches one probe — the half-open
# state. A pause is not a tombstone: whatever wedged the lane (a broken sandbox env, a skill
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 76c7ec84c529..1c63ce69fbe9 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -3,14 +3,17 @@ from __future__ import annotations
import time
import asyncio
import logging
+from collections import deque
from dataclasses import dataclass
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
+from functools import lru_cache
from typing import TYPE_CHECKING, Any
from django.db.models import F
from django.utils import timezone
import posthoganalytics
+from croniter import CroniterError, croniter
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
@@ -25,8 +28,11 @@ from products.signals.backend.scout_harness.derived_metadata import stamp_derive
from products.signals.backend.scout_harness.lazy_seed import canonical_skill_names, sync_canonical_skills
from products.signals.backend.scout_harness.limits import (
DEFAULT_MAX_RUNTIME_S,
- FAILURE_STREAK_PAUSE_THRESHOLD,
+ FAILURE_STREAK_MAX_RUNS,
+ FAILURE_STREAK_MIN_SPAN_MINUTES,
STALE_RUN_CUTOFF_S,
+ failure_streak_pause_threshold,
+ interval_runs_in_tolerance_window,
)
from products.signals.backend.scout_harness.model_selection import resolve_scout_model
from products.signals.backend.scout_harness.prompt import (
@@ -69,6 +75,28 @@ SIGNALS_SCOUT_FULL_NETWORK_ENV_NAME = "SIGNALS_SCOUT_FULL_NETWORK"
# up as one stage even though the tag names the individual scout.
SCOUT_AI_STAGE_PREFIX = "scout:"
+# `_cron_runs_in_window` samples a cron schedule from a fixed reference (not `now`) so a lane's
+# breaker threshold is a property of its schedule rather than of when it happened to fail. The
+# horizon is one full pass of the month and day-of-month fields, which keeps cross-month
+# adjacencies in the sample: "first of the month or Sunday" packs its fullest window where a
+# matching Sunday touches a first, and a shorter occurrence-count sample never reaches one.
+# Day-of-week alignments unique to other calendar years can still be missed, which only ever
+# undercounts, so an exotic lane trips a little earlier instead of earning extra lease budget.
+# The sample cap covers the horizon at the 30-minute schedule floor with room to spare; denser
+# out-of-band schedules hit the `FAILURE_STREAK_MAX_RUNS` early exit long before it.
+_CRON_WINDOW_REFERENCE = datetime(2026, 1, 1, tzinfo=UTC)
+_CRON_WINDOW_HORIZON = timedelta(days=366)
+_CRON_WINDOW_MAX_SAMPLES = 20_000
+
+# Cron lanes hold wall-clock time in the project's timezone (see the coordinator's due-check),
+# so on the spring-forward night more wall-clock schedule fits inside the same absolute outage
+# than this transition-free sample sees. Sized to the largest jump among selectable project
+# timezones (Antarctica/Troll advances two hours; every other zone is an hour or less), which
+# keeps the tolerance honest on that night in every zone at the cost of at most a couple of
+# extra tolerated failures the rest of the year. That is far cheaper than sizing per project
+# timezone, which would put DST fold/gap arithmetic and a per-team cache key on the failure path.
+_CRON_WINDOW_DST_SLACK_MINUTES = 120
+
# The report channel (emit_report/edit_report) is opt-in per skill. A scout's sandbox token
# carries the report-write scope ONLY when its skill listed one of these in `allowed_tools` (see
# the posture selection where the sandbox context is built). A baseline scout never carries that
@@ -105,6 +133,7 @@ def run_signals_scout(
skill_version: int | None = None,
repository: str | None = None,
verbose: bool = False,
+ triggered_by: str = "schedule",
) -> RunResult:
"""Synchronous entrypoint: resolves config, spawns sandbox, persists the run row.
@@ -118,6 +147,7 @@ def run_signals_scout(
skill_version=skill_version,
repository=repository,
verbose=verbose,
+ triggered_by=triggered_by,
)
)
@@ -129,8 +159,14 @@ async def arun_signals_scout(
skill_version: int | None = None,
repository: str | None = None,
verbose: bool = False,
+ triggered_by: str = "schedule",
) -> RunResult:
- """Async core. Safe to call from inside a running event loop (Temporal activity)."""
+ """Async core. Safe to call from inside a running event loop (Temporal activity).
+
+ `triggered_by` is `"schedule"` for coordinator-dispatched runs (including breaker probes)
+ and `"manual"` for on-demand triggers (the `run` endpoint, the management command). Only
+ scheduled failures feed the failure-streak breaker; see the failure path below.
+ """
team = await database_sync_to_async(_get_team, thread_sensitive=False)(team_id)
# Honor the per-scout holdback denylist, resolved against the canonical project. Two effects:
@@ -312,7 +348,9 @@ async def arun_signals_scout(
)
# A run that got all the way through closes the breaker: the lane works, so any streak
# it had accumulated is stale and a standing auto-pause is lifted (this is also how the
- # half-open probe recovers a paused lane once its underlying cause is fixed).
+ # half-open probe recovers a paused lane once its underlying cause is fixed). Any
+ # trigger counts, since a manual success is the natural way to revive a lane right
+ # after fixing its skill.
await database_sync_to_async(_clear_failure_streak, thread_sensitive=False)(config.pk)
_capture_run_finished(
team=team,
@@ -366,8 +404,15 @@ async def arun_signals_scout(
else (0, None)
)
# Advance the breaker before the event so the failure that trips it is the one whose
- # `error_message` explains the pause.
- streak = await database_sync_to_async(_record_failure_streak, thread_sensitive=False)(config.pk)
+ # `error_message` explains the pause. Scheduled failures only: the threshold is sized
+ # on the schedule's cadence, so counting off-schedule "run now" retries would let a
+ # burst of them reach a slow lane's threshold in minutes and impose the probe cooldown
+ # on a lane whose schedule never failed.
+ streak = (
+ await database_sync_to_async(_record_failure_streak, thread_sensitive=False)(config.pk)
+ if triggered_by == "schedule"
+ else None
+ )
_capture_run_finished(
team=team,
config=config,
@@ -391,6 +436,7 @@ async def arun_signals_scout(
skill_name=skill.name,
run_id=run_id,
failure_count=streak.count,
+ failure_streak_threshold=streak.threshold,
reason=str(exc)[:300],
)
return RunResult(
@@ -834,6 +880,7 @@ class _FailureStreak:
count: int
tripped: bool
+ threshold: int
def _clear_failure_streak(config_id: Any) -> None:
@@ -867,6 +914,63 @@ def _clear_failure_streak(config_id: Any) -> None:
logger.exception("signals_scout: failed to clear failure streak", extra={"scout_config_id": str(config_id)})
+def _failure_streak_runs_in_window(config: SignalScoutConfig) -> int:
+ """Runs this lane's schedule fits in the breaker's tolerance window — what it scales on.
+
+ A cron schedule takes precedence over `run_interval_minutes` at dispatch, and the column
+ keeps whatever value it held before the cron was set, so reading the column alone would
+ size the breaker off a cadence the lane no longer runs at.
+
+ Cron gaps are uneven, and no single gap answers the question the breaker asks: "0,30 0 * * *"
+ has a 30-minute gap but runs twice a day, so its tightest gap would buy it the tolerance of a
+ lane that runs all day. So count occurrences over a whole schedule cycle and take the fullest
+ window — the most failures an outage of that length can actually leave behind.
+
+ A malformed expression can only arrive via an out-of-band write (the API validates on save);
+ fall back to the rolling interval rather than fail a run's breaker bookkeeping over it.
+ """
+ if config.run_cron_schedule:
+ try:
+ return _cron_runs_in_window(config.run_cron_schedule)
+ except (CroniterError, ValueError):
+ logger.warning(
+ "signals_scout: invalid cron schedule while sizing failure breaker",
+ extra={"scout_config_id": str(config.pk)},
+ )
+ return interval_runs_in_tolerance_window(config.run_interval_minutes)
+
+
+@lru_cache(maxsize=256)
+def _cron_runs_in_window(cron_schedule: str) -> int:
+ """Fullest tolerance window of occurrences (`FAILURE_STREAK_MIN_SPAN_MINUTES` plus the DST
+ slack) anywhere in the schedule's sampled cycle. Cached because it is a pure function of the
+ schedule string given the fixed reference, and the densest schedules cost a few hundred
+ milliseconds to walk.
+
+ Each window's count is read at its last occurrence: the occurrences within `window` looking
+ back from occurrence t are exactly the ones a window opened at its earliest member covers, so
+ the running deque sees every half-open window's count without materializing the sample. That
+ matches `interval_runs_in_tolerance_window`'s half-open count for a lane with no cron.
+ """
+ iterator = croniter(cron_schedule, _CRON_WINDOW_REFERENCE)
+ window = timedelta(minutes=FAILURE_STREAK_MIN_SPAN_MINUTES + _CRON_WINDOW_DST_SLACK_MINUTES)
+ horizon = _CRON_WINDOW_REFERENCE + _CRON_WINDOW_HORIZON + window
+ in_window: deque[datetime] = deque()
+ # A schedule with no occurrence inside the horizon (e.g. February 29th) still runs once.
+ fullest = 1
+ for _ in range(_CRON_WINDOW_MAX_SAMPLES):
+ occurrence = iterator.get_next(datetime)
+ if occurrence > horizon:
+ break
+ while in_window and in_window[0] <= occurrence - window:
+ in_window.popleft()
+ in_window.append(occurrence)
+ fullest = max(fullest, len(in_window))
+ if fullest >= FAILURE_STREAK_MAX_RUNS:
+ break
+ return fullest
+
+
def _record_failure_streak(config_id: Any) -> _FailureStreak | None:
"""Bump the failure streak and pause the lane at the threshold. Returns None when the row
is gone or the write failed — the caller only uses the result to decide whether to emit the
@@ -875,6 +979,10 @@ def _record_failure_streak(config_id: Any) -> _FailureStreak | None:
The bump is an atomic `F()` increment, not read-then-write: the runner's single-flight guard
means one run per (team, skill) at a time, but a config edit's streak reset can land
concurrently, and a stale absolute write would resurrect the streak the edit just cleared.
+ The threshold is per-lane, derived from the runs the config's own schedule fits in the
+ tolerance window (`failure_streak_pause_threshold`), so the same wall-clock tolerance holds
+ whether the lane runs hourly or monthly.
+
The pause goes through the transition helper: `tripped` is True only when the helper actually
moved the status, so a re-failed probe (already paused, transition is a no-op) re-arms the
cooldown via its own `last_run_at` stamp without firing the trip event again. The error text
@@ -891,13 +999,14 @@ def _record_failure_streak(config_id: Any) -> _FailureStreak | None:
if config is None:
return None
count = config.consecutive_failure_count
+ threshold = failure_streak_pause_threshold(_failure_streak_runs_in_window(config))
tripped = False
- if count >= FAILURE_STREAK_PAUSE_THRESHOLD:
+ if count >= threshold:
tripped = config.transition_status_by_system(
SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
)
- return _FailureStreak(count=count, tripped=tripped)
+ return _FailureStreak(count=count, tripped=tripped, threshold=threshold)
except Exception:
logger.exception("signals_scout: failed to record failure streak", extra={"scout_config_id": str(config_id)})
return None
@@ -1032,6 +1141,7 @@ def _capture_config_auto_paused(
skill_name: str,
run_id: Any,
failure_count: int,
+ failure_streak_threshold: int,
reason: str,
) -> None:
"""Emit a scout-owned event when a lane's failure-streak breaker trips.
@@ -1051,7 +1161,12 @@ def _capture_config_auto_paused(
"scout_config_id": str(config.id),
"run_id": str(run_id),
"consecutive_failure_count": failure_count,
- "failure_streak_threshold": FAILURE_STREAK_PAUSE_THRESHOLD,
+ # A wedge count is only readable next to the threshold the lane was actually
+ # held to, and the threshold only next to the schedule it was derived from
+ # (the cron when set, else the interval).
+ "failure_streak_threshold": failure_streak_threshold,
+ "run_interval_minutes": config.run_interval_minutes,
+ "run_cron_schedule": config.run_cron_schedule,
"auto_pause_reason": reason,
},
groups=groups(team.organization, team),
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index 75650ffc7729..1ada13e71fba 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -23,7 +23,12 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.config_registry import live_scout_skill_names, register_missing_configs
from products.signals.backend.scout_harness.lazy_seed import 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,
+ COORDINATOR_INTERVAL_MINUTES,
+ DUE_GRACE_SECONDS,
+ dispatch_ticks_per_interval,
+)
# Per-team cap resolution + the flag-payload read live in the temporalio-free `team_limits` module
# so the HTTP metadata surface can share them. Imported by name so the planning code below calls
@@ -53,14 +58,9 @@ logger = structlog.get_logger(__name__)
# round-robin allocation do the day-to-day fairness work; this is the global ceiling.
MAX_RUNS_PER_TICK = 1000
-# Coordinator tick cadence. Per-scout schedules are enforced via the due-check, so this is
-# just the polling granularity — the floor on how often any scout can run.
-COORDINATOR_INTERVAL_MINUTES = 30
-
-# Slack on the due-check so a scout that's a few seconds short at a tick still counts as due —
-# else stamp jitter makes it skip every other tick (a 60-min scout runs every 2h).
-DUE_GRACE_SECONDS = 60
-
+# The tick grid itself (`COORDINATOR_INTERVAL_MINUTES`, `DUE_GRACE_SECONDS`,
+# `dispatch_ticks_per_interval`) lives in `scout_harness/limits.py` so the failure breaker can
+# size lanes off the cadence dispatch actually produces; it is imported above.
TICK_SECONDS = COORDINATOR_INTERVAL_MINUTES * 60
@@ -164,28 +164,11 @@ def _dispatch_slot(config_pk: str, run_interval_minutes: int) -> int:
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)
+ ticks_per_interval = dispatch_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.
-
- 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.
@@ -201,7 +184,7 @@ def _slot_anchor(config_pk: str, run_interval_minutes: int, dispatched_at: datet
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
+ scout's cadence from `dispatch_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
@@ -212,7 +195,7 @@ def _slot_anchor(config_pk: str, run_interval_minutes: int, dispatched_at: datet
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)
+ ticks_per_interval = dispatch_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)
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index 9e2cb9a0c631..954733998a00 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -37,6 +37,10 @@ class RunSignalsScoutInput:
skill_name: str
skill_version: int | None = None
repository: str | None = None
+ # "schedule" (coordinator dispatch, including breaker probes) or "manual" (the `run`
+ # endpoint). Only scheduled failures feed the failure-streak breaker; the default keeps
+ # in-flight workflow histories decoding to today's behavior.
+ triggered_by: str = "schedule"
@dataclass
@@ -114,6 +118,7 @@ async def run_signals_scout_activity(input: RunSignalsScoutInput) -> RunSignalsS
skill_name=input.skill_name,
skill_version=input.skill_version,
repository=input.repository,
+ triggered_by=input.triggered_by,
)
except (OperationalError, InterfaceError):
# Transient DB connection drop (pgbouncer pool recycle / failover / deploy). Stay
@@ -196,7 +201,9 @@ async def start_manual_signals_scout_run(client: Client, *, team_id: int, skill_
path has — the activity's Signals-credits quota check, and the runner's withheld-skill
denylist, stale-run self-heal, and single-flight. It does NOT honor the per-scout
schedule or `last_run_at`: a manual run is off-schedule and deliberately leaves the
- cadence untouched.
+ cadence untouched — which is also why its failures don't feed the failure-streak
+ breaker (the threshold is sized on the schedule), while a manual success still clears
+ the streak and can resume a breaker-paused lane.
Single-flight is enforced at the Temporal server, so the trigger can't be gamed into
stacking concurrent runs of the same scout: `ALLOW_DUPLICATE` lets the stable id be
@@ -207,7 +214,7 @@ async def start_manual_signals_scout_run(client: Client, *, team_id: int, skill_
workflow_id = manual_run_workflow_id(team_id, skill_name)
await client.start_workflow(
RunSignalsScoutWorkflow.run,
- RunSignalsScoutInput(team_id=team_id, skill_name=skill_name),
+ RunSignalsScoutInput(team_id=team_id, skill_name=skill_name, triggered_by="manual"),
id=workflow_id,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index 66b2391342f8..5e1e852e61fd 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -32,7 +32,7 @@ from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.report_charts import ReportChart
from products.signals.backend.scout_harness.derived_metadata import DERIVED_METADATA_KEY
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, _compute_row_hash
-from products.signals.backend.scout_harness.limits import FAILURE_STREAK_PAUSE_THRESHOLD, STALE_RUN_CUTOFF_S
+from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S, failure_streak_pause_threshold
from products.signals.backend.scout_harness.model_selection import ScoutModel
from products.signals.backend.scout_harness.prompt import _REPORT_CHARTS, HARNESS_PROMPT_VERSION, build_run_prompt
from products.signals.backend.scout_harness.runner import (
@@ -41,6 +41,7 @@ from products.signals.backend.scout_harness.runner import (
RunResult,
_ai_stage,
_create_run_row,
+ _failure_streak_runs_in_window,
arun_signals_scout,
)
from products.signals.backend.scout_harness.skill_loader import (
@@ -1086,6 +1087,65 @@ async def test_sandbox_env_matches_config_network_access(
assert (bridge.metadata or {}).get("network_access") == ("full" if network_access == "full" else None)
+def _resolved_failure_threshold(cron_schedule: str | None, interval_minutes: int) -> int:
+ config = SignalScoutConfig(run_cron_schedule=cron_schedule, run_interval_minutes=interval_minutes)
+ return failure_streak_pause_threshold(_failure_streak_runs_in_window(config))
+
+
+ [
+ # The schedule floor. Bounded, so the densest lane cannot turn the span into an
+ # unbounded lease budget.
+ ("floor_interval", None, 30, 25),
+ # The outage case the breaker used to get wrong: hourly lanes accrued five failures
+ # inside an outage shorter than the 24h probe cooldown the pause then cost them. The
+ # threshold sits one past the 12 runs the window fits, so an outage lasting exactly
+ # the tolerated span still cannot trip the lane.
+ ("hourly_interval", None, 60, 13),
+ ("two_hourly_interval", None, 120, 7),
+ # An off-grid interval dispatches at the next whole coordinator tick (32 minutes runs
+ # hourly), so sizing off the raw column would hand a wedged lane nearly double the
+ # leases its real cadence earns.
+ ("off_grid_interval_sized_at_its_dispatch_cadence", None, 32, 13),
+ # Past the span the count floor takes over — a broken lane must not get more leases
+ # just because it runs rarely.
+ ("six_hourly_interval", None, 360, 5),
+ ("daily_default", None, 1440, 5),
+ ("monthly_interval", None, 43200, 5),
+ # A cron wins at dispatch, but `run_interval_minutes` keeps whatever it held before —
+ # so reading the column alone would size an hourly lane as a daily one. Two runs wider
+ # than the hourly interval lane: cron lanes are wall-clock schedules, so the sizing
+ # window carries DST slack for the largest spring-forward jump a project timezone can
+ # select (two hours).
+ ("hourly_cron_beats_stale_column", "0 * * * *", 1440, 15),
+ ("half_hourly_cron_hits_the_ceiling", "*/30 * * * *", 1440, 25),
+ # Bursty: a 30-minute gap that repeats twice a day is not a lane that runs all day, and
+ # must not be handed the tolerance of one — that is twelve days of leases on a wedge.
+ ("bursty_cron_is_not_a_dense_lane", "0,30 0 * * *", 1440, 5),
+ ("uneven_daily_cron", "0 9,17 * * *", 1440, 5),
+ # First-of-the-month or Sunday: the fullest window (six runs, 21:00 through 02:00) only
+ # exists where a matching Sunday touches a first — May 31st into June 1st in the sampled
+ # year. A sample truncated by occurrence count ends months earlier and sizes the lane
+ # off its ordinary three-run days.
+ ("sparse_cron_fullest_window_at_a_month_boundary", "0 0,1,2,21,22,23 1 * 0", 1440, 7),
+ # Valid but with no occurrence in the sampled year at all; sized as a single-run lane
+ # rather than crashing or zeroing out.
+ ("cron_with_no_occurrence_in_the_sample_year", "0 0 29 2 *", 1440, 5),
+ # Both only reachable by an out-of-band write (the API validates cron and interval on
+ # save); a run's breaker bookkeeping must not die on either.
+ ("malformed_cron_falls_back_to_the_interval", "not a cron", 60, 13),
+ ("nonsensical_interval_falls_back_to_the_floor", None, 0, 5),
+ ]
+)
+def test_failure_breaker_threshold_tracks_the_runs_an_outage_can_consume(
+ _name, cron_schedule, interval_minutes, expected
+):
+ # A fleet-wide count means hours on a tight lane and months on a slow one: it either trips
+ # healthy hourly scouts during a platform outage or lets a wedged daily scout burn leases
+ # for weeks. Both directions have to hold at once, on cron lanes as well as interval ones.
+ assert _resolved_failure_threshold(cron_schedule, interval_minutes) == expected
+
+
@parameterized.expand(
[
("canonical", "signals-scout-general", "scout:general"),
@@ -1397,7 +1457,7 @@ async def test_failure_streak_pauses_scout_once_and_a_success_resumes_it(ateam,
# produce nothing. Nothing else in the harness notices, so the breaker has to.
session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam, "close-out")
- async def _run_once(*, failing: bool, capture):
+ async def _run_once(*, failing: bool, capture, triggered_by: str = "schedule"):
start = (
AsyncMock(side_effect=RuntimeError("poll_for_turn: timed out after 900s"))
if failing
@@ -1411,7 +1471,9 @@ async def test_failure_streak_pauses_scout_once_and_a_success_resumes_it(ateam,
patch("products.signals.backend.scout_harness.runner.sync_canonical_skills"),
_stubbed_spawn_dependencies(),
):
- return await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+ return await arun_signals_scout(
+ team_id=ateam.id, skill_name="signals-scout-errors", triggered_by=triggered_by
+ )
def _paused_events(capture) -> list:
return [c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_config_auto_paused"]
@@ -1422,22 +1484,36 @@ async def test_failure_streak_pauses_scout_once_and_a_success_resumes_it(ateam,
)
capture = MagicMock()
- for _ in range(FAILURE_STREAK_PAUSE_THRESHOLD - 1):
+ await _run_once(failing=True, capture=capture)
+ config = await _reload()
+ # The breaker scales with the lane's schedule, so the streak this run has to reach is
+ # derived from the config rather than fixed.
+ threshold = failure_streak_pause_threshold(_failure_streak_runs_in_window(config))
+
+ # A failed manual "run now" is off-schedule evidence and must not advance the streak:
+ # the threshold is sized on the schedule's cadence, so counting rapid manual retries
+ # would let a burst of them pause a daily lane within minutes of a platform blip.
+ await _run_once(failing=True, capture=capture, triggered_by="manual")
+ config = await _reload()
+ assert config.consecutive_failure_count == 1
+
+ for _ in range(threshold - 2):
await _run_once(failing=True, capture=capture)
config = await _reload()
- assert config.consecutive_failure_count == FAILURE_STREAK_PAUSE_THRESHOLD - 1
+ assert config.consecutive_failure_count == threshold - 1
assert config.status == SignalScoutConfig.Status.ACTIVE
assert _paused_events(capture) == []
await _run_once(failing=True, capture=capture)
config = await _reload()
- assert config.consecutive_failure_count == FAILURE_STREAK_PAUSE_THRESHOLD
+ assert config.consecutive_failure_count == threshold
assert config.status == SignalScoutConfig.Status.PAUSED_BY_SYSTEM
assert config.pause_reason == SignalScoutConfig.PauseReason.REPEATED_FAILURES
assert config.enabled is False
trip = _paused_events(capture)
assert len(trip) == 1
- assert trip[0].kwargs["properties"]["consecutive_failure_count"] == FAILURE_STREAK_PAUSE_THRESHOLD
+ assert trip[0].kwargs["properties"]["consecutive_failure_count"] == threshold
+ assert trip[0].kwargs["properties"]["failure_streak_threshold"] == threshold
assert "timed out after 900s" in trip[0].kwargs["properties"]["auto_pause_reason"]
# A failed probe leaves the lane paused but must not re-alert — otherwise the event stops