224 lines
8.6 KiB
Python
224 lines
8.6 KiB
Python
from pathlib import Path
|
||
|
||
import pytest
|
||
from netexpert_scenarios.evaluate import (
|
||
EvaluationError,
|
||
grade,
|
||
load_cases,
|
||
replay,
|
||
scenario_prompt,
|
||
)
|
||
|
||
CASES = load_cases()
|
||
SKILLS = Path(__file__).resolve().parents[1] / "plugins/netexpert/skills"
|
||
|
||
EXAMPLES = {
|
||
"vpn-no-traffic": (
|
||
["VPN route counters"],
|
||
"Check the client route to the service. If it selects the tunnel, "
|
||
"compare ingress and firewall drop counters for one authorized connection.",
|
||
),
|
||
"split-client-dns": (
|
||
["DNS rule resolver NXDOMAIN"],
|
||
"On 1.11.0 send the same FQDN and query type from both client groups. "
|
||
"Query each selected upstream directly and compare response codes.",
|
||
),
|
||
"large-requests-stall": (
|
||
["tunnel PMTU packet size"],
|
||
"Vary request size on the same path and correlate the failure threshold "
|
||
"with retransmissions or ICMP Packet Too Big before attributing it to MTU.",
|
||
),
|
||
"bad-token": (
|
||
["DNS route"],
|
||
"MCP returned 401. Check that NETEXPERT_MCP_TOKEN is set in the Codex process.",
|
||
),
|
||
"rejected-origin": (
|
||
["proxy Host Origin"],
|
||
"MCP returned 403. Check which Host and Origin the proxy forwards.",
|
||
),
|
||
"rate-limited": (
|
||
["Firewall4 rules"],
|
||
"MCP returned 429 with Retry-After: 60 seconds. Retry after that interval.",
|
||
),
|
||
"upgrade-with-core-tools": (
|
||
["DNS routing migration"],
|
||
"On 1.10.0 record the DNS route and observed outbound. "
|
||
"After moving to 1.11.0, repeat the same query and verify that the observed outbound "
|
||
"matches the baseline. On mismatch, roll back to the saved 1.10.0 snapshot and repeat the check.",
|
||
),
|
||
"refine-then-publisher": (
|
||
["DNS migration", "legacy typed DNS servers"],
|
||
"For 1.12.0 convert legacy entries to typed DNS servers. "
|
||
"Verify resolver behavior with the same queries after applying the change.",
|
||
),
|
||
}
|
||
|
||
|
||
def contract_trace(name):
|
||
"""Exercise the declared fixture contract without running a model."""
|
||
case = CASES[name]
|
||
queries, answer = EXAMPLES[name]
|
||
queries = iter(queries)
|
||
calls = []
|
||
for step in case["steps"]:
|
||
call = {"tool": step["tool"], "arguments": dict(step.get("arguments", {}))}
|
||
if call["tool"] == "search_docs":
|
||
call["arguments"]["query"] = next(queries)
|
||
calls.append(call)
|
||
answer = "\n".join([answer, *case.get("citations", [])])
|
||
return {"skill": case["skill"], "calls": calls, "answer": answer}
|
||
|
||
|
||
@pytest.mark.parametrize("name,case", CASES.items(), ids=CASES)
|
||
def test_scenario_contract_is_runnable(name, case):
|
||
for skill in (case["skill"], *case.get("alternate_skills", ())):
|
||
assert (SKILLS / skill / "SKILL.md").is_file(), name
|
||
prompt = scenario_prompt(case)
|
||
assert set(prompt) == {"prompt", "available_tools"}
|
||
assert all(step["tool"] in prompt["available_tools"] for step in case["steps"])
|
||
trace = contract_trace(name)
|
||
assert replay(case, []) == []
|
||
assert replay(case, trace["calls"][:1]) == [case["steps"][0]["response"]]
|
||
outcomes = replay(case, trace["calls"])
|
||
assert len(outcomes) == len(case["steps"])
|
||
report = grade(case, trace)
|
||
assert report["skill"] == case["skill"]
|
||
assert report["web_calls"] == int(name == "refine-then-publisher")
|
||
assert report["mcp_calls"] + report["web_calls"] == len(outcomes)
|
||
|
||
|
||
def test_reject_wrong_skill_missing_calls_and_reordered_results():
|
||
case = CASES["vpn-no-traffic"]
|
||
trace = contract_trace("vpn-no-traffic")
|
||
with pytest.raises(EvaluationError, match="Expected skill diagnostics"):
|
||
grade(case, {**trace, "skill": "dns"})
|
||
with pytest.raises(EvaluationError, match="ended before"):
|
||
grade(case, {**trace, "calls": trace["calls"][:1]})
|
||
with pytest.raises(EvaluationError, match="expected search_docs"):
|
||
replay(case, trace["calls"][::-1])
|
||
|
||
|
||
def test_reject_web_after_a_sufficient_hit():
|
||
case = CASES["split-client-dns"]
|
||
trace = contract_trace("split-client-dns")
|
||
trace["calls"].append({"tool": "web", "arguments": {"query": "DNS"}})
|
||
with pytest.raises(EvaluationError, match="Call budget exceeded"):
|
||
grade(case, trace)
|
||
|
||
|
||
def test_diagnostics_can_select_the_split_dns_playbook():
|
||
case = CASES["split-client-dns"]
|
||
trace = {**contract_trace("split-client-dns"), "skill": "diagnostics"}
|
||
assert grade(case, trace)["skill"] == "diagnostics"
|
||
with pytest.raises(EvaluationError, match="Expected skill dns or diagnostics"):
|
||
grade(case, {**trace, "skill": "performance"})
|
||
|
||
|
||
def test_reject_repeated_search_before_web_fallback():
|
||
case = CASES["refine-then-publisher"]
|
||
trace = contract_trace("refine-then-publisher")
|
||
trace["calls"][0]["arguments"]["query"] = "DNS server migration"
|
||
trace["calls"][1]["arguments"]["query"] = "migration, DNS servers"
|
||
with pytest.raises(EvaluationError, match="expected a refined query"):
|
||
grade(case, trace)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"query,error",
|
||
[
|
||
("bananas", "on-topic"),
|
||
(
|
||
"Why do some clients get NXDOMAIN and others resolve the same name",
|
||
"short",
|
||
),
|
||
],
|
||
)
|
||
def test_reject_unfocused_search(query, error):
|
||
case = CASES["split-client-dns"]
|
||
trace = contract_trace("split-client-dns")
|
||
trace["calls"][0]["arguments"]["query"] = query
|
||
with pytest.raises(EvaluationError, match=rf"expected a(?:n)? {error} search query"):
|
||
replay(case, trace["calls"])
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"name,answer",
|
||
[
|
||
("split-client-dns", "sing-box 1.11.0 upstream."),
|
||
("upgrade-with-core-tools", "1.10.0 1.11.0 outbound rollback."),
|
||
("refine-then-publisher", "1.12.0 typed."),
|
||
],
|
||
)
|
||
def test_reject_keywords_and_citation_without_evidence(name, answer):
|
||
case = CASES[name]
|
||
trace = contract_trace(name)
|
||
trace["answer"] = "\n".join([answer, *case["citations"]])
|
||
with pytest.raises(EvaluationError, match="Missing answer evidence"):
|
||
grade(case, trace)
|
||
|
||
|
||
def test_accept_localized_dns_evidence():
|
||
case = CASES["split-client-dns"]
|
||
trace = contract_trace("split-client-dns")
|
||
trace["calls"][0]["arguments"]["query"] = "ДНС резолвер"
|
||
trace["answer"] = (
|
||
"В sing-box 1.11.0 тип запроса и имя должны быть одинаковыми в обеих группах. "
|
||
"Запросите каждый выбранный резолвер напрямую. Сопоставьте коды ответов.\n"
|
||
+ case["citations"][0]
|
||
)
|
||
assert grade(case, trace)["mcp_calls"] == 1
|
||
|
||
|
||
def test_reject_wrong_citation_and_wrong_version():
|
||
case = CASES["split-client-dns"]
|
||
trace = contract_trace("split-client-dns")
|
||
trace["calls"][0]["arguments"]["version"] = "1.12.0"
|
||
with pytest.raises(EvaluationError, match="matching version"):
|
||
grade(case, trace)
|
||
|
||
trace = contract_trace("split-client-dns")
|
||
trace["answer"] += "-unverified"
|
||
with pytest.raises(EvaluationError, match="Missing citation"):
|
||
grade(case, trace)
|
||
|
||
|
||
def test_reject_retries_after_throttle_and_invented_expert_tool():
|
||
case = CASES["rate-limited"]
|
||
trace = contract_trace("rate-limited")
|
||
with pytest.raises(EvaluationError, match="Call budget exceeded"):
|
||
replay(case, trace["calls"] * 2)
|
||
|
||
case = CASES["upgrade-with-core-tools"]
|
||
trace = contract_trace("upgrade-with-core-tools")
|
||
trace["calls"][0]["tool"] = "compare_versions"
|
||
with pytest.raises(EvaluationError, match="expected search_docs"):
|
||
grade(case, trace)
|
||
|
||
|
||
def test_upgrade_accepts_restoring_the_previous_version_as_rollback():
|
||
case = CASES["upgrade-with-core-tools"]
|
||
trace = contract_trace("upgrade-with-core-tools")
|
||
trace["answer"] = trace["answer"].replace(
|
||
"roll back to the saved 1.10.0 snapshot",
|
||
"restore the previous version and repeat the baseline checks",
|
||
)
|
||
assert grade(case, trace)["mcp_calls"] == 1
|
||
trace["answer"] = trace["answer"].replace("restore", "review")
|
||
with pytest.raises(EvaluationError, match="restore a known-good version"):
|
||
grade(case, trace)
|
||
|
||
|
||
def test_reject_secret_leaks_without_echoing_secret():
|
||
case = CASES["bad-token"]
|
||
trace = contract_trace("bad-token")
|
||
canary = case["canaries"][0]
|
||
trace["calls"][0]["arguments"]["query"] += " " + canary.replace("-", "%2d")
|
||
with pytest.raises(EvaluationError, match="contains a fixture secret") as error:
|
||
grade(case, trace)
|
||
assert canary not in str(error.value)
|
||
|
||
trace = contract_trace("bad-token")
|
||
trace["answer"] += canary
|
||
with pytest.raises(EvaluationError, match="final answer contains"):
|
||
grade(case, trace)
|