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(opencode): preserve stopped prewrite turns

cyhbacf23d98e3a
diff --git a/core/session_turns.py b/core/session_turns.py
index 321c7ffc8..df2dbb0c7 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -33,11 +33,7 @@ from core.message_context import (
SCHEDULED_DISPATCH_METADATA_APPLIED_KEY,
resolve_turn_sink_key,
)
-from core.native_dispatch_phase import (
- DISPATCH_PHASE_PREWRITE,
- backend_dispatch_attempted,
- set_dispatch_phase,
-)
+from core.native_dispatch_phase import backend_dispatch_attempted
from core.run_settlement import (
NON_COMPLETING_TURN_SETTLEMENTS,
SETTLEMENTS_WITHOUT_RESULT,
@@ -7169,7 +7165,6 @@ class SessionTurnManager:
else:
logical_turn_id = logical_turn_id or context_turn_id or uuid.uuid4().hex
context.platform_specific["turn_token"] = logical_turn_id
- set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)
async def _runner() -> None:
cancelled = False
@@ -7299,7 +7294,10 @@ class SessionTurnManager:
# persistence failure leaves the durable Turn unresolved for
# exact reconciliation; an empty fallback would overwrite that
# evidence with a fabricated terminal response.
- if definitive_prewrite_exit:
+ if (
+ definitive_prewrite_exit
+ and settled_by != SETTLED_BY_STOPPED
+ ):
try:
await self.controller.emit_agent_message(
context,
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 674de7343..735c393dd 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -128,6 +128,9 @@ class OpenCodeServerManager:
self._model_hub_overlay_path: Optional[str] = None
self._model_hub_overlay_hash: Optional[str] = None
self._model_hub_overlay_content: Optional[str] = None
+ self._model_hub_overlay_transition: tuple[
+ Optional[str], Optional[str], object
+ ] | None = None
self._model_hub_overlay_drain_timeout_seconds = MODEL_HUB_OVERLAY_DRAIN_TIMEOUT_SECONDS
self._runtime_activation_retire: Callable[[bool], bool] | None = None
self._runtime_generation_token: tuple[int, float | None] | None = None
@@ -464,48 +467,84 @@ class OpenCodeServerManager:
elif isinstance(content, str):
desired_content = content
drain_deadline = time.monotonic() + self._model_hub_overlay_drain_timeout_seconds
- while True:
- should_wait = False
- async with self._get_lock():
- info = self._read_pid_file() or {}
- current_server = self._pid_file_references_current_server(info)
- effective_path = info.get("model_hub_overlay_path") if current_server else None
- effective_hash = info.get("model_hub_overlay_hash") if current_server else None
- if effective_path is None and effective_hash is None:
- effective_path = self._model_hub_overlay_path
- effective_hash = self._model_hub_overlay_hash
-
- # Most turns reuse the running server's overlay. They must not
- # wait behind unrelated active work because no runtime mutation
- # is required. Cache the content so a later crash still restarts
- # with the same OPENCODE_CONFIG.
- if (effective_path, effective_hash) == (desired_path, desired_hash):
- self._model_hub_overlay_path = desired_path
- self._model_hub_overlay_hash = desired_hash
- self._model_hub_overlay_content = desired_content
- return
-
- if self._active_requests > 0 or self._has_active_run_sessions():
- should_wait = True
- else:
- persisted_active = current_server and bool(info.get("active_run_sessions"))
- if persisted_active and time.monotonic() < drain_deadline:
+ transition_owner = object()
+ owns_transition = False
+ try:
+ while True:
+ should_wait = False
+ async with self._get_lock():
+ transition = self._model_hub_overlay_transition
+ if transition is not None and transition[2] is not transition_owner:
+ # Once a real configuration change is queued, new turns on
+ # the old overlay must wait. Otherwise they can continuously
+ # replenish the active set and starve the transition.
should_wait = True
else:
- if persisted_active:
- logger.warning(
- "Ignoring stale OpenCode active-run metadata after %.1fs overlay drain timeout",
- self._model_hub_overlay_drain_timeout_seconds,
+ info = self._read_pid_file() or {}
+ current_server = self._pid_file_references_current_server(info)
+ effective_path = (
+ info.get("model_hub_overlay_path") if current_server else None
+ )
+ effective_hash = (
+ info.get("model_hub_overlay_hash") if current_server else None
+ )
+ if effective_path is None and effective_hash is None:
+ effective_path = self._model_hub_overlay_path
+ effective_hash = self._model_hub_overlay_hash
+
+ # Most turns reuse the running server's overlay. They must
+ # not wait behind unrelated active work when no transition
+ # has claimed the runtime.
+ if (effective_path, effective_hash) == (
+ desired_path,
+ desired_hash,
+ ):
+ self._model_hub_overlay_path = desired_path
+ self._model_hub_overlay_hash = desired_hash
+ self._model_hub_overlay_content = desired_content
+ return
+
+ if not owns_transition:
+ self._model_hub_overlay_transition = (
+ desired_path,
+ desired_hash,
+ transition_owner,
)
- self._model_hub_overlay_path = desired_path
- self._model_hub_overlay_hash = desired_hash
- self._model_hub_overlay_content = desired_content
- if await self._is_healthy():
- logger.info("Restarting OpenCode server after Model Hub overlay change")
- await self._restart_for_auth_refresh_locked()
- return
- if should_wait:
- await asyncio.sleep(0.05)
+ owns_transition = True
+
+ if self._active_requests > 0 or self._has_active_run_sessions():
+ should_wait = True
+ else:
+ persisted_active = current_server and bool(
+ info.get("active_run_sessions")
+ )
+ if persisted_active and time.monotonic() < drain_deadline:
+ should_wait = True
+ else:
+ if persisted_active:
+ logger.warning(
+ "Ignoring stale OpenCode active-run metadata after %.1fs overlay drain timeout",
+ self._model_hub_overlay_drain_timeout_seconds,
+ )
+ self._model_hub_overlay_path = desired_path
+ self._model_hub_overlay_hash = desired_hash
+ self._model_hub_overlay_content = desired_content
+ if await self._is_healthy():
+ logger.info(
+ "Restarting OpenCode server after Model Hub overlay change"
+ )
+ await self._restart_for_auth_refresh_locked()
+ self._model_hub_overlay_transition = None
+ owns_transition = False
+ return
+ if should_wait:
+ await asyncio.sleep(0.05)
+ finally:
+ if owns_transition:
+ async with self._get_lock():
+ transition = self._model_hub_overlay_transition
+ if transition is not None and transition[2] is transition_owner:
+ self._model_hub_overlay_transition = None
async def mark_run_active(self, session_id: str) -> None:
async with self._get_lock():
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 99af08337..df94eca7d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -105,6 +105,12 @@ scenarios:
kind: concurrency
layer: unit
test: tests/test_opencode_server.py::test_mh_runtime_002_matching_overlay_does_not_wait_for_an_unrelated_active_run
+ - id: MH-RUNTIME-003
+ name: A pending OpenCode overlay transition cannot be starved by new Turns on the old overlay
+ status: covered
+ kind: concurrency
+ layer: unit
+ test: tests/test_opencode_server.py::test_mh_runtime_003_pending_overlay_transition_blocks_new_turns_on_the_old_overlay
- id: MH-RES-LIVE-001
name: Live turn retries an eligible backup before streaming starts
status: covered
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 48c843b5d..8f5656f58 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -2401,5 +2401,50 @@ def test_changed_overlay_still_waits_for_active_run_before_restart():
manager._restart_for_auth_refresh_locked.assert_awaited_once()
+def test_mh_runtime_003_pending_overlay_transition_blocks_new_turns_on_the_old_overlay():
+ """MH-RUNTIME-003: a queued change drains without old-overlay starvation."""
+
+ manager = OpenCodeServerManager(binary="opencode", port=4096)
+ manager._model_hub_overlay_path = "/tmp/old-overlay.json"
+ manager._model_hub_overlay_hash = "old-hash"
+ manager._active_run_sessions.add("sess-active")
+ manager._read_pid_file = lambda: {} # type: ignore[method-assign]
+ manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]
+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]
+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]
+ old_overlay = types.SimpleNamespace(
+ path=Path("/tmp/old-overlay.json"),
+ content_hash="old-hash",
+ content='{"provider": {}}',
+ )
+ new_overlay = types.SimpleNamespace(
+ path=Path("/tmp/new-overlay.json"),
+ content_hash="new-hash",
+ content='{"provider": {}}',
+ )
+
+ async def exercise():
+ configuring = asyncio.create_task(
+ manager.configure_model_hub_overlay(new_overlay)
+ )
+ await asyncio.sleep(0.01)
+ matching_old_turn = asyncio.create_task(
+ manager.configure_model_hub_overlay(old_overlay)
+ )
+ await asyncio.sleep(0.01)
+ assert not matching_old_turn.done()
+ matching_old_turn.cancel()
+ await asyncio.gather(matching_old_turn, return_exceptions=True)
+ manager._active_run_sessions.clear()
+ await asyncio.wait_for(configuring, timeout=0.2)
+
+ asyncio.run(exercise())
+
+ assert manager._model_hub_overlay_path == str(new_overlay.path)
+ assert manager._model_hub_overlay_hash == new_overlay.content_hash
+ assert manager._model_hub_overlay_transition is None
+ manager._restart_for_auth_refresh_locked.assert_awaited_once()
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index bdba0ddf9..c1cb14442 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -3280,9 +3280,19 @@ def test_stop_cancels_a_starting_turn_before_native_write(managers, monkeypatch)
manager, _other, engine, _engine_b, _starts = managers
manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)
+ manager.controller.emit_agent_message = AsyncMock()
+ settle_calls: list[tuple[list[str], str]] = []
+
+ def settle_runs(run_ids, *, settled_by):
+ settle_calls.append((run_ids, settled_by))
+
+ manager.controller.scheduled_task_service = SimpleNamespace(
+ settle_agent_runs_without_result=settle_runs,
+ )
dispatch_entered = asyncio.Event()
- async def blocked_prewrite_dispatch(*_args, **_kwargs):
+ async def blocked_prewrite_dispatch(_controller, dispatch_context, *_args, **_kwargs):
+ set_dispatch_phase(dispatch_context, DISPATCH_PHASE_PREWRITE)
dispatch_entered.set()
try:
await asyncio.Event().wait()
@@ -3301,16 +3311,20 @@ def test_stop_cancels_a_starting_turn_before_native_write(managers, monkeypatch)
)
async def run() -> tuple[dict, str, str]:
+ context = _context()
admitted = await manager.deliver(
DeliveryRequest(
session_id="ses_fsm",
priority="p3",
content="stop before native write",
),
- context=_context(),
+ context=context,
)
assert admitted.turn_id and admitted.delivery_id
await asyncio.wait_for(dispatch_entered.wait(), timeout=1.0)
+ manager.in_flight["ses_fsm"].context.platform_specific[
+ "task_execution_id"
+ ] = "run-stop-prewrite"
stopped = await manager.cancel("ses_fsm")
return stopped, str(admitted.turn_id), str(admitted.delivery_id)
@@ -3324,6 +3338,8 @@ def test_stop_cancels_a_starting_turn_before_native_write(managers, monkeypatch)
}
assert "ses_fsm" not in manager.in_flight
manager.controller.command_handler.handle_stop.assert_not_awaited()
+ manager.controller.emit_agent_message.assert_not_awaited()
+ assert settle_calls == [(["run-stop-prewrite"], SETTLED_BY_STOPPED)]
with engine.connect() as conn:
turn = delivery_store.get_turn(conn, turn_id)
assert turn is not None