File size: 22,798 Bytes
881f9f2 d606d10 881f9f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 | """Unit tests for scripts/aat_runner.py.
These tests use stubbed RunResult objects and mocked Runner.run() so
they don't require network, MCP subprocesses, or WatsonX.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import sys
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
import pytest
def _stub_args(**overrides):
defaults = dict(
prompt="test prompt",
output="/tmp/out.json",
model_id="watsonx/meta-llama/llama-3-3-70b-instruct",
mcp_mode="direct",
max_turns=30,
parallel_tool_calls=False,
verbose=False,
)
defaults.update(overrides)
return argparse.Namespace(**defaults)
def _msg_item(text: str):
"""Build a stub message_output_item matching AOB's parser."""
return SimpleNamespace(
type="message_output_item",
raw_item=SimpleNamespace(content=[SimpleNamespace(text=text)]),
)
def _tool_call_item(name: str, args: dict, call_id: str = "c1"):
"""Build a stub tool_call_item."""
import json as _json
return SimpleNamespace(
type="tool_call_item",
raw_item=SimpleNamespace(
name=name,
arguments=_json.dumps(args),
call_id=call_id,
id=call_id,
),
)
def _tool_output_item(output: str):
return SimpleNamespace(type="tool_call_output_item", output=output)
def _stub_run_result(
items=None, final_output="final answer text", max_turns_reached=False
):
"""Build a minimal RunResult-shaped object for serializer tests.
Matches the shape AOB's _build_trajectory in
../AssetOpsBench/src/agent/openai_agent/runner.py:121 walks.
"""
return SimpleNamespace(
new_items=items or [],
final_output=final_output,
max_turns_reached=max_turns_reached,
raw_responses=[],
)
def test_expand_scenario_glob_accepts_shell_style_explicit_list(tmp_path: Path):
from scripts.aat_runner import _expand_scenario_glob
first = tmp_path / "multi_01_end_to_end_fault_response.json"
second = tmp_path / "multi_02_dga_to_workorder_pipeline.json"
first.write_text("{}", encoding="utf-8")
second.write_text("{}", encoding="utf-8")
scenario_files = _expand_scenario_glob(f"{first.name} {second.name}", tmp_path)
assert [path.name for path in scenario_files] == [first.name, second.name]
def test_expand_scenario_glob_accepts_single_bracket_glob(tmp_path: Path):
from scripts.aat_runner import _expand_scenario_glob
first = tmp_path / "multi_01_end_to_end_fault_response.json"
second = tmp_path / "multi_02_dga_to_workorder_pipeline.json"
third = tmp_path / "multi_03_iot_tsfm_thermal_risk.json"
for path in (first, second, third):
path.write_text("{}", encoding="utf-8")
scenario_files = _expand_scenario_glob("multi_0[12]_*.json", tmp_path)
assert [path.name for path in scenario_files] == [first.name, second.name]
def test_expand_scenario_glob_empty_string_returns_no_paths(tmp_path: Path):
from scripts.aat_runner import _expand_scenario_glob
assert _expand_scenario_glob("", tmp_path) == []
def test_expand_scenario_glob_deduplicates_overlapping_patterns(tmp_path: Path):
from scripts.aat_runner import _expand_scenario_glob
first = tmp_path / "multi_01_end_to_end_fault_response.json"
second = tmp_path / "multi_02_dga_to_workorder_pipeline.json"
first.write_text("{}", encoding="utf-8")
second.write_text("{}", encoding="utf-8")
scenario_files = _expand_scenario_glob(f"{first.name} multi_0[12]_*.json", tmp_path)
assert [path.name for path in scenario_files] == [first.name, second.name]
def test_serialize_run_result_happy_path():
from scripts.aat_runner import _serialize_run_result
args = _stub_args()
result = _stub_run_result(
items=[
_tool_call_item("iot.list_sensors", {"asset_id": "T-1"}, "c1"),
_tool_output_item("[]"),
_msg_item("final answer text"),
]
)
out = _serialize_run_result(args, "test prompt", result, duration_seconds=12.5)
assert out["question"] == "test prompt"
assert out["answer"] == "final answer text"
assert out["success"] is True
assert out["max_turns_exhausted"] is False
assert out["turn_count"] >= 1
assert out["tool_call_count"] == 1
assert out["runner_meta"]["model_id"] == args.model_id
assert out["runner_meta"]["mcp_mode"] == "direct"
assert out["runner_meta"]["max_turns"] == 30
assert out["runner_meta"]["parallel_tool_calls"] is False
assert out["runner_meta"]["duration_seconds"] == 12.5
assert "aob_prompt_sha" in out["runner_meta"]
# Regression guard: a tool call appearing before any message text must
# still surface in history[0].tool_calls (not just tool_call_count).
assert len(out["history"]) >= 1
turn0 = out["history"][0]
assert turn0["content"] == ""
assert len(turn0["tool_calls"]) == 1
assert turn0["tool_calls"][0]["name"] == "iot.list_sensors"
assert turn0["tool_calls"][0]["output"] == "[]"
# Sanity check: the final assistant content made it into the last turn.
assert out["history"][-1]["content"] == "final answer text"
def test_serialize_run_result_warns_on_orphan_tool_output(caplog):
from scripts.aat_runner import _serialize_run_result
args = _stub_args()
result = _stub_run_result(items=[_tool_output_item("late output")])
with caplog.at_level(logging.WARNING, logger="aat_runner"):
out = _serialize_run_result(args, "test prompt", result, duration_seconds=1.0)
assert out["success"] is True
assert "without a pending tool call" in caplog.text
def test_serialize_run_result_max_turns_exhausted():
from scripts.aat_runner import _serialize_run_result
args = _stub_args()
result = _stub_run_result(
items=[_msg_item("still thinking")],
final_output=None,
max_turns_reached=True,
)
out = _serialize_run_result(args, "test prompt", result, duration_seconds=99.0)
assert out["success"] is False
assert out["max_turns_exhausted"] is True
# ---------------------------------------------------------------------------
# #133 — token usage capture from the Agents SDK RunContextWrapper.usage
# ---------------------------------------------------------------------------
def _stub_run_result_with_usage(
*,
input_tokens: int | None = 1234,
output_tokens: int | None = 567,
total_tokens: int | None = 1801,
requests: int | None = 5,
):
"""Stub RunResult with a context_wrapper.usage that mirrors the SDK shape."""
return SimpleNamespace(
new_items=[_msg_item("answer")],
final_output="answer",
max_turns_reached=False,
raw_responses=[],
context_wrapper=SimpleNamespace(
usage=SimpleNamespace(
input_tokens=input_tokens,
output_tokens=output_tokens,
total_tokens=total_tokens,
requests=requests,
)
),
)
def test_serialize_usage_captured_when_present():
"""Trial JSON should carry the usage block from RunContextWrapper.usage."""
from scripts.aat_runner import _serialize_run_result
out = _serialize_run_result(
_stub_args(), "p", _stub_run_result_with_usage(), duration_seconds=1.0
)
assert out["usage"] == {
"input_tokens": 1234,
"output_tokens": 567,
"total_tokens": 1801,
"requests": 5,
}
def test_serialize_usage_missing_yields_null_block():
"""Older SDK / stubbed result without context_wrapper -> all-null usage block.
summary.json's aggregator distinguishes None (no data) from 0 (zero
tokens), so we deliberately don't fall back to zeros here.
"""
from scripts.aat_runner import _serialize_run_result
out = _serialize_run_result(
_stub_args(), "p", _stub_run_result(), duration_seconds=1.0
)
assert out["usage"] == {
"input_tokens": None,
"output_tokens": None,
"total_tokens": None,
"requests": None,
}
def test_serialize_usage_negative_or_non_int_treated_as_missing():
"""A malformed SDK Usage with strings / negatives shouldn't poison the block."""
from scripts.aat_runner import _serialize_run_result
out = _serialize_run_result(
_stub_args(),
"p",
_stub_run_result_with_usage(
input_tokens="not-an-int",
output_tokens=-1,
total_tokens=None,
requests=True, # bool is technically int subclass; explicitly excluded.
),
duration_seconds=1.0,
)
assert out["usage"] == {
"input_tokens": None,
"output_tokens": None,
"total_tokens": None,
"requests": None,
}
# ---------------------------------------------------------------------------
# #131 — type-specific JSON encoder (replaces default=str)
# ---------------------------------------------------------------------------
def test_json_default_serializes_datetime_and_date():
"""stdlib datetime + date land as ISO-8601 strings, matching the prior behavior."""
import datetime as dt
from scripts.aat_runner import _json_default
assert _json_default(dt.datetime(2026, 4, 28, 17, 0, 0)) == "2026-04-28T17:00:00"
assert _json_default(dt.date(2026, 4, 28)) == "2026-04-28"
def test_json_default_serializes_pandas_timestamp_when_available():
"""pandas.Timestamp -> isoformat. Skip cleanly if pandas isn't installed."""
pd = pytest.importorskip("pandas")
from scripts.aat_runner import _json_default
ts = pd.Timestamp("2026-04-28T17:00:00")
assert _json_default(ts) == ts.isoformat()
def test_json_default_serializes_numpy_datetime64_when_available():
"""numpy.datetime64 -> ISO string via pandas if both installed."""
np = pytest.importorskip("numpy")
from scripts.aat_runner import _json_default
out = _json_default(np.datetime64("2026-04-28T17:00:00"))
# Accept either pandas-routed isoformat or the raw datetime64 str()
# (which is also roundtrippable for this type specifically).
assert "2026-04-28" in out
def test_json_default_rejects_numpy_array():
"""numpy.ndarray must raise TypeError, not silently stringify (Anonymous reviewer's M5)."""
np = pytest.importorskip("numpy")
from scripts.aat_runner import _json_default
with pytest.raises(TypeError, match="numpy"):
_json_default(np.array([1, 2, 3]))
def test_json_default_rejects_pandas_dataframe():
"""pandas.DataFrame must raise TypeError, not write the human-readable table."""
pd = pytest.importorskip("pandas")
from scripts.aat_runner import _json_default
with pytest.raises(TypeError, match="pandas"):
_json_default(pd.DataFrame({"a": [1, 2, 3]}))
def test_json_default_rejects_arbitrary_object():
"""Anything outside the allow-list must raise TypeError, not stringify."""
from scripts.aat_runner import _json_default
class Unhandled:
pass
with pytest.raises(TypeError, match="unserializable"):
_json_default(Unhandled())
def test_write_output_uses_type_specific_encoder(tmp_path):
"""End-to-end: _write_output rejects a payload containing a numpy array.
The prior code would silently write '[1 2 3]'; the new code fails closed.
"""
np = pytest.importorskip("numpy")
from scripts.aat_runner import _write_output
bad_payload = {"answer": "ok", "rogue": np.array([1, 2, 3])}
with pytest.raises(TypeError, match="numpy"):
_write_output(tmp_path / "out.json", bad_payload)
def test_write_output_serializes_timestamp_payload(tmp_path):
"""The Timestamp case PR #130 originally fixed must still work."""
pd = pytest.importorskip("pandas")
from scripts.aat_runner import _write_output
payload = {"answer": "ok", "ts": pd.Timestamp("2026-04-28T17:00:00")}
out = tmp_path / "trial.json"
_write_output(out, payload)
loaded = json.loads(out.read_text())
assert loaded["ts"] == "2026-04-28T17:00:00"
def test_cli_parses_required_args():
from scripts.aat_runner import build_parser
parser = build_parser()
args = parser.parse_args(
[
"--prompt",
"p",
"--output",
"/tmp/o.json",
"--model-id",
"watsonx/x",
"--mcp-mode",
"direct",
]
)
assert args.prompt == "p"
assert args.mcp_mode == "direct"
assert args.max_turns == 30 # default
assert args.parallel_tool_calls is False # vLLM-compatible default
def test_cli_parses_parallel_tool_call_modes():
from scripts.aat_runner import build_parser
parser = build_parser()
common = [
"--prompt",
"p",
"--output",
"/tmp/o.json",
"--model-id",
"watsonx/x",
"--mcp-mode",
"direct",
"--parallel-tool-calls",
]
assert parser.parse_args(common + ["false"]).parallel_tool_calls is False
assert parser.parse_args(common + ["true"]).parallel_tool_calls is True
assert parser.parse_args(common + ["auto"]).parallel_tool_calls is None
def test_cli_missing_args_errors():
from scripts.aat_runner import build_parser
parser = build_parser()
with pytest.raises(SystemExit):
parser.parse_args(["--prompt", "p"]) # missing everything else
def test_cli_invalid_mcp_mode_errors():
from scripts.aat_runner import build_parser
parser = build_parser()
with pytest.raises(SystemExit):
parser.parse_args(
[
"--prompt",
"p",
"--output",
"/tmp/o.json",
"--model-id",
"x",
"--mcp-mode",
"nonsense",
]
)
def test_runner_threads_litellm_env(monkeypatch):
from scripts.aat_runner import AaTRunner
captured: dict[str, object] = {}
class FakeLitellmModel:
def __init__(self, model, base_url=None, api_key=None):
captured["model"] = model
captured["base_url"] = base_url
captured["api_key"] = api_key
class FakeModelSettings:
def __init__(self, **kwargs):
self.kwargs = kwargs
class FakeAgent:
def __init__(self, **kwargs):
captured["agent_kwargs"] = kwargs
class FakeRunner:
@staticmethod
async def run(agent, prompt, max_turns):
captured["prompt"] = prompt
captured["max_turns"] = max_turns
return _stub_run_result()
monkeypatch.setenv("LITELLM_BASE_URL", "http://127.0.0.1:8000/v1")
monkeypatch.setenv("LITELLM_API_KEY", "dummy-vllm-not-checked")
monkeypatch.setitem(
sys.modules,
"agents",
SimpleNamespace(
Agent=FakeAgent,
ModelSettings=FakeModelSettings,
Runner=FakeRunner,
__version__="test",
),
)
monkeypatch.setitem(sys.modules, "agents.extensions", SimpleNamespace())
monkeypatch.setitem(sys.modules, "agents.extensions.models", SimpleNamespace())
monkeypatch.setitem(
sys.modules,
"agents.extensions.models.litellm_model",
SimpleNamespace(LitellmModel=FakeLitellmModel),
)
runner = AaTRunner(model_id="openai/Llama-3.1-8B-Instruct", mcp_mode="direct")
asyncio.run(runner.run("hello"))
assert captured["model"] == "openai/Llama-3.1-8B-Instruct"
assert captured["base_url"] == "http://127.0.0.1:8000/v1"
assert captured["api_key"] == "dummy-vllm-not-checked"
assert captured["prompt"] == "hello"
assert captured["max_turns"] == 30
settings = captured["agent_kwargs"]["model_settings"]
assert settings.kwargs["parallel_tool_calls"] is False
def test_watsonx_runner_omits_openai_only_model_settings(monkeypatch):
from scripts.aat_runner import AaTRunner
captured: dict[str, object] = {}
class FakeLitellmModel:
def __init__(self, model, base_url=None, api_key=None):
captured["model"] = model
class FakeModelSettings:
def __init__(self, **kwargs):
self.kwargs = kwargs
class FakeAgent:
def __init__(self, **kwargs):
captured["agent_kwargs"] = kwargs
class FakeRunner:
@staticmethod
async def run(agent, prompt, max_turns):
return _stub_run_result()
fake_litellm = SimpleNamespace(drop_params=False)
monkeypatch.setitem(sys.modules, "litellm", fake_litellm)
monkeypatch.setitem(
sys.modules,
"agents",
SimpleNamespace(
Agent=FakeAgent,
ModelSettings=FakeModelSettings,
Runner=FakeRunner,
__version__="test",
),
)
monkeypatch.setitem(sys.modules, "agents.extensions", SimpleNamespace())
monkeypatch.setitem(sys.modules, "agents.extensions.models", SimpleNamespace())
monkeypatch.setitem(
sys.modules,
"agents.extensions.models.litellm_model",
SimpleNamespace(LitellmModel=FakeLitellmModel),
)
runner = AaTRunner(
model_id="watsonx/meta-llama/llama-3-3-70b-instruct",
mcp_mode="direct",
parallel_tool_calls=False,
)
asyncio.run(runner.run("hello"))
assert captured["model"] == "watsonx/meta-llama/llama-3-3-70b-instruct"
assert "model_settings" not in captured["agent_kwargs"]
assert fake_litellm.drop_params is True
def test_watsonx_runner_rejects_parallel_tool_calls_true(monkeypatch):
from scripts.aat_runner import AaTRunner
monkeypatch.setitem(
sys.modules,
"agents",
SimpleNamespace(
Agent=lambda **_kwargs: None,
ModelSettings=lambda **_kwargs: None,
Runner=SimpleNamespace(run=lambda *_args, **_kwargs: None),
__version__="test",
),
)
monkeypatch.setitem(sys.modules, "agents.extensions", SimpleNamespace())
monkeypatch.setitem(sys.modules, "agents.extensions.models", SimpleNamespace())
monkeypatch.setitem(
sys.modules,
"agents.extensions.models.litellm_model",
SimpleNamespace(LitellmModel=lambda **_kwargs: None),
)
runner = AaTRunner(
model_id="watsonx/meta-llama/llama-3-3-70b-instruct",
mcp_mode="direct",
parallel_tool_calls=True,
)
with pytest.raises(ValueError, match="WatsonX does not support"):
asyncio.run(runner.run("hello"))
def test_batch_mode_requires_output_dir():
from scripts.aat_runner import _main
args = argparse.Namespace(
scenarios_glob="data/scenarios/*.json",
output_dir=None,
prompt=None,
output=None,
model_id="x",
mcp_mode="optimized",
max_turns=30,
parallel_tool_calls=False,
verbose=False,
trials=1,
run_basename="batch",
)
assert asyncio.run(_main(args)) == 2
def test_batch_mode_rejects_non_optimized_mcp_mode(tmp_path):
from scripts.aat_runner import _main
args = argparse.Namespace(
scenarios_glob="nonexistent_xyzzy_*.json",
output_dir=str(tmp_path),
prompt=None,
output=None,
model_id="x",
mcp_mode="direct",
max_turns=30,
parallel_tool_calls=False,
verbose=False,
trials=1,
run_basename="batch",
)
assert asyncio.run(_main(args)) == 2
def test_batch_mode_rejects_zero_trials(tmp_path):
"""--trials must be >= 1; zero/negative must return rc=2 without creating output dir."""
from scripts.aat_runner import _main_multi
from pathlib import Path
repo_root = Path(__file__).resolve().parent.parent
new_subdir = tmp_path / "should_not_be_created"
for bad_trials in (0, -1):
args = argparse.Namespace(
scenarios_glob="nonexistent_xyzzy_*.json",
output_dir=str(new_subdir),
model_id="x",
mcp_mode="optimized",
max_turns=30,
parallel_tool_calls=False,
trials=bad_trials,
run_basename="batch",
)
rc = asyncio.run(_main_multi(args, repo_root))
assert rc == 2, f"expected rc=2 for trials={bad_trials}, got {rc}"
assert (
not new_subdir.exists()
), f"output dir must not be created for trials={bad_trials}"
def test_batch_output_dir_normalization():
"""Regression: relative --output-dir must not raise ValueError in relative_to().
Directly exercises the path arithmetic that crashed before the fix, without
calling _main_multi (which would mkdir under the repo and never reach
relative_to due to the empty-glob early-return).
"""
from pathlib import Path
repo_root = Path(__file__).resolve().parent.parent
# Simulate what _main_multi does: resolve relative arg under repo_root.
raw = Path("benchmarks/cell_C_mcp_optimized/raw/test-run")
output_dir = repo_root / raw # normalization step added by the fix
out_path = output_dir / "batch_scenario_run01.json"
# This is the exact call that raised ValueError before the fix.
rel = out_path.relative_to(repo_root)
assert rel == Path(
"benchmarks/cell_C_mcp_optimized/raw/test-run/batch_scenario_run01.json"
)
def test_batch_mode_rejects_non_optimized_before_mkdir(tmp_path):
"""M1 regression: mcp_mode guard must fire before output_dir is created."""
from scripts.aat_runner import _main_multi
from pathlib import Path
repo_root = Path(__file__).resolve().parent.parent
new_subdir = tmp_path / "should_not_be_created"
args = argparse.Namespace(
scenarios_glob="nonexistent_xyzzy_*.json",
output_dir=str(new_subdir),
model_id="x",
mcp_mode="direct",
max_turns=30,
parallel_tool_calls=False,
trials=1,
run_basename="batch",
)
rc = asyncio.run(_main_multi(args, repo_root))
assert rc == 2
assert not new_subdir.exists()
def test_batch_latency_path_outside_repo_root(tmp_path):
"""M3 regression: relative_to() fallback must not raise for absolute out-of-repo path."""
from pathlib import Path
repo_root = Path(__file__).resolve().parent.parent
out_path = tmp_path / "trial_01.json" # tmp_path is outside repo_root
# Reproduce the exact try/except logic from _main_multi latency record construction.
try:
result = out_path.relative_to(repo_root).as_posix()
except ValueError:
result = out_path.as_posix()
# tmp_path is outside repo_root, so the fallback must kick in.
assert result == out_path.as_posix()
|