74 lines
14 KiB
Markdown
74 lines
14 KiB
Markdown
# Contract invariant boundaries: candidate and counterexamples
|
|
|
|
Non-normative research for [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), 2026-10-09. No feature, type, opcode, code or source spelling below is adopted. The full P6-6 gate remains open, including module scope, statuses and proof rules.
|
|
|
|
## Verified constraints
|
|
|
|
Probes with the existing compiler at `d041c07` contain no invariant declarations. They expose coverage requirements, not compiler defects. Runs use fuel 10,000.
|
|
|
|
| Probe | Result | Consequence |
|
|
|---|---|---|
|
|
| `Range {lo:0, hi:5}`; call `change(mut r.lo)` where `change(part: mut<u64>)` stores 10 | returns 1 for `lo > hi` | the callee's canonical AIR contains only `store %part, %value`; its signature/provenance does not identify the enclosing Range |
|
|
| ordinary `ValidRange {rep: Rep}` built by a checking library function; subsequently set `v.rep.lo = 10` | returns 1 for `lo > hi` | public fields bypass a constructor convention; spec 15 §14.2 permits imported construction and field access |
|
|
| two Counter roots; check `a.n <= b.n`, then change only a | returns 1 for failed relation | individual type claims or checks on a selected function set cannot imply a persistent relation between independent roots |
|
|
| AIR `type @Range = invariant @Rep @ordered` | E0001 | this declaration extension is outside spec 07 §8.7's E0004/E0006 exception |
|
|
| AIR parameter `checked<@Rep>` | E0004 alone, unknown type | a new type constructor has a different compatibility path |
|
|
|
|
The earlier RFC probes also demonstrate invalid Copy publication and shared-reader overflow during a repaired exclusive update. End-of-borrow checks alone miss both. A complete eager alternative must find every affected invariant ancestor after projected writes, including scalar callees, graph nodes and buffer storage in other cells. Current interpreter places carry a cell/path, not enclosing invariant instances. It would require additional provenance and predicate access rules, including how to read a whole root while an exclusive child freezes it.
|
|
|
|
## Leading type candidate: checked representation plus explicit update
|
|
|
|
Investigate `checked<R, @predicate>` in AIR, source `type.checked<R, fn predicate>` under the [module/source refinement](contract-source-and-module-state.md). The reserved type prefix avoids hijacking user modules/types named checked. Identity is structural over representation and resolved function identity. The predicate takes exactly `ref<R>`, returns bool, and has no captures or implicit roots. Source uses existing explicit function resolution/specialization rules; the refinement proposes a narrow checked-type binding, not a general alias facility. A generic representation is checked after concrete substitution.
|
|
|
|
The claim is: every exposed checked value/shared content view satisfies its predicate. An explicit update temporarily exposes ordinary R under exclusive access; R carries no such claim. Whole checked values retain R's Copy/linear, size and structural concurrency classifications, subject to a complete property audit. Copies and transfers need no additional check. The representation is initialized as a complete value, and checked types have no zero constructor even when R is zeroable.
|
|
|
|
| Candidate operation | Type/transfer | Validation boundary |
|
|
|---|---|---|
|
|
| `checked.make checked<R, @p>, %r` | R → checked<R,@p>; 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/mut<checked<R,@p>> → ref<R>, dependent owned shared child | no new check; ordinary lifetime/loan rules preserve the established claim |
|
|
| `checked.take %c` | checked<R,@p> → 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<checked<R,@p>>; direct callback f receives a temporary lent mut<R> 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 |
|
|
|
|
`make` needs an explicit new instruction-internal place for a complete Copy R candidate. Linear R is observed in its existing SSA cell, with no copy, move during validation or new frame local; only success transfers it into the capsule. Its predicate receives a dependent `ref<R>` preserving R itself rather than unwrapping an owner root. The view and every child end before exposure of the result and cannot escape through bool. This adds no general AIR/source addressability for Copy SSA or partially initialized/linear frame locals. The [accounting candidate](contract-accounting-and-status.md) charges size(R) only for the Copy place and retains pending results as SSA; use bounded activation storage, no program heap allocation. Existing `borrow.ref` on a Copy scalar or Copy struct SSA root rejects E1001; both baseline cases were independently verified. Their attempted `borrow.end` adds a dependent second E1001 because the invalid result has placeholder type void.
|
|
|
|
These are proposed operation contracts, not syntax sugar for optional assertions. Ordinary operations cannot project mutable R from a checked value. Interior changes through shared atomic/mutex/endpoint/arc interfaces do not affect the claim because their mutable observations are outside S below. Whole-value store/exchange replaces it with another checked value. Existing `local.alloc`, owners, regions, arrays, buffers, graph storage, channels and mutexes must transport the complete new type under their existing content restrictions; no field write can manufacture it from R. Nested checked values remain checked when an enclosing representation is extracted. A Copy `take` leaves the capsule and its claim intact, while its plain R copy carries no claim.
|
|
|
|
**Explicit update is necessary.** A linear representation with `buffer<T>` held behind a borrow cannot be consumed and rebuilt directly. Replacing its capsule would otherwise need another complete buffer and allocation authority even for an in-capacity update. `checked.modify` must permit this update without allocating a replacement. Limiting the candidate to Copy reconstruction would omit required linear-state behavior.
|
|
|
|
The callback can perform ordinary multi-field updates and use disjoint fields in structured tasks. Its complete effects and authority requirements propagate to the caller; ordinary critical-section/no-wait checks apply. It may return an ordinary borrow-free result, including an owned value removed through a complete initialized exchange. Void and never keep ordinary call/control rules: void binds no result, and a never callback cannot complete normally or publish an update. A borrow result or loan surviving the callback would escape unvalidated storage and must reject. It cannot re-enter the frozen capsule through another argument; ordinary overlapping-argument checks apply. No general borrow joins, holes or implicit cleanup are introduced.
|
|
|
|
Successful callback completion is not yet successful update completion. Predicate false, callback/predicate traps or fuel exhaustion publish no checked result. Failure traps with no rollback of state or external effects. Pending borrow-free results, including linear ones, must be retained and traced until validation finishes. Candidate fuel accounting is one unit for the make/modify operation, then ordinary helper instructions, with no synthetic callback-to-predicate instruction. Callback and predicate use normal call frames, sequentially; the callback frame ends before the predicate starts. Exact dispatch, temporary-view and trap rules still require RFC integration and tests. Checking after a callback must use a legal shared view after its exclusive loan has ended, not privileged access through a frozen ancestor.
|
|
|
|
The [runtime/context candidate](contract-runtime-and-context.md) now supplies concrete continuation, last-fuel, publication, depth/quantum, GC-root and failure-location rules for this sequence. Its executed evidence is ordinary calls/returns/traps, not checked updates. New callback/predicate transitions, pending linear results and context mapping still require normative adoption and vertical implementation/tests.
|
|
|
|
Candidate source surface is an explicit API under type.checked: a shared `ref raw = type.checked.view(parent)` binding, `type.checked.make::<R, fn p>`/`type.checked.take`, and `type.checked.modify::<fn update>(parent, args...)` on a named exclusive binding. Callback specialization uses existing static function identity, not a runtime function value. The module/source refinement gives grammar and clause-root rules; diagnostics and any later scoped block form still need integration. A block form must specify captures and effects before adoption.
|
|
|
|
## Stability is stronger than purity
|
|
|
|
The predicate closure P in RFC 0039 excludes atomic, mutex, channel, authority and ambient observations. Caller-visible observations currently either require exclusive access to change or are deeply immutable; opaque iref identity retains no external graph root. This is a soundness premise for persistent checked claims. A read-only predicate over interior-mutable data could become false after construction without any capsule update.
|
|
|
|
Define a candidate stable-observation closure S within P. All its caller-state observations must remain stable while the checked shared content is exposed. It uses the same direct-call closure and fresh-scratch proof; it does not imply totality. Initially the existing allowed observations satisfy this restriction. Future features must separately justify stable membership for their new operations; admitting a new operation to P alone is insufficient. Freeze each published classification rather than silently extending old invariants. Predicate construction/modification of checked values is excluded to avoid implicit validation dispatch; shared `checked.view` and Copy extraction of Data content are candidates for P/S. Data may admit checked<R,p> when R is Data, subject to publication rules. Compute membership with memoized opcode/type scans and direct-call edge elimination, O(F+C) per closure after local scans. Predicate membership is checked after ordinary SSA/type validation, before accepting the new type; exact diagnostic ordering remains a delivery rule.
|
|
|
|
Interior-mutable members need not be banned when the predicate ignores their mutable interior. A mutex containing ordinary data, an atomic field or a shared arc handle can still be held by R under ordinary rules. Their read/synchronization/count-changing operations stay outside S. Other allocations reached through unique owner/buffer/island roots inside R remain protected by the checked borrow ancestry; immutable frozen/arc content is stable. Audit this reasoning for every new observable primitive, rather than equating `effects []` with stability.
|
|
|
|
## Module claims require explicit roots and scope
|
|
|
|
AIR has one linked module, and source modules contain types/functions without globals or visibility. A module-state identity, hidden singleton or private-field policy cannot be inferred from spec 13's example.
|
|
|
|
Two claims need distinct representations and audit scopes:
|
|
|
|
- A persistent state-root invariant uses one caller-owned checked<State,p>. A State struct can own several correlated roots. Shared views are valid everywhere, including across modules; updates use the explicit primitive. Independent subroots can be lent to joined tasks during an update, but moving a root out relinquishes the joint state claim unless a complete valid replacement remains.
|
|
- A boundary relation over separately owned roots is a predicate mapped to the explicit input/result bindings of listed functions. It holds only at covered entry/normal-exit boundaries, through RFC 0039 pre/post obligations. Unlisted code or public field access can break it between calls. Reports must identify boundary scope and covered functions, never present it as an all-values invariant.
|
|
|
|
Choosing which source declaration spec 13 means by a module invariant, its root mapping and coverage rules remains part of the full gate. The state-root candidate supports explicit module state without adding globals; the boundary candidate does not provide hidden-state encapsulation. Neither closes that decision by changing the P6-6 requirement.
|
|
|
|
## Compatibility, cost and remaining delivery
|
|
|
|
The isolated type probe is not a complete AIR0 audit. Both Claude and the root independently checked full `checked<@Rep,@p>` spellings in seven positions: field, payload, parameter, return, borrowed parameter, block parameter and local allocation. Each aborts with E0004 alone. An opcode-first module with `checked.make`, `checked.take` and a normal use of the latter's result reports E0004, E0004, E5001. Together with the five initial probes and the two Copy-SSA borrow probes, all fifteen baseline cases were verified. These dependent errors retain the RFC 0039/0040 compatibility question (Q-055). No E0001 policy exception or format version is adopted here.
|
|
|
|
This candidate adds a type form, four semantic operations, stable-closure classification and pending update dispatch. It avoids hidden per-write checks and runtime ancestor hooks. That cost must be compared against complete eager/epoch models, not only their simplest examples. The feature must depend on the published predicate rules; nested linear observations additionally need RFC 0040. Definition-only paths must not weaken verifier budgets or initialization.
|
|
|
|
Delivery still needs registered features; exact grammar/type/function identity; closure and boundary diagnostics; false-invariant trap/status/report schemas; legal update/result/loan transfer rules; deterministic interpreter/native semantics; source lowering/formatter/generic/package coverage; and AIR/source positive/reject, GC and schedule tests. Mandatory cases include projected-callee bypass, invalid Copy escape, shared readers, borrowed linear in-place updates without new allocation, nested predicates, buffer/graph storage, mutex critical sections, callback results/traps/fuel, early exits and correlated roots. Measure normative/source/Quick Reference growth before acceptance; this research file is outside their manifests.
|
|
|
|
Claude's read-only review identified the missing linear update in the extraction-only design and distinguished state-root from boundary claims. The proposal remains a candidate; no static proof, unsafe construction mode or completed P6-6 implementation is claimed.
|