From b1100e57d6fa592096e01077a5b8a30650fae9a6 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 28 Nov 2026 12:47:52 +0000 Subject: [PATCH 1/2] fix(novelty): a budget stop that kept its partial result exits 3 (#632) `skill novelty atoms`, `probe`, `analyze`, `skill routing` and `catalog routing` stopped by `--max-usd` or a call with no price kept their partial file and exited 1 through `SystemExit()`, while the exit-code table in docs/quickstart.md gives 3 to a run that stopped short on a budget and kept its partial output, as `tools preference` does. `partial_exit_code(reason)` in `novelty_routing_report.py` is now the one rule: `spend_cap` and `no_price` exit 3, `permanent_error` (a runtime failure) and any other reason exit 1. `exit_partial` takes the stop's reason and `stop_if_partial` reads it from the partial block; both print the same message to stderr and raise `PartialStop`, a `SystemExit` whose `code` is the int and whose `str()` is the message, so the existing message checks hold. `RoutingStopped` carries that code too, and `cli.main` prints no second document for `skill routing --json`. `exit_partial_all_vs_all` (failed model calls) and the stops that keep nothing stay exit 1. The tests that pin these stops also assert the code, and new ones cover the rule, a permanent-error stop, `skill routing --json` and a stop through `cli.main`. quickstart.md, skill-novelty.md and the walkthrough name the new exit, and the walkthrough no longer says `analyze` keeps nothing. Signed-off-by: Anton Volkov --- .../20261128_140000_partial-stop-exit-3.md | 3 + dokimi/docs/quickstart.md | 9 +- dokimi/docs/skill-novelty-walkthrough.md | 10 +- dokimi/docs/skill-novelty.md | 8 +- dokimi/dokimi/commands/novelty_budget.py | 15 +-- dokimi/dokimi/commands/novelty_routing.py | 7 +- .../dokimi/commands/novelty_routing_report.py | 37 +++++-- .../tests/test_novelty_analyze_cap_partial.py | 15 ++- dokimi/tests/test_novelty_cap_partial.py | 17 +++- .../tests/test_novelty_partial_exit_code.py | 81 ++++++++++++++++ .../tests/test_novelty_routing_all_vs_all.py | 15 ++- .../test_novelty_routing_repeat_failures.py | 7 +- .../test_novelty_routing_spend_cap_partial.py | 96 +++++++++++++++---- dokimi/tests/test_novelty_spend_cap.py | 3 +- dokimi/tests/test_report_summary.py | 2 +- 15 files changed, 261 insertions(+), 64 deletions(-) create mode 100644 dokimi/changelog.d/20261128_140000_partial-stop-exit-3.md create mode 100644 dokimi/tests/test_novelty_partial_exit_code.py diff --git a/dokimi/changelog.d/20261128_140000_partial-stop-exit-3.md b/dokimi/changelog.d/20261128_140000_partial-stop-exit-3.md new file mode 100644 index 0000000000..16b2313fc9 --- /dev/null +++ b/dokimi/changelog.d/20261128_140000_partial-stop-exit-3.md @@ -0,0 +1,3 @@ +### Changed + +- **`skill novelty atoms`, `probe`, `analyze`, `skill routing` and `catalog routing` exit 3, not 1, when `--max-usd` or a call with no price stops them and they keep the partial file** — the exit-code table in `docs/quickstart.md` gives 3 to a run that stopped short on a budget and kept its partial output, as `tools preference` does, but these commands exited 1. The message on stderr is the same. A stop on a permanent provider error (`"reason": "permanent_error"`) is a runtime failure and still exits 1, as does a run that kept nothing (`skill shorten`) or an all-vs-all run where model calls failed. A script that read exit 1 as "stopped by the budget" now sees 3. diff --git a/dokimi/docs/quickstart.md b/dokimi/docs/quickstart.md index 7a807ffc0c..a85715a5d4 100644 --- a/dokimi/docs/quickstart.md +++ b/dokimi/docs/quickstart.md @@ -260,7 +260,7 @@ failed check. | 0 | The command ran and, if it checks something, the check passed. | | | 1 | A verdict or a gate that ran and failed, or a runtime failure the command reports (a model call, a run, a clone or fetch); a crash that escapes is 5. `eval judge validate --strict` and `eval leak`/`eval redteam` that fail as blocked. | `baseline compare --max-context-drop 0` over a regression, `repo reach` with a harness binary that cannot run, `eval triggers generate --fail-on warn` over a lint finding | | 2 | A bad invocation: a missing, unreadable or malformed input file, a configuration the agent's CLI rejects (`repo run --tools all` with a `.mcp.json` the CLI does not accept: refused before any cell runs), a device given as one (` : not a file`), a flag combination the command refuses, an output file that cannot be written, a missing provider credential, a source string that is malformed, unpinned or not a repository root. | `baseline save` on a bad eval file, `evaluate --custom-questions` on an empty or non-JSON file (`--custom-questions : `), `benchmark preflight` with no golden set, `repo scan --manifest ../x.yaml` | -| 3 | Inconclusive: the run stopped short because a budget ran out (`--max-usd`, or a call with no price) and kept the partial output (`tools preference` today; `eval personas discover` refuses its one call before it runs, so nothing is written; other spend-capped commands such as `repo run`, `repo hits judge` and `skill routing` still exit 1 on a budget stop), or the result is undecided (`eval judge validate`: a pass whose interval straddles the gate, or a variant no pair was built for, with `--strict` making it 1; `eval leak`: an item that could not be checked, or none could; `eval redteam`: a graded question not measured, or nothing graded; `eval judge agreement --strict`: an arm NOT MEASURED, or no arm to compare; `repo security --fail-on`: an unfinished cell or an arm with no measured cell, when no arm failed and every model has a baseline cell). | `tools preference --max-usd 5` with calls not run; `eval judge validate` with too few bases | +| 3 | Inconclusive: the run stopped short because a budget ran out (`--max-usd`, or a call with no price) and kept the partial output (`tools preference`, `skill novelty atoms`, `probe` and `analyze`, `skill routing` and `catalog routing`; a stop on a permanent provider error exits 1; `eval personas discover` refuses its one call before it runs, so nothing is written; other spend-capped commands such as `repo run` and `repo hits judge` still exit 1 on a budget stop), or the result is undecided (`eval judge validate`: a pass whose interval straddles the gate, or a variant no pair was built for, with `--strict` making it 1; `eval leak`: an item that could not be checked, or none could; `eval redteam`: a graded question not measured, or nothing graded; `eval judge agreement --strict`: an arm NOT MEASURED, or no arm to compare; `repo security --fail-on`: an unfinished cell or an arm with no measured cell, when no arm failed and every model has a baseline cell). | `tools preference --max-usd 5` with calls not run; `eval judge validate` with too few bases | | 4 | Invalid: the result is not comparable or not trustworthy: a model that differs from the baseline's, or one that cannot be verified, under `baseline compare --strict` or the regression gate (`--max-context-drop` or `--max-lift-drop`); under `repo security --fail-on`, a model with no baseline cell when no arm failed; under `eval judge agreement --strict`, an arm JUDGE-DEPENDENT. | `baseline compare --strict` over a baseline scored with another judge | | 5 | Infrastructure failure: a crash (an uncaught exception) in any command, with its traceback on stderr. For a command that emits the cli_output document, `--json` prints its `infra` document on stdout first. Also a `repo run` cell that crashes (a harness that exits nonzero before its first trace line, unless the cap killed it, a docker daemon or CLI failure that stops the agent, a scratch directory that vanished): the batch keeps the other cells and exits 5. | `backends --json` when `detect` raises; `repo run` with the docker daemon down | @@ -272,8 +272,11 @@ a `.mcp.json` the CLI rejects under `--tools all` is exit 2 before any cell; a `--manifest` path that leaves the source tree as typed is exit 2, pinned or not, as a source refusal; a link in the tree that leads out of it is exit 1), and `tools preference` exits 1 when every call failed and 3 when `--max-usd` or an unpriced model stopped it short, and `eval personas discover` exits 3 when its `--max-usd` refuses the one call. `repo run --max-usd`, -`repo hits judge --max-usd` and the novelty commands' `--max-usd` still exit 1 -when the budget or an unpriced call stops them (`catalog novelty` too, once it has written +`repo hits judge --max-usd` still exit 1 when the budget or an unpriced call stops them. +`skill novelty atoms`, `probe` and `analyze` and `skill routing` and `catalog routing` exit 3 when +the budget or an unpriced call stops them and they keep a partial file, and 1 when they keep +nothing (`skill shorten`, and a stop that leaves no partial file: "nothing was written") or a permanent provider error +stopped them (`catalog novelty` exits 1 too, once it has written its rows, when any skill it took on is `partial`, `error` or not run). `eval judge agreement --judges` and `eval score pairwise` exit 1, not 2, when every judge call fails, a missing provider credential included. diff --git a/dokimi/docs/skill-novelty-walkthrough.md b/dokimi/docs/skill-novelty-walkthrough.md index d0ff8b7ef1..e972bfb4cb 100644 --- a/dokimi/docs/skill-novelty-walkthrough.md +++ b/dokimi/docs/skill-novelty-walkthrough.md @@ -100,13 +100,15 @@ What a stopped run leaves behind depends on the step: refused after it came back keeps the verdict it names; one that names none is kept as `error` too. If the cap stops it while the paraphrase or reversal wordings are built, nothing is written. -- Each exits with a message that names the partial file. A partial file is never read as a +- Each exits 3 (1 when a permanent provider error stopped it) with a message that names the partial file. A partial file is never read as a finished one: the atom readers and `novelty items` refuse it. A later stopped run replaces an earlier partial file, but never a finished one: if `.partial.json` holds anything other than a partial result, the new one goes to `.partial2.json` (and so on). -- `analyze` keeps nothing. If the measurement is cut short, it stops before its classify and - attribution stages, writes no artifact, and reports how many probe answers were not run. - Raise `--max-usd`, or measure less (a cheaper `--tier` or a lower `--max-atoms`). +- `analyze` keeps what it paid for in `.partial.json` beside its `novelty.json` + (never over a finished one): the atoms, the probes built and the probe answers so far, with + the stage that was running. If the measurement is cut short, it stops before its classify and + attribution stages and writes no `novelty.json` or view. It exits 3 with a message that names + the partial file. Raise `--max-usd`, or measure less (a cheaper `--tier` or a lower `--max-atoms`). - `shorten` writes no candidate table and no `--out` file. Its retention verdicts are stored in `--cache-dir` as each is adjudicated, and the exit message says how many: rerun with a higher `--max-usd` (with no `--max-usd` when the stop is a model with no known price) and the same diff --git a/dokimi/docs/skill-novelty.md b/dokimi/docs/skill-novelty.md index 1eb2a82c9d..d84ebd6ae8 100644 --- a/dokimi/docs/skill-novelty.md +++ b/dokimi/docs/skill-novelty.md @@ -993,8 +993,8 @@ research runs and for any run you may repeat. `--cache-dir` keeps only the reten **A routing run stopped by `--max-usd` keeps what it paid for.** `skill routing --model`, single artifact or `catalog routing`, writes the result of the calls made before the cap (or a call with no -known price) stopped it, prints the summary and `cost` lines, and still exits non-zero with the -cap message and the path of the file. The file carries +known price) stopped it, prints the summary and `cost` lines, and exits 3 with the +cap message and the path of the file (1 for a `permanent_error` stop). The file carries `"partial": {"reason": "spend_cap", "calls_done": N, "calls_planned": M, "message": ...}` (`"permanent_error"` for the stop above, `"no_price"` for an unpriced call) at the top level (and under the model arm), and no `partial` key when the run finished. The record's `status` is then `"partial"` instead of `"ok"` (a single run; an all-vs-all file carries `status` @@ -1429,7 +1429,7 @@ with no network that is a pause of a few seconds and a warning. Setting **Spend cap on `atoms`, `probe` and `analyze`.** `--max-usd` stops these at the limit and keeps the work it paid for. `atoms` writes `.partial.json` beside the `--out` file (`atoms.json` by default; the spans read so far, the rest marked unread), and `probe` does the same beside its `--out` -file (`probes.json` by default; the answers so far). Both exit with a message naming the file. A partial file is never read as a +file (`probes.json` by default; the answers so far). Both exit 3 (1 for a `permanent_error` stop) with a message naming the file. A partial file is never read as a finished one: `probe` and the other atom readers refuse `atoms.partial.json`, and `novelty items` refuses a partial probe file. A partial probe file keeps its `runs` and `probes` and holds null for the summaries computed over the answers the cap left (`paired`, `arms`, `abstentions`, the reversal and @@ -1446,7 +1446,7 @@ spent), and `spans_read` / `spans_total` for an extraction stop or `calls_done` (the unread spans are in `extraction.unread_span_ids`), the `probes` once built (with the wordings and answer keys in `probes.items`, so a stop before the first answer still keeps them) and the `runs` (probe answers and judgments) so far; it has no `paired`, `arms`, `k0` or view summaries, and no -`novelty.md` or annotated view is written. The exit is non-zero (1), the message names the file and +`novelty.md` or annotated view is written. The exit is 3 (1 for a `permanent_error` stop), the message names the file and how to get the paid calls back: with `DOKIMI_RESPONSE_CACHE` set to a writable directory on the capped run, a rerun with a higher `--max-usd` and the same cache replays them at $0 (a reply that was cut off or unusable is asked again; after a `no_price` stop the message says to price the model or drop `--max-usd` diff --git a/dokimi/dokimi/commands/novelty_budget.py b/dokimi/dokimi/commands/novelty_budget.py index 885275bdc4..669abef1bc 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -19,7 +19,7 @@ from pathlib import Path from typing import NoReturn -from dokimi.commands.novelty_routing_report import _partial_destinations +from dokimi.commands.novelty_routing_report import _partial_destinations, stop_partial def partial_destination(out: Path) -> Path: @@ -63,9 +63,10 @@ def partial_write(out: Path, write: Callable[[Path], object]) -> Path: raise RuntimeError("unreachable: the sidecar names never run out") -def exit_partial(summary: str, path: Path, note: str = "") -> NoReturn: - """Stop with a message that names the partial file, as a run the cap stopped must.""" - raise SystemExit(f"{summary}; the partial result is in {path}{note}") +def exit_partial(summary: str, path: Path, note: str = "", *, reason: str) -> NoReturn: + """Stop with a message that names the partial file, as a run the cap stopped must; ``reason`` is the + stop's (``partial["reason"]``) and picks the exit code (:func:`partial_exit_code`).""" + stop_partial(f"{summary}; the partial result is in {path}{note}", reason) def response_cache_active() -> bool: @@ -110,7 +111,7 @@ def save_analyze_partial(result, out: Path) -> NoReturn: cause = partial.get("cause") summary = f"{partial['message']} ({cause})" if cause else partial["message"] exit_partial(summary, write_run(result.artifact, out, partial), - replay_hint(partial["reason"])) + replay_hint(partial["reason"]), reason=partial["reason"]) def write_run(payload: dict, out: Path, partial: dict | None = None) -> Path: @@ -157,7 +158,7 @@ def save_probe_run(payload: dict, out: Path, *, done: int, not_run: int, payload[block] = None if panel: payload["judge_panel"] = {k: panel[k] for k in ("judges", "rule") if k in panel} - exit_partial(message, write_run(payload, out, partial)) + exit_partial(message, write_run(payload, out, partial), reason=reason) def save_probe_measure(payload: dict, out: Path, result) -> Path: @@ -176,7 +177,7 @@ def save_atoms_run(atoms, spans, out: Path, partial: dict | None, **record) -> P return out dest = partial_write(out, lambda side: save_atoms(atoms, spans, side, partial=partial, **record)) - exit_partial(partial["message"], dest) + exit_partial(partial["message"], dest, reason=partial["reason"]) def verify_or_partial(sample, spans, client) -> dict | None: diff --git a/dokimi/dokimi/commands/novelty_routing.py b/dokimi/dokimi/commands/novelty_routing.py index 51a7a554c0..57d0f24562 100644 --- a/dokimi/dokimi/commands/novelty_routing.py +++ b/dokimi/dokimi/commands/novelty_routing.py @@ -162,7 +162,7 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: stop_if_partial(payload, out, lambda: print_routing_summary(payload, len(competitors), self_derived)) except SystemExit as stop: - raise RoutingStopped(stop.code, payload, out, gold.name) from None + raise RoutingStopped(stop, payload, out, gold.name) from None print(f"OK Saved routing measurement: {out}") print_routing_summary(payload, len(competitors), self_derived) @@ -172,8 +172,9 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: class RoutingStopped(SystemExit): """A routing run the cap or a model error cut short: it exits as before, and carries the saved result for --json.""" - def __init__(self, message: object, payload: dict, out: Path, skill: str) -> None: - super().__init__(message) + def __init__(self, stop: SystemExit, payload: dict, out: Path, skill: str) -> None: + super().__init__(*stop.args) # the message, already printed by stop_if_partial + self.code = stop.code self.result = (payload, out, skill) diff --git a/dokimi/dokimi/commands/novelty_routing_report.py b/dokimi/dokimi/commands/novelty_routing_report.py index 5fcb68be48..84d54dc1e4 100644 --- a/dokimi/dokimi/commands/novelty_routing_report.py +++ b/dokimi/dokimi/commands/novelty_routing_report.py @@ -20,6 +20,7 @@ from pathlib import Path from typing import TYPE_CHECKING, NoReturn +from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE from dokimi.utils import InputError if TYPE_CHECKING: @@ -523,10 +524,10 @@ def exit_partial_all_vs_all(model_arm: dict, cost: dict | None, failed: int, sen noise and cost lines print before the exit; the partial result is already saved in ``out``. """ print_all_vs_all_model(model_arm, cost) - raise SystemExit(f"{failed} of {sent} model call(s) failed " - f"({model_arm['first_error']}); the partial result leaves the failed calls " - "out of model-arm scoring, and a query with a failed repeat out of the " - f"repeat-noise rates, is in {out}") + stop_partial(f"{failed} of {sent} model call(s) failed " + f"({model_arm['first_error']}); the partial result leaves the failed calls " + "out of model-arm scoring, and a query with a failed repeat out of the " + f"repeat-noise rates, is in {out}", "failed_calls") def partial_block(model_arm: dict) -> dict: @@ -657,7 +658,8 @@ def save_result(payload: dict, out: Path, model_arm: dict) -> Path: def stop_if_partial(payload: dict, out: Path, show: Callable[[], None]) -> None: - """Exit non-zero when ``--max-usd`` stopped the run; the result is already saved in ``out``. + """Exit when ``--max-usd`` (or a model error) stopped the run, with :func:`partial_exit_code`; the result + is already saved in ``out``. ``show`` prints the summary and cost lines first, so the calls paid for are on the console. The partial block says how many of the planned model calls were made. @@ -666,8 +668,29 @@ def stop_if_partial(payload: dict, out: Path, show: Callable[[], None]) -> None: if partial is None: return show() - raise SystemExit(f"{partial['message']}. The partial result, {partial['calls_done']} of " - f"{partial['calls_planned']} model calls, is in {out}") + stop_partial(f"{partial['message']}. The partial result, {partial['calls_done']} of " + f"{partial['calls_planned']} model calls, is in {out}", partial["reason"]) + + +class PartialStop(SystemExit): + """A stop that kept its partial result: ``code`` is the exit code (:func:`partial_exit_code`), ``str()`` the + message, which :func:`stop_partial` has already printed (an int ``code`` is not printed by the interpreter).""" + + def __init__(self, message: str, code: int) -> None: + super().__init__(message) + self.code = code + + +def partial_exit_code(reason: str) -> int: + """The exit code of a stop that kept its partial result (docs/quickstart.md, exit codes): 3 for a budget + stop (``spend_cap``, ``no_price``), 1 for a runtime failure (``permanent_error``) or any other reason.""" + return EXIT_INCONCLUSIVE if reason in ("spend_cap", "no_price") else EXIT_FAILURE + + +def stop_partial(message: str, reason: str) -> NoReturn: + """Print ``message`` on stderr and exit with the code of ``reason``.""" + print(message, file=sys.stderr) + raise PartialStop(message, partial_exit_code(reason)) def warn_blind_skills(result: dict, queries_by_skill: dict[str, list[str]]) -> None: diff --git a/dokimi/tests/test_novelty_analyze_cap_partial.py b/dokimi/tests/test_novelty_analyze_cap_partial.py index 741783957f..c38f4c8bfe 100644 --- a/dokimi/tests/test_novelty_analyze_cap_partial.py +++ b/dokimi/tests/test_novelty_analyze_cap_partial.py @@ -277,6 +277,7 @@ def test_the_command_writes_the_partial_file_beside_novelty_json_and_names_it(tm args, out_dir = _command(tmp_path, monkeypatch, _answers_cost) with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 message = str(stop.value) partial = out_dir / "novelty.partial.json" assert f"the partial result is in {partial}" in message @@ -295,8 +296,9 @@ def test_the_message_says_a_rerun_replays_the_paid_calls_when_the_cache_was_set( monkeypatch.setenv("DOKIMI_RESPONSE_CACHE", str(tmp_path / "cache")) args, _out_dir = _command(tmp_path, monkeypatch, _answers_cost) with pytest.raises(SystemExit, match="same DOKIMI_RESPONSE_CACHE: the calls already paid for " - "replay at \\$0"): + "replay at \\$0") as stop: args.func(args) + assert stop.value.code == 3 def test_a_no_price_stop_does_not_advise_a_higher_cap(tmp_path, monkeypatch): @@ -305,6 +307,7 @@ def test_a_no_price_stop_does_not_advise_a_higher_cap(tmp_path, monkeypatch): args, _out_dir = _command(tmp_path, monkeypatch, lambda prompt: None) with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 message = str(stop.value) assert "Rerun with the model priced, or without --max-usd, and the same DOKIMI_RESPONSE_CACHE" \ in message @@ -319,6 +322,7 @@ def test_the_message_does_not_claim_a_replay_when_the_cache_variable_names_a_fil args, _out_dir = _command(tmp_path, monkeypatch, _answers_cost) with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 message = str(stop.value) assert "DOKIMI_RESPONSE_CACHE was not set on this run" in message assert "a rerun pays for these calls again" in message @@ -425,8 +429,9 @@ def test_a_partial_result_never_replaces_a_finished_novelty_json(tmp_path, monke out_dir.mkdir() finished = out_dir / "novelty.json" finished.write_text('{"schema_version": "novelty.v1", "finished": true}', encoding="utf-8") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 assert json.loads(finished.read_text(encoding="utf-8"))["finished"] is True assert json.loads((out_dir / "novelty.partial.json").read_text(encoding="utf-8"))["status"] \ == "partial" @@ -439,8 +444,9 @@ def test_a_partial_analyze_file_is_refused_by_the_readers_of_a_finished_one(tmp_ from dokimi.subjects.novelty_track import load_novelty_artifacts args, out_dir = _command(tmp_path, monkeypatch, _answers_cost) - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 partial = out_dir / "novelty.partial.json" record = json.loads(partial.read_text(encoding="utf-8")) del record["partial"] # the schema lets `status` stand alone @@ -487,7 +493,8 @@ def test_a_partial_analyze_file_is_not_listed_as_a_finished_run(tmp_path, monkey from dokimi.runs.scan import scan args, out_dir = _command(tmp_path, monkeypatch, _answers_cost) - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 result = scan(out_dir) assert result.artifacts == [] and result.skipped["no_leading_schema_version"] == 1 diff --git a/dokimi/tests/test_novelty_cap_partial.py b/dokimi/tests/test_novelty_cap_partial.py index afbbd8c8bc..195b4d4959 100644 --- a/dokimi/tests/test_novelty_cap_partial.py +++ b/dokimi/tests/test_novelty_cap_partial.py @@ -78,6 +78,7 @@ def test_the_atoms_command_saves_a_partial_file_and_exits_without_atoms_json(tmp partial = tmp_path / "atoms.partial.json" with pytest.raises(SystemExit) as exit_info: args.func(args) + assert exit_info.value.code == 3 assert f"the partial result is in {partial}" in str(exit_info.value) assert not out.exists() record = json.loads(partial.read_text(encoding="utf-8")) @@ -106,8 +107,9 @@ def empty_and_paid(prompt, system=None): monkeypatch.setattr(novelty_cost, "client", lambda model, provider, role, args: client) args = _parse(*novelty_argv("atoms"), "--artifact", str(artifact), "--model", "e", "--out", str(tmp_path / "atoms.json"), "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 err = capsys.readouterr().err assert "WARNING atom extraction could not read" in err assert "got an empty reply" in err @@ -177,6 +179,7 @@ def capped(*a, **kw): "--out", str(out), "--max-usd", "1") with pytest.raises(SystemExit) as exit_info: args.func(args) + assert exit_info.value.code == 3 assert f"the partial result is in {tmp_path / 'probes.partial.json'}" in str(exit_info.value) assert not out.exists() record = json.loads((tmp_path / "probes.partial.json").read_text(encoding="utf-8")) @@ -411,8 +414,9 @@ def test_save_probe_measure_keeps_an_ungraded_answer_in_the_partial_file(tmp_pat result = measure.MeasureResult(runs=[object()], arms=("full",), with_arm="full", not_run=0, ungraded=1, stop=("spend_cap", "cap"), probes=[]) out = tmp_path / "probes.json" - with pytest.raises(SystemExit, match="1 of them not graded"): + with pytest.raises(SystemExit, match="1 of them not graded") as stop: save_probe_measure({"runs": []}, out, result) + assert stop.value.code == 3 assert (tmp_path / "probes.partial.json").exists() assert not out.exists() @@ -464,9 +468,10 @@ def unpriced(prompt, system=None): judge=LLMClient(model="j", role="judge"), arms=("no_artifact", "full"), concurrency=1) out = tmp_path / "probes.json" - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: save_probe_run({"runs": []}, out, done=len(result.runs), not_run=result.not_run, stop=result.stop, ungraded=result.ungraded) + assert stop.value.code == 3 partial = json.loads((tmp_path / "probes.partial.json").read_text(encoding="utf-8"))["partial"] assert partial["reason"] == "no_price" assert partial["message"].startswith( @@ -596,8 +601,9 @@ def test_an_answer_whose_grade_the_cap_refused_makes_the_probe_file_partial(tmp_ from dokimi.commands.novelty_budget import save_probe_run out = tmp_path / "probes.json" - with pytest.raises(SystemExit, match="1 of them not graded"): + with pytest.raises(SystemExit, match="1 of them not graded") as stop: save_probe_run({"runs": []}, out, done=1, not_run=0, ungraded=1) + assert stop.value.code == 3 partial = json.loads((tmp_path / "probes.partial.json").read_text(encoding="utf-8"))["partial"] assert partial["calls_done"] == 1 and partial["calls_planned"] == 1 assert not out.exists() @@ -674,8 +680,9 @@ def test_a_partial_probe_file_drops_the_summaries_computed_over_the_cut_subset(t # the second judge shares the run's cap, so it is refused once the cap stops the run "judge2": {"model": "j2", "stopped": "spend cap reached", "cost": 0.0}} out = tmp_path / "probes.json" - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: save_probe_run(payload, out, done=1, not_run=5, stop=("spend_cap", "cap")) + assert stop.value.code == 3 saved = json.loads((tmp_path / "probes.partial.json").read_text(encoding="utf-8")) assert saved["runs"] == [{"verdict": "correct"}] and saved["probes"] == {"n": 3} # a literal list, not PARTIAL_SUMMARIES: a block dropped from that tuple must fail here diff --git a/dokimi/tests/test_novelty_partial_exit_code.py b/dokimi/tests/test_novelty_partial_exit_code.py new file mode 100644 index 0000000000..47bd6d1a79 --- /dev/null +++ b/dokimi/tests/test_novelty_partial_exit_code.py @@ -0,0 +1,81 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""A stop that kept its partial result exits 3 when a budget ran out and 1 when an error did (docs/quickstart.md, exit codes).""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from dokimi import cli +from dokimi.commands.novelty_routing_report import partial_exit_code +from dokimi.novelty import cost as novelty_cost +from dokimi.novelty.client import SpendCap +from tests.cli_paths import novelty_argv +from tests.test_novelty_cap_partial import ROWS, _paid_extractor + + +@pytest.mark.parametrize("reason, code", [("spend_cap", 3), ("no_price", 3), ("permanent_error", 1), + ("stopped", 1), ("anything else", 1)]) +def test_the_exit_code_of_a_kept_partial_result_follows_its_reason(reason, code): + assert partial_exit_code(reason) == code + + +@pytest.mark.parametrize("reason, code", [("no_price", 3), ("permanent_error", 1)]) +def test_a_probe_stopped_on_a_call_with_no_price_or_a_permanent_error_exits_by_the_reason( + tmp_path, reason, code): + from dokimi.commands.novelty_budget import save_probe_run + + with pytest.raises(SystemExit, match="the probes stopped with 1 of 2 answers: because") as stop: + save_probe_run({"runs": []}, tmp_path / "probes.json", done=1, not_run=1, + stop=(reason, "because")) + assert stop.value.code == code + assert (tmp_path / "probes.partial.json").exists() + + +@pytest.mark.parametrize("reason, code", [("no_price", 3), ("permanent_error", 1)]) +def test_an_analyze_stopped_on_a_call_with_no_price_or_a_permanent_error_exits_by_the_reason( + tmp_path, reason, code): + from dokimi.commands.novelty_budget import save_analyze_partial + + partial = {"reason": reason, "message": "the measurement stopped", "cause": "because"} + result = SimpleNamespace(partial=partial, artifact={"runs": []}) + with pytest.raises(SystemExit, match="the measurement stopped .because.; the partial result is in") as stop: + save_analyze_partial(result, tmp_path / "novelty.json") + assert stop.value.code == code + assert json.loads((tmp_path / "novelty.partial.json").read_text(encoding="utf-8"))["status"] == "partial" + + +@pytest.mark.parametrize("reason, code", [("spend_cap", 3), ("permanent_error", 1)]) +def test_an_atoms_run_stopped_by_the_faithfulness_check_exits_by_the_reason( + tmp_path, monkeypatch, reason, code): + from dokimi.commands.novelty_budget import save_atoms_run + from dokimi.novelty import atoms as atoms_mod + + monkeypatch.setattr(atoms_mod, "save_atoms", lambda atoms, spans, dest, partial=None, **record: + dest.write_text(json.dumps({"partial": partial}), encoding="utf-8")) + partial = {"reason": reason, "message": "the check stopped"} + with pytest.raises(SystemExit, match="the check stopped; the partial result is in") as stop: + save_atoms_run([], [], tmp_path / "atoms.json", partial) + assert stop.value.code == code + assert (tmp_path / "atoms.partial.json").exists() + + +def test_atoms_stopped_by_the_cap_exits_3_through_cli_main_with_its_message_once( + tmp_path, monkeypatch, capsys): + artifact = tmp_path / "rows.md" + artifact.write_text(ROWS, encoding="utf-8") + cap, calls = SpendCap(limit_usd=1.0), [] + monkeypatch.setattr(novelty_cost, "client", lambda model, provider, role, args: + _paid_extractor(cap, calls)) + monkeypatch.setattr("sys.argv", ["dokimi", *novelty_argv("atoms"), "--artifact", str(artifact), + "--model", "e", "--out", str(tmp_path / "atoms.json"), + "--max-usd", "1"]) + with pytest.raises(SystemExit) as stop: + cli.main() + assert stop.value.code == 3 + err = capsys.readouterr().err + assert err.count("--max-usd stopped extraction with 50 of 200 spans read; the partial result is in") == 1 diff --git a/dokimi/tests/test_novelty_routing_all_vs_all.py b/dokimi/tests/test_novelty_routing_all_vs_all.py index c470d14758..24a89a0e2f 100644 --- a/dokimi/tests/test_novelty_routing_all_vs_all.py +++ b/dokimi/tests/test_novelty_routing_all_vs_all.py @@ -415,8 +415,9 @@ def transport(prompt: str, system: str | None): "db": ["add an index"]}) args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(tmp_path / "o.json"), "--model", "m") - with pytest.raises(SystemExit, match="2 of 2 model call.s. failed"): + with pytest.raises(SystemExit, match="2 of 2 model call.s. failed") as stop: args.func(args) + assert stop.value.code == 1 captured = capsys.readouterr() assert "OK Saved" not in captured.out assert "2 model call(s) failed" in captured.err and "boom" in captured.err @@ -443,8 +444,9 @@ def transport(prompt: str, system: str | None = None): args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(tmp_path / "o.json"), "--model", "m", "--max-usd", "1") - with pytest.raises(SystemExit, match=r"\$1\.20 of \$1\.00"): + with pytest.raises(SystemExit, match=r"\$1\.20 of \$1\.00") as stop: args.func(args) + assert stop.value.code == 3 assert len(calls) == 2 # the third request was refused before it reached the provider @@ -534,8 +536,9 @@ def transport(prompt: str, system: str | None): out = tmp_path / "o.json" args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(out), "--model", "m") - with pytest.raises(SystemExit, match="2 of 3 model call"): + with pytest.raises(SystemExit, match="2 of 3 model call") as stop: args.func(args) + assert stop.value.code == 1 assert "OK Saved" not in capsys.readouterr().out model = json.loads(out.read_text(encoding="utf-8"))["result"]["model"] assert model["n_failed"] == 2 @@ -807,8 +810,9 @@ def transport(prompt: str, system: str | None): queries = _write_queries(tmp_path, {"db": ["add an index", "the of and"]}) args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(tmp_path / "o.json"), "--model", "m") - with pytest.raises(SystemExit, match="^1 of 1 model call"): + with pytest.raises(SystemExit, match="^1 of 1 model call") as stop: args.func(args) + assert stop.value.code == 1 assert "makes 1 model calls" in capsys.readouterr().err @@ -934,8 +938,9 @@ def transport(prompt: str, system: str | None = None): "db": ["add an index"]}) args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(tmp_path / "o.json"), "--model", "m") - with pytest.raises(SystemExit, match="1 of 2 model call.s. failed"): + with pytest.raises(SystemExit, match="1 of 2 model call.s. failed") as stop: args.func(args) + assert stop.value.code == 1 out = capsys.readouterr().out assert "OK Saved" not in out assert any(line.startswith("cost") for line in out.splitlines()), out diff --git a/dokimi/tests/test_novelty_routing_repeat_failures.py b/dokimi/tests/test_novelty_routing_repeat_failures.py index a9cbeb1e99..eb43d119d5 100644 --- a/dokimi/tests/test_novelty_routing_repeat_failures.py +++ b/dokimi/tests/test_novelty_routing_repeat_failures.py @@ -53,9 +53,10 @@ def transport(prompt: str, system: str | None): "--out", str(out), "--model", "m", "--reps", "2") with pytest.raises(SystemExit) as exc: args.func(args) - assert "1 of 2 model call" in str(exc.value.code) - assert "out of model-arm scoring" in str(exc.value.code) - assert "repeat-noise rates" in str(exc.value.code) + assert exc.value.code == 1 # failed model calls: a runtime failure + assert "1 of 2 model call" in str(exc.value) + assert "out of model-arm scoring" in str(exc.value) + assert "repeat-noise rates" in str(exc.value) model = json.loads(out.read_text(encoding="utf-8"))["result"]["model"] # The good repeat is a scored call; the failed one is unscored. The query has a failed # repeat, so it is in no repeat-noise rate. diff --git a/dokimi/tests/test_novelty_routing_spend_cap_partial.py b/dokimi/tests/test_novelty_routing_spend_cap_partial.py index 51291ad749..1dea0101ae 100644 --- a/dokimi/tests/test_novelty_routing_spend_cap_partial.py +++ b/dokimi/tests/test_novelty_routing_spend_cap_partial.py @@ -73,6 +73,7 @@ def test_a_single_run_stopped_by_the_cap_writes_what_it_scored(tmp_path, monkeyp args, out = _single(tmp_path, [*QUERIES, "annotate the hot loop"], "--max-usd", "1") with pytest.raises(SystemExit, match=r"\$1\.20 of \$1\.00") as stop: args.func(args) + assert stop.value.code == 3 assert str(out) in str(stop.value) assert len(calls) == 2 payload = json.loads(out.read_text(encoding="utf-8")) @@ -89,8 +90,9 @@ def test_a_single_run_stopped_by_the_cap_writes_what_it_scored(tmp_path, monkeyp def test_a_stopped_repeat_run_keeps_the_noise_of_the_queries_it_finished(tmp_path, monkeypatch): _provider(monkeypatch, UsageRecord(cost_usd=0.4)) args, out = _single(tmp_path, QUERIES, "--reps", "2", "--max-usd", "1") - with pytest.raises(SystemExit, match="spend cap reached"): + with pytest.raises(SystemExit, match="spend cap reached") as stop: args.func(args) + assert stop.value.code == 3 payload = json.loads(out.read_text(encoding="utf-8")) assert (payload["partial"]["calls_done"], payload["partial"]["calls_planned"]) == (3, 6) assert len(payload["model"]["per_query"]) == 3 # the half-asked query is kept @@ -101,8 +103,9 @@ def test_a_stopped_repeat_run_keeps_the_noise_of_the_queries_it_finished(tmp_pat def test_a_call_with_no_price_also_leaves_the_partial_result(tmp_path, monkeypatch): _provider(monkeypatch, None) args, out = _single(tmp_path, QUERIES, "--max-usd", "5") - with pytest.raises(SystemExit, match="no price is known"): + with pytest.raises(SystemExit, match="no price is known") as stop: args.func(args) + assert stop.value.code == 3 payload = json.loads(out.read_text(encoding="utf-8")) assert payload["partial"]["reason"] == "no_price" and payload["partial"]["calls_done"] == 1 # The reply came back and was paid for, so it is scored, not lost; no further call is made. @@ -141,6 +144,7 @@ def test_an_all_vs_all_run_stopped_by_the_cap_scores_the_queries_it_finished( "--max-usd", "1") with pytest.raises(SystemExit, match=r"\$1\.20 of \$1\.00") as stop: args.func(args) + assert stop.value.code == 3 assert str(out) in str(stop.value) assert len(calls) == 2 payload = json.loads(out.read_text(encoding="utf-8")) @@ -173,8 +177,9 @@ def test_an_all_vs_all_run_stopped_early_leaves_the_skills_it_never_reached_unsc "--out", str(out), "--model", "m", "--max-usd", "0.5") # The first call is allowed (nothing spent), then 0.6 >= 0.5 refuses the rest. - with pytest.raises(SystemExit, match="spend cap reached"): + with pytest.raises(SystemExit, match="spend cap reached") as stop: args.func(args) + assert stop.value.code == 3 model = json.loads(out.read_text(encoding="utf-8"))["result"]["model"] assert sum(model["n_scored"].values()) == 1 unreached = [skill for skill, n in model["n_scored"].items() if n == 0] @@ -187,8 +192,9 @@ def test_an_all_vs_all_run_stopped_early_leaves_the_skills_it_never_reached_unsc def test_a_stopped_run_is_marked_partial_and_a_finished_one_is_not(tmp_path, monkeypatch): _provider(monkeypatch, UsageRecord(cost_usd=0.6)) args, out = _single(tmp_path, QUERIES, "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 assert json.loads(out.read_text(encoding="utf-8"))["status"] == "partial" sub = tmp_path / "all" sub.mkdir() @@ -197,8 +203,9 @@ def test_a_stopped_run_is_marked_partial_and_a_finished_one_is_not(tmp_path, mon args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(all_out), "--model", "m", "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 assert json.loads(all_out.read_text(encoding="utf-8"))["status"] == "partial" finished = tmp_path / "fin" finished.mkdir() @@ -213,8 +220,9 @@ def test_the_model_line_of_a_partial_run_says_how_many_calls_it_rests_on( _provider(monkeypatch, UsageRecord(cost_usd=0.6)) queries = [f"profile binary number {i}" for i in range(20)] args, _out = _single(tmp_path, queries, "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 lines = capsys.readouterr().out.splitlines() model = next(line for line in lines if line.startswith("model ")) assert "partial: 1 of 20 calls" in model @@ -231,25 +239,29 @@ def test_a_partial_run_does_not_overwrite_a_finished_result(tmp_path, monkeypatc again = _again(tmp_path, out, "second", "--max-usd", "0.5") with pytest.raises(SystemExit) as stop: again.func(again) + assert stop.value.code == 3 side = out.with_suffix(".partial.json") assert out.read_text(encoding="utf-8") == finished # the finished result stays assert json.loads(side.read_text(encoding="utf-8"))["status"] == "partial" assert str(side) in str(stop.value) # A second stopped run replaces the partial file, not the finished one. again2 = _again(tmp_path, out, "third", "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: again2.func(again2) + assert stop.value.code == 3 assert out.read_text(encoding="utf-8") == finished def test_a_partial_run_writes_over_an_earlier_partial_one(tmp_path, monkeypatch): _provider(monkeypatch, UsageRecord(cost_usd=0.6)) args, out = _single(tmp_path, QUERIES, "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 again = _again(tmp_path, out, "second", "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: again.func(again) + assert stop.value.code == 3 assert not out.with_suffix(".partial.json").exists() @@ -265,6 +277,7 @@ def test_a_partial_run_skips_a_sidecar_that_holds_a_finished_result(tmp_path, mo again = _again(tmp_path, out, "third", "--max-usd", "0.5") with pytest.raises(SystemExit) as stop: again.func(again) + assert stop.value.code == 3 third = out.with_name("routing.partial2.json") assert out.read_text(encoding="utf-8") == finished # the finished result stays assert side.read_text(encoding="utf-8") == finished_side # and so does the finished sidecar @@ -277,8 +290,9 @@ def test_a_single_run_capped_before_any_query_finished_has_an_empty_noise_block( # asked for and measures nothing. _provider(monkeypatch, UsageRecord(cost_usd=0.6)) args, out = _single(tmp_path, QUERIES, "--reps", "3", "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: args.func(args) + assert stop.value.code == 3 noise = json.loads(out.read_text(encoding="utf-8"))["model"]["noise"] assert (noise["n_repeats"], noise["n_queries_compared"], noise["mean_agreement"]) == (3, 0, None) @@ -301,8 +315,9 @@ def test_a_partial_run_skips_a_sidecar_it_cannot_read(tmp_path, monkeypatch): side.write_text("not json", encoding="utf-8") # a sidecar this cannot read is no partial result _provider(monkeypatch, UsageRecord(cost_usd=0.6)) again = _again(tmp_path, out, "third", "--max-usd", "0.5") - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as stop: again.func(again) + assert stop.value.code == 3 assert side.read_text(encoding="utf-8") == "not json" # it is left as it is third = out.with_name("routing.partial2.json") assert json.loads(third.read_text(encoding="utf-8"))["status"] == "partial" @@ -710,8 +725,9 @@ def test_an_all_vs_all_repeat_run_stopped_mid_query_pins_its_counts(tmp_path, mo args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(out), "--model", "m", "--reps", "2", "--max-usd", "1") - with pytest.raises(SystemExit, match="spend cap reached"): + with pytest.raises(SystemExit, match="spend cap reached") as stop: args.func(args) + assert stop.value.code == 3 payload = json.loads(out.read_text(encoding="utf-8")) assert (payload["partial"]["calls_done"], payload["partial"]["calls_planned"]) == (3, 10) model = payload["result"]["model"] @@ -754,8 +770,9 @@ def test_an_unpriced_call_stops_the_later_repeats_and_skills_too(tmp_path, monke args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(out), "--model", "m", "--reps", "3", "--max-usd", "5") - with pytest.raises(SystemExit, match="no price is known"): + with pytest.raises(SystemExit, match="no price is known") as stop: args.func(args) + assert stop.value.code == 3 # The first unpriced reply stops the run: no repeat of that query and no later skill is asked. assert len(calls) == 1 payload = json.loads(out.read_text(encoding="utf-8")) @@ -770,8 +787,9 @@ def _cut_and_unpriced(): def test_an_unpriced_reply_cut_at_the_ceiling_abstains_and_stops_the_run(tmp_path, monkeypatch): calls = _provider(monkeypatch, _cut_and_unpriced()) args, out = _single(tmp_path, QUERIES, "--max-usd", "5") - with pytest.raises(SystemExit, match="no price is known"): + with pytest.raises(SystemExit, match="no price is known") as stop: args.func(args) + assert stop.value.code == 3 assert len(calls) == 1 model = json.loads(out.read_text(encoding="utf-8"))["model"] # The cut '{"pick": 1}' is a decline, as a priced cut reply is, not a pick of card 1. @@ -787,8 +805,9 @@ def test_an_all_vs_all_unpriced_reply_cut_at_the_ceiling_is_no_pick(tmp_path, mo args = _parse("catalog", "routing", str(root), "--queries-by-skill", str(queries), "--out", str(out), "--model", "m", "--max-usd", "5") - with pytest.raises(SystemExit, match="no price is known"): + with pytest.raises(SystemExit, match="no price is known") as stop: args.func(args) + assert stop.value.code == 3 assert len(calls) == 1 model = json.loads(out.read_text(encoding="utf-8"))["result"]["model"] assert model["n_abstained"] == 1 @@ -798,8 +817,9 @@ def test_an_all_vs_all_unpriced_reply_cut_at_the_ceiling_is_no_pick(tmp_path, mo def test_an_unpriced_call_stops_the_repeats_of_a_single_artifact_run(tmp_path, monkeypatch): calls = _provider(monkeypatch, None) args, out = _single(tmp_path, QUERIES[:2], "--reps", "3", "--max-usd", "5") - with pytest.raises(SystemExit, match="no price is known"): + with pytest.raises(SystemExit, match="no price is known") as stop: args.func(args) + assert stop.value.code == 3 assert len(calls) == 1 payload = json.loads(out.read_text(encoding="utf-8")) assert (payload["partial"]["calls_done"], payload["partial"]["calls_planned"]) == (1, 6) @@ -809,8 +829,9 @@ def test_a_partial_single_run_rates_its_selections_over_the_calls_it_made(tmp_pa # Three queries, the cap stops after two calls: the rate is over the two asked, not all three. _provider(monkeypatch, UsageRecord(cost_usd=0.6)) args, out = _single(tmp_path, QUERIES, "--max-usd", "1") - with pytest.raises(SystemExit, match="spend cap reached"): + with pytest.raises(SystemExit, match="spend cap reached") as stop: args.func(args) + assert stop.value.code == 3 model = json.loads(out.read_text(encoding="utf-8"))["model"] hits = sum(1 for row in model["per_query"] if row.get("correct")) assert model["n_calls"] == 2 @@ -837,3 +858,44 @@ def test_a_file_nested_too_deep_to_parse_is_not_a_partial_result_and_save_result assert saved != deep assert deep.read_text(encoding="utf-8") == "[" * 20000 assert json.loads(saved.read_text(encoding="utf-8"))["partial"] == PARTIAL + + +class AuthenticationError(Exception): + """Named as litellm's, which ``is_retryable`` reads by class name: every later call would meet it.""" + + +def test_a_stop_on_a_permanent_provider_error_keeps_its_partial_result_and_exits_1(tmp_path, monkeypatch): + # docs/quickstart.md: exit 3 is a budget stop; a provider error every call would meet is a runtime failure (1). + from dokimi import llm + + def refuse(prompt, model, **_kwargs): + raise AuthenticationError("bad key") + + monkeypatch.setattr(llm, "llm_call_with_usage", refuse) + args, out = _single(tmp_path, QUERIES, "--max-usd", "5") + with pytest.raises(SystemExit, match="permanent error: bad key") as stop: + args.func(args) + assert stop.value.code == 1 + assert json.loads(out.read_text(encoding="utf-8"))["partial"]["reason"] == "permanent_error" + + +def test_skill_routing_json_stopped_by_the_cap_prints_one_document_and_exits_3( + tmp_path, monkeypatch, capsys): + from dokimi import cli + + _provider(monkeypatch, UsageRecord(cost_usd=0.6)) + queries = tmp_path / "q.json" + queries.write_text(json.dumps(QUERIES), encoding="utf-8") + out = tmp_path / "routing.json" + monkeypatch.setattr("sys.argv", [ + "dokimi", "skill", "routing", _skill(tmp_path, "a", "profile a binary with perf"), + "--competitors", _skill(tmp_path, "b", "tune a database"), "--queries", str(queries), + "--model", "m", "--out", str(out), "--max-usd", "1", "--json"]) + with pytest.raises(SystemExit) as stop: + cli.main() + assert stop.value.code == 3 + assert str(stop.value).startswith("spend cap reached: ") # str() stays the message, nothing else + shown = capsys.readouterr() + document = json.loads(shown.out) # one document: a second one would not parse + assert document["status"] == "budget_stopped" + assert shown.err.count("The partial result, 2 of 3 model calls") == 1 diff --git a/dokimi/tests/test_novelty_spend_cap.py b/dokimi/tests/test_novelty_spend_cap.py index 9663c2591a..73ba4e4357 100644 --- a/dokimi/tests/test_novelty_spend_cap.py +++ b/dokimi/tests/test_novelty_spend_cap.py @@ -128,8 +128,9 @@ def transport(prompt, system=None): out = tmp_path / "atoms.json" args = _parse("skill", "novelty", "atoms", "--artifact", f"skill:{skill}", "--out", str(out), "--max-usd", "1") - with pytest.raises(SystemExit, match="partial"): + with pytest.raises(SystemExit, match="partial") as stop: args.func(args) + assert stop.value.code == 3 assert len(calls) == 1 # extraction ran; the faithfulness call was refused assert not out.exists() partial = json.loads((tmp_path / "atoms.partial.json").read_text(encoding="utf-8")) diff --git a/dokimi/tests/test_report_summary.py b/dokimi/tests/test_report_summary.py index 21e966d339..ff63d72e15 100644 --- a/dokimi/tests/test_report_summary.py +++ b/dokimi/tests/test_report_summary.py @@ -430,7 +430,7 @@ def test_skill_routing_json_of_a_capped_run_keeps_its_document_and_its_exit(tmp_ arm = {**_ARM, "partial": partial_record("spend cap reached", 1, 2, "spend_cap")} code, out, _ = _routing_with_model(tmp_path, d, c, arm) doc = json.loads(out) - assert code == 1 and schema_errors("cli_output.v1", doc) == [] + assert code == 3 and schema_errors("cli_output.v1", doc) == [] # a budget stop that kept its result (docs/quickstart.md) assert (doc["status"], doc["reason"]) == ("budget_stopped", "spend cap reached") assert doc["cost"]["spent_usd"] == 0.25 and doc["artifacts"]["out"] == str(tmp_path / "r.json") From b190b0945513b324af7b2abc726d6a6d6f99f15f Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 28 Nov 2026 14:00:36 +0000 Subject: [PATCH 2/2] docs(novelty): leave the walkthrough's analyze bullet as main has it The first commit rewrote the walkthrough's `analyze` bullet to say what analyze keeps in its partial file since #633. An open PR rewrites the same bullet, so this branch puts it back to main's text and changes only the walkthrough line that says how the stopped steps exit. Signed-off-by: Anton Volkov --- dokimi/docs/skill-novelty-walkthrough.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/dokimi/docs/skill-novelty-walkthrough.md b/dokimi/docs/skill-novelty-walkthrough.md index e972bfb4cb..accb69d182 100644 --- a/dokimi/docs/skill-novelty-walkthrough.md +++ b/dokimi/docs/skill-novelty-walkthrough.md @@ -104,11 +104,9 @@ What a stopped run leaves behind depends on the step: finished one: the atom readers and `novelty items` refuse it. A later stopped run replaces an earlier partial file, but never a finished one: if `.partial.json` holds anything other than a partial result, the new one goes to `.partial2.json` (and so on). -- `analyze` keeps what it paid for in `.partial.json` beside its `novelty.json` - (never over a finished one): the atoms, the probes built and the probe answers so far, with - the stage that was running. If the measurement is cut short, it stops before its classify and - attribution stages and writes no `novelty.json` or view. It exits 3 with a message that names - the partial file. Raise `--max-usd`, or measure less (a cheaper `--tier` or a lower `--max-atoms`). +- `analyze` keeps nothing. If the measurement is cut short, it stops before its classify and + attribution stages, writes no artifact, and reports how many probe answers were not run. + Raise `--max-usd`, or measure less (a cheaper `--tier` or a lower `--max-atoms`). - `shorten` writes no candidate table and no `--out` file. Its retention verdicts are stored in `--cache-dir` as each is adjudicated, and the exit message says how many: rerun with a higher `--max-usd` (with no `--max-usd` when the stop is a model with no known price) and the same