Repository navigation
fix(wake): park an ending that collides with a running wake's window (#4536) - #4545
Conversation
…4536) A delegate->wake loop with a callee faster than 15 s stalled after a few rounds: the callee's ending landed in the window its own wake had claimed and was dropped as "already woken in this window". - A wake releases its 15 s window when it ends, so an ending after a finished wake wakes at once. - An ending that hits a window whose wake still runs collapses into it only if the run ended at or before the wake's claim (the sweep storm bound is kept). Otherwise it is parked in Redis (trinity:wake_missed:{caller}, 24 h, audited `parked`) and delivered once when the wake ends, on the follow-on key caller_wake:{caller}:after:{wake_id}, drained from the wake row's own terminal and from the holder after it releases. - Redis trouble on the park is audited `skipped_window`, never raised. Tests: tests/unit/test_4536_wake_window.py against the real idempotency claim and fakeredis. Red with the fix absent (5 of 6, the sweep guard green on HEAD). Mutations each turn a test red: no terminal drain (in-flight + follow-on tests), no holder drain (parked-after-terminal), no coverage rule (sweep), no re-check after park (holder-releases race). Fixes #4536 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…caused (#4536) Co-Authored-By: Claude Opus 5.5 <[email protected]>
/review + /validate-pr — REQUEST CHANGES (head
|
| changed symbol | executed by | live consumer | verdict |
|---|---|---|---|
maybe_wake_caller (new wake-row branch, replay branch, finally drain) |
all 7 tests in tests/unit/test_4536_wake_window.py |
src/backend/services/event_dispatch_service.py:672 (every terminal fan-out) |
executed |
release on wake end (_claimed_wake, caller_wake_service.py:687-690) |
test_a_fast_delegate_wake_loop_gets_every_round |
same call chain | executed, red when removed |
_park + re-check (:393-422) |
test_an_ending_while_the_wake_runs…, test_the_holder_releasing_before_the_park…, test_redis_down_on_the_park… |
:615 |
executed, red when removed |
_drain_missed (:425-443) |
5 of 7 tests | :422, :561, :631 |
executed, red when either drain is removed |
_covered / _as_utc (:370-390) |
test_a_sweep_that_ended_before_the_claim_is_one_wake |
:612 |
executed, red when removed or inverted |
_follow_on_key (:157-159) |
2 tests | :442 |
executed, red when replaced by the bucket key |
follow-on key kept completed (:683-686) |
no test | :683 |
unpinned: all 7 tests stay green with it replaced by a release (I1) |
_expect_caller guard (:572-573) |
no test | :443 |
unpinned: all 7 green with it deleted (I4) |
_spawn_followon real body (:361-367) |
no test (the fixture replaces it) | :443 |
not executed by the PR's tests (I4) |
No source-text assertions in the new test file (PROVED: the Step 2.5 grep for inspect.getsource|read_text()|.index( returns nothing). The tests run the real idempotency claim against a real DB and fakeredis; only the dispatch, container probe, policy, audit and the follow-on spawn are stubbed.
Fix mutation (PROVED, scratch worktree off the PR head, new test file kept):
- Whole fix reverted (
caller_wake_service.pyrestored to the merge-base6bbff0d87),pytest -p no:randomly unit/test_4536_wake_window.py→ 6 failed, 1 passed. Red:test_a_fast_delegate_wake_loop_gets_every_round("round 2: the ending was dropped"),test_an_ending_while_the_wake_runs_is_delivered_when_it_ends,test_an_ending_parked_after_the_wake_terminal_is_drained_by_the_holder,test_endings_after_the_claim_collapse_into_one_follow_on,test_the_holder_releasing_before_the_park_still_delivers,test_redis_down_on_the_park_is_audited_not_raised. Green:test_a_sweep_that_ended_before_the_claim_is_one_wake(it guards the old storm bound, as the PR body says). The PR body's "5 of 6" is a stale count; the claim holds. - Per mechanism (each applied alone to the PR head): no release on end → 1 red; no drain at the wake row's terminal → 2 red; no holder drain → 1 red; no coverage check → 1 red (the sweep test); no re-check after the park → 1 red; no
parkedaudit → 1 red; noskipped_windowaudit → 1 red; drain on the bucket key instead of the follow-on key → 2 red;ended <= claimedinverted → 6 red;GETDEL→GET→ the suite never ends (endless follow-ons; I stopped it). The four mechanism claims in the PR body are confirmed. - Green under mutation: follow-on key released instead of completed → 7 passed;
_expect_callerguard deleted → 7 passed.
Other runs (PROVED): at the PR head, unit/test_4536_wake_window.py → 7 passed; unit/test_ent1102_caller_wake.py unit/test_4357_wake_chain_depth.py unit/test_ent1216_wake_turn_reads.py unit/test_4442_wake_model.py unit/test_ent1236_project_steward_trigger.py → 131 passed; the registry reader and the single-flight guard, unit/test_2338_journey_catalog.py unit/test_1920_no_hand_rolled_single_flight.py → 72 passed. tests/registry.json diff is 12 added lines, nothing removed or re-serialised.
Critical
C1. A clean backend stop consumes the parked ending and loses it (confidence 7/10)
File: src/backend/services/caller_wake_service.py:623-631
try:
wake_id = await _claimed_wake(...)
return wake_id
finally:
await _drain_missed(caller, wake_id)Why it is wrong: the holder is a task parked in await _dispatch_wake(...) for the whole wake turn. When the event loop shuts down, the task is cancelled; CancelledError is not an Exception, so nothing in _claimed_wake handles it and the finally runs. _drain_missed then takes the marker out of Redis with GETDEL (:434) and hands the ending to an in-memory task (_spawn_followon, :443) on a loop that is closing. That task stops at its first real await (_container_state runs Docker in an executor) and never resumes. After the restart the wake row's own terminal drains nothing, because the marker is gone. The ending is audited parked and never delivered, which is the stall this PR exists to remove. It also contradicts the PR body and the docs ("the wake row's own terminal, which every terminal writer reaches including after a restart"); the accepted residual names a different, narrower case.
PROVED (probe test added in the scratch worktree, same fixture as the PR's tests but with the real _spawn_followon and a container probe that goes through run_in_executor): a gated holder is created with asyncio.create_task, a late ending parks, the first asyncio.run returns (the pending holder is cancelled at loop teardown), then a second asyncio.run plays the wake row's terminal:
P7: {'marker_before_stop': True, 'marker_after_stop': None, 'wakes_after_stop': 1} wakes = 1 late delivered = False audits = ['parked']
AssertionError: parked ending lost across a graceful stop
With the drain skipped when the exit is a cancellation (drain only on a normal return or an Exception), the same probe gives marker_after_stop = the parked id, wakes = 2, late delivered = True, and the PR's 7 tests still pass (11 passed in that run, including the dispatch-raises and failed-result probes below).
INFERRED: that the production worker reaches this path. uvicorn's Server.run drives the app with asyncio.run-style teardown (read in the installed 0.52; the image pins 0.37.0, not read), which cancels pending tasks once serve() returns. A hard kill skips the finally, and then the marker survives. With an immediate (non-yielding) container stub the follow-on gets far enough to re-park, so the loss depends on the follow-on reaching a real await before the loop closes; the real probe always yields. Trigger: a backend restart or deploy while an ending is parked.
Fix: do not drain when the holder is cancelled; leave the marker for the wake row's terminal. Add a test that cancels the holder with an ending parked and asserts delivery from the wake row's terminal afterwards.
Re-run a second time against 63436dc1d before posting, same result (1 failed, the assertion above). The probe, to reproduce: append it to tests/unit/test_4536_wake_window.py (it uses that file's world fixture and helpers) and run pytest -p no:randomly unit/test_4536_wake_window.py -k p7 -s.
Probe test (not part of the PR)
def _orig_spawn_code():
import ast, inspect, textwrap
import services.caller_wake_service as m
src = inspect.getsource(m)
tree = ast.parse(src)
fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_spawn_followon")
mod = ast.Module(body=[fn], type_ignores=[])
ns = {}
code = compile(mod, m.__file__, "exec")
return next(c for c in code.co_consts if hasattr(c, "co_name") and c.co_name == "_spawn_followon")
def test_probe_p7_loop_shutdown_with_executor_container_probe(world, monkeypatch):
"""P6, but the container probe leaves the loop the way the real one does
(run_in_executor), instead of the fixture's immediate stub."""
import concurrent.futures, time as _t
pool = concurrent.futures.ThreadPoolExecutor(max_workers=2)
async def _state(_agent):
return await asyncio.get_event_loop().run_in_executor(pool, lambda: (_t.sleep(0.05), "running")[1])
monkeypatch.setattr(_WAKE, "_container_state", _state)
import types, services.caller_wake_service as src_mod
monkeypatch.setattr(_WAKE, "_spawn_followon",
types.FunctionType(_orig_spawn_code(), src_mod.__dict__, "_spawn_followon"))
state = {}
async def before_stop():
world.gate["event"] = asyncio.Event()
first = _callee_run()
_end(first, datetime.now(timezone.utc) - timedelta(seconds=1))
asyncio.create_task(_WAKE.maybe_wake_caller(first))
await asyncio.sleep(0.2) # holder claimed, wake running
late = _callee_run(); _end(late)
assert await _WAKE.maybe_wake_caller(late) is None # parked
state["late"] = late
state["marker_before_stop"] = world.redis.get(f"{MISSED}{BOSS}") == late
state["w1"] = world.wakes[0]["id"]
asyncio.run(before_stop())
state["marker_after_stop"] = world.redis.get(f"{MISSED}{BOSS}")
state["wakes_after_stop"] = len(world.wakes)
async def after_restart():
world.gate["event"] = None
monkeypatch.setattr(_WAKE, "_spawn_followon", lambda coro: world.spawned.append(coro))
await _wake_turn_ends(world, state["w1"])
asyncio.run(after_restart())
delivered = any(state["late"] in w["message"] for w in world.wakes)
print("P7:", {k: v for k, v in state.items() if k not in ("late", "w1")},
"wakes =", len(world.wakes), "late delivered =", delivered,
"audits =", [a["status"] for a in world.audits])
assert delivered, "parked ending lost across a graceful stop"Informational (non-blocking)
I1. A second drain of the same wake drops its ending on the completed follow-on key, with no audit (confidence 6/10). :683-686 keeps caller_wake:{caller}:after:{wake_id} as completed; :611-621 treats a completed replay as "already woken in this window" and returns with only an INFO line. GETDEL already guarantees one follow-on per parked value, so the completed key only ever meets a different ending. PROVED (probe): holder running, X parks, the wake row's terminal delivers X and that follow-on wake finishes, Y parks on the window the holder still holds, the holder returns and drains Y:
P2: wakes = 2 y delivered = False marker = None audits = [('parked', False), ('completed', False), ('parked', True), ('completed', False)]
P2 log: ['ent#1102: zq4536-boss already woken in this window — no second wake for <Y>']
With the follow-on key released instead of completed, the same probe gives wakes = 3 y delivered = True and the PR's 7 tests pass. INFERRED reach: it needs the follow-on wake to finish before the holder's own dispatch returns, inside the claim's 15 s bucket (the cross-worker waiter polls every 5 s under pull, so a follow-on that fails fast or a very short turn can do it). Narrow, but it is a silent drop in a PR titled "never dropped". Suggest releasing the follow-on key like the bucket key, or parking on a completed replay.
I2. The storm bound now holds only while the first wake is still running (confidence 7/10). :687-690 releases the window when the wake's dispatch returns, whatever its status; at the merge-base the claim was completed and held the bucket. PROVED (probe): 300 rows from 300 callees, all ended 2 s before the first claim, their fan-outs arriving one after another once the previous wake's dispatch had returned → 300 wakes at the PR head, 1 at the merge-base. Same callee for all 300 → 120 wakes plus 180 skipped_budget (the hourly pair budget is the only bound left). The PR's sweep test holds the wake open with a gate, so it does not see this. INFERRED: it matters when a wake returns fast (a FAILED result, or a short turn) while a sweep is still fanning out; a sweep that fans out in milliseconds against a wake of several seconds stays at 1–2 wakes. The docs sentence "a cleanup sweep stays one wake" and "the window below does [bound a chain spread across many callees]" (docs/memory/requirements/core-agent.md:2206-2207) are stronger than the code. Either state the bound as "one running wake plus one pending" only, or keep collapsing endings that ended before the last claim.
I3. core-agent.md:2206-2207: the wake-budget sentences moved to the wrong bullet. "A wake past the budget is skipped and audited skipped_budget … Fails open when Redis is unavailable." now ends the #4536 window bullet; it belongs to the #4357 budget bullet above it.
I4. Unpinned pieces. The _expect_caller guard (:572-573) and the real _spawn_followon body (:361-367) are executed by no test in the PR; a mistake in either ships green. One test that lets the real spawn run would cover the second.
I5. parked is audited once per ending, but the marker keeps only the latest (:398, by design: "latest wins"). Twenty endings parked during one wake give twenty parked rows and one follow-on naming the last; the other nineteen rely on the frame's "list_recent_executions is the complete list". Collapsed-into-holder endings (:617-621) still leave only an INFO line, as before. Fine as a design, worth one sentence in the feature flow so an operator reading the audit does not expect twenty deliveries.
I6. Failure paths with an ending parked are handled but not tested in the PR. PROVED (probes): holder's dispatch raises with an ending parked → ['parked', 'dispatch_error', 'completed'], delivered; holder's dispatch returns FAILED → ['parked', 'failed', 'completed'], delivered. Worth adding both as tests; they are the "every terminal path releases what it parked" evidence.
I7. PR body. "5 of 6 tests failed on HEAD" should read 6 of 7. No Journey Impact: line (the gate script passes without one, but the template asks for it).
No contradiction with #4472 (the wake carries the delegator's person). INFERRED: _claimed_wake keeps _standing_person(caller, row) and the source_user_id hand-off unchanged, and the follow-on re-reads the parked run's own row, so a follow-on wake carries that run's person. PROVED: #4472's commit is an ancestor of the PR head, and unit/test_ent1216_wake_turn_reads.py passes at the head. With several parked endings the follow-on carries the last one's person, the same rule the window collapse already had.
Budget. INFERRED: a follow-on goes through the same _within_wake_budget as any wake (:635), a park spends nothing, and a capped follow-on releases its key and is audited skipped_budget. A fast loop now reaches the default 120 per hour and then stops with the audit row and one notification, which is visible, not silent.
Methodology (validate-pr)
- Lane B (one service file; no schema, no router, no auth or image path).
/cso --diffnot required for a bug fix. - Issue link:
Fixes #4536in the body; the issue exists, is open,priority-p1,type-bug,theme-reliability,status-in-progress. Base isdev, 6 files, +490/−8. - Commits:
fix(wake): …anddocs(learnings): …, conventional and descriptive. - Docs tier (bug fix + behaviour change): requirements updated (
docs/memory/requirements/core-agent.md), feature flow updated (docs/memory/feature-flows/agent-to-agent-collaboration.md, step 9), learnings fragment added. Both doc statements about restart and the sweep need the corrections in C1 / I2 / I3. - Tests registered:
tests/registry.jsonentry forunit/test_4536_wake_window.py, additive. - Security: key/token, email, IP, hardcoded-secret, env-file, symlink/mode and host-path greps over the PR diff → no hits. Enterprise-docs guard pattern over added lines → no hits (positive control matched). No new env var, no new top-level backend directory. Audit-row script → "no gated write handler touched". No security report needed.
- Journey Impact:
scripts/ci/check_journey_impact.pyon the PR body and SHAs →PASSED — no new: declaration, so no skeleton is owed. - Cross-surface drift: no router or MCP tool touched;
caller_wake_service.pyhas no agent-server twin. - CI at head
63436dc1d: 20 success, 6 skipped, 0 failed or pending.pytest (head, seed 12345)pass (41011 passed, 85 skipped, 8 xfailed),regression diffpass,Analyze (python),Analyze (javascript-typescript),schema-parity,verify-non-root,gitleaks,prod-image-smoke,journey-impactpass. Skipped:e2e,journey-smoke,report,auto-merge, and the two fallback pytest jobs. - Merge with dev:
git merge-tree --write-tree origin/dev HEADexits 0 against the current tip (54f663a61), no conflict. - Reviews: none yet; no comments on the PR.
Not checked
- No run against a live stack, PostgreSQL, or two uvicorn workers. The new tests ran on SQLite locally; I could not confirm from the CI log that they also ran on PostgreSQL, as the PR body says.
- C1's production path (uvicorn teardown cancelling the holder) is read from code, not exercised on a running backend.
- The full pinned-guard set (about 219 files) was not run locally; I relied on CI's full unit run and
regression diffat this head, plus the registry reader and the single-flight guard run locally. - That every terminal writer of a wake row reaches the fan-out (the PR's "16 sites" claim) was not audited site by site.
- The manual RC check in the PR body (the row A5 loop, 12 rounds with a 3–10 s callee) is still open.
webmixgamer
left a comment
There was a problem hiding this comment.
Requesting changes on 63436dc1d: one blocking finding (C1, a clean backend stop loses the parked ending; proven by a probe, with a one-line fix). The /review + /validate-pr report is in the comment above. The fix for the reported stall itself is confirmed by mutation.
…eep bound (#4536) - A holder cancelled by a backend stop no longer drains the parked ending; the wake row's terminal delivers it after the restart. - The follow-on key is released when the follow-on ends, so a second ending parked on the same wake is delivered. - The latest claim of a wake whose turn ran is kept in Redis (trinity:wake_claimed:{caller}); an ending from before it collapses, so a sweep still fanning out after its wake returned is one wake. - Tests for the cancelled holder, the second drain, the late sweep, the _expect_caller guard, the real follow-on spawn, and a holder that raises or returns failed. _complete_idempotency had no caller left and is removed. - Docs: budget sentences back on the #4357 bullet; bound, restart and one-marker audit behaviour stated in the requirements and feature flow. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
All addressed in c4175b9.
|
Re-review — REQUEST CHANGES (head
|
| point | claim | verified how | result |
|---|---|---|---|
| I1 | follow-on key released, _complete_idempotency removed |
mutation (follow-on key completed again) → 1 failed: test_a_second_ending_parked_after_the_follow_on_finished_is_delivered; my probe P2 now prints wakes = 3 y delivered = True |
confirmed. No double delivery found: the marker is taken with GETDEL, so one parked id is in the marker or in one follow-on, never both (INFERRED); no self-loop, a follow-on's own drain finds the marker empty |
| I2 | sweep bound kept through trinity:wake_claimed:{caller} |
probes P1 / P1b (300 endings) → 1 wake each (were 300 and 120); mutations: check removed → 1 failed, claim never recorded → 1 failed (test_a_sweep_still_fanning_out_after_the_wake_returned_is_one_wake) |
the bound holds, but the rule is unsafe — see N1, N2 |
| I3 | budget sentences moved back | read docs/memory/requirements/core-agent.md:2206-2207 |
confirmed |
| I4 | _expect_caller and the real spawn covered |
mutations: guard deleted → 1 failed; real _spawn_followon made a no-op → 1 failed |
confirmed |
| I5 | latest-only marker stated in the flow | read docs/memory/feature-flows/agent-to-agent-collaboration.md:350 |
confirmed |
| I6 | raises / FAILED holder tests | test_a_holder_that_fails_still_delivers_what_was_parked[raises] and [failed] pass; both go red with the normal-return drain removed |
confirmed |
| I7 | PR body counts and Journey Impact | read the body; scripts/ci/check_journey_impact.py → PASSED with the declared none: line |
confirmed |
Runs at this head (PROVED): unit/test_4536_wake_window.py → 14 passed; the five existing wake files (test_ent1102_caller_wake, test_4357_wake_chain_depth, test_ent1216_wake_turn_reads, test_4442_wake_model, test_ent1236_project_steward_trigger) → 131 passed; the registry reader plus 14 guards chosen for scanning service code, Redis claim shapes or allowlists (test_2338_journey_catalog, test_1920_no_hand_rolled_single_flight, test_1560_agent_redis_key_parity, test_ent830_idempotency_caller_scope, test_3317_loop_dispatch_claim, test_1464_monitoring_leader_lock, test_2742_sync_health_leader_lock, test_1881_canary_leader_lease, test_1677_operator_alert_emitters, test_4284_no_exception_text_in_5xx, test_ent1117_s13_service_error_text, test_1804_terminal_activity_parity, test_2944_retained_results, test_2669_minting_accessor_callers, test_ent1066_credential_sink) → 469 passed. No guard names the two new Redis keys.
New in this push
N1 (blocking). A recovered run with a back-dated completed_at is collapsed against a wake that saw it as still running (confidence 8/10)
File: src/backend/services/caller_wake_service.py:633-638
if _ended_by(row, _last_claim(caller)):
# #4536: a wake claimed after this run ended has already run and listed it.completed_at is not always the moment the row became terminal. The retained-result claim writes the agent's own finish instant (src/backend/services/cleanup_service.py:392, completed_at=_retained_at(record)), which by its own comment is at least the claim grace plus up to one cleanup cycle before the write, and that write goes through apply_result, which fans the terminal out to this hook. So a delegated run whose result is recovered minutes late arrives here with an old completed_at. If the delegator was woken for anything else in between and that wake returned, the stored claim is later than the old instant and the ending is collapsed. The wake that "covers" it listed the run as running. Nothing is parked, audited or delivered: one INFO line.
PROVED (probe, same fixture as the PR's tests): slow and other are delegated; other ends and its wake runs and returns while slow is still open; then slow is written terminal with completed_at 300 s in the past, in a later window:
N0: persisted completed_at is the producer's instant: True seconds behind now = 300 (utils.helpers.terminal_completed_at)
N1 @ c4175b9b4: while the covering wake ran, the row was status = running completed_at = None | woken for it = None | wakes = 1 | delivered = False | audits naming it = []
N1 @ 63436dc1d: … woken for it = <id> | wakes = 2 | delivered = True | audits naming it = ['completed']
N1 @ merge-base: … woken for it = <id> | wakes = 2 | delivered = True | audits naming it = ['completed']
This is the issue's own symptom (a delegated run ends and the delegator is never told) on the recovery path, and both the previous head and the merge-base deliver it. INFERRED: that the persisted row carries retained_at on that path (read at cleanup_service.py:388-392 and utils/helpers.py:169-215; not run end to end). The in-flight check at :649 reads the same column, but only inside one 15 s window and while the holder's turn is still running.
N2 (blocking). The claim is recorded for a wake that never ran, and the rule is applied to an ending taken from the marker (confidence 7/10)
Files: caller_wake_service.py:723-724 (_note_claim runs for any result that did not raise, FAILED included; the docstring and the docs say "a wake whose turn ran") and :633 (the same check runs for a follow-on).
PROVED (probes):
- Holder H runs; Y ends after H's claim and is parked; in the next window another run Z ends and its wake comes back FAILED before the agent runs (no free slot). Z's drain takes Y from the marker and the follow-on collapses it on Z's claim:
N2b[failed] @ c4175b9b4: wake rows = 1 | y named in a wake = False | marker after z's drain = None | audits = [('parked','y'), ('failed','z'), ('completed','first')]
N2b[failed] @ 63436dc1d: wake rows = 2 | y named in a wake = True | audits = [('parked','y'), ('failed','z'), ('completed','y'), ('completed','first')]
Y is auditedparked, removed from Redis and never delivered; no wake ran after it ended. With Z's wake succeeding the outcome for Y is the same (y named in a wake = False), resting on Z's turn reading the list. - Three rows ended earlier, each fan-out in a later window, every dispatch FAILED:
N2a @ c4175b9b4: dispatch attempts = 1, at63436dc1dand at the merge-baseattempts = 3. "A FAILED wake still covers, as at the merge-base" holds for 15 s there; here it holds for the key's 24 h. - No test pins the choice either way: recording the claim only for a non-failed result → 14 passed.
Both probes were run a second time, independently, before posting: on c4175b9b4 N1, N2a and both N2b cases fail (the ending is lost); on 63436dc1d the same file passes them. To reproduce, save the block below as tests/unit/test_probe_4536_latest_claim.py and run pytest -p no:randomly unit/test_probe_4536_latest_claim.py -s.
Probe tests N0–N2b (not part of the PR)
from __future__ import annotations
import asyncio
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from types import SimpleNamespace
import fakeredis
import pytest
_BACKEND = Path(__file__).resolve().parents[2] / "src" / "backend"
if str(_BACKEND) not in sys.path:
sys.path.insert(0, str(_BACKEND))
from db.write_params import TaskExecutionFields # noqa: E402
from db_harness import db_backend, run as _hrun # noqa: E402,F401
import services.caller_wake_service as _WAKE # noqa: E402
from database import db # noqa: E402
pytestmark = pytest.mark.unit
BOSS, WORKER = "zq4536-boss", "zq4536-worker"
MISSED = "trinity:wake_missed:"
# Mid-bucket, so nothing in a test crosses a window boundary by accident.
NOW = 1_800_000_000 - (1_800_000_000 % _WAKE.WAKE_BUCKET_SECONDS) + 5
@pytest.fixture
def world(db_backend, monkeypatch):
wakes = []
spawned = []
audits = []
gate = {"event": None}
held = []
async def _dispatch_wake(**kwargs):
# What `dispatch_and_await_terminal` writes before the agent runs.
row = db.create_task_execution(
agent_name=kwargs["agent_name"],
message=kwargs["message"],
triggered_by=kwargs["triggered_by"],
fields=TaskExecutionFields(chain_depth=kwargs.get("chain_depth")),
)
wakes.append({"id": row.id, "message": kwargs["message"]})
ev = gate["event"]
if ev is not None:
held.append(ev)
await ev.wait() # the wake turn is still running
return SimpleNamespace(execution_id=row.id, status="completed", error=None)
async def _state(_agent):
return "running"
async def _audit(**kw):
audits.append(kw)
def _policy(_agent):
from services.wake_policy import WakeVerdict
return WakeVerdict(enabled=True, source="instance")
monkeypatch.setattr(_WAKE, "_dispatch_wake", _dispatch_wake)
monkeypatch.setattr(_WAKE, "_container_state", _state)
monkeypatch.setattr(_WAKE, "_audit", _audit)
monkeypatch.setattr(_WAKE, "_resolve_policy", _policy)
monkeypatch.setattr(_WAKE, "_caller_subscribes_to", lambda *a: False)
monkeypatch.setattr(_WAKE, "_spawn_followon", lambda coro: spawned.append(coro), raising=False)
monkeypatch.setattr(_WAKE, "time", SimpleNamespace(time=lambda: NOW))
redis = fakeredis.FakeRedis(decode_responses=True)
monkeypatch.setattr(_WAKE, "_wake_budget_redis", lambda: redis)
return SimpleNamespace(wakes=wakes, spawned=spawned, audits=audits, gate=gate, held=held, redis=redis)
def _iso(dt: datetime) -> str:
return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def _callee_run() -> str:
return db.create_task_execution(
agent_name=WORKER, message="next number", triggered_by="agent",
fields=TaskExecutionFields(source_agent_name=BOSS),
).id
def _end(execution_id: str, at: datetime | None = None) -> None:
at = at or datetime.now(timezone.utc)
_hrun(
"UPDATE schedule_executions SET status='success', completed_at=:t WHERE id=:i",
t=_iso(at), i=execution_id,
)
async def _wake_turn_ends(world, wake_id: str) -> None:
"""The wake row's own terminal: what every CAS-won writer fans out."""
_end(wake_id)
await _WAKE.maybe_wake_caller(wake_id)
while world.spawned:
await world.spawned.pop(0)
async def _finish(world, holder):
for ev in world.held:
ev.set()
return await holder
def _set_clock(monkeypatch, t):
monkeypatch.setattr(_WAKE, "time", SimpleNamespace(time=lambda: t))
def test_n0_terminal_completed_at_backdates():
from utils.helpers import terminal_completed_at
now = datetime.now(timezone.utc)
given = now - timedelta(seconds=300)
got = terminal_completed_at(given, floor=now - timedelta(seconds=600))
print("N0: persisted completed_at is the producer's instant:", got == given, "seconds behind now =", round((now - got).total_seconds()))
assert got == given
def test_n1_recovered_run_backdated_before_a_returned_wake(world, monkeypatch):
"""`slow` ended on the agent 5 min ago but its row goes terminal only now
(the retained-result claim stamps completed_at = the agent's instant).
In between, the delegator was woken for another run and that wake returned."""
async def scenario():
t0 = datetime.now(timezone.utc)
slow = _callee_run()
other = _callee_run(); _end(other)
w = await _WAKE.maybe_wake_caller(other)
assert w
seen = db.get_execution(slow)
status_seen = getattr(seen.status, "value", seen.status)
ended_seen = seen.completed_at
await _wake_turn_ends(world, w) # that wake ran and returned
_set_clock(monkeypatch, NOW + 30) # a later window
_end(slow, t0 - timedelta(seconds=300)) # terminal written NOW, back-dated
woken = await _WAKE.maybe_wake_caller(slow)
while world.spawned:
await world.spawned.pop(0)
return slow, woken, status_seen, ended_seen
slow, woken, status_seen, ended_seen = asyncio.run(scenario())
print("N1: while the covering wake ran, the row was status =", status_seen, "completed_at =", ended_seen,
"| woken for it =", woken, "| wakes =", len(world.wakes),
"| delivered =", any(slow in w["message"] for w in world.wakes),
"| audits naming it =", [a["status"] for a in world.audits if a["callee_execution_id"] == slow],
"| marker =", world.redis.get(f"{MISSED}{BOSS}"))
assert any(slow in w["message"] for w in world.wakes)
def test_n2a_failed_wake_covers_later_fanouts(world, monkeypatch):
"""Three rows ended earlier; each fan-out arrives in a later 15 s window;
every wake dispatch comes back FAILED before the agent runs (no free slot)."""
attempts = []
async def _capacity(**kw):
attempts.append(1)
return SimpleNamespace(execution_id=None, status="failed", error="Agent at capacity")
monkeypatch.setattr(_WAKE, "_dispatch_wake", _capacity)
async def scenario():
rows = [_callee_run() for _ in range(3)]
earlier = datetime.now(timezone.utc) - timedelta(seconds=2)
for r in rows:
_end(r, earlier)
for i, r in enumerate(rows):
_set_clock(monkeypatch, NOW + 15 * i)
await _WAKE.maybe_wake_caller(r)
while world.spawned:
await world.spawned.pop(0)
asyncio.run(scenario())
print("N2a: dispatch attempts =", len(attempts), "audits =", [a["status"] for a in world.audits],
"last claim stored =", world.redis.get(f"trinity:wake_claimed:{BOSS}") is not None,
"ttl =", world.redis.ttl(f"trinity:wake_claimed:{BOSS}"))
assert len(attempts) == 3
@pytest.mark.parametrize("other_wake", ["failed", "completed"])
def test_n2b_parked_ending_dropped_at_drain_by_another_wakes_claim(world, monkeypatch, other_wake):
"""H's wake runs (window b). Y ends after H's claim -> parked. In window b+1
another run Z ends; its wake claims after Y ended and returns. Its drain
takes Y from the marker and hands it to a follow-on."""
fixture_dispatch = _WAKE._dispatch_wake
calls = []
async def _dispatch(**kw):
calls.append(kw)
if len(calls) == 2 and other_wake == "failed":
return SimpleNamespace(execution_id=None, status="failed", error="Agent at capacity")
return await fixture_dispatch(**kw)
monkeypatch.setattr(_WAKE, "_dispatch_wake", _dispatch)
async def scenario():
world.gate["event"] = asyncio.Event()
first = _callee_run()
_end(first, datetime.now(timezone.utc) - timedelta(seconds=1))
holder = asyncio.create_task(_WAKE.maybe_wake_caller(first))
await asyncio.sleep(0)
y = _callee_run(); _end(y)
assert await _WAKE.maybe_wake_caller(y) is None
assert world.redis.get(f"{MISSED}{BOSS}") == y # parked
world.gate["event"] = None
_set_clock(monkeypatch, NOW + 15)
z = _callee_run(); _end(z)
zw = await _WAKE.maybe_wake_caller(z)
while world.spawned:
await world.spawned.pop(0)
if zw:
await _wake_turn_ends(world, zw)
marker_mid = world.redis.get(f"{MISSED}{BOSS}")
await _wake_turn_ends(world, world.wakes[0]["id"]) # H's wake row ends
await _finish(world, holder)
while world.spawned:
await world.spawned.pop(0)
return y, z, marker_mid
y, z, marker_mid = asyncio.run(scenario())
print(f"N2b[{other_wake}]: wake rows =", len(world.wakes),
"| y named in a wake =", any(y in w["message"].splitlines()[0] for w in world.wakes),
"| z named in a wake =", any(z in w["message"].splitlines()[0] for w in world.wakes),
"| marker after z's drain =", marker_mid,
"| audits =", [(a["status"], "y" if a["callee_execution_id"] == y else "z" if a["callee_execution_id"] == z else "first") for a in world.audits])
assert any(y in w["message"].splitlines()[0] for w in world.wakes)What would clear N1 and N2. Either take the latest-claim rule back out and state the bound in the docs as "one running wake plus one pending" (I2 was non-blocking; the previous head's behaviour is acceptable), or keep it with all three of: record the claim only when the result shows the turn ran; never apply it to an ending taken from the marker; do not apply it when completed_at is older than the row's terminal write can explain (a sweep fans out within seconds; the recovery path is minutes late by construction). Each with a test that goes red without it.
N3 (non-blocking). caller_wake_service.py:667 catches BaseException, so a holder coroutine closed while it awaits (GeneratorExit) still drains. PROVED (probe, coroutine driven by hand and closed): N3: marker before close = True | after close = None | follow-ons handed to the dying loop = 1. INFERRED reach is low (a pending task destroyed with its loop instead of cancelled). except Exception is enough here. The branch is also unpinned: with its drain removed → 14 passed.
N4 (non-blocking).
_note_claimis read-then-write (:413-418); two workers can keep the older claim, which only costs an extra wake (fails toward delivering). Redis down on the read wakes (PROVED: making that read raise turnstest_redis_down_on_the_park_is_audited_not_raisedred). The "newer wins" compare is unpinned: never overwriting a stored claim → 14 passed.trinity:wake_claimed:{caller}andtrinity:wake_missed:{caller}are per-agent Redis keys with a 24 h TTL that the per-agent keyspace registry does not see (its scan matchesagent:literals only). INFERRED harmless: a stale claim can only cover endings older than itself.- The module docstring (
:44-54), the PR summary's second bullet and thetests/registry.jsondescription still describe the first commit; none mentions the latest-claim rule or the seven new tests. - Docs versus code:
core-agent.md:2207says the claim is "of a wake whose turn ran" and that the wake's list shows the ending. N1 and N2 show both are untrue as written. The restart sentences (cancelled holder leaves the marker; wake row's terminal drains) match the code.
CI and merge state
- Head re-read at the end:
c4175b9b4, not moved. gh pr checks 4545on this head: 21 pass, 6 skipped, nothing failed or pending;pytest (head, seed 12345)andregression diffboth pass. A greenregression diffdoes not cover N1 and N2: no existing test exercises those paths.git merge-tree --write-tree origin/dev HEADexits 0;devis 6 commits past the merge-base, no conflict.reviewDecision: CHANGES_REQUESTED (the first review).
Not checked
- No live stack, PostgreSQL or two-worker run; SQLite only, as before.
- N1 end to end through the cleanup watchdog and
apply_result; the back-dating is read from code and the helper, the service decision is proven. - Whether a wake to a busy delegator really returns FAILED fast in production (N2's trigger); the dispatch result was stubbed.
- The full pinned-guard set and the full suite locally; CI's unit run and
regression diffpass on this head. - Uvicorn's teardown on a running backend (C1's production path), as in the first review.
webmixgamer
left a comment
There was a problem hiding this comment.
Re-review of c4175b9b4: the first finding (C1) is fixed and confirmed, and so are I1 and I3–I7. Still requesting changes: the latest-claim rule added for I2 loses endings in two proven cases (N1, N2 in the comment above), and both pass on the previous head. Taking that rule back out and stating the bound in the docs is enough; I2 was non-blocking.
… marker (#4536) - Remove trinity:wake_claimed:{caller}, _note_claim, _last_claim and the pre-claim collapse. An ending collapses only into the wake still running in its window. Bound: one running wake plus one pending per caller. - The holder drains on Exception; GeneratorExit and CancelledError leave the marker for the wake row's terminal. - Tests: a back-dated recovered run, a parked ending drained by a later window's wake (failed and completed), a FAILED wake in an earlier window, a holder closed mid-wake, a holder raising past the dispatch. Removed the test that pinned the dropped rule. - Docs, module docstring and registry entry describe the current behaviour. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Took the first option; fixed in
|
Re-review 2 — APPROVE (head
|
| item | still holds? | how checked |
|---|---|---|
| C1: a clean stop keeps the parked ending | yes | probe P7: marker_after_stop: '<parked id>' … wakes = 2 late delivered = True; mutation (drain on cancel put back) → 1 failed: test_a_cancelled_holder_leaves_the_parked_ending_for_the_wake_terminal |
| I1: second drain after a finished follow-on delivers | yes | probe P2: wakes = 3 y delivered = True; mutation (follow-on key completed again) → 1 failed: test_a_second_ending_parked_after_the_follow_on_finished_is_delivered |
| The original fix (release on end, park, both drains, coverage check) | yes | mutations: window not released → 4 failed (the 12-round loop test among them); never park → 14 failed; no drain after a normal return → 5 failed; wake row's terminal does not drain → 4 failed; coverage check off → 1 failed (the 300-row sweep test) |
I4: _expect_caller and the real spawn pinned |
yes | mutations: each → 1 failed |
| I6: holder that raises / returns FAILED still delivers | yes | probes P3, P4 deliver; both parametrized tests pass and go red without the normal-return drain |
| Tests | 19 pass | unit/test_4536_wake_window.py → 19 passed; the five existing wake files → 131 passed; the same 15 guard files as last round → 469 passed |
Every mutation I tried at this head turns at least one test red; none stayed green.
Diff against the first reviewed head (63436dc1d → d48480a09, service file): the module docstring, import asyncio, the removal of _complete_idempotency and the follow_on parameter (I1), and the try/except in place of the finally (C1, N3) are all explained. One thing is not: _covered is now a one-line wrapper around a new _ended_by(row, claimed_at) (:383-392). That split was made for the removed rule and _ended_by has a single caller again. Harmless; fold it back or leave it.
Tests and registry. No source-text assertion in the test file (PROVED: the grep for inspect.getsource|read_text()|.index( returns nothing). tests/registry.json against the merge-base: 12 added lines, 0 removed; the description matches the final behaviour and the count (19). The three existing wake test files each drop one stub of the removed _complete_idempotency; nothing in them asserted on it.
New in this push
Nothing blocking. Two wording notes, both non-blocking:
- "Bound: one running wake plus one pending per caller" (
docs/memory/requirements/core-agent.md:2207,docs/memory/feature-flows/agent-to-agent-collaboration.md:350, the module docstring:56, the PR body) is looser than the code: the window key is per 15 s bucket, so wakes for endings in successive windows run side by side. PROVED (probe, every wake turn held open, one ending in each of four successive windows):P8: wake turns open at once for one caller = 4 | wake rows dispatched = 4 | parked = None, identical at the merge-base, so this is not a behaviour change. The first commit's wording, "per caller per window", was the accurate one. That phrase came out of my own earlier suggestion, which left "per window" out. - "a cleanup sweep inside one window is one wake" (
core-agent.md:2207; "a sweep inside one window is one wake" in the feature flow; "the window below bounds a sweep" atcore-agent.md:2206) is true while that first wake is still running, which the same sentence says ("the wake still running"). Once it returns, each later ending wakes again. For the record, at this head: 300 endings from 300 callees, all ended before the first claim, arriving after each wake returned → 300 wakes; same callee → 120 wakes plus 180skipped_budget. That is the behaviour of the first reviewed head and was accepted there; the PR body states it plainly ("A finished wake covers nothing: once it returns, the next ending wakes"). The docs would be exact with the same sentence added. The older paragraph in the module docstring (:37-42, "One turn per caller per window") predates this PR and has the same gap.
The PR body no longer mentions the latest-claim rule; counts read 19.
CI and merge state
- Head re-read at the end:
d48480a09, not moved. gh pr checks 4545on this head: 21 pass, 6 skipped, nothing failed or pending.pytest (head, seed 12345)andregression diffpass, with bothAnalyzejobs,schema-parity,verify-non-root,gitleaks,prod-image-smoke,journey-impact, the lints and guards.scripts/ci/check_journey_impact.pyon the body and SHAs →PASSED.git merge-tree --write-tree origin/dev HEADexits 0;devis 8 commits past the merge-base, no conflict.
Not checked
- The full unit suite locally: only the PR's test file, the five wake files, the 15 guard files and my probes were run here. CI's unit run and
regression diffpass on this head. - No live stack, PostgreSQL or two-worker run; SQLite only.
- The recovery path end to end through the cleanup watchdog; the service decision is proven, the back-dating is read from code.
- Uvicorn's teardown on a running backend (C1's production path), as before.
- The manual RC check for row A5 is still open in the PR body.
webmixgamer
left a comment
There was a problem hiding this comment.
Approving d48480a09: the latest-claim rule is removed, so both loss paths from the last round are gone (probes pass); the clean-stop and second-drain fixes still hold; every mutation goes red; CI is green including regression diff. Two non-blocking wording notes on the stated bound are in the re-review comment above. Row A5 still needs a re-test on the next RC by someone other than the author.
…4536 The caller wake no longer has _complete_idempotency (#4545), so patching it raised AttributeError in six continuation-tier tests after merging dev. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nues (Abilityai/trinity-enterprise#1225) (#4546) * fix(access): a platform continuation turn stands as the turn it continues (Abilityai/trinity-enterprise#1225) Four turns the platform dispatches continue another turn's work and carry nobody on the row: caller_wake, operator_response, operator_ending and skill_gate. turn_actor rated each a visitor's turn, so the agent's key read no executions while it ran, a continuation of a shared person's turn got the shell, and a continuation of a delegated turn lost owner tier. Each continuation row now names the turn it continues (schedule_executions.continues_execution_id, nullable, SQLite migration + Alembic 0124). turn_actor and turn_person rate a continuation trigger as that turn. The link is written only through turn_tier_service.continuation_origin, which accepts an id only while it is RUNNING on the same agent and stores the root of a chain: - /chat, /task and fan-out callee rows record the caller key's acting turn; the wake copies it (ent#1216's _standing_person stays the fallback for a callee row with no link); - a native ask raise records its turn under a platform-only context key (stripped from agent-authored context); the answer and ending wakes copy it; agent-written context.execution_id is never used; - a gate request records the requesting agent's turn; the notice copies it; DISPATCH_FIELDS freezes the link for an approved replay. A link that cannot be followed (pruned, another agent's, unreadable, or one ending over asks raised by different turns) rates (share, person, None): no shell, no reads. Rows with no link are rated as before. Tests: tests/unit/test_ent1225_continuation_tier.py (50, real DB, real admission/wake/resume/raise paths). Mutations: disabling the rule turns 24-29 red, dropping the running check 3, removing each producer hand-off at least 1. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(access): a Workspace-reported resume keeps the Workspace rule; auto-memory and /task gated freeze follow the link (Abilityai/trinity-enterprise#1225) Review of #4546: - an answer resume whose result goes into the answering person's Workspace chat records no link, so it keeps the Workspace rating (share, person, None) instead of the asking turn's owner tier; - keeps_shared_auto_memory: a linked continuation keeps auto-memory only when the continued turn is the owner's own; - /task's own gate call freezes continues_execution_id like /chat's. Tests: three new cases in test_ent1225_continuation_tier.py; each goes red with its fix reverted. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(access): an ask's wake follows the asking turn only for an answerer who may stand as it (Abilityai/trinity-enterprise#1225) - operator_resume_service._continuation_of: the answer and ending wakes follow the link only when the answerer or canceller is owner tier on the agent or rates exactly as the asking turn (turn_tier_service.person_may_continue). Anyone else, or an unknown answerer, records NO_SINGLE_ORIGIN and rates (share, person, None). A platform ending with no person follows the link. - claim_next_queued RETURNING carries continues_execution_id, so a pulled continuation judges auto-memory as the push path does. - Tests through ask_service.answer / cancel and the wake filer; pull claim; file-channel strip of the platform key. - Docs: auth.md §2.12 answerer rule and Workspace wording; security.md §5d answerer rule and the cost of a fail-closed continuation. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(access): resolve an ask's answerer by user id for the continuation tier (Abilityai/trinity-enterprise#1225) The resume of an answered or cancelled ask checks the person who ended it with person_may_continue. That check matched on email only, so the admin provisioned from ADMIN_PASSWORD, who has no email on record, failed it on its own agent and the resume ran as a shared person with no shell. person_may_continue now takes the user id when the caller has one. The answer path reads it from the row's responded_by_id; cancel, dismiss and bulk cancel carry it on EndingEvent.actor_user_id into maybe_dispatch_ending. Workspace clients have no users row and keep the email path. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(ent1225): drop the _complete_idempotency stub removed on dev by #4536 The caller wake no longer has _complete_idempotency (#4545), so patching it raised AttributeError in six continuation-tier tests after merging dev. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
trinity:wake_missed:{caller}, 24 h, auditedparked) and delivered once when the wake ends, oncaller_wake:{caller}:after:{wake_id}. It is drained from two places: the wake row's own terminal, which every terminal writer reaches including after a restart, and the holder after it returns or raises anException. A holder cancelled or closed with its loop leaves the marker for the wake row's terminal.skipped_window.Changes
src/backend/services/caller_wake_service.py: release on end, coverage check,_park,_drain_missed, follow-on key.tests/unit/test_4536_wake_window.py: 19 tests against the real idempotency claim and fakeredis.docs/memory/requirements/core-agent.md,docs/memory/feature-flows/agent-to-agent-collaboration.md,tests/registry.json, plus a learnings fragment.Test Plan
cd tests && pytest unit/test_4536_wake_window.py -v -p no:randomly. 19 passed, SQLite only locally; PostgreSQL runs in CI._expect_caller, the real follow-on spawn, a holder that raises or returns failed.completed_atafter a returned wake is delivered; a parked ending drained by a later window's wake (failed and completed) is delivered; a FAILED wake in an earlier window does not cover the next window (3 attempts for 3 windows); a holder closed mid-wake (GeneratorExit) leaves the marker. A holder raising past the dispatch still drains (red with that drain removed).caller_waketurns.Residual, accepted at plan review: if the backend restarts mid-wake and an ending parks in the seconds after that wake's terminal drained, it is delivered by the caller's next wake end, or not at all if none comes within 24 h.
Journey Impact: none: wake delivery fix inside caller_wake_service; no journey promise added or changed
Fixes #4536
🤖 Generated with Claude Code