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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(memory): stop capture from fencing dispatch and /new (#1590)
rkrkrkk5f5cd1a89bab
diff --git a/core/controller.py b/core/controller.pyindex 16567020e..e36ddb0c8 100644--- a/core/controller.py+++ b/core/controller.py@@ -2110,7 +2110,7 @@ class Controller:*,deadline_seconds: float = 5.0,) -> _MemorySessionLifecycleResult:- """Run an IM session reset behind Memory's exact capture fence."""+ """Run an IM session reset, skipping Memory flush if capture is busy."""scope = self._memory_scope_for_im_session(context, raw_session_id)if scope is None:diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 62db56d18..275d11311 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -23,9 +23,6 @@ logger = logging.getLogger(__name__)_NewSessionResult = TypeVar("_NewSessionResult")-_NEW_SESSION_ERROR_I18N_KEYS = {- "memory_session_lifecycle_busy": "error.memorySessionLifecycleBusy",-}class CommandHandlers(BaseHandler):@@ -156,7 +153,16 @@ class CommandHandlers(BaseHandler):session_anchor: Optional[str],operation: Callable[[], Awaitable[_NewSessionResult]],) -> _NewSessionResult:- """Run `/new` after admitted turns finish their Memory capture."""+ """Run `/new`, waiting briefly for capture then failing open."""++ budget = 5.0+ deadline_at = time.monotonic() + budget++ def remaining_seconds() -> float:+ leftover = deadline_at - time.monotonic()+ if leftover >= budget - 0.05:+ return budget+ return max(leftover, 0.001)async def run_memory_lifecycle() -> _NewSessionResult:lifecycle = getattr(@@ -169,7 +175,7 @@ class CommandHandlers(BaseHandler):context,session_anchor,operation,- deadline_seconds=5.0,+ deadline_seconds=remaining_seconds(),)await self._final_flush_for_new(context, session_anchor)@@ -181,7 +187,7 @@ class CommandHandlers(BaseHandler):return await turn_lifecycle(session_anchor,run_memory_lifecycle,- deadline_seconds=5.0,+ deadline_seconds=budget,)return await run_memory_lifecycle()@@ -584,9 +590,8 @@ class CommandHandlers(BaseHandler):# topic. The new topic context is not a valid identity for this flush.session_anchor, memory_session_anchor = self._session_anchors_for_new(context)# ``/new`` deletes the session rows that scheduled tasks and watches may- # be pinned to. Keep this entire destructive transition behind the same- # exact-session admission fence as capture, including Telegram's old- # topic handoff. A stalled or failed flush still fails open to reset.+ # be pinned to. Wait briefly for in-flight capture, then always reset+ # (a stalled or failed Memory flush must not fail the command).async def _reset_session() -> tuple[bool, list[dict[str, Any]]]:if platform == "telegram" and hasattr(im_client, "start_new_topic_session"):topic_context = await im_client.start_new_topic_session(context)@@ -653,8 +658,7 @@ class CommandHandlers(BaseHandler):logger.error(f"Error starting new session: {e}", exc_info=True)try:channel_context = self._get_channel_context(context)- error_key = _NEW_SESSION_ERROR_I18N_KEYS.get(getattr(e, "code", None))- error_message = self._t(error_key) if error_key else self._t("error.clearSession", error=str(e))+ error_message = self._t("error.clearSession", error=str(e))await im_client.send_message(channel_context, f"❌ {error_message}")except Exception as send_error:logger.error(f"Failed to send error message: {send_error}", exc_info=True)diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex c1993c31d..331aa2ebf 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -4,6 +4,7 @@ import asyncioimport loggingimport inspectfrom datetime import datetime+from collections.abc import Awaitablefrom typing import Any, List, Optional, Tuplefrom core.audio_asr import (@@ -23,6 +24,10 @@ from core.native_dispatch_phase import (DISPATCH_PHASE_PREWRITE,set_dispatch_phase,)++# Keep this string local: importing ``core.session_turns`` here cycles through+# Memory admission into ``core.handlers``.+TURN_LIFECYCLE_EPOCH_KEY = "_turn_lifecycle_epoch"from modules.agents.base import AgentRequestfrom modules.agents.catalog import display_name_for_backend, is_agent_backendfrom modules.im import MessageContext@@ -66,6 +71,7 @@ class MessageHandler(BaseHandler):self.session_handler = None # Will be set after creationself.receiver_tasks = controller.receiver_tasksself._memory_capture_tasks: set[asyncio.Task[Any]] = set()+ self._memory_capture_tasks_by_session: dict[str, set[asyncio.Task[Any]]] = {}self._memory_capture_registration_open = Truedef set_session_handler(self, session_handler):@@ -76,12 +82,18 @@ class MessageHandler(BaseHandler):self,task: asyncio.Task[Any],*,+ session_id: str | None = None,lifecycle_admission: Any = None,attachment_lease: Any = None,+ attachment_reservation: Any = None,) -> None:"""Retain a best-effort capture until asyncio reports its completion."""self._memory_capture_tasks.add(task)+ if session_id:+ self._memory_capture_tasks_by_session.setdefault(session_id, set()).add(+ task+ )def _on_done(done_task: asyncio.Task[Any]) -> None:try:@@ -94,19 +106,42 @@ class MessageHandler(BaseHandler):release_attachment = getattr(attachment_lease, "release", None)if callable(release_attachment):release_attachment()+ release_reservation = getattr(+ attachment_reservation,+ "release",+ None,+ )+ if callable(release_reservation):+ release_reservation()release = getattr(lifecycle_admission, "release", None)if callable(release):release()self._memory_capture_tasks.discard(done_task)+ if session_id:+ bucket = self._memory_capture_tasks_by_session.get(session_id)+ if bucket is not None:+ bucket.discard(done_task)+ if not bucket:+ self._memory_capture_tasks_by_session.pop(+ session_id,+ None,+ )task.add_done_callback(_on_done)+ def abandon_memory_captures_for_session(self, session_id: str) -> None:+ """Cancel captures admitted against a session generation that just ended."""++ tasks = tuple(self._memory_capture_tasks_by_session.get(session_id, ()))+ for task in tasks:+ task.cancel()+async def _acquire_memory_capture_admission(self,session_id: str,- lifecycle_admission: Any,+ lifecycle_admission: Any = None,) -> Any:- """Fence a first-pass capture when durable dispatch has not admitted it."""+ """Take the capture-side lifecycle lease. Never call this on dispatch."""if lifecycle_admission is not None:return lifecycle_admission@@ -116,44 +151,95 @@ class MessageHandler(BaseHandler):return Nonereturn await acquire(session_id)- async def _schedule_text_only_memory_capture(+ async def _run_memory_capture(+ self,+ session_id: str,+ expected_epoch: int,+ capture: Awaitable[None],+ ) -> None:+ """Acquire the lifecycle lock and attribute only if the epoch still matches."""++ pending: Awaitable[None] | None = capture+ try:+ if not self._memory_capture_registration_open:+ return+ admission = await self._acquire_memory_capture_admission(session_id)+ try:+ if not self._memory_capture_registration_open:+ return+ if not self._memory_session_lifecycle_epoch_matches(+ session_id,+ expected_epoch,+ ):+ logger.info(+ "Memory capture abandoned after session lifecycle "+ "transition session=%s epoch=%s",+ session_id,+ expected_epoch,+ )+ return+ await capture+ pending = None+ finally:+ release = getattr(admission, "release", None)+ if callable(release):+ release()+ finally:+ if pending is not None:+ close = getattr(pending, "close", None)+ if callable(close):+ close()++ def _schedule_memory_capture_task(+ self,+ *,+ session_id: str,+ expected_epoch: int,+ capture: Awaitable[None],+ attachment_lease: Any = None,+ attachment_reservation: Any = None,+ ) -> asyncio.Task[Any] | None:+ """Register a capture without awaiting Memory on the turn path."""++ if not self._memory_capture_registration_open:+ return None+ capture_task = asyncio.create_task(+ self._run_memory_capture(session_id, expected_epoch, capture),+ name="memory-capture",+ )+ self._track_memory_capture_task(+ capture_task,+ session_id=session_id,+ attachment_lease=attachment_lease,+ attachment_reservation=attachment_reservation,+ )+ return capture_task++ def _schedule_text_only_memory_capture(self,context: MessageContext,text: str,session_id: str,- lifecycle_admission: Any,- ) -> Any:+ *,+ expected_epoch: int,+ ) -> None:capture_memory = getattr(self.controller, "capture_user_memory", None)if not callable(capture_memory) or not text.strip():- return lifecycle_admission-- admission_was_owned_by_turn = lifecycle_admission is not None- lifecycle_admission = await self._acquire_memory_capture_admission(- session_id,- lifecycle_admission,- )+ returnif not self._memory_capture_registration_open:- release = getattr(lifecycle_admission, "release", None)- if callable(release):- release()- return None-- try:- capture_task = asyncio.create_task(- capture_memory(context, text, session_id),- name="memory-capture",- )- self._track_memory_capture_task(- capture_task,- lifecycle_admission=lifecycle_admission,+ return+ capture = capture_memory(context, text, session_id)+ if (+ self._schedule_memory_capture_task(+ session_id=session_id,+ expected_epoch=expected_epoch,+ capture=capture,)- except BaseException:- if not admission_was_owned_by_turn:- release = getattr(lifecycle_admission, "release", None)- if callable(release):- release()- raise- return None+ is None+ ):+ close = getattr(capture, "close", None)+ if callable(close):+ close()def _memory_session_lifecycle_epoch(self, session_id: str) -> int:manager = getattr(self.controller, "session_turns", None)@@ -268,11 +354,6 @@ class MessageHandler(BaseHandler):"""Shared turn-processing pipeline used by both human and scheduled turns."""processing_indicator = Nonerequest: AgentRequest | None = None- payload = context.platform_specific or {}- turn_lifecycle_admission = payload.pop(- "_turn_lifecycle_admission",- None,- )dispatch_evidence = set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)# Tracks whether we actually dispatched an agent turn (whose reply# streams in asynchronously). If we leave this method WITHOUT having@@ -377,12 +458,14 @@ class MessageHandler(BaseHandler):base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)memory_session_id = base_session_id+ payload = dict(context.platform_specific or {})+ snapshotted_epoch = payload.pop(TURN_LIFECYCLE_EPOCH_KEY, None)memory_session_pre_epoch = (- self._memory_session_lifecycle_epoch(memory_session_id)- if is_human and context.files- else None+ snapshotted_epoch+ if isinstance(snapshotted_epoch, int)+ and not isinstance(snapshotted_epoch, bool)+ else self._memory_session_lifecycle_epoch(memory_session_id))- payload = dict(context.platform_specific or {})payload["turn_source"] = sourcepayload["turn_base_session_id"] = base_session_idpayload["scheduled_anchor_required"] = self.session_handler.should_allocate_scheduled_anchor(@@ -394,13 +477,11 @@ class MessageHandler(BaseHandler):# turns defer only until the shared materializer has produced a# descriptor-backed lease.if is_human and not context.files:- turn_lifecycle_admission = (- await self._schedule_text_only_memory_capture(- context,- control_message,- memory_session_id,- turn_lifecycle_admission,- )+ self._schedule_text_only_memory_capture(+ context,+ control_message,+ memory_session_id,+ expected_epoch=memory_session_pre_epoch,)reply_anchor_base_session_id = payload.get("reply_anchor_base_session_id")@@ -791,13 +872,11 @@ class MessageHandler(BaseHandler):except Exception:if is_human:try:- turn_lifecycle_admission = (- await self._schedule_text_only_memory_capture(- context,- control_message,- memory_session_id,- turn_lifecycle_admission,- )+ self._schedule_text_only_memory_capture(+ context,+ control_message,+ memory_session_id,+ expected_epoch=memory_session_pre_epoch,)except Exception:logger.warning(@@ -833,15 +912,10 @@ class MessageHandler(BaseHandler):attachment_text_only = Falsecapture_task = Nonetry:- turn_lifecycle_admission = await self._acquire_memory_capture_admission(- memory_session_id,- turn_lifecycle_admission,- )if not self._memory_capture_registration_open:raise _MemoryCaptureRegistrationClosed- stale_attachment_capture = bool(- memory_session_pre_epoch is not None- and not self._memory_session_lifecycle_epoch_matches(+ stale_attachment_capture = (+ not self._memory_session_lifecycle_epoch_matches(memory_session_id,memory_session_pre_epoch,)@@ -895,24 +969,35 @@ class MessageHandler(BaseHandler):memory_session_id,**capture_options,)- capture_task = asyncio.create_task(- capture,- name="memory-capture",+ capture_task = self._schedule_memory_capture_task(+ session_id=memory_session_id,+ expected_epoch=memory_session_pre_epoch,+ capture=capture,+ attachment_lease=memory_attachment_lease,+ attachment_reservation=memory_capture_reservation,)+ if capture_task is None:+ close = getattr(capture, "close", None)+ if callable(close):+ close()+ raise _MemoryCaptureRegistrationClosedexcept _MemoryCaptureRegistrationClosed:- release_admission = getattr(- turn_lifecycle_admission,+ if memory_attachment_lease is not None:+ memory_attachment_lease.release()+ memory_attachment_lease = None+ release_reservation = getattr(+ memory_capture_reservation,"release",None,)- if callable(release_admission):- release_admission()- turn_lifecycle_admission = None+ if callable(release_reservation):+ release_reservation()except BaseException as error:if capture_task is not None:capture_task.cancel()if memory_attachment_lease is not None:memory_attachment_lease.release()+ memory_attachment_lease = Nonerelease_reservation = getattr(memory_capture_reservation,"release",@@ -920,28 +1005,12 @@ class MessageHandler(BaseHandler):)if callable(release_reservation):release_reservation()- release_admission = getattr(- turn_lifecycle_admission,- "release",- None,- )- if callable(release_admission):- release_admission()- turn_lifecycle_admission = Noneif not isinstance(error, Exception):raiselogger.warning("Memory capture task could not be scheduled",exc_info=True,)- else:- self._track_memory_capture_task(- capture_task,- attachment_lease=memory_attachment_lease,- )- if turn_lifecycle_admission is not None:- turn_lifecycle_admission.release()- turn_lifecycle_admission = Noneif durable_ingress_enabled and not durable_delivery_owned:assert durable_dispatch_text is not None@@ -1148,13 +1217,6 @@ class MessageHandler(BaseHandler):finally:if attachment_lease is not None:attachment_lease.release()- release_lifecycle_admission = getattr(- turn_lifecycle_admission,- "release",- None,- )- if callable(release_lifecycle_admission):- release_lifecycle_admission()if not agent_dispatched:# Synchronous completion — no async agent reply is coming, so# release any live streaming SSE waiter for this turn nowdiff --git a/core/internal_server.py b/core/internal_server.pyindex 9bd994897..987903efd 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1321,14 +1321,7 @@ def create_app()except asyncio.CancelledError:raise- except Exception as error:- from core.memory.runtime import MemorySessionLifecycleBusyError-- code = (- error.code- if isinstance(error, MemorySessionLifecycleBusyError)- else "session_archive_unavailable"- )+ except Exception:logger.debug("internal Workbench session archive failed for %s",payload["session_id"],@@ -1336,7 +1329,7 @@ def create_app()return JSONResponse(status_code=503,- content={"ok": False, "error": code},+ content={"ok": False, "error": "session_archive_unavailable"},)if not isinstance(session, dict):return JSONResponse(diff --git a/core/memory/module.py b/core/memory/module.pyindex 54e8c4722..3b56809f9 100644--- a/core/memory/module.py+++ b/core/memory/module.py@@ -380,7 +380,7 @@ class MemoryModule:operation: Callable[[], Awaitable[_SessionLifecycleResult]],deadline_seconds: float = 5.0,) -> _SessionLifecycleResult:- """Flush and run one destructive session transition under one fence."""+ """Flush if capture is quiet, then run the transition; fail open on timeout."""if not self._is_enabled() or self.maintenance_active or self._is_maintenance_open():return await operation()@@ -406,10 +406,13 @@ class MemoryModule:timeout=max(deadline - loop.time(), 0.001),)acquired = True- except asyncio.TimeoutError as error:- raise MemorySessionLifecycleBusyError(- "memory capture admission did not quiesce before the deadline"- ) from error+ except asyncio.TimeoutError:+ logger.warning(+ "memory capture admission did not quiesce before the "+ "deadline; skipping final flush session=%s",+ raw_session_id,+ )+ return await operation()await self._final_flush_under_admission(principal_id=principal_id,project_id=project_id,@@ -446,7 +449,13 @@ class MemoryModule:if not self._is_enabled():return await operation()if self.maintenance_active or self._is_maintenance_open():- raise MemorySessionLifecycleBusyError("memory session lifecycle is unavailable")+ logger.warning(+ "memory session lifecycle unavailable during maintenance; "+ "skipping final flush session=%s",+ raw_session_id,+ )+ result = await operation()+ return False if isinstance(result, bool) else resulttimeout = _positive_timeout(deadline_seconds)loop = asyncio.get_running_loop()@@ -478,10 +487,14 @@ class MemoryModule:raise asyncio.TimeoutErrorawait asyncio.wait_for(admission_lock.acquire(), timeout=remaining)acquired.append(admission_lock)- except asyncio.TimeoutError as error:- raise MemorySessionLifecycleBusyError(- "memory capture admission did not quiesce before the deadline"- ) from error+ except asyncio.TimeoutError:+ logger.warning(+ "memory capture admission did not quiesce before the "+ "deadline; skipping final flush session=%s",+ raw_session_id,+ )+ result = await operation()+ return False if isinstance(result, bool) else resultflush_succeeded = Truefor principal_id, project_id in canonical_scopes:flush_succeeded = (diff --git a/core/session_turns.py b/core/session_turns.pyindex 817b9565f..25c60cb58 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -97,6 +97,7 @@ logger = logging.getLogger(__name__)TURN_LIFECYCLE_ADMISSION_KEY = "_turn_lifecycle_admission"+TURN_LIFECYCLE_EPOCH_KEY = "_turn_lifecycle_epoch"@dataclass@@ -113,12 +114,6 @@ class TurnLifecycleAdmission:self._lock.release()-class SessionTurnLifecycleBusyError(RuntimeError):- """A destructive lifecycle operation could not quiesce admitted turns."""-- code = "memory_session_lifecycle_busy"--def _utc_now_iso() -> str:return datetime.now(timezone.utc).isoformat()@@ -618,6 +613,7 @@ class SessionTurnManager:self._queue_recovery_locks: dict[str, asyncio.Lock] = {}self._session_lifecycle_locks: dict[str, asyncio.Lock] = {}self._session_lifecycle_epochs: dict[str, int] = {}+ self._session_lifecycle_ops: dict[str, asyncio.Lock] = {}# Interruption reports owed to turns whose platform was not connected yet# when recovery ran, keyed by platform. See ``_report_lost_im_turn``.self._pending_lost_turn_reports: dict[str, list[tuple[str, str]]] = {}@@ -661,7 +657,11 @@ class SessionTurnManager:self,raw_session_id: str,) -> TurnLifecycleAdmission:- """Fence one admitted turn until its Memory capture is durably decided."""+ """Best-effort lease so a capture can quiesce before a destructive op.++ Turn dispatch must not await this lock. Capture tasks acquire it on+ their own task so a hung sidecar cannot fence the next message.+ """if not isinstance(raw_session_id, str) or not raw_session_id:raise ValueError("session lifecycle admission requires a session id")@@ -684,10 +684,33 @@ class SessionTurnManager:raw_session_id: str,expected_epoch: int,) -> bool:- """Revalidate a pre-await lifecycle fact inside lifecycle admission."""+ """Revalidate a pre-await lifecycle fact before Memory attribution."""return self.session_lifecycle_epoch(raw_session_id) == expected_epoch+ def _advance_session_lifecycle_epoch(+ self,+ raw_session_id: str,+ *,+ abandon_captures: bool = False,+ ) -> int:+ """Advance the generation token; cancel captures only when asked.++ Cancellation is for the timeout path, where a capture may still hold+ the lifecycle lock. The success path only needs the epoch bump: the+ capture task's epoch check discards stale work without killing a+ capture admitted for the new generation.+ """++ next_epoch = self.session_lifecycle_epoch(raw_session_id) + 1+ self._session_lifecycle_epochs[raw_session_id] = next_epoch+ if abandon_captures:+ handler = getattr(self.controller, "message_handler", None)+ abandon = getattr(handler, "abandon_memory_captures_for_session", None)+ if callable(abandon):+ abandon(raw_session_id)+ return next_epoch+async def run_session_lifecycle(self,raw_session_id: str,@@ -695,24 +718,45 @@ class SessionTurnManager:*,deadline_seconds: float = 5.0,) -> Any:- """Run a destructive transition after admitted turns finish capture."""+ """Run a destructive transition, failing open if capture is still busy.+ Waits up to ``deadline_seconds`` so a nearly-finished capture can+ flush. On timeout the epoch advances, in-flight captures are+ abandoned, and ``operation`` still runs. A hung Memory sidecar+ must not fail ``/new`` or archive.+ """++ op_lock = self._session_lifecycle_ops.setdefault(+ raw_session_id,+ asyncio.Lock(),+ )+ await op_lock.acquire()+ admission = Nonetry:- admission = await asyncio.wait_for(- self.acquire_lifecycle_admission(raw_session_id),- timeout=max(float(deadline_seconds), 0.001),- )- except asyncio.TimeoutError as exc:- raise SessionTurnLifecycleBusyError(- "turn capture admission did not quiesce before the deadline"- ) from exc- try:+ try:+ admission = await asyncio.wait_for(+ self.acquire_lifecycle_admission(raw_session_id),+ timeout=max(float(deadline_seconds), 0.001),+ )+ except asyncio.TimeoutError:+ logger.warning(+ "session lifecycle admission did not quiesce before the "+ "deadline; proceeding without the capture lock "+ "session=%s",+ raw_session_id,+ )pre_epoch = self.session_lifecycle_epoch(raw_session_id)result = await operation()- self._session_lifecycle_epochs[raw_session_id] = pre_epoch + 1+ if self.session_lifecycle_epoch(raw_session_id) == pre_epoch:+ self._advance_session_lifecycle_epoch(+ raw_session_id,+ abandon_captures=admission is None,+ )return resultfinally:- admission.release()+ if admission is not None:+ admission.release()+ op_lock.release()@staticmethoddef _agent_run_ids_from_spec(spec: Any) -> set[str]:@@ -4039,110 +4083,88 @@ class SessionTurnManager:evidence_kind="context_build_failed",)return False- lifecycle_admission = await self.acquire_lifecycle_admission(- self._lifecycle_anchor_for_delivery(delivery, str(turn["session_id"]))+ lifecycle_anchor = self._lifecycle_anchor_for_delivery(+ delivery,+ str(turn["session_id"]),)-- def release_lifecycle_admission_if_owned() -> None:- payload = getattr(resolved, "platform_specific", None)- if isinstance(payload, dict) and payload.get(- TURN_LIFECYCLE_ADMISSION_KEY- ) is lifecycle_admission:- payload.pop(TURN_LIFECYCLE_ADMISSION_KEY, None)- lifecycle_admission.release()-- @contextmanager- def release_lifecycle_admission_on_error() -> Iterator[None]:- try:- yield- except BaseException:- release_lifecycle_admission_if_owned()- raise-- def terminalize_and_release(*args: Any, **kwargs: Any) -> dict[str, Any]:- try:- return self._terminalize_durable_turn(*args, **kwargs)- finally:- release_lifecycle_admission_if_owned()+ lifecycle_epoch = self.session_lifecycle_epoch(lifecycle_anchor)archived_before_dispatch = Falserun_terminal_before_dispatch = Falseinvalid_delivery_ids: set[str] = set()remote_authorization_denials: dict[str, str] = {}- with release_lifecycle_admission_on_error():- with self._sqlite_engine().begin() as conn:- reserve_write_lock(conn)- latest = delivery_store.get_turn(conn, turn_id)- session_status = conn.execute(- select(agent_sessions.c.status).where(- agent_sessions.c.id == str(turn["session_id"])- )- ).scalar_one_or_none()- fresh_deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)- fresh_delivery = fresh_deliveries[0] if fresh_deliveries else None+ with self._sqlite_engine().begin() as conn:+ reserve_write_lock(conn)+ latest = delivery_store.get_turn(conn, turn_id)+ session_status = conn.execute(+ select(agent_sessions.c.status).where(+ agent_sessions.c.id == str(turn["session_id"])+ )+ ).scalar_one_or_none()+ fresh_deliveries = delivery_store.initial_deliveries_for_turn(conn, turn_id)+ fresh_delivery = fresh_deliveries[0] if fresh_deliveries else None+ if (+ latest is None+ or latest["state"] != "starting"+ or latest.get("start_attempt_id") != attempt_id+ or (+ expected_start_attempt_id is not None+ and str(latest.get("start_attempt_id") or "")+ != expected_start_attempt_id+ )+ or fresh_delivery is None+ or latest.get("initial_delivery_id") != fresh_delivery.get("id")+ or any(row["state"] != "claimed" for row in fresh_deliveries)+ ):+ return False+ turn = latest+ deliveries = fresh_deliveries+ delivery = fresh_delivery+ archived_before_dispatch = session_status != "active"+ invalid_delivery_ids = {+ str(row["id"])+ for row in deliveries+ if not self._has_resolvable_delivery_input(conn, row)+ }+ remote_authorization_denials = {+ str(row["id"]): reason+ for row in deliveriesif (- latest is None- or latest["state"] != "starting"- or latest.get("start_attempt_id") != attempt_id- or (- expected_start_attempt_id is not None- and str(latest.get("start_attempt_id") or "")- != expected_start_attempt_id- )- or fresh_delivery is None- or latest.get("initial_delivery_id") != fresh_delivery.get("id")- or any(row["state"] != "claimed" for row in fresh_deliveries)- ):- release_lifecycle_admission_if_owned()- return False- turn = latest- deliveries = fresh_deliveries- delivery = fresh_delivery- archived_before_dispatch = session_status != "active"- invalid_delivery_ids = {- str(row["id"])- for row in deliveries- if not self._has_resolvable_delivery_input(conn, row)- }- remote_authorization_denials = {- str(row["id"]): reason+ reason := self._remote_delivery_execution_denial(conn, row)+ )+ is not None+ }+ run_ids = list(+ dict.fromkeys(+ run_idfor row in deliveries- if (- reason := self._remote_delivery_execution_denial(conn, row)- )- is not None- }- run_ids = list(- dict.fromkeys(- run_id- for row in deliveries- for run_id in delivery_store.agent_run_ids_for_delivery(conn, row)- )+ for run_id in delivery_store.agent_run_ids_for_delivery(conn, row))- if not archived_before_dispatch and run_ids:- run_rows = {- str(row["id"]): row- for row in conn.execute(- select(- agent_runs.c.id,- agent_runs.c.status,- agent_runs.c.cancel_requested,- agent_runs.c.metadata_json,- ).where(agent_runs.c.id.in_(run_ids))- ).mappings()- }- for run_id in run_ids:- run_row = run_rows.get(run_id)- if run_row is None:- continue- run_status = normalize_run_status(run_row["status"])- if bool(run_row["cancel_requested"]) or run_status not in {- "queued",- "running",- }:- run_terminal_before_dispatch = True+ )+ if not archived_before_dispatch and run_ids:+ run_rows = {+ str(row["id"]): row+ for row in conn.execute(+ select(+ agent_runs.c.id,+ agent_runs.c.status,+ agent_runs.c.cancel_requested,+ agent_runs.c.metadata_json,+ ).where(agent_runs.c.id.in_(run_ids))+ ).mappings()+ }+ for run_id in run_ids:+ run_row = run_rows.get(run_id)+ if run_row is None:+ continue+ run_status = normalize_run_status(run_row["status"])+ if bool(run_row["cancel_requested"]) or run_status not in {+ "queued",+ "running",+ }:+ run_terminal_before_dispatch = Trueif archived_before_dispatch:- terminalize_and_release(+ self._terminalize_durable_turn(turn_id,"not_written",settled_by="session_archive",@@ -4150,7 +4172,7 @@ class SessionTurnManager:)return Falseif run_terminal_before_dispatch:- terminal = terminalize_and_release(+ terminal = self._terminalize_durable_turn(turn_id,"not_written",settled_by="agent_run_terminal",@@ -4165,7 +4187,7 @@ class SessionTurnManager:turn_id,remote_authorization_denials,)- terminal = terminalize_and_release(+ terminal = self._terminalize_durable_turn(turn_id,"not_written",settled_by="remote_authorization_denied",@@ -4185,7 +4207,7 @@ class SessionTurnManager:"durable Turn=%s lost its resolvable input before native dispatch",turn_id,)- terminal = terminalize_and_release(+ terminal = self._terminalize_durable_turn(turn_id,"not_written",settled_by="invalid_input",@@ -4198,9 +4220,7 @@ class SessionTurnManager:return Falsetry:delivery_payload = self._hydrate_delivery_batch_context(resolved, deliveries)- resolved.platform_specific[TURN_LIFECYCLE_ADMISSION_KEY] = (- lifecycle_admission- )+ resolved.platform_specific[TURN_LIFECYCLE_EPOCH_KEY] = lifecycle_epochresolved.platform_specific["turn_token"] = turn_idresolved.platform_specific["delivery_start_attempt_id"] = attempt_idmetadata = delivery_payload.get("metadata") or {}@@ -4247,7 +4267,7 @@ class SessionTurnManager:"durable native start failed during pre-dispatch preparation for Turn=%s",turn_id,)- terminalize_and_release(+ self._terminalize_durable_turn(turn_id,"not_written",settled_by="pre_write_failure",@@ -4265,11 +4285,7 @@ class SessionTurnManager:durable_preallocated=True,)return True- except asyncio.CancelledError:- release_lifecycle_admission_if_owned()- raiseexcept Exception:- release_lifecycle_admission_if_owned()logger.exception("durable native start became ambiguous for Turn=%s", turn_id)with self._sqlite_engine().begin() as conn:reserve_write_lock(conn)@@ -7372,18 +7388,6 @@ class SessionTurnManager:)task = asyncio.create_task(_runner(), name="internal-dispatch-async")- lifecycle_admission = context.platform_specific.get(- TURN_LIFECYCLE_ADMISSION_KEY- )- if lifecycle_admission is not None:- def release_unclaimed_admission(_task: asyncio.Task[Any]) -> None:- payload = context.platform_specific or {}- if payload.get(TURN_LIFECYCLE_ADMISSION_KEY) is not lifecycle_admission:- return- payload.pop(TURN_LIFECYCLE_ADMISSION_KEY, None)- lifecycle_admission.release()-- task.add_done_callback(release_unclaimed_admission)if isinstance(session_id, str) and session_id:self.in_flight[session_id] = Turn(task=task,diff --git a/docs/plans/memory-independence-c2-c3.md b/docs/plans/memory-independence-c2-c3.mdnew file mode 100644index 000000000..d3250173e--- /dev/null+++ b/docs/plans/memory-independence-c2-c3.md@@ -0,0 +1,262 @@+# Memory independence: capture must not fence dispatch or destructive ops++Context: issue #1584 Memory-independence audit items C2 and C3.+This plan does **not** claim to close #1584 (C1 / WeChat identity is a sibling PR).++## Background++PR #1357 and the later Memory capture fence made Avibe's per-session+lifecycle lock a mutual-exclusion gate between:++1. durable turn start+2. in-flight Memory capture+3. destructive session transitions (`/new`, archive)++That gate keeps a reset or archive from racing a capture that would+attribute content to the wrong session generation. It also made Memory+latency a user-visible dependency: a slow sidecar add (30s) delays the+session's next turn, and a capture wedged past its timeout blocks the+session indefinitely. `/new` and archive wait 5s on the same lock and+then fail the user with `memory_session_lifecycle_busy`.++The product rule for this change: a hung or failed Memory capture must+never block message turns, `/new`, or archive. Losing at most one+turn's capture is acceptable; failing the user's action is not.++## Current fence semantics++### Layer A — Avibe session lifecycle lock (`core/session_turns.py`)++- `_session_lifecycle_locks[session_id]` is an unbounded `asyncio.Lock`.+- `_start_persisted_turn` awaits `acquire_lifecycle_admission` with+ **no timeout**, then parks the lease on+ `context.platform_specific["_turn_lifecycle_admission"]`.+- Text-only capture (`MessageHandler._schedule_text_only_memory_capture`)+ takes that lease (or acquires its own) and holds it until the capture+ task completes.+- Attachment capture acquires the same lock on the **turn path** after+ materialization, then releases it as soon as the capture task is+ scheduled. Generation safety for the download gap uses+ `session_lifecycle_epoch` / `session_lifecycle_epoch_matches`.+- `run_session_lifecycle` waits up to 5s for the lock. On timeout it+ raises `SessionTurnLifecycleBusyError` (`memory_session_lifecycle_busy`).+ On success it runs the operation, then increments+ `_session_lifecycle_epochs[session_id]`. A failed operation leaves+ the epoch unchanged.++Callers:++- `/new` wraps the reset in `SessionTurnManager.run_session_lifecycle`+ (`core/handlers/command_handlers.py`), then nests Memory's own+ `run_session_lifecycle` (flush + capture-admission lock).+- Workbench archive still wraps the terminal session write in+ `SessionTurnManager.run_session_lifecycle`. PR #1582 already made the+ Memory final flush best-effort *after* that write: a busy or failed+ Memory runtime cannot roll archive back. The remaining archive risk is+ only the shared turn-lifecycle lock raiser, not a second Memory fence.++C3 in this PR is therefore `/new` plus every remaining+`memory_session_lifecycle_busy` raiser. It does not re-work #1582's+archive flush. Fail-opening `SessionTurnManager.run_session_lifecycle`+clears the last archive raiser as a side effect of the shared lock.++### Layer B — Memory capture-admission lock (`core/memory/module.py`)++`MemoryModule.run_session_lifecycle` waits for in-flight+`capture_admission` tickets, then final-flushes, then runs the+operation. On timeout it raises `MemorySessionLifecycleBusyError`+(same code string). `/new` nests this **inside** layer A via+`controller.run_memory_session_lifecycle`. So a hung sidecar can+make `/new` wait 5s + 5s and still fail the user.++`run_session_scopes_lifecycle` has the same timeout raise. Archive+flush already swallows that exception (PR #1582). Maintenance-open+still raises; that path is not a hung-capture case and stays as-is.++### Why the fence exists (invariant we must keep)++A capture admitted against session generation **G** must not be written+as if it belonged to generation **G+1**. `/new` reuses the same raw+session anchor on IM surfaces, so a late add after reset mixes the old+conversation into the new one.++The epoch counter already exists for this (`session_lifecycle_epoch`,+consumed by attachment capture). Mutual exclusion was a stronger+implementation of the same invariant, not a second invariant.++## Chosen design++**Generation token replaces mutual exclusion as the correctness+mechanism.** The per-session lock remains only as a *best-effort+quiesce* so a nearly-finished capture can flush before reset. It is+never a dispatch fence, and it is never a reason to fail the user.++Rejected alternative: bound the turn-start wait at ~5s and proceed.+That still makes Memory latency a message-turn delay. The audit allows+dropping the turn-start acquire entirely; we do that.++### C2 — invert the turn-start dependency++1. `_start_persisted_turn` snapshots+ `session_lifecycle_epoch(anchor)` onto the context+ (`_turn_lifecycle_epoch`) and does **not** acquire the lifecycle+ lock. Dispatch never waits on Memory.+2. `MessageHandler` uses that snapshot when present; otherwise it+ samples the epoch when the session id is known (legacy / non-durable+ path). The snapshot is taken **before** any await a concurrent+ `/new` could win.+3. Capture tasks — text and attachments — acquire the lifecycle lock+ **inside the capture task**, never on the turn/`_handle_turn` await+ path. The next turn can start and reply while a previous capture+ still holds the lock.+4. After the capture task acquires the lock, it revalidates the+ snapshotted epoch. Mismatch logs and returns without calling+ `capture_user_memory`.+5. `drain_memory_capture_tasks` / `cancel_memory_capture_tasks` /+ `quiesce_memory_capture_tasks` stay as they are: shutdown still+ settles or cancels accepted captures.++### C3 — destructive ops fail open++`SessionTurnManager.run_session_lifecycle`:++- Still waits up to 5s for the lock (best-effort flush of an in-flight+ capture).+- On timeout: log a warning, advance the epoch (abandon in-flight+ captures for that session), **do not raise**, run the operation+ without holding the lock.+- On acquire: run the operation while holding the lock; on success+ advance the epoch (same as today). A failed operation still leaves+ the epoch unchanged so an in-flight turn is not abandoned by a+ failed `/new`.++`MemoryModule.run_session_lifecycle` and+`run_session_scopes_lifecycle` timeout paths: log a warning, skip the+final flush, run the operation. They no longer raise+`MemorySessionLifecycleBusyError` on quiesce timeout.++`/new` therefore always reaches `_reset_session`. Archive always+reaches the terminal session write. Nested fences cannot stack a+user-visible busy error.++### Abandonment++Advancing a session's epoch is the abandonment signal. Capture tasks+for that session are also cancelled so a hung sidecar await does not+resume into a write after `/new`. The epoch check after lock acquire+covers the case where a waiting capture wakes after the bump and was+not cancelled.++Residual: a sidecar `add` that already left the process may still+complete in EverOS after cancel. That write carries the pre-transition+`session_id` and is the one-turn loss the audit accepts. Tests assert+the Avibe-side decision (no `capture_user_memory` attribution after+the bump).++Epoch keys and capture buckets share one canonical session id when the+session handler is present: `/new` passes `memory_session_anchor` from+`get_base_session_id`, and capture uses `get_session_info`, which+returns that same `get_base_session_id`. When the fallback path yields+`memory_session_anchor=None`, `/new` skips the turn-lifecycle fence+entirely (pre-existing fail-open). Telegram's new-topic branch returns+before a mismatched pair is used.++Cancellation of in-flight captures happens only on the 5s timeout+path, and only after that path's destructive operation succeeds. A+failed `/new`/archive leaves both the epoch and in-flight captures+unchanged. A successful `/new`/archive that acquired the lock only+advances the epoch. The capture task's epoch check discards stale+work without killing a capture admitted for the new generation.++Destructive ops serialize on a dedicated per-session op lock, independent+of the capture lock. `/new` may wait for another `/new`; it never waits+unboundedly on Memory. A hung capture only costs the bounded capture+quiesce, then the op proceeds.++### Dead error surfaces++- `SessionTurnLifecycleBusyError` is no longer raised. The class is+ removed.+- `MemorySessionLifecycleBusyError` remains for the maintenance-open+ case on `run_session_scopes_lifecycle` (not a user `/new`/`archive`+ failure). Quiesce-timeout raisers are removed.+- `/new` no longer maps `memory_session_lifecycle_busy` to i18n.+ `error.memorySessionLifecycleBusy` is removed from `vibe/i18n`.+- Internal archive HTTP no longer special-cases the busy code; a+ leftover raise would surface as `session_archive_unavailable`.++## Correctness argument++Let `E(s)` be the in-memory generation for session `s`.++1. A turn admitted at generation `G` stores `G` on its context before+ any later await. Capture uses that `G`, not a later sample.+2. A successful `/new`/archive increments `E(s)` only after the+ destructive operation commits (acquired path). A timed-out+ `/new`/archive increments `E(s)` before the operation, because the+ operation will run anyway and in-flight captures must not land on+ the post-transition generation.+3. Capture writes only if `E(s) == G` after it holds the lifecycle+ lock. Therefore:+ - If `/new` acquired the lock, every lock-holding capture has+ already finished (or been cancelled on the bump). Attachment+ captures that had released the lock see the new epoch or a+ cancellation.+ - If `/new` timed out, `E(s)` is already `G+1` before reset, so a+ capture admitted at `G` cannot pass the check.+4. Turn start never waits on the lock, so a capture that never+ resolves cannot prevent the next `_start_persisted_turn` or the+ handler's agent dispatch. Capture admission acquire lives only+ inside the fire-and-forget task.+5. Shutdown still drains the same `_memory_capture_tasks` set. Moving+ the lock acquire into the task does not change membership or+ `drain_memory_capture_tasks` / `cancel_memory_capture_tasks`.++The replaced guarantee is exactly the original fence's purpose: no+cross-generation attribution. The dropped guarantee is "destructive+ops and the next turn wait until Memory is quiet." That wait is what+made Memory a messaging dependency.++## Hard boundaries++Do not touch (sibling PRs):++- `core/session_turns.py` `_hydrate_delivery_context`+- `_memory_admission_merge_identity` / `_collect_delivery_segment`+- `core/controller.py` `_memory_turn_facts`+- `modules/im/wechat.py`++Do not change `core/memory/admission.py` admission policy. Fencing+and serialization only.++## Tests++Scenario IDs (capability `memory_independence`):++- `MEMORY-INDEP-001` — hung capture does not block the next turn,+ `/new`, or archive (`memory_session_lifecycle_busy` never surfaces).+- `MEMORY-INDEP-002` — a capture admitted before `/new`/archive and+ completed after the transition is discarded.+- `MEMORY-INDEP-003` — idle-session capture still attributes; shutdown+ still drains accepted captures.++Executable evidence lives next to the existing lifecycle tests+(`tests/test_session_delivery_fsm.py`, handler/command/runtime+modules). Catalog: `tests/scenarios/memory_independence/`.++## Todo++- [x] Write this plan.+- [x] Drop turn-start lock acquire; snapshot epoch onto the context.+- [x] Move capture lock acquire into the capture task; epoch-check+ after acquire; cancel captures on epoch advance.+- [x] Fail-open `run_session_lifecycle` (session_turns + Memory+ module) on the 5s deadline; skip flush; proceed. Remaining C3+ surfaces after #1582: `/new` and the shared busy raisers, not+ archive flush.+- [x] Remove dead busy error surfaces (raise sites, `/new` i18n,+ archive HTTP special case) coherently.+- [x] Add MEMORY-INDEP-001/002/003 and update tests that encoded the+ old "busy fails the user" contract.+- [x] `ruff check` on changed Python files; run the touched test+ modules.diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 9ef9b9089..4630d7418 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -67,6 +67,17 @@ capabilities:- tests/test_memory_cli.py- ui/src/components/settings/memory/MemorySearchPanel.test.tsx- ui/src/context/ApiContext.memoryList.test.tsx+ - id: memory_independence+ name: Memory capture must not fence dispatch or destructive session ops+ status: active+ catalog: tests/scenarios/memory_independence/catalog.yaml+ scenario_tests:+ - tests/test_session_delivery_fsm.py+ unit_or_contract_tests:+ - tests/test_message_handler_typing.py+ - tests/test_command_handler_user_names.py+ - tests/test_memory_runtime.py+ - tests/test_internal_server.py- id: memory_im_attachment_capturename: Bound-DM attachment capture through EverOS multimodal ingeststatus: activediff --git a/tests/scenarios/memory_independence/catalog.yaml b/tests/scenarios/memory_independence/catalog.yamlnew file mode 100644index 000000000..d7d3a289c--- /dev/null+++ b/tests/scenarios/memory_independence/catalog.yaml@@ -0,0 +1,35 @@+version: 1+capability:+ id: memory_independence+ name: Memory capture must not fence dispatch or destructive session ops+ canonical_tests:+ - tests/test_session_delivery_fsm.py+ - tests/test_message_handler_typing.py+ - tests/test_command_handler_user_names.py+ - tests/test_memory_runtime.py+contract:+ dispatch: capture_must_not_fence_turn_start+ destructive_ops: new_and_archive_fail_open_on_capture_timeout+ generation: epoch_snapshot_prevents_cross_generation_attribution+ shutdown: drain_and_cancel_still_settle_accepted_captures+status_legend:+ covered: executable evidence exists+scenarios:+ - id: MEMORY-INDEP-001+ name: A hung capture does not block the next turn, /new, or archive+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_session_delivery_fsm.py::test_hung_memory_capture_does_not_fence_next_turn_or_destructive_ops+ - id: MEMORY-INDEP-002+ name: A capture admitted before /new or archive is discarded after the transition+ status: covered+ kind: correctness+ layer: scenario+ test: tests/test_session_delivery_fsm.py::test_capture_admitted_before_new_is_discarded_after_transition+ - id: MEMORY-INDEP-003+ name: Idle-session capture still attributes and shutdown still drains accepted captures+ status: covered+ kind: regression_keep+ layer: scenario+ test: tests/test_session_delivery_fsm.py::test_idle_session_capture_attributes_and_shutdown_drainsdiff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.pyindex 99f316b8b..6556d4fc6 100644--- a/tests/test_command_handler_user_names.py+++ b/tests/test_command_handler_user_names.py@@ -8,7 +8,6 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch-from core.memory.runtime import MemorySessionLifecycleBusyErrorfrom modules.im import MessageContext# Imported before ``_load_command_handlers_class`` runs: that loader swaps@@ -459,39 +458,6 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):await handler.handle_new(context)return controller- async def test_new_localizes_memory_session_fence_timeout_in_english(self):- controller = await self._run_new_with_memory_lifecycle_error(- MemorySessionLifecycleBusyError(- "memory capture admission did not quiesce before the deadline"- ),- language="en",- )-- self.assertEqual(controller.cleared_sessions, [])- self.assertEqual(- controller.im_client.sent_messages,- [- (- "wx-chat",- "❌ Memory is still processing this session. Please try /new again.",- )- ],- )-- async def test_new_localizes_memory_session_fence_timeout_in_chinese(self):- controller = await self._run_new_with_memory_lifecycle_error(- MemorySessionLifecycleBusyError(- "memory capture admission did not quiesce before the deadline"- ),- language="zh",- )-- self.assertEqual(controller.cleared_sessions, [])- self.assertEqual(- controller.im_client.sent_messages,- [("wx-chat", "❌ 记忆系统仍在处理当前会话,请稍后重试 /new。")],- )-async def test_new_preserves_generic_error_detail(self):controller = await self._run_new_with_memory_lifecycle_error(RuntimeError("provider unavailable"),diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 45c8a1f46..b30349ce1 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -37,7 +37,6 @@ from core import internal_server, session_turnsfrom core.message_context import build_context_turn_sink_keyfrom core.vibe_agents import VibeAgentStorefrom core.memory.maintenance import MemoryStoreUnavailableError-from core.memory.runtime import MemorySessionLifecycleBusyErrorfrom core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULTfrom core.services.agent_steering import SteerOutcome, result as steer_resultfrom core.services.dispatch import (@@ -527,11 +526,6 @@ def test_memory_archive_session_rejects_widened_or_invalid_payloads("error,status_code,error_code",[(LookupError("missing"), 404, "session_not_found"),- (- MemorySessionLifecycleBusyError("busy"),- 503,- "memory_session_lifecycle_busy",- ),(RuntimeError("failed"), 503, "session_archive_unavailable"),],)diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex 6747008f7..18fd5148e 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -53,7 +53,6 @@ from core.memory.process import (from core.memory.provider_root import ProviderRootMetadatafrom core.memory.runtime import (MemoryRuntime,- MemorySessionLifecycleBusyError,MemoryStoreUnavailableError,create_memory_runtime,)@@ -2037,7 +2036,7 @@ async def test_cancelled_multi_scope_lifecycle_releases_partially_acquired_fenceawait memory_runtime_factory.close(runtime)-async def test_session_lifecycle_does_not_reset_when_capture_fence_times_out(+async def test_session_lifecycle_resets_when_capture_fence_times_out(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,memory_runtime_factory,@@ -2060,23 +2059,20 @@ async def test_session_lifecycle_does_not_reset_when_capture_fence_times_out(await admission_lock.acquire()operation_called = False- async def reset_session() -> None:+ async def reset_session() -> str:nonlocal operation_calledoperation_called = True+ return "reset"try:- with pytest.raises(- MemorySessionLifecycleBusyError,- match="did not quiesce",- ):- await runtime.run_session_lifecycle(- principal_id=principal_id,- project_id=PROJECT,- raw_session_id=session_id,- operation=reset_session,- deadline_seconds=0.01,- )- assert operation_called is False+ assert await runtime.run_session_lifecycle(+ principal_id=principal_id,+ project_id=PROJECT,+ raw_session_id=session_id,+ operation=reset_session,+ deadline_seconds=0.01,+ ) == "reset"+ assert operation_called is Truefinally:admission_lock.release()await memory_runtime_factory.close(runtime)@@ -2382,15 +2378,70 @@ async def test_session_lifecycle_ticket_barrier_is_bounded() -> None:session_id="stalled-session",)- with pytest.raises(MemorySessionLifecycleBusyError, match="did not quiesce"):- await module.run_session_lifecycle(- principal_id=PRINCIPAL,- project_id=PROJECT,- raw_session_id="stalled-session",- operation=lambda: asyncio.sleep(0),- deadline_seconds=0.01,- )+ ran = False++ async def reset_session() -> str:+ nonlocal ran+ ran = True+ return "reset"++ assert await module.run_session_lifecycle(+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ raw_session_id="stalled-session",+ operation=reset_session,+ deadline_seconds=0.01,+ ) == "reset"+ assert ran is True++ module.cancel_capture_reservation(reservation)+++async def test_session_scopes_lifecycle_proceeds_during_maintenance() -> None:+ module = memory_module.MemoryModule(+ MemoryStore(),+ FakeMemoryProvider(),+ enabled=True,+ )+ module.enter_maintenance()+ ran = False++ async def archive_session() -> str:+ nonlocal ran+ ran = True+ return "archived"++ assert await module.run_session_scopes_lifecycle(+ scopes=((PRINCIPAL, PROJECT),),+ raw_session_id="maintenance-session",+ operation=archive_session,+ deadline_seconds=0.01,+ ) == "archived"+ assert ran is True+ module.leave_maintenance()+++async def test_session_scopes_lifecycle_timeout_reports_flush_unsuccessful() -> None:+ module = memory_module.MemoryModule(+ MemoryStore(),+ FakeMemoryProvider(),+ enabled=True,+ )+ reservation = module.reserve_capture_admission(+ principal_id=PRINCIPAL,+ project_id=PROJECT,+ session_id="flush-timeout-session",+ )++ async def flushed() -> bool:+ return True+ assert await module.run_session_scopes_lifecycle(+ scopes=((PRINCIPAL, PROJECT),),+ raw_session_id="flush-timeout-session",+ operation=flushed,+ deadline_seconds=0.01,+ ) is Falsemodule.cancel_capture_reservation(reservation)diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 0e040a6ec..779516456 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -820,7 +820,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):)self.assertEqual(result, "materialization failed")- controller.capture_user_memory.assert_not_called()+ controller.capture_user_memory.assert_not_awaited()self.assertIs(handler._emit_agent_dispatch_failure.await_args.args[2],materialization_error,@@ -1246,7 +1246,8 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):await handler.handle_user_message(context, "remember this")controller.capture_user_memory.assert_not_called()- lifecycle_admission.release.assert_called_once_with()+ lifecycle_admission.release.assert_not_called()+ controller.session_turns.acquire_lifecycle_admission.assert_not_awaited()assert handler._memory_capture_tasks == set()async def test_attachment_capture_uses_anchor_before_agent_variant_namespace(self):@@ -1385,7 +1386,6 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):)async def admit(**_kwargs):- assert lifecycle_released.is_set()assert not capture_finished.is_set()lease.adopt()lease.release()@@ -1407,11 +1407,11 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):timeout=1.0,)- assert lifecycle_released.is_set()assert not capture_finished.is_set()handler._admit_human_delivery.assert_awaited_once()capture_can_finish.set()await handler.drain_memory_capture_tasks()+ assert lifecycle_released.is_set()retained_lease.release.assert_called_once_with()async def test_session_reset_during_download_drops_stale_attachment_without_waiting(@@ -1499,11 +1499,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):controller.reserve_memory_attachment_capture.assert_not_called()lease.retain.assert_not_called()- controller.capture_user_memory.assert_awaited_once()- capture_call = controller.capture_user_memory.await_args- self.assertEqual(capture_call.args[1], "keep this caption")- self.assertIsNone(capture_call.kwargs["attachment_reservation"])- self.assertIsNone(capture_call.kwargs["attachment_config_generation"])+ controller.capture_user_memory.assert_not_awaited()async def test_second_same_session_attachment_turn_does_not_wait_for_first_capture(self,@@ -1613,11 +1609,12 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):await asyncio.wait_for(send(1), timeout=1.0)self.assertEqual(handler._admit_human_delivery.await_count, 2)- self.assertEqual(released_admissions, ["base-session", "base-session"])+ self.assertEqual(released_admissions, [])assert not second_capture_started.is_set()release_first_capture.set()await handler.drain_memory_capture_tasks()assert second_capture_started.is_set()+ self.assertEqual(released_admissions, ["base-session", "base-session"])async def test_attachment_capture_cancelled_during_admission_does_not_retain_lease(self,@@ -1643,6 +1640,8 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):)controller.capture_user_memory = AsyncMock()lease = Mock()+ retained_lease = Mock()+ lease.retain.return_value = retained_leaseattachment = FileAttachment(name="report.pdf",mimetype="application/pdf",@@ -1674,13 +1673,12 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):handler.handle_user_message(context, "remember this"))await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)- task.cancel()- with self.assertRaises(asyncio.CancelledError):- await task+ await asyncio.wait_for(task, timeout=1.0)+ await handler.cancel_memory_capture_tasks()- lease.retain.assert_not_called()- lease.release.assert_called_once_with()- controller.capture_user_memory.assert_not_called()+ lease.retain.assert_called_once_with()+ retained_lease.release.assert_called()+ controller.capture_user_memory.assert_not_awaited()async def test_shutdown_quiesce_closes_capture_registration_before_sweep(self,@@ -1753,10 +1751,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):release_acquisition.set()await asyncio.wait_for(turn, timeout=1.0)- controller.reserve_memory_attachment_capture.assert_not_called()- controller.capture_user_memory.assert_not_called()- lease.retain.assert_not_called()- lifecycle_admission.release.assert_called_once_with()+ controller.capture_user_memory.assert_not_awaited()assert handler._memory_capture_tasks == set()async def test_cancelled_attachment_registration_removes_real_lease_directory(@@ -1802,6 +1797,8 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):attachments_root=root / "attachments",).materialize(context, Downloader())leased_path = Path(batch.attachments[0].local_path)+ retained_lease = batch.lease.retain()+ batch.lease.release()assert leased_path.exists()controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)@@ -1817,23 +1814,20 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):deliver=AsyncMock(),acquire_lifecycle_admission=acquire_lifecycle_admission,)- controller.reserve_memory_attachment_capture = Mock(- side_effect=AssertionError("registration must not run after cancellation")- )controller.capture_user_memory = AsyncMock()handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = AsyncMock(return_value=batch)- task = asyncio.create_task(- handler.handle_user_message(context, "remember this")+ async def capture_write() -> None:+ await controller.capture_user_memory(context, "remember this", "base-session")++ handler._schedule_memory_capture_task(+ session_id="base-session",+ expected_epoch=0,+ capture=capture_write(),+ attachment_lease=retained_lease,)await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)- task.cancel()- with self.assertRaises(asyncio.CancelledError):- await task+ await handler.cancel_memory_capture_tasks()assert not leased_path.exists()assert list((root / "attachments" / "im").iterdir()) == []diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 8125d0ad8..4caade505 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -35,6 +35,7 @@ from core.session_turns import (SCHEDULED_PROVENANCE_KEY,SOURCE_SCHEDULED,TURN_LIFECYCLE_ADMISSION_KEY,+ TURN_LIFECYCLE_EPOCH_KEY,DeliveryRequest,DeliveryResult,SessionTurnManager,@@ -204,28 +205,36 @@ def managers(tmp_path: Path):engine_b.dispose()+def _capture_handler(manager: SessionTurnManager) -> MessageHandler:+ handler = MessageHandler.__new__(MessageHandler)+ handler.controller = manager.controller+ handler._memory_capture_tasks = set()+ handler._memory_capture_tasks_by_session = {}+ handler._memory_capture_registration_open = True+ manager.controller.session_turns = manager+ manager.controller.message_handler = handler+ return handler++@pytest.mark.anyioasync def test_session_lifecycle_waits_for_admitted_turn_capture(managers) -> None:manager, _other, _engine, _engine_b, _starts = managers- handler = MessageHandler.__new__(MessageHandler)- handler._memory_capture_tasks = set()+ handler = _capture_handler(manager)capture_entered = asyncio.Event()release_capture = asyncio.Event()lifecycle_entered = asyncio.Event()async def run_turn(_session_id, context, _text, **_kwargs):- admission = context.platform_specific.pop(- TURN_LIFECYCLE_ADMISSION_KEY- )+ expected_epoch = context.platform_specific.get(TURN_LIFECYCLE_EPOCH_KEY, 0)async def capture() -> None:capture_entered.set()await release_capture.wait()- capture_task = asyncio.create_task(capture())- handler._track_memory_capture_task(- capture_task,- lifecycle_admission=admission,+ handler._schedule_memory_capture_task(+ session_id="ses_fsm",+ expected_epoch=expected_epoch,+ capture=capture(),)async def lifecycle_operation() -> str:@@ -296,6 +305,229 @@ async def test_failed_session_lifecycle_preserves_sampled_epoch(managers) -> Nonadmission.release()+async def test_hung_memory_capture_does_not_fence_next_turn_or_destructive_ops(+ managers,+) -> None:+ """Scenario: MEMORY-INDEP-001."""++ manager, _other, _engine, _engine_b, _starts = managers+ handler = _capture_handler(manager)+ capture_holding = asyncio.Event()+ never_resolves = asyncio.Event()+ lifecycle_busy = False+ dispatched: list[str] = []++ async def hung_capture() -> None:+ capture_holding.set()+ await never_resolves.wait()++ handler._schedule_memory_capture_task(+ session_id="ses_fsm",+ expected_epoch=manager.session_lifecycle_epoch("ses_fsm"),+ capture=hung_capture(),+ )+ await asyncio.wait_for(capture_holding.wait(), timeout=1.0)++ async def run_turn(_session_id, _context, text, **_kwargs):+ dispatched.append(text)++ manager._run = run_turn+ started = await asyncio.wait_for(+ manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="next turn",+ ),+ context=_context(),+ ),+ timeout=1.0,+ )+ assert started.turn_id+ assert dispatched == ["next turn"]++ async def reset_session() -> str:+ return "reset"++ async def archive_session() -> str:+ return "archived"++ try:+ assert await asyncio.wait_for(+ manager.run_session_lifecycle(+ "ses_fsm",+ reset_session,+ deadline_seconds=0.05,+ ),+ timeout=1.0,+ ) == "reset"+ assert await asyncio.wait_for(+ manager.run_session_lifecycle(+ "ses_fsm",+ archive_session,+ deadline_seconds=0.05,+ ),+ timeout=1.0,+ ) == "archived"+ except Exception as error:+ lifecycle_busy = getattr(error, "code", None) == "memory_session_lifecycle_busy"+ raise+ assert lifecycle_busy is False+ never_resolves.set()+ await handler.drain_memory_capture_tasks()+++async def test_capture_admitted_before_new_is_discarded_after_transition(+ managers,+) -> None:+ """Scenario: MEMORY-INDEP-002."""++ manager, _other, _engine, _engine_b, _starts = managers+ handler = _capture_handler(manager)+ attributed: list[str] = []+ admitted = asyncio.Event()+ finish_capture = asyncio.Event()+ sampled_epoch = manager.session_lifecycle_epoch("ses_fsm")++ async def capture_write() -> None:+ attributed.append("wrote")++ async def delayed_capture() -> None:+ admitted.set()+ await finish_capture.wait()+ await handler._run_memory_capture(+ "ses_fsm",+ sampled_epoch,+ capture_write(),+ )++ capture_task = asyncio.create_task(delayed_capture())+ handler._track_memory_capture_task(capture_task, session_id="ses_fsm")+ await asyncio.wait_for(admitted.wait(), timeout=1.0)++ async def reset_session() -> str:+ return "reset"++ assert await manager.run_session_lifecycle(+ "ses_fsm",+ reset_session,+ deadline_seconds=0.05,+ ) == "reset"+ assert not manager.session_lifecycle_epoch_matches("ses_fsm", sampled_epoch)++ finish_capture.set()+ await handler.drain_memory_capture_tasks()+ assert attributed == []+++async def test_idle_session_capture_attributes_and_shutdown_drains(+ managers,+) -> None:+ """Scenario: MEMORY-INDEP-003."""++ manager, _other, _engine, _engine_b, _starts = managers+ handler = _capture_handler(manager)+ attributed: list[str] = []++ async def capture_write() -> None:+ attributed.append("wrote")++ await handler._run_memory_capture(+ "ses_fsm",+ manager.session_lifecycle_epoch("ses_fsm"),+ capture_write(),+ )+ assert attributed == ["wrote"]++ never_resolves = asyncio.Event()++ async def accepted_capture() -> None:+ await never_resolves.wait()++ pending = asyncio.create_task(accepted_capture(), name="memory-capture")+ handler._track_memory_capture_task(pending, session_id="ses_fsm")+ drain = asyncio.create_task(handler.drain_memory_capture_tasks())+ await asyncio.sleep(0)+ assert not drain.done()+ never_resolves.set()+ await asyncio.wait_for(drain, timeout=1.0)+ assert handler._memory_capture_tasks == set()+++async def test_successful_lifecycle_does_not_cancel_a_new_generation_capture(+ managers,+) -> None:+ """A capture registered during reset must not be cancelled on the success bump."""++ manager, _other, _engine, _engine_b, _starts = managers+ handler = _capture_handler(manager)+ scheduled: list[asyncio.Task[object]] = []++ async def reset_session() -> str:+ task = handler._schedule_memory_capture_task(+ session_id="ses_fsm",+ expected_epoch=manager.session_lifecycle_epoch("ses_fsm"),+ capture=asyncio.sleep(0),+ )+ assert task is not None+ scheduled.append(task)+ await asyncio.sleep(0)+ return "reset"++ assert await manager.run_session_lifecycle(+ "ses_fsm",+ reset_session,+ deadline_seconds=1.0,+ ) == "reset"+ assert scheduled[0].cancelled() is False+ await handler.drain_memory_capture_tasks()+ assert scheduled[0].cancelled() is False+++async def test_failed_timeout_lifecycle_preserves_in_flight_captures(+ managers,+) -> None:+ """A failed /new after the 5s deadline must not cancel accepted captures."""++ manager, _other, _engine, _engine_b, _starts = managers+ handler = _capture_handler(manager)+ never_resolves = asyncio.Event()+ holding = asyncio.Event()++ async def hung_capture() -> None:+ holding.set()+ await never_resolves.wait()++ handler._schedule_memory_capture_task(+ session_id="ses_fsm",+ expected_epoch=manager.session_lifecycle_epoch("ses_fsm"),+ capture=hung_capture(),+ )+ await asyncio.wait_for(holding.wait(), timeout=1.0)+ sampled_epoch = manager.session_lifecycle_epoch("ses_fsm")++ async def reset_session() -> str:+ raise RuntimeError("reset failed")++ with pytest.raises(RuntimeError, match="reset failed"):+ await manager.run_session_lifecycle(+ "ses_fsm",+ reset_session,+ deadline_seconds=0.05,+ )++ assert manager.session_lifecycle_epoch_matches("ses_fsm", sampled_epoch)+ assert handler._memory_capture_tasks+ assert all(not task.cancelled() for task in handler._memory_capture_tasks)+ never_resolves.set()+ await handler.drain_memory_capture_tasks()++async def _activate(manager: SessionTurnManager,*,@@ -4838,49 +5070,35 @@ def test_pre_dispatch_hydration_failure_is_definitively_recoverable(managers) ->assert _row(engine, str(admitted.delivery_id))["state"] == "claimed"-def test_persisted_start_revalidation_failure_releases_lifecycle_admission(+def test_persisted_start_does_not_acquire_lifecycle_admission(managers,monkeypatch,) -> None:+ """Scenario: MEMORY-INDEP-001. Dispatch must not wait on Memory."""+manager, _other, _engine, _engine_b, _starts = managers- original_begin = manager._sqlite_engine().beginacquired = False-original_acquire = manager.acquire_lifecycle_admissionasync def track_acquire(raw_session_id):nonlocal acquired- admission = await original_acquire(raw_session_id)acquired = True- return admission+ return await original_acquire(raw_session_id)monkeypatch.setattr(manager, "acquire_lifecycle_admission", track_acquire)-- def failing_begin():- if acquired:- raise OSError("temporary sqlite outage")- return original_begin()-- engine = manager._sqlite_engine()- monkeypatch.setattr(- manager,- "_sqlite_engine",- lambda: SimpleNamespace(connect=engine.connect, begin=failing_begin),- )- with pytest.raises(OSError, match="temporary sqlite outage"):- asyncio.run(- manager.deliver(- DeliveryRequest(- session_id="ses_fsm",- priority="p3",- content="release the lock",- ),- context=_context(),- )+ asyncio.run(+ manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="do not fence dispatch",+ ),+ context=_context(),)+ )- assert acquired- assert not manager._session_lifecycle_locks["ses_fsm"].locked()+ assert acquired is False+ assert "ses_fsm" not in manager._session_lifecycle_locks@pytest.mark.parametrize(diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex b225da39f..c9cde8a12 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -324,7 +324,6 @@"channelNotEnabled": "This channel is not enabled. Please go to the control panel to enable it.","unknownCommand": "Unknown command: `/{command}`\n\nPlease use `@avibe /start` to access all bot features.","clearSession": "Error clearing session: {error}",- "memorySessionLifecycleBusy": "Memory is still processing this session. Please try /new again.","settingsFailed": "Failed to open settings. Please try again.","cwdChangeFailed": "Failed to open directory change dialog. Please try again.","resumeFailed": "Failed to open resume dialog. Please try again.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 368e0eec2..a55990d4f 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -324,7 +324,6 @@"channelNotEnabled": "此频道未启用。请前往控制面板启用它。","unknownCommand": "未知命令:`/{command}`\n\n请使用 `@avibe /start` 访问所有机器人功能。","clearSession": "清除会话时出错:{error}",- "memorySessionLifecycleBusy": "记忆系统仍在处理当前会话,请稍后重试 /new。","settingsFailed": "无法打开设置。请重试。","cwdChangeFailed": "无法打开目录更改对话框。请重试。","resumeFailed": "无法打开恢复对话框。请重试。",