Skip to content

feat(dispatcher): defer limit-blocked runs instead of dropping them - #756

Merged
neubig merged 8 commits into
mainfrom
feat/defer-limit-blocked-runs
Nov 16, 2026
Merged

neubig merged 8 commits into
mainfrom
feat/defer-limit-blocked-runs

Conversation

@neubig

@neubig neubig commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

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, migration 038 is 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_run marked an organization concurrency-limit 429
(ConcurrencyLimitReachedError) or a daily-sandbox-quota 429
(DailySandboxLimitReachedError) as terminal SKIPPED via mark_run_terminal.
SKIPPED is terminal, so the run is never retried: an event-triggered run
consumes 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

  • Defer instead of drop. A run blocked by a transient limit returns to
    PENDING with deferred_until set from a bounded exponential backoff
    (AUTOMATION_DEFER_BACKOFF_BASE_SECONDS, capped at the max age). The dispatch
    poll skips a PENDING run whose deferred_until is still in the future.
  • Bounded deferral. Past AUTOMATION_DEFER_MAX_AGE_SECONDS (default 6h,
    measured from the run's creation) the run is marked SKIPPED with a
    defer_expired status_detail, distinct from concurrency_limit /
    daily_sandbox_limit, so the outcome stays truthful. Setting the age to 0
    disables deferral and restores today's immediate-skip behavior.
  • Admission gate. 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 (0) preserves today's
    behavior. Ordering stays FIFO by created_at, unchanged from the current poll.
  • Schema. automation_runs gains deferred_until and deferral_count
    (migration 038, one head, PostgreSQL and SQLite aligned). The requeue write
    is guarded by status == RUNNING, so a run that already reached a terminal
    state (callback, cancel, watchdog) is never resurrected and cannot
    double-execute. deferral_count lives on the row because status_detail is
    cleared when the run goes RUNNING.
  • Emits an automation_run_deferred telemetry event with the retry timing, and
    an automation_run_skipped event with skip_reason: defer_expired on expiry.
  • AutomationRunResponse returns deferred_until so a client can show a queued
    run'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:

  • Admission is serialized across replicas. Counting RUNNING and then
    claiming rows under SKIP LOCKED let two replicas read the same count under
    read-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, which
    runs single-process, skips it (the same pattern as conversations.py).
  • Aged deferred runs are reaped even at capacity. Expiry used to run only on
    a dispatch attempt, but a poll that finds every slot occupied returns before
    claiming, so a deferred run could sit PENDING forever. An independent sweep
    now expires aged deferred runs on every poll, regardless of free capacity.
  • A failed requeue write fails the run instead of stranding it.
    requeue_deferred_run used to return False on a write error, which the
    caller could not tell apart from a lost terminal race, leaving the run
    RUNNING with no sandbox until the watchdog. It now raises
    DeferredRunRequeueError; False means only "the guarded update matched no
    row".
  • Backoff cannot overshoot the deadline. The delay is bounded by the time
    left before the max age (max_age - age), not by the age limit itself, so a
    run near the deadline is not rescheduled to start after it.
  • Disabling deferral keeps the original reason. With the max age at 0 the
    run is skipped with its original concurrency_limit / daily_sandbox_limit
    status 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:

  • Expiring a subject run releases its subject atomically. A deferred run has
    no started_at (the requeue clears it), so a terminal run that kept its
    subject still answered continue_conversation and swallowed the next event
    for that subject into a run that would never dispatch. The sweep now stamps
    subject_released_at in the same guarded UPDATE that sets SKIPPED, so the
    terminal status and the release cannot be observed apart.
  • The sweep emits the skip event. It runs on every poll, including one that
    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_skipped with skip_reason: defer_expired for each row the
    guarded update actually changed, attributed to the run and its automation
    (the SELECT returns the rows with the automation eager-loaded, and the
    UPDATE ... RETURNING id bounds 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, clears
started_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.py reproduces 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 --check and uv run pyright on the
changed 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 8 run were container read timeouts and tests needing caplog, which pass when re-run).

Before / after

.pr/issue-673/demo_673.py drives the real dispatch_pending_runs / _execute_run against 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.

Before (main 949c001) After (this PR)
before after

On main, 3 of 5 runs are SKIPPED for good on the first pass. On this branch they are deferred with backoff (automation_run_deferred) and all 5 complete. With AUTOMATION_MAX_CONCURRENT_RUNS=2 the gate keeps the extra runs PENDING, so the sandbox API never returns a 429.

Notes

This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig.

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>
@github-actions

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR adds or changes temporary PR-specific documents under .pr/. They stay on this branch for review. After this PR merges, the next release PR removes them from main.

@github-actions github-actions Bot added the type: feat A new feature label Nov 13, 2026
@neubig
neubig requested a review from all-hands-bot November 13, 2026 23:55
@github-actions

Copy link
Copy Markdown
Contributor

Coverage

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.

@neubig

neubig commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

@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 all-hands-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_run is guarded by status == RUNNING and clears started_at/timeout_at/current_phase; terminal writes stay guarded in mark_run_terminal; the expiry sweep's guarded UPDATE ... RETURNING bounds telemetry to rows actually transitioned. The subject release rides the same statement, closing the continue_conversation fold-into-dead-run gap (covered by the new routing test in test_conversations.py).
  • Admission gate is sound. The transaction-scoped advisory lock spans count-and-claim until commit, mirroring the existing conversations.py pattern; SQLite skips it consistently with the rest of the codebase. Capacity counts RUNNING only, FIFO order and the SKIP LOCKED claim 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, verified alembic heads = 038), PostgreSQL/SQLite-aligned column defaults, and a partial index matching the model. AutomationRunResponse.deferred_until is additive.
  • Deferral stays bounded: backoff is capped by remaining time to the max-age deadline, expiry yields a distinct defer_expired detail, and AUTOMATION_DEFER_MAX_AGE_SECONDS=0 restores 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

@neubig
neubig merged commit af3ab78 into main Nov 16, 2026
13 checks passed
@openhands-release-bot openhands-release-bot Bot added the released: 1.33.0 Shipped in 1.33.0 label Nov 17, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.33.0.

hieptl added a commit that referenced this pull request Nov 18, 2026
…-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.
VascoSch92 pushed a commit that referenced this pull request Nov 19, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released: 1.33.0 Shipped in 1.33.0 type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Defer (queue) automation runs blocked by a concurrency/quota limit instead of dropping them as terminal SKIPPED

3 participants