diff --git a/.agents/skills/openultrasast-scan/SKILL.md b/.agents/skills/openultrasast-scan/SKILL.md index 9ffd08db..37ede3c9 100644 --- a/.agents/skills/openultrasast-scan/SKILL.md +++ b/.agents/skills/openultrasast-scan/SKILL.md @@ -68,6 +68,12 @@ Each entry in `manifest.json` `degradations` is `{"stage": ..., "reason": ...}`. - `learning_endpoint_unavailable` (stage `model`): no provider key resolved. The graph's entailed findings are still reported; the residual question is skipped. This is recorded in `manifest.json` but has no line in `report.md`'s "What could not be analysed" section. +- `judge_calls_failed` (stage `model`): `count` judge calls gave no decision, because the endpoint sent no + answer or nothing the scan can read as one. Each dropped its claim as a `no` would, so its finding is not + in the report; that is not a refutation. The first call that gets no answer from the endpoint ends the + asking, and `judge_withheld` (stage `model`) follows it: `questions` counts the judge calls refused after + that failure in the question being put; no question after it was put to the judge either. Both have a line + under "What could not be analysed". - `hunter_model_unavailable` (stage `map`): `[models] hunter` is unset, so the tool hunter did not run. Recorded on every standard scan without that setting; it is expected, not an error. - `ledger_not_written` (stage `record_calibration`): the scan rejected or held a finding and could not write the diff --git a/src/openultrasast/model/pipeline.py b/src/openultrasast/model/pipeline.py index 70cedb5a..e162d7d6 100644 --- a/src/openultrasast/model/pipeline.py +++ b/src/openultrasast/model/pipeline.py @@ -209,6 +209,15 @@ def _ask(client: Any, model: str, question: str) -> bool | None: except Exception as exc: # noqa: BLE001 — an endpoint failure is a degradation, never a verdict logger.warning("judge call failed: %s", exc) return None + return judge_decision(response) + + +def judge_decision(response: Any) -> bool | None: + """What the judge decided, or `None` when its answer holds no decision. + + `None` is also what a call that raised amounts to, and both drop the claim: the driver counts them + alike (`model.scan._CountingClient`), because a reader who is not told cannot tell that from a `no`. + """ content = getattr(response, "content", None) if not isinstance(content, str) or not content.strip(): return None @@ -245,4 +254,4 @@ def _site(path: str, function: str, verdict: Verdict) -> str: return f"{path or '?'}:{line}:{function or '?'}" -__all__ = ["CANDIDATE_QUESTION", "MAX_JUDGED_CANDIDATES", "ModelFinding", "residual_question", "scan_region"] +__all__ = ["CANDIDATE_QUESTION", "MAX_JUDGED_CANDIDATES", "ModelFinding", "judge_decision", "residual_question", "scan_region"] diff --git a/src/openultrasast/model/scan.py b/src/openultrasast/model/scan.py index 668f0e99..cf698054 100644 --- a/src/openultrasast/model/scan.py +++ b/src/openultrasast/model/scan.py @@ -46,7 +46,7 @@ from .evidence import TIER_EXCLUDE, Evidence, evidence_from_rows from .ladder import Rung from .layout import is_vendored, layout_facts, with_layout from .partitions import PartitionCoverage, build_partitions -from .pipeline import ModelFinding, scan_region +from .pipeline import ModelFinding, judge_decision, scan_region from .regions import MODULE_SCOPE, ScanRegion, affected_context from .specs import ConfigSpec, DominanceSpec, TaintSpec, config_specs, dominance_specs, taint_specs from .taint import request_params as taint_params @@ -106,7 +106,8 @@ class ModelScanResult: regions_scanned: int = 0 regions_unjudged: int = 0 # Arbitrated by the graph, but with the judge withheld because the budget was spent. Not the same as - # unjudged, and not the same as clean. + # unjudged, and not the same as clean. A judge that could not be reached is counted apart, as + # `judge_withheld`. regions_unasked: int = 0 model_calls: int = 0 cost_usd: float = 0.0 @@ -544,9 +545,10 @@ def _scan_repository_impl( if rid not in rows_by_id: continue exhausted = counted is not None and counted.calls >= limits.max_model_calls + unreachable = counted is not None and counted.unreachable family = getattr(spec, "family", "") prefetched = CpgResult(cpg_path=cpg.cpg_path, run=_prefetched(rows_by_id.get(rid, []))) - judge = None if exhausted else counted + judge = None if exhausted or unreachable else counted try: # Candidates exist to be PUT to the judge, and `scan_region` discards them the moment there is # no judge to put them to. Enumerating them anyway costs a parse of the region's file per family @@ -588,6 +590,11 @@ def _scan_repository_impl( if unasked: degradations.append({"stage": "model", "reason": "budget_exhausted", "regions_unasked": len(unasked)}) + if counted is not None and counted.failed: + degradations.append({"stage": "model", "reason": "judge_calls_failed", "count": counted.failed}) + if counted is not None and counted.unreachable: + degradations.append({"stage": "model", "reason": "judge_withheld", "questions": counted.refused}) + graph_gaps = tuple(str(d["reason"]) for d in degradations if d.get("reason") in GRAPH_INTEGRITY_GAPS) # An integrity gap reaches the questions it can actually be wrong about, which for a census gap is the # ONE partition it came from. A partitioned scan raises a gap per graph, and a repository-wide demotion @@ -1626,15 +1633,39 @@ def _tally(findings: Sequence[ModelFinding]) -> dict[str, int]: class _CountingClient: - """Wraps a chat client so the driver counts its own spend, whatever the client records.""" + """Wraps a chat client so the driver counts its own spend, whatever the client records. + + It also counts the calls that gave no decision. A call that raises is no verdict, and it used to be read + as one: with a key set and the network off, every judge call failed, three attempts each, and each dropped + its claim as a `no` would. So the first call that raises ends the asking. The calls left in the question + that was being put are refused there and then, and the driver withholds the judge from the questions after + it, as it does from regions when the budget runs out. The failures and the refused calls reach the + manifest as degradations. + """ def __init__(self, inner: Any) -> None: self._inner = inner self.calls = 0 + self.failed = 0 + self.refused = 0 + self.unreachable = False def complete(self, **kwargs: Any) -> Any: + if self.unreachable: + self.refused += 1 + # No decision in it, which is what `_ask` reads in an answer that says nothing. Not a failure of + # its own: nothing was attempted. + return None self.calls += 1 - return self._inner.complete(**kwargs) + try: + response = self._inner.complete(**kwargs) + except Exception: + self.failed += 1 + self.unreachable = True + raise + if judge_decision(response) is None: + self.failed += 1 + return response def cost_usd(self) -> float: meter = getattr(self._inner, "cost_usd", None) diff --git a/src/openultrasast/reports.py b/src/openultrasast/reports.py index a501a502..4aece892 100644 --- a/src/openultrasast/reports.py +++ b/src/openultrasast/reports.py @@ -430,6 +430,17 @@ _COVERAGE_DEGRADATIONS: dict[str, str] = { "No model endpoint is configured, so the graph's entailed findings are reported and the residual " "`suspicion` questions went unasked." ), + # Recorded by model/scan.py. A judge call that gave no decision dropped its claim as a `no` would, and a + # scan with a key set and the network off, where every call failed, said nothing about it. + "judge_calls_failed": ( + "{count} judge call(s) gave no decision, so the question each one put **went unanswered: its finding is " + "not in this report, and that is not a `no` from the judge**. The endpoint sent no answer, or nothing " + "the scan can read as one." + ), + "judge_withheld": ( + "After a judge call got no answer from the endpoint, the judge was not asked again: {questions} further " + "question(s) were refused in the question being put, and no question after it was put to the judge." + ), "model_withheld_execution_budget": "The model was not asked, because the run's time budget leaves no room for it.", "facts_unavailable": "The fact tables for the `{stage}` stage could not be loaded, so that stage decided nothing. {detail}", "policy_invalid": "The `{stage}` policy could not be loaded, so that stage decided nothing. {detail}", diff --git a/tests/test_model_scan.py b/tests/test_model_scan.py index 4dbf31cc..e36ee0f3 100644 --- a/tests/test_model_scan.py +++ b/tests/test_model_scan.py @@ -40,6 +40,31 @@ class _Backend: return CpgResult(cpg_path=Path("cpg.bin"), run=lambda q, p: []) +class _AnsweringJudge: + """The judge as it is when the endpoint answers: one call per question put to it, each answered `yes`.""" + + def __init__(self) -> None: + self.calls = 0 + + def complete(self, **kw): # type: ignore[no-untyped-def] + from openultrasast.tool_hunter import ChatResponse + + self.calls += 1 + return ChatResponse(content='{"vulnerable": true}') + + +def _ten_files_with_six_sinks(tmp_path): # type: ignore[no-untyped-def] + """Ten identical files with six sinks each, in two families: twenty questions that each put six to the judge.""" + source = ( + "import os\nimport subprocess\n\n\ndef run(cmd):\n" + " os.system(cmd)\n subprocess.call(cmd, shell=True)\n eval(cmd)\n" + " exec(cmd)\n open(cmd).read()\n os.popen(cmd)\n" + ) + for i in range(10): + (tmp_path / f"f{i}.py").write_text(source) + return tuple(_region(path=f"f{i}.py", families=("injection", "path")) for i in range(10)) + + def test_one_cpg_is_built_for_the_whole_repository() -> None: from openultrasast.model.scan import scan_repository @@ -122,6 +147,69 @@ def test_a_region_the_budget_could_not_afford_is_not_reported_as_clean(tmp_path) assert starved.regions_scanned == generous.regions_scanned == 10 +def test_a_judge_that_cannot_be_reached_is_recorded_and_asked_no_further(tmp_path) -> None: + """A failed judge call is no verdict. It used to be read as one: with a key set and the network off, every + call failed, three attempts each, each dropped its claim as a `no` would, and nothing recorded it. The first + failure is now counted and the questions after it are not put to the judge. + """ + from openultrasast.model.scan import ScanBudget, scan_repository + + class _Unreachable(_AnsweringJudge): + def complete(self, **kw): # type: ignore[no-untyped-def] + self.calls += 1 + raise ConnectionError("network is unreachable") + + regions = _ten_files_with_six_sinks(tmp_path) + budget = ScanBudget(max_model_calls=500, max_regions=10) + + agreeing = _AnsweringJudge() + scan_repository(tmp_path, regions, backend=_Backend(), client=agreeing, model="m", budget=budget) + per_question = agreeing.calls // 20 + assert agreeing.calls == per_question * 20 and per_question > 1, "twenty questions with the same calls each, more than one" + + judge = _Unreachable() + result = scan_repository(tmp_path, regions, backend=_Backend(), client=judge, model="m", budget=budget) + + assert judge.calls == 1, "a judge that could not be reached is not asked again" + assert result.model_calls == 1, "the call that was made and failed is counted as one" + assert result.regions_scanned == 10, "the graph still arbitrated every region" + failed = [dict(d) for d in result.degradations if d.get("reason") == "judge_calls_failed"] + assert failed == [{"stage": "model", "reason": "judge_calls_failed", "count": 1}] + withheld = [dict(d) for d in result.degradations if d.get("reason") == "judge_withheld"] + # The judge calls refused after the failure in the first question. The nineteen questions after it (the + # other family of the first region, and nine regions with both of theirs) are not counted here: the count + # is of judge calls, and the report says of the rest that none was put to the judge. + assert withheld == [{"stage": "model", "reason": "judge_withheld", "questions": per_question - 1}] + + +def test_a_judge_answer_with_no_decision_in_it_is_counted_and_the_rest_are_still_asked(tmp_path) -> None: + """An answer that decides nothing drops its claim as a call that raises does. The judge was reached, so the + questions after it are still put; the scan counts the failures and goes on. + """ + from openultrasast.model.scan import ScanBudget, scan_repository + + class _Rambling(_AnsweringJudge): + def complete(self, **kw): # type: ignore[no-untyped-def] + from openultrasast.tool_hunter import ChatResponse + + self.calls += 1 + return ChatResponse(content="I cannot say.") + + regions = _ten_files_with_six_sinks(tmp_path) + budget = ScanBudget(max_model_calls=500, max_regions=10) + + agreeing = _AnsweringJudge() + scan_repository(tmp_path, regions, backend=_Backend(), client=agreeing, model="m", budget=budget) + judge = _Rambling() + result = scan_repository(tmp_path, regions, backend=_Backend(), client=judge, model="m", budget=budget) + + assert judge.calls == agreeing.calls, "a judge that answered is asked the next question" + assert result.findings == () + failed = [dict(d) for d in result.degradations if d.get("reason") == "judge_calls_failed"] + assert failed == [{"stage": "model", "reason": "judge_calls_failed", "count": judge.calls}] + assert not [d for d in result.degradations if d.get("reason") == "judge_withheld"] + + def test_the_budget_is_spent_on_the_highest_ranked_regions_first() -> None: from openultrasast.model.scan import ScanBudget, scan_repository diff --git a/tests/test_reports.py b/tests/test_reports.py index d556ae9b..c709e879 100644 --- a/tests/test_reports.py +++ b/tests/test_reports.py @@ -569,6 +569,28 @@ def test_every_recorded_scan_degradation_is_rendered(tmp_path) -> None: # type: assert needle in text, needle +def test_a_failed_judge_call_is_reported_as_unasked_and_not_as_a_no(tmp_path) -> None: + """With a key set and the network off, 16 judge calls failed in one scan and each dropped its claim as a + `no` would; the report then said less than that of a run without an endpoint. + """ + from openultrasast.reports import write_markdown_report + + path = tmp_path / "report.md" + write_markdown_report( + [], + path, + [], + degradations=[ + {"stage": "model", "reason": "judge_calls_failed", "count": 3}, + {"stage": "model", "reason": "judge_withheld", "questions": 5}, + ], + ) + section = path.read_text().split("### What could not be analysed", 1)[1] + assert "3 judge call(s) gave no decision" in section + assert "went unanswered: its finding is not in this report, and that is not a `no` from the judge" in section + assert "5 further question(s) were refused in the question being put, and no question after it was put to the judge" in section + + def test_an_unwritable_ledger_is_stated_in_the_report(tmp_path) -> None: # type: ignore[no-untyped-def] """What was not written, and where this scan's learnings are instead: a reader told only a code cannot find them."""