File size: 8,335 Bytes
2ce79be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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")]])