Skip to content
Merged
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
4 changes: 3 additions & 1 deletion packages/yugos-evals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@ harness=..., version=...)` returns a copy whose solver is Claude Code
release; samples, sandbox and scorer are unchanged. The harness runs inside the
task's sandbox and its model requests come back to the router, so the sandbox
needs no network and every turn is routed and metered as usual. The copy is a
separate source, `<source>@<harness>`, without difficulty labels.
separate source, `<source>@<harness>`, without difficulty labels. It drops the
task's message limit, which sizes the native agent's loop; the run's call, cost
and time limits bound a harness session.

Install the `harness` extra to use it. The harness release is fetched once on
the host and copied into the sandbox.
Expand Down
11 changes: 9 additions & 2 deletions packages/yugos-evals/src/yugos_evals/harnessed.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

BUILDER = "yugos_evals.harnessed"
HARNESSES = ("claude_code", "codex_cli", "opencode")
# OpenCode formats requests as one model from its release's own catalog, which drops
# older models; the routed model still answers. This one is in current releases.
OPTIONS = {"opencode": {"opencode_model": "anthropic/claude-sonnet-4-6"}}
_RELEASE = re.compile(r"\d+(\.\d+)+")


Expand Down Expand Up @@ -45,7 +48,8 @@ def harness_agent(harness: str, version: str):
_check(harness, version)
import inspect_swe

return getattr(inspect_swe, harness)(version=version, filter=portable_request)
options = OPTIONS.get(harness, {})
return getattr(inspect_swe, harness)(version=version, filter=portable_request, **options)


def build(*, options: dict, harness: str, version: str, builder: str, builder_args: dict) -> Task:
Expand All @@ -62,7 +66,9 @@ def harness_question(question, *, harness: str, version: str):
"""A frozen sandboxed question re-presented to a harness, without reloading it.

The copy is a separate source (`<source>@<harness>`) with no difficulty labels:
panel evidence for the task's own agent does not describe a harness.
panel evidence for the task's own agent does not describe a harness. The task's
message limit is dropped too: it sizes the native agent's loop, and a harness
session is bounded by the run's call, cost and time limits instead.
"""
_check(harness, version)
config = question.inspect_task
Expand Down Expand Up @@ -93,6 +99,7 @@ def harness_question(question, *, harness: str, version: str):
"builder": BUILDER,
"builder_args": builder_args,
"packages": packages,
"message_limit": None,
},
}
)
27 changes: 26 additions & 1 deletion packages/yugos-evals/tests/test_harnessed.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from yugos.inference.chat import ModelInput
from yugos.inspect_engine import restore_tasks
from yugos_evals.catalog import entry, freeze_entry, load_task
from yugos_evals.harnessed import harness_question, portable_request
from yugos_evals.harnessed import harness_agent, harness_question, portable_request


@pytest.fixture
Expand Down Expand Up @@ -51,6 +51,31 @@ def test_harnessed_question_keeps_the_native_samples_sandbox_and_scorer(sandboxe
assert other.inspect_task != harnessed.inspect_task


def test_harness_session_is_not_cut_at_the_native_agents_message_limit(sandboxed):
limited = sandboxed.model_copy(
update={"inspect_task": {**sandboxed.inspect_task, "message_limit": 30}}
)
[(native, _)] = restore_tasks([limited])
[(task, _)] = restore_tasks([harness_question(limited, harness="codex_cli", version="0.80.0")])
# Thirty messages end a harness after about a dozen turns, before it can finish.
assert (native.message_limit, task.message_limit) == (30, None)


def test_opencode_is_given_a_model_its_release_can_resolve(monkeypatch):
import inspect_swe

seen = {}
monkeypatch.setattr(inspect_swe, "opencode", lambda **options: seen.update(options))
monkeypatch.setattr(inspect_swe, "claude_code", lambda **options: seen.update(options))
harness_agent("claude_code", "2.1.311")
assert "opencode_model" not in seen
harness_agent("opencode", "1.19.6")
# The inspect-swe default names a model newer OpenCode releases no longer list,
# which fails every session before its first request.
assert seen["opencode_model"] not in (None, "anthropic/claude-sonnet-4-5")
assert seen["version"] == "1.19.6" and seen["filter"] is portable_request


def test_harnessed_question_drops_evidence_measured_with_the_native_agent(sandboxed):
labelled = sandboxed.model_copy(update={"difficulty_decile": 3, "panel_solve_share": "0.5"})
harnessed = harness_question(labelled, harness="codex_cli", version="0.80.0")
Expand Down
56 changes: 55 additions & 1 deletion packages/yugos/src/yugos/inspect_engine/router_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import math
import time
import uuid
import weakref
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from dataclasses import dataclass
Expand Down Expand Up @@ -121,6 +122,33 @@ def __init__(self, message: str, *, retry_after: float | None = None) -> None:
}


def _calls(message: ChatMessageAssistant) -> list[tuple]:
return [(call.id, call.function, call.arguments) for call in message.tool_calls or ()]


def restore_continuations(
input: list[ChatMessage], replies: dict[tuple[str, ...], ChatMessageAssistant]
) -> list[ChatMessage]:
"""Give each replayed tool-calling turn back the reply it came from.

A coding harness keeps its own transcript and rebuilds every request from it, so
its assistant turns arrive without the metadata that carries the provider's
reasoning state, and an empty reply arrives as placeholder text. A turn whose tool
calls are exactly those of a reply this sample was given is that reply.
"""
restored = []
for message in input:
if isinstance(message, ChatMessageAssistant) and not (message.metadata or {}).get(
PROVIDER_STATE_KEY
):
calls = _calls(message)
reply = replies.get(tuple(call[0] for call in calls))
if reply is not None and _calls(reply) == calls:
message = reply
restored.append(message)
return restored


def _output(reply: RouterReply, model: str, elapsed_s: float) -> ModelOutput:
tool_calls = [
ToolCall(id=call.id, function=call.function, arguments=call.arguments)
Expand Down Expand Up @@ -183,7 +211,33 @@ def record_model_time(seconds: float) -> None:


class _RouterInspectModel(Model):
async def generate(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# Tool-calling replies that carry provider state, by sample and call IDs.
self._replies: dict[int, dict[tuple[str, ...], ChatMessageAssistant]] = {}

def _sample_replies(self) -> dict[tuple[str, ...], ChatMessageAssistant]:
sample = store()
replies = self._replies.get(id(sample))
if replies is None:
replies = self._replies[id(sample)] = {}
# A sample's replies are dropped with its store.
weakref.finalize(sample, self._replies.pop, id(sample), None)
return replies

async def generate(self, input, *args, **kwargs):
# Restored here, before Inspect records the request, so the log shows the
# conversation the router was sent.
replies = self._sample_replies()
if not isinstance(input, str):
input = restore_continuations(input, replies)
output = await self._timed_generate(input, *args, **kwargs)
message = output.message if output.choices else None
if message and message.tool_calls and (message.metadata or {}).get(PROVIDER_STATE_KEY):
replies[tuple(call.id for call in message.tool_calls)] = message
return output

async def _timed_generate(self, *args, **kwargs):
# Inspect reconciles successful generations across every retry, while a
# terminal exception skips that reconciliation. Own the final adjustment
# around its complete generation so earlier callbacks cannot earn credit twice.
Expand Down
68 changes: 67 additions & 1 deletion packages/yugos/tests/test_inspect_router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import json
import threading
from dataclasses import replace
from decimal import Decimal
from types import SimpleNamespace

Expand All @@ -11,14 +12,22 @@
from inspect_ai import Task # noqa: E402
from inspect_ai.dataset import MemoryDataset, Sample # noqa: E402
from inspect_ai.log import read_eval_log # noqa: E402
from inspect_ai.model import GenerateConfig, ModelOutput, RetryDecision # noqa: E402
from inspect_ai.model import ( # noqa: E402
ChatMessageAssistant,
ChatMessageTool,
GenerateConfig,
ModelOutput,
RetryDecision,
get_model,
)
from inspect_ai.scorer import includes # noqa: E402
from inspect_ai.solver import generate, solver, use_tools # noqa: E402
from inspect_ai.tool import tool # noqa: E402
from inspect_ai.util import LimitExceededError # noqa: E402
from inspect_fakes import ScriptedRouter, exact_question, pack_task, reply, run # noqa: E402

from yugos.inference.calls import QuestionLimitExceeded # noqa: E402
from yugos.inference.chat import ProviderState, provider_state # noqa: E402
from yugos.inspect_engine import ( # noqa: E402
QUESTION_EXHAUSTED,
JsonlReceipts,
Expand Down Expand Up @@ -143,6 +152,63 @@ async def client(call):
assert event.output.time is not None and event.output.time >= 0


def test_a_harness_replayed_turn_gets_its_reasoning_state_back(tmp_path):
# A coding harness rebuilds each request from its own transcript: the assistant
# turn returns without metadata and an empty reply returns as placeholder text.
state = ProviderState(
provider_id="google",
model_id="m",
effort="medium",
data={"api": "google", "message": {"role": "assistant", "content": ""}},
)
requests = {"faithful": [], "edited": []}

async def client(call):
requests[call.scope.sample_id].append(call.request)
if len(requests[call.scope.sample_id]) == 1:
return RouterReply(
tool_calls=(
RouterToolCall(id="t1", function="lookup", arguments={"city": "Oslo"}),
),
provider_state=state,
finish_reason="tool_calls",
)
return reply("sunny")

@solver
def replaying_harness():
async def solve(sample, generate):
model = get_model()
first = (await model.generate(sample.messages)).message
calls = first.tool_calls
if sample.sample_id == "edited":
calls = [replace(calls[0], arguments={"city": "Rome"})]
replayed = ChatMessageAssistant(content="(no content)", tool_calls=calls)
result = ChatMessageTool(content="sunny", tool_call_id="t1")
sample.output = await model.generate([*sample.messages, replayed, result])
return sample

return solve

task = pack_task(
[exact_question("faithful", "sunny"), exact_question("edited", "sunny")], name="pack"
)
task.solver = replaying_harness()
log = run_competition_eval(
task, router_model(client, submission_id="sub"), log_dir=str(tmp_path), display="none"
)
assert not any(sample.error for sample in log.samples)

faithful, edited = (requests[name][1].messages[-2] for name in ("faithful", "edited"))
assert provider_state(faithful) == state and faithful.text == ""
# A turn the harness changed is no longer the reply the state belongs to.
assert provider_state(edited) is None and edited.text == "(no content)"
# The log records the request the router was sent.
[sample] = [sample for sample in log.samples if sample.id == "faithful"]
logged = [event for event in sample.events if event.event == "model"][1].input[-2]
assert provider_state(logged) == state and logged.text == ""


def test_only_infrastructure_unavailability_is_retried():
# Catches retrying a miner failure (a second attempt) or failing on a transient outage.
api = RouterModel("sub", client=None)
Expand Down