Files
aji/docs/design/contract-accounting-and-status.md
T

24 KiB

Contract accounting, diagnostics and status candidate

Non-normative research for RFC 0039, following the invariant-boundary candidate. All new constructs, limits and codes here are proposals, not registry allocations. Full P6-6 remains open.

Evidence and budget rule

At 9a3e135, the verifier runs limits before CFG, SSA and types, stopping at the first failing stage (spec 08 §14; src/verifier.zig). Frame storage counts local.alloc; SSA values have the separate maximum-value bound. Nine current-language probes confirm:

  • an exactly 1,048,576-byte local accepts and returns 0; one extra byte rejects E5101;
  • that local plus a 1,048,576-byte SSA array still accepts and returns 0;
  • limits beat malformed CFG (E5101); CFG beats forward SSA use (E5002); forward SSA use beats type mismatch (two E5001s);
  • type mismatch beats unsafe-boundary failure (two E1001s); unsafe beats initialization (E6001); initialization beats a live-borrow leak (E1010).

Runs use fuel 10,000. These are baseline constraints, not tests of implemented contracts.

Four complete pre/post assume/document opcode probes each reject E0004 alone. An existing source assume(false) in an unsafe function accepts verification and traps T0009 when run with fuel 10,000. These five further baselines constrain compatibility and unsafe enforcement; they do not implement the proposed modes.

Proposed activation storage, using spec 08's checked, platform-independent accounted sizes:

L = sum of all local.alloc content sizes in the function
S = old helper's declared Data return size, or zero
E(clause) = sum of Copy-value places for each explicit ref binding
E(old) = the same sum for old's input bindings
E(checked.make) = size(R) for Copy R; zero for linear R
E(checked.modify) = 0
activation = L + S + max(0, E for executable clause/old/make sites)

Each explicit Copy ref binding creates its own temporary place, even when two bindings name the same parameter. Borrow/owner/linear-root observations use in-place views and contribute zero; they MUST NOT copy or transfer ownership. Documented clauses create no runtime places. Their virtual access checks still apply. Locals and S persist for the activation; clauses execute sequentially and their places end before the next evaluation. Helper/callback activations have their own bounds and ordinary call-depth rules.

For make, a Copy representation needs the instruction-internal whole-value place; a linear representation is observed through its existing SSA cell before transfer into the checked value. The latter contributes no new place and cannot be copied, moved during validation or exposed before success. The explicit R operand supplies size/root shape before SSA; both cases retain the ordinary maximum-value bound.

Pending callback/return values remain ordinary SSA values, bounded by max_value_size and traced by GC. They are not a new frame term. A Copy ref result place is counted once in E; an update result retained during validation is not materialized merely because it is pending. The candidate maximum activation size is 1,048,576 bytes, using E5101's existing limit: "local frame bytes", max and found fields; overflow is found: "overflow". Functions without the new sites retain their current accounting.

All descriptors MUST be available before SSA inference: clause bindings name original parameters, the snapshot or result; parameter/result types come from the enclosing header, snapshot type from its helper header, and make explicitly names checked<R,@p>. Callback result types come from callback signatures. Budget calculation never dereferences an absent parameter or assumes predicate validity. Malformed bindings wait for their later stage; size and Copy/root-shape queries must be total on recursive/invalid types, with cycle detection and memoization, without invoking full type verification. Existing size accounting supplies the size-query precedent; the current recursive linearity query is not a safe pre-types substitute. An arbitrary body SSA binding is forbidden. Accounted size of checked<R,p> is size(R); predicate identity contributes no runtime member.

For this budget query, seed the existing intrinsically linear kinds and propagate linearity backwards through array elements, nominal struct/enum members and checked<R,@p>'s representation R to a least fixed point. Predicate identity contributes no edge. An invalid member cycle with no reachable linear leaf is non-linear (Copy for accounting); one reaching an owner or another linear leaf is linear. Direct borrow/root bindings remain in-place. This matches ordinary linearity on valid types and supplies a deterministic value on cycles, without accepting them. Use the corrected nominal-edge size-depth convention (Q-058); anonymous checked representation edges preserve that depth. Keep invalid-graph queries bounded rather than replacing a whole cyclic type's size with zero. Required candidate vectors include both kinds of cycle next to the frame limit: budget excess still reports E5101 first; otherwise the invalid cycle reaches the ordinary type rejection. These vectors are not among the fourteen executed baselines.

Two sequential clauses each materializing 600,000 bytes fit when L=S=0. One clause materializing both needs 1,200,000 and rejects. Snapshot 600,000 plus locals 500,000 rejects even with no temporary place. This rule does not infer lifetime reuse between arbitrary locals.

Bound the virtual boundary work

Post bindings are checked at every return, so instruction count alone does not adequately bound the product. Count syntactically, including unreachable blocks, before SSA:

W = sum_pre/old(1 + binding_count)
  + ret_count * sum_post(1 + binding_count)
  + 2 * make_count
  + sum_modify(4 + extra_argument_count)

The proposed limit is 1,048,576 virtual binding positions per function: four times the ordinary instruction limit, independent of any benchmark. The extra position covers each virtual invocation; modify covers its callback's first argument, extra arguments and predicate invocation. Count documented clauses because their virtual legality checks still run. Excess/overflow rejects E5101 with limit: "contract binding positions" and the existing fields. Actual argument lists retain the 64-argument limit, including modify's generated first argument. P/S closure computation and diagnostic witnesses need independent memoized bounds; this formula is not a bound on every verifier algorithm.

Four statuses, three enforcement modes

Default contract.pre/post and checked make/modify evaluate their predicates at every specified boundary. Source requires/ensures retain this default. Propose explicit variants contract.pre.assume/post.assume and contract.pre.document/post.document, with contextual source requires/ensures assume and requires/ensures document groups.

Mode Proof treatment Spec 13 status Execution
runtime, all boundaries proved by the closed rule below proven PROVEN_STATICALLY predicate still executes
runtime, no complete proof none CHECKED_AT_RUNTIME predicate executes
explicit assume not attempted ASSUMED_UNSAFE interpreter evaluates; false is T0009; native unsafe treatment follows assume
explicit document not attempted UNPROVEN declaration recorded; predicate is not executed

Assumed variants require the existing unsafe effect/trusted boundary and appear in the unsafe report; ordinary P/helper typing, availability and lifetime checks remain mandatory. They need a separately gated extension depending on contracts and unsafe, so ordinary contracts need not declare unsafe support solely to be understood. False unsafe assumptions retain the existing unsafe-precondition semantics, rather than becoming a safe guarantee.

Documented variants also retain P membership and the same virtual observation/access checks at entry and every normal return. They grant no fact to a caller or the body. Switching a clause to document removes its guarantee and must remain visible in the report/Quick Reference. A documented post may bind an old snapshot only when an executable runtime/assumed post also uses that snapshot; a snapshot used solely by documents rejects as unused. Checked types have no document/assume construction mode in this candidate: persistent value claims remain enforced.

Every executed prefix operation still costs one fuel step, including document declarations and post installation. Documented clauses invoke no helper at entry or return; executable clauses use ordinary helper instruction and frame accounting. Recording metadata introduces no extra dispatch step. This extends the prefix accounting candidate without making classification change execution.

No successful run, absence of a trap, check count or empty effect set establishes proof. Profiles may reject statuses but MUST NOT alter enforcement or proof classification. Static classification adds no skipped helper instruction or fuel/scheduler change. Even PROVEN_STATICALLY does not promise termination or freedom from other traps. Counts describe declaration/operation sites, separately from the number of covered returns, never invocation frequencies.

Closed initial proof classification

This is deliberately a restricted classifier, not a restriction on executable contracts. Unsupported predicates remain CHECKED_AT_RUNTIME. It never imports a caller fact into a callee's global pre status and never assumes an unchecked declaration.

An eligible predicate has one block, no calls, and only typed constants, copy, Data struct construction/projection, integer/bool comparisons, bool and/or/xor, and shared binding-derived field views with load/end, ending in ret bool. The same form with a Data return can describe old's snapshot fields. Arithmetic, casts, indexing, graph/buffer/enum operations, calls and multiple blocks are unsupported initially. Normalization uses an immutable DAG, not expanded copies of paths/aggregate trees.

Terms are typed constants, immutable Data parameter identities/projections, stable shared parameter field projections, snapshot terms from an eligible old helper, and the current return operand's Data origin. Resolve return origins through constants, copy, struct.make and struct.get; every other Data SSA definition is an opaque identity at this boundary. A snapshot cannot capture body SSA, so a loop's repeated definition is not conflated with an entry observation. Borrow-return origins remain unsupported. Mutable-root entry/current observations have distinct identities, even when the body happens not to write; no interprocedural write-summary proof is inferred.

Shared field terms are stable because ref cannot become mut, overlapping mutable call arguments and root consumption are forbidden, and task loans exclude writers. Field views in this normal form do not traverse interior-mutable interfaces. P/S alone are not substituted for this exact normal-form condition; future pure observations outside the form stay unsupported.

Decision rules are closed: compare typed constants with their declared signedness; identical typed terms give true for eq/le/ge and false for ne/lt/gt; otherwise an atom is unknown. Bool combinations use three-valued logic (true or unknown is true, false and unknown is false; xor with unknown is unknown). A runtime clause is proven only if its formula is definitely true at every prescribed boundary. Pre parameters are universally unconstrained; a post must hold at every syntactic ret, including unreachable ones, and zero ret sites give no vacuous proof. A make site may substitute a constant/parameter-derived representation; modify remains runtime initially.

Examples: a Data identity function whose every return is x can prove result == old(x) when old merely captures x. A second return of y prevents that classification. A constant Range representation or {lo:x, hi:x} can prove lo <= hi through shared field inspection. A pre over unrelated lo/hi remains runtime. x + 0 == x, hashing and mutation-based restoration remain runtime even when mathematically true.

The proof/report candidate refines the work bound with exact opcode/node charges, binding-substitution positions, checked u64 counters and ordered fallback reasons. Pre has one boundary and no body-origin work; adding unrelated body instructions cannot make a pre proof exceed its budget. Post/make charge each required origin definition once per record, including shared definitions across return sites. The proposed bound is 1,048,576 per record. Excess, overflow or unsupported forms yield proof none without rejecting or weakening runtime enforcement; logical costs are independent of cache hits. The concrete candidate and its vectors await adoption and implementation rather than an implementation-dependent prover choice.

Diagnostics and report

Map the new rules into existing stages: limits first; prefix order/entry predecessors in CFG; snapshot-use restrictions and binding identities in SSA; signatures/Data followed by P/S membership at the end of types; callback effects in effects; assumed boundaries in unsafe; ordinary initialization checks unchanged; virtual access/loans/return availability in borrows; existing bounds last. Observation places are materialized from complete parameter/result/snapshot values and introduce no independent initialization failure. Parse/name and feature errors precede verification. Invalid signature errors precede purity classification. Runtime clauses retain ordinary E2001/E3001/E2101 and lifetime codes instead of a generic contract error.

Candidate new codes are E8001 contract.invalid_binding (snapshot escape/unused/document-only snapshot with stable reason), E8002 contract.predicate_not_pure, E8003 contract.predicate_not_stable, and T0011/T0012/T0013 for false runtime pre/post/invariant. None is allocated here; adopting E8xxx also requires a new family entry in spec 10 and the error registry. Existing signature/type errors use E1001, structural errors E5002, limits E5101 and missing unsafe boundary E6001. Source-decided errors follow spec 15 §10's E7xxx policy; semantic new codes retain source provenance. A purity witness must contain real helper/type/op facts, with bounded length and explicit truncation, not invented locations.

Collection at returns

For a contracted ret, retain the body state before return transfer. Run the ordinary return check on isolated working state, keeping its existing diagnostics and early-return/leak behavior. Track failure of the returned operand's availability, transfer access or declared borrow origin separately from resource/borrow leaks; do not infer that flag by parsing a diagnostic message. If return legality failed, suppress virtual post access checks at this ret: the invalid returned boundary is not a usable clause observation. Keep every ordinary diagnostic that today's return check would emit, and continue other independently valid returns.

Otherwise check every installed post in prefix order against the original pre-transfer body state, using isolated temporary view/state bookkeeping for each. Isolation includes borrow/loan state, transfer summaries and emitted verifier events; commit ordinary return facts/events only once, and discard synthetic temporary-view events after each virtual check. A failed clause cannot leave synthetic live borrows or suppress a later clause or the ordinary leak records. Type/P rules ensure these helpers cannot permanently mutate caller state, so successful sequential predicates have the same available roots. This is static legality collection, not runtime execution of later predicates after a trap. Runtime still stops at the first failing predicate. Finally merge ordinary and virtual facts using the existing AIR (line,col,code) order; source mapping retains existing one-per-code/source-location selection. Contract-free returns use today's path unchanged.

A virtual post-access error's primary span is its binding token, not ret; code-specific function/block/inst fields identify the installing post instruction. They are not additions to the common diagnostic envelope. Function and block are AIR names without sigils, as in ordinary borrow diagnostic payloads; inst is the zero-based instruction index. Map that binding independently to the source root occurrence in its clause. Preserve existing factual payload and conflict/spawn origins; result payloads name the actual ret operand, not a synthetic result ValueId. Add proposed code-specific fields contract_binding (zero-based argument index) and contract_return (the evaluated return position). The latter's field order is function,block,inst, followed by file/line/col only when exactly mapped, then mandatory air_line/air_col. Its block is a name, not an index; names/inst identify the actual ret and source coordinates map independently. This is a separate factual position object: today's related_locations roles require a value identity and cannot represent ret without inventing one. No role is silently added to that closed schema.

For AIR-only input, contract_return still includes air_line/air_col and omits file/line/col because no source lowering map exists; the primary envelope continues to identify the input AIR file. This deliberately differs from today's AIR-only related_locations serialization and must not be normalized by inventing a source map.

All returns are checked. Buffer only the new virtual facts and append them in increasing return block index, then instruction index, retaining clause/binding order within each return. The existing stable (line,col,code) sort therefore retains that return order within a tied virtual primary/code, before source duplicate selection; the current comparator itself supplies no return key. Internal block indices establish this order, while JSON records contain block names. Ordinary facts and contract-free ordering stay unchanged. Source may retain one representative failure for a binding across several returns or repeated mapped specializations under its existing code/location rule. This output selection does not suppress checking another clause or return. Distinct source clause bindings have distinct primary positions and survive independently. Future collection tests must cover two clauses failing with the same code at one ret, one clause failing at several returns, and duplicate imported/template maps, with the exact retained return context. No contract diagnostic fields are implemented by this candidate.

Current baselines at 8df6cac: a wrong-origin borrow return with an unrelated live owner emits only E2102, while a valid-origin or scalar return retaining that owner emits E3002. Returning an already taken owner emits E2002. Returning an owner with a live child view emits both E2101 and E2105: the current return check kills the root after reporting its transfer conflict, then reports the view leak. Do not replace this with an invented first-error-only return contract. Future vectors must pair an otherwise valid ret's unavailable post root with an unrelated leak, proving both survive; a return-legality failure must preserve the baseline list and suppress dependent post errors. These are proposed collection rules, not an implemented post checker.

Purity/stability witnesses

Complete ordinary type validation first. Compute P and then S membership once over the direct-call graph, including unreachable instruction/call sites. For each locally inadmissible function select its first seed in this fixed order: declared effects, trusted metadata, header/block-parameter types in declaration order, then instruction type operands/results before opcode in textual block/instruction order. Each seed names its real function/type/op position. Required predicate roots outside P report E8002; if any such root fails, stop the types stage before required S-root checks. Ordinary functions outside P do not reject unless a contract requires them. After all required P roots pass, S uses published stable classifications and required roots outside S report E8003. No source annotation or proof result substitutes for either closure.

Use a reverse-edge multi-source BFS to give each excluded function its minimum number of call edges to a local seed. Resolve ties after distances are known: select the first textual call site leading to distance minus one. A distance-zero function keeps its first local seed even if it also calls another invalid helper. Recursive components with no local failure remain admitted; a component reaching a seed is excluded. The selected witness edges strictly decrease distance, so a witness never loops. Propagate the terminal fact and bounded path summaries in increasing distance order. BFS/local scans cost O(F+C); retaining the first/last 16 edges per excluded function adds at most 32F position copies, not a fresh graph traversal per clause.

Candidate E8002/E8003 fields are predicate,reason,witness. Predicate is the referenced AIR name without @; reason is the terminal seed category, independently of prose. Witness field order is call_count,prefix,suffix,omitted_calls,terminal. For at most 32 calls, prefix contains every call and suffix is empty. For a longer path, prefix is its first 16 and suffix its last 16; omitted_calls is call_count minus 32 and represents the gap between them. Terminal is always retained. This bounds witness positions, not the size of arbitrary input names/type strings. A malformed/unreachable callee has already failed ordinary validation and is not an invented seed.

Each call record is function,block,inst,callee,source, in that order, with exact zero-based AIR instruction identity and source {file,line,col} or null. Terminal is function,block,inst,reason,type,operation,source; header seeds have null block/inst, unused fact fields are null, and reason is effects/trusted/type/operation. Operation is the actual canonical opcode, not a suggested repair. Source positions use the exact lowering map; missing maps stay null. The primary diagnostic belongs to the clause/checked-type use that requires the predicate. Witness positions identify the callee chain and terminal fact independently, preserving real imported/template locations. This is a candidate typed field extension; no code/field registry is allocated here.

The diagnostic vectors retain the five executed return baselines and proposed graph cases for recursion, shortest-path/tie selection and a 40-edge witness with eight omitted calls. Graph/vector checks validate the candidate algorithm and metadata, not a new compiler diagnostic. Required vertical tests additionally cover several clauses sharing a seed, unreachable calls, duplicate source mappings, invalid types preceding purity, constant-true predicates with forbidden unused operations, and leak/access collection at several returns.

Emit the proposed additive contracts section only for modules declaring the relevant feature; contract-free canonical report bytes stay unchanged. Each row identifies function/block/instruction, helper, kind, scope (boundary or persistent value), status, proof and enforcement, plus covered return sites and positions. A pre row belongs to the callee declaration, not a selected caller. A type guarantee and a relation over listed functions require distinct scopes. Include per-status site totals; totals are not sums over executions or returned branches. Snapshot metadata is not itself a truth obligation. Rejected modules still produce diagnostics and no audit document.

Required tests include max/sum activation cases, invalid descriptors before SSA, argument/work limits, all four modes, mixed executable/documented snapshot use, unsafe/trap/fuel behavior, multi-return and trap-only coverage, proof-budget fallback, old/current mutation counterexamples, callback/GC pending values, exact rejection ordering and identical contract-free report bytes. Predicate/trap rows must survive generic/package/source mapping. The linked research supplies a concrete function/value report grammar and classifier; module-claim representation, owner adoption, RFC 0040 observations, diagnostic collection and full vertical implementation remain gates. This file changes no normative bundle.