tests: preserve audited CFG loan handoff contexts

This commit is contained in:
dev committed 2026-10-08 21:57:27 +03:00
1 parent 50d1bb2c4b
commit fe63ae9586
12 files changed
+377 -8

No files matched your search

+3 -1
View File
@@ -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: <path>` 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.
+110
View File
@@ -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<T> 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."
}
}
}
@@ -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<mutex<u64>>) -> ref<u64> 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] {
@@ -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>) -> 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<u8> = 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);
}
}
@@ -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>) -> 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<u8> = 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);
}
}
@@ -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>) -> 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<u8> = 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);
}
}
@@ -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>) -> 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<u8> = 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);
}
}
@@ -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>) -> 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);
}
}
@@ -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 [] {}
+75
View File
@@ -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'):