: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
from __future__ import annotations
from products.signals.backend.constants import DEFAULT_MAX_RUNTIME_S
TRIGGERED_BY_ONBOARDING = "onboarding"
# Task teardown can wait up to 15 minutes for spend settlement after the agent stops.
ACTIVITY_SLACK_S = 15 * 60 + 60
WORKFLOW_HARD_CEILING_S = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S
# Leave a margin beyond the activity timeout before reaping an unfinished run.
STALE_RUN_CUTOFF_S = 2 * WORKFLOW_HARD_CEILING_S
# How many of a lane's newest runs the self-heal checks for orphans. An orphan is a run stuck in
# `QUEUED`/`IN_PROGRESS`, or a run that the Tasks inactivity timeout closed after a worker death,
# which is no longer stuck, only unreported. Every dispatch of the lane runs the self-heal first, so
# the orphan is one of the newest runs at the next dispatch. The bound is a run count and not an
# age, because an age window expires before a 30-day interval, a monthly cron, or a paused lane
# dispatches again. The count also keeps the per-dispatch scan to a short read of the
# `(team, skill_name, -created_at)` index.
ORPHAN_RECENT_RUNS = 10
# Bridge-row `metadata` key the self-heal stamps when it reports a run that the Tasks inactivity
# timeout closed. It makes the reap a one-time claim, so a later dispatch does not report it again.
SCOUT_RUN_REAPED_METADATA_KEY = "reaped_at"
# Cap on the one-off steering note an on-demand ("Run now") dispatch carries. It renders verbatim
# into that run's prompt, so it is held to the 1,000 characters `report_steering` cuts a durable
# note to: steering meant for one run must not crowd out the run's own instructions.
MAX_RUN_NOTE_CHARS = 1_000
# Cap on the pre-check rows a scheduled run carries into its prompt. The rows are raw product data
# the scout owner's query selected, so they must not crowd out the run's own instructions.
MAX_PRECHECK_ROWS_BYTES = 8 * 1024
SCOUT_TRIAL_METADATA_KEY = "scout_trial"
TRIAL_MAX_RUNTIME_S = 30 * 60
# Poll budgets count sleeps, excluding startup and I/O; keep that overhead separate from cleanup time.
TRIAL_RUNTIME_OVERHEAD_S = 5 * 60
TRIAL_ACTIVITY_TIMEOUT_S = TRIAL_MAX_RUNTIME_S + TRIAL_RUNTIME_OVERHEAD_S + ACTIVITY_SLACK_S
# Time a trial scout activity can wait in the task queue before it starts.
TRIAL_QUEUE_ALLOWANCE_MINUTES = 19
# How long a comparison waits for its scout runs. The activity timeout does not include queue time.
TRIAL_SCOUT_WAIT_MINUTES = TRIAL_ACTIVITY_TIMEOUT_S // 60 + TRIAL_QUEUE_ALLOWANCE_MINUTES
MAX_TRIAL_VARIANTS = 20
MAX_TRIAL_REPEATS = 20
MAX_TRIAL_RUNS = MAX_TRIAL_VARIANTS * MAX_TRIAL_REPEATS
TRIAL_JUDGE_CONCURRENCY = 3
TRIAL_JUDGE_TIMEOUT_MINUTES = 33
# Leave time to load evidence and save the report after every judging wave.
TRIAL_EVALUATION_TIMEOUT_MINUTES = -(-MAX_TRIAL_RUNS // TRIAL_JUDGE_CONCURRENCY) * TRIAL_JUDGE_TIMEOUT_MINUTES + 10
# Consecutive failed runs after which a scout config trips its circuit breaker and is
# auto-paused (`SignalScoutConfig.auto_paused_at`). Nothing else in the harness notices a
# 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), 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
DISPATCH_SMEAR_SECONDS = 600
DISPATCH_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 = 200
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
# the model can't work through) usually gets fixed without anyone thinking to un-pause a
# scout, so the breaker has to re-test itself. A successful probe resumes the lane; a failed
# one restarts the cooldown through its own `last_run_at` stamp. Set to a day so a wedged
# lane costs one lease per day instead of one per interval. Deliberately independent of the
# scout's own schedule: for a scout on a slower-than-daily cadence the probe IS more frequent
# than its healthy schedule, which trades at most one lease per day for recovery within a day
# rather than up to a full (possibly 30-day) interval after the underlying cause is fixed.
AUTO_PAUSE_PROBE_INTERVAL_S = 24 * 60 * 60
# How a run was dispatched, carried on `RunSignalsScoutInput.triggered_by` and stamped onto
# `SignalScoutRun.metadata` for anything but the schedule (absence means "schedule", matching how
# the rest of that blob omits default-path keys). Only `schedule` failures feed the failure-streak
# breaker — the threshold is sized on the schedule's cadence, so off-schedule runs must not count.
TRIGGERED_BY_SCHEDULE = "schedule"
TRIGGERED_BY_MANUAL = "manual"
TRIGGERED_BY_WORKFLOW = "workflow"
# A report check the coordinator dispatched (`report_check_agent`). It is a fourth source rather
# than a flavour of `schedule` because the check owns the clock: the scout's own cadence decides
# nothing about it, so it must not stamp `last_run_at` and its failures must not size a breaker
# threshold derived from that cadence.
TRIGGERED_BY_CHECK = "check"
TRIGGERED_BY_MONITORING = "monitoring"
# Minimum gap between two workflow-triggered runs of the same (team, skill), enforced scout-side.
# The workflow layer has its own first line of defence (trigger masking), but that lives in
# customer-editable config, so this backstop deliberately does not trust it: an event trigger on a
# high-volume event would otherwise fire hundreds of times an hour. 30 minutes is the floor the
# system already applies to `run_interval_minutes` for the same worker-pool reason, and it bounds
# the workflow path at 48 runs/day/skill regardless of how the workflow is configured. Suppressed
# fires are dropped, not queued — there is deliberately no trailing-edge coalescing.
WORKFLOW_RUN_COOLDOWN_S = 30 * 60
# Per-team ceiling on ENABLED scout configs — the per-team cost cap. Each enabled scout
# is a recurring LLM sandbox run, so this bounds what one team can switch on. Set high so
# teams can freely author scouts with minimal friction; it's a backstop against runaway
# spend, not a routine limit (the canonical fleet is ~16 scouts). Enforced at the write
# surfaces (config create/update) and in auto-registration, which falls back to registering
# new scouts disabled once the team is at the cap.
#
# This is the LAST-RESORT default, like the run budgets beside it. The effective ceiling
# resolves most-specific-first through `team_limits.resolve_max_enabled_scouts`: a project's
# `team_configs` entry → the fleet-wide `default_team_config` → this constant, all under the
# `max_enabled_scouts` key of the `signals-scout` flag payload. A project that needs more
# capacity gets it in the flag UI, with no deploy.
MAX_ENABLED_SCOUTS_PER_TEAM = 250