Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(runtime): answer a caught cancellation when a store step fails, at every runtime-work door (#2661)

Call Whitee11b76e2d881
diff --git a/core/internal_server.py b/core/internal_server.py
index 26a57cad9..e4f8f7bb3 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -236,28 +236,22 @@ def create_app(
return await supervisor.run_sync(operation)
return await asyncio.to_thread(operation)
- async def _off_loop(operation: Callable[[], Any]) -> tuple[Any, bool]:
+ async def _off_loop(operation: Callable[[], Any]) -> tuple["asyncio.Future[Any]", bool]:
"""Run one scheduled-turn store step on the runtime-work executor, the door the
scheduler's own store work uses, so its write-lock wait and commit never hold
the loop (#2630).
Cancellation cannot split the step, as it could not while the step ran
synchronously on the loop: one that arrives meanwhile waits for the step to
- land. Returns ``(result, cancelled)``, and the caller answers the cancellation
- from what the step committed. Once a Run's ownership has moved to its Delivery,
- the answer is recovery, never an escaping cancellation that would let the
- executor settle the Run and drop the turn.
+ land. Returns the landed step and whether a cancellation was caught, and the
+ caller answers the cancellation from what the step committed. Once a Run's
+ ownership has moved to its Delivery, the answer is recovery, never an escaping
+ cancellation that would let the executor settle the Run and drop the turn.
"""
- step = asyncio.ensure_future(_run_store_step(operation))
- cancelled = False
- while True:
- try:
- return await asyncio.shield(step), cancelled
- except asyncio.CancelledError:
- if step.cancelled():
- raise
- cancelled = True
+ from core.runtime_work import land_step
+
+ return await land_step(_run_store_step(operation))
async def _submit_scheduled_turn(
session_id: str,
@@ -280,6 +274,7 @@ def create_app(
from core.message_mirror import _scope_id_for_session
from core.message_priority import normalize_delivery_intent
+ from core.runtime_work import answer_caught_cancellation, step_failed
from core.session_turns import (
DeliveryRequest,
SCHEDULED_PROVENANCE_KEY,
@@ -528,7 +523,11 @@ def create_app(
delivery_owner_transferred = True
return _ADMITTED
- admission, admission_cancelled = await _off_loop(_admit_delivery)
+ admission_step, admission_cancelled = await _off_loop(_admit_delivery)
+ if admission_cancelled and not delivery_owner_transferred and step_failed(admission_step):
+ # A failed admission moved nothing to the Delivery: answer the cancellation, not its error.
+ answer_caught_cancellation(admission_step)
+ admission = admission_step.result()
if admission is not _ADMITTED:
if admission_cancelled and not getattr(admission, "delivery_owner_transferred", False):
raise asyncio.CancelledError
@@ -591,7 +590,8 @@ def create_app(
delivery_status = "reserved"
try:
# Already answering a cancellation: a further one cannot change the answer.
- (delivery_status, recorded), _cancelled = await _off_loop(_record_deferred_outcome)
+ deferred_step, _cancelled = await _off_loop(_record_deferred_outcome)
+ delivery_status, recorded = deferred_step.result()
if not recorded:
logger.warning(
"Agent Run deferred Delivery outcome lost its exact CAS: "
@@ -689,7 +689,8 @@ def create_app(
try:
# Ownership has moved to the Delivery: the submission's answer must reach
# the executor, so a cancellation here does not escape it.
- recorded, _cancelled = await _off_loop(_record_outcome)
+ outcome_step, _cancelled = await _off_loop(_record_outcome)
+ recorded = outcome_step.result()
if not recorded:
logger.warning(
"Agent Run Delivery outcome lost its exact CAS after ownership "
diff --git a/core/runtime_work.py b/core/runtime_work.py
index fdbbf4e4c..7a2539d2c 100644
--- a/core/runtime_work.py
+++ b/core/runtime_work.py
@@ -11,7 +11,7 @@ from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from enum import Enum
from functools import partial
-from typing import Any, Protocol, TypeVar
+from typing import Any, NoReturn, Protocol, TypeVar
from core.inbox_events import (
DEFINITIONS_UPDATED_EVENT,
@@ -26,6 +26,48 @@ logger = logging.getLogger(__name__)
_T = TypeVar("_T")
+
+async def land_step(step: Awaitable[_T]) -> tuple[asyncio.Future[_T], bool]:
+ """Wait for one store step to finish, whatever cancels the caller meanwhile.
+
+ A Python thread cannot be cancelled safely, and a step a cancellation split would
+ leave what it committed unowned, so the step is never cancelled: every
+ cancellation that reaches the caller meanwhile is caught instead. Returns the
+ finished step, whose ``result()`` gives its outcome, and whether a cancellation
+ was caught, for the caller to answer from that outcome.
+ """
+
+ future = asyncio.ensure_future(step)
+ cancelled = False
+ while not future.done():
+ try:
+ # ``wait`` never cancels the step, and raises only the caller's cancellation.
+ await asyncio.wait((future,))
+ except asyncio.CancelledError:
+ cancelled = True
+ return future, cancelled
+
+
+def step_failed(step: asyncio.Future[Any]) -> bool:
+ return step.cancelled() or step.exception() is not None
+
+
+def answer_caught_cancellation(step: asyncio.Future[Any]) -> NoReturn:
+ """Answer a cancellation ``land_step`` caught, now.
+
+ A failed step has no result to hand back, so this is also how a caller that keeps
+ a landed step's result answers a failed one: its error is logged and kept as the
+ cancellation's cause, never left to replace the cancellation.
+ """
+
+ error = None if step.cancelled() else step.exception()
+ if error is not None:
+ logger.warning(
+ "A store step failed while its caller was being cancelled; answering the cancellation",
+ exc_info=error,
+ )
+ raise asyncio.CancelledError from error
+
_DEFAULT_RECONCILE_INTERVAL_SECONDS = 30.0
_DEFAULT_LANE_CAPACITY = 4
_DEFAULT_SCAN_PAGE_SIZE = 32
@@ -479,23 +521,15 @@ class RuntimeWorkSupervisor:
loop = asyncio.get_running_loop()
future = loop.run_in_executor(self._sync_executor, operation)
self._sync_futures.add(future)
- cancelled = False
try:
- while True:
- try:
- result = await asyncio.shield(future)
- break
- except asyncio.CancelledError:
- # Python threads are not safely cancellable. Consume every
- # cancellation until the exact store operation exits; the
- # partition task remains the owner throughout.
- cancelled = True
- if cancelled:
- raise asyncio.CancelledError
- return result
+ # The partition task remains the owner until the exact store operation exits.
+ future, cancelled = await land_step(future)
finally:
if future.done():
self._sync_futures.discard(future)
+ if cancelled:
+ answer_caught_cancellation(future)
+ return future.result()
async def stop(self) -> None:
stop_task = self._begin_stop()
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 43cd2dcb4..c7176fd70 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -52,6 +52,9 @@ from core.runtime_work import (
RuntimeWorkLane,
RuntimeWorkRegistrationToken,
RuntimeWorkSupervisor,
+ answer_caught_cancellation,
+ land_step,
+ step_failed,
)
from core.run_settlement import (
INTERRUPT_REASON_DELIVERY_TARGET_MISSING,
@@ -5052,16 +5055,12 @@ class ScheduledTaskService:
A store step cannot be split by cancellation, as it could not while it ran on
the loop: a cancellation that arrives meanwhile waits for the step to land and
- is raised after it, so the caller sees exactly what committed. A step that
- raised raises its own error, with the cancellation re-armed behind it.
+ is raised after it, so the caller sees exactly what committed.
"""
step, cancelled = await self._land_runtime_step(operation, *args, **kwargs)
- if cancelled and not step.cancelled():
- if step.exception() is not None:
- _rearm_cancellation()
- return step.result()
- raise asyncio.CancelledError
+ if cancelled:
+ answer_caught_cancellation(step)
return step.result()
async def _store_step(self, operation, /, *args, **kwargs): # noqa: ANN001, ANN202
@@ -5070,40 +5069,32 @@ class ScheduledTaskService:
These steps ran synchronously on the loop before #2649, so a cancellation could
land only at the execution's next real await -- the dispatch, the command, a
- delivery -- with every step before it complete and its outcome in hand. It still
+ delivery -- with every step before it complete and its result in hand. It still
does: a cancellation that arrives while a step runs waits for the step to land,
- the step's result is returned (or its error raised), and the cancellation is
- re-armed for the next await that is not itself a store step. So a result a step
- committed (a reservation, a binding recovery, a settlement) is never dropped
- between steps, and each cancellation is answered where the execution always
- answered it.
+ the step's result is returned, and the cancellation is re-armed for the next
+ await that is not itself a store step. So a result a step committed (a
+ reservation, a binding recovery, a settlement) is never dropped between steps,
+ and each cancellation is answered where the execution always answered it. A
+ step that failed has no result to hand back, so its cancellation is answered
+ at once, even where no await follows.
"""
step, cancelled = await self._land_runtime_step(operation, *args, **kwargs)
- if cancelled and not step.cancelled():
+ if cancelled:
+ if step_failed(step):
+ answer_caught_cancellation(step)
_rearm_cancellation()
return step.result()
async def _land_runtime_step(self, operation, /, *args, **kwargs): # noqa: ANN001, ANN202
- """Run one store step on the runtime-work door and wait for it to land, whatever
- cancels the caller meanwhile. Returns ``(step, cancelled)``: the finished step,
- whose ``result()`` gives its outcome, and whether a cancellation was caught."""
+ """Run one store step on the runtime-work door and ``land_step`` it."""
call = partial(operation, *args, **kwargs)
supervisor = getattr(self.controller, "runtime_work_supervisor", None)
# Gate on the type: a stand-in controller's attribute can be callable without being awaitable.
if isinstance(supervisor, RuntimeWorkSupervisor):
- step = asyncio.ensure_future(supervisor.run_sync(call))
- else:
- step = asyncio.ensure_future(asyncio.to_thread(call))
- cancelled = False
- while not step.done():
- try:
- # ``wait`` never cancels the step, and raises only the caller's cancellation.
- await asyncio.wait((step,))
- except asyncio.CancelledError:
- cancelled = True
- return step, cancelled
+ return await land_step(supervisor.run_sync(call))
+ return await land_step(asyncio.to_thread(call))
def _start_legacy_runtime_work_probes(self) -> None:
if self.store.sqlite_backend is None:
@@ -5404,7 +5395,10 @@ class ScheduledTaskService:
pass
# A claim cancelled before it ran is settled by an owned task its done-callback
# started; it lands before shutdown returns, like an execution's own settlement.
- if self._cancel_settlements:
+ # An execution already done when it was awaited above did not suspend, so its
+ # done-callback may still be pending: yield to it, then drain until none is left.
+ await asyncio.sleep(0)
+ while self._cancel_settlements:
await asyncio.gather(*tuple(self._cancel_settlements), return_exceptions=True)
teardown = self._ensure_service_teardown_task()
if teardown is not None:
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 0413a5ae9..bec483d2b 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -8595,15 +8595,20 @@ def test_a_scheduled_turns_admission_never_holds_the_loop(monkeypatch, tmp_path)
assert released_in_time == [True]
-def test_a_cancellation_during_admission_keeps_the_runs_delivery_ownership(monkeypatch, tmp_path):
[email protected]("admission_fails", [False, True])
+def test_a_cancellation_during_admission_keeps_the_runs_delivery_ownership(monkeypatch, tmp_path, admission_fails):
"""#2630: admission runs on a thread now, so a cancellation can arrive while it waits for SQLite's write lock.
Once its transaction moves the Run's ownership to the Delivery, the submission must hand the turn to recovery,
- as a cancellation during delivery does, instead of letting the Run be terminalized and the turn dropped."""
+ as a cancellation during delivery does, instead of letting the Run be terminalized and the turn dropped.
+
+ #2657: an admission that fails moved nothing, so the submission answers the cancellation, not the error: the
+ error would have the executor settle an ordinary failure instead of the stop or shutdown that cancelled it."""
import sqlite3
import threading
from core import session_turns
from core.scheduled_tasks import TaskExecutionStore
+ from storage import background
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
engine, session = _create_test_session(tmp_path, native_id="proj_admission_cancel")
@@ -8643,6 +8648,12 @@ def test_a_cancellation_during_admission_keeps_the_runs_delivery_ownership(monke
},
)
held, release = threading.Event(), threading.Event()
+ if admission_fails:
+
+ def _refuse_binding(*_args, **_kwargs):
+ raise sqlite3.OperationalError("disk I/O error")
+
+ monkeypatch.setattr(background, "attach_agent_run_delivery_in_connection", _refuse_binding)
def _hold_write_lock() -> None:
holder = sqlite3.connect(engine.url.database, timeout=10)
@@ -8666,10 +8677,16 @@ def test_a_cancellation_during_admission_keeps_the_runs_delivery_ownership(monke
release.set()
try:
return await submitting
+ except asyncio.CancelledError:
+ return "cancelled"
finally:
await asyncio.to_thread(holder.join, 5)
result = asyncio.run(_go())
- assert result.delivery_owner_transferred is True
stored = request_store.get_run(run.id)
+ if admission_fails:
+ assert result == "cancelled", f"the admission's error replaced the cancellation: {result!r}"
+ assert not stored["delivery_id"]
+ return
+ assert result.delivery_owner_transferred is True
assert stored["delivery_id"] and stored["status"] in {"running", "queued"}
diff --git a/tests/test_runtime_work_supervisor.py b/tests/test_runtime_work_supervisor.py
index 74c455107..6e3cf80cb 100644
--- a/tests/test_runtime_work_supervisor.py
+++ b/tests/test_runtime_work_supervisor.py
@@ -1630,6 +1630,41 @@ async def test_hfr_160_canceled_sync_worker_remains_owner_until_thread_exits() -
await supervisor.stop()
+async def test_a_store_operation_that_fails_while_its_caller_is_cancelled_answers_the_cancellation() -> None:
+ """#2657: ``run_sync`` holds a cancellation that arrives while its store operation runs until the operation exits.
+ An operation that then fails has no result to hand back, so the cancellation is answered, with the error as its
+ cause, rather than replaced by the error: a caller would settle that as an ordinary failure, not a stop."""
+
+ started = threading.Event()
+ release = threading.Event()
+ causes: list[BaseException | None] = []
+
+ def failing_store_call() -> str:
+ started.set()
+ release.wait(5)
+ raise RuntimeError("store error")
+
+ supervisor = RuntimeWorkSupervisor(reconcile_interval=3600)
+
+ async def caller() -> None:
+ try:
+ await supervisor.run_sync(failing_store_call)
+ except asyncio.CancelledError as exc:
+ causes.append(exc.__cause__)
+ raise
+
+ task = asyncio.create_task(caller())
+ assert await asyncio.to_thread(started.wait, 1)
+ task.cancel()
+ await asyncio.sleep(0.05)
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert [str(cause) for cause in causes] == ["store error"]
+ await supervisor.stop()
+
+
@pytest.mark.anyio
async def test_hfr_164_unregister_joins_partition_not_outer_caller_task() -> None:
"""HFR-164: lane teardown joins only the exact protected operation."""
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 0fc198b96..31b20585d 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -20601,15 +20601,24 @@ class _TaskWithoutCancelCount:
@pytest.mark.parametrize(
- ("door", "step_raises", "python310"),
- [("_store_step", True, False), ("_run_runtime_sync", True, False), ("_store_step", False, True)],
+ ("door", "step_raises", "python310", "expected"),
+ [
+ ("_store_step", False, False, ["step result", "cancelled at the next await"]),
+ ("_store_step", False, True, ["step result", "cancelled at the next await"]),
+ ("_store_step", True, False, ["cancelled at the door, caused by: step error"]),
+ ("_run_runtime_sync", False, False, ["cancelled at the door, caused by: None"]),
+ ("_run_runtime_sync", True, False, ["cancelled at the door, caused by: step error"]),
+ ],
)
-def test_a_cancellation_caught_by_a_store_step_is_answered_at_the_next_await(
- tmp_path: Path, monkeypatch, door: str, step_raises: bool, python310: bool
+def test_a_cancellation_caught_by_a_store_step_is_answered_from_its_outcome(
+ tmp_path: Path, monkeypatch, door: str, step_raises: bool, python310: bool, expected: list[str]
) -> None:
- """#2649: a store step on the runtime-work door holds a cancellation that arrives while it runs until it lands, then
- hands it back for the caller's next await -- also when the step raised (its error must not swallow the cancellation
- and let the caller settle an ordinary failure), and on Python 3.10, whose tasks keep no cancellation count."""
+ """#2649, #2660: a store step on the runtime-work door holds a cancellation that arrives while it runs until it
+ lands, then answers it from the step's outcome. ``_store_step`` hands a landed step's result back and the
+ cancellation to the caller's next await (also on Python 3.10, whose tasks keep no cancellation count);
+ ``_run_runtime_sync`` answers it at once. A failed step has no result to hand back, so either door answers its
+ cancellation at once, with the error as its cause: an error that replaced the cancellation would let the caller
+ settle an ordinary failure, or end the task failed where no await follows."""
service = ScheduledTaskService(
controller=SimpleNamespace(platform_settings_managers={}, im_clients={}),
@@ -20635,8 +20644,9 @@ def test_a_cancellation_caught_by_a_store_step_is_answered_at_the_next_await(
async def caller() -> None:
try:
outcomes.append(await getattr(service, door)(step))
- except RuntimeError as exc:
- outcomes.append(str(exc))
+ except asyncio.CancelledError as exc:
+ outcomes.append(f"cancelled at the door, caused by: {exc.__cause__}")
+ raise
try:
await asyncio.sleep(5)
except asyncio.CancelledError:
@@ -20653,9 +20663,10 @@ def test_a_cancellation_caught_by_a_store_step_is_answered_at_the_next_await(
await run
asyncio.run(_go())
- assert outcomes == ["step error" if step_raises else "step result", "cancelled at the next await"]
+ assert outcomes == expected
[email protected](sys.version_info < (3, 11), reason="Task.uncancel and asyncio.timeout are Python 3.11+")
def test_a_timeout_that_expires_during_a_store_step_still_reads_as_a_timeout(tmp_path: Path) -> None:
"""#2649: a cancellation a store step holds and re-arms is counted once, so an ``asyncio.timeout`` around the caller
still turns its own expiry into ``TimeoutError`` instead of letting a bare cancellation escape the caller."""
@@ -20673,3 +20684,62 @@ def test_a_timeout_that_expires_during_a_store_step_still_reads_as_a_timeout(tmp
await asyncio.sleep(5)
asyncio.run(_go())
+
+
+def test_a_claim_whose_terminal_settlement_fails_while_cancelled_is_settled_as_cancelled(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """#2660: a claimed execution's terminal settlement is its last step, with no await after it. When a cancellation
+ arrives while it runs and the settlement then fails, the execution must still end cancelled, so the cancelled-claim
+ settlement takes over, instead of ending failed with the run left ``running`` and its claim no longer live."""
+
+ service, request_store, claimed = _sqlite_claimed_agent_run(tmp_path, monkeypatch)
+ service._execute_agent_run = AsyncMock( # type: ignore[assignment]
+ return_value=scheduled_tasks.AgentRunExecutionResult(error=None, complete_on_return=True)
+ )
+ entered, release = threading.Event(), threading.Event()
+
+ def failing_settlement(*_args, **_kwargs):
+ entered.set()
+ assert release.wait(5)
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(service, "_settle_claimed_request", failing_settlement)
+
+ async def _go() -> None:
+ service._spawn_execution(claimed, None)
+ execution = service._inflight_executions[claimed.id]
+ assert await asyncio.to_thread(entered.wait, 5)
+ execution.cancel()
+ await asyncio.sleep(0.05)
+ release.set()
+ await asyncio.gather(execution, return_exceptions=True)
+ assert execution.cancelled(), "the settlement's error replaced the cancellation"
+ for _ in range(100):
+ if not service._cancel_settlements:
+ break
+ await asyncio.sleep(0.05)
+
+ asyncio.run(_go())
+ settled = request_store.get_run(claimed.id)
+ assert settled["status"] != "running", "the run was left running, with no live claim to settle it"
+ assert claimed.id not in service._live_claimed_run_ids
+
+
+def test_stop_waits_for_the_settlement_of_a_claim_cancelled_just_before_it(tmp_path: Path, monkeypatch) -> None:
+ """#2660: ``stop`` joins every execution, then the settlements their done-callbacks start. An execution already
+ cancelled and done when ``stop`` awaits it does not suspend, so its done-callback may not have run yet: ``stop``
+ must still wait for the settlement that callback starts, not return with the claim's requeue pending."""
+
+ service, request_store, claimed = _sqlite_claimed_agent_run(tmp_path, monkeypatch)
+
+ async def _go() -> str:
+ service._spawn_execution(claimed, None)
+ execution = service._inflight_executions[claimed.id]
+ execution.cancel()
+ await asyncio.sleep(0)
+ assert execution.cancelled() and claimed.id in service._inflight_executions, "its done-callback already ran"
+ await service.stop()
+ return request_store.get_run(claimed.id)["status"]
+
+ assert asyncio.run(_go()) == "queued", "stop returned before the cancelled claim was given back to the queue"