diff --git a/dokimi/changelog.d/20261203_100000_failed-call-exit.md b/dokimi/changelog.d/20261203_100000_failed-call-exit.md new file mode 100644 index 000000000..a494d667a --- /dev/null +++ b/dokimi/changelog.d/20261203_100000_failed-call-exit.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A model call that failed and the run went on makes `skill routing` and `skill novelty atoms`, `probe` and `analyze` exit 1** (#1556) — a call that raised an error the commands do not expect (an extraction call, a probe wording call, a routing pick) was absorbed: the command exited 0, and `skill routing` wrote `"status": "ok"` with "1 failed" in its summary line. It now writes its result as before, then prints the failed calls with the first error and exits 1, as `catalog routing` already did; `skill routing` writes `"status": "partial"` (no `partial` block unless the cap stopped it too). A failed call in a run `--max-usd` stopped exits 1 too, not 3. A script that read exit 0 from these commands after a failed call may notice. A reply that does not parse stays exit 0, and `tools preference` and `repo hits judge` still record a failed item in their output and exit 0 (`docs/quickstart.md`, exit codes). diff --git a/dokimi/docs/quickstart.md b/dokimi/docs/quickstart.md index 28f22ed59..556be024f 100644 --- a/dokimi/docs/quickstart.md +++ b/dokimi/docs/quickstart.md @@ -258,9 +258,9 @@ failed check. | Code | Meaning | Examples | |------|---------|----------| | 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 | +| 1 | A verdict or a gate that ran and failed, or a runtime failure the command reports (a model call, a model call that failed and the run went on, a run, a clone or fetch); `skill routing`, `skill novelty atoms`, `probe` and `analyze` and `catalog routing` write their result first, with a status that is not `ok` where the file has one, while `tools preference` and `repo hits judge` record the failed item in their output and exit 0; 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 --questions` on an empty or non-JSON file (`--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`, `skill novelty atoms`, `probe` and `analyze`, `skill routing` and `catalog routing`, `repo run` when the batch budget is the only reason a cell was not started (with a cell error or a failed probe too it exits 1, 5 for a cell that crashed of the machinery; a batch that started no cell exits 1), and `repo hits judge`; a stop on a permanent provider error, on 3 judge calls in a row failing with one error, or a `catalog routing` run with a failed model call, exits 1; `eval personas discover` refuses its one call before it runs, so nothing is written), or the result is undecided (`trace consistency --contract`: a rule depends on an unlabelled write; `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`, `repo run` when the batch budget is the only reason a cell was not started (with a cell error or a failed probe too it exits 1, 5 for a cell that crashed of the machinery; a batch that started no cell exits 1), and `repo hits judge`; a stop on a permanent provider error, on 3 judge calls in a row failing with one error, or a `skill routing`, `skill novelty atoms`, `probe` or `analyze` or `catalog routing` run with a failed model call, exits 1; `eval personas discover` refuses its one call before it runs, so nothing is written), or the result is undecided (`trace consistency --contract`: a rule depends on an unlabelled write; `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; under `runs baseline save --expect-previous`, a baseline that no longer points to the run expected (a stale baseline, the pointer left as it was). | `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 | @@ -277,7 +277,7 @@ or an unpriced model stopped it short, and `eval personas discover` exits 3 when `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 or, in `catalog routing`, a model call failed (`catalog novelty` exits 1 too, once it has written +stopped them or a model call failed and the run went on (`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` with a repeated `--judge` 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.md b/dokimi/docs/skill-novelty.md index c1a9806df..076933254 100644 --- a/dokimi/docs/skill-novelty.md +++ b/dokimi/docs/skill-novelty.md @@ -887,7 +887,9 @@ Two numbers, reported side by side and never merged: the gold card was shown at are recorded per query. **An abstention counts against `selection_rate`** — not picking anything is the routing failure — with `selection_rate_among_answered` beside it; a failed call is excluded from both and - counted, and one failed query does not lose the rest. + counted, and one failed query does not lose the rest. A run with a failed call writes + its result with `"status": "partial"` (no `partial` block unless the cap stopped it too) + and exits 1, naming `N of M model call(s) failed` and the first error. Each abstention or unparseable pick keeps the model's raw reply under `per_query[].raw_reply` (the first 2000 characters), so a decline can be read. A reply cut at the output ceiling is an abstention too, whether or not its price is known. @@ -1016,12 +1018,12 @@ fewer calls than the printed count. The response cache is opt-in: without `DOKIM set to a writable directory nothing is stored, and a rerun pays for every call again. Set it for research runs and for any run you may repeat. `--cache-dir` keeps only the retention verdicts. -**A permanent provider error that every call would meet stops a routing run the way the cap does.** An authentication or permission error, an unknown model ID (`not found`), a parameter the provider does not take (every call sends the same ones) or missing credentials (with `claude-cli`: not logged in, a usage limit, no `claude` binary; with AWS: "Unable to locate credentials", a missing config profile or an expired SSO session, whichever class litellm wraps it in) would fail every later call alike, so the run stops at that call, keeps the rows made before it and writes the partial result below, with `"reason": "permanent_error"` and the error text as the message (`--max-usd` is not involved; the exit line gives `calls_done` of `calls_planned`). Any other failure is one failed row and the run goes on: a refusal, a request one query makes too long, an unparseable reply, an error the client does not recognise, a transient error that ran out of retries. `skill novelty atoms`, `probe` and `analyze` and `skill shorten` stop the same way at the first such error in an atom extraction call, the faithfulness check, a probe wording, an answer, a grade, a value or conflict batch or a retention adjudication, and keep what they paid for as they do at the cap, with `"reason": "permanent_error"`; a refusal, an unparseable reply or a request one item makes too long is still one failed item. +**A permanent provider error that every call would meet stops a routing run the way the cap does.** An authentication or permission error, an unknown model ID (`not found`), a parameter the provider does not take (every call sends the same ones) or missing credentials (with `claude-cli`: not logged in, a usage limit, no `claude` binary; with AWS: "Unable to locate credentials", a missing config profile or an expired SSO session, whichever class litellm wraps it in) would fail every later call alike, so the run stops at that call, keeps the rows made before it and writes the partial result below, with `"reason": "permanent_error"` and the error text as the message (`--max-usd` is not involved; the exit line gives `calls_done` of `calls_planned`). Any other failure is one failed row and the run goes on: a refusal, a request one query makes too long, an unparseable reply, an error the client does not recognise, a transient error that ran out of retries. Such a failed row or item is a model call that failed and the run went on: `skill routing`, `skill novelty atoms`, `probe` and `analyze` write their result and then exit 1 (an atom extraction call or a probe wording call that raised; a reply that does not parse is not one, and exits 0 as before). `skill novelty atoms`, `probe` and `analyze` and `skill shorten` stop the same way at the first such error in an atom extraction call, the faithfulness check, a probe wording, an answer, a grade, a value or conflict batch or a retention adjudication, and keep what they paid for as they do at the cap, with `"reason": "permanent_error"`; a refusal, an unparseable reply or a request one item makes too long is still one failed item. **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 exits 3 with the -cap message and the path of the file (1 for a `permanent_error` stop, and for an all-vs-all run with a failed model call, whose message then ends with `N of M model call(s) failed, so this exits 1`). The file carries +cap message and the path of the file (1 for a `permanent_error` stop, and for a run with a failed model call, whose message then names the failed calls and ends with `so this exits 1`). 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` diff --git a/dokimi/dokimi/commands/novelty.py b/dokimi/dokimi/commands/novelty.py index 0e63ff5c8..d29e2cfd7 100644 --- a/dokimi/dokimi/commands/novelty.py +++ b/dokimi/dokimi/commands/novelty.py @@ -41,7 +41,12 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: render_novelty_markdown, ) - from dokimi.commands.novelty_budget import print_estimate_only, print_run_estimate + from dokimi.commands.novelty_budget import ( + analyze_failed_calls, + exit_if_calls_failed, + print_estimate_only, + print_run_estimate, + ) from dokimi.novelty import cli_preset cli_preset.apply(args) @@ -117,12 +122,18 @@ def cmd_novelty_analyze(args: argparse.Namespace) -> None: print(f"OK Saved atom verdicts: {atom_verdicts_path}") print(f"OK Saved atoms: {atoms_path}") _print_headline(result.artifact) + exit_if_calls_failed(analyze_failed_calls(result), out_json) def cmd_novelty_atoms(args: argparse.Namespace) -> None: """Extract atoms and spans only — the expensive stage, cached for reuse.""" from dokimi.novelty import cost - from dokimi.commands.novelty_budget import save_atoms_run, verify_or_partial + from dokimi.commands.novelty_budget import ( + exit_if_calls_failed, + failed_calls_note, + save_atoms_run, + verify_or_partial, + ) from dokimi.novelty.atoms import ExtractionError, ExtractionReport, extract_atoms, sample_atoms from dokimi.novelty.report import cap_warning from dokimi.novelty.spans import segment, span_summary @@ -147,11 +158,13 @@ def cmd_novelty_atoms(args: argparse.Namespace) -> None: if settings.values["verify_faithfulness"] and partial is None: partial = verify_or_partial(sample, spans, extractor) out = Path(args.out) if args.out else default_dir(args.artifact) / "atoms.json" - save_atoms_run(atoms, spans, out, partial, extractor=extractor.model, + failed = failed_calls_note(extraction, n_spans=len(spans)) + save_atoms_run(atoms, spans, out, partial, failed=failed, extractor=extractor.model, extractor_provider=extractor.provider, cap=cap, bundle=artifact_bundle.summary(), extraction=extraction, sample=sample) print(f"OK Saved {len(atoms)} atoms ({len(sample)} sampled) over {len(spans)} spans: {out}") print(json.dumps(span_summary(spans, atoms), indent=2)) + exit_if_calls_failed(failed, out) def cmd_novelty_probe(args: argparse.Namespace) -> None: @@ -165,7 +178,7 @@ def cmd_novelty_probe(args: argparse.Namespace) -> None: from dokimi.novelty.measure import SelfJudgeError, check_self_judge, run_measurement from dokimi.novelty.probes import build_probe_set from dokimi.novelty.report import build_probe_record - from dokimi.commands.novelty_budget import save_probe_measure + from dokimi.commands.novelty_budget import exit_if_calls_failed, failed_calls_note, save_probe_measure from dokimi.novelty import cli_preset preset = cli_preset.apply(args, report=False) # roles and refusals now; the warnings once the key is known @@ -225,7 +238,8 @@ def cmd_novelty_probe(args: argparse.Namespace) -> None: stamp(payload, args, result, answerer=answerer, judge=judge, judge2=judge2) out = Path(args.out) if args.out else default_dir(args.artifact) / "probes.json" # A run the cap stopped keeps the answers it paid for, as a partial result (and exits). - save_probe_measure(payload, out, result) + failed = failed_calls_note(probe_set=probe_set) + save_probe_measure(payload, out, result, failed) print(f"OK Saved {len(result.runs)} probe runs: {out}") for scoring in ("lenient", "strict"): row = payload["paired"][scoring] @@ -234,6 +248,7 @@ def cmd_novelty_probe(args: argparse.Namespace) -> None: f"degraded {row['degraded']} still-missing {row['still_missing']} " f"(n={row['n_paired']})" ) + exit_if_calls_failed(failed, out) def _write_item_analysis(payload: dict, out: Path) -> None: diff --git a/dokimi/dokimi/commands/novelty_budget.py b/dokimi/dokimi/commands/novelty_budget.py index 3bfa51adb..fa5e66dfc 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -63,10 +63,42 @@ 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 = "", *, reason: str) -> NoReturn: +def exit_partial(summary: str, path: Path, note: str = "", *, reason: str, failed: 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) + stop's (``partial["reason"]``) and picks the exit code (:func:`partial_exit_code`). A model call that + failed earlier in the run (``failed``, from :func:`failed_calls_note`) ends the message and makes the + exit 1, as :func:`~dokimi.commands.novelty_routing_report.stop_if_partial` does.""" + message = f"{summary}; the partial result is in {path}{note}" + if failed: + message, reason = f"{message}; {failed}, so this exits 1", "failed_calls" + stop_partial(message, reason) + + +# mutation-ok[bump-int]: n_spans only words the extraction part, which every caller that passes one also gives it +def failed_calls_note(extraction=None, probe_set=None, n_spans: int = 0) -> str: + """What model calls failed in a run that went on, or ``""``: the extraction calls that left spans unread + (``extraction``, an :class:`~dokimi.novelty.atoms.ExtractionReport`) and the wording calls that raised + (``probe_set``). A reply that did not parse is not a failed call.""" + parts = [] + if extraction is not None and extraction.failed_spans: + parts.append(f"{extraction.failed_spans} of {n_spans} spans were lost to extraction calls that " + f"failed (last error: {extraction.call_error})") + if probe_set is not None and probe_set.failed_calls: + parts.append(f"{len(probe_set.failed_calls)} wording call(s) failed " + f"(last error: {probe_set.failed_calls[-1]})") + return "; ".join(parts) + + +def analyze_failed_calls(result) -> str: + """:func:`failed_calls_note` of an :class:`~dokimi.novelty.analyze.AnalyzeResult`.""" + return failed_calls_note(getattr(result, "extraction", None), getattr(result, "probe_set", None), + len(getattr(result, "spans", ()))) + + +def exit_if_calls_failed(failed: str, path: Path) -> None: + """Exit 1 once the result is written and printed when a model call failed and the run went on.""" + if failed: + stop_partial(f"{failed}; the result is in {path}, so this exits 1", "failed_calls") def response_cache_active() -> bool: @@ -111,8 +143,9 @@ def save_analyze_partial(result, out: Path) -> NoReturn: partial = result.partial cause = partial.get("cause") summary = f"{partial['message']} ({cause})" if cause else partial["message"] + failed = analyze_failed_calls(result) exit_partial(summary, write_run(result.artifact, out, partial), - replay_hint(partial["reason"]), reason=partial["reason"]) + replay_hint(partial["reason"]), reason=partial["reason"], failed=failed) def write_run(payload: dict, out: Path, partial: dict | None = None) -> Path: @@ -135,12 +168,12 @@ def write_run(payload: dict, out: Path, partial: dict | None = None) -> Path: def save_probe_run(payload: dict, out: Path, *, done: int, not_run: int, - stop: tuple[str, str] | None = None, ungraded: int = 0) -> Path: + stop: tuple[str, str] | None = None, ungraded: int = 0, failed: str = "") -> Path: """Write a probe measurement; one the cap stopped keeps its ``done`` answers and exits. ``stop`` is the reason and message of the call the cap refused: a call with no known price is named as such, not as a ``--max-usd`` stop. ``ungraded`` answers were paid for and kept, - but never graded, so the file is partial too.""" + but never graded, so the file is partial too. ``failed`` is :func:`failed_calls_note`.""" if not not_run and not ungraded: return write_run(payload, out) reason, cause = stop or ("spend_cap", "") @@ -159,18 +192,18 @@ 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), reason=reason) + exit_partial(message, write_run(payload, out, partial), reason=reason, failed=failed) -def save_probe_measure(payload: dict, out: Path, result) -> Path: +def save_probe_measure(payload: dict, out: Path, result, failed: str = "") -> Path: """Save a probe measurement from its :class:`~dokimi.novelty.measure.MeasureResult`.""" return save_probe_run(payload, out, done=len(result.runs), not_run=result.not_run, - stop=result.stop, ungraded=result.ungraded) + stop=result.stop, ungraded=result.ungraded, failed=failed) -def save_atoms_run(atoms, spans, out: Path, partial: dict | None, **record) -> Path: +def save_atoms_run(atoms, spans, out: Path, partial: dict | None, *, failed: str = "", **record) -> Path: """Save an atom set (:func:`~dokimi.novelty.atoms.save_atoms`); a cap-stopped one goes beside - ``out`` and exits.""" + ``out`` and exits (1 when a model call ``failed`` too).""" from dokimi.novelty.atoms import save_atoms if not partial: @@ -178,7 +211,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, reason=partial["reason"]) + exit_partial(partial["message"], dest, reason=partial["reason"], failed=failed) 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 cf1670721..3c244f837 100644 --- a/dokimi/dokimi/commands/novelty_routing.py +++ b/dokimi/dokimi/commands/novelty_routing.py @@ -33,6 +33,7 @@ routing_queries, save_result, stop_if_partial, + stop_partial, warn_blind_skills, ) from dokimi.files import InputError @@ -159,18 +160,38 @@ def cmd_routing(args: argparse.Namespace) -> tuple[dict, Path, str] | None: ) payload["cost"] = roll_up_cost([selector]) + failed = _mark_failed_calls(payload) out = save_result(payload, out, payload.get("model", {})) try: + # A failed model call is a runtime failure (exit 1) even when the cap stopped the run too. stop_if_partial(payload, out, - lambda: print_routing_summary(payload, len(competitors), self_derived)) + lambda: print_routing_summary(payload, len(competitors), self_derived), failed) except SystemExit as stop: raise RoutingStopped(stop, payload, out, gold.name) from None print(f"OK Saved routing measurement: {out}") print_routing_summary(payload, len(competitors), self_derived) + if failed: + try: + stop_partial(f"{failed}; the result, with status partial, leaves the failed calls out of the " + f"rates and is in {out}", "failed_calls") + except SystemExit as stop: + raise RoutingStopped(stop, payload, out, gold.name) from None return payload, out, gold.name +def _mark_failed_calls(payload: dict) -> str: + """``N of M model call(s) failed (first error: ...)`` when a call of the model arm failed and the run + went on, else ``""``. The result then has status ``partial``, as one the cap stopped has.""" + model = payload.get("model") or {} + if not model.get("n_failed"): + # mutation-ok[return-none]: the caller reads the empty string and None alike, as false + return "" + payload["status"] = "partial" + error = next(row["error"] for row in model["per_query"] if row.get("error")) + return f"{model['n_failed']} of {model['n_calls']} model call(s) failed (first error: {error})" + + 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.""" @@ -210,8 +231,11 @@ def cmd_skill_routing(args: argparse.Namespace) -> None: cost["remaining_usd"] = round(cost["cap_usd"] - cost["spent_usd"], 6) partial = payload.get("partial") status = "complete" if partial is None else ("budget_stopped" if partial["reason"] in ("spend_cap", "call_cap") else "partial") + reason = partial and partial["message"] + if partial is None and stopped is not None: # a failed model call, no cap + status, reason = "partial", str(stopped) cli_output.emit_leaf( - "skill routing", payload, status=status, reason=partial and partial["message"], + "skill routing", payload, status=status, reason=reason, subjects=[{"subject": skill, "verdict": None}], summary={"queries_self_derived": payload["queries_self_derived"], "n_candidates": payload["n_candidates"], "lexical_recall_at_1": lexical.get("recall_at_1"), "model_selection_rate": model.get("selection_rate")}, diff --git a/dokimi/dokimi/novelty/analyze.py b/dokimi/dokimi/novelty/analyze.py index 09053fb84..bd7485ed4 100644 --- a/dokimi/dokimi/novelty/analyze.py +++ b/dokimi/dokimi/novelty/analyze.py @@ -125,6 +125,8 @@ class AnalyzeResult: #: Ids of the atoms the conflict check never compared with anything, and the extraction report. unchecked: list = field(default_factory=list) extraction: object | None = None + #: The wordings (:class:`~dokimi.novelty.probes.ProbeSet`), with the calls that failed to make them. + probe_set: object | None = None def kind_agreement_warnings(rows: dict[str, dict]) -> list[str]: @@ -242,7 +244,7 @@ def analyze( return AnalyzeResult( artifact=record, atoms=progress.atoms, spans=progress.spans, measure_result=progress.measure_result, extracted_atoms=progress.extracted, - partial=record["partial"]) + partial=record["partial"], extraction=progress.extraction, probe_set=progress.probe_set) @dataclass @@ -419,6 +421,12 @@ def _verify_and_probe(sampled: _Sampled, config: AnalyzeConfig, *, extractor: LL # reversed, corrupts the answer key the judge grades against. Rejects are dropped, # but a high reject rate also means the kind it hit was measured on a thinner probe # budget than the run claims, so it has to be visible. + if probe_set.failed_calls: + warnings.append( + f"{len(probe_set.failed_calls)} wording call(s) failed (last error: " + f"{probe_set.failed_calls[-1]}); the atoms in them have no reworded probe, and count " + "as rejected wordings" + ) for kind, row in probe_set.fidelity.items(): if row["generated"] and row["rejected"] / row["generated"] > 0.2: warnings.append( @@ -662,6 +670,7 @@ def _assemble(sampled: _Sampled, probed: _Probed, measured: _Measured, classifie conflicts=classified.conflicts, unchecked=classified.unchecked, extraction=sampled.extraction, + probe_set=probed.probe_set, ) diff --git a/dokimi/dokimi/novelty/atoms.py b/dokimi/dokimi/novelty/atoms.py index c0010b8a9..f089d449e 100644 --- a/dokimi/dokimi/novelty/atoms.py +++ b/dokimi/dokimi/novelty/atoms.py @@ -222,6 +222,12 @@ def last_error(self) -> str: return self.call_error or self.parse_error or self.unusable_error return _EMPTY_REPLY if self.empty_span_ids else "" + @property + def failed_spans(self) -> int: + """How many spans a call that failed left unread (a cap's own are not among them).""" + unread = self.pre_cap[0] if self.pre_cap else len(self.unread_span_ids) + return unread - len(self.unparseable_span_ids) - len(self.empty_span_ids) - len(self.unusable_span_ids) + def warnings(self, n_spans: int) -> list[str]: """Artifact warnings: spans left unread, and the calls re-asking cost. Spans a cap stopped are left out: the exit names them.""" @@ -231,7 +237,7 @@ def warnings(self, n_spans: int) -> list[str]: unparseable = len(self.unparseable_span_ids) empty = len(self.empty_span_ids) unusable = len(self.unusable_span_ids) - failed = unread - unparseable - empty - unusable + failed = self.failed_spans causes = [] if unparseable: causes.append( diff --git a/dokimi/dokimi/novelty/probes.py b/dokimi/dokimi/novelty/probes.py index f53459b11..a0e513d3e 100644 --- a/dokimi/dokimi/novelty/probes.py +++ b/dokimi/dokimi/novelty/probes.py @@ -39,7 +39,7 @@ from dokimi.files import InputError from .atoms import Atom -from .client import LLMClient, SpendCapReached +from .client import LLMClient, OutputTruncated, SpendCapReached, accepting from .routing_stop import stop_if_run_wide PROBE_KINDS = ("direct", "paraphrase", "reversal") @@ -232,6 +232,9 @@ class ProbeSet: #: ``{kind: {generated, kept, rejected, reasons: {reason: n}, rejected_examples: [...]}}``; #: at most :data:`MAX_REJECTED_EXAMPLES` examples, while ``reasons`` counts every one. fidelity: dict[str, dict] = field(default_factory=dict) + #: One ``Type: message`` per wording call that failed (an error, not a malformed reply); its + #: atoms count as rejected wordings in ``fidelity``. + failed_calls: list[str] = field(default_factory=list) def malformed_rate(self, kind: str | None = None) -> float: """Share of generated wordings rejected, over one kind or all of them.""" @@ -548,7 +551,8 @@ def tally(kind: str, atom: Atom, source: str, candidate: str, reasons: list[str] return False if paraphrases: - for chunk, worded in _worded(client, _PARAPHRASE_PROMPT, atoms, batch, "question"): + for chunk, worded in _worded(client, _PARAPHRASE_PROMPT, atoms, batch, "question", + built.failed_calls): for atom, question in zip(chunk, worded, strict=False): reasons = check_wording( "paraphrase", source=atom.question, candidate=question, @@ -559,7 +563,8 @@ def tally(kind: str, atom: Atom, source: str, candidate: str, reasons: list[str] question=question.strip(), expected=atom.answer, grading=atom_grading(atom))) if reversals: - for chunk, worded in _worded(client, _REVERSAL_PROMPT, atoms, batch, "statement"): + for chunk, worded in _worded(client, _REVERSAL_PROMPT, atoms, batch, "statement", + built.failed_calls): for atom, question in zip(chunk, worded, strict=False): reasons = check_wording( "reversal", source=atom.statement, candidate=question, @@ -610,7 +615,7 @@ def _chunks(items: list, size: int) -> list[list]: return [items[i:i + size] for i in range(0, len(items), size)] -def _generate(client: LLMClient, template: str, lines: list[str]) -> list[str]: +def _generate(client: LLMClient, template: str, lines: list[str], failed: list[str]) -> list[str]: """One wording per input line, aligned by position. The result always has ``len(lines)`` entries. A failed call, a truncated array or a row @@ -618,19 +623,33 @@ def _generate(client: LLMClient, template: str, lines: list[str]) -> list[str]: rejected wording. That keeps the malformed rate counted per *atom asked for*: a generator that produced nothing must not read as a perfect run, and it must not be indistinguishable from "no generator was available". + + A call that raised adds its error to ``failed``, whatever its type: the call and the parse of its + reply are separate steps, so a transport's ``ValueError`` counts and a reply that did not parse + (or was cut at the output ceiling, :class:`OutputTruncated`) does not. """ + from dokimi.llm_json import extract_json_array + numbered = "\n".join(f"{i + 1}. {line}" for i, line in enumerate(lines)) key = "questions" if "{questions}" in template else "statements" + rows: list = [] try: - rows = client.json_array(template.format(**{key: numbered})) - except Exception: # noqa: BLE001 - a failed rewording call leaves the lines unworded + reply = client.text(template.format(**{key: numbered}), accept=accepting(extract_json_array)) + except Exception as exc: # noqa: BLE001 - a failed rewording call leaves the lines unworded stop_if_run_wide() # raises a permanent stop; any other failure is a chunk of rejected wordings - rows = [] + if not isinstance(exc, OutputTruncated): + # mutation-ok[bump-int]: the cut only keeps a long message short + failed.append(f"{type(exc).__name__}: {str(exc)[:120]}") + else: + try: + rows = extract_json_array(reply) + except ValueError: # a reply that is no array leaves the lines unworded, and is no failed call + pass return _aligned(rows, len(lines)) def _worded(client: LLMClient, template: str, atoms: list, batch: int, - field_name: str) -> Iterator[tuple[list, list[str]]]: + field_name: str, failed: list[str]) -> Iterator[tuple[list, list[str]]]: """Each chunk of ``atoms`` with its wordings. A call with no price was paid for: its reply's wordings are yielded, and the stop is raised once the caller has kept them.""" from dokimi.llm_json import extract_json_array @@ -638,7 +657,7 @@ def _worded(client: LLMClient, template: str, atoms: list, batch: int, for chunk in _chunks(atoms, batch): lines = [getattr(atom, field_name) for atom in chunk] try: - worded = _generate(client, template, lines) + worded = _generate(client, template, lines, failed) except SpendCapReached as stop: if not stop.reply: raise diff --git a/dokimi/tests/test_failed_call_exit.py b/dokimi/tests/test_failed_call_exit.py new file mode 100644 index 000000000..90676d246 --- /dev/null +++ b/dokimi/tests/test_failed_call_exit.py @@ -0,0 +1,277 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""A model call that failed and did not stop the run makes the command exit 1, after the result is written. + +docs/quickstart.md, exit codes: exit 1 is "a model call that failed and the run went on". The four commands +(`skill routing`, `skill novelty atoms|probe|analyze`) absorb a call that raises an unforeseen error; they +used to exit 0 (and `skill routing` wrote status ok) with it. +""" + +from __future__ import annotations + +import json +import re +import sys + +import pytest + +from dokimi import cli, llm +from tests.cli_paths import novelty_argv + +SETTINGS = "\n\n".join(f"Setting number {i} defaults to {i * 10}." for i in range(1, 201)) + "\n" +SMALL = "\n\n".join(f"Setting number {i} defaults to {i * 10}." for i in range(1, 7)) + "\n" + + +class Unforeseen(Exception): + """An exception type nothing in dokimi expects (not a litellm one).""" + + +def _atoms_reply(prompt: str) -> str: + rows = [{"statement": f"{sid} holds a default.", "question": f"What of {sid}?", "answer": "a value", + "kind": "proposition", "tags": [], "span_ids": [sid]} + for sid in re.findall(r"^\[(s\d+)\]", prompt, flags=re.M)] + return json.dumps(rows) + + +def _respond(fail_on: str | None = None, nth: int = 2): + """Answers each prompt by what it asks; the ``nth`` prompt containing ``fail_on`` (any, when None) raises.""" + seen: list[str] = [] + + def respond(request): + prompt = llm.prompt_text(request) + if fail_on is None or fail_on in prompt: + seen.append(prompt) + if len(seen) == nth: + raise Unforeseen("the provider returned something unforeseen") + if "Extract the checkable knowledge" in prompt: + return _atoms_reply(prompt) + if "Reword each question" in prompt or "Rewrite each statement" in prompt: + count = len(re.findall(r"^\d+\. ", prompt, flags=re.M)) + return json.dumps([f"Which value does setting {i} take by default?" for i in range(count)]) + if "verdict" in prompt: + return json.dumps({"verdict": "correct_complete"}) + return json.dumps({"pick": 1}) + + return respond + + +def _run(monkeypatch, argv, respond) -> int | str | None: + monkeypatch.setattr(sys, "argv", ["dokimi", *argv]) + with llm.use_adapter(llm.FakeAdapter(respond=respond)): + try: + cli.main() + except SystemExit as stop: + return stop.code + return 0 + + +def _routing_argv(tmp_path): + for name, desc in {"a": "profile a binary with perf", "b": "tune a database"}.items(): + (tmp_path / name).mkdir() + (tmp_path / name / "SKILL.md").write_text( + f"---\nname: {name}\ndescription: {desc}\n---\n\n# B\n", encoding="utf-8") + queries = tmp_path / "q.json" + queries.write_text(json.dumps(["profile a binary", "tune a slow query", "record a perf profile"]), + encoding="utf-8") + out = tmp_path / "routing.json" + return [*novelty_argv("routing"), f"skill:{tmp_path / 'a'}", "--competitors", f"skill:{tmp_path / 'b'}", + "--queries", str(queries), "--model", "m", "--out", str(out)], out + + +def test_skill_routing_with_one_failed_call_writes_a_partial_result_and_exits_1(tmp_path, monkeypatch, capsys): + argv, out = _routing_argv(tmp_path) + assert _run(monkeypatch, argv, _respond(nth=2)) == 1 + result = json.loads(out.read_text(encoding="utf-8")) + assert result["status"] == "partial" + assert (result["model"]["n_failed"], result["model"]["n_calls"]) == (1, 3) + assert "1 of 3 model call(s) failed (first error: the provider returned something unforeseen)" in capsys.readouterr().err + + +def test_skill_routing_without_a_failed_call_exits_0_with_status_ok(tmp_path, monkeypatch): + argv, out = _routing_argv(tmp_path) + assert _run(monkeypatch, argv, _respond(nth=99)) == 0 + assert json.loads(out.read_text(encoding="utf-8"))["status"] == "ok" + + +def test_skill_routing_json_reports_a_failed_call_as_partial_and_still_exits_1(tmp_path, monkeypatch, capsys): + argv, out = _routing_argv(tmp_path) + assert _run(monkeypatch, [*argv, "--json"], _respond(nth=2)) == 1 + document = json.loads(capsys.readouterr().out) + assert document["status"] == "partial" + assert "1 of 3 model call(s) failed" in document["reason"] + assert json.loads(out.read_text(encoding="utf-8"))["status"] == "partial" + + +def test_skill_routing_json_of_a_clean_run_is_complete_and_of_a_capped_run_budget_stopped( + tmp_path, monkeypatch, capsys): + from dokimi.metrics.usage import UsageRecord + + argv, _ = _routing_argv(tmp_path) + assert _run(monkeypatch, [*argv, "--json"], _respond(nth=99)) == 0 + clean = json.loads(capsys.readouterr().out) + assert (clean["status"], clean["reason"]) == ("complete", None) + (tmp_path / "q.json").write_text(json.dumps(["profile a binary", "tune a slow query", + "record a perf profile", "add an index"]), encoding="utf-8") + monkeypatch.setattr(llm, "llm_call_with_usage", lambda prompt, model, **_kw: ('{"pick": 1}', UsageRecord(cost_usd=0.6))) + assert _run(monkeypatch, [*argv, "--json", "--max-usd", "1"], _respond(nth=99)) == 3 + capped = json.loads(capsys.readouterr().out) + assert capped["status"] == "budget_stopped" + assert capped["reason"].startswith("spend cap reached") + + +def test_a_failed_call_that_a_cap_stop_meets_still_exits_1_for_skill_routing(tmp_path, monkeypatch): + from dokimi.metrics.usage import UsageRecord + + argv, out = _routing_argv(tmp_path) + (tmp_path / "q.json").write_text(json.dumps(["profile a binary", "tune a slow query", + "record a perf profile", "add an index"]), encoding="utf-8") + calls: list[str] = [] + + def stub(prompt, model, **_kwargs): + calls.append(prompt) + if len(calls) == 1: + raise Unforeseen("rate limited") + return '{"pick": 1}', UsageRecord(cost_usd=0.6) + + monkeypatch.setattr(llm, "llm_call_with_usage", stub) + monkeypatch.setattr(sys, "argv", ["dokimi", *argv, "--max-usd", "1"]) + with pytest.raises(SystemExit) as stop: + cli.main() + assert stop.value.code == 1 + assert "1 of 3 model call(s) failed" in str(stop.value) + assert json.loads(out.read_text(encoding="utf-8"))["partial"]["reason"] == "spend_cap" + + +def _atoms_argv(tmp_path, text): + artifact = tmp_path / "rows.md" + artifact.write_text(text, encoding="utf-8") + return [*novelty_argv("atoms"), "--artifact", str(artifact), "--model", "m", + "--out", str(tmp_path / "atoms.json")], artifact + + +def test_novelty_atoms_with_a_failed_extraction_call_writes_atoms_json_and_exits_1(tmp_path, monkeypatch, capsys): + argv, _ = _atoms_argv(tmp_path, SETTINGS) + assert _run(monkeypatch, argv, _respond(nth=2)) == 1 + record = json.loads((tmp_path / "atoms.json").read_text(encoding="utf-8")) + assert len(record["extraction"]["unread_span_ids"]) == 25 + assert "25 of 200 spans were lost to extraction calls that failed" in capsys.readouterr().err + + +def test_novelty_atoms_without_a_failed_call_exits_0(tmp_path, monkeypatch): + argv, _ = _atoms_argv(tmp_path, SETTINGS) + assert _run(monkeypatch, argv, _respond(nth=99)) == 0 + + +def _probe_argv(tmp_path, monkeypatch): + argv, artifact = _atoms_argv(tmp_path, SMALL) + assert _run(monkeypatch, argv, _respond(nth=99)) == 0 + return [*novelty_argv("probe"), "--artifact", str(artifact), "--atoms", str(tmp_path / "atoms.json"), + "--model", "m", "--judge-model", "j", "--out", str(tmp_path / "probes.json")] + + +def test_novelty_probe_with_a_failed_wording_call_writes_probes_json_and_exits_1(tmp_path, monkeypatch, capsys): + argv = _probe_argv(tmp_path, monkeypatch) + assert _run(monkeypatch, argv, _respond("Rewrite each statement", nth=1)) == 1 + assert json.loads((tmp_path / "probes.json").read_text(encoding="utf-8"))["paired"] + assert "1 wording call(s) failed (last error: Unforeseen: the provider returned something unforeseen)" in capsys.readouterr().err + + +def test_novelty_probe_with_a_wording_transport_raising_value_error_is_a_failed_call_and_exits_1( + tmp_path, monkeypatch, capsys): + argv = _probe_argv(tmp_path, monkeypatch) + + def respond(request): + if "Rewrite each statement" in llm.prompt_text(request): + raise ValueError("provider failure") + return _respond(nth=99)(request) + + assert _run(monkeypatch, argv, respond) == 1 + assert "1 wording call(s) failed (last error: ValueError: provider failure)" in capsys.readouterr().err + + +def test_novelty_probe_with_a_malformed_wording_reply_is_no_failed_call_and_exits_0(tmp_path, monkeypatch): + argv = _probe_argv(tmp_path, monkeypatch) + + def respond(request): + prompt = llm.prompt_text(request) + return "not a json array" if "Rewrite each statement" in prompt else _respond(nth=99)(request) + + assert _run(monkeypatch, argv, respond) == 0 + assert (tmp_path / "probes.json").exists() + + +def test_a_wording_reply_cut_at_the_output_ceiling_is_no_failed_call(): + from dokimi.metrics.usage import UsageRecord + from dokimi.novelty.client import LLMClient + from dokimi.novelty.probes import _generate + + client = LLMClient(model="m", transport=lambda prompt, system: ('["a", "b', UsageRecord(truncated=True))) + failed: list[str] = [] + assert _generate(client, "Reword each question:\n{questions}", ["q1", "q2"], failed) == ["", ""] + assert failed == [] + + +def test_novelty_probe_without_a_failed_call_exits_0(tmp_path, monkeypatch): + argv = _probe_argv(tmp_path, monkeypatch) + assert _run(monkeypatch, argv, _respond(nth=99)) == 0 + + +def _analyze_argv(tmp_path): + artifact = tmp_path / "rows.md" + artifact.write_text(SMALL, encoding="utf-8") + return [*novelty_argv("analyze"), "--artifact", str(artifact), "--model", "m", "--judge-model", "j", + "--out-dir", str(tmp_path / "out")] + + +def test_novelty_analyze_with_a_failed_wording_call_writes_its_artifact_and_exits_1(tmp_path, monkeypatch, capsys): + argv = _analyze_argv(tmp_path) + assert _run(monkeypatch, argv, _respond("Rewrite each statement", nth=1)) == 1 + artifact = json.loads((tmp_path / "out" / "novelty.json").read_text(encoding="utf-8")) + assert any("1 wording call(s) failed" in warning for warning in artifact["warnings"]) + assert "1 wording call(s) failed" in capsys.readouterr().err + + +def test_novelty_analyze_without_a_failed_call_exits_0(tmp_path, monkeypatch): + assert _run(monkeypatch, _analyze_argv(tmp_path), _respond(nth=99)) == 0 + + +FAILED = "1 wording call(s) failed (last error: Unforeseen: x)" + + +@pytest.mark.parametrize("failed, code", [("", 3), (FAILED, 1)]) +def test_a_probe_the_cap_stopped_exits_1_when_a_call_failed_too(tmp_path, failed, code): + from dokimi.commands.novelty_budget import save_probe_run + + with pytest.raises(SystemExit) as stop: + save_probe_run({"runs": []}, tmp_path / "probes.json", done=1, not_run=1, + stop=("spend_cap", "cap"), failed=failed) + assert stop.value.code == code + assert str(stop.value).endswith(f"; {FAILED}, so this exits 1") == bool(failed) + + +@pytest.mark.parametrize("failed, code", [("", 3), (FAILED, 1)]) +def test_an_atoms_run_the_cap_stopped_exits_1_when_a_call_failed_too(tmp_path, monkeypatch, failed, 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 *args, **kwargs: None) + with pytest.raises(SystemExit) as stop: + save_atoms_run([], [], tmp_path / "atoms.json", {"reason": "spend_cap", "message": "cap"}, failed=failed) + assert stop.value.code == code + + +@pytest.mark.parametrize("failed_spans, code", [(0, 3), (2, 1)]) +def test_an_analyze_the_cap_stopped_exits_1_when_extraction_calls_failed_too(tmp_path, failed_spans, code): + from types import SimpleNamespace + + from dokimi.commands.novelty_budget import save_analyze_partial + + extraction = SimpleNamespace(failed_spans=failed_spans, call_error="Unforeseen: x") + partial = {"reason": "spend_cap", "message": "the measurement stopped"} + result = SimpleNamespace(partial=partial, artifact={"runs": []}, extraction=extraction, probe_set=None, + spans=[1, 2, 3]) + with pytest.raises(SystemExit) as stop: + save_analyze_partial(result, tmp_path / "novelty.json") + assert stop.value.code == code + assert ("2 of 3 spans were lost to extraction calls that failed" in str(stop.value)) == bool(failed_spans) diff --git a/dokimi/tests/test_novelty_routing_cost.py b/dokimi/tests/test_novelty_routing_cost.py index 9387895f3..66c4d7e46 100644 --- a/dokimi/tests/test_novelty_routing_cost.py +++ b/dokimi/tests/test_novelty_routing_cost.py @@ -7,6 +7,8 @@ import json +import pytest + from dokimi.cli import build_parser @@ -104,7 +106,10 @@ def failing(prompt, model, **_kwargs): raise RuntimeError("provider refused") monkeypatch.setattr(llm, "llm_call_with_usage", failing) - payload = _model_run(tmp_path) + with pytest.raises(SystemExit) as stop: # a failed model call makes the run exit 1, after the result is written + _model_run(tmp_path) + assert stop.value.code == 1 + payload = json.loads((tmp_path / "routing.json").read_text(encoding="utf-8")) assert payload["cost"]["llm_calls"] == 0 assert payload["cost"]["usd"] is None # no calls: nothing known, not "free" out = capsys.readouterr().out