examples: complete source ports and run the corpus in CI
This commit is contained in:
1 parent
b1629a59fd
commit
184cb7b321
11 files changed
+491
-91
No files matched your search
@@ -26,6 +26,7 @@ jobs:
|
|||||||
- run: python3 tests/hosted/source_format.py
|
- run: python3 tests/hosted/source_format.py
|
||||||
- run: python3 tests/hosted/source_diagnostic_reasons.py
|
- run: python3 tests/hosted/source_diagnostic_reasons.py
|
||||||
- run: python3 tests/hosted/related_locations.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_static_functions.py
|
||||||
- run: python3 tests/hosted/source_linear.py
|
- run: python3 tests/hosted/source_linear.py
|
||||||
- run: python3 tests/hosted/source_buffers.py
|
- run: python3 tests/hosted/source_buffers.py
|
||||||
|
|||||||
@@ -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_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/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/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_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_linear.py # whole-value owners, canonical AIR and CLI errors
|
||||||
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
|
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
|
||||||
|
|||||||
@@ -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-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-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-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-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 |
|
| 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.
|
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.
|
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`.
|
||||||
@@ -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`.
|
||||||
+100
-36
@@ -1,52 +1,116 @@
|
|||||||
module examples.append_log;
|
// Run: aji run --fuel 100000 --grant fs_write=fs.write:/out examples/append_log.aji
|
||||||
|
module examples.append_log
|
||||||
const HEADER_SIZE: usize = 16;
|
import std.bytes;
|
||||||
|
import std.hash;
|
||||||
|
import std.math;
|
||||||
|
|
||||||
struct Header {
|
struct Header {
|
||||||
len: u32,
|
length: u32,
|
||||||
crc: u32,
|
crc: u32,
|
||||||
sequence: u64,
|
offset: u64
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Log {
|
struct Log {
|
||||||
file: File,
|
file: file<write>,
|
||||||
offset: u64,
|
offset: u64,
|
||||||
|
failed: bool
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_header(header: ref<Header>) -> [u8; HEADER_SIZE]
|
enum AppendResult {
|
||||||
effects []
|
ok(u64),
|
||||||
{
|
too_large,
|
||||||
var out = [0u8; HEADER_SIZE];
|
offset_overflow,
|
||||||
bytes.put_u32_le(mut out, 0, header.len);
|
poisoned,
|
||||||
bytes.put_u32_le(mut out, 4, header.crc);
|
io_failed(io_error)
|
||||||
bytes.put_u64_le(mut out, 8, header.sequence);
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn append(
|
fn encoded(result: std.bytes.WriteResult) -> void effects [] {
|
||||||
log: mut<Log>,
|
match result {
|
||||||
data: slice<u8>
|
std.bytes.WriteResult::ok => {}
|
||||||
) -> Result<u64, AppendError>
|
std.bytes.WriteResult::short_output => {
|
||||||
requires {
|
trap;
|
||||||
len(data) <= 16 MiB
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
effects [fs.write]
|
|
||||||
{
|
|
||||||
let crc = crc32c(data);
|
|
||||||
let len32 = checked_cast<u32>(len(data))?;
|
|
||||||
|
|
||||||
let header = Header {
|
fn encode_header(header: ref<Header>) -> [u8; 16] effects [] {
|
||||||
len: len32,
|
var out: [u8; 16] = zero;
|
||||||
crc: crc,
|
encoded(std.bytes.write_u32_le(mut out[0usize..4usize], header.length));
|
||||||
sequence: log.offset,
|
encoded(std.bytes.write_u32_le(mut out[4usize..8usize], header.crc));
|
||||||
};
|
encoded(std.bytes.write_u64_le(mut out[8usize..16usize], header.offset));
|
||||||
let encoded = encode_header(ref header);
|
out
|
||||||
|
}
|
||||||
fs.write_all(ref log.file, slice.of(encoded))?;
|
|
||||||
fs.write_all(ref log.file, data)?;
|
|
||||||
|
|
||||||
|
fn append(log: mut<Log>, data: slice<u8>) -> 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;
|
let old = log.offset;
|
||||||
log.offset = checked_add(log.offset, HEADER_SIZE + len(data))?;
|
let next = match std.math.checked_add_u64(old, 16u64 + data.len as! u64) {
|
||||||
|
std.math.U64Result::ok(value) => {
|
||||||
return Ok(old);
|
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<fs.write>) -> 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
|
||||||
}
|
}
|
||||||
+58
-17
@@ -1,25 +1,66 @@
|
|||||||
module examples.atomic_publish;
|
// Run: aji run --fuel 100000 examples/atomic_publish.aji
|
||||||
|
module examples.atomic_publish
|
||||||
|
|
||||||
struct Shared {
|
struct Shared {
|
||||||
ready: AtomicBool,
|
ready: atomic<bool>,
|
||||||
value: AtomicU64,
|
value: atomic<u64>
|
||||||
}
|
}
|
||||||
|
|
||||||
fn publish(shared: ref<Shared>, value: u64) -> void
|
enum ReadResult {
|
||||||
effects [atomic]
|
some(u64),
|
||||||
{
|
none
|
||||||
atomic.store(ref shared.value, value, relaxed);
|
|
||||||
atomic.store(ref shared.ready, true, release);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_read(shared: ref<Shared>) -> Option<u64>
|
fn publish(shared: ref<Shared>, value: u64) -> void effects [atomic, atomic.weak] {
|
||||||
effects [atomic]
|
ref data = shared.value;
|
||||||
{
|
ref ready = shared.ready;
|
||||||
if atomic.load(ref shared.ready, acquire) {
|
atomic.store(data, value, relaxed);
|
||||||
// The acquire observes the release on `ready`; the earlier relaxed
|
atomic.store(ready, true, release);
|
||||||
// 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 try_read(shared: ref<Shared>) -> 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
|
||||||
}
|
}
|
||||||
@@ -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 {
|
struct Message {
|
||||||
id: u64,
|
id: u64
|
||||||
}
|
}
|
||||||
|
|
||||||
fn producer(
|
fn producer(tx: sender<island<Message>>, heap: cap<mem.alloc>) -> void effects [mem.alloc, task.wait] {
|
||||||
tx: ref<Sender<Island<Message>>>,
|
let message = island.create(Message { id: 0u64 }, heap) or trap;
|
||||||
alloc: cap<mem.alloc>
|
{
|
||||||
) -> Result<void, ChannelError>
|
mut graph = message;
|
||||||
effects [mem.alloc]
|
let address = island.root(graph);
|
||||||
{
|
mut root = island.at(graph, address);
|
||||||
var message = island.create(alloc, Message { id: 0 })?;
|
root.id = 42u64;
|
||||||
|
}
|
||||||
borrow message as mut root {
|
match channel.send(tx, move message) {
|
||||||
root.id = 42;
|
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<mem.alloc>) -> u64 effects [mem.alloc, task.spawn, task.wait] {
|
||||||
|
match channel.make<island<Message>>(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();
|
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hello"
|
name = "hello"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
entry = "main.air"
|
entry = "main.aji"
|
||||||
|
|
||||||
[capabilities]
|
[capabilities]
|
||||||
out = "io.write"
|
out = "io.write"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module examples.hello
|
||||||
|
|
||||||
|
fn main(out: cap<io.write>) -> void effects [io.write] {
|
||||||
|
io.stdout_write(out, b"hello, aji\n") or trap;
|
||||||
|
}
|
||||||
+24
-19
@@ -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<u64>) -> void
|
fn square_half(values: slice_mut<u64>) -> void effects [] {
|
||||||
effects []
|
for i in 0usize..values.len {
|
||||||
{
|
|
||||||
for i in 0..len(values) {
|
|
||||||
values[i] = values[i] * values[i];
|
values[i] = values[i] * values[i];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn square_all(values: slice_mut<u64>) -> Result<void, TaskError>
|
fn square_all(values: slice_mut<u64>) -> void effects [task.spawn, task.wait] {
|
||||||
effects [task.spawn]
|
let (left, right) = values.split_at(values.len / 2usize);
|
||||||
{
|
scope s {
|
||||||
let mid = len(values) / 2;
|
let a = task.spawn(s, square_half, left);
|
||||||
let (left, right) = slice.split_mut(values, mid);
|
let b = task.spawn(s, square_half, right);
|
||||||
|
task.join(move a);
|
||||||
task.scope s {
|
task.join(move b);
|
||||||
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)?;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
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
|
||||||
}
|
}
|
||||||
@@ -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('<IIQ', len(payload), crc32c(payload), offset) + payload
|
||||||
|
|
||||||
|
|
||||||
|
assert crc32c(b'123456789') == 0xe3069283
|
||||||
|
expected = {
|
||||||
|
'hello.aji': None, 'file_copy.aji': None, 'append_log.aji': 19,
|
||||||
|
'parallel_map.aji': 204, 'channel_transfer.aji': 42, 'atomic_publish.aji': 42,
|
||||||
|
'std/bounded.aji': 10, 'std/buffered_io.aji': 8, 'std/bytes.aji': 42,
|
||||||
|
'std/deque.aji': 42, 'std/endian.aji': 0x12345678, 'std/format.aji': 17,
|
||||||
|
'std/generics.aji': 42, 'std/hash.aji': 42, 'std/hashmap.aji': 42,
|
||||||
|
'std/hashset.aji': 42, 'std/heap.aji': 42, 'std/io.aji': 8,
|
||||||
|
'std/map.aji': 42, 'std/owning-option.aji': 42, 'std/path.aji': 42,
|
||||||
|
'std/static_functions.aji': 42, 'std/text.aji': 0x20ac, 'std/vector.aji': 42,
|
||||||
|
}
|
||||||
|
flags = {
|
||||||
|
'hello.aji': ['--grant', 'stdout=io.write'],
|
||||||
|
'file_copy.aji': ['--grant', 'fs_read=fs.read:/in', '--grant', 'fs_write=fs.write:/out',
|
||||||
|
'--vfs', '/in/data.txt=some text'],
|
||||||
|
'append_log.aji': ['--grant', 'fs_write=fs.write:/out', '--vfs', '/out/log.bin=old'],
|
||||||
|
'channel_transfer.aji': ['--grant', 'heap=mem.alloc:256'],
|
||||||
|
}
|
||||||
|
for name in ('deque', 'hashmap', 'hashset', 'heap', 'map', 'owning-option', 'vector', 'buffered_io'):
|
||||||
|
flags[f'std/{name}.aji'] = ['--grant', 'heap=mem.alloc:4096']
|
||||||
|
for name in ('io', 'buffered_io'):
|
||||||
|
flags.setdefault(f'std/{name}.aji', []).extend(
|
||||||
|
['--grant', 'src=fs.read:/in', '--grant', 'dst=fs.write:/out', '--vfs', '/in/data=abcdefgh'])
|
||||||
|
|
||||||
|
# Every standalone example must have an explicit expected value and world.
|
||||||
|
# The module example is linked by its explicit manifest below.
|
||||||
|
standalone = {str(p.relative_to(REPO / 'examples')) for p in (REPO / 'examples').rglob('*.aji')
|
||||||
|
if 'modules' not in p.parts and 'packages' not in p.parts}
|
||||||
|
assert standalone == set(expected), (standalone - set(expected), set(expected) - standalone)
|
||||||
|
packaged = {'modules/main.aji', 'modules/model.aji', 'packages/hello/main.aji'}
|
||||||
|
discovered = {str(p.relative_to(REPO / 'examples')) for p in (REPO / 'examples').rglob('*.aji')}
|
||||||
|
assert discovered == set(expected) | packaged, discovered ^ (set(expected) | packaged)
|
||||||
|
for name, value in expected.items():
|
||||||
|
path = REPO / 'examples' / name
|
||||||
|
cli('check', path)
|
||||||
|
result = run(path, *flags.get(name, []))
|
||||||
|
assert result['value'] == value, (name, result)
|
||||||
|
if name == 'hello.aji':
|
||||||
|
assert result['stdout'] == 'hello from aji\n', result
|
||||||
|
if name in ('file_copy.aji', 'std/io.aji', 'std/buffered_io.aji', 'append_log.aji'):
|
||||||
|
key, data = ('/out/copy.txt', b'some text') if name == 'file_copy.aji' else (
|
||||||
|
('/out/log.bin', record_bytes(b'aji', 0)) if name == 'append_log.aji' else
|
||||||
|
('/out/data', b'abcdefgh'))
|
||||||
|
assert base64.b64decode(result['files'][key]['data']) == data, (name, result)
|
||||||
|
|
||||||
|
for name, value in (('modules', 42), ('packages/hello', None)):
|
||||||
|
manifest = REPO / 'examples' / name / 'aji.toml'
|
||||||
|
cli('check', '--manifest', manifest)
|
||||||
|
result = run(manifest)
|
||||||
|
assert result['value'] == value, result
|
||||||
|
if name == 'packages/hello':
|
||||||
|
assert result['stdout'] == 'hello, aji\n', result
|
||||||
|
twin = run(manifest.parent / 'main.air', '--grant', 'out=io.write')
|
||||||
|
assert result == twin, (result, twin)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory(prefix='aji-examples-') as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
# The changed concurrent examples retain explicit ownership and memory
|
||||||
|
# ordering under source/AIR execution and independent scheduler choices.
|
||||||
|
for name in ('parallel_map.aji', 'channel_transfer.aji', 'atomic_publish.aji'):
|
||||||
|
source = REPO / 'examples' / name
|
||||||
|
air = root / 'program.air'
|
||||||
|
canonical = cli('lower', source)
|
||||||
|
assert cli('lower', source) == canonical
|
||||||
|
air.write_text(canonical)
|
||||||
|
for quantum in (1, 7, 64):
|
||||||
|
for seed in range(seeds):
|
||||||
|
args = [*flags.get(name, []), '--quantum', quantum, '--schedule-seed', seed]
|
||||||
|
actual = run(source, *args)
|
||||||
|
assert actual['value'] == expected[name], actual
|
||||||
|
assert run(air, *args) == actual, (name, quantum, seed)
|
||||||
|
|
||||||
|
# Import the actual example functions, without copied implementations.
|
||||||
|
(root / 'log.aji').write_text((REPO / 'examples/append_log.aji').read_text())
|
||||||
|
manifest = root / 'aji.toml'
|
||||||
|
manifest.write_text('[package]\nname="log-tests"\nversion="1"\nentry="main.aji"\n'
|
||||||
|
'[modules]\nexamples.append_log="log.aji"\n')
|
||||||
|
entry = root / 'main.aji'
|
||||||
|
prefix = 'module test.log\nimport examples.append_log;\n'
|
||||||
|
success = '''fn good(result: examples.append_log.AppendResult) -> 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<fs.write>) -> 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<fs.write>) -> 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<fs.write>, input: cap<io.read>, status: cap<io.write>) -> 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)')
|
||||||
Reference in new issue
Block a user