The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): keep async delegation results past a failed durable write and never prune live records
fangliquanflq27e3fc51ff45
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..ce4151eec7a--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+luckystar2026+# PR #112031 author emaildiff --git a/tests/tools/test_async_delegation.py b/tests/tools/test_async_delegation.pyindex 74701f39048..4b0e846e87f 100644--- a/tests/tools/test_async_delegation.py+++ b/tests/tools/test_async_delegation.py@@ -1150,3 +1150,44 @@ def test_connect_creates_state_db_0o600_under_permissive_umask(tmp_path, monkeypsidecar = tmp_path / f"state.db{suffix}"if sidecar.exists():assert stat.S_IMODE(sidecar.stat().st_mode) == 0o600+++def test_persist_failure_still_delivers_result_and_frees_slot(monkeypatch):+ """A failing terminal durable write (locked/full state.db) must not eat the completion+ event or park the record on ``finalizing`` (#76605, #112030): the event is the only delivery+ path and ``finalizing`` counts against ``max_concurrent_children`` forever."""+ def boom(event, result):+ raise RuntimeError("database is locked")++ monkeypatch.setattr(ad, "_persist_completion", boom)+ res = ad.dispatch_async_delegation(+ goal="g", context=None, toolsets=None, role="leaf", model="m", session_key="",+ runner=lambda: {"status": "completed", "summary": "done"}, max_async_children=1,+ )+ evt = _drain_for(res["delegation_id"])++ assert evt is not None and evt["status"] == "completed" and evt["summary"] == "done"+ deadline = time.monotonic() + 2.0+ while ad.active_count() and time.monotonic() < deadline:+ time.sleep(0.02)+ assert ad.active_count() == 0+ with ad._records_lock:+ assert ad._records[res["delegation_id"]]["status"] == "completed"+++def test_prune_never_evicts_live_records():+ """Retention pruning drops TERMINAL records only; ``stalling``/``finalizing`` are live work+ (#76605, #112030). A stalling record has no ``completed_at`` so it sorts oldest and was the+ first eviction candidate, sending its late runner return into the missing-record path."""+ with ad._records_lock:+ for status, ts in (("stalling", 1.0), ("finalizing", 2.0), ("running", 3.0)):+ ad._records[f"live-{status}"] = {"delegation_id": f"live-{status}", "status": status,+ "dispatched_at": ts, "completed_at": None}+ for i in range(ad._MAX_RETAINED_COMPLETED + 1):+ ad._records[f"done-{i}"] = {"delegation_id": f"done-{i}", "status": "completed",+ "dispatched_at": 100.0 + i, "completed_at": 200.0 + i}+ ad._prune_completed_locked()+ survivors = set(ad._records)++ assert {"live-stalling", "live-finalizing", "live-running"} <= survivors+ assert "done-0" not in survivors and len(survivors - {"live-stalling", "live-finalizing", "live-running"}) == ad._MAX_RETAINED_COMPLETEDdiff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 23a82dcc76e..46592451203 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -486,8 +486,10 @@ def _new_delegation_id() -> str:def _prune_completed_locked() -> None:- """Drop the oldest completed records beyond the cap. Caller holds ``_records_lock``."""- completed = [(rid, r) for rid, r in _records.items() if r.get("status") != "running"]+ """Drop the oldest completed records beyond the cap. Caller holds ``_records_lock``.+ ``stalling``/``finalizing`` are still live: evicting one makes the late runner return hit+ ``_finalize``'s missing-record path and silently drop a real result."""+ completed = [(rid, r) for rid, r in _records.items() if r.get("status") not in _LIVE_STATES]completed.sort(key=lambda kv: kv[1].get("completed_at") or kv[1].get("dispatched_at") or 0)for rid, _ in completed[: max(0, len(completed) - _MAX_RETAINED_COMPLETED)]:_records.pop(rid, None)@@ -722,7 +724,11 @@ def _push_completion_event(record: Dict[str, Any], result: Dict[str, Any], statu**({} if is_batch else {"exit_reason": result.get("exit_reason")}),**{k: record[k] for k in _ROUTING_KEYS if record.get(k)},**{k: result[k] for k in _STALL_META_KEYS if k in result}}- _persist_completion(evt, result)+ try:+ _persist_completion(evt, result)+ except Exception as exc: # noqa: BLE001 — a lost durable row is recoverable; a lost result + leaked slot is not+ logger.error(f"Async delegation{label} %s: durable completion write failed; delivering in-memory "+ "only (a restart may report this unit as unknown): %s", record.get("delegation_id"), exc)try:process_registry.completion_queue.put(evt)except Exception as exc: # pragma: no cover