Datasets:
Release Klein-Code-Bench v0.1.0: 260 validated project-generation tasks
Browse files- .gitattributes +1 -0
- .github/workflows/checks.yml +16 -0
- .gitignore +11 -0
- LICENSE +21 -0
- README.md +143 -0
- dist/klein_code_bench-0.1.0-py3-none-any.whl +3 -0
- docs/BANANA_HARNESS.md +21 -0
- docs/CATALOG.md +343 -0
- docs/EVALUATION.md +30 -0
- klein_code_bench/__init__.py +3 -0
- klein_code_bench/__main__.py +3 -0
- klein_code_bench/build.py +108 -0
- klein_code_bench/catalog.py +1194 -0
- klein_code_bench/cli.py +136 -0
- klein_code_bench/data/easy.jsonl +0 -0
- klein_code_bench/data/hard.jsonl +0 -0
- klein_code_bench/data/intermediate.jsonl +0 -0
- klein_code_bench/data/manifest.json +27 -0
- klein_code_bench/data/max.jsonl +0 -0
- klein_code_bench/fuzz.py +426 -0
- klein_code_bench/protocol.py +47 -0
- klein_code_bench/reference/__init__.py +1 -0
- klein_code_bench/reference/domains.py +869 -0
- klein_code_bench/reference/export.py +53 -0
- klein_code_bench/reference/service.py +228 -0
- klein_code_bench/runner.py +338 -0
- klein_code_bench/scenarios.py +451 -0
- klein_code_bench/scoring.py +40 -0
- klein_code_bench/validation.py +58 -0
- pyproject.toml +25 -0
- tests/test_benchmark.py +328 -0
- tools/publish_hf.py +59 -0
- validation-summary.json +16 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
dist/klein_code_bench-0.1.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/checks.yml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: benchmark checks
|
| 2 |
+
on: [push, pull_request]
|
| 3 |
+
jobs:
|
| 4 |
+
test:
|
| 5 |
+
runs-on: ubuntu-latest
|
| 6 |
+
strategy:
|
| 7 |
+
matrix:
|
| 8 |
+
python-version: ['3.11', '3.12', '3.13', '3.14']
|
| 9 |
+
steps:
|
| 10 |
+
- uses: actions/checkout@v4
|
| 11 |
+
- uses: actions/setup-python@v5
|
| 12 |
+
with:
|
| 13 |
+
python-version: ${{ matrix.python-version }}
|
| 14 |
+
- run: python -m pip install -e .
|
| 15 |
+
- run: python -m unittest discover -s tests -v
|
| 16 |
+
- run: python -m klein_code_bench validate
|
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.venv/
|
| 4 |
+
*.egg-info/
|
| 5 |
+
build/
|
| 6 |
+
dist/
|
| 7 |
+
results/
|
| 8 |
+
workspaces/
|
| 9 |
+
.env
|
| 10 |
+
.env.*
|
| 11 |
+
*.token
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Klein ML
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
license: mit
|
| 5 |
+
pretty_name: Klein-Code-Bench
|
| 6 |
+
task_categories:
|
| 7 |
+
- text-generation
|
| 8 |
+
tags:
|
| 9 |
+
- code
|
| 10 |
+
- benchmark
|
| 11 |
+
- project-generation
|
| 12 |
+
- small-language-models
|
| 13 |
+
- local-models
|
| 14 |
+
- python
|
| 15 |
+
size_categories:
|
| 16 |
+
- n<1K
|
| 17 |
+
configs:
|
| 18 |
+
- config_name: default
|
| 19 |
+
default: true
|
| 20 |
+
data_files:
|
| 21 |
+
- split: test
|
| 22 |
+
path: klein_code_bench/data/*.jsonl
|
| 23 |
+
- config_name: easy
|
| 24 |
+
data_files:
|
| 25 |
+
- split: test
|
| 26 |
+
path: klein_code_bench/data/easy.jsonl
|
| 27 |
+
- config_name: intermediate
|
| 28 |
+
data_files:
|
| 29 |
+
- split: test
|
| 30 |
+
path: klein_code_bench/data/intermediate.jsonl
|
| 31 |
+
- config_name: hard
|
| 32 |
+
data_files:
|
| 33 |
+
- split: test
|
| 34 |
+
path: klein_code_bench/data/hard.jsonl
|
| 35 |
+
- config_name: max
|
| 36 |
+
data_files:
|
| 37 |
+
- split: test
|
| 38 |
+
path: klein_code_bench/data/max.jsonl
|
| 39 |
+
---
|
| 40 |
+
|
| 41 |
+
# Klein-Code-Bench
|
| 42 |
+
|
| 43 |
+
**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.
|
| 44 |
+
|
| 45 |
+
| Subset | Target model size | Project to build | Tasks |
|
| 46 |
+
| --- | --- | --- | ---: |
|
| 47 |
+
| easy | 2–8B | JSONL command-line tool with a domain algorithm and error recovery | 65 |
|
| 48 |
+
| intermediate | 8–16B | Stateful document service with CRUD, listing and domain evaluation | 65 |
|
| 49 |
+
| hard | 16–32B | Service with atomic batches, revision checks and nested transactions | 65 |
|
| 50 |
+
| max | 60–200B | Durable service with forced-kill recovery, idempotency, history and pagination | 65 |
|
| 51 |
+
|
| 52 |
+
**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.
|
| 53 |
+
|
| 54 |
+
## What the tasks measure
|
| 55 |
+
|
| 56 |
+
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).
|
| 57 |
+
|
| 58 |
+
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.
|
| 59 |
+
|
| 60 |
+
**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.
|
| 61 |
+
|
| 62 |
+
## Quick start (Python 3.11+, Linux or macOS)
|
| 63 |
+
|
| 64 |
+
Clone this Hugging Face dataset repository, then install the evaluator:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
git clone https://huggingface.co/datasets/klein-ml/klein-code-bench
|
| 68 |
+
cd klein-code-bench
|
| 69 |
+
python -m pip install -e .
|
| 70 |
+
klein-bench list --subset easy
|
| 71 |
+
|
| 72 |
+
# Put the prompt outside the initially empty project directory.
|
| 73 |
+
klein-bench prepare kcb-easy-001-word-frequency --output workspaces/first
|
| 74 |
+
# Give workspaces/first/PROMPT.md to your coding model.
|
| 75 |
+
# Have the model create files inside workspaces/first/project/.
|
| 76 |
+
|
| 77 |
+
klein-bench evaluate kcb-easy-001-word-frequency \
|
| 78 |
+
--solution workspaces/first/project --output results/first.json
|
| 79 |
+
klein-bench score results/first.json
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
`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.
|
| 83 |
+
|
| 84 |
+
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.
|
| 85 |
+
|
| 86 |
+
## Load with Hugging Face Datasets
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
from datasets import load_dataset
|
| 90 |
+
|
| 91 |
+
easy = load_dataset("klein-ml/klein-code-bench", "easy", split="test")
|
| 92 |
+
all_tasks = load_dataset("klein-ml/klein-code-bench", split="test")
|
| 93 |
+
assert len(easy) == 65
|
| 94 |
+
assert len(all_tasks) == 260
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
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.
|
| 98 |
+
|
| 99 |
+
The JSONL rows contain:
|
| 100 |
+
|
| 101 |
+
| Field | Meaning |
|
| 102 |
+
| --- | --- |
|
| 103 |
+
| `task_id` | Stable unique identifier |
|
| 104 |
+
| `subset`, `family`, `category`, `title` | Tier and project descriptors |
|
| 105 |
+
| `target_model_parameters` | Intended parameter band, uncalibrated |
|
| 106 |
+
| `language`, `entrypoint`, `protocol_version` | Python, main.py and contract version |
|
| 107 |
+
| `prompt` | Entire participant-visible project specification |
|
| 108 |
+
| `public_tests` | JSON-encoded list of example requests and responses |
|
| 109 |
+
| `acceptance_tests` | JSON-encoded evaluator scenarios, with sessions, requests and expected responses |
|
| 110 |
+
| `num_scenarios`, `num_assertions`, `timeout_seconds` | Evaluation sizes and per-session wall-clock limit |
|
| 111 |
+
|
| 112 |
+
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.
|
| 113 |
+
|
| 114 |
+
## Scoring and reproducibility
|
| 115 |
+
|
| 116 |
+
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.
|
| 117 |
+
|
| 118 |
+
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.
|
| 119 |
+
|
| 120 |
+
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.
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
# Unit/property tests for the benchmark and runner:
|
| 124 |
+
python -m unittest discover -s tests -v
|
| 125 |
+
|
| 126 |
+
# Regenerate data and manifest from authored source:
|
| 127 |
+
klein-bench build
|
| 128 |
+
|
| 129 |
+
# Export and run every trusted reference project, and reject every empty project:
|
| 130 |
+
klein-bench validate --output results/validation.json
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
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.
|
| 134 |
+
|
| 135 |
+
## Execution boundary
|
| 136 |
+
|
| 137 |
+
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.
|
| 138 |
+
|
| 139 |
+
## Release, provenance and limitations
|
| 140 |
+
|
| 141 |
+
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.
|
| 142 |
+
|
| 143 |
+
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.
|
dist/klein_code_bench-0.1.0-py3-none-any.whl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d83fa0ec5908e855707323411d0b743581d57468b532bfd8097828ef96f11841
|
| 3 |
+
size 791399
|
docs/BANANA_HARNESS.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# banana-harness integration
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
From a banana-harness checkout with the Klein adapter:
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
# Both checkouts are local; the benchmark evaluator has no runtime dependencies.
|
| 9 |
+
python -m pip install -e /path/to/klein-code-bench
|
| 10 |
+
python -m pip install -e '/path/to/banana-harness[models,datasets]'
|
| 11 |
+
|
| 12 |
+
# Endpoint options use the harness's --model-options JSON file.
|
| 13 |
+
printf '%s\n' '{"api_base":"http://127.0.0.1:8000/v1","api_key":"local","temperature":0}' > local-model.json
|
| 14 |
+
banana run klein-code-bench --allow-downloads --dataset-config easy \
|
| 15 |
+
--backend native --model openai/your-local-model \
|
| 16 |
+
--model-options local-model.json --output jobs/klein-easy
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
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.
|
| 20 |
+
|
| 21 |
+
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.
|
docs/CATALOG.md
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project catalog
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
| # | Family | Category | Domain behavior |
|
| 6 |
+
| --- | --- | --- | --- |
|
| 7 |
+
| 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. |
|
| 8 |
+
| 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. |
|
| 9 |
+
| 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 []. |
|
| 10 |
+
| 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. |
|
| 11 |
+
| 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. |
|
| 12 |
+
| 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 []. |
|
| 13 |
+
| 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. |
|
| 14 |
+
| 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. |
|
| 15 |
+
| 009 | roman_codec | text | Input: integer number in 1..3999. Return canonical uppercase Roman numeral using subtractive pairs IV,IX,XL,XC,CD,CM. |
|
| 16 |
+
| 010 | caesar_cipher | text | Input: text and integer shift. Rotate only ASCII letters by shift modulo 26, preserving case. All other characters unchanged. |
|
| 17 |
+
| 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. |
|
| 18 |
+
| 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. |
|
| 19 |
+
| 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. |
|
| 20 |
+
| 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 []. |
|
| 21 |
+
| 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. |
|
| 22 |
+
| 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. |
|
| 23 |
+
| 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. |
|
| 24 |
+
| 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. |
|
| 25 |
+
| 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. |
|
| 26 |
+
| 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. |
|
| 27 |
+
| 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. |
|
| 28 |
+
| 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. |
|
| 29 |
+
| 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. |
|
| 30 |
+
| 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. |
|
| 31 |
+
| 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. |
|
| 32 |
+
| 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 []. |
|
| 33 |
+
| 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. |
|
| 34 |
+
| 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}. |
|
| 35 |
+
| 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. |
|
| 36 |
+
| 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. |
|
| 37 |
+
| 031 | prime_factors | numeric | Input: integer number in 1..10000000. Return [prime,exponent] pairs in ascending prime order; 1 returns []. |
|
| 38 |
+
| 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. |
|
| 39 |
+
| 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. |
|
| 40 |
+
| 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. |
|
| 41 |
+
| 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. |
|
| 42 |
+
| 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. |
|
| 43 |
+
| 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. |
|
| 44 |
+
| 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. |
|
| 45 |
+
| 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. |
|
| 46 |
+
| 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. |
|
| 47 |
+
| 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. |
|
| 48 |
+
| 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. |
|
| 49 |
+
| 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. |
|
| 50 |
+
| 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. |
|
| 51 |
+
| 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. |
|
| 52 |
+
| 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. |
|
| 53 |
+
| 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. |
|
| 54 |
+
| 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}. |
|
| 55 |
+
| 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. |
|
| 56 |
+
| 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}. |
|
| 57 |
+
| 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. |
|
| 58 |
+
| 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. |
|
| 59 |
+
| 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. |
|
| 60 |
+
| 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. |
|
| 61 |
+
| 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. |
|
| 62 |
+
| 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. |
|
| 63 |
+
| 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. |
|
| 64 |
+
| 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 []. |
|
| 65 |
+
| 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. |
|
| 66 |
+
| 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. |
|
| 67 |
+
| 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. |
|
| 68 |
+
| 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. |
|
| 69 |
+
| 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. |
|
| 70 |
+
| 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. |
|
| 71 |
+
| 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. |
|
| 72 |
+
|
| 73 |
+
## Easy — 2–8B target
|
| 74 |
+
|
| 75 |
+
- `kcb-easy-001-word-frequency`
|
| 76 |
+
- `kcb-easy-002-slug-registry`
|
| 77 |
+
- `kcb-easy-003-run-length`
|
| 78 |
+
- `kcb-easy-004-bracket-audit`
|
| 79 |
+
- `kcb-easy-005-text-wrap`
|
| 80 |
+
- `kcb-easy-006-ngram-index`
|
| 81 |
+
- `kcb-easy-007-glob-filter`
|
| 82 |
+
- `kcb-easy-008-edit-distance`
|
| 83 |
+
- `kcb-easy-009-roman-codec`
|
| 84 |
+
- `kcb-easy-010-caesar-cipher`
|
| 85 |
+
- `kcb-easy-011-csv-records`
|
| 86 |
+
- `kcb-easy-012-record-query`
|
| 87 |
+
- `kcb-easy-013-inner-join`
|
| 88 |
+
- `kcb-easy-014-group-totals`
|
| 89 |
+
- `kcb-easy-015-json-flatten`
|
| 90 |
+
- `kcb-easy-016-merge-patch`
|
| 91 |
+
- `kcb-easy-017-json-pointer`
|
| 92 |
+
- `kcb-easy-018-dedupe-records`
|
| 93 |
+
- `kcb-easy-019-pivot-table`
|
| 94 |
+
- `kcb-easy-020-schema-check`
|
| 95 |
+
- `kcb-easy-021-interval-union`
|
| 96 |
+
- `kcb-easy-022-interval-gaps`
|
| 97 |
+
- `kcb-easy-023-booking-peak`
|
| 98 |
+
- `kcb-easy-024-business-days`
|
| 99 |
+
- `kcb-easy-025-calendar-month`
|
| 100 |
+
- `kcb-easy-026-moving-average`
|
| 101 |
+
- `kcb-easy-027-statistics`
|
| 102 |
+
- `kcb-easy-028-histogram`
|
| 103 |
+
- `kcb-easy-029-matrix-product`
|
| 104 |
+
- `kcb-easy-030-polynomial`
|
| 105 |
+
- `kcb-easy-031-prime-factors`
|
| 106 |
+
- `kcb-easy-032-base-convert`
|
| 107 |
+
- `kcb-easy-033-money-split`
|
| 108 |
+
- `kcb-easy-034-invoice-total`
|
| 109 |
+
- `kcb-easy-035-coin-change`
|
| 110 |
+
- `kcb-easy-036-graph-reach`
|
| 111 |
+
- `kcb-easy-037-shortest-path`
|
| 112 |
+
- `kcb-easy-038-topological-order`
|
| 113 |
+
- `kcb-easy-039-connected-components`
|
| 114 |
+
- `kcb-easy-040-grid-route`
|
| 115 |
+
- `kcb-easy-041-tree-outline`
|
| 116 |
+
- `kcb-easy-042-dependency-build`
|
| 117 |
+
- `kcb-easy-043-path-normalize`
|
| 118 |
+
- `kcb-easy-044-url-query`
|
| 119 |
+
- `kcb-easy-045-version-sort`
|
| 120 |
+
- `kcb-easy-046-lru-trace`
|
| 121 |
+
- `kcb-easy-047-rate-limit`
|
| 122 |
+
- `kcb-easy-048-priority-queue`
|
| 123 |
+
- `kcb-easy-049-round-robin`
|
| 124 |
+
- `kcb-easy-050-inventory-ledger`
|
| 125 |
+
- `kcb-easy-051-bank-ledger`
|
| 126 |
+
- `kcb-easy-052-ballot-count`
|
| 127 |
+
- `kcb-easy-053-search-rank`
|
| 128 |
+
- `kcb-easy-054-log-summary`
|
| 129 |
+
- `kcb-easy-055-uptime-report`
|
| 130 |
+
- `kcb-easy-056-segment-intersection`
|
| 131 |
+
- `kcb-easy-057-polygon-area`
|
| 132 |
+
- `kcb-easy-058-skyline`
|
| 133 |
+
- `kcb-easy-059-knapsack`
|
| 134 |
+
- `kcb-easy-060-task-selection`
|
| 135 |
+
- `kcb-easy-061-sequence-diff`
|
| 136 |
+
- `kcb-easy-062-finite-automaton`
|
| 137 |
+
- `kcb-easy-063-content-manifest`
|
| 138 |
+
- `kcb-easy-064-cellular-automaton`
|
| 139 |
+
- `kcb-easy-065-expression-eval`
|
| 140 |
+
|
| 141 |
+
## Intermediate — 8–16B target
|
| 142 |
+
|
| 143 |
+
- `kcb-intermediate-001-word-frequency`
|
| 144 |
+
- `kcb-intermediate-002-slug-registry`
|
| 145 |
+
- `kcb-intermediate-003-run-length`
|
| 146 |
+
- `kcb-intermediate-004-bracket-audit`
|
| 147 |
+
- `kcb-intermediate-005-text-wrap`
|
| 148 |
+
- `kcb-intermediate-006-ngram-index`
|
| 149 |
+
- `kcb-intermediate-007-glob-filter`
|
| 150 |
+
- `kcb-intermediate-008-edit-distance`
|
| 151 |
+
- `kcb-intermediate-009-roman-codec`
|
| 152 |
+
- `kcb-intermediate-010-caesar-cipher`
|
| 153 |
+
- `kcb-intermediate-011-csv-records`
|
| 154 |
+
- `kcb-intermediate-012-record-query`
|
| 155 |
+
- `kcb-intermediate-013-inner-join`
|
| 156 |
+
- `kcb-intermediate-014-group-totals`
|
| 157 |
+
- `kcb-intermediate-015-json-flatten`
|
| 158 |
+
- `kcb-intermediate-016-merge-patch`
|
| 159 |
+
- `kcb-intermediate-017-json-pointer`
|
| 160 |
+
- `kcb-intermediate-018-dedupe-records`
|
| 161 |
+
- `kcb-intermediate-019-pivot-table`
|
| 162 |
+
- `kcb-intermediate-020-schema-check`
|
| 163 |
+
- `kcb-intermediate-021-interval-union`
|
| 164 |
+
- `kcb-intermediate-022-interval-gaps`
|
| 165 |
+
- `kcb-intermediate-023-booking-peak`
|
| 166 |
+
- `kcb-intermediate-024-business-days`
|
| 167 |
+
- `kcb-intermediate-025-calendar-month`
|
| 168 |
+
- `kcb-intermediate-026-moving-average`
|
| 169 |
+
- `kcb-intermediate-027-statistics`
|
| 170 |
+
- `kcb-intermediate-028-histogram`
|
| 171 |
+
- `kcb-intermediate-029-matrix-product`
|
| 172 |
+
- `kcb-intermediate-030-polynomial`
|
| 173 |
+
- `kcb-intermediate-031-prime-factors`
|
| 174 |
+
- `kcb-intermediate-032-base-convert`
|
| 175 |
+
- `kcb-intermediate-033-money-split`
|
| 176 |
+
- `kcb-intermediate-034-invoice-total`
|
| 177 |
+
- `kcb-intermediate-035-coin-change`
|
| 178 |
+
- `kcb-intermediate-036-graph-reach`
|
| 179 |
+
- `kcb-intermediate-037-shortest-path`
|
| 180 |
+
- `kcb-intermediate-038-topological-order`
|
| 181 |
+
- `kcb-intermediate-039-connected-components`
|
| 182 |
+
- `kcb-intermediate-040-grid-route`
|
| 183 |
+
- `kcb-intermediate-041-tree-outline`
|
| 184 |
+
- `kcb-intermediate-042-dependency-build`
|
| 185 |
+
- `kcb-intermediate-043-path-normalize`
|
| 186 |
+
- `kcb-intermediate-044-url-query`
|
| 187 |
+
- `kcb-intermediate-045-version-sort`
|
| 188 |
+
- `kcb-intermediate-046-lru-trace`
|
| 189 |
+
- `kcb-intermediate-047-rate-limit`
|
| 190 |
+
- `kcb-intermediate-048-priority-queue`
|
| 191 |
+
- `kcb-intermediate-049-round-robin`
|
| 192 |
+
- `kcb-intermediate-050-inventory-ledger`
|
| 193 |
+
- `kcb-intermediate-051-bank-ledger`
|
| 194 |
+
- `kcb-intermediate-052-ballot-count`
|
| 195 |
+
- `kcb-intermediate-053-search-rank`
|
| 196 |
+
- `kcb-intermediate-054-log-summary`
|
| 197 |
+
- `kcb-intermediate-055-uptime-report`
|
| 198 |
+
- `kcb-intermediate-056-segment-intersection`
|
| 199 |
+
- `kcb-intermediate-057-polygon-area`
|
| 200 |
+
- `kcb-intermediate-058-skyline`
|
| 201 |
+
- `kcb-intermediate-059-knapsack`
|
| 202 |
+
- `kcb-intermediate-060-task-selection`
|
| 203 |
+
- `kcb-intermediate-061-sequence-diff`
|
| 204 |
+
- `kcb-intermediate-062-finite-automaton`
|
| 205 |
+
- `kcb-intermediate-063-content-manifest`
|
| 206 |
+
- `kcb-intermediate-064-cellular-automaton`
|
| 207 |
+
- `kcb-intermediate-065-expression-eval`
|
| 208 |
+
|
| 209 |
+
## Hard — 16–32B target
|
| 210 |
+
|
| 211 |
+
- `kcb-hard-001-word-frequency`
|
| 212 |
+
- `kcb-hard-002-slug-registry`
|
| 213 |
+
- `kcb-hard-003-run-length`
|
| 214 |
+
- `kcb-hard-004-bracket-audit`
|
| 215 |
+
- `kcb-hard-005-text-wrap`
|
| 216 |
+
- `kcb-hard-006-ngram-index`
|
| 217 |
+
- `kcb-hard-007-glob-filter`
|
| 218 |
+
- `kcb-hard-008-edit-distance`
|
| 219 |
+
- `kcb-hard-009-roman-codec`
|
| 220 |
+
- `kcb-hard-010-caesar-cipher`
|
| 221 |
+
- `kcb-hard-011-csv-records`
|
| 222 |
+
- `kcb-hard-012-record-query`
|
| 223 |
+
- `kcb-hard-013-inner-join`
|
| 224 |
+
- `kcb-hard-014-group-totals`
|
| 225 |
+
- `kcb-hard-015-json-flatten`
|
| 226 |
+
- `kcb-hard-016-merge-patch`
|
| 227 |
+
- `kcb-hard-017-json-pointer`
|
| 228 |
+
- `kcb-hard-018-dedupe-records`
|
| 229 |
+
- `kcb-hard-019-pivot-table`
|
| 230 |
+
- `kcb-hard-020-schema-check`
|
| 231 |
+
- `kcb-hard-021-interval-union`
|
| 232 |
+
- `kcb-hard-022-interval-gaps`
|
| 233 |
+
- `kcb-hard-023-booking-peak`
|
| 234 |
+
- `kcb-hard-024-business-days`
|
| 235 |
+
- `kcb-hard-025-calendar-month`
|
| 236 |
+
- `kcb-hard-026-moving-average`
|
| 237 |
+
- `kcb-hard-027-statistics`
|
| 238 |
+
- `kcb-hard-028-histogram`
|
| 239 |
+
- `kcb-hard-029-matrix-product`
|
| 240 |
+
- `kcb-hard-030-polynomial`
|
| 241 |
+
- `kcb-hard-031-prime-factors`
|
| 242 |
+
- `kcb-hard-032-base-convert`
|
| 243 |
+
- `kcb-hard-033-money-split`
|
| 244 |
+
- `kcb-hard-034-invoice-total`
|
| 245 |
+
- `kcb-hard-035-coin-change`
|
| 246 |
+
- `kcb-hard-036-graph-reach`
|
| 247 |
+
- `kcb-hard-037-shortest-path`
|
| 248 |
+
- `kcb-hard-038-topological-order`
|
| 249 |
+
- `kcb-hard-039-connected-components`
|
| 250 |
+
- `kcb-hard-040-grid-route`
|
| 251 |
+
- `kcb-hard-041-tree-outline`
|
| 252 |
+
- `kcb-hard-042-dependency-build`
|
| 253 |
+
- `kcb-hard-043-path-normalize`
|
| 254 |
+
- `kcb-hard-044-url-query`
|
| 255 |
+
- `kcb-hard-045-version-sort`
|
| 256 |
+
- `kcb-hard-046-lru-trace`
|
| 257 |
+
- `kcb-hard-047-rate-limit`
|
| 258 |
+
- `kcb-hard-048-priority-queue`
|
| 259 |
+
- `kcb-hard-049-round-robin`
|
| 260 |
+
- `kcb-hard-050-inventory-ledger`
|
| 261 |
+
- `kcb-hard-051-bank-ledger`
|
| 262 |
+
- `kcb-hard-052-ballot-count`
|
| 263 |
+
- `kcb-hard-053-search-rank`
|
| 264 |
+
- `kcb-hard-054-log-summary`
|
| 265 |
+
- `kcb-hard-055-uptime-report`
|
| 266 |
+
- `kcb-hard-056-segment-intersection`
|
| 267 |
+
- `kcb-hard-057-polygon-area`
|
| 268 |
+
- `kcb-hard-058-skyline`
|
| 269 |
+
- `kcb-hard-059-knapsack`
|
| 270 |
+
- `kcb-hard-060-task-selection`
|
| 271 |
+
- `kcb-hard-061-sequence-diff`
|
| 272 |
+
- `kcb-hard-062-finite-automaton`
|
| 273 |
+
- `kcb-hard-063-content-manifest`
|
| 274 |
+
- `kcb-hard-064-cellular-automaton`
|
| 275 |
+
- `kcb-hard-065-expression-eval`
|
| 276 |
+
|
| 277 |
+
## Max — 60–200B target
|
| 278 |
+
|
| 279 |
+
- `kcb-max-001-word-frequency`
|
| 280 |
+
- `kcb-max-002-slug-registry`
|
| 281 |
+
- `kcb-max-003-run-length`
|
| 282 |
+
- `kcb-max-004-bracket-audit`
|
| 283 |
+
- `kcb-max-005-text-wrap`
|
| 284 |
+
- `kcb-max-006-ngram-index`
|
| 285 |
+
- `kcb-max-007-glob-filter`
|
| 286 |
+
- `kcb-max-008-edit-distance`
|
| 287 |
+
- `kcb-max-009-roman-codec`
|
| 288 |
+
- `kcb-max-010-caesar-cipher`
|
| 289 |
+
- `kcb-max-011-csv-records`
|
| 290 |
+
- `kcb-max-012-record-query`
|
| 291 |
+
- `kcb-max-013-inner-join`
|
| 292 |
+
- `kcb-max-014-group-totals`
|
| 293 |
+
- `kcb-max-015-json-flatten`
|
| 294 |
+
- `kcb-max-016-merge-patch`
|
| 295 |
+
- `kcb-max-017-json-pointer`
|
| 296 |
+
- `kcb-max-018-dedupe-records`
|
| 297 |
+
- `kcb-max-019-pivot-table`
|
| 298 |
+
- `kcb-max-020-schema-check`
|
| 299 |
+
- `kcb-max-021-interval-union`
|
| 300 |
+
- `kcb-max-022-interval-gaps`
|
| 301 |
+
- `kcb-max-023-booking-peak`
|
| 302 |
+
- `kcb-max-024-business-days`
|
| 303 |
+
- `kcb-max-025-calendar-month`
|
| 304 |
+
- `kcb-max-026-moving-average`
|
| 305 |
+
- `kcb-max-027-statistics`
|
| 306 |
+
- `kcb-max-028-histogram`
|
| 307 |
+
- `kcb-max-029-matrix-product`
|
| 308 |
+
- `kcb-max-030-polynomial`
|
| 309 |
+
- `kcb-max-031-prime-factors`
|
| 310 |
+
- `kcb-max-032-base-convert`
|
| 311 |
+
- `kcb-max-033-money-split`
|
| 312 |
+
- `kcb-max-034-invoice-total`
|
| 313 |
+
- `kcb-max-035-coin-change`
|
| 314 |
+
- `kcb-max-036-graph-reach`
|
| 315 |
+
- `kcb-max-037-shortest-path`
|
| 316 |
+
- `kcb-max-038-topological-order`
|
| 317 |
+
- `kcb-max-039-connected-components`
|
| 318 |
+
- `kcb-max-040-grid-route`
|
| 319 |
+
- `kcb-max-041-tree-outline`
|
| 320 |
+
- `kcb-max-042-dependency-build`
|
| 321 |
+
- `kcb-max-043-path-normalize`
|
| 322 |
+
- `kcb-max-044-url-query`
|
| 323 |
+
- `kcb-max-045-version-sort`
|
| 324 |
+
- `kcb-max-046-lru-trace`
|
| 325 |
+
- `kcb-max-047-rate-limit`
|
| 326 |
+
- `kcb-max-048-priority-queue`
|
| 327 |
+
- `kcb-max-049-round-robin`
|
| 328 |
+
- `kcb-max-050-inventory-ledger`
|
| 329 |
+
- `kcb-max-051-bank-ledger`
|
| 330 |
+
- `kcb-max-052-ballot-count`
|
| 331 |
+
- `kcb-max-053-search-rank`
|
| 332 |
+
- `kcb-max-054-log-summary`
|
| 333 |
+
- `kcb-max-055-uptime-report`
|
| 334 |
+
- `kcb-max-056-segment-intersection`
|
| 335 |
+
- `kcb-max-057-polygon-area`
|
| 336 |
+
- `kcb-max-058-skyline`
|
| 337 |
+
- `kcb-max-059-knapsack`
|
| 338 |
+
- `kcb-max-060-task-selection`
|
| 339 |
+
- `kcb-max-061-sequence-diff`
|
| 340 |
+
- `kcb-max-062-finite-automaton`
|
| 341 |
+
- `kcb-max-063-content-manifest`
|
| 342 |
+
- `kcb-max-064-cellular-automaton`
|
| 343 |
+
- `kcb-max-065-expression-eval`
|
docs/EVALUATION.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Evaluation protocol v1.0
|
| 2 |
+
|
| 3 |
+
1. Pin the dataset revision and evaluator version. Select a subset or all 260 tasks before generation.
|
| 4 |
+
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.
|
| 5 |
+
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.
|
| 6 |
+
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.
|
| 7 |
+
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.
|
| 8 |
+
|
| 9 |
+
## Candidate execution
|
| 10 |
+
|
| 11 |
+
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.
|
| 12 |
+
|
| 13 |
+
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.
|
| 14 |
+
|
| 15 |
+
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.
|
| 16 |
+
|
| 17 |
+
## Contract coverage
|
| 18 |
+
|
| 19 |
+
- **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.
|
| 20 |
+
- **Intermediate+:** revision increments, deep values/null, repeated replacement, evaluation without mutation, deletion failures, prefix matching and sorted listing.
|
| 21 |
+
- **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.
|
| 22 |
+
- **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.
|
| 23 |
+
|
| 24 |
+
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.
|
| 25 |
+
|
| 26 |
+
## Interpretation
|
| 27 |
+
|
| 28 |
+
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.
|
| 29 |
+
|
| 30 |
+
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.
|
klein_code_bench/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Klein-Code-Bench: from-scratch project generation benchmark."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.1.0"
|
klein_code_bench/__main__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .cli import main
|
| 2 |
+
|
| 3 |
+
raise SystemExit(main())
|
klein_code_bench/build.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproducibly compile contracts and static acceptance suites into HF JSONL."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from .catalog import FAMILIES
|
| 10 |
+
from .protocol import PROTOCOL_VERSION, TIERS, contract
|
| 11 |
+
from .reference.domains import solve
|
| 12 |
+
from .scenarios import expected_scenarios
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def dumps(value):
|
| 16 |
+
return json.dumps(
|
| 17 |
+
value,
|
| 18 |
+
ensure_ascii=False,
|
| 19 |
+
sort_keys=True,
|
| 20 |
+
separators=(",", ":"),
|
| 21 |
+
allow_nan=False,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def build(destination=None):
|
| 26 |
+
root = Path(destination) if destination else Path(__file__).parent / "data"
|
| 27 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
counts, hashes, assertions = {}, {}, {}
|
| 29 |
+
for tier, models in TIERS.items():
|
| 30 |
+
rows = []
|
| 31 |
+
for index, f in enumerate(FAMILIES.values(), 1):
|
| 32 |
+
# Hand-written goldens are independent of the oracle code.
|
| 33 |
+
if solve(f.slug, f.inputs[0]) != f.golden:
|
| 34 |
+
raise ValueError(f"Golden mismatch: {f.slug}")
|
| 35 |
+
tests = expected_scenarios(f.slug, tier)
|
| 36 |
+
examples = [
|
| 37 |
+
{
|
| 38 |
+
"request": {"op": "solve", "input": x},
|
| 39 |
+
"response": {"ok": True, "result": solve(f.slug, x)},
|
| 40 |
+
}
|
| 41 |
+
for x in f.inputs[:2]
|
| 42 |
+
]
|
| 43 |
+
task_id = f"kcb-{tier}-{index:03d}-{f.slug.replace('_', '-')}"
|
| 44 |
+
title = (
|
| 45 |
+
f"{f.slug.replace('_', ' ').title()} — "
|
| 46 |
+
+ {
|
| 47 |
+
"easy": "CLI project",
|
| 48 |
+
"intermediate": "workspace service",
|
| 49 |
+
"hard": "transactional service",
|
| 50 |
+
"max": "durable service",
|
| 51 |
+
}[tier]
|
| 52 |
+
)
|
| 53 |
+
prompt = (
|
| 54 |
+
f"# {title}\n\n"
|
| 55 |
+
+ contract(tier)
|
| 56 |
+
+ "\nDomain contract:\n"
|
| 57 |
+
+ f.specification
|
| 58 |
+
+ "\nRequired input fields: "
|
| 59 |
+
+ ", ".join(f.required)
|
| 60 |
+
+ ".\n\nExamples:\n"
|
| 61 |
+
+ json.dumps(examples, indent=2, ensure_ascii=False)
|
| 62 |
+
)
|
| 63 |
+
rows.append(
|
| 64 |
+
{
|
| 65 |
+
"task_id": task_id,
|
| 66 |
+
"subset": tier,
|
| 67 |
+
"family": f.slug,
|
| 68 |
+
"title": title,
|
| 69 |
+
"category": f.category,
|
| 70 |
+
"target_model_parameters": models,
|
| 71 |
+
"language": "python",
|
| 72 |
+
"entrypoint": "main.py",
|
| 73 |
+
"protocol_version": PROTOCOL_VERSION,
|
| 74 |
+
"prompt": prompt,
|
| 75 |
+
"timeout_seconds": 10,
|
| 76 |
+
"public_tests": dumps(examples),
|
| 77 |
+
"acceptance_tests": dumps(tests),
|
| 78 |
+
"num_scenarios": len(tests),
|
| 79 |
+
"num_assertions": sum(
|
| 80 |
+
len(s["expected"]) for t in tests for s in t["sessions"]
|
| 81 |
+
),
|
| 82 |
+
}
|
| 83 |
+
)
|
| 84 |
+
file = root / f"{tier}.jsonl"
|
| 85 |
+
file.write_text("".join(dumps(r) + "\n" for r in rows), encoding="utf-8")
|
| 86 |
+
counts[tier] = len(rows)
|
| 87 |
+
assertions[tier] = sum(r["num_assertions"] for r in rows)
|
| 88 |
+
hashes[file.name] = hashlib.sha256(file.read_bytes()).hexdigest()
|
| 89 |
+
manifest = {
|
| 90 |
+
"benchmark": "Klein-Code-Bench",
|
| 91 |
+
"version": "0.1.0",
|
| 92 |
+
"protocol_version": PROTOCOL_VERSION,
|
| 93 |
+
"tasks": 260,
|
| 94 |
+
"families": 65,
|
| 95 |
+
"counts": counts,
|
| 96 |
+
"assertions": assertions,
|
| 97 |
+
"sha256": hashes,
|
| 98 |
+
"seed": 1729,
|
| 99 |
+
"difficulty_calibrated": False,
|
| 100 |
+
}
|
| 101 |
+
(root / "manifest.json").write_text(
|
| 102 |
+
json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
|
| 103 |
+
)
|
| 104 |
+
return manifest
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
print(json.dumps(build(), indent=2))
|
klein_code_bench/catalog.py
ADDED
|
@@ -0,0 +1,1194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hand-authored project contracts and domain fixtures; no downloaded problems."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass(frozen=True)
|
| 9 |
+
class Family:
|
| 10 |
+
slug: str
|
| 11 |
+
category: str
|
| 12 |
+
required: tuple[str, ...]
|
| 13 |
+
specification: str
|
| 14 |
+
inputs: tuple[dict, ...]
|
| 15 |
+
golden: object
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
FAMILIES: dict[str, Family] = {}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def add(slug, category, required, specification, inputs, golden):
|
| 22 |
+
assert slug not in FAMILIES
|
| 23 |
+
FAMILIES[slug] = Family(
|
| 24 |
+
slug, category, tuple(required.split()), specification, tuple(inputs), golden
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
add(
|
| 29 |
+
"word_frequency",
|
| 30 |
+
"text",
|
| 31 |
+
"text",
|
| 32 |
+
"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.",
|
| 33 |
+
[
|
| 34 |
+
{"text": "Red blue RED! 42"},
|
| 35 |
+
{"text": ""},
|
| 36 |
+
{"text": "é É 中文"},
|
| 37 |
+
{"text": "a_a a-b"},
|
| 38 |
+
{"text": "12 012 12\nX"},
|
| 39 |
+
{"text": "z a z b a b"},
|
| 40 |
+
],
|
| 41 |
+
[
|
| 42 |
+
{"word": "red", "count": 2},
|
| 43 |
+
{"word": "42", "count": 1},
|
| 44 |
+
{"word": "blue", "count": 1},
|
| 45 |
+
],
|
| 46 |
+
)
|
| 47 |
+
add(
|
| 48 |
+
"slug_registry",
|
| 49 |
+
"text",
|
| 50 |
+
"titles",
|
| 51 |
+
'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.',
|
| 52 |
+
[
|
| 53 |
+
{"titles": ["Hello World", "hello world", "hello-world-2", ""]},
|
| 54 |
+
{"titles": []},
|
| 55 |
+
{"titles": ["!!!", "", "ITEM"]},
|
| 56 |
+
{"titles": ["a", "a-2", "a", "a"]},
|
| 57 |
+
{"titles": ["Ünicode", " A___B "]},
|
| 58 |
+
{"titles": ["1", "1", "1-2"]},
|
| 59 |
+
],
|
| 60 |
+
["hello-world", "hello-world-2", "hello-world-2-2", "item"],
|
| 61 |
+
)
|
| 62 |
+
add(
|
| 63 |
+
"run_length",
|
| 64 |
+
"text",
|
| 65 |
+
"text",
|
| 66 |
+
"Input: text (string). Return [character,count] pairs for consecutive identical Unicode code points; retain order and include whitespace. Empty text produces [].",
|
| 67 |
+
[
|
| 68 |
+
{"text": "aaabbcaa"},
|
| 69 |
+
{"text": ""},
|
| 70 |
+
{"text": "😀😀é"},
|
| 71 |
+
{"text": " \n\n "},
|
| 72 |
+
{"text": "abcd"},
|
| 73 |
+
{"text": "1111000"},
|
| 74 |
+
],
|
| 75 |
+
[["a", 3], ["b", 2], ["c", 1], ["a", 2]],
|
| 76 |
+
)
|
| 77 |
+
add(
|
| 78 |
+
"bracket_audit",
|
| 79 |
+
"text",
|
| 80 |
+
"text",
|
| 81 |
+
"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.",
|
| 82 |
+
[
|
| 83 |
+
{"text": "a([)]"},
|
| 84 |
+
{"text": ""},
|
| 85 |
+
{"text": "abc"},
|
| 86 |
+
{"text": "([]{})"},
|
| 87 |
+
{"text": "(("},
|
| 88 |
+
{"text": "é]"},
|
| 89 |
+
{"text": "[(]"},
|
| 90 |
+
],
|
| 91 |
+
{"balanced": False, "position": 3},
|
| 92 |
+
)
|
| 93 |
+
add(
|
| 94 |
+
"text_wrap",
|
| 95 |
+
"text",
|
| 96 |
+
"text width",
|
| 97 |
+
"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.",
|
| 98 |
+
[
|
| 99 |
+
{"text": "one two three four", "width": 7},
|
| 100 |
+
{"text": "", "width": 1},
|
| 101 |
+
{"text": "abcdef a", "width": 2},
|
| 102 |
+
{"text": " a\t b\n c ", "width": 3},
|
| 103 |
+
{"text": "éé a", "width": 2},
|
| 104 |
+
{"text": "a b c", "width": 20},
|
| 105 |
+
],
|
| 106 |
+
["one two", "three", "four"],
|
| 107 |
+
)
|
| 108 |
+
add(
|
| 109 |
+
"ngram_index",
|
| 110 |
+
"text",
|
| 111 |
+
"tokens n",
|
| 112 |
+
"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 [].",
|
| 113 |
+
[
|
| 114 |
+
{"tokens": ["a", "b", "a", "b"], "n": 2},
|
| 115 |
+
{"tokens": [], "n": 1},
|
| 116 |
+
{"tokens": ["x"], "n": 2},
|
| 117 |
+
{"tokens": ["b", "a", "b"], "n": 1},
|
| 118 |
+
{"tokens": ["", "a", ""], "n": 2},
|
| 119 |
+
{"tokens": ["x", "x", "x"], "n": 3},
|
| 120 |
+
],
|
| 121 |
+
[
|
| 122 |
+
{"tokens": ["a", "b"], "positions": [0, 2]},
|
| 123 |
+
{"tokens": ["b", "a"], "positions": [1]},
|
| 124 |
+
],
|
| 125 |
+
)
|
| 126 |
+
add(
|
| 127 |
+
"glob_filter",
|
| 128 |
+
"text",
|
| 129 |
+
"paths pattern",
|
| 130 |
+
"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.",
|
| 131 |
+
[
|
| 132 |
+
{"paths": ["a.py", "B.py", "a.txt", "a.py", "x/a.py"], "pattern": "*.py"},
|
| 133 |
+
{"paths": [], "pattern": "*"},
|
| 134 |
+
{"paths": ["a", "b", "c"], "pattern": "[!b]"},
|
| 135 |
+
{"paths": ["ab", "a", "a/b"], "pattern": "a?"},
|
| 136 |
+
{"paths": ["A", "a"], "pattern": "a"},
|
| 137 |
+
{"paths": ["", "a"], "pattern": "*"},
|
| 138 |
+
],
|
| 139 |
+
["B.py", "a.py", "x/a.py"],
|
| 140 |
+
)
|
| 141 |
+
add(
|
| 142 |
+
"edit_distance",
|
| 143 |
+
"text",
|
| 144 |
+
"a b",
|
| 145 |
+
"Input: strings a,b of <=200 code points. Return Levenshtein distance with unit insertion, deletion and substitution costs. Compare Unicode code points, case-sensitive.",
|
| 146 |
+
[
|
| 147 |
+
{"a": "kitten", "b": "sitting"},
|
| 148 |
+
{"a": "", "b": ""},
|
| 149 |
+
{"a": "", "b": "abc"},
|
| 150 |
+
{"a": "ab", "b": "ba"},
|
| 151 |
+
{"a": "é", "b": "e"},
|
| 152 |
+
{"a": "banana", "b": "banana"},
|
| 153 |
+
],
|
| 154 |
+
3,
|
| 155 |
+
)
|
| 156 |
+
add(
|
| 157 |
+
"roman_codec",
|
| 158 |
+
"text",
|
| 159 |
+
"number",
|
| 160 |
+
"Input: integer number in 1..3999. Return canonical uppercase Roman numeral using subtractive pairs IV,IX,XL,XC,CD,CM.",
|
| 161 |
+
[
|
| 162 |
+
{"number": 1994},
|
| 163 |
+
{"number": 1},
|
| 164 |
+
{"number": 4},
|
| 165 |
+
{"number": 9},
|
| 166 |
+
{"number": 3999},
|
| 167 |
+
{"number": 944},
|
| 168 |
+
{"number": 58},
|
| 169 |
+
],
|
| 170 |
+
"MCMXCIV",
|
| 171 |
+
)
|
| 172 |
+
add(
|
| 173 |
+
"caesar_cipher",
|
| 174 |
+
"text",
|
| 175 |
+
"text shift",
|
| 176 |
+
"Input: text and integer shift. Rotate only ASCII letters by shift modulo 26, preserving case. All other characters unchanged.",
|
| 177 |
+
[
|
| 178 |
+
{"text": "Az-z! 9", "shift": 1},
|
| 179 |
+
{"text": "", "shift": 0},
|
| 180 |
+
{"text": "Abc", "shift": -1},
|
| 181 |
+
{"text": "é中", "shift": 13},
|
| 182 |
+
{"text": "XYZ abc", "shift": 52},
|
| 183 |
+
{"text": "aZ", "shift": -53},
|
| 184 |
+
],
|
| 185 |
+
"Ba-a! 9",
|
| 186 |
+
)
|
| 187 |
+
add(
|
| 188 |
+
"csv_records",
|
| 189 |
+
"data",
|
| 190 |
+
"csv",
|
| 191 |
+
"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.",
|
| 192 |
+
[
|
| 193 |
+
{"csv": "name,n\na,1\nb,2\n"},
|
| 194 |
+
{"csv": ""},
|
| 195 |
+
{"csv": "x,y\n"},
|
| 196 |
+
{"csv": 'a,b\n"hi,there","say ""yes"""\n'},
|
| 197 |
+
{"csv": 'x\n"a\nb"\n'},
|
| 198 |
+
{"csv": "x,y\r\na,\r\n"},
|
| 199 |
+
],
|
| 200 |
+
[{"name": "a", "n": "1"}, {"name": "b", "n": "2"}],
|
| 201 |
+
)
|
| 202 |
+
add(
|
| 203 |
+
"record_query",
|
| 204 |
+
"data",
|
| 205 |
+
"rows where select",
|
| 206 |
+
"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.",
|
| 207 |
+
[
|
| 208 |
+
{
|
| 209 |
+
"rows": [{"a": 1, "b": "x"}, {"a": 2}, {"a": 1}],
|
| 210 |
+
"where": {"a": 1},
|
| 211 |
+
"select": ["b"],
|
| 212 |
+
},
|
| 213 |
+
{"rows": [], "where": {}, "select": []},
|
| 214 |
+
{"rows": [{"a": None}, {}], "where": {"a": None}, "select": ["a"]},
|
| 215 |
+
{"rows": [{"x": 1}], "where": {}, "select": []},
|
| 216 |
+
{"rows": [{"x": [1]}, {"x": [2]}], "where": {"x": [1]}, "select": ["x"]},
|
| 217 |
+
],
|
| 218 |
+
[{"b": "x"}, {"b": None}],
|
| 219 |
+
)
|
| 220 |
+
add(
|
| 221 |
+
"inner_join",
|
| 222 |
+
"data",
|
| 223 |
+
"left right key",
|
| 224 |
+
"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.",
|
| 225 |
+
[
|
| 226 |
+
{
|
| 227 |
+
"left": [{"id": 1}, {"id": 2}],
|
| 228 |
+
"right": [{"id": 2}, {"id": 2, "x": 3}],
|
| 229 |
+
"key": "id",
|
| 230 |
+
},
|
| 231 |
+
{"left": [], "right": [], "key": "k"},
|
| 232 |
+
{"left": [{}], "right": [{}], "key": "k"},
|
| 233 |
+
{"left": [{"k": None}], "right": [{"k": None}], "key": "k"},
|
| 234 |
+
{"left": [{"k": 1}, {"k": 1}], "right": [{"k": 1}], "key": "k"},
|
| 235 |
+
],
|
| 236 |
+
[
|
| 237 |
+
{"left": {"id": 2}, "right": {"id": 2}},
|
| 238 |
+
{"left": {"id": 2}, "right": {"id": 2, "x": 3}},
|
| 239 |
+
],
|
| 240 |
+
)
|
| 241 |
+
add(
|
| 242 |
+
"group_totals",
|
| 243 |
+
"data",
|
| 244 |
+
"rows group value",
|
| 245 |
+
"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 [].",
|
| 246 |
+
[
|
| 247 |
+
{
|
| 248 |
+
"rows": [{"g": "b", "v": 2}, {"g": "a", "v": 3}, {"g": "b", "v": -1}],
|
| 249 |
+
"group": "g",
|
| 250 |
+
"value": "v",
|
| 251 |
+
},
|
| 252 |
+
{"rows": [], "group": "g", "value": "v"},
|
| 253 |
+
{"rows": [{"g": "", "v": 0}], "group": "g", "value": "v"},
|
| 254 |
+
{"rows": [{"g": "é", "v": 9}, {"g": "A", "v": -9}], "group": "g", "value": "v"},
|
| 255 |
+
],
|
| 256 |
+
[{"key": "a", "count": 1, "sum": 3}, {"key": "b", "count": 2, "sum": 1}],
|
| 257 |
+
)
|
| 258 |
+
add(
|
| 259 |
+
"json_flatten",
|
| 260 |
+
"data",
|
| 261 |
+
"value",
|
| 262 |
+
'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.',
|
| 263 |
+
[
|
| 264 |
+
{"value": {"a": [1, {"x/y": None}], "b": {}}},
|
| 265 |
+
{"value": []},
|
| 266 |
+
{"value": None},
|
| 267 |
+
{"value": {"~": {"/": 2}, "": 3}},
|
| 268 |
+
{"value": [False, {}, []]},
|
| 269 |
+
],
|
| 270 |
+
{"/a/0": 1, "/a/1/x~1y": None, "/b": {}},
|
| 271 |
+
)
|
| 272 |
+
add(
|
| 273 |
+
"merge_patch",
|
| 274 |
+
"data",
|
| 275 |
+
"target patch",
|
| 276 |
+
"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.",
|
| 277 |
+
[
|
| 278 |
+
{
|
| 279 |
+
"target": {"a": 1, "b": {"c": 2, "d": 3}},
|
| 280 |
+
"patch": {"a": None, "b": {"c": 9}},
|
| 281 |
+
},
|
| 282 |
+
{"target": {}, "patch": None},
|
| 283 |
+
{"target": [1], "patch": {"x": 2}},
|
| 284 |
+
{"target": {"a": [1]}, "patch": {"a": [2, 3]}},
|
| 285 |
+
{"target": 4, "patch": {}},
|
| 286 |
+
{"target": {"a": 1}, "patch": {"z": None}},
|
| 287 |
+
],
|
| 288 |
+
{"b": {"c": 9, "d": 3}},
|
| 289 |
+
)
|
| 290 |
+
add(
|
| 291 |
+
"json_pointer",
|
| 292 |
+
"data",
|
| 293 |
+
"value pointer",
|
| 294 |
+
"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.",
|
| 295 |
+
[
|
| 296 |
+
{"value": {"a/b": [7]}, "pointer": "/a~1b/0"},
|
| 297 |
+
{"value": None, "pointer": ""},
|
| 298 |
+
{"value": [1], "pointer": "/01"},
|
| 299 |
+
{"value": {"": {"~": 2}}, "pointer": "//~0"},
|
| 300 |
+
{"value": [1], "pointer": "/9"},
|
| 301 |
+
{"value": {"a": None}, "pointer": "/a/x"},
|
| 302 |
+
{"value": [], "pointer": "/-"},
|
| 303 |
+
],
|
| 304 |
+
{"found": True, "value": 7},
|
| 305 |
+
)
|
| 306 |
+
add(
|
| 307 |
+
"dedupe_records",
|
| 308 |
+
"data",
|
| 309 |
+
"rows keys",
|
| 310 |
+
"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.",
|
| 311 |
+
[
|
| 312 |
+
{"rows": [{"id": 1, "x": "a"}, {"id": 1, "x": "b"}, {"id": 2}], "keys": ["id"]},
|
| 313 |
+
{"rows": [], "keys": []},
|
| 314 |
+
{"rows": [{"x": 1}, {"x": 2}], "keys": []},
|
| 315 |
+
{"rows": [{}, {"x": None}], "keys": ["x"]},
|
| 316 |
+
{"rows": [{"x": {"a": 1, "b": 2}}, {"x": {"b": 2, "a": 1}}], "keys": ["x"]},
|
| 317 |
+
],
|
| 318 |
+
[{"id": 1, "x": "a"}, {"id": 2}],
|
| 319 |
+
)
|
| 320 |
+
add(
|
| 321 |
+
"pivot_table",
|
| 322 |
+
"data",
|
| 323 |
+
"rows row column value",
|
| 324 |
+
"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.",
|
| 325 |
+
[
|
| 326 |
+
{
|
| 327 |
+
"rows": [
|
| 328 |
+
{"r": "a", "c": "x", "v": 2},
|
| 329 |
+
{"r": "b", "c": "y", "v": 3},
|
| 330 |
+
{"r": "a", "c": "x", "v": -1},
|
| 331 |
+
],
|
| 332 |
+
"row": "r",
|
| 333 |
+
"column": "c",
|
| 334 |
+
"value": "v",
|
| 335 |
+
},
|
| 336 |
+
{"rows": [], "row": "r", "column": "c", "value": "v"},
|
| 337 |
+
{"rows": [{"r": "", "c": "", "v": 0}], "row": "r", "column": "c", "value": "v"},
|
| 338 |
+
{
|
| 339 |
+
"rows": [{"r": "z", "c": "b", "v": -5}, {"r": "a", "c": "a", "v": 1}],
|
| 340 |
+
"row": "r",
|
| 341 |
+
"column": "c",
|
| 342 |
+
"value": "v",
|
| 343 |
+
},
|
| 344 |
+
],
|
| 345 |
+
{"rows": ["a", "b"], "columns": ["x", "y"], "values": [[1, 0], [0, 3]]},
|
| 346 |
+
)
|
| 347 |
+
add(
|
| 348 |
+
"schema_check",
|
| 349 |
+
"data",
|
| 350 |
+
"schema value",
|
| 351 |
+
'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.',
|
| 352 |
+
[
|
| 353 |
+
{
|
| 354 |
+
"schema": {
|
| 355 |
+
"a": {"type": "integer", "required": True},
|
| 356 |
+
"b": {"type": "string", "required": True},
|
| 357 |
+
},
|
| 358 |
+
"value": {"a": True},
|
| 359 |
+
},
|
| 360 |
+
{"schema": {}, "value": {"a": 1}},
|
| 361 |
+
{"schema": {"x": {"type": "null", "required": False}}, "value": {}},
|
| 362 |
+
{"schema": {"x": {"type": "number", "required": True}}, "value": {"x": 1.5}},
|
| 363 |
+
{"schema": {"x": {"type": "array", "required": True}}, "value": {"x": []}},
|
| 364 |
+
],
|
| 365 |
+
[{"field": "a", "error": "type"}, {"field": "b", "error": "required"}],
|
| 366 |
+
)
|
| 367 |
+
add(
|
| 368 |
+
"interval_union",
|
| 369 |
+
"intervals",
|
| 370 |
+
"intervals",
|
| 371 |
+
"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.",
|
| 372 |
+
[
|
| 373 |
+
{"intervals": [[5, 7], [1, 3], [3, 6], [9, 9]]},
|
| 374 |
+
{"intervals": []},
|
| 375 |
+
{"intervals": [[0, 0], [0, 0]]},
|
| 376 |
+
{"intervals": [[-4, -1], [-2, 3]]},
|
| 377 |
+
{"intervals": [[1, 10], [2, 3], [12, 14]]},
|
| 378 |
+
],
|
| 379 |
+
[[1, 7], [9, 9]],
|
| 380 |
+
)
|
| 381 |
+
add(
|
| 382 |
+
"interval_gaps",
|
| 383 |
+
"intervals",
|
| 384 |
+
"intervals bounds",
|
| 385 |
+
"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.",
|
| 386 |
+
[
|
| 387 |
+
{"intervals": [[2, 4], [6, 9]], "bounds": [0, 10]},
|
| 388 |
+
{"intervals": [], "bounds": [0, 5]},
|
| 389 |
+
{"intervals": [[-3, 8]], "bounds": [0, 5]},
|
| 390 |
+
{"intervals": [[8, 9], [-3, -1]], "bounds": [0, 5]},
|
| 391 |
+
{"intervals": [[2, 2]], "bounds": [0, 5]},
|
| 392 |
+
{"intervals": [], "bounds": [2, 2]},
|
| 393 |
+
],
|
| 394 |
+
[[0, 2], [4, 6], [9, 10]],
|
| 395 |
+
)
|
| 396 |
+
add(
|
| 397 |
+
"booking_peak",
|
| 398 |
+
"intervals",
|
| 399 |
+
"bookings",
|
| 400 |
+
"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.",
|
| 401 |
+
[
|
| 402 |
+
{"bookings": [[1, 4], [2, 3], [3, 5]]},
|
| 403 |
+
{"bookings": []},
|
| 404 |
+
{"bookings": [[1, 1]]},
|
| 405 |
+
{"bookings": [[0, 1], [1, 2]]},
|
| 406 |
+
{"bookings": [[-2, 2], [-2, 2]]},
|
| 407 |
+
],
|
| 408 |
+
{"peak": 2, "at": 2},
|
| 409 |
+
)
|
| 410 |
+
add(
|
| 411 |
+
"business_days",
|
| 412 |
+
"calendar",
|
| 413 |
+
"start end holidays",
|
| 414 |
+
"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.",
|
| 415 |
+
[
|
| 416 |
+
{"start": "2024-02-28", "end": "2024-03-04", "holidays": ["2024-02-29"]},
|
| 417 |
+
{"start": "2024-01-01", "end": "2024-01-01", "holidays": []},
|
| 418 |
+
{"start": "2024-01-06", "end": "2024-01-08", "holidays": []},
|
| 419 |
+
{
|
| 420 |
+
"start": "2024-12-30",
|
| 421 |
+
"end": "2025-01-03",
|
| 422 |
+
"holidays": ["2025-01-01", "2025-01-01"],
|
| 423 |
+
},
|
| 424 |
+
{"start": "2000-02-28", "end": "2000-03-02", "holidays": []},
|
| 425 |
+
],
|
| 426 |
+
["2024-02-28", "2024-03-01"],
|
| 427 |
+
)
|
| 428 |
+
add(
|
| 429 |
+
"calendar_month",
|
| 430 |
+
"calendar",
|
| 431 |
+
"year month",
|
| 432 |
+
"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.",
|
| 433 |
+
[
|
| 434 |
+
{"year": 2021, "month": 2},
|
| 435 |
+
{"year": 2024, "month": 2},
|
| 436 |
+
{"year": 1900, "month": 2},
|
| 437 |
+
{"year": 2023, "month": 1},
|
| 438 |
+
{"year": 2000, "month": 12},
|
| 439 |
+
],
|
| 440 |
+
[
|
| 441 |
+
[1, 2, 3, 4, 5, 6, 7],
|
| 442 |
+
[8, 9, 10, 11, 12, 13, 14],
|
| 443 |
+
[15, 16, 17, 18, 19, 20, 21],
|
| 444 |
+
[22, 23, 24, 25, 26, 27, 28],
|
| 445 |
+
],
|
| 446 |
+
)
|
| 447 |
+
add(
|
| 448 |
+
"moving_average",
|
| 449 |
+
"numeric",
|
| 450 |
+
"values window",
|
| 451 |
+
"Input: values (finite numbers), window (positive integer). Return arithmetic means for all contiguous full windows. Empty input or window>length gives [].",
|
| 452 |
+
[
|
| 453 |
+
{"values": [1, 2, 3, 4], "window": 2},
|
| 454 |
+
{"values": [], "window": 1},
|
| 455 |
+
{"values": [1], "window": 3},
|
| 456 |
+
{"values": [-2, 0, 2], "window": 1},
|
| 457 |
+
{"values": [1, 2], "window": 2},
|
| 458 |
+
{"values": [0.1, 0.2, 0.3], "window": 2},
|
| 459 |
+
],
|
| 460 |
+
[1.5, 2.5, 3.5],
|
| 461 |
+
)
|
| 462 |
+
add(
|
| 463 |
+
"statistics",
|
| 464 |
+
"numeric",
|
| 465 |
+
"values",
|
| 466 |
+
"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.",
|
| 467 |
+
[
|
| 468 |
+
{"values": [1, 2, 3, 4]},
|
| 469 |
+
{"values": []},
|
| 470 |
+
{"values": [7]},
|
| 471 |
+
{"values": [-2, -2, 2, 2]},
|
| 472 |
+
{"values": [0.1, 0.2, 0.3]},
|
| 473 |
+
{"values": [9, 1, 3]},
|
| 474 |
+
],
|
| 475 |
+
{"count": 4, "min": 1, "max": 4, "mean": 2.5, "median": 2.5, "variance": 1.25},
|
| 476 |
+
)
|
| 477 |
+
add(
|
| 478 |
+
"histogram",
|
| 479 |
+
"numeric",
|
| 480 |
+
"values edges",
|
| 481 |
+
"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}.",
|
| 482 |
+
[
|
| 483 |
+
{"values": [-1, 0, 1, 2, 3], "edges": [0, 1, 3]},
|
| 484 |
+
{"values": [], "edges": [0, 1]},
|
| 485 |
+
{"values": [0, 1, 2], "edges": [0, 1, 2]},
|
| 486 |
+
{"values": [-5, -3, -1], "edges": [-4, -2, 0]},
|
| 487 |
+
{"values": [0.1, 0.2], "edges": [0, 0.2, 1]},
|
| 488 |
+
],
|
| 489 |
+
{"counts": [1, 2], "underflow": 1, "overflow": 1},
|
| 490 |
+
)
|
| 491 |
+
add(
|
| 492 |
+
"matrix_product",
|
| 493 |
+
"numeric",
|
| 494 |
+
"a b",
|
| 495 |
+
"Input: a (m by n), b (n by p), nonempty rectangular integer matrices of compatible dimensions, each dimension <=20. Return matrix product.",
|
| 496 |
+
[
|
| 497 |
+
{"a": [[1, 2], [3, 4]], "b": [[5], [6]]},
|
| 498 |
+
{"a": [[0]], "b": [[9]]},
|
| 499 |
+
{"a": [[-2, 3, 1]], "b": [[1, 0], [0, 1], [2, 2]]},
|
| 500 |
+
{"a": [[1, 0], [0, 1]], "b": [[3, 4], [5, 6]]},
|
| 501 |
+
{"a": [[2], [3]], "b": [[4, 5]]},
|
| 502 |
+
],
|
| 503 |
+
[[17], [39]],
|
| 504 |
+
)
|
| 505 |
+
add(
|
| 506 |
+
"polynomial",
|
| 507 |
+
"numeric",
|
| 508 |
+
"coefficients points",
|
| 509 |
+
"Input: integer coefficients in ascending power order (c0,c1,...) and integer evaluation points. Return values at each point. Empty coefficients denote zero polynomial.",
|
| 510 |
+
[
|
| 511 |
+
{"coefficients": [1, 2, 3], "points": [0, 1, -1, 2]},
|
| 512 |
+
{"coefficients": [], "points": [1, 0]},
|
| 513 |
+
{"coefficients": [7], "points": []},
|
| 514 |
+
{"coefficients": [0, 0, 1], "points": [-3, 3]},
|
| 515 |
+
{"coefficients": [-1, 1], "points": [100, -100]},
|
| 516 |
+
],
|
| 517 |
+
[1, 6, 2, 17],
|
| 518 |
+
)
|
| 519 |
+
add(
|
| 520 |
+
"prime_factors",
|
| 521 |
+
"numeric",
|
| 522 |
+
"number",
|
| 523 |
+
"Input: integer number in 1..10000000. Return [prime,exponent] pairs in ascending prime order; 1 returns [].",
|
| 524 |
+
[
|
| 525 |
+
{"number": 360},
|
| 526 |
+
{"number": 1},
|
| 527 |
+
{"number": 2},
|
| 528 |
+
{"number": 9973},
|
| 529 |
+
{"number": 65536},
|
| 530 |
+
{"number": 99991},
|
| 531 |
+
],
|
| 532 |
+
[[2, 3], [3, 2], [5, 1]],
|
| 533 |
+
)
|
| 534 |
+
add(
|
| 535 |
+
"base_convert",
|
| 536 |
+
"numeric",
|
| 537 |
+
"digits from_base to_base",
|
| 538 |
+
'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.',
|
| 539 |
+
[
|
| 540 |
+
{"digits": "ff", "from_base": 16, "to_base": 2},
|
| 541 |
+
{"digits": "-0", "from_base": 10, "to_base": 36},
|
| 542 |
+
{"digits": "-101", "from_base": 2, "to_base": 10},
|
| 543 |
+
{"digits": "ZZ", "from_base": 36, "to_base": 16},
|
| 544 |
+
{"digits": "00042", "from_base": 10, "to_base": 10},
|
| 545 |
+
{"digits": "10000000000000000", "from_base": 16, "to_base": 10},
|
| 546 |
+
],
|
| 547 |
+
"11111111",
|
| 548 |
+
)
|
| 549 |
+
add(
|
| 550 |
+
"money_split",
|
| 551 |
+
"numeric",
|
| 552 |
+
"amount weights",
|
| 553 |
+
"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.",
|
| 554 |
+
[
|
| 555 |
+
{"amount": 10, "weights": [1, 1, 1]},
|
| 556 |
+
{"amount": 0, "weights": [1]},
|
| 557 |
+
{"amount": 2, "weights": [0, 1, 1]},
|
| 558 |
+
{"amount": 7, "weights": [1, 2]},
|
| 559 |
+
{"amount": 1, "weights": [3, 3, 3]},
|
| 560 |
+
{"amount": 1000001, "weights": [9, 1]},
|
| 561 |
+
],
|
| 562 |
+
[4, 3, 3],
|
| 563 |
+
)
|
| 564 |
+
add(
|
| 565 |
+
"invoice_total",
|
| 566 |
+
"numeric",
|
| 567 |
+
"items tax_rate",
|
| 568 |
+
"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.",
|
| 569 |
+
[
|
| 570 |
+
{"items": [{"price": "0.335", "quantity": 3}], "tax_rate": "0.20"},
|
| 571 |
+
{"items": [], "tax_rate": "0"},
|
| 572 |
+
{"items": [{"price": "0.05", "quantity": 1}], "tax_rate": "0.1"},
|
| 573 |
+
{"items": [{"price": "1.005", "quantity": 1}], "tax_rate": "0"},
|
| 574 |
+
{
|
| 575 |
+
"items": [
|
| 576 |
+
{"price": "19.99", "quantity": 2},
|
| 577 |
+
{"price": "3.50", "quantity": 3},
|
| 578 |
+
],
|
| 579 |
+
"tax_rate": "0.075",
|
| 580 |
+
},
|
| 581 |
+
],
|
| 582 |
+
{"subtotal": "1.01", "tax": "0.20", "total": "1.21"},
|
| 583 |
+
)
|
| 584 |
+
add(
|
| 585 |
+
"coin_change",
|
| 586 |
+
"numeric",
|
| 587 |
+
"coins amount",
|
| 588 |
+
"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.",
|
| 589 |
+
[
|
| 590 |
+
{"coins": [1, 3, 4], "amount": 6},
|
| 591 |
+
{"coins": [], "amount": 0},
|
| 592 |
+
{"coins": [2], "amount": 3},
|
| 593 |
+
{"coins": [2, 2, 5], "amount": 10},
|
| 594 |
+
{"coins": [], "amount": 4},
|
| 595 |
+
{"coins": [7, 3], "amount": 11},
|
| 596 |
+
],
|
| 597 |
+
2,
|
| 598 |
+
)
|
| 599 |
+
add(
|
| 600 |
+
"graph_reach",
|
| 601 |
+
"graphs",
|
| 602 |
+
"nodes edges start",
|
| 603 |
+
"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.",
|
| 604 |
+
[
|
| 605 |
+
{
|
| 606 |
+
"nodes": ["a", "b", "c", "d"],
|
| 607 |
+
"edges": [["a", "b"], ["b", "c"]],
|
| 608 |
+
"start": "a",
|
| 609 |
+
},
|
| 610 |
+
{"nodes": ["a"], "edges": [], "start": "a"},
|
| 611 |
+
{"nodes": ["a", "b"], "edges": [["b", "a"]], "start": "a"},
|
| 612 |
+
{
|
| 613 |
+
"nodes": ["a", "b"],
|
| 614 |
+
"edges": [["a", "b"], ["b", "a"], ["a", "b"]],
|
| 615 |
+
"start": "b",
|
| 616 |
+
},
|
| 617 |
+
{"nodes": ["x", "y"], "edges": [["x", "x"]], "start": "x"},
|
| 618 |
+
],
|
| 619 |
+
["a", "b", "c"],
|
| 620 |
+
)
|
| 621 |
+
add(
|
| 622 |
+
"shortest_path",
|
| 623 |
+
"graphs",
|
| 624 |
+
"nodes edges start",
|
| 625 |
+
"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.",
|
| 626 |
+
[
|
| 627 |
+
{
|
| 628 |
+
"nodes": ["a", "b", "c", "d"],
|
| 629 |
+
"edges": [["a", "b", 5], ["a", "c", 1], ["c", "b", 1]],
|
| 630 |
+
"start": "a",
|
| 631 |
+
},
|
| 632 |
+
{"nodes": ["a"], "edges": [], "start": "a"},
|
| 633 |
+
{"nodes": ["a", "b"], "edges": [["b", "a", 1]], "start": "a"},
|
| 634 |
+
{
|
| 635 |
+
"nodes": ["a", "b", "c"],
|
| 636 |
+
"edges": [["a", "b", 0], ["b", "a", 0], ["b", "c", 2], ["a", "c", 9]],
|
| 637 |
+
"start": "a",
|
| 638 |
+
},
|
| 639 |
+
{"nodes": ["a", "b"], "edges": [["a", "b", 8], ["a", "b", 2]], "start": "a"},
|
| 640 |
+
],
|
| 641 |
+
{"a": 0, "b": 2, "c": 1, "d": None},
|
| 642 |
+
)
|
| 643 |
+
add(
|
| 644 |
+
"topological_order",
|
| 645 |
+
"graphs",
|
| 646 |
+
"nodes edges",
|
| 647 |
+
"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.",
|
| 648 |
+
[
|
| 649 |
+
{"nodes": ["c", "a", "b"], "edges": [["a", "c"]]},
|
| 650 |
+
{"nodes": [], "edges": []},
|
| 651 |
+
{"nodes": ["a", "b"], "edges": [["a", "b"], ["b", "a"]]},
|
| 652 |
+
{"nodes": ["a"], "edges": [["a", "a"]]},
|
| 653 |
+
{"nodes": ["a", "b"], "edges": [["a", "b"], ["a", "b"]]},
|
| 654 |
+
{"nodes": ["z", "a", "b"], "edges": []},
|
| 655 |
+
],
|
| 656 |
+
["a", "b", "c"],
|
| 657 |
+
)
|
| 658 |
+
add(
|
| 659 |
+
"connected_components",
|
| 660 |
+
"graphs",
|
| 661 |
+
"nodes edges",
|
| 662 |
+
"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.",
|
| 663 |
+
[
|
| 664 |
+
{"nodes": ["d", "c", "b", "a"], "edges": [["a", "b"], ["c", "d"]]},
|
| 665 |
+
{"nodes": [], "edges": []},
|
| 666 |
+
{"nodes": ["a"], "edges": [["a", "a"]]},
|
| 667 |
+
{"nodes": ["z", "a"], "edges": []},
|
| 668 |
+
{"nodes": ["a", "b", "c"], "edges": [["a", "b"], ["b", "a"], ["b", "c"]]},
|
| 669 |
+
],
|
| 670 |
+
[["a", "b"], ["c", "d"]],
|
| 671 |
+
)
|
| 672 |
+
add(
|
| 673 |
+
"grid_route",
|
| 674 |
+
"graphs",
|
| 675 |
+
"grid start end",
|
| 676 |
+
"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.",
|
| 677 |
+
[
|
| 678 |
+
{"grid": ["...", ".#.", "..."], "start": [0, 0], "end": [2, 2]},
|
| 679 |
+
{"grid": ["."], "start": [0, 0], "end": [0, 0]},
|
| 680 |
+
{"grid": ["#"], "start": [0, 0], "end": [0, 0]},
|
| 681 |
+
{"grid": [".#."], "start": [0, 0], "end": [0, 2]},
|
| 682 |
+
{"grid": ["..", ".."], "start": [1, 1], "end": [0, 0]},
|
| 683 |
+
],
|
| 684 |
+
4,
|
| 685 |
+
)
|
| 686 |
+
add(
|
| 687 |
+
"tree_outline",
|
| 688 |
+
"graphs",
|
| 689 |
+
"nodes",
|
| 690 |
+
"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.",
|
| 691 |
+
[
|
| 692 |
+
{
|
| 693 |
+
"nodes": [
|
| 694 |
+
{"id": "b", "parent": "a"},
|
| 695 |
+
{"id": "a", "parent": None},
|
| 696 |
+
{"id": "c", "parent": None},
|
| 697 |
+
]
|
| 698 |
+
},
|
| 699 |
+
{"nodes": []},
|
| 700 |
+
{"nodes": [{"id": "x", "parent": None}]},
|
| 701 |
+
{
|
| 702 |
+
"nodes": [
|
| 703 |
+
{"id": "c", "parent": "b"},
|
| 704 |
+
{"id": "b", "parent": "a"},
|
| 705 |
+
{"id": "a", "parent": None},
|
| 706 |
+
]
|
| 707 |
+
},
|
| 708 |
+
{"nodes": [{"id": "z", "parent": None}, {"id": "a", "parent": None}]},
|
| 709 |
+
],
|
| 710 |
+
[{"id": "a", "depth": 0}, {"id": "b", "depth": 1}, {"id": "c", "depth": 0}],
|
| 711 |
+
)
|
| 712 |
+
add(
|
| 713 |
+
"dependency_build",
|
| 714 |
+
"graphs",
|
| 715 |
+
"dependencies targets",
|
| 716 |
+
"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.",
|
| 717 |
+
[
|
| 718 |
+
{
|
| 719 |
+
"dependencies": {
|
| 720 |
+
"app": ["lib", "cfg"],
|
| 721 |
+
"lib": ["cfg"],
|
| 722 |
+
"cfg": [],
|
| 723 |
+
"unused": [],
|
| 724 |
+
},
|
| 725 |
+
"targets": ["app"],
|
| 726 |
+
},
|
| 727 |
+
{"dependencies": {}, "targets": []},
|
| 728 |
+
{"dependencies": {"a": ["b"], "b": ["a"]}, "targets": ["a"]},
|
| 729 |
+
{"dependencies": {"a": [], "x": ["x"]}, "targets": ["a"]},
|
| 730 |
+
{"dependencies": {"a": [], "b": ["a"]}, "targets": ["b", "a", "b"]},
|
| 731 |
+
],
|
| 732 |
+
["cfg", "lib", "app"],
|
| 733 |
+
)
|
| 734 |
+
add(
|
| 735 |
+
"path_normalize",
|
| 736 |
+
"systems",
|
| 737 |
+
"paths",
|
| 738 |
+
"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.",
|
| 739 |
+
[
|
| 740 |
+
{"paths": ["a/../b//c/", "/../../x", ""]},
|
| 741 |
+
{"paths": []},
|
| 742 |
+
{"paths": ["/", ".", "..", "a/./b"]},
|
| 743 |
+
{"paths": ["a\\b/c", "/a/.../b"]},
|
| 744 |
+
{"paths": ["é/../中", "a/../../"]},
|
| 745 |
+
],
|
| 746 |
+
["/b/c", "/x", "/"],
|
| 747 |
+
)
|
| 748 |
+
add(
|
| 749 |
+
"url_query",
|
| 750 |
+
"systems",
|
| 751 |
+
"query",
|
| 752 |
+
"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.",
|
| 753 |
+
[
|
| 754 |
+
{"query": "a=1&a=2&x=hello+world&empty="},
|
| 755 |
+
{"query": ""},
|
| 756 |
+
{"query": "flag&&=x"},
|
| 757 |
+
{"query": "q=%C3%A9&a%2Fb=x%3Dy"},
|
| 758 |
+
{"query": "x=%2B&x=+&x=a=b"},
|
| 759 |
+
],
|
| 760 |
+
{"a": ["1", "2"], "x": ["hello world"], "empty": [""]},
|
| 761 |
+
)
|
| 762 |
+
add(
|
| 763 |
+
"version_sort",
|
| 764 |
+
"systems",
|
| 765 |
+
"versions",
|
| 766 |
+
"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.",
|
| 767 |
+
[
|
| 768 |
+
{"versions": ["1.0.0", "1.0.0-beta", "1.0.0-alpha.10", "1.0.0-alpha.2"]},
|
| 769 |
+
{"versions": []},
|
| 770 |
+
{"versions": ["2.0.0", "10.0.0", "1.9.9"]},
|
| 771 |
+
{"versions": ["1.0.0-a", "1.0.0-1", "1.0.0-a.1", "1.0.0"]},
|
| 772 |
+
{"versions": ["1.0.0", "1.0.0"]},
|
| 773 |
+
],
|
| 774 |
+
["1.0.0-alpha.2", "1.0.0-alpha.10", "1.0.0-beta", "1.0.0"],
|
| 775 |
+
)
|
| 776 |
+
add(
|
| 777 |
+
"lru_trace",
|
| 778 |
+
"systems",
|
| 779 |
+
"capacity accesses",
|
| 780 |
+
"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.",
|
| 781 |
+
[
|
| 782 |
+
{"capacity": 2, "accesses": ["a", "b", "a", "c", "b"]},
|
| 783 |
+
{"capacity": 0, "accesses": ["a", "a"]},
|
| 784 |
+
{"capacity": 3, "accesses": []},
|
| 785 |
+
{"capacity": 1, "accesses": ["a", "a", "b"]},
|
| 786 |
+
{"capacity": 9, "accesses": ["x", "y", "x"]},
|
| 787 |
+
],
|
| 788 |
+
{"hits": 1, "misses": 4, "keys": ["c", "b"]},
|
| 789 |
+
)
|
| 790 |
+
add(
|
| 791 |
+
"rate_limit",
|
| 792 |
+
"systems",
|
| 793 |
+
"events window limit",
|
| 794 |
+
"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.",
|
| 795 |
+
[
|
| 796 |
+
{
|
| 797 |
+
"events": [{"key": "a", "time": t} for t in [0, 0, 1, 5]],
|
| 798 |
+
"window": 5,
|
| 799 |
+
"limit": 2,
|
| 800 |
+
},
|
| 801 |
+
{"events": [], "window": 1, "limit": 1},
|
| 802 |
+
{"events": [{"key": "x", "time": 0}], "window": 1, "limit": 0},
|
| 803 |
+
{
|
| 804 |
+
"events": [
|
| 805 |
+
{"key": "a", "time": 0},
|
| 806 |
+
{"key": "b", "time": 0},
|
| 807 |
+
{"key": "a", "time": 1},
|
| 808 |
+
],
|
| 809 |
+
"window": 1,
|
| 810 |
+
"limit": 1,
|
| 811 |
+
},
|
| 812 |
+
{
|
| 813 |
+
"events": [{"key": "a", "time": t} for t in [-3, -2, -1, 0]],
|
| 814 |
+
"window": 2,
|
| 815 |
+
"limit": 1,
|
| 816 |
+
},
|
| 817 |
+
],
|
| 818 |
+
[True, True, False, True],
|
| 819 |
+
)
|
| 820 |
+
add(
|
| 821 |
+
"priority_queue",
|
| 822 |
+
"systems",
|
| 823 |
+
"events",
|
| 824 |
+
'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}.',
|
| 825 |
+
[
|
| 826 |
+
{
|
| 827 |
+
"events": [
|
| 828 |
+
{"op": "push", "priority": 2, "value": "a"},
|
| 829 |
+
{"op": "push", "priority": 1, "value": "b"},
|
| 830 |
+
{"op": "pop"},
|
| 831 |
+
]
|
| 832 |
+
},
|
| 833 |
+
{"events": []},
|
| 834 |
+
{"events": [{"op": "pop"}, {"op": "pop"}]},
|
| 835 |
+
{
|
| 836 |
+
"events": [
|
| 837 |
+
{"op": "push", "priority": 0, "value": {"x": 1}},
|
| 838 |
+
{"op": "push", "priority": 0, "value": None},
|
| 839 |
+
{"op": "pop"},
|
| 840 |
+
]
|
| 841 |
+
},
|
| 842 |
+
{"events": [{"op": "push", "priority": -1, "value": 3}]},
|
| 843 |
+
],
|
| 844 |
+
{"popped": ["b"], "remaining": ["a"]},
|
| 845 |
+
)
|
| 846 |
+
add(
|
| 847 |
+
"round_robin",
|
| 848 |
+
"systems",
|
| 849 |
+
"jobs quantum",
|
| 850 |
+
"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.",
|
| 851 |
+
[
|
| 852 |
+
{
|
| 853 |
+
"jobs": [{"id": "a", "duration": 3}, {"id": "b", "duration": 2}],
|
| 854 |
+
"quantum": 2,
|
| 855 |
+
},
|
| 856 |
+
{"jobs": [], "quantum": 1},
|
| 857 |
+
{"jobs": [{"id": "a", "duration": 1}], "quantum": 10},
|
| 858 |
+
{
|
| 859 |
+
"jobs": [{"id": "a", "duration": 2}, {"id": "b", "duration": 1}],
|
| 860 |
+
"quantum": 1,
|
| 861 |
+
},
|
| 862 |
+
{"jobs": [{"id": "x", "duration": 4}], "quantum": 2},
|
| 863 |
+
],
|
| 864 |
+
{
|
| 865 |
+
"slices": [
|
| 866 |
+
{"id": "a", "start": 0, "end": 2},
|
| 867 |
+
{"id": "b", "start": 2, "end": 4},
|
| 868 |
+
{"id": "a", "start": 4, "end": 5},
|
| 869 |
+
],
|
| 870 |
+
"completion": {"b": 4, "a": 5},
|
| 871 |
+
},
|
| 872 |
+
)
|
| 873 |
+
add(
|
| 874 |
+
"inventory_ledger",
|
| 875 |
+
"business",
|
| 876 |
+
"events",
|
| 877 |
+
"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}.",
|
| 878 |
+
[
|
| 879 |
+
{
|
| 880 |
+
"events": [
|
| 881 |
+
{"sku": "a", "delta": 3},
|
| 882 |
+
{"sku": "a", "delta": -4},
|
| 883 |
+
{"sku": "a", "delta": -2},
|
| 884 |
+
]
|
| 885 |
+
},
|
| 886 |
+
{"events": []},
|
| 887 |
+
{"events": [{"sku": "x", "delta": -1}]},
|
| 888 |
+
{
|
| 889 |
+
"events": [
|
| 890 |
+
{"sku": "x", "delta": 0},
|
| 891 |
+
{"sku": "y", "delta": 2},
|
| 892 |
+
{"sku": "y", "delta": -2},
|
| 893 |
+
]
|
| 894 |
+
},
|
| 895 |
+
{"events": [{"sku": "", "delta": 1}]},
|
| 896 |
+
],
|
| 897 |
+
{"stock": {"a": 1}, "rejected": [1]},
|
| 898 |
+
)
|
| 899 |
+
add(
|
| 900 |
+
"bank_ledger",
|
| 901 |
+
"business",
|
| 902 |
+
"balances transfers",
|
| 903 |
+
"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.",
|
| 904 |
+
[
|
| 905 |
+
{
|
| 906 |
+
"balances": {"a": 10, "b": 0},
|
| 907 |
+
"transfers": [
|
| 908 |
+
{"from": "a", "to": "b", "amount": 7},
|
| 909 |
+
{"from": "a", "to": "b", "amount": 4},
|
| 910 |
+
],
|
| 911 |
+
},
|
| 912 |
+
{"balances": {}, "transfers": []},
|
| 913 |
+
{"balances": {"a": 2}, "transfers": [{"from": "a", "to": "a", "amount": 2}]},
|
| 914 |
+
{"balances": {"a": 3}, "transfers": [{"from": "a", "to": "x", "amount": 1}]},
|
| 915 |
+
{"balances": {"a": 0}, "transfers": [{"from": "x", "to": "a", "amount": 1}]},
|
| 916 |
+
],
|
| 917 |
+
{"balances": {"a": 3, "b": 7}, "rejected": [1]},
|
| 918 |
+
)
|
| 919 |
+
add(
|
| 920 |
+
"ballot_count",
|
| 921 |
+
"business",
|
| 922 |
+
"candidates votes",
|
| 923 |
+
"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.",
|
| 924 |
+
[
|
| 925 |
+
{"candidates": ["b", "a", "c"], "votes": ["a", "b", "a", "x"]},
|
| 926 |
+
{"candidates": [], "votes": []},
|
| 927 |
+
{"candidates": ["a"], "votes": ["x", ""]},
|
| 928 |
+
{"candidates": ["b", "a"], "votes": ["b", "a"]},
|
| 929 |
+
{"candidates": [], "votes": ["x"]},
|
| 930 |
+
],
|
| 931 |
+
{
|
| 932 |
+
"ranking": [
|
| 933 |
+
{"candidate": "a", "votes": 2},
|
| 934 |
+
{"candidate": "b", "votes": 1},
|
| 935 |
+
{"candidate": "c", "votes": 0},
|
| 936 |
+
],
|
| 937 |
+
"invalid": 1,
|
| 938 |
+
},
|
| 939 |
+
)
|
| 940 |
+
add(
|
| 941 |
+
"search_rank",
|
| 942 |
+
"business",
|
| 943 |
+
"documents query",
|
| 944 |
+
"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.",
|
| 945 |
+
[
|
| 946 |
+
{
|
| 947 |
+
"documents": [
|
| 948 |
+
{"id": "b", "text": "red blue"},
|
| 949 |
+
{"id": "a", "text": "red red"},
|
| 950 |
+
{"id": "c", "text": "green"},
|
| 951 |
+
],
|
| 952 |
+
"query": "RED red blue",
|
| 953 |
+
},
|
| 954 |
+
{"documents": [], "query": "x"},
|
| 955 |
+
{"documents": [{"id": "a", "text": "x"}], "query": ""},
|
| 956 |
+
{
|
| 957 |
+
"documents": [{"id": "z", "text": "x"}, {"id": "a", "text": "x"}],
|
| 958 |
+
"query": "x",
|
| 959 |
+
},
|
| 960 |
+
{"documents": [{"id": "a", "text": "é RED_42"}], "query": "red 42"},
|
| 961 |
+
],
|
| 962 |
+
[{"id": "a", "score": 2}, {"id": "b", "score": 2}],
|
| 963 |
+
)
|
| 964 |
+
add(
|
| 965 |
+
"log_summary",
|
| 966 |
+
"business",
|
| 967 |
+
"events",
|
| 968 |
+
"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.",
|
| 969 |
+
[
|
| 970 |
+
{
|
| 971 |
+
"events": [
|
| 972 |
+
{"level": "INFO", "message": "start"},
|
| 973 |
+
{"level": "ERROR", "message": "bad"},
|
| 974 |
+
{"level": "ERROR", "message": "worse"},
|
| 975 |
+
]
|
| 976 |
+
},
|
| 977 |
+
{"events": []},
|
| 978 |
+
{"events": [{"level": "error", "message": "x"}]},
|
| 979 |
+
{
|
| 980 |
+
"events": [
|
| 981 |
+
{"level": "WARN", "message": ""},
|
| 982 |
+
{"level": "INFO", "message": "ok"},
|
| 983 |
+
]
|
| 984 |
+
},
|
| 985 |
+
{"events": [{"level": "ERROR", "message": "é"}]},
|
| 986 |
+
],
|
| 987 |
+
{"counts": {"INFO": 1, "ERROR": 2}, "errors": ["bad", "worse"]},
|
| 988 |
+
)
|
| 989 |
+
add(
|
| 990 |
+
"uptime_report",
|
| 991 |
+
"business",
|
| 992 |
+
"start end downtime",
|
| 993 |
+
"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.",
|
| 994 |
+
[
|
| 995 |
+
{"start": 0, "end": 10, "downtime": [[-2, 3], [2, 5], [8, 12]]},
|
| 996 |
+
{"start": 0, "end": 0, "downtime": []},
|
| 997 |
+
{"start": 0, "end": 5, "downtime": []},
|
| 998 |
+
{"start": 0, "end": 5, "downtime": [[-10, 10]]},
|
| 999 |
+
{"start": 0, "end": 5, "downtime": [[1, 1], [5, 8]]},
|
| 1000 |
+
],
|
| 1001 |
+
{"down": 7, "up": 3},
|
| 1002 |
+
)
|
| 1003 |
+
add(
|
| 1004 |
+
"segment_intersection",
|
| 1005 |
+
"geometry",
|
| 1006 |
+
"a b c d",
|
| 1007 |
+
"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.",
|
| 1008 |
+
[
|
| 1009 |
+
{"a": [0, 0], "b": [2, 2], "c": [0, 2], "d": [2, 0]},
|
| 1010 |
+
{"a": [0, 0], "b": [1, 0], "c": [2, 0], "d": [3, 0]},
|
| 1011 |
+
{"a": [0, 0], "b": [2, 0], "c": [1, 0], "d": [3, 0]},
|
| 1012 |
+
{"a": [0, 0], "b": [0, 0], "c": [-1, 0], "d": [1, 0]},
|
| 1013 |
+
{"a": [0, 0], "b": [0, 1], "c": [0, 1], "d": [1, 1]},
|
| 1014 |
+
{"a": [0, 0], "b": [0, 0], "c": [1, 1], "d": [1, 1]},
|
| 1015 |
+
],
|
| 1016 |
+
True,
|
| 1017 |
+
)
|
| 1018 |
+
add(
|
| 1019 |
+
"polygon_area",
|
| 1020 |
+
"geometry",
|
| 1021 |
+
"points",
|
| 1022 |
+
"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.",
|
| 1023 |
+
[
|
| 1024 |
+
{"points": [[0, 0], [4, 0], [4, 3], [0, 3]]},
|
| 1025 |
+
{"points": []},
|
| 1026 |
+
{"points": [[1, 2]]},
|
| 1027 |
+
{"points": [[0, 0], [1, 0], [0, 1]]},
|
| 1028 |
+
{"points": [[0, 0], [0, 3], [4, 3], [4, 0]]},
|
| 1029 |
+
{"points": [[-1, -1], [1, 1]]},
|
| 1030 |
+
],
|
| 1031 |
+
12,
|
| 1032 |
+
)
|
| 1033 |
+
add(
|
| 1034 |
+
"skyline",
|
| 1035 |
+
"geometry",
|
| 1036 |
+
"buildings",
|
| 1037 |
+
"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 [].",
|
| 1038 |
+
[
|
| 1039 |
+
{"buildings": [[1, 4, 3], [2, 6, 5], [7, 8, 2]]},
|
| 1040 |
+
{"buildings": []},
|
| 1041 |
+
{"buildings": [[0, 1, 2], [1, 2, 2]]},
|
| 1042 |
+
{"buildings": [[0, 5, 4], [1, 2, 1]]},
|
| 1043 |
+
{"buildings": [[-2, 0, 3], [-2, 0, 3]]},
|
| 1044 |
+
],
|
| 1045 |
+
[[1, 3], [2, 5], [6, 0], [7, 2], [8, 0]],
|
| 1046 |
+
)
|
| 1047 |
+
add(
|
| 1048 |
+
"knapsack",
|
| 1049 |
+
"optimization",
|
| 1050 |
+
"items capacity",
|
| 1051 |
+
"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.",
|
| 1052 |
+
[
|
| 1053 |
+
{
|
| 1054 |
+
"items": [
|
| 1055 |
+
{"weight": 2, "value": 3},
|
| 1056 |
+
{"weight": 3, "value": 4},
|
| 1057 |
+
{"weight": 4, "value": 8},
|
| 1058 |
+
],
|
| 1059 |
+
"capacity": 5,
|
| 1060 |
+
},
|
| 1061 |
+
{"items": [], "capacity": 5},
|
| 1062 |
+
{"items": [{"weight": 1, "value": 2}], "capacity": 0},
|
| 1063 |
+
{
|
| 1064 |
+
"items": [{"weight": 2, "value": 3}, {"weight": 2, "value": 3}],
|
| 1065 |
+
"capacity": 4,
|
| 1066 |
+
},
|
| 1067 |
+
{"items": [{"weight": 9, "value": 20}], "capacity": 3},
|
| 1068 |
+
],
|
| 1069 |
+
8,
|
| 1070 |
+
)
|
| 1071 |
+
add(
|
| 1072 |
+
"task_selection",
|
| 1073 |
+
"optimization",
|
| 1074 |
+
"tasks",
|
| 1075 |
+
"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.",
|
| 1076 |
+
[
|
| 1077 |
+
{
|
| 1078 |
+
"tasks": [
|
| 1079 |
+
{"id": "a", "start": 0, "end": 3},
|
| 1080 |
+
{"id": "b", "start": 1, "end": 2},
|
| 1081 |
+
{"id": "c", "start": 2, "end": 4},
|
| 1082 |
+
]
|
| 1083 |
+
},
|
| 1084 |
+
{"tasks": []},
|
| 1085 |
+
{
|
| 1086 |
+
"tasks": [
|
| 1087 |
+
{"id": "b", "start": 0, "end": 1},
|
| 1088 |
+
{"id": "a", "start": 0, "end": 1},
|
| 1089 |
+
]
|
| 1090 |
+
},
|
| 1091 |
+
{
|
| 1092 |
+
"tasks": [
|
| 1093 |
+
{"id": "a", "start": -3, "end": -1},
|
| 1094 |
+
{"id": "b", "start": -1, "end": 0},
|
| 1095 |
+
]
|
| 1096 |
+
},
|
| 1097 |
+
{"tasks": [{"id": "x", "start": 0, "end": 9}]},
|
| 1098 |
+
],
|
| 1099 |
+
["b", "c"],
|
| 1100 |
+
)
|
| 1101 |
+
add(
|
| 1102 |
+
"sequence_diff",
|
| 1103 |
+
"optimization",
|
| 1104 |
+
"a b",
|
| 1105 |
+
'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.',
|
| 1106 |
+
[
|
| 1107 |
+
{"a": ["a", "b"], "b": ["b", "c"]},
|
| 1108 |
+
{"a": [], "b": []},
|
| 1109 |
+
{"a": ["a"], "b": []},
|
| 1110 |
+
{"a": [], "b": ["x", "y"]},
|
| 1111 |
+
{"a": ["a", "b"], "b": ["b", "a"]},
|
| 1112 |
+
{"a": ["x", "x"], "b": ["x"]},
|
| 1113 |
+
],
|
| 1114 |
+
[["delete", "a"], ["keep", "b"], ["insert", "c"]],
|
| 1115 |
+
)
|
| 1116 |
+
add(
|
| 1117 |
+
"finite_automaton",
|
| 1118 |
+
"languages",
|
| 1119 |
+
"start accepting transitions words",
|
| 1120 |
+
"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.",
|
| 1121 |
+
[
|
| 1122 |
+
{
|
| 1123 |
+
"start": "a",
|
| 1124 |
+
"accepting": ["a"],
|
| 1125 |
+
"transitions": [
|
| 1126 |
+
{"from": "a", "symbol": "x", "to": "b"},
|
| 1127 |
+
{"from": "b", "symbol": "x", "to": "a"},
|
| 1128 |
+
],
|
| 1129 |
+
"words": ["", "x", "xx", "y"],
|
| 1130 |
+
},
|
| 1131 |
+
{"start": "s", "accepting": [], "transitions": [], "words": ["", "a"]},
|
| 1132 |
+
{"start": "s", "accepting": ["s"], "transitions": [], "words": [""]},
|
| 1133 |
+
{
|
| 1134 |
+
"start": "s",
|
| 1135 |
+
"accepting": ["t"],
|
| 1136 |
+
"transitions": [{"from": "s", "symbol": "é", "to": "t"}],
|
| 1137 |
+
"words": ["é", "éé"],
|
| 1138 |
+
},
|
| 1139 |
+
{"start": "s", "accepting": ["s"], "transitions": [], "words": []},
|
| 1140 |
+
],
|
| 1141 |
+
[True, False, True, False],
|
| 1142 |
+
)
|
| 1143 |
+
add(
|
| 1144 |
+
"content_manifest",
|
| 1145 |
+
"systems",
|
| 1146 |
+
"files",
|
| 1147 |
+
"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.",
|
| 1148 |
+
[
|
| 1149 |
+
{"files": {"empty": ""}},
|
| 1150 |
+
{"files": {}},
|
| 1151 |
+
{"files": {"b": "hello", "a": "é"}},
|
| 1152 |
+
{"files": {"x": "a\n", "y": "a"}},
|
| 1153 |
+
{"files": {"中": "😀", "nul": "\u0000"}},
|
| 1154 |
+
],
|
| 1155 |
+
[
|
| 1156 |
+
{
|
| 1157 |
+
"path": "empty",
|
| 1158 |
+
"bytes": 0,
|
| 1159 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 1160 |
+
}
|
| 1161 |
+
],
|
| 1162 |
+
)
|
| 1163 |
+
add(
|
| 1164 |
+
"cellular_automaton",
|
| 1165 |
+
"simulation",
|
| 1166 |
+
"live steps",
|
| 1167 |
+
"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.",
|
| 1168 |
+
[
|
| 1169 |
+
{"live": [[0, 0], [0, 1], [0, 2]], "steps": 1},
|
| 1170 |
+
{"live": [], "steps": 10},
|
| 1171 |
+
{"live": [[0, 0]], "steps": 1},
|
| 1172 |
+
{"live": [[0, 0], [0, 1], [1, 0], [1, 1]], "steps": 5},
|
| 1173 |
+
{"live": [[1, 2], [1, 2], [-1, 0]], "steps": 0},
|
| 1174 |
+
{"live": [[0, 0], [0, 1], [0, 2]], "steps": 2},
|
| 1175 |
+
],
|
| 1176 |
+
[[-1, 1], [0, 1], [1, 1]],
|
| 1177 |
+
)
|
| 1178 |
+
add(
|
| 1179 |
+
"expression_eval",
|
| 1180 |
+
"languages",
|
| 1181 |
+
"tokens",
|
| 1182 |
+
"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.",
|
| 1183 |
+
[
|
| 1184 |
+
{"tokens": ["5", "2", "-", "4", "*"]},
|
| 1185 |
+
{"tokens": ["-7", "3", "/"]},
|
| 1186 |
+
{"tokens": ["7", "-3", "/"]},
|
| 1187 |
+
{"tokens": ["42"]},
|
| 1188 |
+
{"tokens": ["2", "3", "4", "*", "+"]},
|
| 1189 |
+
{"tokens": ["100000000000000000001", "3", "/"]},
|
| 1190 |
+
],
|
| 1191 |
+
12,
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
assert len(FAMILIES) == 65
|
klein_code_bench/cli.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from .runner import evaluate, find_task, load_tasks
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def write_json(path, value):
|
| 12 |
+
path = Path(path)
|
| 13 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
path.write_text(
|
| 15 |
+
json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def main(argv=None):
|
| 20 |
+
parser = argparse.ArgumentParser(
|
| 21 |
+
prog="klein-bench",
|
| 22 |
+
description="Klein-Code-Bench: 260 from-scratch Python projects. No Docker.",
|
| 23 |
+
)
|
| 24 |
+
commands = parser.add_subparsers(dest="command", required=True)
|
| 25 |
+
listing = commands.add_parser("list", help="List task IDs and titles")
|
| 26 |
+
listing.add_argument("--subset", choices=["easy", "intermediate", "hard", "max"])
|
| 27 |
+
for name in ("prepare", "reference", "evaluate"):
|
| 28 |
+
p = commands.add_parser(name)
|
| 29 |
+
p.add_argument("task_id")
|
| 30 |
+
if name == "evaluate":
|
| 31 |
+
p.add_argument("--solution", type=Path, required=True)
|
| 32 |
+
p.add_argument("--output", type=Path)
|
| 33 |
+
p.add_argument("--fail-fast", action="store_true")
|
| 34 |
+
p.add_argument(
|
| 35 |
+
"--public-only",
|
| 36 |
+
action="store_true",
|
| 37 |
+
help="Smoke test only; never an official task pass",
|
| 38 |
+
)
|
| 39 |
+
else:
|
| 40 |
+
p.add_argument("--output", type=Path, required=True)
|
| 41 |
+
validation = commands.add_parser(
|
| 42 |
+
"validate",
|
| 43 |
+
help="Validate manifest, all goldens, references and empty submissions",
|
| 44 |
+
)
|
| 45 |
+
validation.add_argument("--subset", choices=["easy", "intermediate", "hard", "max"])
|
| 46 |
+
validation.add_argument(
|
| 47 |
+
"--output", type=Path, default=Path("results/validation.json")
|
| 48 |
+
)
|
| 49 |
+
commands.add_parser(
|
| 50 |
+
"build", help="Rebuild dataset reproducibly from authored source"
|
| 51 |
+
)
|
| 52 |
+
score = commands.add_parser(
|
| 53 |
+
"score", help="Aggregate one JSON evaluation report per submitted task"
|
| 54 |
+
)
|
| 55 |
+
score.add_argument("reports", nargs="+", type=Path)
|
| 56 |
+
args = parser.parse_args(argv)
|
| 57 |
+
try:
|
| 58 |
+
if args.command == "list":
|
| 59 |
+
for task in load_tasks(args.subset):
|
| 60 |
+
print(task["task_id"] + "\t" + task["title"])
|
| 61 |
+
return 0
|
| 62 |
+
if args.command == "build":
|
| 63 |
+
from .build import build
|
| 64 |
+
|
| 65 |
+
print(json.dumps(build(), indent=2))
|
| 66 |
+
return 0
|
| 67 |
+
if args.command == "score":
|
| 68 |
+
from .scoring import summarize
|
| 69 |
+
|
| 70 |
+
print(
|
| 71 |
+
json.dumps(
|
| 72 |
+
summarize([json.loads(p.read_text()) for p in args.reports]),
|
| 73 |
+
indent=2,
|
| 74 |
+
)
|
| 75 |
+
)
|
| 76 |
+
return 0
|
| 77 |
+
if args.command == "validate":
|
| 78 |
+
from .validation import validate
|
| 79 |
+
|
| 80 |
+
report = validate(args.subset)
|
| 81 |
+
write_json(args.output, report)
|
| 82 |
+
print(
|
| 83 |
+
json.dumps(
|
| 84 |
+
{k: v for k, v in report.items() if k != "results"}, indent=2
|
| 85 |
+
)
|
| 86 |
+
)
|
| 87 |
+
return 0 if report["passed"] else 1
|
| 88 |
+
task = find_task(args.task_id)
|
| 89 |
+
if args.command == "prepare":
|
| 90 |
+
if args.output.exists() and any(args.output.iterdir()):
|
| 91 |
+
raise ValueError("Prepare destination must be empty")
|
| 92 |
+
args.output.mkdir(parents=True, exist_ok=True)
|
| 93 |
+
(args.output / "project").mkdir()
|
| 94 |
+
(args.output / "PROMPT.md").write_text(
|
| 95 |
+
task["prompt"] + "\n", encoding="utf-8"
|
| 96 |
+
)
|
| 97 |
+
public = {k: v for k, v in task.items() if k != "acceptance_tests"}
|
| 98 |
+
write_json(args.output / "task.json", public)
|
| 99 |
+
print(f"Empty project: {args.output / 'project'}")
|
| 100 |
+
elif args.command == "reference":
|
| 101 |
+
from .reference.export import export_reference
|
| 102 |
+
|
| 103 |
+
print(export_reference(task["family"], task["subset"], args.output))
|
| 104 |
+
else:
|
| 105 |
+
tests = None
|
| 106 |
+
if args.public_only:
|
| 107 |
+
examples = json.loads(task["public_tests"])
|
| 108 |
+
tests = [
|
| 109 |
+
{
|
| 110 |
+
"name": "public-smoke-only",
|
| 111 |
+
"sessions": [
|
| 112 |
+
{
|
| 113 |
+
"requests": [e["request"] for e in examples],
|
| 114 |
+
"expected": [e["response"] for e in examples],
|
| 115 |
+
}
|
| 116 |
+
],
|
| 117 |
+
}
|
| 118 |
+
]
|
| 119 |
+
report = evaluate(
|
| 120 |
+
task, args.solution, tests=tests, fail_fast=args.fail_fast
|
| 121 |
+
)
|
| 122 |
+
report["evaluation_scope"] = "public" if args.public_only else "acceptance"
|
| 123 |
+
if args.public_only:
|
| 124 |
+
report["resolved"] = False
|
| 125 |
+
if args.output:
|
| 126 |
+
write_json(args.output, report)
|
| 127 |
+
print(json.dumps(report, indent=2))
|
| 128 |
+
return 0 if report["passed"] else 1
|
| 129 |
+
return 0
|
| 130 |
+
except (OSError, ValueError) as error:
|
| 131 |
+
print(f"klein-bench: {error}", file=sys.stderr)
|
| 132 |
+
return 2
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
raise SystemExit(main())
|
klein_code_bench/data/easy.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
klein_code_bench/data/hard.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
klein_code_bench/data/intermediate.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
klein_code_bench/data/manifest.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"benchmark": "Klein-Code-Bench",
|
| 3 |
+
"version": "0.1.0",
|
| 4 |
+
"protocol_version": "1.0",
|
| 5 |
+
"tasks": 260,
|
| 6 |
+
"families": 65,
|
| 7 |
+
"counts": {
|
| 8 |
+
"easy": 65,
|
| 9 |
+
"intermediate": 65,
|
| 10 |
+
"hard": 65,
|
| 11 |
+
"max": 65
|
| 12 |
+
},
|
| 13 |
+
"assertions": {
|
| 14 |
+
"easy": 3075,
|
| 15 |
+
"intermediate": 5415,
|
| 16 |
+
"hard": 9705,
|
| 17 |
+
"max": 15490
|
| 18 |
+
},
|
| 19 |
+
"sha256": {
|
| 20 |
+
"easy.jsonl": "07c3bbf7b25787574e8350ea8f9abe2646ccb26fc2d1ffe8ca86674f82703d1d",
|
| 21 |
+
"intermediate.jsonl": "d00b88b9f18272ed69f4e0dcc4b8742ee919c66ecd016716e10de2a0012178f5",
|
| 22 |
+
"hard.jsonl": "c8eb001ba240298a96e0bef8c3b0f60dd6728e462f76d87757dfc69b477a159d",
|
| 23 |
+
"max.jsonl": "b0613d3beb00ad302932f6fe1b90c26d8209874f6b07fb7fbf0651b332911d84"
|
| 24 |
+
},
|
| 25 |
+
"seed": 1729,
|
| 26 |
+
"difficulty_calibrated": false
|
| 27 |
+
}
|
klein_code_bench/data/max.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
klein_code_bench/fuzz.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic additional domain inputs, generated without model/reference output."""
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import datetime as dt
|
| 5 |
+
import io
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generated_inputs(family, count=24, seed=1729):
|
| 10 |
+
r = random.Random(f"{seed}/{family}/domain")
|
| 11 |
+
|
| 12 |
+
def nums():
|
| 13 |
+
return [r.randrange(-9, 10) for _ in range(r.randrange(12))]
|
| 14 |
+
|
| 15 |
+
def words():
|
| 16 |
+
return [
|
| 17 |
+
r.choice(["a", "b", "c", "", "é", "a/b"]) for _ in range(r.randrange(12))
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
def text(chars="abAB09_ -é\n"):
|
| 21 |
+
return "".join(r.choices(chars, k=r.randrange(60)))
|
| 22 |
+
|
| 23 |
+
def intervals():
|
| 24 |
+
return [
|
| 25 |
+
sorted([r.randrange(-10, 11), r.randrange(-10, 11)])
|
| 26 |
+
for _ in range(r.randrange(10))
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
for _ in range(count):
|
| 30 |
+
if family in {"word_frequency", "run_length"}:
|
| 31 |
+
x = {"text": text()}
|
| 32 |
+
elif family == "bracket_audit":
|
| 33 |
+
x = {"text": text("()[]{}abcé ")}
|
| 34 |
+
elif family == "slug_registry":
|
| 35 |
+
x = {"titles": [text("aAB -_/é") for _ in range(r.randrange(12))]}
|
| 36 |
+
elif family == "text_wrap":
|
| 37 |
+
x = {"text": text(), "width": r.randrange(1, 20)}
|
| 38 |
+
elif family == "ngram_index":
|
| 39 |
+
x = {"tokens": words(), "n": r.randrange(1, 5)}
|
| 40 |
+
elif family == "glob_filter":
|
| 41 |
+
x = {
|
| 42 |
+
"paths": words(),
|
| 43 |
+
"pattern": r.choice(["*", "?", "[abc]*", "*/*", "[!a]*", "é"]),
|
| 44 |
+
}
|
| 45 |
+
elif family == "edit_distance":
|
| 46 |
+
x = {"a": text(), "b": text()}
|
| 47 |
+
elif family == "roman_codec":
|
| 48 |
+
x = {"number": r.randrange(1, 4000)}
|
| 49 |
+
elif family == "caesar_cipher":
|
| 50 |
+
x = {"text": text(), "shift": r.randrange(-1000, 1001)}
|
| 51 |
+
elif family == "csv_records":
|
| 52 |
+
stream = io.StringIO()
|
| 53 |
+
writer = csv.writer(stream)
|
| 54 |
+
writer.writerow(["a", "b"])
|
| 55 |
+
writer.writerows(
|
| 56 |
+
[[text('a,b"\né '), text()] for _ in range(r.randrange(8))]
|
| 57 |
+
)
|
| 58 |
+
x = {"csv": stream.getvalue()}
|
| 59 |
+
elif family in {"record_query", "dedupe_records"}:
|
| 60 |
+
rows = [
|
| 61 |
+
{k: r.choice([None, 1, 2, "x"]) for k in ("a", "b") if r.random() < 0.8}
|
| 62 |
+
for _ in range(r.randrange(15))
|
| 63 |
+
]
|
| 64 |
+
x = (
|
| 65 |
+
{
|
| 66 |
+
"rows": rows,
|
| 67 |
+
"where": {"a": r.choice([None, 1, 2])},
|
| 68 |
+
"select": ["b", "c"],
|
| 69 |
+
}
|
| 70 |
+
if family == "record_query"
|
| 71 |
+
else {"rows": rows, "keys": r.choice([[], ["a"], ["a", "b"]])}
|
| 72 |
+
)
|
| 73 |
+
elif family == "inner_join":
|
| 74 |
+
x = {
|
| 75 |
+
"left": [{"k": r.randrange(4)} for _ in range(r.randrange(8))],
|
| 76 |
+
"right": [{"k": r.randrange(4)} for _ in range(r.randrange(8))],
|
| 77 |
+
"key": "k",
|
| 78 |
+
}
|
| 79 |
+
elif family == "group_totals":
|
| 80 |
+
x = {
|
| 81 |
+
"rows": [
|
| 82 |
+
{"g": r.choice(["a", "b", ""]), "v": r.randrange(-20, 21)}
|
| 83 |
+
for _ in range(r.randrange(16))
|
| 84 |
+
],
|
| 85 |
+
"group": "g",
|
| 86 |
+
"value": "v",
|
| 87 |
+
}
|
| 88 |
+
elif family == "pivot_table":
|
| 89 |
+
x = {
|
| 90 |
+
"rows": [
|
| 91 |
+
{
|
| 92 |
+
"r": r.choice(["a", "b", ""]),
|
| 93 |
+
"c": r.choice(["x", "y"]),
|
| 94 |
+
"v": r.randrange(-9, 10),
|
| 95 |
+
}
|
| 96 |
+
for _ in range(r.randrange(16))
|
| 97 |
+
],
|
| 98 |
+
"row": "r",
|
| 99 |
+
"column": "c",
|
| 100 |
+
"value": "v",
|
| 101 |
+
}
|
| 102 |
+
elif family in {"json_flatten", "merge_patch", "json_pointer"}:
|
| 103 |
+
value = {
|
| 104 |
+
"a/b": [nums(), {}, None],
|
| 105 |
+
"~": {"": r.randrange(9)},
|
| 106 |
+
"x": r.choice([True, None, "é"]),
|
| 107 |
+
}
|
| 108 |
+
if family == "json_flatten":
|
| 109 |
+
x = {"value": value}
|
| 110 |
+
elif family == "merge_patch":
|
| 111 |
+
x = {
|
| 112 |
+
"target": value,
|
| 113 |
+
"patch": {
|
| 114 |
+
"a/b": r.choice([None, [1], {"z": 2}]),
|
| 115 |
+
"x": {"v": r.randrange(9)},
|
| 116 |
+
},
|
| 117 |
+
}
|
| 118 |
+
else:
|
| 119 |
+
x = {
|
| 120 |
+
"value": value,
|
| 121 |
+
"pointer": r.choice(
|
| 122 |
+
["", "/a~1b/0", "/a~1b/99", "/~0/", "/x/no", "/absent"]
|
| 123 |
+
),
|
| 124 |
+
}
|
| 125 |
+
elif family == "schema_check":
|
| 126 |
+
x = {
|
| 127 |
+
"schema": {
|
| 128 |
+
k: {
|
| 129 |
+
"type": r.choice(
|
| 130 |
+
[
|
| 131 |
+
"integer",
|
| 132 |
+
"number",
|
| 133 |
+
"boolean",
|
| 134 |
+
"string",
|
| 135 |
+
"array",
|
| 136 |
+
"object",
|
| 137 |
+
"null",
|
| 138 |
+
]
|
| 139 |
+
),
|
| 140 |
+
"required": r.choice([True, False]),
|
| 141 |
+
}
|
| 142 |
+
for k in ("a", "b", "c")
|
| 143 |
+
},
|
| 144 |
+
"value": {
|
| 145 |
+
k: r.choice([True, 1, 1.5, "x", [], {}, None])
|
| 146 |
+
for k in ("a", "b")
|
| 147 |
+
if r.random() < 0.8
|
| 148 |
+
},
|
| 149 |
+
}
|
| 150 |
+
elif family in {
|
| 151 |
+
"interval_union",
|
| 152 |
+
"interval_gaps",
|
| 153 |
+
"booking_peak",
|
| 154 |
+
"uptime_report",
|
| 155 |
+
}:
|
| 156 |
+
pairs = intervals()
|
| 157 |
+
if family == "booking_peak":
|
| 158 |
+
x = {"bookings": pairs}
|
| 159 |
+
elif family == "uptime_report":
|
| 160 |
+
x = {"start": -5, "end": 5, "downtime": pairs}
|
| 161 |
+
else:
|
| 162 |
+
x = {"intervals": pairs}
|
| 163 |
+
if family == "interval_gaps":
|
| 164 |
+
x["bounds"] = [-5, 5]
|
| 165 |
+
elif family == "business_days":
|
| 166 |
+
start = dt.date(2000, 1, 1) + dt.timedelta(days=r.randrange(9000))
|
| 167 |
+
x = {
|
| 168 |
+
"start": start.isoformat(),
|
| 169 |
+
"end": (start + dt.timedelta(days=r.randrange(30))).isoformat(),
|
| 170 |
+
"holidays": [
|
| 171 |
+
(start + dt.timedelta(days=r.randrange(30))).isoformat()
|
| 172 |
+
for _ in range(5)
|
| 173 |
+
],
|
| 174 |
+
}
|
| 175 |
+
elif family == "calendar_month":
|
| 176 |
+
x = {"year": r.randrange(1900, 2101), "month": r.randrange(1, 13)}
|
| 177 |
+
elif family == "moving_average":
|
| 178 |
+
x = {"values": nums(), "window": r.randrange(1, 8)}
|
| 179 |
+
elif family == "statistics":
|
| 180 |
+
x = {"values": nums()}
|
| 181 |
+
elif family == "histogram":
|
| 182 |
+
x = {"values": nums(), "edges": sorted(r.sample(range(-10, 11), 5))}
|
| 183 |
+
elif family == "matrix_product":
|
| 184 |
+
m, n, p = [r.randrange(1, 5) for _ in range(3)]
|
| 185 |
+
x = {
|
| 186 |
+
"a": [[r.randrange(-4, 5) for _ in range(n)] for _ in range(m)],
|
| 187 |
+
"b": [[r.randrange(-4, 5) for _ in range(p)] for _ in range(n)],
|
| 188 |
+
}
|
| 189 |
+
elif family == "polynomial":
|
| 190 |
+
x = {"coefficients": nums(), "points": nums()}
|
| 191 |
+
elif family == "prime_factors":
|
| 192 |
+
x = {"number": r.randrange(1, 100001)}
|
| 193 |
+
elif family == "base_convert":
|
| 194 |
+
x = {
|
| 195 |
+
"digits": str(r.randrange(-(2**70), 2**70)),
|
| 196 |
+
"from_base": 10,
|
| 197 |
+
"to_base": r.randrange(2, 37),
|
| 198 |
+
}
|
| 199 |
+
elif family == "money_split":
|
| 200 |
+
x = {
|
| 201 |
+
"amount": r.randrange(10000),
|
| 202 |
+
"weights": [r.randrange(1, 20)]
|
| 203 |
+
+ [r.randrange(20) for _ in range(r.randrange(8))],
|
| 204 |
+
}
|
| 205 |
+
elif family == "invoice_total":
|
| 206 |
+
x = {
|
| 207 |
+
"items": [
|
| 208 |
+
{
|
| 209 |
+
"price": f"{r.randrange(100)}.{r.randrange(1000):03d}",
|
| 210 |
+
"quantity": r.randrange(10),
|
| 211 |
+
}
|
| 212 |
+
for _ in range(r.randrange(8))
|
| 213 |
+
],
|
| 214 |
+
"tax_rate": r.choice(["0", "0.075", "0.20"]),
|
| 215 |
+
}
|
| 216 |
+
elif family == "coin_change":
|
| 217 |
+
x = {
|
| 218 |
+
"coins": [r.randrange(1, 15) for _ in range(r.randrange(8))],
|
| 219 |
+
"amount": r.randrange(100),
|
| 220 |
+
}
|
| 221 |
+
elif family in {
|
| 222 |
+
"graph_reach",
|
| 223 |
+
"shortest_path",
|
| 224 |
+
"topological_order",
|
| 225 |
+
"connected_components",
|
| 226 |
+
}:
|
| 227 |
+
nodes = list("abcdef")[: r.randrange(1, 7)]
|
| 228 |
+
edges = [[r.choice(nodes), r.choice(nodes)] for _ in range(r.randrange(15))]
|
| 229 |
+
if family == "shortest_path":
|
| 230 |
+
edges = [edge + [r.randrange(10)] for edge in edges]
|
| 231 |
+
x = {"nodes": nodes, "edges": edges}
|
| 232 |
+
if family in {"graph_reach", "shortest_path"}:
|
| 233 |
+
x["start"] = r.choice(nodes)
|
| 234 |
+
elif family == "grid_route":
|
| 235 |
+
grid = ["".join(r.choices(".#", weights=[4, 1], k=5)) for _ in range(5)]
|
| 236 |
+
x = {
|
| 237 |
+
"grid": grid,
|
| 238 |
+
"start": [r.randrange(5), r.randrange(5)],
|
| 239 |
+
"end": [r.randrange(5), r.randrange(5)],
|
| 240 |
+
}
|
| 241 |
+
elif family == "tree_outline":
|
| 242 |
+
nodes = []
|
| 243 |
+
for key in list("abcdefgh")[: r.randrange(9)]:
|
| 244 |
+
nodes.append(
|
| 245 |
+
{"id": key, "parent": r.choice([None] + [n["id"] for n in nodes])}
|
| 246 |
+
)
|
| 247 |
+
r.shuffle(nodes)
|
| 248 |
+
x = {"nodes": nodes}
|
| 249 |
+
elif family == "dependency_build":
|
| 250 |
+
nodes = list("abcde")[: r.randrange(1, 6)]
|
| 251 |
+
x = {
|
| 252 |
+
"dependencies": {
|
| 253 |
+
n: r.sample(nodes, r.randrange(len(nodes) + 1)) for n in nodes
|
| 254 |
+
},
|
| 255 |
+
"targets": r.sample(nodes, r.randrange(len(nodes) + 1)),
|
| 256 |
+
}
|
| 257 |
+
elif family == "path_normalize":
|
| 258 |
+
x = {
|
| 259 |
+
"paths": [
|
| 260 |
+
"/".join(
|
| 261 |
+
r.choices(["a", "b", "..", ".", "", "é"], k=r.randrange(10))
|
| 262 |
+
)
|
| 263 |
+
for _ in range(r.randrange(12))
|
| 264 |
+
]
|
| 265 |
+
}
|
| 266 |
+
elif family == "url_query":
|
| 267 |
+
x = {
|
| 268 |
+
"query": "&".join(
|
| 269 |
+
r.choices(
|
| 270 |
+
["a=1", "a=2", "x=a+b", "x=%2B", "flag", "", "=v", "q=%C3%A9"],
|
| 271 |
+
k=r.randrange(12),
|
| 272 |
+
)
|
| 273 |
+
)
|
| 274 |
+
}
|
| 275 |
+
elif family == "version_sort":
|
| 276 |
+
x = {
|
| 277 |
+
"versions": [
|
| 278 |
+
f"{r.randrange(3)}.{r.randrange(12)}.{r.randrange(5)}"
|
| 279 |
+
+ r.choice(["", "-a", "-a.2", "-a.10", "-1", "-b"])
|
| 280 |
+
for _ in range(r.randrange(15))
|
| 281 |
+
]
|
| 282 |
+
}
|
| 283 |
+
elif family == "lru_trace":
|
| 284 |
+
x = {"capacity": r.randrange(6), "accesses": words()}
|
| 285 |
+
elif family == "rate_limit":
|
| 286 |
+
x = {
|
| 287 |
+
"events": [
|
| 288 |
+
{"time": t, "key": r.choice(["a", "b"])}
|
| 289 |
+
for t in sorted(r.choices(range(12), k=r.randrange(20)))
|
| 290 |
+
],
|
| 291 |
+
"window": r.randrange(1, 8),
|
| 292 |
+
"limit": r.randrange(5),
|
| 293 |
+
}
|
| 294 |
+
elif family == "priority_queue":
|
| 295 |
+
x = {
|
| 296 |
+
"events": [
|
| 297 |
+
{"op": "pop"}
|
| 298 |
+
if r.random() < 0.4
|
| 299 |
+
else {
|
| 300 |
+
"op": "push",
|
| 301 |
+
"priority": r.randrange(-2, 3),
|
| 302 |
+
"value": r.choice([None, "x", {"a": 1}, []]),
|
| 303 |
+
}
|
| 304 |
+
for _ in range(r.randrange(20))
|
| 305 |
+
]
|
| 306 |
+
}
|
| 307 |
+
elif family == "round_robin":
|
| 308 |
+
x = {
|
| 309 |
+
"jobs": [
|
| 310 |
+
{"id": str(i), "duration": r.randrange(1, 12)}
|
| 311 |
+
for i in range(r.randrange(6))
|
| 312 |
+
],
|
| 313 |
+
"quantum": r.randrange(1, 6),
|
| 314 |
+
}
|
| 315 |
+
elif family == "inventory_ledger":
|
| 316 |
+
x = {
|
| 317 |
+
"events": [
|
| 318 |
+
{"sku": r.choice(["a", "b", "c"]), "delta": r.randrange(-5, 6)}
|
| 319 |
+
for _ in range(r.randrange(20))
|
| 320 |
+
]
|
| 321 |
+
}
|
| 322 |
+
elif family == "bank_ledger":
|
| 323 |
+
x = {
|
| 324 |
+
"balances": {"a": r.randrange(20), "b": r.randrange(20)},
|
| 325 |
+
"transfers": [
|
| 326 |
+
{
|
| 327 |
+
"from": r.choice(["a", "b", "missing"]),
|
| 328 |
+
"to": r.choice(["a", "b", "missing"]),
|
| 329 |
+
"amount": r.randrange(1, 12),
|
| 330 |
+
}
|
| 331 |
+
for _ in range(r.randrange(12))
|
| 332 |
+
],
|
| 333 |
+
}
|
| 334 |
+
elif family == "ballot_count":
|
| 335 |
+
x = {
|
| 336 |
+
"candidates": ["a", "b", "c"],
|
| 337 |
+
"votes": r.choices(["a", "b", "c", "bad"], k=r.randrange(30)),
|
| 338 |
+
}
|
| 339 |
+
elif family == "search_rank":
|
| 340 |
+
x = {
|
| 341 |
+
"documents": [
|
| 342 |
+
{"id": str(i), "text": text()} for i in range(r.randrange(8))
|
| 343 |
+
],
|
| 344 |
+
"query": text(),
|
| 345 |
+
}
|
| 346 |
+
elif family == "log_summary":
|
| 347 |
+
x = {
|
| 348 |
+
"events": [
|
| 349 |
+
{
|
| 350 |
+
"level": r.choice(["ERROR", "INFO", "WARN", "error"]),
|
| 351 |
+
"message": text(),
|
| 352 |
+
}
|
| 353 |
+
for _ in range(r.randrange(12))
|
| 354 |
+
]
|
| 355 |
+
}
|
| 356 |
+
elif family == "segment_intersection":
|
| 357 |
+
x = {k: [r.randrange(-4, 5), r.randrange(-4, 5)] for k in "abcd"}
|
| 358 |
+
elif family == "polygon_area":
|
| 359 |
+
a, b, c, d = [r.randrange(1, 10) for _ in range(4)]
|
| 360 |
+
x = {"points": [[-a, -b], [c, -b], [c, d], [-a, d]]}
|
| 361 |
+
if r.random() < 0.5:
|
| 362 |
+
x["points"].reverse()
|
| 363 |
+
elif family == "skyline":
|
| 364 |
+
x = {
|
| 365 |
+
"buildings": [
|
| 366 |
+
[a, a + r.randrange(1, 8), r.randrange(1, 10)]
|
| 367 |
+
for a in [r.randrange(-5, 6) for _ in range(r.randrange(12))]
|
| 368 |
+
]
|
| 369 |
+
}
|
| 370 |
+
elif family == "knapsack":
|
| 371 |
+
x = {
|
| 372 |
+
"items": [
|
| 373 |
+
{"weight": r.randrange(1, 10), "value": r.randrange(20)}
|
| 374 |
+
for _ in range(r.randrange(10))
|
| 375 |
+
],
|
| 376 |
+
"capacity": r.randrange(25),
|
| 377 |
+
}
|
| 378 |
+
elif family == "task_selection":
|
| 379 |
+
x = {
|
| 380 |
+
"tasks": [
|
| 381 |
+
{"id": str(i), "start": a, "end": a + r.randrange(1, 8)}
|
| 382 |
+
for i, a in enumerate(
|
| 383 |
+
[r.randrange(-5, 8) for _ in range(r.randrange(12))]
|
| 384 |
+
)
|
| 385 |
+
]
|
| 386 |
+
}
|
| 387 |
+
elif family == "sequence_diff":
|
| 388 |
+
x = {"a": words(), "b": words()}
|
| 389 |
+
elif family == "finite_automaton":
|
| 390 |
+
x = {
|
| 391 |
+
"start": "a",
|
| 392 |
+
"accepting": r.sample(["a", "b"], r.randrange(3)),
|
| 393 |
+
"transitions": [
|
| 394 |
+
{"from": a, "symbol": c, "to": r.choice(["a", "b"])}
|
| 395 |
+
for a in ["a", "b"]
|
| 396 |
+
for c in "xy"
|
| 397 |
+
if r.random() < 0.8
|
| 398 |
+
],
|
| 399 |
+
"words": [
|
| 400 |
+
"".join(r.choices("xy", k=r.randrange(10)))
|
| 401 |
+
for _ in range(r.randrange(12))
|
| 402 |
+
],
|
| 403 |
+
}
|
| 404 |
+
elif family == "content_manifest":
|
| 405 |
+
x = {"files": {str(i) + "/é": text() for i in range(r.randrange(8))}}
|
| 406 |
+
elif family == "cellular_automaton":
|
| 407 |
+
x = {
|
| 408 |
+
"live": [
|
| 409 |
+
[r.randrange(-3, 4), r.randrange(-3, 4)]
|
| 410 |
+
for _ in range(r.randrange(20))
|
| 411 |
+
],
|
| 412 |
+
"steps": r.randrange(5),
|
| 413 |
+
}
|
| 414 |
+
elif family == "expression_eval":
|
| 415 |
+
x = {
|
| 416 |
+
"tokens": [
|
| 417 |
+
str(r.randrange(-100, 101)),
|
| 418 |
+
str(r.randrange(-100, 101)),
|
| 419 |
+
r.choice(["+", "-", "*"]),
|
| 420 |
+
str(r.randrange(1, 10)),
|
| 421 |
+
"/",
|
| 422 |
+
]
|
| 423 |
+
}
|
| 424 |
+
else:
|
| 425 |
+
raise ValueError(f"No generator for {family}")
|
| 426 |
+
yield x
|
klein_code_bench/protocol.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned task contracts. These contracts are included verbatim in each prompt."""
|
| 2 |
+
|
| 3 |
+
TIERS = {"easy": "2–8B", "intermediate": "8–16B", "hard": "16–32B", "max": "60–200B"}
|
| 4 |
+
PROTOCOL_VERSION = "1.0"
|
| 5 |
+
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.
|
| 6 |
+
Run: python main.py (max-tier invocation adds --state-dir DIRECTORY).
|
| 7 |
+
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.
|
| 8 |
+
Success response: {"ok":true,"result":RESULT}. Error response: {"ok":false,"error":CODE} with no extra fields.
|
| 9 |
+
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.
|
| 10 |
+
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.
|
| 11 |
+
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.
|
| 12 |
+
"""
|
| 13 |
+
STORE = """
|
| 14 |
+
Also implement an in-memory document workspace, initially empty, shared across request lines:
|
| 15 |
+
* {"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}.
|
| 16 |
+
* {"op":"get","key":K}: result {"key":K,"value":STORED_VALUE,"revision":REVISION_OF_LAST_PUT_FOR_K}. Missing key: not_found.
|
| 17 |
+
* {"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.
|
| 18 |
+
* {"op":"list","prefix":P}: result sorted list of keys starting with P; prefix optional, defaults "", must be a string.
|
| 19 |
+
* {"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.
|
| 20 |
+
* {"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.
|
| 21 |
+
"""
|
| 22 |
+
TRANSACTIONS = """
|
| 23 |
+
Also implement atomicity and nested transactions:
|
| 24 |
+
* 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.
|
| 25 |
+
* {"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.
|
| 26 |
+
* {"op":"begin"}: save complete current state, push transaction, result {"depth":NEW_DEPTH}; at most 8 open transactions, otherwise transaction_limit.
|
| 27 |
+
* {"op":"commit"}: discard most recent saved state, keep its changes; result {"depth":NEW_DEPTH}.
|
| 28 |
+
* {"op":"rollback"}: restore most recent saved state including global and document revisions; result {"depth":NEW_DEPTH}.
|
| 29 |
+
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.
|
| 30 |
+
"""
|
| 31 |
+
DURABILITY = """
|
| 32 |
+
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.
|
| 33 |
+
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.
|
| 34 |
+
* {"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.
|
| 35 |
+
* {"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}.
|
| 36 |
+
* 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.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def contract(tier):
|
| 41 |
+
index = list(TIERS).index(tier)
|
| 42 |
+
return (
|
| 43 |
+
BASE
|
| 44 |
+
+ (STORE if index >= 1 else "")
|
| 45 |
+
+ (TRANSACTIONS if index >= 2 else "")
|
| 46 |
+
+ (DURABILITY if index >= 3 else "")
|
| 47 |
+
)
|
klein_code_bench/reference/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Evaluator-side reference implementations. Never expose to a model run."""
|
klein_code_bench/reference/domains.py
ADDED
|
@@ -0,0 +1,869 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""65 independent domain algorithms used by the evaluator's reference projects."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import calendar
|
| 6 |
+
import collections
|
| 7 |
+
import csv
|
| 8 |
+
import datetime as dt
|
| 9 |
+
import decimal
|
| 10 |
+
import fnmatch
|
| 11 |
+
import hashlib
|
| 12 |
+
import heapq
|
| 13 |
+
import io
|
| 14 |
+
import itertools
|
| 15 |
+
import json
|
| 16 |
+
import math
|
| 17 |
+
import re
|
| 18 |
+
import statistics
|
| 19 |
+
import urllib.parse
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def solve(name: str, x: dict):
|
| 23 |
+
return globals()["solve_" + name](x)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def solve_word_frequency(x):
|
| 27 |
+
words = re.findall(r"[a-z0-9]+", x["text"].lower())
|
| 28 |
+
counts = collections.Counter(words)
|
| 29 |
+
return [
|
| 30 |
+
{"word": w, "count": n}
|
| 31 |
+
for w, n in sorted(counts.items(), key=lambda p: (-p[1], p[0]))
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def solve_slug_registry(x):
|
| 36 |
+
used, out = set(), []
|
| 37 |
+
for title in x["titles"]:
|
| 38 |
+
root = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") or "item"
|
| 39 |
+
slug, i = root, 2
|
| 40 |
+
while slug in used:
|
| 41 |
+
slug, i = f"{root}-{i}", i + 1
|
| 42 |
+
used.add(slug)
|
| 43 |
+
out.append(slug)
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def solve_run_length(x):
|
| 48 |
+
return [[char, len(list(group))] for char, group in itertools.groupby(x["text"])]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def solve_bracket_audit(x):
|
| 52 |
+
stack = []
|
| 53 |
+
for i, c in enumerate(x["text"]):
|
| 54 |
+
if c in "([{":
|
| 55 |
+
stack.append((c, i))
|
| 56 |
+
elif c in ")]}":
|
| 57 |
+
if not stack or "([{".index(stack[-1][0]) != ")]}".index(c):
|
| 58 |
+
return {"balanced": False, "position": i}
|
| 59 |
+
stack.pop()
|
| 60 |
+
return {"balanced": not stack, "position": stack[-1][1] if stack else None}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def solve_text_wrap(x):
|
| 64 |
+
lines, line = [], ""
|
| 65 |
+
for word in x["text"].split():
|
| 66 |
+
if line and len(line) + 1 + len(word) > x["width"]:
|
| 67 |
+
lines.append(line)
|
| 68 |
+
line = ""
|
| 69 |
+
line = line + " " + word if line else word
|
| 70 |
+
if line:
|
| 71 |
+
lines.append(line)
|
| 72 |
+
return lines
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def solve_ngram_index(x):
|
| 76 |
+
tokens, n = x["tokens"], x["n"]
|
| 77 |
+
found = collections.defaultdict(list)
|
| 78 |
+
for i in range(len(tokens) - n + 1):
|
| 79 |
+
found[tuple(tokens[i : i + n])].append(i)
|
| 80 |
+
return [{"tokens": list(k), "positions": found[k]} for k in sorted(found)]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def solve_glob_filter(x):
|
| 84 |
+
return sorted({p for p in x["paths"] if fnmatch.fnmatchcase(p, x["pattern"])})
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def solve_edit_distance(x):
|
| 88 |
+
a, b = x["a"], x["b"]
|
| 89 |
+
row = list(range(len(b) + 1))
|
| 90 |
+
for i, char in enumerate(a, 1):
|
| 91 |
+
nxt = [i]
|
| 92 |
+
for j, other in enumerate(b, 1):
|
| 93 |
+
nxt.append(min(nxt[-1] + 1, row[j] + 1, row[j - 1] + (char != other)))
|
| 94 |
+
row = nxt
|
| 95 |
+
return row[-1]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def solve_roman_codec(x):
|
| 99 |
+
n, out = x["number"], ""
|
| 100 |
+
for value, symbol in [
|
| 101 |
+
(1000, "M"),
|
| 102 |
+
(900, "CM"),
|
| 103 |
+
(500, "D"),
|
| 104 |
+
(400, "CD"),
|
| 105 |
+
(100, "C"),
|
| 106 |
+
(90, "XC"),
|
| 107 |
+
(50, "L"),
|
| 108 |
+
(40, "XL"),
|
| 109 |
+
(10, "X"),
|
| 110 |
+
(9, "IX"),
|
| 111 |
+
(5, "V"),
|
| 112 |
+
(4, "IV"),
|
| 113 |
+
(1, "I"),
|
| 114 |
+
]:
|
| 115 |
+
q, n = divmod(n, value)
|
| 116 |
+
out += symbol * q
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def solve_caesar_cipher(x):
|
| 121 |
+
out = ""
|
| 122 |
+
for c in x["text"]:
|
| 123 |
+
base = ord("a") if "a" <= c <= "z" else ord("A") if "A" <= c <= "Z" else None
|
| 124 |
+
out += chr((ord(c) - base + x["shift"]) % 26 + base) if base is not None else c
|
| 125 |
+
return out
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def solve_csv_records(x):
|
| 129 |
+
rows = list(csv.reader(io.StringIO(x["csv"])))
|
| 130 |
+
return [dict(zip(rows[0], row)) for row in rows[1:]] if rows else []
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def solve_record_query(x):
|
| 134 |
+
rows = [
|
| 135 |
+
r for r in x["rows"] if all(k in r and r[k] == v for k, v in x["where"].items())
|
| 136 |
+
]
|
| 137 |
+
return [{k: r.get(k) for k in x["select"]} for r in rows]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def solve_inner_join(x):
|
| 141 |
+
return [
|
| 142 |
+
{"left": a, "right": b}
|
| 143 |
+
for a in x["left"]
|
| 144 |
+
for b in x["right"]
|
| 145 |
+
if x["key"] in a and x["key"] in b and a[x["key"]] == b[x["key"]]
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def solve_group_totals(x):
|
| 150 |
+
groups = collections.defaultdict(list)
|
| 151 |
+
for row in x["rows"]:
|
| 152 |
+
groups[row[x["group"]]].append(row[x["value"]])
|
| 153 |
+
return [
|
| 154 |
+
{"key": k, "count": len(groups[k]), "sum": sum(groups[k])}
|
| 155 |
+
for k in sorted(groups)
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def solve_json_flatten(x):
|
| 160 |
+
out = {}
|
| 161 |
+
|
| 162 |
+
def walk(value, path):
|
| 163 |
+
if isinstance(value, dict) and value:
|
| 164 |
+
for k in sorted(value):
|
| 165 |
+
walk(value[k], path + "/" + k.replace("~", "~0").replace("/", "~1"))
|
| 166 |
+
elif isinstance(value, list) and value:
|
| 167 |
+
for i, child in enumerate(value):
|
| 168 |
+
walk(child, path + "/" + str(i))
|
| 169 |
+
else:
|
| 170 |
+
out[path] = value
|
| 171 |
+
|
| 172 |
+
walk(x["value"], "")
|
| 173 |
+
return out
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def solve_merge_patch(x):
|
| 177 |
+
def merge(target, patch):
|
| 178 |
+
if not isinstance(patch, dict):
|
| 179 |
+
return patch
|
| 180 |
+
out = dict(target) if isinstance(target, dict) else {}
|
| 181 |
+
for k, v in patch.items():
|
| 182 |
+
if v is None:
|
| 183 |
+
out.pop(k, None)
|
| 184 |
+
else:
|
| 185 |
+
out[k] = merge(out.get(k), v)
|
| 186 |
+
return out
|
| 187 |
+
|
| 188 |
+
return merge(x["target"], x["patch"])
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def solve_json_pointer(x):
|
| 192 |
+
value = x["value"]
|
| 193 |
+
if x["pointer"] == "":
|
| 194 |
+
return {"found": True, "value": value}
|
| 195 |
+
try:
|
| 196 |
+
for token in x["pointer"][1:].split("/"):
|
| 197 |
+
token = token.replace("~1", "/").replace("~0", "~")
|
| 198 |
+
if isinstance(value, list):
|
| 199 |
+
if not re.fullmatch(r"0|[1-9][0-9]*", token):
|
| 200 |
+
raise KeyError(token)
|
| 201 |
+
value = value[int(token)]
|
| 202 |
+
elif isinstance(value, dict):
|
| 203 |
+
value = value[token]
|
| 204 |
+
else:
|
| 205 |
+
raise KeyError(token)
|
| 206 |
+
return {"found": True, "value": value}
|
| 207 |
+
except (KeyError, IndexError):
|
| 208 |
+
return {"found": False, "value": None}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def solve_dedupe_records(x):
|
| 212 |
+
seen, out = set(), []
|
| 213 |
+
for row in x["rows"]:
|
| 214 |
+
key = json.dumps(
|
| 215 |
+
[row.get(k) for k in x["keys"]], sort_keys=True, separators=(",", ":")
|
| 216 |
+
)
|
| 217 |
+
if key not in seen:
|
| 218 |
+
out.append(row)
|
| 219 |
+
seen.add(key)
|
| 220 |
+
return out
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def solve_pivot_table(x):
|
| 224 |
+
cells = collections.defaultdict(int)
|
| 225 |
+
rows, cols = set(), set()
|
| 226 |
+
for item in x["rows"]:
|
| 227 |
+
r, c = item[x["row"]], item[x["column"]]
|
| 228 |
+
rows.add(r)
|
| 229 |
+
cols.add(c)
|
| 230 |
+
cells[r, c] += item[x["value"]]
|
| 231 |
+
rows, cols = sorted(rows), sorted(cols)
|
| 232 |
+
return {
|
| 233 |
+
"rows": rows,
|
| 234 |
+
"columns": cols,
|
| 235 |
+
"values": [[cells[r, c] for c in cols] for r in rows],
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def solve_schema_check(x):
|
| 240 |
+
types = {
|
| 241 |
+
"string": lambda v: isinstance(v, str),
|
| 242 |
+
"integer": lambda v: type(v) is int,
|
| 243 |
+
"number": lambda v: type(v) in (int, float),
|
| 244 |
+
"boolean": lambda v: type(v) is bool,
|
| 245 |
+
"array": lambda v: isinstance(v, list),
|
| 246 |
+
"object": lambda v: isinstance(v, dict),
|
| 247 |
+
"null": lambda v: v is None,
|
| 248 |
+
}
|
| 249 |
+
errors = []
|
| 250 |
+
for key in sorted(x["schema"]):
|
| 251 |
+
rule = x["schema"][key]
|
| 252 |
+
if key not in x["value"]:
|
| 253 |
+
if rule["required"]:
|
| 254 |
+
errors.append({"field": key, "error": "required"})
|
| 255 |
+
elif not types[rule["type"]](x["value"][key]):
|
| 256 |
+
errors.append({"field": key, "error": "type"})
|
| 257 |
+
return errors
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def solve_interval_union(x):
|
| 261 |
+
out = []
|
| 262 |
+
for start, end in sorted(x["intervals"]):
|
| 263 |
+
if out and start <= out[-1][1]:
|
| 264 |
+
out[-1][1] = max(end, out[-1][1])
|
| 265 |
+
else:
|
| 266 |
+
out.append([start, end])
|
| 267 |
+
return out
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def solve_interval_gaps(x):
|
| 271 |
+
low, high = x["bounds"]
|
| 272 |
+
out, cursor = [], low
|
| 273 |
+
for a, b in solve_interval_union(x):
|
| 274 |
+
a, b = max(low, a), min(high, b)
|
| 275 |
+
if a > b:
|
| 276 |
+
continue
|
| 277 |
+
if a > cursor:
|
| 278 |
+
out.append([cursor, a])
|
| 279 |
+
cursor = max(cursor, b)
|
| 280 |
+
if cursor < high:
|
| 281 |
+
out.append([cursor, high])
|
| 282 |
+
return out
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def solve_booking_peak(x):
|
| 286 |
+
events = collections.defaultdict(int)
|
| 287 |
+
for start, end in x["bookings"]:
|
| 288 |
+
if start < end:
|
| 289 |
+
events[start] += 1
|
| 290 |
+
events[end] -= 1
|
| 291 |
+
current = peak = 0
|
| 292 |
+
at = None
|
| 293 |
+
for t, delta in sorted(events.items()):
|
| 294 |
+
current += delta
|
| 295 |
+
if current > peak:
|
| 296 |
+
peak, at = current, t
|
| 297 |
+
return {"peak": peak, "at": at}
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def solve_business_days(x):
|
| 301 |
+
day, end = dt.date.fromisoformat(x["start"]), dt.date.fromisoformat(x["end"])
|
| 302 |
+
holidays, out = set(x["holidays"]), []
|
| 303 |
+
while day < end:
|
| 304 |
+
if day.weekday() < 5 and day.isoformat() not in holidays:
|
| 305 |
+
out.append(day.isoformat())
|
| 306 |
+
day += dt.timedelta(days=1)
|
| 307 |
+
return out
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def solve_calendar_month(x):
|
| 311 |
+
return calendar.Calendar(firstweekday=0).monthdayscalendar(x["year"], x["month"])
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def solve_moving_average(x):
|
| 315 |
+
return [
|
| 316 |
+
sum(x["values"][i : i + x["window"]]) / x["window"]
|
| 317 |
+
for i in range(len(x["values"]) - x["window"] + 1)
|
| 318 |
+
]
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def solve_statistics(x):
|
| 322 |
+
values = x["values"]
|
| 323 |
+
if not values:
|
| 324 |
+
return {
|
| 325 |
+
"count": 0,
|
| 326 |
+
"min": None,
|
| 327 |
+
"max": None,
|
| 328 |
+
"mean": None,
|
| 329 |
+
"median": None,
|
| 330 |
+
"variance": None,
|
| 331 |
+
}
|
| 332 |
+
return {
|
| 333 |
+
"count": len(values),
|
| 334 |
+
"min": min(values),
|
| 335 |
+
"max": max(values),
|
| 336 |
+
"mean": statistics.mean(values),
|
| 337 |
+
"median": statistics.median(values),
|
| 338 |
+
"variance": statistics.pvariance(values),
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def solve_histogram(x):
|
| 343 |
+
edges = x["edges"]
|
| 344 |
+
bins, under, over = [0] * (len(edges) - 1), 0, 0
|
| 345 |
+
for v in x["values"]:
|
| 346 |
+
if v < edges[0]:
|
| 347 |
+
under += 1
|
| 348 |
+
elif v >= edges[-1]:
|
| 349 |
+
over += 1
|
| 350 |
+
else:
|
| 351 |
+
for i in range(len(bins)):
|
| 352 |
+
if edges[i] <= v < edges[i + 1]:
|
| 353 |
+
bins[i] += 1
|
| 354 |
+
break
|
| 355 |
+
return {"counts": bins, "underflow": under, "overflow": over}
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def solve_matrix_product(x):
|
| 359 |
+
return [
|
| 360 |
+
[sum(a * b for a, b in zip(row, col)) for col in zip(*x["b"])] for row in x["a"]
|
| 361 |
+
]
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def solve_polynomial(x):
|
| 365 |
+
return [
|
| 366 |
+
sum(c * value**i for i, c in enumerate(x["coefficients"]))
|
| 367 |
+
for value in x["points"]
|
| 368 |
+
]
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def solve_prime_factors(x):
|
| 372 |
+
n, out, factor = x["number"], [], 2
|
| 373 |
+
while factor * factor <= n:
|
| 374 |
+
count = 0
|
| 375 |
+
while n % factor == 0:
|
| 376 |
+
n //= factor
|
| 377 |
+
count += 1
|
| 378 |
+
if count:
|
| 379 |
+
out.append([factor, count])
|
| 380 |
+
factor += 1
|
| 381 |
+
if n > 1:
|
| 382 |
+
out.append([n, 1])
|
| 383 |
+
return out
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def solve_base_convert(x):
|
| 387 |
+
chars = "0123456789abcdefghijklmnopqrstuvwxyz"
|
| 388 |
+
n = int(x["digits"], x["from_base"])
|
| 389 |
+
sign, n = ("-" if n < 0 else ""), abs(n)
|
| 390 |
+
out = ""
|
| 391 |
+
while n:
|
| 392 |
+
n, rem = divmod(n, x["to_base"])
|
| 393 |
+
out = chars[rem] + out
|
| 394 |
+
return sign + (out or "0")
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def solve_money_split(x):
|
| 398 |
+
weights, amount = x["weights"], x["amount"]
|
| 399 |
+
total = sum(weights)
|
| 400 |
+
shares = [amount * w // total for w in weights]
|
| 401 |
+
order = sorted(
|
| 402 |
+
range(len(weights)), key=lambda i: (-(amount * weights[i] % total), i)
|
| 403 |
+
)
|
| 404 |
+
for i in order[: amount - sum(shares)]:
|
| 405 |
+
shares[i] += 1
|
| 406 |
+
return shares
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def solve_invoice_total(x):
|
| 410 |
+
D = decimal.Decimal
|
| 411 |
+
subtotal = sum(
|
| 412 |
+
(D(item["price"]) * item["quantity"] for item in x["items"]), D(0)
|
| 413 |
+
).quantize(D(".01"), rounding=decimal.ROUND_HALF_UP)
|
| 414 |
+
tax = (subtotal * D(x["tax_rate"])).quantize(
|
| 415 |
+
D(".01"), rounding=decimal.ROUND_HALF_UP
|
| 416 |
+
)
|
| 417 |
+
return {
|
| 418 |
+
"subtotal": f"{subtotal:.2f}",
|
| 419 |
+
"tax": f"{tax:.2f}",
|
| 420 |
+
"total": f"{subtotal + tax:.2f}",
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def solve_coin_change(x):
|
| 425 |
+
amount, coins = x["amount"], sorted(set(x["coins"]))
|
| 426 |
+
dp = [0] + [amount + 1] * amount
|
| 427 |
+
for n in range(1, amount + 1):
|
| 428 |
+
dp[n] = min([dp[n - c] + 1 for c in coins if c <= n] or [amount + 1])
|
| 429 |
+
return None if dp[amount] > amount else dp[amount]
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def graph(x, weighted=False, directed=True):
|
| 433 |
+
adj = {node: [] for node in x["nodes"]}
|
| 434 |
+
for edge in x["edges"]:
|
| 435 |
+
a, b = edge[:2]
|
| 436 |
+
adj[a].append((b, edge[2]) if weighted else b)
|
| 437 |
+
if not directed:
|
| 438 |
+
adj[b].append((a, edge[2]) if weighted else a)
|
| 439 |
+
return adj
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def solve_graph_reach(x):
|
| 443 |
+
adj, found = graph(x), {x["start"]}
|
| 444 |
+
todo = [x["start"]]
|
| 445 |
+
while todo:
|
| 446 |
+
for node in adj[todo.pop()]:
|
| 447 |
+
if node not in found:
|
| 448 |
+
found.add(node)
|
| 449 |
+
todo.append(node)
|
| 450 |
+
return sorted(found)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def solve_shortest_path(x):
|
| 454 |
+
adj = graph(x, weighted=True)
|
| 455 |
+
distances = {x["start"]: 0}
|
| 456 |
+
queue = [(0, x["start"])]
|
| 457 |
+
while queue:
|
| 458 |
+
distance, node = heapq.heappop(queue)
|
| 459 |
+
if distances[node] != distance:
|
| 460 |
+
continue
|
| 461 |
+
for other, weight in adj[node]:
|
| 462 |
+
alt = distance + weight
|
| 463 |
+
if alt < distances.get(other, math.inf):
|
| 464 |
+
distances[other] = alt
|
| 465 |
+
heapq.heappush(queue, (alt, other))
|
| 466 |
+
return {node: distances.get(node) for node in sorted(x["nodes"])}
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def solve_topological_order(x):
|
| 470 |
+
adj, indegree = graph(x), dict.fromkeys(x["nodes"], 0)
|
| 471 |
+
for edges in adj.values():
|
| 472 |
+
for node in edges:
|
| 473 |
+
indegree[node] += 1
|
| 474 |
+
queue = [n for n in indegree if indegree[n] == 0]
|
| 475 |
+
heapq.heapify(queue)
|
| 476 |
+
out = []
|
| 477 |
+
while queue:
|
| 478 |
+
node = heapq.heappop(queue)
|
| 479 |
+
out.append(node)
|
| 480 |
+
for other in adj[node]:
|
| 481 |
+
indegree[other] -= 1
|
| 482 |
+
if indegree[other] == 0:
|
| 483 |
+
heapq.heappush(queue, other)
|
| 484 |
+
return out if len(out) == len(adj) else None
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def solve_connected_components(x):
|
| 488 |
+
adj, seen, out = graph(x, directed=False), set(), []
|
| 489 |
+
for node in sorted(adj):
|
| 490 |
+
if node in seen:
|
| 491 |
+
continue
|
| 492 |
+
group, todo = [], [node]
|
| 493 |
+
seen.add(node)
|
| 494 |
+
while todo:
|
| 495 |
+
n = todo.pop()
|
| 496 |
+
group.append(n)
|
| 497 |
+
for other in adj[n]:
|
| 498 |
+
if other not in seen:
|
| 499 |
+
seen.add(other)
|
| 500 |
+
todo.append(other)
|
| 501 |
+
out.append(sorted(group))
|
| 502 |
+
return out
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def solve_grid_route(x):
|
| 506 |
+
grid, start, end = x["grid"], tuple(x["start"]), tuple(x["end"])
|
| 507 |
+
seen, queue = {start}, collections.deque([(start, 0)])
|
| 508 |
+
if grid[start[0]][start[1]] == "#" or grid[end[0]][end[1]] == "#":
|
| 509 |
+
return None
|
| 510 |
+
while queue:
|
| 511 |
+
(r, c), distance = queue.popleft()
|
| 512 |
+
if (r, c) == end:
|
| 513 |
+
return distance
|
| 514 |
+
for nr, nc in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
|
| 515 |
+
if (
|
| 516 |
+
0 <= nr < len(grid)
|
| 517 |
+
and 0 <= nc < len(grid[0])
|
| 518 |
+
and grid[nr][nc] != "#"
|
| 519 |
+
and (nr, nc) not in seen
|
| 520 |
+
):
|
| 521 |
+
seen.add((nr, nc))
|
| 522 |
+
queue.append(((nr, nc), distance + 1))
|
| 523 |
+
return None
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def solve_tree_outline(x):
|
| 527 |
+
children = collections.defaultdict(list)
|
| 528 |
+
for node in x["nodes"]:
|
| 529 |
+
children[node["parent"]].append(node["id"])
|
| 530 |
+
out = []
|
| 531 |
+
|
| 532 |
+
def walk(parent, depth):
|
| 533 |
+
for node in sorted(children[parent]):
|
| 534 |
+
out.append({"id": node, "depth": depth})
|
| 535 |
+
walk(node, depth + 1)
|
| 536 |
+
|
| 537 |
+
walk(None, 0)
|
| 538 |
+
return out
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def solve_dependency_build(x):
|
| 542 |
+
deps, out, active, done = x["dependencies"], [], set(), set()
|
| 543 |
+
|
| 544 |
+
def visit(node):
|
| 545 |
+
if node in active:
|
| 546 |
+
raise ValueError("cycle")
|
| 547 |
+
if node in done:
|
| 548 |
+
return
|
| 549 |
+
active.add(node)
|
| 550 |
+
for other in sorted(deps[node]):
|
| 551 |
+
visit(other)
|
| 552 |
+
active.remove(node)
|
| 553 |
+
done.add(node)
|
| 554 |
+
out.append(node)
|
| 555 |
+
|
| 556 |
+
try:
|
| 557 |
+
for target in sorted(set(x["targets"])):
|
| 558 |
+
visit(target)
|
| 559 |
+
except ValueError:
|
| 560 |
+
return None
|
| 561 |
+
return out
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def solve_path_normalize(x):
|
| 565 |
+
out = []
|
| 566 |
+
for path in x["paths"]:
|
| 567 |
+
parts = []
|
| 568 |
+
for part in path.split("/"):
|
| 569 |
+
if part in ("", "."):
|
| 570 |
+
continue
|
| 571 |
+
if part == "..":
|
| 572 |
+
if parts:
|
| 573 |
+
parts.pop()
|
| 574 |
+
else:
|
| 575 |
+
parts.append(part)
|
| 576 |
+
out.append("/" + "/".join(parts))
|
| 577 |
+
return out
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def solve_url_query(x):
|
| 581 |
+
out = collections.defaultdict(list)
|
| 582 |
+
for k, v in urllib.parse.parse_qsl(x["query"], keep_blank_values=True):
|
| 583 |
+
out[k].append(v)
|
| 584 |
+
return dict(out)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def solve_version_sort(x):
|
| 588 |
+
def key(v):
|
| 589 |
+
core, _, pre = v.partition("-")
|
| 590 |
+
parts = tuple(map(int, core.split(".")))
|
| 591 |
+
ids = (
|
| 592 |
+
tuple((0, int(p)) if p.isdigit() else (1, p) for p in pre.split("."))
|
| 593 |
+
if pre
|
| 594 |
+
else ()
|
| 595 |
+
)
|
| 596 |
+
return parts, not bool(pre), ids
|
| 597 |
+
|
| 598 |
+
return sorted(x["versions"], key=key)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def solve_lru_trace(x):
|
| 602 |
+
cache, hits, misses = collections.OrderedDict(), 0, 0
|
| 603 |
+
for key in x["accesses"]:
|
| 604 |
+
if key in cache:
|
| 605 |
+
hits += 1
|
| 606 |
+
cache.move_to_end(key)
|
| 607 |
+
else:
|
| 608 |
+
misses += 1
|
| 609 |
+
if x["capacity"]:
|
| 610 |
+
cache[key] = True
|
| 611 |
+
if len(cache) > x["capacity"]:
|
| 612 |
+
cache.popitem(last=False)
|
| 613 |
+
return {"hits": hits, "misses": misses, "keys": list(cache)}
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def solve_rate_limit(x):
|
| 617 |
+
history, out = collections.defaultdict(collections.deque), []
|
| 618 |
+
for event in x["events"]:
|
| 619 |
+
times = history[event["key"]]
|
| 620 |
+
while times and times[0] <= event["time"] - x["window"]:
|
| 621 |
+
times.popleft()
|
| 622 |
+
allowed = len(times) < x["limit"]
|
| 623 |
+
if allowed:
|
| 624 |
+
times.append(event["time"])
|
| 625 |
+
out.append(allowed)
|
| 626 |
+
return out
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def solve_priority_queue(x):
|
| 630 |
+
queue, out, seq = [], [], 0
|
| 631 |
+
for event in x["events"]:
|
| 632 |
+
if event["op"] == "push":
|
| 633 |
+
heapq.heappush(queue, (event["priority"], seq, event["value"]))
|
| 634 |
+
seq += 1
|
| 635 |
+
else:
|
| 636 |
+
out.append(heapq.heappop(queue)[2] if queue else None)
|
| 637 |
+
return {"popped": out, "remaining": [v for _, _, v in sorted(queue)]}
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def solve_round_robin(x):
|
| 641 |
+
quantum = x["quantum"]
|
| 642 |
+
queue = collections.deque((job["id"], job["duration"]) for job in x["jobs"])
|
| 643 |
+
clock, slices, completion = 0, [], {}
|
| 644 |
+
while queue:
|
| 645 |
+
key, left = queue.popleft()
|
| 646 |
+
used = min(quantum, left)
|
| 647 |
+
slices.append({"id": key, "start": clock, "end": clock + used})
|
| 648 |
+
clock += used
|
| 649 |
+
if left > used:
|
| 650 |
+
queue.append((key, left - used))
|
| 651 |
+
else:
|
| 652 |
+
completion[key] = clock
|
| 653 |
+
return {"slices": slices, "completion": completion}
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def solve_inventory_ledger(x):
|
| 657 |
+
stock, rejected = {}, []
|
| 658 |
+
for i, event in enumerate(x["events"]):
|
| 659 |
+
new = stock.get(event["sku"], 0) + event["delta"]
|
| 660 |
+
if new < 0:
|
| 661 |
+
rejected.append(i)
|
| 662 |
+
else:
|
| 663 |
+
stock[event["sku"]] = new
|
| 664 |
+
return {"stock": stock, "rejected": rejected}
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def solve_bank_ledger(x):
|
| 668 |
+
balances, rejected = dict(x["balances"]), []
|
| 669 |
+
for i, t in enumerate(x["transfers"]):
|
| 670 |
+
if (
|
| 671 |
+
t["from"] not in balances
|
| 672 |
+
or t["to"] not in balances
|
| 673 |
+
or balances[t["from"]] < t["amount"]
|
| 674 |
+
):
|
| 675 |
+
rejected.append(i)
|
| 676 |
+
else:
|
| 677 |
+
balances[t["from"]] -= t["amount"]
|
| 678 |
+
balances[t["to"]] += t["amount"]
|
| 679 |
+
return {"balances": balances, "rejected": rejected}
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def solve_ballot_count(x):
|
| 683 |
+
counts = dict.fromkeys(x["candidates"], 0)
|
| 684 |
+
invalid = 0
|
| 685 |
+
for vote in x["votes"]:
|
| 686 |
+
if vote in counts:
|
| 687 |
+
counts[vote] += 1
|
| 688 |
+
else:
|
| 689 |
+
invalid += 1
|
| 690 |
+
return {
|
| 691 |
+
"ranking": [
|
| 692 |
+
{"candidate": c, "votes": n}
|
| 693 |
+
for c, n in sorted(counts.items(), key=lambda p: (-p[1], p[0]))
|
| 694 |
+
],
|
| 695 |
+
"invalid": invalid,
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def solve_search_rank(x):
|
| 700 |
+
terms = set(re.findall(r"[a-z0-9]+", x["query"].lower()))
|
| 701 |
+
scored = []
|
| 702 |
+
for doc in x["documents"]:
|
| 703 |
+
counts = collections.Counter(re.findall(r"[a-z0-9]+", doc["text"].lower()))
|
| 704 |
+
score = sum(counts[t] for t in terms)
|
| 705 |
+
if score:
|
| 706 |
+
scored.append({"id": doc["id"], "score": score})
|
| 707 |
+
return sorted(scored, key=lambda r: (-r["score"], r["id"]))
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def solve_log_summary(x):
|
| 711 |
+
counts = collections.Counter(event["level"] for event in x["events"])
|
| 712 |
+
errors = [e["message"] for e in x["events"] if e["level"] == "ERROR"]
|
| 713 |
+
return {"counts": dict(counts), "errors": errors}
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def solve_uptime_report(x):
|
| 717 |
+
intervals = solve_interval_union(
|
| 718 |
+
{
|
| 719 |
+
"intervals": [
|
| 720 |
+
[max(a, x["start"]), min(b, x["end"])]
|
| 721 |
+
for a, b in x["downtime"]
|
| 722 |
+
if max(a, x["start"]) < min(b, x["end"])
|
| 723 |
+
]
|
| 724 |
+
}
|
| 725 |
+
)
|
| 726 |
+
down = sum(b - a for a, b in intervals)
|
| 727 |
+
return {"down": down, "up": x["end"] - x["start"] - down}
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def solve_segment_intersection(x):
|
| 731 |
+
a, b, c, d = x["a"], x["b"], x["c"], x["d"]
|
| 732 |
+
|
| 733 |
+
def cross(p, q, r):
|
| 734 |
+
return (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
|
| 735 |
+
|
| 736 |
+
def on(p, q, r):
|
| 737 |
+
return (
|
| 738 |
+
cross(p, q, r) == 0
|
| 739 |
+
and min(p[0], q[0]) <= r[0] <= max(p[0], q[0])
|
| 740 |
+
and min(p[1], q[1]) <= r[1] <= max(p[1], q[1])
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
u, v, w, z = cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b)
|
| 744 |
+
return (
|
| 745 |
+
(u * v < 0 and w * z < 0)
|
| 746 |
+
or on(a, b, c)
|
| 747 |
+
or on(a, b, d)
|
| 748 |
+
or on(c, d, a)
|
| 749 |
+
or on(c, d, b)
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def solve_polygon_area(x):
|
| 754 |
+
pts = x["points"]
|
| 755 |
+
return (
|
| 756 |
+
abs(sum(a[0] * b[1] - a[1] * b[0] for a, b in zip(pts, pts[1:] + pts[:1]))) / 2
|
| 757 |
+
if pts
|
| 758 |
+
else 0
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def solve_skyline(x):
|
| 763 |
+
buildings = x["buildings"]
|
| 764 |
+
points, prev = [], 0
|
| 765 |
+
for t in sorted({v for a, b, _ in buildings for v in (a, b)}):
|
| 766 |
+
height = max([h for a, b, h in buildings if a <= t < b] or [0])
|
| 767 |
+
if height != prev:
|
| 768 |
+
points.append([t, height])
|
| 769 |
+
prev = height
|
| 770 |
+
return points
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def solve_knapsack(x):
|
| 774 |
+
capacity = x["capacity"]
|
| 775 |
+
dp = [0] * (capacity + 1)
|
| 776 |
+
for item in x["items"]:
|
| 777 |
+
for w in range(capacity, item["weight"] - 1, -1):
|
| 778 |
+
dp[w] = max(dp[w], dp[w - item["weight"]] + item["value"])
|
| 779 |
+
return dp[capacity]
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def solve_task_selection(x):
|
| 783 |
+
end, out = None, []
|
| 784 |
+
for job in sorted(x["tasks"], key=lambda j: (j["end"], j["start"], j["id"])):
|
| 785 |
+
if end is None or job["start"] >= end:
|
| 786 |
+
out.append(job["id"])
|
| 787 |
+
end = job["end"]
|
| 788 |
+
return out
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def solve_sequence_diff(x):
|
| 792 |
+
a, b = x["a"], x["b"]
|
| 793 |
+
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
|
| 794 |
+
for i in range(len(a) - 1, -1, -1):
|
| 795 |
+
for j in range(len(b) - 1, -1, -1):
|
| 796 |
+
dp[i][j] = (
|
| 797 |
+
1 + dp[i + 1][j + 1]
|
| 798 |
+
if a[i] == b[j]
|
| 799 |
+
else max(dp[i + 1][j], dp[i][j + 1])
|
| 800 |
+
)
|
| 801 |
+
i = j = 0
|
| 802 |
+
out = []
|
| 803 |
+
while i < len(a) or j < len(b):
|
| 804 |
+
if i < len(a) and j < len(b) and a[i] == b[j]:
|
| 805 |
+
out.append(["keep", a[i]])
|
| 806 |
+
i, j = i + 1, j + 1
|
| 807 |
+
elif i < len(a) and (j == len(b) or dp[i + 1][j] >= dp[i][j + 1]):
|
| 808 |
+
out.append(["delete", a[i]])
|
| 809 |
+
i += 1
|
| 810 |
+
else:
|
| 811 |
+
out.append(["insert", b[j]])
|
| 812 |
+
j += 1
|
| 813 |
+
return out
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
def solve_finite_automaton(x):
|
| 817 |
+
transitions = {(t["from"], t["symbol"]): t["to"] for t in x["transitions"]}
|
| 818 |
+
out = []
|
| 819 |
+
for word in x["words"]:
|
| 820 |
+
state = x["start"]
|
| 821 |
+
for symbol in word:
|
| 822 |
+
state = transitions.get((state, symbol))
|
| 823 |
+
if state is None:
|
| 824 |
+
break
|
| 825 |
+
out.append(state in x["accepting"])
|
| 826 |
+
return out
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def solve_content_manifest(x):
|
| 830 |
+
return [
|
| 831 |
+
{
|
| 832 |
+
"path": path,
|
| 833 |
+
"bytes": len(text.encode("utf-8")),
|
| 834 |
+
"sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
|
| 835 |
+
}
|
| 836 |
+
for path, text in sorted(x["files"].items())
|
| 837 |
+
]
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def solve_cellular_automaton(x):
|
| 841 |
+
cells = {tuple(p) for p in x["live"]}
|
| 842 |
+
for _ in range(x["steps"]):
|
| 843 |
+
neighbors = collections.Counter(
|
| 844 |
+
(r + dr, c + dc)
|
| 845 |
+
for r, c in cells
|
| 846 |
+
for dr in (-1, 0, 1)
|
| 847 |
+
for dc in (-1, 0, 1)
|
| 848 |
+
if (dr, dc) != (0, 0)
|
| 849 |
+
)
|
| 850 |
+
cells = {p for p, n in neighbors.items() if n == 3 or n == 2 and p in cells}
|
| 851 |
+
return [list(p) for p in sorted(cells)]
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
def solve_expression_eval(x):
|
| 855 |
+
stack = []
|
| 856 |
+
for token in x["tokens"]:
|
| 857 |
+
if token not in ("+", "-", "*", "/"):
|
| 858 |
+
stack.append(int(token))
|
| 859 |
+
else:
|
| 860 |
+
b, a = stack.pop(), stack.pop()
|
| 861 |
+
if token == "+":
|
| 862 |
+
stack.append(a + b)
|
| 863 |
+
elif token == "-":
|
| 864 |
+
stack.append(a - b)
|
| 865 |
+
elif token == "*":
|
| 866 |
+
stack.append(a * b)
|
| 867 |
+
else:
|
| 868 |
+
stack.append((abs(a) // abs(b)) * (-1 if (a < 0) != (b < 0) else 1))
|
| 869 |
+
return stack[0]
|
klein_code_bench/reference/export.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export self-contained oracle projects for benchmark verification only."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from ..catalog import FAMILIES
|
| 6 |
+
from ..protocol import TIERS
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def export_reference(family, tier, destination):
|
| 10 |
+
f = FAMILIES[family]
|
| 11 |
+
root = Path(destination)
|
| 12 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 13 |
+
path = root / "main.py"
|
| 14 |
+
if path.exists():
|
| 15 |
+
raise FileExistsError(f"Refusing to overwrite {path}")
|
| 16 |
+
here = Path(__file__).parent
|
| 17 |
+
domain = (
|
| 18 |
+
(here / "domains.py")
|
| 19 |
+
.read_text(encoding="utf-8")
|
| 20 |
+
.replace("from __future__ import annotations", "")
|
| 21 |
+
)
|
| 22 |
+
service = (here / "service.py").read_text(encoding="utf-8")
|
| 23 |
+
for line in (
|
| 24 |
+
"from __future__ import annotations",
|
| 25 |
+
"from klein_code_bench.catalog import FAMILIES",
|
| 26 |
+
"from klein_code_bench.protocol import TIERS",
|
| 27 |
+
"from klein_code_bench.reference.domains import solve",
|
| 28 |
+
):
|
| 29 |
+
service = service.replace(line, "")
|
| 30 |
+
header = f"from types import SimpleNamespace\nTIERS = {TIERS!r}\nFAMILIES = {{{family!r}: SimpleNamespace(slug={family!r}, required={f.required!r})}}\n"
|
| 31 |
+
main = f"""
|
| 32 |
+
if __name__ == '__main__':
|
| 33 |
+
import argparse
|
| 34 |
+
import sys
|
| 35 |
+
parser = argparse.ArgumentParser()
|
| 36 |
+
parser.add_argument('--state-dir', required={tier == "max"!r})
|
| 37 |
+
args = parser.parse_args()
|
| 38 |
+
service = Service({family!r}, {tier!r}, args.state_dir)
|
| 39 |
+
for line in sys.stdin:
|
| 40 |
+
try:
|
| 41 |
+
def reject_constant(value):
|
| 42 |
+
raise ValueError(value)
|
| 43 |
+
request = json.loads(line, parse_constant=reject_constant)
|
| 44 |
+
except ValueError:
|
| 45 |
+
response = {{'ok': False, 'error': 'invalid_request'}}
|
| 46 |
+
else:
|
| 47 |
+
response = service.request(request)
|
| 48 |
+
print(json.dumps(response, ensure_ascii=True, allow_nan=False), flush=True)
|
| 49 |
+
"""
|
| 50 |
+
path.write_text(
|
| 51 |
+
domain + "\n" + header + "\n" + service + "\n" + main, encoding="utf-8"
|
| 52 |
+
)
|
| 53 |
+
return path
|
klein_code_bench/reference/service.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from klein_code_bench.catalog import FAMILIES
|
| 11 |
+
from klein_code_bench.protocol import TIERS
|
| 12 |
+
from klein_code_bench.reference.domains import solve
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Fault(Exception):
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def integer(value, minimum=0, maximum=None):
|
| 20 |
+
return (
|
| 21 |
+
type(value) is int
|
| 22 |
+
and value >= minimum
|
| 23 |
+
and (maximum is None or value <= maximum)
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def req_op(request):
|
| 28 |
+
return request.get("op") if isinstance(request, dict) else None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Service:
|
| 32 |
+
def __init__(self, family, tier, state_dir=None):
|
| 33 |
+
self.family = FAMILIES[family]
|
| 34 |
+
self.level = list(TIERS).index(tier)
|
| 35 |
+
self.directory = Path(state_dir) if state_dir is not None else None
|
| 36 |
+
self.state = {"revision": 0, "docs": {}, "history": [], "tokens": {}}
|
| 37 |
+
self.stack = []
|
| 38 |
+
if self.directory is not None:
|
| 39 |
+
self.directory.mkdir(parents=True, exist_ok=True)
|
| 40 |
+
path = self.directory / "workspace.json"
|
| 41 |
+
if path.exists():
|
| 42 |
+
self.state = json.loads(path.read_text(encoding="utf-8"))
|
| 43 |
+
|
| 44 |
+
def persist(self):
|
| 45 |
+
if self.directory is None or self.stack:
|
| 46 |
+
return
|
| 47 |
+
path = self.directory / "workspace.json"
|
| 48 |
+
temporary = self.directory / "workspace.tmp"
|
| 49 |
+
with temporary.open("w", encoding="utf-8") as f:
|
| 50 |
+
json.dump(self.state, f, ensure_ascii=True, allow_nan=False)
|
| 51 |
+
f.flush()
|
| 52 |
+
os.fsync(f.fileno())
|
| 53 |
+
os.replace(temporary, path)
|
| 54 |
+
if os.name == "posix":
|
| 55 |
+
fd = os.open(self.directory, os.O_RDONLY)
|
| 56 |
+
try:
|
| 57 |
+
os.fsync(fd)
|
| 58 |
+
finally:
|
| 59 |
+
os.close(fd)
|
| 60 |
+
|
| 61 |
+
def compute(self, value):
|
| 62 |
+
if not isinstance(value, dict) or not all(
|
| 63 |
+
k in value for k in self.family.required
|
| 64 |
+
):
|
| 65 |
+
raise Fault("invalid_input")
|
| 66 |
+
return solve(self.family.slug, copy.deepcopy(value))
|
| 67 |
+
|
| 68 |
+
def request(self, request):
|
| 69 |
+
before, stack = copy.deepcopy(self.state), copy.deepcopy(self.stack)
|
| 70 |
+
try:
|
| 71 |
+
result = self.dispatch(request)
|
| 72 |
+
response = {"ok": True, "result": result}
|
| 73 |
+
# Writes inside a transaction remain volatile until outermost commit.
|
| 74 |
+
if (
|
| 75 |
+
self.level == 3
|
| 76 |
+
and not self.stack
|
| 77 |
+
and (
|
| 78 |
+
self.state != before or bool(stack) and req_op(request) == "commit"
|
| 79 |
+
)
|
| 80 |
+
):
|
| 81 |
+
self.persist()
|
| 82 |
+
return copy.deepcopy(response)
|
| 83 |
+
except Fault as error:
|
| 84 |
+
self.state, self.stack = before, stack
|
| 85 |
+
return {"ok": False, "error": str(error)}
|
| 86 |
+
|
| 87 |
+
def dispatch(self, req, inside_batch=False):
|
| 88 |
+
if not isinstance(req, dict) or not isinstance(req.get("op"), str):
|
| 89 |
+
raise Fault("invalid_request")
|
| 90 |
+
op = req["op"]
|
| 91 |
+
allowed = {"solve"}
|
| 92 |
+
if self.level >= 1:
|
| 93 |
+
allowed |= {"put", "get", "delete", "list", "evaluate", "status"}
|
| 94 |
+
if self.level >= 2:
|
| 95 |
+
allowed |= {"batch", "begin", "commit", "rollback"}
|
| 96 |
+
if self.level == 3:
|
| 97 |
+
allowed |= {"history", "scan"}
|
| 98 |
+
if op not in allowed:
|
| 99 |
+
raise Fault("invalid_request")
|
| 100 |
+
if inside_batch and op not in {
|
| 101 |
+
"solve",
|
| 102 |
+
"put",
|
| 103 |
+
"get",
|
| 104 |
+
"delete",
|
| 105 |
+
"list",
|
| 106 |
+
"evaluate",
|
| 107 |
+
"status",
|
| 108 |
+
}:
|
| 109 |
+
raise Fault("invalid_request")
|
| 110 |
+
token = req.get("token")
|
| 111 |
+
if self.level == 3 and "token" in req:
|
| 112 |
+
if (
|
| 113 |
+
inside_batch
|
| 114 |
+
or op not in {"put", "delete", "batch"}
|
| 115 |
+
or not isinstance(token, str)
|
| 116 |
+
or not token
|
| 117 |
+
):
|
| 118 |
+
raise Fault("invalid_request")
|
| 119 |
+
canonical = json.dumps(
|
| 120 |
+
{k: v for k, v in req.items() if k != "token"},
|
| 121 |
+
sort_keys=True,
|
| 122 |
+
separators=(",", ":"),
|
| 123 |
+
)
|
| 124 |
+
cached = self.state["tokens"].get(token)
|
| 125 |
+
if cached:
|
| 126 |
+
if cached["request"] != canonical:
|
| 127 |
+
raise Fault("idempotency_conflict")
|
| 128 |
+
return copy.deepcopy(cached["result"])
|
| 129 |
+
else:
|
| 130 |
+
token = None
|
| 131 |
+
result = self.execute(op, req)
|
| 132 |
+
if token is not None:
|
| 133 |
+
self.state["tokens"][token] = {
|
| 134 |
+
"request": canonical,
|
| 135 |
+
"result": copy.deepcopy(result),
|
| 136 |
+
}
|
| 137 |
+
return result
|
| 138 |
+
|
| 139 |
+
def execute(self, op, req):
|
| 140 |
+
if op == "solve":
|
| 141 |
+
return self.compute(req.get("input"))
|
| 142 |
+
docs = self.state["docs"]
|
| 143 |
+
if op in {"put", "get", "delete", "evaluate"}:
|
| 144 |
+
key = req.get("key")
|
| 145 |
+
if (
|
| 146 |
+
not isinstance(key, str)
|
| 147 |
+
or not key
|
| 148 |
+
or op == "put"
|
| 149 |
+
and "value" not in req
|
| 150 |
+
):
|
| 151 |
+
raise Fault("invalid_request")
|
| 152 |
+
if self.level >= 2 and op in {"put", "delete"} and "if_revision" in req:
|
| 153 |
+
if not integer(req["if_revision"]):
|
| 154 |
+
raise Fault("invalid_request")
|
| 155 |
+
if req["if_revision"] != self.state["revision"]:
|
| 156 |
+
raise Fault("conflict")
|
| 157 |
+
if op != "put" and key not in docs:
|
| 158 |
+
raise Fault("not_found")
|
| 159 |
+
if op == "get":
|
| 160 |
+
return copy.deepcopy(docs[key])
|
| 161 |
+
if op == "evaluate":
|
| 162 |
+
return self.compute(docs[key]["value"])
|
| 163 |
+
self.state["revision"] += 1
|
| 164 |
+
revision = self.state["revision"]
|
| 165 |
+
if op == "put":
|
| 166 |
+
docs[key] = {
|
| 167 |
+
"key": key,
|
| 168 |
+
"value": copy.deepcopy(req["value"]),
|
| 169 |
+
"revision": revision,
|
| 170 |
+
}
|
| 171 |
+
else:
|
| 172 |
+
del docs[key]
|
| 173 |
+
if self.level == 3:
|
| 174 |
+
event = {"revision": revision, "op": op, "key": key}
|
| 175 |
+
if op == "put":
|
| 176 |
+
event["value"] = copy.deepcopy(req["value"])
|
| 177 |
+
self.state["history"].append(event)
|
| 178 |
+
return {"key": key, "revision": revision}
|
| 179 |
+
if op == "list":
|
| 180 |
+
prefix = req.get("prefix", "")
|
| 181 |
+
if not isinstance(prefix, str):
|
| 182 |
+
raise Fault("invalid_request")
|
| 183 |
+
return sorted(k for k in docs if k.startswith(prefix))
|
| 184 |
+
if op == "status":
|
| 185 |
+
return {"revision": self.state["revision"], "size": len(docs)}
|
| 186 |
+
if op == "batch":
|
| 187 |
+
commands = req.get("commands")
|
| 188 |
+
if not isinstance(commands, list) or len(commands) > 32:
|
| 189 |
+
raise Fault("invalid_request")
|
| 190 |
+
return [self.dispatch(command, inside_batch=True) for command in commands]
|
| 191 |
+
if op == "begin":
|
| 192 |
+
if len(self.stack) >= 8:
|
| 193 |
+
raise Fault("transaction_limit")
|
| 194 |
+
self.stack.append(copy.deepcopy(self.state))
|
| 195 |
+
return {"depth": len(self.stack)}
|
| 196 |
+
if op in {"commit", "rollback"}:
|
| 197 |
+
if not self.stack:
|
| 198 |
+
raise Fault("no_transaction")
|
| 199 |
+
previous = self.stack.pop()
|
| 200 |
+
if op == "rollback":
|
| 201 |
+
self.state = previous
|
| 202 |
+
return {"depth": len(self.stack)}
|
| 203 |
+
if op == "history":
|
| 204 |
+
after, limit = req.get("after", 0), req.get("limit", 100)
|
| 205 |
+
if not integer(after) or not integer(limit, maximum=100):
|
| 206 |
+
raise Fault("invalid_request")
|
| 207 |
+
return copy.deepcopy(
|
| 208 |
+
[e for e in self.state["history"] if e["revision"] > after][:limit]
|
| 209 |
+
)
|
| 210 |
+
if op == "scan":
|
| 211 |
+
prefix, after, limit = (
|
| 212 |
+
req.get("prefix", ""),
|
| 213 |
+
req.get("after", ""),
|
| 214 |
+
req.get("limit", 100),
|
| 215 |
+
)
|
| 216 |
+
if (
|
| 217 |
+
not isinstance(prefix, str)
|
| 218 |
+
or not isinstance(after, str)
|
| 219 |
+
or not integer(limit, maximum=100)
|
| 220 |
+
):
|
| 221 |
+
raise Fault("invalid_request")
|
| 222 |
+
keys = sorted(k for k in docs if k.startswith(prefix) and k > after)
|
| 223 |
+
chosen = keys[:limit]
|
| 224 |
+
return {
|
| 225 |
+
"items": [copy.deepcopy(docs[k]) for k in chosen],
|
| 226 |
+
"next": chosen[-1] if chosen and len(keys) > len(chosen) else None,
|
| 227 |
+
}
|
| 228 |
+
raise Fault("invalid_request")
|
klein_code_bench/runner.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dependency-free local evaluator. This is process isolation, NOT a security sandbox."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
import selectors
|
| 10 |
+
import shutil
|
| 11 |
+
import signal
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
DATA = Path(__file__).parent / "data"
|
| 19 |
+
MAX_OUTPUT = 1_048_576
|
| 20 |
+
EXCLUDED = {".git", ".venv", "venv", "__pycache__", "node_modules", ".env"}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def load_tasks(subset=None, data_dir=None):
|
| 24 |
+
root = Path(data_dir) if data_dir else DATA
|
| 25 |
+
tiers = [subset] if subset else ["easy", "intermediate", "hard", "max"]
|
| 26 |
+
if any(t not in {"easy", "intermediate", "hard", "max"} for t in tiers):
|
| 27 |
+
raise ValueError("Unknown subset")
|
| 28 |
+
for tier in tiers:
|
| 29 |
+
for line in (root / f"{tier}.jsonl").read_text(encoding="utf-8").splitlines():
|
| 30 |
+
if line.strip():
|
| 31 |
+
yield json.loads(line)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def find_task(task_id, data_dir=None):
|
| 35 |
+
for row in load_tasks(data_dir=data_dir):
|
| 36 |
+
if row["task_id"] == task_id:
|
| 37 |
+
return row
|
| 38 |
+
raise ValueError(f"Unknown task: {task_id}")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def equal(actual, expected):
|
| 42 |
+
if isinstance(expected, bool) or expected is None or isinstance(expected, str):
|
| 43 |
+
return type(actual) is type(expected) and actual == expected
|
| 44 |
+
if type(expected) in (int, float):
|
| 45 |
+
if type(actual) not in (int, float):
|
| 46 |
+
return False
|
| 47 |
+
if type(actual) is int and type(expected) is int:
|
| 48 |
+
return actual == expected
|
| 49 |
+
return (
|
| 50 |
+
math.isfinite(actual)
|
| 51 |
+
and math.isfinite(expected)
|
| 52 |
+
and math.isclose(actual, expected, rel_tol=1e-9, abs_tol=1e-9)
|
| 53 |
+
)
|
| 54 |
+
if isinstance(expected, list):
|
| 55 |
+
return (
|
| 56 |
+
isinstance(actual, list)
|
| 57 |
+
and len(actual) == len(expected)
|
| 58 |
+
and all(equal(a, b) for a, b in zip(actual, expected))
|
| 59 |
+
)
|
| 60 |
+
if isinstance(expected, dict):
|
| 61 |
+
return (
|
| 62 |
+
isinstance(actual, dict)
|
| 63 |
+
and actual.keys() == expected.keys()
|
| 64 |
+
and all(equal(actual[k], expected[k]) for k in expected)
|
| 65 |
+
)
|
| 66 |
+
return False
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def strict_json(line):
|
| 70 |
+
def invalid(value):
|
| 71 |
+
raise ValueError(f"Nonfinite JSON constant: {value}")
|
| 72 |
+
|
| 73 |
+
return json.loads(line, parse_constant=invalid)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def kill_group(process):
|
| 77 |
+
if os.name == "posix":
|
| 78 |
+
try:
|
| 79 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 80 |
+
except ProcessLookupError:
|
| 81 |
+
pass
|
| 82 |
+
elif process.poll() is None:
|
| 83 |
+
process.kill()
|
| 84 |
+
process.wait()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def child_environment(home):
|
| 88 |
+
# Do not inherit credentials, PYTHONPATH, proxies, or user site configuration.
|
| 89 |
+
return {
|
| 90 |
+
"PATH": os.defpath,
|
| 91 |
+
"HOME": str(home),
|
| 92 |
+
"LANG": "C.UTF-8",
|
| 93 |
+
"LC_ALL": "C.UTF-8",
|
| 94 |
+
"TZ": "UTC",
|
| 95 |
+
"PYTHONHASHSEED": "0",
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def copy_project(source, target):
|
| 100 |
+
"""No symlinks, special files, or environment files may enter a submission."""
|
| 101 |
+
source = Path(source).resolve()
|
| 102 |
+
if not source.is_dir():
|
| 103 |
+
raise ValueError(f"Solution directory does not exist: {source}")
|
| 104 |
+
count = size = 0
|
| 105 |
+
for root, dirs, files in os.walk(source, followlinks=False):
|
| 106 |
+
base = Path(root)
|
| 107 |
+
dirs[:] = sorted(
|
| 108 |
+
d for d in dirs if d not in EXCLUDED and not (base / d).is_symlink()
|
| 109 |
+
)
|
| 110 |
+
relative = base.relative_to(source)
|
| 111 |
+
(target / relative).mkdir(parents=True, exist_ok=True)
|
| 112 |
+
for name in sorted(files):
|
| 113 |
+
if (
|
| 114 |
+
name in EXCLUDED
|
| 115 |
+
or name.startswith(".env.")
|
| 116 |
+
or name.endswith((".pyc", ".token"))
|
| 117 |
+
):
|
| 118 |
+
continue
|
| 119 |
+
path = base / name
|
| 120 |
+
if path.is_symlink() or not path.is_file():
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"Submission contains a symlink or special file: {relative / name}"
|
| 123 |
+
)
|
| 124 |
+
count += 1
|
| 125 |
+
size += path.stat().st_size
|
| 126 |
+
if count > 2000 or size > 20_000_000:
|
| 127 |
+
raise ValueError("Submission exceeds 2000 files / 20 MB")
|
| 128 |
+
shutil.copyfile(path, target / relative / name)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def run_session(project, state, session, *, durable=False, timeout=10.0):
|
| 132 |
+
if os.name != "posix":
|
| 133 |
+
raise RuntimeError(
|
| 134 |
+
"The local evaluator requires POSIX process groups and pipe selectors"
|
| 135 |
+
)
|
| 136 |
+
argv = [sys.executable, "-E", "-s", "-S", "main.py"]
|
| 137 |
+
if durable:
|
| 138 |
+
argv += ["--state-dir", str(state)]
|
| 139 |
+
start = time.monotonic()
|
| 140 |
+
deadline = start + timeout
|
| 141 |
+
process = subprocess.Popen(
|
| 142 |
+
argv,
|
| 143 |
+
cwd=project,
|
| 144 |
+
env=child_environment(state.parent / "home"),
|
| 145 |
+
stdin=subprocess.PIPE,
|
| 146 |
+
stdout=subprocess.PIPE,
|
| 147 |
+
stderr=subprocess.PIPE,
|
| 148 |
+
start_new_session=True,
|
| 149 |
+
bufsize=0,
|
| 150 |
+
)
|
| 151 |
+
selector = selectors.DefaultSelector()
|
| 152 |
+
for pipe in (process.stdin, process.stdout, process.stderr):
|
| 153 |
+
os.set_blocking(pipe.fileno(), False)
|
| 154 |
+
selector.register(process.stdout, selectors.EVENT_READ, "out")
|
| 155 |
+
selector.register(process.stderr, selectors.EVENT_READ, "err")
|
| 156 |
+
buffer = b""
|
| 157 |
+
stderr = bytearray()
|
| 158 |
+
output_bytes = passed = 0
|
| 159 |
+
failure = None
|
| 160 |
+
actual = None
|
| 161 |
+
|
| 162 |
+
def read_events(wait):
|
| 163 |
+
nonlocal buffer, output_bytes
|
| 164 |
+
for key, _ in selector.select(max(0, wait)):
|
| 165 |
+
if key.data == "in":
|
| 166 |
+
continue
|
| 167 |
+
chunk = os.read(key.fileobj.fileno(), 65536)
|
| 168 |
+
if not chunk:
|
| 169 |
+
selector.unregister(key.fileobj)
|
| 170 |
+
continue
|
| 171 |
+
if key.data == "out":
|
| 172 |
+
buffer += chunk
|
| 173 |
+
output_bytes += len(chunk)
|
| 174 |
+
if output_bytes > MAX_OUTPUT:
|
| 175 |
+
raise ValueError("stdout exceeded 1 MiB")
|
| 176 |
+
elif len(stderr) < 8192:
|
| 177 |
+
stderr.extend(chunk[: 8192 - len(stderr)])
|
| 178 |
+
|
| 179 |
+
try:
|
| 180 |
+
if len(session["requests"]) != len(session["expected"]):
|
| 181 |
+
raise ValueError("Invalid acceptance session lengths")
|
| 182 |
+
for index, (request, expected) in enumerate(
|
| 183 |
+
zip(session["requests"], session["expected"])
|
| 184 |
+
):
|
| 185 |
+
actual = None
|
| 186 |
+
wire = (
|
| 187 |
+
request
|
| 188 |
+
if isinstance(request, str)
|
| 189 |
+
else json.dumps(request, ensure_ascii=True, allow_nan=False)
|
| 190 |
+
) + "\n"
|
| 191 |
+
pending = memoryview(wire.encode("utf-8"))
|
| 192 |
+
selector.register(process.stdin, selectors.EVENT_WRITE, "in")
|
| 193 |
+
while pending:
|
| 194 |
+
if time.monotonic() >= deadline:
|
| 195 |
+
raise TimeoutError("session timeout while sending request")
|
| 196 |
+
try:
|
| 197 |
+
written = os.write(process.stdin.fileno(), pending)
|
| 198 |
+
pending = pending[written:]
|
| 199 |
+
except BlockingIOError:
|
| 200 |
+
read_events(min(0.02, deadline - time.monotonic()))
|
| 201 |
+
selector.unregister(process.stdin)
|
| 202 |
+
while b"\n" not in buffer:
|
| 203 |
+
remaining = deadline - time.monotonic()
|
| 204 |
+
if remaining <= 0:
|
| 205 |
+
raise TimeoutError(
|
| 206 |
+
"session timeout waiting for flushed JSON response"
|
| 207 |
+
)
|
| 208 |
+
read_events(min(0.05, remaining))
|
| 209 |
+
if process.poll() is not None and b"\n" not in buffer:
|
| 210 |
+
raise ValueError(
|
| 211 |
+
f"process exited before response (code {process.returncode})"
|
| 212 |
+
)
|
| 213 |
+
line, buffer = buffer.split(b"\n", 1)
|
| 214 |
+
actual = strict_json(line.decode("utf-8"))
|
| 215 |
+
if not equal(actual, expected):
|
| 216 |
+
failure = {
|
| 217 |
+
"request_index": index,
|
| 218 |
+
"reason": "response mismatch",
|
| 219 |
+
"expected": expected,
|
| 220 |
+
"actual": actual,
|
| 221 |
+
}
|
| 222 |
+
break
|
| 223 |
+
passed += 1
|
| 224 |
+
if failure is None:
|
| 225 |
+
if durable:
|
| 226 |
+
# Test persistence after acknowledgement without graceful shutdown hooks.
|
| 227 |
+
kill_group(process)
|
| 228 |
+
else:
|
| 229 |
+
process.stdin.close()
|
| 230 |
+
while process.poll() is None or selector.get_map():
|
| 231 |
+
if time.monotonic() >= deadline:
|
| 232 |
+
raise TimeoutError("process did not exit cleanly on EOF")
|
| 233 |
+
read_events(min(0.02, deadline - time.monotonic()))
|
| 234 |
+
if process.returncode:
|
| 235 |
+
raise ValueError(f"nonzero exit code {process.returncode}")
|
| 236 |
+
# Catch extra lines even if the child has exited or was force-killed.
|
| 237 |
+
read_events(0)
|
| 238 |
+
if buffer:
|
| 239 |
+
raise ValueError("extra stdout beyond one JSON response per request")
|
| 240 |
+
except (ValueError, OSError, TimeoutError, UnicodeError) as error:
|
| 241 |
+
failure = {
|
| 242 |
+
"request_index": passed,
|
| 243 |
+
"reason": str(error),
|
| 244 |
+
"timed_out": isinstance(error, TimeoutError),
|
| 245 |
+
}
|
| 246 |
+
finally:
|
| 247 |
+
kill_group(process)
|
| 248 |
+
selector.close()
|
| 249 |
+
for pipe in (process.stdin, process.stdout, process.stderr):
|
| 250 |
+
if not pipe.closed:
|
| 251 |
+
pipe.close()
|
| 252 |
+
return {
|
| 253 |
+
"passed": failure is None,
|
| 254 |
+
"assertions_passed": passed,
|
| 255 |
+
"assertions": len(session["expected"]),
|
| 256 |
+
"duration": time.monotonic() - start,
|
| 257 |
+
"failure": failure,
|
| 258 |
+
"stderr": stderr.decode("utf-8", errors="replace") if failure else "",
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def evaluate(task, solution, *, timeout=None, tests=None, fail_fast=False):
|
| 263 |
+
"""A task passes only when every scenario and every restart session passes."""
|
| 264 |
+
traces = tests if tests is not None else json.loads(task["acceptance_tests"])
|
| 265 |
+
if not traces:
|
| 266 |
+
raise ValueError("Refusing an empty acceptance suite")
|
| 267 |
+
source = Path(solution).resolve()
|
| 268 |
+
reports = []
|
| 269 |
+
began = time.monotonic()
|
| 270 |
+
with tempfile.TemporaryDirectory(prefix="klein-bench-") as temporary:
|
| 271 |
+
root = Path(temporary)
|
| 272 |
+
clean = root / "submission"
|
| 273 |
+
clean.mkdir()
|
| 274 |
+
rejection = None
|
| 275 |
+
try:
|
| 276 |
+
copy_project(source, clean)
|
| 277 |
+
except ValueError as error:
|
| 278 |
+
rejection = str(error)
|
| 279 |
+
if rejection or not (clean / "main.py").is_file():
|
| 280 |
+
return {
|
| 281 |
+
"task_id": task["task_id"],
|
| 282 |
+
"subset": task["subset"],
|
| 283 |
+
"passed": False,
|
| 284 |
+
"resolved": False,
|
| 285 |
+
"reason": rejection or "main.py is missing",
|
| 286 |
+
"scenarios": [],
|
| 287 |
+
"duration": time.monotonic() - began,
|
| 288 |
+
}
|
| 289 |
+
source_hash = hashlib.sha256()
|
| 290 |
+
for file in sorted(p for p in clean.rglob("*") if p.is_file()):
|
| 291 |
+
source_hash.update(str(file.relative_to(clean)).encode())
|
| 292 |
+
source_hash.update(b"\0" + file.read_bytes() + b"\0")
|
| 293 |
+
for index, trace in enumerate(traces):
|
| 294 |
+
scenario = root / str(index)
|
| 295 |
+
project, state = scenario / "project", scenario / "state"
|
| 296 |
+
project.mkdir(parents=True)
|
| 297 |
+
state.mkdir()
|
| 298 |
+
(scenario / "home").mkdir()
|
| 299 |
+
copy_project(clean, project)
|
| 300 |
+
sessions = []
|
| 301 |
+
for session in trace["sessions"]:
|
| 302 |
+
report = run_session(
|
| 303 |
+
project,
|
| 304 |
+
state,
|
| 305 |
+
session,
|
| 306 |
+
durable=task["subset"] == "max",
|
| 307 |
+
timeout=timeout or task["timeout_seconds"],
|
| 308 |
+
)
|
| 309 |
+
sessions.append(report)
|
| 310 |
+
if not report["passed"]:
|
| 311 |
+
break
|
| 312 |
+
reports.append(
|
| 313 |
+
{
|
| 314 |
+
"name": trace["name"],
|
| 315 |
+
"passed": all(s["passed"] for s in sessions),
|
| 316 |
+
"sessions": sessions,
|
| 317 |
+
}
|
| 318 |
+
)
|
| 319 |
+
if fail_fast and not reports[-1]["passed"]:
|
| 320 |
+
break
|
| 321 |
+
passed = len(reports) == len(traces) and all(r["passed"] for r in reports)
|
| 322 |
+
return {
|
| 323 |
+
"task_id": task["task_id"],
|
| 324 |
+
"subset": task["subset"],
|
| 325 |
+
"passed": passed,
|
| 326 |
+
"resolved": passed,
|
| 327 |
+
"scenarios_passed": sum(r["passed"] for r in reports),
|
| 328 |
+
"scenarios_total": len(traces),
|
| 329 |
+
"assertions_passed": sum(
|
| 330 |
+
s["assertions_passed"] for r in reports for s in r["sessions"]
|
| 331 |
+
),
|
| 332 |
+
"assertions_total": sum(
|
| 333 |
+
len(s["expected"]) for t in traces for s in t["sessions"]
|
| 334 |
+
),
|
| 335 |
+
"source_sha256": source_hash.hexdigest(),
|
| 336 |
+
"duration": time.monotonic() - began,
|
| 337 |
+
"scenarios": reports,
|
| 338 |
+
}
|
klein_code_bench/scenarios.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Acceptance scenarios: every scenario gets an independent project/state copy."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import copy
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
from .catalog import FAMILIES
|
| 10 |
+
from .fuzz import generated_inputs
|
| 11 |
+
from .protocol import TIERS
|
| 12 |
+
from .reference.service import Service
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def scenarios(family, tier, seed=1729):
|
| 16 |
+
f = FAMILIES[family]
|
| 17 |
+
level = list(TIERS).index(tier)
|
| 18 |
+
rng = random.Random(f"{seed}/{family}/{tier}")
|
| 19 |
+
a, b, c = [
|
| 20 |
+
prefix + str(rng.randrange(10**8)) for prefix in ("doc/", "doc/", "other/")
|
| 21 |
+
]
|
| 22 |
+
a, b = sorted((a, b))
|
| 23 |
+
value, other = copy.deepcopy(f.inputs[0]), copy.deepcopy(f.inputs[-1])
|
| 24 |
+
traces = []
|
| 25 |
+
|
| 26 |
+
def add(name, *sessions):
|
| 27 |
+
traces.append(
|
| 28 |
+
{"name": name, "sessions": [{"requests": list(s)} for s in sessions]}
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
add(
|
| 32 |
+
"generated-domain",
|
| 33 |
+
[{"op": "solve", "input": v} for v in generated_inputs(family, seed=seed)],
|
| 34 |
+
)
|
| 35 |
+
add("domain-boundaries", [{"op": "solve", "input": v} for v in f.inputs])
|
| 36 |
+
add(
|
| 37 |
+
"protocol-errors",
|
| 38 |
+
[
|
| 39 |
+
"{broken",
|
| 40 |
+
"",
|
| 41 |
+
"null",
|
| 42 |
+
"[]",
|
| 43 |
+
"42",
|
| 44 |
+
{},
|
| 45 |
+
{"op": 1},
|
| 46 |
+
{"op": "unknown"},
|
| 47 |
+
{"op": "solve"},
|
| 48 |
+
{"op": "solve", "input": []},
|
| 49 |
+
{"op": "solve", "input": {}},
|
| 50 |
+
{"op": "solve", "input": value},
|
| 51 |
+
],
|
| 52 |
+
)
|
| 53 |
+
add(
|
| 54 |
+
"required-fields",
|
| 55 |
+
[
|
| 56 |
+
{"op": "solve", "input": {k: v for k, v in value.items() if k != missing}}
|
| 57 |
+
for missing in f.required
|
| 58 |
+
]
|
| 59 |
+
+ [{"op": "solve", "input": dict(value, ignored_extra={"nested": True})}],
|
| 60 |
+
)
|
| 61 |
+
if level == 0:
|
| 62 |
+
add(
|
| 63 |
+
"unsupported-store",
|
| 64 |
+
[
|
| 65 |
+
{"op": "put", "key": a, "value": value},
|
| 66 |
+
{"op": "status"},
|
| 67 |
+
{"op": "batch", "commands": []},
|
| 68 |
+
],
|
| 69 |
+
)
|
| 70 |
+
if level >= 1:
|
| 71 |
+
add(
|
| 72 |
+
"document-lifecycle",
|
| 73 |
+
[
|
| 74 |
+
{"op": "status"},
|
| 75 |
+
{"op": "list"},
|
| 76 |
+
{"op": "get", "key": a},
|
| 77 |
+
{"op": "put", "key": a, "value": value},
|
| 78 |
+
{"op": "evaluate", "key": a},
|
| 79 |
+
{"op": "get", "key": a},
|
| 80 |
+
{"op": "put", "key": a, "value": other},
|
| 81 |
+
{"op": "evaluate", "key": a},
|
| 82 |
+
{"op": "put", "key": b, "value": value},
|
| 83 |
+
{"op": "delete", "key": a},
|
| 84 |
+
{"op": "get", "key": a},
|
| 85 |
+
{"op": "delete", "key": a},
|
| 86 |
+
{"op": "get", "key": b},
|
| 87 |
+
{"op": "status"},
|
| 88 |
+
],
|
| 89 |
+
)
|
| 90 |
+
add(
|
| 91 |
+
"listing-and-json-values",
|
| 92 |
+
[
|
| 93 |
+
{"op": "put", "key": c, "value": None},
|
| 94 |
+
{"op": "put", "key": b, "value": [True, False, {"x": [1, None]}]},
|
| 95 |
+
{"op": "put", "key": a, "value": {}},
|
| 96 |
+
{"op": "put", "key": "../é/😀", "value": "value"},
|
| 97 |
+
{"op": "list"},
|
| 98 |
+
{"op": "list", "prefix": "doc/"},
|
| 99 |
+
{"op": "list", "prefix": "missing"},
|
| 100 |
+
{"op": "get", "key": c},
|
| 101 |
+
{"op": "evaluate", "key": c},
|
| 102 |
+
{"op": "evaluate", "key": a},
|
| 103 |
+
{"op": "get", "key": b},
|
| 104 |
+
{"op": "put", "key": c, "value": None},
|
| 105 |
+
{"op": "status"},
|
| 106 |
+
],
|
| 107 |
+
)
|
| 108 |
+
add(
|
| 109 |
+
"store-errors",
|
| 110 |
+
[
|
| 111 |
+
{"op": "put", "key": "", "value": 1},
|
| 112 |
+
{"op": "put", "key": a},
|
| 113 |
+
{"op": "put", "key": 1, "value": None},
|
| 114 |
+
{"op": "get"},
|
| 115 |
+
{"op": "delete", "key": []},
|
| 116 |
+
{"op": "list", "prefix": None},
|
| 117 |
+
{"op": "evaluate", "key": "missing"},
|
| 118 |
+
{"op": "status"},
|
| 119 |
+
],
|
| 120 |
+
)
|
| 121 |
+
if level == 1:
|
| 122 |
+
add(
|
| 123 |
+
"unsupported-transactions",
|
| 124 |
+
[
|
| 125 |
+
{"op": "begin"},
|
| 126 |
+
{"op": "batch", "commands": []},
|
| 127 |
+
{"op": "history"},
|
| 128 |
+
{"op": "status"},
|
| 129 |
+
],
|
| 130 |
+
)
|
| 131 |
+
if level >= 2:
|
| 132 |
+
add(
|
| 133 |
+
"compare-and-swap",
|
| 134 |
+
[
|
| 135 |
+
{"op": "put", "key": a, "value": value, "if_revision": 0},
|
| 136 |
+
{"op": "put", "key": b, "value": value, "if_revision": 0},
|
| 137 |
+
{"op": "delete", "key": "missing", "if_revision": 0},
|
| 138 |
+
{"op": "delete", "key": a, "if_revision": True},
|
| 139 |
+
{"op": "put", "key": a, "value": other, "if_revision": -1},
|
| 140 |
+
{"op": "put", "key": a, "value": other, "if_revision": 1},
|
| 141 |
+
{"op": "get", "key": a},
|
| 142 |
+
{"op": "delete", "key": a, "if_revision": 2},
|
| 143 |
+
{"op": "status"},
|
| 144 |
+
],
|
| 145 |
+
)
|
| 146 |
+
add(
|
| 147 |
+
"atomic-batches",
|
| 148 |
+
[
|
| 149 |
+
{"op": "batch", "commands": []},
|
| 150 |
+
{
|
| 151 |
+
"op": "batch",
|
| 152 |
+
"commands": [
|
| 153 |
+
{"op": "put", "key": a, "value": value},
|
| 154 |
+
{"op": "evaluate", "key": a},
|
| 155 |
+
{"op": "status"},
|
| 156 |
+
],
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"op": "batch",
|
| 160 |
+
"commands": [
|
| 161 |
+
{"op": "put", "key": a, "value": other},
|
| 162 |
+
{"op": "delete", "key": "missing"},
|
| 163 |
+
],
|
| 164 |
+
},
|
| 165 |
+
{"op": "get", "key": a},
|
| 166 |
+
{"op": "status"},
|
| 167 |
+
{
|
| 168 |
+
"op": "batch",
|
| 169 |
+
"commands": [
|
| 170 |
+
{"op": "delete", "key": a},
|
| 171 |
+
{"op": "put", "key": b, "value": other, "if_revision": 2},
|
| 172 |
+
{"op": "list"},
|
| 173 |
+
],
|
| 174 |
+
},
|
| 175 |
+
{"op": "list"},
|
| 176 |
+
{"op": "status"},
|
| 177 |
+
],
|
| 178 |
+
)
|
| 179 |
+
add(
|
| 180 |
+
"batch-errors",
|
| 181 |
+
[
|
| 182 |
+
{
|
| 183 |
+
"op": "batch",
|
| 184 |
+
"commands": [
|
| 185 |
+
{"op": "put", "key": a, "value": value},
|
| 186 |
+
{"op": "begin"},
|
| 187 |
+
],
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"op": "batch",
|
| 191 |
+
"commands": [
|
| 192 |
+
{"op": "put", "key": a, "value": value},
|
| 193 |
+
{"op": "batch", "commands": []},
|
| 194 |
+
],
|
| 195 |
+
},
|
| 196 |
+
{"op": "batch", "commands": [None]},
|
| 197 |
+
{"op": "batch", "commands": {}},
|
| 198 |
+
{"op": "batch", "commands": [{"op": "status"}] * 33},
|
| 199 |
+
{
|
| 200 |
+
"op": "batch",
|
| 201 |
+
"commands": [
|
| 202 |
+
{"op": "put", "key": a, "value": {}},
|
| 203 |
+
{"op": "evaluate", "key": a},
|
| 204 |
+
],
|
| 205 |
+
},
|
| 206 |
+
{"op": "status"},
|
| 207 |
+
{"op": "list"},
|
| 208 |
+
],
|
| 209 |
+
)
|
| 210 |
+
add(
|
| 211 |
+
"nested-transactions",
|
| 212 |
+
[
|
| 213 |
+
{"op": "commit"},
|
| 214 |
+
{"op": "rollback"},
|
| 215 |
+
{"op": "put", "key": a, "value": value},
|
| 216 |
+
{"op": "begin"},
|
| 217 |
+
{"op": "put", "key": a, "value": other},
|
| 218 |
+
{"op": "begin"},
|
| 219 |
+
{"op": "delete", "key": a},
|
| 220 |
+
{"op": "put", "key": b, "value": value},
|
| 221 |
+
{"op": "commit"},
|
| 222 |
+
{"op": "status"},
|
| 223 |
+
{"op": "rollback"},
|
| 224 |
+
{"op": "get", "key": a},
|
| 225 |
+
{"op": "get", "key": b},
|
| 226 |
+
{"op": "status"},
|
| 227 |
+
{"op": "begin"},
|
| 228 |
+
{"op": "delete", "key": a},
|
| 229 |
+
{"op": "rollback"},
|
| 230 |
+
{"op": "get", "key": a},
|
| 231 |
+
{"op": "begin"},
|
| 232 |
+
{"op": "put", "key": b, "value": other},
|
| 233 |
+
{"op": "commit"},
|
| 234 |
+
{"op": "status"},
|
| 235 |
+
],
|
| 236 |
+
)
|
| 237 |
+
add(
|
| 238 |
+
"transaction-limits",
|
| 239 |
+
[{"op": "begin"}] * 9
|
| 240 |
+
+ [{"op": "put", "key": a, "value": value}]
|
| 241 |
+
+ [{"op": "rollback"}] * 9
|
| 242 |
+
+ [{"op": "status"}],
|
| 243 |
+
)
|
| 244 |
+
if level == 2:
|
| 245 |
+
add(
|
| 246 |
+
"unsupported-durability",
|
| 247 |
+
[{"op": "history"}, {"op": "scan"}, {"op": "status"}],
|
| 248 |
+
)
|
| 249 |
+
if level == 3:
|
| 250 |
+
add(
|
| 251 |
+
"durable-writes",
|
| 252 |
+
[
|
| 253 |
+
{"op": "put", "key": a, "value": value},
|
| 254 |
+
{"op": "put", "key": b, "value": other},
|
| 255 |
+
],
|
| 256 |
+
[
|
| 257 |
+
{"op": "status"},
|
| 258 |
+
{"op": "get", "key": a},
|
| 259 |
+
{"op": "evaluate", "key": b},
|
| 260 |
+
{"op": "delete", "key": a},
|
| 261 |
+
],
|
| 262 |
+
[
|
| 263 |
+
{"op": "list"},
|
| 264 |
+
{"op": "get", "key": a},
|
| 265 |
+
{"op": "history"},
|
| 266 |
+
{"op": "status"},
|
| 267 |
+
],
|
| 268 |
+
)
|
| 269 |
+
add(
|
| 270 |
+
"durable-commit",
|
| 271 |
+
[
|
| 272 |
+
{"op": "begin"},
|
| 273 |
+
{"op": "put", "key": a, "value": value},
|
| 274 |
+
{"op": "begin"},
|
| 275 |
+
{"op": "put", "key": b, "value": other},
|
| 276 |
+
{"op": "commit"},
|
| 277 |
+
{"op": "commit"},
|
| 278 |
+
],
|
| 279 |
+
[
|
| 280 |
+
{"op": "get", "key": a},
|
| 281 |
+
{"op": "get", "key": b},
|
| 282 |
+
{"op": "history"},
|
| 283 |
+
{"op": "status"},
|
| 284 |
+
],
|
| 285 |
+
)
|
| 286 |
+
add(
|
| 287 |
+
"discard-open-transactions",
|
| 288 |
+
[
|
| 289 |
+
{"op": "put", "key": a, "value": value},
|
| 290 |
+
{"op": "begin"},
|
| 291 |
+
{"op": "put", "key": a, "value": other},
|
| 292 |
+
{"op": "begin"},
|
| 293 |
+
{"op": "put", "key": b, "value": value},
|
| 294 |
+
{"op": "commit"},
|
| 295 |
+
{"op": "status"},
|
| 296 |
+
],
|
| 297 |
+
[
|
| 298 |
+
{"op": "get", "key": a},
|
| 299 |
+
{"op": "get", "key": b},
|
| 300 |
+
{"op": "history"},
|
| 301 |
+
{"op": "status"},
|
| 302 |
+
{"op": "rollback"},
|
| 303 |
+
],
|
| 304 |
+
)
|
| 305 |
+
add(
|
| 306 |
+
"pagination-and-history",
|
| 307 |
+
[
|
| 308 |
+
{"op": "put", "key": b, "value": other},
|
| 309 |
+
{"op": "put", "key": a, "value": value},
|
| 310 |
+
{"op": "put", "key": c, "value": None},
|
| 311 |
+
{"op": "scan", "prefix": "doc/", "limit": 1},
|
| 312 |
+
{"op": "scan", "prefix": "doc/", "after": a, "limit": 1},
|
| 313 |
+
{"op": "scan", "limit": 0},
|
| 314 |
+
{"op": "scan", "after": "zzzz"},
|
| 315 |
+
{"op": "scan"},
|
| 316 |
+
{"op": "history", "after": 1, "limit": 1},
|
| 317 |
+
{"op": "delete", "key": a},
|
| 318 |
+
{"op": "history", "after": 2},
|
| 319 |
+
{"op": "begin"},
|
| 320 |
+
{"op": "put", "key": c, "value": {}},
|
| 321 |
+
{"op": "history"},
|
| 322 |
+
{"op": "rollback"},
|
| 323 |
+
{"op": "history"},
|
| 324 |
+
],
|
| 325 |
+
)
|
| 326 |
+
add(
|
| 327 |
+
"durable-errors",
|
| 328 |
+
[
|
| 329 |
+
{"op": "history", "after": True},
|
| 330 |
+
{"op": "history", "limit": 101},
|
| 331 |
+
{"op": "history", "limit": -1},
|
| 332 |
+
{"op": "scan", "prefix": None},
|
| 333 |
+
{"op": "scan", "after": 2},
|
| 334 |
+
{"op": "scan", "limit": False},
|
| 335 |
+
{"op": "get", "key": a, "token": "bad"},
|
| 336 |
+
{"op": "put", "key": a, "value": 1, "token": ""},
|
| 337 |
+
{
|
| 338 |
+
"op": "batch",
|
| 339 |
+
"commands": [
|
| 340 |
+
{"op": "put", "key": a, "value": value, "token": "nested"}
|
| 341 |
+
],
|
| 342 |
+
},
|
| 343 |
+
{"op": "status"},
|
| 344 |
+
{"op": "history"},
|
| 345 |
+
],
|
| 346 |
+
)
|
| 347 |
+
first = {
|
| 348 |
+
"op": "put",
|
| 349 |
+
"key": a,
|
| 350 |
+
"value": value,
|
| 351 |
+
"if_revision": 0,
|
| 352 |
+
"token": "request/α",
|
| 353 |
+
}
|
| 354 |
+
add(
|
| 355 |
+
"idempotency-and-restart",
|
| 356 |
+
[
|
| 357 |
+
first,
|
| 358 |
+
dict(reversed(list(first.items()))),
|
| 359 |
+
dict(first, value=other if other != value else None),
|
| 360 |
+
{"op": "status"},
|
| 361 |
+
],
|
| 362 |
+
[
|
| 363 |
+
first,
|
| 364 |
+
{"op": "history"},
|
| 365 |
+
{"op": "status"},
|
| 366 |
+
{"op": "delete", "key": a, "token": "delete"},
|
| 367 |
+
{"op": "delete", "key": a, "token": "delete"},
|
| 368 |
+
],
|
| 369 |
+
[
|
| 370 |
+
{"op": "delete", "key": a, "token": "delete"},
|
| 371 |
+
{"op": "history"},
|
| 372 |
+
{"op": "status"},
|
| 373 |
+
],
|
| 374 |
+
)
|
| 375 |
+
add(
|
| 376 |
+
"failed-tokens-and-rollback",
|
| 377 |
+
[
|
| 378 |
+
{"op": "delete", "key": a, "token": "retry"},
|
| 379 |
+
{"op": "put", "key": a, "value": value},
|
| 380 |
+
{"op": "delete", "key": a, "token": "retry"},
|
| 381 |
+
{"op": "begin"},
|
| 382 |
+
{"op": "put", "key": b, "value": other, "token": "tx"},
|
| 383 |
+
{"op": "rollback"},
|
| 384 |
+
{"op": "put", "key": b, "value": value, "token": "tx"},
|
| 385 |
+
{
|
| 386 |
+
"op": "batch",
|
| 387 |
+
"token": "atomic",
|
| 388 |
+
"commands": [
|
| 389 |
+
{"op": "put", "key": c, "value": other},
|
| 390 |
+
{"op": "delete", "key": b},
|
| 391 |
+
],
|
| 392 |
+
},
|
| 393 |
+
{
|
| 394 |
+
"op": "batch",
|
| 395 |
+
"token": "atomic",
|
| 396 |
+
"commands": [
|
| 397 |
+
{"op": "put", "key": c, "value": other},
|
| 398 |
+
{"op": "delete", "key": b},
|
| 399 |
+
],
|
| 400 |
+
},
|
| 401 |
+
{"op": "history"},
|
| 402 |
+
{"op": "status"},
|
| 403 |
+
],
|
| 404 |
+
[
|
| 405 |
+
{"op": "history"},
|
| 406 |
+
{"op": "status"},
|
| 407 |
+
{"op": "put", "key": b, "value": value, "token": "tx"},
|
| 408 |
+
],
|
| 409 |
+
)
|
| 410 |
+
add(
|
| 411 |
+
"volatile-token-discard",
|
| 412 |
+
[
|
| 413 |
+
{"op": "begin"},
|
| 414 |
+
{"op": "put", "key": a, "value": value, "token": "volatile"},
|
| 415 |
+
{"op": "begin"},
|
| 416 |
+
{"op": "commit"},
|
| 417 |
+
],
|
| 418 |
+
[
|
| 419 |
+
{"op": "put", "key": a, "value": other, "token": "volatile"},
|
| 420 |
+
{"op": "history"},
|
| 421 |
+
{"op": "status"},
|
| 422 |
+
],
|
| 423 |
+
)
|
| 424 |
+
return traces
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def expected_scenarios(family, tier, seed=1729):
|
| 428 |
+
"""Materialize static expectations once; grading never loads reference code."""
|
| 429 |
+
traces = scenarios(family, tier, seed)
|
| 430 |
+
for trace in traces:
|
| 431 |
+
service = Service(family, tier)
|
| 432 |
+
durable = copy.deepcopy(service.state)
|
| 433 |
+
for session in trace["sessions"]:
|
| 434 |
+
service = Service(family, tier)
|
| 435 |
+
if tier == "max":
|
| 436 |
+
service.state = copy.deepcopy(durable)
|
| 437 |
+
expected = []
|
| 438 |
+
for request in session["requests"]:
|
| 439 |
+
try:
|
| 440 |
+
parsed = (
|
| 441 |
+
json.loads(request) if isinstance(request, str) else request
|
| 442 |
+
)
|
| 443 |
+
except json.JSONDecodeError:
|
| 444 |
+
response = {"ok": False, "error": "invalid_request"}
|
| 445 |
+
else:
|
| 446 |
+
response = service.request(parsed)
|
| 447 |
+
expected.append(response)
|
| 448 |
+
if tier == "max" and not service.stack:
|
| 449 |
+
durable = copy.deepcopy(service.state)
|
| 450 |
+
session["expected"] = expected
|
| 451 |
+
return traces
|
klein_code_bench/scoring.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strict all-tests-pass scoring; partial assertions are diagnostics only."""
|
| 2 |
+
|
| 3 |
+
from .protocol import TIERS
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def summarize(reports):
|
| 7 |
+
from .runner import load_tasks
|
| 8 |
+
|
| 9 |
+
catalog = {t["task_id"]: t for t in load_tasks()}
|
| 10 |
+
seen = set()
|
| 11 |
+
buckets = {tier: [] for tier in TIERS}
|
| 12 |
+
for report in reports:
|
| 13 |
+
task_id = report["task_id"]
|
| 14 |
+
if task_id in seen:
|
| 15 |
+
raise ValueError(f"Duplicate task report: {task_id}")
|
| 16 |
+
seen.add(task_id)
|
| 17 |
+
if task_id not in catalog or report.get("subset") != catalog[task_id]["subset"]:
|
| 18 |
+
raise ValueError(f"Unknown task or mismatched subset: {task_id}")
|
| 19 |
+
if report.get("evaluation_scope") == "public":
|
| 20 |
+
raise ValueError("Public-only smoke tests cannot be scored")
|
| 21 |
+
buckets[report["subset"]].append(report.get("resolved") is True)
|
| 22 |
+
tiers = {}
|
| 23 |
+
for tier, statuses in buckets.items():
|
| 24 |
+
resolved = sum(statuses)
|
| 25 |
+
tiers[tier] = {
|
| 26 |
+
"submitted": len(statuses),
|
| 27 |
+
"total": 65,
|
| 28 |
+
"resolved": resolved,
|
| 29 |
+
"resolution_rate": resolved / 65,
|
| 30 |
+
"submitted_resolution_rate": resolved / len(statuses) if statuses else None,
|
| 31 |
+
}
|
| 32 |
+
return {
|
| 33 |
+
"metric": "resolve@1",
|
| 34 |
+
"total": 260,
|
| 35 |
+
"submitted": len(seen),
|
| 36 |
+
"resolved": sum(r["resolved"] for r in tiers.values()),
|
| 37 |
+
"resolution_rate": sum(r["resolved"] for r in tiers.values()) / 260,
|
| 38 |
+
"complete": len(seen) == 260,
|
| 39 |
+
"subsets": tiers,
|
| 40 |
+
}
|
klein_code_bench/validation.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import tempfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from .catalog import FAMILIES
|
| 9 |
+
from .reference.domains import solve
|
| 10 |
+
from .reference.export import export_reference
|
| 11 |
+
from .runner import DATA, equal, evaluate, load_tasks
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def validate(subset=None):
|
| 15 |
+
manifest_bytes = (DATA / "manifest.json").read_bytes()
|
| 16 |
+
manifest = json.loads(manifest_bytes)
|
| 17 |
+
for name, digest in manifest["sha256"].items():
|
| 18 |
+
if hashlib.sha256((DATA / name).read_bytes()).hexdigest() != digest:
|
| 19 |
+
raise ValueError(f"Manifest checksum mismatch: {name}")
|
| 20 |
+
for f in FAMILIES.values():
|
| 21 |
+
if not equal(solve(f.slug, f.inputs[0]), f.golden):
|
| 22 |
+
raise ValueError(f"Independent golden mismatch: {f.slug}")
|
| 23 |
+
results = []
|
| 24 |
+
tasks = list(load_tasks(subset))
|
| 25 |
+
with tempfile.TemporaryDirectory(prefix="klein-validation-") as temporary:
|
| 26 |
+
root = Path(temporary)
|
| 27 |
+
empty = root / "empty"
|
| 28 |
+
empty.mkdir()
|
| 29 |
+
for index, task in enumerate(tasks, 1):
|
| 30 |
+
project = root / task["task_id"]
|
| 31 |
+
export_reference(task["family"], task["subset"], project)
|
| 32 |
+
reference = evaluate(task, project, fail_fast=True)
|
| 33 |
+
rejected_empty = not evaluate(task, empty)["passed"]
|
| 34 |
+
results.append(
|
| 35 |
+
{
|
| 36 |
+
"task_id": task["task_id"],
|
| 37 |
+
"passed": reference["passed"] and rejected_empty,
|
| 38 |
+
"empty_rejected": rejected_empty,
|
| 39 |
+
"reference": reference,
|
| 40 |
+
}
|
| 41 |
+
)
|
| 42 |
+
print(
|
| 43 |
+
f"[{index}/{len(tasks)}] {task['task_id']}: {'PASS' if results[-1]['passed'] else 'FAIL'}",
|
| 44 |
+
flush=True,
|
| 45 |
+
)
|
| 46 |
+
if (DATA / "manifest.json").read_bytes() != manifest_bytes:
|
| 47 |
+
raise ValueError(
|
| 48 |
+
"Dataset changed during validation; rerun against a stable snapshot"
|
| 49 |
+
)
|
| 50 |
+
return {
|
| 51 |
+
"passed": all(r["passed"] for r in results),
|
| 52 |
+
"tasks": len(results),
|
| 53 |
+
"reference_passes": sum(r["reference"]["passed"] for r in results),
|
| 54 |
+
"empty_rejected": sum(r["empty_rejected"] for r in results),
|
| 55 |
+
"assertions": sum(r["reference"].get("assertions_total", 0) for r in results),
|
| 56 |
+
"manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
|
| 57 |
+
"results": results,
|
| 58 |
+
}
|
pyproject.toml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "klein-code-bench"
|
| 7 |
+
version = "0.1.0"
|
| 8 |
+
description = "260 from-scratch Python project tasks for local language models"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.11"
|
| 11 |
+
license = "MIT"
|
| 12 |
+
authors = [{name = "Klein ML"}]
|
| 13 |
+
dependencies = []
|
| 14 |
+
|
| 15 |
+
[project.optional-dependencies]
|
| 16 |
+
publish = ["huggingface-hub>=0.26,<2"]
|
| 17 |
+
|
| 18 |
+
[project.scripts]
|
| 19 |
+
klein-bench = "klein_code_bench.cli:main"
|
| 20 |
+
|
| 21 |
+
[tool.setuptools.packages.find]
|
| 22 |
+
include = ["klein_code_bench*"]
|
| 23 |
+
|
| 24 |
+
[tool.setuptools.package-data]
|
| 25 |
+
klein_code_bench = ["data/*.jsonl", "data/*.json"]
|
tests/test_benchmark.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
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from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from klein_code_bench.build import build
|
| 9 |
+
from klein_code_bench.catalog import FAMILIES
|
| 10 |
+
from klein_code_bench.fuzz import generated_inputs
|
| 11 |
+
from klein_code_bench.reference.domains import solve
|
| 12 |
+
from klein_code_bench.reference.export import export_reference
|
| 13 |
+
from klein_code_bench.reference.service import Service
|
| 14 |
+
from klein_code_bench.runner import (
|
| 15 |
+
DATA,
|
| 16 |
+
copy_project,
|
| 17 |
+
equal,
|
| 18 |
+
evaluate,
|
| 19 |
+
load_tasks,
|
| 20 |
+
run_session,
|
| 21 |
+
)
|
| 22 |
+
from klein_code_bench.scoring import summarize
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DomainTests(unittest.TestCase):
|
| 26 |
+
def test_all_65_independent_goldens(self):
|
| 27 |
+
self.assertEqual(len(FAMILIES), 65)
|
| 28 |
+
for family in FAMILIES.values():
|
| 29 |
+
with self.subTest(family=family.slug):
|
| 30 |
+
self.assertTrue(
|
| 31 |
+
equal(solve(family.slug, family.inputs[0]), family.golden)
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def test_generators_cover_every_family_without_mutating_input(self):
|
| 35 |
+
for family in FAMILIES:
|
| 36 |
+
for data in generated_inputs(family):
|
| 37 |
+
original = copy.deepcopy(data)
|
| 38 |
+
json.dumps(solve(family, data), allow_nan=False)
|
| 39 |
+
self.assertEqual(data, original, family)
|
| 40 |
+
|
| 41 |
+
def test_money_conservation(self):
|
| 42 |
+
for x in generated_inputs("money_split", count=100):
|
| 43 |
+
shares = solve("money_split", x)
|
| 44 |
+
self.assertEqual(sum(shares), x["amount"])
|
| 45 |
+
self.assertTrue(all(v >= 0 for v in shares))
|
| 46 |
+
|
| 47 |
+
def test_knapsack_against_exhaustive_subsets(self):
|
| 48 |
+
for x in generated_inputs("knapsack", count=50):
|
| 49 |
+
best = max(
|
| 50 |
+
sum(item["value"] for i, item in enumerate(x["items"]) if mask >> i & 1)
|
| 51 |
+
for mask in range(1 << len(x["items"]))
|
| 52 |
+
if sum(
|
| 53 |
+
item["weight"] for i, item in enumerate(x["items"]) if mask >> i & 1
|
| 54 |
+
)
|
| 55 |
+
<= x["capacity"]
|
| 56 |
+
)
|
| 57 |
+
self.assertEqual(solve("knapsack", x), best)
|
| 58 |
+
|
| 59 |
+
def test_shortest_path_against_bellman_ford(self):
|
| 60 |
+
for x in generated_inputs("shortest_path", count=50):
|
| 61 |
+
d = {n: float("inf") for n in x["nodes"]}
|
| 62 |
+
d[x["start"]] = 0
|
| 63 |
+
for _ in x["nodes"]:
|
| 64 |
+
for a, b, w in x["edges"]:
|
| 65 |
+
d[b] = min(d[b], d[a] + w)
|
| 66 |
+
expected = {k: v if v != float("inf") else None for k, v in d.items()}
|
| 67 |
+
self.assertEqual(solve("shortest_path", x), expected)
|
| 68 |
+
|
| 69 |
+
def test_factorization_reconstructs_input(self):
|
| 70 |
+
for x in generated_inputs("prime_factors", count=100):
|
| 71 |
+
product = 1
|
| 72 |
+
for p, exponent in solve("prime_factors", x):
|
| 73 |
+
self.assertTrue(all(p % d for d in range(2, int(p**0.5) + 1)))
|
| 74 |
+
product *= p**exponent
|
| 75 |
+
self.assertEqual(product, x["number"])
|
| 76 |
+
|
| 77 |
+
def test_base_conversion_roundtrip(self):
|
| 78 |
+
for x in generated_inputs("base_convert", count=100):
|
| 79 |
+
self.assertEqual(
|
| 80 |
+
int(solve("base_convert", x), x["to_base"]), int(x["digits"])
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def test_sequence_script_reconstructs_both_inputs(self):
|
| 84 |
+
for x in generated_inputs("sequence_diff", count=100):
|
| 85 |
+
result = solve("sequence_diff", x)
|
| 86 |
+
self.assertEqual([v for op, v in result if op != "insert"], x["a"])
|
| 87 |
+
self.assertEqual([v for op, v in result if op != "delete"], x["b"])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class ServiceTests(unittest.TestCase):
|
| 91 |
+
def setUp(self):
|
| 92 |
+
self.s = Service("word_frequency", "max")
|
| 93 |
+
|
| 94 |
+
def call(self, op, **kwargs):
|
| 95 |
+
return self.s.request(dict(op=op, **kwargs))
|
| 96 |
+
|
| 97 |
+
def test_revisions_and_failed_cas(self):
|
| 98 |
+
self.assertEqual(
|
| 99 |
+
self.call("put", key="a", value=None),
|
| 100 |
+
{"ok": True, "result": {"key": "a", "revision": 1}},
|
| 101 |
+
)
|
| 102 |
+
self.assertEqual(
|
| 103 |
+
self.call("delete", key="missing", if_revision=0),
|
| 104 |
+
{"ok": False, "error": "conflict"},
|
| 105 |
+
)
|
| 106 |
+
self.assertEqual(
|
| 107 |
+
self.call("get", key="a")["result"],
|
| 108 |
+
{"key": "a", "value": None, "revision": 1},
|
| 109 |
+
)
|
| 110 |
+
self.assertEqual(self.call("status")["result"], {"revision": 1, "size": 1})
|
| 111 |
+
|
| 112 |
+
def test_batch_rollback_and_revision_reuse(self):
|
| 113 |
+
self.assertEqual(
|
| 114 |
+
self.call(
|
| 115 |
+
"batch",
|
| 116 |
+
commands=[
|
| 117 |
+
{"op": "put", "key": "a", "value": 1},
|
| 118 |
+
{"op": "get", "key": "bad"},
|
| 119 |
+
],
|
| 120 |
+
),
|
| 121 |
+
{"ok": False, "error": "not_found"},
|
| 122 |
+
)
|
| 123 |
+
self.assertEqual(self.call("status")["result"], {"revision": 0, "size": 0})
|
| 124 |
+
self.assertEqual(self.call("history")["result"], [])
|
| 125 |
+
self.assertEqual(self.call("put", key="b", value=2)["result"]["revision"], 1)
|
| 126 |
+
|
| 127 |
+
def test_nested_commit_outer_rollback(self):
|
| 128 |
+
self.call("begin")
|
| 129 |
+
self.call("put", key="a", value=1)
|
| 130 |
+
self.call("begin")
|
| 131 |
+
self.call("put", key="b", value=2)
|
| 132 |
+
self.assertEqual(self.call("commit")["result"], {"depth": 1})
|
| 133 |
+
self.assertEqual(self.call("rollback")["result"], {"depth": 0})
|
| 134 |
+
self.assertEqual(self.call("list")["result"], [])
|
| 135 |
+
self.assertEqual(self.call("history")["result"], [])
|
| 136 |
+
|
| 137 |
+
def test_idempotent_request_checks_cache_before_cas(self):
|
| 138 |
+
first = self.call("put", key="a", value=1, token="t", if_revision=0)
|
| 139 |
+
self.assertEqual(
|
| 140 |
+
self.call("put", key="a", value=1, token="t", if_revision=0), first
|
| 141 |
+
)
|
| 142 |
+
self.assertEqual(self.call("status")["result"]["revision"], 1)
|
| 143 |
+
self.assertEqual(
|
| 144 |
+
self.call("put", key="a", value=2, token="t"),
|
| 145 |
+
{"ok": False, "error": "idempotency_conflict"},
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def test_failed_and_rolled_back_tokens_forgotten(self):
|
| 149 |
+
self.call("delete", key="a", token="t")
|
| 150 |
+
self.assertTrue(self.call("put", key="a", value=1, token="t")["ok"])
|
| 151 |
+
self.call("begin")
|
| 152 |
+
self.call("put", key="b", value=2, token="u")
|
| 153 |
+
self.call("rollback")
|
| 154 |
+
self.assertTrue(self.call("put", key="b", value=3, token="u")["ok"])
|
| 155 |
+
|
| 156 |
+
def test_evaluate_is_read_only(self):
|
| 157 |
+
self.call("put", key="a", value={"text": "x x"})
|
| 158 |
+
self.assertEqual(
|
| 159 |
+
self.call("evaluate", key="a")["result"], [{"word": "x", "count": 2}]
|
| 160 |
+
)
|
| 161 |
+
self.assertEqual(self.call("get", key="a")["result"]["value"], {"text": "x x"})
|
| 162 |
+
self.assertEqual(self.call("status")["result"]["revision"], 1)
|
| 163 |
+
|
| 164 |
+
def test_scan_pages(self):
|
| 165 |
+
for key in ["c", "a", "b"]:
|
| 166 |
+
self.call("put", key=key, value=key)
|
| 167 |
+
self.assertEqual(
|
| 168 |
+
self.call("scan", limit=1)["result"],
|
| 169 |
+
{"items": [{"key": "a", "value": "a", "revision": 2}], "next": "a"},
|
| 170 |
+
)
|
| 171 |
+
self.assertEqual(self.call("scan", after="b", limit=1)["result"]["next"], None)
|
| 172 |
+
self.assertEqual(
|
| 173 |
+
self.call("scan", limit=0)["result"], {"items": [], "next": None}
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def test_outer_commit_is_durable_and_open_transaction_is_not(self):
|
| 177 |
+
with tempfile.TemporaryDirectory() as d:
|
| 178 |
+
self.s = Service("word_frequency", "max", d)
|
| 179 |
+
self.call("begin")
|
| 180 |
+
self.call("put", key="a", value={"text": "saved"}, token="t")
|
| 181 |
+
self.call("commit")
|
| 182 |
+
self.call("begin")
|
| 183 |
+
self.call("delete", key="a")
|
| 184 |
+
reloaded = Service("word_frequency", "max", d)
|
| 185 |
+
self.assertEqual(
|
| 186 |
+
reloaded.request({"op": "get", "key": "a"})["result"]["revision"], 1
|
| 187 |
+
)
|
| 188 |
+
self.assertEqual(reloaded.state["tokens"].keys(), {"t"})
|
| 189 |
+
self.assertEqual(len(reloaded.state["history"]), 1)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class DatasetTests(unittest.TestCase):
|
| 193 |
+
def test_exact_counts_unique_ids_and_manifest(self):
|
| 194 |
+
rows = list(load_tasks())
|
| 195 |
+
self.assertEqual(len(rows), 260)
|
| 196 |
+
self.assertEqual(len({r["task_id"] for r in rows}), 260)
|
| 197 |
+
for tier in ["easy", "intermediate", "hard", "max"]:
|
| 198 |
+
self.assertEqual(sum(r["subset"] == tier for r in rows), 65)
|
| 199 |
+
manifest = json.loads((DATA / "manifest.json").read_text())
|
| 200 |
+
for name, digest in manifest["sha256"].items():
|
| 201 |
+
self.assertEqual(
|
| 202 |
+
hashlib.sha256((DATA / name).read_bytes()).hexdigest(), digest
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
def test_build_reproducible(self):
|
| 206 |
+
with tempfile.TemporaryDirectory() as d:
|
| 207 |
+
build(d)
|
| 208 |
+
for file in DATA.iterdir():
|
| 209 |
+
if file.suffix in {".json", ".jsonl"}:
|
| 210 |
+
self.assertEqual(
|
| 211 |
+
file.read_bytes(), (Path(d) / file.name).read_bytes(), file.name
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def test_public_examples_in_prompt_and_nonempty_acceptance(self):
|
| 215 |
+
for row in load_tasks():
|
| 216 |
+
self.assertTrue(json.loads(row["public_tests"]))
|
| 217 |
+
traces = json.loads(row["acceptance_tests"])
|
| 218 |
+
self.assertTrue(traces)
|
| 219 |
+
self.assertEqual(
|
| 220 |
+
row["num_assertions"],
|
| 221 |
+
sum(len(s["expected"]) for t in traces for s in t["sessions"]),
|
| 222 |
+
)
|
| 223 |
+
for trace in traces:
|
| 224 |
+
for session in trace["sessions"]:
|
| 225 |
+
self.assertTrue(session["requests"])
|
| 226 |
+
self.assertEqual(len(session["requests"]), len(session["expected"]))
|
| 227 |
+
|
| 228 |
+
def test_scoring_uses_full_denominator_and_rejects_smoke(self):
|
| 229 |
+
row = next(load_tasks("easy"))
|
| 230 |
+
report = {"task_id": row["task_id"], "subset": "easy", "resolved": True}
|
| 231 |
+
self.assertEqual(
|
| 232 |
+
summarize([report])["subsets"]["easy"]["resolution_rate"], 1 / 65
|
| 233 |
+
)
|
| 234 |
+
with self.assertRaises(ValueError):
|
| 235 |
+
summarize([report, report])
|
| 236 |
+
with self.assertRaises(ValueError):
|
| 237 |
+
summarize([dict(report, evaluation_scope="public")])
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class RunnerTests(unittest.TestCase):
|
| 241 |
+
def setUp(self):
|
| 242 |
+
self.temporary = tempfile.TemporaryDirectory()
|
| 243 |
+
self.root = Path(self.temporary.name)
|
| 244 |
+
self.project, self.state = self.root / "project", self.root / "state"
|
| 245 |
+
self.project.mkdir()
|
| 246 |
+
self.state.mkdir()
|
| 247 |
+
self.session = {
|
| 248 |
+
"requests": [{"op": "status"}],
|
| 249 |
+
"expected": [{"ok": True, "result": 7}],
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
def tearDown(self):
|
| 253 |
+
self.temporary.cleanup()
|
| 254 |
+
|
| 255 |
+
def run_code(self, code, timeout=1):
|
| 256 |
+
(self.project / "main.py").write_text(code)
|
| 257 |
+
return run_session(self.project, self.state, self.session, timeout=timeout)
|
| 258 |
+
|
| 259 |
+
def test_response_and_clean_exit(self):
|
| 260 |
+
self.assertTrue(
|
| 261 |
+
self.run_code(
|
| 262 |
+
'import sys\nfor line in sys.stdin:\n print(\'{"ok":true,"result":7}\', flush=True)\n'
|
| 263 |
+
)["passed"]
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
def test_rejects_wrong_boolean_numeric_type(self):
|
| 267 |
+
self.assertFalse(equal(True, 1))
|
| 268 |
+
self.assertFalse(equal(1, True))
|
| 269 |
+
self.assertFalse(equal(float("nan"), 1))
|
| 270 |
+
self.assertTrue(equal(1.0, 1))
|
| 271 |
+
self.assertFalse(equal(10**30, 10**30 + 1))
|
| 272 |
+
|
| 273 |
+
def test_timeout_without_output(self):
|
| 274 |
+
self.assertFalse(
|
| 275 |
+
self.run_code("import time\ntime.sleep(20)", timeout=0.2)["passed"]
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
def test_failure_on_nonzero_exit(self):
|
| 279 |
+
self.assertFalse(
|
| 280 |
+
self.run_code(
|
| 281 |
+
'import sys\nsys.stdin.readline()\nprint(\'{"ok":true,"result":7}\',flush=True)\nsys.exit(1)'
|
| 282 |
+
)["passed"]
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
def test_rejects_extra_stdout(self):
|
| 286 |
+
self.assertFalse(
|
| 287 |
+
self.run_code(
|
| 288 |
+
'import sys\nsys.stdin.readline()\nprint(\'{"ok":true,"result":7}\')\nprint("extra",flush=True)'
|
| 289 |
+
)["passed"]
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
def test_output_flood_is_bounded(self):
|
| 293 |
+
self.assertFalse(
|
| 294 |
+
self.run_code('import os\nwhile True: os.write(1,b"x"*65536)')["passed"]
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
def test_stderr_flood_does_not_deadlock(self):
|
| 298 |
+
self.assertTrue(
|
| 299 |
+
self.run_code(
|
| 300 |
+
'import os,sys\nfor line in sys.stdin:\n os.write(2,b"x"*200000)\n print(\'{"ok":true,"result":7}\',flush=True)'
|
| 301 |
+
)["passed"]
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def test_symlinks_rejected(self):
|
| 305 |
+
(self.project / "main.py").symlink_to("/etc/passwd")
|
| 306 |
+
target = self.root / "copied"
|
| 307 |
+
target.mkdir()
|
| 308 |
+
with self.assertRaises(ValueError):
|
| 309 |
+
copy_project(self.project, target)
|
| 310 |
+
|
| 311 |
+
def test_invalid_submission_is_failed_rather_than_infrastructure_error(self):
|
| 312 |
+
(self.project / "main.py").symlink_to("/etc/passwd")
|
| 313 |
+
result = evaluate(next(load_tasks("easy")), self.project)
|
| 314 |
+
self.assertFalse(result["resolved"])
|
| 315 |
+
self.assertIn("symlink", result["reason"])
|
| 316 |
+
|
| 317 |
+
def test_reference_max_restart_and_empty_submission(self):
|
| 318 |
+
row = next(load_tasks("max"))
|
| 319 |
+
export_reference(row["family"], "max", self.project)
|
| 320 |
+
result = evaluate(row, self.project)
|
| 321 |
+
self.assertTrue(result["passed"], result)
|
| 322 |
+
empty = self.root / "empty"
|
| 323 |
+
empty.mkdir()
|
| 324 |
+
self.assertFalse(evaluate(row, empty)["passed"])
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
unittest.main()
|
tools/publish_hf.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish reviewed benchmark artifacts, never local credentials or workspaces."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
from huggingface_hub import HfApi
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument("--repo", default="klein-ml/klein-code-bench")
|
| 14 |
+
args = parser.parse_args()
|
| 15 |
+
root = Path(__file__).resolve().parents[1]
|
| 16 |
+
summary = json.loads((root / "validation-summary.json").read_text())
|
| 17 |
+
digest = hashlib.sha256(
|
| 18 |
+
(root / "klein_code_bench/data/manifest.json").read_bytes()
|
| 19 |
+
).hexdigest()
|
| 20 |
+
if (
|
| 21 |
+
not summary["passed"]
|
| 22 |
+
or summary["tasks"] != 260
|
| 23 |
+
or summary["manifest_sha256"] != digest
|
| 24 |
+
):
|
| 25 |
+
raise SystemExit(
|
| 26 |
+
"Full validation of the current dataset is required before publishing"
|
| 27 |
+
)
|
| 28 |
+
api = HfApi()
|
| 29 |
+
api.create_repo(
|
| 30 |
+
repo_id=args.repo, repo_type="dataset", private=False, exist_ok=True
|
| 31 |
+
)
|
| 32 |
+
result = api.upload_folder(
|
| 33 |
+
repo_id=args.repo,
|
| 34 |
+
repo_type="dataset",
|
| 35 |
+
folder_path=str(root),
|
| 36 |
+
allow_patterns=[
|
| 37 |
+
"README.md",
|
| 38 |
+
"LICENSE",
|
| 39 |
+
"pyproject.toml",
|
| 40 |
+
".gitignore",
|
| 41 |
+
".github/workflows/*.yml",
|
| 42 |
+
"klein_code_bench/*.py",
|
| 43 |
+
"klein_code_bench/reference/*.py",
|
| 44 |
+
"klein_code_bench/data/*.jsonl",
|
| 45 |
+
"klein_code_bench/data/*.json",
|
| 46 |
+
"tests/*.py",
|
| 47 |
+
"docs/*.md",
|
| 48 |
+
"tools/*.py",
|
| 49 |
+
"dist/*.whl",
|
| 50 |
+
"validation-summary.json",
|
| 51 |
+
],
|
| 52 |
+
commit_message="Release Klein-Code-Bench v0.1.0: 260 validated project-generation tasks",
|
| 53 |
+
)
|
| 54 |
+
print(result.oid)
|
| 55 |
+
print(f"https://huggingface.co/datasets/{args.repo}")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
main()
|
validation-summary.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"passed": true,
|
| 3 |
+
"tasks": 260,
|
| 4 |
+
"reference_passes": 260,
|
| 5 |
+
"empty_rejected": 260,
|
| 6 |
+
"assertions": 33685,
|
| 7 |
+
"manifest_sha256": "a8b5fe2378da63c1fac3a093b7a762d8793e9573fc2025bfb5a8de4e8bcd838b",
|
| 8 |
+
"unit_tests": {
|
| 9 |
+
"passed": 30,
|
| 10 |
+
"failed": 0
|
| 11 |
+
},
|
| 12 |
+
"package_smoke_test": "passed: clean wheel install, all 260 bundled tasks",
|
| 13 |
+
"python_version": "3.14.7",
|
| 14 |
+
"platform": "Linux",
|
| 15 |
+
"purpose": "Evaluator/reference validation, not a model score."
|
| 16 |
+
}
|