wip: shield index relations, dev evaluation tasks, Q-063 audit notes
Verifier borrow/provenance work, new phase3 shield_index conformance cases, dev-intervals/dev-lru/dev-shards tasks with evaluate.py harness, and agent skill/hook config.
This commit is contained in:
1 parent
2d750a0525
commit
e3fc896a0a
68 files changed
+2132
-37
No files matched your search
@@ -367,3 +367,120 @@ Reproduction and qualification artifacts are retained in
|
||||
`conformance.jsonl`, CLI-suite logs and `qualification.json` with source and
|
||||
executable hashes. The reproducible targeted test is
|
||||
`python3 tests/hosted/source_loop_exit.py`.
|
||||
|
||||
## Third optimization: indexed resource relations (2026-10-14)
|
||||
|
||||
`provenance.State` now keeps an insertion-ordered active list, endpoint
|
||||
adjacency lists and lists by relation kind. A fact retains its complete
|
||||
identity: kind, both value IDs and the loan's spawn span. Duplicate insertion
|
||||
keeps the original position. `kill(v)` unlinks only facts whose first or second
|
||||
endpoint is `v`, including self-edges exactly once. It neither compacts nor
|
||||
scans unrelated facts. The killed endpoint bucket remains pinned until its
|
||||
chains are empty; Zig 0.17's hash-map removal tombstones other buckets without
|
||||
relocating them. Removed node slots are recycled, so one state's node storage
|
||||
tracks its live-fact high-water mark rather than historical insertions.
|
||||
|
||||
`borrow.step` checks E4305 through the ended shield's second-endpoint list,
|
||||
retaining the old live-subject filter and first-conflict choice. Generic access
|
||||
checks visit only loan facts; borrow-end guard checks visit only guards, and
|
||||
scope-end checks visit only that scope's target list. These restricted lists
|
||||
preserve the corresponding full-list order. Whole-state clone, union and
|
||||
simultaneous edge/handle renaming still traverse surviving insertion order.
|
||||
Exact shield joins compare the same `.inner` set and choose the same first
|
||||
mismatching resource. No fact is inferred or discarded by the new indexes.
|
||||
|
||||
The internal relation-kind tag is explicitly `u32`. This leaves the fact's
|
||||
five scalar words without padding and selects Zig's standard byte-hash path
|
||||
instead of recursive field hashing in Debug. Fact equality, printed names and
|
||||
AIR are unchanged. Membership insertion is rolled back if subsequent host
|
||||
growth fails; endpoint, kind and order links are published only after growth
|
||||
succeeds. Clone/rename replacement is published only after the replacement is
|
||||
complete. Removal and iteration allocate nothing. The checker still returns
|
||||
actual host allocation failures as `error.OutOfMemory`.
|
||||
|
||||
### Paired timing and memory
|
||||
|
||||
Zig 0.17.0, Debug, CPU 0; one warmup and three measured repetitions per binary
|
||||
and case, alternating version order. Both frozen executables receive the same
|
||||
bytes. Twenty lowering preflights produce exact identical AIR. Timings cover
|
||||
shield depths 128/256/512/1024 through AIR checking and full source checking,
|
||||
plus six source controls at 512: 28 warmups and 84 measured commands. All
|
||||
commands accept cleanly. Each child's CPU time and peak RSS come from `wait4`.
|
||||
These are finite measurements, not portable latency or whole-compiler bounds.
|
||||
|
||||
| Shield depth | AIR check seconds, before → after | Source check seconds, before → after | Source speedup | Source RSS MiB, before → after |
|
||||
|---|---|---|---|---|
|
||||
| 128 | 0.0903 → 0.0934 | 0.1277 → 0.1092 | 1.17× | 20.4 → 20.4 |
|
||||
| 256 | 0.3623 → 0.3166 | 0.3948 → 0.3499 | 1.13× | 24.0 → 44.9 |
|
||||
| 512 | 1.9534 → 1.1833 | 1.9848 → 1.2405 | 1.60× | 56.4 → 120.9 |
|
||||
| 1024 | 14.8610 → 7.6246 | 12.1542 → 5.0732 | 2.40× | 166.8 → 400.9 |
|
||||
|
||||
The endpoint/kind indexes trade memory for reduced scanning. The larger RSS
|
||||
is material; small-case RSS can include the runner's inherited process floor.
|
||||
The implementation still creates n(n−1)/2 shield-order facts. A complete
|
||||
innermost-first pop now removes each such fact once per state application,
|
||||
rather than visiting lists totaling (n³−n)/6 entries; hash-table work has
|
||||
expected constant cost per lookup/removal. Creation, cloning, live-value
|
||||
checks and other verifier passes remain. Reducing the quadratic fact count or
|
||||
index footprint is separate work, so Q-063 stays open.
|
||||
|
||||
Source-check controls at 512 (seconds):
|
||||
|
||||
| Shape | Before | After | Change |
|
||||
|---|---:|---:|---:|
|
||||
| scope | 0.097691 | 0.098552 | +0.9% |
|
||||
| while | 0.305123 | 0.308303 | +1.0% |
|
||||
| loop | 0.128656 | 0.134261 | +4.4% |
|
||||
| match | 0.317832 | 0.324534 | +2.1% |
|
||||
| while_live | 0.825396 | 0.828236 | +0.3% |
|
||||
| match_live | 0.770816 | 0.782526 | +1.5% |
|
||||
|
||||
### Correctness and concurrency invariants
|
||||
|
||||
This is an implementation optimization of existing spec 04 §34/§37.3,
|
||||
spec 06 §6 and spec 08 §11. The AGENTS.md memory/concurrency checklist is:
|
||||
|
||||
| Contract | Preserved behavior and evidence |
|
||||
|---|---|
|
||||
| Invariant | Identical fact membership and survivor order; loans retain task, borrower and spawn origin; both endpoints are killed |
|
||||
| Verifier | Innermost shield ending (E4305), exact incoming shield order (E3002), loan/scope/guard transfer and existing error recovery |
|
||||
| Runtime | Interpreter, shield depth, pending cancellation and scheduler rules are unchanged |
|
||||
| Valid example | `shield_index_handoff.air`, `shield_index_reuse.air`, and source `layer8/shield_index_reuse.aji` |
|
||||
| Rejected example | `shield_index_first_conflict.air` and `shield_index_join_priority.air` |
|
||||
| Diagnostic impact | Same codes, order, conflict/resource names, source/AIR positions and loan-related locations |
|
||||
| Determinism | Exact old/new records and exits at finite fuel, quantum and scheduler choices, plus scheduled conformance runs |
|
||||
| Compatibility | All public source/AIR comparisons below are exact; AIR format 0 and source rules are unchanged |
|
||||
|
||||
Validation on the final source and executable:
|
||||
|
||||
- **348 unit tests**, including the frozen compact-list oracle over 2,304
|
||||
mixed operations with duplicates, self-edges, deletion/reinsertion, clones,
|
||||
self/ordinary merges and simultaneous renaming. Both indexes and kind/order
|
||||
links are checked against that independent oracle. Storage reuse and
|
||||
allocation-failure probes cover empty and grown indexes, atomic publication,
|
||||
deduplicating rename and complete arena release.
|
||||
- **1,813 conformance cases** pass with unique complete inventory, including
|
||||
five new cases. The three new run cases use 32 scheduler seeds each; existing
|
||||
cancellation/resource tests retain their own scheduled runs.
|
||||
- **3,252 exact old/new comparisons** on 1,813 public files: check all 1,439
|
||||
source and 374 AIR files, and lower every source file. Exit, stdout and
|
||||
stderr match byte for byte, including rejections.
|
||||
- **378 exact runtime/fuel/schedule pairs** on nine source/AIR inputs, including
|
||||
pending cancellation under a shield, resource handoff, returned loans,
|
||||
repeated cancelled join and task-loop propagation. Two quanta, three
|
||||
scheduler seeds and seven fuel values are compared; final-fuel results are
|
||||
checked against the fixture's expected value.
|
||||
- Targeted shield CLI suite: **291 checks**; existing CFG-provenance suite:
|
||||
**146 checks**; related-location suite: **409 checks** with 220 context
|
||||
records. These cover first E4305 conflict after node reuse, E3002/E4305
|
||||
priority at a join, source formatting/AIR fidelity and hosted execution.
|
||||
Hosted smoke, including local TCP sockets, and Zig formatting pass.
|
||||
|
||||
The frozen baseline contains both earlier Q-063 optimizations and Q-064. Raw
|
||||
qualification is in `/tmp/aji-q063-shield-20261014-y7i34hqh/`:
|
||||
`baseline.json`, frozen executables, `unit-final.log`,
|
||||
`conformance-final.jsonl`, `parity.jsonl`, `runtime-parity.jsonl`,
|
||||
`performance-final/` and `qualification.json` with source/binary hashes. The
|
||||
first endpoint-only experiment and intermediate sources remain separately
|
||||
labelled; they are not the final qualification. The reproducible targeted suite
|
||||
is `python3 tests/hosted/shield_relations.py`.
|
||||
@@ -675,9 +675,16 @@ frames, with AST identity/name/construct guards. Paired Debug mutable-match
|
||||
lowering at 512 levels falls from 30.982 to 0.635 seconds (48.77×), with 341 unit
|
||||
tests, 1,799 conformance cases and exact source/AIR/runtime comparisons. This
|
||||
preserves first-use kills, sibling exclusion and loop reads; it is not a global
|
||||
variable-liveness cache. Remaining assignment/read/positive-query costs and a
|
||||
separately reviewed shield relation optimization remain open. A later
|
||||
optimization needs exact CFG/SSA,
|
||||
variable-liveness cache. The
|
||||
[third optimization](control-depth-performance-audit.md#third-optimization-indexed-resource-relations-2026-10-14)
|
||||
indexes resource relations by endpoints and kind while preserving insertion
|
||||
order. Removal touches only incident facts, and loan checks no longer scan
|
||||
shield-order facts. Paired Debug source checking at 1,024 nested shields falls
|
||||
from 12.154 to 5.073 seconds (2.40×), with 348 unit tests,
|
||||
1,813 conformance cases and exact diagnostic/runtime/fuel comparisons. Index
|
||||
storage increases peak RSS; the audit records the measured tradeoff. The
|
||||
quadratic number of `.inner` facts and remaining assignment/read/positive-query
|
||||
costs keep Q-063 open. A later optimization needs exact CFG/SSA,
|
||||
diagnostic-order, host-OOM and runtime/fuel compatibility checks.
|
||||
No source-depth limit, new diagnostic, verifier rule, AIR instruction or
|
||||
language semantic change is introduced by recording this limitation.
|
||||
|
||||
@@ -10,6 +10,7 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](..
|
||||
| [harness.md](harness.md) | Agent scaffold and run recorder (E0-3): task format, evaluator contract, run record, commands |
|
||||
| [protocol.md](protocol.md) | Agent Language Evaluation Protocol 0.2: variables, benchmark families T01–T10, conditions `Aji/AIR` and `Aji/source`, maintenance and seeded-bug benchmarks, metrics, statistics, stages A–E, success and falsification criteria |
|
||||
| [../agent/README.md](../agent/README.md) | Agent Reference Bundle: contents, measurement, growth policy, milestones |
|
||||
| [dev-tasks/](dev-tasks/) | Public dev tasks. `dev-echo` and `dev-netprobe` check the harness. `dev-intervals`, `dev-lru` and `dev-shards` (family `failure-calibration`) cover collections with invalid input, an owning cache and sharded concurrency; their failures calibrate `ajieval classify --suggest`. Each has a public evaluator over a Python model and a Rust reference under `reference/`. [dev-failure-plan.json](dev-failure-plan.json) runs them. Dev material: never evidence, and the language is not tuned to them |
|
||||
|
||||
## Integrity rules (protocol §7, §29; spec 14 §12)
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"comment": "Dev failure-calibration matrix (dev set; never evidence): runs whose failures calibrate `ajieval classify --suggest`. Run from tools/eval: python3 -m ajieval matrix ../../docs/evaluation/dev-failure-plan.json",
|
||||
"tasks": ["dev-tasks/dev-intervals", "dev-tasks/dev-lru", "dev-tasks/dev-shards"],
|
||||
"languages": ["aji_source", "aji_air", "rust", "zig"],
|
||||
"models": [
|
||||
{"label": "N1", "agent": "codex", "model": "gpt-6.1-sol", "effort": "high"},
|
||||
{"label": "N2", "agent": "claude", "model": "claude-opus-5-5", "effort": "high"},
|
||||
{"label": "N3", "agent": "opencode", "model": "zai-coding-plan/glm-5.3-flash"}
|
||||
],
|
||||
"runs": 1,
|
||||
"evaluator": "dev-tasks/evaluate.py",
|
||||
"evaluator_hash_path": "dev-tasks",
|
||||
"out": "../../tools/eval/runs-dev-failure"
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Evaluator for dev-intervals (dev set; public).
|
||||
|
||||
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import devlib # noqa: E402
|
||||
|
||||
LIMIT = 1 << 63
|
||||
|
||||
|
||||
def number(tok):
|
||||
if not tok or not tok.isascii() or not tok.isdigit() or (len(tok) > 1 and tok[0] == "0"):
|
||||
return None
|
||||
v = int(tok)
|
||||
return v if v < LIMIT else None
|
||||
|
||||
|
||||
def model(text):
|
||||
"""Reference semantics: the sorted list of disjoint, non-touching intervals."""
|
||||
ivs, out = [], []
|
||||
lines = text.split("\n")
|
||||
if text.endswith("\n"):
|
||||
lines.pop()
|
||||
if text == "":
|
||||
lines = []
|
||||
for line in lines:
|
||||
parts = line.split(" ")
|
||||
cmd, args = parts[0], parts[1:]
|
||||
nums = [number(a) for a in args]
|
||||
if None in nums:
|
||||
out.append("error")
|
||||
elif cmd in ("add", "remove") and len(nums) == 2 and nums[0] < nums[1]:
|
||||
a, b = nums
|
||||
keep = []
|
||||
for x, y in ivs:
|
||||
if cmd == "remove" or y < a or x > b:
|
||||
if y <= a or x >= b:
|
||||
keep.append((x, y))
|
||||
else:
|
||||
if x < a:
|
||||
keep.append((x, a))
|
||||
if y > b:
|
||||
keep.append((b, y))
|
||||
else:
|
||||
a, b = min(a, x), max(b, y)
|
||||
if cmd == "add":
|
||||
keep.append((a, b))
|
||||
ivs = sorted(keep)
|
||||
elif cmd == "covered" and len(nums) == 1:
|
||||
out.append("yes" if any(x <= nums[0] < y for x, y in ivs) else "no")
|
||||
elif cmd == "count" and not args:
|
||||
out.append(str(len(ivs)))
|
||||
elif cmd == "total" and not args:
|
||||
out.append(str(sum(y - x for x, y in ivs)))
|
||||
elif cmd == "list" and not args:
|
||||
out.append(" ".join(f"{x}-{y}" for x, y in ivs) or "empty")
|
||||
else:
|
||||
out.append("error")
|
||||
return "".join(o + "\n" for o in out)
|
||||
|
||||
|
||||
def gen(rng, n, lo, hi, invalid=0.0):
|
||||
lines = []
|
||||
for _ in range(n):
|
||||
r = rng.random()
|
||||
if r < invalid:
|
||||
lines.append(rng.choice(["", "add", "add 1", "add 3 3", "add 5 2", "remove 01 4", "add -1 4", "covered",
|
||||
"covered x", "count 1", "list now", "total ", " total", "add 1 2", "Add 1 2",
|
||||
f"add 0 {LIMIT}", f"covered {LIMIT + 5}", "add 1 2 3", "add\t1 2", "remove 2 1"]))
|
||||
continue
|
||||
k = rng.random()
|
||||
a = rng.randrange(lo, hi)
|
||||
b = a + rng.randrange(1, max(2, (hi - lo) // 8))
|
||||
if k < 0.35:
|
||||
lines.append(f"add {a} {b}")
|
||||
elif k < 0.55:
|
||||
lines.append(f"remove {a} {b}")
|
||||
elif k < 0.75:
|
||||
lines.append(f"covered {rng.randrange(lo, hi)}")
|
||||
else:
|
||||
lines.append(rng.choice(["count", "total", "list"]))
|
||||
return "\n".join(lines) + ("\n" if rng.random() < 0.8 else "")
|
||||
|
||||
|
||||
def case(text):
|
||||
return (text, model(text))
|
||||
|
||||
|
||||
PUBLIC = [case("add 10 20\nadd 20 25\ncovered 24\nremove 12 14\nlist\ncount\ntotal\nadd 5 5\n")]
|
||||
|
||||
rng = random.Random(20261007)
|
||||
HIDDEN = [
|
||||
case(""),
|
||||
case("list\ncount\ntotal\ncovered 0\n"),
|
||||
case("add 0 1\nadd 2 3\nadd 1 2\nlist\nremove 0 3\nlist\n"),
|
||||
case(f"add 0 {LIMIT - 1}\ntotal\ncovered {LIMIT - 2}\ncovered {LIMIT - 1}\nlist\nremove 1 {LIMIT - 2}\nlist\ntotal"),
|
||||
case("add 5 10\nremove 0 100\nadd 1 2\nadd 3 4\nadd 5 6\nadd 2 3\nlist\ncount\nadd 4 5\nlist\n"),
|
||||
case("add 7 9\n\nadd 9 11\nlist\nadd 1 2 \nlist"),
|
||||
case(gen(rng, 60, 0, 100, invalid=0.25)),
|
||||
case(gen(rng, 400, 0, 1000, invalid=0.05)),
|
||||
case(gen(rng, 700, 0, 1 << 40, invalid=0.02)),
|
||||
case("\n".join(f"add {2 * i} {2 * i + 1}" for i in range(1400)) + "\ncount\ntotal\ncovered 2799\ncovered 2798\n"),
|
||||
]
|
||||
|
||||
if __name__ == "__main__":
|
||||
devlib.evaluate(devlib.Spec("intervals", heap=4 << 20, fuel=400_000_000, public=PUBLIC, hidden=HIDDEN))
|
||||
@@ -0,0 +1,6 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.air`, a text AIR module.
|
||||
- Entry point: `@main(%in: cap<io.read>, %out: cap<io.write>, %heap: cap<mem.alloc>)`; any return type.
|
||||
- The program is run as `aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.air`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
|
||||
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
rec=$(aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'add 10 20
|
||||
add 20 25
|
||||
covered 24
|
||||
remove 12 14
|
||||
list
|
||||
count
|
||||
total
|
||||
add 5 5
|
||||
' main.air)
|
||||
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
|
||||
expected=$(printf "%s" 'yes
|
||||
10-12 14-25
|
||||
2
|
||||
13
|
||||
error
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.aji`, an `.aji` module.
|
||||
- Entry point: `main(input: cap<io.read>, out: cap<io.write>, heap: cap<mem.alloc>)`; any return type.
|
||||
- The program is run as `aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.aji`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
|
||||
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
rec=$(aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'add 10 20
|
||||
add 20 25
|
||||
covered 24
|
||||
remove 12 14
|
||||
list
|
||||
count
|
||||
total
|
||||
add 5 5
|
||||
' main.aji)
|
||||
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
|
||||
expected=$(printf "%s" 'yes
|
||||
10-12 14-25
|
||||
2
|
||||
13
|
||||
error
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "intervals"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,5 @@
|
||||
# Interface
|
||||
|
||||
- Cargo package `intervals` in this directory; the binary is `target/debug/intervals`.
|
||||
- The program reads standard input and writes standard output, as the task describes.
|
||||
- Only the standard library is available (no network, `--offline`).
|
||||
@@ -0,0 +1 @@
|
||||
fn main() {}
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'add 10 20
|
||||
add 20 25
|
||||
covered 24
|
||||
remove 12 14
|
||||
list
|
||||
count
|
||||
total
|
||||
add 5 5
|
||||
' | ./target/debug/intervals) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'yes
|
||||
10-12 14-25
|
||||
2
|
||||
13
|
||||
error
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,4 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`.
|
||||
- The program reads standard input and writes standard output, as the task describes.
|
||||
@@ -0,0 +1 @@
|
||||
pub fn main() void {}
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'add 10 20
|
||||
add 20 25
|
||||
covered 24
|
||||
remove 12 14
|
||||
list
|
||||
count
|
||||
total
|
||||
add 5 5
|
||||
' | ./main) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'yes
|
||||
10-12 14-25
|
||||
2
|
||||
13
|
||||
error
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,57 @@
|
||||
# Task: interval set
|
||||
|
||||
Development task (dev set). Its results are not evidence about any language.
|
||||
|
||||
Write a program that maintains a set of non-negative integers, described as half-open intervals, and answers queries about it. The program reads commands from standard input, one per line, and writes its answers to standard output.
|
||||
|
||||
## Input
|
||||
|
||||
The input is a sequence of lines separated by `\n`. If the input ends with `\n`, that final `\n` does not start another line. The input is at most 24 KiB and has at most 2000 lines. It may be empty.
|
||||
|
||||
A **number** is written in decimal with the ASCII digits `0`–`9`. It has no sign, no leading zeros (except the number `0` itself), and is less than 2^63 = 9223372036854775808.
|
||||
|
||||
A line is a valid command when it is exactly one of the forms below: the command word, then the stated number of arguments, each separated by exactly one space. There are no other spaces or characters.
|
||||
|
||||
| Command | Meaning | Output |
|
||||
|---|---|---|
|
||||
| `add A B` | requires `A < B`; adds every integer x with A ≤ x < B to the set | nothing |
|
||||
| `remove A B` | requires `A < B`; removes every integer x with A ≤ x < B from the set | nothing |
|
||||
| `covered X` | is X in the set? | `yes` or `no` |
|
||||
| `count` | the number of maximal intervals the set consists of | the number |
|
||||
| `total` | how many integers the set contains | the number |
|
||||
| `list` | the maximal intervals in increasing order | `A-B` for each maximal interval [A, B), separated by single spaces; `empty` if the set is empty |
|
||||
|
||||
A **maximal interval** is a half-open interval [A, B) contained in the set such that neither A − 1 nor B is in the set. For example, after `add 1 3` and `add 3 5`, the set consists of one maximal interval, `1-5`.
|
||||
|
||||
Any other line, including an empty line, an unknown command, a wrong number of arguments, a malformed number, a number of 2^63 or more, and `add` or `remove` with `A ≥ B`, is **invalid**. For an invalid line the program writes `error` and leaves the set unchanged.
|
||||
|
||||
## Output
|
||||
|
||||
One output line for each command that produces output and for each invalid line, in input order. Every output line ends with `\n`. Nothing else is written to standard output.
|
||||
|
||||
## Example
|
||||
|
||||
Input:
|
||||
|
||||
```text
|
||||
add 10 20
|
||||
add 20 25
|
||||
covered 24
|
||||
remove 12 14
|
||||
list
|
||||
count
|
||||
total
|
||||
add 5 5
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```text
|
||||
yes
|
||||
10-12 14-25
|
||||
2
|
||||
13
|
||||
error
|
||||
```
|
||||
|
||||
The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. Hidden tests check the requirements above, including invalid input.
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "intervals"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,55 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
const LIMIT: u64 = 1 << 63;
|
||||
|
||||
fn number(t: &str) -> Option<u64> {
|
||||
if t.is_empty() || !t.bytes().all(|b| b.is_ascii_digit()) || (t.len() > 1 && t.starts_with('0')) || t.len() > 19 {
|
||||
return None;
|
||||
}
|
||||
t.parse::<u64>().ok().filter(|&v| v < LIMIT)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_to_string(&mut input).unwrap();
|
||||
let mut lines: Vec<&str> = input.split('\n').collect();
|
||||
if input.ends_with('\n') || input.is_empty() {
|
||||
lines.pop();
|
||||
}
|
||||
let mut set: BTreeMap<u64, u64> = BTreeMap::new(); // start -> end, disjoint, non-touching
|
||||
let mut out = String::new();
|
||||
for line in lines {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
let nums: Option<Vec<u64>> = parts[1..].iter().map(|t| number(t)).collect();
|
||||
let Some(nums) = nums else { out.push_str("error\n"); continue };
|
||||
match (parts[0], nums.as_slice()) {
|
||||
("add", &[a, b]) | ("remove", &[a, b]) if a < b => {
|
||||
let (mut a2, mut b2) = (a, b);
|
||||
let hit: Vec<(u64, u64)> = set.range(..=b).filter(|&(_, &y)| y >= a).map(|(&x, &y)| (x, y)).collect();
|
||||
for (x, y) in hit {
|
||||
set.remove(&x);
|
||||
if parts[0] == "add" {
|
||||
a2 = a2.min(x);
|
||||
b2 = b2.max(y);
|
||||
} else {
|
||||
if x < a { set.insert(x, a); }
|
||||
if y > b { set.insert(b, y); }
|
||||
}
|
||||
}
|
||||
if parts[0] == "add" { set.insert(a2, b2); }
|
||||
}
|
||||
("covered", &[x]) => out.push_str(if set.range(..=x).next_back().map_or(false, |(_, &y)| x < y) { "yes\n" } else { "no\n" }),
|
||||
("count", &[]) => out.push_str(&format!("{}\n", set.len())),
|
||||
("total", &[]) => out.push_str(&format!("{}\n", set.iter().map(|(x, y)| y - x).sum::<u64>())),
|
||||
("list", &[]) => {
|
||||
let s: Vec<String> = set.iter().map(|(x, y)| format!("{x}-{y}")).collect();
|
||||
out.push_str(if s.is_empty() { "empty" } else { "" });
|
||||
out.push_str(&s.join(" "));
|
||||
out.push('\n');
|
||||
}
|
||||
_ => out.push_str("error\n"),
|
||||
}
|
||||
}
|
||||
std::io::stdout().write_all(out.as_bytes()).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'add 10 20
|
||||
add 20 25
|
||||
covered 24
|
||||
remove 12 14
|
||||
list
|
||||
count
|
||||
total
|
||||
add 5 5
|
||||
' | ./target/debug/intervals) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'yes
|
||||
10-12 14-25
|
||||
2
|
||||
13
|
||||
error
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"id": "dev-intervals",
|
||||
"version": "1",
|
||||
"set": "dev",
|
||||
"family": "failure-calibration",
|
||||
"prompt": "prompt.md",
|
||||
"languages": {
|
||||
"aji_air": {"workspace": "lang/aji_air", "test": "sh test.sh"},
|
||||
"aji_source": {"workspace": "lang/aji_source", "test": "sh test.sh"},
|
||||
"rust": {"workspace": "lang/rust", "test": "sh test.sh"},
|
||||
"zig": {"workspace": "lang/zig", "test": "sh test.sh"}
|
||||
},
|
||||
"limits": {"tool_calls": 80, "total_tokens": 1500000, "wall_seconds": 1800, "command_timeout": 120},
|
||||
"concurrency": false
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Evaluator for dev-lru (dev set; public).
|
||||
|
||||
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import devlib # noqa: E402
|
||||
|
||||
TOKEN = re.compile(r"[a-z0-9]{1,16}")
|
||||
|
||||
|
||||
def model(text):
|
||||
lines = text.split("\n")
|
||||
if text.endswith("\n"):
|
||||
lines.pop()
|
||||
cap = int(lines[0].split(" ")[1])
|
||||
cache = OrderedDict() # least recent first
|
||||
hits = misses = evictions = 0
|
||||
out = []
|
||||
for line in lines[1:]:
|
||||
parts = line.split(" ")
|
||||
cmd, args = parts[0], parts[1:]
|
||||
if not all(TOKEN.fullmatch(a) for a in args):
|
||||
out.append("error")
|
||||
elif cmd == "put" and len(args) == 2:
|
||||
k, v = args
|
||||
if k in cache:
|
||||
out.append("ok")
|
||||
elif len(cache) == cap:
|
||||
old, _ = cache.popitem(last=False)
|
||||
evictions += 1
|
||||
out.append(f"evict {old}")
|
||||
else:
|
||||
out.append("ok")
|
||||
cache[k] = v
|
||||
cache.move_to_end(k)
|
||||
elif cmd == "get" and len(args) == 1:
|
||||
k = args[0]
|
||||
if k in cache:
|
||||
hits += 1
|
||||
cache.move_to_end(k)
|
||||
out.append(cache[k])
|
||||
else:
|
||||
misses += 1
|
||||
out.append("miss")
|
||||
elif cmd == "peek" and len(args) == 1:
|
||||
out.append(cache.get(args[0], "miss"))
|
||||
elif cmd == "del" and len(args) == 1:
|
||||
out.append("ok" if cache.pop(args[0], None) is not None else "miss")
|
||||
elif cmd == "stats" and not args:
|
||||
out.append(f"size {len(cache)} hits {hits} misses {misses} evictions {evictions}")
|
||||
elif cmd == "dump" and not args:
|
||||
out.append(" ".join(reversed(cache)) or "empty")
|
||||
else:
|
||||
out.append("error")
|
||||
return "".join(o + "\n" for o in out)
|
||||
|
||||
|
||||
def token(rng, alphabet="abcdefghijklmnopqrstuvwxyz0123456789", lo=1, hi=16):
|
||||
return "".join(rng.choice(alphabet) for _ in range(rng.randint(lo, hi)))
|
||||
|
||||
|
||||
def gen(rng, cap, n, keys, invalid=0.0):
|
||||
pool = [token(rng, lo=1, hi=8) for _ in range(keys)]
|
||||
lines = [f"capacity {cap}"]
|
||||
for _ in range(n):
|
||||
r = rng.random()
|
||||
if r < invalid:
|
||||
lines.append(rng.choice(["", "put a", "put A 1", "get", "get a b", "peek -", "del " + "x" * 17, "stats now",
|
||||
"dump 1", "put a 1", "put a 1 ", "Get a", "put a\t1", "put é 1", "evict a", "get a_b"]))
|
||||
continue
|
||||
k = rng.choice(pool)
|
||||
c = rng.random()
|
||||
if c < 0.4:
|
||||
lines.append(f"put {k} {token(rng)}")
|
||||
elif c < 0.7:
|
||||
lines.append(f"get {k}")
|
||||
elif c < 0.8:
|
||||
lines.append(f"peek {k}")
|
||||
elif c < 0.9:
|
||||
lines.append(f"del {k}")
|
||||
else:
|
||||
lines.append(rng.choice(["stats", "dump"]))
|
||||
return "\n".join(lines) + ("\n" if rng.random() < 0.8 else "")
|
||||
|
||||
|
||||
def case(text):
|
||||
return (text, model(text))
|
||||
|
||||
|
||||
PUBLIC = [case("capacity 2\nput a 1\nput b 2\nget a\nput c 3\npeek b\ndump\nget b\nstats\nput a 9\nget a\ndel zz\n")]
|
||||
|
||||
rng = random.Random(20261008)
|
||||
HIDDEN = [
|
||||
case("capacity 1\ndump\nstats\nput k v\nput k w\nget k\nput j x\ndump\nget k\nstats\n"),
|
||||
case("capacity 3\nput a 1\nput b 2\nput c 3\nget a\nput d 4\ndel c\nput e 5\ndump\nstats"),
|
||||
case("capacity 2\nput a 1\npeek a\nput b 2\nput c 3\ndump\nput b 7\nput d 8\ndump\n"),
|
||||
case("capacity 4\n\nput a 1\nput a 1 2\nput " + "z" * 16 + " " + "9" * 16 + "\nget " + "z" * 16 + "\nput " + "z" * 17 + " 1\nstats\n"),
|
||||
case(gen(rng, 3, 80, 6, invalid=0.2)),
|
||||
case(gen(rng, 10, 600, 30, invalid=0.05)),
|
||||
case(gen(rng, 50, 1200, 200, invalid=0.02)),
|
||||
case(gen(rng, 1000, 1400, 900, invalid=0.01)),
|
||||
case("capacity 1000\n" + "".join(f"put k{i} v{i}\n" for i in range(1000)) + "put kx vx\ndump\nstats\n"),
|
||||
]
|
||||
|
||||
if __name__ == "__main__":
|
||||
devlib.evaluate(devlib.Spec("lru", heap=4 << 20, fuel=400_000_000, public=PUBLIC, hidden=HIDDEN))
|
||||
@@ -0,0 +1,6 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.air`, a text AIR module.
|
||||
- Entry point: `@main(%in: cap<io.read>, %out: cap<io.write>, %heap: cap<mem.alloc>)`; any return type.
|
||||
- The program is run as `aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.air`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
|
||||
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
rec=$(aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'capacity 2
|
||||
put a 1
|
||||
put b 2
|
||||
get a
|
||||
put c 3
|
||||
peek b
|
||||
dump
|
||||
get b
|
||||
stats
|
||||
put a 9
|
||||
get a
|
||||
del zz
|
||||
' main.air)
|
||||
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
|
||||
expected=$(printf "%s" 'ok
|
||||
ok
|
||||
1
|
||||
evict b
|
||||
miss
|
||||
c a
|
||||
miss
|
||||
size 2 hits 1 misses 1 evictions 1
|
||||
ok
|
||||
9
|
||||
miss
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.aji`, an `.aji` module.
|
||||
- Entry point: `main(input: cap<io.read>, out: cap<io.write>, heap: cap<mem.alloc>)`; any return type.
|
||||
- The program is run as `aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.aji`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
|
||||
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
rec=$(aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'capacity 2
|
||||
put a 1
|
||||
put b 2
|
||||
get a
|
||||
put c 3
|
||||
peek b
|
||||
dump
|
||||
get b
|
||||
stats
|
||||
put a 9
|
||||
get a
|
||||
del zz
|
||||
' main.aji)
|
||||
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
|
||||
expected=$(printf "%s" 'ok
|
||||
ok
|
||||
1
|
||||
evict b
|
||||
miss
|
||||
c a
|
||||
miss
|
||||
size 2 hits 1 misses 1 evictions 1
|
||||
ok
|
||||
9
|
||||
miss
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "lru"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,5 @@
|
||||
# Interface
|
||||
|
||||
- Cargo package `lru` in this directory; the binary is `target/debug/lru`.
|
||||
- The program reads standard input and writes standard output, as the task describes.
|
||||
- Only the standard library is available (no network, `--offline`).
|
||||
@@ -0,0 +1 @@
|
||||
fn main() {}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'capacity 2
|
||||
put a 1
|
||||
put b 2
|
||||
get a
|
||||
put c 3
|
||||
peek b
|
||||
dump
|
||||
get b
|
||||
stats
|
||||
put a 9
|
||||
get a
|
||||
del zz
|
||||
' | ./target/debug/lru) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'ok
|
||||
ok
|
||||
1
|
||||
evict b
|
||||
miss
|
||||
c a
|
||||
miss
|
||||
size 2 hits 1 misses 1 evictions 1
|
||||
ok
|
||||
9
|
||||
miss
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,4 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`.
|
||||
- The program reads standard input and writes standard output, as the task describes.
|
||||
@@ -0,0 +1 @@
|
||||
pub fn main() void {}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'capacity 2
|
||||
put a 1
|
||||
put b 2
|
||||
get a
|
||||
put c 3
|
||||
peek b
|
||||
dump
|
||||
get b
|
||||
stats
|
||||
put a 9
|
||||
get a
|
||||
del zz
|
||||
' | ./main) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'ok
|
||||
ok
|
||||
1
|
||||
evict b
|
||||
miss
|
||||
c a
|
||||
miss
|
||||
size 2 hits 1 misses 1 evictions 1
|
||||
ok
|
||||
9
|
||||
miss
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,69 @@
|
||||
# Task: least-recently-used cache
|
||||
|
||||
Development task (dev set). Its results are not evidence about any language.
|
||||
|
||||
Write a program that simulates a key–value cache of bounded size which evicts the least recently used key. The program reads commands from standard input, one per line, and writes its answers to standard output.
|
||||
|
||||
## Input
|
||||
|
||||
The input is a sequence of lines separated by `\n`. If the input ends with `\n`, that final `\n` does not start another line. The input is at most 32 KiB and has at most 1500 lines.
|
||||
|
||||
The first line is always `capacity C`, where C is a decimal number with 1 ≤ C ≤ 1000 and no leading zeros. It produces no output. Every later line is a command.
|
||||
|
||||
A **token** is 1 to 16 characters, each an ASCII lowercase letter `a`–`z` or digit `0`–`9`. Keys and values are tokens.
|
||||
|
||||
A line is a valid command when it is exactly one of the forms below: the command word, then its arguments, each separated by exactly one space. There are no other spaces or characters.
|
||||
|
||||
| Command | Effect | Output |
|
||||
|---|---|---|
|
||||
| `put K V` | If K is in the cache, its value becomes V. Otherwise, if the cache holds C keys, the least recently used key L is removed first, then K is added with value V. In both cases K becomes the most recently used key. | `evict L` if a key was removed, otherwise `ok` |
|
||||
| `get K` | If K is in the cache, K becomes the most recently used key. | the value of K, or `miss` |
|
||||
| `peek K` | Nothing changes. | the value of K, or `miss` |
|
||||
| `del K` | Removes K if it is in the cache. | `ok` if it was removed, otherwise `miss` |
|
||||
| `stats` | Nothing changes. | `size S hits H misses M evictions E` |
|
||||
| `dump` | Nothing changes. | the keys from the most to the least recently used, separated by single spaces; `empty` if the cache is empty |
|
||||
|
||||
**Recency** changes only through `put` and a `get` that finds its key. S is the number of keys in the cache. H and M count the `get` commands that found and did not find their key; `peek` is not counted. E counts the keys removed by `put`; `del` is not counted.
|
||||
|
||||
Any other line, including an empty line, an unknown command, a wrong number of arguments, or an argument that is not a token, is **invalid**. For an invalid line the program writes `error` and changes nothing.
|
||||
|
||||
## Output
|
||||
|
||||
One output line for each command and for each invalid line, in input order. Every output line ends with `\n`. Nothing else is written to standard output.
|
||||
|
||||
## Example
|
||||
|
||||
Input:
|
||||
|
||||
```text
|
||||
capacity 2
|
||||
put a 1
|
||||
put b 2
|
||||
get a
|
||||
put c 3
|
||||
peek b
|
||||
dump
|
||||
get b
|
||||
stats
|
||||
put a 9
|
||||
get a
|
||||
del zz
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```text
|
||||
ok
|
||||
ok
|
||||
1
|
||||
evict b
|
||||
miss
|
||||
c a
|
||||
miss
|
||||
size 2 hits 1 misses 1 evictions 1
|
||||
ok
|
||||
9
|
||||
miss
|
||||
```
|
||||
|
||||
The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. Hidden tests check the requirements above, including invalid input.
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "lru"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,61 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn token(t: &str) -> bool {
|
||||
(1..=16).contains(&t.len()) && t.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_to_string(&mut input).unwrap();
|
||||
let mut lines: Vec<&str> = input.split('\n').collect();
|
||||
if input.ends_with('\n') {
|
||||
lines.pop();
|
||||
}
|
||||
let cap: usize = lines[0]["capacity ".len()..].parse().unwrap();
|
||||
// key -> (value, last use); recency is the use counter.
|
||||
let mut map: HashMap<String, (String, u64)> = HashMap::new();
|
||||
let (mut clock, mut hits, mut misses, mut evictions) = (0u64, 0u64, 0u64, 0u64);
|
||||
let mut out = String::new();
|
||||
for line in &lines[1..] {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
let args = &parts[1..];
|
||||
if !args.iter().all(|a| token(a)) {
|
||||
out.push_str("error\n");
|
||||
continue;
|
||||
}
|
||||
clock += 1;
|
||||
match (parts[0], args) {
|
||||
("put", [k, v]) => {
|
||||
if map.contains_key(*k) {
|
||||
out.push_str("ok\n");
|
||||
} else if map.len() == cap {
|
||||
let old = map.iter().min_by_key(|(_, (_, t))| *t).map(|(k, _)| k.clone()).unwrap();
|
||||
map.remove(&old);
|
||||
evictions += 1;
|
||||
out.push_str(&format!("evict {old}\n"));
|
||||
} else {
|
||||
out.push_str("ok\n");
|
||||
}
|
||||
map.insert(k.to_string(), (v.to_string(), clock));
|
||||
}
|
||||
("get", [k]) => match map.get_mut(*k) {
|
||||
Some((v, t)) => { *t = clock; hits += 1; out.push_str(&format!("{v}\n")); }
|
||||
None => { misses += 1; out.push_str("miss\n"); }
|
||||
},
|
||||
("peek", [k]) => out.push_str(&format!("{}\n", map.get(*k).map_or("miss", |(v, _)| v.as_str()))),
|
||||
("del", [k]) => out.push_str(if map.remove(*k).is_some() { "ok\n" } else { "miss\n" }),
|
||||
("stats", []) => out.push_str(&format!("size {} hits {hits} misses {misses} evictions {evictions}\n", map.len())),
|
||||
("dump", []) => {
|
||||
let mut keys: Vec<(&String, u64)> = map.iter().map(|(k, (_, t))| (k, *t)).collect();
|
||||
keys.sort_by(|a, b| b.1.cmp(&a.1));
|
||||
let s: Vec<&str> = keys.iter().map(|(k, _)| k.as_str()).collect();
|
||||
out.push_str(if s.is_empty() { "empty" } else { "" });
|
||||
out.push_str(&s.join(" "));
|
||||
out.push('\n');
|
||||
}
|
||||
_ => out.push_str("error\n"),
|
||||
}
|
||||
}
|
||||
std::io::stdout().write_all(out.as_bytes()).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'capacity 2
|
||||
put a 1
|
||||
put b 2
|
||||
get a
|
||||
put c 3
|
||||
peek b
|
||||
dump
|
||||
get b
|
||||
stats
|
||||
put a 9
|
||||
get a
|
||||
del zz
|
||||
' | ./target/debug/lru) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'ok
|
||||
ok
|
||||
1
|
||||
evict b
|
||||
miss
|
||||
c a
|
||||
miss
|
||||
size 2 hits 1 misses 1 evictions 1
|
||||
ok
|
||||
9
|
||||
miss
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"id": "dev-lru",
|
||||
"version": "1",
|
||||
"set": "dev",
|
||||
"family": "failure-calibration",
|
||||
"prompt": "prompt.md",
|
||||
"languages": {
|
||||
"aji_air": {"workspace": "lang/aji_air", "test": "sh test.sh"},
|
||||
"aji_source": {"workspace": "lang/aji_source", "test": "sh test.sh"},
|
||||
"rust": {"workspace": "lang/rust", "test": "sh test.sh"},
|
||||
"zig": {"workspace": "lang/zig", "test": "sh test.sh"}
|
||||
},
|
||||
"limits": {"tool_calls": 80, "total_tokens": 1500000, "wall_seconds": 1800, "command_timeout": 120},
|
||||
"concurrency": false
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Evaluator for dev-shards (dev set; public).
|
||||
|
||||
Besides the output, two gates cover the concurrency requirement:
|
||||
uses_concurrency the source starts threads or tasks (a coarse static check);
|
||||
hidden for Aji, every hidden case runs under three schedule seeds.
|
||||
|
||||
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout
|
||||
"""
|
||||
import collections
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import devlib # noqa: E402
|
||||
|
||||
WORD = re.compile(r"[A-Za-z]+")
|
||||
SPAWN = {
|
||||
"aji_air": r"\btask\.spawn\b",
|
||||
"aji_source": r"\btask\.spawn\b",
|
||||
"rust": r"thread::(spawn|scope)|\.spawn\(",
|
||||
"zig": r"Thread\.spawn|std\.Thread",
|
||||
}
|
||||
|
||||
|
||||
def model(text):
|
||||
lines = text.split("\n")
|
||||
if text.endswith("\n"):
|
||||
lines.pop()
|
||||
w = int(lines[0].split(" ")[1])
|
||||
per = [[0, 0] for _ in range(w)]
|
||||
counts = collections.Counter()
|
||||
for k, line in enumerate(lines[1:]):
|
||||
words = [m.lower()[:16] for m in WORD.findall(line)]
|
||||
per[k % w][0] += 1
|
||||
per[k % w][1] += len(words)
|
||||
counts.update(words)
|
||||
out = [f"worker {i} lines {l} words {n}" for i, (l, n) in enumerate(per)]
|
||||
out.append(f"distinct {len(counts)}")
|
||||
out += [f"{word} {c}" for word, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].encode()))[:10]]
|
||||
return "".join(o + "\n" for o in out)
|
||||
|
||||
|
||||
def gen(rng, w, n, vocab):
|
||||
words = ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(1, 20))) for _ in range(vocab)]
|
||||
lines = [f"workers {w}"]
|
||||
for _ in range(n):
|
||||
parts = []
|
||||
for _ in range(rng.randint(0, 6)):
|
||||
word = rng.choice(words) if rng.random() < 0.8 else rng.choice(words[:5])
|
||||
if rng.random() < 0.2:
|
||||
word = word.upper() if rng.random() < 0.5 else word.capitalize()
|
||||
parts.append(word)
|
||||
parts.append(rng.choice([" ", " ", ", ", ". ", "-", " ", "1", "'", "\t", "_"]))
|
||||
lines.append("".join(parts))
|
||||
return "\n".join(lines) + ("\n" if rng.random() < 0.8 else "")
|
||||
|
||||
|
||||
def case(text):
|
||||
return (text, model(text))
|
||||
|
||||
|
||||
PUBLIC = [case("workers 2\nThe cat sat.\nthe CAT, the hat\na-b-c\n")]
|
||||
|
||||
rng = random.Random(20261009)
|
||||
HIDDEN = [
|
||||
case("workers 1\n"),
|
||||
case("workers 8\nalpha\n\n...\nBeta beta\n"),
|
||||
case("workers 3\nabcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopXYZ\nx1y2z3\n"),
|
||||
case("workers 4\nb a\na b\nc\nb\n"),
|
||||
case(gen(rng, 2, 50, 12)),
|
||||
case(gen(rng, 5, 400, 80)),
|
||||
case(gen(rng, 8, 600, 600)),
|
||||
case(gen(rng, 7, 550, 1500)),
|
||||
case("workers 6\n" + "".join(rng.choice(["a", "b b", "", "C", "d.e"]) + "\n" for _ in range(1990))),
|
||||
]
|
||||
|
||||
|
||||
def gates(ws, lang):
|
||||
return {"uses_concurrency": devlib.source_matches(ws, lang, SPAWN)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
devlib.evaluate(devlib.Spec("shards", heap=16 << 20, fuel=800_000_000, public=PUBLIC, hidden=HIDDEN,
|
||||
extra_gates=gates, schedule_seeds=(0, 1, 2)))
|
||||
@@ -0,0 +1,6 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.air`, a text AIR module.
|
||||
- Entry point: `@main(%in: cap<io.read>, %out: cap<io.write>, %heap: cap<mem.alloc>)`; any return type.
|
||||
- The program is run as `aji run --fuel 800000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin TEXT main.air`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
|
||||
- The heap budget is 16777216 bytes of live allocations; the run stops after 800000000 executed instructions. The program may spawn tasks (effect `task.spawn`); the evaluator runs it under several schedule seeds (`--schedule-seed N`), and the output must be the same for each.
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
rec=$(aji run --fuel 800000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin 'workers 2
|
||||
The cat sat.
|
||||
the CAT, the hat
|
||||
a-b-c
|
||||
' main.air)
|
||||
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
|
||||
expected=$(printf "%s" 'worker 0 lines 2 words 6
|
||||
worker 1 lines 1 words 4
|
||||
distinct 7
|
||||
the 3
|
||||
cat 2
|
||||
a 1
|
||||
b 1
|
||||
c 1
|
||||
hat 1
|
||||
sat 1
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.aji`, an `.aji` module.
|
||||
- Entry point: `main(input: cap<io.read>, out: cap<io.write>, heap: cap<mem.alloc>)`; any return type.
|
||||
- The program is run as `aji run --fuel 800000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin TEXT main.aji`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
|
||||
- The heap budget is 16777216 bytes of live allocations; the run stops after 800000000 executed instructions. The program may spawn tasks (effect `task.spawn`); the evaluator runs it under several schedule seeds (`--schedule-seed N`), and the output must be the same for each.
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
rec=$(aji run --fuel 800000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin 'workers 2
|
||||
The cat sat.
|
||||
the CAT, the hat
|
||||
a-b-c
|
||||
' main.aji)
|
||||
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
|
||||
expected=$(printf "%s" 'worker 0 lines 2 words 6
|
||||
worker 1 lines 1 words 4
|
||||
distinct 7
|
||||
the 3
|
||||
cat 2
|
||||
a 1
|
||||
b 1
|
||||
c 1
|
||||
hat 1
|
||||
sat 1
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "shards"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,5 @@
|
||||
# Interface
|
||||
|
||||
- Cargo package `shards` in this directory; the binary is `target/debug/shards`.
|
||||
- The program reads standard input and writes standard output, as the task describes.
|
||||
- Only the standard library is available (no network, `--offline`).
|
||||
@@ -0,0 +1 @@
|
||||
fn main() {}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'workers 2
|
||||
The cat sat.
|
||||
the CAT, the hat
|
||||
a-b-c
|
||||
' | ./target/debug/shards) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'worker 0 lines 2 words 6
|
||||
worker 1 lines 1 words 4
|
||||
distinct 7
|
||||
the 3
|
||||
cat 2
|
||||
a 1
|
||||
b 1
|
||||
c 1
|
||||
hat 1
|
||||
sat 1
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,4 @@
|
||||
# Interface
|
||||
|
||||
- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`.
|
||||
- The program reads standard input and writes standard output, as the task describes.
|
||||
@@ -0,0 +1 @@
|
||||
pub fn main() void {}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'workers 2
|
||||
The cat sat.
|
||||
the CAT, the hat
|
||||
a-b-c
|
||||
' | ./main) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'worker 0 lines 2 words 6
|
||||
worker 1 lines 1 words 4
|
||||
distinct 7
|
||||
the 3
|
||||
cat 2
|
||||
a 1
|
||||
b 1
|
||||
c 1
|
||||
hat 1
|
||||
sat 1
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,53 @@
|
||||
# Task: sharded word count
|
||||
|
||||
Development task (dev set). Its results are not evidence about any language.
|
||||
|
||||
Write a program that counts words in its standard input using several concurrent workers, then merges their results.
|
||||
|
||||
## Input
|
||||
|
||||
The input is a sequence of lines separated by `\n`. If the input ends with `\n`, that final `\n` does not start another line. The input is at most 24 KiB and has at most 2000 lines.
|
||||
|
||||
The first line is always `workers W`, where W is a decimal number with 1 ≤ W ≤ 8 and no leading zeros. Every later line is a **text line**; text lines are numbered from 0. Text lines contain only ASCII characters other than `\n`.
|
||||
|
||||
A **word** is a maximal run of ASCII letters (`A`–`Z`, `a`–`z`) in a text line, converted to lowercase. A word longer than 16 letters counts as its first 16 letters. Every other character separates words. There are at most 2000 distinct words.
|
||||
|
||||
## Concurrency requirement
|
||||
|
||||
The program MUST start W workers (threads or tasks) that run concurrently. Text line k is assigned to worker k mod W. Each worker counts the words of its own lines only. After all workers have finished, the results are merged. The output must not depend on how the workers are scheduled.
|
||||
|
||||
## Output
|
||||
|
||||
1. For each worker i from 0 to W − 1: `worker i lines L words N`, where L is the number of text lines assigned to worker i and N the number of words in them.
|
||||
2. `distinct D`, where D is the number of distinct words in the whole input.
|
||||
3. Up to 10 lines `word count` for the most frequent words: by count, highest first; equal counts in increasing byte order of the word.
|
||||
|
||||
Every output line ends with `\n`. Nothing else is written to standard output.
|
||||
|
||||
## Example
|
||||
|
||||
Input:
|
||||
|
||||
```text
|
||||
workers 2
|
||||
The cat sat.
|
||||
the CAT, the hat
|
||||
a-b-c
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```text
|
||||
worker 0 lines 2 words 6
|
||||
worker 1 lines 1 words 4
|
||||
distinct 7
|
||||
the 3
|
||||
cat 2
|
||||
a 1
|
||||
b 1
|
||||
c 1
|
||||
hat 1
|
||||
sat 1
|
||||
```
|
||||
|
||||
The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. Hidden tests check the requirements above.
|
||||
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "shards"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
fn words(line: &str) -> Vec<String> {
|
||||
line.split(|c: char| !c.is_ascii_alphabetic())
|
||||
.filter(|w| !w.is_empty())
|
||||
.map(|w| w.to_ascii_lowercase().chars().take(16).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut input = String::new();
|
||||
std::io::stdin().read_to_string(&mut input).unwrap();
|
||||
let mut lines: Vec<&str> = input.split('\n').collect();
|
||||
if input.ends_with('\n') {
|
||||
lines.pop();
|
||||
}
|
||||
let w: usize = lines[0]["workers ".len()..].parse().unwrap();
|
||||
let text = &lines[1..];
|
||||
let results: Vec<(usize, usize, HashMap<String, u64>)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..w)
|
||||
.map(|i| {
|
||||
s.spawn(move || {
|
||||
let (mut l, mut n, mut m) = (0, 0, HashMap::new());
|
||||
for line in text.iter().skip(i).step_by(w) {
|
||||
l += 1;
|
||||
for word in words(line) {
|
||||
n += 1;
|
||||
*m.entry(word).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
(l, n, m)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
let mut out = String::new();
|
||||
let mut total: HashMap<String, u64> = HashMap::new();
|
||||
for (i, (l, n, m)) in results.into_iter().enumerate() {
|
||||
out.push_str(&format!("worker {i} lines {l} words {n}\n"));
|
||||
for (k, v) in m {
|
||||
*total.entry(k).or_insert(0) += v;
|
||||
}
|
||||
}
|
||||
out.push_str(&format!("distinct {}\n", total.len()));
|
||||
let mut top: Vec<(String, u64)> = total.into_iter().collect();
|
||||
top.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.as_bytes().cmp(b.0.as_bytes())));
|
||||
for (k, v) in top.into_iter().take(10) {
|
||||
out.push_str(&format!("{k} {v}\n"));
|
||||
}
|
||||
std::io::stdout().write_all(out.as_bytes()).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Public test: the example from the task statement.
|
||||
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
|
||||
got=$(printf '%s' 'workers 2
|
||||
The cat sat.
|
||||
the CAT, the hat
|
||||
a-b-c
|
||||
' | ./target/debug/shards) || { echo "FAIL: the program exited with an error"; exit 1; }
|
||||
expected=$(printf "%s" 'worker 0 lines 2 words 6
|
||||
worker 1 lines 1 words 4
|
||||
distinct 7
|
||||
the 3
|
||||
cat 2
|
||||
a 1
|
||||
b 1
|
||||
c 1
|
||||
hat 1
|
||||
sat 1
|
||||
')
|
||||
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"id": "dev-shards",
|
||||
"version": "1",
|
||||
"set": "dev",
|
||||
"family": "failure-calibration",
|
||||
"prompt": "prompt.md",
|
||||
"languages": {
|
||||
"aji_air": {"workspace": "lang/aji_air", "test": "sh test.sh"},
|
||||
"aji_source": {"workspace": "lang/aji_source", "test": "sh test.sh"},
|
||||
"rust": {"workspace": "lang/rust", "test": "sh test.sh"},
|
||||
"zig": {"workspace": "lang/zig", "test": "sh test.sh"}
|
||||
},
|
||||
"limits": {"tool_calls": 80, "total_tokens": 1500000, "wall_seconds": 1800, "command_timeout": 120},
|
||||
"concurrency": true
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Shared evaluator code for the dev-set tasks that use a line-oriented
|
||||
stdin → stdout interface (dev-intervals, dev-lru, dev-shards).
|
||||
|
||||
These tasks and their evaluators are public because they are dev-set
|
||||
material (protocol §7): they exist to produce realistic failures for
|
||||
harness and classifier work, never evidence about the language.
|
||||
|
||||
An evaluator calls `evaluate(spec)` and prints the JSON verdict:
|
||||
builds the program builds or verifies;
|
||||
public the public cases (the ones in test.sh) pass;
|
||||
hidden every hidden case passes;
|
||||
+ any extra gates the task adds (e.g. uses_concurrency, schedules).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||
AJI = os.path.join(REPO, "zig-out", "bin", "aji")
|
||||
NATIVE_TIMEOUT = 60 # Rust/Zig binaries only; Aji runs end by fuel (spec 11 §7)
|
||||
|
||||
|
||||
class Spec:
|
||||
"""binary: the Rust package/binary name; heap: the Aji mem.alloc
|
||||
budget in bytes; fuel: the Aji instruction budget per case."""
|
||||
|
||||
def __init__(self, binary, heap, fuel, public, hidden, extra_gates=None, schedule_seeds=(0,)):
|
||||
self.binary, self.heap, self.fuel = binary, heap, fuel
|
||||
self.public, self.hidden = public, hidden
|
||||
self.extra_gates = extra_gates or (lambda ws, lang: {})
|
||||
self.schedule_seeds = schedule_seeds
|
||||
|
||||
|
||||
def build(ws, lang):
|
||||
if lang == "rust":
|
||||
cmd = ["cargo", "build", "-q", "--offline"]
|
||||
elif lang == "zig":
|
||||
cmd = ["zig", "build-exe", "main.zig"]
|
||||
else:
|
||||
cmd = [AJI, "check", "main.aji" if lang == "aji_source" else "main.air"]
|
||||
return subprocess.run(cmd, cwd=ws, capture_output=True).returncode == 0
|
||||
|
||||
|
||||
def run(ws, lang, spec, text, schedule_seed=0):
|
||||
"""The program's stdout for one input, or None if it did not complete."""
|
||||
if lang in ("aji_air", "aji_source"):
|
||||
src, inp = ("main.aji", "input") if lang == "aji_source" else ("main.air", "in")
|
||||
argv = [AJI, "run", "--fuel", str(spec.fuel), "--schedule-seed", str(schedule_seed),
|
||||
"--grant", f"{inp}=io.read", "--grant", "out=io.write", "--grant", f"heap=mem.alloc:{spec.heap}",
|
||||
"--stdin", text, src]
|
||||
p = subprocess.run(argv, cwd=ws, capture_output=True, text=True)
|
||||
try:
|
||||
rec = json.loads(p.stdout)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return rec.get("stdout") if rec.get("status") == "returned" else None
|
||||
exe = f"./target/debug/{spec.binary}" if lang == "rust" else "./main"
|
||||
try:
|
||||
p = subprocess.run([exe], cwd=ws, input=text, capture_output=True, text=True, timeout=NATIVE_TIMEOUT)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
return None
|
||||
return p.stdout if p.returncode == 0 else None
|
||||
|
||||
|
||||
def passes(ws, lang, spec, cases, seeds=(0,)):
|
||||
return all(run(ws, lang, spec, inp, s) == expected for inp, expected in cases for s in seeds)
|
||||
|
||||
|
||||
def source_matches(ws, lang, patterns):
|
||||
"""True if the program's source mentions one of the language's patterns
|
||||
(a coarse static gate for requirements tests cannot observe)."""
|
||||
files = {"aji_air": ["main.air"], "aji_source": ["main.aji"], "zig": ["main.zig"]}.get(lang)
|
||||
if files is None:
|
||||
files = [os.path.join(r, f) for r, _, fs in os.walk(os.path.join(ws, "src")) for f in fs if f.endswith(".rs")]
|
||||
text = ""
|
||||
for f in files:
|
||||
try:
|
||||
with open(os.path.join(ws, f)) as fh:
|
||||
text += fh.read()
|
||||
except OSError:
|
||||
pass
|
||||
return re.search(patterns[lang], text) is not None
|
||||
|
||||
|
||||
def evaluate(spec):
|
||||
ws, lang = sys.argv[1], sys.argv[2]
|
||||
gates = {"builds": build(ws, lang)}
|
||||
gates["public"] = gates["builds"] and passes(ws, lang, spec, spec.public)
|
||||
seeds = spec.schedule_seeds if lang in ("aji_air", "aji_source") else (0,)
|
||||
gates["hidden"] = gates["builds"] and passes(ws, lang, spec, spec.hidden, seeds)
|
||||
gates.update(spec.extra_gates(ws, lang))
|
||||
print(json.dumps({"accepted": all(gates.values()), "gates": gates}))
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One evaluator command for a plan over several dev tasks: runs the
|
||||
task's own evaluator.py with the harness's arguments.
|
||||
|
||||
usage: evaluate.py WORKSPACE LANGUAGE TASK_DIR
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
ws, lang, task = sys.argv[1:4]
|
||||
os.execv(sys.executable, [sys.executable, os.path.join(task, "evaluator.py"), ws, lang, task])
|
||||
Reference in new issue
Block a user