From 2db752dba95b7671360aca447ad8648dd9d8ad85 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Fri, 9 Oct 2026 17:00:38 +0300 Subject: [PATCH] docs: define contract AIR bindings and access diagnostics --- docs/design/contract-accounting-and-status.md | 6 + docs/design/contract-air-bindings.md | 81 +++++ docs/design/contract-binding-vectors.json | 344 ++++++++++++++++++ docs/design/contract-invariant-boundaries.md | 2 +- docs/design/contract-naming-vectors.json | 36 ++ .../contract-source-and-module-state.md | 6 +- docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 2 + docs/rfcs/0039-verifier-visible-contracts.md | 6 +- 9 files changed, 479 insertions(+), 6 deletions(-) create mode 100644 docs/design/contract-air-bindings.md create mode 100644 docs/design/contract-binding-vectors.json diff --git a/docs/design/contract-accounting-and-status.md b/docs/design/contract-accounting-and-status.md index 6407ced..8d3e925 100644 --- a/docs/design/contract-accounting-and-status.md +++ b/docs/design/contract-accounting-and-status.md @@ -99,6 +99,12 @@ For a contracted ret, retain the body state before return transfer. Run the ordi 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 diff --git a/docs/design/contract-air-bindings.md b/docs/design/contract-air-bindings.md new file mode 100644 index 0000000..16e52e4 --- /dev/null +++ b/docs/design/contract-air-bindings.md @@ -0,0 +1,81 @@ +# Contract AIR bindings candidate + +Non-normative completion of the binding grammar in [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), following [source elaboration](contract-source-and-module-state.md) and [accounting/diagnostics](contract-accounting-and-status.md). This document allocates no feature, instruction or diagnostic and authorizes no implementation. Compatibility, trap/dispatch schemas, owner adoption and full vertical delivery remain gates. + +## Text and identity + +Reuse AIR format 0's tokens, comments, significant instruction newlines, global/local namespaces and list conventions (air-text.ebnf). Proposed additions are: + +```ebnf +contract_pre = ( "contract.pre" | "contract.pre.assume" | "contract.pre.document" ) + global bindings ; +contract_old = local "=" "contract.old" global bindings ; +contract_post = ( "contract.post" | "contract.post.assume" | "contract.post.document" ) + global bindings ; +bindings = "(" [ binding { "," binding } ] ")" ; +binding = [ "ref" ] ( local | "result" ) ; +checked_type = "checked" "<" type "," global ">" ; +checked_op = "checked.make" checked_type "," local + | ( "checked.view" | "checked.take" ) local + | "checked.modify" local "," global "(" [ local_list ] ")" ; +``` + +The generic instruction production still governs checked operation result bindings: make/view/take bind exactly one result; modify follows ordinary call rules (one for a value return, none for void, optional for never). A never callback cannot publish an update or produce an observable result; an optional never-typed SSA binding does not change this. Old binds exactly one snapshot, while pre/post bind none. There is no old.assume/document or optional old result. Lists have no trailing comma, matching ordinary AIR call lists. Empty bindings are valid for parameter-free helpers. There are no type annotations, constants, projections, nested calls, mut/move modifiers or inline expressions in a binding. Compute those inside the helper. Source spelling remains type.checked and explicit static function application; this grammar does not reserve a source module named checked. + +Checked operands and modify extras remain ordinary body SSA operands, not restricted clause roots. Make's explicit checked type determines R/p without operand inference; its operand has exactly R. View accepts ref/mut> and produces a shared dependent ref; take accepts the whole checked value and produces R. Modify's first operand is mut>, and its callback signature starts with mut, followed by exactly the extra argument types. The implicit first argument counts toward the 64-argument bound, leaving at most 63 extras. Callback return/effects/loan rules remain those of the invariant candidate; no runtime function value or optional inline callback is added. + +The word result is a contextual placeholder only in these binding lists. `%result` is always an ordinary SSA identity and may name a header parameter; `@result` is an ordinary global. Names such as `%ref` remain locals. Parsing does not infer a placeholder from an SSA spelling or reverse a generated name. Contract operations occupy the uninterrupted entry prefix pre*, at most one old, then post*; entry has no predecessors. Interleaved modes retain textual order within each class. Ordinary instructions, including constants, start the body and end the prefix. These are CFG rules, not a new function header or lexer keyword policy. + +A resolved binding is `(root,form,span)`, where root is a header parameter ordinal, this function's single snapshot identity, or result, and form is value or shared. Span identifies the binding token (`ref` when present) separately from the installing operation. The parser retains ordinary ValueIds for local name resolution; verifier preparation converts legal roots to the typed descriptor without inventing a body SSA type. Bindings are descriptors, not immediate ordinary SSA reads: the SSA stage classifies their root/context before applying ordinary instruction-use dominance checks. Thus a pre naming the later snapshot reports snapshot_not_post, rather than pretending it reads that snapshot early. Ordinary body uses retain their existing SSA rules. All binding fields needed for pre-SSA budgets come from the header or old-helper signature. A malformed/unknown root is not dereferenced for size calculations. + +Local resolution is ordinary function-wide AIR resolution, including forward definitions. A known body/block-parameter identity is not silently reinterpreted as a header parameter. Function lookup accepts forward global declarations; helpers need not appear before their uses. Repeated bindings are legal and preserve their order and count. Handwritten AIR is not deduplicated; repeated Copy ref bindings materialize separate places, while repeated in-place shared roots create ordinary overlapping shared children. Source capture deduplication remains a frontend rule, with each selected binding counted once. Canonical serialization preserves the binding list and inserts `ref ` only for shared form; it cannot erase a duplicate or replace result with a ret-specific SSA name. + +## Observation type and lifetime + +A binding's produced type must exactly equal the corresponding helper parameter. Arity must match and retain the ordinary 64-argument bound. There is no numeric conversion, array-to-slice coercion, dereference or owner/checked representation fallback based on the expected helper type. Post result type is the enclosing declared return type, independent of which valid SSA operand a particular ret uses. The checked predicate signature is exactly ref -> bool; clause/old root adaptation is a different operation from make/modify's whole-R observation. + +| Root type T | Value form | Shared form | +|---|---|---| +| Data T, including snapshot Data | T, ordinary Copy observation | ref, through a complete temporary Copy place | +| complete Copy non-Data T, e.g. cap | rejected | ref, temporary Copy place; predicate rules still forbid extracting non-Data content | +| ref or mut | rejected | ref, shared child/reborrow | +| slice or slice_mut | rejected | slice, shared child/reborrow | +| own | rejected | ref, ordinary owner-content view | +| own_array | rejected | slice, ordinary owner-array view | +| addressable linear aggregate/resource/graph/buffer root | rejected | ordinary borrow.ref result type, dependent view without ownership transfer | +| checked | value only when R is Data | ref>; Copy uses a temporary place, linear uses a direct dependent SSA-root view; never implicitly ref | + +Apply the ordinary type validity and root-position rules before accepting a row. Storage/function-bound/void/never values do not become complete Copy places merely because a shallow Copy query returns true. Shared observation of a borrowed checked value uses the borrow row, preserving checked content. Predicate P entry signatures contain no mutable parameters; S additionally applies to persistent checked predicates. The table does not admit new operations to P/S or widen ordinary body addressability. On Data checked values, shared materialization preserves the existing claim without reevaluating the predicate. + +Linear checked roots require an explicit checked case in ordinary borrow.ref typing and runtime root access, analogous to linear named/array roots; a frame local cannot substitute because it requires Copy content. Before CFG/SSA, the accounting candidate charges every Copy ref occurrence to E(clause/old), including duplicates and shared snapshots/results, using header/helper descriptors and its total size/Copy queries. The activation bound is L + S + max E; each materialized complete value also retains the ordinary maximum-value bound. For example, 64 ref bindings of array with L=S=0 require 1,048,640 bytes and reject E5101, whereas 64 bindings of array exactly fit. Sequential clauses use max, not sum; views within one evaluation coexist. Documented bindings create no runtime places and contribute no E, while their argument/W limits and virtual access checks remain. + +Pre/old bindings may name only original header parameters. Post bindings may additionally name the earlier snapshot and result. A bare borrow or linear root cannot bind by value; shared roots require explicit ref. Result in pre/old is rejected even if no evaluation would occur. A void function has no result binding; a never function cannot install any post, including document. No contract fact revives a consumed root or bypasses a frozen parent. + +Pre evaluates in entry state; old evaluates after all executable pre helpers and before the body. Post installation creates no view/place/read. Every normal ret re-resolves its bindings against the final pre-transfer state, including result's actual operand and the current loan ancestry. All arguments of one helper are prepared in list order and coexist for that evaluation. Their temporary views/places and descendants end before the next predicate or normal result transfer. Helpers may not return their views through bool/Data. Post observation through an exclusive result may be valid while a simultaneous observation through its frozen input parent rejects; selecting a different form does not bypass ordinary access checks. Preserve the isolated return/post collection rule in the accounting candidate. + +The snapshot is a named contract-only Data value, not a general body definition. Its only legal uses are post bindings, including shared form. It cannot be passed into old/pre, copied/projected in the body, used in an ordinary helper call/branch or returned. At least one executable post (runtime or assume) must use it. A documented post may reuse that snapshot but cannot be its only consumer. Projections occur inside post helpers after receiving the Data record; direct prefix field projection is not a binding. No snapshot is created for a function with no executable old expressions. + +## Stages and factual errors + +Ordinary parsing/name resolution retains E0001 for malformed syntax, E0004 for unknown globals/opcodes and E5001 for undefined/duplicate SSA values. Known new operations require their registered feature before verification (E0006 if missing); assumed variants require their separate extension. No registry spelling/status is allocated here. Unknown-opcode research probes do not establish full format-0 compatibility, particularly when an unknown snapshot also has a dependent body use (Q-055). + +Limits use total queries/descriptors and retain E5101; CFG checks prefix order and entry predecessors with E5002. SSA then checks root identity/context and snapshot escape/use. Proposed E8001 has stable reason values: + +| Reason | Fact | +|---|---| +| invalid_root | a resolved binding names a body definition or block parameter rather than an allowed root | +| result_not_post | result is used by pre/old | +| snapshot_not_post | a snapshot binding is used by pre/old | +| snapshot_escape | an ordinary body instruction uses the snapshot | +| snapshot_unused | no post binding uses the snapshot | +| snapshot_document_only | post uses exist, all in document mode | + +Invalid root/context facts belong to each binding use; escape belongs to the body use. Unused/document-only belongs to the old declaration, and is classified only after that snapshot's root/context/escape checks pass, preventing a secondary unused diagnosis for the same misuse. Any correctly resolved snapshot binding in a post counts as a use, even if another binding in that post is invalid. An old operation referencing its own snapshot is snapshot_not_post and suppresses its dependent unused check. Ordinary SSA duplicate/undefined checks remain earlier evidence; descriptor operands do not undergo ordinary dominance checks and cannot add a competing E5001 for an invalid root/context. Prefix structural failure stops before SSA, and malformed root metadata cannot cause an earlier budget crash. This table defines proposal reasons, not allocated public codes. + +Candidate E8001 code-specific fields are `function,block,inst,reason,binding,root`, in that order; none is a new common-envelope field. Function/block are the enclosing AIR names without sigils and inst is the zero-based primary instruction index. Binding is the zero-based argument index for a binding misuse, null for a body escape or old-declaration failure; root is `%name` for the actual resolved local or `result` for the placeholder. A body escape identifies the actual body instruction; unused/document-only identifies old; invalid bindings identify their prefix instruction. No synthetic ValueId or invented name is serialized. Types/access errors retain their existing payload rather than adding this schema. + +Types checks Data/value admissibility, shared adaptation, exact arity/signatures, Data old result and bool pre/post result with E1001. It also rejects result on void and every post on never. Complete ordinary type validation precedes P/S and their proposed E8002/E8003 witnesses. Effects and unsafe follow existing stage order. At the evaluation boundary, use existing initialization, availability, borrow-conflict and lifetime diagnostics; a post's invalid result transfer preserves the ordinary return diagnostic list and suppresses dependent post checks. An alias-conflict message is not relabeled as invalid_binding. Runtime false/helper traps and their exact invocation metadata remain a separate gate. + +The [binding vectors](contract-binding-vectors.json) retain 18 current-language probes at `5ed0d86`: eleven ordinary-view/call cases verify owner/owner-array adaptation, mut/slice_mut reborrows, simultaneous shared children, frozen-parent rejection, exclusive-result observation, scalar/authority Copy non-addressability, and both never-call binding forms. Seven complete prefix spellings reject E0004 alone without falsely declaring a future feature. These constrain the design; they do not test implemented contract bindings or settle Q-055. + +Future vertical fixtures must cover every grammar form/mode, empty/64/65 lists, duplicate binding storage, scalar Copy places versus owner unwrapping, result/%result, snapshot shared uses/escapes, unrelated prefix/SSA/type errors and return legality. Current-language probes and candidate vectors are evidence for these requirements, not implemented-contract conformance. diff --git a/docs/design/contract-binding-vectors.json b/docs/design/contract-binding-vectors.json new file mode 100644 index 0000000..040111f --- /dev/null +++ b/docs/design/contract-binding-vectors.json @@ -0,0 +1,344 @@ +{ + "purpose": "Non-normative current-language probes; no contract binding semantics implemented.", + "compiler": "5ed0d86", + "cases": [ + { + "case": "owner_unwrap", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: own) -> u64", + "effects []", + "entry:", + " %r = borrow.ref %v", + " %x = load %r", + " borrow.end %r", + " %taken = own.take %v", + " ret %taken" + ] + }, + { + "case": "owner_array_unwrap", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: own_array) -> own_array", + "effects []", + "entry:", + " %r = borrow.ref %v", + " %n = slice.len %r", + " borrow.end %r", + " ret %v" + ] + }, + { + "case": "mutable_scalar_reborrow", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: mut) -> u64", + "effects []", + "entry:", + " %r = borrow.ref %v", + " %x = load %r", + " borrow.end %r", + " ret %x" + ] + }, + { + "case": "mutable_slice_reborrow", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: slice_mut) -> usize", + "effects []", + "entry:", + " %r = borrow.ref %v", + " %n = slice.len %r", + " borrow.end %r", + " ret %n" + ] + }, + { + "case": "repeated_shared_owner_children", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: own) -> own", + "effects []", + "entry:", + " %a = borrow.ref %v", + " %b = borrow.ref %v", + " %ok = call @same(%a, %b)", + " borrow.end %b", + " borrow.end %a", + " ret %v", + "fn @same(%a: ref, %b: ref) -> bool", + "effects []", + "entry:", + " %yes = const.bool true", + " ret %yes" + ] + }, + { + "case": "frozen_parent_observation", + "codes": ["E2101"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: mut) -> void", + "effects []", + "entry:", + " %exclusive = borrow.mut %v", + " %wrong = borrow.ref %v", + " borrow.end %wrong", + " borrow.end %exclusive", + " ret" + ] + }, + { + "case": "exclusive_result_shared_observation", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: mut) -> mut from %v", + "effects []", + "entry:", + " %exclusive = borrow.mut %v", + " %view = borrow.ref %exclusive", + " %x = load %view", + " borrow.end %view", + " ret %exclusive" + ] + }, + { + "case": "copy_scalar_not_addressable", + "codes": ["E1001"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: u64) -> u64", + "effects []", + "entry:", + " %r = borrow.ref %v", + " ret %v" + ] + }, + { + "case": "copy_authority_not_addressable", + "codes": ["E1001"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%v: cap) -> u64", + "effects []", + "entry:", + " %r = borrow.ref %v", + " %x = const.u64 0", + " ret %x" + ] + }, + { + "case": "never_call_with_binding", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f() -> never", + "effects []", + "entry:", + " %n = call @die()", + " trap", + "fn @die() -> never", + "effects []", + "entry:", + " trap" + ] + }, + { + "case": "never_call_without_binding", + "codes": [], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f() -> never", + "effects []", + "entry:", + " call @die()", + " trap", + "fn @die() -> never", + "effects []", + "entry:", + " trap" + ] + }, + { + "case": "unknown_contract.pre", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " contract.pre @yes()", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + }, + { + "case": "unknown_contract.pre.assume", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " contract.pre.assume @yes()", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + }, + { + "case": "unknown_contract.pre.document", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " contract.pre.document @yes()", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + }, + { + "case": "unknown_contract.old", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " %old = contract.old @yes()", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + }, + { + "case": "unknown_contract.post", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " contract.post @yes(ref result)", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + }, + { + "case": "unknown_contract.post.assume", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " contract.post.assume @yes(result)", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + }, + { + "case": "unknown_contract.post.document", + "codes": ["E0004"], + "source": [ + "module contract.bindings", + "air 0", + "lang 0.1", + "features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]", + "fn @f(%result: u64) -> u64", + "effects []", + "entry:", + " contract.post.document @yes(%result)", + " ret %result", + "fn @yes() -> bool", + "effects []", + "entry:", + " %t = const.bool true", + " ret %t" + ] + } + ] +} diff --git a/docs/design/contract-invariant-boundaries.md b/docs/design/contract-invariant-boundaries.md index 95cde1d..2413689 100644 --- a/docs/design/contract-invariant-boundaries.md +++ b/docs/design/contract-invariant-boundaries.md @@ -25,7 +25,7 @@ The claim is: every exposed checked value/shared content view satisfies its pred | Candidate operation | Type/transfer | Validation boundary | |---|---|---| | `checked.make checked, %r` | R → checked; move linear R, copy Copy R | observe the complete candidate through a temporary shared view; run p before exposing the result; false traps | -| `checked.view %c` | ref> → ref, dependent owned shared child | no new check; ordinary lifetime/loan rules preserve the established claim | +| `checked.view %c` | ref/mut> → ref, dependent owned shared child | no new check; ordinary lifetime/loan rules preserve the established claim | | `checked.take %c` | checked → R; consume linear capsule, copy Copy content | output is ordinary R with no invariant claim; live views block consuming the root | | `checked.modify %m, @f(args)` | mut>; direct callback f receives a temporary lent mut first, then ordinary typed arguments | suspend capsule access, call f, end its temporary mutation view, run p on the resulting R, then expose f's result | diff --git a/docs/design/contract-naming-vectors.json b/docs/design/contract-naming-vectors.json index 7297836..398e40a 100644 --- a/docs/design/contract-naming-vectors.json +++ b/docs/design/contract-naming-vectors.json @@ -140,6 +140,42 @@ "__aji_contract_1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338_1" ], "allocated": "__aji_contract_1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338_2" + }, + { + "kind": "pre", + "owner": "fn:app.work.bump", + "ordinal": 2, + "level": 0, + "group": 0, + "encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n2\n0\n0\n", + "digest": "c9f6aaa9419c3218c57598f9a73556160d402558e308c578bce6bd4af5bc293f", + "occupied": [], + "allocated": "__aji_contract_c9f6aaa9419c3218c57598f9a73556160d402558e308c578bce6bd4af5bc293f" + }, + { + "kind": "pre", + "owner": "fn:app.work.bump", + "ordinal": 10, + "level": 0, + "group": 0, + "encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n10\n0\n0\n", + "digest": "e6f22da69e00ebc6fef2fa201fce7f02e8ec4eeaff4bf57875ba70fac0fbfb5c", + "occupied": [], + "allocated": "__aji_contract_e6f22da69e00ebc6fef2fa201fce7f02e8ec4eeaff4bf57875ba70fac0fbfb5c" + } + ], + "ordering_cases": [ + { + "kind": "pre", + "owner": "fn:app.work.bump", + "input_ordinals": [ + 2, + 10 + ], + "sorted_ordinals": [ + 10, + 2 + ] } ] } diff --git a/docs/design/contract-source-and-module-state.md b/docs/design/contract-source-and-module-state.md index 79938fe..8cfa4e0 100644 --- a/docs/design/contract-source-and-module-state.md +++ b/docs/design/contract-source-and-module-state.md @@ -92,15 +92,15 @@ LEVEL\n GROUP\n ``` -The owner length is canonical decimal and counts bytes. The length prefix makes components unambiguous; full tuples/bytes, not digests, determine identity and reuse. The descriptor adds bounded fixed overhead to its bounded owner; it does not tighten the existing ordinary specialization-key limit. The AIR base is `__aji_contract_` plus lowercase SHA-256 of these bytes. Sort artifacts lexicographically by complete encoding bytes, then allocate the smallest unused positive `_1`, `_2`, ... suffix when the base is occupied. Reserve each allocation immediately; handle a digest collision identically to an original-name collision. No user identifier prefix is reserved. +The owner length is canonical decimal and counts bytes. The length prefix makes components unambiguous; full tuples/bytes, not digests, determine identity and reuse. The descriptor adds bounded fixed overhead to its bounded owner; it does not tighten the existing ordinary specialization-key limit. The AIR base is `__aji_contract_` plus lowercase SHA-256 of these bytes. Sort artifacts lexicographically by complete encoding bytes, then allocate the smallest unused positive `_1`, `_2`, ... suffix when the base is occupied. Decimal fields compare as text: ordinal 10 sorts before 2, and owner length 100: before 16:. This is artifact emission order, not clause evaluation order, which remains lexical. Reserve each allocation immediately; handle a digest collision identically to an original-name collision. No user identifier prefix is reserved. Emit ordinary types followed by snapshot types in artifact order, then ordinary functions followed by helper/witness functions in artifact order; each category retains today's original/generic ordering. Ordinary specialization counters retain their meaning, including specialized invariant declarations; helpers/snapshot records are not additional generic instantiations. All emitted types/functions/instructions/arguments count toward the ordinary AIR limits, including documented helpers and unused witnesses. No new unbounded generation exemption or private runtime storage is introduced. A contract-free input creates no descriptors and keeps today's canonical bytes. -Use the defining declaration/clause map rather than reversing a mangled name. The witness header/ret map to its invariant declaration. A pre/post prefix site maps to its bool expression; the old prefix/collector header map to the first executable old occurrence. Predicate/collector instructions preserve each original expression/subexpression span. Snapshot struct declarations and packing/projection operations map to the first old slot they represent. Explicit checked operations map to the source operation; implicit/tail returns retain today's return/tail span. Helper call/parameter adaptation maps to the source argument/root that caused it, not the surrounding generated name. Repeated generic specializations retain template spans; supplied static/type argument errors retain application spans. In a clause helper, its header/parameter facts map to that clause expression; a named external helper retains its own header and body spans. +Use the defining declaration/clause map rather than reversing a mangled name. The witness header/ret map to its invariant declaration. A pre/post prefix site maps to its bool expression; the old prefix/collector header map to the first executable old occurrence. Predicate/collector instructions preserve each original expression/subexpression span. Snapshot struct declarations and packing/projection operations map to the first old slot they represent. Explicit checked operations map to the source operation; implicit/tail returns retain today's return/tail span. Helper call/parameter adaptation maps to the source argument/root that caused it, not the surrounding generated name. A deduplicated capture binding maps to the first lexical occurrence of that root/form in its clause; old's capture union uses the first such occurrence across its executable old expressions. A post's snapshot argument maps to its first old occurrence, including a documented reuse; result forms map to their first corresponding result occurrence. Repeated generic specializations retain template spans; supplied static/type argument errors retain application spans. In a clause helper, its header/parameter facts map to that clause expression; a named external helper retains its own header and body spans. The lowering output carries a separate typed declaration map `(canonical source declaration name, witness function identity, declaration span)` for inventory provenance. It is not parsed from comments or consumed as semantic evidence; verified signature/body/type identity still controls the inventory record. Runtime dispatch retains both the installing site and evaluated boundary, so a post failure reports its clause plus the actual ret separately. Missing exact mappings use the existing primary fallback; related positions omit source coordinates instead of borrowing another mapping. Complete dispatch/trap schema and AIR0 compatibility remain separate gates. -[Naming vectors](contract-naming-vectors.json) retain three current-language source groups at `8df6cac` (ten CLI checks): a generic base plus _1 collision allocates _2, two calls with the same static-function key reuse one specialization, and flattened module-name collisions allocate _2/_3 in canonical module order. Runs return 42 with fuel 10,000. Tested comment/position changes, path changes and import/mapping permutations preserve AIR bytes. Seven proposed artifact descriptors separately pin encoding, digest and collision allocation; hashlib and sha256sum agree. They are design vectors, not implemented contract-helper output. +[Naming vectors](contract-naming-vectors.json) retain three current-language source groups at `8df6cac` (ten CLI checks): a generic base plus _1 collision allocates _2, two calls with the same static-function key reuse one specialization, and flattened module-name collisions allocate _2/_3 in canonical module order. Runs return 42 with fuel 10,000. Tested comment/position changes, path changes and import/mapping permutations preserve AIR bytes. Nine proposed artifact descriptors separately pin encoding, digest and collision allocation; hashlib and sha256sum agree. The follow-up ordinal 2/10 pair pins text-byte ordering. They are design vectors, not implemented contract-helper output. ## Representation, properties and positions diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index b4235f8..c005be4 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -413,6 +413,8 @@ The [property/inventory refinement](contract-source-and-module-state.md#represen The next candidate fixes contract artifact name encoding/order and typed declaration maps, with three naming groups (ten CLI checks) and seven hash/collision vectors. Global P-before-S subpasses, bounded shortest-call witnesses and isolated return/post collection now have concrete rules; five current-language return probes preserve existing leak/early-return code lists and six graph vectors validate proposed witness selection. These remain unimplemented research constraints. Complete binding/diagnostic/trap schemas, compatibility, model adoption and vertical delivery remain open. +The [AIR binding grammar](contract-air-bindings.md) now proposes exact prefix/checked spellings, root descriptors, observation adaptation and E8001 reason/field shapes. Eighteen ordinary view/call/unknown-opcode probes confirm existing constraints, including optional never-call result bindings and the difference between an owner root and a complete Copy place. Candidate grammar is not adopted spec; source reasons, trap/dispatch schemas, compatibility, model adoption and vertical delivery remain gates. + ## 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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index be28dce..73454b8 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -362,3 +362,5 @@ The property/type-position audit exposed a pre-existing accounted-size defect ([ The [property/inventory refinement](../design/contract-source-and-module-state.md#representation-properties-and-positions) specifies candidate complete representation/position checks, inherited properties, recursive endpoint gates, dedicated representation traversal, forbidden zero manufacture, size versus ABI and representation-only result rendering. The inventory's universal raw-R proof is distinct from construction-site proofs and supplied declaration provenance. Twelve prior property baselines match `4cda448`; eight new reproducible vectors verify ordinary identity/content restrictions and the Range predicate. The report research component includes six sites, seven boundaries and three checked identities with distinct type/site proofs. These are current-language/design checks, not implemented contracts. Claude's earlier property audit is incorporated; the live Herdr channel is unavailable for fresh review. Mangling/source-map, diagnostics/dispatch, compatibility and owner model selection remain gates; RFC 0039 stays Draft and full P6-6 remains doing. The [naming/provenance candidate](../design/contract-source-and-module-state.md#generated-names-and-source-provenance) fixes full descriptor bytes, ordinary-first collision allocation, emission categories and clause/witness maps. Three current-language naming groups pass ten CLI checks; seven proposed descriptors agree under two SHA-256 implementations. The [diagnostic refinement](../design/contract-accounting-and-status.md#collection-at-returns) preserves ordinary return/leak facts while isolating virtual post checks, orders required P/S subpasses, and bounds shortest real-call witnesses. Five executed return baselines and six graph vectors independently verify current constraints and proposed selection. No semantic/code/registry change is made; the vectors are not new-contract conformance. Binding/source-reason/trap schemas, Q-055 compatibility, owner adoption and full vertical implementation remain gates; RFC 0039 stays Draft and full P6-6 remains doing. + +The [AIR binding candidate](../design/contract-air-bindings.md) supplies prefix/type/operation grammar, explicit root/form identity, exact shared adaptation, snapshot-use checks and proposed E8001 reasons/fields. Eighteen current-language probes verify view/alias/never-call constraints and isolated E0004 rejection of complete candidate prefixes. Claude independently reproduced all eighteen and the nine descriptor hashes/order cases; review clarified linear checked root access, repeated Copy-place budgets, SSA/root priority, source dedup positions and stable return-fact ordering. This is non-normative design evidence, with no implementation or registry change. Source reasons, trap/dispatch schema, compatibility, owner adoption and vertical tests remain gates; RFC 0039 stays Draft and P6-6 remains doing. diff --git a/docs/rfcs/0039-verifier-visible-contracts.md b/docs/rfcs/0039-verifier-visible-contracts.md index 32428fd..c19aa98 100644 --- a/docs/rfcs/0039-verifier-visible-contracts.md +++ b/docs/rfcs/0039-verifier-visible-contracts.md @@ -155,9 +155,11 @@ Module invariants need a definition of their roots and observation boundaries. S The candidate distinguishes a persistent checked state root owning correlated values from a boundary relation over separately owned roots and an explicit function set. Their audit scopes and coverage claims must differ. The [module/source refinement](../design/contract-source-and-module-state.md) proposes a narrow named binding for caller-owned checked state, collision-safe type.checked syntax, independent type-level audit claims and eager snapshot/capture rules. Its property/position refinement preserves representation properties and recursive transfer gates, prohibits zero manufacture, keeps accounted size separate from ABI and proposes representation-only JSON rendering. The exact type inventory classifies predicates over raw universal representations, separately from make sites and source provenance. Twenty current-language property baselines constrain these rules; no checked feature, type proof or inventory is implemented. It adds no boundary-group or hidden-global abstraction. Rooted state as the module-invariant model remains an owner decision; source-map/mangling, diagnostics/dispatch and vertical integration remain open. Ordinary pre/post reuse alone must not silently redefine module invariants. -The source refinement also fixes descriptor encodings, collision order, emission categories and exact clause/witness maps; three current-language naming groups and seven proposed descriptors constrain the candidate. The accounting refinement specifies global P-before-S diagnostic subpasses, shortest real-call witnesses with bounded head/tail facts, and isolated post/ordinary-return collection preserving legacy leak and early-return lists. Five current-language return probes and six independent graph vectors check those constraints. This is design evidence; neither new diagnostics nor contract dispatch are implemented. +The source refinement also fixes descriptor encodings, collision order, emission categories and exact clause/witness maps; three current-language naming groups and nine proposed descriptors constrain the candidate, including decimal byte-order cases. The accounting refinement specifies global P-before-S diagnostic subpasses, shortest real-call witnesses with bounded head/tail facts, and isolated post/ordinary-return collection preserving legacy leak and early-return lists. Five current-language return probes and six independent graph vectors check those constraints. This is design evidence; neither new diagnostics nor contract dispatch are implemented. -Remaining decisions: shared observation coverage (Q-057) and invariant-evaluation interactions; complete AIR binding grammar and source diagnostic reason allocations; purity/snapshot diagnostic schemas and format-0 compatibility; final feature/status policy adoption; invariant/module model adoption; traps/run-record schema and tested pending-return dispatch. The RFC stays Draft until these have concrete rules and counterexamples, followed by full vertical delivery. +The [AIR binding candidate](../design/contract-air-bindings.md) gives complete prefix/type/operation spellings, discriminated parameter/snapshot/result observations, exact adaptation and candidate E8001 reasons/fields. It preserves ordinary never-call binding forms and distinguishes whole checked observation from representation access. Eighteen current-language view/call/opcode probes constrain the proposal; they do not implement it or settle format-0 compatibility. + +Remaining decisions: shared observation coverage (Q-057) and invariant-evaluation interactions; source diagnostic reason allocations; final purity/snapshot schema adoption and format-0 compatibility; final feature/status policy adoption; invariant/module model adoption; traps/run-record schema and tested pending-return dispatch. The RFC stays Draft until these have concrete rules and counterexamples, followed by full vertical delivery. ## Compatibility and integration