"""The problem model shared by kreatix-code-hard, kreatix-code-debug and kreatix-code-plan. A family's sample(rng, lang) returns a Problem: the statement, an efficient reference solution, a separate brute-force oracle (never shown), and inputs. verify() runs both on small and edge inputs and requires identical results, then runs the reference on the large input within the time limit. Only verified problems are used. """ from __future__ import annotations import ast import hashlib import json import random import re from dataclasses import dataclass, field from .runner import RunError, run_calls FAMILIES: dict[str, object] = {} def family(name: str, weight: float = 1.0): def deco(fn): def sample(rng, lang): p = fn(rng, lang) p.solution = annotate(p.solution, p.signature) return p FAMILIES[name] = (sample, weight) return fn return deco def _defs(tree): """{qualified name: FunctionDef} for top-level functions and methods of top-level classes.""" out = {} for node in tree.body: if isinstance(node, ast.FunctionDef): out[node.name] = node elif isinstance(node, ast.ClassDef): for sub in node.body: if isinstance(sub, ast.FunctionDef): out[f"{node.name}.{sub.name}"] = sub return out def _argnames(fn): a = fn.args return [x.arg for x in a.posonlyargs + a.args + a.kwonlyargs], (a.vararg and a.vararg.arg, a.kwarg and a.kwarg.arg) def annotate(solution: str, signature: str) -> str: """Copy the type hints of the given signature onto the matching single-line def lines of the solution, so the code shown carries the same typed signature the user was given. A def is left alone when its argument names differ from the signature's or it spans several lines.""" try: stub = ast.parse(signature.rstrip() + (" ..." if signature.rstrip().endswith(":") else "")) tree = ast.parse(solution) except SyntaxError: return solution stub_lines, lines = signature.splitlines(), solution.splitlines() sdefs, defs = _defs(stub), _defs(tree) for qual, sfn in sdefs.items(): fn = defs.get(qual) if fn is None or _argnames(fn) != _argnames(sfn) or sfn.lineno != sfn.end_lineno: continue head_end = fn.body[0].lineno - 1 if head_end != fn.lineno or fn.decorator_list: continue # multi-line header or decorated: leave it text = stub_lines[sfn.lineno - 1].strip() if text.endswith("..."): text = text[:-3].rstrip() if not text.endswith(":"): continue indent = lines[fn.lineno - 1][:fn.col_offset] old, comment = lines[fn.lineno - 1], "" if "#" in old: code_part, comment = old.split("#", 1) old, comment = code_part.rstrip(), " # " + comment.strip() if not old.rstrip().endswith(":"): continue # body on the same line lines[fn.lineno - 1] = indent + text + comment out = "\n".join(lines) + ("\n" if solution.endswith("\n") else "") try: ast.parse(out) except SyntaxError: return solution return out @dataclass class Problem: family: str variant: str entry: str # function or class name signature: str # first line(s) the user is given statement: str # rendered task text (no examples) solution: str # efficient reference solution (shown) oracle: str # brute-force solution with the same entry name (never shown) approach: str # short explanation of the idea plan: list[str] # reasoning steps (used in ) complexity: str small: list # calls for the oracle comparison edge: list # edge-case calls big: list # large calls (time limit only) kind: str = "function" time_limit: float = 4.0 lang: str = "en" difficulty: int = 2 # 1 easy .. 3 hard results: dict = field(default_factory=dict) # filled by verify(): repr(call) -> output def examples(self, n: int = 2) -> list[tuple]: out = [] for c in self.small[:n]: out.append((c, self.results[json.dumps(c)])) return out def verify(p: Problem) -> tuple[bool, str]: calls = p.small + p.edge try: ref, _ = run_calls(p.solution, p.entry, calls, p.kind) orc, _ = run_calls(p.oracle, p.entry, calls, p.kind) except RunError as e: return False, f"run error: {e}" for c, a, b in zip(calls, ref, orc): if "err" in a or "err" in b or a != b: return False, f"mismatch on {json.dumps(c)[:120]}: ref {str(a)[:80]} oracle {str(b)[:80]}" p.results[json.dumps(c)] = a["ok"] key = hash((p.family, p.variant, re.sub(r"\b%s\b" % re.escape(p.entry), "ENTRY", p.solution))) if p.big and key not in _PERF_OK: # the speed check depends only on the solution: run it once per solution big = p.big() if callable(p.big) else p.big try: res, dt = run_calls(p.solution, p.entry, big, p.kind, timeout=p.time_limit + 2.0) except RunError as e: return False, f"too slow or crashed on the large input: {e}" if dt > p.time_limit or any("err" in r for r in res): return False, f"large input took {dt:.1f}s" _PERF_OK.add(key) return True, "ok" _PERF_OK: set = set() # Families that only ever appear in the test splits of kreatix-code-hard, -debug and -plan, so test measures transfer # to algorithms that train never shows (their techniques, such as monotonic stacks or BFS, do appear in train). HELDOUT = frozenset({"water", "bipartite", "next_greater", "decode_ways", "running_median"}) def normalized_solution(p: Problem) -> str: return re.sub(r"\b%s\b" % re.escape(p.entry), "ENTRY", p.solution) def problem_id(p: Problem) -> str: """Identifies the reference solution up to the entry name: rows with the same id show the same code.""" return hashlib.md5(f"{p.family}|{p.variant}|{normalized_solution(p)}".encode()).hexdigest()[:12] def split_of(p: Problem) -> str: return "test" if p.family in HELDOUT else "train" def fmt_call(entry: str, args: list) -> str: return f"{entry}(" + ", ".join(repr(a) for a in args) + ")" def pick(rng: random.Random, *opts): return rng.choice(opts)