cli: add explicit bounded standard I/O composition
Add std.io exact stdin/file/TCP reads, bounded file read-to-end and limited file write/append copies. Use caller slices and resource loans, exact effects, explicit EOF/capacity/limit and confirmed partial progress. No implicit heap, open/close, timeout or new AIR/runtime semantics. Document failure limits and check hosted read errors and a partial external file write under a child-only file-size quota. Integrate normative contracts, RFC, source reference budgets, CLI/profile/package checks and independent byte/count/cursor vectors. Validation: 1027 conformance cases, 20 I/O GC cases, scheduled stress, unit/Quick Reference, formatting, hosted smoke, 55 CLI checks, 111 source coverage constructs and unchanged AIR reference bundle.
This commit is contained in:
1 parent
cfece6080c
commit
3e1c0f34e8
37 files changed
+1181
-6
No files matched your search
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded I/O composition: CLI/AIR/packages, hosted errors and resources."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
AJI = REPO / "zig-out/bin/aji"
|
||||
CASES = REPO / "tests/conformance/source/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/io.aji"
|
||||
grants = ("src=fs.read:/in", "dst=fs.write:/out")
|
||||
record = returned(example, *grants, extra=("--vfs", "/in/data=abcd"))
|
||||
assert record["value"] == 4 and base64.b64decode(record["files"]["/out/data"]["data"]) == b"abcd", 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 name in ("file", "copy", "copy_limit", "copy_exact_limit", "append", "zero_scratch", "maximum_limit", "to_end", "model"):
|
||||
path = CASES / (name + ".aji")
|
||||
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
|
||||
assert returned(CASES / "stdin.aji", "input=io.read", extra=("--stdin", "abcd"))["value"] == 42
|
||||
for name, expected in (("missing_effect", "E3101"), ("wrong_kind", "E7005"), ("wrong_mode", "E7005"),
|
||||
("copy_mode", "E7005"), ("alias", "E2101"), ("close_borrowed", "E2101"), ("loan", "E4101")):
|
||||
commands = ("check", "lower", "report", "run", "explore") if expected == "E7005" else ("check", "report", "run", "explore")
|
||||
for command in commands:
|
||||
errors = [json.loads(line) for line in cli(command, CASES / (name + ".aji"), code=1).splitlines()]
|
||||
assert errors and {error["code"] for error in errors} == {expected}, errors
|
||||
assert all(Path(error["file"]).resolve() == (CASES / (name + ".aji")).resolve() for error in errors), errors
|
||||
|
||||
tags = ("not_found", "permission_denied", "already_exists", "invalid_input", "no_space", "broken_pipe",
|
||||
"connection_refused", "connection_reset", "address_in_use", "address_unavailable", "timed_out", "other")
|
||||
kind = "fn kind(error: io_error) -> u64 effects [] { match error { " + ",".join(f"io_error::{tag} => {{ return {i}; }}" for i, tag in enumerate(tags)) + " } }\n"
|
||||
with tempfile.TemporaryDirectory(prefix="aji-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=abcd")) == record
|
||||
entry = root / "main.aji"
|
||||
manifest = root / "aji.toml"
|
||||
entry.write_text(example.read_text())
|
||||
manifest.write_text('[package]\nname = "io"\nversion = "1"\nentry = "main.aji"\n[capabilities]\nsrc = "fs.read:/in"\ndst = "fs.write:/out"\n')
|
||||
package = json.loads(cli("run", "--fuel", "2000000", "--vfs", "/in/data=abcd", "--manifest", manifest))
|
||||
assert package == record, package
|
||||
assert cli("lower", "--manifest", manifest) == canonical
|
||||
imports = example.read_text().replace("import std.io;", "import std.io;\nimport std.bytes;")
|
||||
entry.write_text(imports)
|
||||
ordered = cli("lower", "--manifest", manifest)
|
||||
entry.write_text(imports.replace("import std.io;\nimport std.bytes;", "import std.bytes;\nimport std.io;"))
|
||||
assert cli("lower", "--manifest", manifest) == ordered
|
||||
source, target, result = root / "input", root / "output", root / "result.json"
|
||||
source.write_text("abcdef")
|
||||
hosted = example.read_text().replace('b"/in/data"', f'b"{source}"').replace('b"/out/data"', f'b"{target}"')
|
||||
entry.write_text(hosted)
|
||||
stdout = cli("run", "--profile", "hosted", "--fuel", "2000000", "--grant", f"src=fs.read:{root}", "--grant", f"dst=fs.write:{root}", "--result-file", result, entry)
|
||||
assert stdout == "" and json.loads(result.read_text())["value"] == 6 and target.read_text() == "abcdef"
|
||||
# A directory used as stdin gives a real hosted read error, with zero progress.
|
||||
entry.write_text('''module app.read_error
|
||||
import std.io;
|
||||
''' + kind + '''fn main(input: cap<io.read>) -> u64 effects [io.read] {
|
||||
var bytes: [u8;4] = [99u8;4];
|
||||
match std.io.read_exact_stdin(input,mut bytes[1usize..3usize]) {
|
||||
std.io.ReadExactResult::err(error) => { assert(error.completed == 0usize); assert(kind(error.error) == 3u64); },
|
||||
std.io.ReadExactResult::ok => { trap; }, std.io.ReadExactResult::eof(count) => { trap; }
|
||||
}
|
||||
assert(bytes[0] == 99u8); assert(bytes[3] == 99u8); return 42;
|
||||
}
|
||||
''')
|
||||
descriptor = os.open(root, os.O_RDONLY)
|
||||
try:
|
||||
cli("run", "--profile", "hosted", "--fuel", "2000000", "--grant", "input=io.read", "--result-file", result, entry, stdin=descriptor)
|
||||
assert json.loads(result.read_text())["value"] == 42
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
# Child-only file-size quota forces a partial second write: no wall timeout.
|
||||
# The program's stdout is a pipe; no result file is written under this quota.
|
||||
entry.write_text('''module app.partial_write
|
||||
import std.io;
|
||||
''' + kind + f'''fn main(src: cap<fs.read>,dst: cap<fs.write>,print: cap<io.write>) -> u64 effects [fs.read,fs.write,io.write] {{
|
||||
let input = fs.open_read(src,b"{source}") or trap; let output = fs.create(dst,b"{target}") or trap; var scratch: [u8;2] = [0u8;2];
|
||||
match std.io.copy_file(mut input,mut output,mut scratch,8usize) {{
|
||||
std.io.CopyResult::err(error) => {{ assert(error.read == 4usize); assert(error.confirmed_written == 2usize); assert(kind(error.error) == 11u64); }},
|
||||
std.io.CopyResult::eof(count) => {{ trap; }}, std.io.CopyResult::limit(count) => {{ trap; }}
|
||||
}}
|
||||
match std.io.read_exact_file(mut input,mut scratch) {{ std.io.ReadExactResult::ok => {{}}, std.io.ReadExactResult::eof(count) => {{ trap; }}, std.io.ReadExactResult::err(error) => {{ trap; }} }}
|
||||
assert(scratch[0] == 101u8); assert(scratch[1] == 102u8); fs.close(move input) or trap; fs.close(move output) or trap;
|
||||
io.stdout_write(print,b"42") or trap; return 42;
|
||||
}}
|
||||
''')
|
||||
|
||||
def partial_write_limit():
|
||||
signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (3, 3))
|
||||
|
||||
stdout = cli("run", "--profile", "hosted", "--fuel", "2000000", "--grant", f"src=fs.read:{root}", "--grant", f"dst=fs.write:{root}", "--grant", "print=io.write", entry, preexec_fn=partial_write_limit)
|
||||
assert stdout == "42" and target.read_bytes() == b"abc"
|
||||
|
||||
print(f"bounded I/O CLI integration passed ({checks} checks, hosted read error and partial external write)")
|
||||
Reference in new issue
Block a user