File size: 5,087 Bytes
2ce79be | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | """Replay Arena admission actions and reward oracles against a running server."""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
from urllib.request import urlopen
from websockets.sync.client import connect
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from sql_investigation.tasks import TASK_IDS, build_task
EXAMPLE_ACTIONS = [
{"op": "query", "sql": "SELECT 1 AS ready"},
{"op": "finish"},
]
def exchange(socket, message: dict) -> dict:
socket.send(json.dumps(message))
response = json.loads(socket.recv(timeout=15))
assert response.get("type") == "observation", response
data = response["data"]
assert isinstance(data["done"], bool), data
reward = data["reward"]
assert isinstance(reward, (int, float)) and not isinstance(reward, bool), data
assert 0 <= reward <= 1, data
assert isinstance(data["observation"], dict), data
return data
def websocket_url(base_url: str) -> str:
parsed = urlsplit(base_url)
if parsed.scheme not in {"http", "https"}:
raise ValueError("--url must use http:// or https://")
return urlunsplit(
(
"wss" if parsed.scheme == "https" else "ws",
parsed.netloc,
parsed.path.rstrip("/") + "/ws",
"",
"",
)
)
def run(base_url: str, output: Path) -> None:
base_url = base_url.rstrip("/")
output.parent.mkdir(parents=True, exist_ok=True)
with urlopen(f"{base_url}/schema", timeout=15) as response:
schema = json.load(response)
for field in ("action", "observation", "state"):
assert isinstance(schema.get(field), dict), f"Missing {field} schema"
submission_schema = {key: schema[key] for key in ("action", "observation")}
(output.parent / "schema.json").write_text(json.dumps(submission_schema, indent=2) + "\n")
report = {
"passed": False,
"url": base_url,
"seed": 42,
"example_actions": EXAMPLE_ACTIONS,
"episodes": [],
}
started = time.monotonic()
try:
for task_id in TASK_IDS:
task = build_task(task_id, 42)
try:
# Admission uses this identical sequence for every named task.
with connect(websocket_url(base_url), open_timeout=15, close_timeout=5) as socket:
reset = exchange(
socket,
{"type": "reset", "data": {"task_id": task_id, "seed": 42}},
)
assert not reset["done"], (task_id, reset)
assert task.oracle_sql not in json.dumps(reset), task_id
for action in EXAMPLE_ACTIONS:
example_result = exchange(socket, {"type": "step", "data": action})
assert example_result["done"], (task_id, example_result)
assert example_result["reward"] == 0.0, (task_id, example_result)
# A fresh session also proves that the actual solution gets 1.
with connect(websocket_url(base_url), open_timeout=15, close_timeout=5) as socket:
exchange(
socket,
{"type": "reset", "data": {"task_id": task_id, "seed": 42}},
)
oracle_result = exchange(
socket,
{
"type": "step",
"data": {"op": "submit", "sql": task.oracle_sql},
},
)
assert oracle_result["done"], (task_id, oracle_result)
assert oracle_result["reward"] == 1.0, (task_id, oracle_result)
report["episodes"].append(
{
"task_id": task_id,
"example": {
"steps": len(EXAMPLE_ACTIONS),
"done": example_result["done"],
"reward": example_result["reward"],
},
"oracle": {
"steps": 1,
"done": oracle_result["done"],
"reward": oracle_result["reward"],
},
}
)
finally:
task.connection.close()
report["passed"] = True
finally:
report["duration_s"] = round(time.monotonic() - started, 3)
output.write_text(json.dumps(report, indent=2) + "\n")
print(f"Passed example and oracle episodes for all {len(TASK_IDS)} tasks: {output}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default="http://127.0.0.1:8000")
parser.add_argument("--output", type=Path, default=Path("artifacts/episodes.json"))
args = parser.parse_args()
run(args.url, args.output)
|