Files
aji/tests/hosted/source_heap.py
T
dev cfece6080c cli: add safe owning binary heaps
Add std.heap with an exact explicit pure ordering operation, bounded
push, Copy-only peek, moving pop and empty-only free. Sift Copy indices
while complete owners remain in dense initialized storage; repair holes
through complete exchange. Reserve preserves layout on returned failure
and accounts for both old/new buffers and separately owned payloads.

Integrate normative contracts, RFC, references, bundle measurements,
independent heapq/permutation oracles and CLI/package/profile checks.

Validation: 1007 conformance cases; 34 heap GC fixtures and scheduled
stress; unit/Quick Reference, formatting, hosted smoke, 70 CLI checks,
109 source coverage constructs and unchanged AIR reference bundle.
2026-10-07 11:41:35 +03:00

101 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""Owning binary heap through source/AIR, explicit policies and profiles."""
import json
from pathlib import Path
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / "zig-out/bin/aji"
CASES = REPO / "tests/conformance/source/heap"
checks = 0
def cli(*args, code=0):
global checks
run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr)
checks += 1
return run.stdout
def returned(path, *grants):
args = [item for grant in grants for item in ("--grant", grant)]
record = json.loads(cli("run", "--fuel", "2000000", *args, path))
assert record["status"] == "returned" and record["value"] == 42, record
return record
example = REPO / "examples/std/heap.aji"
returned(example, "heap=mem.alloc:40")
cli("check", example)
report = json.loads(cli("report", example))
assert report["unsafe"]["operations"] == 0 and report["unsafe"]["trusted_functions"] == [], report
canonical = cli("lower", example)
assert canonical == cli("lower", example)
assert "trusted" not in canonical and "unsafe" not in canonical
for name in ("copy", "owner", "direct_owner", "byte_values", "owner_growth", "owner_failure", "reserve_failure", "reserve_peak",
"reserve_authority", "layout_failure", "zero", "rollback", "model", "model_owner", "permutations",
"free_returns", "shared", "full_no_callback"):
path = CASES / (name + ".aji")
grants = [line.removeprefix("// grant: ") for line in path.read_text().splitlines() if line.startswith("// grant: ")]
returned(path, *grants)
for name, expected in (("full_leak", "E3002"), ("free_leak", "E3002"), ("pop_leak", "E3002"),
("missing_move", "E7003"), ("peek_owner", "E7005"), ("policy_effect", "E7005"),
("policy_mismatch", "E7005"), ("not_share", "E4002")):
commands = ("check", "report", "run", "explore") if expected in ("E3002", "E4002") else ("check", "lower", "report", "run", "explore")
for command in commands:
records = [json.loads(line) for line in cli(command, CASES / (name + ".aji"), code=1).splitlines()]
assert records and {error["code"] for error in records} == {expected}, records
with tempfile.TemporaryDirectory(prefix="aji-heap-") as directory:
root = Path(directory)
air = root / "lowered.air"
air.write_text(canonical)
cli("check", air)
assert returned(air, "heap=mem.alloc:40") == returned(example, "heap=mem.alloc:40")
result = root / "hosted.json"
stdout = cli("run", "--profile", "hosted", "--fuel", "2000000", "--grant", "heap=mem.alloc:40", "--result-file", result, example)
assert stdout == "" and json.loads(result.read_text())["value"] == 42
policy = root / "policy.aji"
policy.write_text('''module app.policy
struct Item { priority: u64, owner: own<u64> }
fn before(a: ref<Item>, b: ref<Item>) -> bool effects [] { return a.priority < b.priority; }
''')
entry, manifest = root / "main.aji", root / "aji.toml"
manifest.write_text('[package]\nname = "heap"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.policy = "policy.aji"\n[capabilities]\nheap = "mem.alloc:40"\n')
program = example.read_text().replace("module demo.heap", "module app.entry")
start, end = program.index("struct Item"), program.index("fn main(")
program = program[:start].replace("import std.option;", "import std.option;\nimport app.policy;") + program[end:]
program = program.replace("<Item,", "<app.policy.Item,").replace("<Item>", "<app.policy.Item>").replace("fn before", "fn app.policy.before").replace("Item {", "app.policy.Item {")
entry.write_text(program)
record = json.loads(cli("run", "--fuel", "2000000", "--manifest", manifest))
assert record["status"] == "returned" and record["value"] == 42, record
package_air = cli("lower", "--manifest", manifest)
cli("report", "--manifest", manifest)
imports = "import std.heap;\nimport std.option;\nimport app.policy;"
entry.write_text(program.replace(imports, "import app.policy;\nimport std.option;\nimport std.heap;"))
assert cli("lower", "--manifest", manifest) == package_air
# A second item makes the selected comparator run inside heap sifting.
extra = '''let second = app.policy.Item { priority: 0,owner: own.new(99u64,heap) or trap };
match std.heap.push::<app.policy.Item,fn app.policy.before>(q,move second) {
std.heap.PushResult::<app.policy.Item>::ok => {}, std.heap.PushResult::<app.policy.Item>::full(item) => { trap; }
}
match std.heap.pop::<app.policy.Item,fn app.policy.before>(q) {
std.option.Option::<app.policy.Item>::some(item) => { let (priority,owner) = struct.unpack(move item); assert(own.take(move owner) == 99u64); },
std.option.Option::<app.policy.Item>::none => { trap; }
}
'''
trapped = program.replace("(1,heap)", "(2,heap)").replace(" match std.heap.pop", " " + extra + "match std.heap.pop", 1)
entry.write_text(trapped)
manifest.write_text(manifest.read_text().replace("mem.alloc:40", "mem.alloc:80"))
record = json.loads(cli("run", "--fuel", "2000000", "--manifest", manifest))
assert record["value"] == 42, record
policy.write_text(policy.read_text().replace("return a.priority", "assert(false); return a.priority"))
record = json.loads(cli("run", "--fuel", "2000000", "--manifest", manifest, code=4))
assert Path(record["source_location"]["file"]).name == "policy.aji", record
record = json.loads(cli("run", "--fuel", "2000000", "--grant", "heap=mem.alloc:24", CASES / "invalid_indices.aji", code=4))
assert record["code"] == "T0008" and record["source_location"]["file"] == "std/heap.aji", record
print(f"binary-heap CLI integration passed ({checks} checks)")