#!/usr/bin/env python3 """Dependency-light tests for the SPAgent grid-puzzle training environment.""" from __future__ import annotations import importlib.util import os import sys import tempfile import types from pathlib import Path from PIL import Image ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from spagent.frozenlake_v3_protocol import count_explicit_images # noqa: E402 from spagent.grid_puzzle_protocol import ( # noqa: E402 FIFTEEN_TASK, SOKOBAN_TASK, build_system_prompt, build_user_prompt, canonical_fifteen_state, canonical_sokoban_state, decode_initial_state, encode_initial_state, is_solved, parse_action_tokens, render_state, replay_actions, state_text, step_state, ) _builder_spec = importlib.util.spec_from_file_location( "build_grid_puzzle_training_data", ROOT / "train" / "build_grid_puzzle_training_data.py", ) builder = importlib.util.module_from_spec(_builder_spec) assert _builder_spec.loader is not None _builder_spec.loader.exec_module(builder) def simple_sokoban_state() -> dict: return canonical_sokoban_state( rows=3, cols=5, walls={ (0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), }, goals={(1, 3)}, boxes={(1, 2)}, player=(1, 1), ) def one_move_fifteen_state() -> dict: return canonical_fifteen_state( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 15] ) def test_action_parser() -> None: assert parse_action_tokens("left, DOWN; right. up") == [ "Left", "Down", "Right", "Up" ] assert parse_action_tokens("junk") == [] def test_state_json_round_trip() -> None: state = simple_sokoban_state() assert decode_initial_state(encode_initial_state(state)) == state def test_sokoban_push_and_replay() -> None: state = simple_sokoban_state() outcome = step_state(SOKOBAN_TASK, state, "Right") assert outcome.changed assert outcome.success assert outcome.done assert state["player"] == [1, 2] assert state["boxes"] == [[1, 3]] assert replay_actions( SOKOBAN_TASK, encode_initial_state(simple_sokoban_state()), ["Right"] ) def test_sokoban_blocked_push() -> None: state = simple_sokoban_state() state["goals"] = [[1, 2]] state["boxes"] = [[1, 3]] state["player"] = [1, 2] outcome = step_state(SOKOBAN_TASK, state, "Right") assert not outcome.changed assert outcome.tool_result["error"] == "blocked_box" def test_fifteen_direction_matches_upstream() -> None: state = one_move_fifteen_state() outcome = step_state(FIFTEEN_TASK, state, "Left") assert outcome.changed assert outcome.success assert state["board"] == list(range(1, 16)) + [0] assert replay_actions( FIFTEEN_TASK, encode_initial_state(one_move_fifteen_state()), ["Left"], ) def test_fifteen_invalid_slide() -> None: solved = canonical_fifteen_state(list(range(1, 16)) + [0]) outcome = step_state(FIFTEEN_TASK, solved, "Left") assert not outcome.changed assert outcome.tool_result["error"] == "invalid_slide" assert is_solved(FIFTEEN_TASK, solved) def test_invalid_direction_type() -> None: state = one_move_fifteen_state() outcome = step_state(FIFTEEN_TASK, state, ["Left"]) assert not outcome.changed assert outcome.tool_result["error"] == "invalid_direction" assert not replay_actions( FIFTEEN_TASK, encode_initial_state(state), [["Left"]], ) def test_fifteen_solvability_filter() -> None: solved = list(range(1, 16)) + [0] unsolvable = solved.copy() unsolvable[0], unsolvable[1] = unsolvable[1], unsolvable[0] assert builder.is_fifteen_solvable(solved) assert not builder.is_fifteen_solvable(unsolvable) def test_sokoban_padding_is_deterministic() -> None: base = [ { "id": "sokoban_000000", "task_id": SOKOBAN_TASK, "initial_state": "state-a", }, { "id": "sokoban_000001", "task_id": SOKOBAN_TASK, "initial_state": "state-b", }, ] padded = builder.pad_records(base, count=5, seed=0) assert len(padded) == 5 assert len({row["initial_state"] for row in padded}) == 2 assert [row["id"] for row in padded] == [ f"sokoban_{index:06d}" for index in range(5) ] assert all("duplicate_of" in row for row in padded[2:]) assert builder.pad_records(base, count=5, seed=0) == padded def test_text_and_prompt_contract(tmp: Path) -> None: state = simple_sokoban_state() image_path = tmp / "initial.png" render_state(SOKOBAN_TASK, state, image_path) prompt = build_user_prompt(SOKOBAN_TASK, state, image_path) assert "# Initial Grid (text view, 3x5)" in prompt assert state_text(SOKOBAN_TASK, state) in prompt assert count_explicit_images(prompt) == 1 assert '"name": "move"' in build_system_prompt(SOKOBAN_TASK) def test_renderers(tmp: Path) -> None: sokoban_path = tmp / "sokoban.png" fifteen_path = tmp / "fifteen.png" render_state(SOKOBAN_TASK, simple_sokoban_state(), sokoban_path) render_state(FIFTEEN_TASK, one_move_fifteen_state(), fifteen_path) with Image.open(sokoban_path) as image: assert image.mode == "RGB" assert image.size == (360, 232) with Image.open(fifteen_path) as image: assert image.mode == "RGB" assert image.size == (360, 360) def load_plugin_with_stubs(): class FakeRolloutInferRequest: def __init__(self, **kwargs): self.__dict__.update(kwargs) class FakeScheduler: def __init__(self, max_turns=20, *args, **kwargs): self.max_turns = max_turns def check_finished(self, infer_request, response_choice, current_turn): return current_turn >= self.max_turns class FakeORM: pass class FakeLogger: def info(self, *args, **kwargs): pass def warning(self, *args, **kwargs): pass swift = types.ModuleType("swift") swift_llm = types.ModuleType("swift.llm") swift_llm.RolloutInferRequest = FakeRolloutInferRequest swift_infer = types.ModuleType("swift.llm.infer") swift_protocol = types.ModuleType("swift.llm.infer.protocol") swift_protocol.ChatCompletionResponseChoice = object swift_plugin = types.ModuleType("swift.plugin") swift_plugin.ORM = FakeORM swift_plugin.orms = {} swift_multi = types.ModuleType("swift.plugin.multi_turn") swift_multi.MultiTurnScheduler = FakeScheduler swift_multi.multi_turns = {} swift_utils = types.ModuleType("swift.utils") swift_utils.get_logger = lambda: FakeLogger() trainer = types.ModuleType("grpo_filtered_trainer") trainer.CURRENT_STEP = 0 modules = { "swift": swift, "swift.llm": swift_llm, "swift.llm.infer": swift_infer, "swift.llm.infer.protocol": swift_protocol, "swift.plugin": swift_plugin, "swift.plugin.multi_turn": swift_multi, "swift.utils": swift_utils, "grpo_filtered_trainer": trainer, } previous = {name: sys.modules.get(name) for name in modules} sys.modules.update(modules) try: spec = importlib.util.spec_from_file_location( "grid_puzzle_plugin_under_test", ROOT / "train" / "grid_puzzle_plugin.py", ) module = importlib.util.module_from_spec(spec) assert spec.loader is not None spec.loader.exec_module(module) return module, FakeRolloutInferRequest finally: for name, old in previous.items(): if old is None: sys.modules.pop(name, None) else: sys.modules[name] = old def test_reward_and_scheduler_step(tmp: Path) -> None: plugin, request_type = load_plugin_with_stubs() initial = one_move_fifteen_state() encoded = encode_initial_state(initial) completion = "One move.Left" assert plugin.GridPuzzleReward()( [completion], [FIFTEEN_TASK], [encoded] ) == [1.0] assert plugin.GridPuzzleReward()( ["Push.Right"], [SOKOBAN_TASK], [encode_initial_state(simple_sokoban_state())], ) == [1.0] assert plugin.GridPuzzleFormatReward()([completion]) == [0.5] initial_image = tmp / "initial_fifteen.png" render_state(FIFTEEN_TASK, initial, initial_image) old_dir = os.environ.get("GRID_PUZZLE_IMG_DIR") os.environ["GRID_PUZZLE_IMG_DIR"] = str(tmp / "rollout") try: scheduler = plugin.GridPuzzleScheduler(max_turns=5) request = request_type( messages=[ {"role": "system", "content": "system"}, {"role": "user", "content": "user"}, ], images=[str(initial_image)], audios=None, videos=None, tools=None, objects=None, data_dict={ "task_id": FIFTEEN_TASK, "initial_state": encoded, }, ) choice = types.SimpleNamespace( message=types.SimpleNamespace( content=( "Slide 15 left." '{"name":"move","arguments":' '{"direction":"Left"}}' ) ) ) result = scheduler.step(request, choice, 1) assert result["rollout_infos"]["gp_success"] next_request = result["infer_request"] assert len(next_request.images) == 2 assert Path(next_request.images[-1]).is_file() assert "[image:" in next_request.messages[-1]["content"] final_choice = types.SimpleNamespace( message=types.SimpleNamespace(content=completion) ) assert scheduler.check_finished(next_request, final_choice, 2) for malformed_content, expected_phrase in ( ( "Bad shape.[]", "JSON value must be an object", ), ( ( "Bad arguments." '{"name":"move","arguments":["Left"]}' "" ), "`arguments` must be a JSON object", ), ): malformed_request = request_type( messages=[ {"role": "system", "content": "system"}, {"role": "user", "content": "user"}, ], images=[str(initial_image)], audios=None, videos=None, tools=None, objects=None, data_dict={ "task_id": FIFTEEN_TASK, "initial_state": encoded, }, ) malformed_choice = types.SimpleNamespace( message=types.SimpleNamespace(content=malformed_content) ) malformed_result = scheduler.step( malformed_request, malformed_choice, 1 ) assert len(malformed_result["infer_request"].images) == 1 assert count_explicit_images( malformed_result["infer_request"].messages[-1]["content"] ) == 1 logged_tool_result = malformed_result["rollout_infos"] assert not logged_tool_result["gp_success"] continuation = malformed_result["infer_request"].messages[-1][ "content" ] assert expected_phrase in continuation finally: if old_dir is None: os.environ.pop("GRID_PUZZLE_IMG_DIR", None) else: os.environ["GRID_PUZZLE_IMG_DIR"] = old_dir def main() -> None: with tempfile.TemporaryDirectory() as directory: tmp = Path(directory) test_action_parser() test_state_json_round_trip() test_sokoban_push_and_replay() test_sokoban_blocked_push() test_fifteen_direction_matches_upstream() test_fifteen_invalid_slide() test_invalid_direction_type() test_fifteen_solvability_filter() test_sokoban_padding_is_deterministic() test_text_and_prompt_contract(tmp) test_renderers(tmp) test_reward_and_scheduler_step(tmp) print("grid-puzzle training tests passed") if __name__ == "__main__": main()