Skip to content

Commit 0a39f90

Browse files
authored
Keep the original OAR session for confirmed operations (#9967)
* fix(turn): retain the selected operation transport across OAR resume Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> * Close managed OAR sessions when initialization loses its binding (#9984) Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --------- Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 9f652a5 commit 0a39f90

5 files changed

Lines changed: 124 additions & 10 deletions

File tree

‎loopx/control_plane/turn_driver/codex_sessions.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ def _store_codex_cli_session(
233233
goal_ref: Mapping[str, Any] | None = None,
234234
session_profile_digest: str | None = None,
235235
operation_profile_digest: str | None = None,
236+
operation_transport: str | None = None,
236237
operation_model: str | None = None,
237238
operation_reasoning_effort: str | None = None,
238239
ordinary_dsh: bool = False,
@@ -299,6 +300,7 @@ def _store_codex_cli_session(
299300
session_id=session_id,
300301
goal_ref=goal_ref,
301302
operation_profile_digest=operation_profile_digest,
303+
operation_transport=operation_transport,
302304
operation_model=operation_model,
303305
operation_reasoning_effort=operation_reasoning_effort,
304306
ordinary_dsh=ordinary_dsh,
@@ -326,6 +328,7 @@ class ManagedOperationSession:
326328
original: dict[str, Any] | None
327329
goal_ref: Mapping[str, Any] | None
328330
profile_digest: str
331+
transport: str
329332
model: str
330333
reasoning_effort: str
331334
goal_admission: FirstPartyHostGoalAdmission | None
@@ -335,6 +338,7 @@ def commit() -> None:
335338
values: dict[str, Any] = dict(
336339
lineage=self.lineage, host=self.host, session_id=session_id,
337340
goal_ref=self.goal_ref, operation_profile_digest=self.profile_digest,
341+
operation_transport=self.transport,
338342
operation_model=self.model, operation_reasoning_effort=self.reasoning_effort,
339343
)
340344
if self.host == "dsh":
@@ -394,7 +398,7 @@ def select_managed_operation_session(
394398
)
395399
return ManagedOperationSession(
396400
runtime_root, dict(lineage), host, binding, original, request.get("goal_ref"),
397-
profile_digest, model, reasoning_effort, goal_admission,
401+
profile_digest, transport, model, reasoning_effort, goal_admission,
398402
)
399403

400404

@@ -434,6 +438,7 @@ def _write_codex_cli_session(
434438
goal_ref: Mapping[str, Any] | None = None,
435439
session_profile_digest: str | None = None,
436440
operation_profile_digest: str | None = None,
441+
operation_transport: str | None = None,
437442
operation_model: str | None = None,
438443
operation_reasoning_effort: str | None = None,
439444
ordinary_dsh: bool = False,
@@ -484,7 +489,7 @@ def _write_codex_cli_session(
484489
if checkpoint_model_transition is not None:
485490
payload["checkpoint_model_transition"] = dict(checkpoint_model_transition)
486491
if operation_profile_digest is not None:
487-
payload["operation_transport"] = (
492+
payload["operation_transport"] = operation_transport or (
488493
"dsh-native-operation-tools-v0" if host == "dsh"
489494
else "app-server-operation-tools-v0"
490495
)

‎loopx/control_plane/turn_driver/oar_operation_host.py‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from __future__ import annotations
99

1010
from collections.abc import Callable, Mapping
11+
from contextlib import ExitStack, suppress
1112
import hashlib
1213
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
1314
import json
@@ -212,7 +213,7 @@ def run_oar_operation_host(
212213
)
213214

214215
client = oar_client or default_oar_client()
215-
with _LoopbackOperationCallbackServer(handler) as callback:
216+
with _LoopbackOperationCallbackServer(handler) as callback, ExitStack() as cleanup:
216217
if runtime_id == "dsh":
217218
assert dsh_home is not None
218219
dsh_home.mkdir(parents=True, exist_ok=True)
@@ -254,7 +255,17 @@ def run_oar_operation_host(
254255

255256
opened = client.open_session(open_params)
256257
session_key = str(opened["session_key"])
257-
native_session_id = str(opened.get("native_session_id") or session_id)
258+
# The handle is live before binding and prompt preparation can fail.
259+
@cleanup.callback
260+
def close_opened_session() -> None:
261+
with suppress(Exception):
262+
client.close_session(session_key)
263+
264+
native_session_id = opened.get("native_session_id")
265+
if not isinstance(native_session_id, str) or not native_session_id.strip() or (
266+
binding and native_session_id != session_id
267+
):
268+
raise ValueError("OAR did not return the selected native operation session")
258269
if not binding:
259270
session_id = native_session_id
260271
route = operations.operation_executor_route(
@@ -334,11 +345,6 @@ def run_oar_operation_host(
334345
failure_kind=exc.failure_kind or "unknown",
335346
recovery_kind="resume_session",
336347
) from exc
337-
finally:
338-
try:
339-
client.close_session(session_key)
340-
except Exception:
341-
pass
342348

343349
raw_outcome = prompt_result.get("outcome")
344350
outcome: dict[str, Any] = raw_outcome if isinstance(raw_outcome, dict) else {}

‎loopx/control_plane/work_items/operation_agent_handoff.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,9 @@ export function managedOperationBindingCurrent(input: JsonObject): JsonObject {
144144
: session.schema_version === "loopx_codex_cli_session_v1" && (session.host == null || session.host === "codex-cli"))
145145
&& session.goal_id === parameters.goal_id && session.agent_id === parameters.agent_id
146146
&& session.todo_id === executor.todo_id && session.session_id === executor.session_id
147-
&& session.operation_transport === (managedHost(executor) === "dsh" ? "dsh-native-operation-tools-v0" : "app-server-operation-tools-v0")
147+
&& (managedHost(executor) === "dsh"
148+
? session.operation_transport === "dsh-native-operation-tools-v0" || session.operation_transport === "oar-dsh-operation-mcp-v0"
149+
: session.operation_transport === "app-server-operation-tools-v0" || session.operation_transport === "oar-codex-operation-mcp-v0")
148150
&& session.operation_profile_digest === executor.profile_digest
149151
&& session.operation_model === executor.model && session.operation_reasoning_effort === executor.reasoning_effort
150152
&& sameGoalRef};

‎tests/control_plane/test_operation_requests.py‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,3 +346,92 @@ def test_codex_app_server_resolves_ref_and_freezes_profile_while_inline_remains_
346346
source.path.write_bytes(source.path.read_bytes() + b" ")
347347
with pytest.raises(ValueError, match="content changed"):
348348
run_codex_operation_host(resumed, **options)
349+
350+
351+
@pytest.mark.parametrize(("host", "transport", "other"), [
352+
("dsh", "oar-dsh-operation-mcp-v0", "dsh-native-operation-tools-v0"),
353+
("codex-cli", "oar-codex-operation-mcp-v0", "app-server-operation-tools-v0"),
354+
])
355+
def test_oar_session_resumes_only_its_recorded_operation_transport(tmp_path, host, transport, other):
356+
from loopx.control_plane.turn_driver.codex_sessions import _lineage, select_managed_operation_session
357+
358+
request = _managed_operation_turn_request()
359+
options = dict(request=request, lineage=_lineage(request), host=host,
360+
profile_digest="a" * 64, model="fixture-model", reasoning_effort="high")
361+
select_managed_operation_session(tmp_path, transport=transport, **options).store("owned-session")
362+
request["session"]["action"] = "resume"
363+
selected = select_managed_operation_session(tmp_path, transport=transport, **options)
364+
assert selected.binding["session_id"] == "owned-session"
365+
with pytest.raises(ValueError, match="profile changed"):
366+
select_managed_operation_session(tmp_path, transport=other, **options)
367+
368+
369+
@pytest.mark.parametrize("returned_id", ["replacement-session", None])
370+
def test_oar_refuses_missing_or_replaced_native_session_before_prompt(tmp_path, returned_id):
371+
from loopx.control_plane.turn_driver.oar_operation_host import run_oar_operation_host
372+
373+
class Client:
374+
native_id = "original-session"
375+
376+
def __init__(self):
377+
self.prompts = []
378+
self.closed = []
379+
380+
def open_session(self, params):
381+
if self.prompts:
382+
assert params["resume"] == "original-session"
383+
return {"session_key": "fixture-key", "native_session_id": self.native_id}
384+
385+
def prompt(self, params, *, timeout):
386+
self.prompts.append(params["sessionKey"])
387+
return {"text": "{}"}
388+
389+
def close_session(self, key):
390+
self.closed.append(key)
391+
392+
service, store = fixtures.service(tmp_path)
393+
client = Client()
394+
request = _managed_operation_turn_request()
395+
options = dict(host="dsh", runtime_id="dsh", runtime_root=store.root.parent.parent,
396+
registry_path=service.registry_path, project=tmp_path / "project",
397+
dsh_home=tmp_path / "dsh", max_tokens=64, provider="deepseek-official",
398+
model="fixture-model", reasoning_effort="high", oar_client=client)
399+
run_oar_operation_host(request, **options)
400+
request["session"]["action"] = "resume"
401+
client.native_id = returned_id
402+
with pytest.raises(ValueError, match="selected native operation session"):
403+
run_oar_operation_host(request, **options)
404+
assert client.prompts == ["fixture-key"]
405+
assert client.closed == ["fixture-key", "fixture-key"]
406+
407+
408+
@pytest.mark.parametrize("host", ["dsh", "codex-cli"])
409+
def test_oar_closes_opened_session_when_another_writer_wins_initialization(tmp_path, host):
410+
from unittest.mock import Mock
411+
412+
from loopx.control_plane.turn_driver.codex_sessions import _lineage, load_codex_cli_session
413+
from loopx.control_plane.turn_driver.oar_operation_host import run_oar_operation_host
414+
from loopx.hosts.oar_client import OarSessionClient
415+
416+
service, store = fixtures.service(tmp_path)
417+
runtime = store.root.parent.parent
418+
request = _managed_operation_turn_request()
419+
lineage = _lineage(request)
420+
client = Mock(spec=OarSessionClient)
421+
422+
def open_then_replace(params):
423+
_store_codex_cli_session(runtime, lineage=lineage, host=host, session_id="winner")
424+
return {"session_key": "owned-handle", "native_session_id": "new-session"}
425+
426+
client.open_session.side_effect = open_then_replace
427+
with pytest.raises(ValueError, match="binding changed during"):
428+
run_oar_operation_host(
429+
request, host=host, runtime_id="dsh" if host == "dsh" else "codex",
430+
runtime_root=runtime, registry_path=service.registry_path, project=tmp_path,
431+
dsh_home=tmp_path / "dsh", max_tokens=256, provider="fixture-provider",
432+
model="fixture-model", reasoning_effort="high", oar_client=client,
433+
)
434+
435+
client.close_session.assert_called_once_with("owned-handle")
436+
client.prompt.assert_not_called()
437+
assert load_codex_cli_session(runtime, lineage=lineage, host=host)["session_id"] == "winner"

‎tests/control_plane_ts/operation_agent_handoff.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,18 @@ test("managed binding is the existing exact Goal/Todo/session/profile owner, nev
227227
operation_model: "test-model", operation_reasoning_effort: "xhigh",
228228
goal_ref: {goal_instance_id: "instance-1", goal_id: "test-goal"}};
229229
assert.equal(managedOperationBindingCurrent({parameters, session}).current, true);
230+
const dsh = {...session, host: "dsh", schema_version: "loopx_managed_cli_session_v1"};
231+
const dshParameters = {...parameters, executor: {...parameters.executor as JsonObject, host: "dsh"}};
232+
for (const [transport, codexCurrent, dshCurrent] of [
233+
["oar-codex-operation-mcp-v0", true, false],
234+
["oar-dsh-operation-mcp-v0", false, true],
235+
["dsh-native-operation-tools-v0", false, true],
236+
["app-server-operation-tools-v0", true, false],
237+
["unknown", false, false],
238+
] as const) {
239+
assert.equal(managedOperationBindingCurrent({parameters, session: {...session, operation_transport: transport}}).current, codexCurrent);
240+
assert.equal(managedOperationBindingCurrent({parameters: dshParameters, session: {...dsh, operation_transport: transport}}).current, dshCurrent);
241+
}
230242
for (const changed of [{session_id: "replacement"}, {todo_id: "other"}, {agent_id: "other"},
231243
{operation_profile_digest: "b".repeat(64)}, {operation_transport: null}, {goal_ref: {goal_id: "test-goal", goal_instance_id: "instance-2"}},
232244
{schema_version: "future"}]) assert.equal(managedOperationBindingCurrent({parameters, session: {...session, ...changed}}).current, false);

0 commit comments

Comments
 (0)