diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index e045089..11b01f5 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -399,8 +399,18 @@ P6-6 requires contracts and their four audit statuses, but spec 13 §1/spec 08 [RFC 0039](../rfcs/0039-verifier-visible-contracts.md) is a Draft spec gate covering requires/ensures and preserving the unresolved type/module invariant work. Decide complete rules before implementation; function-boundary checks alone do not establish value invariants, and source 0.1 has no module-state/visibility declaration surface. No semantic policy, feature or code is introduced by this entry. +2026-10-09: the candidate function representation now uses a leading `contract.pre/old/post` prefix; all three isolated spellings currently reject E0004, avoiding Q-055's header-specific E0001 conflict. The used-result probe additionally reports E5001; complete rejection-code compatibility remains to be audited. Deferred post bindings require ordinary access checks at every return. Verified Range probes distinguish a repaired exclusive update from an invalid Copy escape and shared-reader overflow; exclusive-borrow end alone cannot establish publication coverage. Type/module invariant representation and predicate purity remain unresolved; no implementation is authorized. + ## Q-055 — Feature-gated AIR headers and frozen rejection codes Spec 07 §8.7 permits changes to earlier E0004/E0006 rejections, not E0001. Source inspection of the parser before commit `0086549` shows that an unfeatured `trusted "..."` header was parsed as a block label and failed while expecting `:`; current spec 13 §6.3 and the parser require E0006 `feature_not_declared`. RFC 0009 calls the header additive, although this diagnostic transition is outside the literal exception. The historical parser has not been executed in this audit. Resolve this compatibility policy before using `trusted` as a precedent for new contract headers (Q-054). Preserving legacy E0001 parsing conflicts with §8.1's E0006 for an undeclared construct; replacing E0001 conflicts with §8.7. Instructions whose old rejection is E0004 or a new AIR version avoid this header conflict. Amending either rule is an owner decision, not implied by the implementation. No existing parser, diagnostic or stability rule changes here; other historical syntax extensions remain unaudited. + +The opcode candidate needs a separate dependent-error audit: at `94414da`, `%old = contract.old @snapshot(%x)` followed by `add.checked.u64 %old, %x` reports both E0004 for the unknown opcode and E5001 for its undefined result. This body-use shape remains invalid under the candidate's contract-only snapshot rule; audit its rejection-code transition, not its acceptance. A snapshot used only by `contract.post` currently reports two E0004s without E5001. Establish how §8.7's named-opcode exception applies to combined rejections before claiming the entire extension compatible. An unrelated invalid SSA use must not be accepted merely because the same module also contains a new opcode. + +## Q-056 — Source zeroability versus AIR zeroability + +Spec 15 §4 calls `var x: T = zero` a lowering to `local.zero` for zeroable types, without naming a narrower source set. Spec 07a's `local.zero` includes structs whose fields are zeroable. At `94414da`, source `var range: Range = zero` with two u64 fields rejects E7006 `zero_not_zeroable`; AIR `local.alloc @Range` followed by `local.zero` accepts and runs. `src/frontend/lower.zig` restricts source zeroability to integers, bool and arrays of those types. + +Decide whether source intentionally exposes that narrower set (and make spec 15 precise), or whether the missing structural lowering is an implementation gap. This entry changes neither layer. P6-6 invariant coverage must independently include the existing AIR construction path, regardless of the source decision. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 54c63ad..236dc94 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -335,3 +335,5 @@ Spec 15's initial Phase 6A limits now point to its existing extensions. Its intr ## P6-6 contract spec gate (2026-10-09) Q-054/RFC 0039 Draft identifies the missing executable contract model. Public probes at `94414da` demonstrate identical audit reports for mandatory/bypassable assertions, effects-empty mutation and ambient task.cancelled observation, E3001 after consuming an observed owner, and E0001 versus E0006 for candidate unfeatured/featured AIR headers. All runs use fuel 10,000. Claude independently audited the architecture and compatibility constraints. Predicate rules, old/result lifetime, coverage, statuses and type/module invariant boundaries need concrete normative rules before implementation; function contracts alone do not complete P6-6. Q-055 records the historical header-compatibility question from source inspection, without claiming an executed old-parser result. No compiler, semantic rule, registry, conformance fixture or normative bundle changes. + +The next design increment prefers leading `contract.pre/old/post` operations, isolated uses currently E0004, with no entry predecessors, contract-only snapshots and per-return access checks. The candidate specifies pending-return dispatch, ordinary fuel/quantum accounting and temporary observations without resurrecting consumed values. Current ordinary observations before returning an owner accept and preserve 42; observing its old binding after a call transfer rejects E2001. Verified invariant probes return width 10 after a repaired exclusive update, expose an invalid mid-update Copy and trap T0003 in a shared reader. Source struct-zero rejects E7006, while AIR struct-zero accepts; Q-056 records that separate surface question. Claude independently reviewed the candidate and identified dispatch/availability clarifications. A body use of an unknown snapshot additionally yields E5001; use only by a post yields E0004s alone. Q-055 retains the invalid body-use rejection-code audit. All twelve targeted probes match their reported results, and local documentation links/diff checks pass. These are current-language probes of design obligations, not conformance tests for an implemented contract feature. Type/module boundaries, predicate closure and status rules remain open; Draft status and the full P6-6 exit criterion are unchanged. diff --git a/docs/rfcs/0039-verifier-visible-contracts.md b/docs/rfcs/0039-verifier-visible-contracts.md index 21eb7e1..13c9845 100644 --- a/docs/rfcs/0039-verifier-visible-contracts.md +++ b/docs/rfcs/0039-verifier-visible-contracts.md @@ -29,9 +29,9 @@ fn main() -> u64 effects [] { return positive(0u64); } After the same `module` header, both accepted variants produce identical `aji report` JSON. With fuel 10,000, A traps T0002 and B returns zero. A check count cannot establish mandatory coverage. -An `effects []` function taking `mut` can write through it and return 42; calling it inside `assert` is accepted. Even a no-parameter effects-empty function can call `task.cancelled()` and observe ambient state. Empty effects or parameter restrictions alone do not establish observational purity. Borrowing an owner after `own.take(move owner)` rejects E3001; a postcondition cannot resurrect that owner. +An `effects []` function taking `mut` can write through it and return 42; calling it inside `assert` is accepted. Even a no-parameter effects-empty function can call `task.cancelled()` and observe ambient state. Empty effects or parameter restrictions alone do not establish observational purity. Borrowing an owner after `own.take(move owner)` rejects E3001; a postcondition cannot resurrect that owner. Conversely, an ordinary shared observation in a nested block before returning `move owner` is accepted; a caller taking the returned owner gets 42. Availability must be checked at the boundary, not banned solely because a parameter is linear. -A candidate AIR `requires @predicate(%x)` header without a new feature rejects E0001 today; declaring unknown feature `contracts` instead rejects E0006 first. This difference matters to format-0 compatibility. +A candidate AIR `requires @predicate(%x)` header without a new feature rejects E0001 today; declaring unknown feature `contracts` instead rejects E0006 first. In contrast, each proposed `contract.pre`, `contract.old` and `contract.post` operation rejects E0004. A snapshot used by a post reports only E0004 for those two operations. Using the unknown `%old` result in an ordinary body instruction additionally reports E5001; the candidate also rejects that snapshot escape. The prefix is an opcode-extension candidate; these probes do not yet prove complete format-0 compatibility. The intended gains are verifier strength, explicit guarantees and truthful machine-readable audit status. No empirical agent-capability improvement is established. @@ -45,19 +45,43 @@ Preconditions cover every invocation, including entry instantiation, recursion a The candidate source spelling is `requires { condition; }` and `ensures { condition; }`, after `effects [...]` and before the body. This retains blocks but deliberately moves the clauses and adds terminators compared with spec 13's illustrative example. Each condition is bool. These words are contextual in headers; `result` and `old(expression)` have meaning only in postconditions. Exact grammar and collision rules still need integration in spec 15. -Safe contracts are enforced, and profiles may reject statuses without disabling checks. Predicate evaluation is read-only, with no heap/region allocation, authority use, ambient-state observation, synchronization, unsafe operation or ownership transfer; callees must satisfy the same restriction. This requires an opcode/call-closure rule in addition to `effects []`: effect-free `arc.clone`, endpoint duplication and `task.cancel` can change state, while `task.cancelled` has no parameter to restrict. The readable types and projection rules remain a gate decision. +Safe contracts are enforced, and profiles may reject statuses without disabling checks. Predicates cannot write caller-visible storage, allocate heap/region storage, use authority, observe ambient state, synchronize, execute unsafe operations or transfer caller ownership. Callees must satisfy the same restriction. This requires an opcode/call-closure rule in addition to `effects []`: effect-free `arc.clone`, endpoint duplication and `task.cancel` can change state, while `task.cancelled` has no parameter to restrict. + +The candidate allows arithmetic, Copy aggregate construction, control flow, ordinary trapping checks, read-only data projections and mutation of fresh predicate-frame storage. It excludes all task/atomic/mutex/channel operations, authority intrinsics and ownership duplication/release. An effects-empty callee with a `mut` parameter still needs a proof that its writes target only fresh predicate storage; its signature alone is insufficient. The exact allowed opcodes, readable types, write-root propagation and recursive call-closure algorithm remain gate decisions. Contract operations inside the predicate closure are initially excluded to avoid recursive contract dispatch; that restriction still needs a complete rule for type-invariant evaluation. `old(expression)` captures a Copy observation after preconditions and before the body. Snapshots belong to the activation, use bounded frame storage, and do not retain borrows or copy an ownership graph. Postconditions may observe the actual result. Referencing a consumed input is rejected; taking an old scalar observation does not make the input available again. A returned exclusive view must not permit a postcondition to bypass its parent's alias restrictions. ## AIR, verifier and runtime candidate -Prefer feature-gated contract descriptors associated with function declarations and independently checked typed predicate bodies. The interpreter enforces preconditions at invocation and postconditions at normal return, so omitting an inline check cannot bypass a descriptor. Source lowering supplies the same descriptors, including generic/package specializations; the verifier checks their types, bindings and predicate restrictions without trusting the frontend. +Prefer a feature-gated entry prefix over new function headers. The following spellings are candidates, not registered instructions: -This adds semantic declaration constructs rather than an opcode solely for syntax sugar. Descriptor binding, snapshot production, return-value observation and execution order need a complete AIR grammar and transfer contract before publication. No existing instruction changes meaning. +```text +entry: + contract.pre @positive(%x) + %old = contract.old @snapshot(%x) + contract.post @unchanged(%old, result) + ... ordinary body ... +``` -Predicate instructions consume ordinary fuel and quantum steps. False pre/post conditions need distinct stable traps; a predicate's own arithmetic/bounds trap retains its code. Snapshot/dispatch charging and cancellation ordering still need exact rules. Both runtime profiles execute the same contracts; policy may reject statuses but must not silently disable checks. +Only contracted functions gain these rules. Their entry block MUST have no predecessors. The contract operations MUST be its leading, uninterrupted prefix, ordered `pre*`, at most one `old`, then `post*`. A conditionally installed or later contract operation rejects. Existing functions may still branch to entry under existing rules. Constants and projections are computed inside helpers; ordinary instructions MUST NOT precede or interrupt the prefix. -The verifier must check contract access at the relevant boundary, including task loans, returned views and cleanup. A function-entry proof cannot stand in for a return-state proof. Limits on descriptor count, predicate traversal and total snapshot frame size must be explicit and tested with counted cases. +| Candidate operation | Types and result | Verifier transfer | Runtime rule | +|---|---|---|---| +| `contract.pre @p(bindings)` | typed observations → `bool`; no SSA result | validate pure helper and an ordinary observation/call at entry | invoke now; false traps at this clause | +| `%old = contract.old @s(bindings)` | typed observations → bounded Copy record without borrows/authority | validate entry access; produce a contract-only snapshot | invoke once after all preconditions; retain result in this activation | +| `contract.post @q(bindings)` | typed observations → `bool`; no SSA result | register ordered obligation; check its virtual observation/call at every normal `ret` | install now; invoke before each normal return transfers its result; false traps at this clause | + +Bindings identify function parameters, the prior snapshot, or the post-only placeholder `result`. They do not capture an entry-time borrow for later reuse. Copy data may bind by value; candidate `ref %parameter`/`ref result` bindings request a temporary shared view at evaluation time. Existing `borrow.ref` shapes apply: `mut` becomes `ref`, `slice_mut` becomes `slice`, owners expose their content, and exclusive results may be shared-reborrowed. Authority and other types excluded by the eventual purity rule cannot bind merely because they are Copy. A void return has no `result`; postconditions on a `never` return are rejected rather than reported as evaluated. + +Post installation reads no resource and takes no loan. At each `ret`, the verifier checks the bindings as a virtual ordinary predicate call in the final body state, before return transfer. A still-available owner being returned may be observed without consuming it. A consumed owner remains unavailable (the current owner case gives E3001); a moved binding remains unavailable under E2001. An owner moved through another call can be observed through `result`, without reviving its old parameter binding. An input lent to a returned exclusive view cannot also be read through its parent; ordinary alias checks reject that observation. Temporary views end after each predicate call and before result transfer. Existing leak/return rules still apply; diagnostic ordering between new predicate access errors and return/leak errors needs an explicit stage rule and regression cases. Source typing must specify explicit read-only places and clause-root elaboration; no implicit dereference of owned parameters is adopted here. + +The snapshot cannot appear in body expressions, copies, branch arguments or a return; its only use is a post binding, and a snapshot used by no post is rejected. Multiple source `old` expressions lower to fields of one record. Its accounted size is bounded by `max_value_size`; the proposed combined snapshot plus `local.alloc` budget is `max_local_frame`, with checked arithmetic. These limits apply only to new contracted functions and need exact diagnostics. Prefix size and helper argument counts use existing instruction/call limits. Predicate closure traversal still needs a counted complexity bound. + +All three operations have empty declared effects, transfer no caller ownership, and perform no synchronization or capability use. `pre` and `old` read permitted observations; `old` additionally writes its bounded activation snapshot. `post` installation stores clause metadata, and its return-time evaluation reads only currently legal observations. Pure helper frame writes are local. No implicit heap allocation or opaque library hook is introduced. The prefix and implicit return obligations are semantic coverage constructs, not abbreviations for optional asserts. Source/package/generic lowering must supply the same verifiable operations; AIR verification cannot trust frontend coverage claims. + +Each prefix operation costs one fuel/quantum step; helper instructions use ordinary limits. Every implicit helper frame counts toward the existing 1,024-frame call-depth limit (T0007). A `ret` pays its ordinary step once, then invokes post helpers in installation order, charging their instructions. The proposed spec 11 §7 rule is: post dispatch and pending-return resumption are not new instructions and add no fuel/quantum unit; predicate instructions are charged normally. Resumption performs no new fuel check; stopping before the first predicate instruction already counts the begun `ret`. This dispatch policy needs interpreter tests, including that edge and limits between predicates. Explicit body cleanup occurs before `ret`; return views retain the ordinary permitted ancestor chain. A failed predicate traps without hidden cleanup/unwinding, under existing trap termination rules. + +False pre/post conditions need distinct stable trap codes, not allocated here; a predicate's own arithmetic/bounds trap retains its code. Clause identity/location and invocation context need an exact additive run-record schema. Entry predicates run in the invoked task, including spawned workers. Capability exclusions still permit parameter-free conditions on `@main`, including a false condition. Both profiles enforce the same contracts. Predicate execution consumes fuel and can change schedule interleavings: contracts are not observationally free. Fuel exhaustion during a postcondition produces no successful return; cancellation checks and synchronization remain excluded from predicate code. ## Status and diagnostics @@ -74,21 +98,33 @@ Valid target example: a function with `requires { x > 0u64; }` and `ensures { re ## Invariants and unresolved decisions -Type invariants require a choice between enforcing every construction/write and introducing encapsulation plus checked publication boundaries. Spec 15 §14.1 currently permits imported construction and field access; function-boundary checks alone do not establish a value invariant. Exclusive mutation, nested aggregates, value.swap, outcomes, transfers and partial initialization all need explicit coverage rules. +Type invariants require a choice between enforcing every construction/write and checking publication from exclusive mutation. Spec 15 §14.1 currently permits imported construction and field access; function-boundary checks alone do not establish a value invariant. These current programs contain no invariant declaration: they demonstrate where a future `Range.lo <= Range.hi` rule would need coverage, not current compiler defects. + +| Probe at `94414da`, fuel 10,000 | Verified outcome | Design consequence | +|---|---|---| +| `{0,5}` → `r.lo = 10; r.hi = 20` through one exclusive view | returns width 10 | eager checks reject the intermediate `{10,5}`; deferred checks permit repair | +| copy `*r` into another `Range` between those writes | returns 1 for the escaped copy's `lo > hi` | checking only the exclusive borrow's end misses Copy publication | +| call `width(ref r)` between those writes | T0003 at `hi - lo` | shared reborrows need checks if readers may rely on the invariant | +| source `var range: Range = zero` | E7006 `zero_not_zeroable` | source currently prohibits this construction | +| AIR `local.zero` of `local<@Range>` with integer fields | accepted, returns 0 | AIR construction needs coverage: `{0,0}` meets `lo <= hi`, but would violate a strict invariant `lo < hi` | + +Eager enforcement requires root/projection tracking for every complete construction, store and swap, including nested invariant types. It forces multi-field updates to use valid whole-value replacements. Exclusive-epoch enforcement permits intermediate invalid states, but must validate Copy publication and shared readers as well as epoch end. It also needs a rule for mutable callees: check entry, or prohibit reliance on a possibly broken invariant. Returned mutable views and task loans can transfer the validation boundary to another function/join. Neither model may bypass initialization or ordinary alias restrictions to read a root for validation. Format 0 tracks whole-local initialization, not partially initialized field states. + +Both models must cover AIR `local.zero`, nested aggregates, buffers/graphs, `value.swap`, outcome payloads and ownership transfer; a narrower source constructor policy is insufficient. Source/AIR zeroability wording is a separate question (Q-056). Invariant metadata and its AIR representation remain unresolved: the function prefix does not by itself provide a type/module declaration mechanism. Module invariants need a definition of their roots and observation boundaries. Source 0.1 has no module-state declarations or visibility modifiers; neither nonexistent globals nor arbitrary private-state semantics may be inferred from spec 13's example. Loop invariants, if included by P6-6, need an explicit initiation/preservation/exit rule. Implementing function contracts alone leaves these requirements and P6-6 open. -Remaining decisions: predicate language/types and totality; mutable/linear result views and cleanup order; snapshot limits; proof and assumption modes; invariant boundaries; AIR grammar and compatibility; traps, fuel and report schema. The RFC stays Draft until these have concrete rules and counterexamples. +Remaining decisions: exact predicate language/types, write-root proofs and termination policy; source clause elaboration and complete AIR binding grammar; snapshot diagnostics; proof and assumption modes; invariant boundaries and metadata representation; traps/report schema and tested pending-return dispatch. The RFC stays Draft until these have concrete rules and counterexamples. ## Compatibility and integration -An AIR0 implementation must preserve all earlier accepted behavior, canonical bytes and rejected codes (spec 07 §8.7). Preserving the old E0001 for an unfeatured header conflicts with §8.1's required E0006; replacing it with E0006 conflicts with §8.7. Q-055 records the existing trusted-header precedent, not an exception contracts may assume. An instruction-based form fits the E0004 exception; the header candidate requires an owner decision on compatibility policy or AIR1. +An AIR0 implementation must preserve all earlier accepted behavior, canonical bytes and rejected codes (spec 07 §8.7). Isolated candidate function operations and the snapshot/post prefix currently reject only E0004; registering them may produce E0006 when their feature is undeclared, matching the named-opcode exception and §8.1. The body-use probe also reports E5001 because the unknown instruction does not define `%old`. That shape remains invalid under the candidate's snapshot restriction; the audit concerns its rejection-code transition, not acceptance of this escape. Establish whether §8.7 covers those dependent errors, and preserve independently invalid cases; precedent alone does not settle that interpretation (Q-055). Full dependency closure and syntax audits are still required. The prefix avoids the header-specific E0001 conflict without changing compatibility policy. New type/module metadata must independently satisfy compatibility or use AIR1. -On acceptance integrate spec 13 §1, spec 08 §8, spec 10 §6.1, spec 07/07a, spec 15, grammar, feature/error registries and the Quick Reference together. Delivery requires source/AIR positive and negative coverage, bypass attempts, generic/package/worker cases, borrow/loan/snapshot failures, deterministic profiles/schedules and independently verified audit statuses. No implementation is authorized by this Draft alone. +On acceptance integrate spec 13 §1, spec 08 §8, spec 10 §6.1, spec 11 §7, spec 07/07a, spec 15, grammar, feature/error registries and the Quick Reference together. Delivery requires source/AIR positive and negative coverage, bypass attempts, generic/package/worker cases, borrow/loan/snapshot failures, deterministic profiles/schedules and independently verified audit statuses. No implementation is authorized by this Draft alone. ## Agent complexity impact -New concepts: boundary obligations, result/old observations and audit statuses. New verifier state: descriptor bindings, predicate restrictions, snapshot and return availability, plus the chosen invariant/proof state. New source forms: contract clauses and contextual result/old; diagnostic and AIR counts await a completed design. +New concepts: boundary obligations, result/old observations and audit statuses. New verifier state: ordered obligations, predicate restrictions, snapshot and return availability, plus the chosen invariant/proof state. New interpreter state: pending return and its next postcondition. New source forms: contract clauses and contextual result/old; diagnostic and AIR counts await a completed design. Assertions express individual checks today, but the probes show why they do not encode a public guarantee with verified coverage. The cost must be compared with keeping explicit checks and making no contract claim. No SMT solver, implicit allocation or effect inference is proposed. @@ -100,4 +136,4 @@ The acceptance change must demonstrate: preserved availability/alias/loan invari ## Alternatives considered -Frontend-generated asserts with annotations fail the coverage invariant. Inline contract instructions plus a boundary-coverage verifier could satisfy it, but require explicit entry/return and snapshot state. Callee-enforced descriptors avoid that bypass class while enlarging interpreter invocation semantics. A format-1 design remains an alternative if format-0 compatibility cannot be proved. +Frontend-generated asserts with annotations fail the coverage invariant. Ordinary explicit predicate calls remain useful checks but do not establish public contract coverage. The entry prefix combines verifiable installation with callee-enforced returns; arbitrary inline installation is rejected. Header descriptors could encode the same semantics, but add the Q-055 compatibility conflict. A format-1 design remains an alternative for complete invariant metadata if format-0 compatibility cannot be proved.