File size: 21,312 Bytes
9e64e71 | 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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 | """Unit tests for the TRL adapter shell."""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
import pytest
from sql_env.models import SQLAction
from sql_env.server.sql_environment import SQLEnvironment
from sql_env.training.notebook_pipeline import build_trainer
from sql_env.training.trl_adapter import (
SQLEnvTRL,
_REPEAT_PENALTY,
_MinimalTokenizer,
sql_env_reward_func,
)
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_QUESTIONS_PATH = _PROJECT_ROOT / "data/questions/student_assessment.json"
_DB_DIR = _PROJECT_ROOT / "data/databases"
@pytest.fixture(autouse=True)
def _reset_class_configuration() -> None:
previous_questions_path = SQLEnvTRL._questions_path
previous_db_dir = SQLEnvTRL._db_dir
previous_step_budget = SQLEnvTRL._step_budget
SQLEnvTRL._questions_path = None
SQLEnvTRL._db_dir = None
SQLEnvTRL._step_budget = 10
yield
SQLEnvTRL._questions_path = previous_questions_path
SQLEnvTRL._db_dir = previous_db_dir
SQLEnvTRL._step_budget = previous_step_budget
def test_minimal_tokenizer_apply_chat_template() -> None:
tokenizer = _MinimalTokenizer()
rendered = tokenizer.apply_chat_template(
[
{"role": "user", "content": "hi"},
]
)
assert isinstance(rendered, str)
def test_minimal_tokenizer_empty_messages() -> None:
tokenizer = _MinimalTokenizer()
rendered = tokenizer.apply_chat_template([])
assert isinstance(rendered, str)
def test_configure_sets_class_attrs() -> None:
SQLEnvTRL._configure(
questions_path="q.json",
db_dir="dbs",
step_budget=10,
)
assert SQLEnvTRL._questions_path == "q.json"
assert SQLEnvTRL._db_dir == "dbs"
assert SQLEnvTRL._step_budget == 10
def test_configure_custom_step_budget() -> None:
SQLEnvTRL._configure(
questions_path="q.json",
db_dir="dbs",
step_budget=5,
)
assert SQLEnvTRL._step_budget == 5
def test_configure_default_step_budget() -> None:
SQLEnvTRL._configure(
questions_path="q.json",
db_dir="dbs",
)
assert SQLEnvTRL._step_budget == 10
def test_configure_is_classmethod() -> None:
SQLEnvTRL._configure(
questions_path="q.json",
db_dir="dbs",
step_budget=8,
)
assert SQLEnvTRL._questions_path == "q.json"
assert SQLEnvTRL._db_dir == "dbs"
assert SQLEnvTRL._step_budget == 8
def test_configure_overwrites_previous() -> None:
SQLEnvTRL._configure(
questions_path="one.json",
db_dir="one-dbs",
step_budget=3,
)
SQLEnvTRL._configure(
questions_path="two.json",
db_dir="two-dbs",
step_budget=9,
)
assert SQLEnvTRL._questions_path == "two.json"
assert SQLEnvTRL._db_dir == "two-dbs"
assert SQLEnvTRL._step_budget == 9
def test_init_after_configure() -> None:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
step_budget=10,
)
adapter = SQLEnvTRL()
assert isinstance(adapter._env, SQLEnvironment)
def test_init_no_args() -> None:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
assert isinstance(adapter, SQLEnvTRL)
def test_init_without_configure_raises() -> None:
with pytest.raises(RuntimeError):
SQLEnvTRL()
def test_init_sets_reward_zero() -> None:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
assert adapter.reward == 0.0
def test_init_sets_done_false() -> None:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
assert adapter._done is False
def test_init_invalid_questions_path() -> None:
SQLEnvTRL._configure(
questions_path="/no/such/file.json",
db_dir=str(_DB_DIR),
)
with pytest.raises(FileNotFoundError):
SQLEnvTRL()
def test_init_invalid_db_dir() -> None:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir="/no/such/dir",
)
with pytest.raises(FileNotFoundError):
SQLEnvTRL()
class _RecordingEnv:
def __init__(self, observations: list[SimpleNamespace]) -> None:
self._observations = observations
self.actions: list[SQLAction] = []
def step(self, action: SQLAction) -> SimpleNamespace:
self.actions.append(action)
return self._observations.pop(0)
class _ResetRecordingEnv:
def __init__(self, observations: list[SimpleNamespace]) -> None:
self._observations = observations
self.reset_calls: list[dict[str, object]] = []
def reset(self, *, seed: int | None = None) -> SimpleNamespace:
self.reset_calls.append({"seed": seed})
return self._observations.pop(0)
class _RecordingEnvWithReset:
def __init__(
self,
*,
step_observations: list[SimpleNamespace],
reset_observations: list[SimpleNamespace],
) -> None:
self._step_observations = step_observations
self._reset_observations = reset_observations
self.actions: list[SQLAction] = []
self.reset_calls: list[dict[str, object]] = []
def step(self, action: SQLAction) -> SimpleNamespace:
self.actions.append(action)
return self._step_observations.pop(0)
def reset(self, *, seed: int | None = None) -> SimpleNamespace:
self.reset_calls.append({"seed": seed})
return self._reset_observations.pop(0)
def _observation(
*,
result: str = "ok",
reward: float | None = 0.0,
done: bool = False,
) -> SimpleNamespace:
return SimpleNamespace(result=result, error="", reward=reward, done=done)
def _build_adapter_with_recording_env(
observation: SimpleNamespace,
) -> tuple[SQLEnvTRL, _RecordingEnv]:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
recording_env = _RecordingEnv([observation])
adapter._env = recording_env
return adapter, recording_env
def _build_adapter_with_recording_observations(
observations: list[SimpleNamespace],
) -> tuple[SQLEnvTRL, _RecordingEnv]:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
recording_env = _RecordingEnv(observations)
adapter._env = recording_env
return adapter, recording_env
def _build_adapter_with_reset_env(
observations: list[SimpleNamespace],
) -> tuple[SQLEnvTRL, _ResetRecordingEnv]:
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
reset_env = _ResetRecordingEnv(observations)
adapter._env = reset_env
return adapter, reset_env
def test_describe_dispatches_action_and_accumulates_reward() -> None:
observation = SimpleNamespace(result="schema", reward=0.25, done=False)
adapter, recording_env = _build_adapter_with_recording_env(observation)
result = adapter.describe("employees")
assert result == "schema"
assert adapter.reward == 0.25
assert adapter._done is False
assert recording_env.actions == [
SQLAction(action_type="DESCRIBE", argument="employees")
]
def test_sample_dispatches_action_and_accumulates_reward() -> None:
observation = SimpleNamespace(result="rows", reward=0.1, done=False)
adapter, recording_env = _build_adapter_with_recording_env(observation)
result = adapter.sample("employees")
assert result == "rows"
assert adapter.reward == 0.1
assert adapter._done is False
assert recording_env.actions == [
SQLAction(action_type="SAMPLE", argument="employees")
]
def test_query_dispatches_action_and_accumulates_reward() -> None:
observation = SimpleNamespace(result="query output", reward=0.5, done=False)
adapter, recording_env = _build_adapter_with_recording_env(observation)
result = adapter.query("SELECT 1")
assert result == "query output"
assert adapter.reward == 0.5
assert adapter._done is False
assert recording_env.actions == [
SQLAction(action_type="QUERY", argument="SELECT 1")
]
def test_answer_dispatches_action_sets_done_and_accumulates_reward() -> None:
observation = SimpleNamespace(
result="Answer submitted: correct.", reward=1.0, done=True
)
adapter, recording_env = _build_adapter_with_recording_env(observation)
result = adapter.answer("42")
assert result == "Answer submitted: correct."
assert adapter.reward == 1.0
assert adapter._done is True
assert recording_env.actions == [SQLAction(action_type="ANSWER", argument="42")]
def test_query_repeat_penalty_applies_on_exact_repeat() -> None:
adapter, _ = _build_adapter_with_recording_observations(
[_observation(), _observation()]
)
adapter.query("SELECT 1")
adapter.query("SELECT 1")
assert adapter.reward == pytest.approx(_REPEAT_PENALTY)
assert adapter._repeat_count == 1
def test_query_repeat_penalty_not_applied_for_different_sql() -> None:
adapter, _ = _build_adapter_with_recording_observations(
[_observation(), _observation()]
)
adapter.query("SELECT 1")
adapter.query("SELECT 2")
assert adapter.reward == pytest.approx(0.0)
assert adapter._repeat_count == 0
def test_repeat_penalty_not_applied_for_different_method_same_argument() -> None:
adapter, _ = _build_adapter_with_recording_observations(
[_observation(), _observation()]
)
adapter.describe("employees")
adapter.sample("employees")
assert adapter.reward == pytest.approx(0.0)
assert adapter._repeat_count == 0
def test_reset_clears_recent_call_tracker_for_penalty() -> None:
reset_obs = SimpleNamespace(
question="Q",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
)
SQLEnvTRL._configure(
questions_path=str(_QUESTIONS_PATH),
db_dir=str(_DB_DIR),
)
adapter = SQLEnvTRL()
adapter._env = _RecordingEnvWithReset(
step_observations=[_observation(), _observation(), _observation()],
reset_observations=[reset_obs],
)
adapter.query("SELECT 1")
adapter.query("SELECT 1")
reward_before_reset = adapter.reward
adapter.reset()
adapter.query("SELECT 1")
assert reward_before_reset == pytest.approx(_REPEAT_PENALTY)
assert adapter.reward == pytest.approx(0.0)
assert adapter._repeat_count == 0
def test_repeat_penalty_catches_alternating_reuse_within_window() -> None:
adapter, _ = _build_adapter_with_recording_observations(
[_observation(), _observation(), _observation()]
)
adapter.query("A")
adapter.query("B")
adapter.query("A")
assert adapter.reward == pytest.approx(_REPEAT_PENALTY)
assert adapter._repeat_count == 1
def test_repeat_penalty_stacks_for_three_identical_calls() -> None:
adapter, _ = _build_adapter_with_recording_observations(
[_observation(), _observation(), _observation()]
)
adapter.query("SELECT 1")
adapter.query("SELECT 1")
adapter.query("SELECT 1")
assert adapter.reward == pytest.approx(_REPEAT_PENALTY * 2)
assert adapter._repeat_count == 2
def test_repeat_count_matches_penalty_fire_count_across_methods() -> None:
adapter, _ = _build_adapter_with_recording_observations(
[_observation(), _observation(), _observation(), _observation(), _observation()]
)
adapter.describe("t")
adapter.describe("t")
adapter.sample("t")
adapter.sample("t")
adapter.describe("t")
assert adapter._repeat_count == 3
assert adapter.reward == pytest.approx(_REPEAT_PENALTY * 3)
@pytest.mark.parametrize(
"method_name, argument",
[
("describe", "employees"),
("sample", "employees"),
("query", "SELECT 1"),
("answer", "42"),
],
)
def test_tool_methods_raise_when_episode_is_over(
method_name: str, argument: str
) -> None:
observation = SimpleNamespace(result="unused", reward=0.0, done=False)
adapter, _ = _build_adapter_with_recording_env(observation)
adapter._done = True
with pytest.raises(ValueError, match="Episode is over"):
getattr(adapter, method_name)(argument)
def test_tool_method_docstrings_include_args_and_returns_sections() -> None:
for method_name in ["describe", "sample", "query", "answer"]:
doc = getattr(SQLEnvTRL, method_name).__doc__
assert isinstance(doc, str)
assert "Args:" in doc
assert "Returns:" in doc
def test_tool_methods_have_annotations() -> None:
assert SQLEnvTRL.describe.__annotations__ == {
"table_name": "str",
"return": "str",
}
assert SQLEnvTRL.sample.__annotations__ == {
"table_name": "str",
"return": "str",
}
assert SQLEnvTRL.query.__annotations__ == {
"sql": "str",
"return": "str",
}
assert SQLEnvTRL.answer.__annotations__ == {
"value": "str",
"return": "str",
}
def test_reset_returns_observation_string() -> None:
adapter, reset_env = _build_adapter_with_reset_env(
[
SimpleNamespace(
question="How many students?",
schema_info="student(id, name)",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
)
]
)
observation_text = adapter.reset()
assert isinstance(observation_text, str)
assert observation_text.strip() != ""
assert reset_env.reset_calls == [{"seed": None}]
def test_reset_clears_reward() -> None:
adapter, _ = _build_adapter_with_reset_env(
[
SimpleNamespace(
question="Q",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
)
]
)
adapter.reward = 3.5
adapter.reset()
assert adapter.reward == 0.0
def test_reset_clears_done() -> None:
adapter, _ = _build_adapter_with_reset_env(
[
SimpleNamespace(
question="Q",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
)
]
)
adapter._done = True
adapter.reset()
assert adapter._done is False
def test_reset_accepts_kwargs() -> None:
adapter, reset_env = _build_adapter_with_reset_env(
[
SimpleNamespace(
question="Q",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
)
]
)
observation_text = adapter.reset(foo="bar")
assert isinstance(observation_text, str)
assert reset_env.reset_calls == [{"seed": None}]
def test_reset_multiple_times() -> None:
adapter, reset_env = _build_adapter_with_reset_env(
[
SimpleNamespace(
question="Q1",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
),
SimpleNamespace(
question="Q2",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
),
SimpleNamespace(
question="Q3",
schema_info="schema",
result="",
error="",
step_count=0,
budget_remaining=10,
action_history=[],
done=False,
reward=None,
),
]
)
first = adapter.reset()
adapter.reward = 1.5
adapter._done = True
second = adapter.reset()
adapter.reward = 2.0
adapter._done = True
third = adapter.reset()
assert isinstance(first, str)
assert isinstance(second, str)
assert isinstance(third, str)
assert adapter.reward == 0.0
assert adapter._done is False
assert reset_env.reset_calls == [{"seed": None}, {"seed": None}, {"seed": None}]
def test_reward_func_reads_accumulated_rewards() -> None:
env_one = SimpleNamespace(reward=0.5)
env_two = SimpleNamespace(reward=1.0)
env_three = SimpleNamespace(reward=0.0)
rewards = sql_env_reward_func([env_one, env_two, env_three])
assert rewards == [0.5, 1.0, 0.0]
def test_reward_func_empty_list() -> None:
rewards = sql_env_reward_func([])
assert rewards == []
def test_reward_func_single_env() -> None:
env = SimpleNamespace(reward=0.75)
rewards = sql_env_reward_func([env])
assert rewards == [0.75]
def test_reward_func_ignores_kwargs() -> None:
env = SimpleNamespace(reward=2.25)
rewards = sql_env_reward_func([env], completions=[], foo="bar")
assert rewards == [2.25]
def test_reward_func_returns_list_of_floats() -> None:
env_one = SimpleNamespace(reward=1)
env_two = SimpleNamespace(reward=0.25)
rewards = sql_env_reward_func([env_one, env_two])
assert isinstance(rewards, list)
assert all(isinstance(value, float) for value in rewards)
class _BuildTrainerConfigRecorder:
def __init__(self, **kwargs: object) -> None:
self.kwargs = kwargs
class _BuildTrainerClassRecorder:
def __init__(self, **kwargs: object) -> None:
self.kwargs = kwargs
class _EnvironmentFactoryWithConfigure:
configure_calls: list[dict[str, object]] = []
@classmethod
def configure(
cls,
*,
questions_path: str,
db_dir: str,
step_budget: int,
) -> None:
cls.configure_calls.append(
{
"questions_path": questions_path,
"db_dir": db_dir,
"step_budget": step_budget,
}
)
class _EnvironmentFactoryWithoutConfigure:
pass
def _build_trainer_config() -> SimpleNamespace:
return SimpleNamespace(
output_dir="outputs/test",
learning_rate=1e-5,
per_device_train_batch_size=2,
gradient_accumulation_steps=2,
num_train_epochs=1,
logging_steps=1,
max_new_tokens=128,
num_generations=2,
questions_path="data/questions/student_assessment.json",
db_dir="data/databases",
step_budget=7,
)
def test_build_trainer_with_environment_factory() -> None:
_EnvironmentFactoryWithConfigure.configure_calls = []
config = _build_trainer_config()
trainer = build_trainer(
model=object(),
tokenizer=object(),
prompts=["prompt"],
config=config,
trl_grpo_config_cls=_BuildTrainerConfigRecorder,
grpo_trainer_cls=_BuildTrainerClassRecorder,
reward_funcs=[sql_env_reward_func],
environment_factory=_EnvironmentFactoryWithConfigure,
)
assert trainer.kwargs["environment_factory"] is _EnvironmentFactoryWithConfigure
assert _EnvironmentFactoryWithConfigure.configure_calls == [
{
"questions_path": config.questions_path,
"db_dir": config.db_dir,
"step_budget": config.step_budget,
}
]
def test_build_trainer_without_environment_factory() -> None:
config = _build_trainer_config()
trainer = build_trainer(
model=object(),
tokenizer=object(),
prompts=["prompt"],
config=config,
trl_grpo_config_cls=_BuildTrainerConfigRecorder,
grpo_trainer_cls=_BuildTrainerClassRecorder,
reward_funcs=[sql_env_reward_func],
environment_factory=None,
)
assert "environment_factory" not in trainer.kwargs
def test_build_trainer_passes_reward_funcs() -> None:
config = _build_trainer_config()
reward_funcs = [sql_env_reward_func]
trainer = build_trainer(
model=object(),
tokenizer=object(),
prompts=["prompt"],
config=config,
trl_grpo_config_cls=_BuildTrainerConfigRecorder,
grpo_trainer_cls=_BuildTrainerClassRecorder,
reward_funcs=reward_funcs,
environment_factory=_EnvironmentFactoryWithoutConfigure,
)
assert trainer.kwargs["reward_funcs"] == reward_funcs
|