Publish SmolScript 0.1.0 execution-unverified candidate
Browse files2000 generated examples; exact language/difficulty allocation, isolated runners and Hugging Face evaluation. Static audit passes. Full reference and negative-control execution remains unverified because a Docker/Podman sandbox is unavailable.
- .gitignore +5 -0
- LICENSE +21 -0
- README.md +110 -0
- SHA256SUMS +38 -0
- data/smolscript.jsonl +0 -0
- data/smolscript.parquet +0 -0
- evaluate.py +89 -0
- examples/local-test-report.json +25 -0
- examples/result-format.json +6 -0
- generators/__init__.py +0 -0
- generators/build.py +114 -0
- generators/code.py +169 -0
- generators/specs.py +136 -0
- generators/web.py +144 -0
- manifest.json +28 -0
- metrics.py +18 -0
- private_tests/hidden.jsonl +0 -0
- pyproject.toml +14 -0
- references/solutions.jsonl +0 -0
- runners/__init__.py +5 -0
- runners/c_runner.py +5 -0
- runners/common.py +61 -0
- runners/cpp_runner.py +5 -0
- runners/csharp_runner.py +5 -0
- runners/css_runner.py +5 -0
- runners/html_runner.py +5 -0
- runners/javascript_runner.py +6 -0
- runners/lua_runner.py +5 -0
- runners/protocol.py +46 -0
- runners/python_runner.py +5 -0
- runners/rust_runner.py +5 -0
- runners/sandbox.py +46 -0
- sandbox/Dockerfile +14 -0
- sandbox/worker.py +143 -0
- tests/test_core.py +48 -0
- validate.py +58 -0
- validation_report.json +93 -0
- validators/__init__.py +0 -0
- validators/dataset.py +69 -0
.gitignore
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.venv/
|
| 4 |
+
results*.json
|
| 5 |
+
*.lock
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 dotlabs
|
| 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,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: SmolScript
|
| 3 |
+
license: mit
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
tags:
|
| 7 |
+
- code
|
| 8 |
+
- code-generation
|
| 9 |
+
- evaluation
|
| 10 |
+
- multilingual
|
| 11 |
+
configs:
|
| 12 |
+
- config_name: default
|
| 13 |
+
data_files:
|
| 14 |
+
- split: test
|
| 15 |
+
path: data/smolscript.parquet
|
| 16 |
+
---
|
| 17 |
+
# SmolScript
|
| 18 |
+
|
| 19 |
+
An original execution-based benchmark of basic programming for 25M–350M parameter language models. Version **0.1.0**, **2,000 examples**, nine languages, MIT license.
|
| 20 |
+
|
| 21 |
+
**Release status: execution-unverified candidate.** All 2,000 records have been generated and statically validated. No complete reference execution run or model baseline is claimed. The authoring environment has no Docker/Podman daemon; all 2,000 reference solutions and their negative controls still require execution in the supplied sandbox image. See `validation_report.json` for the machine-readable audit. Do not treat this candidate as a validated leaderboard release until `python validate.py` succeeds.
|
| 22 |
+
|
| 23 |
+
## Composition
|
| 24 |
+
|
| 25 |
+
| Language | Easy | Medium | Moderate | Total |
|
| 26 |
+
|---|---:|---:|---:|---:|
|
| 27 |
+
| Python | 150 | 75 | 25 | 250 |
|
| 28 |
+
| JavaScript | 150 | 75 | 25 | 250 |
|
| 29 |
+
| HTML | 120 | 60 | 20 | 200 |
|
| 30 |
+
| CSS | 120 | 60 | 20 | 200 |
|
| 31 |
+
| C++ | 135 | 68 | 22 | 225 |
|
| 32 |
+
| C | 135 | 68 | 22 | 225 |
|
| 33 |
+
| Lua | 120 | 60 | 20 | 200 |
|
| 34 |
+
| C# | 135 | 67 | 23 | 225 |
|
| 35 |
+
| Rust | 135 | 67 | 23 | 225 |
|
| 36 |
+
| **Total** | **1,200** | **600** | **200** | **2,000** |
|
| 37 |
+
|
| 38 |
+
Programming tasks cover arithmetic and conditions, ASCII string transformations, filtered collection reductions, frequency tables, and short combinations of basic operations. JavaScript includes 20 browser DOM/event tasks. HTML tasks check elements, attributes, text, and nesting. CSS tasks check computed properties, selector scope, unaffected distractors, flex row/column geometry, and responsive breakpoints. No generated solution uses external packages.
|
| 39 |
+
|
| 40 |
+
Tasks are original compositions from an explicit operation grammar, not scraped HumanEval/MBPP/MultiPL-E questions. Variants change operations and observable behavior, not just names or numbers. Shared tasks across programming languages are intentional translations for comparative coverage. Within each language, deterministic behavioral probe fingerprints reject equivalent programming tasks. Web tasks have unique structural specs. Trigram similarity flags are reported; the seven retained pairs differ in count versus sum and have distinct behavior. This is a finite behavioral/structural audit, not a mathematical proof of semantic uniqueness. Difficulty labels are design judgments; empirical calibration on small models remains future work.
|
| 41 |
+
|
| 42 |
+
## Install and build the offline sandbox
|
| 43 |
+
|
| 44 |
+
Requires Python 3.11+, Docker or Podman on Linux (or Docker Desktop's Linux VM), approximately 2 GB memory per concurrent container, and disk space for Chromium and compilers. GPU is optional for generation. All runtime downloads occur during image construction.
|
| 45 |
+
|
| 46 |
+
```sh
|
| 47 |
+
python -m venv .venv
|
| 48 |
+
. .venv/bin/activate
|
| 49 |
+
pip install -e '.[inference]'
|
| 50 |
+
docker build -f sandbox/Dockerfile -t smolscript-runtime:0.1.0 .
|
| 51 |
+
python validate.py
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
The image supplies CPython, Node.js, GCC/G++ (C11/C++17), Lua 5.4, Mono C#, Rust (edition 2021), and Playwright Chromium. Candidate functions use basic C# features supported by Mono. The base Playwright image and Python browser dependencies are pinned. OS compiler packages are resolved at build time; preserve/export the built image for exact runtime reproduction. Every evaluation records the immutable local image ID and available registry digests. Rebuilding later may produce a different image.
|
| 55 |
+
|
| 56 |
+
Containers run as UID 1000 with network disabled, a read-only root, no Linux capabilities, no privilege escalation, 2 GB memory/swap ceiling, one CPU, 128 processes, bounded temporary filesystems, CPU/wall timeouts, and bounded output. Compilation has a separate 30-second limit; each program test has a three-second CPU limit plus a one-second wall allowance. Browser operations have three-second timeouts and a container supervisor limit. Candidates have access only to their code, fixture, and input values; expected answers remain in the host scorer. No host home, Docker socket, credentials, or full dataset is mounted. There is no host-execution fallback. Containers are the required isolation boundary; use a dedicated worker for adversarial submissions.
|
| 57 |
+
|
| 58 |
+
The sandbox uses the documented [Docker resource and isolation options](https://docs.docker.com/reference/cli/docker/container/run/) and the [Playwright Python container image](https://playwright.dev/python/docs/docker). Evaluation requires no network after model/tokenizer weights and the image have been cached. To enforce offline Hugging Face loading, set `HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1`.
|
| 59 |
+
|
| 60 |
+
## Validate
|
| 61 |
+
|
| 62 |
+
```sh
|
| 63 |
+
python validate.py # Full reference + negative-control execution
|
| 64 |
+
python validate.py --static-only # Counts, uniqueness, oracle cases, hashes, Parquet
|
| 65 |
+
python -m unittest discover -s tests -v
|
| 66 |
+
python generators/build.py # Deterministically regenerate all artifacts
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
`validate.py` checks every reference against every hidden test and rejects a deliberately wrong solution for every task. For programming tasks it also checks a plausible near-miss mutation where the hidden inputs distinguish it (missing transformation stage, mapping, or filter). Failure stops validation with the task ID. Missing sandbox/runtime exits 2 and records unverified coverage. Static-only success never marks execution as passed. The reference ASTs for all 250 Python tasks are also parsed by the local unit suite.
|
| 70 |
+
|
| 71 |
+
## Evaluate a model
|
| 72 |
+
|
| 73 |
+
```sh
|
| 74 |
+
python evaluate.py --model HuggingFaceTB/SmolLM2-135M --output results.json
|
| 75 |
+
python evaluate.py --model HuggingFaceTB/SmolLM2-135M --output results.json --resume
|
| 76 |
+
python evaluate.py --model HuggingFaceTB/SmolLM2-135M --language python rust --difficulty easy --output subset.json
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
One fixed completion prompt (`smolscript-completion-v1`), one generation, seed 0, greedy decoding, no beam search, and a fixed 384-token output cap. The same completion template is used for base and instruction models; no model-specific chat template is applied. The model revision resolves to an immutable commit and is retained on resume. Use `--revision SHA` for an explicit pin. Prompts contain only instructions, signature, input domain, and web fixture/base styles. References, public examples, hidden tests, and expected answers are never sent to the model.
|
| 80 |
+
|
| 81 |
+
Existing files require `--resume`. Settings, dataset/runner hashes, image ID and selected IDs must match. Completed task results are checkpointed atomically; a generated response is saved before execution, so an execution interruption can reuse it. Partial runs never receive a full score. Use one process per output path (a file lock enforces this). Context overflow is an explicit failure; input prompts are never silently truncated.
|
| 82 |
+
|
| 83 |
+
For externally generated code, create JSONL records `{"id":"...","code":"..."}` and use:
|
| 84 |
+
|
| 85 |
+
```sh
|
| 86 |
+
python evaluate.py --predictions predictions.jsonl --output results.json
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
Raw code or a single fenced code block is accepted. Multiple or unfinished fences are rejected. Function tasks receive fixed stdin/stdout wrappers. Compiled languages compile once per task, then run a fresh process per test. HTML is parsed with html5lib and checked in Chromium with document scripts disabled. CSS is parsed with tinycss2 and tested against a fixed fixture at the specified widths. Browser tests assert DOM/computed styles and geometry, without image similarity.
|
| 90 |
+
|
| 91 |
+
## Metrics
|
| 92 |
+
|
| 93 |
+
All metrics are on **0–100**. A task passes only when every hidden assertion passes. With one generation, per-language accuracy is Pass@1. **SmolScript Score and overall Pass@1 are the macro-average of the nine language accuracies.** Syntax Success is likewise macro-averaged across languages and measures parse/compile success, separately from behavior. `micro_accuracy` is an explicitly secondary count-weighted diagnostic. No score is chance-adjusted.
|
| 94 |
+
|
| 95 |
+
Filters produce `filtered_macro_score` over selected languages rather than the official nine-language `smolscript_score`. Per-test outputs and pass/fail results are retained. Build failures count as syntax failures; runtime failures count as behavioral failures. Sandbox infrastructure errors stop the run instead of assigning a score.
|
| 96 |
+
|
| 97 |
+
`examples/result-format.json` illustrates output structure using explicitly synthetic numbers; it is not a model result.
|
| 98 |
+
|
| 99 |
+
## Files and Hugging Face
|
| 100 |
+
|
| 101 |
+
`data/smolscript.jsonl` and `data/smolscript.parquet` contain the public test examples. To keep one consistent Parquet schema across modalities, `tests` and `metadata` are JSON strings in Parquet; JSONL uses native JSON values. Decode them with `json.loads` after loading through Hugging Face Datasets. Public `reference_solution` is null; full references are in `references/solutions.jsonl`. Hidden tests live in `private_tests/hidden.jsonl`, outside the public dataset split. These evaluation-only files are published for independent auditing; they are **not access-controlled secrets**. Never include them in model context. Offline evaluation requires downloading the complete repository, including these files.
|
| 102 |
+
|
| 103 |
+
```python
|
| 104 |
+
from datasets import load_dataset
|
| 105 |
+
import json
|
| 106 |
+
rows = load_dataset('dotlabs/smolscript', split='test')
|
| 107 |
+
metadata = json.loads(rows[0]['metadata'])
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
The generator, runners and audit reports are included in this repository. Record the Hugging Face repository commit, manifest checksums, generation settings, dependency versions and image ID with any reported result.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ff73ee904edc9381bd1ea24847e41c6176aec22ba4b63321e8354562f24ba5ce .gitignore
|
| 2 |
+
8719af4397a8387b8f04140613943545f8ecd90f06529dcab9e68a94927d13fe LICENSE
|
| 3 |
+
24908849b2c3cac77e1c0cc1aa82b943c4f8c377bc3930b526f0e4f49e1fa7de README.md
|
| 4 |
+
1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9 data/smolscript.jsonl
|
| 5 |
+
7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9 data/smolscript.parquet
|
| 6 |
+
9bd849e38e3e50d19fd2c8ccfae05b7c54060f8d151b832b2bc37c14ae8714c2 evaluate.py
|
| 7 |
+
b6a465089448e1c2eb7f26c981a1ad3e962d73a0433a337d4e781f4ca9525b65 examples/local-test-report.json
|
| 8 |
+
713855348ffc53f49b03a0df47b67294fe2d3593054636eec12b9f184fb3534e examples/result-format.json
|
| 9 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 generators/__init__.py
|
| 10 |
+
eeb947e9704931e5b23ed79aee180e4dd49708f9294d7481f51c7da2f5c33e7e generators/build.py
|
| 11 |
+
e1cf493b995f15470c56c097b73e7403ae06f74f5d12cbb3a43ce522514d8577 generators/code.py
|
| 12 |
+
60be0a7ac6fcd3dfd8b663fc19af189aba3acfdd923219dc6cc1972033380240 generators/specs.py
|
| 13 |
+
ae6a8d5109035027b71df7eb7297e7c0b811a4a98c649e1729a3fe2a2c09c5bf generators/web.py
|
| 14 |
+
62a01609810b5c488f4a5abe284063b41b780c382046a9da7cc2a6ca755b5488 manifest.json
|
| 15 |
+
6bac32e6045f1788e8b68e96ff6ee41f1b2152cca1b17de24be405025f294930 metrics.py
|
| 16 |
+
2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac private_tests/hidden.jsonl
|
| 17 |
+
a2de1bc75c21817ba1883ee4c5aa04b60a0f4288f3f45893e1c7e71e435f1997 pyproject.toml
|
| 18 |
+
84d3411fe45189c62ae50fbd31c1dc5795bc099d5037c3a817e3d280f6097e83 references/solutions.jsonl
|
| 19 |
+
5a3cb2a82cf3784c41fc9f9046fe6806d5bbe7ce8ae415a9ed1c373abcfe7826 runners/__init__.py
|
| 20 |
+
965bc9e3dabfc3fba4b745994b43118c456be477edcc34a3ba929ebf39e19ce9 runners/c_runner.py
|
| 21 |
+
47eaf32ac4ce76fcfbd01d515f6befccfcd2bf6c277447a73e8b7b58fa7e96f8 runners/common.py
|
| 22 |
+
17c846633f3730669790ee2f11fc93661648eedc950c96d47996d0db4514672b runners/cpp_runner.py
|
| 23 |
+
e87545f911f6f25238b1f84ed0ac1602900676b77cb3dd5f1560cd62e0b931e4 runners/csharp_runner.py
|
| 24 |
+
96e542ceb76e18759aa8f19fd87beef3612e535f7b9f04944a6bdf1e2fddffec runners/css_runner.py
|
| 25 |
+
3a02716d96a0061567f50514b5e5df3b30812ed21b524f772ebcb12de915f585 runners/html_runner.py
|
| 26 |
+
21c05c048f2cfcc6e263645b6322527cd8869e6530f3bc8dc11aaf54bb777f5e runners/javascript_runner.py
|
| 27 |
+
2941363382d517261153a7d38a9f49c63fd2dbb4c52b851bc0d1726f8196f4e9 runners/lua_runner.py
|
| 28 |
+
217be73aeb9055bfcf897d4cc72eb7b06092b9da96202ac2eab95a26d9302b56 runners/protocol.py
|
| 29 |
+
efabd7a4b829eb917116a2f51358a8fa8056370dbb57f6b6a9646c1cd342ffc5 runners/python_runner.py
|
| 30 |
+
63514e35b2687742ea6453e15d089da5a6cb4ab57ca0100da6189b187511ecf7 runners/rust_runner.py
|
| 31 |
+
824119581e0bf1c913059fdf506c26494c9aa2f65f718f08630ff5fe74779ff3 runners/sandbox.py
|
| 32 |
+
4fb1552346d86503372e6762f3ddcb0fc7e7e0be2cc1209f419b7c5e37aeccdc sandbox/Dockerfile
|
| 33 |
+
39adc44592af2d485b8755baa0b90b94e987b8a76b37dd70cc7c879285b6faaa sandbox/worker.py
|
| 34 |
+
eb5c448ef50f2a7f4f08be8d9b6a0d9719180c6c144b56b8514803312338902b tests/test_core.py
|
| 35 |
+
44d0be27ea6bb4050d2e6cfdcc0926400999e8cea3f62ed0bba5303231a424ab validate.py
|
| 36 |
+
cb6e2f58736c45a63635c574ed989ff7910ad2cb81ad59f8a444594c78066ab4 validation_report.json
|
| 37 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 validators/__init__.py
|
| 38 |
+
c21a19dd9e2b362c6634eac0334765d0b6edf0a567bba61a234b3d40bdb13612 validators/dataset.py
|
data/smolscript.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/smolscript.parquet
ADDED
|
Binary file (63.4 kB). View file
|
|
|
evaluate.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One deterministic generation per task, followed by isolated execution."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import sys
|
| 7 |
+
from validators.dataset import load
|
| 8 |
+
from runners import get_runner,LANGUAGES
|
| 9 |
+
from runners.common import extract_code
|
| 10 |
+
from runners.sandbox import Sandbox
|
| 11 |
+
from metrics import aggregate
|
| 12 |
+
ROOT=Path(__file__).resolve().parent
|
| 13 |
+
PROMPT_VERSION='smolscript-completion-v1'
|
| 14 |
+
|
| 15 |
+
def prompt(row):
|
| 16 |
+
# Only these public fields reach the model. No tests, answers or references.
|
| 17 |
+
fixture=row['metadata'].get('fixture','');base=row['metadata'].get('base_css','')
|
| 18 |
+
return ('Write code for the following task. Use the standard library only. Return code only.\n'
|
| 19 |
+
+row['prompt']+'\n'+row['output_format']+'\n'+(row['metadata'].get('input_domain') or '')
|
| 20 |
+
+('\nHTML fixture:\n'+fixture if fixture else '')+('\nExisting CSS:\n'+base if base else '')+'\nCode:\n')
|
| 21 |
+
|
| 22 |
+
def save(path,value):
|
| 23 |
+
path.parent.mkdir(parents=True,exist_ok=True);temp=path.with_suffix('.tmp');temp.write_text(json.dumps(value,indent=2,allow_nan=False)+'\n');temp.replace(path)
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--model');p.add_argument('--revision',default='main');p.add_argument('--output',type=Path,required=True)
|
| 27 |
+
p.add_argument('--language',nargs='+',choices=LANGUAGES);p.add_argument('--difficulty',nargs='+',choices=('easy','medium','moderate'))
|
| 28 |
+
p.add_argument('--resume',action='store_true');p.add_argument('--predictions',type=Path,help='JSONL with id and code; bypass model inference')
|
| 29 |
+
p.add_argument('--image',default='smolscript-runtime:0.1.0');p.add_argument('--engine',default='docker');p.add_argument('--max-new-tokens',type=int,default=384);p.add_argument('--device',default='auto');a=p.parse_args()
|
| 30 |
+
if not a.model and not a.predictions:p.error('--model or --predictions required')
|
| 31 |
+
if a.max_new_tokens<1:p.error('--max-new-tokens must be positive')
|
| 32 |
+
sandbox=Sandbox(a.image,a.engine)
|
| 33 |
+
rows=[r for r in load(ROOT/'data/smolscript.jsonl') if (not a.language or r['language'] in a.language) and (not a.difficulty or r['difficulty'] in a.difficulty)]
|
| 34 |
+
hidden={r['id']:r for r in load(ROOT/'private_tests/hidden.jsonl')}
|
| 35 |
+
files=['data/smolscript.jsonl','private_tests/hidden.jsonl','evaluate.py','metrics.py']+[str(p.relative_to(ROOT)) for p in sorted((ROOT/'runners').glob('*.py'))]+['sandbox/worker.py']
|
| 36 |
+
fingerprint={f:hashlib.sha256((ROOT/f).read_bytes()).hexdigest() for f in files}
|
| 37 |
+
settings={'model':a.model,'requested_revision':a.revision,'language':a.language,'difficulty':a.difficulty,
|
| 38 |
+
'max_new_tokens':a.max_new_tokens,'prompt_version':PROMPT_VERSION,'dataset':fingerprint,'sandbox':sandbox.identity,
|
| 39 |
+
'predictions_sha':hashlib.sha256(a.predictions.read_bytes()).hexdigest() if a.predictions else None}
|
| 40 |
+
if a.output.exists() and not a.resume:p.error('Output exists; use --resume or a new path')
|
| 41 |
+
state=json.loads(a.output.read_text()) if a.output.exists() else {'settings':settings,'results':[],'complete':False}
|
| 42 |
+
if state['settings']!=settings:p.error('Resume settings mismatch')
|
| 43 |
+
if a.resume and not a.output.exists():p.error('Resume output missing')
|
| 44 |
+
# Lock the output across processes to prevent concurrent checkpoint overwrites.
|
| 45 |
+
import fcntl
|
| 46 |
+
lock=a.output.with_suffix(a.output.suffix+'.lock');lock.parent.mkdir(parents=True,exist_ok=True)
|
| 47 |
+
with lock.open('a') as stream:
|
| 48 |
+
fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
| 49 |
+
codes={}
|
| 50 |
+
if a.predictions:codes={r['id']:r['code'] for r in load(a.predictions)}
|
| 51 |
+
else:
|
| 52 |
+
import torch
|
| 53 |
+
from transformers import AutoTokenizer,AutoModelForCausalLM,AutoConfig
|
| 54 |
+
from huggingface_hub import HfApi
|
| 55 |
+
revision=state.get('resolved_revision') or HfApi().model_info(a.model,revision=a.revision).sha
|
| 56 |
+
state['resolved_revision']=revision
|
| 57 |
+
tokenizer=AutoTokenizer.from_pretrained(a.model,revision=revision)
|
| 58 |
+
model=AutoModelForCausalLM.from_pretrained(a.model,revision=revision,torch_dtype='auto',device_map=a.device)
|
| 59 |
+
model.eval();torch.manual_seed(0)
|
| 60 |
+
import importlib.metadata
|
| 61 |
+
state['environment']={'python':sys.version,'packages':{n:importlib.metadata.version(n) for n in ('torch','transformers','huggingface-hub')},'device':str(model.device)}
|
| 62 |
+
done={r['id'] for r in state['results']}
|
| 63 |
+
if len(done)!=len(state['results']) or done-set(r['id'] for r in rows):raise ValueError('Corrupt resume IDs')
|
| 64 |
+
save(a.output,state)
|
| 65 |
+
for row in rows:
|
| 66 |
+
if row['id'] in done:continue
|
| 67 |
+
if state.get('pending',{}).get('id')==row['id']:
|
| 68 |
+
text=state['pending']['generation']
|
| 69 |
+
elif a.predictions:
|
| 70 |
+
if row['id'] not in codes:raise ValueError('Missing prediction '+row['id'])
|
| 71 |
+
text=codes[row['id']]
|
| 72 |
+
else:
|
| 73 |
+
encoded=tokenizer(prompt(row),return_tensors='pt',return_token_type_ids=False).to(model.device)
|
| 74 |
+
native=getattr(model.config,'max_position_embeddings',getattr(model.config,'n_positions',4096))
|
| 75 |
+
if encoded['input_ids'].shape[1]+a.max_new_tokens>native:
|
| 76 |
+
raise ValueError('Insufficient context for fixed generation settings: '+row['id'])
|
| 77 |
+
with torch.inference_mode():out=model.generate(**encoded,max_new_tokens=a.max_new_tokens,do_sample=False,num_beams=1,pad_token_id=tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id)
|
| 78 |
+
text=tokenizer.decode(out[0,encoded['input_ids'].shape[1]:],skip_special_tokens=True)
|
| 79 |
+
state['pending']={'id':row['id'],'generation':text};save(a.output,state)
|
| 80 |
+
try:code=extract_code(text)
|
| 81 |
+
except ValueError as e:result={'passed':False,'syntax_success':False,'tests':[],'error':str(e)}
|
| 82 |
+
else:result=get_runner(row['language']).evaluate(row,code,hidden[row['id']],sandbox)
|
| 83 |
+
state['results'].append({'id':row['id'],'language':row['language'],'difficulty':row['difficulty'],'generation':text,**result})
|
| 84 |
+
state.pop('pending',None)
|
| 85 |
+
save(a.output,state);print(f"{len(state['results'])}/{len(rows)} {row['id']} {'PASS' if result['passed'] else 'FAIL'}",flush=True)
|
| 86 |
+
state['metrics']=aggregate(state['results'],[r['id'] for r in rows],full_run=not(a.language or a.difficulty));state['complete']=True;save(a.output,state)
|
| 87 |
+
print(json.dumps(state['metrics'],indent=2))
|
| 88 |
+
|
| 89 |
+
if __name__=='__main__':main()
|
examples/local-test-report.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"unit_tests": {
|
| 3 |
+
"passed": 8,
|
| 4 |
+
"command": "python -m unittest discover -s tests -q"
|
| 5 |
+
},
|
| 6 |
+
"python_reference_ast_parse": 250,
|
| 7 |
+
"candidate_execution_on_host": false,
|
| 8 |
+
"reference_execution": {
|
| 9 |
+
"verified": 0,
|
| 10 |
+
"unverified": 2000
|
| 11 |
+
},
|
| 12 |
+
"unverified_by_language": {
|
| 13 |
+
"python": 250,
|
| 14 |
+
"javascript": 250,
|
| 15 |
+
"html": 200,
|
| 16 |
+
"css": 200,
|
| 17 |
+
"cpp": 225,
|
| 18 |
+
"c": 225,
|
| 19 |
+
"lua": 200,
|
| 20 |
+
"csharp": 225,
|
| 21 |
+
"rust": 225
|
| 22 |
+
},
|
| 23 |
+
"blocked_reason": "Docker/Podman unavailable; no isolated runtime for reference and negative-control execution.",
|
| 24 |
+
"model_baselines": "not run"
|
| 25 |
+
}
|
examples/result-format.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"illustrative_only": true,
|
| 3 |
+
"note": "Synthetic format illustration, not a measured model result.",
|
| 4 |
+
"complete": false,
|
| 5 |
+
"results": [{"id": "smolscript-python-0001", "language": "python", "syntax_success": true, "passed": false, "tests": [{"test": 0, "passed": false, "actual": {"stdout": "wrong\n", "exit_code": 0}}]}]
|
| 6 |
+
}
|
generators/__init__.py
ADDED
|
File without changes
|
generators/build.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministically build 2,000 task records, references and separate hidden tests."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0,str(ROOT))
|
| 8 |
+
from generators.specs import task_specs,oracle,probes
|
| 9 |
+
from generators.code import render,signature
|
| 10 |
+
from generators.web import html_tasks,css_tasks,dom_tasks,BASE_CSS
|
| 11 |
+
|
| 12 |
+
ALLOCATION={'python':(150,75,25),'javascript':(150,75,25),'html':(120,60,20),'css':(120,60,20),
|
| 13 |
+
'cpp':(135,68,22),'c':(135,68,22),'lua':(120,60,20),'csharp':(135,67,23),'rust':(135,67,23)}
|
| 14 |
+
NAMES={'python':'Python','javascript':'JavaScript','html':'HTML','css':'CSS','cpp':'C++','c':'C','lua':'Lua','csharp':'C#','rust':'Rust'}
|
| 15 |
+
VERSION='smolscript-0.1.0'
|
| 16 |
+
|
| 17 |
+
def stable(value):return json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False)
|
| 18 |
+
def sha(value):return hashlib.sha256(stable(value).encode()).hexdigest()
|
| 19 |
+
def write_rows(path,rows):path.write_text(''.join(stable(x)+'\n' for x in rows))
|
| 20 |
+
|
| 21 |
+
def build():
|
| 22 |
+
public=[];private=[];references=[];specs=task_specs()
|
| 23 |
+
suites={}
|
| 24 |
+
for kind in ('scalar','string','array'):
|
| 25 |
+
candidates=[s for group in specs.values() for s in group if s['kind']==kind]
|
| 26 |
+
pool=probes(kind)
|
| 27 |
+
chosen=([-120,-11,-10,-5,-2,-1,0,1,2,5,10,11,120] if kind=='scalar' else pool[:13])+pool[-8:]
|
| 28 |
+
while True:
|
| 29 |
+
groups={}
|
| 30 |
+
for spec in candidates:
|
| 31 |
+
key=tuple(oracle(spec,v) for v in chosen)
|
| 32 |
+
groups.setdefault(key,[]).append(spec)
|
| 33 |
+
collisions=[g for g in groups.values() if len(g)>1]
|
| 34 |
+
if not collisions:break
|
| 35 |
+
def discrimination(v):
|
| 36 |
+
return sum(len(set(oracle(spec,v) for spec in group))-1 for group in collisions)
|
| 37 |
+
best=max(pool,key=discrimination)
|
| 38 |
+
if discrimination(best)==0:raise ValueError('Cannot distinguish hidden tasks')
|
| 39 |
+
chosen.append(best)
|
| 40 |
+
suites[kind]=chosen
|
| 41 |
+
for lang,counts in ALLOCATION.items():
|
| 42 |
+
items=[]
|
| 43 |
+
if lang in ('html','css'):items=html_tasks() if lang=='html' else css_tasks()
|
| 44 |
+
else:
|
| 45 |
+
for difficulty,count in zip(('easy','medium','moderate'),counts):
|
| 46 |
+
if lang=='javascript' and difficulty=='medium':count-=15
|
| 47 |
+
if lang=='javascript' and difficulty=='moderate':count-=5
|
| 48 |
+
for spec in specs[difficulty][:count]:items.append({'difficulty':difficulty,'spec':spec})
|
| 49 |
+
if lang=='javascript':items+=dom_tasks()
|
| 50 |
+
for i,item in enumerate(items,1):
|
| 51 |
+
spec=item['spec'];kind=spec['kind'];difficulty=item['difficulty']
|
| 52 |
+
rid=f'smolscript-{lang}-{i:04d}'
|
| 53 |
+
metadata={'protocol':VERSION,'family':kind,'semantic_id':sha(spec),'input_domain':None}
|
| 54 |
+
if kind in ('scalar','string','array'):
|
| 55 |
+
from generators.specs import instruction
|
| 56 |
+
prompt=f'In {NAMES[lang]}, '+instruction(spec)
|
| 57 |
+
sig=signature(lang,kind)
|
| 58 |
+
output_format='Return only the function '+sig+(' inside public class Solution.' if lang=='csharp' else '. Do not include a main program.')
|
| 59 |
+
metadata['input_domain']={'scalar':'Integer n from -120 to 120.','string':'ASCII s of at most 80 characters, without newlines.','array':'At most eight integers, each from -6 to 6.'}[kind]
|
| 60 |
+
reference=render(lang,spec)
|
| 61 |
+
values=probes(kind)
|
| 62 |
+
# Public examples do not use the hidden edge/adversarial inputs.
|
| 63 |
+
public_values={'scalar':[3,-2],'string':['Hello',' Code '],'array':[[1,2,3],[-2,0,2]]}[kind]
|
| 64 |
+
public_tests=[{'input':v,'expected':oracle(spec,v)} for v in public_values]
|
| 65 |
+
selected=[v for v in suites[kind] if v not in public_values]
|
| 66 |
+
hidden=[{'input':v,'expected':oracle(spec,v)} for v in selected]
|
| 67 |
+
category={'scalar':'arithmetic_conditions','string':'strings','array':'collections_loops'}[kind]
|
| 68 |
+
if spec.get('reduce')=='frequency':category='frequency_tables'
|
| 69 |
+
entry='Solve' if lang=='csharp' else 'solve'
|
| 70 |
+
else:
|
| 71 |
+
prompt='In '+NAMES[lang]+', '+item['prompt'];reference=item['reference'];entry='setup' if kind=='dom' else ''
|
| 72 |
+
output_format={'html':'Return an HTML fragment only.','css':'Return a stylesheet only.','dom':'Return function setup() only. The harness calls it once after loading the fixture.'}[kind]
|
| 73 |
+
public_tests=[];category={'html':'semantic_structure','css':'styles_layout','dom':'dom_events'}[kind]
|
| 74 |
+
metadata['fixture']=item['fixture']
|
| 75 |
+
metadata['base_css']=BASE_CSS if kind=='css' else ''
|
| 76 |
+
hidden=[{'checks':item['checks'],'steps':item.get('steps',[])}]
|
| 77 |
+
if kind=='dom':
|
| 78 |
+
# A no-op toggler must not pass merely because two toggles cancel.
|
| 79 |
+
from generators.web import DOM_ACTIONS
|
| 80 |
+
action=spec['action'];check=item['checks']
|
| 81 |
+
initial=[{'kind':'text','selector':'#output','value':'0'}, {'kind':'value','selector':'#input','value':''},
|
| 82 |
+
{'kind':'count','selector':'#items > li','value':0}, {'kind':'property','selector':'#input','name':'disabled','value':False},
|
| 83 |
+
{'kind':'property','selector':'#output','name':'hidden','value':False}, {'kind':'property','selector':'#check','name':'checked','value':False},
|
| 84 |
+
{'kind':'attribute','selector':'#output','name':'class','value':None},{'kind':'attribute','selector':'#output','name':'title','value':None}]
|
| 85 |
+
hidden.insert(0,{'checks':initial,'steps':[]})
|
| 86 |
+
if action=='toggle_class':hidden.append({'steps':[{'action':'click','selector':'#action'}],'checks':[{'kind':'attribute','selector':'#output','name':'class','value':'active'}]})
|
| 87 |
+
# Nonconstant input-dependent behaviors also tested with empty input.
|
| 88 |
+
expected={'mirror':'','uppercase':'','length':'0','reverse':'','mark_empty':'Empty'}
|
| 89 |
+
if action in expected:
|
| 90 |
+
steps=[{'action':'event','selector':'#input','value':'input'}] if spec['event']=='input' else [{'action':'click','selector':'#action'}]
|
| 91 |
+
hidden.append({'steps':steps,'checks':[{'kind':'text','selector':'#output','value':expected[action]}]})
|
| 92 |
+
row={'id':rid,'language':lang,'difficulty':difficulty,'category':category,'prompt':prompt,
|
| 93 |
+
'output_format':output_format,'entry_point':entry,'reference_solution':None,'tests':public_tests,
|
| 94 |
+
'timeout_seconds':3,'metadata':metadata}
|
| 95 |
+
public.append(row);private.append({'id':rid,'tests':hidden,'spec':spec});references.append({'id':rid,'reference_solution':reference})
|
| 96 |
+
assert len(public)==2000
|
| 97 |
+
for directory in ('data','private_tests','references'): (ROOT/directory).mkdir(exist_ok=True)
|
| 98 |
+
write_rows(ROOT/'data/smolscript.jsonl',public)
|
| 99 |
+
write_rows(ROOT/'private_tests/hidden.jsonl',private)
|
| 100 |
+
write_rows(ROOT/'references/solutions.jsonl',references)
|
| 101 |
+
import pyarrow as pa
|
| 102 |
+
import pyarrow.parquet as pq
|
| 103 |
+
# HF-compatible nested metadata; JSON strings give consistent test schemas across modalities.
|
| 104 |
+
parquet_rows=[{**r,'tests':stable(r['tests']),'metadata':stable(r['metadata'])} for r in public]
|
| 105 |
+
pq.write_table(pa.Table.from_pylist(parquet_rows),ROOT/'data/smolscript.parquet',compression='zstd')
|
| 106 |
+
manifest={'version':VERSION,'examples':2000,'languages':{k:sum(v) for k,v in ALLOCATION.items()},
|
| 107 |
+
'difficulty':{'easy':1200,'medium':600,'moderate':200},'generator_seed':7301,
|
| 108 |
+
'validation_status':'execution_unverified','files':{}}
|
| 109 |
+
for name in ('data/smolscript.jsonl','data/smolscript.parquet','private_tests/hidden.jsonl','references/solutions.jsonl'):
|
| 110 |
+
manifest['files'][name]=hashlib.sha256((ROOT/name).read_bytes()).hexdigest()
|
| 111 |
+
(ROOT/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
| 112 |
+
print('Generated exactly 2000 examples and matching private tests/references.')
|
| 113 |
+
|
| 114 |
+
if __name__=='__main__':build()
|
generators/code.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Language renderers for the original task algebra; no eval/exec."""
|
| 2 |
+
LANGS=('python','javascript','cpp','c','lua','csharp','rust')
|
| 3 |
+
|
| 4 |
+
def scalar_expr(op,x,lang):
|
| 5 |
+
absx={'python':f'abs({x})','javascript':f'Math.abs({x})','cpp':f'std::abs({x})',
|
| 6 |
+
'c':f'llabs({x})','lua':f'math.abs({x})','csharp':f'Math.Abs({x})','rust':f'({x}).abs()'}[lang]
|
| 7 |
+
tern=lambda c,a,b: f'({a} if {c} else {b})' if lang=='python' else (f'(({c}) and {a} or {b})' if lang=='lua' else (f'(if {c} {{ {a} }} else {{ {b} }})' if lang=='rust' else f'(({c}) ? {a} : {b})'))
|
| 8 |
+
div=f'({absx} // 10)' if lang=='python' else (f'math.floor({absx} / 10)' if lang=='lua' else (f'Math.floor({absx} / 10)' if lang=='javascript' else f'({absx} / 10)'))
|
| 9 |
+
return {'double':f'({x} * 2)','negate':f'(-{x})','absolute':absx,'square':f'({x} * {x})',
|
| 10 |
+
'successor':f'({x} + 1)','sign':tern(f'{x} > 0','1',tern(f'{x} < 0','-1','0')),
|
| 11 |
+
'positive':tern(f'{x} > 0',x,'0'),'even':tern(f'{x} % 2 == 0','1','0'),
|
| 12 |
+
'clamp':tern(f'{x} < -5','-5',tern(f'{x} > 5','5',x)),
|
| 13 |
+
'ones':f'({absx} % 10)','tens':f'({div} % 10)',
|
| 14 |
+
'negative':tern(f'{x} < 0','1','0'),'complement':f'(10 - {x})'}[op]
|
| 15 |
+
|
| 16 |
+
def signature(lang,kind):
|
| 17 |
+
return {
|
| 18 |
+
'python':{'scalar':'def solve(n: int) -> int:','string':'def solve(s: str) -> str:','array':'def solve(values: list[int]) -> int:'},
|
| 19 |
+
'javascript':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)'},
|
| 20 |
+
'cpp':{'scalar':'long long solve(long long n)','string':'std::string solve(std::string s)','array':'long long solve(const std::vector<long long>& values)'},
|
| 21 |
+
'c':{'scalar':'long long solve(long long n)','string':'const char *solve(const char *input)','array':'long long solve(const long long *values, int length)'},
|
| 22 |
+
'lua':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)'},
|
| 23 |
+
'csharp':{'scalar':'public static long Solve(long n)','string':'public static string Solve(string s)','array':'public static long Solve(long[] values)'},
|
| 24 |
+
'rust':{'scalar':'fn solve(mut n: i64) -> i64','string':'fn solve(mut s: String) -> String','array':'fn solve(values: Vec<i64>) -> i64'},
|
| 25 |
+
}[lang][kind]
|
| 26 |
+
|
| 27 |
+
def wrap(lang,kind,lines):
|
| 28 |
+
sig=signature(lang,kind)
|
| 29 |
+
if lang=='python':return sig+'\n'+''.join(' '+x+'\n' for x in lines)
|
| 30 |
+
if lang=='lua':return sig+'\n'+''.join(' '+x+'\n' for x in lines)+'end\n'
|
| 31 |
+
code=sig+' {\n'+''.join(' '+x+'\n' for x in lines)+'}\n'
|
| 32 |
+
if lang=='csharp':code='public class Solution {\n'+code+'}\n'
|
| 33 |
+
return code
|
| 34 |
+
|
| 35 |
+
def string_line(op,lang):
|
| 36 |
+
if lang=='python':return 's = '+{
|
| 37 |
+
'upper':'s.upper()','lower':'s.lower()','reverse':'s[::-1]','trim':"s.strip(' ')",
|
| 38 |
+
'letters':"''.join(c for c in s if ('a' <= c <= 'z') or ('A' <= c <= 'Z'))",
|
| 39 |
+
'digits':"''.join(c for c in s if '0' <= c <= '9')",
|
| 40 |
+
'no_vowels':"''.join(c for c in s if c.lower() not in 'aeiou')",
|
| 41 |
+
'no_spaces':"s.replace(' ', '')",'first_half':'s[:len(s)//2]','second_half':'s[len(s)//2:]',
|
| 42 |
+
'swap_case':'s.swapcase()','collapse':"' '.join(part for part in s.split(' ') if part) + (' ' if s.endswith(' ') and s.strip(' ') else '')"}[op] if op!='collapse' else "s = __import__('re').sub(' +', ' ', s)"
|
| 43 |
+
if lang=='javascript':return 's = '+{
|
| 44 |
+
'upper':'s.toUpperCase()','lower':'s.toLowerCase()', 'reverse':"s.split('').reverse().join('')",'trim':"s.replace(/^ +| +$/g, '')",
|
| 45 |
+
'letters':"s.replace(/[^a-zA-Z]/g, '')",'digits':"s.replace(/[^0-9]/g, '')",'no_vowels':"s.replace(/[aeiou]/gi, '')",
|
| 46 |
+
'no_spaces':"s.replace(/ /g, '')",'first_half':'s.slice(0, Math.floor(s.length/2))','second_half':'s.slice(Math.floor(s.length/2))',
|
| 47 |
+
'swap_case':"s.replace(/[a-zA-Z]/g, c => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase())",
|
| 48 |
+
'collapse':"s.replace(/ +/g, ' ')"}[op]+';'
|
| 49 |
+
if lang=='lua':return 's = '+{
|
| 50 |
+
'upper':'string.upper(s)','lower':'string.lower(s)','reverse':'string.reverse(s)', 'trim':'(s:gsub("^ +", ""):gsub(" +$", ""))',
|
| 51 |
+
'letters':'(s:gsub("[^a-zA-Z]", ""))','digits':'(s:gsub("[^0-9]", ""))','no_vowels':'(s:gsub("[aeiouAEIOU]", ""))',
|
| 52 |
+
'no_spaces':'(s:gsub(" ", ""))','first_half':'s:sub(1, math.floor(#s/2))','second_half':'s:sub(math.floor(#s/2)+1)',
|
| 53 |
+
'swap_case':'(s:gsub("%a", function(c) if c == c:upper() then return c:lower() else return c:upper() end end))',
|
| 54 |
+
'collapse':'(s:gsub(" +", " "))'}[op]
|
| 55 |
+
if lang=='csharp':return 's = '+{
|
| 56 |
+
'upper':'s.ToUpperInvariant()','lower':'s.ToLowerInvariant()','reverse':'new string(s.Reverse().ToArray())','trim':"s.Trim(' ')",
|
| 57 |
+
'letters':"new string(s.Where(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')).ToArray())",
|
| 58 |
+
'digits':"new string(s.Where(c => c >= '0' && c <= '9').ToArray())",
|
| 59 |
+
'no_vowels':'new string(s.Where(c => !"aeiouAEIOU".Contains(c)).ToArray())',
|
| 60 |
+
'no_spaces':'s.Replace(" ", "")','first_half':'s.Substring(0, s.Length/2)','second_half':'s.Substring(s.Length/2)',
|
| 61 |
+
'swap_case':'new string(s.Select(c => char.IsUpper(c) ? char.ToLowerInvariant(c) : char.ToUpperInvariant(c)).ToArray())',
|
| 62 |
+
'collapse':'System.Text.RegularExpressions.Regex.Replace(s, " +", " ")'}[op]+';'
|
| 63 |
+
if lang=='rust':return 's = '+{
|
| 64 |
+
'upper':'s.to_ascii_uppercase()','lower':'s.to_ascii_lowercase()','reverse':'s.chars().rev().collect()', 'trim':"s.trim_matches(' ').to_string()",
|
| 65 |
+
'letters':'s.chars().filter(|c| c.is_ascii_alphabetic()).collect()', 'digits':'s.chars().filter(|c| c.is_ascii_digit()).collect()',
|
| 66 |
+
'no_vowels':'s.chars().filter(|c| !"aeiouAEIOU".contains(*c)).collect()', 'no_spaces':"s.replace(' ', \"\")",
|
| 67 |
+
'first_half':'s[..s.len()/2].to_string()','second_half':'s[s.len()/2..].to_string()',
|
| 68 |
+
'swap_case':"s.chars().map(|c| if c.is_ascii_uppercase() { c.to_ascii_lowercase() } else { c.to_ascii_uppercase() }).collect()",
|
| 69 |
+
'collapse':"{ let mut t=String::new(); for c in s.chars() { if c != ' ' || !t.ends_with(' ') { t.push(c); } } t }"}[op]+';'
|
| 70 |
+
if lang=='cpp':
|
| 71 |
+
loop={
|
| 72 |
+
'upper':"t += (c >= 'a' && c <= 'z') ? char(c-32) : c;",
|
| 73 |
+
'lower':"t += (c >= 'A' && c <= 'Z') ? char(c+32) : c;",
|
| 74 |
+
'letters':"if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) t += c;",
|
| 75 |
+
'digits':"if (c >= '0' && c <= '9') t += c;",
|
| 76 |
+
'no_vowels':"if (std::string(\"aeiouAEIOU\").find(c) == std::string::npos) t += c;",
|
| 77 |
+
'no_spaces':"if (c != ' ') t += c;",
|
| 78 |
+
'swap_case':"t += (c >= 'a' && c <= 'z') ? char(c-32) : ((c >= 'A' && c <= 'Z') ? char(c+32) : c);",
|
| 79 |
+
'collapse':"if (c != ' ' || t.empty() || t.back() != ' ') t += c;",
|
| 80 |
+
}
|
| 81 |
+
if op in loop:return '{ std::string t; for (char c : s) { '+loop[op]+' } s=t; }'
|
| 82 |
+
return {'reverse':'std::reverse(s.begin(), s.end());','trim':"{ auto a=s.find_first_not_of(' '); auto b=s.find_last_not_of(' '); s=a==std::string::npos ? \"\" : s.substr(a,b-a+1); }",'first_half':'s=s.substr(0,s.size()/2);','second_half':'s=s.substr(s.size()/2);'}[op]
|
| 83 |
+
if lang=='c':
|
| 84 |
+
condition={ 'letters':"(c>='a' && c<='z') || (c>='A' && c<='Z')",'digits':"c>='0' && c<='9'",
|
| 85 |
+
'no_vowels':'strchr("aeiouAEIOU",c)==NULL','no_spaces':"c!=' '",'collapse':"c!=' ' || j==0 || t[j-1]!=' '"}
|
| 86 |
+
change={'upper':"c>='a' && c<='z' ? c-32 : c",'lower':"c>='A' && c<='Z' ? c+32 : c",
|
| 87 |
+
'swap_case':"c>='a' && c<='z' ? c-32 : (c>='A' && c<='Z' ? c+32 : c)"}
|
| 88 |
+
if op in condition:body=f'if ({condition[op]}) t[j++]=c;'
|
| 89 |
+
elif op in change:body=f't[j++]={change[op]};'
|
| 90 |
+
else:body={'reverse':'t[j++]=s[len-1-i];','first_half':'if (i<len/2) t[j++]=c;',
|
| 91 |
+
'second_half':'if (i>=len/2) t[j++]=c;','trim':'if (i>=a && i<b) t[j++]=c;'}[op]
|
| 92 |
+
init="int a=0,b=len; while(a<b && s[a]==' ') a++; while(b>a && s[b-1]==' ') b--; " if op=='trim' else ''
|
| 93 |
+
return '{ int len=(int)strlen(s), j=0; '+init+'for(int i=0;i<len;i++) { char c=s[i]; '+body+' } t[j]=0; strcpy(s,t); }'
|
| 94 |
+
|
| 95 |
+
def filter_expr(key,lang):
|
| 96 |
+
ab=scalar_expr('absolute','x',lang)
|
| 97 |
+
cond={'all':'true','positive':'x>0','negative':'x<0','even':'x%2==0','odd':'x%2!=0','nonzero':'x!=0',
|
| 98 |
+
'small':ab+'<=3','large':ab+'>3','even_index':'i%2==0','odd_index':'i%2==1'}[key]
|
| 99 |
+
if lang=='python':cond=cond.replace('true','True')
|
| 100 |
+
if lang=='lua':cond=cond.replace('!=','~=')
|
| 101 |
+
return cond
|
| 102 |
+
|
| 103 |
+
def render(lang,spec):
|
| 104 |
+
kind=spec['kind']
|
| 105 |
+
if kind=='scalar':
|
| 106 |
+
lines=['n = '+scalar_expr(op,'n',lang)+(';' if lang not in ('python','lua') else '') for op in spec['steps']]
|
| 107 |
+
lines+=['return n'+(';' if lang not in ('python','lua') else '')]
|
| 108 |
+
return wrap(lang,kind,lines)
|
| 109 |
+
if kind=='string':
|
| 110 |
+
lines=['static char s[512]; char t[512]; strcpy(s,input);'] if lang=='c' else []
|
| 111 |
+
lines += [string_line(op,lang) for op in spec['steps']]
|
| 112 |
+
return wrap(lang,kind,lines+['return s'+(';' if lang not in ('python','lua') else '')])
|
| 113 |
+
pred=filter_expr(spec['filter'],lang)
|
| 114 |
+
val=scalar_expr(spec['map'],'x',lang) if spec.get('map') else 'x'
|
| 115 |
+
r=spec['reduce']
|
| 116 |
+
if lang=='python':
|
| 117 |
+
lines=[f'a = [{val} for i, x in enumerate(values) if {pred}]']
|
| 118 |
+
if r=='frequency':lines+=['counts = {}','for x in a: counts[x] = counts.get(x, 0) + 1','return max(counts.values(), default=0)']
|
| 119 |
+
elif r=='product':lines+=['result = 1','for x in a: result *= x','return result']
|
| 120 |
+
else:lines+=['return '+{'sum':'sum(a)','count':'len(a)','min':'min(a, default=0)','max':'max(a, default=0)',
|
| 121 |
+
'first':'a[0] if a else 0','last':'a[-1] if a else 0','range':'max(a)-min(a) if a else 0','distinct':'len(set(a))'}[r]]
|
| 122 |
+
return wrap(lang,kind,lines)
|
| 123 |
+
if lang=='javascript':
|
| 124 |
+
lines=[f'const a = values.filter((x,i) => {pred}).map(x => {val});']
|
| 125 |
+
returns={'sum':'a.reduce((s,x)=>s+x,0)','count':'a.length','product':'a.reduce((s,x)=>s*x,1)',
|
| 126 |
+
'min':'a.length ? Math.min(...a) : 0','max':'a.length ? Math.max(...a) : 0','first':'a.length ? a[0] : 0',
|
| 127 |
+
'last':'a.length ? a[a.length-1] : 0','range':'a.length ? Math.max(...a)-Math.min(...a) : 0','distinct':'new Set(a).size'}
|
| 128 |
+
if r=='frequency':lines+=['const counts = new Map();','for (const x of a) counts.set(x, (counts.get(x)||0)+1);','return Math.max(0,...counts.values());']
|
| 129 |
+
else:lines+=['return '+returns[r]+';']
|
| 130 |
+
return wrap(lang,kind,lines)
|
| 131 |
+
if lang=='lua':
|
| 132 |
+
lines=['local a = {}',f'for k,x in ipairs(values) do local i=k-1; if {pred} then a[#a+1]={val} end end']
|
| 133 |
+
if r in ('distinct','frequency'):
|
| 134 |
+
lines+=['local counts = {}; local result = 0','for _,x in ipairs(a) do counts[x]=(counts[x] or 0)+1 end',
|
| 135 |
+
('for _ in pairs(counts) do result=result+1 end' if r=='distinct' else 'for _,n in pairs(counts) do result=math.max(result,n) end'),'return result']
|
| 136 |
+
elif r in ('sum','product'):lines += ['local result = '+('1' if r=='product' else '0'),f'for _,x in ipairs(a) do result=result {"*" if r=="product" else "+"} x end','return result']
|
| 137 |
+
elif r=='count':lines+=['return #a']
|
| 138 |
+
else:
|
| 139 |
+
lines+=['if #a==0 then return 0 end']
|
| 140 |
+
if r in ('first','last'):lines+=['return a['+('1' if r=='first' else '#a')+']']
|
| 141 |
+
else:lines+=['local lo,hi=a[1],a[1]','for _,x in ipairs(a) do lo=math.min(lo,x); hi=math.max(hi,x) end','return '+{'min':'lo','max':'hi','range':'hi-lo'}[r]]
|
| 142 |
+
return wrap(lang,kind,lines)
|
| 143 |
+
if lang=='csharp':
|
| 144 |
+
lines=[f'var a = values.Where((x,i) => {pred}).Select(x => {val}).ToList();']
|
| 145 |
+
returns={'sum':'a.Sum()','count':'a.Count','product':'a.Aggregate(1L,(s,x)=>s*x)', 'min':'a.Count>0 ? a.Min() : 0',
|
| 146 |
+
'max':'a.Count>0 ? a.Max() : 0','first':'a.Count>0 ? a[0] : 0','last':'a.Count>0 ? a[a.Count-1] : 0',
|
| 147 |
+
'range':'a.Count>0 ? a.Max()-a.Min() : 0','distinct':'a.Distinct().Count()',
|
| 148 |
+
'frequency':'a.Count>0 ? a.GroupBy(x=>x).Max(g=>g.Count()) : 0'}
|
| 149 |
+
return wrap(lang,kind,lines+['return '+returns[r]+';'])
|
| 150 |
+
if lang=='rust':
|
| 151 |
+
lines=['let mut a: Vec<i64> = Vec::new();',f'for (i, &x) in values.iter().enumerate() {{ if {pred} {{ a.push({val}); }} }}']
|
| 152 |
+
returns={'sum':'a.iter().sum()','count':'a.len() as i64','product':'a.iter().product()',
|
| 153 |
+
'min':'*a.iter().min().unwrap_or(&0)','max':'*a.iter().max().unwrap_or(&0)',
|
| 154 |
+
'first':'*a.first().unwrap_or(&0)','last':'*a.last().unwrap_or(&0)',
|
| 155 |
+
'range':'a.iter().max().unwrap_or(&0)-a.iter().min().unwrap_or(&0)',
|
| 156 |
+
'distinct':'{ a.sort(); a.dedup(); a.len() as i64 }',
|
| 157 |
+
'frequency':'{ let mut counts=std::collections::HashMap::new(); for x in a { *counts.entry(x).or_insert(0i64)+=1; } *counts.values().max().unwrap_or(&0) }'}
|
| 158 |
+
return wrap(lang,kind,lines+['return '+returns[r]+';'])
|
| 159 |
+
lines=(['std::vector<long long> a;',f'for(size_t i=0;i<values.size();i++) {{ auto x=values[i]; if({pred}) a.push_back({val}); }}','int size=(int)a.size();'] if lang=='cpp' else
|
| 160 |
+
['long long a[64]; int size=0;',f'for(int i=0;i<length;i++) {{ long long x=values[i]; if({pred}) a[size++]={val}; }}'])
|
| 161 |
+
if r in ('sum','product'):lines += ['long long result='+('1;' if r=='product' else '0;'),f'for(int i=0;i<size;i++) result {"*=" if r=="product" else "+="} a[i];','return result;']
|
| 162 |
+
elif r=='count':lines+=['return size;']
|
| 163 |
+
elif r in ('distinct','frequency'):
|
| 164 |
+
lines+=['long long result=0;','for(int i=0;i<size;i++) { int count=0, earlier=0; for(int j=0;j<size;j++) { if(a[j]==a[i]) { count++; if(j<i) earlier=1; } } '+('if(!earlier) result++;' if r=='distinct' else 'if(count>result) result=count;')+' }','return result;']
|
| 165 |
+
else:
|
| 166 |
+
lines+=['if(size==0) return 0;']
|
| 167 |
+
if r in ('first','last'):lines+=['return '+('a[0];' if r=='first' else 'a[size-1];')]
|
| 168 |
+
else:lines+=['long long lo=a[0],hi=a[0];','for(int i=0;i<size;i++) { if(a[i]<lo) lo=a[i]; if(a[i]>hi) hi=a[i]; }','return '+{'min':'lo;','max':'hi;','range':'hi-lo;'}[r]]
|
| 169 |
+
return wrap(lang,kind,lines)
|
generators/specs.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Original deterministic task algebra and independent Python behavioral oracle.
|
| 2 |
+
No runtime-generated candidate code is executed by this module.
|
| 3 |
+
"""
|
| 4 |
+
import itertools
|
| 5 |
+
import random
|
| 6 |
+
import string
|
| 7 |
+
|
| 8 |
+
SCALAR = {
|
| 9 |
+
'double':('double it',lambda n:2*n),
|
| 10 |
+
'negate':('negate it',lambda n:-n),
|
| 11 |
+
'absolute':('take its absolute value',abs),
|
| 12 |
+
'square':('square it',lambda n:n*n),
|
| 13 |
+
'successor':('add one',lambda n:n+1),
|
| 14 |
+
'sign':('replace it with -1, 0, or 1 according to its sign',lambda n:(n>0)-(n<0)),
|
| 15 |
+
'positive':('replace negative values with zero',lambda n:max(n,0)),
|
| 16 |
+
'even':('replace it with 1 if even, otherwise 0',lambda n:int(n%2==0)),
|
| 17 |
+
'clamp':('clamp it to the inclusive range -5 to 5',lambda n:max(-5,min(5,n))),
|
| 18 |
+
'ones':('take the last decimal digit of its absolute value',lambda n:abs(n)%10),
|
| 19 |
+
'tens':('take the tens digit of its absolute value',lambda n:abs(n)//10%10),
|
| 20 |
+
'negative':('replace it with 1 if negative, otherwise 0',lambda n:int(n<0)),
|
| 21 |
+
'complement':('subtract it from ten',lambda n:10-n),
|
| 22 |
+
}
|
| 23 |
+
STRINGS = {
|
| 24 |
+
'upper':('convert lowercase ASCII letters to uppercase',lambda s:s.upper()),
|
| 25 |
+
'lower':('convert uppercase ASCII letters to lowercase',lambda s:s.lower()),
|
| 26 |
+
'reverse':('reverse the characters',lambda s:s[::-1]),
|
| 27 |
+
'trim':('remove leading and trailing spaces',lambda s:s.strip(' ')),
|
| 28 |
+
'letters':('keep only ASCII letters',lambda s:''.join(c for c in s if c in string.ascii_letters)),
|
| 29 |
+
'digits':('keep only decimal digits',lambda s:''.join(c for c in s if c in string.digits)),
|
| 30 |
+
'no_vowels':('remove vowels aeiou in either case',lambda s:''.join(c for c in s if c.lower() not in 'aeiou')),
|
| 31 |
+
'no_spaces':('remove every space',lambda s:s.replace(' ','')),
|
| 32 |
+
'first_half':('keep the first floor(length/2) characters',lambda s:s[:len(s)//2]),
|
| 33 |
+
'second_half':('keep characters from index floor(length/2) onward',lambda s:s[len(s)//2:]),
|
| 34 |
+
'swap_case':('swap the case of ASCII letters',lambda s:s.swapcase()),
|
| 35 |
+
'collapse':('replace each run of spaces with one space',lambda s:__import__('re').sub(' +',' ',s)),
|
| 36 |
+
}
|
| 37 |
+
FILTERS={
|
| 38 |
+
'all':('all items',lambda x,i:True),
|
| 39 |
+
'positive':('positive items',lambda x,i:x>0),
|
| 40 |
+
'negative':('negative items',lambda x,i:x<0),
|
| 41 |
+
'even':('even items',lambda x,i:x%2==0),
|
| 42 |
+
'odd':('odd items',lambda x,i:x%2!=0),
|
| 43 |
+
'nonzero':('nonzero items',lambda x,i:x!=0),
|
| 44 |
+
'small':('items with absolute value at most three',lambda x,i:abs(x)<=3),
|
| 45 |
+
'large':('items with absolute value greater than three',lambda x,i:abs(x)>3),
|
| 46 |
+
'even_index':('items at even zero-based indices',lambda x,i:i%2==0),
|
| 47 |
+
'odd_index':('items at odd zero-based indices',lambda x,i:i%2==1),
|
| 48 |
+
}
|
| 49 |
+
REDUCERS={
|
| 50 |
+
'sum':'sum', 'count':'count', 'product':'product', 'min':'minimum', 'max':'maximum',
|
| 51 |
+
'first':'first value','last':'last value','range':'maximum minus minimum',
|
| 52 |
+
'distinct':'number of distinct values','frequency':'largest frequency of a value',
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
def reduce_values(key,values):
|
| 56 |
+
if key=='sum':return sum(values)
|
| 57 |
+
if key=='count':return len(values)
|
| 58 |
+
if key=='product':
|
| 59 |
+
import math
|
| 60 |
+
return math.prod(values)
|
| 61 |
+
if key=='distinct':return len(set(values))
|
| 62 |
+
if key=='frequency':
|
| 63 |
+
from collections import Counter
|
| 64 |
+
return max(Counter(values).values(),default=0)
|
| 65 |
+
if not values:return 0
|
| 66 |
+
return {'min':lambda:min(values),'max':lambda:max(values),'first':lambda:values[0],
|
| 67 |
+
'last':lambda:values[-1],'range':lambda:max(values)-min(values)}[key]()
|
| 68 |
+
|
| 69 |
+
def oracle(spec,value):
|
| 70 |
+
if spec['kind'] in ('scalar','string'):
|
| 71 |
+
operations=SCALAR if spec['kind']=='scalar' else STRINGS
|
| 72 |
+
for step in spec['steps']:value=operations[step][1](value)
|
| 73 |
+
return value
|
| 74 |
+
selected=[x for i,x in enumerate(value) if FILTERS[spec['filter']][1](x,i)]
|
| 75 |
+
if spec.get('map'):selected=[SCALAR[spec['map']][1](x) for x in selected]
|
| 76 |
+
return reduce_values(spec['reduce'],selected)
|
| 77 |
+
|
| 78 |
+
def probes(kind):
|
| 79 |
+
rng=random.Random(20261105)
|
| 80 |
+
if kind=='scalar':return list(range(-120,121))
|
| 81 |
+
if kind=='string':
|
| 82 |
+
return ['', 'a','A','0',' ', ' Ab9 eE! 02 ', 'aeiouAEIOU', 'xyzXYZ', '123456', ' a b ',
|
| 83 |
+
'odd!?', 'Aa0 !', 'bCdEf']+[''.join(rng.choice('aAbBcCeE019 !?') for _ in range(rng.randrange(1,24))) for _ in range(120)]
|
| 84 |
+
return [[],[0],[1],[-1],[2,-3,0,5,2],[-4,-4,-1],[1,2,3,4], [4,3,2,1], [0,0,0], [1,-1,1,-1]]+[
|
| 85 |
+
[rng.randint(-6,6) for _ in range(rng.randrange(1,9))] for _ in range(180)]
|
| 86 |
+
|
| 87 |
+
def bank(kind):
|
| 88 |
+
if kind in ('scalar','string'):
|
| 89 |
+
ops=SCALAR if kind=='scalar' else STRINGS
|
| 90 |
+
candidates=[{'kind':kind,'steps':list(pair)} for pair in itertools.product(ops,repeat=2)]
|
| 91 |
+
else:
|
| 92 |
+
candidates=[{'kind':'array','filter':f,'reduce':r} for f,r in itertools.product(FILTERS,REDUCERS)]
|
| 93 |
+
# An exhaustive finite probe signature rejects algebraic/behavioral duplicates
|
| 94 |
+
# in this restricted grammar, including reordered commuting operations.
|
| 95 |
+
seen=set();out=[]
|
| 96 |
+
for spec in candidates:
|
| 97 |
+
signature=tuple(oracle(spec,x) for x in probes(kind))
|
| 98 |
+
if signature in seen:continue
|
| 99 |
+
seen.add(signature);out.append(spec)
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
def instruction(spec):
|
| 103 |
+
kind=spec['kind']
|
| 104 |
+
if kind in ('scalar','string'):
|
| 105 |
+
ops=SCALAR if kind=='scalar' else STRINGS
|
| 106 |
+
return ('Starting with n, ' if kind=='scalar' else 'Starting with ASCII string s, ')+', then '.join(ops[k][0] for k in spec['steps'])+'. Return the result.'
|
| 107 |
+
text='Select '+FILTERS[spec['filter']][0]+' from values in original order. '
|
| 108 |
+
if spec.get('map'):text+='For each selected item, '+SCALAR[spec['map']][0]+'. '
|
| 109 |
+
text+='Return their '+REDUCERS[spec['reduce']]+'. '
|
| 110 |
+
if spec['reduce']=='product':text+='The empty product is 1.'
|
| 111 |
+
elif spec['reduce'] not in ('sum','count','distinct','frequency'):text+='Return 0 when none are selected.'
|
| 112 |
+
return text
|
| 113 |
+
|
| 114 |
+
def task_specs():
|
| 115 |
+
scalars=bank('scalar');strings=bank('string');arrays=bank('array')
|
| 116 |
+
assert len(scalars)>=80 and len(strings)>=70 and len(arrays)>=75,(len(scalars),len(strings),len(arrays))
|
| 117 |
+
# Interleave operation families so shorter language allocations retain diversity.
|
| 118 |
+
rng=random.Random(7301)
|
| 119 |
+
for b in (scalars,strings,arrays):rng.shuffle(b)
|
| 120 |
+
easy=[]
|
| 121 |
+
for i in range(80):
|
| 122 |
+
easy.append(scalars[i])
|
| 123 |
+
if i<70:easy.append(strings[i])
|
| 124 |
+
medium=arrays[:75]
|
| 125 |
+
seen={tuple(oracle(s,x) for x in probes('array')) for s in medium}
|
| 126 |
+
moderate=[]
|
| 127 |
+
candidates=[{'kind':'array','filter':f,'map':m,'reduce':r}
|
| 128 |
+
for f,m,r in itertools.product(FILTERS,('absolute','square','negate','double','sign','successor'),REDUCERS)
|
| 129 |
+
if r!='count']
|
| 130 |
+
rng.shuffle(candidates)
|
| 131 |
+
for s in candidates:
|
| 132 |
+
sig=tuple(oracle(s,x) for x in probes('array'))
|
| 133 |
+
if sig in seen:continue
|
| 134 |
+
seen.add(sig);moderate.append(s)
|
| 135 |
+
if len(moderate)==25:break
|
| 136 |
+
return {'easy':easy,'medium':medium,'moderate':moderate}
|
generators/web.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Browser tasks with explicit semantic DOM and computed-style checks."""
|
| 2 |
+
from html import escape
|
| 3 |
+
|
| 4 |
+
HTML_BASES=[
|
| 5 |
+
('heading','h1','<h1>Welcome</h1>','an h1 heading reading Welcome',{}),
|
| 6 |
+
('paragraph','p','<p>Hello reader</p>','a paragraph reading Hello reader',{}),
|
| 7 |
+
('link','a','<a href="/help">Help</a>','a Help link to /help',{'href':'/help'}),
|
| 8 |
+
('button','button','<button type="button">Save</button>','a Save button with type button',{'type':'button'}),
|
| 9 |
+
('image','img','<img src="icon.png" alt="Star">','an image sourced from icon.png with alt text Star',{'src':'icon.png','alt':'Star'}),
|
| 10 |
+
('email','input','<input type="email" name="email">','an email input named email',{'type':'email','name':'email'}),
|
| 11 |
+
('checkbox','input','<input type="checkbox" name="agree">','a checkbox named agree',{'type':'checkbox','name':'agree'}),
|
| 12 |
+
('form','form','<form action="/send" method="post"><button>Send</button></form>','a POST form targeting /send containing a Send button',{'action':'/send','method':'post'}),
|
| 13 |
+
('list','ul','<ul><li>Tea</li><li>Water</li></ul>','an unordered list containing Tea then Water',{}),
|
| 14 |
+
('ordered_list','ol','<ol><li>Open</li><li>Close</li></ol>','an ordered list containing Open then Close',{}),
|
| 15 |
+
('navigation','nav','<nav><a href="/">Home</a></nav>','a navigation element with a Home link to /',{}),
|
| 16 |
+
('article','article','<article><h2>News</h2><p>Today</p></article>','an article with an h2 News and a paragraph Today',{}),
|
| 17 |
+
('footer','footer','<footer>Copyright</footer>','a footer reading Copyright',{}),
|
| 18 |
+
('quote','blockquote','<blockquote cite="/source">Be kind</blockquote>','a blockquote reading Be kind citing /source',{'cite':'/source'}),
|
| 19 |
+
('code','pre','<pre><code>x = 1</code></pre>','a preformatted code block reading x = 1',{}),
|
| 20 |
+
('details','details','<details><summary>More</summary><p>Details</p></details>','a details element with summary More and paragraph Details',{}),
|
| 21 |
+
('select','select','<select name="color"><option value="red">Red</option><option value="blue">Blue</option></select>','a select named color with Red/red and Blue/blue options',{'name':'color'}),
|
| 22 |
+
('textarea','textarea','<textarea name="note" rows="3">Note</textarea>','a textarea named note with three rows initially reading Note',{'name':'note','rows':'3'}),
|
| 23 |
+
('label','label','<label for="username">Name</label>','a Name label associated with input ID username',{'for':'username'}),
|
| 24 |
+
('progress','progress','<progress max="10" value="4">4/10</progress>','a progress element with maximum 10 and value 4',{'max':'10','value':'4'}),
|
| 25 |
+
]
|
| 26 |
+
GLOBAL=[('title','Information','a title attribute of Information'),('lang','en','English language via lang'),
|
| 27 |
+
('dir','rtl','right-to-left direction via dir'),('hidden','','the hidden attribute'),
|
| 28 |
+
('tabindex','0','keyboard focus via tabindex 0'),('contenteditable','true','contenteditable set to true')]
|
| 29 |
+
|
| 30 |
+
def html_assertions(markup,prefix=''):
|
| 31 |
+
# Derive structural checks from the authored spec tree, not candidate text.
|
| 32 |
+
from html.parser import HTMLParser
|
| 33 |
+
class Parse(HTMLParser):
|
| 34 |
+
def __init__(self):super().__init__();self.stack=[];self.counts={};self.out=[]
|
| 35 |
+
def handle_starttag(self,tag,attrs):
|
| 36 |
+
parent=self.stack[-1][0] if self.stack else prefix
|
| 37 |
+
key=(parent,tag);self.counts[key]=self.counts.get(key,0)+1
|
| 38 |
+
selector=(parent+' > ' if parent else '')+tag+f':nth-of-type({self.counts[key]})'
|
| 39 |
+
self.out.append({'kind':'exists','selector':selector})
|
| 40 |
+
for k,v in attrs:self.out.append({'kind':'attribute','selector':selector,'name':k,'value':v or ''})
|
| 41 |
+
if tag not in ('img','input','br','hr','meta','link'):self.stack.append((selector,tag))
|
| 42 |
+
def handle_endtag(self,tag):
|
| 43 |
+
if self.stack and self.stack[-1][1]==tag:self.stack.pop()
|
| 44 |
+
def handle_data(self,text):
|
| 45 |
+
if text.strip() and self.stack:self.out.append({'kind':'text','selector':self.stack[-1][0],'value':text})
|
| 46 |
+
p=Parse();p.feed(markup);return p.out
|
| 47 |
+
|
| 48 |
+
def html_tasks():
|
| 49 |
+
tasks=[]
|
| 50 |
+
for name,tag,code,desc,attrs in HTML_BASES:
|
| 51 |
+
for attr,value,detail in GLOBAL:
|
| 52 |
+
markup=code.replace('<'+tag,'<'+tag+' '+attr+'="'+value+'"',1)
|
| 53 |
+
tasks.append(('easy',{'kind':'html','base':name,'feature':attr},'Create '+desc+'. On its outer element, set '+detail+'. Return an HTML fragment.',markup))
|
| 54 |
+
for i,(name,tag,code,desc,attrs) in enumerate(HTML_BASES):
|
| 55 |
+
for offset,wrapper in ((1,'section'),(4,'aside'),(9,'div')):
|
| 56 |
+
_,_,code2,desc2,_=HTML_BASES[(i+offset)%len(HTML_BASES)]
|
| 57 |
+
markup=f'<{wrapper}>{code}{code2}</{wrapper}>'
|
| 58 |
+
tasks.append(('medium',{'kind':'html','pair':[i,(i+offset)%20],'wrapper':wrapper},f'Create a {wrapper} containing {desc}, followed by {desc2}. Return an HTML fragment.',markup))
|
| 59 |
+
for i,(_,_,code,desc,_) in enumerate(HTML_BASES):
|
| 60 |
+
_,_,code2,desc2,_=HTML_BASES[(i+7)%20]
|
| 61 |
+
markup=f'<main><section>{code}</section><aside>{code2}</aside></main>'
|
| 62 |
+
tasks.append(('moderate',{'kind':'html','layout':[i,(i+7)%20]},f'Create a main element. Put {desc} inside its section, and {desc2} inside its following aside. Return an HTML fragment.',markup))
|
| 63 |
+
return [dict(difficulty=d,spec=s,prompt=p,reference=c,fixture='',checks=html_assertions(c)) for d,s,p,c in tasks]
|
| 64 |
+
|
| 65 |
+
# Fixed values are chosen to have exact, stable computed representations.
|
| 66 |
+
CSS_PROPERTIES=[
|
| 67 |
+
('color','rgb(10, 20, 30)'),('background-color','rgb(240, 220, 200)'),('font-size','20px'),('font-weight','700'),
|
| 68 |
+
('font-style','italic'),('text-align','center'),('text-transform','uppercase'),('letter-spacing','2px'),
|
| 69 |
+
('word-spacing','4px'),('line-height','28px'),('text-indent','12px'),('white-space','pre'),
|
| 70 |
+
('padding-top','8px'),('padding-right','10px'),('padding-bottom','12px'),('padding-left','14px'),
|
| 71 |
+
('margin-top','6px'),('margin-right','8px'),('margin-bottom','10px'),('margin-left','12px'),
|
| 72 |
+
('border-top-width','3px'),('border-bottom-color','rgb(0, 80, 120)'),('border-radius','6px'),('opacity','0.5'),
|
| 73 |
+
('width','120px'),('height','60px'),('min-width','90px'),('max-width','180px'),('box-sizing','border-box'),
|
| 74 |
+
('display','flex'),('flex-direction','column'),('justify-content','center'),('align-items','center'),('gap','8px'),
|
| 75 |
+
('position','relative'),('top','5px'),('overflow-x','hidden'),('visibility','hidden'),('cursor','pointer'),('list-style-type','square')]
|
| 76 |
+
BASE_CSS='* { box-sizing: content-box; } .target,.other { border: 1px solid black; width:200px; height:80px; min-width:0; max-width:none; margin:0; padding:0; display:block; position:static; }'
|
| 77 |
+
FIXTURE='<div id="scope"><div id="target" class="target" data-kind="card">Alpha<span>One</span><span>Two</span></div><div class="other">Beta</div></div><div class="target" id="outside">Outside</div>'
|
| 78 |
+
|
| 79 |
+
def css_tasks():
|
| 80 |
+
tasks=[]
|
| 81 |
+
for prop,val in CSS_PROPERTIES:
|
| 82 |
+
for sel,description,affected in [('.target','every element with class target',['#target','#outside']),('#target','only the element with ID target',['#target']),('#scope > .target','only direct children of #scope having class target',['#target'])]:
|
| 83 |
+
spec={'kind':'css','selector':sel,'declarations':{prop:val}}
|
| 84 |
+
checks=[{'kind':'style','selector':x,'property':prop,'value':val} for x in affected]
|
| 85 |
+
extra = 'display: flex;' if prop in ('flex-direction','justify-content','align-items','gap') else ('position: relative;' if prop=='top' else '')
|
| 86 |
+
if extra:
|
| 87 |
+
extra_prop='display' if prop!='top' else 'position'
|
| 88 |
+
extra_val='flex' if prop!='top' else 'relative'
|
| 89 |
+
checks += [{'kind':'style','selector':x,'property':extra_prop,'value':extra_val} for x in affected]
|
| 90 |
+
spec['declarations'][extra_prop]=extra_val
|
| 91 |
+
if prop=='flex-direction':checks += [{'kind':'layout_column','selector':x} for x in affected]
|
| 92 |
+
if prop=='display':checks += [{'kind':'layout_row','selector':x} for x in affected]
|
| 93 |
+
checks +=[{'kind':'unchanged','selector':'.other','property':prop}]
|
| 94 |
+
if len(affected)==1:checks +=[{'kind':'unchanged','selector':'#outside','property':prop}]
|
| 95 |
+
extra_instruction = ' Use flex display.' if extra.startswith('display') else (' Use relative positioning.' if extra else '')
|
| 96 |
+
tasks.append(dict(difficulty='easy',spec=spec,prompt=f'Style {description}: set {prop} to {val}.{extra_instruction} Leave other elements unchanged. Return CSS only.',reference=f'{sel} {{ {prop}: {val}; {extra} }}',fixture=FIXTURE,checks=checks))
|
| 97 |
+
pairs=[]
|
| 98 |
+
# Avoid interactions that would invalidate literal computed values.
|
| 99 |
+
for i in range(20):
|
| 100 |
+
for offset in (4,7,11):pairs.append((i,(i+offset)%20))
|
| 101 |
+
for i,j in pairs:
|
| 102 |
+
p,v=CSS_PROPERTIES[i];q,w=CSS_PROPERTIES[j]
|
| 103 |
+
spec={'kind':'css','selector':'#scope > .target','declarations':{p:v,q:w}}
|
| 104 |
+
checks=[{'kind':'style','selector':'#target','property':k,'value':x} for k,x in ((p,v),(q,w))]
|
| 105 |
+
checks +=[{'kind':'unchanged','selector':'.other','property':k} for k in (p,q)]
|
| 106 |
+
tasks.append(dict(difficulty='medium',spec=spec,prompt=f'For direct children of #scope with class target, set {p} to {v} and {q} to {w}. Leave .other unchanged. Return CSS only.',reference=f'#scope > .target {{ {p}: {v}; {q}: {w}; }}',fixture=FIXTURE,checks=checks))
|
| 107 |
+
for i,(prop,val) in enumerate(CSS_PROPERTIES[:20]):
|
| 108 |
+
# Baseline captured before candidate CSS; test both sides of the breakpoint.
|
| 109 |
+
spec={'kind':'css','selector':'#target','declarations':{prop:val},'max_width':600}
|
| 110 |
+
checks=[{'kind':'style','selector':'#target','property':prop,'value':val,'viewport':480},
|
| 111 |
+
{'kind':'unchanged','selector':'#target','property':prop,'viewport':900},
|
| 112 |
+
{'kind':'unchanged','selector':'.other','property':prop,'viewport':480}]
|
| 113 |
+
tasks.append(dict(difficulty='moderate',spec=spec,prompt=f'At viewport widths at most 600px, set {prop} to {val} on #target. At wider widths, preserve its original style. Never change .other. Return CSS only.',reference=f'@media (max-width: 600px) {{ #target {{ {prop}: {val}; }} }}',fixture=FIXTURE,checks=checks))
|
| 114 |
+
return tasks
|
| 115 |
+
|
| 116 |
+
DOM_FIXTURE='<button id="action">Go</button><input id="input" value=""><p id="output">0</p><ul id="items"></ul><input id="check" type="checkbox">'
|
| 117 |
+
DOM_ACTIONS=[
|
| 118 |
+
('greeting','make #output read Hello',"o.textContent='Hello'",[{'kind':'text','selector':'#output','value':'Hello'}]),
|
| 119 |
+
('increment','increase the integer in #output by one',"o.textContent=String(Number(o.textContent)+1)",[{'kind':'text','selector':'#output','value':'2'}]),
|
| 120 |
+
('decrement','decrease the integer in #output by one',"o.textContent=String(Number(o.textContent)-1)",[{'kind':'text','selector':'#output','value':'-2'}]),
|
| 121 |
+
('mirror','copy the input value into #output',"o.textContent=i.value",[{'kind':'text','selector':'#output','value':'Ab 9'}]),
|
| 122 |
+
('uppercase','copy the uppercased input into #output',"o.textContent=i.value.toUpperCase()",[{'kind':'text','selector':'#output','value':'AB 9'}]),
|
| 123 |
+
('length','put the input character count in #output',"o.textContent=String(i.value.length)",[{'kind':'text','selector':'#output','value':'4'}]),
|
| 124 |
+
('clear_input','clear the input value',"i.value=''",[{'kind':'value','selector':'#input','value':''}]),
|
| 125 |
+
('disable_input','disable the input',"i.disabled=true",[{'kind':'property','selector':'#input','name':'disabled','value':True}]),
|
| 126 |
+
('hide_output','hide #output using its hidden property',"o.hidden=true",[{'kind':'property','selector':'#output','name':'hidden','value':True}]),
|
| 127 |
+
('toggle_class','toggle class active on #output',"o.classList.toggle('active')",[{'kind':'attribute','selector':'#output','name':'class','value':''}]),
|
| 128 |
+
('append_item','append a list item containing the input to #items',"const li=document.createElement('li'); li.textContent=i.value; document.querySelector('#items').appendChild(li)",[{'kind':'count','selector':'#items > li','value':2},{'kind':'text','selector':'#items > li:first-child','value':'Ab 9'}]),
|
| 129 |
+
('check','check the checkbox',"document.querySelector('#check').checked=true",[{'kind':'property','selector':'#check','name':'checked','value':True}]),
|
| 130 |
+
('title','set #output title to the input value',"o.title=i.value",[{'kind':'attribute','selector':'#output','name':'title','value':'Ab 9'}]),
|
| 131 |
+
('reverse','copy the reversed input into #output',"o.textContent=i.value.split('').reverse().join('')",[{'kind':'text','selector':'#output','value':'9 bA'}]),
|
| 132 |
+
('mark_empty','set #output to Empty if input is empty, otherwise Filled',"o.textContent=i.value.length ? 'Filled':'Empty'",[{'kind':'text','selector':'#output','value':'Filled'}]),
|
| 133 |
+
]
|
| 134 |
+
|
| 135 |
+
def dom_tasks():
|
| 136 |
+
tasks=[]
|
| 137 |
+
for name,desc,body,checks in DOM_ACTIONS:
|
| 138 |
+
spec={'kind':'dom','event':'click','action':name}
|
| 139 |
+
code="function setup() {\n const i=document.querySelector('#input'), o=document.querySelector('#output');\n document.querySelector('#action').addEventListener('click', () => { "+body+"; });\n}\n"
|
| 140 |
+
tasks.append(dict(difficulty='medium',spec=spec,prompt=f'Implement setup(). When #action is clicked, {desc}. Attach an event listener; do not perform the action before a click.',reference=code,fixture=DOM_FIXTURE,checks=checks,steps=[{'action':'fill','selector':'#input','value':'Ab 9'},{'action':'click','selector':'#action'},{'action':'click','selector':'#action'}]))
|
| 141 |
+
for name,desc,body,checks in DOM_ACTIONS[3:8]:
|
| 142 |
+
code="function setup() {\n const i=document.querySelector('#input'), o=document.querySelector('#output');\n i.addEventListener('input', () => { "+body+"; });\n}\n"
|
| 143 |
+
tasks.append(dict(difficulty='moderate',spec={'kind':'dom','event':'input','action':name},prompt=f'Implement setup(). On an input event from #input, {desc}. Use a listener, leave the initial page unchanged, and handle repeated events.',reference=code,fixture=DOM_FIXTURE,checks=checks,steps=[{'action':'set_value','selector':'#input','value':'Ab 9'},{'action':'event','selector':'#input','value':'input'}]))
|
| 144 |
+
return tasks
|
manifest.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"version": "smolscript-0.1.0",
|
| 3 |
+
"examples": 2000,
|
| 4 |
+
"languages": {
|
| 5 |
+
"python": 250,
|
| 6 |
+
"javascript": 250,
|
| 7 |
+
"html": 200,
|
| 8 |
+
"css": 200,
|
| 9 |
+
"cpp": 225,
|
| 10 |
+
"c": 225,
|
| 11 |
+
"lua": 200,
|
| 12 |
+
"csharp": 225,
|
| 13 |
+
"rust": 225
|
| 14 |
+
},
|
| 15 |
+
"difficulty": {
|
| 16 |
+
"easy": 1200,
|
| 17 |
+
"medium": 600,
|
| 18 |
+
"moderate": 200
|
| 19 |
+
},
|
| 20 |
+
"generator_seed": 7301,
|
| 21 |
+
"validation_status": "execution_unverified",
|
| 22 |
+
"files": {
|
| 23 |
+
"data/smolscript.jsonl": "1926bca1b0c6b2244554577135a9c3c305b18fd834c654803b4e8480fff0d3d9",
|
| 24 |
+
"data/smolscript.parquet": "7bf25948750648aa036bdf277cfd7c38597c98aa06131e805628b9055a7938d9",
|
| 25 |
+
"private_tests/hidden.jsonl": "2447d09ae445094c1ae59df644b46e3ca2f4cc64de630966b94bd5db8b8bf0ac",
|
| 26 |
+
"references/solutions.jsonl": "84d3411fe45189c62ae50fbd31c1dc5795bc099d5037c3a817e3d280f6097e83"
|
| 27 |
+
}
|
| 28 |
+
}
|
metrics.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""All published metrics are percentages; no incomplete full-benchmark index."""
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
from runners import LANGUAGES
|
| 4 |
+
|
| 5 |
+
def aggregate(results,expected_ids,full_run=True):
|
| 6 |
+
if len({r['id'] for r in results})!=len(results):raise ValueError('Duplicate result IDs')
|
| 7 |
+
if {r['id'] for r in results}!=set(expected_ids):raise ValueError('Incomplete or extra results')
|
| 8 |
+
groups=defaultdict(list)
|
| 9 |
+
for r in results:groups[r['language']].append(r)
|
| 10 |
+
accuracy={lang:100*sum(bool(r['passed']) for r in group)/len(group) for lang,group in sorted(groups.items())}
|
| 11 |
+
syntax={lang:100*sum(bool(r['syntax_success']) for r in group)/len(group) for lang,group in sorted(groups.items())}
|
| 12 |
+
if full_run and set(groups)!=set(LANGUAGES):raise ValueError('Missing language')
|
| 13 |
+
score=sum(accuracy.values())/len(accuracy)
|
| 14 |
+
result={'scope':'full' if full_run else 'filtered','examples':len(results),'pass_at_1':score,
|
| 15 |
+
'syntax_success':sum(syntax.values())/len(syntax),'per_language_accuracy':accuracy,
|
| 16 |
+
'per_language_syntax_success':syntax,'micro_accuracy':100*sum(r['passed'] for r in results)/len(results)}
|
| 17 |
+
result['smolscript_score' if full_run else 'filtered_macro_score']=score
|
| 18 |
+
return result
|
private_tests/hidden.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pyproject.toml
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
[project]
|
| 5 |
+
name = "smolscript"
|
| 6 |
+
version = "0.1.0"
|
| 7 |
+
description = "A small-model multilingual execution benchmark"
|
| 8 |
+
requires-python = ">=3.11"
|
| 9 |
+
license = {text = "MIT"}
|
| 10 |
+
dependencies = ["pyarrow==19.0.1"]
|
| 11 |
+
[project.optional-dependencies]
|
| 12 |
+
inference = ["torch>=2.5,<3", "transformers>=4.57,<6", "huggingface-hub>=0.36,<2", "accelerate>=1,<2"]
|
| 13 |
+
[tool.setuptools]
|
| 14 |
+
packages = ["runners", "generators", "validators"]
|
references/solutions.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
runners/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from importlib import import_module
|
| 2 |
+
LANGUAGES=('python','javascript','html','css','cpp','c','lua','csharp','rust')
|
| 3 |
+
def get_runner(language):
|
| 4 |
+
if language not in LANGUAGES:raise ValueError('Unknown language '+language)
|
| 5 |
+
return import_module('runners.'+language+'_runner').Runner()
|
runners/c_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""c runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import FunctionRunner
|
| 3 |
+
|
| 4 |
+
class Runner(FunctionRunner):
|
| 5 |
+
pass
|
runners/common.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from decimal import Decimal,InvalidOperation
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def extract_code(text):
|
| 6 |
+
text=text.strip()
|
| 7 |
+
blocks=re.findall(r'```[^\n`]*\n(.*?)```',text,re.S)
|
| 8 |
+
if len(blocks)==1:return blocks[0].strip()+'\n'
|
| 9 |
+
if len(blocks)>1:raise ValueError('Multiple code blocks are ambiguous')
|
| 10 |
+
if '```' in text:raise ValueError('Unclosed code fence')
|
| 11 |
+
return text+'\n'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def compare_output(actual,expected):
|
| 15 |
+
# Remove one terminal newline only: spaces in string results are observable.
|
| 16 |
+
value=actual.removesuffix('\n').removesuffix('\r')
|
| 17 |
+
if isinstance(expected,int):
|
| 18 |
+
try:return Decimal(value.strip())==expected and value.strip()!=''
|
| 19 |
+
except InvalidOperation:return False
|
| 20 |
+
return value==expected
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class FunctionRunner:
|
| 24 |
+
def evaluate(self,row,code,hidden,sandbox):
|
| 25 |
+
inputs=[t['input'] for t in hidden['tests']]
|
| 26 |
+
response=sandbox.run({'language':row['language'],'kind':row['metadata']['family'],
|
| 27 |
+
'code':code,'inputs':inputs,'timeout_seconds':row['timeout_seconds']},
|
| 28 |
+
timeout=50+len(inputs)*(row['timeout_seconds']+2))
|
| 29 |
+
results=[]
|
| 30 |
+
observations=response['observations']
|
| 31 |
+
for i,test in enumerate(hidden['tests']):
|
| 32 |
+
actual=observations[i] if i<len(observations) else None
|
| 33 |
+
passed=bool(actual and actual['exit_code']==0 and not actual['timeout'] and not actual['output_limit'] and compare_output(actual['stdout'],test['expected']))
|
| 34 |
+
results.append({'test':i,'passed':passed,'actual':actual})
|
| 35 |
+
return {'syntax_success':response['syntax_success'],'passed':bool(results) and all(t['passed'] for t in results),
|
| 36 |
+
'tests':results,'compilation':response.get('compilation')}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BrowserRunner:
|
| 40 |
+
def evaluate(self,row,code,hidden,sandbox):
|
| 41 |
+
scenarios=[];expected=[]
|
| 42 |
+
for t in hidden['tests']:
|
| 43 |
+
widths=sorted(set(c.get('viewport',800) for c in t['checks']))
|
| 44 |
+
for width in widths:
|
| 45 |
+
checks=[c for c in t['checks'] if c.get('viewport',800)==width]
|
| 46 |
+
# Deliberately do not send expected values into the sandbox.
|
| 47 |
+
scenarios.append({'viewport':width,'steps':t.get('steps',[]),
|
| 48 |
+
'checks':[{k:v for k,v in c.items() if k not in ('value','viewport')} for c in checks]})
|
| 49 |
+
expected.append(checks)
|
| 50 |
+
response=sandbox.run({'language':row['language'],'kind':row['metadata']['family'],'code':code,
|
| 51 |
+
'fixture':row['metadata'].get('fixture',''),'base_css':row['metadata'].get('base_css',''),
|
| 52 |
+
'scenarios':scenarios,'timeout_seconds':row['timeout_seconds']},timeout=30+len(scenarios)*20)
|
| 53 |
+
results=[]
|
| 54 |
+
for i,checks in enumerate(expected):
|
| 55 |
+
actual=response['observations'][i] if i<len(response['observations']) else None
|
| 56 |
+
for j,c in enumerate(checks):
|
| 57 |
+
observed=actual['actual'][j] if actual and j<len(actual['actual']) else None
|
| 58 |
+
target=actual['baseline'][j] if actual and c['kind']=='unchanged' else c.get('value',True)
|
| 59 |
+
passed=bool(actual and not actual['error'] and j<len(actual['actual']) and observed==target)
|
| 60 |
+
results.append({'scenario':i,'test':j,'passed':passed,'actual':observed,'error':actual['error'] if actual else 'syntax failure'})
|
| 61 |
+
return {'syntax_success':response['syntax_success'],'passed':bool(results) and all(r['passed'] for r in results),'tests':results}
|
runners/cpp_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""cpp runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import FunctionRunner
|
| 3 |
+
|
| 4 |
+
class Runner(FunctionRunner):
|
| 5 |
+
pass
|
runners/csharp_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""csharp runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import FunctionRunner
|
| 3 |
+
|
| 4 |
+
class Runner(FunctionRunner):
|
| 5 |
+
pass
|
runners/css_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""css runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import BrowserRunner
|
| 3 |
+
|
| 4 |
+
class Runner(BrowserRunner):
|
| 5 |
+
pass
|
runners/html_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""html runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import BrowserRunner
|
| 3 |
+
|
| 4 |
+
class Runner(BrowserRunner):
|
| 5 |
+
pass
|
runners/javascript_runner.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Node function tasks and Chromium DOM tasks share one language score."""
|
| 2 |
+
from runners.common import FunctionRunner,BrowserRunner
|
| 3 |
+
class Runner:
|
| 4 |
+
def evaluate(self,row,code,hidden,sandbox):
|
| 5 |
+
runner=BrowserRunner() if row['metadata']['family']=='dom' else FunctionRunner()
|
| 6 |
+
return runner.evaluate(row,code,hidden,sandbox)
|
runners/lua_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""lua runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import FunctionRunner
|
| 3 |
+
|
| 4 |
+
class Runner(FunctionRunner):
|
| 5 |
+
pass
|
runners/protocol.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runtime adapters: signature wrappers, no execution on the host."""
|
| 2 |
+
HEADERS={
|
| 3 |
+
'python':'', 'javascript':'', 'lua':'',
|
| 4 |
+
'cpp':'#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cstdlib>\n',
|
| 5 |
+
'c':'#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n',
|
| 6 |
+
'csharp':'using System;\nusing System.Linq;\nusing System.Collections.Generic;\n',
|
| 7 |
+
'rust':'use std::io::{self, Read};\n',
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
def wrap_source(language,kind,code):
|
| 11 |
+
"""Candidate function plus a fixed stdin/stdout adapter. No expected answers."""
|
| 12 |
+
if language=='python':
|
| 13 |
+
expr={'scalar':'int(line)','string':'line','array':'list(map(int,line.split())) if line else []'}[kind]
|
| 14 |
+
tail=f'\nimport sys\nline=sys.stdin.readline().rstrip("\\n")\nprint(solve({expr}))\n'
|
| 15 |
+
elif language=='javascript':
|
| 16 |
+
expr={'scalar':'Number(line)','string':'line','array':"line ? line.split(' ').map(Number) : []"}[kind]
|
| 17 |
+
tail=f"\nconst line=require('fs').readFileSync(0,'utf8').replace(/\\n$/, '');\nconsole.log(solve({expr}));\n"
|
| 18 |
+
elif language=='lua':
|
| 19 |
+
init={'scalar':'local v=tonumber(line)','string':'local v=line','array':'local v={}; for n in line:gmatch("%-?%d+") do v[#v+1]=tonumber(n) end'}[kind]
|
| 20 |
+
tail='\nlocal line=io.read("*l") or ""\n'+init+'\nprint(solve(v))\n'
|
| 21 |
+
elif language=='cpp':
|
| 22 |
+
init={'scalar':'long long v; std::cin>>v;','string':'std::string v; std::getline(std::cin,v);','array':'std::vector<long long> v; long long x; while(std::cin>>x) v.push_back(x);'}[kind]
|
| 23 |
+
tail='\nint main() { '+init+' std::cout << solve(v) << "\\n"; }\n'
|
| 24 |
+
elif language=='c':
|
| 25 |
+
init={'scalar':'long long v; scanf("%lld",&v); printf("%lld\\n",solve(v));',
|
| 26 |
+
'string':'char v[512]; if(!fgets(v,sizeof v,stdin)) v[0]=0; v[strcspn(v,"\\n")]=0; printf("%s\\n",solve(v));',
|
| 27 |
+
'array':'long long v[64]; int n=0; while(n<64 && scanf("%lld",&v[n])==1) n++; printf("%lld\\n",solve(v,n));'}[kind]
|
| 28 |
+
tail='\nint main(void) { '+init+' return 0; }\n'
|
| 29 |
+
elif language=='csharp':
|
| 30 |
+
expr={'scalar':'long.Parse(line)','string':'line','array':'line.Length==0 ? new long[0] : line.Split(\' \').Select(long.Parse).ToArray()'}[kind]
|
| 31 |
+
tail='\npublic class Harness { public static void Main() { string line=Console.ReadLine() ?? ""; Console.WriteLine(Solution.Solve('+expr+')); } }\n'
|
| 32 |
+
elif language=='rust':
|
| 33 |
+
expr={'scalar':'line.parse::<i64>().unwrap()','string':'line.to_string()','array':'line.split_whitespace().map(|x| x.parse::<i64>().unwrap()).collect()'}[kind]
|
| 34 |
+
tail='\nfn main() { let mut text=String::new(); io::stdin().read_to_string(&mut text).unwrap(); let line=text.strip_suffix("\\n").unwrap_or(&text); println!("{}",solve('+expr+')); }\n'
|
| 35 |
+
else:raise ValueError(language)
|
| 36 |
+
return HEADERS[language]+code+'\n'+tail
|
| 37 |
+
|
| 38 |
+
COMMANDS={
|
| 39 |
+
'python':('solution.py',['python3','-m','py_compile','solution.py'],['python3','-I','solution.py']),
|
| 40 |
+
'javascript':('solution.js',['node','--check','solution.js'],['node','solution.js']),
|
| 41 |
+
'lua':('solution.lua',['luac','-p','solution.lua'],['lua','solution.lua']),
|
| 42 |
+
'cpp':('solution.cpp',['g++','-std=c++17','-O0','solution.cpp','-o','program'],['./program']),
|
| 43 |
+
'c':('solution.c',['gcc','-std=c11','-O0','solution.c','-o','program'],['./program']),
|
| 44 |
+
'csharp':('solution.cs',['mcs','-out:program.exe','solution.cs'],['mono','program.exe']),
|
| 45 |
+
'rust':('solution.rs',['rustc','--edition=2021','-C','opt-level=0','solution.rs','-o','program'],['./program']),
|
| 46 |
+
}
|
runners/python_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""python runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import FunctionRunner
|
| 3 |
+
|
| 4 |
+
class Runner(FunctionRunner):
|
| 5 |
+
pass
|
runners/rust_runner.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""rust runner: executed only through the container boundary."""
|
| 2 |
+
from runners.common import FunctionRunner
|
| 3 |
+
|
| 4 |
+
class Runner(FunctionRunner):
|
| 5 |
+
pass
|
runners/sandbox.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed container boundary. Candidate code never runs on the host."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
+
import tempfile
|
| 8 |
+
import uuid
|
| 9 |
+
|
| 10 |
+
class SandboxUnavailable(RuntimeError):pass
|
| 11 |
+
|
| 12 |
+
class Sandbox:
|
| 13 |
+
def __init__(self,image='smolscript-runtime:0.1.0',engine='docker'):
|
| 14 |
+
if not shutil.which(engine):raise SandboxUnavailable(f'{engine} is unavailable; install Docker/Podman and build sandbox/Dockerfile. No host fallback exists.')
|
| 15 |
+
self.engine=engine
|
| 16 |
+
try:
|
| 17 |
+
info=json.loads(subprocess.check_output([engine,'image','inspect',image],timeout=15))[0]
|
| 18 |
+
except (subprocess.SubprocessError,ValueError,KeyError) as e:raise SandboxUnavailable('Sandbox image unavailable; build it before offline evaluation') from e
|
| 19 |
+
self.image=info['Id'] # Immutable local ID, not a moving tag.
|
| 20 |
+
self.identity={'engine':engine,'image_id':self.image,'repo_digests':info.get('RepoDigests',[])}
|
| 21 |
+
|
| 22 |
+
def run(self,payload,timeout):
|
| 23 |
+
# Only candidate, fixture, input values and observation selectors cross the
|
| 24 |
+
# boundary. Expected answers, references, credentials and dataset do not.
|
| 25 |
+
name='smolscript-'+uuid.uuid4().hex
|
| 26 |
+
with tempfile.TemporaryDirectory(prefix='smolscript-input-') as directory:
|
| 27 |
+
path=Path(directory)/'request.json'
|
| 28 |
+
path.write_text(json.dumps(payload));path.chmod(0o444);os.chmod(directory,0o755)
|
| 29 |
+
command=[self.engine,'run','--rm','--name',name,'--network','none','--read-only',
|
| 30 |
+
'--cap-drop','ALL','--security-opt','no-new-privileges','--user','1000:1000',
|
| 31 |
+
'--memory','2g','--memory-swap','2g','--cpus','1','--pids-limit','128',
|
| 32 |
+
'--ulimit','nofile=256:256','--ulimit','core=0:0',
|
| 33 |
+
'--tmpfs','/work:rw,exec,nosuid,size=256m,uid=1000,gid=1000',
|
| 34 |
+
'--tmpfs','/tmp:rw,nosuid,size=128m,uid=1000,gid=1000','--shm-size','128m',
|
| 35 |
+
'--mount',f'type=bind,src={directory},dst=/input,readonly',
|
| 36 |
+
self.image,'python3','/opt/smolscript/worker.py','/input/request.json']
|
| 37 |
+
try:
|
| 38 |
+
result=subprocess.run(command,capture_output=True,text=True,timeout=timeout)
|
| 39 |
+
if result.returncode:raise RuntimeError('Sandbox infrastructure failed: '+result.stderr[-2000:])
|
| 40 |
+
value=json.loads(result.stdout)
|
| 41 |
+
if 'infrastructure_error' in value:raise RuntimeError(value['infrastructure_error'])
|
| 42 |
+
return value
|
| 43 |
+
except subprocess.TimeoutExpired:
|
| 44 |
+
raise RuntimeError('Sandbox supervisor timed out; outcome incomplete')
|
| 45 |
+
finally:
|
| 46 |
+
subprocess.run([self.engine,'rm','-f',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=15)
|
sandbox/Dockerfile
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Build once with internet; inference/evaluation never downloads runtime assets.
|
| 2 |
+
FROM mcr.microsoft.com/playwright/python:v1.56.0-noble
|
| 3 |
+
USER root
|
| 4 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 5 |
+
gcc g++ nodejs lua5.4 mono-mcs mono-runtime rustc && \
|
| 6 |
+
rm -rf /var/lib/apt/lists/*
|
| 7 |
+
RUN python3 -m pip install --no-cache-dir playwright==1.56.0 html5lib==1.1 tinycss2==1.4.0
|
| 8 |
+
RUN ln -sf /usr/bin/lua5.4 /usr/local/bin/lua && ln -sf /usr/bin/luac5.4 /usr/local/bin/luac
|
| 9 |
+
COPY sandbox/worker.py /opt/smolscript/worker.py
|
| 10 |
+
COPY runners/protocol.py /opt/smolscript/protocol.py
|
| 11 |
+
RUN useradd --uid 1000 --create-home --non-unique benchmark 2>/dev/null || true
|
| 12 |
+
ENV HOME=/tmp PYTHONHASHSEED=0 LANG=C.UTF-8 LC_ALL=C.UTF-8 TZ=UTC
|
| 13 |
+
WORKDIR /work
|
| 14 |
+
USER 1000:1000
|
sandbox/worker.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trusted in-container supervisor. Never import or invoke this on host candidates."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import resource
|
| 6 |
+
import signal
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
from protocol import COMMANDS,wrap_source
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def limits(seconds):
|
| 14 |
+
os.setsid()
|
| 15 |
+
resource.setrlimit(resource.RLIMIT_CPU,(seconds,seconds+1))
|
| 16 |
+
resource.setrlimit(resource.RLIMIT_FSIZE,(1024*1024,1024*1024))
|
| 17 |
+
resource.setrlimit(resource.RLIMIT_CORE,(0,0))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def execute(command,stdin,seconds):
|
| 21 |
+
with tempfile.TemporaryFile() as out,tempfile.TemporaryFile() as err:
|
| 22 |
+
p=subprocess.Popen(command,stdin=subprocess.PIPE,stdout=out,stderr=err,
|
| 23 |
+
preexec_fn=lambda:limits(seconds),env={'PATH':os.environ['PATH'],'HOME':'/tmp','LANG':'C.UTF-8',
|
| 24 |
+
'LC_ALL':'C.UTF-8','TZ':'UTC','PYTHONHASHSEED':'0','MONO_THREADS_PER_CPU':'1'})
|
| 25 |
+
timed_out=False
|
| 26 |
+
try:p.communicate(stdin.encode(),timeout=seconds+1)
|
| 27 |
+
except subprocess.TimeoutExpired:timed_out=True
|
| 28 |
+
finally:
|
| 29 |
+
try:os.killpg(p.pid,signal.SIGKILL)
|
| 30 |
+
except ProcessLookupError:pass
|
| 31 |
+
p.wait()
|
| 32 |
+
out.seek(0);err.seek(0)
|
| 33 |
+
output=out.read(65537)
|
| 34 |
+
return {'exit_code':p.returncode,'timeout':timed_out,'output_limit':len(output)>65536,
|
| 35 |
+
'stdout':output[:65536].decode('utf8','replace'),'stderr':err.read(2000).decode('utf8','replace')}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def program(request):
|
| 39 |
+
filename,compile_cmd,run_cmd=COMMANDS[request['language']]
|
| 40 |
+
Path(filename).write_text(wrap_source(request['language'],request['kind'],request['code']))
|
| 41 |
+
compilation=execute(compile_cmd,'',30)
|
| 42 |
+
syntax=compilation['exit_code']==0 and not compilation['timeout']
|
| 43 |
+
if not syntax:return {'syntax_success':False,'compilation':compilation,'observations':[]}
|
| 44 |
+
observations=[]
|
| 45 |
+
for value in request['inputs']:
|
| 46 |
+
line=' '.join(map(str,value)) if isinstance(value,list) else str(value)
|
| 47 |
+
observations.append(execute(run_cmd,line+'\n',request['timeout_seconds']))
|
| 48 |
+
return {'syntax_success':True,'observations':observations}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def observe(page,check):
|
| 52 |
+
loc=page.locator(check['selector']);kind=check['kind']
|
| 53 |
+
if kind=='count':return loc.count()
|
| 54 |
+
if kind in ('layout_column','layout_row'):
|
| 55 |
+
return loc.evaluate('''(e,kind) => { const a=e.querySelectorAll('span'); if(a.length!==2) return false;
|
| 56 |
+
const x=a[0].getBoundingClientRect(), y=a[1].getBoundingClientRect();
|
| 57 |
+
return kind==='layout_column' ? Math.abs(x.x-y.x)<1 && y.y>=x.bottom : Math.abs(x.y-y.y)<1 && y.x>=x.right; }''',kind)
|
| 58 |
+
if kind=='exists':return loc.count()>0
|
| 59 |
+
if loc.count()!=1:return {'error':'selector must resolve to exactly one element','count':loc.count()}
|
| 60 |
+
if kind=='text':return loc.text_content()
|
| 61 |
+
if kind=='attribute':return loc.get_attribute(check['name'])
|
| 62 |
+
if kind=='value':return loc.input_value()
|
| 63 |
+
if kind=='property':return loc.evaluate('(e,k)=>e[k]',check['name'])
|
| 64 |
+
if kind in ('style','unchanged'):return loc.evaluate('(e,p)=>getComputedStyle(e).getPropertyValue(p)',check['property'])
|
| 65 |
+
raise ValueError(kind)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def browser(request):
|
| 69 |
+
from playwright.sync_api import sync_playwright,TimeoutError as BrowserTimeout
|
| 70 |
+
kind=request['kind'];code=request['code']
|
| 71 |
+
if kind=='html':
|
| 72 |
+
import html5lib
|
| 73 |
+
parser=html5lib.HTMLParser();parser.parseFragment(code)
|
| 74 |
+
syntax=not parser.errors
|
| 75 |
+
elif kind=='css':
|
| 76 |
+
import tinycss2
|
| 77 |
+
rules=tinycss2.parse_stylesheet(code,skip_comments=True,skip_whitespace=True)
|
| 78 |
+
def errors(nodes):
|
| 79 |
+
for n in nodes:
|
| 80 |
+
if n.type=='error':return True
|
| 81 |
+
if n.type=='qualified-rule':
|
| 82 |
+
if any(x.type=='error' for x in tinycss2.parse_declaration_list(n.content)):return True
|
| 83 |
+
if n.type=='at-rule' and n.content is not None:
|
| 84 |
+
if errors(tinycss2.parse_rule_list(n.content)):return True
|
| 85 |
+
return False
|
| 86 |
+
syntax=bool(rules) and not errors(rules)
|
| 87 |
+
else:
|
| 88 |
+
Path('candidate.js').write_text(code)
|
| 89 |
+
syntax=execute(['node','--check','candidate.js'],'',5)['exit_code']==0
|
| 90 |
+
if not syntax:return {'syntax_success':False,'observations':[]}
|
| 91 |
+
observations=[]
|
| 92 |
+
with sync_playwright() as p:
|
| 93 |
+
# Container namespace, seccomp, uid, cgroups and disabled networking are
|
| 94 |
+
# the mandatory boundary; no browser flag substitutes for that boundary.
|
| 95 |
+
b=p.chromium.launch(headless=True,args=['--disable-dev-shm-usage'])
|
| 96 |
+
try:
|
| 97 |
+
for scenario in request['scenarios']:
|
| 98 |
+
page=b.new_page(viewport={'width':scenario.get('viewport',800),'height':600},java_script_enabled=kind=='dom')
|
| 99 |
+
page.set_default_timeout(request['timeout_seconds']*1000)
|
| 100 |
+
page.route('**/*',lambda route:route.abort())
|
| 101 |
+
actual=[];baseline=[];error=None
|
| 102 |
+
try:
|
| 103 |
+
page.set_content(request['fixture'],wait_until='domcontentloaded')
|
| 104 |
+
if request.get('base_css'):page.add_style_tag(content=request['base_css'])
|
| 105 |
+
baseline=[observe(page,c) if c['kind']=='unchanged' else None for c in scenario['checks']]
|
| 106 |
+
if kind=='html':page.set_content(code,wait_until='domcontentloaded')
|
| 107 |
+
elif kind=='css':page.add_style_tag(content=code)
|
| 108 |
+
else:
|
| 109 |
+
page.add_script_tag(content=code)
|
| 110 |
+
page.evaluate('() => setup()')
|
| 111 |
+
for step in scenario.get('steps',[]):
|
| 112 |
+
loc=page.locator(step['selector']);action=step['action']
|
| 113 |
+
if action=='fill':loc.fill(step['value'])
|
| 114 |
+
elif action=='click':loc.click()
|
| 115 |
+
elif action=='event':loc.dispatch_event(step['value'])
|
| 116 |
+
elif action=='set_value':loc.evaluate('(e,v)=>{e.value=v}',step['value'])
|
| 117 |
+
else:raise ValueError(action)
|
| 118 |
+
actual=[observe(page,c) for c in scenario['checks']]
|
| 119 |
+
except Exception as e:error=type(e).__name__+': '+str(e)[:500]
|
| 120 |
+
observations.append({'actual':actual,'baseline':baseline,'error':error})
|
| 121 |
+
page.close()
|
| 122 |
+
finally:b.close()
|
| 123 |
+
return {'syntax_success':True,'observations':observations}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def main():
|
| 127 |
+
r=json.loads(Path(sys.argv[1]).read_text())
|
| 128 |
+
if r.get('diagnostic'):
|
| 129 |
+
result={}
|
| 130 |
+
for lang,(_,cmd,run) in COMMANDS.items():
|
| 131 |
+
import shutil
|
| 132 |
+
result[lang]=bool(shutil.which(cmd[0]) and (run[0].startswith('./') or shutil.which(run[0])))
|
| 133 |
+
from playwright.sync_api import sync_playwright
|
| 134 |
+
with sync_playwright() as p:
|
| 135 |
+
b=p.chromium.launch();b.close()
|
| 136 |
+
result.update(html=True,css=True)
|
| 137 |
+
return {'runtimes':result}
|
| 138 |
+
return browser(r) if r['kind'] in ('html','css','dom') else program(r)
|
| 139 |
+
|
| 140 |
+
if __name__=='__main__':
|
| 141 |
+
try:result=main()
|
| 142 |
+
except Exception as e:result={'infrastructure_error':type(e).__name__+': '+str(e)[:2000]}
|
| 143 |
+
print(json.dumps(result,allow_nan=False))
|
tests/test_core.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT))
|
| 8 |
+
from evaluate import prompt
|
| 9 |
+
from metrics import aggregate
|
| 10 |
+
from runners.common import extract_code,compare_output,FunctionRunner,BrowserRunner
|
| 11 |
+
from runners.sandbox import Sandbox,SandboxUnavailable
|
| 12 |
+
from validators.dataset import load
|
| 13 |
+
|
| 14 |
+
class CoreTests(unittest.TestCase):
|
| 15 |
+
def test_prompt_has_no_reference_or_tests(self):
|
| 16 |
+
row=load(ROOT/'data/smolscript.jsonl')[0];row['tests']=[{'input':'SECRET_TEST','expected':'SECRET_ANSWER'}];row['reference_solution']='SECRET_REFERENCE'
|
| 17 |
+
text=prompt(row)
|
| 18 |
+
for token in ('SECRET_TEST','SECRET_ANSWER','SECRET_REFERENCE'):self.assertNotIn(token,text)
|
| 19 |
+
def test_macro_not_micro(self):
|
| 20 |
+
rows=[{'id':str(i),'language':'python','passed':True,'syntax_success':True} for i in range(3)]
|
| 21 |
+
rows+=[{'id':'x','language':'rust','passed':False,'syntax_success':True}]
|
| 22 |
+
result=aggregate(rows,[r['id'] for r in rows],full_run=False)
|
| 23 |
+
self.assertEqual(result['filtered_macro_score'],50);self.assertEqual(result['micro_accuracy'],75)
|
| 24 |
+
self.assertNotIn('smolscript_score',result)
|
| 25 |
+
def test_incomplete_results_rejected(self):
|
| 26 |
+
with self.assertRaises(ValueError):aggregate([],['missing'])
|
| 27 |
+
def test_whitespace_observable_and_numeric_format(self):
|
| 28 |
+
self.assertTrue(compare_output(' a \n',' a '));self.assertFalse(compare_output('a\n',' a'))
|
| 29 |
+
self.assertTrue(compare_output('2.0\n',2));self.assertFalse(compare_output('NaN\n',2))
|
| 30 |
+
def test_extraction(self):
|
| 31 |
+
self.assertEqual(extract_code('```python\ndef solve(n): return n\n```'),'def solve(n): return n\n')
|
| 32 |
+
with self.assertRaises(ValueError):extract_code('```a\nx\n```\n```b\ny\n```')
|
| 33 |
+
def test_missing_engine_fails_closed(self):
|
| 34 |
+
with patch('runners.sandbox.shutil.which',return_value=None),self.assertRaises(SandboxUnavailable):Sandbox()
|
| 35 |
+
def test_python_reference_syntax(self):
|
| 36 |
+
ids={r['id'] for r in load(ROOT/'data/smolscript.jsonl') if r['language']=='python'}
|
| 37 |
+
for r in load(ROOT/'references/solutions.jsonl'):
|
| 38 |
+
if r['id'] in ids:ast.parse(r['reference_solution'])
|
| 39 |
+
def test_answers_not_sent_to_sandbox(self):
|
| 40 |
+
class Fake:
|
| 41 |
+
def run(self,payload,timeout):
|
| 42 |
+
self.payload=payload
|
| 43 |
+
return {'syntax_success':True,'observations':[{'exit_code':0,'timeout':False,'output_limit':False,'stdout':'9\n'}]}
|
| 44 |
+
fake=Fake();row={'language':'python','timeout_seconds':3,'metadata':{'family':'scalar'}}
|
| 45 |
+
result=FunctionRunner().evaluate(row,'def solve(n): return 9',{'tests':[{'input':3,'expected':9}]},fake)
|
| 46 |
+
self.assertTrue(result['passed']);self.assertNotIn('expected',json.dumps(fake.payload))
|
| 47 |
+
|
| 48 |
+
if __name__=='__main__':unittest.main()
|
validate.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate structure, then run every reference and negative control in Docker."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from validators.dataset import check,load
|
| 6 |
+
from runners import get_runner
|
| 7 |
+
from runners.sandbox import Sandbox,SandboxUnavailable
|
| 8 |
+
|
| 9 |
+
ROOT=Path(__file__).resolve().parent
|
| 10 |
+
|
| 11 |
+
def main():
|
| 12 |
+
p=argparse.ArgumentParser();p.add_argument('--static-only',action='store_true');p.add_argument('--image',default='smolscript-runtime:0.1.0');p.add_argument('--engine',default='docker');p.add_argument('--output',type=Path,default=ROOT/'validation_report.json');a=p.parse_args()
|
| 13 |
+
report=check(ROOT);report['reference_execution']='unverified';report['negative_controls']='unverified'
|
| 14 |
+
try:
|
| 15 |
+
if a.static_only:
|
| 16 |
+
report['remaining']='All 2000 references and negative controls require sandbox execution.';return 0
|
| 17 |
+
sandbox=Sandbox(a.image,a.engine)
|
| 18 |
+
report['sandbox']=sandbox.identity
|
| 19 |
+
report['runtimes']=sandbox.run({'diagnostic':True},60)['runtimes']
|
| 20 |
+
if not all(report['runtimes'].values()):raise SandboxUnavailable('Missing language runtime')
|
| 21 |
+
hidden={r['id']:r for r in load(ROOT/'private_tests/hidden.jsonl')}
|
| 22 |
+
refs={r['id']:r['reference_solution'] for r in load(ROOT/'references/solutions.jsonl')}
|
| 23 |
+
results=[]
|
| 24 |
+
from generators.code import wrap
|
| 25 |
+
for row in load(ROOT/'data/smolscript.jsonl'):
|
| 26 |
+
rid=row['id'];runner=get_runner(row['language']);family=row['metadata']['family']
|
| 27 |
+
result=runner.evaluate(row,refs[rid],hidden[rid],sandbox)
|
| 28 |
+
if family in ('html','css'):wrong=''
|
| 29 |
+
elif family=='dom':wrong='function setup() {}'
|
| 30 |
+
else:
|
| 31 |
+
wrong=wrap(row['language'],family,[('return '+('"__wrong__"' if family=='string' else '-999999')+(';' if row['language'] not in ('python','lua') else ''))])
|
| 32 |
+
negative=runner.evaluate(row,wrong,hidden[rid],sandbox)
|
| 33 |
+
# Also reject a plausible near-miss: keep only the first composition
|
| 34 |
+
# stage, or remove the map/filter in collection tasks.
|
| 35 |
+
mutant=None
|
| 36 |
+
if family in ('scalar','string','array'):
|
| 37 |
+
from generators.code import render
|
| 38 |
+
spec=dict(hidden[rid]['spec'])
|
| 39 |
+
if family in ('scalar','string'):spec['steps']=spec['steps'][:1]
|
| 40 |
+
elif spec.get('map'):spec.pop('map')
|
| 41 |
+
else:spec['filter']='all' if spec['filter']!='all' else 'positive'
|
| 42 |
+
from generators.specs import oracle
|
| 43 |
+
if any(oracle(spec,t['input'])!=t['expected'] for t in hidden[rid]['tests']):
|
| 44 |
+
mutant=runner.evaluate(row,render(row['language'],spec),hidden[rid],sandbox)
|
| 45 |
+
results.append({'id':rid,'reference_passed':result['passed'],'negative_rejected':not negative['passed'],
|
| 46 |
+
'near_miss_rejected':not mutant['passed'] if mutant is not None else None})
|
| 47 |
+
report['execution_results']=results
|
| 48 |
+
if not result['passed'] or negative['passed'] or (mutant and mutant['passed']):
|
| 49 |
+
raise ValueError('Reference or negative control failed: '+rid)
|
| 50 |
+
if len(results)%25==0:
|
| 51 |
+
print(f'Validated {len(results)}/2000',flush=True);a.output.write_text(json.dumps(report,indent=2)+'\n')
|
| 52 |
+
report['reference_execution']='passed';report['negative_controls']='passed';return 0
|
| 53 |
+
except SandboxUnavailable as e:
|
| 54 |
+
report['blocked_reason']=str(e);report['unverified_languages']=['python','javascript','html','css','cpp','c','lua','csharp','rust'];print(str(e));return 2
|
| 55 |
+
except Exception as e:report['error']=str(e);raise
|
| 56 |
+
finally:a.output.write_text(json.dumps(report,indent=2)+'\n')
|
| 57 |
+
|
| 58 |
+
if __name__=='__main__':raise SystemExit(main())
|
validation_report.json
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"static_validation": "passed",
|
| 3 |
+
"examples": 2000,
|
| 4 |
+
"languages": {
|
| 5 |
+
"python": 250,
|
| 6 |
+
"javascript": 250,
|
| 7 |
+
"html": 200,
|
| 8 |
+
"css": 200,
|
| 9 |
+
"cpp": 225,
|
| 10 |
+
"c": 225,
|
| 11 |
+
"lua": 200,
|
| 12 |
+
"csharp": 225,
|
| 13 |
+
"rust": 225
|
| 14 |
+
},
|
| 15 |
+
"difficulty": {
|
| 16 |
+
"easy": 1200,
|
| 17 |
+
"medium": 600,
|
| 18 |
+
"moderate": 200
|
| 19 |
+
},
|
| 20 |
+
"categories": {
|
| 21 |
+
"arithmetic_conditions": 492,
|
| 22 |
+
"strings": 468,
|
| 23 |
+
"collections_loops": 540,
|
| 24 |
+
"frequency_tables": 80,
|
| 25 |
+
"dom_events": 20,
|
| 26 |
+
"semantic_structure": 200,
|
| 27 |
+
"styles_layout": 200
|
| 28 |
+
},
|
| 29 |
+
"prompt_words": {
|
| 30 |
+
"min": 13,
|
| 31 |
+
"max": 38,
|
| 32 |
+
"over_50": 0
|
| 33 |
+
},
|
| 34 |
+
"solution_lines": {
|
| 35 |
+
"min": 1,
|
| 36 |
+
"max": 9
|
| 37 |
+
},
|
| 38 |
+
"exact_duplicates": 0,
|
| 39 |
+
"semantic_duplicates_within_language": 0,
|
| 40 |
+
"near_text_pairs": [
|
| 41 |
+
{
|
| 42 |
+
"a": "smolscript-python-0173",
|
| 43 |
+
"b": "smolscript-python-0188",
|
| 44 |
+
"trigram_jaccard": 0.8667
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"a": "smolscript-javascript-0173",
|
| 48 |
+
"b": "smolscript-javascript-0188",
|
| 49 |
+
"trigram_jaccard": 0.8667
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"a": "smolscript-cpp-0158",
|
| 53 |
+
"b": "smolscript-cpp-0173",
|
| 54 |
+
"trigram_jaccard": 0.8667
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"a": "smolscript-c-0158",
|
| 58 |
+
"b": "smolscript-c-0173",
|
| 59 |
+
"trigram_jaccard": 0.8667
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"a": "smolscript-lua-0143",
|
| 63 |
+
"b": "smolscript-lua-0158",
|
| 64 |
+
"trigram_jaccard": 0.8667
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"a": "smolscript-csharp-0158",
|
| 68 |
+
"b": "smolscript-csharp-0173",
|
| 69 |
+
"trigram_jaccard": 0.8667
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"a": "smolscript-rust-0158",
|
| 73 |
+
"b": "smolscript-rust-0173",
|
| 74 |
+
"trigram_jaccard": 0.8667
|
| 75 |
+
}
|
| 76 |
+
],
|
| 77 |
+
"semantic_check_scope": "finite deterministic probes plus exact DSL/DOM/CSS spec equality; not a general equivalence proof",
|
| 78 |
+
"cross_language_policy": "Aligned original tasks intentionally recur across languages for comparable coverage.",
|
| 79 |
+
"reference_execution": "unverified",
|
| 80 |
+
"negative_controls": "unverified",
|
| 81 |
+
"blocked_reason": "docker is unavailable; install Docker/Podman and build sandbox/Dockerfile. No host fallback exists.",
|
| 82 |
+
"unverified_languages": [
|
| 83 |
+
"python",
|
| 84 |
+
"javascript",
|
| 85 |
+
"html",
|
| 86 |
+
"css",
|
| 87 |
+
"cpp",
|
| 88 |
+
"c",
|
| 89 |
+
"lua",
|
| 90 |
+
"csharp",
|
| 91 |
+
"rust"
|
| 92 |
+
]
|
| 93 |
+
}
|
validators/__init__.py
ADDED
|
File without changes
|
validators/dataset.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Static checks are deliberately distinct from sandbox reference validation."""
|
| 2 |
+
from collections import Counter,defaultdict
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import re
|
| 7 |
+
from generators.build import ALLOCATION
|
| 8 |
+
from generators.specs import oracle,probes
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load(path):
|
| 12 |
+
rows=[json.loads(x) for x in Path(path).read_text().splitlines() if x.strip()]
|
| 13 |
+
if len({r['id'] for r in rows})!=len(rows):raise ValueError('Duplicate IDs: '+str(path))
|
| 14 |
+
return rows
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def check(root):
|
| 18 |
+
rows=load(root/'data/smolscript.jsonl');hidden=load(root/'private_tests/hidden.jsonl');refs=load(root/'references/solutions.jsonl')
|
| 19 |
+
assert len(rows)==2000,'Expected exactly 2000 examples'
|
| 20 |
+
assert Counter(r['language'] for r in rows)=={k:sum(v) for k,v in ALLOCATION.items()},'Language allocation'
|
| 21 |
+
assert Counter(r['difficulty'] for r in rows)=={'easy':1200,'medium':600,'moderate':200},'Difficulty allocation'
|
| 22 |
+
assert {r['id'] for r in rows}=={r['id'] for r in hidden}=={r['id'] for r in refs},'Private/public ID mismatch'
|
| 23 |
+
assert len({r['prompt'] for r in rows})==2000,'Duplicate prompts'
|
| 24 |
+
hm={r['id']:r for r in hidden};rm={r['id']:r for r in refs}
|
| 25 |
+
hidden_behavior={};seen={};behavior={};categories=Counter();lengths=[];solutions=[];similarity=[]
|
| 26 |
+
by_language=defaultdict(list)
|
| 27 |
+
for r in rows:
|
| 28 |
+
rid=r['id'];spec=hm[rid]['spec'];kind=spec['kind'];categories[r['category']]+=1
|
| 29 |
+
assert r['reference_solution'] is None,'Public reference leakage'
|
| 30 |
+
assert 1<=r['timeout_seconds']<=10
|
| 31 |
+
assert r['difficulty'] in ('easy','medium','moderate')
|
| 32 |
+
assert r['output_format'] and r['prompt']
|
| 33 |
+
assert hm[rid]['tests'],'Missing hidden tests'
|
| 34 |
+
assert rm[rid]['reference_solution'].strip(),'Missing reference'
|
| 35 |
+
assert rm[rid]['reference_solution'] not in r['prompt'],'Reference in prompt'
|
| 36 |
+
lengths.append(len(r['prompt'].split()));solutions.append(len(rm[rid]['reference_solution'].splitlines()))
|
| 37 |
+
semantic=(r['language'],r['metadata']['semantic_id'])
|
| 38 |
+
assert semantic not in seen,('Duplicate semantic spec',rid,seen.get(semantic))
|
| 39 |
+
seen[semantic]=rid
|
| 40 |
+
# Input/output fingerprints catch algebraic identities in this bounded DSL.
|
| 41 |
+
if kind in ('scalar','string','array'):
|
| 42 |
+
fingerprint=(r['language'],kind,tuple(oracle(spec,x) for x in probes(kind)))
|
| 43 |
+
assert fingerprint not in behavior,('Equivalent behavior',rid,behavior.get(fingerprint))
|
| 44 |
+
behavior[fingerprint]=rid
|
| 45 |
+
suite_key=(r['language'],kind,tuple(t['expected'] for t in hm[rid]['tests']))
|
| 46 |
+
assert suite_key not in hidden_behavior,('Hidden-suite behavior collision',rid)
|
| 47 |
+
hidden_behavior[suite_key]=rid
|
| 48 |
+
for t in hm[rid]['tests']+r['tests']:
|
| 49 |
+
assert oracle(spec,t['input'])==t['expected'],('Oracle mismatch',rid)
|
| 50 |
+
normalized=re.sub(r'\d+','N',r['prompt'].lower())
|
| 51 |
+
words=normalized.split();grams={tuple(words[i:i+3]) for i in range(len(words)-2)}
|
| 52 |
+
for other,othergrams in by_language[r['language']]:
|
| 53 |
+
ratio=len(grams&othergrams)/max(1,len(grams|othergrams))
|
| 54 |
+
if ratio>=0.85:similarity.append({'a':other,'b':rid,'trigram_jaccard':round(ratio,4)})
|
| 55 |
+
by_language[r['language']].append((rid,grams))
|
| 56 |
+
# Near-text pairs are disclosed for review; no identical behavioral or semantic
|
| 57 |
+
# specifications are accepted. Translations across languages are intentional.
|
| 58 |
+
import pyarrow.parquet as pq
|
| 59 |
+
parquet=pq.read_table(root/'data/smolscript.parquet').to_pylist()
|
| 60 |
+
decoded=[{**r,'tests':json.loads(r['tests']),'metadata':json.loads(r['metadata'])} for r in parquet]
|
| 61 |
+
assert decoded==rows,'JSONL/Parquet mismatch'
|
| 62 |
+
manifest=json.loads((root/'manifest.json').read_text())
|
| 63 |
+
for name,digest in manifest['files'].items():assert hashlib.sha256((root/name).read_bytes()).hexdigest()==digest,('Hash mismatch',name)
|
| 64 |
+
return {'static_validation':'passed','examples':len(rows),'languages':dict(Counter(r['language'] for r in rows)),
|
| 65 |
+
'difficulty':dict(Counter(r['difficulty'] for r in rows)),'categories':dict(categories),
|
| 66 |
+
'prompt_words':{'min':min(lengths),'max':max(lengths),'over_50':sum(n>50 for n in lengths)},
|
| 67 |
+
'solution_lines':{'min':min(solutions),'max':max(solutions)},'exact_duplicates':0,'semantic_duplicates_within_language':0,
|
| 68 |
+
'near_text_pairs':similarity,'semantic_check_scope':'finite deterministic probes plus exact DSL/DOM/CSS spec equality; not a general equivalence proof',
|
| 69 |
+
'cross_language_policy':'Aligned original tasks intentionally recur across languages for comparable coverage.'}
|