Datasets:
Release Klein-Code-Bench v0.1.0: 260 validated project-generation tasks
Browse filesFiles changed (33)
- .gitattributes+1
- .github/workflows/checks.ymlAdded+16
- .gitignoreAdded+11
- LICENSEAdded+21
- README.mdAdded+143
- dist/klein_code_bench-0.1.0-py3-none-any.whlAdded+3
- docs/BANANA_HARNESS.mdAdded+21
- docs/CATALOG.mdAdded+343
- docs/EVALUATION.mdAdded+30
- klein_code_bench/__init__.pyAdded+3
- klein_code_bench/__main__.pyAdded+3
- klein_code_bench/build.pyAdded+108
- klein_code_bench/catalog.pyAdded+1194
- klein_code_bench/cli.pyAdded+136
- klein_code_bench/data/easy.jsonlAdded
- klein_code_bench/data/hard.jsonlAdded
- klein_code_bench/data/intermediate.jsonlAdded
- klein_code_bench/data/manifest.jsonAdded+27
- klein_code_bench/data/max.jsonlAdded
- klein_code_bench/fuzz.pyAdded+426
- klein_code_bench/protocol.pyAdded+47
- klein_code_bench/reference/__init__.pyAdded+1
- klein_code_bench/reference/domains.pyAdded+869
- klein_code_bench/reference/export.pyAdded+53
- klein_code_bench/reference/service.pyAdded+228
- klein_code_bench/runner.pyAdded+338
- klein_code_bench/scenarios.pyAdded+451
- klein_code_bench/scoring.pyAdded+40
- klein_code_bench/validation.pyAdded+58
- pyproject.tomlAdded+25
- tests/test_benchmark.pyAdded+328
- tools/publish_hf.pyAdded+59
- validation-summary.jsonAdded+16
57 unmodified lines58596057 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text57 unmodified lines5859606157 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textdist/klein_code_bench-0.1.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
12345678910111213141516name: benchmark checkson: [push, pull_request]jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ['3.11', '3.12', '3.13', '3.14'] steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - run: python -m pip install -e . - run: python -m unittest discover -s tests -v - run: python -m klein_code_bench validate1234567891011__pycache__/*.py[cod].venv/*.egg-info/build/dist/results/workspaces/.env.env.**.token123456789101112131415161718192021MIT License
Copyright (c) 2026 Klein ML
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143---language:- enlicense: mitpretty_name: Klein-Code-Benchtask_categories:- text-generationtags:- code- benchmark- project-generation- small-language-models- local-models- pythonsize_categories:- n<1Kconfigs:- config_name: default default: true data_files: - split: test path: klein_code_bench/data/*.jsonl- config_name: easy data_files: - split: test path: klein_code_bench/data/easy.jsonl- config_name: intermediate data_files: - split: test path: klein_code_bench/data/intermediate.jsonl- config_name: hard data_files: - split: test path: klein_code_bench/data/hard.jsonl- config_name: max data_files: - split: test path: klein_code_bench/data/max.jsonl---
# Klein-Code-Bench
**260 tasks that ask a coding model to build a working Python project from an empty directory.** There are four subsets of exactly 65 tasks. A project is resolved only when **every acceptance test passes**, including process restarts where required. No Docker, container runtime, cloud model, or third-party runtime library is required by the evaluator.
| Subset | Target model size | Project to build | Tasks || --- | --- | --- | ---: || easy | 2–8B | JSONL command-line tool with a domain algorithm and error recovery | 65 || intermediate | 8–16B | Stateful document service with CRUD, listing and domain evaluation | 65 || hard | 16–32B | Service with atomic batches, revision checks and nested transactions | 65 || max | 60–200B | Durable service with forced-kill recovery, idempotency, history and pagination | 65 |
**The parameter ranges are design targets, not measured capability thresholds.** Version 0.1.0 has no model leaderboard or empirical difficulty calibration. It is an initial benchmark release, not an extension of or an official result on SWE-bench.
## What the tasks measure
Each of 65 domain families has one version in each subset. The higher versions require the entire lower-tier behavior plus additional service behavior. Domains include text processing, CSV and JSON tools, calendars, numerical utilities, graph algorithms, scheduling, ledgers, geometry, parsing and simulation. See [the task catalog](docs/CATALOG.md).
A participant receives a complete specification and two examples, then creates `main.py` and any supporting files. There is no repository to fix, starter solution, injected implementation, or preinstalled dependency to discover. Tests run the finished project as a real subprocess, exchange JSONL requests, and check results and state transitions. Max-tier restart sessions force-kill the process immediately after its final acknowledged response and then reopen the same state directory.
**Cross-tier overlap is intentional.** These are 260 project specifications across 65 families, not 260 unrelated algorithms. Shared service requirements and domain families make outcomes correlated; report each subset separately. Do not train on one tier and describe another tier as an uncontaminated evaluation. The easy subset includes some standard graph/DP algorithms; the target bands need calibration across actual local models.
## Quick start (Python 3.11+, Linux or macOS)
Clone this Hugging Face dataset repository, then install the evaluator:
```bashgit clone https://huggingface.co/datasets/klein-ml/klein-code-benchcd klein-code-benchpython -m pip install -e .klein-bench list --subset easy
# Put the prompt outside the initially empty project directory.klein-bench prepare kcb-easy-001-word-frequency --output workspaces/first# Give workspaces/first/PROMPT.md to your coding model.# Have the model create files inside workspaces/first/project/.
klein-bench evaluate kcb-easy-001-word-frequency \ --solution workspaces/first/project --output results/first.jsonklein-bench score results/first.json```
`python -m klein_code_bench` is equivalent to `klein-bench`. A failed submission exits 1; an invalid invocation exits 2. `--public-only` runs examples as a smoke test and marks the result ineligible for scoring. The evaluator has no Python dependencies. Participants use only the Python standard library.
Use your own coding agent, a local API endpoint, or the [banana-harness integration](docs/BANANA_HARNESS.md). Model size does not enforce access to a tier; evaluate any model on any subset and record its inference settings.
## Load with Hugging Face Datasets
```pythonfrom datasets import load_dataset
easy = load_dataset("klein-ml/klein-code-bench", "easy", split="test")all_tasks = load_dataset("klein-ml/klein-code-bench", split="test")assert len(easy) == 65assert len(all_tasks) == 260```
Pin `revision` to a dataset commit when reporting results. All four named configurations expose a `test` split; the default configuration concatenates them. There is no training split. No dataset loading script or `trust_remote_code` is needed.
The JSONL rows contain:
| Field | Meaning || --- | --- || `task_id` | Stable unique identifier || `subset`, `family`, `category`, `title` | Tier and project descriptors || `target_model_parameters` | Intended parameter band, uncalibrated || `language`, `entrypoint`, `protocol_version` | Python, main.py and contract version || `prompt` | Entire participant-visible project specification || `public_tests` | JSON-encoded list of example requests and responses || `acceptance_tests` | JSON-encoded evaluator scenarios, with sessions, requests and expected responses || `num_scenarios`, `num_assertions`, `timeout_seconds` | Evaluation sizes and per-session wall-clock limit |
Tests are JSON strings to provide a stable Arrow schema across projects with different input and output structures. Decode with `json.loads`. `acceptance_tests` is evaluator-side information: **never include it in the model prompt, context or workspace**. The source and expected outputs are public for reproducibility, so these tests are not secret holdouts. Examples also occur in the full suite. Source code and evaluator references must be excluded from an agent's accessible benchmark materials in a controlled evaluation.
## Scoring and reproducibility
The primary metric is **resolve@1**: one generated project per task, with all tests passing. Within a subset the score is resolved tasks / 65. Across the complete benchmark it is resolved tasks / 260. Missing submissions remain in that denominator. The report also includes the rate among submitted tasks and marks incomplete runs. Partial assertion success is diagnostic, never a resolved task.
Every run starts each scenario with a fresh copy of the submission and empty state directory. Sessions within a max-tier scenario share that state directory. JSON comparisons preserve array order and distinguish booleans from numbers; finite floating point values use absolute/relative tolerance 1e-9. Exact integer comparisons avoid precision loss. The default limit is 10 seconds per session and 1 MiB of stdout. See [the evaluation protocol](docs/EVALUATION.md) for execution limits and score reporting requirements.
The four dataset files contain **33,685 response assertions**: 3,075 easy, 5,415 intermediate, 9,705 hard and 15,490 max. Fixtures include 65 independently hand-authored golden outputs, boundary cases, 24 deterministically generated extra inputs per domain family, malformed requests, failure atomicity, nested rollback, revision conflicts and retry/restart sequences. Generated domain inputs are shared across tiers. The suite uses seed 1729; all expected results are materialized before grading, rather than computed inside a candidate process.
```bash# Unit/property tests for the benchmark and runner:python -m unittest discover -s tests -v
# Regenerate data and manifest from authored source:klein-bench build
# Export and run every trusted reference project, and reject every empty project:klein-bench validate --output results/validation.json```
The readable reference implementations are evaluator maintenance tools. They are not starter code and must never be supplied to participants. `klein-bench reference TASK_ID --output DIRECTORY` exports a self-contained reference for auditing. A published `validation-summary.json` records the checked dataset manifest and validation totals; it is not a model evaluation score.
## Execution boundary
This is a local host runner, **not a security sandbox**. It strips inherited credentials from the subprocess environment, copies submissions to temporary directories, rejects file symlinks, limits captured output and time, and kills process groups. Native processes can still access the host filesystem and network. Run generated code under a dedicated unprivileged account on an expendable machine if host access is unacceptable. No Docker workflow is required or provided. Timing and resource availability depend on your host; record them with results.
## Release, provenance and limitations
Version 0.1.0 was authored specifically for this benchmark. No task was copied from SWE-bench, LiveCodeBench or another benchmark. This claim describes authoring provenance, not novelty of standard algorithms or proof against overlap with model training data. All prompts, fixtures and reference implementations are released under MIT. Some use Python standard-library semantics explicitly; the initial release evaluates Python projects only. The rubric measures behavioral correctness rather than UI quality, architectural elegance or production readiness. It does not require concurrent writers, fuzz external disk corruption, or simulate a power failure during a disk write.
The fixed tests are not exhaustive. Reference validation and additional independent golden/property checks establish internal consistency; they cannot prove the absence of every specification or oracle error. Contributions should include a contract, meaningful boundary tests, an independent expected-output check, and a passing reference. Changing a contract or expected behavior requires a dataset version change; retain task IDs only for compatible corrections.123version https://git-lfs.github.com/spec/v1oid sha256:d83fa0ec5908e855707323411d0b743581d57468b532bfd8097828ef96f11841size 791399123456789101112131415161718192021# banana-harness integration
The companion banana-harness adapter uses benchmark name `klein-code-bench`, creates an empty native workspace, and keeps evaluator scenarios in `Task.grading`, outside `Task.public()` and the model prompt. It grades the complete generated project using this package's evaluator. It requires Python 3.11+ and POSIX. No Docker/rootfs backend is used.
From a banana-harness checkout with the Klein adapter:
```bash# Both checkouts are local; the benchmark evaluator has no runtime dependencies.python -m pip install -e /path/to/klein-code-benchpython -m pip install -e '/path/to/banana-harness[models,datasets]'
# Endpoint options use the harness's --model-options JSON file.printf '%s\n' '{"api_base":"http://127.0.0.1:8000/v1","api_key":"local","temperature":0}' > local-model.jsonbanana run klein-code-bench --allow-downloads --dataset-config easy \ --backend native --model openai/your-local-model \ --model-options local-model.json --output jobs/klein-easy```
Use the CLI's `--help` to confirm endpoint/model options for the installed harness. The source-loading path also accepts a single subset JSONL file from `klein_code_bench/data/` through `--source`, avoiding dataset downloads. Use `--dataset-config intermediate`, `hard`, `max`, or `default` for the other subsets or all tasks. Pin `--revision` to the HF commit for remote loading. Record generation settings and use one attempt per task.
Generation uses the harness's existing agent and local-model providers. Grading imports `klein_code_bench.runner` lazily; installing or importing banana-harness alone does not download the benchmark. A missing evaluator gives an actionable install error. The optional `klein` dependency installs a wheel pinned to a benchmark dataset commit.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343# Project catalog
65 domain families × 4 cumulative project tiers = 260 tasks. Each ID below identifies a complete from-scratch project, not a patch. See README for contracts and correlation limitations.
| # | Family | Category | Domain behavior || --- | --- | --- | --- || 001 | word_frequency | text | Input: text (string). Tokenize maximal ASCII [a-z0-9]+ runs after lowercasing. Return [{word,count}], sorted by decreasing count then ascending word. Non-ASCII letters are separators. || 002 | slug_registry | text | Input: titles (list of strings). Lowercase each, replace maximal runs outside ASCII a-z0-9 with a hyphen, strip hyphens, use "item" if empty. Assign in input order. If already used, append -2, -3, ... to the base until globally unique. Return slugs. || 003 | run_length | text | Input: text (string). Return [character,count] pairs for consecutive identical Unicode code points; retain order and include whitespace. Empty text produces []. || 004 | bracket_audit | text | Input: text. Audit (), [], {} ignoring all other code points. Return {balanced,position}. On first unmatched/mismatched closing bracket, position is its zero-based code-point index. If openings remain at EOF, position is the most recent unmatched opening. Balanced input has position:null. || 005 | text_wrap | text | Input: text and positive integer width. Split on Unicode whitespace. Greedily pack words into lines with single spaces; a next word fits iff length including separating space <= width. Never split a long word. Return lines without empty lines. || 006 | ngram_index | text | Input: tokens (strings), n (positive integer). Return [{tokens,positions}] for each distinct contiguous n-gram, sorted lexicographically by token sequence. Positions are ascending zero-based starting indices. n greater than length produces []. || 007 | glob_filter | text | Input: paths (strings), pattern. Return sorted unique matches using case-sensitive shell glob semantics: * matches any run including /, ? one character, [abc] a class, [!abc] a negated class. Python fnmatch.fnmatchcase semantics apply. No filesystem access. || 008 | edit_distance | text | Input: strings a,b of <=200 code points. Return Levenshtein distance with unit insertion, deletion and substitution costs. Compare Unicode code points, case-sensitive. || 009 | roman_codec | text | Input: integer number in 1..3999. Return canonical uppercase Roman numeral using subtractive pairs IV,IX,XL,XC,CD,CM. || 010 | caesar_cipher | text | Input: text and integer shift. Rotate only ASCII letters by shift modulo 26, preserving case. All other characters unchanged. || 011 | csv_records | data | Input: csv (string). Parse comma-separated CSV with double-quoted fields, doubled quote escaping and quoted newlines (Python csv.reader dialect excel). First row is unique nonempty header names. Subsequent rows have the same width. Return objects in source order. Empty document returns []. Blank data rows and malformed CSV are out of scope. || 012 | record_query | data | Input: rows (objects), where (object), select (list of field names). Keep rows containing every where field with an equal JSON value. Return selected fields for each in source order; missing selected fields become null. Values contain no booleans compared with numbers. || 013 | inner_join | data | Input: left,right (lists of objects), key (string). Return [{left,right}] for all pairs with key present on both sides and equal JSON values. Order by left source index then right source index; duplicates multiply. Null keys can match. No boolean-versus-number comparisons. || 014 | group_totals | data | Input: rows (objects), group,value (field names). Each row has a string group value and integer numeric value. Return [{key,count,sum}] sorted by key. Empty rows returns []. || 015 | json_flatten | data | Input: arbitrary JSON value. Return an object mapping JSON Pointer paths to leaves. Root path is "". Escape ~ as ~0 and / as ~1; array indices are decimal. Empty objects/arrays count as leaves. Nonempty containers do not produce their own entries. || 016 | merge_patch | data | Input: target,patch (JSON values). Apply JSON Merge Patch: a nonobject patch replaces the target. An object patch treats a nonobject target as {}; null-valued members remove keys; other members recursively merge. Arrays replace wholesale. Return resulting value. || 017 | json_pointer | data | Input: value (JSON), pointer (empty or starting /, valid ~0/~1 escapes). Resolve object keys or array indices. Array tokens must be 0 or a nonzero decimal digit followed by decimal digits (no leading zero, sign, or -). Return {found:true,value:...}; missing keys, noncontainers or out-of-range indices return {found:false,value:null}. Empty pointer returns root. || 018 | dedupe_records | data | Input: rows (objects), keys (field names). Retain first row for each distinct tuple of requested field values; missing fields equal null. Structural JSON equality ignores object key order. Keep source order. Boolean and numeric key values are not mixed. || 019 | pivot_table | data | Input: rows, row,column,value field names. Row/column values are strings; numeric values are integers. Return {rows:sorted row labels,columns:sorted column labels,values:2D sums}, filling missing cells with 0. Empty input yields three empty arrays. || 020 | schema_check | data | Input: schema object maps field names to {type,required}; value is an object. Types: string,integer,number,boolean,array,object,null. Booleans are neither integers nor numbers. For each schema field in lexical order, report {field,error:"required"} if missing and required, or {field,error:"type"} if present with wrong type. Optional missing fields and extra fields are ignored. No recursive validation. || 021 | interval_union | intervals | Input: intervals, list of [start,end] integer pairs with start<=end. Return sorted merged intervals, combining overlaps and touching endpoints. Retain isolated zero-length intervals. || 022 | interval_gaps | intervals | Input: intervals ([a,b] with a<=b), bounds [low,high] with low<=high. Return positive-length gaps in [low,high] after unioning and clipping occupied intervals. Touching endpoints do not make gaps. Sorted ascending; no zero-length results. || 023 | booking_peak | intervals | Input: bookings ([start,end] integer pairs, start<=end). Intervals are half-open; zero-length bookings ignored. Return {peak,at} for maximum simultaneous active bookings and earliest timestamp attaining that maximum. Empty effective input: {peak:0,at:null}. Endings at t happen before starts at t. || 024 | business_days | calendar | Input: start,end ISO dates (start<=end) and holidays (ISO dates). Return all Monday-Friday dates in [start,end) excluding holidays, ascending. Duplicate holidays have no additional effect. Dates are valid in years 1900..2100, range <=400 days. || 025 | calendar_month | calendar | Input: year (1900..2100), month (1..12). Return weeks as arrays of seven day numbers, Monday first. Use 0 for days outside the month; include only weeks intersecting this month. || 026 | moving_average | numeric | Input: values (finite numbers), window (positive integer). Return arithmetic means for all contiguous full windows. Empty input or window>length gives []. || 027 | statistics | numeric | Input: values (finite numbers). Return {count,min,max,mean,median,variance}. Variance is population variance (divide by n); even-length median is mean of middle two. Empty values: count=0 and all other fields null. || 028 | histogram | numeric | Input: finite numeric values and strictly increasing edges (>=2). Bins are [edge[i],edge[i+1]); values below first edge underflow, values >=last edge overflow. Return {counts,underflow,overflow}. || 029 | matrix_product | numeric | Input: a (m by n), b (n by p), nonempty rectangular integer matrices of compatible dimensions, each dimension <=20. Return matrix product. || 030 | polynomial | numeric | Input: integer coefficients in ascending power order (c0,c1,...) and integer evaluation points. Return values at each point. Empty coefficients denote zero polynomial. || 031 | prime_factors | numeric | Input: integer number in 1..10000000. Return [prime,exponent] pairs in ascending prime order; 1 returns []. || 032 | base_convert | numeric | Input: digits (valid integer representation, optional leading -, case-insensitive ASCII), from_base,to_base (2..36). Convert to lowercase digits 0-9a-z with no leading zero or plus; zero is "0". Magnitude <=2^100. || 033 | money_split | numeric | Input: nonnegative integer amount in cents, nonempty nonnegative integer weights with positive sum. Allocate by largest remainder: floor exact proportional shares, then give leftover cents to greatest fractional remainders, ties to lowest index. Return integer shares totaling amount. || 034 | invoice_total | numeric | Input: items [{price:nonnegative decimal string,quantity:nonnegative integer}], tax_rate (nonnegative decimal string). Sum exact price*quantity then round subtotal to cents using ROUND_HALF_UP. Tax = rounded subtotal * tax_rate, rounded half-up to cents. Total=subtotal+tax. Return {subtotal,tax,total} as strings with exactly two decimal places; do not use binary floating point for monetary arithmetic. || 035 | coin_change | numeric | Input: coins (positive integer denominations, duplicates allowed), amount (0..10000). Unlimited supply of each coin. Return minimum number of coins or null if impossible. Empty coins can make only zero. || 036 | graph_reach | graphs | Input: nodes (unique strings), edges ([from,to] directed pairs, endpoints in nodes), start (in nodes). Return sorted nodes reachable from start including itself. Allow cycles, self-edges and duplicate edges; <=100 nodes. || 037 | shortest_path | graphs | Input: nodes (unique strings), edges ([from,to,nonnegative integer weight], directed), start. Endpoints and start are in nodes. Return object mapping each node to shortest distance or null if unreachable. Cycles, parallel edges, zero weights allowed; <=100 nodes. || 038 | topological_order | graphs | Input: unique string nodes, directed edges [from,to]. Return topological order choosing lexicographically smallest currently available node each step, or null on any cycle. Duplicate edges allowed and do not change dependencies. Endpoints in nodes; <=100 nodes. || 039 | connected_components | graphs | Input: unique string nodes, undirected edges [a,b], endpoints in nodes. Return components as sorted lists of nodes, ordered by each component first node. Include isolated vertices; allow duplicate edges and self-loops. || 040 | grid_route | graphs | Input: grid (nonempty equal-length strings containing . or #), start,end ([row,column], valid coordinates). Move one cell up/down/left/right through . cells. Return shortest step count, or null if blocked/unreachable, including blocked start or end. Grid <=50x50. || 041 | tree_outline | graphs | Input: nodes [{id:unique string,parent:string or null}], forming a forest (all nonnull parents exist, no cycles), <=100 nodes. Return preorder [{id,depth}], roots and each sibling list sorted by id, roots depth 0. || 042 | dependency_build | graphs | Input: dependencies (object of string node -> dependency string list), targets (strings). Every referenced name exists. DFS each distinct target in sorted order, visit dependencies in sorted order, append each node after dependencies once. Return build order; return null on a cycle reachable from a target. Unreachable cycles ignored; <=100 nodes. || 043 | path_normalize | systems | Input: paths (POSIX path strings). Treat all paths as rooted at /. Remove repeated / and . segments; .. pops a segment if available and is ignored at root. Preserve other segment code points and backslashes literally. Return absolute paths without trailing / except root. No filesystem access. || 044 | url_query | systems | Input: query string (without leading ?). Parse &-separated key/value pairs using first =, retain blank values and bare keys, decode + as space and percent-encoded UTF-8. Return object of decoded keys -> lists of values in source order. Empty segments ignored. Python urllib.parse.parse_qsl with keep_blank_values=True semantics. || 045 | version_sort | systems | Input: versions valid MAJOR.MINOR.PATCH optionally -prerelease.identifiers; no build metadata, numeric components/identifiers have no leading zeros. Sort by semantic version precedence: numeric core, prerelease before release, numeric prerelease identifiers numerically and before nonnumeric; nonnumeric ASCII lexical; shorter equal prefix first. Stable equal versions retained. || 046 | lru_trace | systems | Input: nonnegative capacity and accesses (string keys). Simulate initially empty LRU cache. Hit moves key to most recent. Miss inserts and evicts oldest if full. Capacity 0 stores nothing. Return {hits,misses,keys}, keys oldest to newest. || 047 | rate_limit | systems | Input: events [{key:string,time:integer}] in nondecreasing time order, positive integer window, nonnegative limit. Per key, accept if fewer than limit previously accepted events have timestamps in (time-window,time]. Rejected events do not count. Process same-time events in input order. Return boolean decisions. || 048 | priority_queue | systems | Input: events of {op:"push",priority:integer,value:JSON} or {op:"pop"}. Smaller priority first, FIFO ties. Pop empty produces null. Return {popped:list of pop results,remaining:list of queued values in pop order}. || 049 | round_robin | systems | Input: jobs [{id:unique string,duration:positive integer}], positive integer quantum. All jobs arrive at 0 in input order. Repeatedly run first job min(remaining,quantum) time, append unfinished job to end. Return {slices:[{id,start,end}],completion:{id:completion time}}. Empty jobs gives empty structures. || 050 | inventory_ledger | business | Input: events [{sku:string,delta:integer}]. Stock initially absent/zero. Apply in order, rejecting an event if stock would become negative; rejected events leave no state. Accepted events create the SKU even if delta=0. Return {stock:object,rejected:zero-based event indices}. || 051 | bank_ledger | business | Input: balances (account -> nonnegative integer cents), transfers [{from,to,amount:positive integer}]. Reject missing accounts or insufficient source balance; otherwise subtract then add, including self-transfers. Return {balances,rejected:event indices}. Rejected transfers change nothing; never create accounts. || 052 | ballot_count | business | Input: candidates (unique strings), votes (strings). Count candidate votes, unrecognized votes invalid. Return {ranking:[{candidate,votes}],invalid}. Include zero-vote candidates. Rank by decreasing votes then ascending name. || 053 | search_rank | business | Input: documents [{id:unique string,text:string}], query string. Tokenize lowercase ASCII [a-z0-9]+. Score each document by total occurrence counts of distinct query tokens. Omit score=0 docs. Return [{id,score}] sorted by decreasing score then id. || 054 | log_summary | business | Input: events [{level:string,message:string}]. Return {counts:level->count,errors:messages of exactly ERROR-level events in source order}. Levels are case-sensitive; include only encountered levels. || 055 | uptime_report | business | Input: integer start<=end, downtime intervals [a,b] with a<=b. Clip to [start,end), merge overlaps, count duration without double-counting. Return {down,up}, up=end-start-down. || 056 | segment_intersection | geometry | Input: a,b,c,d each [integer x,integer y]. Return boolean whether closed segments ab and cd intersect, including collinear overlap, endpoint touches and degenerate point-segments. Coordinates magnitude <=100000. || 057 | polygon_area | geometry | Input: points, ordered integer [x,y] vertices of a simple polygon (clockwise or counterclockwise), possibly empty or fewer than three points. Return nonnegative area by shoelace, implicitly close last to first. Degenerate polygon has zero area. || 058 | skyline | geometry | Input: buildings [left,right,height], integer left<right and positive height. Return skyline keypoints [x,height] in ascending x where max active height changes. Buildings cover [left,right); omit redundant same-height points; finish with height 0 at last active end. Empty input returns []. || 059 | knapsack | optimization | Input: items [{weight:positive integer,value:nonnegative integer}], capacity (0..1000). Each item usable at most once; return maximum total value within capacity. Identical items remain independently usable; no need to return selected indices. || 060 | task_selection | optimization | Input: tasks [{id:unique string,start:integer,end:integer}], start<end. Greedy maximum-count nonoverlapping schedule: sort by (end,start,id), choose each task iff start>=previous chosen end. Return chosen IDs. Intervals are half-open, negative times allowed. || 061 | sequence_diff | optimization | Input: a,b (lists of strings, length<=100). Produce minimal insert/delete edit script via longest common subsequence. If current tokens equal, emit ["keep",token] and advance both. Otherwise choose deletion when remaining LCS lengths tie; else choose operation retaining longer LCS. Emit ["delete",token] or ["insert",token]; process until both exhausted. || 062 | finite_automaton | languages | Input: start (state string), accepting (state strings), transitions [{from,symbol,to}] with unique (from,symbol) and one-code-point symbols, words (strings). Simulate DFA separately per word. Missing transition rejects immediately. Return acceptance booleans. Empty word accepted iff start accepting. || 063 | content_manifest | systems | Input: files (object of logical file path -> text). Do not read filesystem. Return [{path,bytes,sha256}] sorted by path; bytes is length of UTF-8 encoding and sha256 is lowercase hexadecimal SHA-256 of that encoding. No newline insertion or Unicode normalization. || 064 | cellular_automaton | simulation | Input: live (integer [row,column] pairs, duplicates ignored), steps (0..20). Simulate Conway Life on infinite 2D grid, eight neighbors: live survives with 2 or 3, dead born with 3. Return sorted unique live pairs lexicographically. Initial <=50 cells. || 065 | expression_eval | languages | Input: tokens, a valid postfix integer expression as strings with binary operators +,-,*,/. Return integer result. Division truncates toward zero, including negative operands; all divisors nonzero. Other tokens are signed base-10 integers. All intermediate magnitudes <=2^100; expression leaves exactly one value. |
## Easy — 2–8B target
- `kcb-easy-001-word-frequency`- `kcb-easy-002-slug-registry`- `kcb-easy-003-run-length`- `kcb-easy-004-bracket-audit`- `kcb-easy-005-text-wrap`- `kcb-easy-006-ngram-index`- `kcb-easy-007-glob-filter`- `kcb-easy-008-edit-distance`- `kcb-easy-009-roman-codec`- `kcb-easy-010-caesar-cipher`- `kcb-easy-011-csv-records`- `kcb-easy-012-record-query`- `kcb-easy-013-inner-join`- `kcb-easy-014-group-totals`- `kcb-easy-015-json-flatten`- `kcb-easy-016-merge-patch`- `kcb-easy-017-json-pointer`- `kcb-easy-018-dedupe-records`- `kcb-easy-019-pivot-table`- `kcb-easy-020-schema-check`- `kcb-easy-021-interval-union`- `kcb-easy-022-interval-gaps`- `kcb-easy-023-booking-peak`- `kcb-easy-024-business-days`- `kcb-easy-025-calendar-month`- `kcb-easy-026-moving-average`- `kcb-easy-027-statistics`- `kcb-easy-028-histogram`- `kcb-easy-029-matrix-product`- `kcb-easy-030-polynomial`- `kcb-easy-031-prime-factors`- `kcb-easy-032-base-convert`- `kcb-easy-033-money-split`- `kcb-easy-034-invoice-total`- `kcb-easy-035-coin-change`- `kcb-easy-036-graph-reach`- `kcb-easy-037-shortest-path`- `kcb-easy-038-topological-order`- `kcb-easy-039-connected-components`- `kcb-easy-040-grid-route`- `kcb-easy-041-tree-outline`- `kcb-easy-042-dependency-build`- `kcb-easy-043-path-normalize`- `kcb-easy-044-url-query`- `kcb-easy-045-version-sort`- `kcb-easy-046-lru-trace`- `kcb-easy-047-rate-limit`- `kcb-easy-048-priority-queue`- `kcb-easy-049-round-robin`- `kcb-easy-050-inventory-ledger`- `kcb-easy-051-bank-ledger`- `kcb-easy-052-ballot-count`- `kcb-easy-053-search-rank`- `kcb-easy-054-log-summary`- `kcb-easy-055-uptime-report`- `kcb-easy-056-segment-intersection`- `kcb-easy-057-polygon-area`- `kcb-easy-058-skyline`- `kcb-easy-059-knapsack`- `kcb-easy-060-task-selection`- `kcb-easy-061-sequence-diff`- `kcb-easy-062-finite-automaton`- `kcb-easy-063-content-manifest`- `kcb-easy-064-cellular-automaton`- `kcb-easy-065-expression-eval`
## Intermediate — 8–16B target
- `kcb-intermediate-001-word-frequency`- `kcb-intermediate-002-slug-registry`- `kcb-intermediate-003-run-length`- `kcb-intermediate-004-bracket-audit`- `kcb-intermediate-005-text-wrap`- `kcb-intermediate-006-ngram-index`- `kcb-intermediate-007-glob-filter`- `kcb-intermediate-008-edit-distance`- `kcb-intermediate-009-roman-codec`- `kcb-intermediate-010-caesar-cipher`- `kcb-intermediate-011-csv-records`- `kcb-intermediate-012-record-query`- `kcb-intermediate-013-inner-join`- `kcb-intermediate-014-group-totals`- `kcb-intermediate-015-json-flatten`- `kcb-intermediate-016-merge-patch`- `kcb-intermediate-017-json-pointer`- `kcb-intermediate-018-dedupe-records`- `kcb-intermediate-019-pivot-table`- `kcb-intermediate-020-schema-check`- `kcb-intermediate-021-interval-union`- `kcb-intermediate-022-interval-gaps`- `kcb-intermediate-023-booking-peak`- `kcb-intermediate-024-business-days`- `kcb-intermediate-025-calendar-month`- `kcb-intermediate-026-moving-average`- `kcb-intermediate-027-statistics`- `kcb-intermediate-028-histogram`- `kcb-intermediate-029-matrix-product`- `kcb-intermediate-030-polynomial`- `kcb-intermediate-031-prime-factors`- `kcb-intermediate-032-base-convert`- `kcb-intermediate-033-money-split`- `kcb-intermediate-034-invoice-total`- `kcb-intermediate-035-coin-change`- `kcb-intermediate-036-graph-reach`- `kcb-intermediate-037-shortest-path`- `kcb-intermediate-038-topological-order`- `kcb-intermediate-039-connected-components`- `kcb-intermediate-040-grid-route`- `kcb-intermediate-041-tree-outline`- `kcb-intermediate-042-dependency-build`- `kcb-intermediate-043-path-normalize`- `kcb-intermediate-044-url-query`- `kcb-intermediate-045-version-sort`- `kcb-intermediate-046-lru-trace`- `kcb-intermediate-047-rate-limit`- `kcb-intermediate-048-priority-queue`- `kcb-intermediate-049-round-robin`- `kcb-intermediate-050-inventory-ledger`- `kcb-intermediate-051-bank-ledger`- `kcb-intermediate-052-ballot-count`- `kcb-intermediate-053-search-rank`- `kcb-intermediate-054-log-summary`- `kcb-intermediate-055-uptime-report`- `kcb-intermediate-056-segment-intersection`- `kcb-intermediate-057-polygon-area`- `kcb-intermediate-058-skyline`- `kcb-intermediate-059-knapsack`- `kcb-intermediate-060-task-selection`- `kcb-intermediate-061-sequence-diff`- `kcb-intermediate-062-finite-automaton`- `kcb-intermediate-063-content-manifest`- `kcb-intermediate-064-cellular-automaton`- `kcb-intermediate-065-expression-eval`
## Hard — 16–32B target
- `kcb-hard-001-word-frequency`- `kcb-hard-002-slug-registry`- `kcb-hard-003-run-length`- `kcb-hard-004-bracket-audit`- `kcb-hard-005-text-wrap`- `kcb-hard-006-ngram-index`- `kcb-hard-007-glob-filter`- `kcb-hard-008-edit-distance`- `kcb-hard-009-roman-codec`- `kcb-hard-010-caesar-cipher`- `kcb-hard-011-csv-records`- `kcb-hard-012-record-query`- `kcb-hard-013-inner-join`- `kcb-hard-014-group-totals`- `kcb-hard-015-json-flatten`- `kcb-hard-016-merge-patch`- `kcb-hard-017-json-pointer`- `kcb-hard-018-dedupe-records`- `kcb-hard-019-pivot-table`- `kcb-hard-020-schema-check`- `kcb-hard-021-interval-union`- `kcb-hard-022-interval-gaps`- `kcb-hard-023-booking-peak`- `kcb-hard-024-business-days`- `kcb-hard-025-calendar-month`- `kcb-hard-026-moving-average`- `kcb-hard-027-statistics`- `kcb-hard-028-histogram`- `kcb-hard-029-matrix-product`- `kcb-hard-030-polynomial`- `kcb-hard-031-prime-factors`- `kcb-hard-032-base-convert`- `kcb-hard-033-money-split`- `kcb-hard-034-invoice-total`- `kcb-hard-035-coin-change`- `kcb-hard-036-graph-reach`- `kcb-hard-037-shortest-path`- `kcb-hard-038-topological-order`- `kcb-hard-039-connected-components`- `kcb-hard-040-grid-route`- `kcb-hard-041-tree-outline`- `kcb-hard-042-dependency-build`- `kcb-hard-043-path-normalize`- `kcb-hard-044-url-query`- `kcb-hard-045-version-sort`- `kcb-hard-046-lru-trace`- `kcb-hard-047-rate-limit`- `kcb-hard-048-priority-queue`- `kcb-hard-049-round-robin`- `kcb-hard-050-inventory-ledger`- `kcb-hard-051-bank-ledger`- `kcb-hard-052-ballot-count`- `kcb-hard-053-search-rank`- `kcb-hard-054-log-summary`- `kcb-hard-055-uptime-report`- `kcb-hard-056-segment-intersection`- `kcb-hard-057-polygon-area`- `kcb-hard-058-skyline`- `kcb-hard-059-knapsack`- `kcb-hard-060-task-selection`- `kcb-hard-061-sequence-diff`- `kcb-hard-062-finite-automaton`- `kcb-hard-063-content-manifest`- `kcb-hard-064-cellular-automaton`- `kcb-hard-065-expression-eval`
## Max — 60–200B target
- `kcb-max-001-word-frequency`- `kcb-max-002-slug-registry`- `kcb-max-003-run-length`- `kcb-max-004-bracket-audit`- `kcb-max-005-text-wrap`- `kcb-max-006-ngram-index`- `kcb-max-007-glob-filter`- `kcb-max-008-edit-distance`- `kcb-max-009-roman-codec`- `kcb-max-010-caesar-cipher`- `kcb-max-011-csv-records`- `kcb-max-012-record-query`- `kcb-max-013-inner-join`- `kcb-max-014-group-totals`- `kcb-max-015-json-flatten`- `kcb-max-016-merge-patch`- `kcb-max-017-json-pointer`- `kcb-max-018-dedupe-records`- `kcb-max-019-pivot-table`- `kcb-max-020-schema-check`- `kcb-max-021-interval-union`- `kcb-max-022-interval-gaps`- `kcb-max-023-booking-peak`- `kcb-max-024-business-days`- `kcb-max-025-calendar-month`- `kcb-max-026-moving-average`- `kcb-max-027-statistics`- `kcb-max-028-histogram`- `kcb-max-029-matrix-product`- `kcb-max-030-polynomial`- `kcb-max-031-prime-factors`- `kcb-max-032-base-convert`- `kcb-max-033-money-split`- `kcb-max-034-invoice-total`- `kcb-max-035-coin-change`- `kcb-max-036-graph-reach`- `kcb-max-037-shortest-path`- `kcb-max-038-topological-order`- `kcb-max-039-connected-components`- `kcb-max-040-grid-route`- `kcb-max-041-tree-outline`- `kcb-max-042-dependency-build`- `kcb-max-043-path-normalize`- `kcb-max-044-url-query`- `kcb-max-045-version-sort`- `kcb-max-046-lru-trace`- `kcb-max-047-rate-limit`- `kcb-max-048-priority-queue`- `kcb-max-049-round-robin`- `kcb-max-050-inventory-ledger`- `kcb-max-051-bank-ledger`- `kcb-max-052-ballot-count`- `kcb-max-053-search-rank`- `kcb-max-054-log-summary`- `kcb-max-055-uptime-report`- `kcb-max-056-segment-intersection`- `kcb-max-057-polygon-area`- `kcb-max-058-skyline`- `kcb-max-059-knapsack`- `kcb-max-060-task-selection`- `kcb-max-061-sequence-diff`- `kcb-max-062-finite-automaton`- `kcb-max-063-content-manifest`- `kcb-max-064-cellular-automaton`- `kcb-max-065-expression-eval`123456789101112131415161718192021222324252627282930# Evaluation protocol v1.0
1. Pin the dataset revision and evaluator version. Select a subset or all 260 tasks before generation.2. Give the agent only `prompt` (including its examples) and an empty project directory. Keep acceptance tests, the benchmark package and references outside its context and workspace. Use a consistent token, time and tool budget across the reported comparison.3. Generate one project per task. Save the complete project, model name/version, parameter count, quantization, chat template, context size, sampling settings, seed, tool access, agent version, token use, wall time and host specifications. Record interventions and retries; a manually corrected project is not a first-attempt result.4. Evaluate with the dataset's static acceptance scenarios. Do not tune submissions after seeing test failures when reporting resolve@1. A timeout, crash, protocol violation, absent entrypoint or any wrong response fails the task.5. Report tier totals, resolved counts, the complete denominator, dataset commit, evaluator version and any excluded tasks. Use `klein-bench score` to aggregate unique report files. Do not compare partial runs as complete benchmark scores.
## Candidate execution
The candidate is invoked with the evaluator's Python executable using `-E -s -S` (ignore Python environment variables and disable site-package loading). It retains its own project directory on the import path for supporting modules. Working directory is a fresh copy per scenario. A max-tier process also receives an absolute `--state-dir` path. No shell is involved in candidate launch. UTF-8 JSON is exchanged one line at a time; each response must be flushed. Normal tiers must exit with code zero on EOF. Max-tier sessions are killed after their final response and are not given graceful shutdown time.
A session is limited to 10 seconds total wall time, including startup, all its requests and normal EOF handling. The runner caps stdout at 1 MiB and retains at most 8 KiB of stderr diagnostics. A submission is limited to 2,000 files and 20 MB of source/data. `.git`, virtual environments, node_modules, caches and credential files are not copied. Symlink files and special files are rejected; symlink directories are not traversed. Process-group cleanup also applies after normal termination to remove surviving same-group children. These limits are evaluator limits, not security isolation or protection from all memory/disk exhaustion.
Each request has one expected response. Malformed input lines are literal strings in the scenario request list; regular requests are JSON objects. Each scenario has `name` and `sessions`; each session has equally sized nonempty `requests` and `expected` lists. Acceptance tests live only in the parent evaluator. A source hash identifies the copied submission; the dataset SHA-256 manifest identifies test data.
## Contract coverage
- **All tiers:** valid cases, Unicode, deterministic domain generation, each missing required field, malformed JSON, malformed envelopes, unknown commands, post-error recovery and tier-specific unavailable operations.- **Intermediate+:** revision increments, deep values/null, repeated replacement, evaluation without mutation, deletion failures, prefix matching and sorted listing.- **Hard+:** compare-and-swap conflicts and type checks, atomic batch success/failure, nested forbidden operations, maximum batch size, transaction nesting limits, missing transactions, revision/history restoration and nested commit followed by outer rollback.- **Max:** force-kill restart of writes/deletes and outer commits, discarded open transactions and nested commits, key pagination, history cursor/limits, replayed requests after restart, cached revision-conditional retries, token conflicts and tokens forgotten after failure/rollback.
The protocol in every task prompt is the normative interface. All layers are cumulative. A tier's task differs from another tier of the same family through required project behavior rather than an artificial increase in numerical input bounds.
## Interpretation
Targets 2–8B, 8–16B, 16–32B and 60–200B are unvalidated. Shared service functionality may make implementation reuse easier than a collection of independent projects. Reset agent memory and workspaces between tasks; disclose whether the same agent has already seen other tasks or tiers. Score differences can reflect Python familiarity, tool quality, quantization and generation budgets as well as parameter count.
The public source contains fixed evaluation cases and oracles. An unrestricted host agent can discover these files or fetch them from the internet. The benchmark does not claim to enforce test secrecy or prevent deliberate cheating. Controlled experiments must enforce their own access policy without exposing evaluator data to the agent. The default runner is for trusted local experiments.123"""Klein-Code-Bench: from-scratch project generation benchmark."""
__version__ = "0.1.0"123from .cli import main
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Reproducibly compile contracts and static acceptance suites into HF JSONL."""
from __future__ import annotations
import hashlibimport jsonfrom pathlib import Path
from .catalog import FAMILIESfrom .protocol import PROTOCOL_VERSION, TIERS, contractfrom .reference.domains import solvefrom .scenarios import expected_scenarios
def dumps(value): return json.dumps( value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False, )
def build(destination=None): root = Path(destination) if destination else Path(__file__).parent / "data" root.mkdir(parents=True, exist_ok=True) counts, hashes, assertions = {}, {}, {} for tier, models in TIERS.items(): rows = [] for index, f in enumerate(FAMILIES.values(), 1): # Hand-written goldens are independent of the oracle code. if solve(f.slug, f.inputs[0]) != f.golden: raise ValueError(f"Golden mismatch: {f.slug}") tests = expected_scenarios(f.slug, tier) examples = [ { "request": {"op": "solve", "input": x}, "response": {"ok": True, "result": solve(f.slug, x)}, } for x in f.inputs[:2] ] task_id = f"kcb-{tier}-{index:03d}-{f.slug.replace('_', '-')}" title = ( f"{f.slug.replace('_', ' ').title()} — " + { "easy": "CLI project", "intermediate": "workspace service", "hard": "transactional service", "max": "durable service", }[tier] ) prompt = ( f"# {title}\n\n" + contract(tier) + "\nDomain contract:\n" + f.specification + "\nRequired input fields: " + ", ".join(f.required) + ".\n\nExamples:\n" + json.dumps(examples, indent=2, ensure_ascii=False) ) rows.append( { "task_id": task_id, "subset": tier, "family": f.slug, "title": title, "category": f.category, "target_model_parameters": models, "language": "python", "entrypoint": "main.py", "protocol_version": PROTOCOL_VERSION, "prompt": prompt, "timeout_seconds": 10, "public_tests": dumps(examples), "acceptance_tests": dumps(tests), "num_scenarios": len(tests), "num_assertions": sum( len(s["expected"]) for t in tests for s in t["sessions"] ), } ) file = root / f"{tier}.jsonl" file.write_text("".join(dumps(r) + "\n" for r in rows), encoding="utf-8") counts[tier] = len(rows) assertions[tier] = sum(r["num_assertions"] for r in rows) hashes[file.name] = hashlib.sha256(file.read_bytes()).hexdigest() manifest = { "benchmark": "Klein-Code-Bench", "version": "0.1.0", "protocol_version": PROTOCOL_VERSION, "tasks": 260, "families": 65, "counts": counts, "assertions": assertions, "sha256": hashes, "seed": 1729, "difficulty_calibrated": False, } (root / "manifest.json").write_text( json.dumps(manifest, indent=2) + "\n", encoding="utf-8" ) return manifest
if __name__ == "__main__": print(json.dumps(build(), indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194"""Hand-authored project contracts and domain fixtures; no downloaded problems."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)class Family: slug: str category: str required: tuple[str, ...] specification: str inputs: tuple[dict, ...] golden: object
FAMILIES: dict[str, Family] = {}
def add(slug, category, required, specification, inputs, golden): assert slug not in FAMILIES FAMILIES[slug] = Family( slug, category, tuple(required.split()), specification, tuple(inputs), golden )
add( "word_frequency", "text", "text", "Input: text (string). Tokenize maximal ASCII [a-z0-9]+ runs after lowercasing. Return [{word,count}], sorted by decreasing count then ascending word. Non-ASCII letters are separators.", [ {"text": "Red blue RED! 42"}, {"text": ""}, {"text": "é É 中文"}, {"text": "a_a a-b"}, {"text": "12 012 12\nX"}, {"text": "z a z b a b"}, ], [ {"word": "red", "count": 2}, {"word": "42", "count": 1}, {"word": "blue", "count": 1}, ],)add( "slug_registry", "text", "titles", 'Input: titles (list of strings). Lowercase each, replace maximal runs outside ASCII a-z0-9 with a hyphen, strip hyphens, use "item" if empty. Assign in input order. If already used, append -2, -3, ... to the base until globally unique. Return slugs.', [ {"titles": ["Hello World", "hello world", "hello-world-2", ""]}, {"titles": []}, {"titles": ["!!!", "", "ITEM"]}, {"titles": ["a", "a-2", "a", "a"]}, {"titles": ["Ünicode", " A___B "]}, {"titles": ["1", "1", "1-2"]}, ], ["hello-world", "hello-world-2", "hello-world-2-2", "item"],)add( "run_length", "text", "text", "Input: text (string). Return [character,count] pairs for consecutive identical Unicode code points; retain order and include whitespace. Empty text produces [].", [ {"text": "aaabbcaa"}, {"text": ""}, {"text": "😀😀é"}, {"text": " \n\n "}, {"text": "abcd"}, {"text": "1111000"}, ], [["a", 3], ["b", 2], ["c", 1], ["a", 2]],)add( "bracket_audit", "text", "text", "Input: text. Audit (), [], {} ignoring all other code points. Return {balanced,position}. On first unmatched/mismatched closing bracket, position is its zero-based code-point index. If openings remain at EOF, position is the most recent unmatched opening. Balanced input has position:null.", [ {"text": "a([)]"}, {"text": ""}, {"text": "abc"}, {"text": "([]{})"}, {"text": "(("}, {"text": "é]"}, {"text": "[(]"}, ], {"balanced": False, "position": 3},)add( "text_wrap", "text", "text width", "Input: text and positive integer width. Split on Unicode whitespace. Greedily pack words into lines with single spaces; a next word fits iff length including separating space <= width. Never split a long word. Return lines without empty lines.", [ {"text": "one two three four", "width": 7}, {"text": "", "width": 1}, {"text": "abcdef a", "width": 2}, {"text": " a\t b\n c ", "width": 3}, {"text": "éé a", "width": 2}, {"text": "a b c", "width": 20}, ], ["one two", "three", "four"],)add( "ngram_index", "text", "tokens n", "Input: tokens (strings), n (positive integer). Return [{tokens,positions}] for each distinct contiguous n-gram, sorted lexicographically by token sequence. Positions are ascending zero-based starting indices. n greater than length produces [].", [ {"tokens": ["a", "b", "a", "b"], "n": 2}, {"tokens": [], "n": 1}, {"tokens": ["x"], "n": 2}, {"tokens": ["b", "a", "b"], "n": 1}, {"tokens": ["", "a", ""], "n": 2}, {"tokens": ["x", "x", "x"], "n": 3}, ], [ {"tokens": ["a", "b"], "positions": [0, 2]}, {"tokens": ["b", "a"], "positions": [1]}, ],)add( "glob_filter", "text", "paths pattern", "Input: paths (strings), pattern. Return sorted unique matches using case-sensitive shell glob semantics: * matches any run including /, ? one character, [abc] a class, [!abc] a negated class. Python fnmatch.fnmatchcase semantics apply. No filesystem access.", [ {"paths": ["a.py", "B.py", "a.txt", "a.py", "x/a.py"], "pattern": "*.py"}, {"paths": [], "pattern": "*"}, {"paths": ["a", "b", "c"], "pattern": "[!b]"}, {"paths": ["ab", "a", "a/b"], "pattern": "a?"}, {"paths": ["A", "a"], "pattern": "a"}, {"paths": ["", "a"], "pattern": "*"}, ], ["B.py", "a.py", "x/a.py"],)add( "edit_distance", "text", "a b", "Input: strings a,b of <=200 code points. Return Levenshtein distance with unit insertion, deletion and substitution costs. Compare Unicode code points, case-sensitive.", [ {"a": "kitten", "b": "sitting"}, {"a": "", "b": ""}, {"a": "", "b": "abc"}, {"a": "ab", "b": "ba"}, {"a": "é", "b": "e"}, {"a": "banana", "b": "banana"}, ], 3,)add( "roman_codec", "text", "number", "Input: integer number in 1..3999. Return canonical uppercase Roman numeral using subtractive pairs IV,IX,XL,XC,CD,CM.", [ {"number": 1994}, {"number": 1}, {"number": 4}, {"number": 9}, {"number": 3999}, {"number": 944}, {"number": 58}, ], "MCMXCIV",)add( "caesar_cipher", "text", "text shift", "Input: text and integer shift. Rotate only ASCII letters by shift modulo 26, preserving case. All other characters unchanged.", [ {"text": "Az-z! 9", "shift": 1}, {"text": "", "shift": 0}, {"text": "Abc", "shift": -1}, {"text": "é中", "shift": 13}, {"text": "XYZ abc", "shift": 52}, {"text": "aZ", "shift": -53}, ], "Ba-a! 9",)add( "csv_records", "data", "csv", "Input: csv (string). Parse comma-separated CSV with double-quoted fields, doubled quote escaping and quoted newlines (Python csv.reader dialect excel). First row is unique nonempty header names. Subsequent rows have the same width. Return objects in source order. Empty document returns []. Blank data rows and malformed CSV are out of scope.", [ {"csv": "name,n\na,1\nb,2\n"}, {"csv": ""}, {"csv": "x,y\n"}, {"csv": 'a,b\n"hi,there","say ""yes"""\n'}, {"csv": 'x\n"a\nb"\n'}, {"csv": "x,y\r\na,\r\n"}, ], [{"name": "a", "n": "1"}, {"name": "b", "n": "2"}],)add( "record_query", "data", "rows where select", "Input: rows (objects), where (object), select (list of field names). Keep rows containing every where field with an equal JSON value. Return selected fields for each in source order; missing selected fields become null. Values contain no booleans compared with numbers.", [ { "rows": [{"a": 1, "b": "x"}, {"a": 2}, {"a": 1}], "where": {"a": 1}, "select": ["b"], }, {"rows": [], "where": {}, "select": []}, {"rows": [{"a": None}, {}], "where": {"a": None}, "select": ["a"]}, {"rows": [{"x": 1}], "where": {}, "select": []}, {"rows": [{"x": [1]}, {"x": [2]}], "where": {"x": [1]}, "select": ["x"]}, ], [{"b": "x"}, {"b": None}],)add( "inner_join", "data", "left right key", "Input: left,right (lists of objects), key (string). Return [{left,right}] for all pairs with key present on both sides and equal JSON values. Order by left source index then right source index; duplicates multiply. Null keys can match. No boolean-versus-number comparisons.", [ { "left": [{"id": 1}, {"id": 2}], "right": [{"id": 2}, {"id": 2, "x": 3}], "key": "id", }, {"left": [], "right": [], "key": "k"}, {"left": [{}], "right": [{}], "key": "k"}, {"left": [{"k": None}], "right": [{"k": None}], "key": "k"}, {"left": [{"k": 1}, {"k": 1}], "right": [{"k": 1}], "key": "k"}, ], [ {"left": {"id": 2}, "right": {"id": 2}}, {"left": {"id": 2}, "right": {"id": 2, "x": 3}}, ],)add( "group_totals", "data", "rows group value", "Input: rows (objects), group,value (field names). Each row has a string group value and integer numeric value. Return [{key,count,sum}] sorted by key. Empty rows returns [].", [ { "rows": [{"g": "b", "v": 2}, {"g": "a", "v": 3}, {"g": "b", "v": -1}], "group": "g", "value": "v", }, {"rows": [], "group": "g", "value": "v"}, {"rows": [{"g": "", "v": 0}], "group": "g", "value": "v"}, {"rows": [{"g": "é", "v": 9}, {"g": "A", "v": -9}], "group": "g", "value": "v"}, ], [{"key": "a", "count": 1, "sum": 3}, {"key": "b", "count": 2, "sum": 1}],)add( "json_flatten", "data", "value", 'Input: arbitrary JSON value. Return an object mapping JSON Pointer paths to leaves. Root path is "". Escape ~ as ~0 and / as ~1; array indices are decimal. Empty objects/arrays count as leaves. Nonempty containers do not produce their own entries.', [ {"value": {"a": [1, {"x/y": None}], "b": {}}}, {"value": []}, {"value": None}, {"value": {"~": {"/": 2}, "": 3}}, {"value": [False, {}, []]}, ], {"/a/0": 1, "/a/1/x~1y": None, "/b": {}},)add( "merge_patch", "data", "target patch", "Input: target,patch (JSON values). Apply JSON Merge Patch: a nonobject patch replaces the target. An object patch treats a nonobject target as {}; null-valued members remove keys; other members recursively merge. Arrays replace wholesale. Return resulting value.", [ { "target": {"a": 1, "b": {"c": 2, "d": 3}}, "patch": {"a": None, "b": {"c": 9}}, }, {"target": {}, "patch": None}, {"target": [1], "patch": {"x": 2}}, {"target": {"a": [1]}, "patch": {"a": [2, 3]}}, {"target": 4, "patch": {}}, {"target": {"a": 1}, "patch": {"z": None}}, ], {"b": {"c": 9, "d": 3}},)add( "json_pointer", "data", "value pointer", "Input: value (JSON), pointer (empty or starting /, valid ~0/~1 escapes). Resolve object keys or array indices. Array tokens must be 0 or a nonzero decimal digit followed by decimal digits (no leading zero, sign, or -). Return {found:true,value:...}; missing keys, noncontainers or out-of-range indices return {found:false,value:null}. Empty pointer returns root.", [ {"value": {"a/b": [7]}, "pointer": "/a~1b/0"}, {"value": None, "pointer": ""}, {"value": [1], "pointer": "/01"}, {"value": {"": {"~": 2}}, "pointer": "//~0"}, {"value": [1], "pointer": "/9"}, {"value": {"a": None}, "pointer": "/a/x"}, {"value": [], "pointer": "/-"}, ], {"found": True, "value": 7},)add( "dedupe_records", "data", "rows keys", "Input: rows (objects), keys (field names). Retain first row for each distinct tuple of requested field values; missing fields equal null. Structural JSON equality ignores object key order. Keep source order. Boolean and numeric key values are not mixed.", [ {"rows": [{"id": 1, "x": "a"}, {"id": 1, "x": "b"}, {"id": 2}], "keys": ["id"]}, {"rows": [], "keys": []}, {"rows": [{"x": 1}, {"x": 2}], "keys": []}, {"rows": [{}, {"x": None}], "keys": ["x"]}, {"rows": [{"x": {"a": 1, "b": 2}}, {"x": {"b": 2, "a": 1}}], "keys": ["x"]}, ], [{"id": 1, "x": "a"}, {"id": 2}],)add( "pivot_table", "data", "rows row column value", "Input: rows, row,column,value field names. Row/column values are strings; numeric values are integers. Return {rows:sorted row labels,columns:sorted column labels,values:2D sums}, filling missing cells with 0. Empty input yields three empty arrays.", [ { "rows": [ {"r": "a", "c": "x", "v": 2}, {"r": "b", "c": "y", "v": 3}, {"r": "a", "c": "x", "v": -1}, ], "row": "r", "column": "c", "value": "v", }, {"rows": [], "row": "r", "column": "c", "value": "v"}, {"rows": [{"r": "", "c": "", "v": 0}], "row": "r", "column": "c", "value": "v"}, { "rows": [{"r": "z", "c": "b", "v": -5}, {"r": "a", "c": "a", "v": 1}], "row": "r", "column": "c", "value": "v", }, ], {"rows": ["a", "b"], "columns": ["x", "y"], "values": [[1, 0], [0, 3]]},)add( "schema_check", "data", "schema value", 'Input: schema object maps field names to {type,required}; value is an object. Types: string,integer,number,boolean,array,object,null. Booleans are neither integers nor numbers. For each schema field in lexical order, report {field,error:"required"} if missing and required, or {field,error:"type"} if present with wrong type. Optional missing fields and extra fields are ignored. No recursive validation.', [ { "schema": { "a": {"type": "integer", "required": True}, "b": {"type": "string", "required": True}, }, "value": {"a": True}, }, {"schema": {}, "value": {"a": 1}}, {"schema": {"x": {"type": "null", "required": False}}, "value": {}}, {"schema": {"x": {"type": "number", "required": True}}, "value": {"x": 1.5}}, {"schema": {"x": {"type": "array", "required": True}}, "value": {"x": []}}, ], [{"field": "a", "error": "type"}, {"field": "b", "error": "required"}],)add( "interval_union", "intervals", "intervals", "Input: intervals, list of [start,end] integer pairs with start<=end. Return sorted merged intervals, combining overlaps and touching endpoints. Retain isolated zero-length intervals.", [ {"intervals": [[5, 7], [1, 3], [3, 6], [9, 9]]}, {"intervals": []}, {"intervals": [[0, 0], [0, 0]]}, {"intervals": [[-4, -1], [-2, 3]]}, {"intervals": [[1, 10], [2, 3], [12, 14]]}, ], [[1, 7], [9, 9]],)add( "interval_gaps", "intervals", "intervals bounds", "Input: intervals ([a,b] with a<=b), bounds [low,high] with low<=high. Return positive-length gaps in [low,high] after unioning and clipping occupied intervals. Touching endpoints do not make gaps. Sorted ascending; no zero-length results.", [ {"intervals": [[2, 4], [6, 9]], "bounds": [0, 10]}, {"intervals": [], "bounds": [0, 5]}, {"intervals": [[-3, 8]], "bounds": [0, 5]}, {"intervals": [[8, 9], [-3, -1]], "bounds": [0, 5]}, {"intervals": [[2, 2]], "bounds": [0, 5]}, {"intervals": [], "bounds": [2, 2]}, ], [[0, 2], [4, 6], [9, 10]],)add( "booking_peak", "intervals", "bookings", "Input: bookings ([start,end] integer pairs, start<=end). Intervals are half-open; zero-length bookings ignored. Return {peak,at} for maximum simultaneous active bookings and earliest timestamp attaining that maximum. Empty effective input: {peak:0,at:null}. Endings at t happen before starts at t.", [ {"bookings": [[1, 4], [2, 3], [3, 5]]}, {"bookings": []}, {"bookings": [[1, 1]]}, {"bookings": [[0, 1], [1, 2]]}, {"bookings": [[-2, 2], [-2, 2]]}, ], {"peak": 2, "at": 2},)add( "business_days", "calendar", "start end holidays", "Input: start,end ISO dates (start<=end) and holidays (ISO dates). Return all Monday-Friday dates in [start,end) excluding holidays, ascending. Duplicate holidays have no additional effect. Dates are valid in years 1900..2100, range <=400 days.", [ {"start": "2024-02-28", "end": "2024-03-04", "holidays": ["2024-02-29"]}, {"start": "2024-01-01", "end": "2024-01-01", "holidays": []}, {"start": "2024-01-06", "end": "2024-01-08", "holidays": []}, { "start": "2024-12-30", "end": "2025-01-03", "holidays": ["2025-01-01", "2025-01-01"], }, {"start": "2000-02-28", "end": "2000-03-02", "holidays": []}, ], ["2024-02-28", "2024-03-01"],)add( "calendar_month", "calendar", "year month", "Input: year (1900..2100), month (1..12). Return weeks as arrays of seven day numbers, Monday first. Use 0 for days outside the month; include only weeks intersecting this month.", [ {"year": 2021, "month": 2}, {"year": 2024, "month": 2}, {"year": 1900, "month": 2}, {"year": 2023, "month": 1}, {"year": 2000, "month": 12}, ], [ [1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28], ],)add( "moving_average", "numeric", "values window", "Input: values (finite numbers), window (positive integer). Return arithmetic means for all contiguous full windows. Empty input or window>length gives [].", [ {"values": [1, 2, 3, 4], "window": 2}, {"values": [], "window": 1}, {"values": [1], "window": 3}, {"values": [-2, 0, 2], "window": 1}, {"values": [1, 2], "window": 2}, {"values": [0.1, 0.2, 0.3], "window": 2}, ], [1.5, 2.5, 3.5],)add( "statistics", "numeric", "values", "Input: values (finite numbers). Return {count,min,max,mean,median,variance}. Variance is population variance (divide by n); even-length median is mean of middle two. Empty values: count=0 and all other fields null.", [ {"values": [1, 2, 3, 4]}, {"values": []}, {"values": [7]}, {"values": [-2, -2, 2, 2]}, {"values": [0.1, 0.2, 0.3]}, {"values": [9, 1, 3]}, ], {"count": 4, "min": 1, "max": 4, "mean": 2.5, "median": 2.5, "variance": 1.25},)add( "histogram", "numeric", "values edges", "Input: finite numeric values and strictly increasing edges (>=2). Bins are [edge[i],edge[i+1]); values below first edge underflow, values >=last edge overflow. Return {counts,underflow,overflow}.", [ {"values": [-1, 0, 1, 2, 3], "edges": [0, 1, 3]}, {"values": [], "edges": [0, 1]}, {"values": [0, 1, 2], "edges": [0, 1, 2]}, {"values": [-5, -3, -1], "edges": [-4, -2, 0]}, {"values": [0.1, 0.2], "edges": [0, 0.2, 1]}, ], {"counts": [1, 2], "underflow": 1, "overflow": 1},)add( "matrix_product", "numeric", "a b", "Input: a (m by n), b (n by p), nonempty rectangular integer matrices of compatible dimensions, each dimension <=20. Return matrix product.", [ {"a": [[1, 2], [3, 4]], "b": [[5], [6]]}, {"a": [[0]], "b": [[9]]}, {"a": [[-2, 3, 1]], "b": [[1, 0], [0, 1], [2, 2]]}, {"a": [[1, 0], [0, 1]], "b": [[3, 4], [5, 6]]}, {"a": [[2], [3]], "b": [[4, 5]]}, ], [[17], [39]],)add( "polynomial", "numeric", "coefficients points", "Input: integer coefficients in ascending power order (c0,c1,...) and integer evaluation points. Return values at each point. Empty coefficients denote zero polynomial.", [ {"coefficients": [1, 2, 3], "points": [0, 1, -1, 2]}, {"coefficients": [], "points": [1, 0]}, {"coefficients": [7], "points": []}, {"coefficients": [0, 0, 1], "points": [-3, 3]}, {"coefficients": [-1, 1], "points": [100, -100]}, ], [1, 6, 2, 17],)add( "prime_factors", "numeric", "number", "Input: integer number in 1..10000000. Return [prime,exponent] pairs in ascending prime order; 1 returns [].", [ {"number": 360}, {"number": 1}, {"number": 2}, {"number": 9973}, {"number": 65536}, {"number": 99991}, ], [[2, 3], [3, 2], [5, 1]],)add( "base_convert", "numeric", "digits from_base to_base", 'Input: digits (valid integer representation, optional leading -, case-insensitive ASCII), from_base,to_base (2..36). Convert to lowercase digits 0-9a-z with no leading zero or plus; zero is "0". Magnitude <=2^100.', [ {"digits": "ff", "from_base": 16, "to_base": 2}, {"digits": "-0", "from_base": 10, "to_base": 36}, {"digits": "-101", "from_base": 2, "to_base": 10}, {"digits": "ZZ", "from_base": 36, "to_base": 16}, {"digits": "00042", "from_base": 10, "to_base": 10}, {"digits": "10000000000000000", "from_base": 16, "to_base": 10}, ], "11111111",)add( "money_split", "numeric", "amount weights", "Input: nonnegative integer amount in cents, nonempty nonnegative integer weights with positive sum. Allocate by largest remainder: floor exact proportional shares, then give leftover cents to greatest fractional remainders, ties to lowest index. Return integer shares totaling amount.", [ {"amount": 10, "weights": [1, 1, 1]}, {"amount": 0, "weights": [1]}, {"amount": 2, "weights": [0, 1, 1]}, {"amount": 7, "weights": [1, 2]}, {"amount": 1, "weights": [3, 3, 3]}, {"amount": 1000001, "weights": [9, 1]}, ], [4, 3, 3],)add( "invoice_total", "numeric", "items tax_rate", "Input: items [{price:nonnegative decimal string,quantity:nonnegative integer}], tax_rate (nonnegative decimal string). Sum exact price*quantity then round subtotal to cents using ROUND_HALF_UP. Tax = rounded subtotal * tax_rate, rounded half-up to cents. Total=subtotal+tax. Return {subtotal,tax,total} as strings with exactly two decimal places; do not use binary floating point for monetary arithmetic.", [ {"items": [{"price": "0.335", "quantity": 3}], "tax_rate": "0.20"}, {"items": [], "tax_rate": "0"}, {"items": [{"price": "0.05", "quantity": 1}], "tax_rate": "0.1"}, {"items": [{"price": "1.005", "quantity": 1}], "tax_rate": "0"}, { "items": [ {"price": "19.99", "quantity": 2}, {"price": "3.50", "quantity": 3}, ], "tax_rate": "0.075", }, ], {"subtotal": "1.01", "tax": "0.20", "total": "1.21"},)add( "coin_change", "numeric", "coins amount", "Input: coins (positive integer denominations, duplicates allowed), amount (0..10000). Unlimited supply of each coin. Return minimum number of coins or null if impossible. Empty coins can make only zero.", [ {"coins": [1, 3, 4], "amount": 6}, {"coins": [], "amount": 0}, {"coins": [2], "amount": 3}, {"coins": [2, 2, 5], "amount": 10}, {"coins": [], "amount": 4}, {"coins": [7, 3], "amount": 11}, ], 2,)add( "graph_reach", "graphs", "nodes edges start", "Input: nodes (unique strings), edges ([from,to] directed pairs, endpoints in nodes), start (in nodes). Return sorted nodes reachable from start including itself. Allow cycles, self-edges and duplicate edges; <=100 nodes.", [ { "nodes": ["a", "b", "c", "d"], "edges": [["a", "b"], ["b", "c"]], "start": "a", }, {"nodes": ["a"], "edges": [], "start": "a"}, {"nodes": ["a", "b"], "edges": [["b", "a"]], "start": "a"}, { "nodes": ["a", "b"], "edges": [["a", "b"], ["b", "a"], ["a", "b"]], "start": "b", }, {"nodes": ["x", "y"], "edges": [["x", "x"]], "start": "x"}, ], ["a", "b", "c"],)add( "shortest_path", "graphs", "nodes edges start", "Input: nodes (unique strings), edges ([from,to,nonnegative integer weight], directed), start. Endpoints and start are in nodes. Return object mapping each node to shortest distance or null if unreachable. Cycles, parallel edges, zero weights allowed; <=100 nodes.", [ { "nodes": ["a", "b", "c", "d"], "edges": [["a", "b", 5], ["a", "c", 1], ["c", "b", 1]], "start": "a", }, {"nodes": ["a"], "edges": [], "start": "a"}, {"nodes": ["a", "b"], "edges": [["b", "a", 1]], "start": "a"}, { "nodes": ["a", "b", "c"], "edges": [["a", "b", 0], ["b", "a", 0], ["b", "c", 2], ["a", "c", 9]], "start": "a", }, {"nodes": ["a", "b"], "edges": [["a", "b", 8], ["a", "b", 2]], "start": "a"}, ], {"a": 0, "b": 2, "c": 1, "d": None},)add( "topological_order", "graphs", "nodes edges", "Input: unique string nodes, directed edges [from,to]. Return topological order choosing lexicographically smallest currently available node each step, or null on any cycle. Duplicate edges allowed and do not change dependencies. Endpoints in nodes; <=100 nodes.", [ {"nodes": ["c", "a", "b"], "edges": [["a", "c"]]}, {"nodes": [], "edges": []}, {"nodes": ["a", "b"], "edges": [["a", "b"], ["b", "a"]]}, {"nodes": ["a"], "edges": [["a", "a"]]}, {"nodes": ["a", "b"], "edges": [["a", "b"], ["a", "b"]]}, {"nodes": ["z", "a", "b"], "edges": []}, ], ["a", "b", "c"],)add( "connected_components", "graphs", "nodes edges", "Input: unique string nodes, undirected edges [a,b], endpoints in nodes. Return components as sorted lists of nodes, ordered by each component first node. Include isolated vertices; allow duplicate edges and self-loops.", [ {"nodes": ["d", "c", "b", "a"], "edges": [["a", "b"], ["c", "d"]]}, {"nodes": [], "edges": []}, {"nodes": ["a"], "edges": [["a", "a"]]}, {"nodes": ["z", "a"], "edges": []}, {"nodes": ["a", "b", "c"], "edges": [["a", "b"], ["b", "a"], ["b", "c"]]}, ], [["a", "b"], ["c", "d"]],)add( "grid_route", "graphs", "grid start end", "Input: grid (nonempty equal-length strings containing . or #), start,end ([row,column], valid coordinates). Move one cell up/down/left/right through . cells. Return shortest step count, or null if blocked/unreachable, including blocked start or end. Grid <=50x50.", [ {"grid": ["...", ".#.", "..."], "start": [0, 0], "end": [2, 2]}, {"grid": ["."], "start": [0, 0], "end": [0, 0]}, {"grid": ["#"], "start": [0, 0], "end": [0, 0]}, {"grid": [".#."], "start": [0, 0], "end": [0, 2]}, {"grid": ["..", ".."], "start": [1, 1], "end": [0, 0]}, ], 4,)add( "tree_outline", "graphs", "nodes", "Input: nodes [{id:unique string,parent:string or null}], forming a forest (all nonnull parents exist, no cycles), <=100 nodes. Return preorder [{id,depth}], roots and each sibling list sorted by id, roots depth 0.", [ { "nodes": [ {"id": "b", "parent": "a"}, {"id": "a", "parent": None}, {"id": "c", "parent": None}, ] }, {"nodes": []}, {"nodes": [{"id": "x", "parent": None}]}, { "nodes": [ {"id": "c", "parent": "b"}, {"id": "b", "parent": "a"}, {"id": "a", "parent": None}, ] }, {"nodes": [{"id": "z", "parent": None}, {"id": "a", "parent": None}]}, ], [{"id": "a", "depth": 0}, {"id": "b", "depth": 1}, {"id": "c", "depth": 0}],)add( "dependency_build", "graphs", "dependencies targets", "Input: dependencies (object of string node -> dependency string list), targets (strings). Every referenced name exists. DFS each distinct target in sorted order, visit dependencies in sorted order, append each node after dependencies once. Return build order; return null on a cycle reachable from a target. Unreachable cycles ignored; <=100 nodes.", [ { "dependencies": { "app": ["lib", "cfg"], "lib": ["cfg"], "cfg": [], "unused": [], }, "targets": ["app"], }, {"dependencies": {}, "targets": []}, {"dependencies": {"a": ["b"], "b": ["a"]}, "targets": ["a"]}, {"dependencies": {"a": [], "x": ["x"]}, "targets": ["a"]}, {"dependencies": {"a": [], "b": ["a"]}, "targets": ["b", "a", "b"]}, ], ["cfg", "lib", "app"],)add( "path_normalize", "systems", "paths", "Input: paths (POSIX path strings). Treat all paths as rooted at /. Remove repeated / and . segments; .. pops a segment if available and is ignored at root. Preserve other segment code points and backslashes literally. Return absolute paths without trailing / except root. No filesystem access.", [ {"paths": ["a/../b//c/", "/../../x", ""]}, {"paths": []}, {"paths": ["/", ".", "..", "a/./b"]}, {"paths": ["a\\b/c", "/a/.../b"]}, {"paths": ["é/../中", "a/../../"]}, ], ["/b/c", "/x", "/"],)add( "url_query", "systems", "query", "Input: query string (without leading ?). Parse &-separated key/value pairs using first =, retain blank values and bare keys, decode + as space and percent-encoded UTF-8. Return object of decoded keys -> lists of values in source order. Empty segments ignored. Python urllib.parse.parse_qsl with keep_blank_values=True semantics.", [ {"query": "a=1&a=2&x=hello+world&empty="}, {"query": ""}, {"query": "flag&&=x"}, {"query": "q=%C3%A9&a%2Fb=x%3Dy"}, {"query": "x=%2B&x=+&x=a=b"}, ], {"a": ["1", "2"], "x": ["hello world"], "empty": [""]},)add( "version_sort", "systems", "versions", "Input: versions valid MAJOR.MINOR.PATCH optionally -prerelease.identifiers; no build metadata, numeric components/identifiers have no leading zeros. Sort by semantic version precedence: numeric core, prerelease before release, numeric prerelease identifiers numerically and before nonnumeric; nonnumeric ASCII lexical; shorter equal prefix first. Stable equal versions retained.", [ {"versions": ["1.0.0", "1.0.0-beta", "1.0.0-alpha.10", "1.0.0-alpha.2"]}, {"versions": []}, {"versions": ["2.0.0", "10.0.0", "1.9.9"]}, {"versions": ["1.0.0-a", "1.0.0-1", "1.0.0-a.1", "1.0.0"]}, {"versions": ["1.0.0", "1.0.0"]}, ], ["1.0.0-alpha.2", "1.0.0-alpha.10", "1.0.0-beta", "1.0.0"],)add( "lru_trace", "systems", "capacity accesses", "Input: nonnegative capacity and accesses (string keys). Simulate initially empty LRU cache. Hit moves key to most recent. Miss inserts and evicts oldest if full. Capacity 0 stores nothing. Return {hits,misses,keys}, keys oldest to newest.", [ {"capacity": 2, "accesses": ["a", "b", "a", "c", "b"]}, {"capacity": 0, "accesses": ["a", "a"]}, {"capacity": 3, "accesses": []}, {"capacity": 1, "accesses": ["a", "a", "b"]}, {"capacity": 9, "accesses": ["x", "y", "x"]}, ], {"hits": 1, "misses": 4, "keys": ["c", "b"]},)add( "rate_limit", "systems", "events window limit", "Input: events [{key:string,time:integer}] in nondecreasing time order, positive integer window, nonnegative limit. Per key, accept if fewer than limit previously accepted events have timestamps in (time-window,time]. Rejected events do not count. Process same-time events in input order. Return boolean decisions.", [ { "events": [{"key": "a", "time": t} for t in [0, 0, 1, 5]], "window": 5, "limit": 2, }, {"events": [], "window": 1, "limit": 1}, {"events": [{"key": "x", "time": 0}], "window": 1, "limit": 0}, { "events": [ {"key": "a", "time": 0}, {"key": "b", "time": 0}, {"key": "a", "time": 1}, ], "window": 1, "limit": 1, }, { "events": [{"key": "a", "time": t} for t in [-3, -2, -1, 0]], "window": 2, "limit": 1, }, ], [True, True, False, True],)add( "priority_queue", "systems", "events", 'Input: events of {op:"push",priority:integer,value:JSON} or {op:"pop"}. Smaller priority first, FIFO ties. Pop empty produces null. Return {popped:list of pop results,remaining:list of queued values in pop order}.', [ { "events": [ {"op": "push", "priority": 2, "value": "a"}, {"op": "push", "priority": 1, "value": "b"}, {"op": "pop"}, ] }, {"events": []}, {"events": [{"op": "pop"}, {"op": "pop"}]}, { "events": [ {"op": "push", "priority": 0, "value": {"x": 1}}, {"op": "push", "priority": 0, "value": None}, {"op": "pop"}, ] }, {"events": [{"op": "push", "priority": -1, "value": 3}]}, ], {"popped": ["b"], "remaining": ["a"]},)add( "round_robin", "systems", "jobs quantum", "Input: jobs [{id:unique string,duration:positive integer}], positive integer quantum. All jobs arrive at 0 in input order. Repeatedly run first job min(remaining,quantum) time, append unfinished job to end. Return {slices:[{id,start,end}],completion:{id:completion time}}. Empty jobs gives empty structures.", [ { "jobs": [{"id": "a", "duration": 3}, {"id": "b", "duration": 2}], "quantum": 2, }, {"jobs": [], "quantum": 1}, {"jobs": [{"id": "a", "duration": 1}], "quantum": 10}, { "jobs": [{"id": "a", "duration": 2}, {"id": "b", "duration": 1}], "quantum": 1, }, {"jobs": [{"id": "x", "duration": 4}], "quantum": 2}, ], { "slices": [ {"id": "a", "start": 0, "end": 2}, {"id": "b", "start": 2, "end": 4}, {"id": "a", "start": 4, "end": 5}, ], "completion": {"b": 4, "a": 5}, },)add( "inventory_ledger", "business", "events", "Input: events [{sku:string,delta:integer}]. Stock initially absent/zero. Apply in order, rejecting an event if stock would become negative; rejected events leave no state. Accepted events create the SKU even if delta=0. Return {stock:object,rejected:zero-based event indices}.", [ { "events": [ {"sku": "a", "delta": 3}, {"sku": "a", "delta": -4}, {"sku": "a", "delta": -2}, ] }, {"events": []}, {"events": [{"sku": "x", "delta": -1}]}, { "events": [ {"sku": "x", "delta": 0}, {"sku": "y", "delta": 2}, {"sku": "y", "delta": -2}, ] }, {"events": [{"sku": "", "delta": 1}]}, ], {"stock": {"a": 1}, "rejected": [1]},)add( "bank_ledger", "business", "balances transfers", "Input: balances (account -> nonnegative integer cents), transfers [{from,to,amount:positive integer}]. Reject missing accounts or insufficient source balance; otherwise subtract then add, including self-transfers. Return {balances,rejected:event indices}. Rejected transfers change nothing; never create accounts.", [ { "balances": {"a": 10, "b": 0}, "transfers": [ {"from": "a", "to": "b", "amount": 7}, {"from": "a", "to": "b", "amount": 4}, ], }, {"balances": {}, "transfers": []}, {"balances": {"a": 2}, "transfers": [{"from": "a", "to": "a", "amount": 2}]}, {"balances": {"a": 3}, "transfers": [{"from": "a", "to": "x", "amount": 1}]}, {"balances": {"a": 0}, "transfers": [{"from": "x", "to": "a", "amount": 1}]}, ], {"balances": {"a": 3, "b": 7}, "rejected": [1]},)add( "ballot_count", "business", "candidates votes", "Input: candidates (unique strings), votes (strings). Count candidate votes, unrecognized votes invalid. Return {ranking:[{candidate,votes}],invalid}. Include zero-vote candidates. Rank by decreasing votes then ascending name.", [ {"candidates": ["b", "a", "c"], "votes": ["a", "b", "a", "x"]}, {"candidates": [], "votes": []}, {"candidates": ["a"], "votes": ["x", ""]}, {"candidates": ["b", "a"], "votes": ["b", "a"]}, {"candidates": [], "votes": ["x"]}, ], { "ranking": [ {"candidate": "a", "votes": 2}, {"candidate": "b", "votes": 1}, {"candidate": "c", "votes": 0}, ], "invalid": 1, },)add( "search_rank", "business", "documents query", "Input: documents [{id:unique string,text:string}], query string. Tokenize lowercase ASCII [a-z0-9]+. Score each document by total occurrence counts of distinct query tokens. Omit score=0 docs. Return [{id,score}] sorted by decreasing score then id.", [ { "documents": [ {"id": "b", "text": "red blue"}, {"id": "a", "text": "red red"}, {"id": "c", "text": "green"}, ], "query": "RED red blue", }, {"documents": [], "query": "x"}, {"documents": [{"id": "a", "text": "x"}], "query": ""}, { "documents": [{"id": "z", "text": "x"}, {"id": "a", "text": "x"}], "query": "x", }, {"documents": [{"id": "a", "text": "é RED_42"}], "query": "red 42"}, ], [{"id": "a", "score": 2}, {"id": "b", "score": 2}],)add( "log_summary", "business", "events", "Input: events [{level:string,message:string}]. Return {counts:level->count,errors:messages of exactly ERROR-level events in source order}. Levels are case-sensitive; include only encountered levels.", [ { "events": [ {"level": "INFO", "message": "start"}, {"level": "ERROR", "message": "bad"}, {"level": "ERROR", "message": "worse"}, ] }, {"events": []}, {"events": [{"level": "error", "message": "x"}]}, { "events": [ {"level": "WARN", "message": ""}, {"level": "INFO", "message": "ok"}, ] }, {"events": [{"level": "ERROR", "message": "é"}]}, ], {"counts": {"INFO": 1, "ERROR": 2}, "errors": ["bad", "worse"]},)add( "uptime_report", "business", "start end downtime", "Input: integer start<=end, downtime intervals [a,b] with a<=b. Clip to [start,end), merge overlaps, count duration without double-counting. Return {down,up}, up=end-start-down.", [ {"start": 0, "end": 10, "downtime": [[-2, 3], [2, 5], [8, 12]]}, {"start": 0, "end": 0, "downtime": []}, {"start": 0, "end": 5, "downtime": []}, {"start": 0, "end": 5, "downtime": [[-10, 10]]}, {"start": 0, "end": 5, "downtime": [[1, 1], [5, 8]]}, ], {"down": 7, "up": 3},)add( "segment_intersection", "geometry", "a b c d", "Input: a,b,c,d each [integer x,integer y]. Return boolean whether closed segments ab and cd intersect, including collinear overlap, endpoint touches and degenerate point-segments. Coordinates magnitude <=100000.", [ {"a": [0, 0], "b": [2, 2], "c": [0, 2], "d": [2, 0]}, {"a": [0, 0], "b": [1, 0], "c": [2, 0], "d": [3, 0]}, {"a": [0, 0], "b": [2, 0], "c": [1, 0], "d": [3, 0]}, {"a": [0, 0], "b": [0, 0], "c": [-1, 0], "d": [1, 0]}, {"a": [0, 0], "b": [0, 1], "c": [0, 1], "d": [1, 1]}, {"a": [0, 0], "b": [0, 0], "c": [1, 1], "d": [1, 1]}, ], True,)add( "polygon_area", "geometry", "points", "Input: points, ordered integer [x,y] vertices of a simple polygon (clockwise or counterclockwise), possibly empty or fewer than three points. Return nonnegative area by shoelace, implicitly close last to first. Degenerate polygon has zero area.", [ {"points": [[0, 0], [4, 0], [4, 3], [0, 3]]}, {"points": []}, {"points": [[1, 2]]}, {"points": [[0, 0], [1, 0], [0, 1]]}, {"points": [[0, 0], [0, 3], [4, 3], [4, 0]]}, {"points": [[-1, -1], [1, 1]]}, ], 12,)add( "skyline", "geometry", "buildings", "Input: buildings [left,right,height], integer left<right and positive height. Return skyline keypoints [x,height] in ascending x where max active height changes. Buildings cover [left,right); omit redundant same-height points; finish with height 0 at last active end. Empty input returns [].", [ {"buildings": [[1, 4, 3], [2, 6, 5], [7, 8, 2]]}, {"buildings": []}, {"buildings": [[0, 1, 2], [1, 2, 2]]}, {"buildings": [[0, 5, 4], [1, 2, 1]]}, {"buildings": [[-2, 0, 3], [-2, 0, 3]]}, ], [[1, 3], [2, 5], [6, 0], [7, 2], [8, 0]],)add( "knapsack", "optimization", "items capacity", "Input: items [{weight:positive integer,value:nonnegative integer}], capacity (0..1000). Each item usable at most once; return maximum total value within capacity. Identical items remain independently usable; no need to return selected indices.", [ { "items": [ {"weight": 2, "value": 3}, {"weight": 3, "value": 4}, {"weight": 4, "value": 8}, ], "capacity": 5, }, {"items": [], "capacity": 5}, {"items": [{"weight": 1, "value": 2}], "capacity": 0}, { "items": [{"weight": 2, "value": 3}, {"weight": 2, "value": 3}], "capacity": 4, }, {"items": [{"weight": 9, "value": 20}], "capacity": 3}, ], 8,)add( "task_selection", "optimization", "tasks", "Input: tasks [{id:unique string,start:integer,end:integer}], start<end. Greedy maximum-count nonoverlapping schedule: sort by (end,start,id), choose each task iff start>=previous chosen end. Return chosen IDs. Intervals are half-open, negative times allowed.", [ { "tasks": [ {"id": "a", "start": 0, "end": 3}, {"id": "b", "start": 1, "end": 2}, {"id": "c", "start": 2, "end": 4}, ] }, {"tasks": []}, { "tasks": [ {"id": "b", "start": 0, "end": 1}, {"id": "a", "start": 0, "end": 1}, ] }, { "tasks": [ {"id": "a", "start": -3, "end": -1}, {"id": "b", "start": -1, "end": 0}, ] }, {"tasks": [{"id": "x", "start": 0, "end": 9}]}, ], ["b", "c"],)add( "sequence_diff", "optimization", "a b", 'Input: a,b (lists of strings, length<=100). Produce minimal insert/delete edit script via longest common subsequence. If current tokens equal, emit ["keep",token] and advance both. Otherwise choose deletion when remaining LCS lengths tie; else choose operation retaining longer LCS. Emit ["delete",token] or ["insert",token]; process until both exhausted.', [ {"a": ["a", "b"], "b": ["b", "c"]}, {"a": [], "b": []}, {"a": ["a"], "b": []}, {"a": [], "b": ["x", "y"]}, {"a": ["a", "b"], "b": ["b", "a"]}, {"a": ["x", "x"], "b": ["x"]}, ], [["delete", "a"], ["keep", "b"], ["insert", "c"]],)add( "finite_automaton", "languages", "start accepting transitions words", "Input: start (state string), accepting (state strings), transitions [{from,symbol,to}] with unique (from,symbol) and one-code-point symbols, words (strings). Simulate DFA separately per word. Missing transition rejects immediately. Return acceptance booleans. Empty word accepted iff start accepting.", [ { "start": "a", "accepting": ["a"], "transitions": [ {"from": "a", "symbol": "x", "to": "b"}, {"from": "b", "symbol": "x", "to": "a"}, ], "words": ["", "x", "xx", "y"], }, {"start": "s", "accepting": [], "transitions": [], "words": ["", "a"]}, {"start": "s", "accepting": ["s"], "transitions": [], "words": [""]}, { "start": "s", "accepting": ["t"], "transitions": [{"from": "s", "symbol": "é", "to": "t"}], "words": ["é", "éé"], }, {"start": "s", "accepting": ["s"], "transitions": [], "words": []}, ], [True, False, True, False],)add( "content_manifest", "systems", "files", "Input: files (object of logical file path -> text). Do not read filesystem. Return [{path,bytes,sha256}] sorted by path; bytes is length of UTF-8 encoding and sha256 is lowercase hexadecimal SHA-256 of that encoding. No newline insertion or Unicode normalization.", [ {"files": {"empty": ""}}, {"files": {}}, {"files": {"b": "hello", "a": "é"}}, {"files": {"x": "a\n", "y": "a"}}, {"files": {"中": "😀", "nul": "\u0000"}}, ], [ { "path": "empty", "bytes": 0, "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", } ],)add( "cellular_automaton", "simulation", "live steps", "Input: live (integer [row,column] pairs, duplicates ignored), steps (0..20). Simulate Conway Life on infinite 2D grid, eight neighbors: live survives with 2 or 3, dead born with 3. Return sorted unique live pairs lexicographically. Initial <=50 cells.", [ {"live": [[0, 0], [0, 1], [0, 2]], "steps": 1}, {"live": [], "steps": 10}, {"live": [[0, 0]], "steps": 1}, {"live": [[0, 0], [0, 1], [1, 0], [1, 1]], "steps": 5}, {"live": [[1, 2], [1, 2], [-1, 0]], "steps": 0}, {"live": [[0, 0], [0, 1], [0, 2]], "steps": 2}, ], [[-1, 1], [0, 1], [1, 1]],)add( "expression_eval", "languages", "tokens", "Input: tokens, a valid postfix integer expression as strings with binary operators +,-,*,/. Return integer result. Division truncates toward zero, including negative operands; all divisors nonzero. Other tokens are signed base-10 integers. All intermediate magnitudes <=2^100; expression leaves exactly one value.", [ {"tokens": ["5", "2", "-", "4", "*"]}, {"tokens": ["-7", "3", "/"]}, {"tokens": ["7", "-3", "/"]}, {"tokens": ["42"]}, {"tokens": ["2", "3", "4", "*", "+"]}, {"tokens": ["100000000000000000001", "3", "/"]}, ], 12,)
assert len(FAMILIES) == 65123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
from .runner import evaluate, find_task, load_tasks
def write_json(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" )
def main(argv=None): parser = argparse.ArgumentParser( prog="klein-bench", description="Klein-Code-Bench: 260 from-scratch Python projects. No Docker.", ) commands = parser.add_subparsers(dest="command", required=True) listing = commands.add_parser("list", help="List task IDs and titles") listing.add_argument("--subset", choices=["easy", "intermediate", "hard", "max"]) for name in ("prepare", "reference", "evaluate"): p = commands.add_parser(name) p.add_argument("task_id") if name == "evaluate": p.add_argument("--solution", type=Path, required=True) p.add_argument("--output", type=Path) p.add_argument("--fail-fast", action="store_true") p.add_argument( "--public-only", action="store_true", help="Smoke test only; never an official task pass", ) else: p.add_argument("--output", type=Path, required=True) validation = commands.add_parser( "validate", help="Validate manifest, all goldens, references and empty submissions", ) validation.add_argument("--subset", choices=["easy", "intermediate", "hard", "max"]) validation.add_argument( "--output", type=Path, default=Path("results/validation.json") ) commands.add_parser( "build", help="Rebuild dataset reproducibly from authored source" ) score = commands.add_parser( "score", help="Aggregate one JSON evaluation report per submitted task" ) score.add_argument("reports", nargs="+", type=Path) args = parser.parse_args(argv) try: if args.command == "list": for task in load_tasks(args.subset): print(task["task_id"] + "\t" + task["title"]) return 0 if args.command == "build": from .build import build
print(json.dumps(build(), indent=2)) return 0 if args.command == "score": from .scoring import summarize
print( json.dumps( summarize([json.loads(p.read_text()) for p in args.reports]), indent=2, ) ) return 0 if args.command == "validate": from .validation import validate
report = validate(args.subset) write_json(args.output, report) print( json.dumps( {k: v for k, v in report.items() if k != "results"}, indent=2 ) ) return 0 if report["passed"] else 1 task = find_task(args.task_id) if args.command == "prepare": if args.output.exists() and any(args.output.iterdir()): raise ValueError("Prepare destination must be empty") args.output.mkdir(parents=True, exist_ok=True) (args.output / "project").mkdir() (args.output / "PROMPT.md").write_text( task["prompt"] + "\n", encoding="utf-8" ) public = {k: v for k, v in task.items() if k != "acceptance_tests"} write_json(args.output / "task.json", public) print(f"Empty project: {args.output / 'project'}") elif args.command == "reference": from .reference.export import export_reference
print(export_reference(task["family"], task["subset"], args.output)) else: tests = None if args.public_only: examples = json.loads(task["public_tests"]) tests = [ { "name": "public-smoke-only", "sessions": [ { "requests": [e["request"] for e in examples], "expected": [e["response"] for e in examples], } ], } ] report = evaluate( task, args.solution, tests=tests, fail_fast=args.fail_fast ) report["evaluation_scope"] = "public" if args.public_only else "acceptance" if args.public_only: report["resolved"] = False if args.output: write_json(args.output, report) print(json.dumps(report, indent=2)) return 0 if report["passed"] else 1 return 0 except (OSError, ValueError) as error: print(f"klein-bench: {error}", file=sys.stderr) return 2
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627{ "benchmark": "Klein-Code-Bench", "version": "0.1.0", "protocol_version": "1.0", "tasks": 260, "families": 65, "counts": { "easy": 65, "intermediate": 65, "hard": 65, "max": 65 }, "assertions": { "easy": 3075, "intermediate": 5415, "hard": 9705, "max": 15490 }, "sha256": { "easy.jsonl": "07c3bbf7b25787574e8350ea8f9abe2646ccb26fc2d1ffe8ca86674f82703d1d", "intermediate.jsonl": "d00b88b9f18272ed69f4e0dcc4b8742ee919c66ecd016716e10de2a0012178f5", "hard.jsonl": "c8eb001ba240298a96e0bef8c3b0f60dd6728e462f76d87757dfc69b477a159d", "max.jsonl": "b0613d3beb00ad302932f6fe1b90c26d8209874f6b07fb7fbf0651b332911d84" }, "seed": 1729, "difficulty_calibrated": false}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426"""Deterministic additional domain inputs, generated without model/reference output."""
import csvimport datetime as dtimport ioimport random
def generated_inputs(family, count=24, seed=1729): r = random.Random(f"{seed}/{family}/domain")
def nums(): return [r.randrange(-9, 10) for _ in range(r.randrange(12))]
def words(): return [ r.choice(["a", "b", "c", "", "é", "a/b"]) for _ in range(r.randrange(12)) ]
def text(chars="abAB09_ -é\n"): return "".join(r.choices(chars, k=r.randrange(60)))
def intervals(): return [ sorted([r.randrange(-10, 11), r.randrange(-10, 11)]) for _ in range(r.randrange(10)) ]
for _ in range(count): if family in {"word_frequency", "run_length"}: x = {"text": text()} elif family == "bracket_audit": x = {"text": text("()[]{}abcé ")} elif family == "slug_registry": x = {"titles": [text("aAB -_/é") for _ in range(r.randrange(12))]} elif family == "text_wrap": x = {"text": text(), "width": r.randrange(1, 20)} elif family == "ngram_index": x = {"tokens": words(), "n": r.randrange(1, 5)} elif family == "glob_filter": x = { "paths": words(), "pattern": r.choice(["*", "?", "[abc]*", "*/*", "[!a]*", "é"]), } elif family == "edit_distance": x = {"a": text(), "b": text()} elif family == "roman_codec": x = {"number": r.randrange(1, 4000)} elif family == "caesar_cipher": x = {"text": text(), "shift": r.randrange(-1000, 1001)} elif family == "csv_records": stream = io.StringIO() writer = csv.writer(stream) writer.writerow(["a", "b"]) writer.writerows( [[text('a,b"\né '), text()] for _ in range(r.randrange(8))] ) x = {"csv": stream.getvalue()} elif family in {"record_query", "dedupe_records"}: rows = [ {k: r.choice([None, 1, 2, "x"]) for k in ("a", "b") if r.random() < 0.8} for _ in range(r.randrange(15)) ] x = ( { "rows": rows, "where": {"a": r.choice([None, 1, 2])}, "select": ["b", "c"], } if family == "record_query" else {"rows": rows, "keys": r.choice([[], ["a"], ["a", "b"]])} ) elif family == "inner_join": x = { "left": [{"k": r.randrange(4)} for _ in range(r.randrange(8))], "right": [{"k": r.randrange(4)} for _ in range(r.randrange(8))], "key": "k", } elif family == "group_totals": x = { "rows": [ {"g": r.choice(["a", "b", ""]), "v": r.randrange(-20, 21)} for _ in range(r.randrange(16)) ], "group": "g", "value": "v", } elif family == "pivot_table": x = { "rows": [ { "r": r.choice(["a", "b", ""]), "c": r.choice(["x", "y"]), "v": r.randrange(-9, 10), } for _ in range(r.randrange(16)) ], "row": "r", "column": "c", "value": "v", } elif family in {"json_flatten", "merge_patch", "json_pointer"}: value = { "a/b": [nums(), {}, None], "~": {"": r.randrange(9)}, "x": r.choice([True, None, "é"]), } if family == "json_flatten": x = {"value": value} elif family == "merge_patch": x = { "target": value, "patch": { "a/b": r.choice([None, [1], {"z": 2}]), "x": {"v": r.randrange(9)}, }, } else: x = { "value": value, "pointer": r.choice( ["", "/a~1b/0", "/a~1b/99", "/~0/", "/x/no", "/absent"] ), } elif family == "schema_check": x = { "schema": { k: { "type": r.choice( [ "integer", "number", "boolean", "string", "array", "object", "null", ] ), "required": r.choice([True, False]), } for k in ("a", "b", "c") }, "value": { k: r.choice([True, 1, 1.5, "x", [], {}, None]) for k in ("a", "b") if r.random() < 0.8 }, } elif family in { "interval_union", "interval_gaps", "booking_peak", "uptime_report", }: pairs = intervals() if family == "booking_peak": x = {"bookings": pairs} elif family == "uptime_report": x = {"start": -5, "end": 5, "downtime": pairs} else: x = {"intervals": pairs} if family == "interval_gaps": x["bounds"] = [-5, 5] elif family == "business_days": start = dt.date(2000, 1, 1) + dt.timedelta(days=r.randrange(9000)) x = { "start": start.isoformat(), "end": (start + dt.timedelta(days=r.randrange(30))).isoformat(), "holidays": [ (start + dt.timedelta(days=r.randrange(30))).isoformat() for _ in range(5) ], } elif family == "calendar_month": x = {"year": r.randrange(1900, 2101), "month": r.randrange(1, 13)} elif family == "moving_average": x = {"values": nums(), "window": r.randrange(1, 8)} elif family == "statistics": x = {"values": nums()} elif family == "histogram": x = {"values": nums(), "edges": sorted(r.sample(range(-10, 11), 5))} elif family == "matrix_product": m, n, p = [r.randrange(1, 5) for _ in range(3)] x = { "a": [[r.randrange(-4, 5) for _ in range(n)] for _ in range(m)], "b": [[r.randrange(-4, 5) for _ in range(p)] for _ in range(n)], } elif family == "polynomial": x = {"coefficients": nums(), "points": nums()} elif family == "prime_factors": x = {"number": r.randrange(1, 100001)} elif family == "base_convert": x = { "digits": str(r.randrange(-(2**70), 2**70)), "from_base": 10, "to_base": r.randrange(2, 37), } elif family == "money_split": x = { "amount": r.randrange(10000), "weights": [r.randrange(1, 20)] + [r.randrange(20) for _ in range(r.randrange(8))], } elif family == "invoice_total": x = { "items": [ { "price": f"{r.randrange(100)}.{r.randrange(1000):03d}", "quantity": r.randrange(10), } for _ in range(r.randrange(8)) ], "tax_rate": r.choice(["0", "0.075", "0.20"]), } elif family == "coin_change": x = { "coins": [r.randrange(1, 15) for _ in range(r.randrange(8))], "amount": r.randrange(100), } elif family in { "graph_reach", "shortest_path", "topological_order", "connected_components", }: nodes = list("abcdef")[: r.randrange(1, 7)] edges = [[r.choice(nodes), r.choice(nodes)] for _ in range(r.randrange(15))] if family == "shortest_path": edges = [edge + [r.randrange(10)] for edge in edges] x = {"nodes": nodes, "edges": edges} if family in {"graph_reach", "shortest_path"}: x["start"] = r.choice(nodes) elif family == "grid_route": grid = ["".join(r.choices(".#", weights=[4, 1], k=5)) for _ in range(5)] x = { "grid": grid, "start": [r.randrange(5), r.randrange(5)], "end": [r.randrange(5), r.randrange(5)], } elif family == "tree_outline": nodes = [] for key in list("abcdefgh")[: r.randrange(9)]: nodes.append( {"id": key, "parent": r.choice([None] + [n["id"] for n in nodes])} ) r.shuffle(nodes) x = {"nodes": nodes} elif family == "dependency_build": nodes = list("abcde")[: r.randrange(1, 6)] x = { "dependencies": { n: r.sample(nodes, r.randrange(len(nodes) + 1)) for n in nodes }, "targets": r.sample(nodes, r.randrange(len(nodes) + 1)), } elif family == "path_normalize": x = { "paths": [ "/".join( r.choices(["a", "b", "..", ".", "", "é"], k=r.randrange(10)) ) for _ in range(r.randrange(12)) ] } elif family == "url_query": x = { "query": "&".join( r.choices( ["a=1", "a=2", "x=a+b", "x=%2B", "flag", "", "=v", "q=%C3%A9"], k=r.randrange(12), ) ) } elif family == "version_sort": x = { "versions": [ f"{r.randrange(3)}.{r.randrange(12)}.{r.randrange(5)}" + r.choice(["", "-a", "-a.2", "-a.10", "-1", "-b"]) for _ in range(r.randrange(15)) ] } elif family == "lru_trace": x = {"capacity": r.randrange(6), "accesses": words()} elif family == "rate_limit": x = { "events": [ {"time": t, "key": r.choice(["a", "b"])} for t in sorted(r.choices(range(12), k=r.randrange(20))) ], "window": r.randrange(1, 8), "limit": r.randrange(5), } elif family == "priority_queue": x = { "events": [ {"op": "pop"} if r.random() < 0.4 else { "op": "push", "priority": r.randrange(-2, 3), "value": r.choice([None, "x", {"a": 1}, []]), } for _ in range(r.randrange(20)) ] } elif family == "round_robin": x = { "jobs": [ {"id": str(i), "duration": r.randrange(1, 12)} for i in range(r.randrange(6)) ], "quantum": r.randrange(1, 6), } elif family == "inventory_ledger": x = { "events": [ {"sku": r.choice(["a", "b", "c"]), "delta": r.randrange(-5, 6)} for _ in range(r.randrange(20)) ] } elif family == "bank_ledger": x = { "balances": {"a": r.randrange(20), "b": r.randrange(20)}, "transfers": [ { "from": r.choice(["a", "b", "missing"]), "to": r.choice(["a", "b", "missing"]), "amount": r.randrange(1, 12), } for _ in range(r.randrange(12)) ], } elif family == "ballot_count": x = { "candidates": ["a", "b", "c"], "votes": r.choices(["a", "b", "c", "bad"], k=r.randrange(30)), } elif family == "search_rank": x = { "documents": [ {"id": str(i), "text": text()} for i in range(r.randrange(8)) ], "query": text(), } elif family == "log_summary": x = { "events": [ { "level": r.choice(["ERROR", "INFO", "WARN", "error"]), "message": text(), } for _ in range(r.randrange(12)) ] } elif family == "segment_intersection": x = {k: [r.randrange(-4, 5), r.randrange(-4, 5)] for k in "abcd"} elif family == "polygon_area": a, b, c, d = [r.randrange(1, 10) for _ in range(4)] x = {"points": [[-a, -b], [c, -b], [c, d], [-a, d]]} if r.random() < 0.5: x["points"].reverse() elif family == "skyline": x = { "buildings": [ [a, a + r.randrange(1, 8), r.randrange(1, 10)] for a in [r.randrange(-5, 6) for _ in range(r.randrange(12))] ] } elif family == "knapsack": x = { "items": [ {"weight": r.randrange(1, 10), "value": r.randrange(20)} for _ in range(r.randrange(10)) ], "capacity": r.randrange(25), } elif family == "task_selection": x = { "tasks": [ {"id": str(i), "start": a, "end": a + r.randrange(1, 8)} for i, a in enumerate( [r.randrange(-5, 8) for _ in range(r.randrange(12))] ) ] } elif family == "sequence_diff": x = {"a": words(), "b": words()} elif family == "finite_automaton": x = { "start": "a", "accepting": r.sample(["a", "b"], r.randrange(3)), "transitions": [ {"from": a, "symbol": c, "to": r.choice(["a", "b"])} for a in ["a", "b"] for c in "xy" if r.random() < 0.8 ], "words": [ "".join(r.choices("xy", k=r.randrange(10))) for _ in range(r.randrange(12)) ], } elif family == "content_manifest": x = {"files": {str(i) + "/é": text() for i in range(r.randrange(8))}} elif family == "cellular_automaton": x = { "live": [ [r.randrange(-3, 4), r.randrange(-3, 4)] for _ in range(r.randrange(20)) ], "steps": r.randrange(5), } elif family == "expression_eval": x = { "tokens": [ str(r.randrange(-100, 101)), str(r.randrange(-100, 101)), r.choice(["+", "-", "*"]), str(r.randrange(1, 10)), "/", ] } else: raise ValueError(f"No generator for {family}") yield x1234567891011121314151617181920212223242526272829303132333435363738394041424344454647"""Versioned task contracts. These contracts are included verbatim in each prompt."""
TIERS = {"easy": "2–8B", "intermediate": "8–16B", "hard": "16–32B", "max": "60–200B"}PROTOCOL_VERSION = "1.0"BASE = """Build a complete project from an EMPTY directory, using Python 3.11+ and only the standard library. Create main.py as the entry point; any number of supporting files is allowed. No starter implementation is provided.Run: python main.py (max-tier invocation adds --state-dir DIRECTORY).Read one JSON object per stdin line, write exactly one JSON response per request line, flush it immediately, and continue after an error. No banners or diagnostics on stdout. EOF exits cleanly. Values are finite JSON; object key order is irrelevant, array order matters. Float results use tolerance 1e-9 (absolute or relative). Do not read any benchmark/evaluator files.Success response: {"ok":true,"result":RESULT}. Error response: {"ok":false,"error":CODE} with no extra fields.Every tier supports {"op":"solve","input":OBJECT}. Compute the domain result specified below without changing workspace state. input must be an object containing all required domain fields; otherwise error invalid_input. Other domain constraints are guarantees about supplied inputs, not additional validation requirements.Malformed JSON, a nonobject request, a missing/nonstring op, missing/mistyped command fields, or an unavailable/unknown operation: invalid_request. An empty or whitespace-only line is malformed JSON and receives invalid_request. Ignore extra command fields except the max-tier token field. Domain input fields beyond required ones are ignored.Keys are arbitrary nonempty strings (Unicode and / allowed), never filesystem paths. Each fresh evaluation scenario starts empty. An error changes no state. Commands are sequential, one client; concurrency is not required."""STORE = """Also implement an in-memory document workspace, initially empty, shared across request lines:* {"op":"put","key":K,"value":V}: store any JSON value (including null), replacing if present. Each successful put increments global revision by 1, even if unchanged. Result {"key":K,"revision":NEW_GLOBAL_REVISION}.* {"op":"get","key":K}: result {"key":K,"value":STORED_VALUE,"revision":REVISION_OF_LAST_PUT_FOR_K}. Missing key: not_found.* {"op":"delete","key":K}: delete existing key and increment global revision by 1. Result {"key":K,"revision":NEW_GLOBAL_REVISION}. Missing key: not_found, no increment.* {"op":"list","prefix":P}: result sorted list of keys starting with P; prefix optional, defaults "", must be a string.* {"op":"evaluate","key":K}: solve the stored document as domain input without modifying it. Missing key: not_found; nonobject or missing required domain fields: invalid_input.* {"op":"status"}: result {"revision":GLOBAL_REVISION,"size":NUMBER_OF_KEYS}. Reads never increment revision. Global revision begins at 0. Deep JSON values must not alias or be mutated by computation."""TRANSACTIONS = """Also implement atomicity and nested transactions:* put/delete may include if_revision (nonnegative integer, never boolean): require equality with current GLOBAL revision before doing anything else; mismatch -> conflict, even if the key is absent. Missing if_revision means unconditional. Other commands ignore if_revision.* {"op":"batch","commands":[REQUEST,...]}: 0..32 commands from solve/put/get/delete/list/evaluate/status only. Execute sequentially against evolving state. All succeed: result is the list of each command's unwrapped result. Any error: return that error and roll back the entire batch, including revision. Empty batch returns []. Disallowed commands, nonobject entries or invalid command list -> invalid_request and rollback.* {"op":"begin"}: save complete current state, push transaction, result {"depth":NEW_DEPTH}; at most 8 open transactions, otherwise transaction_limit.* {"op":"commit"}: discard most recent saved state, keep its changes; result {"depth":NEW_DEPTH}.* {"op":"rollback"}: restore most recent saved state including global and document revisions; result {"depth":NEW_DEPTH}.commit/rollback with no open transaction -> no_transaction. A failing command inside a transaction leaves that transaction open and unchanged. Nested commit changes remain subject to outer rollback. status still has exactly revision and size, not transaction depth."""DURABILITY = """Also implement durable storage and retry handling. Invocation is python main.py --state-dir DIRECTORY (existing empty or previously used directory). Choose your own on-disk format.After each successful state-changing command outside a transaction, and after an outermost commit, persist the entire logical state BEFORE flushing its response. On process termination and restart with the same directory, restore documents, revisions, history, and retry records. An open transaction and all changes since its outermost begin are discarded on restart, even if nested commits occurred. No writes on an error. Evaluation may force-kill the process immediately after reading a complete response. Single writer; torn writes during persistence, external disk corruption, and simultaneous processes are out of scope. Persist nothing outside state-dir. Never derive storage filenames from document keys.* {"op":"history","after":R,"limit":N}: result earliest up to N mutation records with revision>R, ascending. R optional default 0 (nonnegative integer); N optional default 100 (integer 0..100). Every successful put creates {"revision":R,"op":"put","key":K,"value":V}; delete creates {"revision":R,"op":"delete","key":K}. Batch records each internal write, not a batch event. Reads/transaction-control commands create no history. Rollback removes rolled-back records. History sees active transaction changes.* {"op":"scan","prefix":P,"after":K,"limit":N}: sorted matching document records as in get, keys strictly greater than after. prefix defaults "", after defaults "" (both strings), limit defaults 100 (integer 0..100). Return {"items":[...],"next":LAST_RETURNED_KEY_OR_NULL}. next is nonnull only when more matching records remain AND at least one item was returned. limit=0 returns {items:[],next:null}.* put/delete/batch may carry token, a nonempty string. First successful token-bearing request caches its full response and canonical parsed request excluding token (object order ignored, array order significant). An identical retry returns that exact cached response with NO mutation or revision increment. Reusing a token for a different request -> idempotency_conflict. Failed requests are never cached. Check a cached token before checking if_revision. Invalid/empty/nonstring token or token on any other operation -> invalid_request. A token within any batch subcommand is invalid_request. Retry records follow transaction rollback and restart rules exactly like documents; an outer rollback forgets tokens first used inside it."""
def contract(tier): index = list(TIERS).index(tier) return ( BASE + (STORE if index >= 1 else "") + (TRANSACTIONS if index >= 2 else "") + (DURABILITY if index >= 3 else "") )1"""Evaluator-side reference implementations. Never expose to a model run."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869"""65 independent domain algorithms used by the evaluator's reference projects."""
from __future__ import annotations
import calendarimport collectionsimport csvimport datetime as dtimport decimalimport fnmatchimport hashlibimport heapqimport ioimport itertoolsimport jsonimport mathimport reimport statisticsimport urllib.parse
def solve(name: str, x: dict): return globals()["solve_" + name](x)
def solve_word_frequency(x): words = re.findall(r"[a-z0-9]+", x["text"].lower()) counts = collections.Counter(words) return [ {"word": w, "count": n} for w, n in sorted(counts.items(), key=lambda p: (-p[1], p[0])) ]
def solve_slug_registry(x): used, out = set(), [] for title in x["titles"]: root = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") or "item" slug, i = root, 2 while slug in used: slug, i = f"{root}-{i}", i + 1 used.add(slug) out.append(slug) return out
def solve_run_length(x): return [[char, len(list(group))] for char, group in itertools.groupby(x["text"])]
def solve_bracket_audit(x): stack = [] for i, c in enumerate(x["text"]): if c in "([{": stack.append((c, i)) elif c in ")]}": if not stack or "([{".index(stack[-1][0]) != ")]}".index(c): return {"balanced": False, "position": i} stack.pop() return {"balanced": not stack, "position": stack[-1][1] if stack else None}
def solve_text_wrap(x): lines, line = [], "" for word in x["text"].split(): if line and len(line) + 1 + len(word) > x["width"]: lines.append(line) line = "" line = line + " " + word if line else word if line: lines.append(line) return lines
def solve_ngram_index(x): tokens, n = x["tokens"], x["n"] found = collections.defaultdict(list) for i in range(len(tokens) - n + 1): found[tuple(tokens[i : i + n])].append(i) return [{"tokens": list(k), "positions": found[k]} for k in sorted(found)]
def solve_glob_filter(x): return sorted({p for p in x["paths"] if fnmatch.fnmatchcase(p, x["pattern"])})
def solve_edit_distance(x): a, b = x["a"], x["b"] row = list(range(len(b) + 1)) for i, char in enumerate(a, 1): nxt = [i] for j, other in enumerate(b, 1): nxt.append(min(nxt[-1] + 1, row[j] + 1, row[j - 1] + (char != other))) row = nxt return row[-1]
def solve_roman_codec(x): n, out = x["number"], "" for value, symbol in [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ]: q, n = divmod(n, value) out += symbol * q return out
def solve_caesar_cipher(x): out = "" for c in x["text"]: base = ord("a") if "a" <= c <= "z" else ord("A") if "A" <= c <= "Z" else None out += chr((ord(c) - base + x["shift"]) % 26 + base) if base is not None else c return out
def solve_csv_records(x): rows = list(csv.reader(io.StringIO(x["csv"]))) return [dict(zip(rows[0], row)) for row in rows[1:]] if rows else []
def solve_record_query(x): rows = [ r for r in x["rows"] if all(k in r and r[k] == v for k, v in x["where"].items()) ] return [{k: r.get(k) for k in x["select"]} for r in rows]
def solve_inner_join(x): return [ {"left": a, "right": b} for a in x["left"] for b in x["right"] if x["key"] in a and x["key"] in b and a[x["key"]] == b[x["key"]] ]
def solve_group_totals(x): groups = collections.defaultdict(list) for row in x["rows"]: groups[row[x["group"]]].append(row[x["value"]]) return [ {"key": k, "count": len(groups[k]), "sum": sum(groups[k])} for k in sorted(groups) ]
def solve_json_flatten(x): out = {}
def walk(value, path): if isinstance(value, dict) and value: for k in sorted(value): walk(value[k], path + "/" + k.replace("~", "~0").replace("/", "~1")) elif isinstance(value, list) and value: for i, child in enumerate(value): walk(child, path + "/" + str(i)) else: out[path] = value
walk(x["value"], "") return out
def solve_merge_patch(x): def merge(target, patch): if not isinstance(patch, dict): return patch out = dict(target) if isinstance(target, dict) else {} for k, v in patch.items(): if v is None: out.pop(k, None) else: out[k] = merge(out.get(k), v) return out
return merge(x["target"], x["patch"])
def solve_json_pointer(x): value = x["value"] if x["pointer"] == "": return {"found": True, "value": value} try: for token in x["pointer"][1:].split("/"): token = token.replace("~1", "/").replace("~0", "~") if isinstance(value, list): if not re.fullmatch(r"0|[1-9][0-9]*", token): raise KeyError(token) value = value[int(token)] elif isinstance(value, dict): value = value[token] else: raise KeyError(token) return {"found": True, "value": value} except (KeyError, IndexError): return {"found": False, "value": None}
def solve_dedupe_records(x): seen, out = set(), [] for row in x["rows"]: key = json.dumps( [row.get(k) for k in x["keys"]], sort_keys=True, separators=(",", ":") ) if key not in seen: out.append(row) seen.add(key) return out
def solve_pivot_table(x): cells = collections.defaultdict(int) rows, cols = set(), set() for item in x["rows"]: r, c = item[x["row"]], item[x["column"]] rows.add(r) cols.add(c) cells[r, c] += item[x["value"]] rows, cols = sorted(rows), sorted(cols) return { "rows": rows, "columns": cols, "values": [[cells[r, c] for c in cols] for r in rows], }
def solve_schema_check(x): types = { "string": lambda v: isinstance(v, str), "integer": lambda v: type(v) is int, "number": lambda v: type(v) in (int, float), "boolean": lambda v: type(v) is bool, "array": lambda v: isinstance(v, list), "object": lambda v: isinstance(v, dict), "null": lambda v: v is None, } errors = [] for key in sorted(x["schema"]): rule = x["schema"][key] if key not in x["value"]: if rule["required"]: errors.append({"field": key, "error": "required"}) elif not types[rule["type"]](x["value"][key]): errors.append({"field": key, "error": "type"}) return errors
def solve_interval_union(x): out = [] for start, end in sorted(x["intervals"]): if out and start <= out[-1][1]: out[-1][1] = max(end, out[-1][1]) else: out.append([start, end]) return out
def solve_interval_gaps(x): low, high = x["bounds"] out, cursor = [], low for a, b in solve_interval_union(x): a, b = max(low, a), min(high, b) if a > b: continue if a > cursor: out.append([cursor, a]) cursor = max(cursor, b) if cursor < high: out.append([cursor, high]) return out
def solve_booking_peak(x): events = collections.defaultdict(int) for start, end in x["bookings"]: if start < end: events[start] += 1 events[end] -= 1 current = peak = 0 at = None for t, delta in sorted(events.items()): current += delta if current > peak: peak, at = current, t return {"peak": peak, "at": at}
def solve_business_days(x): day, end = dt.date.fromisoformat(x["start"]), dt.date.fromisoformat(x["end"]) holidays, out = set(x["holidays"]), [] while day < end: if day.weekday() < 5 and day.isoformat() not in holidays: out.append(day.isoformat()) day += dt.timedelta(days=1) return out
def solve_calendar_month(x): return calendar.Calendar(firstweekday=0).monthdayscalendar(x["year"], x["month"])
def solve_moving_average(x): return [ sum(x["values"][i : i + x["window"]]) / x["window"] for i in range(len(x["values"]) - x["window"] + 1) ]
def solve_statistics(x): values = x["values"] if not values: return { "count": 0, "min": None, "max": None, "mean": None, "median": None, "variance": None, } return { "count": len(values), "min": min(values), "max": max(values), "mean": statistics.mean(values), "median": statistics.median(values), "variance": statistics.pvariance(values), }
def solve_histogram(x): edges = x["edges"] bins, under, over = [0] * (len(edges) - 1), 0, 0 for v in x["values"]: if v < edges[0]: under += 1 elif v >= edges[-1]: over += 1 else: for i in range(len(bins)): if edges[i] <= v < edges[i + 1]: bins[i] += 1 break return {"counts": bins, "underflow": under, "overflow": over}
def solve_matrix_product(x): return [ [sum(a * b for a, b in zip(row, col)) for col in zip(*x["b"])] for row in x["a"] ]
def solve_polynomial(x): return [ sum(c * value**i for i, c in enumerate(x["coefficients"])) for value in x["points"] ]
def solve_prime_factors(x): n, out, factor = x["number"], [], 2 while factor * factor <= n: count = 0 while n % factor == 0: n //= factor count += 1 if count: out.append([factor, count]) factor += 1 if n > 1: out.append([n, 1]) return out
def solve_base_convert(x): chars = "0123456789abcdefghijklmnopqrstuvwxyz" n = int(x["digits"], x["from_base"]) sign, n = ("-" if n < 0 else ""), abs(n) out = "" while n: n, rem = divmod(n, x["to_base"]) out = chars[rem] + out return sign + (out or "0")
def solve_money_split(x): weights, amount = x["weights"], x["amount"] total = sum(weights) shares = [amount * w // total for w in weights] order = sorted( range(len(weights)), key=lambda i: (-(amount * weights[i] % total), i) ) for i in order[: amount - sum(shares)]: shares[i] += 1 return shares
def solve_invoice_total(x): D = decimal.Decimal subtotal = sum( (D(item["price"]) * item["quantity"] for item in x["items"]), D(0) ).quantize(D(".01"), rounding=decimal.ROUND_HALF_UP) tax = (subtotal * D(x["tax_rate"])).quantize( D(".01"), rounding=decimal.ROUND_HALF_UP ) return { "subtotal": f"{subtotal:.2f}", "tax": f"{tax:.2f}", "total": f"{subtotal + tax:.2f}", }
def solve_coin_change(x): amount, coins = x["amount"], sorted(set(x["coins"])) dp = [0] + [amount + 1] * amount for n in range(1, amount + 1): dp[n] = min([dp[n - c] + 1 for c in coins if c <= n] or [amount + 1]) return None if dp[amount] > amount else dp[amount]
def graph(x, weighted=False, directed=True): adj = {node: [] for node in x["nodes"]} for edge in x["edges"]: a, b = edge[:2] adj[a].append((b, edge[2]) if weighted else b) if not directed: adj[b].append((a, edge[2]) if weighted else a) return adj
def solve_graph_reach(x): adj, found = graph(x), {x["start"]} todo = [x["start"]] while todo: for node in adj[todo.pop()]: if node not in found: found.add(node) todo.append(node) return sorted(found)
def solve_shortest_path(x): adj = graph(x, weighted=True) distances = {x["start"]: 0} queue = [(0, x["start"])] while queue: distance, node = heapq.heappop(queue) if distances[node] != distance: continue for other, weight in adj[node]: alt = distance + weight if alt < distances.get(other, math.inf): distances[other] = alt heapq.heappush(queue, (alt, other)) return {node: distances.get(node) for node in sorted(x["nodes"])}
def solve_topological_order(x): adj, indegree = graph(x), dict.fromkeys(x["nodes"], 0) for edges in adj.values(): for node in edges: indegree[node] += 1 queue = [n for n in indegree if indegree[n] == 0] heapq.heapify(queue) out = [] while queue: node = heapq.heappop(queue) out.append(node) for other in adj[node]: indegree[other] -= 1 if indegree[other] == 0: heapq.heappush(queue, other) return out if len(out) == len(adj) else None
def solve_connected_components(x): adj, seen, out = graph(x, directed=False), set(), [] for node in sorted(adj): if node in seen: continue group, todo = [], [node] seen.add(node) while todo: n = todo.pop() group.append(n) for other in adj[n]: if other not in seen: seen.add(other) todo.append(other) out.append(sorted(group)) return out
def solve_grid_route(x): grid, start, end = x["grid"], tuple(x["start"]), tuple(x["end"]) seen, queue = {start}, collections.deque([(start, 0)]) if grid[start[0]][start[1]] == "#" or grid[end[0]][end[1]] == "#": return None while queue: (r, c), distance = queue.popleft() if (r, c) == end: return distance for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]: if ( 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#" and (nr, nc) not in seen ): seen.add((nr, nc)) queue.append(((nr, nc), distance + 1)) return None
def solve_tree_outline(x): children = collections.defaultdict(list) for node in x["nodes"]: children[node["parent"]].append(node["id"]) out = []
def walk(parent, depth): for node in sorted(children[parent]): out.append({"id": node, "depth": depth}) walk(node, depth + 1)
walk(None, 0) return out
def solve_dependency_build(x): deps, out, active, done = x["dependencies"], [], set(), set()
def visit(node): if node in active: raise ValueError("cycle") if node in done: return active.add(node) for other in sorted(deps[node]): visit(other) active.remove(node) done.add(node) out.append(node)
try: for target in sorted(set(x["targets"])): visit(target) except ValueError: return None return out
def solve_path_normalize(x): out = [] for path in x["paths"]: parts = [] for part in path.split("/"): if part in ("", "."): continue if part == "..": if parts: parts.pop() else: parts.append(part) out.append("/" + "/".join(parts)) return out
def solve_url_query(x): out = collections.defaultdict(list) for k, v in urllib.parse.parse_qsl(x["query"], keep_blank_values=True): out[k].append(v) return dict(out)
def solve_version_sort(x): def key(v): core, _, pre = v.partition("-") parts = tuple(map(int, core.split("."))) ids = ( tuple((0, int(p)) if p.isdigit() else (1, p) for p in pre.split(".")) if pre else () ) return parts, not bool(pre), ids
return sorted(x["versions"], key=key)
def solve_lru_trace(x): cache, hits, misses = collections.OrderedDict(), 0, 0 for key in x["accesses"]: if key in cache: hits += 1 cache.move_to_end(key) else: misses += 1 if x["capacity"]: cache[key] = True if len(cache) > x["capacity"]: cache.popitem(last=False) return {"hits": hits, "misses": misses, "keys": list(cache)}
def solve_rate_limit(x): history, out = collections.defaultdict(collections.deque), [] for event in x["events"]: times = history[event["key"]] while times and times[0] <= event["time"] - x["window"]: times.popleft() allowed = len(times) < x["limit"] if allowed: times.append(event["time"]) out.append(allowed) return out
def solve_priority_queue(x): queue, out, seq = [], [], 0 for event in x["events"]: if event["op"] == "push": heapq.heappush(queue, (event["priority"], seq, event["value"])) seq += 1 else: out.append(heapq.heappop(queue)[2] if queue else None) return {"popped": out, "remaining": [v for _, _, v in sorted(queue)]}
def solve_round_robin(x): quantum = x["quantum"] queue = collections.deque((job["id"], job["duration"]) for job in x["jobs"]) clock, slices, completion = 0, [], {} while queue: key, left = queue.popleft() used = min(quantum, left) slices.append({"id": key, "start": clock, "end": clock + used}) clock += used if left > used: queue.append((key, left - used)) else: completion[key] = clock return {"slices": slices, "completion": completion}
def solve_inventory_ledger(x): stock, rejected = {}, [] for i, event in enumerate(x["events"]): new = stock.get(event["sku"], 0) + event["delta"] if new < 0: rejected.append(i) else: stock[event["sku"]] = new return {"stock": stock, "rejected": rejected}
def solve_bank_ledger(x): balances, rejected = dict(x["balances"]), [] for i, t in enumerate(x["transfers"]): if ( t["from"] not in balances or t["to"] not in balances or balances[t["from"]] < t["amount"] ): rejected.append(i) else: balances[t["from"]] -= t["amount"] balances[t["to"]] += t["amount"] return {"balances": balances, "rejected": rejected}
def solve_ballot_count(x): counts = dict.fromkeys(x["candidates"], 0) invalid = 0 for vote in x["votes"]: if vote in counts: counts[vote] += 1 else: invalid += 1 return { "ranking": [ {"candidate": c, "votes": n} for c, n in sorted(counts.items(), key=lambda p: (-p[1], p[0])) ], "invalid": invalid, }
def solve_search_rank(x): terms = set(re.findall(r"[a-z0-9]+", x["query"].lower())) scored = [] for doc in x["documents"]: counts = collections.Counter(re.findall(r"[a-z0-9]+", doc["text"].lower())) score = sum(counts[t] for t in terms) if score: scored.append({"id": doc["id"], "score": score}) return sorted(scored, key=lambda r: (-r["score"], r["id"]))
def solve_log_summary(x): counts = collections.Counter(event["level"] for event in x["events"]) errors = [e["message"] for e in x["events"] if e["level"] == "ERROR"] return {"counts": dict(counts), "errors": errors}
def solve_uptime_report(x): intervals = solve_interval_union( { "intervals": [ [max(a, x["start"]), min(b, x["end"])] for a, b in x["downtime"] if max(a, x["start"]) < min(b, x["end"]) ] } ) down = sum(b - a for a, b in intervals) return {"down": down, "up": x["end"] - x["start"] - down}
def solve_segment_intersection(x): a, b, c, d = x["a"], x["b"], x["c"], x["d"]
def cross(p, q, r): return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
def on(p, q, r): return ( cross(p, q, r) == 0 and min(p[0], q[0]) <= r[0] <= max(p[0], q[0]) and min(p[1], q[1]) <= r[1] <= max(p[1], q[1]) )
u, v, w, z = cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b) return ( (u * v < 0 and w * z < 0) or on(a, b, c) or on(a, b, d) or on(c, d, a) or on(c, d, b) )
def solve_polygon_area(x): pts = x["points"] return ( abs(sum(a[0] * b[1] - a[1] * b[0] for a, b in zip(pts, pts[1:] + pts[:1]))) / 2 if pts else 0 )
def solve_skyline(x): buildings = x["buildings"] points, prev = [], 0 for t in sorted({v for a, b, _ in buildings for v in (a, b)}): height = max([h for a, b, h in buildings if a <= t < b] or [0]) if height != prev: points.append([t, height]) prev = height return points
def solve_knapsack(x): capacity = x["capacity"] dp = [0] * (capacity + 1) for item in x["items"]: for w in range(capacity, item["weight"] - 1, -1): dp[w] = max(dp[w], dp[w - item["weight"]] + item["value"]) return dp[capacity]
def solve_task_selection(x): end, out = None, [] for job in sorted(x["tasks"], key=lambda j: (j["end"], j["start"], j["id"])): if end is None or job["start"] >= end: out.append(job["id"]) end = job["end"] return out
def solve_sequence_diff(x): a, b = x["a"], x["b"] dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] for i in range(len(a) - 1, -1, -1): for j in range(len(b) - 1, -1, -1): dp[i][j] = ( 1 + dp[i + 1][j + 1] if a[i] == b[j] else max(dp[i + 1][j], dp[i][j + 1]) ) i = j = 0 out = [] while i < len(a) or j < len(b): if i < len(a) and j < len(b) and a[i] == b[j]: out.append(["keep", a[i]]) i, j = i + 1, j + 1 elif i < len(a) and (j == len(b) or dp[i + 1][j] >= dp[i][j + 1]): out.append(["delete", a[i]]) i += 1 else: out.append(["insert", b[j]]) j += 1 return out
def solve_finite_automaton(x): transitions = {(t["from"], t["symbol"]): t["to"] for t in x["transitions"]} out = [] for word in x["words"]: state = x["start"] for symbol in word: state = transitions.get((state, symbol)) if state is None: break out.append(state in x["accepting"]) return out
def solve_content_manifest(x): return [ { "path": path, "bytes": len(text.encode("utf-8")), "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), } for path, text in sorted(x["files"].items()) ]
def solve_cellular_automaton(x): cells = {tuple(p) for p in x["live"]} for _ in range(x["steps"]): neighbors = collections.Counter( (r + dr, c + dc) for r, c in cells for dr in (-1, 0, 1) for dc in (-1, 0, 1) if (dr, dc) != (0, 0) ) cells = {p for p, n in neighbors.items() if n == 3 or n == 2 and p in cells} return [list(p) for p in sorted(cells)]
def solve_expression_eval(x): stack = [] for token in x["tokens"]: if token not in ("+", "-", "*", "/"): stack.append(int(token)) else: b, a = stack.pop(), stack.pop() if token == "+": stack.append(a + b) elif token == "-": stack.append(a - b) elif token == "*": stack.append(a * b) else: stack.append((abs(a) // abs(b)) * (-1 if (a < 0) != (b < 0) else 1)) return stack[0]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Export self-contained oracle projects for benchmark verification only."""
from pathlib import Path
from ..catalog import FAMILIESfrom ..protocol import TIERS
def export_reference(family, tier, destination): f = FAMILIES[family] root = Path(destination) root.mkdir(parents=True, exist_ok=True) path = root / "main.py" if path.exists(): raise FileExistsError(f"Refusing to overwrite {path}") here = Path(__file__).parent domain = ( (here / "domains.py") .read_text(encoding="utf-8") .replace("from __future__ import annotations", "") ) service = (here / "service.py").read_text(encoding="utf-8") for line in ( "from __future__ import annotations", "from klein_code_bench.catalog import FAMILIES", "from klein_code_bench.protocol import TIERS", "from klein_code_bench.reference.domains import solve", ): service = service.replace(line, "") header = f"from types import SimpleNamespace\nTIERS = {TIERS!r}\nFAMILIES = {{{family!r}: SimpleNamespace(slug={family!r}, required={f.required!r})}}\n" main = f"""if __name__ == '__main__': import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('--state-dir', required={tier == "max"!r}) args = parser.parse_args() service = Service({family!r}, {tier!r}, args.state_dir) for line in sys.stdin: try: def reject_constant(value): raise ValueError(value) request = json.loads(line, parse_constant=reject_constant) except ValueError: response = {{'ok': False, 'error': 'invalid_request'}} else: response = service.request(request) print(json.dumps(response, ensure_ascii=True, allow_nan=False), flush=True)""" path.write_text( domain + "\n" + header + "\n" + service + "\n" + main, encoding="utf-8" ) return path123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Readable oracle, not code injected into candidate projects."""
from __future__ import annotations
import copyimport jsonimport osfrom pathlib import Path
from klein_code_bench.catalog import FAMILIESfrom klein_code_bench.protocol import TIERSfrom klein_code_bench.reference.domains import solve
class Fault(Exception): pass
def integer(value, minimum=0, maximum=None): return ( type(value) is int and value >= minimum and (maximum is None or value <= maximum) )
def req_op(request): return request.get("op") if isinstance(request, dict) else None
class Service: def __init__(self, family, tier, state_dir=None): self.family = FAMILIES[family] self.level = list(TIERS).index(tier) self.directory = Path(state_dir) if state_dir is not None else None self.state = {"revision": 0, "docs": {}, "history": [], "tokens": {}} self.stack = [] if self.directory is not None: self.directory.mkdir(parents=True, exist_ok=True) path = self.directory / "workspace.json" if path.exists(): self.state = json.loads(path.read_text(encoding="utf-8"))
def persist(self): if self.directory is None or self.stack: return path = self.directory / "workspace.json" temporary = self.directory / "workspace.tmp" with temporary.open("w", encoding="utf-8") as f: json.dump(self.state, f, ensure_ascii=True, allow_nan=False) f.flush() os.fsync(f.fileno()) os.replace(temporary, path) if os.name == "posix": fd = os.open(self.directory, os.O_RDONLY) try: os.fsync(fd) finally: os.close(fd)
def compute(self, value): if not isinstance(value, dict) or not all( k in value for k in self.family.required ): raise Fault("invalid_input") return solve(self.family.slug, copy.deepcopy(value))
def request(self, request): before, stack = copy.deepcopy(self.state), copy.deepcopy(self.stack) try: result = self.dispatch(request) response = {"ok": True, "result": result} # Writes inside a transaction remain volatile until outermost commit. if ( self.level == 3 and not self.stack and ( self.state != before or bool(stack) and req_op(request) == "commit" ) ): self.persist() return copy.deepcopy(response) except Fault as error: self.state, self.stack = before, stack return {"ok": False, "error": str(error)}
def dispatch(self, req, inside_batch=False): if not isinstance(req, dict) or not isinstance(req.get("op"), str): raise Fault("invalid_request") op = req["op"] allowed = {"solve"} if self.level >= 1: allowed |= {"put", "get", "delete", "list", "evaluate", "status"} if self.level >= 2: allowed |= {"batch", "begin", "commit", "rollback"} if self.level == 3: allowed |= {"history", "scan"} if op not in allowed: raise Fault("invalid_request") if inside_batch and op not in { "solve", "put", "get", "delete", "list", "evaluate", "status", }: raise Fault("invalid_request") token = req.get("token") if self.level == 3 and "token" in req: if ( inside_batch or op not in {"put", "delete", "batch"} or not isinstance(token, str) or not token ): raise Fault("invalid_request") canonical = json.dumps( {k: v for k, v in req.items() if k != "token"}, sort_keys=True, separators=(",", ":"), ) cached = self.state["tokens"].get(token) if cached: if cached["request"] != canonical: raise Fault("idempotency_conflict") return copy.deepcopy(cached["result"]) else: token = None result = self.execute(op, req) if token is not None: self.state["tokens"][token] = { "request": canonical, "result": copy.deepcopy(result), } return result
def execute(self, op, req): if op == "solve": return self.compute(req.get("input")) docs = self.state["docs"] if op in {"put", "get", "delete", "evaluate"}: key = req.get("key") if ( not isinstance(key, str) or not key or op == "put" and "value" not in req ): raise Fault("invalid_request") if self.level >= 2 and op in {"put", "delete"} and "if_revision" in req: if not integer(req["if_revision"]): raise Fault("invalid_request") if req["if_revision"] != self.state["revision"]: raise Fault("conflict") if op != "put" and key not in docs: raise Fault("not_found") if op == "get": return copy.deepcopy(docs[key]) if op == "evaluate": return self.compute(docs[key]["value"]) self.state["revision"] += 1 revision = self.state["revision"] if op == "put": docs[key] = { "key": key, "value": copy.deepcopy(req["value"]), "revision": revision, } else: del docs[key] if self.level == 3: event = {"revision": revision, "op": op, "key": key} if op == "put": event["value"] = copy.deepcopy(req["value"]) self.state["history"].append(event) return {"key": key, "revision": revision} if op == "list": prefix = req.get("prefix", "") if not isinstance(prefix, str): raise Fault("invalid_request") return sorted(k for k in docs if k.startswith(prefix)) if op == "status": return {"revision": self.state["revision"], "size": len(docs)} if op == "batch": commands = req.get("commands") if not isinstance(commands, list) or len(commands) > 32: raise Fault("invalid_request") return [self.dispatch(command, inside_batch=True) for command in commands] if op == "begin": if len(self.stack) >= 8: raise Fault("transaction_limit") self.stack.append(copy.deepcopy(self.state)) return {"depth": len(self.stack)} if op in {"commit", "rollback"}: if not self.stack: raise Fault("no_transaction") previous = self.stack.pop() if op == "rollback": self.state = previous return {"depth": len(self.stack)} if op == "history": after, limit = req.get("after", 0), req.get("limit", 100) if not integer(after) or not integer(limit, maximum=100): raise Fault("invalid_request") return copy.deepcopy( [e for e in self.state["history"] if e["revision"] > after][:limit] ) if op == "scan": prefix, after, limit = ( req.get("prefix", ""), req.get("after", ""), req.get("limit", 100), ) if ( not isinstance(prefix, str) or not isinstance(after, str) or not integer(limit, maximum=100) ): raise Fault("invalid_request") keys = sorted(k for k in docs if k.startswith(prefix) and k > after) chosen = keys[:limit] return { "items": [copy.deepcopy(docs[k]) for k in chosen], "next": chosen[-1] if chosen and len(keys) > len(chosen) else None, } raise Fault("invalid_request")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338"""Dependency-free local evaluator. This is process isolation, NOT a security sandbox."""
from __future__ import annotations
import hashlibimport jsonimport mathimport osimport selectorsimport shutilimport signalimport subprocessimport sysimport tempfileimport timefrom pathlib import Path
DATA = Path(__file__).parent / "data"MAX_OUTPUT = 1_048_576EXCLUDED = {".git", ".venv", "venv", "__pycache__", "node_modules", ".env"}
def load_tasks(subset=None, data_dir=None): root = Path(data_dir) if data_dir else DATA tiers = [subset] if subset else ["easy", "intermediate", "hard", "max"] if any(t not in {"easy", "intermediate", "hard", "max"} for t in tiers): raise ValueError("Unknown subset") for tier in tiers: for line in (root / f"{tier}.jsonl").read_text(encoding="utf-8").splitlines(): if line.strip(): yield json.loads(line)
def find_task(task_id, data_dir=None): for row in load_tasks(data_dir=data_dir): if row["task_id"] == task_id: return row raise ValueError(f"Unknown task: {task_id}")
def equal(actual, expected): if isinstance(expected, bool) or expected is None or isinstance(expected, str): return type(actual) is type(expected) and actual == expected if type(expected) in (int, float): if type(actual) not in (int, float): return False if type(actual) is int and type(expected) is int: return actual == expected return ( math.isfinite(actual) and math.isfinite(expected) and math.isclose(actual, expected, rel_tol=1e-9, abs_tol=1e-9) ) if isinstance(expected, list): return ( isinstance(actual, list) and len(actual) == len(expected) and all(equal(a, b) for a, b in zip(actual, expected)) ) if isinstance(expected, dict): return ( isinstance(actual, dict) and actual.keys() == expected.keys() and all(equal(actual[k], expected[k]) for k in expected) ) return False
def strict_json(line): def invalid(value): raise ValueError(f"Nonfinite JSON constant: {value}")
return json.loads(line, parse_constant=invalid)
def kill_group(process): if os.name == "posix": try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass elif process.poll() is None: process.kill() process.wait()
def child_environment(home): # Do not inherit credentials, PYTHONPATH, proxies, or user site configuration. return { "PATH": os.defpath, "HOME": str(home), "LANG": "C.UTF-8", "LC_ALL": "C.UTF-8", "TZ": "UTC", "PYTHONHASHSEED": "0", }
def copy_project(source, target): """No symlinks, special files, or environment files may enter a submission.""" source = Path(source).resolve() if not source.is_dir(): raise ValueError(f"Solution directory does not exist: {source}") count = size = 0 for root, dirs, files in os.walk(source, followlinks=False): base = Path(root) dirs[:] = sorted( d for d in dirs if d not in EXCLUDED and not (base / d).is_symlink() ) relative = base.relative_to(source) (target / relative).mkdir(parents=True, exist_ok=True) for name in sorted(files): if ( name in EXCLUDED or name.startswith(".env.") or name.endswith((".pyc", ".token")) ): continue path = base / name if path.is_symlink() or not path.is_file(): raise ValueError( f"Submission contains a symlink or special file: {relative / name}" ) count += 1 size += path.stat().st_size if count > 2000 or size > 20_000_000: raise ValueError("Submission exceeds 2000 files / 20 MB") shutil.copyfile(path, target / relative / name)
def run_session(project, state, session, *, durable=False, timeout=10.0): if os.name != "posix": raise RuntimeError( "The local evaluator requires POSIX process groups and pipe selectors" ) argv = [sys.executable, "-E", "-s", "-S", "main.py"] if durable: argv += ["--state-dir", str(state)] start = time.monotonic() deadline = start + timeout process = subprocess.Popen( argv, cwd=project, env=child_environment(state.parent / "home"), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, bufsize=0, ) selector = selectors.DefaultSelector() for pipe in (process.stdin, process.stdout, process.stderr): os.set_blocking(pipe.fileno(), False) selector.register(process.stdout, selectors.EVENT_READ, "out") selector.register(process.stderr, selectors.EVENT_READ, "err") buffer = b"" stderr = bytearray() output_bytes = passed = 0 failure = None actual = None
def read_events(wait): nonlocal buffer, output_bytes for key, _ in selector.select(max(0, wait)): if key.data == "in": continue chunk = os.read(key.fileobj.fileno(), 65536) if not chunk: selector.unregister(key.fileobj) continue if key.data == "out": buffer += chunk output_bytes += len(chunk) if output_bytes > MAX_OUTPUT: raise ValueError("stdout exceeded 1 MiB") elif len(stderr) < 8192: stderr.extend(chunk[: 8192 - len(stderr)])
try: if len(session["requests"]) != len(session["expected"]): raise ValueError("Invalid acceptance session lengths") for index, (request, expected) in enumerate( zip(session["requests"], session["expected"]) ): actual = None wire = ( request if isinstance(request, str) else json.dumps(request, ensure_ascii=True, allow_nan=False) ) + "\n" pending = memoryview(wire.encode("utf-8")) selector.register(process.stdin, selectors.EVENT_WRITE, "in") while pending: if time.monotonic() >= deadline: raise TimeoutError("session timeout while sending request") try: written = os.write(process.stdin.fileno(), pending) pending = pending[written:] except BlockingIOError: read_events(min(0.02, deadline - time.monotonic())) selector.unregister(process.stdin) while b"\n" not in buffer: remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError( "session timeout waiting for flushed JSON response" ) read_events(min(0.05, remaining)) if process.poll() is not None and b"\n" not in buffer: raise ValueError( f"process exited before response (code {process.returncode})" ) line, buffer = buffer.split(b"\n", 1) actual = strict_json(line.decode("utf-8")) if not equal(actual, expected): failure = { "request_index": index, "reason": "response mismatch", "expected": expected, "actual": actual, } break passed += 1 if failure is None: if durable: # Test persistence after acknowledgement without graceful shutdown hooks. kill_group(process) else: process.stdin.close() while process.poll() is None or selector.get_map(): if time.monotonic() >= deadline: raise TimeoutError("process did not exit cleanly on EOF") read_events(min(0.02, deadline - time.monotonic())) if process.returncode: raise ValueError(f"nonzero exit code {process.returncode}") # Catch extra lines even if the child has exited or was force-killed. read_events(0) if buffer: raise ValueError("extra stdout beyond one JSON response per request") except (ValueError, OSError, TimeoutError, UnicodeError) as error: failure = { "request_index": passed, "reason": str(error), "timed_out": isinstance(error, TimeoutError), } finally: kill_group(process) selector.close() for pipe in (process.stdin, process.stdout, process.stderr): if not pipe.closed: pipe.close() return { "passed": failure is None, "assertions_passed": passed, "assertions": len(session["expected"]), "duration": time.monotonic() - start, "failure": failure, "stderr": stderr.decode("utf-8", errors="replace") if failure else "", }
def evaluate(task, solution, *, timeout=None, tests=None, fail_fast=False): """A task passes only when every scenario and every restart session passes.""" traces = tests if tests is not None else json.loads(task["acceptance_tests"]) if not traces: raise ValueError("Refusing an empty acceptance suite") source = Path(solution).resolve() reports = [] began = time.monotonic() with tempfile.TemporaryDirectory(prefix="klein-bench-") as temporary: root = Path(temporary) clean = root / "submission" clean.mkdir() rejection = None try: copy_project(source, clean) except ValueError as error: rejection = str(error) if rejection or not (clean / "main.py").is_file(): return { "task_id": task["task_id"], "subset": task["subset"], "passed": False, "resolved": False, "reason": rejection or "main.py is missing", "scenarios": [], "duration": time.monotonic() - began, } source_hash = hashlib.sha256() for file in sorted(p for p in clean.rglob("*") if p.is_file()): source_hash.update(str(file.relative_to(clean)).encode()) source_hash.update(b"\0" + file.read_bytes() + b"\0") for index, trace in enumerate(traces): scenario = root / str(index) project, state = scenario / "project", scenario / "state" project.mkdir(parents=True) state.mkdir() (scenario / "home").mkdir() copy_project(clean, project) sessions = [] for session in trace["sessions"]: report = run_session( project, state, session, durable=task["subset"] == "max", timeout=timeout or task["timeout_seconds"], ) sessions.append(report) if not report["passed"]: break reports.append( { "name": trace["name"], "passed": all(s["passed"] for s in sessions), "sessions": sessions, } ) if fail_fast and not reports[-1]["passed"]: break passed = len(reports) == len(traces) and all(r["passed"] for r in reports) return { "task_id": task["task_id"], "subset": task["subset"], "passed": passed, "resolved": passed, "scenarios_passed": sum(r["passed"] for r in reports), "scenarios_total": len(traces), "assertions_passed": sum( s["assertions_passed"] for r in reports for s in r["sessions"] ), "assertions_total": sum( len(s["expected"]) for t in traces for s in t["sessions"] ), "source_sha256": source_hash.hexdigest(), "duration": time.monotonic() - began, "scenarios": reports, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451"""Acceptance scenarios: every scenario gets an independent project/state copy."""
from __future__ import annotations
import copyimport jsonimport random
from .catalog import FAMILIESfrom .fuzz import generated_inputsfrom .protocol import TIERSfrom .reference.service import Service
def scenarios(family, tier, seed=1729): f = FAMILIES[family] level = list(TIERS).index(tier) rng = random.Random(f"{seed}/{family}/{tier}") a, b, c = [ prefix + str(rng.randrange(10**8)) for prefix in ("doc/", "doc/", "other/") ] a, b = sorted((a, b)) value, other = copy.deepcopy(f.inputs[0]), copy.deepcopy(f.inputs[-1]) traces = []
def add(name, *sessions): traces.append( {"name": name, "sessions": [{"requests": list(s)} for s in sessions]} )
add( "generated-domain", [{"op": "solve", "input": v} for v in generated_inputs(family, seed=seed)], ) add("domain-boundaries", [{"op": "solve", "input": v} for v in f.inputs]) add( "protocol-errors", [ "{broken", "", "null", "[]", "42", {}, {"op": 1}, {"op": "unknown"}, {"op": "solve"}, {"op": "solve", "input": []}, {"op": "solve", "input": {}}, {"op": "solve", "input": value}, ], ) add( "required-fields", [ {"op": "solve", "input": {k: v for k, v in value.items() if k != missing}} for missing in f.required ] + [{"op": "solve", "input": dict(value, ignored_extra={"nested": True})}], ) if level == 0: add( "unsupported-store", [ {"op": "put", "key": a, "value": value}, {"op": "status"}, {"op": "batch", "commands": []}, ], ) if level >= 1: add( "document-lifecycle", [ {"op": "status"}, {"op": "list"}, {"op": "get", "key": a}, {"op": "put", "key": a, "value": value}, {"op": "evaluate", "key": a}, {"op": "get", "key": a}, {"op": "put", "key": a, "value": other}, {"op": "evaluate", "key": a}, {"op": "put", "key": b, "value": value}, {"op": "delete", "key": a}, {"op": "get", "key": a}, {"op": "delete", "key": a}, {"op": "get", "key": b}, {"op": "status"}, ], ) add( "listing-and-json-values", [ {"op": "put", "key": c, "value": None}, {"op": "put", "key": b, "value": [True, False, {"x": [1, None]}]}, {"op": "put", "key": a, "value": {}}, {"op": "put", "key": "../é/😀", "value": "value"}, {"op": "list"}, {"op": "list", "prefix": "doc/"}, {"op": "list", "prefix": "missing"}, {"op": "get", "key": c}, {"op": "evaluate", "key": c}, {"op": "evaluate", "key": a}, {"op": "get", "key": b}, {"op": "put", "key": c, "value": None}, {"op": "status"}, ], ) add( "store-errors", [ {"op": "put", "key": "", "value": 1}, {"op": "put", "key": a}, {"op": "put", "key": 1, "value": None}, {"op": "get"}, {"op": "delete", "key": []}, {"op": "list", "prefix": None}, {"op": "evaluate", "key": "missing"}, {"op": "status"}, ], ) if level == 1: add( "unsupported-transactions", [ {"op": "begin"}, {"op": "batch", "commands": []}, {"op": "history"}, {"op": "status"}, ], ) if level >= 2: add( "compare-and-swap", [ {"op": "put", "key": a, "value": value, "if_revision": 0}, {"op": "put", "key": b, "value": value, "if_revision": 0}, {"op": "delete", "key": "missing", "if_revision": 0}, {"op": "delete", "key": a, "if_revision": True}, {"op": "put", "key": a, "value": other, "if_revision": -1}, {"op": "put", "key": a, "value": other, "if_revision": 1}, {"op": "get", "key": a}, {"op": "delete", "key": a, "if_revision": 2}, {"op": "status"}, ], ) add( "atomic-batches", [ {"op": "batch", "commands": []}, { "op": "batch", "commands": [ {"op": "put", "key": a, "value": value}, {"op": "evaluate", "key": a}, {"op": "status"}, ], }, { "op": "batch", "commands": [ {"op": "put", "key": a, "value": other}, {"op": "delete", "key": "missing"}, ], }, {"op": "get", "key": a}, {"op": "status"}, { "op": "batch", "commands": [ {"op": "delete", "key": a}, {"op": "put", "key": b, "value": other, "if_revision": 2}, {"op": "list"}, ], }, {"op": "list"}, {"op": "status"}, ], ) add( "batch-errors", [ { "op": "batch", "commands": [ {"op": "put", "key": a, "value": value}, {"op": "begin"}, ], }, { "op": "batch", "commands": [ {"op": "put", "key": a, "value": value}, {"op": "batch", "commands": []}, ], }, {"op": "batch", "commands": [None]}, {"op": "batch", "commands": {}}, {"op": "batch", "commands": [{"op": "status"}] * 33}, { "op": "batch", "commands": [ {"op": "put", "key": a, "value": {}}, {"op": "evaluate", "key": a}, ], }, {"op": "status"}, {"op": "list"}, ], ) add( "nested-transactions", [ {"op": "commit"}, {"op": "rollback"}, {"op": "put", "key": a, "value": value}, {"op": "begin"}, {"op": "put", "key": a, "value": other}, {"op": "begin"}, {"op": "delete", "key": a}, {"op": "put", "key": b, "value": value}, {"op": "commit"}, {"op": "status"}, {"op": "rollback"}, {"op": "get", "key": a}, {"op": "get", "key": b}, {"op": "status"}, {"op": "begin"}, {"op": "delete", "key": a}, {"op": "rollback"}, {"op": "get", "key": a}, {"op": "begin"}, {"op": "put", "key": b, "value": other}, {"op": "commit"}, {"op": "status"}, ], ) add( "transaction-limits", [{"op": "begin"}] * 9 + [{"op": "put", "key": a, "value": value}] + [{"op": "rollback"}] * 9 + [{"op": "status"}], ) if level == 2: add( "unsupported-durability", [{"op": "history"}, {"op": "scan"}, {"op": "status"}], ) if level == 3: add( "durable-writes", [ {"op": "put", "key": a, "value": value}, {"op": "put", "key": b, "value": other}, ], [ {"op": "status"}, {"op": "get", "key": a}, {"op": "evaluate", "key": b}, {"op": "delete", "key": a}, ], [ {"op": "list"}, {"op": "get", "key": a}, {"op": "history"}, {"op": "status"}, ], ) add( "durable-commit", [ {"op": "begin"}, {"op": "put", "key": a, "value": value}, {"op": "begin"}, {"op": "put", "key": b, "value": other}, {"op": "commit"}, {"op": "commit"}, ], [ {"op": "get", "key": a}, {"op": "get", "key": b}, {"op": "history"}, {"op": "status"}, ], ) add( "discard-open-transactions", [ {"op": "put", "key": a, "value": value}, {"op": "begin"}, {"op": "put", "key": a, "value": other}, {"op": "begin"}, {"op": "put", "key": b, "value": value}, {"op": "commit"}, {"op": "status"}, ], [ {"op": "get", "key": a}, {"op": "get", "key": b}, {"op": "history"}, {"op": "status"}, {"op": "rollback"}, ], ) add( "pagination-and-history", [ {"op": "put", "key": b, "value": other}, {"op": "put", "key": a, "value": value}, {"op": "put", "key": c, "value": None}, {"op": "scan", "prefix": "doc/", "limit": 1}, {"op": "scan", "prefix": "doc/", "after": a, "limit": 1}, {"op": "scan", "limit": 0}, {"op": "scan", "after": "zzzz"}, {"op": "scan"}, {"op": "history", "after": 1, "limit": 1}, {"op": "delete", "key": a}, {"op": "history", "after": 2}, {"op": "begin"}, {"op": "put", "key": c, "value": {}}, {"op": "history"}, {"op": "rollback"}, {"op": "history"}, ], ) add( "durable-errors", [ {"op": "history", "after": True}, {"op": "history", "limit": 101}, {"op": "history", "limit": -1}, {"op": "scan", "prefix": None}, {"op": "scan", "after": 2}, {"op": "scan", "limit": False}, {"op": "get", "key": a, "token": "bad"}, {"op": "put", "key": a, "value": 1, "token": ""}, { "op": "batch", "commands": [ {"op": "put", "key": a, "value": value, "token": "nested"} ], }, {"op": "status"}, {"op": "history"}, ], ) first = { "op": "put", "key": a, "value": value, "if_revision": 0, "token": "request/α", } add( "idempotency-and-restart", [ first, dict(reversed(list(first.items()))), dict(first, value=other if other != value else None), {"op": "status"}, ], [ first, {"op": "history"}, {"op": "status"}, {"op": "delete", "key": a, "token": "delete"}, {"op": "delete", "key": a, "token": "delete"}, ], [ {"op": "delete", "key": a, "token": "delete"}, {"op": "history"}, {"op": "status"}, ], ) add( "failed-tokens-and-rollback", [ {"op": "delete", "key": a, "token": "retry"}, {"op": "put", "key": a, "value": value}, {"op": "delete", "key": a, "token": "retry"}, {"op": "begin"}, {"op": "put", "key": b, "value": other, "token": "tx"}, {"op": "rollback"}, {"op": "put", "key": b, "value": value, "token": "tx"}, { "op": "batch", "token": "atomic", "commands": [ {"op": "put", "key": c, "value": other}, {"op": "delete", "key": b}, ], }, { "op": "batch", "token": "atomic", "commands": [ {"op": "put", "key": c, "value": other}, {"op": "delete", "key": b}, ], }, {"op": "history"}, {"op": "status"}, ], [ {"op": "history"}, {"op": "status"}, {"op": "put", "key": b, "value": value, "token": "tx"}, ], ) add( "volatile-token-discard", [ {"op": "begin"}, {"op": "put", "key": a, "value": value, "token": "volatile"}, {"op": "begin"}, {"op": "commit"}, ], [ {"op": "put", "key": a, "value": other, "token": "volatile"}, {"op": "history"}, {"op": "status"}, ], ) return traces
def expected_scenarios(family, tier, seed=1729): """Materialize static expectations once; grading never loads reference code.""" traces = scenarios(family, tier, seed) for trace in traces: service = Service(family, tier) durable = copy.deepcopy(service.state) for session in trace["sessions"]: service = Service(family, tier) if tier == "max": service.state = copy.deepcopy(durable) expected = [] for request in session["requests"]: try: parsed = ( json.loads(request) if isinstance(request, str) else request ) except json.JSONDecodeError: response = {"ok": False, "error": "invalid_request"} else: response = service.request(parsed) expected.append(response) if tier == "max" and not service.stack: durable = copy.deepcopy(service.state) session["expected"] = expected return traces12345678910111213141516171819202122232425262728293031323334353637383940"""Strict all-tests-pass scoring; partial assertions are diagnostics only."""
from .protocol import TIERS
def summarize(reports): from .runner import load_tasks
catalog = {t["task_id"]: t for t in load_tasks()} seen = set() buckets = {tier: [] for tier in TIERS} for report in reports: task_id = report["task_id"] if task_id in seen: raise ValueError(f"Duplicate task report: {task_id}") seen.add(task_id) if task_id not in catalog or report.get("subset") != catalog[task_id]["subset"]: raise ValueError(f"Unknown task or mismatched subset: {task_id}") if report.get("evaluation_scope") == "public": raise ValueError("Public-only smoke tests cannot be scored") buckets[report["subset"]].append(report.get("resolved") is True) tiers = {} for tier, statuses in buckets.items(): resolved = sum(statuses) tiers[tier] = { "submitted": len(statuses), "total": 65, "resolved": resolved, "resolution_rate": resolved / 65, "submitted_resolution_rate": resolved / len(statuses) if statuses else None, } return { "metric": "resolve@1", "total": 260, "submitted": len(seen), "resolved": sum(r["resolved"] for r in tiers.values()), "resolution_rate": sum(r["resolved"] for r in tiers.values()) / 260, "complete": len(seen) == 260, "subsets": tiers, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from __future__ import annotations
import hashlibimport jsonimport tempfilefrom pathlib import Path
from .catalog import FAMILIESfrom .reference.domains import solvefrom .reference.export import export_referencefrom .runner import DATA, equal, evaluate, load_tasks
def validate(subset=None): manifest_bytes = (DATA / "manifest.json").read_bytes() manifest = json.loads(manifest_bytes) for name, digest in manifest["sha256"].items(): if hashlib.sha256((DATA / name).read_bytes()).hexdigest() != digest: raise ValueError(f"Manifest checksum mismatch: {name}") for f in FAMILIES.values(): if not equal(solve(f.slug, f.inputs[0]), f.golden): raise ValueError(f"Independent golden mismatch: {f.slug}") results = [] tasks = list(load_tasks(subset)) with tempfile.TemporaryDirectory(prefix="klein-validation-") as temporary: root = Path(temporary) empty = root / "empty" empty.mkdir() for index, task in enumerate(tasks, 1): project = root / task["task_id"] export_reference(task["family"], task["subset"], project) reference = evaluate(task, project, fail_fast=True) rejected_empty = not evaluate(task, empty)["passed"] results.append( { "task_id": task["task_id"], "passed": reference["passed"] and rejected_empty, "empty_rejected": rejected_empty, "reference": reference, } ) print( f"[{index}/{len(tasks)}] {task['task_id']}: {'PASS' if results[-1]['passed'] else 'FAIL'}", flush=True, ) if (DATA / "manifest.json").read_bytes() != manifest_bytes: raise ValueError( "Dataset changed during validation; rerun against a stable snapshot" ) return { "passed": all(r["passed"] for r in results), "tasks": len(results), "reference_passes": sum(r["reference"]["passed"] for r in results), "empty_rejected": sum(r["empty_rejected"] for r in results), "assertions": sum(r["reference"].get("assertions_total", 0) for r in results), "manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(), "results": results, }12345678910111213141516171819202122232425[build-system]requires = ["setuptools>=68"]build-backend = "setuptools.build_meta"
[project]name = "klein-code-bench"version = "0.1.0"description = "260 from-scratch Python project tasks for local language models"readme = "README.md"requires-python = ">=3.11"license = "MIT"authors = [{name = "Klein ML"}]dependencies = []
[project.optional-dependencies]publish = ["huggingface-hub>=0.26,<2"]
[project.scripts]klein-bench = "klein_code_bench.cli:main"
[tool.setuptools.packages.find]include = ["klein_code_bench*"]
[tool.setuptools.package-data]klein_code_bench = ["data/*.jsonl", "data/*.json"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328import copyimport hashlibimport jsonimport tempfileimport unittestfrom pathlib import Path
from klein_code_bench.build import buildfrom klein_code_bench.catalog import FAMILIESfrom klein_code_bench.fuzz import generated_inputsfrom klein_code_bench.reference.domains import solvefrom klein_code_bench.reference.export import export_referencefrom klein_code_bench.reference.service import Servicefrom klein_code_bench.runner import ( DATA, copy_project, equal, evaluate, load_tasks, run_session,)from klein_code_bench.scoring import summarize
class DomainTests(unittest.TestCase): def test_all_65_independent_goldens(self): self.assertEqual(len(FAMILIES), 65) for family in FAMILIES.values(): with self.subTest(family=family.slug): self.assertTrue( equal(solve(family.slug, family.inputs[0]), family.golden) )
def test_generators_cover_every_family_without_mutating_input(self): for family in FAMILIES: for data in generated_inputs(family): original = copy.deepcopy(data) json.dumps(solve(family, data), allow_nan=False) self.assertEqual(data, original, family)
def test_money_conservation(self): for x in generated_inputs("money_split", count=100): shares = solve("money_split", x) self.assertEqual(sum(shares), x["amount"]) self.assertTrue(all(v >= 0 for v in shares))
def test_knapsack_against_exhaustive_subsets(self): for x in generated_inputs("knapsack", count=50): best = max( sum(item["value"] for i, item in enumerate(x["items"]) if mask >> i & 1) for mask in range(1 << len(x["items"])) if sum( item["weight"] for i, item in enumerate(x["items"]) if mask >> i & 1 ) <= x["capacity"] ) self.assertEqual(solve("knapsack", x), best)
def test_shortest_path_against_bellman_ford(self): for x in generated_inputs("shortest_path", count=50): d = {n: float("inf") for n in x["nodes"]} d[x["start"]] = 0 for _ in x["nodes"]: for a, b, w in x["edges"]: d[b] = min(d[b], d[a] + w) expected = {k: v if v != float("inf") else None for k, v in d.items()} self.assertEqual(solve("shortest_path", x), expected)
def test_factorization_reconstructs_input(self): for x in generated_inputs("prime_factors", count=100): product = 1 for p, exponent in solve("prime_factors", x): self.assertTrue(all(p % d for d in range(2, int(p**0.5) + 1))) product *= p**exponent self.assertEqual(product, x["number"])
def test_base_conversion_roundtrip(self): for x in generated_inputs("base_convert", count=100): self.assertEqual( int(solve("base_convert", x), x["to_base"]), int(x["digits"]) )
def test_sequence_script_reconstructs_both_inputs(self): for x in generated_inputs("sequence_diff", count=100): result = solve("sequence_diff", x) self.assertEqual([v for op, v in result if op != "insert"], x["a"]) self.assertEqual([v for op, v in result if op != "delete"], x["b"])
class ServiceTests(unittest.TestCase): def setUp(self): self.s = Service("word_frequency", "max")
def call(self, op, **kwargs): return self.s.request(dict(op=op, **kwargs))
def test_revisions_and_failed_cas(self): self.assertEqual( self.call("put", key="a", value=None), {"ok": True, "result": {"key": "a", "revision": 1}}, ) self.assertEqual( self.call("delete", key="missing", if_revision=0), {"ok": False, "error": "conflict"}, ) self.assertEqual( self.call("get", key="a")["result"], {"key": "a", "value": None, "revision": 1}, ) self.assertEqual(self.call("status")["result"], {"revision": 1, "size": 1})
def test_batch_rollback_and_revision_reuse(self): self.assertEqual( self.call( "batch", commands=[ {"op": "put", "key": "a", "value": 1}, {"op": "get", "key": "bad"}, ], ), {"ok": False, "error": "not_found"}, ) self.assertEqual(self.call("status")["result"], {"revision": 0, "size": 0}) self.assertEqual(self.call("history")["result"], []) self.assertEqual(self.call("put", key="b", value=2)["result"]["revision"], 1)
def test_nested_commit_outer_rollback(self): self.call("begin") self.call("put", key="a", value=1) self.call("begin") self.call("put", key="b", value=2) self.assertEqual(self.call("commit")["result"], {"depth": 1}) self.assertEqual(self.call("rollback")["result"], {"depth": 0}) self.assertEqual(self.call("list")["result"], []) self.assertEqual(self.call("history")["result"], [])
def test_idempotent_request_checks_cache_before_cas(self): first = self.call("put", key="a", value=1, token="t", if_revision=0) self.assertEqual( self.call("put", key="a", value=1, token="t", if_revision=0), first ) self.assertEqual(self.call("status")["result"]["revision"], 1) self.assertEqual( self.call("put", key="a", value=2, token="t"), {"ok": False, "error": "idempotency_conflict"}, )
def test_failed_and_rolled_back_tokens_forgotten(self): self.call("delete", key="a", token="t") self.assertTrue(self.call("put", key="a", value=1, token="t")["ok"]) self.call("begin") self.call("put", key="b", value=2, token="u") self.call("rollback") self.assertTrue(self.call("put", key="b", value=3, token="u")["ok"])
def test_evaluate_is_read_only(self): self.call("put", key="a", value={"text": "x x"}) self.assertEqual( self.call("evaluate", key="a")["result"], [{"word": "x", "count": 2}] ) self.assertEqual(self.call("get", key="a")["result"]["value"], {"text": "x x"}) self.assertEqual(self.call("status")["result"]["revision"], 1)
def test_scan_pages(self): for key in ["c", "a", "b"]: self.call("put", key=key, value=key) self.assertEqual( self.call("scan", limit=1)["result"], {"items": [{"key": "a", "value": "a", "revision": 2}], "next": "a"}, ) self.assertEqual(self.call("scan", after="b", limit=1)["result"]["next"], None) self.assertEqual( self.call("scan", limit=0)["result"], {"items": [], "next": None} )
def test_outer_commit_is_durable_and_open_transaction_is_not(self): with tempfile.TemporaryDirectory() as d: self.s = Service("word_frequency", "max", d) self.call("begin") self.call("put", key="a", value={"text": "saved"}, token="t") self.call("commit") self.call("begin") self.call("delete", key="a") reloaded = Service("word_frequency", "max", d) self.assertEqual( reloaded.request({"op": "get", "key": "a"})["result"]["revision"], 1 ) self.assertEqual(reloaded.state["tokens"].keys(), {"t"}) self.assertEqual(len(reloaded.state["history"]), 1)
class DatasetTests(unittest.TestCase): def test_exact_counts_unique_ids_and_manifest(self): rows = list(load_tasks()) self.assertEqual(len(rows), 260) self.assertEqual(len({r["task_id"] for r in rows}), 260) for tier in ["easy", "intermediate", "hard", "max"]: self.assertEqual(sum(r["subset"] == tier for r in rows), 65) manifest = json.loads((DATA / "manifest.json").read_text()) for name, digest in manifest["sha256"].items(): self.assertEqual( hashlib.sha256((DATA / name).read_bytes()).hexdigest(), digest )
def test_build_reproducible(self): with tempfile.TemporaryDirectory() as d: build(d) for file in DATA.iterdir(): if file.suffix in {".json", ".jsonl"}: self.assertEqual( file.read_bytes(), (Path(d) / file.name).read_bytes(), file.name )
def test_public_examples_in_prompt_and_nonempty_acceptance(self): for row in load_tasks(): self.assertTrue(json.loads(row["public_tests"])) traces = json.loads(row["acceptance_tests"]) self.assertTrue(traces) self.assertEqual( row["num_assertions"], sum(len(s["expected"]) for t in traces for s in t["sessions"]), ) for trace in traces: for session in trace["sessions"]: self.assertTrue(session["requests"]) self.assertEqual(len(session["requests"]), len(session["expected"]))
def test_scoring_uses_full_denominator_and_rejects_smoke(self): row = next(load_tasks("easy")) report = {"task_id": row["task_id"], "subset": "easy", "resolved": True} self.assertEqual( summarize([report])["subsets"]["easy"]["resolution_rate"], 1 / 65 ) with self.assertRaises(ValueError): summarize([report, report]) with self.assertRaises(ValueError): summarize([dict(report, evaluation_scope="public")])
class RunnerTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() self.root = Path(self.temporary.name) self.project, self.state = self.root / "project", self.root / "state" self.project.mkdir() self.state.mkdir() self.session = { "requests": [{"op": "status"}], "expected": [{"ok": True, "result": 7}], }
def tearDown(self): self.temporary.cleanup()
def run_code(self, code, timeout=1): (self.project / "main.py").write_text(code) return run_session(self.project, self.state, self.session, timeout=timeout)
def test_response_and_clean_exit(self): self.assertTrue( self.run_code( 'import sys\nfor line in sys.stdin:\n print(\'{"ok":true,"result":7}\', flush=True)\n' )["passed"] )
def test_rejects_wrong_boolean_numeric_type(self): self.assertFalse(equal(True, 1)) self.assertFalse(equal(1, True)) self.assertFalse(equal(float("nan"), 1)) self.assertTrue(equal(1.0, 1)) self.assertFalse(equal(10**30, 10**30 + 1))
def test_timeout_without_output(self): self.assertFalse( self.run_code("import time\ntime.sleep(20)", timeout=0.2)["passed"] )
def test_failure_on_nonzero_exit(self): self.assertFalse( self.run_code( 'import sys\nsys.stdin.readline()\nprint(\'{"ok":true,"result":7}\',flush=True)\nsys.exit(1)' )["passed"] )
def test_rejects_extra_stdout(self): self.assertFalse( self.run_code( 'import sys\nsys.stdin.readline()\nprint(\'{"ok":true,"result":7}\')\nprint("extra",flush=True)' )["passed"] )
def test_output_flood_is_bounded(self): self.assertFalse( self.run_code('import os\nwhile True: os.write(1,b"x"*65536)')["passed"] )
def test_stderr_flood_does_not_deadlock(self): self.assertTrue( self.run_code( 'import os,sys\nfor line in sys.stdin:\n os.write(2,b"x"*200000)\n print(\'{"ok":true,"result":7}\',flush=True)' )["passed"] )
def test_symlinks_rejected(self): (self.project / "main.py").symlink_to("/etc/passwd") target = self.root / "copied" target.mkdir() with self.assertRaises(ValueError): copy_project(self.project, target)
def test_invalid_submission_is_failed_rather_than_infrastructure_error(self): (self.project / "main.py").symlink_to("/etc/passwd") result = evaluate(next(load_tasks("easy")), self.project) self.assertFalse(result["resolved"]) self.assertIn("symlink", result["reason"])
def test_reference_max_restart_and_empty_submission(self): row = next(load_tasks("max")) export_reference(row["family"], "max", self.project) result = evaluate(row, self.project) self.assertTrue(result["passed"], result) empty = self.root / "empty" empty.mkdir() self.assertFalse(evaluate(row, empty)["passed"])
if __name__ == "__main__": unittest.main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Publish reviewed benchmark artifacts, never local credentials or workspaces."""
import argparseimport hashlibimport jsonfrom pathlib import Path
def main(): from huggingface_hub import HfApi
parser = argparse.ArgumentParser() parser.add_argument("--repo", default="klein-ml/klein-code-bench") args = parser.parse_args() root = Path(__file__).resolve().parents[1] summary = json.loads((root / "validation-summary.json").read_text()) digest = hashlib.sha256( (root / "klein_code_bench/data/manifest.json").read_bytes() ).hexdigest() if ( not summary["passed"] or summary["tasks"] != 260 or summary["manifest_sha256"] != digest ): raise SystemExit( "Full validation of the current dataset is required before publishing" ) api = HfApi() api.create_repo( repo_id=args.repo, repo_type="dataset", private=False, exist_ok=True ) result = api.upload_folder( repo_id=args.repo, repo_type="dataset", folder_path=str(root), allow_patterns=[ "README.md", "LICENSE", "pyproject.toml", ".gitignore", ".github/workflows/*.yml", "klein_code_bench/*.py", "klein_code_bench/reference/*.py", "klein_code_bench/data/*.jsonl", "klein_code_bench/data/*.json", "tests/*.py", "docs/*.md", "tools/*.py", "dist/*.whl", "validation-summary.json", ], commit_message="Release Klein-Code-Bench v0.1.0: 260 validated project-generation tasks", ) print(result.oid) print(f"https://huggingface.co/datasets/{args.repo}")
if __name__ == "__main__": main()12345678910111213141516{ "passed": true, "tasks": 260, "reference_passes": 260, "empty_rejected": 260, "assertions": 33685, "manifest_sha256": "a8b5fe2378da63c1fac3a093b7a762d8793e9573fc2025bfb5a8de4e8bcd838b", "unit_tests": { "passed": 30, "failed": 0 }, "package_smoke_test": "passed: clean wheel install, all 260 bundled tasks", "python_version": "3.14.7", "platform": "Linux", "purpose": "Evaluator/reference validation, not a model score."}.gitattributes+1
.github/workflows/checks.ymlAdded+16
.gitignoreAdded+11
LICENSEAdded+21
README.mdAdded+143
dist/klein_code_bench-0.1.0-py3-none-any.whlAdded+3
docs/BANANA_HARNESS.mdAdded+21
docs/CATALOG.mdAdded+343
docs/EVALUATION.mdAdded+30
klein_code_bench/__init__.pyAdded+3
klein_code_bench/__main__.pyAdded+3
klein_code_bench/build.pyAdded+108
klein_code_bench/catalog.pyAdded+1194
klein_code_bench/cli.pyAdded+136
klein_code_bench/data/easy.jsonlAdded
klein_code_bench/data/hard.jsonlAdded
klein_code_bench/data/intermediate.jsonlAdded
klein_code_bench/data/manifest.jsonAdded+27
klein_code_bench/data/max.jsonlAdded
klein_code_bench/fuzz.pyAdded+426
klein_code_bench/protocol.pyAdded+47
klein_code_bench/reference/__init__.pyAdded+1
klein_code_bench/reference/domains.pyAdded+869
klein_code_bench/reference/export.pyAdded+53
klein_code_bench/reference/service.pyAdded+228
klein_code_bench/runner.pyAdded+338
klein_code_bench/scenarios.pyAdded+451
klein_code_bench/scoring.pyAdded+40
klein_code_bench/validation.pyAdded+58
pyproject.tomlAdded+25
tests/test_benchmark.pyAdded+328
tools/publish_hf.pyAdded+59
validation-summary.jsonAdded+16