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:
dev committed 2026-10-17 12:30:37 +03:00
1 parent 2d750a0525
commit e3fc896a0a
68 files changed
+2132 -37

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
---
name: aji-jev
description: Use when classifying failed Aji evaluation runs, deciding whether a spec, diagnostic, agent-bundle or documentation improvement is warranted, or when TypeSafe/Jev comes up in this repository. Covers `ajieval classify --suggest`, `calibrate` and `triage`, and the hard limits on where Jev may be used.
---
# Jev in Aji: advisory triage only
Jev (TypeSafe) is a System One classifier. It answers typed questions (`choice`, `score`, `noul`) about a small state and returns calibrated probabilities. In this repository it only *suggests*. The verifier, conformance tests and the owner decide.
## Hard limits
- Only `tools/eval/`. Never call Jev from `src/`, the verifier, the interpreter, `build.zig`, CI gates or conformance verdicts. Aji is deterministic, and an external model is not.
- Only failed runs of the `dev` and `validation` sets. Never send a `test`-set run, a held-out task or anything from the private benchmark repository (protocol §29, spec 14 §12). `jev.check_sendable` enforces this; do not bypass it.
- No language change follows from a classification alone. Protocol §38 requires repeated failures across tasks and agents; `triage` enforces this through the minimums in `tools/eval/triage.json`.
- Nothing during a frozen experiment. Pass `--plan` to `triage`. Record observations with `ajieval journal` and act only after the last cell has run.
- Never tune the language to the M or C corpus or to one benchmark task.
## Workflow
1. For each failed dev/validation run: `python3 -m ajieval classify RUN --suggest`. This needs `TYPESAFE_API_KEY`; never print or record it.
2. A human confirms or overrides the suggestion with `python3 -m ajieval classify RUN CATEGORY --cause CAUSE [--caught-by ...]`.
3. Once enough runs have both a human label and a suggestion, run `python3 -m ajieval calibrate runs/`. Propose `"calibrated": true` and the thresholds in `triage.json` to the owner only when agreement among auto-accepted suggestions is high. Do not flip it yourself.
4. Run `python3 -m ajieval triage runs/ [--plan PLAN]`. For each proposal, act according to its route:
- `diagnostics`: patch the message in `src/diag.zig` and `docs/reference/error-codes.md`, add a test, open a PR.
- `agent_bundle` / `documentation`: clarify `docs/agent/`, the Quick Reference or the reference without changing meaning. Check the bundle growth (`tools/agent_bundle_tokens.py`).
- `language`: add an entry to `docs/design/open-questions.md` with the evidence (runs, tasks, agents, codes). Only the owner turns it into an RFC.
- `harness`: fix `tools/eval/`.
- `task_ambiguity`: run the task acceptance review (protocol §8).
- `model_capability`: nothing.
## Session feedback on instructions and skills
A personal SessionEnd hook (`.Codex/settings.local.json`, never the shared settings) runs `python3 -m ajieval sessions hook` from `tools/eval`. In the background it pairs each human prompt with what the assistant did just before, redacts credential-like strings, truncates both, and asks Jev two questions: whether the prompt was a correction, and which rule in `sessions.RULES` the corrected behaviour broke. Answers stay in `~/.cache/aji-sessions/events.jsonl`. Without a TypeSafe key the hook does nothing.
`python3 -m ajieval sessions report` proposes clarifying a rule only when corrections pointing to it recur across sessions (thresholds in `triage.json`, `sessions`). Act on a proposal by sharpening the rule where it lives (`AGENTS.md`, this skill, or memory) and only after the owner agrees. The report never edits anything. Corrections no rule explains are listed as `unattributed`; recurring ones suggest a missing rule.
## Changing the questions
The option descriptions in `tools/eval/ajieval/jev.py` are the classifier's input. A change there changes `questions_hash`, and suggestions made under different hashes must not be mixed in `calibrate`. Keep the descriptions atomic and literal: Jev reads instructions at face value and handles multi-hop reasoning poorly.
+15
View File
@@ -0,0 +1,15 @@
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "cd \"$CLAUDE_PROJECT_DIR/tools/eval\" && python3 -m ajieval sessions hook",
"timeout": 10
}
]
}
]
}
}
+2
View File
@@ -35,10 +35,12 @@ python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministi
python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity
python3 tests/hosted/source_expression_depth.py # deep unary chains, exact AIR/fuel and rejection positions
python3 tests/hosted/source_liveness_depth.py # deep SSA liveness, join decisions, formatting and exact fuel
python3 tests/hosted/source_loop_exit.py # CFG exits, naming collisions, diagnostic priority and packages
python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance
python3 tests/hosted/source_repair_advice.py # contextual syntax/cast/array-call advice and CLI/package parity
python3 tests/hosted/source_independent_errors.py # bounded source error collection without cascades or partial AIR
python3 tests/hosted/source_cfg_provenance.py # resource handoff, loan origins and source/package/AIR diagnostics
python3 tests/hosted/shield_relations.py # shield ordering, handoff, relation reuse, cancellation and exact diagnostics
python3 tools/source_reject_twins.py # audited same-code pairs and exhaustive, explicitly incomplete AIR inventory
python3 tests/hosted/source_reject_twins.py # false-pair, mapping and inventory regression probes
python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules
@@ -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`.
+10 -3
View File
@@ -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.
+1
View File
@@ -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)
+14
View File
@@ -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
View File
@@ -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() {}
+19
View File
@@ -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 {}
+19
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+29
View File
@@ -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
View File
@@ -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
View File
@@ -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();
}
+29
View File
@@ -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
View File
@@ -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.
+20
View File
@@ -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
View File
@@ -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
View File
@@ -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
}
+95
View File
@@ -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}))
+11
View File
@@ -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])
+26 -12
View File
@@ -154,7 +154,8 @@ const Walker = struct {
return;
}
// Borrows lent to live tasks are accessed concurrently (spec 04 §34).
for (w.facts.items.items) |l| {
var loans = w.facts.byKind(.loan);
while (loans.next()) |l| {
if (l.kind != .loan or !w.live[l.a]) continue;
const li = w.info[l.b] orelse continue;
if (li.root != root) continue;
@@ -436,7 +437,8 @@ fn walkFunction(w: *Walker, dom: ssa.Dominators, facts: ?[]provenance.State, eve
/// are overwritten; implicit outcome definitions were recorded as events.
fn edgeProvenance(arena: std.mem.Allocator, base: provenance.State, f: air.Function, types: []const air.Type, dom: ssa.Dominators, e: Edge) !provenance.State {
var out: provenance.State = .{};
for (base.items.items) |old| {
var facts = base.iterator();
while (facts.next()) |old| {
var fact = old;
fact.a = edgeValue(old.a, f, types, dom, e) orelse continue;
fact.b = edgeValue(old.b, f, types, dom, e) orelse continue;
@@ -492,7 +494,7 @@ fn solveProvenance(arena: std.mem.Allocator, f: air.Function, types: []const air
for (out.items) |e| {
const incoming = try edgeProvenance(arena, state, f, types, dom, e);
const changed = try entries[e.target].merge(arena, incoming);
if (stats) |s| s.facts += incoming.items.items.len;
if (stats) |s| s.facts += incoming.count();
if ((!visited[e.target] or changed) and !queued[e.target]) {
try queue.append(arena, e.target);
queued[e.target] = true;
@@ -544,10 +546,12 @@ fn step(w: *Walker, inst: air.Inst) !void {
if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null);
// Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false;
for (w.facts.items.items) |l| if (l.kind == .loan and w.live[l.a] and (l.b == v or w.isAncestor(v, l.b))) {
var loans = w.facts.byKind(.loan);
while (loans.next()) |l| if (l.kind == .loan and w.live[l.a] and (l.b == v or w.isAncestor(v, l.b))) {
return w.reportWithOrigin("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.a }, l.spawn);
};
for (w.facts.items.items) |g| if (g.kind == .guard and w.live[g.a] and w.isAncestor(v, g.b)) {
var guards = w.facts.byKind(.guard);
while (guards.next()) |g| if (g.kind == .guard and w.live[g.a] and w.isAncestor(v, g.b)) {
return w.report("E2102", "mutex borrow ended while a guard locked through it is live", v, .{ "guard", g.a });
};
for (w.live, 0..) |is_live, cv| {
@@ -644,7 +648,8 @@ fn step(w: *Walker, inst: air.Inst) !void {
.task_scope_end => |s| {
// Copy the selected handles before killing their facts.
var children: std.ArrayList(ValueId) = .empty;
for (w.facts.items.items) |fact| if (fact.kind == .scope and fact.b == s and w.live[fact.a]) {
var facts = w.facts.byTarget(s);
while (facts.next()) |fact| if (fact.kind == .scope and fact.b == s and w.live[fact.a]) {
if (std.mem.indexOfScalar(ValueId, children.items, fact.a) == null) try children.append(w.c.arena, fact.a);
};
for (children.items) |v| {
@@ -703,10 +708,13 @@ fn step(w: *Walker, inst: air.Inst) !void {
w.live[r] = true;
},
.task_shield_end => |sh| {
if (w.live[sh]) for (w.facts.items.items) |fact| if (fact.kind == .inner and fact.b == sh and w.live[fact.a]) {
try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", fact.a });
break;
};
if (w.live[sh]) {
var inner = w.facts.byTarget(sh);
while (inner.next()) |fact| if (fact.kind == .inner and w.live[fact.a]) {
try w.report("E4305", "shield ended while a more inner shield is live", sh, .{ "inner", fact.a });
break;
};
}
try w.consume(sh, .closed);
},
.channel_dup => |v| {
@@ -803,7 +811,8 @@ fn step(w: *Walker, inst: air.Inst) !void {
/// Taking a mutex or an atomic cell while a borrow of it is lent to a live
/// task races with that task: `E4101` rather than `E2101` (spec 04 §28, §40).
fn takeLent(w: *Walker, v: ValueId) !bool {
for (w.facts.items.items) |l| if (l.kind == .loan and w.live[l.a] and w.info[l.b] != null and w.info[l.b].?.root == v) {
var loans = w.facts.byKind(.loan);
while (loans.next()) |l| if (l.kind == .loan and w.live[l.a] and w.info[l.b] != null and w.info[l.b].?.root == v) {
try w.report("E4101", "taken while a borrow of it is lent to a live task", v, .{ "task", l.a });
// Consumed all the same, so the mistake is not reported again as a leak.
w.live[v] = false;
@@ -993,7 +1002,8 @@ test "task provenance rotation reaches every header parameter with bounded visit
var stats: ProvenanceStats = .{};
const entries = try solveProvenance(a, f, types, dom, events, &stats);
var loans: usize = 0;
for (entries[1].items.items) |fact| if (fact.kind == .loan) {
var facts = entries[1].iterator();
while (facts.next()) |fact| if (fact.kind == .loan) {
loans += 1;
try std.testing.expectEqual(@as(u32, 12), fact.spawn.line);
};
@@ -1001,3 +1011,7 @@ test "task provenance rotation reaches every header parameter with bounded visit
try std.testing.expect(stats.visits <= count + 2);
try std.testing.expect(stats.facts <= 2 * count * (count + 2));
}
test {
_ = provenance;
}
+462 -22
View File
@@ -4,7 +4,9 @@
const std = @import("std");
const air = @import("../air.zig");
pub const Kind = enum { loan, scope, guard, inner };
// Fixed-width fields make Fact padding-free, so the hash map can hash its
// bytes once instead of recursively hashing five small fields in Debug.
pub const Kind = enum(u32) { loan, scope, guard, inner };
pub const Fact = struct {
kind: Kind,
a: air.ValueId,
@@ -21,19 +23,113 @@ pub const Event = union(enum) {
};
pub const State = struct {
items: std.ArrayList(Fact) = .empty,
set: std.AutoHashMapUnmanaged(Fact, void) = .empty,
/// Storage is recycled at the high-water mark of live facts. Active facts
/// have four independent links: insertion order, both endpoints and kind.
nodes: std.ArrayList(Node) = .empty,
set: std.AutoHashMapUnmanaged(Fact, usize) = .empty,
endpoints: std.AutoHashMapUnmanaged(air.ValueId, Ends) = .empty,
first: usize = none,
last: usize = none,
free: usize = none,
kind_first: [std.enums.values(Kind).len]usize = @splat(none),
kind_last: [std.enums.values(Kind).len]usize = @splat(none),
const none: usize = std.math.maxInt(usize);
const Node = struct {
fact: Fact,
prev: usize = none,
next: usize = none,
a_prev: usize = none,
a_next: usize = none,
b_prev: usize = none,
b_next: usize = none,
kind_prev: usize = none,
kind_next: usize = none,
};
const Ends = struct { a: usize = none, b_first: usize = none, b_last: usize = none };
pub const Iterator = struct {
state: *const State,
index: usize,
link: enum { ordered, target, kind } = .ordered,
pub fn next(it: *Iterator) ?Fact {
if (it.index == none) return null;
const node = &it.state.nodes.items[it.index];
it.index = switch (it.link) {
.ordered => node.next,
.target => node.b_next,
.kind => node.kind_next,
};
return node.fact;
}
};
/// Surviving facts retain their insertion order, including after slot reuse.
pub fn iterator(s: *const State) Iterator {
return .{ .state = s, .index = s.first };
}
/// Facts with this second endpoint, in the same order as a full traversal.
pub fn byTarget(s: *const State, v: air.ValueId) Iterator {
return .{ .state = s, .index = if (s.endpoints.get(v)) |ends| ends.b_first else none, .link = .target };
}
/// The same insertion order, restricted to one relation kind. Generic
/// access checks must not scan all shield-order facts looking for loans.
pub fn byKind(s: *const State, kind: Kind) Iterator {
return .{ .state = s, .index = s.kind_first[@backingInt(kind)], .link = .kind };
}
pub fn count(s: State) usize {
return s.set.count();
}
pub fn add(s: *State, arena: std.mem.Allocator, fact: Fact) !bool {
const r = try s.set.getOrPut(arena, fact);
if (r.found_existing) return false;
try s.items.append(arena, fact);
const member = try s.set.getOrPut(arena, fact);
if (member.found_existing) return false;
// Roll back membership if host growth fails. Endpoint/order links are
// published only after all growth succeeds; this reservation's pointers
// stay valid because subsequent growth belongs to different containers.
errdefer s.set.removeByPtr(member.key_ptr);
try s.endpoints.ensureUnusedCapacity(arena, 2);
if (s.free == none) try s.nodes.ensureUnusedCapacity(arena, 1);
const a_entry = s.endpoints.getOrPutAssumeCapacity(fact.a);
if (!a_entry.found_existing) a_entry.value_ptr.* = .{};
const a = a_entry.value_ptr;
const b = if (fact.a == fact.b) a else blk: {
const b_entry = s.endpoints.getOrPutAssumeCapacity(fact.b);
if (!b_entry.found_existing) b_entry.value_ptr.* = .{};
break :blk b_entry.value_ptr;
};
const index = if (s.free != none) blk: {
const index = s.free;
s.free = s.nodes.items[index].next;
break :blk index;
} else blk: {
const index = s.nodes.items.len;
s.nodes.appendAssumeCapacity(undefined);
break :blk index;
};
const kind = @backingInt(fact.kind);
s.nodes.items[index] = .{ .fact = fact, .prev = s.last, .a_next = a.a, .b_prev = b.b_last, .kind_prev = s.kind_last[kind] };
if (s.kind_last[kind] != none) s.nodes.items[s.kind_last[kind]].kind_next = index else s.kind_first[kind] = index;
s.kind_last[kind] = index;
if (s.last != none) s.nodes.items[s.last].next = index else s.first = index;
s.last = index;
if (a.a != none) s.nodes.items[a.a].a_prev = index;
a.a = index;
if (b.b_last != none) s.nodes.items[b.b_last].b_next = index else b.b_first = index;
b.b_last = index;
member.value_ptr.* = index;
return true;
}
pub fn merge(s: *State, arena: std.mem.Allocator, other: State) !bool {
var changed = false;
for (other.items.items) |fact| changed = (try s.add(arena, fact)) or changed;
var facts = other.iterator();
while (facts.next()) |fact| changed = (try s.add(arena, fact)) or changed;
return changed;
}
@@ -43,17 +139,40 @@ pub const State = struct {
return out;
}
/// Remove exactly the incident facts; unlinking the other endpoint and
/// insertion-order links needs no scan or allocation. Self-edges are removed
/// once because both endpoint chains are updated by the same removal.
pub fn kill(s: *State, v: air.ValueId) void {
var n: usize = 0;
for (s.items.items) |fact| {
if (fact.a == v or fact.b == v) {
_ = s.set.remove(fact);
} else {
s.items.items[n] = fact;
n += 1;
}
const ends = s.endpoints.getPtr(v) orelse return;
// Hash-map removal does not relocate other entries. Keep this bucket
// until all incident facts are unlinked, then remove it once.
while (ends.a != none or ends.b_first != none) {
const index = if (ends.a != none) ends.a else ends.b_first;
s.remove(index, v, ends);
}
s.items.shrinkRetainingCapacity(n);
_ = s.endpoints.remove(v);
}
fn remove(s: *State, index: usize, killed: air.ValueId, ends: *Ends) void {
const node = s.nodes.items[index];
const a = if (node.fact.a == killed) ends else s.endpoints.getPtr(node.fact.a).?;
const b = if (node.fact.b == killed) ends else s.endpoints.getPtr(node.fact.b).?;
if (node.a_prev != none) s.nodes.items[node.a_prev].a_next = node.a_next else a.a = node.a_next;
if (node.a_next != none) s.nodes.items[node.a_next].a_prev = node.a_prev;
if (node.b_prev != none) s.nodes.items[node.b_prev].b_next = node.b_next else b.b_first = node.b_next;
if (node.b_next != none) s.nodes.items[node.b_next].b_prev = node.b_prev else b.b_last = node.b_prev;
if (node.prev != none) s.nodes.items[node.prev].next = node.next else s.first = node.next;
if (node.next != none) s.nodes.items[node.next].prev = node.prev else s.last = node.prev;
const kind = @backingInt(node.fact.kind);
if (node.kind_prev != none) s.nodes.items[node.kind_prev].kind_next = node.kind_next else s.kind_first[kind] = node.kind_next;
if (node.kind_next != none) s.nodes.items[node.kind_next].kind_prev = node.kind_prev else s.kind_last[kind] = node.kind_prev;
_ = s.set.remove(node.fact);
// The killed value's bucket remains pinned until kill completes. An
// empty other bucket can be removed immediately without moving it.
if (node.fact.a != killed and a.a == none and a.b_first == none) _ = s.endpoints.remove(node.fact.a);
if (node.fact.b != killed and b.a == none and b.b_first == none) _ = s.endpoints.remove(node.fact.b);
s.nodes.items[index].next = s.free;
s.free = index;
}
pub fn apply(s: *State, arena: std.mem.Allocator, event: Event) !void {
@@ -62,7 +181,8 @@ pub const State = struct {
.kill => |v| s.kill(v),
.rename => |r| {
var out: State = .{};
for (s.items.items) |old| {
var facts = s.iterator();
while (facts.next()) |old| {
var f = old;
if (f.a == r.from) f.a = r.to;
if (f.b == r.from) f.b = r.to;
@@ -78,10 +198,19 @@ pub const State = struct {
}
pub fn differentShield(a: State, b: State) ?air.ValueId {
for (a.items.items) |f| if (f.kind == .inner and !b.set.contains(f)) return f.a;
for (b.items.items) |f| if (f.kind == .inner and !a.set.contains(f)) return f.a;
var af = a.byKind(.inner);
while (af.next()) |f| if (!b.set.contains(f)) return f.a;
var bf = b.byKind(.inner);
while (bf.next()) |f| if (!a.set.contains(f)) return f.a;
return null;
}
pub fn deinit(s: *State, allocator: std.mem.Allocator) void {
s.nodes.deinit(allocator);
s.set.deinit(allocator);
s.endpoints.deinit(allocator);
s.* = .{};
}
};
test "relations retain loan origin, join once and remove both endpoints" {
@@ -93,8 +222,319 @@ test "relations retain loan origin, join once and remove both endpoints" {
try std.testing.expect(try s.add(a, loan));
try std.testing.expect(!try s.add(a, loan));
try s.apply(a, .{ .rename = .{ .from = 1, .to = 4 } });
try std.testing.expectEqual(@as(air.ValueId, 4), s.items.items[0].a);
try std.testing.expectEqual(loan.spawn, s.items.items[0].spawn);
var facts = s.iterator();
const renamed = facts.next().?;
try std.testing.expectEqual(@as(air.ValueId, 4), renamed.a);
try std.testing.expectEqual(loan.spawn, renamed.spawn);
s.kill(2);
try std.testing.expectEqual(@as(usize, 0), s.items.items.len);
try std.testing.expectEqual(@as(usize, 0), s.count());
}
// Frozen compact-list semantics, independent of the indexed representation.
const FlatState = struct {
items: std.ArrayList(Fact) = .empty,
set: std.AutoHashMapUnmanaged(Fact, void) = .empty,
pub fn add(s: *FlatState, arena: std.mem.Allocator, fact: Fact) !bool {
const r = try s.set.getOrPut(arena, fact);
if (r.found_existing) return false;
try s.items.append(arena, fact);
return true;
}
pub fn merge(s: *FlatState, arena: std.mem.Allocator, other: FlatState) !bool {
var changed = false;
for (other.items.items) |fact| changed = (try s.add(arena, fact)) or changed;
return changed;
}
pub fn clone(s: FlatState, arena: std.mem.Allocator) !FlatState {
var out: FlatState = .{};
_ = try out.merge(arena, s);
return out;
}
pub fn kill(s: *FlatState, v: air.ValueId) void {
var n: usize = 0;
for (s.items.items) |fact| {
if (fact.a == v or fact.b == v) {
_ = s.set.remove(fact);
} else {
s.items.items[n] = fact;
n += 1;
}
}
s.items.shrinkRetainingCapacity(n);
}
pub fn apply(s: *FlatState, arena: std.mem.Allocator, event: Event) !void {
switch (event) {
.add => |f| _ = try s.add(arena, f),
.kill => |v| s.kill(v),
.rename => |r| {
var out: FlatState = .{};
for (s.items.items) |old| {
var f = old;
if (f.a == r.from) f.a = r.to;
if (f.b == r.from) f.b = r.to;
_ = try out.add(arena, f);
}
s.* = out;
},
}
}
pub fn sameShields(a: FlatState, b: FlatState) bool {
return a.differentShield(b) == null;
}
pub fn differentShield(a: FlatState, b: FlatState) ?air.ValueId {
for (a.items.items) |f| if (f.kind == .inner and !b.set.contains(f)) return f.a;
for (b.items.items) |f| if (f.kind == .inner and !a.set.contains(f)) return f.a;
return null;
}
};
fn expectFlat(s: *const State, flat: FlatState) !void {
try std.testing.expectEqual(flat.items.items.len, s.count());
var facts = s.iterator();
var prev = State.none;
var index = s.first;
for (flat.items.items) |expected| {
try std.testing.expectEqualDeep(expected, facts.next().?);
try std.testing.expectEqual(prev, s.nodes.items[index].prev);
try std.testing.expectEqual(index, s.set.get(expected).?);
try std.testing.expect(s.endpoints.contains(expected.a));
try std.testing.expect(s.endpoints.contains(expected.b));
prev = index;
index = s.nodes.items[index].next;
}
try std.testing.expect(facts.next() == null);
try std.testing.expectEqual(State.none, index);
try std.testing.expectEqual(prev, s.last);
for (std.enums.values(Kind)) |kind| {
var by_kind = s.byKind(kind);
var kind_prev = State.none;
var kind_index = s.kind_first[@backingInt(kind)];
for (flat.items.items) |expected| if (expected.kind == kind) {
try std.testing.expectEqualDeep(expected, by_kind.next().?);
try std.testing.expectEqual(kind_prev, s.nodes.items[kind_index].kind_prev);
kind_prev = kind_index;
kind_index = s.nodes.items[kind_index].kind_next;
};
try std.testing.expect(by_kind.next() == null);
try std.testing.expectEqual(State.none, kind_index);
try std.testing.expectEqual(kind_prev, s.kind_last[@backingInt(kind)]);
}
var endpoints = s.endpoints.iterator();
while (endpoints.next()) |entry| {
const value = entry.key_ptr.*;
var by_target = s.byTarget(value);
var expected_a: usize = 0;
var expected_b: usize = 0;
for (flat.items.items) |expected| {
if (expected.a == value) expected_a += 1;
if (expected.b == value) {
try std.testing.expectEqualDeep(expected, by_target.next().?);
expected_b += 1;
}
}
try std.testing.expect(by_target.next() == null);
try std.testing.expect(expected_a + expected_b != 0);
var a_count: usize = 0;
var a_prev = State.none;
var at = entry.value_ptr.a;
while (at != State.none) {
try std.testing.expect(a_count < expected_a);
const node = s.nodes.items[at];
try std.testing.expectEqual(value, node.fact.a);
try std.testing.expectEqual(a_prev, node.a_prev);
a_prev = at;
at = node.a_next;
a_count += 1;
}
try std.testing.expectEqual(expected_a, a_count);
var b_count: usize = 0;
var b_prev = State.none;
at = entry.value_ptr.b_first;
while (at != State.none) {
try std.testing.expect(b_count < expected_b);
const node = s.nodes.items[at];
try std.testing.expectEqual(value, node.fact.b);
try std.testing.expectEqual(b_prev, node.b_prev);
b_prev = at;
at = node.b_next;
b_count += 1;
}
try std.testing.expectEqual(b_prev, entry.value_ptr.b_last);
try std.testing.expectEqual(expected_b, b_count);
}
var free = s.free;
var free_count: usize = 0;
while (free != State.none) {
try std.testing.expect(free_count < s.nodes.items.len);
var live = s.first;
while (live != State.none) : (live = s.nodes.items[live].next) try std.testing.expect(live != free);
free = s.nodes.items[free].next;
free_count += 1;
}
try std.testing.expectEqual(s.nodes.items.len, free_count + s.count());
}
test "indexed relations preserve frozen order endpoints merges renames and shield conflicts" {
for ([_]u64{ 1, 0x1ab_543, 0xdeaf_beef }) |seed| {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var s: State = .{};
var old: FlatState = .{};
var random = std.Random.DefaultPrng.init(seed);
const rng = random.random();
var saved: State = .{};
var old_saved: FlatState = .{};
for (0..768) |step_index| {
const x = rng.uintLessThan(u32, 12);
const y = rng.uintLessThan(u32, 12);
switch (rng.uintLessThan(u8, 8)) {
0, 1, 2 => {
const fact: Fact = .{ .kind = @fromBackingInt(@intCast(rng.uintLessThan(u8, 4))), .a = x, .b = y, .spawn = .{ .line = @intCast(step_index % 3), .col = 7 } };
try std.testing.expectEqual(try old.add(a, fact), try s.add(a, fact));
try std.testing.expect(!try s.add(a, fact));
},
3 => {
old.kill(x);
s.kill(x);
},
4 => {
const event: Event = .{ .rename = .{ .from = x, .to = y } };
try old.apply(a, event);
try s.apply(a, event);
},
5 => {
saved = try s.clone(a);
old_saved = try old.clone(a);
},
6 => try std.testing.expectEqual(try old.merge(a, old_saved), try s.merge(a, saved)),
7 => try std.testing.expectEqual(try old.merge(a, old), try s.merge(a, s)),
else => unreachable,
}
try expectFlat(&s, old);
try std.testing.expectEqual(old.differentShield(old_saved), s.differentShield(saved));
try std.testing.expectEqual(old_saved.differentShield(old), saved.differentShield(s));
}
}
}
test "indexed relations recycle disconnected self edges and nested shield storage" {
var s: State = .{};
defer s.deinit(std.testing.allocator);
const a = std.testing.allocator;
for (0..1024) |value| {
const v: u32 = @intCast(value);
_ = try s.add(a, .{ .kind = .inner, .a = v, .b = v });
s.kill(v);
try std.testing.expectEqual(@as(usize, 0), s.count());
try std.testing.expectEqual(@as(u32, 0), s.endpoints.count());
try std.testing.expectEqual(@as(usize, 1), s.nodes.items.len);
}
const depth = 128;
for (0..depth) |inner| for (0..inner) |outer| {
_ = try s.add(a, .{ .kind = .inner, .a = @intCast(inner), .b = @intCast(outer) });
};
const high_water = s.nodes.items.len;
try std.testing.expectEqual(@as(usize, depth * (depth - 1) / 2), high_water);
var remaining: usize = depth;
while (remaining != 0) {
remaining -= 1;
var incoming = s.byTarget(@intCast(remaining));
try std.testing.expect(incoming.next() == null);
s.kill(@intCast(remaining));
try std.testing.expectEqual(remaining * (remaining -| 1) / 2, s.count());
try std.testing.expectEqual(high_water, s.nodes.items.len);
}
try std.testing.expectEqual(@as(u32, 0), s.endpoints.count());
}
fn addFailure(a: std.mem.Allocator, self: bool) !void {
var s: State = .{};
defer s.deinit(a);
const fact: Fact = .{ .kind = .inner, .a = 1, .b = if (self) 1 else 2 };
_ = s.add(a, fact) catch |err| {
try std.testing.expectEqual(@as(usize, 0), s.count());
try std.testing.expectEqual(@as(u32, 0), s.endpoints.count());
try std.testing.expectEqual(@as(usize, 0), s.nodes.items.len);
try std.testing.expectEqual(State.none, s.first);
try std.testing.expectEqual(State.none, s.last);
return err;
};
try std.testing.expectEqual(@as(usize, 1), s.count());
s.kill(1);
try std.testing.expectEqual(@as(usize, 0), s.count());
}
test "indexed relation add publishes all views together and frees partial growth on OOM" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, addFailure, .{false});
try std.testing.checkAllAllocationFailures(std.testing.allocator, addFailure, .{true});
}
fn growingAddFailure(a: std.mem.Allocator) !void {
var s: State = .{};
defer s.deinit(a);
for (0..96) |i| {
const fact: Fact = .{ .kind = .loan, .a = @intCast(i), .b = @intCast(i + 1), .spawn = .{ .line = @intCast(i + 1), .col = 7 } };
_ = s.add(a, fact) catch |err| {
try std.testing.expectEqual(i, s.count());
var facts = s.iterator();
for (0..i) |j| {
const previous = facts.next().?;
try std.testing.expectEqual(@as(u32, @intCast(j)), previous.a);
try std.testing.expectEqual(@as(u32, @intCast(j + 1)), previous.b);
try std.testing.expectEqual(@as(u32, @intCast(j + 1)), previous.spawn.line);
var target = s.byTarget(previous.b);
try std.testing.expectEqualDeep(previous, target.next().?);
try std.testing.expect(target.next() == null);
}
try std.testing.expect(facts.next() == null);
try std.testing.expect(!s.set.contains(fact));
return err;
};
}
}
test "indexed relations retain old ordered facts when any index growth fails" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, growingAddFailure, .{});
}
fn renameFailure(backing: std.mem.Allocator) !void {
var arena = std.heap.ArenaAllocator.init(backing);
defer arena.deinit();
const a = arena.allocator();
var s: State = .{};
for (0..48) |i| {
_ = try s.add(a, .{ .kind = .loan, .a = 1, .b = @intCast(i + 3), .spawn = .{ .line = 7, .col = 3 } });
_ = try s.add(a, .{ .kind = .loan, .a = 2, .b = @intCast(i + 3), .spawn = .{ .line = 7, .col = 3 } });
}
s.apply(a, .{ .rename = .{ .from = 1, .to = 2 } }) catch |err| {
try std.testing.expectEqual(@as(usize, 96), s.count());
var facts = s.iterator();
for (0..48) |i| {
for ([_]u32{ 1, 2 }) |task| {
const fact = facts.next().?;
try std.testing.expectEqual(task, fact.a);
try std.testing.expectEqual(@as(u32, @intCast(i + 3)), fact.b);
try std.testing.expectEqual(@as(u32, 7), fact.spawn.line);
}
}
return err;
};
try std.testing.expectEqual(@as(usize, 48), s.count());
var facts = s.iterator();
while (facts.next()) |fact| {
try std.testing.expectEqual(@as(u32, 2), fact.a);
try std.testing.expectEqual(@as(u32, 7), fact.spawn.line);
}
}
test "indexed relations rename deduplicates simultaneously and publishes only on success" {
try std.testing.checkAllAllocationFailures(std.testing.allocator, renameFailure, .{});
}
@@ -0,0 +1,20 @@
; expect: reject E4305
; phase: 3
; spec: docs/spec/04-concurrency-and-atomics.md §37.3
module test.shield_index
air 0
lang 0.1
features [cancellation, effects, ownership, tasks]
fn @main() -> void
effects []
entry:
%a = task.shield.begin
%b = task.shield.begin
%c = task.shield.begin
task.shield.end %c
%d = task.shield.begin
task.shield.end %a
task.shield.end %d
task.shield.end %b
ret
@@ -0,0 +1,21 @@
; expect: reject E3002 E4305
; phase: 3
; spec: docs/spec/04-concurrency-and-atomics.md §37.3
module test.shield_index
air 0
lang 0.1
features [cancellation, effects, ownership, tasks]
fn @main() -> void
effects []
entry:
%a = task.shield.begin
%b = task.shield.begin
%c = task.shield.begin
%condition = const.bool true
cbr %condition, @joined(%a, %b, %c), @joined(%b, %a, %c)
joined(%x: shield, %y: shield, %z: shield):
task.shield.end %z
task.shield.end %y
task.shield.end %x
ret
@@ -0,0 +1,23 @@
; expect: run
; phase: 3
; spec: docs/spec/04-concurrency-and-atomics.md §37.3
; schedules: 32
; result: 42
module test.shield_index
air 0
lang 0.1
features [cancellation, effects, ownership, tasks]
fn @main() -> u8
effects []
entry:
%a = task.shield.begin
%b = task.shield.begin
%c = task.shield.begin
br @next(%c, %a, %b)
next(%inner: shield, %outer: shield, %middle: shield):
task.shield.end %inner
task.shield.end %middle
task.shield.end %outer
%answer = const.u8 42
ret %answer
@@ -0,0 +1,23 @@
; expect: run
; phase: 3
; spec: docs/spec/04-concurrency-and-atomics.md §37.3
; schedules: 32
; result: 42
module test.shield_index
air 0
lang 0.1
features [cancellation, effects, ownership, tasks]
fn @main() -> u8
effects []
entry:
%a = task.shield.begin
%b = task.shield.begin
%c = task.shield.begin
task.shield.end %c
%d = task.shield.begin
task.shield.end %d
task.shield.end %b
task.shield.end %a
%answer = const.u8 42
ret %answer
@@ -0,0 +1,14 @@
// expect: run
// result: 42
// schedules: 32
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md §37.3; docs/spec/15-source-language.md §7
module test.shield_index
fn main() -> u64 effects [] {
var x: u64 = 0u64;
shield {
shield { shield { x = x + 1u64; } shield { x = x + 1u64; } }
shield { x = x + 40u64; }
}
return x;
}
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Q-063: stable shield conflicts, handoff, slot reuse and cancellation."""
import json
from pathlib import Path
import re
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / 'zig-out/bin/aji'
CORPUS = REPO / 'tests/conformance'
checks = 0
def cli(*args, code=0):
global checks
p = subprocess.run([str(AJI), *map(str, args)], capture_output=True)
checks += 1
assert p.returncode == code and not p.stderr, (args, p.returncode, p.stdout, p.stderr)
return p.stdout
def location(path, text):
rows = [(i + 1, line.index(text) + 1) for i, line in enumerate(path.read_text().splitlines()) if text in line]
assert len(rows) == 1, rows
return rows[0]
with tempfile.TemporaryDirectory(prefix='aji-shield-relations-') as directory:
root = Path(directory)
first = CORPUS / 'phase3/reject/shield_index_first_conflict.air'
joined = CORPUS / 'phase3/reject/shield_index_join_priority.air'
for path in (first, joined):
output = cli('check', path, code=1)
ds = [json.loads(line) for line in output.splitlines()]
assert [d['code'] for d in ds] == (['E4305'] if path == first else ['E3002', 'E4305']), ds
conflict = ds[-1]
if path == first:
expected = ('%a', '%b', 'entry', 5)
site = 'task.shield.end %a'
else:
expected = ('%y', '%x', 'joined', 1)
site = 'task.shield.end %y'
assert ds[0]['resource'] == '%x' and (ds[0]['line'], ds[0]['col']) == location(path, 'joined(%x:')
assert (conflict['borrow'], conflict['inner'], conflict['block'], conflict['inst']) == expected, conflict
assert (conflict['line'], conflict['col']) == location(path, site), conflict
assert all(d['file'] == str(path) for d in ds), ds
for command in ('check', 'run', 'report', 'explore'):
assert cli(command, path, code=1) == output
source = CORPUS / 'source/layer8/shield_index_reuse.aji'
canonical = cli('lower', source)
formatted = root / source.name
formatted.write_bytes(cli('fmt', source))
assert cli('fmt', formatted) == formatted.read_bytes()
assert cli('lower', formatted) == canonical
lowered = root / 'shield_index_reuse.air'
lowered.write_bytes(canonical)
cli('check', lowered)
positives = [
CORPUS / 'phase3/run/shield_index_handoff.air',
CORPUS / 'phase3/run/shield_index_reuse.air',
source, lowered,
CORPUS / 'phase3/run/cancel_shield.air',
CORPUS / 'source/layer8/cancel_shield.aji',
]
for path in positives:
cli('check', path)
grants = re.findall(r'^[;/]+ grant: (.+)$', path.read_text(), re.M)
args = [argument for grant in grants for argument in ('--grant', grant)]
expected = 105 if path.stem == 'cancel_shield' else 42
for quantum in (1, 5):
for seed in (0, 7, 31):
for fuel in (0, 1, 4, 16, 64, 256, 10000):
p = subprocess.run([str(AJI), 'run', '--fuel', str(fuel), '--quantum', str(quantum),
'--schedule-seed', str(seed), *args, str(path)], capture_output=True)
checks += 1
assert p.returncode in (0, 5) and not p.stderr, (path, p)
record = json.loads(p.stdout)
assert record['status'] == ('returned' if p.returncode == 0 else 'limit_exceeded'), record
if p.returncode == 0:
assert record['value'] == expected, (path, record)
if fuel == 10000:
assert p.returncode == 0, (path, record)
result = root / 'hosted.json'
for seed in (0, 7, 31):
cli('run', '--profile', 'hosted', '--result-file', result, '--fuel', '10000',
'--quantum', '1', '--schedule-seed', str(seed), *args, path)
assert json.loads(result.read_text())['value'] == expected
print(f'shield relations passed ({checks} CLI checks)')