diff --git a/sources/aggregator.py b/sources/aggregator.py new file mode 100644 index 00000000..991a2e06 --- /dev/null +++ b/sources/aggregator.py @@ -0,0 +1,73 @@ + #!/usr/bin/env python3 + import csv, json, sys, argparse + from collections import defaultdict + + def read_csv(path): + with open(path, newline='') as f: + reader = csv.DictReader(f) + return list(reader) + + def parse_date(dt): + # dt is like '2024-06-15 12:34:56+00' + return dt.split(' ')[0] # just the date part + + def main(): + p = argparse.ArgumentParser() + p.add_argument('--trades', required=True) + p.add_argument('--positions', required=True) + p.add_argument('--user-id', type=int, required=True) + p.add_argument('--start-date', required=True) + p.add_argument('--end-date', required=True) + p.add_argument('--output', required=True) + args = p.parse_args() + + trades = [] + with open(args.trades) as f: + reader = csv.DictReader(f) + for row in reader: + # filter by date range (date part of exec_timestamp) + exec_date = parse_date(row['exec_timestamp']) + if args.start_date <= exec_date <= args.end_date: + trades.append(row) + + # total_fills + total_fills = len(trades) + + # total_pnl (only completed trades) + total_pnl = sum(float(r['net_pnl']) for r in trades if r['completed_trade_id']) + + # symbol_quantities + symbol_qty = defaultdict(int) + for r in trades: + symbol_qty[r['symbol']] += int(r['qty']) + + # position mismatches + mismatches = [] + # load positions into dict keyed by symbol + pos_by_symbol = defaultdict(int) + with open(args.positions) as f: + reader = csv.DictReader(f) + for row in reader: + if row['user_id'] == str(args.user_id): + pos_by_symbol[row['symbol']] += int(row['net_qty']) + + for symbol, trade_total in symbol_qty.items(): + pos_total = pos_by_symbol.get(symbol, 0) + if abs(trade_total - pos_total) > 1: + mismatches.append(symbol) + + report = { + "user_id": args.user_id, + "date_range_start": args.start_date, + "date_range_end": args.end_date, + "total_fills": total_fills, + "total_pnl": round(total_pnl, 2), + "symbol_quantities": dict(symbol_qty), + "position_mismatches": mismatches + } + + with open(args.output, 'w') as f: + json.dump(report, f, indent=2) + + if __name__ == '__main__': + main() \ No newline at end of file diff --git a/sources/aggregator2.py b/sources/aggregator2.py new file mode 100644 index 00000000..4604ad14 --- /dev/null +++ b/sources/aggregator2.py @@ -0,0 +1,82 @@ + #!/usr/bin/env python3 + import csv, json, argparse, sys + from collections import defaultdict + from datetime import datetime + + def read_csv(path): + with open(path, newline='') as f: + return list(csv.DictReader(f)) + + def date_in_range(ts, start, end): + # ts is like '2024-06-15 12:34:56+00' + d = datetime.fromisoformat(ts).date() + return start <= d <= end + + def main(): + p = argparse.ArgumentParser() + p.add_argument('--trades', required=True) + p.add_argument('--positions', required=True) + p.add_argument('--user-id', type=int, required=True) + p.add_argument('--start-date', required=True) + p.add_argument('--end-date', required=True) + p.add_argument('--output', required=True) + args = p.parse_args() + + # ------------------------------------------------------------------ + # Load trades, filter by date and event_type + # ------------------------------------------------------------------ + trades = [] + with open(args.trades) as f: + for row in csv.DictReader(f): + if row['event_type'] != 'fill': + continue + if not (args.start_date <= row['exec_timestamp'].split(' ')[0] <= args.end_date): + continue + trades.append(row) + + total_fills = len(trades) + + # total_pnl – only completed trades + total_pnl = sum(float(r['net_pnl']) for r in trades if r['completed_trade_id']) + + # symbol_quantities (net qty per symbol) + symbol_qty = defaultdict(int) + for r in trades: + symbol_qty[r['symbol']] += int(r['qty']) # qty is already signed (+ for BUY, - for SELL) + + # ------------------------------------------------------------------ + # Position mismatch check + # ------------------------------------------------------------------ + # Build a map: symbol → net_qty from positions for this user + pos_by_symbol = defaultdict(int) + with open(args.positions) as f: + reader = csv.DictReader(f) + for row in reader: + if int(row['user_id']) != args.user_id: + continue + pos_by_symbol[row['symbol']] += int(row['net_qty']) + + mismatches = [] + for symbol, trade_total in symbol_qty.items(): + pos_total = pos_by_symbol.get(symbol, 0) + if abs(trade_total - pos_total) > 1: + mismatches.append(symbol) + + # ------------------------------------------------------------------ + # Assemble the final JSON + # ------------------------------------------------------------------ + report = { + "user_id": args.user_id, + "date_range_start": args.start_date, + "date_range_end": args.end_date, + "total_fills": total_fills, + "total_pnl": round(total_pnl, 2), + "symbol_quantities": dict(symbol_qty), + "position_mismatches": mismatches + } + + with open(args.output, 'w') as f: + json.dump(report, f, indent=2) + + if __name__ == '__main__': + main() \ No newline at end of file diff --git a/sources/instruction.md b/sources/instruction.md new file mode 100644 index 00000000..60713cec --- /dev/null +++ b/sources/instruction.md @@ -0,0 +1,44 @@ +### Task Title + + Trading Activity Summary for a User + + ### Description (instruction.md) + + │ You are given access to a PostgreSQL database that stores trading activity for multiple users and accounts. Using only the tools provided inside the + │ container, your goal is to generate a JSON report that summarizes the trading activity for a specific user (provided via a command‑line argument or + │ environment variable) over a date range (also provided). + + │ The report must be written to /app/report.json and must contain the following fields: + + 1. user_id – the identifier of the user whose activity is being summarized. + 2. date_range_start – the start date (inclusive) of the analysis, in YYYY‑MM‑DD format. + 3. date_range_end – the end date (inclusive) of the analysis, in YYYY‑MM‑DD format. + 4. total_fills – the count of rows in trades where event_type = 'fill' and the exec_timestamp falls within the date range. + 5. total_pnl – the sum of the net_pnl column (numeric) for all rows counted in total_fills. Include only rows where completed_trade_id is not null + (i.e., completed trades). + 6. symbol_quantities – a map (object) where each key is a symbol (e.g., "AAPL") and the value is the net quantity (positive for buys, negative for + sells) that resulted from the filled trades in the date range. Quantities should be summed per symbol. + 7. position_mismatches – an array of symbol names where the net quantity from the trades does not match the net quantity reflected in the positions + table for the same user and date range. A mismatch exists if the absolute difference between the summed trade quantity and the net quantity in + positions is greater than 1 (allowing for rounding). Each entry should be the symbol name. + + │ Constraints & Requirements + │ - The report must be valid JSON (use jsonlint‑compatible syntax). + │ - The file must be written exactly to /app/report.json; no other files are permitted for the final artifact. + │ - You may read any tables in the schema, but you may not modify the underlying data (no INSERT/UPDATE/DELETE). + │ - The solution must run offline (the container has no network access). + │ - The task is considered solved when the oracle (solution/solve.sh) exits with status 0, causing the verifier to award a reward of 1. + + │ Hints + │ - Use the exec_timestamp column (type timestamp with time zone) to filter by date range. Cast it to date for simple filtering. + │ - The positions table contains net_qty (the net quantity for the position) and account_id; you can join on user_id → account_id to verify totals. + │ - The trades table stores the raw trade data; the completed_trades table can be used to confirm that a trade is “completed”, but the net_pnl is + │ already present in trades. + │ - To compute net quantity per symbol, sum the qty values (positive for BUY, negative for SELL) for all rows that satisfy the event type and date + │ filter. + │ - For the mismatch check, join trades (aggregated per symbol) with positions (filtering on user_id, account_id, and the same date range). Compute the + │ absolute difference and include symbols where it exceeds 1. + + │ Success Criteria + │ The verifier will load report.json, parse it, and compare the computed values against a ground‑truth generated by the oracle. If all fields match, the + │ verifier writes a reward of 1 to /logs/verifier/reward.txt and {"reward": 1} to /logs/verifier/reward.json. \ No newline at end of file diff --git a/sources/notes from nemo.md b/sources/notes from nemo.md new file mode 100644 index 00000000..b458b8d2 --- /dev/null +++ b/sources/notes from nemo.md @@ -0,0 +1,358 @@ + + + ### Why this task fits the rubric + + ┌───────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ + │ Rubric │ How the task satisfies it │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Verifiable │ The verifier can parse the JSON, recompute the aggregates using the same schema, and compare each field. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Well‑specified │ Every required field, its type, range, and calculation method are explicitly described. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Solvable │ The core work is aggregation and simple joins – doable in a few hours by an expert. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Difficult │ Requires correct handling of time‑zone conversions, date‑range filtering, aggregation across large tables, and a non‑trivial │ + │ │ mismatch detection that must account for position net quantities. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Interesting │ Mirrors a real‑world reporting need for traders/operations teams (daily activity summary, position reconciliation). │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Outcome‑verified │ The verifier reads only the final report.json; no intermediate files are graded. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Anti‑cheat robust │ The agent cannot fake the result by writing a static file; it must actually read the tables, compute aggregates, and produce a │ + │ │ correctly‑structured JSON. The schema’s foreign‑key relationships make it hard to “guess” the right numbers without real │ + │ │ computation. │ + └───────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + + + ### Checklist for you before you start + + 1. Confirm the DB dump is available inside the container (the db_export.sh script mentioned in the doc usually copies a pre‑populated dump into + /app/data/). Verify you can query trades, positions, and completed_trades with a simple \dt and a test SELECT. + 2. Create the task scaffold (scripts/new-task.sh trading-summary) – this will give you the basic directory structure. + 3. Draft the instruction.md using the template above, substituting the exact column names if they differ (e.g., maybe the timestamp column is called + trade_time instead of exec_timestamp). + 4. Run scripts/check-proposal.sh – iterate until the Decision line reads Accept or Strong Accept. + 5. Implement solution/solve.sh (or adapt the skeleton above) and the accompanying Python helper. + 6. Write tests/test_outputs.py – the verifier will load report.json and compare each field to the ground‑truth generated by your oracle. Make sure the + assertions cover: + - JSON validity, + - correct total_fills, + - correct total_pnl (including only completed trades), + - accurate symbol_quantities mapping, + - correct detection of mismatches (difference > 1). + + 7. Run scripts/validate.sh – it will invoke the oracle and then the verifier. All steps should exit 0 and the reward file should contain 1. + 8. Run a quick cheat trial (scripts/cheat-trial.sh) to ensure no obvious shortcuts (e.g., hard‑coding a JSON file) are possible. + + ──────────────────────────────────────────────────────────────────────────────── + + ### Next step for you + + If you’d like, I can: + + - Generate a minimal aggregator.py that already handles the CSV reading and JSON writing (so you can focus on the SQL queries). + - Help you craft the exact instruction.md with the proper column names from the schema you just saw. + - Provide a sample db_export.sh that you can use to load a test dump into the container. + + Just let me know which piece you want to tackle first! + + Here’s a concise “big‑picture” view of how the whole schema can be turned into a solid, verifiable theProject task. + + ──────────────────────────────────────────────────────────────────────────────── + + 1️⃣ Pick a concrete, end‑to‑end problem + + The schema contains three core families that naturally intertwine: + + ┌─────────────────┬──────────────────────────────────────────────┬───────────────────────────────────────────────────────────────────────────────┐ + │ Family │ Key tables │ Typical analytical question │ + ├─────────────────┼──────────────────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────┤ + │ Trade execution │ trades, completed_trades │ “How much PnL did a user generate in a given period?” │ + ├─────────────────┼──────────────────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────┤ + │ Position book │ positions, completed_trades (via account_id) │ “Do the net quantities from trades match the positions we have on the books?” │ + ├─────────────────┼──────────────────────────────────────────────┼───────────────────────────────────────────────────────────────────────────────┤ + │ Market data │ ohlcv_price_series │ “Is the average trade price close to the VWAP from the price series?” │ + └─────────────────┴──────────────────────────────────────────────┴───────────────────────────────────────────────────────────────────────────────┘ + + A task that aggregates trade data, reconciles it with positions, and optionally checks market‑price consistency hits all the rubric requirements: + + - Verifiable – the verifier can re‑run the same SQL queries and compare the JSON report. + - Well‑specified – every field, its type, and its calculation are explicitly defined. + - Solvable – a few joins, filters, and aggregations; an expert can finish it in ~1‑2 h. + - Difficult – requires correct date‑range handling (timestamp → date), proper aggregation, and a non‑trivial mismatch detection (difference > 1 in net + quantity). + - Interesting – mirrors a real‑world operations report that traders/operations teams would need. + - Outcome‑verified – the verifier reads only the final report.json. + - Anti‑cheat robust – the agent must actually read the tables and compute the numbers; it can’t just write a static file. + + ──────────────────────────────────────────────────────────────────────────────── + + 2️⃣ Suggested task definition (ready to copy into instruction.md) + + ### Title + + Trading Activity Summary for a User + + ### Description + + │ You have access to a PostgreSQL database that stores every trade, position, and market‑price snapshot for a set of users. + │ Your goal is to produce a JSON report that summarizes a specific user’s trading activity for a user‑provided date range. + │ The report must be written exactly to /app/report.json and contain the following fields: + + 1. user_id – the identifier of the user whose activity is being summarized. + 2. date_range_start – the start date (inclusive) in YYYY‑MM‑DD format. + 3. date_range_end – the end date (inclusive) in YYYY‑MM‑DD format. + 4. total_fills – count of rows in trades where event_type = 'fill' and the exec_timestamp falls inside the date range. + 5. total_pnl – sum of the net_pnl column (numeric) for all rows counted in total_fills, but only for rows where completed_trade_id is not null (i.e., + completed trades). + 6. symbol_quantities – a map (symbol → net_quantity) that shows the total quantity (positive for buys, negative for sells) executed for each symbol in + the date range. + 7. position_mismatches – an array of symbols where the net quantity from the trades does not match the net quantity stored in positions for the same + user and date range. A mismatch exists when the absolute difference between the summed trade quantity and the net quantity in positions is greater + than 1 (to allow for rounding). + + │ Constraints + │ - The JSON must be valid (pass jsonlint). + │ - The file must be written only to /app/report.json. + │ - No data may be modified (no INSERT/UPDATE/DELETE). + │ - The container is offline – all data is locally available. + + │ Success – when the oracle (solution/solve.sh) exits with status 0, the verifier awards a reward of 1. + + ### Why this works + + ┌───────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ + │ Rubric aspect │ How the task satisfies it │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Verifiable │ The verifier parses report.json and recomputes each metric using the same schema. │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Well‑specified │ Every required field, its format, and the exact calculation are spelled out. │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Solvable │ Aggregations and simple joins; doable in a few hours by an expert. │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Difficult │ Requires proper timestamp → date conversion, handling of large tables, and a non‑trivial mismatch check. │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Interesting │ Mirrors a real‑world “daily activity & position reconciliation” report. │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Outcome‑verified │ Verifier reads only the final JSON; no hidden steps. │ + ├───────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Anti‑cheat robust │ The agent must read the tables, compute aggregates, and produce a correctly‑structured JSON – no shortcuts. │ + └───────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ──────────────────────────────────────────────────────────────────────────────── + + + + Key points that satisfy the rubric + + - Deterministic – all calculations are pure functions of the CSV data; no randomness. + - Clear mapping – each JSON field corresponds directly to a requirement in the instruction. + - No hidden state – the script reads only the exported CSVs, which are produced from the actual database tables, so the verifier can replay the exact + same steps. + - Anti‑cheat – the agent cannot simply write a static JSON file; it must execute the script that reads the real data. + + ──────────────────────────────────────────────────────────────────────────────── + + 4️⃣ Checklist before you start coding + + ┌───────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ + │ ✅ │ Item │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Schema │ Verify column names (exec_timestamp, event_type, qty, net_pnl, completed_trade_id, symbol, positions.net_qty, etc.). │ + │ familiarity │ │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Export script │ Ensure db_export.sh (or an equivalent) can produce a dump that the container can read. Test a simple \copy query in psql to │ + │ │ confirm you can write to /tmp/… inside the container. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Task scaffold │ Run scripts/new-task.sh trading-summary to generate the directory skeleton. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Draft instruction │ Fill in the exact column names from the schema (e.g., maybe the timestamp column is trade_time instead of exec_timestamp). │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Proposal check │ Run scripts/check-proposal.sh on your draft instruction.md. Iterate until the Decision line reads Accept or Strong Accept. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Implement oracle │ Use the skeleton above, adapt paths/column names, and test locally with a small sample CSV. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Write verifier │ In tests/test_outputs.py add assertions that the JSON contains all required keys, that numeric fields are correctly typed, and │ + │ tests │ that the mismatch logic works (you can seed a tiny DB with a few rows to test). │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Validate │ Run scripts/validate.sh tasks/trading-summary – it should run the oracle, then the verifier, and finally produce │ + │ │ /logs/verifier/reward.txt with 1. │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Cheat trial │ Run scripts/cheat-trial.sh to confirm the task resists simple shortcuts (e.g., hard‑coded JSON). │ + ├───────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ Documentation │ Run scripts/render-readme.sh on the task slug so the README is up‑to‑date. │ + └───────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ + + ──────────────────────────────────────────────────────────────────────────────── + + 5️⃣ Next steps you can take right now + + 1. Open the schema file again and note the exact column names you’ll need (e.g., exec_timestamp vs trade_time). + 2. Create a tiny test dump (maybe just a handful of rows in trades and positions) and run a quick psql query to make sure you can export to CSV from + inside the container. + 3. Copy the aggregator.py skeleton into solution/aggregator.py and the solve.sh wrapper into solution/solve.sh. + 4. Run scripts/preflight.sh to confirm the dev‑container environment is ready (Docker, tmux, credentials, etc.). + + If you’d like, I can: + + - Generate a ready‑to‑run aggregator.py with the exact column names from the schema you posted. + - Help you write the first draft of instruction.md (just give me the column names you want to use). + - Provide a sample db_export.sh that creates a minimal SQLite/Postgres dump you can load into the container for early testing. + + Just let me know which piece you’d like to dive into first! + + + if we go ahead with this as the project, what will I have to provide from my database and schema in the finished work product? + + + Error: ResourceExhausted: Worker local total request limit reached (16/16) + + We need to answer: "if we go ahead with this as the project, what will I have to provide from my database and schema in the finished work product?" So + we need to explain what data and schema elements must be included in the final deliverables. According to the schema and task definition, we need to + provide the database dump (schema and data) that the agent can use. The task expects the agent to export a table (the trades table) to + /app/exported.csv. So we need to provide the data for that table (maybe as a dump file). Also we may need to include the schema (the CREATE TABLE + statements) so that the agent can understand the structure. The schema file is already given, but we need to provide it as part of the task? The + instruction says we must provide the database and schema as part of the finished work product. So we need to supply: + + - The schema.sql (or equivalent) containing the CREATE TABLE statements for the relevant tables (trades, positions, completed_trades, accounts maybe). + The schema is already provided, but we need to include it in the repo. + + - The data: a dump of the trades table (maybe also positions) that the agent will read. Could be a CSV export or a dump file (e.g., trades.sql). The + agent will run db_export.sh to produce /app/exported.csv, but we need to provide the underlying data for that table. So we need to supply a dump + (maybe a .sql file with INSERT statements or a .csv). Also maybe we need to provide the accounts table (for account_id) and any lookup tables needed + for foreign key checks (e.g., accounts). The task may require the agent to join with accounts to get account_id? But the schema shows trades has + account_id foreign key; we need that data. + + - Possibly also provide the accounts table data (or at least the mapping of user_id to account_id) if needed for the verifier. The task definition + mentions using the accounts table for foreign key verification (maybe not needed). But to be safe, include the data for accounts (maybe a small set of + rows) and any other lookup tables used in the verification (e.g., completed_trades, positions). However the task description only requires the + exported table and the JSON report; the verifier will read the exported CSV and maybe also read the DB directly? The verifier runs the oracle which + uses the DB (via psql). So we need to provide a database that contains the relevant tables with data. So we need to provide the full schema (SQL) and + a data dump (maybe as a .sql file with INSERT statements or a .dump file). The container will have the schema already (maybe we need to include it). + The instructions say "image builds may use the internet; the agent and verifier runtime are offline by default". So we need to embed the data in the + repository, not rely on external downloads. + + Thus answer: you need to provide: + + - The schema definition (the CREATE TABLE statements). This can be the schema.sql you already have; include it in the repo. + + - A data dump that contains at least the trades table (and any related tables that the oracle queries, e.g., accounts, positions, completed_trades). + Provide a realistic but limited dataset (maybe a few hundred rows) so the agent can run queries within time limits. Provide as a SQL dump (trades.sql) + or as CSV files that the db_export.sh script can read. + + - Possibly a small accounts table (or at least rows for a few users) so the verifier can check foreign key constraints (if needed). But the main + requirement is to have a database that the oracle can query. + + - Also ensure the data is consistent with the schema constraints (unique keys, foreign keys). Provide enough rows to make the task non‑trivial + (duplicates, mismatches, etc.) but not so large that the container runs out of time. + + - Optionally, provide a db_export.sh script that extracts the needed tables to CSV files (the agent will call this). You may need to supply that script + as part of the deliverable or rely on the scaffold. + + Thus answer: list the required artifacts: + + 1. schema.sql (the full schema, already provided, but must be included in repo). + 2. A data dump (e.g., trades_dump.sql or trades.csv) containing real data for the trades table (and possibly accounts, positions, completed_trades). The + data should include a range of dates covering the requested date_range, multiple symbols, duplicate trade IDs, negative quantities, mismatched + positions, etc., to make the task interesting. + 3. The db_export.sh script (or ensure the scaffold provides it) that can export the needed tables to /app/exported.csv when run inside the container. + The script should be idempotent and produce the CSV in the correct location. + 4. Any additional lookup data (e.g., accounts table) needed for the oracle's joins; include rows for a few users and accounts. + + Explain that the verifier will run the oracle, which reads the exported CSV and queries the database directly (via psql). So the database must be + present in the container at build time (or provided as a dump that can be loaded). The container's Dockerfile (environment) will need to have the + necessary DB client (psql) and the data files. + + Summarize succinctly. + + ### What you have to ship — the “database” part of the final deliverable + + The task you are building (the Trading Activity Summary task) works completely offline. + The agent will: + + 1. Run a script (db_export.sh or the scaffold’s export step) that reads the database and writes a CSV file called /app/exported.csv. + 2. Query the same database (via psql) from inside the oracle (solution/solve.sh) to compute the numbers that go into report.json. + + Therefore the only things you must provide in the finished work‑product are: + + ┌───────────────────────┬──────────────────────────────────────────────────────────────────────┬───────────────────────────────────────────────────────┐ + │ Artifact │ Why it is needed │ Where it lives in the repo │ + ├───────────────────────┼──────────────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤ + │ Schema definition │ Gives the agent (and the verifier) the exact table definitions, │ environment/Dockerfile will COPY this file (or you │ + │ (schema.sql) │ column types, constraints, indexes, etc. The oracle runs SQL against │ can mount it at build time). │ + │ │ this schema, so it must be present when the container is built. │ │ + ├───────────────────────┼──────────────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤ + │ Data dump (real data │ The oracle must be able to query the tables and produce │ • trades_dump.sql (or trades.csv generated by │ + │ for the tables the │ deterministic results. The most important table is trades, but the │ db_export.sh)
• accounts_dump.sql (a few rows │ + │ oracle touches) │ oracle also joins to accounts, positions, and possibly │ showing user‑account mapping)
• │ + │ │ completed_trades to verify foreign‑key relationships and compute net │ positions_dump.sql (optional – the oracle reads it to │ + │ │ quantities. │ check mismatches) │ + ├───────────────────────┼──────────────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤ + │ Export script │ The agent will call this script (or the scaffold’s │ solution/db_export.sh (or the scaffold’s │ + │ (db_export.sh or the │ scripts/validate.sh) to create the CSV that the verifier reads. The │ scripts/validate.sh which calls it). │ + │ scaffold’s helper) │ script must be idempotent and write the file to the exact absolute │ │ + │ │ path /app/exported.csv. │ │ + ├───────────────────────┼──────────────────────────────────────────────────────────────────────┼───────────────────────────────────────────────────────┤ + │ Sample data that │ To make the task “difficult” you need rows that:
• contain │ Include a realistic‑size data set (a few thousand │ + │ exercises the │ duplicate trade_ids,
• have negative qty or price,
• span a │ rows is enough) in the dump files. The data should be │ + │ difficulty │ non‑trivial date range (so date‑truncation is required),
• cause │ consistent with all foreign‑key constraints. │ + │ │ the position‑mismatch logic to fire (e.g., a trade whose net │ │ + │ │ quantity differs from the position by > 1). │ │ + └───────────────────────┴──────────────────────────────────────────────────────────────────────┴───────────────────────────────────────────────────────┘ + + #### Minimal viable data set (what you can ship) + + ┌──────────────────────┬─────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────┐ + │ Table │ Minimum rows (example) │ What it demonstrates │ + ├──────────────────────┼─────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────┤ + │ trades │ 30‑50 rows covering at least 3 dates, multiple symbols, a few duplicate │ Tests date‑range filtering, duplicate │ + │ │ trade_ids, a couple of negative qty values, and some rows whose │ detection, sign handling, and the │ + │ │ completed_trade_id is NULL (open trades) vs. non‑NULL (closed trades). │ “completed‑trade‑only” PnL rule. │ + ├──────────────────────┼─────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────┤ + │ accounts │ 5‑10 rows (different user_ids, matching account_ids). │ Needed if the oracle joins to accounts (e.g., │ + │ │ │ to verify that a trade references a valid │ + │ │ │ account). │ + ├──────────────────────┼─────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────┤ + │ positions │ 10‑20 rows (one per symbol/user) with a net_qty that will not exactly match │ Shows the position‑reconciliation difficulty. │ + │ │ the summed trade quantity for at least one symbol (so the mismatch check is │ │ + │ │ triggered). │ │ + ├──────────────────────┼─────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────┤ + │ completed_trades │ 5‑10 rows that the oracle uses to confirm that completed_trade_id really │ Guarantees the oracle’s “only count completed │ + │ (optional) │ points to a closed trade. │ trades” rule. │ + └──────────────────────┴─────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────┘ + + │ Why the data matters: + │ The verifier will run the oracle, then re‑execute the same SQL queries on a ground‑truth copy of the database. If your dump contains the edge‑cases + │ above, the verifier can automatically check that the JSON report matches the expected numbers. If the data are too clean, the task will be deemed “too + │ easy” and may be rejected during the proposal review. + + #### How to package it + + 1. schema.sql – copy the whole dump you received (/mnt/c/Users/Eric/Downloads/schema.sql). + 2. trades_dump.sql – a INSERT‑style dump (or a CSV file) that loads the trades table. + 3. accounts_dump.sql – a small set of rows for accounts. + 4. positions_dump.sql – optional but recommended for a realistic mismatch check. + 5. db_export.sh – a tiny Bash script that runs the appropriate \copy commands (or psql queries) to turn the tables into /app/exported.csv. The script + should be part of the scaffold (scripts/validate.sh already calls it), but you can also ship a custom version if you need extra filtering logic. + + All of these files belong under the task directory (task‑trading‑summary/). The Dockerfile in environment/ must install the PostgreSQL client (psql) and + any other needed tools (e.g., python3, jq) so the oracle can run its queries. + + ──────────────────────────────────────────────────────────────────────────────── + + ### Quick checklist before you call the task “done” + + - [ ] schema.sql is exactly the same as the one you inspected (no missing columns). + - [ ] trades_dump.sql (or CSV) loads cleanly into a fresh PostgreSQL instance and respects all constraints (unique trade_id, proper foreign‑key + references, etc.). + - [ ] db_export.sh (or the scaffold’s exporter) can be run inside the dev‑container and produces a non‑empty /app/exported.csv whose first line is the + CSV header. + - [ ] The oracle (solution/solve.sh) runs without error, writes a valid report.json to /app/report.json, and exits 0. + - [ ] The verifier (tests/test.sh) reads /app/exported.csv and the database (via the same SQL statements) and awards reward = 1. + - [ ] The README (rendered from task.toml) accurately describes the data you supplied and the expected output format. + + Once those items are in place, you’ll have satisfied the “provide from my database and schema” requirement and can move on to the Proposal phase (run + scripts/check-proposal.sh on your instruction.md). + + Let me know if you’d like a starter db_export.sh, a sample trades_dump.sql, or any help tweaking the schema to match your actual data! \ No newline at end of file diff --git a/sources/solve.sh b/sources/solve.sh new file mode 100644 index 00000000..de672f3f --- /dev/null +++ b/sources/solve.sh @@ -0,0 +1,46 @@ + #!/usr/bin/env bash + # solution/solve.sh – oracle for the Trading Activity Summary task + + set -euo pipefail + + # 1. Parse arguments (user_id, start_date, end_date) – assume they are passed as env vars for simplicity + USER_ID="${USER_ID:-1}" + START_DATE="${START_DATE:-2024-01-01}" + END_DATE="${END_DATE:-2024-12-31}" + + # 2. Export the relevant data to CSV files (or use psql \copy) – keep it simple: + # We'll use psql to emit CSV files for each table we need. + # The container should have a psql binary and a connection to the bundled DB dump. + + # Export trades (only fill events within date range) + psql --quiet --no-psqlrc --set ON_ERROR_STOP=1 < /tmp/trades_filtered.csv + \copy ( + SELECT trade_id, exec_timestamp, event_type, symbol, qty, net_pnl, completed_trade_id, user_id, account_id + FROM public.trades + WHERE event_type = 'fill' + AND (date_trunc('day', exec_timestamp)::date) BETWEEN '${START_DATE}' AND '${END_DATE}' + ) TO '/tmp/trades_filtered.csv' CSV HEADER + SQL + + # Export positions for the same user and date range (need account_id) + psql --quiet --no-psqlrc --set ON_ERROR_STOP=1 < /tmp/positions_filtered.csv + \copy ( + SELECT p.position_id, p.symbol, p.net_qty, p.account_id, p.user_id + FROM public.positions p + JOIN public.trades t ON t.account_id = p.account_id AND t.user_id = p.user_id + WHERE p.user_id = ${USER_ID} + AND (date_trunc('day', t.exec_timestamp)::date) BETWEEN '${START_DATE}' AND '${END_DATE}' + ) TO '/tmp/positions_filtered.csv' CSV HEADER + SQL + + # 3. Compute aggregates using a small Python script (or awk) that reads the CSVs. + python3 /app/solution/aggregator.py \ + --trades /tmp/trades_filtered.csv \ + --positions /tmp/positions_filtered.csv \ + --user-id ${USER_ID} \ + --start-date ${START_DATE} \ + --end-date ${END_DATE} \ + --output /app/report.json + + # 4. Exit with 0 to signal success (reward = 1) + exit 0 \ No newline at end of file diff --git a/sources/solve2.sh b/sources/solve2.sh new file mode 100644 index 00000000..b9d5c304 --- /dev/null +++ b/sources/solve2.sh @@ -0,0 +1,67 @@ + #!/usr/bin/env bash + # solution/solve.sh – oracle for the Trading Activity Summary task + + set -euo pipefail + + # ------------------------------------------------------------------ + # 1️⃣ Parse inputs (you can also read env vars or command‑line args) + # ------------------------------------------------------------------ + USER_ID="${USER_ID:-1}" # default for quick testing + START_DATE="${START_DATE:-2024-01-01}" # inclusive + END_DATE="${END_DATE:-2024-12-31}" # inclusive + + # ------------------------------------------------------------------ + # 2️⃣ Export the data we need to CSV files (psql \copy is fast and clean) + # ------------------------------------------------------------------ + # 2a – trades: only 'fill' events within the date window + psql --quiet --no-psqlrc --set ON_ERROR_STOP=1 < /tmp/trades_filtered.csv + \copy ( + SELECT + trade_id, + exec_timestamp, + event_type, + symbol, + qty, + net_pnl, + completed_trade_id, + user_id, + account_id + FROM public.trades + WHERE event_type = 'fill' + AND (date_trunc('day', exec_timestamp)::date) BETWEEN '${START_DATE}' AND '${END_DATE}' + ) TO '/tmp/trades_filtered.csv' CSV HEADER + SQL + + # 2b – positions: we need the net quantity per symbol for the same user/account + psql --quiet --no-psqlrc --set ON_ERROR_STOP=1 < /tmp/positions_filtered.csv + \copy ( + SELECT + p.position_id, + p.symbol, + p.net_qty, + p.account_id, + p.user_id + FROM public.positions p + JOIN public.trades t + ON t.account_id = p.account_id + AND t.user_id = p.user_id + AND (date_trunc('day', t.exec_timestamp)::date) BETWEEN '${START_DATE}' AND '${END_DATE}' + WHERE p.user_id = ${USER_ID} + ) TO '/tmp/positions_filtered.csv' CSV HEADER + SQL + + # ------------------------------------------------------------------ + # 3️⃣ Run a tiny Python helper that does the heavy lifting + # ------------------------------------------------------------------ + python3 /app/solution/aggregator.py \ + --trades /tmp/trades_filtered.csv \ + --positions /tmp/positions_filtered.csv \ + --user-id ${USER_ID} \ + --start-date ${START_DATE} \ + --end-date ${END_DATE} \ + --output /app/report.json + + # ------------------------------------------------------------------ + # 4️⃣ Exit successfully → verifier will give reward = 1 + # ------------------------------------------------------------------ + exit 0 \ No newline at end of file diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/README.md b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/README.md new file mode 100644 index 00000000..e5f0c40f --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/README.md @@ -0,0 +1,19 @@ +# Trading Activity Summary + +## Task Metadata + +- **Author:** Author (anonymous@example.invalid) +- **Expert time:** 0 minutes +- **Agent timeout:** 8 hours +- **CPUs:** 2 +- **Memory:** 4 GB + +See [instruction.md](instruction.md) for the full task instruction. Additional information on the task environment and verifier can be found in [task.toml](task.toml). + +## Difficulty explanation + +## Solution explanation + +## Verification explanation + +## Relevant experience diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/environment/Dockerfile b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/environment/Dockerfile new file mode 100644 index 00000000..db7123c1 --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/environment/Dockerfile @@ -0,0 +1,35 @@ +# Builds the container the agent runs in. Replace the example below with the +# system packages, language toolchains, and seed data your task actually needs. +# Full guidance: profiles/terminal-bench-sota/docs/task-anatomy.md → environment/Dockerfile section. +# +# Don't: pin apt versions; COPY tests/ or solution/ (Harbor mounts them at +# runtime); install test-only deps here. Verifier deps go in tests/Dockerfile. +# Do keep the tmux block below, and keep it before any USER instruction (if the +# image switches to a non-root user, wrap it in USER root ... USER ). + +FROM ubuntu:24.04 + +# triton-terminus-offline-runtime: tmux (Terminus-2 drives the container over tmux; the image must carry it) +RUN set -eux; \ + if command -v apt-get >/dev/null; then apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*; \ + elif command -v apk >/dev/null; then apk add --no-cache tmux; \ + elif command -v dnf >/dev/null; then dnf install -y tmux && dnf clean all; \ + elif command -v yum >/dev/null; then yum install -y tmux && yum clean all; \ + else echo "no supported package manager for tmux" >&2; exit 1; fi + +WORKDIR /app + +# REPLACE: list the packages your agent needs at runtime. +RUN apt-get update && apt-get install -y \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# OPTIONAL: copy seed files the agent will read at runtime. +# COPY data /app/data + +# OPTIONAL: install pinned language deps (Python/Node/Rust/etc.) from a +# lockfile committed under environment/. Pinning is required by the +# `deterministic_reproducible` rubric criterion. Everything the image fetches +# is fetched here, at build time; the agent phase runs offline by default. +# COPY requirements.txt /app/ +# RUN pip install --no-cache-dir -r /app/requirements.txt diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/instruction.md b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/instruction.md new file mode 100644 index 00000000..267e59bd --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/instruction.md @@ -0,0 +1,15 @@ + + +Create a file at `/app/done.txt` containing the exact text `done`. + +You have 28800 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task. diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/solution/solve.sh b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/solution/solve.sh new file mode 100644 index 00000000..905c80d7 --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/solution/solve.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -euo pipefail + +# The reference solution. Replace the example below with the steps that solve +# your task end-to-end. Full guidance: profiles/terminal-bench-sota/docs/task-anatomy.md → solve.sh section. +# +# Rules: +# - Must genuinely solve the task. No hardcoded outputs that pass tests +# without computing the answer (the `solution_quality` criterion checks). +# - Must produce reward 1.0 when run as Harbor's oracle (validate.sh enforces). +# - If the solution exceeds ~20 lines, factor logic into solution/solve.py +# (or .js, .rs, etc.) and call from this script. + +# REPLACE: the example below solves the hello-world example task. +echo "done" > /app/done.txt diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/task.toml b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/task.toml new file mode 100644 index 00000000..369b7ee8 --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/task.toml @@ -0,0 +1,38 @@ +# Task metadata and resource configuration. +# Full guidance: profiles/terminal-bench-sota/docs/task-anatomy.md -> task.toml section. + +artifacts = ["/app/done.txt"] # paths the verifier reads from the agent; must be above the first [section] + +[task] +name = "terminal-use-agents/trading-activity-summary" + +[metadata] +author_name = "Author" # anonymous default; do not use your legal name +author_email = "anonymous@example.invalid" # anonymous default; do not use a personal/work email +author_organization = "" # optional; leave blank unless an admin tells you otherwise +difficulty_explanation = "" # why this task is hard for agents and humans +solution_explanation = "" # high-level approach and key insights +verification_explanation = "" # how the tests verify correctness +category = "" # task-domain: Science, Software, ML, Operations, Security, Hardware, or Media +subcategory = "" # finer subdomain within the category +tags = [] # e.g., ["debugging", "python"] +expert_time_estimate_hours = 0 # best-case hours for a focused domain expert +relevant_experience = "" # non-identifying experience relevant to building this task + +[verifier] +timeout_sec = 600.0 +environment_mode = "separate" + +[agent] +timeout_sec = 28800.0 # 8 h default, which is also the cap; lower it only with a reason in difficulty_explanation + +[environment] +build_timeout_sec = 6000.0 +cpus = 2 +memory_mb = 4096 +storage_mb = 10240 +gpus = 0 # GPU tasks are not accepted; leave at 0 +# Agent and verifier run offline; the image build stays online. For an external +# API set "allowlist" + allowed_hosts and add a [verifier.environment] block +# (see profiles/terminal-bench-sota/docs/task-anatomy.md -> network section). +network_mode = "no-network" diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/Dockerfile b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/Dockerfile new file mode 100644 index 00000000..8133ca9a --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.13-slim-bookworm + +# Bake verifier tooling into the verifier image. tests/test.sh should run tests, +# not install pytest or fetch packages at verify time. +RUN pip install --no-cache-dir pytest==9.1.1 pytest-json-ctrf==0.5.2 + +# Harbor does not upload tests/ in separate verifier mode; the verifier image +# must own the test files. +COPY . /tests/ + +# Pre-create parent dirs for top-level artifacts declared in task.toml. +RUN mkdir -p /app diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/test.sh b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/test.sh new file mode 100644 index 00000000..9b5fc34b --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/test.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# The verifier entrypoint: runs the baked pytest suite and writes the reward. +# Both reward files carry the same literal (Harbor reads reward.json first when +# both exist); 0 is written first so a verifier that crashes still scores 0, +# and 1 only when pytest exits 0. Never install anything here: the verifier +# runs offline, so verifier dependencies belong in tests/Dockerfile. Keep the +# reward files readable by the host user that collects them (no umask or chmod +# on /logs/verifier). + +echo 0 > /logs/verifier/reward.txt +echo '{"reward": 0}' > /logs/verifier/reward.json + +if pytest --ctrf /logs/verifier/ctrf.json /tests/test_outputs.py -rA; then + echo 1 > /logs/verifier/reward.txt + echo '{"reward": 1}' > /logs/verifier/reward.json +fi diff --git a/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/test_outputs.py b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/test_outputs.py new file mode 100644 index 00000000..90c4ef58 --- /dev/null +++ b/triton-sota-toolkit-bb5effd/tasks/trading-activity-summary/tests/test_outputs.py @@ -0,0 +1,28 @@ +""" +The verifier. Replace the example tests below with assertions that check +whether the agent solved your task. Full guidance: profiles/terminal-bench-sota/docs/task-anatomy.md → +tests/test_outputs.py section. + +Each test: + - needs a docstring (it surfaces in the rubric review) + - should check behavior (file contents, runtime state), not source patterns + - should trace to a named requirement in instruction.md + - must survive an adversarial agent (agents run as root in /app/) + +Non-stdlib verifier imports belong in tests/Dockerfile. In separate-verifier +mode, tests/test.sh should run baked verifier tooling rather than installing +packages at verify time. +""" + +from pathlib import Path + + +def test_done_file_exists(): + """The expected output file is created.""" + assert Path("/app/done.txt").exists(), "/app/done.txt does not exist" + + +def test_done_file_content(): + """The output file has the expected content.""" + content = Path("/app/done.txt").read_text().strip() + assert content == "done", f"Expected 'done', got {content!r}"