Repository navigation
feat(dispatcher): defer limit-blocked runs instead of dropping them - #756
Conversation
A burst of automations firing together (shared cron tick, webhook burst) could exceed the organization concurrency cap or the daily sandbox quota. The blocked runs were marked terminal SKIPPED, so event-triggered work was consumed with nothing to show and a missed cron fire never came back. Return those runs to the queue instead: - A run blocked by a transient limit goes back to PENDING with deferred_until set from a bounded exponential backoff; the dispatch poll skips a PENDING run whose deferred_until is still in the future. Past AUTOMATION_DEFER_MAX_AGE_SECONDS the run is SKIPPED with a defer_expired status_detail, so the outcome stays truthful. Setting the age to 0 restores the previous immediate-skip behavior. - AUTOMATION_MAX_CONCURRENT_RUNS caps runs in flight: the dispatcher admits only up to the cap per poll and leaves the rest PENDING (the table is the queue) until a slot frees. Unset preserves today's behavior. - automation_runs gains deferred_until + deferral_count (migration 038, single head, PostgreSQL and SQLite aligned). requeue is guarded by status == RUNNING so a run that already reached a terminal state is never resurrected, and cannot double-execute. Co-authored-by: openhands <openhands@all-hands.dev>
Address review findings on the deferral change: - Serialize the count-and-claim admission step across replicas with a transaction-scoped advisory lock, so two simultaneous polls cannot each admit the full apparent capacity under read-committed isolation. - Sweep-expire deferred runs past their max deferral age on every poll, independent of available capacity, so a run deferred behind a full cap is still reaped instead of sitting PENDING forever. - Raise DeferredRunRequeueError when the requeue write fails, so the caller records the failure and fails the run instead of stranding it as RUNNING with no sandbox. - Bound the retry backoff by the time left before the max deferral age, so a run near the deadline is not rescheduled to start after it. - Preserve the original limit reason (concurrency_limit/daily_sandbox_limit) when deferral is disabled, keeping status kinds and telemetry skip reasons unchanged. Co-authored-by: openhands <openhands@all-hands.dev>
…deferred runs The expiry sweep marked an aged deferred run SKIPPED without releasing its subject or emitting a skip event, so two gaps followed. A deferred run has no started_at (requeue_deferred_run clears it), so a terminal run that kept its subject still answered continue_conversation: the next event for that subject was folded into the SKIPPED run's payload and never dispatched. The sweep now stamps subject_released_at in the same guarded update that sets SKIPPED, keeping the terminal status and the subject release atomic. The sweep also ran on every poll, including one that finds every slot occupied and returns before the dispatcher's own skip handler, so those expirations were absent from telemetry. It now emits automation_run_skipped with skip_reason defer_expired for each row it actually updated, attributed to the run and its automation. The SELECT now returns the rows (with the automation eager-loaded) and the UPDATE returns the ids it matched, so events are emitted only for rows the guarded update really changed.
The capacity gate returns before the dispatcher's skip handler, so the sweep is the only emitter for a run expired while every slot is occupied. Assert the automation_run_skipped event with skip_reason defer_expired on that path, matching the reviewer's example.
…append order The serialization test compared an append-order list built by two concurrent tasks. The holder's post-commit append and the waiter's resume are both scheduled after the same lock release, so their order is not guaranteed and the assertion flaked (~1/5 runs). Assert the invariant under test instead: the second holder observes the first holder's release flag set, i.e. it could only acquire after the first released the lock. Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
|
📁 PR Artifacts Notice This PR adds or changes temporary PR-specific documents under |
|
Warning Your comment is too long (maximum is 65536 characters), so the coverage report was not added. See the job log for how to reduce it. |
|
@all-hands-bot Please review the latest head 90df40b. All CI checks are green and the branch merges cleanly with main. Before/after evidence is in the PR description. This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig. |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Scope and design context check out: this is automation-service dispatch/run-state work, squarely in this repository's ownership per AGENTS.md, implementing the bounded queue requested in #673 (labeled ready-for-dev), with a full design write-up in the description and .pr/issue-673/ evidence pinned to this head. Superseding #674 is fine — all six of its commits are carried unchanged.
Reviewed the diff at 90df40b against main (949c001) with the repository's run-state, capacity, and migration-parity checkpoints:
- No resurrection or double-execute path.
requeue_deferred_runis guarded bystatus == RUNNINGand clearsstarted_at/timeout_at/current_phase; terminal writes stay guarded inmark_run_terminal; the expiry sweep's guardedUPDATE ... RETURNINGbounds telemetry to rows actually transitioned. The subject release rides the same statement, closing thecontinue_conversationfold-into-dead-run gap (covered by the new routing test intest_conversations.py). - Admission gate is sound. The transaction-scoped advisory lock spans count-and-claim until commit, mirroring the existing
conversations.pypattern; SQLite skips it consistently with the rest of the codebase. Capacity counts RUNNING only, FIFO order and theSKIP LOCKEDclaim are unchanged, and the expiry sweep runs independently of capacity so aged deferred runs cannot sit behind a full cap. - Migration 038 is one coherent head (
038→037, verifiedalembic heads=038), PostgreSQL/SQLite-aligned column defaults, and a partial index matching the model.AutomationRunResponse.deferred_untilis additive. - Deferral stays bounded: backoff is capped by remaining time to the max-age deadline, expiry yields a distinct
defer_expireddetail, andAUTOMATION_DEFER_MAX_AGE_SECONDS=0restores the previous immediate-skip behavior with the original status kinds — existing consumers are unaffected. - Local static checks on the changed files are clean (
ruff check,ruff format --check,pyright). The full focused test suite could not run here (no Docker daemon for the testcontainers PostgreSQL), but CI on this exact head is green (unit-tests, ci/backend, windows-tests), and the new tests target every hardening item described.
No material correctness, security, or compatibility findings.
✅ APPROVED
|
🚀 Released in 1.33.0. |
…-enforcement-unlicensed-mode main (#756) now defers runs blocked by the concurrency and daily sandbox limits instead of skipping them. A license limit is not transient, so it is still skipped at once. - run_status_detail.py: keep both DEFER_EXPIRED and LICENSE_LIMIT. - test_dispatcher.py: keep main's test_quota_limit_defers_run_and_keeps_enabled as is, and cover the license limit in its own test, which also checks the run is not deferred.
…ation (#752) * feat(factories): add the Factory model and automation link Add a factories table and a nullable automations.factory_id, the factory CRUD API under /v1/factories, factory assignment through PATCH /v1/{id}, and a factory_id filter on GET /v1. Co-authored-by: openhands <openhands@all-hands.dev> * feat(worklogs): mint a worklog run token, add the factory lookup and delete notification Co-authored-by: openhands <openhands@all-hands.dev> * feat(worklogs): document the worklog contract and map the factory lookup Co-authored-by: openhands <openhands@all-hands.dev> * Address review: address factories by id, accept factory_id on create Drop the factory slug (column, unique index, derivation, 409, routes now use the id). Advertise `factories` in capabilities. Accept factory_id on POST /v1, /v1/plugin-spec, /v1/preset/prompt and /v1/preset/plugin through one shared authorize_factory_change helper also used by PATCH. Drafts store factory_id but their hidden test run does not carry it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Update F03 default capabilities check for the factories feature Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Fix F19 delete recipe to delete the recreated factory by its own id Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * docs: describe the run token, lookup and delete notification as factory-reference support Worklogs in Enterprise are the first consumer, not the purpose. Reword AGENTS.md, docstrings and a dispatcher comment accordingly. No behavior change; names, claims and paths are unchanged. Co-authored-by: openhands <openhands@all-hands.dev> * refactor(factories): make the run token and delete notification general purpose Nothing in them is specific to worklogs, which are only the first consumer. - AUTOMATION_WORKLOG_TOKEN -> AUTOMATION_FACTORY_TOKEN - aud 'worklog' -> 'factory'; HKDF info openhands-worklog-run-token-v1 -> openhands-factory-run-token-v1; test vector regenerated - utils/worklog.py -> utils/factory_token.py - delete notification: DELETE .../factories/{id}/worklogs -> POST .../factories/{id}/deleted; log messages reworded The contract with OpenHands/enterprise#1297 changes with it; that side is not merged yet. Co-authored-by: openhands <openhands@all-hands.dev> * Renumber factories migration to 039 after #756 took 038 * Address review: factory_id edge cases, drafts, locking - Template re-enable naming a factory the automation is not in is 409 instead of silently dropping factory_id. - PATCH checks manage_automations for factory_id only when it changes. - Any PATCH of an automation in a factory needs manage_automations. - Drafts and /v1/validate report factory_id_403/404 validation errors. - Assignment takes FOR KEY SHARE (SQLite: a no-op write) right before the write, so a rename is not blocked by a slow create. - Delete is one conditional DELETE, closing the SQLite delete-vs-assign race. - Lock mode is a Literal; FactoryUpdate subclasses FactoryCreate. Co-authored-by: openhands <openhands@all-hands.dev> * Renumber factories migration to 040 after main took 039 Co-authored-by: openhands <openhands@all-hands.dev> * Address review: keep drafts out of factories, dedupe create-side factory checks - PATCH refuses a factory change on a DRAFT-state automation (409), so a draft's hidden test run cannot hold a factory open or receive its token. - authorize_factory_for_create and a None-tolerant lock_factory_for_assignment leave one unconditional line per step in each create endpoint. - FACTORY_ID_DESCRIPTION replaces five pasted descriptions. - create_factory flushes like rename_factory; _count_live builds its own query. - Drop the unasserted outcomes set from the race test. - AGENTS.md: draft rule and the git-sync/plugin-ref trust boundary. Co-authored-by: openhands <openhands@all-hands.dev> * docs: state what the factory run token authorizes Co-authored-by: openhands <openhands@all-hands.dev> * fix(factories): configurable token lifetime, sturdier delete notification - Add AUTOMATION_FACTORY_TOKEN_TTL_SECONDS (default 24 hours, the shared contract) and an expires_in parameter on create_factory_token. Enterprise reads only exp, so operators can shorten it without a contract change. - notify_factory_deleted catches every exception, so its "never raises" docstring is true (closed client -> RuntimeError, malformed base URL -> httpx.InvalidURL). Both warnings now name the org, factory and URL. - AGENTS.md: note that a run can write under a deleted factory's id until the receiver's purge runs, and put service_router.py in order in the tree. Co-authored-by: openhands <openhands@all-hands.dev> --------- Co-authored-by: openhands <openhands@all-hands.dev> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Why
Fixes #673. Supersedes #674 (fork PR whose CI could not run without fork-workflow approval). All six commits from #674 are kept unchanged; this branch adds a merge of current
main(clean, migration038is still the single head) and before/after evidence under.pr/issue-673/.When many automations fire at once (several 5-minute cron schedules sharing a
timestamp, or a burst of webhook events), the runs that hit a limit are lost
rather than queued.
_execute_runmarked an organization concurrency-limit 429(
ConcurrencyLimitReachedError) or a daily-sandbox-quota 429(
DailySandboxLimitReachedError) as terminalSKIPPEDviamark_run_terminal.SKIPPEDis terminal, so the run is never retried: an event-triggered runconsumes its event with nothing to show, and a cron run misses its fire for a
whole interval.
This implements the bounded queue the issue asks for: a run that cannot start
now is deferred and started later instead of being dropped.
Summary
PENDINGwithdeferred_untilset from a bounded exponential backoff(
AUTOMATION_DEFER_BACKOFF_BASE_SECONDS, capped at the max age). The dispatchpoll skips a
PENDINGrun whosedeferred_untilis still in the future.AUTOMATION_DEFER_MAX_AGE_SECONDS(default 6h,measured from the run's creation) the run is marked
SKIPPEDwith adefer_expiredstatus_detail, distinct fromconcurrency_limit/daily_sandbox_limit, so the outcome stays truthful. Setting the age to0disables deferral and restores today's immediate-skip behavior.
AUTOMATION_MAX_CONCURRENT_RUNScaps runs in flight: thedispatcher admits only up to the cap per poll and leaves the rest
PENDING(the table is the queue) until a slot frees. Unset (
0) preserves today'sbehavior. Ordering stays FIFO by
created_at, unchanged from the current poll.automation_runsgainsdeferred_untilanddeferral_count(migration
038, one head, PostgreSQL and SQLite aligned). The requeue writeis guarded by
status == RUNNING, so a run that already reached a terminalstate (callback, cancel, watchdog) is never resurrected and cannot
double-execute.
deferral_countlives on the row becausestatus_detailiscleared when the run goes
RUNNING.automation_run_deferredtelemetry event with the retry timing, andan
automation_run_skippedevent withskip_reason: defer_expiredon expiry.AutomationRunResponsereturnsdeferred_untilso a client can show a queuedrun's retry time.
Hardening after review
A follow-up commit closes five gaps in the first pass, each with a test that
fails without the fix:
claiming rows under
SKIP LOCKEDlet two replicas read the same count underread-committed isolation and claim disjoint rows, so combined admissions could
exceed the cap. A transaction-scoped advisory lock
(
pg_advisory_xact_lock) now spans the count and the commit; SQLite, whichruns single-process, skips it (the same pattern as
conversations.py).a dispatch attempt, but a poll that finds every slot occupied returns before
claiming, so a deferred run could sit
PENDINGforever. An independent sweepnow expires aged deferred runs on every poll, regardless of free capacity.
requeue_deferred_runused to returnFalseon a write error, which thecaller could not tell apart from a lost terminal race, leaving the run
RUNNINGwith no sandbox until the watchdog. It now raisesDeferredRunRequeueError;Falsemeans only "the guarded update matched norow".
left before the max age (
max_age - age), not by the age limit itself, so arun near the deadline is not rescheduled to start after it.
0therun is skipped with its original
concurrency_limit/daily_sandbox_limitstatus kind and skip reason, so existing consumers are unchanged.
A second follow-up closes two gaps in the expiry sweep itself, also each with a
test that fails without the fix:
no
started_at(the requeue clears it), so a terminal run that kept itssubject still answered
continue_conversationand swallowed the next eventfor that subject into a run that would never dispatch. The sweep now stamps
subject_released_atin the same guardedUPDATEthat setsSKIPPED, so theterminal status and the release cannot be observed apart.
finds every slot occupied and returns before the dispatcher's own skip
handler, so those expirations were missing from telemetry. It now captures
automation_run_skippedwithskip_reason: defer_expiredfor each row theguarded update actually changed, attributed to the run and its automation
(the
SELECTreturns the rows with the automation eager-loaded, and theUPDATE ... RETURNING idbounds the events to rows really updated).How to Test
uv run python -m pytest tests/— full suite passes (2444 passed, 7 skipped).New unit tests cover the capacity gate (admit up to capacity, count existing
RUNNING, empty at capacity, deferred runs excluded then eligible after
deferred_until), defer/requeue (returns to PENDING, clearsstarted_at/timeout_at, is idempotent, never resurrects a terminal run),backoff progression and its deadline bound, deadline expiry (including the
capacity-independent sweep, subject release, and the skip event), the
cross-replica admission lock, the failed-requeue path, and
count_running_runs.An end-to-end routing test in
test_conversations.pyreproduces the swallow:an expired deferred run releases its subject, so the next thread event starts a
fresh run instead of folding into the dead one.
uv run ruff check,uv run ruff format --checkanduv run pyrighton thechanged files are clean. Migration 038 verified as the single Alembic head.
Re-run on this branch after merging
main: full suite 3011 passed, 7 skipped (the only failures in a parallel-n 8run were container read timeouts and tests needingcaplog, which pass when re-run).Before / after
.pr/issue-673/demo_673.pydrives the realdispatch_pending_runs/_execute_runagainst Postgres: five cron runs are due in one tick, and a fake sandbox API admits two concurrent sandboxes and answers the rest with the org concurrency-limit 429. A sandbox's completion callback arrives two dispatcher passes after it starts.On
main, 3 of 5 runs areSKIPPEDfor good on the first pass. On this branch they are deferred with backoff (automation_run_deferred) and all 5 complete. WithAUTOMATION_MAX_CONCURRENT_RUNS=2the gate keeps the extra runsPENDING, so the sandbox API never returns a 429.Notes
issue. A permanent failure still marks the run
FAILEDunchanged.overlap guards (Add a minimal per-automation overlap guard (skip when a run is already in-flight) #218), hierarchical admission limits (Implement hierarchical concurrency limits for automation runs #72), event-inflow
backpressure (Implement event queue management with backpressure strategies #74), and Canvas UI work (#18576) — this ships the service-side
signal only.
defer_expireddistinction matters for operators:concurrency_limit/daily_sandbox_limitnow mean "waiting to retry", whiledefer_expiredmeans"gave up after the deadline".
This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig.