Files
aji/tests/hosted/source_hashmap.py
dev 7bb5bd7931 cli: add safe owning general-key hash maps
Use explicit static hash/equality functions, dense complete key/value entries
and Copy probe indices. Preserve returned ownership and allocation failure
state without unsafe code or new runtime instructions.

Add normative contracts, API/reference budgets, 33 conformance cases, independent
Copy/owner dict traces and 55 CLI/package/profile checks. Full corpus: 947 passing.
Collection-every-step scheduler stress remains in progress, recorded in RFC/plan.
2026-10-07 10:55:09 +03:00

102 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""General owning maps through explicit policies, source/AIR, packages 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/hashmap"
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", "4000000", *args, path))
assert record["status"] == "returned" and record["value"] == 42, record
return record
example = REPO / "examples/std/hashmap.aji"
returned(example, "heap=mem.alloc:66")
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, budget in [("copy", 1024), ("owner", 1024), ("owner_returned", 98), ("byte_keys", 256),
("key_copy_lookup", 82), ("reserve_failure", 251), ("reserve_peak", 174),
("no_empty", 116), ("zero", 0), ("rollback", 40), ("model", 1120), ("model_owner", 1120)]:
returned(CASES / (name + ".aji"), f"heap=mem.alloc:{budget}")
for name, expected in [("full_leak", "E3002"), ("key_missing_move", "E7003"),
("get_owner", "E7005"), ("policy_mismatch", "E7005"),
("policy_effect", "E7005"), ("free_leak", "E3002")]:
commands = ("check", "report", "run", "explore") if expected == "E3002" 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-hashmap-") as directory:
root = Path(directory)
air = root / "lowered.air"
air.write_text(canonical)
cli("check", air)
assert returned(air, "heap=mem.alloc:66") == returned(example, "heap=mem.alloc:66")
# Hosted results use the same pinned library and explicit heap accounting.
result = root / "hosted.json"
stdout = cli("run", "--profile", "hosted", "--fuel", "4000000", "--grant", "heap=mem.alloc:66", "--result-file", result, example)
assert stdout == "" and json.loads(result.read_text())["value"] == 42
# Package policy selection is explicit and preserves nominal identities.
policy = root / "policy.aji"
policy.write_text('''module app.policy
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
''')
entry, manifest = root / "main.aji", root / "aji.toml"
manifest.write_text('[package]\nname = "hashmap"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.policy = "policy.aji"\n[capabilities]\nheap = "mem.alloc:66"\n')
program = example.read_text().replace("module demo.hashmap", "module app.entry")
start, end = program.index("struct Key"), program.index("fn main(")
program = program[:start].replace("import std.option;", "import std.option;\nimport app.policy;") + program[end:]
program = program.replace("<Key,", "<app.policy.Key,").replace("fn hash", "fn app.policy.hash").replace("fn equal", "fn app.policy.equal").replace("Key {", "app.policy.Key {")
entry.write_text(program)
record = json.loads(cli("run", "--fuel", "4000000", "--manifest", manifest))
assert record["value"] == 42, record
package_air = cli("lower", "--manifest", manifest)
cli("report", "--manifest", manifest)
imports = "import std.hashmap;\nimport std.option;\nimport app.policy;"
entry.write_text(program.replace(imports, "import app.policy;\nimport std.option;\nimport std.hashmap;"))
assert cli("lower", "--manifest", manifest) == package_air
entry.write_text(program)
policy.write_text(policy.read_text().replace("return 3;", "assert(false); return 3;"))
record = json.loads(cli("run", "--fuel", "4000000", "--manifest", manifest, code=4))
assert Path(record["source_location"]["file"]).name == "policy.aji", record
# Imported standard code diagnostics/traps retain repository paths.
invalid = (CASES / "copy.aji").read_text()
invalid = invalid.replace("fn main(", "fn entry_original(")
invalid += '''
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key,u64,fn hash,fn equal>(1,heap);
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key,u64,fn hash,fn equal>(q, Key { id: 1 },42));
mut storage = q.buckets; mut buckets = buffer.view(storage); buckets[1].index = 7usize; }
{ ref q = map; let key = Key { id: 1 }; std.hashmap.contains::<Key,u64,fn hash,fn equal>(q,ref key); }
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key,u64,fn hash,fn equal>(q)); }
released::<Key,u64,fn hash,fn equal>(move map); return 42;
}
'''
entry.write_text(invalid)
record = json.loads(cli("run", "--fuel", "4000000", "--grant", "heap=mem.alloc:1024", entry, code=4))
assert record["code"] == "T0008" and record["source_location"]["file"] == "std/hashmap.aji", record
print(f"general hash-map CLI integration passed ({checks} checks)")