codex-python / tests /test_session.py
tailot's picture
Upload folder using huggingface_hub
f628309 verified
Raw History Blame
24.3 kB
"""Tests for PythonWorkspaceSession transactional editing, verification, and rollback."""
from __future__ import annotations
import os
import time
from pathlib import Path
from typing import Any, Dict, Tuple
import pytest
from lingologos_codex.fsadapter import FileSystemAdapterError
import lingologos_python.session as session_module
from lingologos_python.adapter import GATE_TIMEOUT_ENV
from lingologos_python.session import (
LINKED_PATH_IN_WORKSPACE,
NODE_TIMEOUT,
NodeTimeoutError,
PythonWorkspaceSession,
SessionResult,
WorkspaceLinkError,
_verify_probe,
)
def test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None:
session = PythonWorkspaceSession(sample_pkg)
res = session.verify("src/mathops.py")
assert res.verdict == "VERIFIED"
assert res.assurance == 3
assert res.committed is False
def test_edit_file_commits_only_when_verified(sample_pkg: Path) -> None:
session = PythonWorkspaceSession(sample_pkg)
res = session.edit_file(
"src/mathops.py",
"return left + right",
"return int(left) + int(right)",
commit=True,
)
assert res.verdict == "VERIFIED"
assert res.assurance == 3
assert res.committed is True
assert "return int(left) + int(right)" in (sample_pkg / "src" / "mathops.py").read_text(
encoding="utf-8"
)
def test_edit_file_does_not_touch_disk_when_tests_fail(sample_pkg: Path) -> None:
session = PythonWorkspaceSession(sample_pkg)
before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")
res = session.edit_file(
"src/mathops.py",
"return left + right",
"return left - right",
commit=True,
)
after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")
assert res.verdict == "UNKNOWN"
assert res.reason == "GATE_REJECTED"
assert res.committed is False
assert before == after
def test_edit_file_refuses_protected_and_traversal_paths(sample_pkg: Path) -> None:
(sample_pkg / ".env").write_text("KEY=1\n", encoding="utf-8")
session = PythonWorkspaceSession(sample_pkg)
env_res = session.edit_file(".env", "KEY=1", "KEY=2", commit=True)
assert env_res.verdict == "UNKNOWN"
assert env_res.reason == "PROTECTED_PATH"
assert env_res.committed is False
assert (sample_pkg / ".env").read_text(encoding="utf-8") == "KEY=1\n"
esc_res = session.edit_file("../outside.py", "a = 1", "a = 2", commit=True)
assert esc_res.verdict == "UNKNOWN"
assert esc_res.reason in ("PROTECTED_PATH", "NOT_APPLIED")
assert esc_res.committed is False
def test_create_and_delete_file_transactions(sample_pkg: Path) -> None:
session = PythonWorkspaceSession(sample_pkg)
created = session.create_file(
"src/helper.py",
'"""Extra module."""\n\n\ndef square(x: int) -> int:\n return x * x\n',
commit=True,
)
assert created.verdict == "VERIFIED"
assert created.committed is True
assert (sample_pkg / "src" / "helper.py").is_file()
deleted = session.delete_file("src/helper.py", commit=True)
assert deleted.verdict == "VERIFIED"
assert deleted.committed is True
assert not (sample_pkg / "src" / "helper.py").exists()
def test_retry_loop_stops_on_identical_failure_stall(sample_pkg: Path) -> None:
session = PythonWorkspaceSession(sample_pkg)
def repeated_bad_edit(attempt: int, last_result: object) -> tuple[str, str]:
return ("return left + right", "return left - right")
final, attempts = session.run_retry_loop("src/mathops.py", repeated_bad_edit, max_attempts=5)
assert final.verdict == "UNKNOWN"
assert len(attempts) == 2
assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", []))
def test_a_three_argument_proposer_is_handed_the_failure_it_should_learn_from(sample_pkg: Path) -> None:
session = PythonWorkspaceSession(sample_pkg)
seen: Dict[str, object] = {}
def learning_proposer(attempt: int, last_result: object, context: object) -> tuple[str, str]:
if attempt == 1:
# An anchor that is not in the file: the patch is not applied, so the
# second attempt is a move and not the loop the stall detector blocks.
return ("return left * right", "return left / right")
seen["reasons"] = tuple(context.failure_reasons)
seen["trace"] = context.attempts[0].trace
seen["attempt"] = context.attempt
seen["path"] = context.rel_path
return ("return left + right", "return left + right # proposed again")
final, _attempts = session.run_retry_loop("src/mathops.py", learning_proposer, max_attempts=3)
assert final.committed is True
assert seen["reasons"]
assert len(seen["trace"]) >= 6
assert seen["attempt"] == 2
assert seen["path"] == "src/mathops.py"
def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None:
text = '"""Module doc.\n\nSpread over several lines.\n"""\n\n\ndef go() -> int:\n return 1\n'
search, replace, original = _verify_probe(text)
assert search == "def go() -> int:"
assert replace == search + " # codex-verify-probe\n"
assert original is text
compile(original.replace(search, replace, 1), "module.py", "exec")
empty_search, _empty_replace, empty_text = _verify_probe("")
assert empty_text == "# empty\n"
assert empty_search in empty_text
def test_edit_file_refuses_when_the_file_moved_during_the_run(sample_pkg: Path, monkeypatch) -> None:
session = PythonWorkspaceSession(sample_pkg)
real_run = session._run_six_nodes
def run_with_a_moving_workspace(case: Dict[str, Any]) -> Tuple[Any, ...]:
path = sample_pkg / "src" / "mathops.py"
path.write_text(
path.read_text(encoding="utf-8", newline="").replace(
"return left + right", "return left + right # moved"
),
encoding="utf-8",
newline="",
)
return real_run(case)
monkeypatch.setattr(session, "_run_six_nodes", run_with_a_moving_workspace)
res = session.edit_file(
"src/mathops.py",
"return left + right",
"return int(left) + int(right)",
commit=True,
)
assert res.verdict == "REFUSED"
assert res.reason == "PATCH_NOT_APPLIED"
assert res.committed is False
on_disk = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8")
assert "# moved" in on_disk
assert "int(left)" not in on_disk
def test_create_file_refuses_when_a_file_landed_at_its_path_during_the_run(
sample_pkg: Path, monkeypatch
) -> None:
session = PythonWorkspaceSession(sample_pkg)
real_run = session._run_six_nodes
def run_that_lands_a_file(case: Dict[str, Any]) -> Tuple[Any, ...]:
(sample_pkg / "src" / "landed.py").write_text("VALUE = 1\n", encoding="utf-8", newline="\n")
return real_run(case)
monkeypatch.setattr(session, "_run_six_nodes", run_that_lands_a_file)
res = session.create_file("src/landed.py", "VALUE = 2\n", commit=True)
assert res.verdict == "REFUSED"
assert res.reason == "PATCH_NOT_APPLIED"
assert res.committed is False
assert (sample_pkg / "src" / "landed.py").read_text(encoding="utf-8") == "VALUE = 1\n"
def test_retry_loop_spots_repetition_even_without_a_patch_signature(
sample_pkg: Path, monkeypatch
) -> None:
session = PythonWorkspaceSession(sample_pkg)
def always_unknown(rel_path: str, search: str, replace: str, **kwargs: Any) -> SessionResult:
return SessionResult(
case_id=str(kwargs.get("case_id", "python-edit")),
verdict="UNKNOWN",
assurance=0,
reason="GATE_REJECTED",
detail="",
committed=False,
)
monkeypatch.setattr(session, "edit_file", always_unknown)
def same_proposal(attempt: int, last_result: object) -> tuple:
return ("return left + right", "return left - right")
final, attempts = session.run_retry_loop("src/mathops.py", same_proposal, max_attempts=5)
assert final.verdict == "UNKNOWN"
assert len(attempts) == 2
def test_create_file_refuses_an_escaping_path_before_touching_it(tmp_path: Path) -> None:
"""The path policy answers before the workspace code probes the named path.
Joining the workspace root with an absolute path replaces the root on Windows,
so an exists probe placed before the guard reaches files outside the workspace
and can even name one back in an error.
"""
ws = tmp_path / "ws"
ws.mkdir()
(ws / "value.py").write_text("VALUE = 1\n", encoding="utf-8")
outside = tmp_path / "outside.py"
outside.write_text("VALUE = 1\n", encoding="utf-8", newline="")
session = PythonWorkspaceSession(ws)
res = session.create_file(str(outside), "VALUE = 2\n", commit=True)
assert res.committed is False
assert res.verdict in ("UNKNOWN", "REFUSED")
assert outside.read_text(encoding="utf-8", newline="") == "VALUE = 1\n"
def test_a_commit_refused_by_the_disk_restores_the_file_from_memory(
sample_pkg: Path, monkeypatch
) -> None:
"""A commit that fails mid flight must not leave the run claiming a write it lost."""
session = PythonWorkspaceSession(sample_pkg)
real_os_fs = session._os_fs
class CommitRefusingFs:
def __init__(self, inner: Any) -> None:
self._inner = inner
def __getattr__(self, name: str) -> Any:
return getattr(self._inner, name)
def commit_transaction(self, tx: Any) -> None:
raise FileSystemAdapterError("the disk refused the replace")
def os_fs(root: Path, *, check_allowed: bool = True) -> Any:
fs = real_os_fs(root, check_allowed=check_allowed)
if Path(root).resolve() == sample_pkg.resolve():
return CommitRefusingFs(fs)
return fs
monkeypatch.setattr(session, "_os_fs", os_fs)
before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
res = session.edit_file(
"src/mathops.py",
"return left + right",
"return int(left) + int(right)",
commit=True,
)
after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
assert res.verdict == "REFUSED"
assert res.reason == "PATCH_NOT_APPLIED"
assert res.committed is False
assert "refused the replace" in res.detail
assert before == after
def test_a_delete_refused_by_the_disk_leaves_the_file_in_place(
sample_pkg: Path, monkeypatch
) -> None:
"""A delete goes through the kernel transaction, and committed only says the file is gone."""
session = PythonWorkspaceSession(sample_pkg)
created = session.create_file(
"src/helper.py", '"""Extra module."""\n\nVALUE = 1\n', commit=True
)
assert created.committed is True
real_os_fs = session._os_fs
class DeleteRefusingFs:
def __init__(self, inner: Any) -> None:
self._inner = inner
def __getattr__(self, name: str) -> Any:
return getattr(self._inner, name)
def stage_delete(self, tx: Any, rel_path: str) -> None:
raise FileSystemAdapterError("the disk refused the removal")
def os_fs(root: Path, *, check_allowed: bool = True) -> Any:
fs = real_os_fs(root, check_allowed=check_allowed)
if Path(root).resolve() == sample_pkg.resolve():
return DeleteRefusingFs(fs)
return fs
monkeypatch.setattr(session, "_os_fs", os_fs)
res = session.delete_file("src/helper.py", commit=True)
assert res.verdict == "REFUSED"
assert res.reason == "PATCH_NOT_APPLIED"
assert res.committed is False
helper = sample_pkg / "src" / "helper.py"
assert helper.is_file()
assert helper.read_text(encoding="utf-8", newline="") == '"""Extra module."""\n\nVALUE = 1\n'
def test_a_linked_directory_in_the_workspace_refuses_any_staged_run(
sample_pkg: Path, tmp_path: Path, dir_link
) -> None:
"""A junction or symlink makes the staging copy lie, so the session refuses by name."""
outside = tmp_path / "outside"
outside.mkdir()
(outside / "elsewhere.py").write_text("SECRET = 1\n", encoding="ascii", newline="")
link = sample_pkg / "vendor"
if not dir_link(link, outside):
pytest.skip("this host offers no way to create a directory link")
session = PythonWorkspaceSession(sample_pkg)
res = session.edit_file(
"src/mathops.py",
"return left + right",
"return int(left) + int(right)",
commit=False,
)
assert res.verdict == "REFUSED"
assert res.reason == LINKED_PATH_IN_WORKSPACE
assert "vendor" in res.detail
assert res.committed is False
created = session.create_file("src/newcomer.py", "VALUE = 1\n", commit=True)
assert created.verdict == "REFUSED"
assert created.reason == LINKED_PATH_IN_WORKSPACE
assert created.committed is False
assert not (sample_pkg / "src" / "newcomer.py").exists()
assert (outside / "elsewhere.py").read_text(encoding="utf-8") == "SECRET = 1\n"
def test_the_staging_copy_refuses_a_linked_file_by_name(sample_pkg: Path, tmp_path: Path) -> None:
"""The refusal is not limited to directories: one linked file is enough."""
target = tmp_path / "outside_helper.py"
target.write_text("VALUE = 1\n", encoding="ascii", newline="")
link = sample_pkg / "src" / "linked.py"
try:
os.symlink(str(target), str(link))
except (OSError, NotImplementedError):
pytest.skip("this host does not allow creating a file symlink")
with pytest.raises(WorkspaceLinkError) as caught:
session_module._copy_workspace_for_staging(sample_pkg, tmp_path / "staged")
assert "src/linked.py" in str(caught.value)
def test_a_node_that_exhausts_its_budget_raises_a_named_error(tmp_path: Path) -> None:
"""The subprocess runner turns an exhausted per-node budget into NodeTimeoutError."""
stub = tmp_path / "sleeping_agent.py"
stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")
with pytest.raises(NodeTimeoutError) as caught:
session_module.run_topology_subprocesses(
{"case_id": "budget"}, agent_script=stub, timeout_sec=1.0
)
assert "exhausted its" in str(caught.value)
def test_a_timed_out_node_answers_unknown_instead_of_a_traceback(
sample_pkg: Path, tmp_path: Path, monkeypatch
) -> None:
"""The session reports the budget refusal with a reason, like any other abstain."""
stub = tmp_path / "sleeping_agent.py"
stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")
monkeypatch.setattr(session_module, "DEFAULT_AGENT_SCRIPT", stub)
session = PythonWorkspaceSession(sample_pkg, use_subprocesses=True, node_timeout_sec=1.0)
res = session.verify("src/mathops.py")
assert res.verdict == "UNKNOWN"
assert res.reason == NODE_TIMEOUT
assert res.assurance == 0
assert res.committed is False
def test_a_total_budget_shrinks_the_wait_of_the_first_node(tmp_path: Path) -> None:
"""A node gets the smaller of its own budget and what the total still allows."""
stub = tmp_path / "sleeping_agent.py"
stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="")
with pytest.raises(NodeTimeoutError) as caught:
session_module.run_topology_subprocesses(
{"case_id": "total"}, agent_script=stub, timeout_sec=30.0, total_budget_sec=1.0
)
assert "exhausted its 1.0 s budget" in str(caught.value)
def test_a_spent_total_budget_refuses_a_node_before_starting_it(tmp_path: Path, monkeypatch) -> None:
"""Once the total is gone, the run says so instead of paying for one more node."""
echo = tmp_path / "echo_agent.py"
echo.write_text("import sys\n\nsys.stdout.write(sys.stdin.read())\n", encoding="ascii", newline="")
clock = iter([1000.0, 1000.5, 2000.0])
monkeypatch.setattr(session_module, "_MONOTONIC", lambda: next(clock))
with pytest.raises(NodeTimeoutError) as caught:
session_module.run_topology_subprocesses(
{"case_id": "late"}, agent_script=echo, timeout_sec=10.0, total_budget_sec=5.0
)
assert "total budget" in str(caught.value)
def test_a_nonpositive_budget_is_refused_before_anything_runs(sample_pkg: Path) -> None:
"""A budget of zero seconds is a mistake, not a promise to abstain instantly."""
with pytest.raises(ValueError):
session_module.run_topology_subprocesses({"case_id": "bad"}, timeout_sec=0.0)
with pytest.raises(ValueError):
PythonWorkspaceSession(sample_pkg, total_budget_sec=-1.0)
with pytest.raises(ValueError):
PythonWorkspaceSession(sample_pkg, gate_timeout_sec=0.0)
def test_the_session_hands_its_gate_budget_to_the_environment(
sample_pkg: Path, monkeypatch
) -> None:
"""The kernel builds the adapter from a ref string, so the environment carries the number."""
monkeypatch.delenv(GATE_TIMEOUT_ENV, raising=False)
session = PythonWorkspaceSession(sample_pkg, gate_timeout_sec=2.5)
previous = session._enter_gate_timeout_env()
try:
assert os.environ[GATE_TIMEOUT_ENV] == "2.5"
finally:
session._exit_gate_timeout_env(previous)
assert GATE_TIMEOUT_ENV not in os.environ
def test_a_test_runner_that_outruns_its_gate_budget_abstains(sample_pkg: Path) -> None:
"""A runner that hangs is answered with a named abstain, not an endless wait."""
sleeper = sample_pkg / "tests" / "conftest.py"
sleeper.write_text("import time\n\ntime.sleep(60)\n", encoding="ascii", newline="")
session = PythonWorkspaceSession(sample_pkg, gate_timeout_sec=2.0)
started = time.monotonic()
res = session.verify("src/mathops.py")
elapsed = time.monotonic() - started
assert res.verdict == "UNKNOWN"
assert res.reason == "GATE_ABSTAIN"
assert res.committed is False
# The runner sleeps for a minute; a run that comes back long before it was
# waited out, and abstains instead of passing, was cut by the budget.
assert elapsed < 30.0
assert "abstained" in res.detail
def test_a_junction_created_while_the_gates_run_is_refused_at_commit(
sample_pkg: Path, tmp_path: Path, dir_link
) -> None:
"""The commit re-asks the link question, so a link that appeared mid-run is refused too."""
vendor = tmp_path / "vendor"
vendor.mkdir()
(vendor / "helper.py").write_text("VALUE = 1\n", encoding="ascii", newline="")
if not dir_link(tmp_path / "probe_link", vendor):
pytest.skip("this host offers no way to create a directory link")
link = sample_pkg / "vendor_link"
hook = sample_pkg / "tests" / "conftest.py"
hook.write_text(
"import subprocess\n"
"import sys\n\n"
"VENDOR = %r\n"
"LINK = %r\n\n\n"
"def pytest_configure(config):\n"
" try:\n"
" if sys.platform == 'win32':\n"
" subprocess.run(\n"
" ['cmd', '/c', 'mklink', '/J', LINK, VENDOR],\n"
" stdin=subprocess.DEVNULL,\n"
" stdout=subprocess.DEVNULL,\n"
" stderr=subprocess.DEVNULL,\n"
" )\n"
" else:\n"
" import os\n\n"
" os.symlink(VENDOR, LINK, target_is_directory=True)\n"
" except OSError:\n"
" pass\n" % (str(vendor), str(link)),
encoding="ascii",
newline="",
)
session = PythonWorkspaceSession(sample_pkg)
res = session.edit_file(
"src/mathops.py",
"return left + right",
"return int(left) + int(right)",
commit=True,
)
assert res.verdict == "REFUSED"
assert res.reason == LINKED_PATH_IN_WORKSPACE
assert res.committed is False
assert "before the commit" in res.detail
text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
assert "return left + right" in text
def test_verify_refuses_a_workspace_held_together_by_a_link(
sample_pkg: Path, tmp_path: Path, dir_link
) -> None:
"""verify has no staging copy to refuse for it, so it asks the link question itself."""
outside = tmp_path / "outside"
outside.mkdir()
(outside / "elsewhere.py").write_text("VALUE = 1\n", encoding="ascii", newline="")
link = sample_pkg / "vendor"
if not dir_link(link, outside):
pytest.skip("this host offers no way to create a directory link")
session = PythonWorkspaceSession(sample_pkg)
res = session.verify("src/mathops.py")
assert res.verdict == "REFUSED"
assert res.reason == LINKED_PATH_IN_WORKSPACE
assert res.assurance == 0
assert "vendor" in res.detail
assert res.touched_files == ("vendor",)
def test_a_second_session_on_one_workspace_is_answered_session_locked(
sample_pkg: Path,
) -> None:
"""The lock is an exclusive create, so claiming a held workspace is a refusal, not a queue."""
session = PythonWorkspaceSession(sample_pkg)
lock = sample_pkg / session_module.SESSION_LOCK_NAME
assert not lock.exists()
handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
try:
os.write(handle, str(os.getpid()).encode("ascii"))
finally:
os.close(handle)
res = session.verify("src/mathops.py")
assert res.verdict == "REFUSED"
assert res.reason == session_module.SESSION_LOCKED
assert res.committed is False
assert str(os.getpid()) in res.detail
lock.unlink()
again = session.verify("src/mathops.py")
assert again.verdict == "VERIFIED"
def test_a_locked_edit_refuses_before_reading_anything(sample_pkg: Path) -> None:
"""The refusal precedes the edit machinery: no staging copy, no disk read of the pair."""
session = PythonWorkspaceSession(sample_pkg)
lock = sample_pkg / session_module.SESSION_LOCK_NAME
handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
try:
os.write(handle, str(os.getpid()).encode("ascii"))
finally:
os.close(handle)
res = session.edit_file(
"src/mathops.py", "return left + right", "return left * right", commit=True
)
assert res.verdict == "REFUSED"
assert res.reason == session_module.SESSION_LOCKED
assert res.touched_files == ("src/mathops.py",)
text = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="")
assert "return left + right" in text
lock.unlink()
def test_the_lock_lives_for_exactly_the_length_of_a_run(
sample_pkg: Path, monkeypatch
) -> None:
"""Held while the six nodes judge, gone the moment the run ends, refusal included."""
session = PythonWorkspaceSession(sample_pkg)
lock = sample_pkg / session_module.SESSION_LOCK_NAME
seen = {}
real_pipeline = session_module.run_pipeline
def spy_pipeline(case):
seen["held_mid_run"] = lock.exists()
return real_pipeline(case)
monkeypatch.setattr(session_module, "run_pipeline", spy_pipeline)
res = session.verify("src/mathops.py")
assert res.verdict == "VERIFIED"
assert seen.get("held_mid_run") is True
assert not lock.exists()
def test_a_lock_left_by_a_dead_process_is_taken_over(sample_pkg: Path) -> None:
"""A leftover lock names a process that no longer runs; the takeover is honest, not rude."""
lock = sample_pkg / session_module.SESSION_LOCK_NAME
lock.write_text("99999999\n", encoding="ascii", newline="")
session = PythonWorkspaceSession(sample_pkg)
res = session.verify("src/mathops.py")
assert res.verdict == "VERIFIED"
assert not lock.exists()
def test_a_lock_whose_owner_cannot_be_read_is_never_stolen(sample_pkg: Path) -> None:
"""Unreadable owner means a live holder we cannot name: the refusal stands."""
lock = sample_pkg / session_module.SESSION_LOCK_NAME
lock.write_text("not a pid\n", encoding="ascii", newline="")
session = PythonWorkspaceSession(sample_pkg)
res = session.verify("src/mathops.py")
assert res.verdict == "REFUSED"
assert res.reason == session_module.SESSION_LOCKED
assert "cannot be read" in res.detail
lock.unlink()