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(show): run Show checkpoints off the controller loop, before the prompt (#2750)

Call Whitedef45332a77e
diff --git a/core/ordered_worker.py b/core/ordered_worker.py
new file mode 100644
index 000000000..7507a8b4a
--- /dev/null
+++ b/core/ordered_worker.py
@@ -0,0 +1,77 @@
+"""One daemon thread that runs submitted work in submission order.
+
+For work the controller loop hands off and must never wait on: each job is
+started only after the one before it has finished, and its outcome is delivered
+through the ``Future`` that ``submit`` returns. The thread is a daemon, so a job
+blocked on a dead disk or a hung subprocess cannot hold process exit; ``drain``
+waits for the queue with a bound and abandons what is left.
+"""
+
+from __future__ import annotations
+
+import logging
+import queue
+import threading
+from concurrent.futures import Future
+from concurrent.futures import TimeoutError as FuturesTimeoutError
+from typing import Any, Callable
+
+logger = logging.getLogger(__name__)
+
+
+class OrderedWorker:
+ """Runs submitted jobs one at a time, in submission order, on a daemon thread."""
+
+ def __init__(self, name: str) -> None:
+ self._name = name
+ self._jobs: queue.SimpleQueue[tuple[Future[None], Callable[..., object], tuple[Any, ...]]] = (
+ queue.SimpleQueue()
+ )
+ self._start_lock = threading.Lock()
+ self._thread: threading.Thread | None = None
+
+ def submit(self, fn: Callable[..., object], *args: Any) -> Future[None]:
+ future: Future[None] = Future()
+ self._jobs.put((future, fn, args))
+ with self._start_lock:
+ if self._thread is None:
+ self._thread = threading.Thread(target=self._run, name=self._name, daemon=True)
+ self._thread.start()
+ return future
+
+ def _run(self) -> None:
+ while True:
+ future, fn, args = self._jobs.get()
+ if not future.set_running_or_notify_cancel():
+ continue
+ try:
+ fn(*args)
+ except BaseException as error: # noqa: BLE001 - delivered through the future
+ future.set_exception(error)
+ else:
+ future.set_result(None)
+
+ def drain(self, timeout: float) -> bool:
+ """Wait up to ``timeout`` for every queued job; on timeout discard the rest and return False."""
+
+ drained = self.submit(lambda: None)
+ try:
+ drained.result(timeout=timeout)
+ except FuturesTimeoutError:
+ # Python 3.10's futures timeout is not the builtin TimeoutError.
+ discarded = 0
+ while True:
+ try:
+ future, _fn, _args = self._jobs.get_nowait()
+ except queue.Empty:
+ break
+ if future.cancel() and future is not drained:
+ discarded += 1
+ logger.warning(
+ "%s work abandoned at shutdown after %.1fs: %d discarded",
+ self._name,
+ timeout,
+ discarded,
+ )
+ return False
+ return True
diff --git a/core/show_git.py b/core/show_git.py
index 09a2582a4..304238327 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import json
import logging
import os
@@ -9,6 +10,7 @@ import re
import shutil
import subprocess
import time
+from concurrent.futures import Future
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
@@ -16,6 +18,7 @@ from typing import Any
from config import paths
from core.git_binary import ResolvedGit, resolve_git
+from core.ordered_worker import OrderedWorker
from vibe.message_types import input_author_type_pairs
logger = logging.getLogger(__name__)
@@ -28,6 +31,8 @@ MAX_GITDIR_BYTES = 200 * 1024 * 1024
STALE_INDEX_LOCK_SECONDS = 5 * 60
GIT_COMMAND_TIMEOUT_SECONDS = 60
GIT_MAINTENANCE_TIMEOUT_SECONDS = 5 * 60
+# Queued checkpoints get this long at service stop before the rest are abandoned.
+CHECKPOINT_DRAIN_SECONDS = 10.0
_PLATFORM_EXCLUDES = ("node_modules/", "dist/", ".vite/")
_CHECKPOINT_KINDS = {PRE_TURN, POST_TURN, ADOPT}
@@ -713,14 +718,27 @@ _UNSET = object()
class ShowGitCheckpointService:
- """Synchronous turn-boundary subscriber owned by the Controller process."""
+ """Turn-boundary subscriber owned by the Controller process.
+
+ The bus delivers turn events on the controller loop. The subscriber records
+ them there and runs the checkpoint work, storage reads and ``git``, on one
+ ordered worker thread (#2734), so a slow or hung ``git`` stalls no Session.
+ Order is kept per event: a Turn's PRE_TURN snapshot runs before its POST_TURN
+ one, and before the next Turn's. A Turn's dispatch waits for its own PRE_TURN
+ snapshot (``wait_for_turn_start``) before the prompt reaches the backend, so
+ the snapshot still precedes the agent's first edit.
+ """
def __init__(self, git: ResolvedGit | None | object = _UNSET) -> None:
self.git = resolve_git() if git is _UNSET else git
self._bus: Any = None
self._subscription_id: int | None = None
+ # Read and written only by the worker.
self._active_turns: dict[str, _ActiveTurnCheckpoint] = {}
self._open_bus_turns: set[str] = set()
+ self._worker = OrderedWorker("show-git-checkpoints")
+ # Each Session's latest PRE_TURN job, until its dispatch has waited for it.
+ self._pre_turn_jobs: dict[str, Future[None]] = {}
@property
def enabled(self) -> bool:
@@ -746,8 +764,11 @@ class ShowGitCheckpointService:
self._bus.unsubscribe(self._subscription_id)
self._bus = None
self._subscription_id = None
+ # A Turn that ended just before shutdown still gets its POST_TURN snapshot.
+ self._worker.drain(CHECKPOINT_DRAIN_SECONDS)
self._active_turns.clear()
self._open_bus_turns.clear()
+ self._pre_turn_jobs.clear()
_record_checkpoint_service_state(False)
_checkpoint_service_active = None
@@ -857,6 +878,20 @@ class ShowGitCheckpointService:
event["turn_id"] = turn_id
self._bus.publish("turn.end", event)
+ async def wait_for_turn_start(self, session_id: str) -> None:
+ """Wait, without holding the loop, for this Session's PRE_TURN snapshot."""
+
+ job = self._pre_turn_jobs.get(session_id)
+ if job is None:
+ return
+ try:
+ # Shielded: a Stop that cancels the dispatch must not cancel the
+ # snapshot the Turn's POST_TURN checkpoint is compared against.
+ await asyncio.shield(asyncio.wrap_future(job))
+ finally:
+ if self._pre_turn_jobs.get(session_id) is job:
+ del self._pre_turn_jobs[session_id]
+
def _handle_event(self, event_type: str, data: Any) -> None:
if event_type not in {"turn.start", "turn.end"} or not isinstance(data, dict):
return
@@ -869,28 +904,37 @@ class ShowGitCheckpointService:
self._open_bus_turns.discard(session_id)
if not paths.get_show_page_dir(session_id).is_dir():
if event_type == "turn.end":
- self._active_turns.pop(session_id, None)
+ self._worker.submit(self._active_turns.pop, session_id, None)
return
+ turn_id = str(data.get("turn_id") or "").strip() or None
+ if event_type == "turn.start":
+ started_at = datetime.now(timezone.utc).isoformat()
+ self._pre_turn_jobs[session_id] = self._worker.submit(
+ self._checkpoint_turn_start, session_id, turn_id, started_at
+ )
+ else:
+ self._worker.submit(self._checkpoint_turn_end, session_id, turn_id)
+
+ def _checkpoint_turn_start(self, session_id: str, turn_id: str | None, started_at: str) -> None:
try:
- if event_type == "turn.start":
- started_at = datetime.now(timezone.utc).isoformat()
- turn_id = str(data.get("turn_id") or "").strip() or None
- context = (
- load_turn_checkpoint_context(session_id, turn_id=turn_id)
- if turn_id
- else load_turn_checkpoint_context(session_id)
- )
- self._active_turns[session_id] = _ActiveTurnCheckpoint(
- context=context,
- started_at=started_at,
- turn_id=turn_id or context.turn_id,
- )
- self._repository(session_id).checkpoint(PRE_TURN, run_id=context.run_id)
- return
+ context = (
+ load_turn_checkpoint_context(session_id, turn_id=turn_id)
+ if turn_id
+ else load_turn_checkpoint_context(session_id)
+ )
+ self._active_turns[session_id] = _ActiveTurnCheckpoint(
+ context=context,
+ started_at=started_at,
+ turn_id=turn_id or context.turn_id,
+ )
+ self._repository(session_id).checkpoint(PRE_TURN, run_id=context.run_id)
+ except Exception:
+ logger.exception("Show Page checkpoint failed at turn.start for session=%s", session_id)
+ def _checkpoint_turn_end(self, session_id: str, turn_id: str | None) -> None:
+ try:
active = self._active_turns.pop(session_id, None)
if active is None:
- turn_id = str(data.get("turn_id") or "").strip() or None
context = (
load_turn_checkpoint_context(session_id, turn_id=turn_id)
if turn_id
@@ -919,7 +963,7 @@ class ShowGitCheckpointService:
run_id=run_id,
)
except Exception:
- logger.exception("Show Page checkpoint failed at %s for session=%s", event_type, session_id)
+ logger.exception("Show Page checkpoint failed at turn.end for session=%s", session_id)
def _repository(self, session_id: str) -> ShowGitRepository:
if not isinstance(self.git, ResolvedGit):
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index d69316766..bd2caf6f2 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -8,13 +8,10 @@ import ipaddress
import json
import logging
import os
-import queue
import copy
import re
import shutil
-import threading
from concurrent.futures import Future
-from concurrent.futures import TimeoutError as FuturesTimeoutError
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Callable, Literal, Mapping, Optional, cast
@@ -24,6 +21,7 @@ from config import paths
from config.atomic_io import write_atomic
from config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig, ModelHubSourceConfig
from core.handlers.model_hub.capability_evidence import identity_digest
+from core.ordered_worker import OrderedWorker
from core.handlers.model_hub.classification import ResolutionDecision
from core.handlers.model_hub.events import (
EventAgent,
@@ -74,70 +72,11 @@ logger = logging.getLogger(__name__)
LaunchChannel = Literal["direct", "native_cli", "hub"]
TurnMode = Literal["direct", "hub"]
-class _TurnModeWriter:
- """Stamps each settled turn's mode on its Message rows, one at a time, in settlement order.
-
- Settlement runs on the service's event loop and never waits on this
- database write. The worker is a daemon thread: an abandoned stamp costs only
- that turn's provenance detail, and SQLite rolls back a write cut off
- mid-transaction, so nothing here may hold process exit.
- """
-
- def __init__(self, name: str) -> None:
- self._name = name
- self._jobs: queue.SimpleQueue[tuple[Future[None], Callable[..., object], tuple[Any, ...]]] = (
- queue.SimpleQueue()
- )
- self._start_lock = threading.Lock()
- self._thread: threading.Thread | None = None
-
- def submit(self, fn: Callable[..., object], *args: Any) -> Future[None]:
- future: Future[None] = Future()
- self._jobs.put((future, fn, args))
- with self._start_lock:
- if self._thread is None:
- self._thread = threading.Thread(target=self._run, name=self._name, daemon=True)
- self._thread.start()
- return future
-
- def _run(self) -> None:
- while True:
- future, fn, args = self._jobs.get()
- if not future.set_running_or_notify_cancel():
- continue
- try:
- fn(*args)
- except BaseException as error: # noqa: BLE001 - delivered through the future
- future.set_exception(error)
- else:
- future.set_result(None)
-
- def drain(self, timeout: float) -> bool:
- """Wait up to ``timeout`` for every queued stamp; on timeout discard the rest and return False."""
-
- drained = self.submit(lambda: None)
- try:
- drained.result(timeout=timeout)
- except FuturesTimeoutError:
- # Python 3.10's futures timeout is not the builtin TimeoutError.
- discarded = 0
- while True:
- try:
- future, _fn, _args = self._jobs.get_nowait()
- except queue.Empty:
- break
- if future.cancel() and future is not drained:
- discarded += 1
- logger.warning(
- "Model Hub turn mode stamps abandoned at shutdown after %.1fs: %d discarded",
- timeout,
- discarded,
- )
- return False
- return True
-
-
-_TURN_MODE_WRITER = _TurnModeWriter("model-hub-turn-mode")
+# Stamps each settled turn's mode on its Message rows, one at a time, in settlement
+# order. Settlement never waits on this database write; an abandoned stamp costs
+# only that turn's provenance detail, and SQLite rolls back a write cut off
+# mid-transaction.
+_TURN_MODE_WRITER = OrderedWorker("model-hub-turn-mode")
def _log_turn_mode_failure(stamp: Future[None]) -> None:
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 6c7de63be..74a09dad4 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -475,6 +475,9 @@ class AgentService:
# are optional and guarded so a missing hook or a bubble failure can
# never break the turn.
await self._begin_turn_status(request.context)
+ # The Turn's PRE_TURN Show checkpoint runs off the loop; the prompt
+ # waits for it so the snapshot precedes the agent's first edit (#2734).
+ await self._wait_for_show_checkpoint(request.context)
from core.agent_model_selection import require_agent_model
from modules.agents.catalog import AGENT_BACKENDS, is_builtin_backend
from modules.agents.model_hub import ModelSupplyRefusal, hold_refused_input, hub_supply_refusal
@@ -1419,6 +1422,18 @@ class AgentService:
except Exception:
logger.debug("begin_status_bubble failed at turn start", exc_info=True)
+ async def _wait_for_show_checkpoint(self, context: Any) -> None:
+ """Wait for the Session's PRE_TURN Show checkpoint, if one is queued."""
+
+ service = getattr(self.controller, "show_git_checkpoint_service", None)
+ wait = getattr(service, "wait_for_turn_start", None)
+ session_id_from_context = getattr(self.controller, "_session_id_from_context", None)
+ if not callable(wait) or not callable(session_id_from_context):
+ return
+ session_id = session_id_from_context(context)
+ if session_id:
+ await wait(session_id)
+
async def _emit_staged_harness_prompt(self, context: Any) -> None:
"""Echo a staged Harness prompt into its IM conversation at turn start.
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index 83844974e..8bb534a0b 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -126,17 +126,30 @@ class _OrderRecordingDispatcher:
return "echo-msg"
+class _OrderRecordingCheckpoints:
+ def __init__(self, log: list[str]):
+ self._log = log
+
+ async def wait_for_turn_start(self, session_id):
+ self._log.append(f"show_checkpoint:{session_id}")
+
+
class _TurnStartController:
"""Records the relative order of the turn-start hooks vs the agent run."""
def __init__(self, log: list[str]):
self.session_turns = _OrderRecordingTurnManager(log)
self.message_dispatcher = _OrderRecordingDispatcher(log)
+ self.show_git_checkpoint_service = _OrderRecordingCheckpoints(log)
self._log = log
def update_thread_message_id(self, _context):
self._log.append("update_thread_message_id")
+ @staticmethod
+ def _session_id_from_context(_context):
+ return "ses_order"
+
class _OrderRecordingAgent(_RuntimeAgent):
def __init__(self, log: list[str]):
@@ -164,10 +177,13 @@ def test_agent_service_runs_turn_start_hooks_after_gate_before_agent() -> None:
# on_running (gate confirmed) must precede the bubble hooks, which in turn
# precede the agent run. This is what keeps a queued turn from claiming
# the trigger id / posting a premature bubble before it actually starts.
+ # The Session's PRE_TURN Show checkpoint is waited for before the prompt
+ # reaches the backend, so it snapshots the workspace before any edit.
assert log == [
"on_running",
"update_thread_message_id",
"begin_status_bubble",
+ "show_checkpoint:ses_order",
"handle_message",
]
assert backend_dispatch_attempted(request.context) is False
diff --git a/tests/test_show_git.py b/tests/test_show_git.py
index 4503faa6e..94e7f2413 100644
--- a/tests/test_show_git.py
+++ b/tests/test_show_git.py
@@ -5,6 +5,7 @@ import json
import os
import shutil
import subprocess
+import threading
import time
from pathlib import Path
from types import SimpleNamespace
@@ -624,6 +625,8 @@ def test_duplicate_turn_events_do_not_create_duplicate_checkpoint_commits(resolv
bus.publish("turn.start", {"session_id": session_id})
bus.publish("turn.start", {"session_id": session_id})
+ # The Turn's dispatch waits for its PRE_TURN snapshot before the agent edits.
+ asyncio.run(service.wait_for_turn_start(session_id))
(workspace / "page.txt").write_text("after\n", encoding="utf-8")
bus.publish("turn.end", {"session_id": session_id})
bus.publish("turn.end", {"session_id": session_id})
@@ -637,6 +640,55 @@ def test_duplicate_turn_events_do_not_create_duplicate_checkpoint_commits(resolv
]
+def test_turn_checkpoints_run_off_the_publishing_thread_in_event_order(resolved_git, monkeypatch):
+ """#2734: a checkpoint's ``git`` work used to run inside ``bus.publish`` on the
+ controller loop, so a slow or hung ``git`` stalled every Session. The publish
+ now returns at once; the Turn's dispatch waits for its PRE_TURN snapshot without
+ holding the loop, and POST_TURN still follows PRE_TURN."""
+
+ session_id = "ses_bus_off_loop"
+ _workspace(session_id)
+ release = threading.Event()
+ calls = []
+
+ class HeldRepository:
+ def checkpoint(self, checkpoint, **kwargs):
+ if checkpoint == PRE_TURN:
+ release.wait(10)
+ calls.append(checkpoint)
+ return True
+
+ monkeypatch.setattr(
+ show_git,
+ "load_turn_checkpoint_context",
+ lambda _session_id, **_kwargs: TurnCheckpointContext(message="edit"),
+ )
+ service = ShowGitCheckpointService(resolved_git)
+ monkeypatch.setattr(service, "_repository", lambda _session_id: HeldRepository())
+ bus = InboxEventBus()
+ service.start(bus)
+
+ async def run() -> None:
+ started = time.monotonic()
+ bus.publish("turn.start", {"session_id": session_id})
+ bus.publish("turn.end", {"session_id": session_id})
+ assert time.monotonic() - started < 1.0, "the publisher waited for git"
+ waiting = asyncio.create_task(service.wait_for_turn_start(session_id))
+ # The loop keeps turning while git is held.
+ await asyncio.sleep(0.05)
+ assert not waiting.done(), "the dispatch did not wait for the PRE_TURN snapshot"
+ release.set()
+ await asyncio.wait_for(waiting, 10)
+
+ try:
+ asyncio.run(run())
+ finally:
+ release.set()
+ service.stop()
+
+ assert calls == [PRE_TURN, POST_TURN]
+
+
def test_shared_turn_hooks_reuse_path_owned_bus_lifecycle(resolved_git, monkeypatch):
session_id = "ses_path_owned"
context = SimpleNamespace(platform="avibe", platform_specific={"agent_session_id": session_id})