AGA-Stage-BC / framework.py
Plans11's picture
Stage B/C datasets v1.0.0: 25k deep-CoT + 10k exec problems (+verify twin), manifests, audit, generators
cafb492 verified
Raw History Blame Contribute Delete
13 kB
"""AGA-Code Stage B/C dataset framework.
Everything here is original, procedurally generated, and execution-verified.
No distillation, no third-party traces — correctness is established by
RUNNING the code, never by copying anyone's answer.
Execution harness semantics are byte-identical to aga_code.run_tests:
harness = code + "\\n" + tests + "\\nprint('AGA_EXEC_OK')"
pass = returncode == 0 and sentinel in stdout
"""
from __future__ import annotations
import hashlib
import random
import subprocess
import sys
from dataclasses import dataclass, field
MASTER_SEED = 1147
SENTINEL = "AGA_EXEC_OK"
# --------------------------------------------------------------------------
# Execution harness (identical semantics to aga_code.run_tests)
# --------------------------------------------------------------------------
def run_code(code: str, tests: str, timeout: int = 5):
"""Run code+tests in a subprocess. Returns (passed: bool, output: str)."""
harness = code + "\n" + tests + "\nprint('AGA_EXEC_OK')"
try:
r = subprocess.run([sys.executable, "-c", harness],
capture_output=True, timeout=timeout, text=True)
ok = r.returncode == 0 and SENTINEL in (r.stdout or "")
return ok, (r.stdout or "") + (r.stderr or "")
except subprocess.TimeoutExpired:
return False, "TIMEOUT"
except Exception as e: # loud, never silent
return False, f"HARNESS ERROR: {e}"
def run_tests(code: str, tests: str, timeout: int = 5) -> bool:
return run_code(code, tests, timeout)[0]
class _ExecTimeout(BaseException):
pass
def _alarm_handler(signum, frame):
raise _ExecTimeout()
def exec_run(code: str, tests: str, timeout: float = 2.0) -> bool:
"""Fast in-process execution gate with identical pass/fail semantics to
run_tests (code + tests + sentinel print; pass = completes cleanly).
Used for the high-volume build gates; the shipped data is additionally
re-verified with the true subprocess harness (driver spot-check + the
independent audit). BaseException timeout so mutant code cannot swallow
it with a bare `except Exception`.
"""
import signal
import contextlib
import io
src = code + "\n" + tests + "\nprint('AGA_EXEC_OK')"
try:
compiled = compile(src, "<gate>", "exec")
except SyntaxError:
return False
old = signal.signal(signal.SIGALRM, _alarm_handler)
signal.setitimer(signal.ITIMER_REAL, timeout)
try:
with contextlib.redirect_stdout(io.StringIO()):
exec(compiled, {})
return True
except BaseException:
return False
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, old)
def first_failing_assert(code: str, tests: str, timeout: int = 5):
"""Return the first single test line that fails against `code`, or None.
Non-assert lines (e.g. fixture setup like `s = Stack()`) are prepended as
setup context so the failing assertion reflects the real bug.
"""
setup = [ln for ln in tests.splitlines()
if ln.strip() and not ln.strip().startswith("assert")]
asserts = [ln for ln in tests.splitlines() if ln.strip().startswith("assert")]
ctx = "\n".join(setup)
for ln in asserts:
ok, _ = run_code(code, ctx + "\n" + ln if ctx else ln, timeout)
if not ok:
return ln.strip()
return None
# --------------------------------------------------------------------------
# Data structures
# --------------------------------------------------------------------------
@dataclass
class Bug:
code: str # buggy variant of the reference
kind: str # off_by_one | wrong_operator | wrong_edge | swapped_branch | missing_case
note: str # family-provided diagnosis detail (what is actually wrong)
@dataclass
class Gen:
params: dict
instruction: str # fully rendered instruction text
phrasing: str # which instruction template produced it
think_slots: dict # goal/approach/steps/edges/complexity
reference: str # correct solution code
tests: str # newline-joined assert statements
difficulty: str # easy | medium | hard (per-instance)
bugs: list = field(default_factory=list) # list[Bug]
func: str = "" # primary function/class name
@dataclass
class Family:
name: str
difficulty: str # base: easy | medium | hard
instruction_templates: list # list[str] with {slots}
gen: object # callable(rng, hard: bool) -> Gen
REGISTRY: list = []
def family(name, difficulty, instruction_templates):
def deco(fn):
REGISTRY.append(Family(name=name, difficulty=difficulty,
instruction_templates=instruction_templates, gen=fn))
return fn
return deco
# --------------------------------------------------------------------------
# Think skeletons — 12 varied phrasings filled from family-provided slots.
# Slots: {goal} {approach} {steps} {edges} {complexity}
# --------------------------------------------------------------------------
THINK_SKELETONS = [
"The task is to {goal}. My plan: {approach}. Concretely: {steps}. I have to be careful with {edges}. Overall this runs in {complexity}.",
"Breaking it down: {goal}. The clean way to do this is {approach}. Steps: {steps}. Watch out for {edges}. Time complexity: {complexity}.",
"Plan first. Goal: {goal}. Approach: {approach}. Then {steps}. Edge cases that could bite: {edges}. Expected complexity {complexity}.",
"I need to {goal}. Strategy: {approach}. Walkthrough: {steps}. Before finalizing, check {edges}. This should be {complexity}.",
"Let me think about {goal}. A direct approach is {approach}: {steps}. The risky parts are {edges}. Complexity is {complexity}.",
"Decomposition: {goal}. Main idea: {approach}. Sub-steps: {steps}. Handle {edges} explicitly. Cost: {complexity}.",
"For {goal}, I'll {approach}. The algorithm: {steps}. Non-obvious cases: {edges}. That gives {complexity}.",
"Thinking it through: to {goal}, the natural method is {approach}. Sequence: {steps}. Don't forget {edges}. {complexity} overall.",
"Approach for {goal}: {approach}. In order: {steps}. Special attention to {edges}. Complexity: {complexity}.",
"First principles: {goal}. I'll {approach} because it is straightforward and correct: {steps}. Verify against {edges}. Runs in {complexity}.",
"Target: {goal}. Method: {approach}. Implementation sketch: {steps}. Failure modes to avoid: {edges}. {complexity}.",
"Here's my reasoning for {goal}: {approach} is the right tool. Steps: {steps}. Edge review: {edges}. Complexity {complexity}.",
]
# --------------------------------------------------------------------------
# Critique templates per bug kind — filled with the family's diagnosis note
# and the ACTUAL failing assertion observed by execution.
# Bug kinds mirror real small-model errors (review point 2b):
# off_by_one, wrong_operator, missing_return, wrong_variable,
# wrong_edge (bad edge-case handling), swapped_branch, missing_case.
# --------------------------------------------------------------------------
CRITIQUE_TEMPLATES = {
"off_by_one": [
"First attempt:\n```python\n{buggy}\n```\nThat draft has an off-by-one error: {note}. The check `{failing}` fails because of it, so the boundary handling has to be corrected.",
"First attempt:\n```python\n{buggy}\n```\nReviewing this, the loop/slice bound is off by one — {note}. Indeed, running the tests shows `{failing}` does not hold. Fix the bound and the behavior follows.",
"First attempt:\n```python\n{buggy}\n```\nBug found: an off-by-one. {note}. Evidence: `{failing}` fails. The corrected version must include the endpoint properly.",
],
"wrong_operator": [
"First attempt:\n```python\n{buggy}\n```\nThe operator used here is wrong: {note}. That is why `{failing}` fails. Swapping in the correct operator fixes the logic.",
"First attempt:\n```python\n{buggy}\n```\nProblem: the wrong comparison/arithmetic operator — {note}. The test `{failing}` exposes it. The fix is to use the right operator.",
"First attempt:\n```python\n{buggy}\n```\nThis draft miscomputes because of an operator mistake: {note}. `{failing}` fails as a direct consequence. Correct the operator.",
],
"wrong_edge": [
"First attempt:\n```python\n{buggy}\n```\nEdge case handled incorrectly: {note}. The failing check `{failing}` is exactly that edge. Handle it explicitly.",
"First attempt:\n```python\n{buggy}\n```\nThe main path is plausible but the edge case is wrong — {note}. `{failing}` fails. A correct solution must special-case or generalize this.",
"First attempt:\n```python\n{buggy}\n```\nBoundary bug: {note}. Running the tests, `{failing}` breaks. Fix the edge handling.",
],
"swapped_branch": [
"First attempt:\n```python\n{buggy}\n```\nThe branches are effectively swapped: {note}. That makes `{failing}` fail. Put each result under the right condition.",
"First attempt:\n```python\n{buggy}\n```\nLogic inversion: {note}. Evidence: `{failing}` does not hold. The two outcomes need to trade places.",
"First attempt:\n```python\n{buggy}\n```\nThe conditional returns the wrong thing on each side — {note}. `{failing}` catches it. Swap the branch results.",
],
"missing_case": [
"First attempt:\n```python\n{buggy}\n```\nA required case is missing: {note}. The check `{failing}` fails because the input falls through. Add the missing case.",
"First attempt:\n```python\n{buggy}\n```\nIncomplete: {note}. `{failing}` demonstrates the gap. The fix is to cover that case explicitly.",
"First attempt:\n```python\n{buggy}\n```\nThis draft forgets a case — {note}. As a result `{failing}` fails. Cover it and the tests pass.",
],
"missing_return": [
"First attempt:\n```python\n{buggy}\n```\nThe computation is right but the result is never returned: {note}. Every check like `{failing}` fails because the function yields None. Add the return statement.",
"First attempt:\n```python\n{buggy}\n```\nMissing return: {note}. The function computes the value and then drops it, so `{failing}` sees None. Return the computed value.",
"First attempt:\n```python\n{buggy}\n```\nBug: no return statement — {note}. `{failing}` fails with None on the left side. The fix is one line: return the result.",
],
"wrong_variable": [
"First attempt:\n```python\n{buggy}\n```\nThe wrong variable is used: {note}. That is why `{failing}` fails — the computation reads or returns the wrong value. Use the correct variable.",
"First attempt:\n```python\n{buggy}\n```\nVariable mix-up: {note}. The test `{failing}` exposes it. Swap in the intended variable.",
"First attempt:\n```python\n{buggy}\n```\nIt operates on the wrong name — {note}. `{failing}` fails as a consequence. Correct the variable reference.",
],
}
# --------------------------------------------------------------------------
# Clean critiques (review point 2a): ~20% of Stage B examples have an
# ALREADY-CORRECT draft. The critique must explicitly say no bug was found;
# revise is a no-op. Slots: {ref}, {check}
# --------------------------------------------------------------------------
CRITIQUE_CLEAN = [
"First attempt:\n```python\n{ref}\n```\nI reviewed this draft line by line against the requirements ({check}): the logic is correct, the edge cases are handled, and every test passes. No bug found — the draft stands as written.",
"First attempt:\n```python\n{ref}\n```\nCareful review ({check}) turns up no defect: control flow, bounds, and return values are all right, and the tests pass. There is nothing to fix here.",
"First attempt:\n```python\n{ref}\n```\nChecking this draft ({check}) — each step matches the specification and the full test suite passes. Verdict: no bug. Leaving the code unchanged.",
"First attempt:\n```python\n{ref}\n```\nI looked for the usual suspects — off-by-one, wrong operator, missing return ({check}) — and found none. The draft is correct and all tests pass, so no revision is needed.",
]
def sha256_hex(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def norm_instruction(s: str) -> str:
return " ".join(s.lower().split())
def trivial_wrong_solutions(g: Gen) -> list:
"""Canonical wrong solutions used to guard against vacuous tests."""
fn = g.func
out = []
if fn:
out.append(f"def {fn}(*args, **kwargs):\n return None")
out.append(f"def {fn}(*args, **kwargs):\n raise NotImplementedError")
return out