#!/usr/bin/env python3 """Owning buffered adapters: CLI/AIR/packages, hosted failure and no retry.""" import base64 import json from pathlib import Path import resource import signal import subprocess import sys import tempfile REPO = Path(__file__).resolve().parents[2] AJI = REPO / "zig-out/bin/aji" CASES = REPO / "tests/conformance/source/buffered_io" checks = 0 def cli(*args, code=0, **kwargs): global checks run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True, **kwargs) detail = None if run.returncode != code and "--result-file" in args: result = Path(args[args.index("--result-file") + 1]) if result.exists(): detail = result.read_text() assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr, detail) checks += 1 return run.stdout def returned(path, *grants, extra=()): args = [item for grant in grants for item in ("--grant", grant)] record = json.loads(cli("run", "--fuel", "2000000", *args, *extra, path)) assert record["status"] == "returned", record return record example = REPO / "examples/std/buffered_io.aji" grants = ("src=fs.read:/in", "dst=fs.write:/out", "heap=mem.alloc:6") record = returned(example, *grants, extra=("--vfs", "/in/data=abcdefgh")) assert record["value"] == 8 and base64.b64decode(record["files"]["/out/data"]["data"]) == b"abcdefgh", record 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) for path in sorted(CASES.glob("*.aji")): if "// expect: run\n" not in path.read_text(): continue args = [] for line in path.read_text().splitlines(): if line.startswith("// grant: "): args.extend(("--grant", line.removeprefix("// grant: "))) if line.startswith("// vfs: "): args.extend(("--vfs", line.removeprefix("// vfs: "))) assert returned(path, extra=args)["value"] == 42 for name, expected in (("missing_read_effect", "E3101"), ("missing_write_effect", "E3101"), ("missing_alloc_effect", "E3101"), ("wrong_kind", "E7005"), ("wrong_mode", "E7005"), ("missing_move", "E7003"), ("discard_leak", "E3002"), ("finish_error_leak", "E3002"), ("reader_alias", "E2101"), ("writer_alias", "E2101"), ("loan", "E4101"), ("not_share", "E4002")): commands = ("check", "lower", "report", "run", "explore") if expected in ("E7003", "E7005") else ("check", "report", "run", "explore") for command in commands: path = CASES / (name + ".aji") errors = [json.loads(line) for line in cli(command, path, code=1).splitlines()] assert errors and {error["code"] for error in errors} == {expected}, errors assert all(Path(error["file"]).resolve() == path.resolve() for error in errors), errors CHECK_ERROR = '''fn error_is_other(error: io_error) -> void effects [] { match error { io_error::other => {}, _ => { trap; } } } fn flush_failed(result: std.io.writer.FlushResult) -> void effects [] { match result { std.io.writer.FlushResult::err(error) => { error_is_other(error); }, std.io.writer.FlushResult::ok => { trap; } } } fn write_failed(result: std.io.writer.WriteResult,accepted: usize) -> void effects [] { match result { std.io.writer.WriteResult::err(error) => { assert(error.accepted == accepted); error_is_other(error.error); }, std.io.writer.WriteResult::ok => { trap; } } } fn pending(value: ref,expected: usize) -> void effects [] { assert(value.used == expected); if expected != 0usize { ref storage = value.storage; ref bytes = buffer.view(storage); assert(bytes[0] == 99u8); assert(bytes[1] == 100u8); } } ''' # Enum matches are exhaustive (no enum wildcard); construct the remaining arms. TAGS = ("not_found", "permission_denied", "already_exists", "invalid_input", "no_space", "broken_pipe", "connection_refused", "connection_reset", "address_in_use", "address_unavailable", "timed_out") CHECK_ERROR = CHECK_ERROR.replace('_ => { trap; }', ', '.join(f'io_error::{tag} => {{ trap; }}' for tag in TAGS)) with tempfile.TemporaryDirectory(prefix="aji-buffered-io-") as directory: root = Path(directory) air = root / "lowered.air" air.write_text(canonical) cli("check", air) assert returned(air, *grants, extra=("--vfs", "/in/data=abcdefgh")) == record entry, manifest = root / "main.aji", root / "aji.toml" entry.write_text(example.read_text()) manifest.write_text('[package]\nname = "buffered"\nversion = "1"\nentry = "main.aji"\n[capabilities]\nsrc = "fs.read:/in"\ndst = "fs.write:/out"\nheap = "mem.alloc:6"\n') package = json.loads(cli("run", "--fuel", "2000000", "--vfs", "/in/data=abcdefgh", "--manifest", manifest)) assert package == record, package assert cli("lower", "--manifest", manifest) == canonical entry.write_text(example.read_text().replace('import std.io.reader;\nimport std.io.writer;', 'import std.io.writer;\nimport std.io.reader;')) assert cli("lower", "--manifest", manifest) == canonical source, target, result = root / "input", root / "output", root / "result.json" source.write_text("abcdefgh") entry.write_text(example.read_text().replace('b"/in/data"', f'b"{source}"').replace('b"/out/data"', f'b"{target}"')) stdout = cli("run", "--profile", "hosted", "--fuel", "2000000", "--grant", f"src=fs.read:{root}", "--grant", f"dst=fs.write:{root}", "--grant", "heap=mem.alloc:6", "--result-file", result, entry) assert stdout == "" and json.loads(result.read_text())["value"] == 8 and target.read_bytes() == b"abcdefgh" # Linux /proc/self/mem opens normally but offset zero cannot be read. # No memory contents are read; the hosted primitive returns EIO / other. if sys.platform.startswith("linux"): entry.write_text('''module app.read_error import std.io; import std.io.reader; ''' + CHECK_ERROR.split("fn flush_failed")[0] + '''fn main(src: cap,heap: cap) -> u64 effects [fs.read,mem.alloc] { let file = fs.open_read(src,b"/proc/self/mem") or trap; match std.io.reader.new(move file,3usize,heap) { std.io.reader.NewResult::err(error) => { trap; }, std.io.reader.NewResult::ok(value) => { var bytes: [u8;6] = [99u8;6]; { mut q = value; match std.io.reader.read_exact(q,mut bytes[1usize..5usize]) { std.io.ReadExactResult::err(error) => { assert(error.completed == 0usize); error_is_other(error.error); }, std.io.ReadExactResult::ok => { trap; }, std.io.ReadExactResult::eof(n) => { trap; } } assert(q.begin == 0usize); assert(q.end == 0usize); match std.io.reader.read(q,mut bytes[0usize..0usize]) { std.io.reader.ReadResult::ok(n) => { assert(n == 0usize); }, std.io.reader.ReadResult::err(error) => { trap; } } match std.io.reader.read(q,mut bytes[1usize..5usize]) { std.io.reader.ReadResult::err(error) => { error_is_other(error); }, std.io.reader.ReadResult::ok(n) => { trap; } } } assert(bytes[0] == 99u8); assert(bytes[5] == 99u8); let (file,unread) = struct.unpack(std.io.reader.discard(move value)); assert(unread == 0usize); fs.close(move file) or trap; } } let allocation = own.new([0u8;3],heap) or trap; own.free(move allocation); return 42; } ''') cli("run", "--profile", "hosted", "--fuel", "2000000", "--grant", "src=fs.read:/proc/self", "--grant", "heap=mem.alloc:3", "--result-file", result, entry) assert json.loads(result.read_text())["value"] == 42 def partial_write_limit(): signal.signal(signal.SIGXFSZ, signal.SIG_IGN) resource.setrlimit(resource.RLIMIT_FSIZE, (3, 1048576)) for mode in ("room", "prior", "flush", "direct"): capacity = 0 if mode == "direct" else 2 initial = { "direct": 'write_failed(std.io.writer.write(q,b"abcdef"),0usize);', "room": 'write_failed(std.io.writer.write(q,b"abcdef"),4usize);', "prior": 'match std.io.writer.write(q,b"ab") { std.io.writer.WriteResult::ok => {}, std.io.writer.WriteResult::err(error) => { trap; } } write_failed(std.io.writer.write(q,b"cdefgh"),2usize);', "flush": 'match std.io.writer.write(q,b"abcd") { std.io.writer.WriteResult::ok => {}, std.io.writer.WriteResult::err(error) => { trap; } } flush_failed(std.io.writer.flush(q));', }[mode] entry.write_text('''module app.partial_write import std.io; import std.io.writer; import std.option; ''' + CHECK_ERROR + f'''fn main(dst: cap,heap: cap,input: cap,print: cap) -> u64 effects [fs.write,mem.alloc,io.read,io.write] {{ let file = fs.create(dst,b"{target}") or trap; match std.io.writer.new(move file,{capacity}usize,heap) {{ std.io.writer.NewResult::err(error) => {{ trap; }}, std.io.writer.NewResult::ok(value) => {{ {{ mut q = value; {initial} pending(ref q,{capacity}usize); match q.failed {{ std.option.Option::::some(error) => {{ error_is_other(error); }}, std.option.Option::::none => {{ trap; }} }} }} io.stdout_write(print,b"E") or trap; var ack: [u8;1] = [0u8;1]; match std.io.read_exact_stdin(input,mut ack) {{ std.io.ReadExactResult::ok => {{}}, std.io.ReadExactResult::eof(n) => {{ trap; }}, std.io.ReadExactResult::err(error) => {{ trap; }} }} assert(ack[0] == 89u8); {{ mut q = value; flush_failed(std.io.writer.flush(q)); write_failed(std.io.writer.write(q,b"z"),0usize); write_failed(std.io.writer.write(q,ref ack[0usize..0usize]),0usize); pending(ref q,{capacity}usize); }} match std.io.writer.finish(move value) {{ std.io.writer.FinishResult::ok(file) => {{ trap; }}, std.io.writer.FinishResult::err(error) => {{ let (writer,error) = struct.unpack(move error); error_is_other(error); let (file,pending,failed) = struct.unpack(std.io.writer.discard(move writer)); assert(pending == {capacity}usize); match failed {{ std.option.Option::::some(error) => {{ error_is_other(error); }}, std.option.Option::::none => {{ trap; }} }} fs.close(move file) or trap; }} }} }} }} let allocation = own.new([0u8;2],heap) or trap; own.free(move allocation); io.stdout_write(print,b"42") or trap; return 42; }} ''') cli("check", entry) command = [str(AJI), "run", "--profile", "hosted", "--fuel", "2000000", "--grant", f"dst=fs.write:{root}", "--grant", "heap=mem.alloc:2", "--grant", "input=io.read", "--grant", "print=io.write", str(entry)] with subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=partial_write_limit) as process: marker = process.stdout.read(1) if marker != b"E": output, error = process.communicate() raise AssertionError((mode, marker, process.returncode, output, error)) assert target.read_bytes() == b"abc", (mode, target.read_bytes()) # On Linux raise the child's quota before subsequent calls. A retry # would now succeed and append duplicated buffered bytes to the file. if hasattr(resource, "prlimit"): resource.prlimit(process.pid, resource.RLIMIT_FSIZE, (1048576, 1048576)) output, error = process.communicate(b"Y") assert process.returncode == 0 and output == b"42", (mode, process.returncode, output, error) assert target.read_bytes() == b"abc", (mode, target.read_bytes()) checks += 1 print(f"buffered I/O integration passed ({checks} checks, partial room/flush/direct writes; Linux read error and raised-quota no retry)")