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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,24 @@

## [Unreleased]

### Fixed

- Six Apps defects from the 2026-11-23 repository review (Refs #595, group 2):
- CUDA inspection and qualification share one whole-token device-model match, so
`--device-model L4` no longer accepts an `L40S`.
- `benchmarks compare --action status` marks a trial whose job evidence cannot be read
as blocked instead of failing the whole command, as `report` already did.
- Delivery after `final` exports from the session root Harness committed under, so a
session reached through a symlinked directory publishes its report.
- The service-reuse dashboard page carries the generator marker the writer checks, so
it can be refreshed in place. A page written before this fix has no marker: write
the refreshed dashboard to a new output path or remove the old page first.
- `campaign import-search` unwraps shell options before `-c` and a leading `env`, on
either OS's path style. Other shells, script files and options it cannot read now
count as incomplete coverage instead of a complete record with no retrieval.
- The read agent records `agent.failed` when the workspace has no `task.json` or
contains a symbolic link.

### Changed

- `inferrsi.harness.scenarios` is now `inferrsi.harness.trials` (Refs #558). Its one
Expand Down
8 changes: 6 additions & 2 deletions src/inferrsi/apps/delivery/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,13 @@ def after_final(args, result):
if args.session_action != "final":
return result
export_id = uuid.uuid4().hex
output = args.session / "delivery" / export_id
# Export from the resolved root Harness committed final under; resolving the
# caller's path again could fail after the commit, and the exporter refuses
# symlinked ancestors.
session = Path(result["session"])
output = session / "delivery" / export_id
try:
delivery = export_bundle(args.session, output, export_id=export_id)
delivery = export_bundle(session, output, export_id=export_id)
except Exception:
# Presentation failure must never change the already committed execution outcome.
delivery = {
Expand Down
11 changes: 7 additions & 4 deletions src/inferrsi/apps/host/platforms/cuda.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
import subprocess


def _names_model(name: str, device_model: str) -> bool:
# The requested model must be a whole token of the reported name: L4 is not L40S.
return re.search(rf"\b{re.escape(device_model)}\b", name, re.IGNORECASE) is not None


def inspect_devices(*, device_ids, device_model, command):
from . import tool_facts

Expand Down Expand Up @@ -35,9 +40,7 @@ def inspect_devices(*, device_ids, device_model, command):
)
if not device["selection_verified"]:
device["status"] = "unavailable"
elif device_model and any(
device_model.casefold() not in row["name"].casefold() for row in selected
):
elif device_model and any(not _names_model(row["name"], device_model) for row in selected):
device["status"] = "device_model_mismatch"
else:
device["status"] = "available"
Expand Down Expand Up @@ -70,7 +73,7 @@ def qualify_devices(*, count: int, device_model: str):
]
selected = [gpu for gpu in devices if gpu["index"] in ids or gpu["uuid"] in ids]
if len(selected) != count or any(
not re.search(r"\b" + re.escape(device_model) + r"\b", gpu["name"]) for gpu in selected
not _names_model(gpu["name"], device_model) for gpu in selected
):
raise ValueError(
f"The {count} requested physical devices must all be {device_model}; "
Expand Down
10 changes: 6 additions & 4 deletions src/inferrsi/apps/integrations/anthropic/anthropic_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,6 @@ def run_agent(workspace, schema, prompt, model, spec, timeout, emit, *, send,
emit({"type": "agent.protocol", "client_kind": FULL_CONTEXT_KIND})
return run_full_context(workspace, schema, prompt, model, spec, timeout, emit,
send=send, input_token_ceiling=input_token_ceiling)
files = exposed_files(workspace)
tools = [
{"name": "read_file",
"description": "Read one complete exposed UTF-8 file by relative path.",
Expand All @@ -465,12 +464,15 @@ def run_agent(workspace, schema, prompt, model, spec, timeout, emit, *, send,
{"name": "submit_answer",
"description": "Submit a structured answer after reading task.json.",
"input_schema": schema}]
messages = [{"role": "user", "content": prompt
+ "\nUse read_file to read task.json; finish with submit_answer. "
"Plain text is not a submission. Exposed paths: " + canonical(sorted(files))}]
deadline, task_read_at, tool_count = time.monotonic() + timeout, None, 0
totals = {"input_tokens": 0, "output_tokens": 0, "cached_input_tokens": 0}
try:
# A rejected workspace is a retained failure like any later one.
files = exposed_files(workspace)
messages = [{"role": "user", "content": prompt
+ "\nUse read_file to read task.json; finish with submit_answer. "
"Plain text is not a submission. Exposed paths: "
+ canonical(sorted(files))}]
for number in range(1, spec["max_requests"] + 1):
remaining = deadline - time.monotonic()
if remaining <= 0:
Expand Down
48 changes: 44 additions & 4 deletions src/inferrsi/apps/views/codex_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
from .codex_tool_returns import _output_lines, _path, correlate_window

_SHELLS = ("sh", "bash", "zsh", "dash")
# Interpreters whose inline code this reader does not tokenize.
_OPAQUE_SHELLS = ("pwsh", "powershell", "cmd", "fish")
_TOOLS = ("rg", "cat", "sed", "nl")
_SHELL_OPERATORS = {"|", "||", "&&", ";", ">", ">>", "<"}
_MAX_PASSAGES = 12
Expand Down Expand Up @@ -196,17 +198,55 @@ def _rg_hits(output, cwd, corpus, scopes, mode, with_filename):
return [{"ref": ref, "match_line": line} for ref, line in hits.items()], complete


def _program(word):
"""Program name of a recorded argv word from either OS, lower-cased, without .exe."""
return re.split(r"[\\/]", word)[-1].lower().removesuffix(".exe")


def _without_env(argv):
"""Drop a leading `env` and its NAME=value words; None for env options it cannot read."""
if _program(argv[0]) != "env":
return argv
rest = argv[1:]
while rest and "=" in rest[0] and not rest[0].startswith("-"):
rest = rest[1:]
return rest if rest and not rest[0].startswith("-") else None


def _shell_script(options):
"""Return a shell's inline `-c` script, or None when it runs no inline script."""
words = iter(options)
for word in words:
if word == "--":
return None # What follows is a script file, even if it looks like -c.
if word in ("-o", "+o"):
next(words, None)
elif word.startswith("-") and not word.startswith("--") and "c" in word[1:]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please stop scanning shell options at --. A later -c can be a script filename rather than an inline-code flag. The current loop can read the following argument as inline code and report complete provenance even though it never saw the script. Please retain the incomplete status for this form and add a regression.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ef8cda3. _shell_script() now stops at -- and returns no inline script, so bash -- -c ... is recorded as incomplete.

Two regressions cover it:

  • test_dash_c_after_double_dash_names_a_script_file checks _recorded_argv directly. It failed against the previous source on H200: that source decoded rg -n needle docs as inline code.
  • The end-to-end case in test_unreadable_shell_forms_stay_incomplete also covers this form.

return next(words, None)
elif not word.startswith(("-", "+")):
return None # A script file or another operand.
return None


def _recorded_argv(item):
original_argv = item.get("command")
if (not isinstance(original_argv, list) or not original_argv
or not all(isinstance(arg, str) for arg in original_argv)):
return None, False
argv = original_argv
argv = _without_env(original_argv)
if not argv:
return None, False
multiline = False
if (Path(argv[0]).name in _SHELLS and len(argv) == 3
and argv[1] in ("-c", "-lc", "-ic", "-ilc")):
shell = _program(argv[0])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could a shell still present after one unwrap remain opaque? A direct shell that runs an unread script is now incomplete, but wrapping that same shell command in an outer shell can leave the inner shell in argv; the caller then reports complete/no retrieval without reading the script. Please mark an undecoded inner shell incomplete and test direct vs wrapped parity.

if shell in _OPAQUE_SHELLS:
return None, False
if shell in _SHELLS:
script = _shell_script(argv[1:])
if script is None:
# Code this reader cannot see may still have searched.
return None, False
try:
argv, multiline = _shell_argv(argv[2])
argv, multiline = _shell_argv(script)
except ValueError:
return None, False
compound = multiline or any(word in _SHELL_OPERATORS for word in argv)
Expand Down
3 changes: 2 additions & 1 deletion src/inferrsi/apps/views/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,8 @@ def render_dashboard(snapshot: dict, *, live: bool = False) -> str:
return render_attempt(snapshot["data"]["fixed_attempt"], title="fixed attempt Dashboard")
if snapshot["data"].get("evaluation_mode") == "service_reuse":
refresh = '<meta http-equiv="refresh" content="3">' if live else ""
return ('<!doctype html><html lang="en"><meta charset="utf-8">' + refresh
return ('<!doctype html><html lang="en"><meta charset="utf-8">'
+ '<meta name="generator" content="InferRSI dashboard">' + refresh
+ '<title>Service-reuse optimization</title><main>' + snapshot["chart"]
+ '</main></html>')
view = {**snapshot["data"], "live": live}
Expand Down
7 changes: 6 additions & 1 deletion src/inferrsi/apps/workflows/benchmark_compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,12 @@ def _status(root, plan, state, *, host_views=None):
for trial in plan["trials"]:
job = _job(root, trial)
if host_views is None:
view = agent_sessions.status(job) if job.exists() else None
try:
view = agent_sessions.status(job) if job.exists() else None
except (OSError, ValueError) as error:
# As in report: unverifiable job evidence blocks only this trial.
view = {"state": "blocked", "native_session": None,
"error": type(error).__name__}
else:
view = host_views[trial["id"]]
collection = state["collections"].get(trial["id"])
Expand Down
15 changes: 14 additions & 1 deletion tests/test_anthropic_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,23 @@ def test_symlink_workspace_is_rejected_before_transport(workspace, spec):
except OSError:
pytest.skip("Host does not permit fixture symlinks")
send, requests = scripted()
events = []
with pytest.raises(agent.AgentError, match="workspace_symlink"):
agent.run_agent(workspace, SCHEMA_SMALL, "fixture", MODEL, spec, 30,
lambda _: None, send=send)
events.append, send=send)
assert not requests
assert events == [{"type": "agent.failed", "reason": "workspace_symlink"}]


def test_missing_task_is_retained_as_a_failure_before_transport(workspace, spec):
(workspace / "task.json").unlink()
send, requests = scripted()
events = []
with pytest.raises(agent.AgentError, match="missing_task"):
agent.run_agent(workspace, SCHEMA_SMALL, "fixture", MODEL, spec, 30,
events.append, send=send)
assert not requests
assert events == [{"type": "agent.failed", "reason": "missing_task"}]


@pytest.mark.parametrize("field,value,reason,responses", [
Expand Down
2 changes: 2 additions & 0 deletions tests/test_benchmark_compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,8 @@ def test_bad_native_receipt_keeps_verified_arm_in_report(experiment, damage, fie
for name in ("markdown", "html"):
assert evidence_gap in Path(report["reports"][name]).read_text(encoding="utf-8")
next_action = report["next_action"]
# The documented resume path reads the same damaged job without failing.
assert compare.status(root)["next_action"]["operation"] == next_action["operation"]
if collected:
assert next_action["operation"] == "completed"
else:
Expand Down
40 changes: 40 additions & 0 deletions tests/test_codex_search_shell_forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import pytest

from inferrsi.apps.views.codex_search import _command, _recorded_argv

PLAIN = ["bash", "-lc", "rg -n needle docs"]


@pytest.mark.parametrize("wrapped", [
["bash", "-o", "pipefail", "-lc", "rg -n needle docs"],
["/usr/bin/env", "bash", "-lc", "rg -n needle docs"],
["env", "LC_ALL=C", "bash", "-e", "-lc", "rg -n needle docs"],
# Recorded on Windows, read on any OS.
["C:\\Program Files\\Git\\bin\\bash.exe", "-lc", "rg -n needle docs"],
["C:\\Program Files\\Git\\usr\\bin\\env.exe", "bash", "-lc", "rg -n needle docs"],
])
def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped):
assert _recorded_argv({"command": PLAIN}) == (["rg", "-n", "needle", "docs"], False)
assert _recorded_argv({"command": wrapped}) == _recorded_argv({"command": PLAIN})


@pytest.mark.parametrize("command", [
["pwsh", "-Command", "rg -n needle docs"],
["bash", "search.sh"],
["env", "-i", "bash", "-lc", "rg -n needle docs"],
# After --, -c is a script file name, not inline code.
["bash", "--", "-c", "rg -n needle docs"],
# Recorded on Windows, read on any OS.
["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n needle docs"],
["C:\\Tools\\env.exe", "C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command",
"rg -n needle docs"],
])
def test_unreadable_shell_forms_stay_incomplete(tmp_path, command):
# A search this reader cannot decode must not count as complete coverage.
item = {"command": command, "exit_code": 0, "aggregated_output": ""}
assert _command(item, tmp_path) == (None, False, None)


def test_dash_c_after_double_dash_names_a_script_file():
# bash -- -c runs a script file named -c, so no inline code is visible.
assert _recorded_argv({"command": ["bash", "--", "-c", "rg -n needle docs"]}) == (None, False)
11 changes: 11 additions & 0 deletions tests/test_dashboard_service_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from inferrsi.apps.views.dashboard import _write_view_document, render_dashboard


def test_service_reuse_page_can_be_rewritten_by_the_dashboard_writer(tmp_path):
# write_dashboard renders this page and replaces only pages it recognizes as its own.
snapshot = {"data": {"evaluation_mode": "service_reuse"}, "chart": "<svg></svg>"}
page = render_dashboard(snapshot)
output = tmp_path / "dashboard.html"
assert _write_view_document(output, page, generator="InferRSI dashboard") == output
assert _write_view_document(output, page, generator="InferRSI dashboard") == output
assert output.read_text(encoding="utf-8") == page
7 changes: 7 additions & 0 deletions tests/test_inspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ def test_requested_device_and_model_are_checked(self):
mismatch = self.inspect_cuda(rows, ids=("0",), model="H200")
self.assertEqual(mismatch["device"]["status"], "device_model_mismatch")

def test_cuda_model_must_be_a_whole_token_of_the_reported_name(self):
rows = "0, GPU-A, NVIDIA L40S, 999.0\n"
shorter = self.inspect_cuda(rows, model="L4")
self.assertEqual(shorter["device"]["status"], "device_model_mismatch")
exact = self.inspect_cuda(rows, model="l40s")
self.assertEqual(exact["device"]["status"], "available")

def test_successful_tool_without_requested_gpu_is_not_available(self):
empty = self.inspect_cuda("")
self.assertEqual(empty["device"]["status"], "unavailable")
Expand Down
4 changes: 4 additions & 0 deletions tests/test_module_boundaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ def test_cuda_qualification_accepts_campaign_supplied_count_and_sku(monkeypatch)
with patch("inferrsi.apps.host.platforms.cuda.subprocess.run", side_effect=[device, busy]):
with pytest.raises(ValueError, match="already has a compute process"):
qualify_devices(count=1, device_model="H100")
# Inspection and qualification share one rule: H10 is not a token of H100.
with patch("inferrsi.apps.host.platforms.cuda.subprocess.run", side_effect=[device]):
with pytest.raises(ValueError, match="must all be H10"):
qualify_devices(count=1, device_model="H10")


def test_shared_layers_do_not_import_campaigns_or_reverse_dependencies():
Expand Down
38 changes: 38 additions & 0 deletions tests/test_project_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import os
import subprocess
import sys
from pathlib import Path

import pytest

Expand Down Expand Up @@ -156,6 +157,43 @@ def test_project_runs_shared_rounds_and_final_from_retained_multifile_candidate(
assert not (root / "rounds.jsonl").exists() # No second mutable control log.


def test_final_delivery_publishes_through_a_symlinked_session_path(project, capsys, tmp_path):
start(project, capsys)
submit(project, capsys, 20)
root = project[3]
alias = tmp_path / "alias"
try:
alias.symlink_to(root, target_is_directory=True)
except OSError:
pytest.skip("Host does not permit fixture symlinks")
assert main(["campaign", "final", "--directory", str(alias),
"--reason", "Caller ended the up-to-budget search"]) == 0
receipt = json.loads(capsys.readouterr().out)
assert receipt["delivery"]["status"] == "published"
assert (root / "delivery" / receipt["delivery"]["export_id"] / "report.md").is_file()


def test_final_delivery_never_resolves_the_session_path_after_commit(project, capsys, monkeypatch):
start(project, capsys)
submit(project, capsys, 20)
root = project[3]
original = Path.resolve

def resolve(self, *args, **kwargs):
# The workspace becomes unavailable once final is committed.
state = json.loads((root / "state.json").read_text(encoding="utf-8"))
if self == root and state["final"] is not None:
raise OSError("Session path unavailable after commit")
return original(self, *args, **kwargs)

monkeypatch.setattr(Path, "resolve", resolve)
assert main(["campaign", "final", "--directory", str(root),
"--reason", "Caller ended the up-to-budget search"]) == 0
receipt = json.loads(capsys.readouterr().out)
assert receipt["state"] == "completed"
assert receipt["delivery"]["status"] == "published"


def test_quality_failure_is_retained_and_cannot_win(project, capsys):
start(project, capsys)
(project[0] / "engine.py").write_text("def compute(x):\n return 0\n", encoding="utf-8")
Expand Down
9 changes: 8 additions & 1 deletion tests/test_project_service_reuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,13 +409,20 @@ def test_knowledge_and_dashboard_never_enter_legacy_fingerprint_readers(campaign
assert context["context"]["contexts"]
project_service.no_fingerprints(context)
submit(campaign, version="selected", a=90)
from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard
from inferrsi.apps.views.dashboard import (
dashboard_snapshot,
render_dashboard,
write_dashboard,
)

snapshot = dashboard_snapshot(campaign["root"])
project_service.no_fingerprints(snapshot)
page = render_dashboard(snapshot)
assert "Service-reuse optimization" in page and "Objective values" in page
assert "sha256" not in page.lower()
# A refresh replaces the page this writer produced earlier.
output = write_dashboard(campaign["root"])
assert write_dashboard(campaign["root"]) == output


@pytest.mark.parametrize(
Expand Down
Loading