diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c7a0a3..8c44d52 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,7 @@ jobs: - run: python3 tests/hosted/source_format.py - run: python3 tests/hosted/source_diagnostic_reasons.py - run: python3 tests/hosted/related_locations.py + - run: python3 tests/hosted/examples.py --stress 200 - run: python3 tests/hosted/source_static_functions.py - run: python3 tests/hosted/source_linear.py - run: python3 tests/hosted/source_buffers.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dafc195..8378897 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,7 @@ python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and public-corpus AIR fidelity python3 tests/hosted/source_diagnostic_reasons.py # stable E7006 categories and CLI/package provenance python3 tests/hosted/related_locations.py # factual conflict/spawn positions, source mapping and package provenance +python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index aef6f7e..37b06e7 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -138,7 +138,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a | P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN | | P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code | | P6-8 | done | Formatter for implemented source syntax | P6-2 | `aji fmt`, spec 15 §11 | token/comment/declaration preservation; idempotence, identical AIR and CLI write/check tests | -| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes | +| P6-9 | done | Port reference programs and examples to `.aji` | P6-5 | `tests/conformance/source/programs/`, `examples/` | all five source/AIR reference pairs and every example source/package pass | | P6-11 | done (implementation; RFC 0036 Proposed) | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics | | P6-10 | todo | Phase exit review | all | plan status | exit criterion passes | @@ -188,3 +188,13 @@ Validation: the new pipeline test reproduces a failure before correction and pas Q-041 is resolved in spec 15 §7 (DD-020): source scope names are lexical identifiers, used only as the named first operand of `task.spawn`. Ordinary plain/moved value use rejects E7006 `invalid_expression`, with `name` and `type: scope`, before any misleading E7003 transfer hint. Borrowing and assignment retain their existing reasons; non-name/wrong-type spawn operands retain E7005. Ordinary shadowing, saved completion identity, live-child/loan checks and function-local AIR scope flow are unchanged. Formerly accepted aliases and scope-valued expressions now reject. No new source syntax, diagnostic code/reason, feature or verifier/runtime state is introduced. P6-2 remains open for its remaining block forms. Validation: unit tests and full conformance pass, 1,186/1,186 with no failures or pending tests, including 24 new source fixtures (four runs, twenty rejects). New cases cover aliases, block/branch/scope yields, aggregates, arguments, specialized bodies, shadowing, outer/nested scope lookup and unjoined children. Scope tests pass with 200 schedule seeds and collection before every instruction; the strengthened return case joins a task holding a ref loan, while break/continue cases join mutable loans. CLI diagnostics pass 206 checks over 88 public E7006 fixtures, including exact imported generic locations, unchanged alternate reasons and deterministic/hosted runs at three quanta. Formatter checks pass 3,359 assertions over 900 public files, with 888 parsed files, 12 syntax-error fixtures and 565 identical successful AIR outputs. Coverage remains 120/120. Across 1,208 original public source/AIR/std/example files, all 2,084 check/lower outputs and exit codes are byte-identical, including 560 successful source lowerings. Independent read-only Claude review found no accepted bypass or cleanup regression; its immutable-assignment spec clarification is included. Bundle growth is recorded in docs/agent/README.md; frozen evaluation inputs remain unchanged. This completes Q-041, not Phase 6. + +## P6-9 executable examples (2026-10-07) + +Four legacy examples now use implemented source syntax: disjoint parallel map, Island channel transfer, atomic publication and a bounded journal. The hello package now enters through `.aji`, retaining its AIR counterpart. All 27 example source files are checked through 24 standalone entry points and two explicit packages, including the module helper. Five larger source/AIR reference pairs already live in `tests/conformance/source/programs/`; their stress validation completes this task. P6-10 remains open. + +No language/spec, AIR, diagnostic, verifier or interpreter rule changes. Existing ownership, borrow, effect, capability and task rules enforce explicit joins, resource consumption and release/acquire ordering; existing source rejects such as `layer9/reject/use_after_send.aji` retain E2001. Previously unparsable examples become executable. The journal creates a fresh file, checks length/offset before writing, documents its payload-only CRC and blocks further appends after partial I/O failure; explicit close remains required. This is an application example, not a durable-log contract or an implementation of source `requires`/`ensures`. + +Validation: unit tests and full conformance pass, 1,186/1,186. All five reference pairs pass with 200 schedule seeds and collection before every instruction. New CI checks pass 3,662 CLI calls: every example/package, independent journal encoding/CRC/offset checks, overflow without writes, partial hosted writes, and concurrent source/AIR record equality at 200 seeds across three quanta. Linux raises the failed file's quota before retry to verify poisoning; the branch without `prlimit` also passes, retaining the original quota. Independent Claude review found the old-file offset error and two integration issues; these are corrected. A separate formatter correction preserves spaces in unpack/grouped range forms, with a failing-before/passing-after unit test and CLI AIR-fidelity test. Source Bundle hashes are unchanged for all 16 files; Quick Reference, AIR and token budgets do not grow. Frozen evaluation inputs remain unchanged. + +Separate P6-5 implementation follow-up: a struct field named `len` currently reaches the array/slice `.len` path and rejects E7005. Spec 15 §5 already permits ordinary struct field access; fixing that dispatch requires no new language design. The executable header uses the explicit field name `length`. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..31ad6ee --- /dev/null +++ b/examples/README.md @@ -0,0 +1,18 @@ +# Executable Aji examples + +These examples use the implemented `.aji` syntax. Build with `zig build`, then run from the repository root. Each command supplies a deterministic fuel budget and the capabilities its program requests. + +| Example | Demonstrates | Command | +|---|---|---| +| [hello.aji](hello.aji) | Explicit stdout authority | `zig-out/bin/aji run --fuel 100000 --grant stdout=io.write examples/hello.aji` | +| [file_copy.aji](file_copy.aji) | Borrowed files and explicit close | `zig-out/bin/aji run --fuel 100000 --grant fs_read=fs.read:/in --grant fs_write=fs.write:/out --vfs '/in/data.txt=some text' examples/file_copy.aji` | +| [parallel_map.aji](parallel_map.aji) | Disjoint mutable loans to two scoped tasks; returns 204 | `zig-out/bin/aji run --fuel 100000 examples/parallel_map.aji` | +| [channel_transfer.aji](channel_transfer.aji) | Move an Island through a bounded channel; returns 42 | `zig-out/bin/aji run --fuel 100000 --grant heap=mem.alloc:256 examples/channel_transfer.aji` | +| [atomic_publish.aji](atomic_publish.aji) | Explicit release/acquire publication, including a read before join; returns 42 | `zig-out/bin/aji run --fuel 100000 examples/atomic_publish.aji` | +| [append_log.aji](append_log.aji) | Bounded records, checked offsets and recoverable I/O; returns 19 | `zig-out/bin/aji run --fuel 100000 --grant fs_write=fs.write:/out examples/append_log.aji` | + +The journal example creates a new file, replacing previous contents. Its wire format is a 16-byte little-endian header (u32 payload length, u32 payload-only CRC32C, u64 byte offset), followed by the payload. A failed write poisons the Log and blocks further appends; closing the file remains explicit. Header integrity, atomic durable records and recovery are outside this demonstration. The 16 MiB limit is an explicit guard; source `requires`/`ensures` support remains P6-6. + +[modules/](modules/aji.toml) demonstrates explicit module inputs: `zig-out/bin/aji run --fuel 100000 --manifest examples/modules/aji.toml`. [packages/hello/](packages/hello/aji.toml) runs a source entry with manifest grants: `zig-out/bin/aji run --fuel 100000 --manifest examples/packages/hello/aji.toml`. Its retained `main.air` is an execution counterpart, rather than the package entry. + +[std/](std/) contains eighteen examples for the compiler-pinned standard modules. `python3 tests/hosted/examples.py --stress 200` checks and runs every standalone example and both packages, verifies journal bytes independently, injects a partial host write, and compares concurrent source/AIR runs over schedule seeds. The five larger [reference programs](../tests/conformance/source/programs/) run with their AIR counterparts through `zig build conformance -- --filter source/programs --stress 200`. diff --git a/examples/append_log.aji b/examples/append_log.aji index 1db5251..58925fe 100644 --- a/examples/append_log.aji +++ b/examples/append_log.aji @@ -1,52 +1,116 @@ -module examples.append_log; - -const HEADER_SIZE: usize = 16; +// Run: aji run --fuel 100000 --grant fs_write=fs.write:/out examples/append_log.aji +module examples.append_log +import std.bytes; +import std.hash; +import std.math; struct Header { - len: u32, + length: u32, crc: u32, - sequence: u64, + offset: u64 } struct Log { - file: File, + file: file, offset: u64, + failed: bool } -fn encode_header(header: ref
) -> [u8; HEADER_SIZE] -effects [] -{ - var out = [0u8; HEADER_SIZE]; - bytes.put_u32_le(mut out, 0, header.len); - bytes.put_u32_le(mut out, 4, header.crc); - bytes.put_u64_le(mut out, 8, header.sequence); - return out; +enum AppendResult { + ok(u64), + too_large, + offset_overflow, + poisoned, + io_failed(io_error) } -fn append( - log: mut, - data: slice -) -> Result -requires { - len(data) <= 16 MiB +fn encoded(result: std.bytes.WriteResult) -> void effects [] { + match result { + std.bytes.WriteResult::ok => {} + std.bytes.WriteResult::short_output => { + trap; + } + } } -effects [fs.write] -{ - let crc = crc32c(data); - let len32 = checked_cast(len(data))?; - let header = Header { - len: len32, - crc: crc, - sequence: log.offset, - }; - let encoded = encode_header(ref header); - - fs.write_all(ref log.file, slice.of(encoded))?; - fs.write_all(ref log.file, data)?; +fn encode_header(header: ref
) -> [u8; 16] effects [] { + var out: [u8; 16] = zero; + encoded(std.bytes.write_u32_le(mut out[0usize..4usize], header.length)); + encoded(std.bytes.write_u32_le(mut out[4usize..8usize], header.crc)); + encoded(std.bytes.write_u64_le(mut out[8usize..16usize], header.offset)); + out +} +fn append(log: mut, data: slice) -> AppendResult effects [fs.write] { + // Explicit guards until source contracts (P6-6) are implemented. + if log.failed { + return AppendResult::poisoned; + } + if data.len > 16777216usize { + return AppendResult::too_large; + } let old = log.offset; - log.offset = checked_add(log.offset, HEADER_SIZE + len(data))?; - - return Ok(old); + let next = match std.math.checked_add_u64(old, 16u64 + data.len as! u64) { + std.math.U64Result::ok(value) => { + value + }, + std.math.U64Result::overflow => { + return AppendResult::offset_overflow; + } + }; + // Wire format: little-endian length, payload-only CRC32C, byte offset. + // This demonstration has no header checksum or crash-recovery protocol. + let header = Header { length: data.len as! u32, crc: std.hash.crc32c(data), offset: old }; + let bytes = encode_header(ref header); + { + mut output = log.file; + match fs.write_all(output, ref bytes) { + ok => {} + err(error) => { + log.failed = true; + return AppendResult::io_failed(error); + } + } + match fs.write_all(output, data) { + ok => {} + err(error) => { + log.failed = true; + return AppendResult::io_failed(error); + } + } + } + // I/O failure may leave a partial record. Further appends are blocked; + // the caller must close and recover the file outside this example. + log.offset = next; + AppendResult::ok(old) +} + +fn main(fs_write: cap) -> u64 effects [fs.write] { + // Start a new log, replacing any existing file rather than guessing its size. + let file = fs.create(fs_write, b"/out/log.bin") or trap; + let log = Log { file: move file, offset: 0u64, failed: false }; + let result = append(mut log, b"aji"); + let offset = match result { + AppendResult::ok(value) => { + value + }, + AppendResult::too_large => { + trap; + } + AppendResult::offset_overflow => { + trap; + } + AppendResult::io_failed(error) => { + trap; + } + AppendResult::poisoned => { + trap; + } + }; + let (file, end, failed) = struct.unpack(move log); + fs.close(move file) or trap; + assert(offset == 0u64); + assert(end == 19u64); + assert(not failed); + end } diff --git a/examples/atomic_publish.aji b/examples/atomic_publish.aji index 5627e37..56310ad 100644 --- a/examples/atomic_publish.aji +++ b/examples/atomic_publish.aji @@ -1,25 +1,66 @@ -module examples.atomic_publish; +// Run: aji run --fuel 100000 examples/atomic_publish.aji +module examples.atomic_publish struct Shared { - ready: AtomicBool, - value: AtomicU64, + ready: atomic, + value: atomic } -fn publish(shared: ref, value: u64) -> void -effects [atomic] -{ - atomic.store(ref shared.value, value, relaxed); - atomic.store(ref shared.ready, true, release); +enum ReadResult { + some(u64), + none } -fn try_read(shared: ref) -> Option -effects [atomic] -{ - if atomic.load(ref shared.ready, acquire) { - // The acquire observes the release on `ready`; the earlier relaxed - // store to `value` is ordered before publication. `value` remains - // atomic storage, so no ordinary-memory alias exception is needed. - return Some(atomic.load(ref shared.value, relaxed)); +fn publish(shared: ref, value: u64) -> void effects [atomic, atomic.weak] { + ref data = shared.value; + ref ready = shared.ready; + atomic.store(data, value, relaxed); + atomic.store(ready, true, release); +} + +fn try_read(shared: ref) -> ReadResult effects [atomic, atomic.weak] { + ref ready = shared.ready; + if atomic.load(ready, acquire) { + // The acquire observes publication through ready. Value remains + // atomic storage; no ordinary-memory alias exception is needed. + ref data = shared.value; + return ReadResult::some(atomic.load(data, relaxed)); } - return None; + ReadResult::none +} + +fn main() -> u64 effects [atomic, atomic.weak, task.spawn, task.wait] { + let shared = Shared { ready: atomic.new(false), value: atomic.new(0u64) }; + var result: u64 = 0; + { + ref view = shared; + match try_read(view) { + ReadResult::some(value) => { + trap; + } + ReadResult::none => {} + } + scope s { + let t = task.spawn(s, publish, view, 42u64); + match try_read(view) { + ReadResult::some(value) => { + assert(value == 42u64); + } + ReadResult::none => {} + } + task.join(move t); + } + result = match try_read(view) { + ReadResult::some(value) => { + value + }, + ReadResult::none => { + trap; + } + }; + } + let (ready, value) = struct.unpack(move shared); + assert(atomic.take(move ready)); + assert(atomic.take(move value) == result); + result } diff --git a/examples/channel_transfer.aji b/examples/channel_transfer.aji index 133ca7a..8952f06 100644 --- a/examples/channel_transfer.aji +++ b/examples/channel_transfer.aji @@ -1,23 +1,51 @@ -module examples.channel_transfer; +// Run: aji run --fuel 100000 --grant heap=mem.alloc:256 examples/channel_transfer.aji +module examples.channel_transfer struct Message { - id: u64, + id: u64 } -fn producer( - tx: ref>>, - alloc: cap -) -> Result -effects [mem.alloc] -{ - var message = island.create(alloc, Message { id: 0 })?; - - borrow message as mut root { - root.id = 42; +fn producer(tx: sender>, heap: cap) -> void effects [mem.alloc, task.wait] { + let message = island.create(Message { id: 0u64 }, heap) or trap; + { + mut graph = message; + let address = island.root(graph); + mut root = island.at(graph, address); + root.id = 42u64; + } + match channel.send(tx, move message) { + ok => {} + closed(back) => { + island.destroy(move back); + } cancelled(back) => { + island.destroy(move back); + } + } + // The producer cannot use message after its ownership transfer. + channel.close_sender(move tx); +} + +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + match channel.make>(1usize, heap) { + ok(tx, rx) => { + var result: u64 = 0; + scope s { + let t = task.spawn(s, producer, move tx, heap); + let message = channel.recv(rx) or trap; + { + ref graph = message; + let address = island.root(graph); + ref root = island.at(graph, address); + result = root.id; + } + island.destroy(move message); + task.join(move t); + } + channel.close_receiver(move rx) or trap; + result + } + err(error) => { + trap; + } } - - channel.send(tx, move message)?; - - // message is MOVED and cannot be used here. - return Ok(); } diff --git a/examples/packages/hello/aji.toml b/examples/packages/hello/aji.toml index 0b5ee8e..f26a3c2 100644 --- a/examples/packages/hello/aji.toml +++ b/examples/packages/hello/aji.toml @@ -6,7 +6,7 @@ [package] name = "hello" version = "0.1.0" -entry = "main.air" +entry = "main.aji" [capabilities] out = "io.write" diff --git a/examples/packages/hello/main.aji b/examples/packages/hello/main.aji new file mode 100644 index 0000000..e0bf26d --- /dev/null +++ b/examples/packages/hello/main.aji @@ -0,0 +1,5 @@ +module examples.hello + +fn main(out: cap) -> void effects [io.write] { + io.stdout_write(out, b"hello, aji\n") or trap; +} diff --git a/examples/parallel_map.aji b/examples/parallel_map.aji index eda6986..c1e6e7e 100644 --- a/examples/parallel_map.aji +++ b/examples/parallel_map.aji @@ -1,26 +1,31 @@ -module examples.parallel_map; +// Run: aji run --fuel 100000 examples/parallel_map.aji +module examples.parallel_map -fn square_half(values: slice_mut) -> void -effects [] -{ - for i in 0..len(values) { +fn square_half(values: slice_mut) -> void effects [] { + for i in 0usize..values.len { values[i] = values[i] * values[i]; } } -fn square_all(values: slice_mut) -> Result -effects [task.spawn] -{ - let mid = len(values) / 2; - let (left, right) = slice.split_mut(values, mid); - - task.scope s { - let a = task.spawn_borrow_mut(s, square_half, left)?; - let b = task.spawn_borrow_mut(s, square_half, right)?; - - task.join(move a)?; - task.join(move b)?; +fn square_all(values: slice_mut) -> void effects [task.spawn, task.wait] { + let (left, right) = values.split_at(values.len / 2usize); + scope s { + let a = task.spawn(s, square_half, left); + let b = task.spawn(s, square_half, right); + task.join(move a); + task.join(move b); } - - return Ok(); +} + +fn main() -> u64 effects [task.spawn, task.wait] { + var values: [u64; 8] = zero; + for i in 0usize..values.len { + values[i] = i as! u64 + 1u64; + } + square_all(mut values); + var total: u64 = 0; + for i in 0usize..values.len { + total = total + values[i]; + } + total } diff --git a/tests/hosted/examples.py b/tests/hosted/examples.py new file mode 100644 index 0000000..27b3b0c --- /dev/null +++ b/tests/hosted/examples.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Execute public examples, including packages, wire bytes and task schedules.""" +import argparse +import base64 +import json +from pathlib import Path +import resource +import signal +import struct +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / 'zig-out/bin/aji' +options = argparse.ArgumentParser() +options.add_argument('--stress', type=int, default=8) +seeds = options.parse_args().stress +assert seeds > 0 +checks = 0 + + +def cli(*args, **kwargs): + global checks + result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True, **kwargs) + assert result.returncode == 0, (args, result.returncode, result.stdout, result.stderr) + checks += 1 + return result.stdout + + +def run(path, *args, **kwargs): + target = ('--manifest', path) if Path(path).suffix == '.toml' else (path,) + result = json.loads(cli('run', '--fuel', '2000000', *args, *target, **kwargs)) + assert result['status'] == 'returned', result + return result + + +def crc32c(data): + crc = 0xffffffff + for byte in data: + crc ^= byte + for _ in range(8): + crc = (crc >> 1) ^ (0x82f63b78 if crc & 1 else 0) + return crc ^ 0xffffffff + + +def record_bytes(payload, offset): + return struct.pack(' u64 effects [] { + match result { + examples.append_log.AppendResult::ok(offset) => { offset }, + examples.append_log.AppendResult::too_large => { trap; } + examples.append_log.AppendResult::offset_overflow => { trap; } + examples.append_log.AppendResult::io_failed(error) => { trap; } + examples.append_log.AppendResult::poisoned => { trap; } + } + } + ''' + entry.write_text(prefix + success + '''fn main(out: cap) -> u64 effects [fs.write] { + let file = fs.create(out, b"/out/log") or trap; + let log = examples.append_log.Log { file: move file, offset: 0u64, failed: false }; + assert(good(examples.append_log.append(mut log, b"aji")) == 0u64); + assert(good(examples.append_log.append(mut log, b"ok")) == 19u64); + var empty: [u8; 1] = zero; + assert(good(examples.append_log.append(mut log, ref empty[0usize..0usize])) == 37u64); + let (file, end, failed) = struct.unpack(move log); + fs.close(move file) or trap; + assert(not failed); + end + }''') + result = run(manifest, '--grant', 'out=fs.write:/out') + assert result['value'] == 53, result + wire = base64.b64decode(result['files']['/out/log']['data']) + assert wire == record_bytes(b'aji', 0) + record_bytes(b'ok', 19) + record_bytes(b'', 37), wire + + entry.write_text(prefix + '''fn main(out: cap) -> u64 effects [fs.write] { + let file = fs.create(out, b"/out/log") or trap; + let log = examples.append_log.Log { file: move file, offset: 18446744073709551600u64, failed: false }; + var empty: [u8; 1] = zero; + match examples.append_log.append(mut log, ref empty[0usize..0usize]) { + examples.append_log.AppendResult::offset_overflow => {} + examples.append_log.AppendResult::ok(offset) => { trap; } + examples.append_log.AppendResult::too_large => { trap; } + examples.append_log.AppendResult::io_failed(error) => { trap; } + examples.append_log.AppendResult::poisoned => { trap; } + } + let (file, end, failed) = struct.unpack(move log); + fs.close(move file) or trap; + assert(end == 18446744073709551600u64 and not failed); + 42u64 + }''') + result = run(manifest, '--grant', 'out=fs.write:/out') + assert result['value'] == 42 and result['files']['/out/log']['data'] == '', result + + # A host file-size limit permits a header and one payload byte, then + # fails. Poisoning blocks a second write while preserving explicit close. + output = root / 'partial.log' + entry.write_text(prefix + '''fn main(out: cap, input: cap, status: cap) -> u64 effects [fs.write, io.read, io.write] { + let file = fs.create(out, b"''' + str(output) + '''") or trap; + let log = examples.append_log.Log { file: move file, offset: 0u64, failed: false }; + match examples.append_log.append(mut log, b"aji") { + examples.append_log.AppendResult::io_failed(error) => {} + examples.append_log.AppendResult::ok(offset) => { trap; } + examples.append_log.AppendResult::too_large => { trap; } + examples.append_log.AppendResult::offset_overflow => { trap; } + examples.append_log.AppendResult::poisoned => { trap; } + } + io.stdout_write(status, b"X") or trap; + var gate: [u8; 1] = zero; + let n = io.stdin_read(input, mut gate) or trap; + assert(n == 1usize); + match examples.append_log.append(mut log, b"retry") { + examples.append_log.AppendResult::poisoned => {} + examples.append_log.AppendResult::ok(offset) => { trap; } + examples.append_log.AppendResult::too_large => { trap; } + examples.append_log.AppendResult::offset_overflow => { trap; } + examples.append_log.AppendResult::io_failed(error) => { trap; } + } + let (file, end, failed) = struct.unpack(move log); + fs.close(move file) or trap; + assert(end == 0u64 and failed); + io.stdout_write(status, b"ok") or trap; + 42u64 + }''') + + def limited_file(): + signal.signal(signal.SIGXFSZ, signal.SIG_IGN) + resource.setrlimit(resource.RLIMIT_FSIZE, (17, 1048576)) + + command = [str(AJI), 'run', '--fuel', '2000000', '--manifest', str(manifest), + '--grant', f'out=fs.write:{root}', '--grant', 'input=io.read', + '--grant', 'status=io.write', '--profile', 'hosted'] + with subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, preexec_fn=limited_file) as process: + assert process.stdout.read(1) == b'X' + # A repeated write would now succeed: failure-state checking, rather + # than the old quota, must stop any additional bytes from being sent. + if hasattr(resource, 'prlimit'): + resource.prlimit(process.pid, resource.RLIMIT_FSIZE, (1048576, 1048576)) + else: + print('partial-write retry checked without quota restoration on this platform') + output_bytes, errors = process.communicate(b'Y') + assert process.returncode == 0 and output_bytes == b'ok', (process.returncode, output_bytes, errors) + checks += 1 + assert output.read_bytes() == record_bytes(b'aji', 0)[:17] + +print(f'examples passed ({checks} CLI checks; {len(expected)} standalone examples; 2 packages; {seeds} schedule seeds)')