From 1eca3eb751d5808b9dcc20a2abf5b77fd9461999 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:54:02 +0800 Subject: [PATCH 1/3] Check the original Steward Session after verifying its binding Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../smoke/bound-conversation-http-fixture.py | 12 +++++------- .../native_chat/conversation_bindings.py | 4 +++- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py b/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py index 5635ac587f..5384a0ab51 100644 --- a/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py +++ b/apps/presentation/dashboard/smoke/bound-conversation-http-fixture.py @@ -203,19 +203,17 @@ def fail_first_image_read(handler, parts): hold_steward_discovery, resume_steward_discovery = threading.Event(), threading.Event() if self.steward: - core = bindings._core + recheck = bindings._recheck_local_bindings - def controlled_core(operation, params, **kwargs): - result = core(operation, params, **kwargs) - if (operation == "collaboration.conversation.local_sessions" - and params.get("app_steward_entry") and hold_steward_discovery.is_set()): + def controlled_binding_recheck(observed): + if hold_steward_discovery.is_set(): hold_steward_discovery.clear() print(json.dumps({"steward_discovery_held": True}), flush=True) if not resume_steward_discovery.wait(15): raise TimeoutError("steward discovery fixture was not released") - return result + recheck(observed) - bindings._core = controlled_core + bindings._recheck_local_bindings = controlled_binding_recheck def delayed_history(handler, selected_session): if selected_session == sid and slow_page.is_set(): diff --git a/loopx/capabilities/native_chat/conversation_bindings.py b/loopx/capabilities/native_chat/conversation_bindings.py index 0ef70a6856..a7fe96c9c9 100644 --- a/loopx/capabilities/native_chat/conversation_bindings.py +++ b/loopx/capabilities/native_chat/conversation_bindings.py @@ -289,13 +289,15 @@ def app_steward_session(self) -> dict[str, Any] | None: if not sessions: raise ValueError("the original steward Session is unavailable") session = max(sessions, key=lambda item: (item.get("last_activity_at") or "", item["session_id"])) + self._recheck_local_bindings(current) + # Close may commit while we verify the grant. Read the original Session + # afterwards so an already committed Close cannot return a stale target. fresh = self.controller.store.load_session(session["session_id"]) if fresh is None or fresh.get("status") == "closed": raise ValueError("the original steward Session is unavailable") expected = {**self._session_observation(session), "status": fresh.get("status")} if self._session_observation(fresh) != expected: raise ValueError("the original steward Session is unavailable") - self._recheck_local_bindings(current) return fresh def _revoke_delivery_sources(self, binding_id: str) -> None: From f1b459af1f11e26cb7d513fceb07e16b8fb002d5 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:23:23 +0800 Subject: [PATCH 2/3] Keep original Steward discovery coherent with Session Close Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/conversation_bindings.py | 20 +++-- loopx/chat_store.py | 26 +++++- tests/test_chat_conversation_bindings.py | 90 +++++++++++++++++++ 3 files changed, 126 insertions(+), 10 deletions(-) diff --git a/loopx/capabilities/native_chat/conversation_bindings.py b/loopx/capabilities/native_chat/conversation_bindings.py index 0ef70a6856..a38ac0d472 100644 --- a/loopx/capabilities/native_chat/conversation_bindings.py +++ b/loopx/capabilities/native_chat/conversation_bindings.py @@ -289,14 +289,18 @@ def app_steward_session(self) -> dict[str, Any] | None: if not sessions: raise ValueError("the original steward Session is unavailable") session = max(sessions, key=lambda item: (item.get("last_activity_at") or "", item["session_id"])) - fresh = self.controller.store.load_session(session["session_id"]) - if fresh is None or fresh.get("status") == "closed": - raise ValueError("the original steward Session is unavailable") - expected = {**self._session_observation(session), "status": fresh.get("status")} - if self._session_observation(fresh) != expected: - raise ValueError("the original steward Session is unavailable") - self._recheck_local_bindings(current) - return fresh + # Close uses the same Session fences. Keep it from committing between + # this read and the final grant decision; grant revocation still races + # freely and is detected by the version check. All provider/Core IO has + # already completed, and background grant inspection remains nonblocking. + with self.controller.store.read_session_fenced(session["session_id"]) as fresh: + if fresh is None or fresh.get("status") == "closed": + raise ValueError("the original steward Session is unavailable") + expected = {**self._session_observation(session), "status": fresh.get("status")} + if self._session_observation(fresh) != expected: + raise ValueError("the original steward Session is unavailable") + self._recheck_local_bindings(current) + return fresh def _revoke_delivery_sources(self, binding_id: str) -> None: if self.controller is not None: diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 343b03ab5a..35d2da9776 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -4,7 +4,7 @@ from bisect import bisect_right from collections import OrderedDict -from contextlib import suppress +from contextlib import contextmanager, suppress from copy import deepcopy from datetime import datetime, timedelta, timezone import hashlib @@ -38,7 +38,7 @@ AcceptedManagedTurn, plan_managed_turn_acceptance, ) -from .file_lock import exclusive_file_lock, write_json_atomic +from .file_lock import exclusive_file_lock, try_exclusive_file_lock, write_json_atomic CHAT_STORE_SCHEMA_VERSION = "loopx_chat_store_v1" @@ -394,6 +394,28 @@ def load_session(self, session_id: str) -> dict[str, Any] | None: payload = _read_json(self._session_path(session_id)) return payload if payload.get("schema_version") == CHAT_SESSION_SCHEMA_VERSION else None + @contextmanager + def read_session_fenced(self, session_id: str) -> Iterator[dict[str, Any] | None]: + """Keep Session state stable through a caller's local decision. + + Reuse the writer fences without waiting for ongoing work or changing + its holder record. Callers must keep provider IO outside this scope. + """ + path = self._session_path(session_id) + if not path.exists(): + yield None + return + lock = self._session_lock(session_id) + if not lock.acquire(blocking=False): + raise ValueError("chat session is changing; retry") + try: + with try_exclusive_file_lock(path, preserve_holder=True) as held: + if held is None: + raise ValueError("chat session is changing; retry") + yield self.load_session(session_id) + finally: + lock.release() + def reserve_loopx_outcome_request( self, session_id: str, *, turn_id: str, operation_id: str, request: dict[str, Any], diff --git a/tests/test_chat_conversation_bindings.py b/tests/test_chat_conversation_bindings.py index c93d513cb9..523b0f4214 100644 --- a/tests/test_chat_conversation_bindings.py +++ b/tests/test_chat_conversation_bindings.py @@ -999,6 +999,96 @@ def change_after_discovery(operation, params, **kwargs): assert (capture.read_bytes(), store.messages(sid)) == before +@pytest.mark.parametrize("change", ["close", "revocation"]) +def test_steward_final_discovery_keeps_session_live_until_grant_decision(steward, monkeypatch, change): # noqa: F811 + import threading + from concurrent.futures import ThreadPoolExecutor + + store, runtime, provider, transport, binding, capture, _ = steward + event = provider.event("steward-app", "final-live-decision", "Read the original workspace") + transport.admit("steward-app", event) + request = transport.core.read_request(identity_ref(binding["provider_ref"], event["message_id"])) + sid = request["session_id"] + assert runtime.wait_for_turn(session_id=sid, turn_id=request["turn_id"], timeout_sec=10)["status"] == "completed" + bindings = transport.bindings + bindings.select_app_steward(binding["binding_id"], expected_revision=bindings.read()["revision"]) + before = capture.read_bytes(), store.messages(sid), len(store.list_sessions()) + recheck, close = bindings._recheck_local_bindings, store.close_managed_session + close_entered, close_completed = threading.Event(), threading.Event() + + def close_original(session_id): + close_entered.set() + try: + return close(session_id) + finally: + close_completed.set() + + monkeypatch.setattr(store, "close_managed_session", close_original) + with ThreadPoolExecutor(max_workers=1) as workers: + pending = [] + + def before_final_decision(observed): + if change == "revocation": + bindings.disconnect(binding["binding_id"], expected_revision=bindings.read()["revision"]) + else: + pending.append(workers.submit(runtime.close_session, sid)) + assert close_entered.wait(2) + assert not close_completed.wait(.15), "Close committed inside the final live Session decision" + recheck(observed) + + with monkeypatch.context() as patch: + patch.setattr(bindings, "_recheck_local_bindings", before_final_decision) + if change == "revocation": + with pytest.raises(ValueError, match="changed"): + bindings.app_steward_target() + else: + assert bindings.app_steward_target() == {"binding_id": binding["binding_id"], "session_id": sid} + if pending: + assert pending[0].result(timeout=2) is True + assert store.load_session(sid)["status"] == "closed" + with pytest.raises(ValueError): + bindings.app_steward_target() + assert (capture.read_bytes(), store.messages(sid), len(store.list_sessions())) == before + + +@pytest.mark.parametrize("fence", ["thread", "file"]) +def test_steward_session_writer_is_unavailable_without_waiting_and_retries(steward, fence): # noqa: F811 + import threading + from concurrent.futures import ThreadPoolExecutor + from loopx.file_lock import exclusive_file_lock + + store, runtime, provider, transport, binding, capture, _ = steward + event = provider.event("steward-app", "busy-original", "Read the original workspace") + transport.admit("steward-app", event) + request = transport.core.read_request(identity_ref(binding["provider_ref"], event["message_id"])) + sid = request["session_id"] + assert runtime.wait_for_turn(session_id=sid, turn_id=request["turn_id"], timeout_sec=10)["status"] == "completed" + bindings = transport.bindings + bindings.select_app_steward(binding["binding_id"], expected_revision=bindings.read()["revision"]) + before = capture.read_bytes(), store.messages(sid), store.load_session(sid) + held, release = threading.Event(), threading.Event() + + def existing_writer(): + lock = (store._session_lock(sid) if fence == "thread" else + exclusive_file_lock(store._session_path(sid), operation="hold_session_update")) + with lock: + held.set() + assert release.wait(5) + + with ThreadPoolExecutor(max_workers=2) as workers: + writer = workers.submit(existing_writer) + try: + assert held.wait(2) + opened = workers.submit(bindings.app_steward_target) + with pytest.raises(ValueError, match="changing"): + opened.result(timeout=.75) + finally: + release.set() + writer.result(timeout=2) + assert bindings.app_steward_target() == {"binding_id": binding["binding_id"], "session_id": sid} + assert (capture.read_bytes(), store.messages(sid), store.load_session(sid)) == before + + def _request_for_event(transport, event): binding = transport._binding("notes-app") return transport.core.read_request( From 62b40b56387a898edaa6b0dd5754626ab723ecf1 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:31:25 +0800 Subject: [PATCH 3/3] Account for the bounded Session observation fence Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/canary/module_metric_baseline.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index c42a77b450..abc03df3f8 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -47,7 +47,7 @@ "lines": 2058 }, "loopx/chat_store.py": { - "lines": 2163 + "lines": 2180 }, "loopx/codex_cli_probe.py": { "any_count": 37,