Skip to content

fix(wake): one wake per caller at a time, and a wake refused at capacity is parked (#4733, #4734) - #4745

Merged
vybe merged 5 commits into
devfrom
feature/4733-wake-hold-per-caller
Nov 24, 2026
Merged

vybe merged 5 commits into
devfrom
feature/4733-wake-hold-per-caller

Conversation

@webmixgamer

@webmixgamer webmixgamer commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Changes

  • src/backend/services/caller_wake_service.py — the hold (_hold_key, _claim_hold, _wake_live, _caller_busy, _release_hold_of), the fold skew in _covered, the capacity park (_has_free_slot, _park_at_capacity, _drain_if_idle, _refused_for_a_slot), module text. The window key, _bucket_for, _follow_on_key and maybe_wake_caller(_key=) are gone.
  • src/backend/services/chat_execution_service.py — run_chat_turn's finally and release_admission call caller_wake_service.drain_after_slot_release after the slot is released.
  • src/backend/db/idempotency.py, src/backend/database.py, src/backend/services/idempotency_service.py — a read-only peek beside claim (the DB half refactor(reliability): read-only idempotency lookup — one deterministic answer to 'which execution is mine?', retiring the per-route timeout heuristic #2671 asks for; that issue's endpoint stays with it).
  • src/backend/db/schedules/executions.py, src/backend/database.py — has_execution_with_status (one indexed EXISTS).
  • scripts/ci/sync_on_loop_baseline.json — caller_wake_service.py 4 → 6, accepted by name (see Test Plan).
  • Tests: new tests/unit/test_4733_wake_hold.py; test_4536_wake_window.py, test_ent1102_caller_wake.py, test_4357_wake_chain_depth.py, test_ent1216_wake_turn_reads.py updated for the hold; tests/registry.json.
  • Docs: docs/user-docs/collaboration/agent-network.md, docs/user-docs/faq/collaboration.md, docs/memory/requirements/core-agent.md, docs/memory/feature-flows/agent-to-agent-collaboration.md, docs/memory/architecture/execution.md (the /chat exception), learnings fragment docs/memory/learnings/2026-11-23-terminal-fanout-is-not-every-release-path.md.

No DB migration on either track. No frontend, docker/ or base-image change. No .env, compose or system_settings key changes meaning.

Journey Impact

Journey Impact: none: the caller wake's scheduling and its docs; J10's invariants (permission edge, attribution, cascade, fan-out and loop bounds, depth) are unchanged

Test Plan

  • cd tests && pytest unit/test_4733_wake_hold.py -v — 30 tests. Red on the base commit for the reported defect (AssertionError: 3 wake turns were running at once for one caller), the later-window fold, the back-dated ending, the capacity park and its delivery, and the timed-out holder.
  • Mutation battery, 12 of 12 red (each part of the fix reverted from a scratch copy, restored byte-identical): window key restored, no wake-row release, started_at in the release rule, no live-row check, no slot check, no run-end drain, no fold skew, no stale reclaim, the holder draining the refused ending, a pilot refusal parked, a full meter trusted, an unreclaimable stale hold kept. Review fixes, 4 of 4 red: no /chat drain in run_chat_turn, drain_after_slot_release a no-op, no race re-check, a drained ending folding.
  • The ten wake suites (4733, 4536, ent1102, 4357, ent1216, ent1225, 4442, ent1236, 2048, 1920), test_chat_admission.py, the ratchet and the registry reader: 421 passed after merging dev and the review fixes.
  • Full unit run: the failures that remain on this machine are identical with the base commit's source (memory/live-connection/client-ip/hook suites; none touches the wake).
  • test_4674_sync_on_loop_ratchet.py (landed on dev after this branch was cut). Seven of the nine new blocking reads are off the loop (asyncio.to_thread): the slot check, the three park/drain re-checks, the wake row's release and the race-park check. Two are accepted by name (--allow-growth, baseline 4 → 6): maybe_wake_caller's hold claim and its live-row read. Both sit before the dispatch beside the claim that was already synchronous (_begin_idempotency, uncounted only because it lives one module down); moving them alone would not take the wake path off the loop and would reorder the bug(wake): a fast callee's ending is dropped by the 15 s wake window, so a delegate→wake loop stalls silently #4536 harness.
  • Eyeball on localhost (recipe below): both scenarios pass (on 7942a7b05; the later commits move reads to threads and add the /chat drain, both covered by the tests above).
  • CI.

Eyeball recipe (localhost)

This branch must be what serves localhost:8000. Fixtures: two running agents, boss and worker, and:

  • an agent_permissions link from boss to worker (boss → Permissions tab), needed even when one person owns both;
  • a standing rule in boss's CLAUDE.md: "Whenever you are woken for a result, run python3 -c "import time; time.sleep(60)" before you answer." A wake turn does not get the delegating turn's instructions, so this cannot go in the chat message. (Claude Code refuses a bare sleep N; use the Python form.)
  • the wake on (default: Settings › Guardrails › Reliability › Wake this agent when its asks end).
  1. One wake at a time. In boss's Chat tab send: "Use chat_with_agent with async=true to send worker three messages: 'Run python3 -c "import time; time.sleep(20)", then reply done 1', the same for done 2 and done 3. Then end your turn." Open /operations?tab=executions, set All agents to boss, watch the caller_wake rows. Expect at most one running caller_wake at a time; endings 2 and 3 audited parked; exactly one follow-on, naming the newest ending.
  2. At capacity. Set boss → Settings › General › Parallel capacity to 1. In boss's Chat send: "Use chat_with_agent async=true to ask worker 'Run python3 -c "import time; time.sleep(10)", then reply done'. Then run python3 -c "import time; time.sleep(90)" and reply 'finished'." Expect no caller_wake row when worker ends (before: a FAILED row, Agent at capacity (1/1 parallel tasks running)); an audit parked row with "reason": "at_capacity"; the wake starts when boss's turn ends. Reset Parallel capacity afterwards.

Stated limits

  • A wake can still run beside the turn that delegated it: that is bug(wake): a sync agent-to-agent call still wakes the caller, billing a second turn for an answer it already has #4538's case, ruled there (wake: false).
  • An answer wake (operator_response) is a separate producer and can run beside a caller wake.
  • The parked marker keeps only the latest ending; the others are in list_recent_executions, which is narrowed while a shared person's or a visitor's turn runs (Agent cannot read a child execution it started during a share holder's turn (404 Execution not found) #4173).
  • A wake that delegates again still multiplies turns; chain depth and the hourly per-pair budget bound it.
  • A refusal that races the slot check leaves one FAILED caller_wake row (its ending is still parked).
  • While the caller is at capacity every ending is parked and audited on its own (one parked row each, as behind a running wake).
  • An ending folded into a claim that then dispatches nothing (a budget cap, a dispatch error) is not woken (as before this PR; a drained ending never folds).
  • An ending parked when no wake or run of the caller is left to end (a clean stop inside the 120 s grace, then nothing) is delivered by the caller's next run end or next ending, or not at all within the 24 h marker TTL.
  • A claim that fails on a DB error, or a stale hold that cannot be reclaimed, wakes without the hold (fail-open).

Notes for review

  • Conflict with fix(wake): a wake turn knows the conversation that delegated and replies into it (#4537) #4606 (open): it inserts a line in the wake-row branch of maybe_wake_caller and lines += conversation in _framed_wake (this PR edits the next line, the frame's "around the same time"), a bullet between the two agent-network.md bullets rewritten here, and a feature-flow item 10 after item 9. Whoever merges second keeps both edits.
  • Review round (independent reviewer): a push /chat never drained a parked wake (fixed: the slot-release drain), the race park had no re-check after its SET (fixed), a drained ending could fold into a claim that never dispatched (fixed), five doc sentences (fixed).
  • test_4536_wake_window.py: the later-window test pinned the defect (Z's own wake started beside H and drained Y) and is rewritten to the new rule; two tests now expect an ending after a wake row's terminal to wake at once, because that terminal frees its own hold. The harness's dispatch now marks its row terminal before returning, as dispatch_and_await_terminal does.
  • test_4357_wake_chain_depth.py / test_ent1216_wake_turn_reads.py already stub the claim out ("the storm bound has its own tests"); they now stub the hold's live-row read and the slot check the same way, because their wake rows stay RUNNING on purpose.

Fixes #4733
Fixes #4734

🤖 Generated with Claude Code

webmixgamer and others added 3 commits November 23, 2026 16:48
…ity is parked (#4733, #4734)

The caller wake was keyed caller_wake:{caller}:{now // 15}, and the #4536 park
ran only when that key replayed in flight. A wake turn outlives its 15 s
window, so an ending in a later window claimed a new key and started a second
wake beside the first (reproduced: three wake turns running at once; seen live
as four wake turns for one scheduled run).

- Every wake, a first ending's and a drained one's, now claims one hold per
  caller, caller_wake:{caller}:running, in place of the window key and the
  follow-on key. An ending while the caller is held folds into the running
  wake when it ended by that wake's claim and arrived within 15 s of ending;
  otherwise it is parked and delivered once when the wake ends.
- The hold is read from the rows: the caller is held while a caller_wake row
  of it is queued, running or pending a retry, or while a claim is younger
  than 120 s. An older claim with no live row is reclaimed by its owner
  token. A clean backend stop cancels the holder and writes the wake row
  FAILED with no terminal fan-out, so a release at the terminal alone would
  have held the caller for about 65 minutes after every deploy. A wake row's
  terminal still frees its own hold (claimed at or before the row's
  admission, queued_at over a re-stamped started_at), never a later wake's.
  A stale hold that cannot be reclaimed wakes without it instead of looping.
- At capacity (product ruling on #4733): with every slot taken and a run of
  the caller running, no wake row is written. The ending is parked
  (audit parked, reason at_capacity) and delivered when any run of the caller
  ends. A full meter with no running run, a pull pilot, or an unreadable meter
  dispatches as before. A refusal that races the check is the one FAILED row
  left; its ending is parked too, except on a pilot.
- New read-only idempotency peek (db + facade + service, the DB half #2671
  asks for) and db.has_execution_with_status.
- Docs (#4734): the module text, requirements, the collaboration flow, the
  Agent Network section and the FAQ state the rule as built, say a wake stands
  as the turn that delegated, and say a wake's reads are narrowed while a
  shared person's or a visitor's turn runs (#4173).

Tests: tests/unit/test_4733_wake_hold.py (26). Red on the base commit for the
reported defect ("3 wake turns were running at once for one caller"), the
later-window fold, the back-dated ending, the capacity park and its delivery,
and the timed-out holder. Mutation battery, 12 of 12 red: window key restored,
no wake-row release, started_at in the release rule, no live-row check, no
slot check, no run-end drain, no fold skew, no stale reclaim, holder drains
the refused ending, pilot refusal parked, full meter trusted, unreclaimable
stale hold kept. The #4536, ent1102, 4357 and ent1216 suites are updated for
the hold (the later-window test there pinned the defect).

Fixes #4733
Fixes #4734

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sync-on-loop ratchet (#4674) reached dev after this branch was cut and
counts a sync db read inside `async def`, directly or one helper down. Seven
of the nine reads the hold added now run in `asyncio.to_thread`: the slot
check, the park and drain re-checks, the wake row's release and the
race-park check.

Two stay on the loop and are accepted by name (baseline 4 -> 6):
maybe_wake_caller's hold claim and its live-row read. Both run before the
dispatch beside the claim that was already synchronous (_begin_idempotency,
uncounted only because it sits one module down), so moving them alone would
not take the wake path off the loop, and it would reorder the #4536 harness.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…(review of #4745)

Review findings, each with a test that fails without its fix:

- A push /chat writes its terminal without the fan-out, so a wake parked
  for a free slot behind a /chat turn was never drained when that turn
  ended. run_chat_turn's finally (and release_admission) now call
  caller_wake_service.drain_after_slot_release right after the slot is
  released; a test drives the real finally.
- The race park (admission refused after the slot check passed) now
  re-checks the slot once after its SET, so a busy run that ended in
  between does not strand the ending.
- A drained ending never folds into a claim that may yet not dispatch (a
  budget cap, a dispatch error); it parks.
- Docs: the /chat drain in the module text, requirements, the flow and
  architecture/execution.md; "a slot no run holds" instead of "expired
  slots"; the race exception and "none for a visitor" in the user docs; the
  wake frame says "around the same time", not "in the same window". Stated
  limits: one parked audit per ending at capacity; an ending folded into a
  claim that dispatches nothing is not woken.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vybe

vybe commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-24): on this train. Validated at 9cdeb72e0, and the review-fix commit re-validated at b6f30c47c; no critical findings.

Train decision, ruled by the operator at Gate 1 on 2026-11-24: the sync-on-loop baseline growth for caller_wake_service.py (4 → 6, total 1921) is accepted. Please acknowledge after merge.

Nothing was pushed to this branch. This PR and #4606 both edit docs/user-docs/collaboration/agent-network.md; whichever merges second gets one dev merge from the train that keeps both bullets. On the two heads merged together the wake suites of both PRs pass (172 tests).

Follow-ups, none blocking:

  • The release_admission hand-off is unpinned (chat_execution_service.py:171). Deleting the drain_after_slot_release call there leaves the suite green; the run_chat_turn one at :1290 is pinned.
  • A drained wake can still land before the ended run's slot is released. The release is in execute_task's finally; if admission refuses, _refused_for_a_slot (caller_wake_service.py:959 at 9cdeb72e0) sees no running run and leaves a FAILED row without re-parking. Read from code, not reproduced.
  • A possible repeat loop when the meter cannot be read. _has_free_slot answers "free" then; if admission refuses for capacity at the same time, _deliver_if_a_slot_freed retries, and each pass writes a FAILED caller_wake row and spends a budget unit until the hourly budget stops it. Read from code, not reproduced.
  • A /chat turn cancelled at backend shutdown can lose the parked marker: the finally spawns the drain on a stopping loop, and a GETDEL with no follow-on leaves nothing to deliver. Read from code, not reproduced.
  • The two terminate paths (release_if_matches at chat_execution_service.py:3533 and :3743) do not call the drain.

@vybe

vybe commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

merge-train: merged dev into this branch after #4606 landed. One conflict, in docs/user-docs/collaboration/agent-network.md: both PRs rewrote the Wake on Ending bullets. Kept this PR's three bullets and #4606's "It knows what it was asked, and answers where it was asked" between the first and second. No code conflict. New head bbb83e07c; the tree matches the tested train plus #4749.

@vybe vybe 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.

merge-train: batch validated on train/20261124-0752

@vybe
vybe merged commit 65a2fa5 into dev Nov 24, 2026
27 checks passed
@webmixgamer

Copy link
Copy Markdown
Contributor Author

Acknowledged, thanks. The sync-on-loop count for caller_wake_service.py went from 4 to 6 with this PR. Both new sites are in maybe_wake_caller, on the path that runs when a delegated run ends:

  • _claim_hold claims the caller's hold (one idempotency_keys row).
  • _wake_live checks whether a caller_wake row of that caller is still queued or running.

They are the same kind of single-row DB call as the four already there.

I'll take the five follow-ups above into #4538, which is the next change to this file. Each one gets a failing test first, and a fix only if the test reproduces it; what doesn't reproduce is written down as a stated limit. In the same change I'll look at moving the wake path's DB calls off the event loop, which would bring the count back down.

@webmixgamer
webmixgamer deleted the feature/4733-wake-hold-per-caller branch November 24, 2026 12:37
vybe pushed a commit that referenced this pull request Nov 26, 2026
…ts wake (#4538) (#4766)

* fix(wake): a caller that waits is not woken, and a call can decline its wake (#4538)

The caller wake is for a caller that got a receipt. It also fired for a
caller that held the call open and already had the answer, and a caller
that polled in its own turn could not decline it.

A call now says so itself, and the dispatch records it for the callee
row ("call terms": an idempotency row keyed on the callee execution id,
so no column and no migration):

- `wake: false` on POST /task and /chat, and on the `wake` parameter of
  `chat_with_agent` and every `chat_with_<agent>` tool, starts no wake
  when that run ends. The receipt answers
  `wake_on_ending: {effective: false, source: "call"}`, which the MCP
  server prints as `wake: "none"`, `wake_reason: "caller_declined"`.
- `caller_wait_ms` says how long a sync caller waits (the MCP server
  sends its own ceiling). A run that ends 5 s or more before that
  deadline was answered inline and wakes nobody; one that outlives it
  keeps its wake. A backend handler that gives up first moves the
  deadline before it re-reads the row.

Only positive evidence stands a wake down: a call that declares
neither, and terms that are missing, unreadable, half-written or
unparsable, wake as before. `wake` stays out of the MCP idempotency key.

Behind a wake parked for a free slot (the #4745 follow-ups), each with
a test that failed first:

- every slot release now drains the parked wake, after the backlog
  drain, from the release callback CapacityManager registers. That
  covers a terminate, a cleanup release and a run whose terminal lands
  before its own `finally` releases the slot;
- a wake refused with no run of the caller left running is parked again
  instead of ending as a FAILED row;
- after a capacity park the ending is dispatched again only when the
  meter was read and shows a free slot. An unreadable meter looped
  refused wakes until the hourly budget ran out (120 FAILED rows for
  one ending in the test);
- a delivery cancelled before it holds the caller puts its marker back;
- `release_admission`'s release-then-drain is pinned.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* refactor(wake): the wake hook's database calls run off the event loop (#4538, #4674)

`maybe_wake_caller` runs for every terminal, and a cleanup sweep runs it
hundreds of times in one cycle. Its row read, subscription read, hold
claim, live-wake read, pending-ask read and standing-depth read were
written directly inside `async def`, so each one blocked the worker.
They go through `asyncio.to_thread` now.

The sync-on-loop baseline entry for caller_wake_service.py goes from 6
to none (regenerated with `check_sync_on_loop.py --write`). A row that
cannot be read is logged at warning: it is an ending nobody is woken
for.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* docs(wake): the per-call wake opt-out and the slot-release drain (#4538)

Feature flow step 11 (call terms: carried, stamped, kept, read,
re-opened, receipt), the slot-release drain in step 9, the requirement
for every slot release delivering a parked wake, the execution
architecture note, and the user docs: `wake: false`, `caller_declined`,
no wake after an inline answer, and what a plain REST sync caller has
to send.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* fix(wake): review round — a 10 s inline margin, drains for the removals that fire no callback, a later claim mark (#4538)

From the pre-landing review, each with a test that failed first:

- The inline margin was 5 s, the same as the sync waiter's database
  poll: a run ending on another worker could be stood down as "answered
  inline" while its reply left after the caller gave up. It is 10 s,
  and a test pins it at the poll plus 5 s or more.
- The stale-slot reclaim and `force_release` remove slots without the
  release callback, so they drain a parked wake themselves, under the
  same guard.
- The release drain takes the marker only when the meter shows a free
  slot. The callback also fires for the backlog's sentinel swap, which
  frees nothing, and re-ran the whole hook on every such release.
- A delivery's claim is marked at the dispatch, not at the hold: a
  cancel during the budget check or the reads before the wake row
  exists puts the ending back.

Tests: the time-based ones run on a frozen clock; the terms-write
failure test now proves the write was attempted and that the wake
fires; the real-thread tests assert what they name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

* docs(api): the `wake` and `caller_wait_ms` task fields, and the wake note on chat_with_agent (#4538)

Co-Authored-By: Claude Fable 5.2 <[email protected]>

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants