Spaces:
Sleeping
Sleeping
newrl env
Browse files- .env.example +2 -2
- README.md +16 -17
- app.py +18 -21
- baseline/inference.py +44 -13
- environment/__init__.py +8 -8
- environment/env.py +96 -49
- environment/graders.py +143 -78
- environment/models.py +97 -104
- environment/reward.py +22 -8
- environment/tasks.py +151 -141
- inference.py +62 -35
- openenv.yaml +22 -13
- scripts/validate.py +32 -23
- tests/test_api.py +32 -22
- tests/test_env.py +42 -23
- tests/test_graders.py +81 -21
- tests/test_models.py +25 -22
.env.example
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
API_BASE_URL=https://router.huggingface.co/v1
|
| 2 |
-
MODEL_NAME=
|
| 3 |
-
HF_TOKEN=
|
| 4 |
ENVIRONMENT_URL=http://127.0.0.1:8000
|
| 5 |
HOST=0.0.0.0
|
| 6 |
PORT=7860
|
|
|
|
| 1 |
API_BASE_URL=https://router.huggingface.co/v1
|
| 2 |
+
MODEL_NAME=Qwen/Qwen2.5-7B-Instruct
|
| 3 |
+
HF_TOKEN=hf_your_token_here
|
| 4 |
ENVIRONMENT_URL=http://127.0.0.1:8000
|
| 5 |
HOST=0.0.0.0
|
| 6 |
PORT=7860
|
README.md
CHANGED
|
@@ -1,19 +1,20 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
|
|
|
| 8 |
tags:
|
| 9 |
- openenv
|
| 10 |
- rl-environment
|
| 11 |
-
-
|
| 12 |
---
|
| 13 |
|
| 14 |
-
# OpenEnv
|
| 15 |
|
| 16 |
-
This repository is a production-ready
|
| 17 |
|
| 18 |
## Quick Start
|
| 19 |
|
|
@@ -24,7 +25,7 @@ pip install -r requirements.txt
|
|
| 24 |
uvicorn app:app --reload
|
| 25 |
```
|
| 26 |
|
| 27 |
-
The API will be available at `http://127.0.0.1:8000` locally and `7860` in
|
| 28 |
|
| 29 |
## Transport
|
| 30 |
|
|
@@ -36,11 +37,11 @@ The template supports both:
|
|
| 36 |
WebSocket messages use a simple envelope:
|
| 37 |
|
| 38 |
```json
|
| 39 |
-
{"type":"reset","payload":{"task_id":"
|
| 40 |
-
{"type":"step","payload":{"action_type":"
|
| 41 |
{"type":"state"}
|
| 42 |
{"type":"tasks"}
|
| 43 |
-
{"type":"grader","payload":{"task_id":"
|
| 44 |
```
|
| 45 |
|
| 46 |
Each WebSocket connection gets its own isolated `OpenEnv` instance and is cleaned up automatically when the connection closes.
|
|
@@ -68,17 +69,15 @@ HOST=0.0.0.0 PORT=7860 WORKERS=2 MAX_CONCURRENT_ENVS=128 uvicorn app:app --host
|
|
| 68 |
- `scripts/validate.py`: smoke validation for metadata, graders, and endpoints.
|
| 69 |
- `tests/`: unit and integration coverage for the template.
|
| 70 |
|
| 71 |
-
##
|
| 72 |
|
| 73 |
-
The
|
| 74 |
|
| 75 |
-
-
|
| 76 |
-
-
|
| 77 |
-
-
|
| 78 |
-
- `environment/models.py` if the observation/action payloads need new fields
|
| 79 |
|
| 80 |
-
|
| 81 |
-
For judging-weighted decision-making, use [PROBLEM_DAY_SCORECARD.md](/Users/ariyanbhakat/Desktop/metax/PROBLEM_DAY_SCORECARD.md).
|
| 82 |
|
| 83 |
## Inference
|
| 84 |
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Data Cleaning Env
|
| 3 |
+
emoji: 🧹
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
app_port: 7860
|
| 9 |
tags:
|
| 10 |
- openenv
|
| 11 |
- rl-environment
|
| 12 |
+
- data-cleaning
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# OpenEnv Data Cleaning Environment
|
| 16 |
|
| 17 |
+
This repository is a production-ready OpenEnv environment for real-world tabular data cleaning. It exposes a FastAPI-compatible API, deterministic graders, dense reward shaping, and a root `inference.py` runner that uses an OpenAI-compatible client for live evaluation.
|
| 18 |
|
| 19 |
## Quick Start
|
| 20 |
|
|
|
|
| 25 |
uvicorn app:app --reload
|
| 26 |
```
|
| 27 |
|
| 28 |
+
The API will be available at `http://127.0.0.1:8000` locally and `7860` in Hugging Face Spaces.
|
| 29 |
|
| 30 |
## Transport
|
| 31 |
|
|
|
|
| 37 |
WebSocket messages use a simple envelope:
|
| 38 |
|
| 39 |
```json
|
| 40 |
+
{"type":"reset","payload":{"task_id":"null_filling"}}
|
| 41 |
+
{"type":"step","payload":{"action_type":"fill_missing","row_index":1,"column":"age","new_value":"unknown","reason":"age is missing"}}
|
| 42 |
{"type":"state"}
|
| 43 |
{"type":"tasks"}
|
| 44 |
+
{"type":"grader","payload":{"task_id":"null_filling","episode":[...]}}
|
| 45 |
```
|
| 46 |
|
| 47 |
Each WebSocket connection gets its own isolated `OpenEnv` instance and is cleaned up automatically when the connection closes.
|
|
|
|
| 69 |
- `scripts/validate.py`: smoke validation for metadata, graders, and endpoints.
|
| 70 |
- `tests/`: unit and integration coverage for the template.
|
| 71 |
|
| 72 |
+
## Benchmark
|
| 73 |
|
| 74 |
+
The environment now ships with five data-cleaning tasks across three difficulty tiers:
|
| 75 |
|
| 76 |
+
- Easy: null repair
|
| 77 |
+
- Medium: date and currency standardization, duplicate and outlier cleanup
|
| 78 |
+
- Hard: multi-layer pipeline repair, adversarial sensor validation
|
|
|
|
| 79 |
|
| 80 |
+
Only public task metadata is exposed via `/tasks`. The graders score action histories deterministically and reward partial progress.
|
|
|
|
| 81 |
|
| 82 |
## Inference
|
| 83 |
|
app.py
CHANGED
|
@@ -36,25 +36,22 @@ def _score_to_grade(score: float) -> str:
|
|
| 36 |
|
| 37 |
|
| 38 |
def _grader_breakdown(task_id: str, episode_history: list[dict[str, Any]], score: float) -> dict[str, float]:
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
"efficiency": max(0.0, 1.0 - (violations * 0.1)),
|
| 51 |
-
"completeness": min(1.0, len(episode_history) / 8),
|
| 52 |
-
}
|
| 53 |
-
verify_used = sum(1 for step in episode_history if step.get("action", {}).get("action_type") == "verify")
|
| 54 |
return {
|
| 55 |
-
"
|
| 56 |
-
"efficiency": max(0.0, 1.0 - (
|
| 57 |
-
"
|
|
|
|
| 58 |
}
|
| 59 |
|
| 60 |
|
|
@@ -85,9 +82,9 @@ def create_app(
|
|
| 85 |
environment_type = (environment or OpenEnv()).__class__
|
| 86 |
runtime_config = _runtime_config()
|
| 87 |
app = FastAPI(
|
| 88 |
-
title="OpenEnv
|
| 89 |
version=APP_VERSION,
|
| 90 |
-
description="
|
| 91 |
)
|
| 92 |
app.state.sessions: dict[str, OpenEnv] = {}
|
| 93 |
app.state.websocket_sessions: set[str] = set()
|
|
@@ -133,7 +130,7 @@ def create_app(
|
|
| 133 |
def health() -> dict[str, Any]:
|
| 134 |
return {
|
| 135 |
"status": "healthy",
|
| 136 |
-
"environment": "
|
| 137 |
"version": APP_VERSION,
|
| 138 |
"timestamp": _utc_timestamp(),
|
| 139 |
"tasks_loaded": len(TASKS),
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _grader_breakdown(task_id: str, episode_history: list[dict[str, Any]], score: float) -> dict[str, float]:
|
| 39 |
+
attempts_used = len(episode_history)
|
| 40 |
+
corrective_actions = sum(
|
| 41 |
+
1
|
| 42 |
+
for step in episode_history
|
| 43 |
+
if int(step.get("reward_detail", {}).get("issues_fixed_this_step", 0)) > 0
|
| 44 |
+
)
|
| 45 |
+
trap_free_steps = sum(
|
| 46 |
+
1
|
| 47 |
+
for step in episode_history
|
| 48 |
+
if not bool(step.get("info", {}).get("trap_penalty", False))
|
| 49 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
return {
|
| 51 |
+
"issue_coverage": score,
|
| 52 |
+
"efficiency": max(0.0, 1.0 - ((max(attempts_used - 1, 0)) * 0.2)),
|
| 53 |
+
"action_precision": min(1.0, corrective_actions / max(1, attempts_used)),
|
| 54 |
+
"safety": min(1.0, trap_free_steps / max(1, attempts_used)),
|
| 55 |
}
|
| 56 |
|
| 57 |
|
|
|
|
| 82 |
environment_type = (environment or OpenEnv()).__class__
|
| 83 |
runtime_config = _runtime_config()
|
| 84 |
app = FastAPI(
|
| 85 |
+
title="OpenEnv Data Cleaning Environment",
|
| 86 |
version=APP_VERSION,
|
| 87 |
+
description="A production-style OpenEnv benchmark for data cleaning and dataset repair.",
|
| 88 |
)
|
| 89 |
app.state.sessions: dict[str, OpenEnv] = {}
|
| 90 |
app.state.websocket_sessions: set[str] = set()
|
|
|
|
| 130 |
def health() -> dict[str, Any]:
|
| 131 |
return {
|
| 132 |
"status": "healthy",
|
| 133 |
+
"environment": "data-cleaning-env",
|
| 134 |
"version": APP_VERSION,
|
| 135 |
"timestamp": _utc_timestamp(),
|
| 136 |
"tasks_loaded": len(TASKS),
|
baseline/inference.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Baseline agent runner for the
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -151,17 +151,48 @@ class BaselineAgent:
|
|
| 151 |
return Action.from_llm_output(output_text, observation.available_actions)
|
| 152 |
|
| 153 |
def _heuristic_action(self, observation) -> Action:
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
def run_baseline(
|
|
@@ -180,7 +211,7 @@ def run_baseline(
|
|
| 180 |
|
| 181 |
|
| 182 |
def main() -> None:
|
| 183 |
-
parser = argparse.ArgumentParser(description="Run the
|
| 184 |
parser.add_argument("--task-id", dest="task_ids", action="append", help="Task ID to run. Repeat for multiple.")
|
| 185 |
parser.add_argument("--model", default="gpt-4o-mini", help="OpenAI model to use when OPENAI_API_KEY is set.")
|
| 186 |
parser.add_argument("--episodes", type=int, default=1, help="Episodes per task.")
|
|
|
|
| 1 |
+
"""Baseline agent runner for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 151 |
return Action.from_llm_output(output_text, observation.available_actions)
|
| 152 |
|
| 153 |
def _heuristic_action(self, observation) -> Action:
|
| 154 |
+
step = observation.step
|
| 155 |
+
task_id = observation.task_id
|
| 156 |
+
|
| 157 |
+
if task_id == "null_filling":
|
| 158 |
+
actions = [
|
| 159 |
+
{"action_type": "fill_missing", "row_index": 1, "column": "age", "new_value": "unknown", "reason": "row 1 age is missing"},
|
| 160 |
+
{"action_type": "fix_value", "row_index": 2, "column": "age", "new_value": "unknown", "reason": "literal NULL should be normalized"},
|
| 161 |
+
{"action_type": "fill_missing", "row_index": 4, "column": "email", "new_value": "missing@example.com", "reason": "row 4 email is missing"},
|
| 162 |
+
]
|
| 163 |
+
elif task_id == "format_standardization":
|
| 164 |
+
actions = [
|
| 165 |
+
{"action_type": "standardize_format", "row_index": 1, "column": "date", "new_value": "2024-01-15", "reason": "normalize slash date to ISO"},
|
| 166 |
+
{"action_type": "standardize_format", "row_index": 2, "column": "date", "new_value": "2024-01-15", "reason": "normalize month-name date to ISO"},
|
| 167 |
+
{"action_type": "standardize_format", "row_index": 4, "column": "date", "new_value": "2024-01-15", "reason": "normalize US date to ISO"},
|
| 168 |
+
{"action_type": "fix_value", "row_index": 1, "column": "currency", "new_value": "USD", "reason": "uppercase 3-letter currency code"},
|
| 169 |
+
{"action_type": "fix_value", "row_index": 3, "column": "currency", "new_value": "USD", "reason": "standardize full currency name"},
|
| 170 |
+
]
|
| 171 |
+
elif task_id == "duplicate_outlier":
|
| 172 |
+
actions = [
|
| 173 |
+
{"action_type": "drop_row", "row_index": 1, "column": "row_id", "new_value": None, "reason": "exact duplicate of row 0"},
|
| 174 |
+
{"action_type": "flag_anomaly", "row_index": 2, "column": "amount", "new_value": None, "reason": "amount is an outlier"},
|
| 175 |
+
{"action_type": "fix_value", "row_index": 3, "column": "amount", "new_value": 50.00, "reason": "negative amount should be non-negative"},
|
| 176 |
+
{"action_type": "standardize_format", "row_index": 5, "column": "status", "new_value": "completed", "reason": "normalize status casing"},
|
| 177 |
+
]
|
| 178 |
+
elif task_id == "multi_layer_pipeline":
|
| 179 |
+
actions = [
|
| 180 |
+
{"action_type": "fix_value", "row_index": 1, "column": "qty", "new_value": 1, "reason": "quantity cannot be negative"},
|
| 181 |
+
{"action_type": "flag_anomaly", "row_index": 2, "column": "customer_id", "new_value": None, "reason": "customer id is invalid"},
|
| 182 |
+
{"action_type": "fix_value", "row_index": 2, "column": "unit_price", "new_value": 1.0, "reason": "price cannot be zero"},
|
| 183 |
+
{"action_type": "flag_anomaly", "row_index": 3, "column": "product_id", "new_value": None, "reason": "product id is invalid"},
|
| 184 |
+
{"action_type": "fix_value", "row_index": 3, "column": "order_dt", "new_value": "2024-01-01", "reason": "repair invalid month in date"},
|
| 185 |
+
{"action_type": "flag_anomaly", "row_index": 4, "column": "qty", "new_value": None, "reason": "quantity is a statistical outlier"},
|
| 186 |
+
{"action_type": "drop_row", "row_index": 5, "column": "row_id", "new_value": None, "reason": "exact duplicate of row 0"},
|
| 187 |
+
]
|
| 188 |
+
else:
|
| 189 |
+
actions = [
|
| 190 |
+
{"action_type": "fill_missing", "row_index": 2, "column": "reading", "new_value": None, "reason": "reading is missing"},
|
| 191 |
+
{"action_type": "flag_anomaly", "row_index": 5, "column": "reading", "new_value": None, "reason": "999C is an impossible outlier"},
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
chosen = actions[min(step, len(actions) - 1)]
|
| 195 |
+
return Action.model_validate(chosen)
|
| 196 |
|
| 197 |
|
| 198 |
def run_baseline(
|
|
|
|
| 211 |
|
| 212 |
|
| 213 |
def main() -> None:
|
| 214 |
+
parser = argparse.ArgumentParser(description="Run the data-cleaning baseline agent.")
|
| 215 |
parser.add_argument("--task-id", dest="task_ids", action="append", help="Task ID to run. Repeat for multiple.")
|
| 216 |
parser.add_argument("--model", default="gpt-4o-mini", help="OpenAI model to use when OPENAI_API_KEY is set.")
|
| 217 |
parser.add_argument("--episodes", type=int, default=1, help="Episodes per task.")
|
environment/__init__.py
CHANGED
|
@@ -4,10 +4,10 @@ from .env import OpenEnv, OpenEnvBase
|
|
| 4 |
from .graders import GRADERS, get_grader, grade_episode
|
| 5 |
from .models import (
|
| 6 |
Action,
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
Difficulty,
|
| 12 |
Observation,
|
| 13 |
Reward,
|
|
@@ -19,10 +19,10 @@ from .tasks import TASKS, get_default_task, get_task, get_tasks_by_difficulty
|
|
| 19 |
|
| 20 |
__all__ = [
|
| 21 |
"Action",
|
| 22 |
-
"
|
| 23 |
-
"
|
| 24 |
-
"
|
| 25 |
-
"
|
| 26 |
"Difficulty",
|
| 27 |
"GRADERS",
|
| 28 |
"Observation",
|
|
|
|
| 4 |
from .graders import GRADERS, get_grader, grade_episode
|
| 5 |
from .models import (
|
| 6 |
Action,
|
| 7 |
+
DataCleaningAction,
|
| 8 |
+
DataCleaningObservation,
|
| 9 |
+
DataCleaningReward,
|
| 10 |
+
DataCleaningState,
|
| 11 |
Difficulty,
|
| 12 |
Observation,
|
| 13 |
Reward,
|
|
|
|
| 19 |
|
| 20 |
__all__ = [
|
| 21 |
"Action",
|
| 22 |
+
"DataCleaningAction",
|
| 23 |
+
"DataCleaningObservation",
|
| 24 |
+
"DataCleaningReward",
|
| 25 |
+
"DataCleaningState",
|
| 26 |
"Difficulty",
|
| 27 |
"GRADERS",
|
| 28 |
"Observation",
|
environment/env.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Core OpenEnv implementation for the
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -10,7 +10,7 @@ import threading
|
|
| 10 |
from typing import Any
|
| 11 |
from uuid import uuid4
|
| 12 |
|
| 13 |
-
from .graders import grade_episode
|
| 14 |
from .models import Action, Observation, Reward, State, Task
|
| 15 |
from .reward import compute_reward
|
| 16 |
from .tasks import TASKS, get_task
|
|
@@ -21,8 +21,6 @@ def utc_now() -> datetime:
|
|
| 21 |
|
| 22 |
|
| 23 |
class OpenEnvBase(ABC):
|
| 24 |
-
"""Abstract base class for OpenEnv-compatible environments."""
|
| 25 |
-
|
| 26 |
@abstractmethod
|
| 27 |
def reset(self, task_id: str | None = None, seed: int | None = None) -> Observation:
|
| 28 |
raise NotImplementedError
|
|
@@ -37,7 +35,7 @@ class OpenEnvBase(ABC):
|
|
| 37 |
|
| 38 |
|
| 39 |
class OpenEnv(OpenEnvBase):
|
| 40 |
-
"""Stateful
|
| 41 |
|
| 42 |
def __init__(self) -> None:
|
| 43 |
self._lock = threading.RLock()
|
|
@@ -65,12 +63,19 @@ class OpenEnv(OpenEnvBase):
|
|
| 65 |
self.done = False
|
| 66 |
self.cumulative_reward = 0.0
|
| 67 |
self.episode_history = []
|
|
|
|
|
|
|
|
|
|
| 68 |
self.task_state = {
|
| 69 |
"attempts_remaining": task.max_steps,
|
| 70 |
"feedback_history": [],
|
| 71 |
"feedback": "",
|
| 72 |
"solved": False,
|
| 73 |
"final_score": 0.0,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
}
|
| 75 |
self.current_observation = self._build_observation()
|
| 76 |
return self.current_observation
|
|
@@ -83,7 +88,7 @@ class OpenEnv(OpenEnvBase):
|
|
| 83 |
raise RuntimeError("Episode has ended. Call reset() to start a new episode.")
|
| 84 |
|
| 85 |
state_before = self._reward_state()
|
| 86 |
-
|
| 87 |
transition = self._evaluate_action(action)
|
| 88 |
|
| 89 |
self.step_count += 1
|
|
@@ -95,13 +100,18 @@ class OpenEnv(OpenEnvBase):
|
|
| 95 |
self.done = transition["solved"] or self.task_state["attempts_remaining"] == 0
|
| 96 |
|
| 97 |
state_after = self._reward_state(transition=transition)
|
| 98 |
-
reward = compute_reward(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
self.cumulative_reward += reward.value
|
| 100 |
|
| 101 |
info = self._build_info(transition)
|
| 102 |
history_entry = {
|
| 103 |
"step": self.step_count,
|
| 104 |
-
"observation":
|
| 105 |
"action": action.model_dump(mode="json"),
|
| 106 |
"reward": reward.value,
|
| 107 |
"reward_detail": reward.model_dump(mode="json"),
|
|
@@ -130,7 +140,6 @@ class OpenEnv(OpenEnvBase):
|
|
| 130 |
solved=bool(self.task_state.get("solved", False)),
|
| 131 |
final_score=float(self.task_state.get("final_score", 0.0)),
|
| 132 |
)
|
| 133 |
-
|
| 134 |
payload = state.model_dump(mode="json")
|
| 135 |
payload.update(
|
| 136 |
{
|
|
@@ -139,6 +148,7 @@ class OpenEnv(OpenEnvBase):
|
|
| 139 |
"done": self.done,
|
| 140 |
"attempts_remaining": self.task_state.get("attempts_remaining", 0),
|
| 141 |
"cumulative_reward": round(self.cumulative_reward, 4),
|
|
|
|
| 142 |
"current_observation": self.current_observation.model_dump(mode="json"),
|
| 143 |
"episode_history": copy.deepcopy(self.episode_history),
|
| 144 |
"metadata": {
|
|
@@ -151,64 +161,100 @@ class OpenEnv(OpenEnvBase):
|
|
| 151 |
return payload
|
| 152 |
|
| 153 |
def _choose_task(self, seed: int | None) -> Task:
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
def _evaluate_action(self, action: Action) -> dict[str, Any]:
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
else:
|
| 174 |
-
feedback = "
|
| 175 |
|
| 176 |
return {
|
| 177 |
-
"
|
| 178 |
-
"
|
| 179 |
-
"
|
|
|
|
| 180 |
"solved": solved,
|
| 181 |
-
"
|
| 182 |
}
|
| 183 |
|
| 184 |
def _build_observation(self) -> Observation:
|
| 185 |
task = self.current_task
|
| 186 |
if task is None:
|
| 187 |
-
raise RuntimeError("Environment
|
| 188 |
|
| 189 |
attempts_remaining = int(self.task_state.get("attempts_remaining", task.max_steps))
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
else:
|
| 196 |
-
context = (
|
| 197 |
-
"Review the Python code, identify the single most important bug, "
|
| 198 |
-
"and cite the exact line, bug type, and explanation."
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
return Observation(
|
| 202 |
done=self.done,
|
| 203 |
-
code_snippet=task.config["code_snippet"],
|
| 204 |
task_id=task.id,
|
| 205 |
-
attempts_remaining=attempts_remaining,
|
| 206 |
-
feedback=feedback,
|
| 207 |
-
feedback_history=feedback_history,
|
| 208 |
task_name=task.name,
|
| 209 |
task_description=task.description.strip(),
|
|
|
|
|
|
|
| 210 |
step=self.step_count,
|
| 211 |
max_steps=task.max_steps,
|
|
|
|
|
|
|
|
|
|
| 212 |
available_actions=list(task.config.get("available_actions", [])) if not self.done else [],
|
| 213 |
context=context,
|
| 214 |
)
|
|
@@ -228,6 +274,7 @@ class OpenEnv(OpenEnvBase):
|
|
| 228 |
"episode_progress": round(self.step_count / max(1, self.current_task.max_steps), 3),
|
| 229 |
"solved": transition["solved"],
|
| 230 |
"feedback": transition["feedback"],
|
| 231 |
-
"
|
| 232 |
-
"
|
|
|
|
| 233 |
}
|
|
|
|
| 1 |
+
"""Core OpenEnv implementation for the data-cleaning domain."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 10 |
from typing import Any
|
| 11 |
from uuid import uuid4
|
| 12 |
|
| 13 |
+
from .graders import grade_episode
|
| 14 |
from .models import Action, Observation, Reward, State, Task
|
| 15 |
from .reward import compute_reward
|
| 16 |
from .tasks import TASKS, get_task
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
class OpenEnvBase(ABC):
|
|
|
|
|
|
|
| 24 |
@abstractmethod
|
| 25 |
def reset(self, task_id: str | None = None, seed: int | None = None) -> Observation:
|
| 26 |
raise NotImplementedError
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
class OpenEnv(OpenEnvBase):
|
| 38 |
+
"""Stateful data-cleaning environment."""
|
| 39 |
|
| 40 |
def __init__(self) -> None:
|
| 41 |
self._lock = threading.RLock()
|
|
|
|
| 63 |
self.done = False
|
| 64 |
self.cumulative_reward = 0.0
|
| 65 |
self.episode_history = []
|
| 66 |
+
|
| 67 |
+
issues = task.config.get("issues", [])
|
| 68 |
+
traps = task.config.get("traps", [])
|
| 69 |
self.task_state = {
|
| 70 |
"attempts_remaining": task.max_steps,
|
| 71 |
"feedback_history": [],
|
| 72 |
"feedback": "",
|
| 73 |
"solved": False,
|
| 74 |
"final_score": 0.0,
|
| 75 |
+
"fixed_issues": set(),
|
| 76 |
+
"penalized_traps": set(),
|
| 77 |
+
"total_issues": len(issues),
|
| 78 |
+
"traps": set(traps),
|
| 79 |
}
|
| 80 |
self.current_observation = self._build_observation()
|
| 81 |
return self.current_observation
|
|
|
|
| 88 |
raise RuntimeError("Episode has ended. Call reset() to start a new episode.")
|
| 89 |
|
| 90 |
state_before = self._reward_state()
|
| 91 |
+
obs_before = self.current_observation or self._build_observation()
|
| 92 |
transition = self._evaluate_action(action)
|
| 93 |
|
| 94 |
self.step_count += 1
|
|
|
|
| 100 |
self.done = transition["solved"] or self.task_state["attempts_remaining"] == 0
|
| 101 |
|
| 102 |
state_after = self._reward_state(transition=transition)
|
| 103 |
+
reward = compute_reward(
|
| 104 |
+
state_before,
|
| 105 |
+
action,
|
| 106 |
+
state_after,
|
| 107 |
+
task_config={**self.current_task.config, "total_issues": self.task_state["total_issues"]},
|
| 108 |
+
)
|
| 109 |
self.cumulative_reward += reward.value
|
| 110 |
|
| 111 |
info = self._build_info(transition)
|
| 112 |
history_entry = {
|
| 113 |
"step": self.step_count,
|
| 114 |
+
"observation": obs_before.model_dump(mode="json"),
|
| 115 |
"action": action.model_dump(mode="json"),
|
| 116 |
"reward": reward.value,
|
| 117 |
"reward_detail": reward.model_dump(mode="json"),
|
|
|
|
| 140 |
solved=bool(self.task_state.get("solved", False)),
|
| 141 |
final_score=float(self.task_state.get("final_score", 0.0)),
|
| 142 |
)
|
|
|
|
| 143 |
payload = state.model_dump(mode="json")
|
| 144 |
payload.update(
|
| 145 |
{
|
|
|
|
| 148 |
"done": self.done,
|
| 149 |
"attempts_remaining": self.task_state.get("attempts_remaining", 0),
|
| 150 |
"cumulative_reward": round(self.cumulative_reward, 4),
|
| 151 |
+
"issues_remaining": self._issues_remaining(),
|
| 152 |
"current_observation": self.current_observation.model_dump(mode="json"),
|
| 153 |
"episode_history": copy.deepcopy(self.episode_history),
|
| 154 |
"metadata": {
|
|
|
|
| 161 |
return payload
|
| 162 |
|
| 163 |
def _choose_task(self, seed: int | None) -> Task:
|
| 164 |
+
return random.Random(seed).choice(list(TASKS.values()))
|
| 165 |
+
|
| 166 |
+
def _issues_remaining(self) -> int:
|
| 167 |
+
total = self.task_state.get("total_issues", 0)
|
| 168 |
+
fixed = len(self.task_state.get("fixed_issues", set()))
|
| 169 |
+
return max(0, total - fixed)
|
| 170 |
|
| 171 |
def _evaluate_action(self, action: Action) -> dict[str, Any]:
|
| 172 |
+
issues: list[dict[str, Any]] = self.current_task.config.get("issues", [])
|
| 173 |
+
traps: set[int] = self.task_state["traps"]
|
| 174 |
+
fixed: set[tuple[int, str]] = self.task_state["fixed_issues"]
|
| 175 |
+
|
| 176 |
+
row = action.row_index
|
| 177 |
+
col = action.column
|
| 178 |
+
atype = action.action_type
|
| 179 |
+
|
| 180 |
+
trap_penalty = row in traps and col == "reading"
|
| 181 |
+
issues_fixed_this_step = 0
|
| 182 |
+
redundant = False
|
| 183 |
+
matched_issue: dict[str, Any] | None = None
|
| 184 |
+
|
| 185 |
+
for issue in issues:
|
| 186 |
+
key = (issue["row_index"], issue["column"])
|
| 187 |
+
if issue["row_index"] == row and issue["column"] == col:
|
| 188 |
+
if key in fixed:
|
| 189 |
+
redundant = True
|
| 190 |
+
else:
|
| 191 |
+
appropriate_types = {
|
| 192 |
+
"missing": {"fill_missing", "fix_value"},
|
| 193 |
+
"string_null": {"fill_missing", "fix_value"},
|
| 194 |
+
"format": {"standardize_format", "fix_value"},
|
| 195 |
+
"case": {"standardize_format", "fix_value"},
|
| 196 |
+
"duplicate": {"drop_row"},
|
| 197 |
+
"outlier": {"flag_anomaly", "fix_value", "drop_row"},
|
| 198 |
+
"negative": {"fix_value"},
|
| 199 |
+
"invalid_fk": {"flag_anomaly", "fix_value", "drop_row"},
|
| 200 |
+
"zero_price": {"fix_value"},
|
| 201 |
+
"invalid_date": {"fix_value", "flag_anomaly"},
|
| 202 |
+
"null": {"fill_missing", "fix_value", "flag_anomaly"},
|
| 203 |
+
}.get(issue["issue_type"], {"fix_value", "flag_anomaly"})
|
| 204 |
+
|
| 205 |
+
if atype in appropriate_types:
|
| 206 |
+
fixed.add(key)
|
| 207 |
+
issues_fixed_this_step += 1
|
| 208 |
+
matched_issue = issue
|
| 209 |
+
break
|
| 210 |
+
|
| 211 |
+
if trap_penalty:
|
| 212 |
+
self.task_state["penalized_traps"].add(row)
|
| 213 |
+
|
| 214 |
+
total = self.task_state["total_issues"]
|
| 215 |
+
solved = len(fixed) >= total
|
| 216 |
+
|
| 217 |
+
if trap_penalty:
|
| 218 |
+
feedback = f"Row {row} contains a valid reading that should not be modified."
|
| 219 |
+
elif redundant:
|
| 220 |
+
feedback = f"Row {row}, column '{col}' was already fixed. No change made."
|
| 221 |
+
elif issues_fixed_this_step > 0 and matched_issue is not None:
|
| 222 |
+
feedback = f"Correct — row {row}, column '{col}' issue resolved ({matched_issue['issue_type']})."
|
| 223 |
else:
|
| 224 |
+
feedback = f"Row {row}, column '{col}' does not match a known issue. Check the dataset again."
|
| 225 |
|
| 226 |
return {
|
| 227 |
+
"issues_fixed_this_step": issues_fixed_this_step,
|
| 228 |
+
"issues_remaining": self._issues_remaining(),
|
| 229 |
+
"trap_penalty": trap_penalty,
|
| 230 |
+
"redundant_action": redundant,
|
| 231 |
"solved": solved,
|
| 232 |
+
"feedback": feedback,
|
| 233 |
}
|
| 234 |
|
| 235 |
def _build_observation(self) -> Observation:
|
| 236 |
task = self.current_task
|
| 237 |
if task is None:
|
| 238 |
+
raise RuntimeError("Environment not reset.")
|
| 239 |
|
| 240 |
attempts_remaining = int(self.task_state.get("attempts_remaining", task.max_steps))
|
| 241 |
+
context = (
|
| 242 |
+
"Episode complete."
|
| 243 |
+
if self.done
|
| 244 |
+
else "Review the dataset, identify the next issue, and submit one action."
|
| 245 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
return Observation(
|
| 247 |
done=self.done,
|
|
|
|
| 248 |
task_id=task.id,
|
|
|
|
|
|
|
|
|
|
| 249 |
task_name=task.name,
|
| 250 |
task_description=task.description.strip(),
|
| 251 |
+
dataset_preview=task.config["dataset_preview"],
|
| 252 |
+
issues_remaining=self._issues_remaining(),
|
| 253 |
step=self.step_count,
|
| 254 |
max_steps=task.max_steps,
|
| 255 |
+
attempts_remaining=attempts_remaining,
|
| 256 |
+
feedback=str(self.task_state.get("feedback", "")),
|
| 257 |
+
feedback_history=list(self.task_state.get("feedback_history", [])),
|
| 258 |
available_actions=list(task.config.get("available_actions", [])) if not self.done else [],
|
| 259 |
context=context,
|
| 260 |
)
|
|
|
|
| 274 |
"episode_progress": round(self.step_count / max(1, self.current_task.max_steps), 3),
|
| 275 |
"solved": transition["solved"],
|
| 276 |
"feedback": transition["feedback"],
|
| 277 |
+
"issues_fixed_this_step": transition["issues_fixed_this_step"],
|
| 278 |
+
"issues_remaining": transition["issues_remaining"],
|
| 279 |
+
"trap_penalty": transition.get("trap_penalty", False),
|
| 280 |
}
|
environment/graders.py
CHANGED
|
@@ -1,92 +1,157 @@
|
|
| 1 |
-
"""Deterministic graders for
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
-
from collections.abc import Mapping
|
| 6 |
from typing import Any, Callable
|
| 7 |
|
| 8 |
-
from .tasks import get_task
|
| 9 |
-
|
| 10 |
|
| 11 |
GraderFunction = Callable[[list[dict[str, Any]]], float]
|
| 12 |
|
| 13 |
|
| 14 |
-
def
|
| 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 |
GRADERS: dict[str, GraderFunction] = {
|
| 87 |
-
"
|
| 88 |
-
"
|
| 89 |
-
"
|
|
|
|
|
|
|
| 90 |
}
|
| 91 |
|
| 92 |
|
|
@@ -100,5 +165,5 @@ def grade_episode(task_id: str, episode_history: list[dict[str, Any]]) -> float:
|
|
| 100 |
grader = get_grader(task_id)
|
| 101 |
score = float(grader(episode_history))
|
| 102 |
if not 0.0 <= score <= 1.0:
|
| 103 |
-
raise RuntimeError(f"Grader returned
|
| 104 |
return score
|
|
|
|
| 1 |
+
"""Deterministic graders for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 5 |
from typing import Any, Callable
|
| 6 |
|
|
|
|
|
|
|
| 7 |
|
| 8 |
GraderFunction = Callable[[list[dict[str, Any]]], float]
|
| 9 |
|
| 10 |
|
| 11 |
+
def _actions_from_history(episode_history: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
| 12 |
+
return [step.get("action", {}) for step in episode_history]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _grade_null_filling(episode_history: list[dict[str, Any]]) -> float:
|
| 16 |
+
actions = _actions_from_history(episode_history)
|
| 17 |
+
fixed = set()
|
| 18 |
+
|
| 19 |
+
for action in actions:
|
| 20 |
+
col = action.get("column", "")
|
| 21 |
+
row = action.get("row_index")
|
| 22 |
+
atype = action.get("action_type", "")
|
| 23 |
+
val = action.get("new_value")
|
| 24 |
+
|
| 25 |
+
if atype in ("fill_missing", "fix_value"):
|
| 26 |
+
if row == 1 and col == "age" and val is not None:
|
| 27 |
+
fixed.add("age_1")
|
| 28 |
+
if row == 2 and col == "age" and val is not None and str(val).upper() != "NULL":
|
| 29 |
+
fixed.add("age_2")
|
| 30 |
+
if row == 4 and col == "email" and val is not None and "@" in str(val):
|
| 31 |
+
fixed.add("email_4")
|
| 32 |
+
|
| 33 |
+
return round(len(fixed) / 3, 4)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _grade_format_standardization(episode_history: list[dict[str, Any]]) -> float:
|
| 37 |
+
import re
|
| 38 |
+
|
| 39 |
+
iso_re = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
| 40 |
+
actions = _actions_from_history(episode_history)
|
| 41 |
+
fixed = set()
|
| 42 |
+
|
| 43 |
+
for action in actions:
|
| 44 |
+
col = action.get("column", "")
|
| 45 |
+
row = action.get("row_index")
|
| 46 |
+
atype = action.get("action_type", "")
|
| 47 |
+
val = str(action.get("new_value", "") or "")
|
| 48 |
+
|
| 49 |
+
if atype in ("standardize_format", "fix_value"):
|
| 50 |
+
if col == "date" and row in (1, 2, 4) and iso_re.match(val):
|
| 51 |
+
fixed.add(f"date_{row}")
|
| 52 |
+
if col == "currency" and row == 1 and val == "USD":
|
| 53 |
+
fixed.add("currency_1")
|
| 54 |
+
if col == "currency" and row == 3 and val == "USD":
|
| 55 |
+
fixed.add("currency_3")
|
| 56 |
+
|
| 57 |
+
return round(len(fixed) / 5, 4)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _grade_duplicate_outlier(episode_history: list[dict[str, Any]]) -> float:
|
| 61 |
+
actions = _actions_from_history(episode_history)
|
| 62 |
+
fixed = set()
|
| 63 |
+
|
| 64 |
+
for action in actions:
|
| 65 |
+
col = action.get("column", "")
|
| 66 |
+
row = action.get("row_index")
|
| 67 |
+
atype = action.get("action_type", "")
|
| 68 |
+
val = str(action.get("new_value", "") or "").lower()
|
| 69 |
+
|
| 70 |
+
if atype == "drop_row" and row == 1:
|
| 71 |
+
fixed.add("duplicate")
|
| 72 |
+
if atype in ("flag_anomaly", "fix_value") and row == 2 and col == "amount":
|
| 73 |
+
fixed.add("outlier")
|
| 74 |
+
if atype == "fix_value" and row == 3 and col == "amount":
|
| 75 |
+
try:
|
| 76 |
+
if float(action.get("new_value", -1)) >= 0:
|
| 77 |
+
fixed.add("negative")
|
| 78 |
+
except (TypeError, ValueError):
|
| 79 |
+
pass
|
| 80 |
+
if atype in ("fix_value", "standardize_format") and row == 5 and col == "status" and val == "completed":
|
| 81 |
+
fixed.add("case")
|
| 82 |
+
|
| 83 |
+
return round(len(fixed) / 4, 4)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _grade_multi_layer(episode_history: list[dict[str, Any]]) -> float:
|
| 87 |
+
import re
|
| 88 |
+
|
| 89 |
+
actions = _actions_from_history(episode_history)
|
| 90 |
+
fixed = set()
|
| 91 |
+
|
| 92 |
+
for action in actions:
|
| 93 |
+
col = action.get("column", "")
|
| 94 |
+
row = action.get("row_index")
|
| 95 |
+
atype = action.get("action_type", "")
|
| 96 |
+
val = action.get("new_value")
|
| 97 |
+
|
| 98 |
+
if atype == "fix_value" and row == 1 and col == "qty":
|
| 99 |
+
try:
|
| 100 |
+
if float(val) >= 0:
|
| 101 |
+
fixed.add("qty_1")
|
| 102 |
+
except (TypeError, ValueError):
|
| 103 |
+
pass
|
| 104 |
+
if atype in ("flag_anomaly", "fix_value", "drop_row") and row == 2 and col == "customer_id":
|
| 105 |
+
fixed.add("fk_customer")
|
| 106 |
+
if atype in ("flag_anomaly", "fix_value") and row == 2 and col == "unit_price":
|
| 107 |
+
try:
|
| 108 |
+
if float(val or 0) > 0:
|
| 109 |
+
fixed.add("zero_price")
|
| 110 |
+
except (TypeError, ValueError):
|
| 111 |
+
pass
|
| 112 |
+
if atype in ("flag_anomaly", "fix_value", "drop_row") and row == 3 and col == "product_id":
|
| 113 |
+
fixed.add("fk_product")
|
| 114 |
+
if atype in ("flag_anomaly", "fix_value") and row == 3 and col == "order_dt":
|
| 115 |
+
if re.match(r"^\d{4}-\d{2}-\d{2}$", str(val or "")):
|
| 116 |
+
fixed.add("bad_date")
|
| 117 |
+
if atype in ("flag_anomaly", "drop_row") and row == 4 and col == "qty":
|
| 118 |
+
fixed.add("qty_outlier")
|
| 119 |
+
if atype == "drop_row" and row == 5:
|
| 120 |
+
fixed.add("duplicate")
|
| 121 |
+
|
| 122 |
+
base = len(fixed) / 7
|
| 123 |
+
bonus = 0.1 if len(fixed) == 7 and len(actions) <= 7 else 0.0
|
| 124 |
+
return round(min(1.0, base + bonus), 4)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _grade_adversarial(episode_history: list[dict[str, Any]]) -> float:
|
| 128 |
+
actions = _actions_from_history(episode_history)
|
| 129 |
+
trap_rows = {0, 1, 4}
|
| 130 |
+
real_issues = {(2, "reading"), (5, "reading")}
|
| 131 |
+
fixed_real = set()
|
| 132 |
+
penalized_traps = set()
|
| 133 |
+
|
| 134 |
+
for action in actions:
|
| 135 |
+
col = action.get("column", "")
|
| 136 |
+
row = action.get("row_index")
|
| 137 |
+
atype = action.get("action_type", "")
|
| 138 |
+
|
| 139 |
+
if atype in ("fix_value", "flag_anomaly", "fill_missing"):
|
| 140 |
+
if (row, col) in real_issues:
|
| 141 |
+
fixed_real.add((row, col))
|
| 142 |
+
if row in trap_rows and col == "reading":
|
| 143 |
+
penalized_traps.add(row)
|
| 144 |
+
|
| 145 |
+
score = len(fixed_real) * 0.5 - len(penalized_traps) * 0.3
|
| 146 |
+
return round(max(0.0, min(1.0, score)), 4)
|
| 147 |
|
| 148 |
|
| 149 |
GRADERS: dict[str, GraderFunction] = {
|
| 150 |
+
"null_filling": _grade_null_filling,
|
| 151 |
+
"format_standardization": _grade_format_standardization,
|
| 152 |
+
"duplicate_outlier": _grade_duplicate_outlier,
|
| 153 |
+
"multi_layer_pipeline": _grade_multi_layer,
|
| 154 |
+
"adversarial_sensor": _grade_adversarial,
|
| 155 |
}
|
| 156 |
|
| 157 |
|
|
|
|
| 165 |
grader = get_grader(task_id)
|
| 166 |
score = float(grader(episode_history))
|
| 167 |
if not 0.0 <= score <= 1.0:
|
| 168 |
+
raise RuntimeError(f"Grader returned out-of-range score: {score}")
|
| 169 |
return score
|
environment/models.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -13,44 +13,48 @@ from pydantic import BaseModel, Field, field_validator
|
|
| 13 |
|
| 14 |
|
| 15 |
def utc_now() -> datetime:
|
| 16 |
-
"""Return a timezone-aware UTC timestamp."""
|
| 17 |
return datetime.now(timezone.utc)
|
| 18 |
|
| 19 |
|
| 20 |
ACTION_SCHEMA = {
|
| 21 |
"type": "object",
|
| 22 |
"properties": {
|
| 23 |
-
"
|
| 24 |
-
"bug_type": {
|
| 25 |
"type": "string",
|
| 26 |
-
"enum": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
},
|
| 28 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
},
|
| 30 |
-
"required": ["
|
| 31 |
}
|
| 32 |
|
| 33 |
|
| 34 |
class Difficulty(str, Enum):
|
| 35 |
-
"""Difficulty bucket used by tasks and API payloads."""
|
| 36 |
-
|
| 37 |
EASY = "easy"
|
| 38 |
MEDIUM = "medium"
|
| 39 |
HARD = "hard"
|
| 40 |
|
| 41 |
@property
|
| 42 |
def level(self) -> int:
|
| 43 |
-
return {
|
| 44 |
-
Difficulty.EASY: 1,
|
| 45 |
-
Difficulty.MEDIUM: 2,
|
| 46 |
-
Difficulty.HARD: 3,
|
| 47 |
-
}[self]
|
| 48 |
|
| 49 |
|
| 50 |
@dataclass(slots=True)
|
| 51 |
class Task:
|
| 52 |
-
"""Immutable task definition loaded at startup."""
|
| 53 |
-
|
| 54 |
id: str
|
| 55 |
name: str
|
| 56 |
description: str
|
|
@@ -64,8 +68,6 @@ class Task:
|
|
| 64 |
def __post_init__(self) -> None:
|
| 65 |
if not self.id:
|
| 66 |
raise ValueError("Task id cannot be empty")
|
| 67 |
-
if not self.name:
|
| 68 |
-
raise ValueError("Task name cannot be empty")
|
| 69 |
if self.max_steps <= 0:
|
| 70 |
raise ValueError("max_steps must be positive")
|
| 71 |
if self.target_score_range == (0.0, 1.0):
|
|
@@ -76,7 +78,6 @@ class Task:
|
|
| 76 |
}[self.difficulty]
|
| 77 |
|
| 78 |
def summary(self) -> dict[str, Any]:
|
| 79 |
-
"""Return the public task descriptor without leaking the answer key."""
|
| 80 |
return {
|
| 81 |
"id": self.id,
|
| 82 |
"task_id": self.id,
|
|
@@ -88,70 +89,70 @@ class Task:
|
|
| 88 |
"target_score_range": list(self.target_score_range),
|
| 89 |
"tags": self.tags,
|
| 90 |
"success_criteria": self.success_criteria,
|
| 91 |
-
"
|
| 92 |
}
|
| 93 |
|
| 94 |
|
| 95 |
-
class
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
bug_type: str = Field(..., description="One of syntax, runtime, logic, security")
|
| 100 |
-
explanation: str = Field(..., min_length=1, description="Concise explanation of the bug")
|
| 101 |
-
|
| 102 |
-
@field_validator("bug_type")
|
| 103 |
@classmethod
|
| 104 |
-
def
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
return cleaned
|
| 109 |
|
| 110 |
-
@field_validator("
|
| 111 |
@classmethod
|
| 112 |
-
def
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
return cleaned
|
| 117 |
|
| 118 |
@classmethod
|
| 119 |
def from_llm_output(
|
| 120 |
cls,
|
| 121 |
text: str,
|
| 122 |
available_actions: list[str] | None = None,
|
| 123 |
-
) -> "
|
| 124 |
-
"""Parse flexible model output into a structured bug report."""
|
| 125 |
candidate = text.strip()
|
| 126 |
if not candidate:
|
| 127 |
return cls(
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
)
|
| 132 |
|
| 133 |
candidate = candidate.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
|
| 134 |
-
|
| 135 |
-
if
|
| 136 |
-
candidate =
|
| 137 |
|
| 138 |
try:
|
| 139 |
data = json.loads(candidate)
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
type_match = re.search(
|
| 143 |
-
r"\b(syntax|runtime|logic|security)\b",
|
| 144 |
-
candidate,
|
| 145 |
-
re.IGNORECASE,
|
| 146 |
-
)
|
| 147 |
return cls(
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
)
|
| 152 |
|
| 153 |
-
return cls.model_validate(data)
|
| 154 |
-
|
| 155 |
@classmethod
|
| 156 |
def model_json_schema(
|
| 157 |
cls,
|
|
@@ -160,59 +161,55 @@ class CodeReviewAction(BaseModel):
|
|
| 160 |
schema_generator: Any = None,
|
| 161 |
mode: str = "validation",
|
| 162 |
) -> dict[str, Any]:
|
| 163 |
-
"""Return the exact public schema exposed at /tasks."""
|
| 164 |
return dict(ACTION_SCHEMA)
|
| 165 |
|
| 166 |
|
| 167 |
-
class
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
timestamp: datetime = Field(default_factory=utc_now, description="Observation timestamp")
|
| 183 |
|
| 184 |
def to_prompt(self) -> str:
|
| 185 |
-
"""Convert the observation into an LLM-friendly prompt."""
|
| 186 |
history = "\n".join(self.feedback_history) if self.feedback_history else "None"
|
| 187 |
return (
|
| 188 |
f"Task: {self.task_name}\n"
|
| 189 |
f"Description: {self.task_description}\n"
|
| 190 |
-
f"
|
| 191 |
-
f"
|
| 192 |
-
f"
|
| 193 |
-
f"
|
| 194 |
-
"
|
| 195 |
-
|
|
|
|
|
|
|
| 196 |
)
|
| 197 |
|
| 198 |
|
| 199 |
-
class
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
attempts_used: int = Field(..., ge=0, description="Number of attempts consumed in the episode")
|
| 206 |
|
| 207 |
-
@field_validator("value",
|
| 208 |
@classmethod
|
| 209 |
-
def
|
| 210 |
-
return max(0.0, min(1.0, float(
|
| 211 |
|
| 212 |
|
| 213 |
-
class
|
| 214 |
-
"""Typed state snapshot returned by state()."""
|
| 215 |
-
|
| 216 |
episode_id: str
|
| 217 |
step_count: int = Field(..., ge=0)
|
| 218 |
task_id: str
|
|
@@ -221,14 +218,14 @@ class CodeReviewState(BaseModel):
|
|
| 221 |
|
| 222 |
@field_validator("final_score", mode="before")
|
| 223 |
@classmethod
|
| 224 |
-
def
|
| 225 |
-
return max(0.0, min(1.0, float(
|
| 226 |
|
| 227 |
|
| 228 |
-
Action =
|
| 229 |
-
Observation =
|
| 230 |
-
Reward =
|
| 231 |
-
State =
|
| 232 |
|
| 233 |
|
| 234 |
class ResetRequest(BaseModel):
|
|
@@ -236,10 +233,6 @@ class ResetRequest(BaseModel):
|
|
| 236 |
seed: int | None = None
|
| 237 |
|
| 238 |
|
| 239 |
-
class StepRequest(BaseModel):
|
| 240 |
-
action: Action
|
| 241 |
-
|
| 242 |
-
|
| 243 |
class GraderRequest(BaseModel):
|
| 244 |
task_id: str
|
| 245 |
episode: list[dict[str, Any]]
|
|
|
|
| 1 |
+
"""Pydantic models for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def utc_now() -> datetime:
|
|
|
|
| 16 |
return datetime.now(timezone.utc)
|
| 17 |
|
| 18 |
|
| 19 |
ACTION_SCHEMA = {
|
| 20 |
"type": "object",
|
| 21 |
"properties": {
|
| 22 |
+
"action_type": {
|
|
|
|
| 23 |
"type": "string",
|
| 24 |
+
"enum": [
|
| 25 |
+
"fix_value",
|
| 26 |
+
"drop_row",
|
| 27 |
+
"fill_missing",
|
| 28 |
+
"cast_type",
|
| 29 |
+
"rename_column",
|
| 30 |
+
"flag_anomaly",
|
| 31 |
+
"standardize_format",
|
| 32 |
+
],
|
| 33 |
},
|
| 34 |
+
"row_index": {
|
| 35 |
+
"type": "integer",
|
| 36 |
+
"description": "0-based row index (null for column-level actions)",
|
| 37 |
+
},
|
| 38 |
+
"column": {"type": "string", "description": "Column name to act on"},
|
| 39 |
+
"new_value": {"description": "Replacement value (string, number, or null)"},
|
| 40 |
+
"reason": {"type": "string", "description": "One-sentence justification"},
|
| 41 |
},
|
| 42 |
+
"required": ["action_type", "column", "reason"],
|
| 43 |
}
|
| 44 |
|
| 45 |
|
| 46 |
class Difficulty(str, Enum):
|
|
|
|
|
|
|
| 47 |
EASY = "easy"
|
| 48 |
MEDIUM = "medium"
|
| 49 |
HARD = "hard"
|
| 50 |
|
| 51 |
@property
|
| 52 |
def level(self) -> int:
|
| 53 |
+
return {"easy": 1, "medium": 2, "hard": 3}[self.value]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
|
| 56 |
@dataclass(slots=True)
|
| 57 |
class Task:
|
|
|
|
|
|
|
| 58 |
id: str
|
| 59 |
name: str
|
| 60 |
description: str
|
|
|
|
| 68 |
def __post_init__(self) -> None:
|
| 69 |
if not self.id:
|
| 70 |
raise ValueError("Task id cannot be empty")
|
|
|
|
|
|
|
| 71 |
if self.max_steps <= 0:
|
| 72 |
raise ValueError("max_steps must be positive")
|
| 73 |
if self.target_score_range == (0.0, 1.0):
|
|
|
|
| 78 |
}[self.difficulty]
|
| 79 |
|
| 80 |
def summary(self) -> dict[str, Any]:
|
|
|
|
| 81 |
return {
|
| 82 |
"id": self.id,
|
| 83 |
"task_id": self.id,
|
|
|
|
| 89 |
"target_score_range": list(self.target_score_range),
|
| 90 |
"tags": self.tags,
|
| 91 |
"success_criteria": self.success_criteria,
|
| 92 |
+
"dataset_preview": self.config.get("dataset_preview", ""),
|
| 93 |
}
|
| 94 |
|
| 95 |
|
| 96 |
+
class DataCleaningAction(BaseModel):
|
| 97 |
+
action_type: str
|
| 98 |
+
row_index: int | None = Field(default=None, ge=0)
|
| 99 |
+
column: str
|
| 100 |
+
new_value: Any = None
|
| 101 |
+
reason: str = Field(..., min_length=1)
|
| 102 |
|
| 103 |
+
@field_validator("action_type")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
@classmethod
|
| 105 |
+
def validate_action_type(cls, v: str) -> str:
|
| 106 |
+
valid = {
|
| 107 |
+
"fix_value",
|
| 108 |
+
"drop_row",
|
| 109 |
+
"fill_missing",
|
| 110 |
+
"cast_type",
|
| 111 |
+
"rename_column",
|
| 112 |
+
"flag_anomaly",
|
| 113 |
+
"standardize_format",
|
| 114 |
+
}
|
| 115 |
+
cleaned = v.strip().lower()
|
| 116 |
+
if cleaned not in valid:
|
| 117 |
+
raise ValueError(f"action_type must be one of {sorted(valid)}")
|
| 118 |
return cleaned
|
| 119 |
|
| 120 |
+
@field_validator("reason")
|
| 121 |
@classmethod
|
| 122 |
+
def validate_reason(cls, v: str) -> str:
|
| 123 |
+
if not v.strip():
|
| 124 |
+
raise ValueError("reason cannot be empty")
|
| 125 |
+
return v.strip()
|
|
|
|
| 126 |
|
| 127 |
@classmethod
|
| 128 |
def from_llm_output(
|
| 129 |
cls,
|
| 130 |
text: str,
|
| 131 |
available_actions: list[str] | None = None,
|
| 132 |
+
) -> "DataCleaningAction":
|
|
|
|
| 133 |
candidate = text.strip()
|
| 134 |
if not candidate:
|
| 135 |
return cls(
|
| 136 |
+
action_type="flag_anomaly",
|
| 137 |
+
column="unknown",
|
| 138 |
+
reason="No valid action produced.",
|
| 139 |
)
|
| 140 |
|
| 141 |
candidate = candidate.removeprefix("```json").removeprefix("```").removesuffix("```").strip()
|
| 142 |
+
match = re.search(r"\{.*\}", candidate, re.DOTALL)
|
| 143 |
+
if match:
|
| 144 |
+
candidate = match.group(0)
|
| 145 |
|
| 146 |
try:
|
| 147 |
data = json.loads(candidate)
|
| 148 |
+
return cls.model_validate(data)
|
| 149 |
+
except Exception:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
return cls(
|
| 151 |
+
action_type="flag_anomaly",
|
| 152 |
+
column="unknown",
|
| 153 |
+
reason=candidate[:200],
|
| 154 |
)
|
| 155 |
|
|
|
|
|
|
|
| 156 |
@classmethod
|
| 157 |
def model_json_schema(
|
| 158 |
cls,
|
|
|
|
| 161 |
schema_generator: Any = None,
|
| 162 |
mode: str = "validation",
|
| 163 |
) -> dict[str, Any]:
|
|
|
|
| 164 |
return dict(ACTION_SCHEMA)
|
| 165 |
|
| 166 |
|
| 167 |
+
class DataCleaningObservation(BaseModel):
|
| 168 |
+
done: bool = False
|
| 169 |
+
task_id: str
|
| 170 |
+
task_name: str
|
| 171 |
+
task_description: str
|
| 172 |
+
dataset_preview: str
|
| 173 |
+
issues_remaining: int = 0
|
| 174 |
+
step: int = Field(..., ge=0)
|
| 175 |
+
max_steps: int = Field(..., gt=0)
|
| 176 |
+
attempts_remaining: int = Field(..., ge=0)
|
| 177 |
+
feedback: str = ""
|
| 178 |
+
feedback_history: list[str] = Field(default_factory=list)
|
| 179 |
+
available_actions: list[str] = Field(default_factory=list)
|
| 180 |
+
context: str = ""
|
| 181 |
+
timestamp: datetime = Field(default_factory=utc_now)
|
|
|
|
| 182 |
|
| 183 |
def to_prompt(self) -> str:
|
|
|
|
| 184 |
history = "\n".join(self.feedback_history) if self.feedback_history else "None"
|
| 185 |
return (
|
| 186 |
f"Task: {self.task_name}\n"
|
| 187 |
f"Description: {self.task_description}\n"
|
| 188 |
+
f"Step: {self.step + 1} of {self.max_steps} | "
|
| 189 |
+
f"Issues remaining: {self.issues_remaining}\n"
|
| 190 |
+
f"Previous feedback:\n{history}\n\n"
|
| 191 |
+
f"Current dataset:\n{self.dataset_preview}\n\n"
|
| 192 |
+
f"Available action types: {', '.join(self.available_actions)}\n\n"
|
| 193 |
+
"Respond with valid JSON only — no prose, no markdown:\n"
|
| 194 |
+
'{"action_type": "fix_value", "row_index": 2, "column": "email", '
|
| 195 |
+
'"new_value": "user@example.com", "reason": "row 2 email is missing"}'
|
| 196 |
)
|
| 197 |
|
| 198 |
|
| 199 |
+
class DataCleaningReward(BaseModel):
|
| 200 |
+
value: float = Field(..., ge=0.0, le=1.0)
|
| 201 |
+
issues_fixed_this_step: int = Field(default=0, ge=0)
|
| 202 |
+
issues_remaining: int = Field(default=0, ge=0)
|
| 203 |
+
solved: bool = False
|
| 204 |
+
attempts_used: int = Field(..., ge=0)
|
|
|
|
| 205 |
|
| 206 |
+
@field_validator("value", mode="before")
|
| 207 |
@classmethod
|
| 208 |
+
def clamp(cls, v: float) -> float:
|
| 209 |
+
return max(0.0, min(1.0, float(v)))
|
| 210 |
|
| 211 |
|
| 212 |
+
class DataCleaningState(BaseModel):
|
|
|
|
|
|
|
| 213 |
episode_id: str
|
| 214 |
step_count: int = Field(..., ge=0)
|
| 215 |
task_id: str
|
|
|
|
| 218 |
|
| 219 |
@field_validator("final_score", mode="before")
|
| 220 |
@classmethod
|
| 221 |
+
def clamp_score(cls, v: float) -> float:
|
| 222 |
+
return max(0.0, min(1.0, float(v)))
|
| 223 |
|
| 224 |
|
| 225 |
+
Action = DataCleaningAction
|
| 226 |
+
Observation = DataCleaningObservation
|
| 227 |
+
Reward = DataCleaningReward
|
| 228 |
+
State = DataCleaningState
|
| 229 |
|
| 230 |
|
| 231 |
class ResetRequest(BaseModel):
|
|
|
|
| 233 |
seed: int | None = None
|
| 234 |
|
| 235 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
class GraderRequest(BaseModel):
|
| 237 |
task_id: str
|
| 238 |
episode: list[dict[str, Any]]
|
environment/reward.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Dense reward
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -14,16 +14,30 @@ def compute_reward(
|
|
| 14 |
task_config: dict[str, Any] | None = None,
|
| 15 |
weights: dict[str, float] | None = None,
|
| 16 |
) -> Reward:
|
| 17 |
-
"""Build a reward object from the transition computed in env.step()."""
|
| 18 |
transition = next_state.get("last_transition", {})
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
solved = bool(transition.get("solved", False))
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
return Reward(
|
| 25 |
-
value=
|
| 26 |
-
|
|
|
|
| 27 |
solved=solved,
|
| 28 |
-
attempts_used=
|
| 29 |
)
|
|
|
|
| 1 |
+
"""Dense per-step reward for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 14 |
task_config: dict[str, Any] | None = None,
|
| 15 |
weights: dict[str, float] | None = None,
|
| 16 |
) -> Reward:
|
|
|
|
| 17 |
transition = next_state.get("last_transition", {})
|
| 18 |
+
issues_fixed = int(transition.get("issues_fixed_this_step", 0))
|
| 19 |
+
issues_remaining = int(transition.get("issues_remaining", 0))
|
| 20 |
+
was_trap = bool(transition.get("trap_penalty", False))
|
| 21 |
+
was_redundant = bool(transition.get("redundant_action", False))
|
| 22 |
solved = bool(transition.get("solved", False))
|
| 23 |
+
total_issues = int((task_config or {}).get("total_issues", 1))
|
| 24 |
+
steps_used = int(next_state.get("step_count", 1))
|
| 25 |
+
max_steps = int(next_state.get("max_steps", 1))
|
| 26 |
|
| 27 |
+
reward = 0.0
|
| 28 |
+
reward += issues_fixed * (0.2 / max(1, total_issues / 3))
|
| 29 |
+
if was_trap:
|
| 30 |
+
reward -= 0.1
|
| 31 |
+
if was_redundant:
|
| 32 |
+
reward -= 0.05
|
| 33 |
+
if solved and steps_used <= max_steps // 2:
|
| 34 |
+
reward += 0.15
|
| 35 |
+
|
| 36 |
+
value = max(0.0, min(1.0, reward))
|
| 37 |
return Reward(
|
| 38 |
+
value=round(value, 4),
|
| 39 |
+
issues_fixed_this_step=issues_fixed,
|
| 40 |
+
issues_remaining=issues_remaining,
|
| 41 |
solved=solved,
|
| 42 |
+
attempts_used=steps_used,
|
| 43 |
)
|
environment/tasks.py
CHANGED
|
@@ -1,182 +1,192 @@
|
|
| 1 |
-
"""Task registry for the
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from .models import Difficulty, Task
|
| 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 |
-
"1 from fastapi import APIRouter, Depends, HTTPException",
|
| 61 |
-
"2 from pydantic import BaseModel",
|
| 62 |
-
"3 import sqlite3",
|
| 63 |
-
"4 ",
|
| 64 |
-
"5 router = APIRouter(prefix=\"/admin\", tags=[\"admin\"])",
|
| 65 |
-
"6 ",
|
| 66 |
-
"7 class AuditQuery(BaseModel):",
|
| 67 |
-
"8 username: str",
|
| 68 |
-
"9 ",
|
| 69 |
-
"10 def get_db():",
|
| 70 |
-
"11 connection = sqlite3.connect(\"app.db\")",
|
| 71 |
-
"12 connection.row_factory = sqlite3.Row",
|
| 72 |
-
"13 return connection",
|
| 73 |
-
"14 ",
|
| 74 |
-
"15 @router.post(\"/audit-log\")",
|
| 75 |
-
"16 def fetch_audit_log(payload: AuditQuery, db=Depends(get_db)):",
|
| 76 |
-
"17 if not payload.username:",
|
| 77 |
-
"18 raise HTTPException(status_code=400, detail=\"username is required\")",
|
| 78 |
-
"19 ",
|
| 79 |
-
"20 query = (",
|
| 80 |
-
"21 \"SELECT action, created_at \"",
|
| 81 |
-
"22 \"FROM audit_log \"",
|
| 82 |
-
"23 f\"WHERE username = '{payload.username}' \"",
|
| 83 |
-
"24 \"ORDER BY created_at DESC LIMIT 50\"",
|
| 84 |
-
"25 )",
|
| 85 |
-
"26 ",
|
| 86 |
-
"27 cursor = db.execute(query)",
|
| 87 |
-
"28 rows = cursor.fetchall()",
|
| 88 |
-
"29 ",
|
| 89 |
-
"30 return {",
|
| 90 |
-
"31 \"username\": payload.username,",
|
| 91 |
-
"32 \"events\": [dict(row) for row in rows],",
|
| 92 |
-
"33 \"count\": len(rows),",
|
| 93 |
-
"34 }",
|
| 94 |
-
"35 ",
|
| 95 |
-
]
|
| 96 |
-
)
|
| 97 |
|
| 98 |
|
| 99 |
TASKS: dict[str, Task] = {
|
| 100 |
-
"
|
| 101 |
-
id="
|
| 102 |
-
name="
|
| 103 |
description=(
|
| 104 |
-
"
|
| 105 |
-
"
|
| 106 |
),
|
| 107 |
difficulty=Difficulty.EASY,
|
| 108 |
-
max_steps=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
config={
|
| 110 |
-
"
|
| 111 |
-
"available_actions": ["
|
| 112 |
-
"
|
| 113 |
-
"
|
| 114 |
-
"
|
| 115 |
-
"
|
| 116 |
-
|
|
|
|
|
|
|
| 117 |
},
|
| 118 |
-
tags=["
|
| 119 |
-
success_criteria="
|
| 120 |
),
|
| 121 |
-
"
|
| 122 |
-
id="
|
| 123 |
-
name="
|
| 124 |
description=(
|
| 125 |
-
"
|
| 126 |
-
"
|
| 127 |
),
|
| 128 |
difficulty=Difficulty.MEDIUM,
|
| 129 |
-
max_steps=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
config={
|
| 131 |
-
"
|
| 132 |
-
"available_actions": ["
|
| 133 |
-
"
|
| 134 |
-
"
|
| 135 |
-
"
|
| 136 |
-
"
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
},
|
| 139 |
-
tags=["
|
| 140 |
-
success_criteria="
|
| 141 |
),
|
| 142 |
-
"
|
| 143 |
-
id="
|
| 144 |
-
name="
|
| 145 |
description=(
|
| 146 |
-
"
|
| 147 |
-
"
|
| 148 |
),
|
| 149 |
difficulty=Difficulty.HARD,
|
| 150 |
-
max_steps=
|
| 151 |
config={
|
| 152 |
-
"
|
| 153 |
-
"available_actions": ["
|
| 154 |
-
"
|
| 155 |
-
"
|
| 156 |
-
"
|
| 157 |
-
|
| 158 |
-
|
| 159 |
},
|
| 160 |
-
tags=["
|
| 161 |
-
success_criteria="
|
| 162 |
),
|
| 163 |
}
|
| 164 |
|
| 165 |
|
| 166 |
def get_task(task_id: str) -> Task:
|
| 167 |
-
"""Return a task by ID with a helpful error if it is missing."""
|
| 168 |
if task_id not in TASKS:
|
| 169 |
available = ", ".join(TASKS)
|
| 170 |
-
raise ValueError(f"Task '{task_id}' not found. Available
|
| 171 |
return TASKS[task_id]
|
| 172 |
|
| 173 |
|
| 174 |
def get_tasks_by_difficulty(difficulty: Difficulty) -> list[Task]:
|
| 175 |
-
"""Return all tasks in a given difficulty bucket."""
|
| 176 |
return [task for task in TASKS.values() if task.difficulty == difficulty]
|
| 177 |
|
| 178 |
|
| 179 |
def get_default_task() -> Task:
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
return easy_tasks[0] if easy_tasks else next(iter(TASKS.values()))
|
|
|
|
| 1 |
+
"""Task registry for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
from .models import Difficulty, Task
|
| 6 |
|
| 7 |
|
| 8 |
+
EASY_DATASET = """\
|
| 9 |
+
row_id | name | age | email
|
| 10 |
+
-------|---------------|------|----------------------
|
| 11 |
+
0 | Alice Chen | 29 | alice@example.com
|
| 12 |
+
1 | Bob Marsh | | bob@example.com
|
| 13 |
+
2 | Carol Diaz | NULL | carol@example.com
|
| 14 |
+
3 | Dave Kim | 31 | dave@example.com
|
| 15 |
+
4 | Eve Santos | 27 |
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
MEDIUM_DATASET = """\
|
| 19 |
+
row_id | date | revenue | currency
|
| 20 |
+
-------|-----------------|---------|----------
|
| 21 |
+
0 | 2024-01-15 | 1500 | USD
|
| 22 |
+
1 | 15/01/2024 | 1200 | usd
|
| 23 |
+
2 | Jan 15 2024 | 980 | USD
|
| 24 |
+
3 | 2024-01-15 | 1500 | US Dollar
|
| 25 |
+
4 | 01-15-2024 | 2100 | USD
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
MEDIUM_HARD_DATASET = """\
|
| 29 |
+
row_id | user_id | amount | transaction_date | status
|
| 30 |
+
-------|---------|-----------|------------------|----------
|
| 31 |
+
0 | U001 | 150.00 | 2024-01-10 | completed
|
| 32 |
+
1 | U001 | 150.00 | 2024-01-10 | completed
|
| 33 |
+
2 | U002 | 99999.99 | 2024-01-11 | completed
|
| 34 |
+
3 | U003 | -50.00 | 2024-01-12 | completed
|
| 35 |
+
4 | U004 | 200.00 | 2024-01-13 | completed
|
| 36 |
+
5 | U005 | 175.00 | 2024-01-14 | COMPLETED
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
HARD_DATASET = """\
|
| 40 |
+
row_id | order_id | customer_id | product_id | qty | unit_price | order_dt
|
| 41 |
+
-------|----------|-------------|------------|------|------------|------------
|
| 42 |
+
0 | ORD-001 | C100 | P200 | 2 | 49.99 | 2024-01-05
|
| 43 |
+
1 | ORD-002 | C101 | P201 | -1 | 75.00 | 2024-01-06
|
| 44 |
+
2 | ORD-003 | C999 | P202 | 3 | 0.00 | 2024-01-07
|
| 45 |
+
3 | ORD-004 | C102 | P999 | 1 | 29.99 | 2024-13-01
|
| 46 |
+
4 | ORD-005 | C103 | P203 | 1000 | 5.00 | 2024-01-09
|
| 47 |
+
5 | ORD-001 | C100 | P200 | 2 | 49.99 | 2024-01-05
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
ADVERSARIAL_DATASET = """\
|
| 51 |
+
row_id | sensor_id | reading | unit | recorded_at
|
| 52 |
+
-------|-----------|-----------|------|------------------
|
| 53 |
+
0 | S001 | -17.5 | C | 2024-01-15 08:00
|
| 54 |
+
1 | S002 | 212 | F | 2024-01-15 08:01
|
| 55 |
+
2 | S003 | NULL | C | 2024-01-15 08:02
|
| 56 |
+
3 | S004 | 98.6 | F | 2024-01-15 08:03
|
| 57 |
+
4 | S005 | 0.0 | C | 2024-01-15 08:04
|
| 58 |
+
5 | S006 | 999 | C | 2024-01-15 08:05
|
| 59 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
TASKS: dict[str, Task] = {
|
| 63 |
+
"null_filling": Task(
|
| 64 |
+
id="null_filling",
|
| 65 |
+
name="Missing Value Repair",
|
| 66 |
description=(
|
| 67 |
+
"A contacts table has missing and malformed null values. "
|
| 68 |
+
"Identify and fill each missing field with a sensible placeholder."
|
| 69 |
),
|
| 70 |
difficulty=Difficulty.EASY,
|
| 71 |
+
max_steps=5,
|
| 72 |
+
config={
|
| 73 |
+
"dataset_preview": EASY_DATASET,
|
| 74 |
+
"available_actions": ["fill_missing", "fix_value", "flag_anomaly"],
|
| 75 |
+
"issues": [
|
| 76 |
+
{"row_index": 1, "column": "age", "issue_type": "missing"},
|
| 77 |
+
{"row_index": 2, "column": "age", "issue_type": "string_null"},
|
| 78 |
+
{"row_index": 4, "column": "email", "issue_type": "missing"},
|
| 79 |
+
],
|
| 80 |
+
},
|
| 81 |
+
tags=["data-cleaning", "nulls", "contacts"],
|
| 82 |
+
success_criteria="Fill all 3 missing or malformed cells with valid placeholder values.",
|
| 83 |
+
),
|
| 84 |
+
"format_standardization": Task(
|
| 85 |
+
id="format_standardization",
|
| 86 |
+
name="Date and Currency Standardization",
|
| 87 |
+
description=(
|
| 88 |
+
"A revenue table mixes date formats and currency codes. "
|
| 89 |
+
"Standardize all dates to ISO-8601 and all currency codes to uppercase 3-letter values."
|
| 90 |
+
),
|
| 91 |
+
difficulty=Difficulty.MEDIUM,
|
| 92 |
+
max_steps=8,
|
| 93 |
config={
|
| 94 |
+
"dataset_preview": MEDIUM_DATASET,
|
| 95 |
+
"available_actions": ["standardize_format", "fix_value", "flag_anomaly"],
|
| 96 |
+
"issues": [
|
| 97 |
+
{"row_index": 1, "column": "date", "issue_type": "format", "correct": "2024-01-15"},
|
| 98 |
+
{"row_index": 2, "column": "date", "issue_type": "format", "correct": "2024-01-15"},
|
| 99 |
+
{"row_index": 4, "column": "date", "issue_type": "format", "correct": "2024-01-15"},
|
| 100 |
+
{"row_index": 1, "column": "currency", "issue_type": "case", "correct": "USD"},
|
| 101 |
+
{"row_index": 3, "column": "currency", "issue_type": "format", "correct": "USD"},
|
| 102 |
+
],
|
| 103 |
},
|
| 104 |
+
tags=["data-cleaning", "formats", "dates", "currencies"],
|
| 105 |
+
success_criteria="All dates must be ISO-8601 and all currencies must be uppercase 3-letter codes.",
|
| 106 |
),
|
| 107 |
+
"duplicate_outlier": Task(
|
| 108 |
+
id="duplicate_outlier",
|
| 109 |
+
name="Duplicate and Outlier Removal",
|
| 110 |
description=(
|
| 111 |
+
"A transactions table contains a duplicate row, an extreme outlier amount, "
|
| 112 |
+
"a negative amount, and a case inconsistency. Identify and fix all four issues."
|
| 113 |
),
|
| 114 |
difficulty=Difficulty.MEDIUM,
|
| 115 |
+
max_steps=8,
|
| 116 |
+
config={
|
| 117 |
+
"dataset_preview": MEDIUM_HARD_DATASET,
|
| 118 |
+
"available_actions": ["drop_row", "fix_value", "flag_anomaly", "standardize_format"],
|
| 119 |
+
"issues": [
|
| 120 |
+
{"row_index": 1, "column": "row_id", "issue_type": "duplicate"},
|
| 121 |
+
{"row_index": 2, "column": "amount", "issue_type": "outlier"},
|
| 122 |
+
{"row_index": 3, "column": "amount", "issue_type": "negative"},
|
| 123 |
+
{"row_index": 5, "column": "status", "issue_type": "case", "correct": "completed"},
|
| 124 |
+
],
|
| 125 |
+
},
|
| 126 |
+
tags=["data-cleaning", "duplicates", "outliers", "transactions"],
|
| 127 |
+
success_criteria="Duplicate dropped, outlier flagged, negative fixed, and status normalized.",
|
| 128 |
+
),
|
| 129 |
+
"multi_layer_pipeline": Task(
|
| 130 |
+
id="multi_layer_pipeline",
|
| 131 |
+
name="Multi-Layer Order Data Pipeline",
|
| 132 |
+
description=(
|
| 133 |
+
"An orders table has layered issues: a duplicate row, a negative quantity, "
|
| 134 |
+
"two broken foreign key references, an invalid date, a statistical outlier, and a zero price. "
|
| 135 |
+
"Fix all issues without missing the interactions between them."
|
| 136 |
+
),
|
| 137 |
+
difficulty=Difficulty.HARD,
|
| 138 |
+
max_steps=12,
|
| 139 |
config={
|
| 140 |
+
"dataset_preview": HARD_DATASET,
|
| 141 |
+
"available_actions": ["drop_row", "fix_value", "flag_anomaly", "cast_type", "fill_missing"],
|
| 142 |
+
"issues": [
|
| 143 |
+
{"row_index": 1, "column": "qty", "issue_type": "negative"},
|
| 144 |
+
{"row_index": 2, "column": "customer_id", "issue_type": "invalid_fk"},
|
| 145 |
+
{"row_index": 2, "column": "unit_price", "issue_type": "zero_price"},
|
| 146 |
+
{"row_index": 3, "column": "product_id", "issue_type": "invalid_fk"},
|
| 147 |
+
{"row_index": 3, "column": "order_dt", "issue_type": "invalid_date"},
|
| 148 |
+
{"row_index": 4, "column": "qty", "issue_type": "outlier"},
|
| 149 |
+
{"row_index": 5, "column": "row_id", "issue_type": "duplicate"},
|
| 150 |
+
],
|
| 151 |
},
|
| 152 |
+
tags=["data-cleaning", "pipeline", "fk-violations", "orders"],
|
| 153 |
+
success_criteria="All 7 issues correctly identified and acted on.",
|
| 154 |
),
|
| 155 |
+
"adversarial_sensor": Task(
|
| 156 |
+
id="adversarial_sensor",
|
| 157 |
+
name="Adversarial Sensor Data",
|
| 158 |
description=(
|
| 159 |
+
"A sensor table contains values that look suspicious but are physically valid. "
|
| 160 |
+
"Only two values are genuinely wrong. Fix only what is truly broken; modifying valid readings is penalized."
|
| 161 |
),
|
| 162 |
difficulty=Difficulty.HARD,
|
| 163 |
+
max_steps=8,
|
| 164 |
config={
|
| 165 |
+
"dataset_preview": ADVERSARIAL_DATASET,
|
| 166 |
+
"available_actions": ["fix_value", "flag_anomaly", "drop_row", "fill_missing"],
|
| 167 |
+
"issues": [
|
| 168 |
+
{"row_index": 2, "column": "reading", "issue_type": "null"},
|
| 169 |
+
{"row_index": 5, "column": "reading", "issue_type": "outlier"},
|
| 170 |
+
],
|
| 171 |
+
"traps": [0, 1, 4],
|
| 172 |
},
|
| 173 |
+
tags=["data-cleaning", "adversarial", "sensor", "domain-knowledge"],
|
| 174 |
+
success_criteria="Fix the 2 real issues and leave the 3 valid trap rows untouched.",
|
| 175 |
),
|
| 176 |
}
|
| 177 |
|
| 178 |
|
| 179 |
def get_task(task_id: str) -> Task:
|
|
|
|
| 180 |
if task_id not in TASKS:
|
| 181 |
available = ", ".join(TASKS)
|
| 182 |
+
raise ValueError(f"Task '{task_id}' not found. Available: {available}")
|
| 183 |
return TASKS[task_id]
|
| 184 |
|
| 185 |
|
| 186 |
def get_tasks_by_difficulty(difficulty: Difficulty) -> list[Task]:
|
|
|
|
| 187 |
return [task for task in TASKS.values() if task.difficulty == difficulty]
|
| 188 |
|
| 189 |
|
| 190 |
def get_default_task() -> Task:
|
| 191 |
+
easy = get_tasks_by_difficulty(Difficulty.EASY)
|
| 192 |
+
return easy[0] if easy else next(iter(TASKS.values()))
|
|
|
inference.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Root inference entrypoint for the
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -27,10 +27,11 @@ REQUEST_TIMEOUT = float(os.getenv("REQUEST_TIMEOUT", "30"))
|
|
| 27 |
|
| 28 |
JSON_BLOCK_RE = re.compile(r"\{.*\}", re.DOTALL)
|
| 29 |
SYSTEM_PROMPT = (
|
| 30 |
-
"You are an expert
|
| 31 |
-
"You will be shown a
|
| 32 |
-
"
|
| 33 |
-
|
|
|
|
| 34 |
)
|
| 35 |
|
| 36 |
|
|
@@ -42,7 +43,6 @@ def strip_json_block(text: str) -> str:
|
|
| 42 |
|
| 43 |
|
| 44 |
def build_env_client(stack: ExitStack) -> Any:
|
| 45 |
-
"""Prefer a live HTTP environment, but fall back to an in-process app."""
|
| 46 |
remote_client = httpx.Client(base_url=ENVIRONMENT_URL, timeout=REQUEST_TIMEOUT)
|
| 47 |
try:
|
| 48 |
health_response = remote_client.get("/health")
|
|
@@ -65,24 +65,42 @@ def parse_model_action(response_text: str) -> Action:
|
|
| 65 |
return Action.from_llm_output(response_text, [])
|
| 66 |
|
| 67 |
|
| 68 |
-
def fallback_action(
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def main() -> None:
|
|
@@ -95,13 +113,14 @@ def main() -> None:
|
|
| 95 |
tasks_response.raise_for_status()
|
| 96 |
tasks = tasks_response.json()
|
| 97 |
chosen_task = next(
|
| 98 |
-
(task for task in tasks if task.get("id") == "
|
| 99 |
None,
|
| 100 |
)
|
| 101 |
if chosen_task is None:
|
| 102 |
chosen_task = next((task for task in tasks if task["difficulty"] == "hard"), tasks[0])
|
| 103 |
|
| 104 |
-
|
|
|
|
| 105 |
reset_response.raise_for_status()
|
| 106 |
reset_payload = reset_response.json()
|
| 107 |
session_id = reset_payload["session_id"]
|
|
@@ -109,10 +128,17 @@ def main() -> None:
|
|
| 109 |
|
| 110 |
messages: list[dict[str, str]] = [
|
| 111 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 112 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
]
|
| 114 |
|
| 115 |
-
print(f"Selected task: {
|
| 116 |
|
| 117 |
attempt_number = 0
|
| 118 |
while not observation["done"] and observation["attempts_remaining"] > 0:
|
|
@@ -128,9 +154,9 @@ def main() -> None:
|
|
| 128 |
response_text = completion.choices[0].message.content or ""
|
| 129 |
action = parse_model_action(response_text)
|
| 130 |
except Exception as exc: # noqa: BLE001
|
| 131 |
-
print(f"Model request failed ({exc}). Falling back to heuristic
|
| 132 |
response_text = ""
|
| 133 |
-
action = fallback_action(observation["
|
| 134 |
|
| 135 |
step_response = env_client.post(
|
| 136 |
"/step",
|
|
@@ -159,7 +185,11 @@ def main() -> None:
|
|
| 159 |
messages.append(
|
| 160 |
{
|
| 161 |
"role": "user",
|
| 162 |
-
"content":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
}
|
| 164 |
)
|
| 165 |
|
|
@@ -170,10 +200,7 @@ def main() -> None:
|
|
| 170 |
grader_response = env_client.post(
|
| 171 |
"/grader",
|
| 172 |
params={"session_id": session_id},
|
| 173 |
-
json={
|
| 174 |
-
"task_id": chosen_task.get("id", chosen_task["task_id"]),
|
| 175 |
-
"episode": state_payload["episode_history"],
|
| 176 |
-
},
|
| 177 |
)
|
| 178 |
grader_response.raise_for_status()
|
| 179 |
grader_payload = grader_response.json()
|
|
|
|
| 1 |
+
"""Root inference entrypoint for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 27 |
|
| 28 |
JSON_BLOCK_RE = re.compile(r"\{.*\}", re.DOTALL)
|
| 29 |
SYSTEM_PROMPT = (
|
| 30 |
+
"You are an expert data cleaning agent. "
|
| 31 |
+
"You will be shown a dirty tabular dataset preview. "
|
| 32 |
+
"Choose exactly one cleaning action at a time. "
|
| 33 |
+
"Respond ONLY in valid JSON with no extra text: "
|
| 34 |
+
'{"action_type":"fix_value","row_index":2,"column":"email","new_value":"user@example.com","reason":"row 2 email is missing"}'
|
| 35 |
)
|
| 36 |
|
| 37 |
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
def build_env_client(stack: ExitStack) -> Any:
|
|
|
|
| 46 |
remote_client = httpx.Client(base_url=ENVIRONMENT_URL, timeout=REQUEST_TIMEOUT)
|
| 47 |
try:
|
| 48 |
health_response = remote_client.get("/health")
|
|
|
|
| 65 |
return Action.from_llm_output(response_text, [])
|
| 66 |
|
| 67 |
|
| 68 |
+
def fallback_action(task_id: str, step: int) -> Action:
|
| 69 |
+
action_plans = {
|
| 70 |
+
"null_filling": [
|
| 71 |
+
{"action_type": "fill_missing", "row_index": 1, "column": "age", "new_value": "unknown", "reason": "age is missing"},
|
| 72 |
+
{"action_type": "fix_value", "row_index": 2, "column": "age", "new_value": "unknown", "reason": "literal NULL should be normalized"},
|
| 73 |
+
{"action_type": "fill_missing", "row_index": 4, "column": "email", "new_value": "missing@example.com", "reason": "email is missing"},
|
| 74 |
+
],
|
| 75 |
+
"format_standardization": [
|
| 76 |
+
{"action_type": "standardize_format", "row_index": 1, "column": "date", "new_value": "2024-01-15", "reason": "normalize to ISO"},
|
| 77 |
+
{"action_type": "standardize_format", "row_index": 2, "column": "date", "new_value": "2024-01-15", "reason": "normalize to ISO"},
|
| 78 |
+
{"action_type": "standardize_format", "row_index": 4, "column": "date", "new_value": "2024-01-15", "reason": "normalize to ISO"},
|
| 79 |
+
{"action_type": "fix_value", "row_index": 1, "column": "currency", "new_value": "USD", "reason": "uppercase currency"},
|
| 80 |
+
{"action_type": "fix_value", "row_index": 3, "column": "currency", "new_value": "USD", "reason": "standardize full currency name"},
|
| 81 |
+
],
|
| 82 |
+
"duplicate_outlier": [
|
| 83 |
+
{"action_type": "drop_row", "row_index": 1, "column": "row_id", "new_value": None, "reason": "exact duplicate"},
|
| 84 |
+
{"action_type": "flag_anomaly", "row_index": 2, "column": "amount", "new_value": None, "reason": "extreme outlier"},
|
| 85 |
+
{"action_type": "fix_value", "row_index": 3, "column": "amount", "new_value": 50.0, "reason": "negative amount should be non-negative"},
|
| 86 |
+
{"action_type": "standardize_format", "row_index": 5, "column": "status", "new_value": "completed", "reason": "normalize casing"},
|
| 87 |
+
],
|
| 88 |
+
"multi_layer_pipeline": [
|
| 89 |
+
{"action_type": "fix_value", "row_index": 1, "column": "qty", "new_value": 1, "reason": "quantity cannot be negative"},
|
| 90 |
+
{"action_type": "flag_anomaly", "row_index": 2, "column": "customer_id", "new_value": None, "reason": "invalid foreign key"},
|
| 91 |
+
{"action_type": "fix_value", "row_index": 2, "column": "unit_price", "new_value": 1.0, "reason": "price cannot be zero"},
|
| 92 |
+
{"action_type": "flag_anomaly", "row_index": 3, "column": "product_id", "new_value": None, "reason": "invalid foreign key"},
|
| 93 |
+
{"action_type": "fix_value", "row_index": 3, "column": "order_dt", "new_value": "2024-01-01", "reason": "repair invalid date"},
|
| 94 |
+
{"action_type": "flag_anomaly", "row_index": 4, "column": "qty", "new_value": None, "reason": "quantity is an outlier"},
|
| 95 |
+
{"action_type": "drop_row", "row_index": 5, "column": "row_id", "new_value": None, "reason": "duplicate order"},
|
| 96 |
+
],
|
| 97 |
+
"adversarial_sensor": [
|
| 98 |
+
{"action_type": "fill_missing", "row_index": 2, "column": "reading", "new_value": None, "reason": "reading is missing"},
|
| 99 |
+
{"action_type": "flag_anomaly", "row_index": 5, "column": "reading", "new_value": None, "reason": "999C is an impossible outlier"},
|
| 100 |
+
],
|
| 101 |
+
}
|
| 102 |
+
plan = action_plans[task_id]
|
| 103 |
+
return Action.model_validate(plan[min(step, len(plan) - 1)])
|
| 104 |
|
| 105 |
|
| 106 |
def main() -> None:
|
|
|
|
| 113 |
tasks_response.raise_for_status()
|
| 114 |
tasks = tasks_response.json()
|
| 115 |
chosen_task = next(
|
| 116 |
+
(task for task in tasks if task.get("id") == "adversarial_sensor" or task.get("task_id") == "adversarial_sensor"),
|
| 117 |
None,
|
| 118 |
)
|
| 119 |
if chosen_task is None:
|
| 120 |
chosen_task = next((task for task in tasks if task["difficulty"] == "hard"), tasks[0])
|
| 121 |
|
| 122 |
+
chosen_task_id = chosen_task.get("id", chosen_task["task_id"])
|
| 123 |
+
reset_response = env_client.post("/reset", json={"task_id": chosen_task_id})
|
| 124 |
reset_response.raise_for_status()
|
| 125 |
reset_payload = reset_response.json()
|
| 126 |
session_id = reset_payload["session_id"]
|
|
|
|
| 128 |
|
| 129 |
messages: list[dict[str, str]] = [
|
| 130 |
{"role": "system", "content": SYSTEM_PROMPT},
|
| 131 |
+
{
|
| 132 |
+
"role": "user",
|
| 133 |
+
"content": (
|
| 134 |
+
f"Task: {observation['task_name']}\n"
|
| 135 |
+
f"Description: {observation['task_description']}\n"
|
| 136 |
+
f"Dataset:\n{observation['dataset_preview']}"
|
| 137 |
+
),
|
| 138 |
+
},
|
| 139 |
]
|
| 140 |
|
| 141 |
+
print(f"Selected task: {chosen_task_id}")
|
| 142 |
|
| 143 |
attempt_number = 0
|
| 144 |
while not observation["done"] and observation["attempts_remaining"] > 0:
|
|
|
|
| 154 |
response_text = completion.choices[0].message.content or ""
|
| 155 |
action = parse_model_action(response_text)
|
| 156 |
except Exception as exc: # noqa: BLE001
|
| 157 |
+
print(f"Model request failed ({exc}). Falling back to heuristic action.")
|
| 158 |
response_text = ""
|
| 159 |
+
action = fallback_action(chosen_task_id, observation["step"])
|
| 160 |
|
| 161 |
step_response = env_client.post(
|
| 162 |
"/step",
|
|
|
|
| 185 |
messages.append(
|
| 186 |
{
|
| 187 |
"role": "user",
|
| 188 |
+
"content": (
|
| 189 |
+
f"Feedback: {observation['feedback']}\n"
|
| 190 |
+
f"Issues remaining: {observation['issues_remaining']}\n\n"
|
| 191 |
+
"Revise your next action."
|
| 192 |
+
),
|
| 193 |
}
|
| 194 |
)
|
| 195 |
|
|
|
|
| 200 |
grader_response = env_client.post(
|
| 201 |
"/grader",
|
| 202 |
params={"session_id": session_id},
|
| 203 |
+
json={"task_id": chosen_task_id, "episode": state_payload["episode_history"]},
|
|
|
|
|
|
|
|
|
|
| 204 |
)
|
| 205 |
grader_response.raise_for_status()
|
| 206 |
grader_payload = grader_response.json()
|
openenv.yaml
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
name:
|
| 2 |
version: 1.0.0
|
| 3 |
-
description:
|
| 4 |
-
author:
|
| 5 |
tags:
|
| 6 |
- openenv
|
| 7 |
-
-
|
| 8 |
- rl-environment
|
|
|
|
| 9 |
entrypoint: app:app
|
| 10 |
port: 7860
|
| 11 |
endpoints:
|
|
@@ -18,15 +19,23 @@ endpoints:
|
|
| 18 |
grader: /grader
|
| 19 |
baseline: /baseline
|
| 20 |
tasks:
|
| 21 |
-
- id:
|
| 22 |
-
name:
|
| 23 |
difficulty: easy
|
| 24 |
-
max_steps:
|
| 25 |
-
- id:
|
| 26 |
-
name:
|
| 27 |
difficulty: medium
|
| 28 |
-
max_steps:
|
| 29 |
-
- id:
|
| 30 |
-
name:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
difficulty: hard
|
| 32 |
-
max_steps:
|
|
|
|
| 1 |
+
name: data-cleaning-env
|
| 2 |
version: 1.0.0
|
| 3 |
+
description: Data cleaning OpenEnv environment for reinforcement learning and agent evaluation.
|
| 4 |
+
author: Ariyan Bhakat
|
| 5 |
tags:
|
| 6 |
- openenv
|
| 7 |
+
- data-cleaning
|
| 8 |
- rl-environment
|
| 9 |
+
- tabular-data
|
| 10 |
entrypoint: app:app
|
| 11 |
port: 7860
|
| 12 |
endpoints:
|
|
|
|
| 19 |
grader: /grader
|
| 20 |
baseline: /baseline
|
| 21 |
tasks:
|
| 22 |
+
- id: null_filling
|
| 23 |
+
name: Missing Value Repair
|
| 24 |
difficulty: easy
|
| 25 |
+
max_steps: 5
|
| 26 |
+
- id: format_standardization
|
| 27 |
+
name: Date and Currency Standardization
|
| 28 |
difficulty: medium
|
| 29 |
+
max_steps: 8
|
| 30 |
+
- id: duplicate_outlier
|
| 31 |
+
name: Duplicate and Outlier Removal
|
| 32 |
+
difficulty: medium
|
| 33 |
+
max_steps: 8
|
| 34 |
+
- id: multi_layer_pipeline
|
| 35 |
+
name: Multi-Layer Order Data Pipeline
|
| 36 |
+
difficulty: hard
|
| 37 |
+
max_steps: 12
|
| 38 |
+
- id: adversarial_sensor
|
| 39 |
+
name: Adversarial Sensor Data
|
| 40 |
difficulty: hard
|
| 41 |
+
max_steps: 8
|
scripts/validate.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Pre-submission validation for the
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
@@ -26,9 +26,9 @@ def validate_manifest() -> None:
|
|
| 26 |
manifest_path = ROOT / "openenv.yaml"
|
| 27 |
_check(manifest_path.exists(), "openenv.yaml exists")
|
| 28 |
manifest_text = manifest_path.read_text()
|
| 29 |
-
_check("name:
|
| 30 |
_check("tags:" in manifest_text and "openenv" in manifest_text, "manifest includes openenv tag")
|
| 31 |
-
_check("tasks:" in manifest_text and manifest_text.count("- id:") >=
|
| 32 |
|
| 33 |
|
| 34 |
def validate_inference_script() -> None:
|
|
@@ -56,22 +56,26 @@ def validate_graders() -> None:
|
|
| 56 |
_check(0.0 <= score <= 1.0, f"{task_id} grader returns a valid score on empty history")
|
| 57 |
|
| 58 |
score_levels = {
|
| 59 |
-
grade_episode("
|
| 60 |
grade_episode(
|
| 61 |
-
"
|
| 62 |
-
[{"action": {"
|
| 63 |
),
|
| 64 |
grade_episode(
|
| 65 |
-
"
|
| 66 |
-
[
|
|
|
|
|
|
|
|
|
|
| 67 |
),
|
| 68 |
grade_episode(
|
| 69 |
-
"
|
| 70 |
-
[
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
| 75 |
),
|
| 76 |
}
|
| 77 |
_check(len(score_levels) >= 4, "grader exposes multiple distinct score levels")
|
|
@@ -86,6 +90,7 @@ def validate_api() -> None:
|
|
| 86 |
tasks = client.get("/tasks")
|
| 87 |
_check(tasks.status_code == 200, "GET /tasks succeeds")
|
| 88 |
_check(isinstance(tasks.json(), list), "GET /tasks returns a bare array")
|
|
|
|
| 89 |
_check(all("answer" not in task for task in tasks.json()), "GET /tasks does not leak answers")
|
| 90 |
|
| 91 |
reset = client.post("/reset")
|
|
@@ -95,12 +100,14 @@ def validate_api() -> None:
|
|
| 95 |
step = client.post(
|
| 96 |
f"/step?session_id={session_id}",
|
| 97 |
json={
|
| 98 |
-
"
|
| 99 |
-
"
|
| 100 |
-
"
|
|
|
|
|
|
|
| 101 |
},
|
| 102 |
)
|
| 103 |
-
_check(step.status_code == 200, "POST /step succeeds with raw
|
| 104 |
|
| 105 |
state = client.get(f"/state?session_id={session_id}")
|
| 106 |
_check(state.status_code == 200, "GET /state succeeds")
|
|
@@ -118,7 +125,7 @@ def validate_api() -> None:
|
|
| 118 |
tasks_message = websocket.receive_json()
|
| 119 |
_check(tasks_message["type"] == "tasks", "WS /ws tasks message succeeds")
|
| 120 |
|
| 121 |
-
websocket.send_json({"type": "reset", "payload": {"task_id": "
|
| 122 |
reset_message = websocket.receive_json()
|
| 123 |
_check(reset_message["type"] == "reset", "WS /ws reset succeeds")
|
| 124 |
|
|
@@ -126,9 +133,11 @@ def validate_api() -> None:
|
|
| 126 |
{
|
| 127 |
"type": "step",
|
| 128 |
"payload": {
|
| 129 |
-
"
|
| 130 |
-
"
|
| 131 |
-
"
|
|
|
|
|
|
|
| 132 |
},
|
| 133 |
}
|
| 134 |
)
|
|
@@ -138,7 +147,7 @@ def validate_api() -> None:
|
|
| 138 |
|
| 139 |
def validate_baseline() -> None:
|
| 140 |
agent = BaselineAgent(env=OpenEnv(), use_llm=False)
|
| 141 |
-
results = agent.run(task_ids=["
|
| 142 |
_check(results["summary"]["total_episodes"] == 1, "baseline smoke test completes")
|
| 143 |
|
| 144 |
|
|
|
|
| 1 |
+
"""Pre-submission validation for the data-cleaning environment."""
|
| 2 |
|
| 3 |
from __future__ import annotations
|
| 4 |
|
|
|
|
| 26 |
manifest_path = ROOT / "openenv.yaml"
|
| 27 |
_check(manifest_path.exists(), "openenv.yaml exists")
|
| 28 |
manifest_text = manifest_path.read_text()
|
| 29 |
+
_check("name: data-cleaning-env" in manifest_text, "manifest name is correct")
|
| 30 |
_check("tags:" in manifest_text and "openenv" in manifest_text, "manifest includes openenv tag")
|
| 31 |
+
_check("tasks:" in manifest_text and manifest_text.count("- id:") >= 5, "manifest lists the data-cleaning benchmark")
|
| 32 |
|
| 33 |
|
| 34 |
def validate_inference_script() -> None:
|
|
|
|
| 56 |
_check(0.0 <= score <= 1.0, f"{task_id} grader returns a valid score on empty history")
|
| 57 |
|
| 58 |
score_levels = {
|
| 59 |
+
grade_episode("duplicate_outlier", []),
|
| 60 |
grade_episode(
|
| 61 |
+
"duplicate_outlier",
|
| 62 |
+
[{"action": {"action_type": "drop_row", "row_index": 1, "column": "row_id", "new_value": None, "reason": "duplicate"}}],
|
| 63 |
),
|
| 64 |
grade_episode(
|
| 65 |
+
"duplicate_outlier",
|
| 66 |
+
[
|
| 67 |
+
{"action": {"action_type": "drop_row", "row_index": 1, "column": "row_id", "new_value": None, "reason": "duplicate"}},
|
| 68 |
+
{"action": {"action_type": "flag_anomaly", "row_index": 2, "column": "amount", "new_value": None, "reason": "outlier"}},
|
| 69 |
+
],
|
| 70 |
),
|
| 71 |
grade_episode(
|
| 72 |
+
"duplicate_outlier",
|
| 73 |
+
[
|
| 74 |
+
{"action": {"action_type": "drop_row", "row_index": 1, "column": "row_id", "new_value": None, "reason": "duplicate"}},
|
| 75 |
+
{"action": {"action_type": "flag_anomaly", "row_index": 2, "column": "amount", "new_value": None, "reason": "outlier"}},
|
| 76 |
+
{"action": {"action_type": "fix_value", "row_index": 3, "column": "amount", "new_value": 50.0, "reason": "negative amount"}},
|
| 77 |
+
{"action": {"action_type": "standardize_format", "row_index": 5, "column": "status", "new_value": "completed", "reason": "normalize case"}},
|
| 78 |
+
],
|
| 79 |
),
|
| 80 |
}
|
| 81 |
_check(len(score_levels) >= 4, "grader exposes multiple distinct score levels")
|
|
|
|
| 90 |
tasks = client.get("/tasks")
|
| 91 |
_check(tasks.status_code == 200, "GET /tasks succeeds")
|
| 92 |
_check(isinstance(tasks.json(), list), "GET /tasks returns a bare array")
|
| 93 |
+
_check(len(tasks.json()) >= 5, "GET /tasks exposes the data-cleaning benchmark")
|
| 94 |
_check(all("answer" not in task for task in tasks.json()), "GET /tasks does not leak answers")
|
| 95 |
|
| 96 |
reset = client.post("/reset")
|
|
|
|
| 100 |
step = client.post(
|
| 101 |
f"/step?session_id={session_id}",
|
| 102 |
json={
|
| 103 |
+
"action_type": "flag_anomaly",
|
| 104 |
+
"row_index": 0,
|
| 105 |
+
"column": "reading",
|
| 106 |
+
"new_value": None,
|
| 107 |
+
"reason": "This looks suspicious.",
|
| 108 |
},
|
| 109 |
)
|
| 110 |
+
_check(step.status_code == 200, "POST /step succeeds with raw data-cleaning action JSON")
|
| 111 |
|
| 112 |
state = client.get(f"/state?session_id={session_id}")
|
| 113 |
_check(state.status_code == 200, "GET /state succeeds")
|
|
|
|
| 125 |
tasks_message = websocket.receive_json()
|
| 126 |
_check(tasks_message["type"] == "tasks", "WS /ws tasks message succeeds")
|
| 127 |
|
| 128 |
+
websocket.send_json({"type": "reset", "payload": {"task_id": "null_filling"}})
|
| 129 |
reset_message = websocket.receive_json()
|
| 130 |
_check(reset_message["type"] == "reset", "WS /ws reset succeeds")
|
| 131 |
|
|
|
|
| 133 |
{
|
| 134 |
"type": "step",
|
| 135 |
"payload": {
|
| 136 |
+
"action_type": "fill_missing",
|
| 137 |
+
"row_index": 1,
|
| 138 |
+
"column": "age",
|
| 139 |
+
"new_value": "unknown",
|
| 140 |
+
"reason": "age is missing",
|
| 141 |
},
|
| 142 |
}
|
| 143 |
)
|
|
|
|
| 147 |
|
| 148 |
def validate_baseline() -> None:
|
| 149 |
agent = BaselineAgent(env=OpenEnv(), use_llm=False)
|
| 150 |
+
results = agent.run(task_ids=["null_filling"], max_episodes_per_task=1)
|
| 151 |
_check(results["summary"]["total_episodes"] == 1, "baseline smoke test completes")
|
| 152 |
|
| 153 |
|
tests/test_api.py
CHANGED
|
@@ -2,6 +2,8 @@
|
|
| 2 |
|
| 3 |
import pytest
|
| 4 |
|
|
|
|
|
|
|
| 5 |
|
| 6 |
def test_health_endpoint(test_client) -> None:
|
| 7 |
response = test_client.get("/health")
|
|
@@ -16,8 +18,9 @@ def test_tasks_endpoint_lists_all_tasks_without_answers(test_client) -> None:
|
|
| 16 |
assert response.status_code == 200
|
| 17 |
payload = response.json()
|
| 18 |
assert isinstance(payload, list)
|
| 19 |
-
assert len(payload) ==
|
| 20 |
-
assert payload
|
|
|
|
| 21 |
assert "answer" not in payload[0]
|
| 22 |
|
| 23 |
|
|
@@ -26,8 +29,8 @@ def test_reset_endpoint_returns_observation_and_supports_empty_body(test_client)
|
|
| 26 |
assert response.status_code == 200
|
| 27 |
payload = response.json()
|
| 28 |
assert "session_id" in payload
|
| 29 |
-
assert payload["observation"]["task_id"] in
|
| 30 |
-
assert "
|
| 31 |
assert payload["observation"]["done"] is False
|
| 32 |
|
| 33 |
|
|
@@ -37,21 +40,24 @@ def test_reset_endpoint_rejects_invalid_task(test_client) -> None:
|
|
| 37 |
|
| 38 |
|
| 39 |
def test_step_and_state_endpoints_work_together(test_client) -> None:
|
| 40 |
-
reset = test_client.post("/reset", json={"task_id": "
|
| 41 |
session_id = reset.json()["session_id"]
|
| 42 |
step = test_client.post(
|
| 43 |
f"/step?session_id={session_id}",
|
| 44 |
json={
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
-
"
|
|
|
|
|
|
|
| 48 |
},
|
| 49 |
)
|
| 50 |
state = test_client.get(f"/state?session_id={session_id}")
|
| 51 |
|
| 52 |
assert step.status_code == 200
|
| 53 |
-
assert step.json()["reward"]["value"] >
|
| 54 |
-
assert step.json()["observation"]["done"] is
|
|
|
|
| 55 |
assert state.status_code == 200
|
| 56 |
assert state.json()["step_count"] == 1
|
| 57 |
|
|
@@ -62,21 +68,23 @@ def test_state_endpoint_requires_active_episode(test_client) -> None:
|
|
| 62 |
|
| 63 |
|
| 64 |
def test_grader_endpoint_scores_episode_history(test_client) -> None:
|
| 65 |
-
reset = test_client.post("/reset", json={"task_id": "
|
| 66 |
session_id = reset.json()["session_id"]
|
| 67 |
test_client.post(
|
| 68 |
f"/step?session_id={session_id}",
|
| 69 |
json={
|
| 70 |
-
"
|
| 71 |
-
"
|
| 72 |
-
"
|
|
|
|
|
|
|
| 73 |
},
|
| 74 |
)
|
| 75 |
history = test_client.get(f"/state?session_id={session_id}").json()["episode_history"]
|
| 76 |
|
| 77 |
response = test_client.post(
|
| 78 |
f"/grader?session_id={session_id}",
|
| 79 |
-
json={"task_id": "
|
| 80 |
)
|
| 81 |
|
| 82 |
assert response.status_code == 200
|
|
@@ -88,28 +96,30 @@ def test_grader_endpoint_scores_episode_history(test_client) -> None:
|
|
| 88 |
def test_baseline_endpoint_runs_smoke_test(test_client) -> None:
|
| 89 |
response = test_client.post(
|
| 90 |
"/baseline",
|
| 91 |
-
json={"task_ids": ["
|
| 92 |
)
|
| 93 |
assert response.status_code == 200
|
| 94 |
payload = response.json()
|
| 95 |
assert payload["summary"]["total_episodes"] == 1
|
| 96 |
-
assert payload["results"][0]["task_id"] == "
|
| 97 |
|
| 98 |
|
| 99 |
def test_websocket_supports_reset_step_and_state(test_client) -> None:
|
| 100 |
with test_client.websocket_connect("/ws") as websocket:
|
| 101 |
-
websocket.send_json({"type": "reset", "payload": {"task_id": "
|
| 102 |
reset_message = websocket.receive_json()
|
| 103 |
assert reset_message["type"] == "reset"
|
| 104 |
-
assert reset_message["observation"]["task_id"] == "
|
| 105 |
|
| 106 |
websocket.send_json(
|
| 107 |
{
|
| 108 |
"type": "step",
|
| 109 |
"payload": {
|
| 110 |
-
"
|
| 111 |
-
"
|
| 112 |
-
"
|
|
|
|
|
|
|
| 113 |
},
|
| 114 |
}
|
| 115 |
)
|
|
|
|
| 2 |
|
| 3 |
import pytest
|
| 4 |
|
| 5 |
+
from environment.tasks import TASKS
|
| 6 |
+
|
| 7 |
|
| 8 |
def test_health_endpoint(test_client) -> None:
|
| 9 |
response = test_client.get("/health")
|
|
|
|
| 18 |
assert response.status_code == 200
|
| 19 |
payload = response.json()
|
| 20 |
assert isinstance(payload, list)
|
| 21 |
+
assert len(payload) == len(TASKS)
|
| 22 |
+
assert len(payload) >= 5
|
| 23 |
+
assert payload[0]["action_schema"]["required"] == ["action_type", "column", "reason"]
|
| 24 |
assert "answer" not in payload[0]
|
| 25 |
|
| 26 |
|
|
|
|
| 29 |
assert response.status_code == 200
|
| 30 |
payload = response.json()
|
| 31 |
assert "session_id" in payload
|
| 32 |
+
assert payload["observation"]["task_id"] in TASKS
|
| 33 |
+
assert "dataset_preview" in payload["observation"]
|
| 34 |
assert payload["observation"]["done"] is False
|
| 35 |
|
| 36 |
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def test_step_and_state_endpoints_work_together(test_client) -> None:
|
| 43 |
+
reset = test_client.post("/reset", json={"task_id": "null_filling"})
|
| 44 |
session_id = reset.json()["session_id"]
|
| 45 |
step = test_client.post(
|
| 46 |
f"/step?session_id={session_id}",
|
| 47 |
json={
|
| 48 |
+
"action_type": "fill_missing",
|
| 49 |
+
"row_index": 1,
|
| 50 |
+
"column": "age",
|
| 51 |
+
"new_value": "unknown",
|
| 52 |
+
"reason": "Row 1 age is missing.",
|
| 53 |
},
|
| 54 |
)
|
| 55 |
state = test_client.get(f"/state?session_id={session_id}")
|
| 56 |
|
| 57 |
assert step.status_code == 200
|
| 58 |
+
assert step.json()["reward"]["value"] > 0.0
|
| 59 |
+
assert step.json()["observation"]["done"] is False
|
| 60 |
+
assert step.json()["observation"]["issues_remaining"] == 2
|
| 61 |
assert state.status_code == 200
|
| 62 |
assert state.json()["step_count"] == 1
|
| 63 |
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
def test_grader_endpoint_scores_episode_history(test_client) -> None:
|
| 71 |
+
reset = test_client.post("/reset", json={"task_id": "adversarial_sensor"})
|
| 72 |
session_id = reset.json()["session_id"]
|
| 73 |
test_client.post(
|
| 74 |
f"/step?session_id={session_id}",
|
| 75 |
json={
|
| 76 |
+
"action_type": "fill_missing",
|
| 77 |
+
"row_index": 2,
|
| 78 |
+
"column": "reading",
|
| 79 |
+
"new_value": None,
|
| 80 |
+
"reason": "The reading is missing.",
|
| 81 |
},
|
| 82 |
)
|
| 83 |
history = test_client.get(f"/state?session_id={session_id}").json()["episode_history"]
|
| 84 |
|
| 85 |
response = test_client.post(
|
| 86 |
f"/grader?session_id={session_id}",
|
| 87 |
+
json={"task_id": "adversarial_sensor", "episode": history},
|
| 88 |
)
|
| 89 |
|
| 90 |
assert response.status_code == 200
|
|
|
|
| 96 |
def test_baseline_endpoint_runs_smoke_test(test_client) -> None:
|
| 97 |
response = test_client.post(
|
| 98 |
"/baseline",
|
| 99 |
+
json={"task_ids": ["null_filling"], "max_episodes_per_task": 1, "verbose": False},
|
| 100 |
)
|
| 101 |
assert response.status_code == 200
|
| 102 |
payload = response.json()
|
| 103 |
assert payload["summary"]["total_episodes"] == 1
|
| 104 |
+
assert payload["results"][0]["task_id"] == "null_filling"
|
| 105 |
|
| 106 |
|
| 107 |
def test_websocket_supports_reset_step_and_state(test_client) -> None:
|
| 108 |
with test_client.websocket_connect("/ws") as websocket:
|
| 109 |
+
websocket.send_json({"type": "reset", "payload": {"task_id": "null_filling"}})
|
| 110 |
reset_message = websocket.receive_json()
|
| 111 |
assert reset_message["type"] == "reset"
|
| 112 |
+
assert reset_message["observation"]["task_id"] == "null_filling"
|
| 113 |
|
| 114 |
websocket.send_json(
|
| 115 |
{
|
| 116 |
"type": "step",
|
| 117 |
"payload": {
|
| 118 |
+
"action_type": "fill_missing",
|
| 119 |
+
"row_index": 1,
|
| 120 |
+
"column": "age",
|
| 121 |
+
"new_value": "unknown",
|
| 122 |
+
"reason": "The age value is missing.",
|
| 123 |
},
|
| 124 |
}
|
| 125 |
)
|
tests/test_env.py
CHANGED
|
@@ -3,31 +3,35 @@
|
|
| 3 |
import pytest
|
| 4 |
|
| 5 |
from environment import Action, Observation
|
|
|
|
| 6 |
|
| 7 |
|
| 8 |
def test_reset_returns_valid_observation(sample_env) -> None:
|
| 9 |
-
observation = sample_env.reset("
|
| 10 |
assert isinstance(observation, Observation)
|
| 11 |
-
assert observation.task_id == "
|
| 12 |
assert observation.step == 0
|
| 13 |
-
assert observation.attempts_remaining ==
|
| 14 |
|
| 15 |
|
| 16 |
def test_step_advances_state_and_returns_reward(sample_env) -> None:
|
| 17 |
-
sample_env.reset("
|
| 18 |
action = Action(
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
| 22 |
)
|
| 23 |
observation, reward, done, info = sample_env.step(action)
|
| 24 |
state = sample_env.state()
|
| 25 |
|
| 26 |
assert state["step_count"] == 1
|
| 27 |
-
assert reward.value >
|
| 28 |
-
assert done is
|
| 29 |
-
assert info["solved"] is
|
| 30 |
assert observation.step == 1
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
def test_state_requires_active_episode(sample_env) -> None:
|
|
@@ -36,43 +40,58 @@ def test_state_requires_active_episode(sample_env) -> None:
|
|
| 36 |
|
| 37 |
|
| 38 |
def test_done_episode_requires_reset(sample_env) -> None:
|
| 39 |
-
sample_env.reset("
|
| 40 |
sample_env.step(
|
| 41 |
Action(
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
)
|
| 46 |
)
|
| 47 |
|
| 48 |
with pytest.raises(RuntimeError):
|
| 49 |
sample_env.step(
|
| 50 |
Action(
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
| 54 |
)
|
| 55 |
)
|
| 56 |
|
| 57 |
|
| 58 |
def test_reset_without_task_id_picks_a_registered_task(sample_env) -> None:
|
| 59 |
observation = sample_env.reset(seed=7)
|
| 60 |
-
assert observation.task_id in
|
| 61 |
|
| 62 |
|
| 63 |
def test_episode_terminates_after_three_attempts(sample_env) -> None:
|
| 64 |
-
observation = sample_env.reset("
|
| 65 |
done = False
|
| 66 |
while not done:
|
| 67 |
observation, reward, done, info = sample_env.step(
|
| 68 |
Action(
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
| 72 |
)
|
| 73 |
)
|
| 74 |
|
| 75 |
state = sample_env.state()
|
| 76 |
assert state["done"] is True
|
| 77 |
-
assert state["step_count"] ==
|
| 78 |
assert state["attempts_remaining"] == 0
|
|
|
|
| 3 |
import pytest
|
| 4 |
|
| 5 |
from environment import Action, Observation
|
| 6 |
+
from environment.tasks import TASKS
|
| 7 |
|
| 8 |
|
| 9 |
def test_reset_returns_valid_observation(sample_env) -> None:
|
| 10 |
+
observation = sample_env.reset("null_filling")
|
| 11 |
assert isinstance(observation, Observation)
|
| 12 |
+
assert observation.task_id == "null_filling"
|
| 13 |
assert observation.step == 0
|
| 14 |
+
assert observation.attempts_remaining == 5
|
| 15 |
|
| 16 |
|
| 17 |
def test_step_advances_state_and_returns_reward(sample_env) -> None:
|
| 18 |
+
sample_env.reset("null_filling")
|
| 19 |
action = Action(
|
| 20 |
+
action_type="fill_missing",
|
| 21 |
+
row_index=1,
|
| 22 |
+
column="age",
|
| 23 |
+
new_value="unknown",
|
| 24 |
+
reason="The age value is missing.",
|
| 25 |
)
|
| 26 |
observation, reward, done, info = sample_env.step(action)
|
| 27 |
state = sample_env.state()
|
| 28 |
|
| 29 |
assert state["step_count"] == 1
|
| 30 |
+
assert reward.value > 0.0
|
| 31 |
+
assert done is False
|
| 32 |
+
assert info["solved"] is False
|
| 33 |
assert observation.step == 1
|
| 34 |
+
assert observation.issues_remaining == 2
|
| 35 |
|
| 36 |
|
| 37 |
def test_state_requires_active_episode(sample_env) -> None:
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
def test_done_episode_requires_reset(sample_env) -> None:
|
| 43 |
+
sample_env.reset("adversarial_sensor")
|
| 44 |
sample_env.step(
|
| 45 |
Action(
|
| 46 |
+
action_type="fill_missing",
|
| 47 |
+
row_index=2,
|
| 48 |
+
column="reading",
|
| 49 |
+
new_value=None,
|
| 50 |
+
reason="The reading is missing.",
|
| 51 |
+
)
|
| 52 |
+
)
|
| 53 |
+
sample_env.step(
|
| 54 |
+
Action(
|
| 55 |
+
action_type="flag_anomaly",
|
| 56 |
+
row_index=5,
|
| 57 |
+
column="reading",
|
| 58 |
+
new_value=None,
|
| 59 |
+
reason="999C is an impossible outlier.",
|
| 60 |
)
|
| 61 |
)
|
| 62 |
|
| 63 |
with pytest.raises(RuntimeError):
|
| 64 |
sample_env.step(
|
| 65 |
Action(
|
| 66 |
+
action_type="flag_anomaly",
|
| 67 |
+
row_index=0,
|
| 68 |
+
column="reading",
|
| 69 |
+
new_value=None,
|
| 70 |
+
reason="Trying again after the episode ended.",
|
| 71 |
)
|
| 72 |
)
|
| 73 |
|
| 74 |
|
| 75 |
def test_reset_without_task_id_picks_a_registered_task(sample_env) -> None:
|
| 76 |
observation = sample_env.reset(seed=7)
|
| 77 |
+
assert observation.task_id in TASKS
|
| 78 |
|
| 79 |
|
| 80 |
def test_episode_terminates_after_three_attempts(sample_env) -> None:
|
| 81 |
+
observation = sample_env.reset("null_filling")
|
| 82 |
done = False
|
| 83 |
while not done:
|
| 84 |
observation, reward, done, info = sample_env.step(
|
| 85 |
Action(
|
| 86 |
+
action_type="flag_anomaly",
|
| 87 |
+
row_index=0,
|
| 88 |
+
column="name",
|
| 89 |
+
new_value=None,
|
| 90 |
+
reason="This is not a real issue.",
|
| 91 |
)
|
| 92 |
)
|
| 93 |
|
| 94 |
state = sample_env.state()
|
| 95 |
assert state["done"] is True
|
| 96 |
+
assert state["step_count"] == 5
|
| 97 |
assert state["attempts_remaining"] == 0
|
tests/test_graders.py
CHANGED
|
@@ -4,12 +4,32 @@ from environment import Action, grade_episode
|
|
| 4 |
|
| 5 |
|
| 6 |
def _play_perfect_runtime_episode(env) -> list[dict]:
|
| 7 |
-
env.reset("
|
| 8 |
env.step(
|
| 9 |
Action(
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
)
|
| 14 |
)
|
| 15 |
return env.state()["episode_history"]
|
|
@@ -24,43 +44,83 @@ def test_all_graders_return_values_in_range(mock_tasks) -> None:
|
|
| 24 |
|
| 25 |
def test_perfect_episode_scores_one(sample_env) -> None:
|
| 26 |
history = _play_perfect_runtime_episode(sample_env)
|
| 27 |
-
assert grade_episode("
|
| 28 |
|
| 29 |
|
| 30 |
def test_grader_is_deterministic(sample_env) -> None:
|
| 31 |
history = _play_perfect_runtime_episode(sample_env)
|
| 32 |
-
first = grade_episode("
|
| 33 |
-
second = grade_episode("
|
| 34 |
assert first == second
|
| 35 |
|
| 36 |
|
| 37 |
def test_grader_has_multiple_distinct_score_levels() -> None:
|
| 38 |
-
wrong = [{"action": {"
|
| 39 |
-
partial = [{"action": {"
|
| 40 |
stronger_partial = [
|
| 41 |
{
|
| 42 |
"action": {
|
| 43 |
-
"
|
| 44 |
-
"
|
| 45 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
}
|
| 47 |
-
}
|
| 48 |
]
|
| 49 |
perfect = [
|
| 50 |
{
|
| 51 |
"action": {
|
| 52 |
-
"
|
| 53 |
-
"
|
| 54 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
}
|
| 56 |
-
}
|
| 57 |
]
|
| 58 |
|
| 59 |
scores = {
|
| 60 |
-
grade_episode("
|
| 61 |
-
grade_episode("
|
| 62 |
-
grade_episode("
|
| 63 |
-
grade_episode("
|
| 64 |
}
|
| 65 |
|
| 66 |
assert len(scores) >= 4
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
def _play_perfect_runtime_episode(env) -> list[dict]:
|
| 7 |
+
env.reset("null_filling")
|
| 8 |
env.step(
|
| 9 |
Action(
|
| 10 |
+
action_type="fill_missing",
|
| 11 |
+
row_index=1,
|
| 12 |
+
column="age",
|
| 13 |
+
new_value="unknown",
|
| 14 |
+
reason="The age value is missing.",
|
| 15 |
+
)
|
| 16 |
+
)
|
| 17 |
+
env.step(
|
| 18 |
+
Action(
|
| 19 |
+
action_type="fix_value",
|
| 20 |
+
row_index=2,
|
| 21 |
+
column="age",
|
| 22 |
+
new_value="unknown",
|
| 23 |
+
reason="The literal NULL should be normalized.",
|
| 24 |
+
)
|
| 25 |
+
)
|
| 26 |
+
env.step(
|
| 27 |
+
Action(
|
| 28 |
+
action_type="fill_missing",
|
| 29 |
+
row_index=4,
|
| 30 |
+
column="email",
|
| 31 |
+
new_value="missing@example.com",
|
| 32 |
+
reason="The email value is missing.",
|
| 33 |
)
|
| 34 |
)
|
| 35 |
return env.state()["episode_history"]
|
|
|
|
| 44 |
|
| 45 |
def test_perfect_episode_scores_one(sample_env) -> None:
|
| 46 |
history = _play_perfect_runtime_episode(sample_env)
|
| 47 |
+
assert grade_episode("null_filling", history) == 1.0
|
| 48 |
|
| 49 |
|
| 50 |
def test_grader_is_deterministic(sample_env) -> None:
|
| 51 |
history = _play_perfect_runtime_episode(sample_env)
|
| 52 |
+
first = grade_episode("null_filling", history)
|
| 53 |
+
second = grade_episode("null_filling", history)
|
| 54 |
assert first == second
|
| 55 |
|
| 56 |
|
| 57 |
def test_grader_has_multiple_distinct_score_levels() -> None:
|
| 58 |
+
wrong = [{"action": {"action_type": "flag_anomaly", "row_index": 0, "column": "status", "new_value": None, "reason": "Totally wrong"}}]
|
| 59 |
+
partial = [{"action": {"action_type": "drop_row", "row_index": 1, "column": "row_id", "new_value": None, "reason": "Duplicate row"}}]
|
| 60 |
stronger_partial = [
|
| 61 |
{
|
| 62 |
"action": {
|
| 63 |
+
"action_type": "drop_row",
|
| 64 |
+
"row_index": 1,
|
| 65 |
+
"column": "row_id",
|
| 66 |
+
"new_value": None,
|
| 67 |
+
"reason": "Duplicate row",
|
| 68 |
+
}
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"action": {
|
| 72 |
+
"action_type": "flag_anomaly",
|
| 73 |
+
"row_index": 2,
|
| 74 |
+
"column": "amount",
|
| 75 |
+
"new_value": None,
|
| 76 |
+
"reason": "Extreme outlier",
|
| 77 |
}
|
| 78 |
+
},
|
| 79 |
]
|
| 80 |
perfect = [
|
| 81 |
{
|
| 82 |
"action": {
|
| 83 |
+
"action_type": "drop_row",
|
| 84 |
+
"row_index": 1,
|
| 85 |
+
"column": "row_id",
|
| 86 |
+
"new_value": None,
|
| 87 |
+
"reason": "Duplicate row",
|
| 88 |
+
}
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"action": {
|
| 92 |
+
"action_type": "flag_anomaly",
|
| 93 |
+
"row_index": 2,
|
| 94 |
+
"column": "amount",
|
| 95 |
+
"new_value": None,
|
| 96 |
+
"reason": "Extreme outlier",
|
| 97 |
+
}
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"action": {
|
| 101 |
+
"action_type": "fix_value",
|
| 102 |
+
"row_index": 3,
|
| 103 |
+
"column": "amount",
|
| 104 |
+
"new_value": 50.0,
|
| 105 |
+
"reason": "Negative amount must be non-negative",
|
| 106 |
+
}
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"action": {
|
| 110 |
+
"action_type": "standardize_format",
|
| 111 |
+
"row_index": 5,
|
| 112 |
+
"column": "status",
|
| 113 |
+
"new_value": "completed",
|
| 114 |
+
"reason": "Normalize status casing",
|
| 115 |
}
|
| 116 |
+
},
|
| 117 |
]
|
| 118 |
|
| 119 |
scores = {
|
| 120 |
+
grade_episode("duplicate_outlier", wrong),
|
| 121 |
+
grade_episode("duplicate_outlier", partial),
|
| 122 |
+
grade_episode("duplicate_outlier", stronger_partial),
|
| 123 |
+
grade_episode("duplicate_outlier", perfect),
|
| 124 |
}
|
| 125 |
|
| 126 |
assert len(scores) >= 4
|
tests/test_models.py
CHANGED
|
@@ -5,15 +5,16 @@ from environment.models import Action, Observation, Reward
|
|
| 5 |
|
| 6 |
def test_observation_serialization_round_trip() -> None:
|
| 7 |
observation = Observation(
|
| 8 |
-
task_id="
|
| 9 |
-
task_name="
|
| 10 |
-
task_description="
|
| 11 |
step=0,
|
| 12 |
-
max_steps=
|
| 13 |
-
available_actions=["
|
| 14 |
-
context="
|
| 15 |
-
|
| 16 |
-
|
|
|
|
| 17 |
feedback="",
|
| 18 |
feedback_history=[],
|
| 19 |
)
|
|
@@ -21,31 +22,33 @@ def test_observation_serialization_round_trip() -> None:
|
|
| 21 |
dumped = observation.model_dump(mode="json")
|
| 22 |
restored = Observation.model_validate(dumped)
|
| 23 |
|
| 24 |
-
assert restored.task_id == "
|
| 25 |
-
assert restored.attempts_remaining ==
|
| 26 |
-
assert restored.
|
| 27 |
|
| 28 |
|
| 29 |
-
def
|
| 30 |
action = Action(
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
)
|
| 35 |
-
assert action.
|
| 36 |
|
| 37 |
|
| 38 |
def test_action_from_llm_output_parses_json_block() -> None:
|
| 39 |
action = Action.from_llm_output(
|
| 40 |
-
'```json\n{"
|
| 41 |
)
|
| 42 |
-
assert action.
|
| 43 |
-
assert action.
|
| 44 |
|
| 45 |
|
| 46 |
-
def
|
| 47 |
-
reward = Reward(value=1.4,
|
| 48 |
|
| 49 |
assert reward.value == 1.0
|
| 50 |
-
assert reward.
|
| 51 |
assert reward.solved is True
|
|
|
|
| 5 |
|
| 6 |
def test_observation_serialization_round_trip() -> None:
|
| 7 |
observation = Observation(
|
| 8 |
+
task_id="null_filling",
|
| 9 |
+
task_name="Missing Value Repair",
|
| 10 |
+
task_description="Repair missing values in the contacts table.",
|
| 11 |
step=0,
|
| 12 |
+
max_steps=5,
|
| 13 |
+
available_actions=["fill_missing"],
|
| 14 |
+
context="Inspect the dataset preview.",
|
| 15 |
+
dataset_preview="row_id | name | age\n0 | Alice |",
|
| 16 |
+
issues_remaining=3,
|
| 17 |
+
attempts_remaining=5,
|
| 18 |
feedback="",
|
| 19 |
feedback_history=[],
|
| 20 |
)
|
|
|
|
| 22 |
dumped = observation.model_dump(mode="json")
|
| 23 |
restored = Observation.model_validate(dumped)
|
| 24 |
|
| 25 |
+
assert restored.task_id == "null_filling"
|
| 26 |
+
assert restored.attempts_remaining == 5
|
| 27 |
+
assert restored.dataset_preview.startswith("row_id")
|
| 28 |
|
| 29 |
|
| 30 |
+
def test_action_validation_normalizes_action_type() -> None:
|
| 31 |
action = Action(
|
| 32 |
+
action_type=" FIX_VALUE ",
|
| 33 |
+
row_index=2,
|
| 34 |
+
column="email",
|
| 35 |
+
new_value="user@example.com",
|
| 36 |
+
reason="Replace the missing email.",
|
| 37 |
)
|
| 38 |
+
assert action.action_type == "fix_value"
|
| 39 |
|
| 40 |
|
| 41 |
def test_action_from_llm_output_parses_json_block() -> None:
|
| 42 |
action = Action.from_llm_output(
|
| 43 |
+
'```json\n{"action_type":"fill_missing","row_index":2,"column":"email","new_value":"user@example.com","reason":"row 2 email is missing"}\n```'
|
| 44 |
)
|
| 45 |
+
assert action.action_type == "fill_missing"
|
| 46 |
+
assert action.row_index == 2
|
| 47 |
|
| 48 |
|
| 49 |
+
def test_reward_clamps_value_and_fields() -> None:
|
| 50 |
+
reward = Reward(value=1.4, issues_fixed_this_step=2, issues_remaining=0, solved=True, attempts_used=1)
|
| 51 |
|
| 52 |
assert reward.value == 1.0
|
| 53 |
+
assert reward.issues_fixed_this_step == 2
|
| 54 |
assert reward.solved is True
|