From fe63ae95869b4b4ab474a1099641f784828a27f2 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Thu, 8 Oct 2026 21:57:27 +0300 Subject: [PATCH] tests: preserve audited CFG loan handoff contexts --- docs/plan/phase-6-source-language.md | 6 +- tests/conformance/README.md | 4 +- tests/conformance/reject-twins.json | 110 ++++++++++++++++++ .../source/borrow_returns/lock_escape.aji | 3 +- .../cfg_provenance_cancel_arg.aji | 34 ++++++ .../cfg_provenance_loan_access.aji | 28 +++++ .../cfg_provenance_loan_backedge.aji | 28 +++++ .../reject_twins/cfg_provenance_loan_br.aji | 29 +++++ .../reject_twins/cfg_provenance_loan_join.aji | 28 +++++ .../source/reject_twins/copy_overlapping.aji | 14 +++ tests/hosted/source_reject_twins.py | 75 ++++++++++++ tools/source_reject_twins.py | 26 ++++- 12 files changed, 377 insertions(+), 8 deletions(-) create mode 100644 tests/conformance/source/reject_twins/cfg_provenance_cancel_arg.aji create mode 100644 tests/conformance/source/reject_twins/cfg_provenance_loan_access.aji create mode 100644 tests/conformance/source/reject_twins/cfg_provenance_loan_backedge.aji create mode 100644 tests/conformance/source/reject_twins/cfg_provenance_loan_br.aji create mode 100644 tests/conformance/source/reject_twins/cfg_provenance_loan_join.aji create mode 100644 tests/conformance/source/reject_twins/copy_overlapping.aji diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index de384f9..c093ca0 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -320,8 +320,8 @@ Validation: unit tests and Zig formatting pass; full conformance is 1,655/1,655. ## P6-7 public rejection-twin audit (2026-10-08) -Verified same-code coverage is 79/199. Audited pairs cover owner/file/receiver leaks, use after transfer, authority/effects, unsafe calls, Send/Share, live task loans, mutex guards, graph content/access, atomic orders/effects, linear unpack/projection, buffer views/failure, static calls and recursive layouts. Independent markers verify instruction, outcome-block and function/type declaration positions. An island-destroy fixture retains a child object borrow and its subsequent load; witnesses preserve discarded-unpack and returned-buffer-failure contexts. Failed-send closed/cancelled edges converge at one source error, matching AIR's merged failure path. E3101 callee identities resolve to their explicit flat effect sets. Send/Share argument comparisons preserve the complete rejected parameter type while normalizing worker/SSA names; source/raw identities and related values remain identical. The producer lookup recognizes island.borrow as a borrow. Three buffer pairs retain shared-view push exclusion, reserve effects and capability kind. Error-value and borrowed-element analogues keep their source-prescribed E7xxx codes; missing feature/dependency headers and reserved primitive floats are AIR-only. A user nominal f64 lowers to @f64 and does not exercise the reserved primitive rule. Module-level cancellation activated by a shield helper preserves the join-wait rule; a taken mutex preserves E3001 on its next borrow. Linear match/unpack, buffer operand/outcome and file-mode analogues keep their prescribed source diagnostics. Legacy nested-owner/resource signatures require the now-published linear_aggregates header, generated automatically in source. Q-016 records the nominal f64 naming decision needed before primitive activation. The legacy reserved_feature comment describes its actual missing_dependency rejection; its body and permanent name are unchanged. The inventory retains 42 pending, 34 E7xxx analogues and 44 AIR-only cases, all still unmet under Q-053. P6-7 remains doing. +Verified same-code coverage is 86/199 across ownership/resources, borrows, effects/capabilities, tasks, graphs, atomics, linear aggregates and buffer operations. The inventory retains 32 pending, 34 prescribed E7xxx analogues and 47 AIR-only cases; all three categories remain unmet under the literal exit criterion (Q-053). P6-7 remains doing. -The diamond budget pair requires an identical named type-declaration table so equal-sized flat arrays cannot replace its shared nominal graph. Early cycle pairs, which produce no canonical AIR, pin both manually audited files with SHA-256; edits require a fresh context review while compiled diagnostics and positions remain checked. Exact opcode counts preserve the shared-view push function shape; an operand witness links the reported conflicting borrow to buffer.view, excluding ended decoys and views of other buffers. These are explicit fixture witnesses, not a second type/layout evaluator or proof of the manual audit. +The [checker documentation](../../tests/conformance/README.md) records the diagnostic-fact, independent-position and context witnesses. Named type tables preserve the nominal diamond; early cycle pairs pin the two artifacts that exist before lowering. Five CFG loan pairs pin original AIR, source and canonical lowering after a manual shape review: single br handoff, lend/plain merge, loop-carried loans, cancelled-handle forwarding and parent access after handoff. Direct cbr/switch arm-parameter cases remain pending: the tested source expressions instead pass handles to a later br merge. The guard-unlock pair retains the returned view's mutex.borrow ancestor through the generated unlock. Fingerprints attest unchanged artifacts, not audit correctness, and introduce no provenance or lifetime analysis. -Validation: full conformance is 1,688/1,688; unit tests, Zig formatting, all 41 checker regressions and the 79-pair source/AIR position check pass. All 46 source reject_twins fixtures pass collection before every instruction; source coverage remains 121/121. The completion gate still rejects partial coverage. Claude independently audited the two new same-code pairs, eleven E7xxx analogues and thirteen AIR-only classifications, including exact structured fields, markers and governing rules. Earlier exclusive-view, ended-view and other-buffer decoys remain covered by regressions and the opcode/operand witnesses. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes. +Validation: full conformance is 1,694/1,694; unit tests, Zig formatting, all 47 checker regressions and the 86-pair source/AIR position check pass. All 52 source reject_twins fixtures pass collection before every instruction; source coverage remains 121/121. The completion gate still rejects partial coverage. Claude independently verified all fifteen CFG fingerprints against another build, audited the seven new pairs and three AIR-only classifications, and confirmed the cross-shape/drift/guard-parent regressions. Existing Git attributes already force LF for pinned AIR/source files. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes. diff --git a/tests/conformance/README.md b/tests/conformance/README.md index efea220..cd42a7d 100644 --- a/tests/conformance/README.md +++ b/tests/conformance/README.md @@ -46,10 +46,12 @@ A key is a single lowercase word; header lines without a `key:` prefix are free- `python3 tools/source_reject_twins.py` checks audited pairs declared by free-form `// AIR twin: ` comments in source tests. These comments are separate from `equivalent`, which applies only to runs. `reject-twins.json` records each reviewed rule, governing spec and diagnostic site; a matching code alone does not establish a twin. -The check compares code multisets, diagnostic kinds, offending AIR operations, identity-field roles, root resource families and stable rule facts (including atomic orderings and budget limits). Resource families distinguish region/frozen/own/file modes; content types and ref/mut/slice forms do not distinguish these generic ownership/loan rules. For E3101, callee names resolve to their explicit flat effect sets; parameter/result types do not decide this effect rule. For E4001/E4002 argument errors, worker/SSA names are identities, while the complete rejected parameter type remains a fact. The worker must resolve to a declaration; its body/result does not decide the argument rule. Result-only E4001 retains the worker result contract and a distinct role. Unsupported identity rules fail closed. The small declaration/producer lookup is not a second type checker. Source diagnostics and E7xxx analogues must hit independent `// diagnostic here` markers. Lowered pairs also agree with canonical AIR and its annotations, including related positions. Source/raw identity fields and related values must agree exactly before original/source spellings are normalized. Several raw diagnostics at one source construct use the first-per-code/location projection required by spec 15 §10. Function/type budget headers use the marked source declaration and exact canonical name, since `--annotate` exposes block/instruction spans; generic/imported headers without a matching declaration fail closed. A by-value cycle rejected before lowering uses an explicit declaration mode; it does not claim generated AIR. +The check compares code multisets, diagnostic kinds, offending AIR operations, identity-field roles, root resource families and stable rule facts (including atomic orderings and budget limits). Resource families distinguish region/frozen/own/file modes; content types and ref/mut/slice forms do not distinguish these generic ownership/loan rules. For E3101, callee names resolve to their explicit flat effect sets; parameter/result types do not decide this effect rule. For E4001/E4002 argument errors, worker/SSA names are identities, while the complete rejected parameter type remains a fact. The worker must resolve to a declaration; its body/result does not decide the argument rule. Result-only E4001 retains the worker result contract and a distinct role. Unsupported identity rules fail closed. Guard-derived `mutex.borrow` results retain the borrow class; guard identities and the offending opcode remain distinct. The small declaration/producer lookup is not a second type checker. Source diagnostics and E7xxx analogues must hit independent `// diagnostic here` markers. Lowered pairs also agree with canonical AIR and its annotations, including related positions. Source/raw identity fields and related values must agree exactly before original/source spellings are normalized. Several raw diagnostics at one source construct use the first-per-code/location projection required by spec 15 §10. Function/type budget headers use the marked source declaration and exact canonical name, since `--annotate` exposes block/instruction spans; generic/imported headers without a matching declaration fail closed. A by-value cycle rejected before lowering uses an explicit declaration mode; it does not claim generated AIR. Case-specific `required_ops` optionally checks minimum operation counts in the diagnostic's function in both original and generated AIR. Cancelled-join regressions require their cancellation operations, so a plain task-loan error cannot replace them. `exact_ops: true` instead requires the full opcode count table of that function to match `required_ops`. The shared-view push case uses it to reject ended decoy views and additional plain borrows; it preserves the reviewed straight-line shape without computing lifetimes. `required_identity_uses` additionally requires the reported SSA identity to occur as an operand of the named opcode. The shared-view case links `conflicts_with` to `buffer.view`, excluding a view of another buffer. These strict witnesses retain both trap continuations; otherwise valid twins may need a separate audit. `match_type_declarations: true` additionally compares the complete named type-declaration tables, ignoring only comments/whitespace. The nominal diamond regression uses it so flat arrays of the same byte size cannot replace its shared type graph. AIR witnesses require a lowered same-code pair. These witnesses and diagnostic facts supplement the manual rule audit; they do not prove full dataflow equivalence. An analogue without structured rule fields relies on the reviewed construct and exact code/position; the check does not infer facts from message prose. +For lowered CFG cases whose diagnostic facts omit the handoff shape, `audited_context` pins three manually reviewed artifacts: the original AIR (`air`), each source file (`sources`) and its canonical UTF-8 lowering (`lowered`). Both maps must name exactly the declared twins; every value is a lowercase SHA-256 digest. Byte changes, including source comments/line endings and harmless lowering renames, require a fresh context review before updating the fingerprints. The regular compiled diagnostics, markers, raw mapping, related positions and lowering determinism remain checked. The five task-loan rows record their reviewed br/merge/back-edge/cancelled-handle contexts in `rule`; a straight-line error cannot replace them. These fingerprints attest unchanged artifacts, not the correctness of the manual audit, and add no provenance or lifetime analysis. Direct cbr/switch target-argument cases remain pending: source arm joins do not preserve those reviewed AIR shapes. + Early rejection produces no canonical AIR. Its mandatory `early_context` records SHA-256 fingerprints of both manually audited AIR/source files, alongside the rule audit; compiled code/kind/type and independent source positions still have to match. The fingerprints preserve the reviewed cycle shape, including long nominal chains and recursive arrays. They attest unchanged bytes, not the correctness of the audit. Any edit, including comments or line endings, requires a fresh context review before updating these fingerprints; do not regenerate them just to make a failed check pass. `--inventory` emits every current AIR rejection as JSON, including newly added unreviewed tests. Its `verification: metadata_only` output does not claim compiled verification. Rows are `same_code`, `source_error` (an audited E7xxx analogue), `air_only` (not authorable in the implemented source) or `pending`. The latter three remain unmet same-code rows. A successful ordinary check verifies the audited pairs against these checks; it does not prove P6-7 complete. `--require-complete` additionally fails until every AIR rejection has a verified same-code twin. Classification is a documented manual audit, not an automatic proof that a rule is inexpressible in source; the phase's literal exit criterion remains unchanged pending Q-053. diff --git a/tests/conformance/reject-twins.json b/tests/conformance/reject-twins.json index efcd6ff..57fabaf 100644 --- a/tests/conformance/reject-twins.json +++ b/tests/conformance/reject-twins.json @@ -1311,6 +1311,116 @@ "kind": "air_only", "spec": "docs/spec/15-source-language.md \u00a76", "rule": "Built-in error expressions lower to error.const with error_values and its closure. Source cannot choose the frozen legacy enum.make spelling for a built-in error family; user nominal enums use a distinct @Name type." + }, + "phase3/reject/cfg_provenance_loan_join.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a734", + "rule": "The lent and plain task branches converge through br edges on one task block parameter; borrow.end precedes its join.", + "audited_context": { + "air": "d63e844a9e4593546aa541f4d0d01e462e08a81bf966b8377916ef596db50747", + "sources": { + "source/reject_twins/cfg_provenance_loan_join.aji": "80828caf5c8384040b847c889c2b3bb8872a28b3e88a0678694987e4813c8807" + }, + "lowered": { + "source/reject_twins/cfg_provenance_loan_join.aji": "c909336bfc888a05db34d4941e70a0c83e5aa527d3453b1e0caeae7ec79000ec" + } + } + }, + "phase3/reject/cfg_provenance_loan_br.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a734", + "rule": "A lent spawn result reaches the diagnostic block parameter by one br edge before borrow.end and join. The source also joins an initial idle task before spawning the lent one.", + "audited_context": { + "air": "1e33c13ef44b53714f2bbb7a058626103e484c234c27a1848e5409d2707f83ae", + "sources": { + "source/reject_twins/cfg_provenance_loan_br.aji": "86dfb422ed925b536913f95f0f51b3a00884acaeb6963db61127b2bc8c8e0d39" + }, + "lowered": { + "source/reject_twins/cfg_provenance_loan_br.aji": "e74e73ba3e7bdbadd80009912bddb4c0f8dd269c41a9bdd34b0090fba4a2cb8b" + } + } + }, + "phase3/reject/cfg_provenance_loan_backedge.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a734", + "rule": "The loop header task parameter merges an initial plain spawn with the lent back-edge spawn; the cbr exit passes it to another task parameter before borrow.end and join.", + "audited_context": { + "air": "8acad722e2fae6094e79ed52c8f2d040bc54c3c8365da81e7fff81cc19446c17", + "sources": { + "source/reject_twins/cfg_provenance_loan_backedge.aji": "54e08ad1129020fb69e910fbc92fb20effa1d1fcf738b952bb47a165d0e7f86e" + }, + "lowered": { + "source/reject_twins/cfg_provenance_loan_backedge.aji": "35d6da75dd383edab75769a7ff4d939163ea5d2140f1b9fd9a29dd23399438a9" + } + } + }, + "phase3/reject/cfg_provenance_cancel_arg.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a734", + "rule": "The cancelled task.join.cancel outcome handle crosses an ordinary br into a task block parameter before borrow.end and join. The source first joins an extra idle task on both outcomes.", + "audited_context": { + "air": "720ac5ecfb56d2140f4b255ebc113074b0caf986a624c079f77e8d40058f0488", + "sources": { + "source/reject_twins/cfg_provenance_cancel_arg.aji": "1a79585e2410e8b5d18515df92757b9ad33f54d502d9b6347b0115a03b122563" + }, + "lowered": { + "source/reject_twins/cfg_provenance_cancel_arg.aji": "0b5394b7b1a32a500172ee6b8580f17aa0e045a35e171ca8c4bdb8f7a0767a84" + } + } + }, + "phase3/reject/cfg_provenance_loan_access.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a734", + "rule": "A task holding the lent exclusive borrow crosses an ordinary br into a task block parameter; its parent writes the lent borrow before joining that handle.", + "audited_context": { + "air": "07f458dba0325dd9961f59d48ad019323b3e18d407ddee49eefee6bb78866fd4", + "sources": { + "source/reject_twins/cfg_provenance_loan_access.aji": "a1a8d0002fcfce0178ad53223cca6cc445ef4066f520439ad4e7cc12c9701ee2" + }, + "lowered": { + "source/reject_twins/cfg_provenance_loan_access.aji": "cf19893fb50ceadef6b258ac261e48c9112669a42de63d5e8d28eb6a03e19645" + } + } + }, + "phase1/reject/copy_overlapping.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/08-verifier.md \u00a711", + "rule": "slice.copy writes the same mutable slice through which its source shared borrow is live. Named slice borrows avoid creating a separate earlier temporary-borrow error.", + "required_ops": { + "slice.copy": 1, + "borrow.ref": 1 + } + }, + "phase3/reject/sync_unlock_live_borrow.air": { + "kind": "same_code", + "site": "instruction", + "spec": "docs/spec/04-concurrency-and-atomics.md \u00a740", + "rule": "mutex.unlock consumes a guard while its mutex.borrow child is still live. A source return transfers the child and its ancestors but still emits the structured unlock, which rejects E2102.", + "required_ops": { + "mutex.borrow": 1, + "mutex.unlock": 1 + } + }, + "phase1/reject/copy_borrow.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a75", + "rule": "Source borrows are not Copy values and cannot be duplicated by copy. Ordinary alias binding is a different E7006 invalid_binding rule; ref/mut reborrowing emits a new borrow, never AIR copy of a borrow." + }, + "phase3/reject/sync_guard_parameter.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a73", + "rule": "guard is not a source type and the lock guard is never a source value. Unknown guard spelling or a user nominal @guard cannot produce the reserved AIR guard_transfer parameter rule." + }, + "phase3/reject/sync_guard_leak.air": { + "kind": "air_only", + "spec": "docs/spec/15-source-language.md \u00a77", + "rule": "Every normal exit of a source lock block emits explicit borrow endings and mutex.unlock. The guard is never a source value, so leaving that guard live at ret cannot be authored; traps terminate without a normal-path leak." } } } diff --git a/tests/conformance/source/borrow_returns/lock_escape.aji b/tests/conformance/source/borrow_returns/lock_escape.aji index e06d12d..20fb268 100644 --- a/tests/conformance/source/borrow_returns/lock_escape.aji +++ b/tests/conformance/source/borrow_returns/lock_escape.aji @@ -2,9 +2,10 @@ // expect: reject E2102 // phase: 6 // spec: docs/spec/15-source-language.md §19 +// AIR twin: phase3/reject/sync_unlock_live_borrow.air module test.returned_lock_view fn get(mr: ref>) -> ref from mr effects [task.wait] { - lock ref mr as count { ref result = count; return result; } + lock ref mr as count { ref result = count; return result; } // diagnostic here: return result cancelled { trap; } } fn main() -> u64 effects [task.wait] { diff --git a/tests/conformance/source/reject_twins/cfg_provenance_cancel_arg.aji b/tests/conformance/source/reject_twins/cfg_provenance_cancel_arg.aji new file mode 100644 index 0000000..1971650 --- /dev/null +++ b/tests/conformance/source/reject_twins/cfg_provenance_cancel_arg.aji @@ -0,0 +1,34 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34; docs/spec/15-source-language.md §4, §9 +// AIR twin: phase3/reject/cfg_provenance_cancel_arg.air +module test.cfg + +fn rd(p: ref) -> u8 effects [] { + return *p; +} + +fn idle() -> u8 effects [] { + return 0u8; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + var t: task = task.spawn(sc, idle); + { + ref part = data; // diagnostic here + let t0 = task.spawn(sc, rd, part); + match task.join_cancel(move t0) { + ok(v) => { + let ignored = task.join(move t); + return v; + } cancelled(t1) => { + let ignored = task.join(move t); + t = move t1; + } + } + } + return task.join(move t); + } +} diff --git a/tests/conformance/source/reject_twins/cfg_provenance_loan_access.aji b/tests/conformance/source/reject_twins/cfg_provenance_loan_access.aji new file mode 100644 index 0000000..2c27470 --- /dev/null +++ b/tests/conformance/source/reject_twins/cfg_provenance_loan_access.aji @@ -0,0 +1,28 @@ +// expect: reject E4101 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34; docs/spec/15-source-language.md §4, §9 +// AIR twin: phase3/reject/cfg_provenance_loan_access.air +module test.cfg + +fn rd(p: mut) -> u8 effects [] { + return *p; +} + +fn idle() -> u8 effects [] { + return 0u8; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + mut part = data; + var t: task = task.spawn(sc, idle); + loop { + let old = task.join(move t); + t = task.spawn(sc, rd, part); + break; + } + *part = 1u8; // diagnostic here + return task.join(move t); + } +} diff --git a/tests/conformance/source/reject_twins/cfg_provenance_loan_backedge.aji b/tests/conformance/source/reject_twins/cfg_provenance_loan_backedge.aji new file mode 100644 index 0000000..c327991 --- /dev/null +++ b/tests/conformance/source/reject_twins/cfg_provenance_loan_backedge.aji @@ -0,0 +1,28 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34; docs/spec/15-source-language.md §4, §9 +// AIR twin: phase3/reject/cfg_provenance_loan_backedge.air +module test.cfg + +fn rd(p: ref) -> u8 effects [] { + return *p; +} + +fn idle() -> u8 effects [] { + return 0u8; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + var t: task = task.spawn(sc, idle); + { + ref part = data; // diagnostic here + while false { + let old = task.join(move t); + t = task.spawn(sc, rd, part); + } + } + return task.join(move t); + } +} diff --git a/tests/conformance/source/reject_twins/cfg_provenance_loan_br.aji b/tests/conformance/source/reject_twins/cfg_provenance_loan_br.aji new file mode 100644 index 0000000..193a365 --- /dev/null +++ b/tests/conformance/source/reject_twins/cfg_provenance_loan_br.aji @@ -0,0 +1,29 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34; docs/spec/15-source-language.md §4, §9 +// AIR twin: phase3/reject/cfg_provenance_loan_br.air +module test.cfg + +fn rd(p: ref) -> u8 effects [] { + return *p; +} + +fn idle() -> u8 effects [] { + return 0u8; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + var t: task = task.spawn(sc, idle); + { + ref part = data; // diagnostic here + loop { + let old = task.join(move t); + t = task.spawn(sc, rd, part); + break; + } + } + return task.join(move t); + } +} diff --git a/tests/conformance/source/reject_twins/cfg_provenance_loan_join.aji b/tests/conformance/source/reject_twins/cfg_provenance_loan_join.aji new file mode 100644 index 0000000..e63d49e --- /dev/null +++ b/tests/conformance/source/reject_twins/cfg_provenance_loan_join.aji @@ -0,0 +1,28 @@ +// expect: reject E4302 +// phase: 6 +// spec: docs/spec/04-concurrency-and-atomics.md §34; docs/spec/15-source-language.md §4, §9 +// AIR twin: phase3/reject/cfg_provenance_loan_join.air +module test.cfg + +fn rd(p: ref) -> u8 effects [] { + return *p; +} + +fn idle() -> u8 effects [] { + return 0u8; +} + +fn main() -> u8 effects [task.spawn, task.wait] { + var data: u8 = zero; + scope sc { + let t = { + ref part = data; // diagnostic here + if true { + task.spawn(sc, rd, part) + } else { + task.spawn(sc, idle) + } + }; + return task.join(move t); + } +} diff --git a/tests/conformance/source/reject_twins/copy_overlapping.aji b/tests/conformance/source/reject_twins/copy_overlapping.aji new file mode 100644 index 0000000..20d761f --- /dev/null +++ b/tests/conformance/source/reject_twins/copy_overlapping.aji @@ -0,0 +1,14 @@ +// expect: reject E2101 +// phase: 6 +// spec: docs/spec/08-verifier.md; docs/spec/15-source-language.md §5 +// AIR twin: phase1/reject/copy_overlapping.air +module test.copy_overlapping + +fn f() -> void effects [] { + var x: [u8; 8] = zero; + mut s = x; + ref src = s; + slice.copy(s, src); // diagnostic here +} + +fn main() -> void effects [] {} diff --git a/tests/hosted/source_reject_twins.py b/tests/hosted/source_reject_twins.py index bf37319..cebc3bf 100644 --- a/tests/hosted/source_reject_twins.py +++ b/tests/hosted/source_reject_twins.py @@ -167,6 +167,81 @@ class CoverageFailures(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'missing diagnostic-identity use witness'): self.verify_fake(row) + def audited_cfg_pair(self, source='cfg_provenance_loan_br', air='cfg_provenance_loan_br'): + row = self.fake_pair(source_path=f'source/reject_twins/{source}.aji', + air_path=f'phase3/reject/{air}.air') + p = self.corpus / 's.aji' + canonical = twins.command(AJI, 'lower', p, status=0) + row['audited_context'] = { + 'air': hashlib.sha256((self.corpus / 'a.air').read_bytes()).hexdigest(), + 'sources': {'s.aji': hashlib.sha256(p.read_bytes()).hexdigest()}, + 'lowered': {'s.aji': hashlib.sha256(canonical.encode('utf-8')).hexdigest()}, + } + return row + + def test_straight_line_loan_cannot_replace_audited_handoff(self): + row = self.audited_cfg_pair() + self.verify_fake(row) + text = (REAL_CORPUS / 'source/cfg_provenance/tasks_end_lent_borrow.aji').read_text() + text = re.sub(r'^// AIR twin: .+$', '// AIR twin: a.air', text, flags=re.MULTILINE) + (self.corpus / 's.aji').write_text(text) + with self.assertRaisesRegex(ValueError, 'audited source changed'): + self.verify_fake(row) + + def test_single_handoff_cannot_replace_audited_loop_or_merge(self): + for air in ('cfg_provenance_loan_backedge', 'cfg_provenance_loan_join'): + with self.subTest(air=air): + row = self.audited_cfg_pair(source=air, air=air) + self.verify_fake(row) + text = (REAL_CORPUS / 'source/reject_twins/cfg_provenance_loan_br.aji').read_text() + text = re.sub(r'^// AIR twin: .+$', '// AIR twin: a.air', text, flags=re.MULTILINE) + (self.corpus / 's.aji').write_text(text) + with self.assertRaisesRegex(ValueError, 'audited source changed'): + self.verify_fake(row) + + def test_changed_audited_air_requires_a_fresh_review(self): + row = self.audited_cfg_pair() + self.verify_fake(row) + (self.corpus / 'a.air').write_text( + (REAL_CORPUS / 'phase3/reject/tasks_end_lent_borrow.air').read_text()) + with self.assertRaisesRegex(ValueError, 'audited AIR changed'): + self.verify_fake(row) + + def test_deterministic_lowering_drift_requires_a_fresh_review(self): + row = self.audited_cfg_pair() + self.verify_fake(row) + real_command = twins.command + def changed(aji, *args, status): + result = real_command(aji, *args, status=status) + if args[0] == 'lower' and '--annotate' not in args: + return result.replace('module test.cfg', 'module changed.cfg') + return result + with patch.object(twins, 'command', changed): + with self.assertRaisesRegex(ValueError, 'audited lowering changed'): + self.verify_fake(row) + + def test_lowered_context_cannot_omit_one_artifact(self): + row = self.audited_cfg_pair() + del row['audited_context']['lowered']['s.aji'] + self.manifest.write_text(json.dumps({'version': 1, 'cases': {'a.air': row}})) + # Manifest rows contain review facts, not computed inventory columns. + data = json.loads(self.manifest.read_text()) + for field in ('air', 'sources', 'codes'): + del data['cases']['a.air'][field] + self.manifest.write_text(json.dumps(data)) + with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest): + with self.assertRaisesRegex(ValueError, 'lowered context needs audited'): + twins.inventory() + + def test_guard_parent_end_cannot_replace_guard_unlock(self): + row = self.fake_pair(source_path='source/borrow_returns/lock_escape.aji', + air_path='phase3/reject/sync_unlock_live_borrow.air') + self.verify_fake(row) + (self.corpus / 'a.air').write_text( + (REAL_CORPUS / 'phase3/reject/cfg_provenance_guard_parent.air').read_text()) + with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): + self.verify_fake(row) + def test_same_code_different_atomic_operation_is_not_a_twin(self): row = self.fake_pair(air_name='load_release') with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): diff --git a/tools/source_reject_twins.py b/tools/source_reject_twins.py index 15472b8..569fcff 100644 --- a/tools/source_reject_twins.py +++ b/tools/source_reject_twins.py @@ -88,7 +88,7 @@ def inventory(): else: allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues', 'required_ops', 'exact_ops', 'required_identity_uses', - 'match_type_declarations', 'early_context'} + 'match_type_declarations', 'early_context', 'audited_context'} if set(review) - allowed: raise ValueError(f'{name}: unknown/reserved review keys: {sorted(set(review) - allowed)}') witnesses = review.get('required_ops', {}) @@ -111,7 +111,8 @@ def inventory(): raise ValueError(f'{name}: type-declaration witness must be true') if review['kind'] not in {'same_code', 'source_error', 'air_only'}: raise ValueError(f'{name}: invalid classification') - if ({'required_ops', 'exact_ops', 'required_identity_uses', 'match_type_declarations'} & review.keys()) and ( + if ({'required_ops', 'exact_ops', 'required_identity_uses', 'match_type_declarations', + 'audited_context'} & review.keys()) and ( review['kind'] != 'same_code' or review.get('lowering') == 'rejected'): raise ValueError(f'{name}: AIR witnesses require a lowered same-code pair') if not review.get('rule') or not review.get('spec'): @@ -137,6 +138,15 @@ def inventory(): raise ValueError(f'{name}: early rejection needs audited AIR/source fingerprints') elif 'early_context' in review: raise ValueError(f'{name}: early context requires rejected lowering') + if 'audited_context' in review: + context = review['audited_context'] + if (not isinstance(context, dict) or set(context) != {'air', 'sources', 'lowered'} or + any(not isinstance(context[key], dict) or set(context[key]) != set(sources) + for key in ('sources', 'lowered')) or + any(not isinstance(x, str) or not re.fullmatch(r'[0-9a-f]{64}', x) + for x in [context['air'], *context['sources'].values(), + *context['lowered'].values()])): + raise ValueError(f'{name}: lowered context needs audited AIR/source/lowered fingerprints') for analogue in review.get('analogues', []): if not analogue.get('codes') or any(not re.fullmatch(r'E7[0-9]{3}', c) for c in analogue['codes']): raise ValueError(f'{name}: source-error analogue must use E7xxx') @@ -209,6 +219,7 @@ def identity_class(air, d, value): whole-resource/loan rule: own/own are owners, and ref/slice forms are borrows. Resource families (region/frozen/own/file/...) must remain distinct. + island.borrow and mutex.borrow are explicit borrow producers. Unsupported producers fail closed and need a reviewed extension. """ function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', air, re.MULTILINE | re.DOTALL) @@ -233,7 +244,7 @@ def identity_class(air, d, value): if definition and value in [x.strip() for x in definition[1].split(',')]: op = definition[2] if op.startswith('borrow.') or op in {'slice.make', 'slice.sub', 'slice.split', - 'buffer.view', 'island.borrow'}: + 'buffer.view', 'island.borrow', 'mutex.borrow'}: return 'borrow' if op in producers: return producers[op] @@ -370,6 +381,13 @@ def type_declarations(air): def verify_pair(aji, root, row, source): air_path = CORPUS / row['air'] src_path = CORPUS / source + context = row.get('audited_context') + if context: + # Preserve a manually reviewed CFG artifact, not inferred loan facts. + if hashlib.sha256(air_path.read_bytes()).hexdigest() != context['air']: + raise ValueError('audited AIR changed; a new context audit is required') + if hashlib.sha256(src_path.read_bytes()).hexdigest() != context['sources'][source]: + raise ValueError('audited source changed; a new context audit is required') original = air_path.read_text() air_ds = errors(aji, air_path) ds = errors(aji, src_path) @@ -403,6 +421,8 @@ def verify_pair(aji, root, row, source): raise ValueError(f'{source}: early type error has different rule facts') return canonical = command(aji, 'lower', src_path, status=0) + if context and hashlib.sha256(canonical.encode('utf-8')).hexdigest() != context['lowered'][source]: + raise ValueError('audited lowering changed; a new context audit is required') if row.get('match_type_declarations') and type_declarations(original) != type_declarations(canonical): raise ValueError(f'{source}: different type-declaration context') if command(aji, 'lower', src_path, status=0) != canonical: