"""An isolated in-memory SQL lab. No runtime files, network, or secrets needed.""" import math import secrets import sqlite3 import time import uuid from openenv.core.env_server.interfaces import Environment from openenv.core.env_server.types import State from .models import SQLAction, SQLObservation from .tasks import TASK_IDS, build_task MAX_STEPS = 12 ALLOWED_FUNCTIONS = frozenset( """abs avg count sum total min max round coalesce ifnull nullif iif length lower upper trim ltrim rtrim substr substring instr replace date time datetime julianday unixepoch strftime row_number rank dense_rank percent_rank cume_dist ntile lag lead first_value last_value nth_value group_concat string_agg typeof cast sign mod ceil ceiling floor sqrt pow power """.split() ) def rows_match(actual, expected): """Compare multisets, preserving duplicate rows and column positions.""" if len(actual) != len(expected): return False unmatched = list(expected) for row in actual: for index, target in enumerate(unmatched): if len(row) != len(target): continue matches = True for a, b in zip(row, target): if isinstance(a, (int, float)) and isinstance(b, (int, float)): matches = ( math.isfinite(a) and math.isfinite(b) and math.isclose(a, b, rel_tol=0, abs_tol=1e-4) ) else: matches = type(a) is type(b) and a == b if not matches: break if matches: unmatched.pop(index) break else: return False return True class SQLInvestigationEnvironment(Environment): SUPPORTS_CONCURRENT_SESSIONS = True def __init__(self): super().__init__() self._state = State(episode_id="", step_count=0) self._task = None self._done = False self._last = None @property def state(self): return self._state def reset(self, seed=None, episode_id=None, task_id=None, **kwargs): self.close() task_id = task_id or TASK_IDS[0] if task_id not in TASK_IDS: raise ValueError(f"Unknown task_id: {task_id}") # Each unseeded reset is a fresh problem, including parallel GRPO rollouts. self._task = build_task(task_id, seed if seed is not None else secrets.randbits(63)) conn = self._task.connection conn.execute("PRAGMA query_only = ON") conn.enable_load_extension(False) conn.setlimit(sqlite3.SQLITE_LIMIT_LENGTH, 100_000) conn.setlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH, 8000) conn.setlimit(sqlite3.SQLITE_LIMIT_COLUMN, 100) conn.setlimit(sqlite3.SQLITE_LIMIT_EXPR_DEPTH, 50) conn.setlimit(sqlite3.SQLITE_LIMIT_COMPOUND_SELECT, 20) conn.set_authorizer(self._authorize) self._state = State(episode_id=episode_id or str(uuid.uuid4()), step_count=0) self._done = False self._last = SQLObservation( message=( f"{self._task.instruction}\n\nDatabase schema:\n{self._task.schema}\n\n" "Use op=query with SQL to inspect data, then op=submit with your final SQL. " "The submitted result must have exactly the requested columns in order and all expected rows. " "Row order is ignored; duplicate rows count. Numeric tolerance is 0.0001. " "Reward is 1 for a fully correct result, otherwise 0. " "You have 12 actions. Queries display at most 40 rows; use aggregates or LIMIT/OFFSET. " "op=finish gives reward 0. Only read-only SQLite queries are allowed." ), reward=0.0, ) return self._last @staticmethod def _authorize(code, arg1, arg2, database, source): if code in (sqlite3.SQLITE_SELECT, sqlite3.SQLITE_READ, sqlite3.SQLITE_RECURSIVE): return sqlite3.SQLITE_OK if code == sqlite3.SQLITE_FUNCTION and (arg2 or "").lower() in ALLOWED_FUNCTIONS: return sqlite3.SQLITE_OK return sqlite3.SQLITE_DENY def _execute(self, sql): if not sql.strip(): raise ValueError("Provide a SELECT or WITH query in sql.") conn = self._task.connection deadline = time.monotonic() + 1.0 ticks = 0 def interrupted(): nonlocal ticks ticks += 1 return ticks >= 500 or time.monotonic() > deadline conn.set_progress_handler(interrupted, 1000) try: cursor = conn.execute(sql) if cursor.description is None: raise ValueError("A query must return a result table.") columns = [col[0][:120] for col in cursor.description] rows = [list(row) for row in cursor.fetchmany(101)] if any(isinstance(value, bytes) for row in rows for value in row): raise ValueError("Binary result values are not supported.") if any( isinstance(value, float) and not math.isfinite(value) for row in rows for value in row ): raise ValueError("Non-finite numeric result values are not supported.") return columns, rows finally: conn.set_progress_handler(None, 0) def step(self, action: SQLAction, timeout_s=None, **kwargs): if self._task is None: raise RuntimeError("Reset before stepping.") if self._done: return self._last self._state.step_count += 1 reward = 0.0 columns, rows = [], [] self._done = action.op in ("submit", "finish") or self._state.step_count >= MAX_STEPS if action.op == "finish": message = "Episode finished without a submitted answer." else: try: columns, rows = self._execute(action.sql) if action.op == "submit": reward = float(len(rows) <= 100 and rows_match(rows, self._task.expected_rows)) message = "Correct result." if reward else "The submitted result is incorrect." # Do not reveal reference answers, or repeat final result tables. columns, rows = [], [] else: truncated = len(rows) > 40 rows = rows[:40] rows = [[v[:300] if isinstance(v, str) else v for v in row] for row in rows] # Bound observation size even for wide SELECT statements. while rows and len(str(rows)) > 12_000: rows.pop() truncated = True message = ( "Query result (truncated; use aggregates or LIMIT/OFFSET)." if truncated else "Query result." ) except (sqlite3.Error, ValueError) as exc: message = f"SQL error: {str(exc)[:250]}" if self._done and action.op == "query": message += " Action budget exhausted without a submitted answer." self._last = SQLObservation( message=message, columns=columns, rows=rows, reward=reward, done=self._done, remaining_steps=MAX_STEPS - self._state.step_count, ) return self._last def close(self): if self._task is not None: self._task.connection.close() self._task = None