Skip to content

Commit 8387525

Browse files
authored
fix(context): reject FIFO replay sources without blocking hooks (#7466)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 1d78f57 commit 8387525

2 files changed

Lines changed: 64 additions & 1 deletion

File tree

‎loopx/control_plane/turn_driver/codex_context_history.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ def _snapshot(event: dict[str, Any]) -> Iterator[tuple[dict[str, Any], BinaryIO]
4646
path = Path(event.get("transcript_path") or "")
4747
if not path.is_absolute() or path.resolve(strict=True) != path:
4848
raise ValueError("native replay source must be physical and absolute")
49-
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
49+
# Inspect the opened descriptor before reading. A FIFO must not wait for a
50+
# writer while the hook holds its context journal lock.
51+
descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
5052
with os.fdopen(descriptor, "rb") as stream:
5153
info = os.fstat(stream.fileno())
5254
if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid()

‎tests/control_plane/test_codex_context_resume.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
from __future__ import annotations
33

44
import json
5+
import os
6+
from pathlib import Path
7+
import subprocess
8+
import sys
9+
510
import pytest
611

712
from loopx.control_plane.turn_driver import codex_context as context
@@ -200,6 +205,62 @@ def test_incomplete_native_read_cannot_gain_resume_continuity(tmp_path, monkeypa
200205
assert wire["mode"] == "full" and wire["context"] == payload
201206

202207

208+
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="Named pipes require POSIX")
209+
@pytest.mark.parametrize("phase", ["resume", "post_tool"])
210+
@pytest.mark.parametrize("enabled", [False, True])
211+
def test_real_hook_rejects_fifo_history_without_waiting_for_a_writer(tmp_path, monkeypatch, phase, enabled):
212+
event, history, payload = observed_read(tmp_path, monkeypatch)
213+
assert "native_resume" in context._state(tmp_path)["candidate"]
214+
fields = {"hook_event_name": "SessionStart", "source": "resume"}
215+
if phase == "post_tool":
216+
current = {**payload, "heartbeat_receipt": {"turn_instance_id": "second"}}
217+
_, wire = project(tmp_path, "second", payload=current)
218+
assert wire["mode"] == "delta"
219+
pages = read_pages(tmp_path, wire, size=8192)
220+
assert len(pages) == 1 and pages[0]["eof"]
221+
fields = {"hook_event_name": "PostToolUse", "tool_use_id": "second-reader",
222+
"tool_response": json.dumps(pages[0])}
223+
224+
history.unlink()
225+
os.mkfifo(history, 0o600) # No writer: opening this source must not block before validation.
226+
journal = tmp_path / "session.json"
227+
original = journal.read_bytes()
228+
before = context._state(tmp_path)
229+
reference = before["recovery"]
230+
captured = Path(reference["path"]).read_bytes()
231+
registry, runtime = tmp_path / "absent-registry.json", tmp_path / "absent-runtime"
232+
cli = [sys.executable, "-m", "loopx.entrypoint", "--registry", str(registry),
233+
"--runtime-root", str(runtime), "quota", "context-hook", "--context-delivery",
234+
"on" if enabled else "off", "--codex-app", "--codex-context-dir", str(tmp_path)]
235+
236+
def hook(values):
237+
result = subprocess.run(cli, input=json.dumps({**event, **values}), capture_output=True,
238+
text=True, timeout=5, cwd=Path(__file__).resolve().parents[2])
239+
assert result.returncode == 0, result.stderr
240+
return json.loads(result.stdout)
241+
242+
result = hook(fields)
243+
if not enabled:
244+
assert result == {} and journal.read_bytes() == original
245+
else:
246+
if phase == "post_tool":
247+
assert result == {}
248+
# Complete page delivery can still support this process, but the
249+
# unreadable history cannot certify a cross-process replay.
250+
candidate = context._state(tmp_path)["candidate"]
251+
assert candidate["capture_bytes_verified"] is True and "native_resume" not in candidate
252+
result = hook({"hook_event_name": "SessionStart", "source": "resume"})
253+
after = context._state(tmp_path)
254+
assert "candidate" not in after and "pending" not in after
255+
assert after["context_epoch"] != before["context_epoch"]
256+
assert after["recovery"] == reference
257+
assert reference["command"] in result["hookSpecificOutput"]["additionalContext"]
258+
_, fallback = project(tmp_path, "after-fifo", payload=payload)
259+
assert fallback["mode"] == "full" and fallback["context"] == payload
260+
assert Path(reference["path"]).read_bytes() == captured
261+
assert not registry.exists() and not runtime.exists()
262+
263+
203264
def test_complete_eof_cannot_hide_a_prior_page_missing_from_native_replay(tmp_path, monkeypatch):
204265
event, _, payload = observed_read(tmp_path, monkeypatch, lost_prefix=True)
205266
context.codex_context_hook(str(tmp_path), {**event, "source": "resume"})

0 commit comments

Comments
 (0)