Deadman922 commited on
Commit
4262d17
·
verified ·
1 Parent(s): e102f6d

Delete server/environment.py

Browse files
Files changed (1) hide show
  1. server/environment.py +0 -509
server/environment.py DELETED
@@ -1,509 +0,0 @@
1
- """SQL Quality Environment - Core environment manager."""
2
-
3
- from __future__ import annotations
4
-
5
- import random as _random
6
- import sqlite3
7
- import threading
8
- import uuid
9
- from typing import Any, Dict
10
-
11
- from fastapi import HTTPException
12
-
13
- from server.models import (
14
- ActionType,
15
- SQLAction,
16
- SQLObservation,
17
- SQLReward,
18
- SQLState,
19
- StepResponse,
20
- TrajectoryStep,
21
- )
22
- from server.tasks import (
23
- create_dedup_bug_task,
24
- create_fk_integrity_task,
25
- create_null_audit_task,
26
- create_schema_drift_task,
27
- create_type_repair_task,
28
- )
29
-
30
- TASK_CREATORS = {
31
- "null_audit": create_null_audit_task,
32
- "type_repair": create_type_repair_task,
33
- "dedup_bug": create_dedup_bug_task,
34
- "fk_integrity": create_fk_integrity_task,
35
- "schema_drift": create_schema_drift_task,
36
- }
37
-
38
-
39
- class SQLQualityEnvironment:
40
- """Main environment class for SQL Quality tasks."""
41
-
42
- def __init__(self) -> None:
43
- """Initialize environment."""
44
- self._current_task_id: str | None = None
45
- self._episode_id: str | None = None
46
- self._attempt_number: int = 1
47
- self._step_count: int = (
48
- 0 # increments on every action (QUERY, PROFILE, FIX, SUBMIT)
49
- )
50
- self._max_steps_per_episode: int = 20 # prevent infinite loops
51
- self._cumulative_reward: float = 0.0
52
- self._done: bool = False
53
- self._ground_truth: Dict[str, Any] = {}
54
- self._cached_observation: SQLObservation | None = None
55
- self._lock = threading.Lock()
56
- # NEW: Multi-step trajectory support
57
- self._trajectory: list = []
58
- self._original_snapshot: dict = {}
59
- self._original_conn: sqlite3.Connection | None = None
60
- self._active: bool = False
61
- self._last_feedback: str | None = None
62
-
63
- def reset(self, task_id: str, seed: int | None = None) -> SQLObservation:
64
- """Reset environment for a new episode.
65
-
66
- Args:
67
- task_id: One of the registered task IDs
68
- seed: Optional deterministic episode seed
69
-
70
- Returns:
71
- SQLObservation for the new episode
72
-
73
- Raises:
74
- ValueError: If task_id is not valid
75
- """
76
- with self._lock:
77
- # ── NEW: close any live connection from the previous episode ──────
78
- if hasattr(self, "_original_conn") and self._original_conn is not None:
79
- try:
80
- self._original_conn.close()
81
- except Exception:
82
- pass # Already closed or never opened — safe to ignore
83
- self._original_conn = None
84
-
85
- # Validate task_id
86
- if task_id not in TASK_CREATORS:
87
- raise ValueError(f"Invalid task_id: {task_id}")
88
-
89
- # Generate new episode
90
- self._episode_id = str(uuid.uuid4())
91
- self._attempt_number = 1
92
- self._step_count = (
93
- 0 # increments on every action (QUERY, PROFILE, FIX, SUBMIT)
94
- )
95
- self._cumulative_reward = 0.0
96
- self._done = False
97
- self._current_task_id = task_id
98
- self._trajectory = []
99
- self._original_snapshot = {}
100
- self._ground_truth = {}
101
- self._cached_observation = None
102
- self._last_feedback = None
103
-
104
- # Create task-specific database to extract observation data
105
- conn = None
106
- try:
107
- # Generate random episode seed for diversity
108
- episode_seed = seed if seed is not None else _random.randint(0, 2**31 - 1)
109
- creator = TASK_CREATORS[task_id]
110
- conn, observation, self._ground_truth = creator(episode_seed)
111
-
112
- # Store original connection for graders (read-only use)
113
- self._original_conn = conn
114
-
115
- # Snapshot the target table for data preservation grading
116
- target_table = self._ground_truth.get("table", "")
117
- if target_table:
118
- from server.graders import _snapshot_table
119
-
120
- self._original_snapshot = _snapshot_table(conn, target_table)
121
-
122
- # Mark episode as active
123
- self._active = True
124
-
125
- # Cache observation for reuse in step()
126
- self._cached_observation = observation.model_copy(
127
- update={"episode_id": self._episode_id}
128
- )
129
-
130
- # Keep connection open for multi-step operations
131
- # Connection will be closed when episode ends or environment is reset
132
-
133
- except Exception as e:
134
- if conn is not None:
135
- conn.close()
136
- raise e
137
-
138
- return self._cached_observation
139
-
140
- def step(self, action: SQLAction) -> StepResponse:
141
- """
142
- Execute one agent action and return the resulting observation and reward.
143
-
144
- Routes by action_type:
145
- QUERY — execute SELECT on episode conn, return result in observation
146
- PROFILE — compute column statistics, return in observation
147
- FIX — execute on fresh_test_db(), score partially, continue episode
148
- SUBMIT — call compute_episode_score(), end episode
149
- """
150
- with self._lock:
151
- if not self._active:
152
- raise HTTPException(
153
- status_code=422, detail="No active episode. Call reset() first."
154
- )
155
- if self._done:
156
- raise HTTPException(
157
- status_code=422,
158
- detail="Episode is already done. Call reset() to start a new episode.",
159
- )
160
-
161
- # Check max steps guard
162
- if self._step_count >= self._max_steps_per_episode:
163
- raise HTTPException(
164
- status_code=422,
165
- detail="Max investigation steps reached. Call SUBMIT or reset().",
166
- )
167
-
168
- action = self._normalize_action(action)
169
-
170
- action_type = action.action_type
171
-
172
- # --- QUERY action ---
173
- if action_type == ActionType.QUERY:
174
- return self._handle_query(action)
175
-
176
- # --- PROFILE action ---
177
- elif action_type == ActionType.PROFILE:
178
- return self._handle_profile(action)
179
-
180
- # --- FIX action ---
181
- elif action_type == ActionType.FIX:
182
- return self._handle_fix(action)
183
-
184
- # --- SUBMIT action (or legacy single-step) ---
185
- else:
186
- return self._handle_submit(action)
187
-
188
- def _normalize_action(self, action: SQLAction) -> SQLAction:
189
- """Infer v2 action_type for backward-compatible payloads without action_type."""
190
- if "action_type" in action.model_fields_set:
191
- return action
192
-
193
- inferred = ActionType.SUBMIT
194
- if action.column_name:
195
- inferred = ActionType.PROFILE
196
- elif action.fix_query:
197
- inferred = ActionType.FIX
198
- elif action.sql:
199
- inferred = (
200
- ActionType.QUERY
201
- if action.sql.strip().upper().startswith("SELECT")
202
- else ActionType.FIX
203
- )
204
- elif action.answer or action.root_cause_table or action.offending_key:
205
- inferred = ActionType.SUBMIT
206
-
207
- return action.model_copy(update={"action_type": inferred})
208
-
209
- def _handle_query(self, action: SQLAction) -> StepResponse:
210
- """
211
- Handle a QUERY action.
212
-
213
- Executes the SQL on the episode connection.
214
- Returns a result preview in the observation. Does NOT end the episode.
215
- Awards small step_reward (0.05) for queries that target the right area.
216
- """
217
- sql = (action.sql or "").strip()
218
-
219
- try:
220
- cursor = self._original_conn.execute(sql)
221
- # Check if query returns rows (SELECT) or just modifies (INSERT/UPDATE/DELETE)
222
- if cursor.description:
223
- rows = cursor.fetchmany(5)
224
- cols = [d[0] for d in cursor.description]
225
- result_preview = str([dict(zip(cols, row)) for row in rows])[:300]
226
- else:
227
- # For INSERT/UPDATE/DELETE, show affected rows
228
- result_preview = f"Query executed successfully. Rows affected: {cursor.rowcount}"
229
- # Small reward for targeted queries
230
- from server.graders import _query_reveals_issue
231
-
232
- step_reward = (
233
- 0.05 if _query_reveals_issue(sql, self._ground_truth) else 0.01
234
- )
235
- except sqlite3.Error as e:
236
- result_preview = f"SQL Error: {e}"
237
- step_reward = 0.0
238
-
239
- # Add to trajectory
240
- self._trajectory.append(
241
- TrajectoryStep(
242
- step_number=len(self._trajectory) + 1,
243
- action_type=ActionType.QUERY,
244
- sql_submitted=sql,
245
- result_preview=result_preview[:200],
246
- step_reward=step_reward,
247
- )
248
- )
249
-
250
- self._cumulative_reward = min(
251
- 1.0, round(self._cumulative_reward + step_reward, 4)
252
- )
253
- self._last_feedback = result_preview[:200]
254
- self._step_count += 1
255
-
256
- # Build updated observation with trajectory history
257
- obs = self._build_observation(result_preview=result_preview)
258
-
259
- return StepResponse(
260
- observation=obs,
261
- reward=SQLReward(
262
- score=self._cumulative_reward,
263
- step_reward=step_reward,
264
- feedback=result_preview[:200],
265
- ),
266
- done=False,
267
- info={"action_type": "query", "step": len(self._trajectory)},
268
- )
269
-
270
- def _handle_profile(self, action: SQLAction) -> StepResponse:
271
- """
272
- Handle a PROFILE action — statistical summary of a named column.
273
-
274
- Computes: null rate, distinct count, data type distribution, min/max.
275
- Does NOT end the episode. Awards step_reward based on column relevance.
276
- """
277
- col = (action.column_name or "").strip()
278
- result_preview = ""
279
-
280
- if not col:
281
- result_preview = "Error: column_name required for PROFILE action."
282
- else:
283
- # Try to find which table has this column
284
- try:
285
- tables = self._original_conn.execute(
286
- "SELECT name FROM sqlite_master WHERE type='table'"
287
- ).fetchall()
288
- profile_results = []
289
- for (tbl,) in tables:
290
- try:
291
- cols = [
292
- row[1]
293
- for row in self._original_conn.execute(
294
- f"PRAGMA table_info({tbl})"
295
- ).fetchall()
296
- ]
297
- if col in cols:
298
- total = self._original_conn.execute(
299
- f"SELECT COUNT(*) FROM {tbl}"
300
- ).fetchone()[0]
301
- nulls = self._original_conn.execute(
302
- f"SELECT COUNT(*) FROM {tbl} WHERE {col} IS NULL"
303
- ).fetchone()[0]
304
- distinct = self._original_conn.execute(
305
- f"SELECT COUNT(DISTINCT {col}) FROM {tbl}"
306
- ).fetchone()[0]
307
- profile_results.append(
308
- f"{tbl}.{col}: total={total}, nulls={nulls} ({100*nulls//total if total else 0}%), distinct={distinct}"
309
- )
310
- except sqlite3.Error:
311
- pass
312
- result_preview = (
313
- " | ".join(profile_results)
314
- if profile_results
315
- else f"Column '{col}' not found."
316
- )
317
- except sqlite3.Error as e:
318
- result_preview = f"Profile error: {e}"
319
-
320
- # Determine step_reward based on relevance to ground truth
321
- ground_table = self._ground_truth.get("table", "").lower()
322
- ground_col = self._ground_truth.get(
323
- "column", self._ground_truth.get("null_column", "")
324
- ).lower()
325
- col_lower = col.lower()
326
-
327
- if col_lower == ground_col:
328
- step_reward = 0.08 # On-target: profiling exact relevant column
329
- elif ground_table and ground_table in result_preview.lower():
330
- step_reward = 0.05 # Near-target: profiled something from right table
331
- elif col_lower in result_preview.lower() and len(col_lower) > 2:
332
- step_reward = 0.01 # Off-target: profiled something real but irrelevant
333
- else:
334
- step_reward = 0.01 # Minimal: invalid column or junk probe
335
-
336
- self._trajectory.append(
337
- TrajectoryStep(
338
- step_number=len(self._trajectory) + 1,
339
- action_type=ActionType.PROFILE,
340
- sql_submitted=f"PROFILE({col})",
341
- result_preview=result_preview[:200],
342
- step_reward=step_reward,
343
- )
344
- )
345
-
346
- self._cumulative_reward = min(
347
- 1.0, round(self._cumulative_reward + step_reward, 4)
348
- )
349
- self._last_feedback = result_preview[:200]
350
- self._step_count += 1
351
- obs = self._build_observation(result_preview=result_preview)
352
-
353
- return StepResponse(
354
- observation=obs,
355
- reward=SQLReward(
356
- score=self._cumulative_reward,
357
- step_reward=step_reward,
358
- feedback=result_preview[:200],
359
- ),
360
- done=False,
361
- info={"action_type": "profile", "column_profiled": col},
362
- )
363
-
364
- def _handle_fix(self, action: SQLAction) -> StepResponse:
365
- """
366
- Handle a FIX action — execute write query on isolated copy for preview scoring.
367
-
368
- Executes on a _fresh_test_db() copy. Does NOT mutate episode state.
369
- Returns intermediate feedback on whether fix appears to work.
370
- Does NOT end episode — agent can follow up with verification query or SUBMIT.
371
- Awards intermediate reward based on quick fix assessment.
372
- """
373
- fix_sql = action.effective_sql or ""
374
- step_reward = 0.0
375
- feedback = ""
376
-
377
- if fix_sql:
378
- from server.graders import grade_fix_correctness
379
-
380
- quick_score, severity = grade_fix_correctness(
381
- fix_sql,
382
- self._original_conn,
383
- self._original_snapshot,
384
- self._ground_truth,
385
- )
386
- step_reward = quick_score * 0.3 # Partial credit for fix attempt
387
- feedback = f"Fix preview: {severity} ({quick_score:.2f}). Submit to finalize score."
388
- else:
389
- feedback = "No SQL provided in fix action."
390
-
391
- self._trajectory.append(
392
- TrajectoryStep(
393
- step_number=len(self._trajectory) + 1,
394
- action_type=ActionType.FIX,
395
- sql_submitted=fix_sql,
396
- result_preview=feedback[:200],
397
- step_reward=step_reward,
398
- )
399
- )
400
-
401
- self._cumulative_reward = min(
402
- 1.0, round(self._cumulative_reward + step_reward, 4)
403
- )
404
- self._last_feedback = feedback
405
- self._step_count += 1
406
- obs = self._build_observation(result_preview=feedback)
407
-
408
- return StepResponse(
409
- observation=obs,
410
- reward=SQLReward(
411
- score=self._cumulative_reward,
412
- step_reward=step_reward,
413
- feedback=feedback,
414
- ),
415
- done=False,
416
- info={
417
- "action_type": "fix",
418
- "severity_preview": severity if fix_sql else "N/A",
419
- },
420
- )
421
-
422
- def _handle_submit(self, action: SQLAction) -> StepResponse:
423
- """
424
- Handle a SUBMIT action — compute final composite score and end episode.
425
-
426
- Calls compute_episode_score() with the full trajectory.
427
- Sets done=True. This is the only action that ends the episode.
428
- """
429
- from server.graders import compute_episode_score
430
-
431
- reward = compute_episode_score(
432
- trajectory=self._trajectory,
433
- ground_truth=self._ground_truth,
434
- original_conn=self._original_conn,
435
- original_snapshot=self._original_snapshot,
436
- submit_action=action,
437
- )
438
-
439
- self._done = True
440
- self._active = False
441
- self._cumulative_reward = min(
442
- 1.0, round(self._cumulative_reward + reward.score, 4)
443
- )
444
- self._last_feedback = reward.feedback
445
- obs = self._build_observation()
446
-
447
- # Close connection when episode ends
448
- if self._original_conn:
449
- self._original_conn.close()
450
- self._original_conn = None
451
-
452
- return StepResponse(
453
- observation=obs,
454
- reward=reward,
455
- done=True,
456
- info={
457
- "action_type": "submit",
458
- "final_score": reward.score,
459
- "dimensions": reward.dimensions,
460
- "trajectory_length": len(self._trajectory),
461
- },
462
- )
463
-
464
- def _build_observation(self, result_preview: str = "") -> SQLObservation:
465
- """Build current observation including trajectory history."""
466
- history = [
467
- {
468
- "step": s.step_number,
469
- "type": s.action_type.value,
470
- "sql": (s.sql_submitted or "")[:80],
471
- "result": s.result_preview[:80],
472
- "reward": s.step_reward,
473
- }
474
- for s in self._trajectory[-5:] # Last 5 steps only (context window)
475
- ]
476
- return SQLObservation(
477
- task_id=self._current_task_id,
478
- task_description=self._cached_observation.task_description,
479
- schema_info=self._cached_observation.schema_info,
480
- sample_rows=self._cached_observation.sample_rows,
481
- attempt_number=self._attempt_number,
482
- episode_id=self._episode_id,
483
- trajectory_history=history,
484
- investigation_hint=result_preview[:200] if result_preview else None,
485
- previous_feedback=(
486
- self._last_feedback if hasattr(self, "_last_feedback") else None
487
- ),
488
- max_attempts=self._cached_observation.max_attempts,
489
- )
490
-
491
- def state(self) -> SQLState:
492
- """Get current environment state.
493
-
494
- Returns:
495
- SQLState with current episode information
496
-
497
- Raises:
498
- ValueError: If no episode has been started
499
- """
500
- if self._episode_id is None:
501
- raise ValueError("No episode started. Call reset() first.")
502
-
503
- return SQLState(
504
- task_id=self._current_task_id,
505
- episode_id=self._episode_id,
506
- attempt_number=self._attempt_number,
507
- cumulative_reward=self._cumulative_reward,
508
- done=self._done,
509
- )