Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 193 additions & 0 deletions tests/test_r21_error_semantics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
"""R21 regression tests: JSON failure contract and handoff lease safety.

Red-first: these tests pin the intended contract before the production fix.
Every case uses the isolated tmp_path/home provided by conftest.
"""
from __future__ import annotations

import json
import os
import sqlite3

import pytest

from voyager import cli, continuity
from voyager.model import new_event, new_session
from voyager.store import Store


def _seed_thread(db, holder_thread: bool = True):
src = db.parent / ("session-%s.jsonl" % os.getpid())
src.write_text("{}\n", encoding="utf-8")
sid = "codex:r21-test-%s" % os.getpid()
now = 1_764_400_000.0
session = new_session(
id=sid, provider="codex", native_session_id="r21-test",
title="R21 contract fixture", started_at=now, updated_at=now + 60,
cwd=str(db.parent), repo_root=str(db.parent), message_count=1,
can_resume=True, resume_cmd="codex resume r21-test")
events = [new_event(sid=sid, ts=now, seq=1, kind="user", role="user",
content="synthetic contract fixture", origin="human")]
store = Store(db)
store.replace_session(session, events, "codex", src)
tid = store.thread_create(repo_root=str(db.parent), title="R21 thread")
store.thread_attach(tid, sid)
store.close()
return tid, sid


def _json_stdout(capsys):
out = capsys.readouterr()
return json.loads(out.out), out


def test_cli_json_continue_missing_thread_is_machine_readable(tmp_path, capsys):
db = tmp_path / "index.db"
Store(db).close()
rc = cli.main(["--db", str(db), "continue", "--json", "--thread",
"does-not-exist", "--no-launch"])
payload, streams = _json_stdout(capsys)
assert rc == 1
assert payload["ok"] is False
assert payload["error_code"] == "THREAD_NOT_FOUND"
assert "does-not-exist" in payload["error"]
assert streams.err == ""


def test_cli_json_show_missing_session_is_machine_readable(tmp_path, capsys):
db = tmp_path / "index.db"
Store(db).close()
# The process exit code is still carried by SystemExit; cli.main() must
# not swallow it, because non-CLI callers rely on that contract.
with pytest.raises(SystemExit) as exc:
cli.main(["--db", str(db), "show", "--json", "missing-session"])
rc = exc.value.code
payload, streams = _json_stdout(capsys)
assert rc == 2
assert payload["ok"] is False
assert payload["error_code"] == "SESSION_NOT_FOUND"
assert streams.err == ""


def test_cli_json_reports_readonly_database_without_traceback(
monkeypatch, tmp_path, capsys):
class ReadOnlyStore:
def __init__(self, *a, **kw):
raise sqlite3.OperationalError("attempt to write a readonly database")

monkeypatch.setattr(cli, "Store", ReadOnlyStore)
rc = cli.main(["--db", str(tmp_path / "index.db"), "continue", "--json",
"--thread", "t", "--no-launch"])
payload, streams = _json_stdout(capsys)
assert rc == 1
assert payload["ok"] is False
assert payload["error_code"] == "DB_READ_ONLY"
assert "Traceback" not in streams.err


def test_cli_json_reports_locked_database_without_traceback(
monkeypatch, tmp_path, capsys):
class LockedStore:
def __init__(self, *a, **kw):
raise sqlite3.OperationalError("database is locked")

monkeypatch.setattr(cli, "Store", LockedStore)
rc = cli.main(["--db", str(tmp_path / "index.db"), "continue", "--json",
"--thread", "t", "--no-launch"])
payload, streams = _json_stdout(capsys)
assert rc == 1
assert payload["ok"] is False
assert payload["error_code"] == "DB_LOCKED"
assert "Traceback" not in streams.err


def test_live_same_holder_lease_is_refused_without_steal(tmp_path):
db = tmp_path / "index.db"
tid, _sid = _seed_thread(db)
store = Store(db)
try:
first, first_row = store.thread_lease_acquire(
tid, "claude", pid=os.getpid())
second, second_row = store.thread_lease_acquire(
tid, "claude", pid=os.getpid())
assert first is True
assert first_row["lease_token"]
assert second is False, "concurrent same-holder re-acquire must refuse"
assert second_row["lease_token"] == first_row["lease_token"]
finally:
store.close()


def test_explicit_steal_still_transfers_same_holder_lease(tmp_path):
db = tmp_path / "index.db"
tid, _sid = _seed_thread(db)
store = Store(db)
try:
first, first_row = store.thread_lease_acquire(
tid, "claude", pid=os.getpid())
stolen, stolen_row = store.thread_lease_acquire(
tid, "claude", pid=os.getpid(), steal=True)
assert first is True
assert stolen is True
assert stolen_row["lease_token"] != first_row["lease_token"]
finally:
store.close()


def test_lease_acquire_lock_failure_does_not_crash_handoff(
monkeypatch, tmp_path):
db = tmp_path / "index.db"
tid, sid = _seed_thread(db)
store = Store(db)
real = store.thread_lease_acquire

def locked(*args, **kwargs):
return False, None

monkeypatch.setattr(store, "thread_lease_acquire", locked)
try:
res = continuity.handoff_thread(
store=store, thread=tid, target="claude", style="package",
output=str(tmp_path / "bundle.md"))
assert res["error_code"] == "DB_LOCKED"
assert res["action"] in ("error", "refused")
finally:
monkeypatch.setattr(store, "thread_lease_acquire", real)
store.close()


def test_cli_json_refused_lease_has_nonzero_exit(tmp_path, capsys):
db = tmp_path / "index.db"
tid, _sid = _seed_thread(db)
holder = Store(db)
ok, row = holder.thread_lease_acquire(tid, "claude", pid=os.getpid())
assert ok is True
holder.close()

rc = cli.main(["--db", str(db), "continue", "--json", "--thread", tid,
"--to", "claude", "--no-launch",
"-o", str(tmp_path / "bundle.md")])
payload, streams = _json_stdout(capsys)
assert rc == 1
assert payload["ok"] is False
assert payload["error_code"] == "LEASE_HELD"
assert streams.err == ""


def test_switch_json_flag_is_accepted(tmp_path, capsys):
db = tmp_path / "index.db"
Store(db).close()
rc = cli.main(["--db", str(db), "switch", "claude", "--json", "--thread",
"does-not-exist", "--no-launch"])
payload, _streams = _json_stdout(capsys)
assert rc == 1
assert payload["ok"] is False
assert payload["error_code"] == "THREAD_NOT_FOUND"


@pytest.mark.parametrize("target", ["claude"])
def test_json_error_keeps_legacy_error_string(target):
"""A machine code is additive; the old string `error` stays a string."""
payload = cli._json_error_payload("THREAD_NOT_FOUND", "thread not found: " + target)
assert payload["error"] == "thread not found: " + target
assert isinstance(payload["error"], str)
Loading
Loading