Pranjal Parashar commited on
Commit
91aacc4
·
unverified ·
1 Parent(s): 56540cc

training better

Browse files
Files changed (6) hide show
  1. baseline.py +38 -8
  2. eval.py +54 -2
  3. plot_metrics.py +120 -0
  4. tasks.py +910 -175
  5. train_sft.py +12 -0
  6. training_utils.py +10 -0
baseline.py CHANGED
@@ -1109,20 +1109,38 @@ def fallback_action(task_name: str, observation: Any) -> dict[str, Any]:
1109
  return {"action_type": "submit_workspace", "parameters": {"summary": spec["summary"]}}
1110
 
1111
  if grader_family == "simulation":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1112
  read_order = [
1113
  "docs/runtime_contract.md",
1114
- "data/sales_orders.csv",
1115
  ]
1116
  for path in read_order:
1117
  if path in observation.known_files and path not in queried.get("read_file", {}):
1118
  return {"action_type": "read_file", "parameters": {"path": path}}
1119
- if "raw.sales_orders_csv" in observation.known_assets and "raw.sales_orders_csv" not in queried.get("inspect_schema", {}):
1120
- return {"action_type": "inspect_schema", "parameters": {"asset": "raw.sales_orders_csv"}}
1121
 
1122
  simulation_edits = [
1123
  (
1124
  "pipelines/report_job.yaml",
1125
- """name: customer_daily_report_job
 
 
1126
  storage_path: mock_s3/staged/sales_orders.csv
1127
  raw_table: raw_sales_orders
1128
  load_sql: sql/load_raw.sql
@@ -1130,10 +1148,13 @@ build_sql: sql/build_table.sql
1130
  report_sql: sql/report_view.sql
1131
  final_view: customer_daily_report
1132
  """,
 
1133
  ),
1134
  (
1135
  "sql/load_raw.sql",
1136
- """create or replace view staged_sales_orders as
 
 
1137
  select
1138
  order_id,
1139
  customer_id,
@@ -1142,10 +1163,13 @@ select
1142
  unit_price
1143
  from raw_sales_orders;
1144
  """,
 
1145
  ),
1146
  (
1147
  "sql/build_table.sql",
1148
- """create or replace table customer_summary as
 
 
1149
  select
1150
  customer_id,
1151
  order_date,
@@ -1154,10 +1178,13 @@ select
1154
  from staged_sales_orders
1155
  group by 1, 2;
1156
  """,
 
1157
  ),
1158
  (
1159
  "sql/report_view.sql",
1160
- """create or replace view customer_daily_report as
 
 
1161
  select
1162
  customer_id,
1163
  order_date,
@@ -1165,6 +1192,7 @@ select
1165
  gross_revenue_usd
1166
  from customer_summary;
1167
  """,
 
1168
  ),
1169
  ]
1170
 
@@ -1179,7 +1207,9 @@ from customer_summary;
1179
  return {
1180
  "action_type": "submit_workspace",
1181
  "parameters": {
1182
- "summary": "Built a DuckDB pipeline from sales_orders.csv and published customer_daily_report."
 
 
1183
  },
1184
  }
1185
 
 
1109
  return {"action_type": "submit_workspace", "parameters": {"summary": spec["summary"]}}
1110
 
1111
  if grader_family == "simulation":
1112
+ scenario = SCENARIO_REGISTRY.get(observation.scenario_id, {})
1113
+ simulation_target = scenario.get("simulation_target", {})
1114
+ reference_solution = scenario.get("llm_draft", {}).get("reference_solution", {})
1115
+ source_csv = simulation_target.get("source_csv", "data/sales_orders.csv")
1116
+ final_view_name = (
1117
+ simulation_target.get("expected_final_view", {}).get("name")
1118
+ or os.path.splitext(os.path.basename(source_csv))[0]
1119
+ )
1120
+ raw_asset = next(
1121
+ (
1122
+ asset
1123
+ for asset in observation.known_assets
1124
+ if asset.startswith("raw.")
1125
+ ),
1126
+ "raw.sales_orders_csv",
1127
+ )
1128
  read_order = [
1129
  "docs/runtime_contract.md",
1130
+ source_csv,
1131
  ]
1132
  for path in read_order:
1133
  if path in observation.known_files and path not in queried.get("read_file", {}):
1134
  return {"action_type": "read_file", "parameters": {"path": path}}
1135
+ if raw_asset in observation.known_assets and raw_asset not in queried.get("inspect_schema", {}):
1136
+ return {"action_type": "inspect_schema", "parameters": {"asset": raw_asset}}
1137
 
1138
  simulation_edits = [
1139
  (
1140
  "pipelines/report_job.yaml",
1141
+ reference_solution.get(
1142
+ "pipeline_yaml",
1143
+ """name: customer_daily_report_job
1144
  storage_path: mock_s3/staged/sales_orders.csv
1145
  raw_table: raw_sales_orders
1146
  load_sql: sql/load_raw.sql
 
1148
  report_sql: sql/report_view.sql
1149
  final_view: customer_daily_report
1150
  """,
1151
+ ),
1152
  ),
1153
  (
1154
  "sql/load_raw.sql",
1155
+ reference_solution.get(
1156
+ "load_sql",
1157
+ """create or replace view staged_sales_orders as
1158
  select
1159
  order_id,
1160
  customer_id,
 
1163
  unit_price
1164
  from raw_sales_orders;
1165
  """,
1166
+ ),
1167
  ),
1168
  (
1169
  "sql/build_table.sql",
1170
+ reference_solution.get(
1171
+ "build_sql",
1172
+ """create or replace table customer_summary as
1173
  select
1174
  customer_id,
1175
  order_date,
 
1178
  from staged_sales_orders
1179
  group by 1, 2;
1180
  """,
1181
+ ),
1182
  ),
1183
  (
1184
  "sql/report_view.sql",
1185
+ reference_solution.get(
1186
+ "report_sql",
1187
+ """create or replace view customer_daily_report as
1188
  select
1189
  customer_id,
1190
  order_date,
 
1192
  gross_revenue_usd
1193
  from customer_summary;
1194
  """,
1195
+ ),
1196
  ),
1197
  ]
1198
 
 
1207
  return {
1208
  "action_type": "submit_workspace",
1209
  "parameters": {
1210
+ "summary": (
1211
+ f"Built a DuckDB pipeline from {os.path.basename(source_csv)} and published {final_view_name}."
1212
+ )
1213
  },
1214
  }
1215
 
eval.py CHANGED
@@ -3,9 +3,12 @@
3
  from __future__ import annotations
4
 
5
  import argparse
 
 
6
  import logging
7
  import re
8
  import statistics
 
9
  from typing import Any
10
 
11
  try:
@@ -55,6 +58,8 @@ def parse_args() -> argparse.Namespace:
55
  parser.add_argument("--load-in-4bit", action="store_true", help="Use 4-bit quantized loading when supported")
56
  parser.add_argument("--max-seq-length", type=int, default=4096, help="Max sequence length for model loading")
57
  parser.add_argument("--debug-actions", action="store_true", help="Log raw completions and fallback actions")
 
 
58
  return parser.parse_args()
59
 
60
 
@@ -203,8 +208,11 @@ def run_policy(
203
  _clean_preview(raw_text),
204
  action,
205
  )
206
- if not action_is_valid(action, observation):
 
 
207
  fallback = fallback_action(sample.task_id, observation)
 
208
  if args.debug_actions:
209
  logger.info(
210
  "Eval fallback task=%s step=%s fallback=%s",
@@ -213,7 +221,14 @@ def run_policy(
213
  fallback,
214
  )
215
  action = fallback
216
- return {"action": action, "metadata": {"text": raw_text}}
 
 
 
 
 
 
 
217
 
218
  metrics = run_episode(
219
  base_url=args.env_url,
@@ -230,11 +245,46 @@ def run_policy(
230
  "score": metrics.score,
231
  "solved": metrics.solved,
232
  "steps": metrics.steps,
 
 
233
  }
234
  )
235
  return results
236
 
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  def print_table(rows: list[dict[str, Any]]) -> None:
239
  headers = ("policy", "avg_reward", "avg_score", "solved_rate", "avg_steps")
240
  line = "{:<10} {:>11} {:>10} {:>12} {:>10}"
@@ -277,6 +327,8 @@ def main() -> None:
277
  )
278
  tuned_results = run_policy(tuned_label, tuned_model, tuned_tokenizer, args)
279
  rows.append({"policy": tuned_label, **summarize(tuned_results)})
 
 
280
 
281
  print_table(rows)
282
 
 
3
  from __future__ import annotations
4
 
5
  import argparse
6
+ import csv
7
+ import json
8
  import logging
9
  import re
10
  import statistics
11
+ from pathlib import Path
12
  from typing import Any
13
 
14
  try:
 
58
  parser.add_argument("--load-in-4bit", action="store_true", help="Use 4-bit quantized loading when supported")
59
  parser.add_argument("--max-seq-length", type=int, default=4096, help="Max sequence length for model loading")
60
  parser.add_argument("--debug-actions", action="store_true", help="Log raw completions and fallback actions")
61
+ parser.add_argument("--disable-fallback", action="store_true", help="Evaluate the raw policy without fallback rescue")
62
+ parser.add_argument("--results-dir", default=None, help="Optional directory to write eval metrics and summaries")
63
  return parser.parse_args()
64
 
65
 
 
208
  _clean_preview(raw_text),
209
  action,
210
  )
211
+ model_action_valid = action_is_valid(action, observation)
212
+ used_fallback = False
213
+ if not model_action_valid and not args.disable_fallback:
214
  fallback = fallback_action(sample.task_id, observation)
215
+ used_fallback = True
216
  if args.debug_actions:
217
  logger.info(
218
  "Eval fallback task=%s step=%s fallback=%s",
 
221
  fallback,
222
  )
223
  action = fallback
224
+ return {
225
+ "action": action,
226
+ "metadata": {
227
+ "text": raw_text,
228
+ "used_fallback": used_fallback,
229
+ "model_action_valid": model_action_valid,
230
+ },
231
+ }
232
 
233
  metrics = run_episode(
234
  base_url=args.env_url,
 
245
  "score": metrics.score,
246
  "solved": metrics.solved,
247
  "steps": metrics.steps,
248
+ "fallback_steps": metrics.fallback_steps,
249
+ "valid_model_steps": metrics.valid_model_steps,
250
  }
251
  )
252
  return results
253
 
254
 
255
+ def write_results(results_dir: str | None, rows: list[dict[str, Any]]) -> None:
256
+ if not results_dir:
257
+ return
258
+ output_dir = Path(results_dir)
259
+ output_dir.mkdir(parents=True, exist_ok=True)
260
+
261
+ per_episode_path = output_dir / "eval_episode_metrics.csv"
262
+ summary_path = output_dir / "eval_summary.json"
263
+
264
+ if rows:
265
+ fieldnames = list(rows[0].keys())
266
+ with per_episode_path.open("w", newline="", encoding="utf-8") as handle:
267
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
268
+ writer.writeheader()
269
+ writer.writerows(rows)
270
+
271
+ summary_rows: list[dict[str, Any]] = []
272
+ grouped: dict[str, list[dict[str, Any]]] = {}
273
+ for row in rows:
274
+ grouped.setdefault(str(row["label"]), []).append(row)
275
+ for label, group in grouped.items():
276
+ aggregate = summarize(group)
277
+ aggregate["policy"] = label
278
+ aggregate["episodes"] = len(group)
279
+ aggregate["avg_fallback_steps"] = statistics.fmean(item["fallback_steps"] for item in group)
280
+ aggregate["avg_valid_model_steps"] = statistics.fmean(item["valid_model_steps"] for item in group)
281
+ summary_rows.append(aggregate)
282
+
283
+ summary_path.write_text(json.dumps(summary_rows, indent=2, ensure_ascii=False), encoding="utf-8")
284
+ logger.info("Wrote eval metrics to %s", per_episode_path)
285
+ logger.info("Wrote eval summary to %s", summary_path)
286
+
287
+
288
  def print_table(rows: list[dict[str, Any]]) -> None:
289
  headers = ("policy", "avg_reward", "avg_score", "solved_rate", "avg_steps")
290
  line = "{:<10} {:>11} {:>10} {:>12} {:>10}"
 
327
  )
328
  tuned_results = run_policy(tuned_label, tuned_model, tuned_tokenizer, args)
329
  rows.append({"policy": tuned_label, **summarize(tuned_results)})
330
+ base_results.extend(tuned_results)
331
+ write_results(args.results_dir, base_results)
332
 
333
  print_table(rows)
334
 
plot_metrics.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate judge-friendly plots for FlowOS training and evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+
9
+ def parse_args() -> argparse.Namespace:
10
+ parser = argparse.ArgumentParser(description="Plot FlowOS training and evaluation metrics")
11
+ parser.add_argument("--train-metrics", default=None, help="CSV from train_sft.py")
12
+ parser.add_argument("--eval-metrics", default=None, help="CSV from eval.py")
13
+ parser.add_argument("--output-dir", default="outputs/plots", help="Directory for PNG plots")
14
+ return parser.parse_args()
15
+
16
+
17
+ def plot_training_metrics(csv_path: Path, output_dir: Path) -> list[Path]:
18
+ import pandas as pd
19
+ import matplotlib.pyplot as plt
20
+
21
+ df = pd.read_csv(csv_path)
22
+ outputs: list[Path] = []
23
+
24
+ if "loss" in df.columns:
25
+ loss_df = df[df["loss"].notna()].copy()
26
+ if not loss_df.empty:
27
+ x_values = loss_df["step"] if "step" in loss_df.columns else loss_df.index
28
+ plt.figure(figsize=(8, 4))
29
+ plt.plot(x_values, loss_df["loss"], marker="o", linewidth=2)
30
+ plt.title("SFT Training Loss")
31
+ plt.xlabel("Training Step")
32
+ plt.ylabel("Loss")
33
+ plt.grid(True, alpha=0.3)
34
+ output = output_dir / "sft_training_loss.png"
35
+ plt.tight_layout()
36
+ plt.savefig(output, dpi=180)
37
+ plt.close()
38
+ outputs.append(output)
39
+
40
+ if "grad_norm" in df.columns:
41
+ grad_df = df[df["grad_norm"].notna()].copy()
42
+ if not grad_df.empty:
43
+ x_values = grad_df["step"] if "step" in grad_df.columns else grad_df.index
44
+ plt.figure(figsize=(8, 4))
45
+ plt.plot(x_values, grad_df["grad_norm"], marker="o", linewidth=2)
46
+ plt.title("SFT Gradient Norm")
47
+ plt.xlabel("Training Step")
48
+ plt.ylabel("Grad Norm")
49
+ plt.grid(True, alpha=0.3)
50
+ output = output_dir / "sft_grad_norm.png"
51
+ plt.tight_layout()
52
+ plt.savefig(output, dpi=180)
53
+ plt.close()
54
+ outputs.append(output)
55
+
56
+ return outputs
57
+
58
+
59
+ def plot_eval_metrics(csv_path: Path, output_dir: Path) -> list[Path]:
60
+ import pandas as pd
61
+ import matplotlib.pyplot as plt
62
+
63
+ df = pd.read_csv(csv_path)
64
+ outputs: list[Path] = []
65
+ if df.empty:
66
+ return outputs
67
+
68
+ grouped = df.groupby("label", as_index=False).agg(
69
+ avg_reward=("total_reward", "mean"),
70
+ avg_score=("score", "mean"),
71
+ solved_rate=("solved", "mean"),
72
+ avg_fallback_steps=("fallback_steps", "mean"),
73
+ avg_valid_model_steps=("valid_model_steps", "mean"),
74
+ )
75
+
76
+ for metric, title, filename, ylabel in [
77
+ ("avg_reward", "Average Reward by Policy", "eval_avg_reward.png", "Average Reward"),
78
+ ("avg_score", "Average Score by Policy", "eval_avg_score.png", "Average Score"),
79
+ ("solved_rate", "Solved Rate by Policy", "eval_solved_rate.png", "Solved Rate"),
80
+ ("avg_fallback_steps", "Fallback Steps by Policy", "eval_fallback_steps.png", "Average Fallback Steps"),
81
+ ("avg_valid_model_steps", "Valid Model Steps by Policy", "eval_valid_model_steps.png", "Average Valid Model Steps"),
82
+ ]:
83
+ plt.figure(figsize=(7, 4))
84
+ plt.bar(grouped["label"], grouped[metric])
85
+ plt.title(title)
86
+ plt.xlabel("Policy")
87
+ plt.ylabel(ylabel)
88
+ if metric == "solved_rate":
89
+ plt.ylim(0, 1)
90
+ plt.grid(True, axis="y", alpha=0.3)
91
+ output = output_dir / filename
92
+ plt.tight_layout()
93
+ plt.savefig(output, dpi=180)
94
+ plt.close()
95
+ outputs.append(output)
96
+
97
+ return outputs
98
+
99
+
100
+ def main() -> None:
101
+ args = parse_args()
102
+ output_dir = Path(args.output_dir)
103
+ output_dir.mkdir(parents=True, exist_ok=True)
104
+
105
+ outputs: list[Path] = []
106
+ if args.train_metrics:
107
+ outputs.extend(plot_training_metrics(Path(args.train_metrics), output_dir))
108
+ if args.eval_metrics:
109
+ outputs.extend(plot_eval_metrics(Path(args.eval_metrics), output_dir))
110
+
111
+ if outputs:
112
+ print("Generated plots:")
113
+ for output in outputs:
114
+ print(output)
115
+ else:
116
+ print("No plots generated. Provide --train-metrics and/or --eval-metrics.")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
tasks.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  from copy import deepcopy
 
6
 
7
 
8
  def repair_validator(
@@ -153,6 +154,239 @@ def workflow_scenario(
153
  }
154
 
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  TASK_DEFINITIONS: dict[str, dict] = {
157
  "repair_data_transform": {
158
  "id": "repair_data_transform",
@@ -310,7 +544,7 @@ TASK_DEFINITIONS: dict[str, dict] = {
310
  ],
311
  "submission_action": "submit_workspace",
312
  "grader_family": "simulation",
313
- "scenario_ids": ["SIM-001"],
314
  },
315
  }
316
 
@@ -2363,66 +2597,333 @@ required_columns:
2363
  ),
2364
  ],
2365
  "simulation_workflow": [
2366
- workflow_scenario(
2367
  scenario_id="SIM-001",
2368
  developer_request=(
2369
- "Create a report out of this CSV file. The workflow should stage the raw data, "
2370
- "load it into the warehouse, and publish a view the user can query."
2371
  ),
2372
  workspace_summary=(
2373
  "This experimental workspace simulates a tiny data platform. Generate the "
2374
  "pipeline YAML and SQL needed to stage the CSV into mock S3, load it into "
2375
  "DuckDB, build a customer summary table, and publish the final report view. "
2376
- "You share the workspace with two roles: Builder starts, Fixer repairs after runtime failures."
2377
  ),
2378
- known_files=[
2379
- "data/sales_orders.csv",
2380
- "docs/runtime_contract.md",
2381
- "templates/report_pipeline_template.yaml",
2382
- "schemas/raw_sales_orders.json",
2383
- ],
2384
- editable_targets=[
2385
- "pipelines/report_job.yaml",
2386
- "sql/load_raw.sql",
2387
- "sql/build_table.sql",
2388
- "sql/report_view.sql",
2389
- ],
2390
- known_assets=[
2391
- "raw.sales_orders_csv",
2392
- "mart.customer_daily_report",
2393
- ],
2394
- available_validators=[
2395
- "storage_stage_check",
2396
- "duckdb_load_check",
2397
- "report_view_check",
2398
- "output_schema_check",
2399
- ],
2400
- files={
2401
- "data/sales_orders.csv": """order_id,customer_id,order_date,product_category,quantity,unit_price
2402
  1001,C001,2026-04-01,books,2,15.00
2403
  1002,C001,2026-04-01,games,1,25.00
2404
  1003,C002,2026-04-02,books,3,12.50
2405
  1004,C003,2026-04-02,gadgets,1,99.99
2406
  1005,C002,2026-04-03,games,2,30.00
2407
  """,
2408
- "docs/runtime_contract.md": """# Runtime contract
2409
-
2410
- - The runtime stages `data/sales_orders.csv` into a local mock S3 path.
2411
- - `pipelines/report_job.yaml` must define:
2412
- - storage_path
2413
- - raw_table
2414
- - load_sql
2415
- - build_sql
2416
- - report_sql
2417
- - final_view
2418
- - The runtime auto-loads the staged CSV into the `raw_table`.
2419
- - `sql/load_raw.sql` must create a staged view named `staged_sales_orders`.
2420
- - `sql/build_table.sql` must create a customer-level summary table named `customer_summary`.
2421
- - `sql/report_view.sql` must create a final view named `customer_daily_report`.
2422
- - The final view must expose columns:
2423
- customer_id, order_date, order_count, gross_revenue_usd
2424
- """,
2425
- "templates/report_pipeline_template.yaml": """name: customer_daily_report_job
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2426
  storage_path: mock_s3/staged/sales_orders.csv
2427
  raw_table: raw_sales_orders
2428
  load_sql: sql/load_raw.sql
@@ -2430,141 +2931,375 @@ build_sql: sql/build_table.sql
2430
  report_sql: sql/report_view.sql
2431
  final_view: customer_daily_report
2432
  """,
2433
- "schemas/raw_sales_orders.json": """{
2434
- "name": "raw_sales_orders",
2435
- "columns": [
2436
- {"name": "order_id", "type": "string"},
2437
- {"name": "customer_id", "type": "string"},
2438
- {"name": "order_date", "type": "date"},
2439
- {"name": "product_category", "type": "string"},
2440
- {"name": "quantity", "type": "integer"},
2441
- {"name": "unit_price", "type": "float"}
2442
- ]
2443
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2444
  """,
2445
  },
2446
- schema_registry={
2447
- "raw.sales_orders_csv": """asset: raw.sales_orders_csv
2448
- columns:
2449
- - order_id: string
2450
- - customer_id: string
2451
- - order_date: date
2452
- - product_category: string
2453
- - quantity: integer
2454
- - unit_price: float
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2455
  """,
2456
- "mart.customer_daily_report": """asset: mart.customer_daily_report
2457
- required_columns:
2458
- - customer_id
2459
- - order_date
2460
- - order_count
2461
- - gross_revenue_usd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2462
  """,
2463
  },
2464
- workflow_target={
2465
- "required_artifacts": ["pipeline_yaml", "load_sql", "build_sql", "report_sql"],
2466
- "artifacts": {
2467
- "pipeline_yaml": workflow_artifact(
2468
- "pipelines/report_job.yaml",
2469
- required_groups=[
2470
- ["storage_path: mock_s3/staged/sales_orders.csv"],
2471
- ["raw_table: raw_sales_orders"],
2472
- ["load_sql: sql/load_raw.sql"],
2473
- ["build_sql: sql/build_table.sql"],
2474
- ["report_sql: sql/report_view.sql"],
2475
- ["final_view: customer_daily_report"],
2476
- ],
2477
- weight=1.0,
2478
- ),
2479
- "load_sql": workflow_artifact(
2480
- "sql/load_raw.sql",
2481
- required_groups=[
2482
- ["create", "staged_sales_orders"],
2483
- ["raw_sales_orders"],
2484
- ["cast(order_date as date)", "try_cast(order_date as date)"],
2485
- ],
2486
- weight=1.0,
2487
- ),
2488
- "build_sql": workflow_artifact(
2489
- "sql/build_table.sql",
2490
- required_groups=[
2491
- ["create", "customer_summary"],
2492
- ["staged_sales_orders"],
2493
- ["quantity * unit_price", "unit_price * quantity"],
2494
- ],
2495
- weight=1.2,
2496
- ),
2497
- "report_sql": workflow_artifact(
2498
- "sql/report_view.sql",
2499
- required_groups=[
2500
- ["create", "customer_daily_report"],
2501
- ["customer_summary"],
2502
- ["order_count"],
2503
- ["gross_revenue_usd"],
2504
- ],
2505
- weight=1.2,
2506
- ),
2507
- },
2508
- "validator_targets": [
2509
- "storage_stage_check",
2510
- "duckdb_load_check",
2511
- "report_view_check",
2512
- "output_schema_check",
2513
- ],
2514
- "solve_validator_targets": [
2515
- "storage_stage_check",
2516
- "duckdb_load_check",
2517
- "report_view_check",
2518
- "output_schema_check",
2519
- ],
2520
- "summary_groups": [
2521
- ["sales_orders.csv"],
2522
- ["customer_daily_report"],
2523
- ["DuckDB", "warehouse"],
2524
- ],
2525
- "investigation_targets": [
2526
- ("read_file", "docs/runtime_contract.md"),
2527
- ("read_file", "data/sales_orders.csv"),
2528
- ("inspect_schema", "raw.sales_orders_csv"),
2529
- ],
2530
- },
2531
- validators={
2532
- "storage_stage_check": {
2533
- "description": "Checks that the CSV could be staged into mock storage.",
2534
- "kind": "runtime_check",
2535
- "check_key": "storage_stage_check",
2536
- },
2537
- "duckdb_load_check": {
2538
- "description": "Checks that the staged CSV loads into DuckDB.",
2539
- "kind": "runtime_check",
2540
- "check_key": "duckdb_load_check",
2541
- },
2542
- "report_view_check": {
2543
- "description": "Checks that the final report view compiles.",
2544
- "kind": "runtime_check",
2545
- "check_key": "report_view_check",
2546
- },
2547
- "output_schema_check": {
2548
- "description": "Checks that the final report view exposes the expected schema.",
2549
- "kind": "runtime_check",
2550
- "check_key": "output_schema_check",
2551
- },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2552
  },
2553
- llm_draft={
2554
- "simulation_target": {
2555
- "source_csv": "data/sales_orders.csv",
2556
- "pipeline_path": "pipelines/report_job.yaml",
2557
- "load_sql_path": "sql/load_raw.sql",
2558
- "build_sql_path": "sql/build_table.sql",
2559
- "report_sql_path": "sql/report_view.sql",
2560
- "required_output_columns": [
2561
- "customer_id",
2562
- "order_date",
2563
- "order_count",
2564
- "gross_revenue_usd",
2565
- ],
2566
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2567
  },
 
 
 
 
 
 
 
 
 
 
2568
  ),
2569
  ],
2570
  }
 
3
  from __future__ import annotations
4
 
5
  from copy import deepcopy
6
+ from pathlib import Path
7
 
8
 
9
  def repair_validator(
 
154
  }
155
 
156
 
157
+ def simulation_scenario(
158
+ *,
159
+ scenario_id: str,
160
+ developer_request: str,
161
+ workspace_summary: str,
162
+ source_csv_path: str,
163
+ source_csv_content: str,
164
+ raw_table: str,
165
+ staged_view: str,
166
+ build_table: str,
167
+ final_view: str,
168
+ raw_asset: str,
169
+ final_asset: str,
170
+ date_column: str,
171
+ raw_schema_columns: list[tuple[str, str]],
172
+ required_output_columns: list[str],
173
+ build_metric_groups: list[list[str]],
174
+ report_terms: list[str],
175
+ correct_load_sql: str,
176
+ correct_build_sql: str,
177
+ correct_report_sql: str,
178
+ starter_files: dict[str, str] | None = None,
179
+ expected_raw_preview: list[dict[str, object]] | None = None,
180
+ expected_derived_preview: list[dict[str, object]] | None = None,
181
+ expected_final_preview: list[dict[str, object]] | None = None,
182
+ ) -> dict:
183
+ starter_files = starter_files or {}
184
+ template_text = "\n".join(
185
+ [
186
+ f"name: {final_view}_job",
187
+ f"storage_path: mock_s3/staged/{Path(source_csv_path).name}",
188
+ f"raw_table: {raw_table}",
189
+ "load_sql: sql/load_raw.sql",
190
+ "build_sql: sql/build_table.sql",
191
+ "report_sql: sql/report_view.sql",
192
+ f"final_view: {final_view}",
193
+ "",
194
+ ]
195
+ )
196
+ runtime_contract = "\n".join(
197
+ [
198
+ "# Runtime contract",
199
+ "",
200
+ f"- The runtime stages `{source_csv_path}` into a local mock S3 path.",
201
+ "- `pipelines/report_job.yaml` must define:",
202
+ " - storage_path",
203
+ " - raw_table",
204
+ " - load_sql",
205
+ " - build_sql",
206
+ " - report_sql",
207
+ " - final_view",
208
+ "- The runtime auto-loads the staged CSV into the `raw_table`.",
209
+ f"- `sql/load_raw.sql` must create a staged view named `{staged_view}`.",
210
+ f"- `sql/build_table.sql` must create a derived table named `{build_table}`.",
211
+ f"- `sql/report_view.sql` must create a final view named `{final_view}`.",
212
+ f"- The final view must expose columns: {', '.join(required_output_columns)}",
213
+ "",
214
+ ]
215
+ )
216
+ schema_json_columns = ",\n".join(
217
+ f' {{"name": "{name}", "type": "{type_name}"}}' for name, type_name in raw_schema_columns
218
+ )
219
+ schema_yaml_columns = "\n".join(f" - {name}: {type_name}" for name, type_name in raw_schema_columns)
220
+
221
+ files = {
222
+ source_csv_path: source_csv_content,
223
+ "docs/runtime_contract.md": runtime_contract,
224
+ "templates/report_pipeline_template.yaml": template_text,
225
+ f"schemas/{raw_table}.json": "{\n"
226
+ f' "name": "{raw_table}",\n'
227
+ ' "columns": [\n'
228
+ f"{schema_json_columns}\n"
229
+ " ]\n"
230
+ "}\n",
231
+ }
232
+ files.update(starter_files)
233
+
234
+ known_files = [
235
+ source_csv_path,
236
+ "docs/runtime_contract.md",
237
+ "templates/report_pipeline_template.yaml",
238
+ f"schemas/{raw_table}.json",
239
+ ]
240
+ for path in ["pipelines/report_job.yaml", "sql/load_raw.sql", "sql/build_table.sql", "sql/report_view.sql"]:
241
+ if path in starter_files:
242
+ known_files.append(path)
243
+
244
+ scenario = workflow_scenario(
245
+ scenario_id=scenario_id,
246
+ developer_request=developer_request,
247
+ workspace_summary=workspace_summary,
248
+ known_files=known_files,
249
+ editable_targets=[
250
+ "pipelines/report_job.yaml",
251
+ "sql/load_raw.sql",
252
+ "sql/build_table.sql",
253
+ "sql/report_view.sql",
254
+ ],
255
+ known_assets=[raw_asset, final_asset],
256
+ available_validators=[
257
+ "storage_stage_check",
258
+ "duckdb_load_check",
259
+ "report_view_check",
260
+ "output_schema_check",
261
+ ],
262
+ files=files,
263
+ schema_registry={
264
+ raw_asset: f"asset: {raw_asset}\ncolumns:\n{schema_yaml_columns}\n",
265
+ final_asset: (
266
+ f"asset: {final_asset}\nrequired_columns:\n"
267
+ + "".join(f" - {column}\n" for column in required_output_columns)
268
+ ),
269
+ },
270
+ workflow_target={
271
+ "required_artifacts": ["pipeline_yaml", "load_sql", "build_sql", "report_sql"],
272
+ "artifacts": {
273
+ "pipeline_yaml": workflow_artifact(
274
+ "pipelines/report_job.yaml",
275
+ required_groups=[
276
+ [f"storage_path: mock_s3/staged/{Path(source_csv_path).name}"],
277
+ [f"raw_table: {raw_table}"],
278
+ ["load_sql: sql/load_raw.sql"],
279
+ ["build_sql: sql/build_table.sql"],
280
+ ["report_sql: sql/report_view.sql"],
281
+ [f"final_view: {final_view}"],
282
+ ],
283
+ weight=1.0,
284
+ ),
285
+ "load_sql": workflow_artifact(
286
+ "sql/load_raw.sql",
287
+ required_groups=[
288
+ ["create", staged_view],
289
+ [raw_table],
290
+ [f"cast({date_column} as date)", f"try_cast({date_column} as date)", date_column],
291
+ ],
292
+ weight=1.0,
293
+ ),
294
+ "build_sql": workflow_artifact(
295
+ "sql/build_table.sql",
296
+ required_groups=[
297
+ ["create", build_table],
298
+ [staged_view],
299
+ *build_metric_groups,
300
+ ],
301
+ weight=1.2,
302
+ ),
303
+ "report_sql": workflow_artifact(
304
+ "sql/report_view.sql",
305
+ required_groups=[
306
+ ["create", final_view],
307
+ [build_table],
308
+ *[[column] for column in required_output_columns],
309
+ ],
310
+ weight=1.2,
311
+ ),
312
+ },
313
+ "validator_targets": [
314
+ "storage_stage_check",
315
+ "duckdb_load_check",
316
+ "report_view_check",
317
+ "output_schema_check",
318
+ ],
319
+ "solve_validator_targets": [
320
+ "storage_stage_check",
321
+ "duckdb_load_check",
322
+ "report_view_check",
323
+ "output_schema_check",
324
+ ],
325
+ "summary_groups": [
326
+ [Path(source_csv_path).name],
327
+ [final_view],
328
+ *[[term] for term in report_terms],
329
+ ],
330
+ "investigation_targets": [
331
+ ("read_file", "docs/runtime_contract.md"),
332
+ ("read_file", source_csv_path),
333
+ ("inspect_schema", raw_asset),
334
+ ],
335
+ },
336
+ validators={
337
+ "storage_stage_check": {
338
+ "description": "Checks that the CSV could be staged into mock storage.",
339
+ "kind": "runtime_check",
340
+ "check_key": "storage_stage_check",
341
+ },
342
+ "duckdb_load_check": {
343
+ "description": "Checks that the staged CSV loads into DuckDB.",
344
+ "kind": "runtime_check",
345
+ "check_key": "duckdb_load_check",
346
+ },
347
+ "report_view_check": {
348
+ "description": "Checks that the final report view compiles.",
349
+ "kind": "runtime_check",
350
+ "check_key": "report_view_check",
351
+ },
352
+ "output_schema_check": {
353
+ "description": "Checks that the final report view exposes the expected schema.",
354
+ "kind": "runtime_check",
355
+ "check_key": "output_schema_check",
356
+ },
357
+ },
358
+ llm_draft={},
359
+ )
360
+ scenario["simulation_target"] = {
361
+ "source_csv": source_csv_path,
362
+ "pipeline_path": "pipelines/report_job.yaml",
363
+ "load_sql_path": "sql/load_raw.sql",
364
+ "build_sql_path": "sql/build_table.sql",
365
+ "report_sql_path": "sql/report_view.sql",
366
+ "required_output_columns": required_output_columns,
367
+ "expected_raw_table": {
368
+ "name": raw_table,
369
+ "preview_rows": expected_raw_preview or [],
370
+ },
371
+ "expected_derived_table": {
372
+ "name": build_table,
373
+ "preview_rows": expected_derived_preview or [],
374
+ },
375
+ "expected_final_view": {
376
+ "name": final_view,
377
+ "preview_rows": expected_final_preview or [],
378
+ },
379
+ }
380
+ scenario["llm_draft"]["simulation_target"] = deepcopy(scenario["simulation_target"])
381
+ scenario["llm_draft"]["reference_solution"] = {
382
+ "pipeline_yaml": template_text,
383
+ "load_sql": correct_load_sql,
384
+ "build_sql": correct_build_sql,
385
+ "report_sql": correct_report_sql,
386
+ }
387
+ return scenario
388
+
389
+
390
  TASK_DEFINITIONS: dict[str, dict] = {
391
  "repair_data_transform": {
392
  "id": "repair_data_transform",
 
544
  ],
545
  "submission_action": "submit_workspace",
546
  "grader_family": "simulation",
547
+ "scenario_ids": ["SIM-001", "SIM-002", "SIM-003", "SIM-004", "SIM-005", "SIM-006", "SIM-007"],
548
  },
549
  }
550
 
 
2597
  ),
2598
  ],
2599
  "simulation_workflow": [
2600
+ simulation_scenario(
2601
  scenario_id="SIM-001",
2602
  developer_request=(
2603
+ "Create a customer daily report from this sales-order CSV. The workflow "
2604
+ "should stage the raw data, load it into the warehouse, and publish a queryable report view."
2605
  ),
2606
  workspace_summary=(
2607
  "This experimental workspace simulates a tiny data platform. Generate the "
2608
  "pipeline YAML and SQL needed to stage the CSV into mock S3, load it into "
2609
  "DuckDB, build a customer summary table, and publish the final report view. "
2610
+ "Builder starts with an empty workspace; Fixer repairs after runtime failures."
2611
  ),
2612
+ source_csv_path="data/sales_orders.csv",
2613
+ source_csv_content="""order_id,customer_id,order_date,product_category,quantity,unit_price
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2614
  1001,C001,2026-04-01,books,2,15.00
2615
  1002,C001,2026-04-01,games,1,25.00
2616
  1003,C002,2026-04-02,books,3,12.50
2617
  1004,C003,2026-04-02,gadgets,1,99.99
2618
  1005,C002,2026-04-03,games,2,30.00
2619
  """,
2620
+ raw_table="raw_sales_orders",
2621
+ staged_view="staged_sales_orders",
2622
+ build_table="customer_summary",
2623
+ final_view="customer_daily_report",
2624
+ raw_asset="raw.sales_orders_csv",
2625
+ final_asset="mart.customer_daily_report",
2626
+ date_column="order_date",
2627
+ raw_schema_columns=[
2628
+ ("order_id", "string"),
2629
+ ("customer_id", "string"),
2630
+ ("order_date", "date"),
2631
+ ("product_category", "string"),
2632
+ ("quantity", "integer"),
2633
+ ("unit_price", "float"),
2634
+ ],
2635
+ required_output_columns=[
2636
+ "customer_id",
2637
+ "order_date",
2638
+ "order_count",
2639
+ "gross_revenue_usd",
2640
+ ],
2641
+ build_metric_groups=[
2642
+ ["quantity * unit_price", "unit_price * quantity"],
2643
+ ["order_count"],
2644
+ ["gross_revenue_usd"],
2645
+ ],
2646
+ report_terms=["customer_daily_report", "DuckDB", "warehouse"],
2647
+ correct_load_sql="""create or replace view staged_sales_orders as
2648
+ select
2649
+ order_id,
2650
+ customer_id,
2651
+ cast(order_date as date) as order_date,
2652
+ quantity,
2653
+ unit_price
2654
+ from raw_sales_orders;
2655
+ """,
2656
+ correct_build_sql="""create or replace table customer_summary as
2657
+ select
2658
+ customer_id,
2659
+ order_date,
2660
+ count(*) as order_count,
2661
+ sum(quantity * unit_price) as gross_revenue_usd
2662
+ from staged_sales_orders
2663
+ group by 1, 2;
2664
+ """,
2665
+ correct_report_sql="""create or replace view customer_daily_report as
2666
+ select
2667
+ customer_id,
2668
+ order_date,
2669
+ order_count,
2670
+ gross_revenue_usd
2671
+ from customer_summary;
2672
+ """,
2673
+ expected_raw_preview=[
2674
+ {"order_id": "1001", "customer_id": "C001", "order_date": "2026-04-01"},
2675
+ {"order_id": "1002", "customer_id": "C001", "order_date": "2026-04-01"},
2676
+ ],
2677
+ expected_derived_preview=[
2678
+ {"customer_id": "C001", "order_date": "2026-04-01", "order_count": 2},
2679
+ ],
2680
+ expected_final_preview=[
2681
+ {"customer_id": "C001", "order_date": "2026-04-01", "gross_revenue_usd": 55.0},
2682
+ ],
2683
+ ),
2684
+ simulation_scenario(
2685
+ scenario_id="SIM-002",
2686
+ developer_request=(
2687
+ "Generate a plan-tier daily subscription report from this events CSV. "
2688
+ "The pipeline should stage the file, load it into the warehouse, and publish a final daily report."
2689
+ ),
2690
+ workspace_summary=(
2691
+ "Build a small DuckDB workflow that turns subscription events into a daily "
2692
+ "subscription report grouped by plan tier and date."
2693
+ ),
2694
+ source_csv_path="data/subscription_events.csv",
2695
+ source_csv_content="""event_id,account_id,event_date,plan_tier,event_type
2696
+ E001,A100,2026-04-01,pro,started
2697
+ E002,A101,2026-04-01,basic,started
2698
+ E003,A100,2026-04-02,pro,cancelled
2699
+ E004,A102,2026-04-02,pro,started
2700
+ E005,A103,2026-04-02,basic,started
2701
+ E006,A101,2026-04-03,basic,cancelled
2702
+ """,
2703
+ raw_table="raw_subscription_events",
2704
+ staged_view="staged_subscription_events",
2705
+ build_table="subscription_daily_metrics",
2706
+ final_view="subscription_daily_report",
2707
+ raw_asset="raw.subscription_events_csv",
2708
+ final_asset="mart.subscription_daily_report",
2709
+ date_column="event_date",
2710
+ raw_schema_columns=[
2711
+ ("event_id", "string"),
2712
+ ("account_id", "string"),
2713
+ ("event_date", "date"),
2714
+ ("plan_tier", "string"),
2715
+ ("event_type", "string"),
2716
+ ],
2717
+ required_output_columns=[
2718
+ "plan_tier",
2719
+ "event_date",
2720
+ "new_subscriptions",
2721
+ "cancelled_subscriptions",
2722
+ "net_subscriptions",
2723
+ ],
2724
+ build_metric_groups=[
2725
+ ["event_type = 'started'", "event_type='started'"],
2726
+ ["event_type = 'cancelled'", "event_type='cancelled'"],
2727
+ ["net_subscriptions"],
2728
+ ],
2729
+ report_terms=["subscription_daily_report", "DuckDB", "plan_tier"],
2730
+ correct_load_sql="""create or replace view staged_subscription_events as
2731
+ select
2732
+ event_id,
2733
+ account_id,
2734
+ cast(event_date as date) as event_date,
2735
+ plan_tier,
2736
+ lower(event_type) as event_type
2737
+ from raw_subscription_events;
2738
+ """,
2739
+ correct_build_sql="""create or replace table subscription_daily_metrics as
2740
+ select
2741
+ plan_tier,
2742
+ event_date,
2743
+ sum(case when event_type = 'started' then 1 else 0 end) as new_subscriptions,
2744
+ sum(case when event_type = 'cancelled' then 1 else 0 end) as cancelled_subscriptions,
2745
+ sum(case when event_type = 'started' then 1 else 0 end) - sum(case when event_type = 'cancelled' then 1 else 0 end) as net_subscriptions
2746
+ from staged_subscription_events
2747
+ group by 1, 2;
2748
+ """,
2749
+ correct_report_sql="""create or replace view subscription_daily_report as
2750
+ select
2751
+ plan_tier,
2752
+ event_date,
2753
+ new_subscriptions,
2754
+ cancelled_subscriptions,
2755
+ net_subscriptions
2756
+ from subscription_daily_metrics;
2757
+ """,
2758
+ expected_raw_preview=[
2759
+ {"event_id": "E001", "plan_tier": "pro", "event_type": "started"},
2760
+ {"event_id": "E002", "plan_tier": "basic", "event_type": "started"},
2761
+ ],
2762
+ expected_derived_preview=[
2763
+ {"plan_tier": "basic", "event_date": "2026-04-01", "new_subscriptions": 1},
2764
+ ],
2765
+ expected_final_preview=[
2766
+ {"plan_tier": "pro", "event_date": "2026-04-02", "net_subscriptions": 0},
2767
+ ],
2768
+ ),
2769
+ simulation_scenario(
2770
+ scenario_id="SIM-003",
2771
+ developer_request=(
2772
+ "Create a warehouse-level inventory movement report from this CSV. "
2773
+ "Stage the file, load it into DuckDB, and publish a daily inventory view."
2774
+ ),
2775
+ workspace_summary=(
2776
+ "Generate a pipeline that turns inventory movement events into a daily "
2777
+ "warehouse inventory report with received, shipped, and net units."
2778
+ ),
2779
+ source_csv_path="data/inventory_movements.csv",
2780
+ source_csv_content="""movement_id,warehouse_id,movement_date,sku,movement_type,units
2781
+ M001,W1,2026-04-01,SKU1,inbound,20
2782
+ M002,W1,2026-04-01,SKU2,outbound,5
2783
+ M003,W2,2026-04-01,SKU9,inbound,12
2784
+ M004,W1,2026-04-02,SKU1,outbound,4
2785
+ M005,W2,2026-04-02,SKU9,outbound,2
2786
+ M006,W2,2026-04-02,SKU8,inbound,8
2787
+ """,
2788
+ raw_table="raw_inventory_movements",
2789
+ staged_view="staged_inventory_movements",
2790
+ build_table="inventory_daily_balance",
2791
+ final_view="inventory_daily_report",
2792
+ raw_asset="raw.inventory_movements_csv",
2793
+ final_asset="mart.inventory_daily_report",
2794
+ date_column="movement_date",
2795
+ raw_schema_columns=[
2796
+ ("movement_id", "string"),
2797
+ ("warehouse_id", "string"),
2798
+ ("movement_date", "date"),
2799
+ ("sku", "string"),
2800
+ ("movement_type", "string"),
2801
+ ("units", "integer"),
2802
+ ],
2803
+ required_output_columns=[
2804
+ "warehouse_id",
2805
+ "movement_date",
2806
+ "received_units",
2807
+ "shipped_units",
2808
+ "net_units",
2809
+ ],
2810
+ build_metric_groups=[
2811
+ ["movement_type = 'inbound'", "movement_type='inbound'"],
2812
+ ["movement_type = 'outbound'", "movement_type='outbound'"],
2813
+ ["net_units"],
2814
+ ],
2815
+ report_terms=["inventory_daily_report", "DuckDB", "warehouse_id"],
2816
+ correct_load_sql="""create or replace view staged_inventory_movements as
2817
+ select
2818
+ movement_id,
2819
+ warehouse_id,
2820
+ cast(movement_date as date) as movement_date,
2821
+ sku,
2822
+ lower(movement_type) as movement_type,
2823
+ units
2824
+ from raw_inventory_movements;
2825
+ """,
2826
+ correct_build_sql="""create or replace table inventory_daily_balance as
2827
+ select
2828
+ warehouse_id,
2829
+ movement_date,
2830
+ sum(case when movement_type = 'inbound' then units else 0 end) as received_units,
2831
+ sum(case when movement_type = 'outbound' then units else 0 end) as shipped_units,
2832
+ sum(case when movement_type = 'inbound' then units else 0 end) - sum(case when movement_type = 'outbound' then units else 0 end) as net_units
2833
+ from staged_inventory_movements
2834
+ group by 1, 2;
2835
+ """,
2836
+ correct_report_sql="""create or replace view inventory_daily_report as
2837
+ select
2838
+ warehouse_id,
2839
+ movement_date,
2840
+ received_units,
2841
+ shipped_units,
2842
+ net_units
2843
+ from inventory_daily_balance;
2844
+ """,
2845
+ expected_raw_preview=[
2846
+ {"movement_id": "M001", "warehouse_id": "W1", "movement_type": "inbound"},
2847
+ {"movement_id": "M002", "warehouse_id": "W1", "movement_type": "outbound"},
2848
+ ],
2849
+ expected_derived_preview=[
2850
+ {"warehouse_id": "W1", "movement_date": "2026-04-01", "received_units": 20},
2851
+ ],
2852
+ expected_final_preview=[
2853
+ {"warehouse_id": "W2", "movement_date": "2026-04-02", "net_units": 6},
2854
+ ],
2855
+ ),
2856
+ simulation_scenario(
2857
+ scenario_id="SIM-004",
2858
+ developer_request=(
2859
+ "Repair the builder's broken customer-order pipeline so the staged CSV loads, "
2860
+ "the summary table builds correctly, and the final report contract stays intact."
2861
+ ),
2862
+ workspace_summary=(
2863
+ "Builder already generated a first pass of the customer report pipeline, but the "
2864
+ "runtime fails. Read the existing draft files, diagnose the SQL bug, and repair the workflow."
2865
+ ),
2866
+ source_csv_path="data/sales_orders.csv",
2867
+ source_csv_content="""order_id,customer_id,order_date,product_category,quantity,unit_price
2868
+ 2001,C010,2026-04-05,books,1,18.00
2869
+ 2002,C011,2026-04-05,gadgets,2,45.00
2870
+ 2003,C010,2026-04-06,games,1,35.00
2871
+ 2004,C012,2026-04-06,books,4,10.00
2872
+ """,
2873
+ raw_table="raw_sales_orders",
2874
+ staged_view="staged_sales_orders",
2875
+ build_table="customer_summary",
2876
+ final_view="customer_daily_report",
2877
+ raw_asset="raw.sales_orders_csv",
2878
+ final_asset="mart.customer_daily_report",
2879
+ date_column="order_date",
2880
+ raw_schema_columns=[
2881
+ ("order_id", "string"),
2882
+ ("customer_id", "string"),
2883
+ ("order_date", "date"),
2884
+ ("product_category", "string"),
2885
+ ("quantity", "integer"),
2886
+ ("unit_price", "float"),
2887
+ ],
2888
+ required_output_columns=[
2889
+ "customer_id",
2890
+ "order_date",
2891
+ "order_count",
2892
+ "gross_revenue_usd",
2893
+ ],
2894
+ build_metric_groups=[
2895
+ ["quantity * unit_price", "unit_price * quantity"],
2896
+ ["gross_revenue_usd"],
2897
+ ],
2898
+ report_terms=["customer_daily_report", "DuckDB", "warehouse"],
2899
+ correct_load_sql="""create or replace view staged_sales_orders as
2900
+ select
2901
+ order_id,
2902
+ customer_id,
2903
+ cast(order_date as date) as order_date,
2904
+ quantity,
2905
+ unit_price
2906
+ from raw_sales_orders;
2907
+ """,
2908
+ correct_build_sql="""create or replace table customer_summary as
2909
+ select
2910
+ customer_id,
2911
+ order_date,
2912
+ count(*) as order_count,
2913
+ sum(quantity * unit_price) as gross_revenue_usd
2914
+ from staged_sales_orders
2915
+ group by 1, 2;
2916
+ """,
2917
+ correct_report_sql="""create or replace view customer_daily_report as
2918
+ select
2919
+ customer_id,
2920
+ order_date,
2921
+ order_count,
2922
+ gross_revenue_usd
2923
+ from customer_summary;
2924
+ """,
2925
+ starter_files={
2926
+ "pipelines/report_job.yaml": """name: customer_daily_report_job
2927
  storage_path: mock_s3/staged/sales_orders.csv
2928
  raw_table: raw_sales_orders
2929
  load_sql: sql/load_raw.sql
 
2931
  report_sql: sql/report_view.sql
2932
  final_view: customer_daily_report
2933
  """,
2934
+ "sql/load_raw.sql": """create or replace view staged_sales_orders as
2935
+ select
2936
+ order_id,
2937
+ customer_id,
2938
+ cast(order_date as date) as order_date,
2939
+ quantity,
2940
+ unit_price
2941
+ from raw_sales_orders;
2942
+ """,
2943
+ "sql/build_table.sql": """create or replace table customer_summary as
2944
+ select
2945
+ customer_id,
2946
+ order_date,
2947
+ count(*) as order_count,
2948
+ sum(quantity * price) as gross_revenue_usd
2949
+ from staged_sales_orders
2950
+ group by 1, 2;
2951
+ """,
2952
+ "sql/report_view.sql": """create or replace view customer_daily_report as
2953
+ select
2954
+ customer_id,
2955
+ order_date,
2956
+ order_count,
2957
+ gross_revenue_usd
2958
+ from customer_summary;
2959
  """,
2960
  },
2961
+ ),
2962
+ simulation_scenario(
2963
+ scenario_id="SIM-005",
2964
+ developer_request=(
2965
+ "Fix this broken subscription reporting workflow. The builder used the right source CSV "
2966
+ "but the final pipeline no longer matches the expected report view contract."
2967
+ ),
2968
+ workspace_summary=(
2969
+ "A builder draft already exists for the subscription daily report. Repair the pipeline "
2970
+ "and SQL so the runtime publishes the intended final view and output columns."
2971
+ ),
2972
+ source_csv_path="data/subscription_events.csv",
2973
+ source_csv_content="""event_id,account_id,event_date,plan_tier,event_type
2974
+ S001,A200,2026-04-07,pro,started
2975
+ S002,A201,2026-04-07,basic,started
2976
+ S003,A200,2026-04-08,pro,cancelled
2977
+ S004,A202,2026-04-08,pro,started
2978
+ """,
2979
+ raw_table="raw_subscription_events",
2980
+ staged_view="staged_subscription_events",
2981
+ build_table="subscription_daily_metrics",
2982
+ final_view="subscription_daily_report",
2983
+ raw_asset="raw.subscription_events_csv",
2984
+ final_asset="mart.subscription_daily_report",
2985
+ date_column="event_date",
2986
+ raw_schema_columns=[
2987
+ ("event_id", "string"),
2988
+ ("account_id", "string"),
2989
+ ("event_date", "date"),
2990
+ ("plan_tier", "string"),
2991
+ ("event_type", "string"),
2992
+ ],
2993
+ required_output_columns=[
2994
+ "plan_tier",
2995
+ "event_date",
2996
+ "new_subscriptions",
2997
+ "cancelled_subscriptions",
2998
+ "net_subscriptions",
2999
+ ],
3000
+ build_metric_groups=[
3001
+ ["event_type = 'started'", "event_type='started'"],
3002
+ ["event_type = 'cancelled'", "event_type='cancelled'"],
3003
+ ["net_subscriptions"],
3004
+ ],
3005
+ report_terms=["subscription_daily_report", "DuckDB", "plan_tier"],
3006
+ correct_load_sql="""create or replace view staged_subscription_events as
3007
+ select
3008
+ event_id,
3009
+ account_id,
3010
+ cast(event_date as date) as event_date,
3011
+ plan_tier,
3012
+ lower(event_type) as event_type
3013
+ from raw_subscription_events;
3014
+ """,
3015
+ correct_build_sql="""create or replace table subscription_daily_metrics as
3016
+ select
3017
+ plan_tier,
3018
+ event_date,
3019
+ sum(case when event_type = 'started' then 1 else 0 end) as new_subscriptions,
3020
+ sum(case when event_type = 'cancelled' then 1 else 0 end) as cancelled_subscriptions,
3021
+ sum(case when event_type = 'started' then 1 else 0 end) - sum(case when event_type = 'cancelled' then 1 else 0 end) as net_subscriptions
3022
+ from staged_subscription_events
3023
+ group by 1, 2;
3024
  """,
3025
+ correct_report_sql="""create or replace view subscription_daily_report as
3026
+ select
3027
+ plan_tier,
3028
+ event_date,
3029
+ new_subscriptions,
3030
+ cancelled_subscriptions,
3031
+ net_subscriptions
3032
+ from subscription_daily_metrics;
3033
+ """,
3034
+ starter_files={
3035
+ "pipelines/report_job.yaml": """name: subscription_daily_report_job
3036
+ storage_path: mock_s3/staged/subscription_events.csv
3037
+ raw_table: raw_subscription_events
3038
+ load_sql: sql/load_raw.sql
3039
+ build_sql: sql/build_table.sql
3040
+ report_sql: sql/report_view.sql
3041
+ final_view: customer_daily_report
3042
+ """,
3043
+ "sql/load_raw.sql": """create or replace view staged_subscription_events as
3044
+ select
3045
+ event_id,
3046
+ account_id,
3047
+ cast(event_date as date) as event_date,
3048
+ plan_tier,
3049
+ lower(event_type) as event_type
3050
+ from raw_subscription_events;
3051
+ """,
3052
+ "sql/build_table.sql": """create or replace table subscription_daily_metrics as
3053
+ select
3054
+ plan_tier,
3055
+ event_date,
3056
+ sum(case when event_type = 'started' then 1 else 0 end) as new_subscriptions,
3057
+ sum(case when event_type = 'cancelled' then 1 else 0 end) as cancelled_subscriptions,
3058
+ sum(case when event_type = 'started' then 1 else 0 end) - sum(case when event_type = 'cancelled' then 1 else 0 end) as net_subscriptions
3059
+ from staged_subscription_events
3060
+ group by 1, 2;
3061
+ """,
3062
+ "sql/report_view.sql": """create or replace view customer_daily_report as
3063
+ select
3064
+ plan_tier,
3065
+ event_date,
3066
+ new_subscriptions as started_subscriptions,
3067
+ cancelled_subscriptions,
3068
+ net_subscriptions
3069
+ from subscription_daily_metrics;
3070
  """,
3071
  },
3072
+ ),
3073
+ simulation_scenario(
3074
+ scenario_id="SIM-006",
3075
+ developer_request=(
3076
+ "Repair the inventory movement report. The current draft runs partway through, "
3077
+ "but the final report schema no longer matches the contract expected by downstream users."
3078
+ ),
3079
+ workspace_summary=(
3080
+ "You are in Fixer mode on an inventory reporting workflow. Read the broken draft "
3081
+ "and repair the output schema without changing the warehouse-level business meaning."
3082
+ ),
3083
+ source_csv_path="data/inventory_movements.csv",
3084
+ source_csv_content="""movement_id,warehouse_id,movement_date,sku,movement_type,units
3085
+ I001,W5,2026-04-09,SKU1,inbound,15
3086
+ I002,W5,2026-04-09,SKU2,outbound,3
3087
+ I003,W6,2026-04-10,SKU8,inbound,10
3088
+ I004,W6,2026-04-10,SKU8,outbound,4
3089
+ """,
3090
+ raw_table="raw_inventory_movements",
3091
+ staged_view="staged_inventory_movements",
3092
+ build_table="inventory_daily_balance",
3093
+ final_view="inventory_daily_report",
3094
+ raw_asset="raw.inventory_movements_csv",
3095
+ final_asset="mart.inventory_daily_report",
3096
+ date_column="movement_date",
3097
+ raw_schema_columns=[
3098
+ ("movement_id", "string"),
3099
+ ("warehouse_id", "string"),
3100
+ ("movement_date", "date"),
3101
+ ("sku", "string"),
3102
+ ("movement_type", "string"),
3103
+ ("units", "integer"),
3104
+ ],
3105
+ required_output_columns=[
3106
+ "warehouse_id",
3107
+ "movement_date",
3108
+ "received_units",
3109
+ "shipped_units",
3110
+ "net_units",
3111
+ ],
3112
+ build_metric_groups=[
3113
+ ["movement_type = 'inbound'", "movement_type='inbound'"],
3114
+ ["movement_type = 'outbound'", "movement_type='outbound'"],
3115
+ ["net_units"],
3116
+ ],
3117
+ report_terms=["inventory_daily_report", "DuckDB", "warehouse_id"],
3118
+ correct_load_sql="""create or replace view staged_inventory_movements as
3119
+ select
3120
+ movement_id,
3121
+ warehouse_id,
3122
+ cast(movement_date as date) as movement_date,
3123
+ sku,
3124
+ lower(movement_type) as movement_type,
3125
+ units
3126
+ from raw_inventory_movements;
3127
+ """,
3128
+ correct_build_sql="""create or replace table inventory_daily_balance as
3129
+ select
3130
+ warehouse_id,
3131
+ movement_date,
3132
+ sum(case when movement_type = 'inbound' then units else 0 end) as received_units,
3133
+ sum(case when movement_type = 'outbound' then units else 0 end) as shipped_units,
3134
+ sum(case when movement_type = 'inbound' then units else 0 end) - sum(case when movement_type = 'outbound' then units else 0 end) as net_units
3135
+ from staged_inventory_movements
3136
+ group by 1, 2;
3137
+ """,
3138
+ correct_report_sql="""create or replace view inventory_daily_report as
3139
+ select
3140
+ warehouse_id,
3141
+ movement_date,
3142
+ received_units,
3143
+ shipped_units,
3144
+ net_units
3145
+ from inventory_daily_balance;
3146
+ """,
3147
+ starter_files={
3148
+ "pipelines/report_job.yaml": """name: inventory_daily_report_job
3149
+ storage_path: mock_s3/staged/inventory_movements.csv
3150
+ raw_table: raw_inventory_movements
3151
+ load_sql: sql/load_raw.sql
3152
+ build_sql: sql/build_table.sql
3153
+ report_sql: sql/report_view.sql
3154
+ final_view: inventory_daily_report
3155
+ """,
3156
+ "sql/load_raw.sql": """create or replace view staged_inventory_movements as
3157
+ select
3158
+ movement_id,
3159
+ warehouse_id,
3160
+ cast(movement_date as date) as movement_date,
3161
+ sku,
3162
+ lower(movement_type) as movement_type,
3163
+ units
3164
+ from raw_inventory_movements;
3165
+ """,
3166
+ "sql/build_table.sql": """create or replace table inventory_daily_balance as
3167
+ select
3168
+ warehouse_id,
3169
+ movement_date,
3170
+ sum(case when movement_type = 'inbound' then units else 0 end) as received_units,
3171
+ sum(case when movement_type = 'outbound' then units else 0 end) as shipped_units,
3172
+ sum(case when movement_type = 'inbound' then units else 0 end) - sum(case when movement_type = 'outbound' then units else 0 end) as net_units
3173
+ from staged_inventory_movements
3174
+ group by 1, 2;
3175
+ """,
3176
+ "sql/report_view.sql": """create or replace view inventory_daily_report as
3177
+ select
3178
+ warehouse_id,
3179
+ movement_date,
3180
+ received_units as inbound_units,
3181
+ shipped_units as outbound_units,
3182
+ net_units
3183
+ from inventory_daily_balance;
3184
+ """,
3185
  },
3186
+ ),
3187
+ simulation_scenario(
3188
+ scenario_id="SIM-007",
3189
+ developer_request=(
3190
+ "Builder already created an initial returns-report pipeline, but the runtime fails. "
3191
+ "Use the shared workspace to diagnose the failure and repair the pipeline so the final report view is queryable."
3192
+ ),
3193
+ workspace_summary=(
3194
+ "This shared Builder + Fixer workspace already contains a first-pass pipeline for a returns report. "
3195
+ "The builder draft stages the CSV and points the runtime at the right files, but one SQL artifact is broken. "
3196
+ "Fixer should use runtime feedback to repair the workflow and publish the expected report view."
3197
+ ),
3198
+ source_csv_path="data/returns_events.csv",
3199
+ source_csv_content="""return_id,customer_id,return_date,return_reason,refund_amount
3200
+ R001,C300,2026-04-11,damaged,45.00
3201
+ R002,C301,2026-04-11,wrong_item,30.00
3202
+ R003,C300,2026-04-12,damaged,15.00
3203
+ R004,C302,2026-04-12,late_delivery,22.50
3204
+ R005,C301,2026-04-13,wrong_item,18.00
3205
+ """,
3206
+ raw_table="raw_returns_events",
3207
+ staged_view="staged_returns_events",
3208
+ build_table="returns_daily_summary",
3209
+ final_view="returns_daily_report",
3210
+ raw_asset="raw.returns_events_csv",
3211
+ final_asset="mart.returns_daily_report",
3212
+ date_column="return_date",
3213
+ raw_schema_columns=[
3214
+ ("return_id", "string"),
3215
+ ("customer_id", "string"),
3216
+ ("return_date", "date"),
3217
+ ("return_reason", "string"),
3218
+ ("refund_amount", "float"),
3219
+ ],
3220
+ required_output_columns=[
3221
+ "return_reason",
3222
+ "return_date",
3223
+ "return_count",
3224
+ "refund_total_usd",
3225
+ ],
3226
+ build_metric_groups=[
3227
+ ["count(*) as return_count", "count(*) return_count"],
3228
+ ["sum(refund_amount) as refund_total_usd", "sum(refund_amount) refund_total_usd"],
3229
+ ],
3230
+ report_terms=["returns_daily_report", "DuckDB", "return_reason"],
3231
+ correct_load_sql="""create or replace view staged_returns_events as
3232
+ select
3233
+ return_id,
3234
+ customer_id,
3235
+ cast(return_date as date) as return_date,
3236
+ return_reason,
3237
+ refund_amount
3238
+ from raw_returns_events;
3239
+ """,
3240
+ correct_build_sql="""create or replace table returns_daily_summary as
3241
+ select
3242
+ return_reason,
3243
+ return_date,
3244
+ count(*) as return_count,
3245
+ sum(refund_amount) as refund_total_usd
3246
+ from staged_returns_events
3247
+ group by 1, 2;
3248
+ """,
3249
+ correct_report_sql="""create or replace view returns_daily_report as
3250
+ select
3251
+ return_reason,
3252
+ return_date,
3253
+ return_count,
3254
+ refund_total_usd
3255
+ from returns_daily_summary;
3256
+ """,
3257
+ starter_files={
3258
+ "pipelines/report_job.yaml": """name: returns_daily_report_job
3259
+ storage_path: mock_s3/staged/returns_events.csv
3260
+ raw_table: raw_returns_events
3261
+ load_sql: sql/load_raw.sql
3262
+ build_sql: sql/build_table.sql
3263
+ report_sql: sql/report_view.sql
3264
+ final_view: returns_daily_report
3265
+ """,
3266
+ "sql/load_raw.sql": """create or replace view staged_returns_events as
3267
+ select
3268
+ return_id,
3269
+ customer_id,
3270
+ cast(return_date as date) as return_date,
3271
+ return_reason,
3272
+ refund_amount
3273
+ from raw_returns_events;
3274
+ """,
3275
+ "sql/build_table.sql": """create or replace table returns_daily_summary as
3276
+ select
3277
+ return_reason,
3278
+ returned_at,
3279
+ count(*) as return_count,
3280
+ sum(refund_amount) as refund_total_usd
3281
+ from staged_returns_events
3282
+ group by 1, 2;
3283
+ """,
3284
+ "sql/report_view.sql": """create or replace view returns_daily_report as
3285
+ select
3286
+ return_reason,
3287
+ return_date,
3288
+ return_count,
3289
+ refund_total_usd
3290
+ from returns_daily_summary;
3291
+ """,
3292
  },
3293
+ expected_raw_preview=[
3294
+ {"return_id": "R001", "customer_id": "C300", "return_reason": "damaged"},
3295
+ {"return_id": "R002", "customer_id": "C301", "return_reason": "wrong_item"},
3296
+ ],
3297
+ expected_derived_preview=[
3298
+ {"return_reason": "damaged", "return_date": "2026-04-11", "return_count": 1},
3299
+ ],
3300
+ expected_final_preview=[
3301
+ {"return_reason": "wrong_item", "return_date": "2026-04-11", "refund_total_usd": 30.0},
3302
+ ],
3303
  ),
3304
  ],
3305
  }
train_sft.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  import argparse
 
6
  import json
7
  import os
8
  from dataclasses import dataclass
@@ -38,6 +39,7 @@ def parse_args() -> argparse.Namespace:
38
  default="paged_adamw_8bit",
39
  help="Transformers Trainer optimizer name",
40
  )
 
41
  parser.add_argument("--report-to", default="none", choices=("none", "tensorboard", "wandb"), help="Logging backend")
42
  return parser.parse_args()
43
 
@@ -221,6 +223,16 @@ def main() -> None:
221
  trainer.train()
222
  trainer.save_model(args.output_dir)
223
  tokenizer.save_pretrained(args.output_dir)
 
 
 
 
 
 
 
 
 
 
224
  print(f"Saved SFT model to {args.output_dir}")
225
 
226
 
 
3
  from __future__ import annotations
4
 
5
  import argparse
6
+ import csv
7
  import json
8
  import os
9
  from dataclasses import dataclass
 
39
  default="paged_adamw_8bit",
40
  help="Transformers Trainer optimizer name",
41
  )
42
+ parser.add_argument("--metrics-file", default="training_metrics.csv", help="CSV file for trainer log history")
43
  parser.add_argument("--report-to", default="none", choices=("none", "tensorboard", "wandb"), help="Logging backend")
44
  return parser.parse_args()
45
 
 
223
  trainer.train()
224
  trainer.save_model(args.output_dir)
225
  tokenizer.save_pretrained(args.output_dir)
226
+ metrics_path = Path(args.output_dir) / args.metrics_file
227
+ history_rows = [row for row in trainer.state.log_history if any(key in row for key in ("loss", "train_loss", "epoch"))]
228
+ if history_rows:
229
+ fieldnames = sorted({key for row in history_rows for key in row.keys()})
230
+ with metrics_path.open("w", newline="", encoding="utf-8") as handle:
231
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
232
+ writer.writeheader()
233
+ for row in history_rows:
234
+ writer.writerow(row)
235
+ print(f"Saved training metrics to {metrics_path}")
236
  print(f"Saved SFT model to {args.output_dir}")
237
 
238
 
training_utils.py CHANGED
@@ -71,6 +71,8 @@ class EpisodeMetrics:
71
  runtime_status: dict[str, Any]
72
  output_schema: list[str]
73
  report_preview: list[dict[str, Any]]
 
 
74
  prompt_ids: list[int] | None = None
75
  completion_ids: list[int] | None = None
76
  logprobs: list[float] | None = None
@@ -269,6 +271,8 @@ async def run_episode_async(
269
  await env.connect()
270
  transcript: list[dict[str, Any]] = []
271
  rewards: list[float] = []
 
 
272
  prompt_ids: list[int] = []
273
  completion_ids: list[int] = []
274
  logprobs: list[float] = []
@@ -285,6 +289,10 @@ async def run_episode_async(
285
  action_payload = policy(observation, transcript)
286
  action = coerce_action(action_payload.get("action"))
287
  metadata = action_payload.get("metadata", {})
 
 
 
 
288
  prompt_ids.extend(metadata.get("prompt_ids", []))
289
  completion_ids.extend(metadata.get("completion_ids", []))
290
  logprobs.extend(metadata.get("logprobs", []))
@@ -319,6 +327,8 @@ async def run_episode_async(
319
  runtime_status=dict(getattr(observation, "runtime_status", {})),
320
  output_schema=list(getattr(observation, "output_schema", [])),
321
  report_preview=list(getattr(observation, "report_preview", [])),
 
 
322
  prompt_ids=prompt_ids,
323
  completion_ids=completion_ids,
324
  logprobs=logprobs,
 
71
  runtime_status: dict[str, Any]
72
  output_schema: list[str]
73
  report_preview: list[dict[str, Any]]
74
+ fallback_steps: int = 0
75
+ valid_model_steps: int = 0
76
  prompt_ids: list[int] | None = None
77
  completion_ids: list[int] | None = None
78
  logprobs: list[float] | None = None
 
271
  await env.connect()
272
  transcript: list[dict[str, Any]] = []
273
  rewards: list[float] = []
274
+ fallback_steps = 0
275
+ valid_model_steps = 0
276
  prompt_ids: list[int] = []
277
  completion_ids: list[int] = []
278
  logprobs: list[float] = []
 
289
  action_payload = policy(observation, transcript)
290
  action = coerce_action(action_payload.get("action"))
291
  metadata = action_payload.get("metadata", {})
292
+ if metadata.get("used_fallback", False):
293
+ fallback_steps += 1
294
+ if metadata.get("model_action_valid", False):
295
+ valid_model_steps += 1
296
  prompt_ids.extend(metadata.get("prompt_ids", []))
297
  completion_ids.extend(metadata.get("completion_ids", []))
298
  logprobs.extend(metadata.get("logprobs", []))
 
327
  runtime_status=dict(getattr(observation, "runtime_status", {})),
328
  output_schema=list(getattr(observation, "output_schema", [])),
329
  report_preview=list(getattr(observation, "report_preview", [])),
330
+ fallback_steps=fallback_steps,
331
+ valid_model_steps=valid_model_steps,
332
  prompt_ids=prompt_ids,
333
  completion_ids=completion_ids,
334
  logprobs=logprobs,