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(sessions): archive without waiting on Memory flush (#1582)

Call Whitefec03e086630
diff --git a/core/controller.py b/core/controller.py
index 2bcf4a439..7094d8beb 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -2219,22 +2219,83 @@ class Controller:
logger.debug("Memory multi-scope final flush failed", exc_info=True)
return False
+ def _schedule_best_effort_archive_memory_flush(self, raw_session_id: str) -> None:
+ """Flush Memory for an archived session without owning the archive result."""
+
+ async def _flush() -> None:
+ try:
+ await self.final_flush_memory_cli_session(raw_session_id)
+ except Exception:
+ logger.debug(
+ "archive: best-effort Memory flush failed for %s",
+ raw_session_id,
+ exc_info=True,
+ )
+
+ def _consume(task: asyncio.Task[None]) -> None:
+ tasks = getattr(self, "_archive_memory_flush_tasks", None)
+ if tasks is not None:
+ tasks.discard(task)
+ try:
+ task.result()
+ except (asyncio.CancelledError, concurrent.futures.CancelledError):
+ return
+ except Exception:
+ logger.debug(
+ "archive: best-effort Memory flush failed for %s",
+ raw_session_id,
+ exc_info=True,
+ )
+
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = getattr(self, "_loop", None)
+ if loop is None or loop.is_closed():
+ logger.debug(
+ "archive: Memory flush dropped; no event loop for %s",
+ raw_session_id,
+ )
+ return
+ future = asyncio.run_coroutine_threadsafe(_flush(), loop)
+
+ def _consume_future(completed: concurrent.futures.Future[None]) -> None:
+ if completed.cancelled():
+ return
+ error = completed.exception()
+ if error is not None:
+ logger.debug(
+ "archive: best-effort Memory flush failed for %s",
+ raw_session_id,
+ exc_info=error,
+ )
+
+ future.add_done_callback(_consume_future)
+ return
+
+ task = loop.create_task(
+ _flush(),
+ name=f"archive-memory-flush:{raw_session_id}",
+ )
+ tasks = getattr(self, "_archive_memory_flush_tasks", None)
+ if tasks is None:
+ self._archive_memory_flush_tasks = tasks = set()
+ tasks.add(task)
+ task.add_done_callback(_consume)
+
async def archive_memory_cli_session(
self,
raw_session_id: str,
*,
deadline_seconds: float = 5.0,
) -> dict[str, Any]:
- """Archive one Workbench session inside its exact Memory capture fence.
+ """Archive one Workbench session without waiting on Memory.
- This is a closed controller-owned use case for the UI process. The UI
- supplies only the durable Workbench session ID; canonical Memory identity
- is resolved here, and the terminal database mutation stays inside the same
- runtime lifecycle operation as final flush.
+ The controller still owns the terminal session write. Memory final flush
+ is best-effort after that write commits: a failed, busy, or fenced Memory
+ runtime must not block or roll back archive.
"""
- from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID
- from core.memory.store import is_principal_id, is_project_id
from core.services import sessions as workbench_sessions_service
from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
from storage.db import create_sqlite_engine
@@ -2275,59 +2336,34 @@ class Controller:
engine.dispose()
async def archive_operation() -> dict[str, Any]:
- # Cancelling the socket request must not release Memory admission
- # while SQLite is still committing the terminal transition.
- return await run_blocking(archive_session)
+ loop = asyncio.get_running_loop()
- async def run_memory_lifecycle() -> dict[str, Any]:
- live_scope = self.memory_scope_for_cli_session(raw_session_id)
- runtime = getattr(self, "memory_runtime", None)
- resolve_scopes = getattr(runtime, "resolve_current_session_scopes", None)
- if not callable(resolve_scopes):
- raise RuntimeError("Memory session scope recovery is unavailable")
- durable_scopes = await resolve_scopes(raw_session_id)
- if durable_scopes is None:
- raise RuntimeError("Memory session scopes could not be recovered safely")
-
- scopes = set(durable_scopes)
- if live_scope is not None:
- scopes.add(live_scope)
- if not scopes:
- return await archive_operation()
- for scope in scopes:
- if (
- not isinstance(scope, tuple)
- or len(scope) != 2
- or not is_principal_id(scope[0])
- or not is_project_id(scope[1])
- ):
- raise RuntimeError("invalid canonical Memory session scope")
- canonical_scopes = tuple(
- sorted(
- scopes,
- key=lambda scope: (scope[1] != DEFAULT_MEMORY_PROJECT_ID, scope),
- )
- )
+ def archive_and_schedule() -> dict[str, Any]:
+ session = archive_session()
+ # Schedule before run_blocking can re-raise a pending cancellation.
+ try:
+ loop.call_soon_threadsafe(
+ self._schedule_best_effort_archive_memory_flush,
+ raw_session_id,
+ )
+ except RuntimeError:
+ logger.debug(
+ "archive: Memory flush dropped; event loop closed for %s",
+ raw_session_id,
+ )
+ return session
- run_lifecycle = getattr(runtime, "run_session_scopes_lifecycle", None)
- if not callable(run_lifecycle):
- raise RuntimeError("Memory session lifecycle is unavailable")
- return await run_lifecycle(
- scopes=canonical_scopes,
- raw_session_id=raw_session_id,
- operation=archive_operation,
- deadline_seconds=deadline_seconds,
- )
+ return await run_blocking(archive_and_schedule)
turn_manager = getattr(self, "session_turns", None)
turn_lifecycle = getattr(turn_manager, "run_session_lifecycle", None)
if callable(turn_lifecycle):
return await turn_lifecycle(
raw_session_id,
- run_memory_lifecycle,
+ archive_operation,
deadline_seconds=deadline_seconds,
)
- return await run_memory_lifecycle()
+ return await archive_operation()
async def _final_flush_memory_scope(
self,
diff --git a/core/internal_server.py b/core/internal_server.py
index bcc50f88b..9bd994897 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1281,7 +1281,7 @@ def create_app(
@app.post("/internal/memory/archive-session")
async def _memory_archive_session(request: Request) -> Any:
- """Archive one Workbench session through the controller lifecycle."""
+ """Archive one Workbench session through the controller-owned write."""
payload = await _safe_json(request)
if (
diff --git a/tests/test_internal_client_timeouts.py b/tests/test_internal_client_timeouts.py
index 54ffdae76..bbd74ce80 100644
--- a/tests/test_internal_client_timeouts.py
+++ b/tests/test_internal_client_timeouts.py
@@ -147,10 +147,9 @@ def test_final_flush_client_outlasts_the_controller_deadline() -> None:
def test_session_archive_client_has_no_reporting_timeout() -> None:
- # Scope resolution and the cancellation-safe archive commit include
- # unbounded local filesystem/SQLite work. The controller keeps the provider
- # final-flush deadline, but the reporting transport must await its terminal
- # result instead of returning a retryable-looking failure mid-commit.
+ # The archive commit includes unbounded local filesystem/SQLite work. The
+ # reporting transport must await that terminal write instead of returning a
+ # retryable-looking failure mid-commit. Memory flush is not on this round-trip.
assert "timeout" not in inspect.signature(memory_archive_session).parameters
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 7c910c0e9..45c8a1f46 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -479,8 +479,8 @@ def test_memory_archive_session_delegates_raw_identity_with_bounded_lifecycle()
"ok": True,
"session": {"id": "ses-memory", "status": "archived"},
}
- # The UI transport waits without a reporting deadline, while the controller
- # still bounds provider lifecycle work before its shielded archive commit.
+ # The UI transport waits without a reporting deadline so the controller can
+ # finish the terminal archive write. Memory flush is scheduled afterwards.
controller.archive_memory_cli_session.assert_awaited_once_with(
"ses-memory",
deadline_seconds=5.0,
diff --git a/tests/test_memory_slice3.py b/tests/test_memory_slice3.py
index 175c14085..722747df8 100644
--- a/tests/test_memory_slice3.py
+++ b/tests/test_memory_slice3.py
@@ -1090,11 +1090,10 @@ def test_final_flush_memory_cli_session_skips_without_stored_scope() -> None:
assert controller.memory_runtime.final_flush_calls == []
-def test_archive_memory_cli_session_holds_capture_fence_through_db_commit(
+def test_archive_memory_cli_session_commits_without_waiting_on_memory(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
- from core.services import sessions as sessions_service
from storage import workbench_sessions_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -1115,22 +1114,22 @@ def test_archive_memory_cli_session_holds_capture_fence_through_db_commit(
)["id"]
principal_id = "u-" + ("2" * 32)
- admission_lock = asyncio.Lock()
- capture_may_enter = asyncio.Event()
- capture_entered = asyncio.Event()
- release_capture = asyncio.Event()
flush_entered = asyncio.Event()
release_flush = asyncio.Event()
- archive_lock_states: list[bool] = []
+ flush_started_after_archive: list[bool] = []
class LifecycleRuntime(_Runtime):
async def run_session_scopes_lifecycle(self, **kwargs):
operation = kwargs.pop("operation")
self.session_lifecycle_calls.append(kwargs)
- async with admission_lock:
- flush_entered.set()
- await release_flush.wait()
- return await operation()
+ with engine.connect() as conn:
+ flush_started_after_archive.append(
+ workbench_sessions_service.get_session(conn, session_id)["status"]
+ == "archived"
+ )
+ flush_entered.set()
+ await release_flush.wait()
+ return await operation()
controller = _controller()
controller.memory_runtime = LifecycleRuntime(controller.memory_module)
@@ -1141,69 +1140,111 @@ def test_archive_memory_cli_session_holds_capture_fence_through_db_commit(
session_id: (principal_id, PROJECT),
}
controller._memory_cli_facts_by_session = {}
-
- original_archive = sessions_service.archive_session
-
- def archive_under_test(conn, actual_session_id):
- archive_lock_states.append(admission_lock.locked())
- return original_archive(conn, actual_session_id)
-
- monkeypatch.setattr(sessions_service, "archive_session", archive_under_test)
+ controller.memory_runtime.recovered_scopes = ((principal_id, PROJECT),)
async def run() -> None:
- turn_admission = await controller.session_turns.acquire_lifecycle_admission(
- session_id
- )
-
- async def old_capture() -> None:
- await capture_may_enter.wait()
- async with admission_lock:
- capture_entered.set()
- await release_capture.wait()
- turn_admission.release()
-
- capture = asyncio.create_task(old_capture())
- archive = asyncio.create_task(
- controller.archive_memory_cli_session(
- session_id,
- deadline_seconds=2.0,
- )
+ result = await controller.archive_memory_cli_session(
+ session_id,
+ deadline_seconds=2.0,
)
- await asyncio.sleep(0)
-
+ assert result["status"] == "archived"
with engine.connect() as conn:
- assert workbench_sessions_service.get_session(conn, session_id)["status"] == "active"
- assert not archive.done()
- assert not flush_entered.is_set()
-
- # This turn was admitted before archive but had not reached capture yet.
- # Archive must not take Memory admission ahead of it.
- capture_may_enter.set()
- await asyncio.wait_for(capture_entered.wait(), timeout=1.0)
- assert not flush_entered.is_set()
-
- release_capture.set()
- await capture
+ assert workbench_sessions_service.get_session(conn, session_id)["status"] == "archived"
await asyncio.wait_for(flush_entered.wait(), timeout=1.0)
-
- with engine.connect() as conn:
- assert workbench_sessions_service.get_session(conn, session_id)["status"] == "active"
- assert not archive.done()
-
- release_flush.set()
- result = await archive
-
- assert result["status"] == "archived"
- assert archive_lock_states == [True]
+ assert flush_started_after_archive == [True]
assert controller.memory_runtime.session_lifecycle_calls == [
{
"scopes": ((principal_id, PROJECT),),
"raw_session_id": session_id,
- "deadline_seconds": 2.0,
+ "deadline_seconds": 5.0,
}
]
+ release_flush.set()
+ pending = list(getattr(controller, "_archive_memory_flush_tasks", set()))
+ if pending:
+ await asyncio.gather(*pending)
+
+ try:
+ asyncio.run(run())
+ finally:
+ engine.dispose()
+
+
+def test_archive_memory_cli_session_schedules_flush_when_commit_is_cancelled(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ from storage import workbench_sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.projects_service import create_project
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ session_id = workbench_sessions_service.create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="claude",
+ title="Archive through cancellation",
+ )["id"]
+
+ principal_id = "u-" + ("2" * 32)
+ flush_entered = asyncio.Event()
+ release_flush = asyncio.Event()
+ commit_entered = threading.Event()
+ release_commit = threading.Event()
+
+ class LifecycleRuntime(_Runtime):
+ async def run_session_scopes_lifecycle(self, **kwargs):
+ operation = kwargs.pop("operation")
+ self.session_lifecycle_calls.append(kwargs)
+ flush_entered.set()
+ await release_flush.wait()
+ return await operation()
+
+ from core.services import sessions as sessions_service
+
+ original_archive = sessions_service.archive_session
+
+ def archive_under_test(conn, actual_session_id):
+ commit_entered.set()
+ assert release_commit.wait(timeout=2.0)
+ return original_archive(conn, actual_session_id)
+
+ monkeypatch.setattr(sessions_service, "archive_session", archive_under_test)
+
+ controller = _controller()
+ controller.memory_runtime = LifecycleRuntime(controller.memory_module)
+ controller._memory_scopes_by_session = {
+ session_id: (principal_id, PROJECT),
+ }
+ controller._memory_cli_facts_by_session = {}
+ controller.memory_runtime.recovered_scopes = ((principal_id, PROJECT),)
+
+ async def run() -> None:
+ archive = asyncio.create_task(controller.archive_memory_cli_session(session_id))
+ deadline = asyncio.get_running_loop().time() + 2.0
+ while not commit_entered.is_set():
+ if asyncio.get_running_loop().time() >= deadline:
+ raise AssertionError("archive commit did not start")
+ await asyncio.sleep(0.01)
+ archive.cancel()
+ await asyncio.sleep(0)
+ release_commit.set()
+ with pytest.raises(asyncio.CancelledError):
+ await archive
with engine.connect() as conn:
assert workbench_sessions_service.get_session(conn, session_id)["status"] == "archived"
+ await asyncio.wait_for(flush_entered.wait(), timeout=1.0)
+ release_flush.set()
+ pending = list(getattr(controller, "_archive_memory_flush_tasks", set()))
+ if pending:
+ await asyncio.gather(*pending)
try:
asyncio.run(run())
@@ -1266,8 +1307,65 @@ def test_archive_memory_cli_session_preflight_skips_memory_lifecycle(
assert controller.memory_runtime.scope_recovery_calls == []
+def test_archive_memory_cli_session_commits_when_memory_lifecycle_is_busy(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ from core.memory.module import MemorySessionLifecycleBusyError
+ from storage import workbench_sessions_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.projects_service import create_project
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ session_id = workbench_sessions_service.create_session(
+ conn,
+ scope_id=project["scope_id"],
+ agent_backend="claude",
+ title="Archive despite Memory maintenance",
+ )["id"]
+
+ controller = _controller()
+ controller.memory_runtime.session_lifecycle_error = MemorySessionLifecycleBusyError(
+ "memory session lifecycle is unavailable"
+ )
+ controller.memory_runtime.recovered_scopes = (
+ ("u-" + ("2" * 32), PROJECT),
+ )
+ controller._memory_scopes_by_session = {}
+ controller._memory_cli_facts_by_session = {}
+
+ async def run() -> dict[str, object]:
+ result = await controller.archive_memory_cli_session(session_id)
+ pending = list(getattr(controller, "_archive_memory_flush_tasks", set()))
+ if pending:
+ await asyncio.gather(*pending, return_exceptions=True)
+ return result
+
+ try:
+ result = asyncio.run(run())
+ assert result["status"] == "archived"
+ with engine.connect() as conn:
+ assert workbench_sessions_service.get_session(conn, session_id)["status"] == "archived"
+ assert controller.memory_runtime.session_lifecycle_calls == [
+ {
+ "scopes": (("u-" + ("2" * 32), PROJECT),),
+ "raw_session_id": session_id,
+ "deadline_seconds": 5.0,
+ }
+ ]
+ finally:
+ engine.dispose()
+
+
@pytest.mark.parametrize("restarted", [False, True])
-def test_archive_memory_cli_session_flushes_every_cwd_scope_deterministically(
+def test_archive_memory_cli_session_flushes_every_cwd_scope_after_commit(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
restarted: bool,
@@ -1306,13 +1404,18 @@ def test_archive_memory_cli_session_flushes_every_cwd_scope_deterministically(
controller._memory_cli_facts_by_session = {}
controller.memory_runtime.recovered_scopes = (second_scope, first_scope)
- try:
- result = asyncio.run(
- controller.archive_memory_cli_session(
- session_id,
- deadline_seconds=3.0,
- )
+ async def run() -> dict[str, object]:
+ result = await controller.archive_memory_cli_session(
+ session_id,
+ deadline_seconds=3.0,
)
+ pending = list(getattr(controller, "_archive_memory_flush_tasks", set()))
+ if pending:
+ await asyncio.gather(*pending)
+ return result
+
+ try:
+ result = asyncio.run(run())
finally:
engine.dispose()
@@ -1322,7 +1425,7 @@ def test_archive_memory_cli_session_flushes_every_cwd_scope_deterministically(
{
"scopes": (first_scope, second_scope),
"raw_session_id": session_id,
- "deadline_seconds": 3.0,
+ "deadline_seconds": 5.0,
}
]
@@ -1386,7 +1489,11 @@ def test_archive_memory_cli_session_skips_flush_when_memory_is_disabled(
async def run() -> dict[str, object]:
try:
- return await controller.archive_memory_cli_session(session_id)
+ result = await controller.archive_memory_cli_session(session_id)
+ pending = list(getattr(controller, "_archive_memory_flush_tasks", set()))
+ if pending:
+ await asyncio.gather(*pending)
+ return result
finally:
await runtime.close()
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index de4b91377..57762af23 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -770,7 +770,11 @@ async def memory_archive_session(
*,
socket_path: Optional[Path] = None,
) -> dict[str, Any]:
- """Await the closed Workbench archive use case without a reporting deadline."""
+ """Await the controller-owned Workbench archive write without a reporting deadline.
+
+ Memory final flush is not on this round-trip. The controller schedules it
+ best-effort after the archive row commits.
+ """
return await _memory_request(
"POST",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index fd2b7cf5d..ceb981a8a 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9583,9 +9583,9 @@ async def _archive_publish_run_updates(
async def sessions_archive(session_id: str):
"""Permanently archive a session and reclaim its bound resources.
- For an active row, the controller owns one closed lifecycle operation: it
- holds Memory capture admission across final flush and the first irreversible
- archive write. If that controller seam is unavailable, archive fails closed.
+ For an active row, the controller owns the terminal session write. Memory
+ final flush is best-effort after that write and never blocks archive. If the
+ controller seam itself is unavailable, archive fails closed.
The DB-level teardown (status, tasks/watches, runs, Show Page) is atomic in
``archive_session``. Cancelling an in-flight chat turn lives in the controller