19 KiB
RFC 0039: Verifier-visible contracts
Status: Draft
Scope: P6-6 — preconditions, postconditions, type/module invariants and audit classification
Language version: 0.1
AIR version: gated format-0 extension under investigation; not approved
This draft opens the spec gate. It neither changes the language nor completes P6-6. The evidence below is verified; the invariant is a proposed acceptance requirement. The representation is a candidate, and unresolved decisions prevent implementation.
Motivation and current evidence
Spec 13 §1 and spec 08 §8 name four contract statuses, but do not define executable obligations. Spec 10 §6.1 and src/report.zig count checks, without a contract table. src/air/module.zig has no contract declarations. Source requires/ensures are outside the current grammar.
These probes with the compiler at 94414da establish constraints:
// Variant A
fn positive(x: u64) -> u64 effects [] {
assert(x > 0u64);
return x;
}
// Variant B, substituted for A
fn positive(x: u64) -> u64 effects [] {
if x > 0u64 { assert(x > 0u64); }
return x;
}
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<u64> 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. 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.
Precise invariant
Every claimed contract status must be derived from verified AIR. A predicate or frontend annotation alone is not evidence that every required execution boundary is covered. Contract evaluation must obey ordinary ownership, borrow, initialization, effects and authority rules; it cannot allocate implicitly or observe a consumed value.
Preconditions cover every invocation, including entry instantiation, recursion and spawned workers. Postconditions cover every normal return, including implicit source returns; traps and execution limits do not claim a successful postcondition. Type/module invariant coverage must be specified independently rather than inferred from these two obligations.
Candidate normative rules
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. 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 a feature-gated entry prefix over new function headers. The following spellings are candidates, not registered instructions:
entry:
contract.pre @positive(%x)
%old = contract.old @snapshot(%x)
contract.post @unchanged(%old, result)
... ordinary body ...
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.
| 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<T> becomes ref<T>, slice_mut<T> becomes slice<T>, 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
| Status | Required evidence |
|---|---|
| PROVEN_STATICALLY | a specified verifier proof of the obligation, including coverage |
| CHECKED_AT_RUNTIME | mandatory evaluation at every specified boundary |
| ASSUMED_UNSAFE | an explicit unsafe assumption and its visible boundary; never inferred from an empty effect list |
| UNPROVEN | no discharged obligation; no caller may rely on it as a fact |
The initial proof calculus and whether unproven/assumed clauses may be accepted remain undecided. The audit table must identify clause, boundary, status and source/AIR position; existing assertion counts remain counts. Proposed E7xxx reason fields and new AIR/contract trap codes are not allocated by this draft.
Valid target example: a function with requires { x > 0u64; } and ensures { result == old(x); } returning x; a positive argument succeeds and zero traps at entry. Rejected target example: a postcondition dereferencing an owner consumed by the body; the existing availability rule must still reject it. These are design targets, not current conformance fixtures.
Invariants and unresolved decisions
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: 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). 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 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: 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.
This Draft adds zero normative bundle tokens: it is outside both manifests. Before acceptance, measure Quick Reference, source and AIR growth with zig build agent-reference and tools/agent_bundle_tokens.py; report all three tokenizers and justify growth. Zero current growth is not an estimate of the delivered feature.
Memory/concurrency review obligations
The acceptance change must demonstrate: preserved availability/alias/loan invariants; independent AIR boundary-access rules; runtime coverage/order; valid and rejected source/AIR examples; diagnostic/trap codes; deterministic fuel/schedule behavior; and legacy compatibility. These are requirements for the completed design, not claims that the Draft has discharged them. Ordinary verifier/interpreter rules remain unchanged today.
Alternatives considered
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.