From c23c9b0c312b84f4cc53c21d5895b7c96ac53380 Mon Sep 17 00:00:00 2001 From: HarryHe <2496583567@qq.com> Date: Tue, 1 Dec 2026 13:25:34 +0800 Subject: [PATCH] fix: harden CLI error semantics and WorkThread leases --- tests/test_r21_error_semantics.py | 193 +++++++++++++++++++++++++ voyager/cli.py | 230 +++++++++++++++++++++++++----- voyager/continuity.py | 20 ++- voyager/store.py | 21 +-- 4 files changed, 418 insertions(+), 46 deletions(-) create mode 100644 tests/test_r21_error_semantics.py diff --git a/tests/test_r21_error_semantics.py b/tests/test_r21_error_semantics.py new file mode 100644 index 0000000..36b927e --- /dev/null +++ b/tests/test_r21_error_semantics.py @@ -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) diff --git a/voyager/cli.py b/voyager/cli.py index dfeb1a7..01bcadf 100644 --- a/voyager/cli.py +++ b/voyager/cli.py @@ -6,6 +6,7 @@ import json import os import shutil +import sqlite3 import subprocess import sys from pathlib import Path @@ -54,6 +55,25 @@ def _expand_path_args(args) -> None: setattr(args, name, os.path.expanduser(value)) +def _json_error_payload(code: str, message: str, details=None) -> dict: + """The R21 CLI failure envelope. + + ``error`` deliberately stays a string: ``thread timeline --json`` and the + bridge already expose that field, and clients read it as text. ``ok``, + ``error_code`` and ``details`` are additive machine-readable fields. We do + not add ``ok`` to successful responses, so success shapes are untouched. + """ + payload = {"ok": False, "error": str(message), "error_code": code} + if details: + payload["details"] = details + return payload + + +def _emit_json_error(code: str, message: str, details=None) -> None: + print(json.dumps(_json_error_payload(code, message, details), + ensure_ascii=False, indent=2, default=str)) + + def _spawn_argv(argv): """Return `argv` with `argv[0]` replaced by the path it resolves to. @@ -328,9 +348,17 @@ def _repo_match(row, pattern: str) -> bool: return False -def _resolve(store: Store, ref: str): +def _resolve(store: Store, ref: str, *, json_mode: bool = False): row, ambiguous = store.session(ref) if row is None and ambiguous: + if json_mode: + _emit_json_error( + "AMBIGUOUS_SESSION", + "'{0}' matches {1} sessions — use a longer prefix".format( + ref, len(ambiguous)), + {"ref": ref, + "candidates": [r["native_id"] for r in ambiguous[:10]]}) + raise SystemExit(2) print(f"error: '{ref}' matches {len(ambiguous)} sessions:", file=sys.stderr) for r in ambiguous[:10]: print(f" [{r['provider']}] {r['native_id']} {(r['title'] or '')[:60]}", @@ -338,6 +366,11 @@ def _resolve(store: Store, ref: str): print("use a longer prefix", file=sys.stderr) sys.exit(2) if row is None: + if json_mode: + _emit_json_error("SESSION_NOT_FOUND", + "session not found: {0}".format(ref), + {"ref": ref}) + raise SystemExit(2) print(f"error: session not found: {ref}", file=sys.stderr) sys.exit(2) return row @@ -345,7 +378,7 @@ def _resolve(store: Store, ref: str): def cmd_show(args) -> int: store = open_read(args.db) - row = _resolve(store, args.session) + row = _resolve(store, args.session, json_mode=args.json) events = store.events(row["id"]) if args.json: import json as j @@ -429,7 +462,11 @@ def cmd_search(args) -> int: rows = store.search(args.query, limit=args.limit, filters=_search_filters(args)) except Exception as e: - print(f"search error: {e}", file=sys.stderr) + if args.json: + _emit_json_error("SEARCH_FAILED", "search error: {0}".format(e), + {"query": args.query}) + else: + print(f"search error: {e}", file=sys.stderr) return 2 if args.json: print(json.dumps([dict(r) for r in rows], ensure_ascii=False, indent=2, default=str)) @@ -919,8 +956,12 @@ def cmd_preview(args) -> int: target=getattr(args, "to", None), ) if not isinstance(out, dict) or out.get("error"): - print(out.get("error") if isinstance(out, dict) else "preview failed", - file=sys.stderr) + message = out.get("error") if isinstance(out, dict) else "preview failed" + if args.json: + _emit_json_error("PREVIEW_FAILED", message, + {"thread_requested": getattr(args, "thread", None)}) + else: + print(message, file=sys.stderr) return 2 # `continue_context` deliberately keeps its response shape stable: it @@ -1142,14 +1183,20 @@ def _continue_thread(store: Store, t, args) -> int: members = store.live_thread_members(t["id"]) retained = len(all_members) - len(members) if not members: - print("thread " + t["id"] + " has no live member sessions" - + (" ({0} retained: every source vanished)".format(retained) - if retained else ""), file=sys.stderr) + message = ("thread " + t["id"] + " has no live member sessions" + + (" ({0} retained: every source vanished)".format(retained) + if retained else "")) + if getattr(args, "json", False): + _emit_json_error("NO_LIVE_MEMBERS", message, + {"thread_id": t["id"], "retained": retained}) + else: + print(message, file=sys.stderr) store.close() return 1 - print("thread {0} [{1}] {2} member(s){3}".format( - t["id"], t["status"], len(members), - ", {0} retained".format(retained) if retained else "")) + if not getattr(args, "json", False): + print("thread {0} [{1}] {2} member(s){3}".format( + t["id"], t["status"], len(members), + ", {0} retained".format(retained) if retained else "")) target = getattr(args, "to", None) if not target: resumable = [m for m in members if m["can_resume"] and m["resume_cmd"]] @@ -1158,8 +1205,9 @@ def _continue_thread(store: Store, t, args) -> int: key=lambda x: x["updated_at"] or 0)["provider"] else: target = "claude" - print("no natively-resumable member — compiling continuation " - "bundle for claude (override with --to)") + if not getattr(args, "json", False): + print("no natively-resumable member — compiling continuation " + "bundle for claude (override with --to)") return _handoff_via_engine(store, args, "continue", thread=t, target=target) @@ -1208,7 +1256,14 @@ def cmd_continue(args) -> int: if getattr(args, "thread", None): t = store.thread_get(args.thread) if not t: - print("thread not found: " + args.thread, file=sys.stderr) + if args.json: + _emit_json_error("THREAD_NOT_FOUND", + "thread not found: " + args.thread, + {"thread_requested": args.thread}) + else: + print("thread not found: " + args.thread, file=sys.stderr) + print(" run `voyager thread list` to see available WorkThreads", + file=sys.stderr) store.close() return 1 elif not args.session and not getattr(args, "from_sessions", None): @@ -1221,11 +1276,19 @@ def cmd_continue(args) -> int: resolved = resolve_work_thread(store, repo=repo, repo_strict=repo_ref is None) if resolved["status"] == "ambiguous": - _print_thread_ambiguity(repo, resolved) + if args.json: + _emit_json_error( + "AMBIGUOUS_THREAD", + "{0} active WorkThreads for this repo — refusing to guess".format( + len(resolved["candidates"])), + {"repo": repo, + "candidates": [c["id"] for c in resolved["candidates"]]}) + else: + _print_thread_ambiguity(repo, resolved) store.close() return 2 t = resolved["thread"] - if t is not None: + if t is not None and not args.json: print("active thread: {0} ({1})".format( t["id"], (t["title"] or "")[:70])) if t is not None: @@ -1236,19 +1299,24 @@ def cmd_continue(args) -> int: if from_sessions: refs = [s.strip() for s in from_sessions.split(",") if s.strip()] if not refs: - print("error: --from requires at least one session id", file=sys.stderr) + if args.json: + _emit_json_error("BAD_ARGUMENT", + "--from requires at least one session id") + else: + print("error: --from requires at least one session id", file=sys.stderr) store.close() return 2 - rows = [_resolve(store, ref) for ref in refs] + rows = [_resolve(store, ref, json_mode=args.json) for ref in refs] target = getattr(args, "to", None) if not target: target = "claude" - print("defaulting continuation target to 'claude' (override with --to)") + if not args.json: + print("defaulting continuation target to 'claude' (override with --to)") return _handoff_via_engine(store, args, "continue", sessions=rows, target=target) if args.session: - row = _resolve(store, args.session) + row = _resolve(store, args.session, json_mode=args.json) else: rows = store.sessions() if args.repo: @@ -1257,12 +1325,18 @@ def cmd_continue(args) -> int: rows = [r for r in rows if r["provider"] == args.platform] rows = [r for r in rows if r["updated_at"]] if not rows: - print("no sessions to continue (run `voyager scan` first)") + message = "no sessions to continue (run `voyager scan` first)" + if args.json: + _emit_json_error("NO_SESSIONS", message, + {"repo": getattr(args, "repo", None)}) + else: + print(message) store.close() return 1 row = rows[0] - print(f"latest session: [{row['provider']}] {(row['title'] or '')[:70]} " - f"({_short_ts(row['updated_at'])})") + if not args.json: + print(f"latest session: [{row['provider']}] {(row['title'] or '')[:70]} " + f"({_short_ts(row['updated_at'])})") target = getattr(args, "to", None) if not target: @@ -1271,8 +1345,9 @@ def cmd_continue(args) -> int: else: # native resume unsupported (e.g. ZCode): hand off instead target = "claude" - print(f"native resume unsupported for '{row['provider']}' — " - f"falling back to cross-agent handoff") + if not args.json: + print(f"native resume unsupported for '{row['provider']}' — " + f"falling back to cross-agent handoff") return _handoff_via_engine(store, args, "continue", source=row, target=target) @@ -1450,6 +1525,23 @@ def _ready(key: str) -> str: return rc +def _handoff_error_code(res: dict) -> str: + if res.get("error_code"): + return res["error_code"] + message = str(res.get("error") or "").lower() + if "leased to" in message: + return "LEASE_HELD" + if "budget" in message: + return "BAD_ARGUMENT" + if "cannot write bundle" in message or "cannot create bundle" in message: + return "BUNDLE_WRITE_FAILED" + if "thread not found" in message: + return "THREAD_NOT_FOUND" + if "session not found" in message: + return "SESSION_NOT_FOUND" + return "HANDOFF_FAILED" + + def _handoff_via_engine(store: Store, args, kind: str, style: Optional[str] = None, *, extra: Optional[dict] = None, **source) -> int: @@ -1501,9 +1593,19 @@ def _handoff_via_engine(store: Store, args, kind: str, payload["context"] = Path(ctx_path).read_text(encoding="utf-8") except Exception: pass + if res.get("action") in ("error", "invalid", "refused"): + envelope = _json_error_payload( + _handoff_error_code(res), + res.get("error") or "handoff failed", + {"action": res.get("action"), + "thread_id": res.get("thread_id"), + "target": res.get("target")}) + payload.update(envelope) store.close() print(json.dumps(payload, ensure_ascii=False, indent=2, default=str)) code = res.get("exit_code") + if code is None and res.get("action") in ("error", "invalid", "refused"): + code = 1 return int(code) if code is not None else 0 store.close() return _render_handoff(store, res, args, kind) @@ -1522,8 +1624,12 @@ def cmd_switch(args) -> int: target = args.agent from .continuity import PROMPT_TARGETS if target not in PROMPT_TARGETS: - print("error: switch target must be one of {0} (got '{1}')".format( - ", ".join(sorted(PROMPT_TARGETS)), target), file=sys.stderr) + message = "switch target must be one of {0} (got '{1}')".format( + ", ".join(sorted(PROMPT_TARGETS)), target) + if getattr(args, "json", False): + _emit_json_error("BAD_ARGUMENT", message, {"target": target}) + else: + print("error: " + message, file=sys.stderr) store.close() return 2 @@ -1531,7 +1637,14 @@ def cmd_switch(args) -> int: if getattr(args, "thread", None): t = store.thread_get(args.thread) if not t: - print("thread not found: " + args.thread, file=sys.stderr) + if getattr(args, "json", False): + _emit_json_error("THREAD_NOT_FOUND", + "thread not found: " + args.thread, + {"thread_requested": args.thread}) + else: + print("thread not found: " + args.thread, file=sys.stderr) + print(" run `voyager thread list` to see available WorkThreads", + file=sys.stderr) store.close() return 1 else: @@ -1542,22 +1655,35 @@ def cmd_switch(args) -> int: resolved = resolve_work_thread(store, repo=repo, repo_strict=repo_ref is None) if resolved["status"] == "no_thread": - print("error: no active WorkThread for this repo ({0}).".format(repo)) - print("Create one: voyager thread create --repo {0} --attach ".format(repo)) - print("Or continue without switching: voyager continue") + message = "no active WorkThread for this repo ({0}).".format(repo) + if getattr(args, "json", False): + _emit_json_error("NO_THREAD", message, {"repo": repo}) + else: + print("error: " + message) + print("Create one: voyager thread create --repo {0} --attach ".format(repo)) + print("Or continue without switching: voyager continue") store.close() return 1 if resolved["status"] == "ambiguous": # A handoff writes a package and takes a lease, so the wrong thread # is not a cosmetic mistake. Refuse, and print every candidate. - _print_thread_ambiguity(repo, resolved) + if getattr(args, "json", False): + _emit_json_error( + "AMBIGUOUS_THREAD", + "{0} active WorkThreads for this repo — refusing to guess".format( + len(resolved["candidates"])), + {"repo": repo, + "candidates": [c["id"] for c in resolved["candidates"]]}) + else: + _print_thread_ambiguity(repo, resolved) store.close() return 2 # `t` used to be leaked from a comprehension here, so `voyager switch # ` without --thread raised UnboundLocalError before that was # fixed. Now the resolver is the only thing that picks. t = resolved["thread"] - print("active thread: {0} ({1})".format(t["id"], (t["title"] or "")[:70])) + if not getattr(args, "json", False): + print("active thread: {0} ({1})".format(t["id"], (t["title"] or "")[:70])) return _handoff_via_engine(store, args, "switch", thread=t, target=target) @@ -1625,7 +1751,7 @@ def cmd_merge(args) -> int: print("error: at least one session id required", file=sys.stderr) store.close() return 2 - rows = [_resolve(store, ref) for ref in session_refs] + rows = [_resolve(store, ref, json_mode=args.json) for ref in session_refs] # The WorkThread comes first, so the engine can lease it and record the # pending attach: a merged handoff is then exactly as safe as a `switch`. @@ -2326,6 +2452,8 @@ def main(argv=None) -> int: "native session id under the lease)") sp.add_argument("--no-launch", action="store_true", help="print what would be launched instead of launching") + sp.add_argument("--json", action="store_true", + help="machine-readable result, including the compiled context") sp.add_argument("--output", "-o", help="bundle file path (when compiling a continuation)") sp.add_argument("--bundles-dir", @@ -2716,9 +2844,37 @@ def _cmd_demo(args) -> int: # the store lands here instead of a traceback (#34). The corrupt # file is not modified and is not removed here -- recovery is # `db check` / a backup restore, by hand. - print("error: {0}".format(e), file=sys.stderr) - print(" run `voyager db check` for details and restore from a" - " backup (`voyager db backup`).", file=sys.stderr) + if getattr(args, "json", False): + _emit_json_error("DB_UNREADABLE", str(e), + {"suggested_action": "db check; restore from backup"}) + else: + print("error: {0}".format(e), file=sys.stderr) + print(" run `voyager db check` for details and restore from a" + " backup (`voyager db backup`).", file=sys.stderr) + return 1 + except sqlite3.OperationalError as e: + # R21: a locked or read-only index is an expected operating condition, + # not a programmer error. A bare OperationalError used to reach the + # console as a traceback on ordinary `continue` commands. + text = str(e).lower() + if "readonly" in text or "read-only" in text: + code = "DB_READ_ONLY" + message = ("index database is read-only; restore write permission " + "or use a writable --db path") + elif "locked" in text or "busy" in text: + code = "DB_LOCKED" + message = ("index database is busy because another sessionFlow " + "operation is using it; retry shortly") + else: + code = "DB_ERROR" + message = "index database operation failed: {0}".format(e) + if getattr(args, "json", False): + _emit_json_error(code, message, {"sqlite_error": str(e)}) + else: + print("error: " + message, file=sys.stderr) + if code == "DB_LOCKED": + print(" no state was changed; wait for the other operation " + "to finish, then retry.", file=sys.stderr) return 1 diff --git a/voyager/continuity.py b/voyager/continuity.py index cf3b7bb..ed6fe63 100644 --- a/voyager/continuity.py +++ b/voyager/continuity.py @@ -1519,7 +1519,8 @@ def handoff_thread( "target": target, "lease_token": None, "lease_holder": None, "bundle_path": None, "context_path": None, "context_chars": None, "pending_recorded": False, "warnings": [], "error": None, - "exit_code": None, "scope": src.get("scope"), "style": style, + "error_code": None, "exit_code": None, + "scope": src.get("scope"), "style": style, "source_provider": src.get("source_provider"), "source_session": src.get("source_session"), "member_count": len(src.get("members") or []), @@ -1528,6 +1529,7 @@ def handoff_thread( if src.get("error"): res["action"] = "error" res["error"] = src["error"] + res["error_code"] = "INVALID_REFERENCE" res["exit_code"] = 2 return res @@ -1545,8 +1547,10 @@ def handoff_thread( res["error"] = ("thread has no live member sessions" + (" (all {0} member(s) retained: every source " "vanished)".format(len(held)) if held else "")) + res["error_code"] = "NO_LIVE_MEMBERS" else: res["error"] = "no source session to hand off" + res["error_code"] = "NO_SOURCE_SESSION" return res # -- git dirty warning (never stash/reset; computed once, always) ------ @@ -1562,7 +1566,18 @@ def handoff_thread( if tid and target: ok, lease = store.thread_lease_acquire(tid, target, steal=steal) if not ok: + db_locked = isinstance(lease, dict) and bool(lease.get("db_locked")) + if not lease or db_locked: + # BEGIN IMMEDIATE could not be taken. This is a transient + # database condition, not a lease conflict; it used to be + # a raw TypeError from `lease["holder"]` (R21/D5). + res["action"] = "error" + res["error_code"] = "DB_LOCKED" + res["error"] = "index database is busy; retry shortly" + res["exit_code"] = 1 + return res res["action"] = "refused" + res["error_code"] = "LEASE_HELD" res["error"] = ("thread {0} is leased to {1} pid={2}, " "heartbeat {3:.0f}s ago".format( tid, lease["holder"], lease["pid"], @@ -1631,6 +1646,7 @@ def release_lease(reason: str) -> None: if tid and lease_token: store.thread_lease_release(tid, lease_token, reason="invalid-budget") res["action"] = "invalid" + res["error_code"] = "BAD_ARGUMENT" res["error"] = str(e) res["exit_code"] = 2 return res @@ -1671,6 +1687,7 @@ def release_lease(reason: str) -> None: except OSError as e: release_lease("bundle-dir-failed") res["action"] = "error" + res["error_code"] = "BUNDLE_WRITE_FAILED" res["error"] = "cannot create bundle directory {0}: {1}".format( out.parent, e.strerror or e) res["exit_code"] = 2 @@ -1680,6 +1697,7 @@ def release_lease(reason: str) -> None: except OSError as e: release_lease("bundle-write-failed") res["action"] = "error" + res["error_code"] = "BUNDLE_WRITE_FAILED" res["error"] = "cannot write bundle {0}: {1}".format( out, e.strerror or e) res["exit_code"] = 2 diff --git a/voyager/store.py b/voyager/store.py index 420d0e5..17320ae 100644 --- a/voyager/store.py +++ b/voyager/store.py @@ -1206,8 +1206,11 @@ def thread_lease_acquire(self, tid: str, holder: str, try: self.con.execute("BEGIN IMMEDIATE") except sqlite3.OperationalError: - # could not take the write lock at all: refuse, never race - return False, self.thread_lease_get(tid) + # Could not take the write lock at all: refuse, never race. A + # sentinel (rather than None) keeps the caller from dereferencing + # a missing blocker row and lets it report DB_LOCKED precisely. + return False, {"holder": None, "pid": None, "heartbeat_at": None, + "lease_token": None, "db_locked": True} try: now = _time.time() row = self.thread_lease_get(tid) @@ -1215,12 +1218,14 @@ def thread_lease_acquire(self, tid: str, holder: str, event = ("acquire" if row is None else "steal" if steal else "takeover-expired") if st["held"] and not st["expired"] and not steal: - if row["holder"] == holder: - # same provider re-acquiring its own lease = transfer - event = "transfer" - else: - self.con.execute("COMMIT") - return False, row + # One live writer per WorkThread, including two concurrent + # requests from the same holder/provider. A sequential + # same-provider native-resume transfer still opts in with + # steal=True; an implicit transfer here let two subprocesses + # both report success and silently replaced each other's + # pending attach (R21/I1-I3). + self.con.execute("COMMIT") + return False, row token = _uuid.uuid4().hex self.con.execute( """INSERT OR REPLACE INTO thread_leases(