Files

158 lines
20 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Design Decisions
This file records short decisions whose rationale does not yet justify a standalone RFC.
## DD-001 — Checked arithmetic by default
Normal integer arithmetic traps on overflow. Wrapping/saturating arithmetic is explicit.
Reason: release/debug behavior must not diverge, and arithmetic assumptions should remain visible to agents/verifier.
## DD-002 — No exceptions
Errors are values. No stack unwinding.
Reason: explicit CFG and resource cleanup are easier to verify and replay.
## DD-003 — No hidden destructors
Cleanup constructs lower to explicit AIR edges.
Reason: hidden control flow harms auditability and agent repair.
## DD-004 — Bounded channels by default
Unbounded queues require explicit library choice.
Reason: memory growth must not be implicit.
## DD-005 — No default atomic ordering
Every atomic operation states its order.
Reason: the compiler must not hide one of the most consequential concurrency choices.
## DD-006 — No arbitrary safe atomic pointer type initially
Reason: reclamation cannot be separated from safe publication.
## DD-007 — Interpreter before optimizer/backend
Reason: executable semantics and verifier behavior must stabilize before native-code complexity is introduced.
## DD-008 — Reference implementation pins one exact Zig version
The toolchain version is pinned in `build.zig.zon` and `mise.toml` (currently 0.17.0) and upgraded deliberately in a dedicated change.
Reason: Zig's standard library changes between minor versions; an unpinned toolchain makes builds non-reproducible (spec 12 §2).
## DD-009 — CLI diagnostics are JSON Lines on stdout
`aji` writes one JSON diagnostic per line on stdout, human notes on stderr, and uses fixed exit codes (0 accepted or returned, 1 rejected, 2 usage/I/O, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked).
Reason: agents consume diagnostics programmatically (spec 10); mixing prose into the machine channel breaks repair loops.
## DD-010 — Conformance tests are text AIR with a metadata header
Tests live in `tests/conformance/phase<N>/{accept,reject}/` with `expect`/`phase`/`spec` header lines that the runner strips before parsing.
Reason: AIR is the conformance format (spec 07 §1), and keeping metadata out of the AIR grammar lets the grammar evolve independently of the test harness.
## DD-011 — The specification is the single normative source
RFCs are decision records. Accepting an RFC integrates its rules into `docs/spec/` in the same change; afterwards the spec is authoritative and the RFC keeps the rationale.
Reason: a permanent "accepted RFC overrides spec" rule makes old RFCs conflict with the current spec over time; one normative source keeps agents from having to reconcile layers.
## DD-012 — AIR format 0 is a frozen semantic baseline
After Phase 0, the meaning of existing format-0 constructs does not change. Later phases may only add instructions, types, features and codes under the rules of spec 07 §8.7; anything else needs `air 1` and an RFC.
Reason: a stable foundation lets generated code, tests and tools rely on format 0 indefinitely.
## DD-013 — Deterministic fuel instead of timeouts
Runs are bounded by fuel (executed AIR instructions), never by wall-clock time. Exhaustion is the outcome `limit_exceeded` (exit code 5), not a trap.
Reason: timeouts make test outcomes depend on machine speed; a trap code for exhaustion would make the test harness part of the language semantics.
## DD-014 — AIR feature negotiation
AIR format 0 uses the mandatory `features [...]` header as an explicit semantic compatibility contract. Every post-baseline AIR 0 extension belongs to a registered feature (`reference/air-features.md`). Modules MUST declare every feature they use and its dependency closure. Implementations MUST validate the feature set before validating the module body. Unknown, unsupported, undeclared, duplicated or dependency-incomplete features are reported as `E0006` with a structured `reason`. Feature semantics are immutable once published. `aji features` reports what a toolchain supports. While a feature is reserved, no valid module can use it, so its dependency set may change; on publication the dependencies freeze with its semantics (owner decision on RFC 0012).
Reason: format 0 is frozen; features make it an extensible protocol without an older implementation half-parsing a module it cannot understand. One code with a reason keeps the §8.7 exception for `E0006` intact.
## DD-015 — Maximum AIR value size
AIR format 0 defines `max_value_size` = 1 048 576 bytes. Every materializable type in a module has an accounted size (spec 08 §7.1, a platform-independent metric, not a layout) of at most this value; violation, including overflow while computing a size, is `E5101`, checked during module validation. `max_local_frame` (1 MiB per function) is a separate guarantee. Neither depends on host memory.
Reason: a verified IR needs its own deterministic validity limits instead of inheriting host behavior; and large data should live in storage reached through borrows, not travel as SSA values. Total allocation is bounded separately in Phase 2, as fuel bounds execution.
## DD-016 — Explicit block statement boundaries
Spec 15 §4 and the grammar resolve Q-040 syntactically: leading bare `if`, `match` and `{…}` finish before outer expression operations in statement/tail position. A final construct remains a tail; `;` explicitly discards its value; without either, a value-producing block statement is E7006. Parentheses opt into continuation, while explicit expression contexts retain full expression parsing.
Reason: `if true { *p = 2u64; } *p = 3u64;` must denote two statements regardless of spacing. Greedy expression parsing consumed multiplication instead. Merely splitting would silently change `{2i64} -3i64` from −1 to −3; rejecting the undiscarded value avoids that change. Neither line-sensitive syntax nor assignment lookahead is needed. This is a small grammar decision, not a new AIR facility.
Compatibility: formerly accepted bare continuations in statement/tail position require parentheses around the initial construct. Formerly accepted value-producing bare block statements require explicit `;`, including mixed branches such as `if c { return 1u64; } else { 2u64 }` before another statement. Existing tails, explicit discards and initializer/return/argument/condition/expression-arm continuations retain their meanings. Ownership, lexical borrow ends, verifier transfers and deterministic runtime rules are unchanged. A borrow bound inside a preceding block remains inaccessible afterwards (E7002); aliasing and task rules still come from the existing verifier. No new diagnostic code, source syntax form, feature or verifier/runtime state is added. One frontend statement marker enforces the value guard and gives the formatter an explicit boundary; it never changes tokens or inserts separators. No empirical Model Capability Compression benefit is claimed; source documentation growth is measured in docs/agent/README.md.
## DD-017 — Stable E7006 reasons before repair-frequency analysis
Spec 15 §10 requires a registered reason on each E7006. Frontend rejection sites select an enum category explicitly; `move_copy` excludes borrowed and non-materializable operands. ajieval groups observed codes/reasons per run and reports unknown historical reasons separately, without reading message prose. Existing code counts remain compatible; missing logs are unavailable evidence. Counts describe observed command outputs, not the true frequency of all errors.
Reason: a shared code cannot establish whether Copy moves occur often enough to justify RFC 0038. Structured categories also let an agent choose the appropriate rule without classifying prose. This small diagnostic schema extension uses a decision record and a P6-7 plan increment; no new rejection, code, source/AIR syntax, verifier/runtime state or repair application is introduced. Existing locations, payloads, interpreter records, resource/borrow invariants and frozen evaluation inputs remain intact. Enum/registry and CLI/report tests cover serialization, generic/package propagation and historical uncertainty. Bundle growth is recorded in docs/agent/README.md. RFC 0038 remains Proposed with its existing recommendation to defer pending frequency and application-usability data.
## DD-018 — Factual related positions without choosing a repair
RFC 0037's implementation/spec integration is prepared under P6-7; formal RFC status remains Proposed for owner adoption. Spec 10 §2 and spec 15 §10 define one typed related record for each identified E2101/E2104 conflict and E4302 task. Definition lookup retains the selected conflict; loan metadata retains the creating spawn even when a cancelled join replaces its SSA handle. Source mapping is independent, and an absent mapping exposes AIR coordinates without a guessed source position. Primary selection, fields and duplicate suppression are unchanged. There is no enclosing-block inference, conflict enumeration or edit.
The invariant is unchanged acceptance, ownership/loan verification and deterministic interpreter behavior; provenance never participates in liveness or transfer decisions. AIR format 0, syntax, effects/capabilities and diagnostic codes are unchanged. Positive/rejected source/AIR fixtures, repeated cancelled joins, CLI/package mapping and typed serialization tests check the contract. Bundle growth is measured in docs/agent/README.md. This improves factual repair context; no measured repair-cost or MCC claim is made, and RFC 0038 stays deferred pending evidence.
## DD-019 — Unique diagnostic fields preserve the machine envelope
Compatibility review found legacy payload collisions: unsupported AIR narrowing and unknown source capability kinds each emitted a second `kind`, and unlock with a live guard borrow emitted `borrow` twice. Ordinary JSON consumers lost the stable machine kind or one identity. Spec 10 §2 requires unique names and reserves envelope fields. Capability payloads use `capability_kind`; unlock reports the selected `borrow` and its `guard` separately, retaining the borrow seen by former last-key-wins readers. Clients must read the capability payload by its new name; stable diagnostic kinds are restored rather than redefined.
These are diagnostic corrections, not new source/AIR or ownership/concurrency rules. Existing rejection codes, positions, conflict selection, guard/loan state and deterministic execution remain unchanged; valid capabilities and guard programs remain accepted. Pipeline/CLI tests reproduce the three cases, the verifier unit helper checks payload uniqueness across its existing rejection tests, and conformance validates every final mapped diagnostic's fields and serialized JSON. The invariant is an unambiguous machine diagnostic without hidden loss of context. Budget growth is recorded in docs/agent/README.md; no repair candidate or measured MCC benefit is introduced.
## DD-020 — Source scope names are lexical identifiers
Spec 15 §7 resolves Q-041: the name introduced by `scope s` is only the named first operand of `task.spawn`, not an ordinary source value. Lowering rejects plain/moved aliases and value expressions before suggesting a transfer. Ordinary lexical shadowing remains legal; block completion retains its original SSA identity independently of source lookup. This removes an apparent ownership transfer that formerly neither consumed nor changed completion of the handle.
The invariant is one retained completion obligation per source scope, with every child joined and every loan released before completion. Existing AIR verification, including E4301/E4302 and function-local scope flow (spec 04 §33), remains authoritative and unchanged. No runtime rule, instruction, feature, syntax, verifier state or interpreter behavior changes. Shield handles and lock guards already have no source value names; task values remain ordinary linear values.
Valid: `scope s { let t = task.spawn(s, work); let s = 0u64; let n = task.join(move t); }`. Rejected: `scope s { let alias = move s; }` (E7006, existing reason `invalid_expression`, fields `name`/`type: scope`); plain aliases, yields, returns, aggregates and ordinary arguments are rejected likewise. Borrowing keeps `invalid_place`, assigning the immutable identifier keeps `invalid_assignment`, and a moved/non-scope spawn operand keeps E7005. The existing structured reason plus type identifies the category without reading prose; no additional reason is needed.
Compatibility: formerly accepted scope aliases, spawning through an alias or the apparently moved original, standalone scope names and block/scope tails now reject. Accepted shadowing, nested scope lookup, cleanup at fall-through/return/break/continue, and all AIR format-0 programs retain their meanings. Public source conformance covers accepted/rejected forms, specialized bodies and live children; CLI tests cover exact reasons/locations, packages and deterministic/hosted execution. Scheduler stress and per-instruction collection check cleanup. Source documentation growth is measured in docs/agent/README.md. The change improves explicitness and repairability without an empirical MCC claim; it does not finish P6-2.
## DD-021 — Whole-array arguments follow explicit parameter types
Q-023 is resolved in spec 15 §5: a temporary `ref`/`mut` argument preserves its array referent when the known parameter is an array borrow, including explicitly specialized calls. This is the existing small inference from one declared signature, with no overload search. It makes an already expressible parameter callable without hand-written AIR. Array bindings and slice parameters retain their slice behavior; bare byte strings retain their shorthand. Consequently, array-borrow origins and task loans require forwarding an existing array-borrow parameter; a local whole-array binding is still a slice.
Invariant: temporary children and ancestors remain live through the call, then end child first; no view escapes a temporary origin. Existing AIR type, aliasing, initialization, bounds, origin and task-loan verification remains authoritative. Runtime and deterministic interpreter rules are unchanged. Valid: `fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }` called with `first(ref data)` for a two-element array. A different length or explicit mode rejects E7005; overlapping exclusive/shared arguments reject E2101. Returning a view from an inline origin and lending an inline argument to a task retain E7006.
Compatibility: formerly rejected array-borrow calls become available; accepted source retains canonical AIR. No new syntax, AIR instruction/feature, diagnostic, verifier/runtime state, allocation or cleanup semantics. The frontend selects array versus slice using the parameter, then emits existing borrow/reborrow and end instructions. Source/AIR conformance and CLI checks cover projections, modes, specialization, packages and temporary cleanup. Source budget growth is recorded in docs/agent/README.md; AIR is unchanged. This improves explicitness and completes source access to an existing primitive without a measured MCC claim.
## DD-022 — Document ordered source parsing and canonical enum payload lists
P6-1/P6-2 synchronizes the grammar with implemented syntax: graph/atomic wrappers, binary literals, signed integer patterns, parenthesized places, declared borrow-return calls and existing list/arm punctuation. Contextual words and the ordered choices for statements, body-opening braces and typed built-ins are explicit. The grammar is not claimed to be LL(k). Existing grouping and optional list delimiters introduce no operation; formatter token preservation remains mandatory.
Q-050 corrects empty parentheses on qualified enum variants, contrary to spec 15 §5–§6. Construction and pattern parsing reject E7001 at the opening parenthesis without symbol lookup, including generic, qualified and built-in variants. Payload-bearing variants with empty lists change from E7005 to E7001; non-empty arity/type checks remain. Bare variants, ordinary zero-argument calls and empty outcome bindings retain their meanings. No AIR, verifier, runtime, ownership/concurrency, feature or code changes; accepted public-source canonical AIR is preserved. Source grammar/CLI tests cover both sides and formatting. Bundle growth is recorded in docs/agent/README.md. Future grammar features still require their RFCs; P6-1 remains open. Q-051 separately records unknown ordinary-function effects.
## DD-023 — Unknown source effects are name errors
Q-051 validates ordinary effect names before body lowering using the existing closed registry. Templates/static contracts use the same E7002 with `name` and `effect`; legacy E0006 without a feature reason was incorrect. Function/template positions remain declaration starts, static contracts use their parameter start. Ordinary parameter/return/from checks retain priority; existing template/header ordering remains. Unknown effects cannot generate malformed AIR or E7900. AIR E0004 and its registry contract are unchanged.
Only invalid-source codes/priority/fields change. Registered effects, explicit authority, effect coverage, duplicate-list set semantics and static-contract uniqueness remain unchanged; no code, reason, syntax, AIR feature, verifier/runtime or ownership/concurrency state is added. Positive/rejected source tests and CLI/package tests cover headers, unused declarations, priority, missing-effect/capability diagnostics, formatting and source/AIR execution. Budget growth is measured in docs/agent/README.md. This completes this diagnostic correction, not P6-2 or an empirical MCC claim.
## DD-024 — Resource obligations survive SSA handoff
Q-052 corrects the verifier's loss of task loans/scopes, guard parents and shield order at block parameters. The preserved invariants are no ending or conflicting access to a loan before its task is joined, no live child at scope completion, no ending a mutex borrow while its guard lives, and properly nested shields. Spec 04 clarifies the already permitted function-local transfer; no AIR feature or new semantic restriction is introduced.
The verifier records static definition/consumption events, solves sparse relations over the CFG to a fixed point, then checks instructions in the existing diagnostic order. Edge transfer renames both positions simultaneously: a scope association follows the scope even if its task is not passed. This preserves correlated permutations of scopes and tasks; independent origin sets would reject valid code. Task/loan/guard alternatives join by union, while the existing shield-stack equality rule is checked separately. Definition sites retain diagnostic spawn positions. The collecting walk excludes relational error recovery; extra facts about subsequently rejected/dead resources are filtered by final liveness. Functions without these resource types retain one walk.
Valid: forward a task and its scope, join the renamed task, then end the renamed scope; end renamed shields inner first; unlock a renamed guard before ending its mutex borrow. Rejected: end the lent borrow or store through its exclusive loan before joining the forwarded task; end a forwarded scope with a live child; end the guard's parent borrow; end the outer forwarded shield first. Source/AIR conformance fixtures cover these cases, cancelled joins, joins with different loan origins, loops and correlated scope/task permutations.
Diagnostic impact: the existing E4302/E4101/E4301/E2102/E4305/E3002 rules now apply after handoff. A transferred live child reports E4301 in preference to E3002. E4302 identifies the current handle and the original spawn. Incompatible shield stacks report E3002 with a shield identity; a subsequent wrong end can also report E4305. New codes, reasons and repairs are unnecessary.
Runtime and deterministic interpreter behavior are unchanged: transfer already moves the same resource, and a cancelled join already returns the same task. Compatibility changes only for violations formerly accepted, or reported with a generic leak after provenance was lost; valid lowering remains unchanged. Counted rotation tests bound fixed-point visits, scheduler/collection tests cover execution, and CLI tests cover exact source/package/generic positions and canonical AIR. Bundle growth is recorded in docs/agent/README.md. This strengthens verification without claiming an empirical MCC improvement or completing P6-7.