openenv-sql-investigation / source /tests /test_environment.py
burtenshaw's picture
burtenshaw HF Staff
Publish procedural SQL investigation tasks and reproducible environment source
2ce79be verified
Raw History Blame Contribute Delete
8.34 kB
"""Independent checks of reward, SQL boundaries, and episode isolation."""
import json
import time
import pytest
from pydantic import ValidationError
from sql_investigation.environment import SQLInvestigationEnvironment, rows_match
from sql_investigation.models import SQLAction
from sql_investigation.tasks import TASK_IDS, build_task
@pytest.fixture
def environment():
env = SQLInvestigationEnvironment()
env.reset(task_id=TASK_IDS[0], seed=42)
try:
yield env
finally:
env.close()
@pytest.mark.parametrize("task_id", TASK_IDS)
@pytest.mark.parametrize("seed", [0, 42, 9001])
def test_oracle_submission_is_terminal_and_rewarded(task_id, seed):
task = build_task(task_id, seed)
env = SQLInvestigationEnvironment()
try:
reset = env.reset(task_id=task_id, seed=seed)
assert not reset.done
assert reset.reward == 0.0
assert task.oracle_sql not in json.dumps(reset.model_dump())
assert reset.metadata == {}
observation = env.step(SQLAction(op="submit", sql=task.oracle_sql))
assert observation.done
assert observation.reward == 1.0
assert observation.metadata == {}
assert observation.rows == []
assert observation.columns == []
finally:
task.connection.close()
env.close()
@pytest.mark.parametrize("task_id", TASK_IDS)
def test_wrong_answer_and_finish_receive_zero(task_id):
env = SQLInvestigationEnvironment()
try:
for action in (
SQLAction(op="submit", sql="SELECT '__incorrect_answer__'"),
SQLAction(op="finish"),
):
env.reset(task_id=task_id, seed=42)
observation = env.step(action)
assert observation.done
assert observation.reward == 0.0
assert observation.metadata == {}
finally:
env.close()
def test_example_sequence_and_action_budget(environment):
first = environment.step(SQLAction(op="query", sql="SELECT 1 AS ready"))
assert first.columns == ["ready"]
assert first.rows == [[1]]
assert first.reward == 0.0
assert not first.done
assert first.remaining_steps == 11
assert first.metadata == {}
final = environment.step(SQLAction(op="finish"))
assert final.done and final.reward == 0.0
environment.reset(task_id=TASK_IDS[0], seed=42)
for step in range(12):
result = environment.step(SQLAction(op="query", sql="SELECT 1"))
assert result.done == (step == 11)
assert result.remaining_steps == 11 - step
assert result.reward == 0.0
state_steps = environment.state.step_count
assert environment.step(SQLAction(op="finish")).model_dump() == result.model_dump()
assert environment.state.step_count == state_steps
@pytest.mark.parametrize(
"sql",
[
"CREATE TABLE injected(value TEXT)",
"PRAGMA query_only = OFF",
"PRAGMA writable_schema = ON",
"ATTACH DATABASE ':memory:' AS injected",
"SELECT load_extension('/tmp/forbidden_extension')",
"SELECT readfile('/etc/passwd')",
"SELECT writefile('/tmp/forbidden_sql_output', 'payload')",
"SELECT 1; SELECT 2",
"BEGIN TRANSACTION",
],
)
def test_unsafe_sql_is_rejected_and_session_recovers(environment, sql):
result = environment.step(SQLAction(op="query", sql=sql))
assert "SQL error:" in result.message
assert result.reward == 0.0
assert result.rows == []
assert not result.done
recovered = environment.step(SQLAction(op="query", sql="SELECT 1 AS intact"))
assert recovered.rows == [[1]]
def test_file_creation_is_rejected(environment, tmp_path):
destination = tmp_path / "forbidden.sqlite"
result = environment.step(SQLAction(op="query", sql=f"VACUUM INTO '{destination}'"))
assert "SQL error:" in result.message
assert not destination.exists()
def test_mutation_does_not_change_existing_data(environment):
table = environment.step(
SQLAction(
op="query",
sql="SELECT name FROM sqlite_master WHERE type='table' ORDER BY name LIMIT 1",
)
).rows[0][0]
quoted_table = '"' + table.replace('"', '""') + '"'
before = environment.step(SQLAction(op="query", sql=f"SELECT * FROM {quoted_table}"))
rejected = environment.step(SQLAction(op="query", sql=f"DELETE FROM {quoted_table}"))
assert "SQL error:" in rejected.message
after = environment.step(SQLAction(op="query", sql=f"SELECT * FROM {quoted_table}"))
assert after.columns == before.columns
assert after.rows == before.rows
def test_recursive_query_is_bounded_and_session_recovers(environment):
started = time.monotonic()
interrupted = environment.step(
SQLAction(
op="query",
sql=(
"WITH RECURSIVE loop(x) AS (VALUES(1) UNION ALL "
"SELECT x+1 FROM loop) SELECT sum(x) FROM loop"
),
)
)
assert time.monotonic() - started < 5.0
assert "SQL error:" in interrupted.message
assert interrupted.reward == 0.0
assert environment.step(SQLAction(op="query", sql="SELECT 2")).rows == [[2]]
def test_large_results_are_bounded(environment):
result = environment.step(
SQLAction(
op="query",
sql=(
"WITH RECURSIVE series(x) AS (VALUES(1) UNION ALL "
"SELECT x+1 FROM series WHERE x<200) SELECT x FROM series"
),
)
)
assert len(result.rows) == 40
assert "truncated" in result.message
assert not result.done
@pytest.mark.parametrize("sql", ["SELECT X'CAFE'", "SELECT 1e999", ""])
def test_invalid_result_values_and_empty_sql_are_rejected(environment, sql):
result = environment.step(SQLAction(op="submit", sql=sql))
assert result.done
assert result.reward == 0.0
assert "SQL error:" in result.message
def test_reset_reproduces_task_and_resets_episode_state(environment):
initial = environment.reset(task_id=TASK_IDS[0], seed=42, episode_id="first")
query = "SELECT * FROM sqlite_master ORDER BY name"
first = environment.step(SQLAction(op="query", sql=query))
reset = environment.reset(task_id=TASK_IDS[0], seed=42, episode_id="second")
assert reset.model_dump() == initial.model_dump()
assert environment.state.episode_id == "second"
assert environment.state.step_count == 0
second = environment.step(SQLAction(op="query", sql=query))
assert second.rows == first.rows
assert second.columns == first.columns
def test_parallel_instances_have_independent_state(environment):
other = SQLInvestigationEnvironment()
try:
other.reset(task_id=TASK_IDS[-1], seed=123)
first_episode = environment.state.episode_id
environment.step(SQLAction(op="query", sql="SELECT 1"))
assert other.state.step_count == 0
other.step(SQLAction(op="finish"))
assert environment.state.episode_id == first_episode
assert environment.state.step_count == 1
assert not environment.step(SQLAction(op="query", sql="SELECT 2")).done
finally:
other.close()
def test_unknown_task_fails_explicitly(environment):
with pytest.raises(ValueError, match="Unknown task_id"):
environment.reset(task_id="does-not-exist", seed=42)
def test_action_schema_rejects_unknown_fields_and_reserved_shapes():
for value in (
{"finish": True},
{"op": "finish", "unexpected": True},
{"op": "bad"},
):
with pytest.raises(ValidationError):
SQLAction.model_validate(value)
def test_reward_matches_multisets_without_coercing_text_or_null():
assert rows_match([["a", 1], ["b", 2], ["a", 1]], [["b", 2], ["a", 1], ["a", 1]])
assert not rows_match([["a", 1], ["b", 2]], [["a", 1], ["a", 1]])
assert not rows_match([[1, "a"]], [["a", 1]])
assert not rows_match([["1"]], [[1]])
assert not rows_match([[None]], [[0]])
assert rows_match([[None]], [[None]])
def test_reward_numeric_tolerance_is_absolute_and_finite():
assert rows_match([[1.00005]], [[1]])
assert not rows_match([[1.001]], [[1]])
assert not rows_match([[1_000_000.5]], [[1_000_000]])
assert not rows_match([[float("inf")]], [[float("inf")]])
assert not rows_match([[float("nan")]], [[float("nan")]])