diff --git a/packages/runtime/src/ginno_runtime/server_shared.py b/packages/runtime/src/ginno_runtime/server_shared.py index a6ef6386..561e74e3 100644 --- a/packages/runtime/src/ginno_runtime/server_shared.py +++ b/packages/runtime/src/ginno_runtime/server_shared.py @@ -256,6 +256,11 @@ def session_registry_put(session_id: str, entry: dict[str, Any]) -> None: # "stream will resume" from "turn is gone — reconcile from history". _RUNNING_TURNS: dict[str, str] = {} +# Task executing a background wake, keyed by (session_id, turn_id). A wake can +# run inline in the assigning session's task, so keep this liveness signal +# separate from _TURN_TASKS, whose entries the WS stop watchdog can cancel. +_WAKE_TURN_TASKS: dict[tuple[str, str], asyncio.Task[Any]] = {} + # When each _RUNNING_TURNS entry was (re)armed — stamped by engine._stream_graph, # the chokepoint every real turn execution passes through (WS/channel/goal/cli # all re-register there). Feeds turn_gate_busy's staleness self-heal: a turn @@ -300,25 +305,14 @@ def heal_stale_running_turn(session_id: str, age: float, via: str = "gate") -> N def running_turn_alive( session_id: str, *, _heal: bool = True, via: str = "gate" ) -> bool: - """Is a turn REALLY live on this session? Three signals, weakest to - strongest (the judgement core behind :func:`turn_gate_busy` and the - read paths — badge / /api/running): - - 1. ``_TURN_TASKS[sid]`` alive — desktop invoke/resume task (definitive); - 2. ``sid in _PENDING_RESUME`` — parked at an interrupt awaiting an answer - (definitive: the resume hasn't happened); - 3. ``_RUNNING_TURNS[sid]`` — armed at turn start; channel/goal turns carry - no task, so this is the only signal for them — BUT it can leak (an end - path that skipped its pop). Liveness is verified with - ``_RUNNING_TURNS_AT`` (stamped by engine._stream_graph, the chokepoint - every real execution passes): NO timestamp = freshly armed, still in - the preamble → conservatively busy; timestamped but silent past - RUNNING_TURN_STALE_S with no live task ⇒ leaked ⇒ heal (drop the flag) - and report not-alive, logging loudly so the leaking path can be traced. - - O(1) dict probes + one time.time() — no disk IO (badge polls this every - 5s). ``_heal=False`` turns it into a pure probe (leave the registries - untouched). + """Check turn liveness for busy gates, the badge and /api/running. + + A live desktop task, a pending interrupt, or a live task matching the + registered wake turn keeps the session busy. For a registration alone, + keep an untimestamped preamble or a recent entry. Heal a timestamped + entry once it passes RUNNING_TURN_STALE_S without any live task. + + O(1) lookups and no disk IO. ``_heal=False`` leaves the registries intact. """ import time as _time @@ -327,17 +321,22 @@ def running_turn_alive( return True if session_id in _PENDING_RESUME: return True - if session_id in _RUNNING_TURNS: - since = _RUNNING_TURNS_AT.get(session_id) - if since is None: - return True # armed but not yet in the engine — can't date it - age = _time.time() - since - if age > RUNNING_TURN_STALE_S: - if _heal: - heal_stale_running_turn(session_id, age, via) - return False + try: + turn_id = _RUNNING_TURNS[session_id] + except KeyError: + return False + wake_task = _WAKE_TURN_TASKS.get((session_id, turn_id)) + if wake_task is not None and not wake_task.done(): return True - return False + since = _RUNNING_TURNS_AT.get(session_id) + if since is None: + return True # armed but not yet in the engine — can't date it + age = _time.time() - since + if age > RUNNING_TURN_STALE_S: + if _heal: + heal_stale_running_turn(session_id, age, via) + return False + return True def turn_gate_busy(session_id: str, *, _heal: bool = True) -> bool: diff --git a/packages/runtime/src/ginno_runtime/subagent_scheduler/runner.py b/packages/runtime/src/ginno_runtime/subagent_scheduler/runner.py index 5fd1d9fc..2f459e5e 100644 --- a/packages/runtime/src/ginno_runtime/subagent_scheduler/runner.py +++ b/packages/runtime/src/ginno_runtime/subagent_scheduler/runner.py @@ -152,9 +152,13 @@ async def _run_managed_turn_locked( "echo_user": True, } } + wake_key = (session_id, turn_id) + wake_task = asyncio.current_task() + if wake_task is not None: + _NS.server_shared._WAKE_TURN_TASKS[wake_key] = wake_task _NS._RUNNING_TURNS[session_id] = turn_id - notify_turn_started(session_id) # 投递 ack(2026-11-18 方案②) try: + notify_turn_started(session_id) # 投递 ack(2026-11-18 方案②) await _run_stream( None, session["graph"], config, text, session, agent_id, user_extra_kwargs=extra_kwargs, origin="subagent", @@ -162,6 +166,7 @@ async def _run_managed_turn_locked( finally: if _NS._RUNNING_TURNS.get(session_id) == turn_id and session_id not in _NS._PENDING_RESUME: _NS._RUNNING_TURNS.pop(session_id, None) + _NS.server_shared._WAKE_TURN_TASKS.pop(wake_key, None) _NS._TURN_STOP.pop(session_id, None) if session_id not in _NS._PENDING_RESUME: try: diff --git a/packages/runtime/tests/api/test_running_work_api.py b/packages/runtime/tests/api/test_running_work_api.py new file mode 100644 index 00000000..5f48ce24 --- /dev/null +++ b/packages/runtime/tests/api/test_running_work_api.py @@ -0,0 +1,60 @@ +"""Running work reports while a Worker assignment executes in the background.""" + +from __future__ import annotations + +import asyncio + +from ginno_runtime import server_shared as shared +from ginno_runtime.testing.fake_model import ScriptedChatModel, script +from ginno_runtime.worker_bus import deliver + + +def test_running_report_keeps_long_worker_wake(client, create_session): + model_entered = asyncio.Event() + release_model = asyncio.Event() + + class HeldModel(ScriptedChatModel): + async def _astream(self, *args, **kwargs): + model_entered.set() + await release_model.wait() + async for chunk in super()._astream(*args, **kwargs): + yield chunk + + title = "Worker target" + sid = create_session(HeldModel(scripts=[script(text="Wake complete.")]), title=title) + + async def start_assignment(): + existing_tasks = set(deliver._ASSIGN_BG_TASKS) + receipt = await deliver.assign_to_worker( + "sender", sid, "Process this assignment.", async_delivery=True, + ) + assert receipt["ok"] and receipt["receipt"] == "queued", receipt + (wake_task,) = deliver._ASSIGN_BG_TASKS - existing_tasks + return wake_task + + wake_task = client.portal.call(start_assignment) + + async def backdate_live_turn(): + await asyncio.wait_for(model_entered.wait(), timeout=10) + assert not wake_task.done() + assert sid not in shared._TURN_TASKS + shared._RUNNING_TURNS_AT[sid] -= shared.RUNNING_TURN_STALE_S + 5 + return shared._RUNNING_TURNS[sid] + + async def finish_assignment(): + release_model.set() + assert await asyncio.wait_for(wake_task, timeout=10) == "ran" + + try: + turn_id = client.portal.call(backdate_live_turn) + response = client.get("/api/running") + assert response.status_code == 200 + assert response.json()["sessions"] == [{"id": sid, "title": title}] + assert client.get("/api/badge").json()["running"] == 1 + assert shared._RUNNING_TURNS[sid] == turn_id + finally: + client.portal.call(finish_assignment) + + assert client.get("/api/running").json()["sessions"] == [] + assert client.get("/api/badge").json()["running"] == 0 + assert (sid, turn_id) not in shared._WAKE_TURN_TASKS diff --git a/packages/runtime/tests/unit/test_zombie_turn_readpath.py b/packages/runtime/tests/unit/test_zombie_turn_readpath.py index 7e2e5644..4c5442d0 100644 --- a/packages/runtime/tests/unit/test_zombie_turn_readpath.py +++ b/packages/runtime/tests/unit/test_zombie_turn_readpath.py @@ -57,6 +57,36 @@ def test_alive_with_live_task_even_if_stale(): shared._RUNNING_TURNS_AT.pop("s-task", None) +async def test_wake_task_only_keeps_its_own_turn_alive(monkeypatch): + sid, tid = "s-wake", "t-wake" + release = asyncio.Event() + wake_task = asyncio.create_task(release.wait()) + monkeypatch.setitem(shared._WAKE_TURN_TASKS, (sid, tid), wake_task) + try: + _arm(sid, tid, age_s=shared.RUNNING_TURN_STALE_S + 5) + assert shared.running_turn_alive(sid) is True + + # Once stop removes the current registration, the task cannot keep + # this session busy, even if its coroutine is still unwinding. + shared._RUNNING_TURNS.pop(sid) + assert shared.running_turn_alive(sid) is False + + # An old task must not protect a leaked registration for a successor. + _arm(sid, "t-leaked", age_s=shared.RUNNING_TURN_STALE_S + 5) + assert shared.running_turn_alive(sid) is False + assert sid not in shared._RUNNING_TURNS + assert sid not in shared._RUNNING_TURNS_AT + finally: + release.set() + await wake_task + + # A finished task is no evidence of liveness even for the same turn ID. + _arm(sid, tid, age_s=shared.RUNNING_TURN_STALE_S + 5) + assert shared.running_turn_alive(sid) is False + assert sid not in shared._RUNNING_TURNS + assert sid not in shared._RUNNING_TURNS_AT + + def test_alive_when_parked_at_interrupt(): """信号②:_PENDING_RESUME(ask_user/权限卡)→ 计活(parked 是活的)。""" _arm("s-park", "t-2", age_s=shared.RUNNING_TURN_STALE_S * 3)