tests: audit swap leak and remaining source rule boundaries

This commit is contained in:
dev committed 2026-10-08 22:25:42 +03:00
1 parent 03305f0957
commit ee09a7a290
12 files changed
+408 -10

No files matched your search

+2 -2
View File
@@ -46,13 +46,13 @@ 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. 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.
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. For an E3002 `borrow` identity produced by `value.swap`, only a unique direct enum.make replacement with a named enum declaration is supported. Its nominal family remains distinct from other enum, owner or resource families; unsupported replacement producers 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.
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 a single E0006 `feature_not_declared` pair, `feature_header_context: true` permits different unrelated declared features. Each diagnostic's `canonical_header` must first equal the sorted union of its module's unique feature header and the verifier-provided `closure`. The comparison then replaces only that repair header with the missing closure set; feature, reason, construct and all other facts remain exact. Invalid/missing closures, dependency errors and malformed repair headers fail closed. Source/raw payload mapping stays exact, including the repair header. This witness does not infer dependencies or support other E0006 reasons.
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.
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 linear swap-leak row also compares its named type table and pins the array/unpack plus the specific enum arm that leaks; another arm with the same diagnostic and operation counts cannot replace it. 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.
+165
View File
@@ -1546,6 +1546,171 @@
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a78",
"rule": "Only registered intrinsic names emit AIR intrinsic calls. An undeclared io.teleport in source is ordinary E7002 name resolution, not an unknown AIR intrinsic; user functions are emitted as ordinary calls."
},
"phase3/reject/channels_endpoint_element.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/04-concurrency-and-atomics.md \u00a738.1; docs/spec/15-source-language.md \u00a710",
"rule": "channel.make has sender<u64> elements, requiring reserved channel_transfer. Both sides retain that feature/construct at channel.make; this diagnostic supplies no closure or canonical repair header."
},
"phase3/reject/select_target_arity.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a77",
"rule": "A select send closed edge omits its unsent value binding. Source checks the authored binding list before emitting a continuation, with outcome closed and expected 1.",
"analogues": [
{
"source": "source/reject_twins/analogue_select_closed_arity.aji",
"codes": [
"E7005"
],
"fields": {
"outcome": "closed",
"expected": "1"
}
}
]
},
"phase4/reject/iref_eq_types.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a78; \u00a710",
"rule": "Equality compares iref<u64> and iref<u8>. Source checks operand types before emitting iref.eq.",
"analogues": [
{
"source": "source/reject_twins/analogue_iref_eq_types.aji",
"codes": [
"E7005"
],
"fields": {
"expected": "iref<u64>",
"found": "iref<u8>"
}
}
]
},
"phase4/reject/island_alloc_via_ref.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a78; \u00a710",
"rule": "island.alloc receives a named shared ref<island<u64>> binding; allocation requires a named exclusive binding. Source rejects before AIR with found; it supplies no expected field.",
"analogues": [
{
"source": "source/reject_twins/analogue_island_alloc_ref.aji",
"codes": [
"E7005"
],
"fields": {
"found": "ref<island<u64>>"
}
}
]
},
"phase3/reject/cancel_shield_order.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a73; \u00a77",
"rule": "Source shields nest by construction and end in reverse order on every normal exit. Shield handles are not source values and cannot be block arguments. The reversed ending/renamed-stack context of this AIR cannot be authored."
},
"phase3/reject/cfg_provenance_shield_order.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a73; \u00a77",
"rule": "Source shields nest by construction and end in reverse order on every normal exit. Shield handles are not source values and cannot be block arguments. The reversed ending/renamed-stack context of this AIR cannot be authored."
},
"phase3/reject/cfg_provenance_shield_stack_join.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a73; \u00a77",
"rule": "Source shields nest by construction and end in reverse order on every normal exit. Shield handles are not source values and cannot be block arguments. The reversed ending/renamed-stack context of this AIR cannot be authored."
},
"phase3/reject/cfg_provenance_scope_alone.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a74; \u00a77",
"rule": "A source scope name is only a lexical identifier for task.spawn, never an ordinary assigned or yielded value. The renamed scope block parameter that is the subject of this AIR regression cannot be emitted. A plain unjoined-child E4301 would drop that context."
},
"phase3/reject/cfg_provenance_scope_task.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a74; \u00a77",
"rule": "A source scope name is only a lexical identifier for task.spawn, never an ordinary assigned or yielded value. The renamed scope block parameter that is the subject of this AIR regression cannot be emitted. A plain unjoined-child E4301 would drop that context."
},
"phase3/reject/cfg_provenance_guard_parent.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a73; \u00a77",
"rule": "The lock guard is never a source value; source branches inside the lock use the originating guard rather than transferring it as a block argument. This AIR regression explicitly forwards the guard through br before ending its parent, a context with no implemented source spelling."
},
"modules/nominal_call.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a75; \u00a710; \u00a714.2",
"rule": "A function receives a structurally identical but nominally distinct struct. The source analogue uses two local nominal declarations rather than package linking; the checked argument-type mismatch precedes AIR.",
"analogues": [
{
"source": "source/reject_twins/analogue_nominal_call.aji",
"codes": [
"E7005"
],
"fields": {
"expected": "@PairA",
"found": "@PairB"
}
}
]
},
"phase0/reject/syntax_error.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "The missing comma is in the AIR text operand grammar, which source does not expose. A source syntax error uses a different grammar and E7001; malformed generated AIR instead reports E7900 as a compiler bug."
},
"phase2/reject/no_capability_comparison.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a78; \u00a710",
"rule": "eq.cap is not an AIR opcode and its undefined result adds E5001. Source equality on capabilities rejects by its operand type rule, before AIR; it cannot emit this absent opcode and invalid SSA context."
},
"phase5/reject/add_bool.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710; \u00a712",
"rule": "atomic.add.wrap is used on a bool cell with a bool operand. Source checks its integer-cell requirement before emitting the operation; found remains bool. Source anchors this at the bool value operand; AIR anchors it at the ref<atomic<bool>> cell operand.",
"analogues": [
{
"source": "source/reject_twins/analogue_atomic_add_bool.aji",
"codes": [
"E7005"
],
"fields": {
"found": "bool"
}
}
]
},
"linear/builtin_take.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a75; \u00a716",
"rule": "alloc_error is a Copy built-in enum. Ordinary Copy matches emit enum.switch, and move of a Copy value outside specialization is rejected; even specialized Copy matches remain non-consuming. Source cannot emit enum.take for this built-in."
},
"linear/copy.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a75; \u00a716",
"rule": "An aggregate containing own<u64> is linear. Plain named use in a consuming initializer requires move (E7003); move transfers rather than duplicates the aggregate. The source frontend cannot emit AIR copy of this linear struct."
},
"phase0/reject/unknown_opcode.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a78; \u00a710",
"rule": "Source has no spelling for arbitrary AIR opcodes. An unknown function name rejects in name resolution; the frontend emits only registered operations, so frobnicate plus the resulting undefined SSA value is an AIR-only malformed module."
},
"phase2/reject/borrow_parameter_not_from_allocation.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a74; \u00a75; \u00a719",
"rule": "The regression passes a borrow through br as a block parameter, requiring reserved borrow_joins. A source borrow is bound lexically by ref/mut, cannot be assigned as a variable or yielded by a nested block, if or match, and cannot reach the generated join as an ordinary value. No source spelling preserves this borrow-parameter context."
},
"linear/swap_leak.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/03-memory-model.md \u00a725; docs/spec/15-source-language.md \u00a716",
"rule": "The array.make/unpack owner enters Maybe::some; value.swap replaces it with none. The original complete value is consumed only on the slot some arm and leaks at ret on the slot none arm. Full type tables and pinned AIR/source/lowering preserve that branch context; operation counts alone would allow leaking on the other arm.",
"match_type_declarations": true,
"audited_context": {
"air": "ffd1b3ae7fd6462601c7dd9044322d9d430ef798fa645b67763d0316df44c831",
"sources": {
"source/reject_twins/linear_swap_leak.aji": "c675d231336f17eadb39d7e63138a1c1b67500c464c59b09f31cb7ea1ff66ed5"
},
"lowered": {
"source/reject_twins/linear_swap_leak.aji": "6f9fa0d8ef40b75951c2a2042d1d171c221268301df18b38775b74a47f606cc7"
}
}
}
}
}
@@ -0,0 +1,14 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §10; §12
module test.bool
fn main() -> bool effects [atomic] {
let t = true;
let c = atomic.new(t);
{
ref r = c;
let x = atomic.add.wrap(r, t, seq_cst); // diagnostic here: t, seq_cst
}
return atomic.take(move c);
}
@@ -0,0 +1,10 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §8; §10
module test.iref_eq_types
fn same(a: iref<u64>, b: iref<u8>) -> bool effects [] {
return a == b; // diagnostic here: b;
}
fn main() -> void effects [] {}
@@ -0,0 +1,14 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §8; §10
module test.island_alloc_via_ref
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let i = island.create(1u64, heap) or trap;
{
ref g = i;
let r = island.alloc(g, 1u64) or trap; // diagnostic here: g, 1u64
}
island.destroy(move i);
return 1;
}
@@ -0,0 +1,21 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §5; §10; §14.2
module test.nominal
struct PairA {
value: u64
}
struct PairB {
value: u64
}
fn total(pair: PairA) -> u64 effects [] {
return pair.value;
}
fn main() -> u64 effects [] {
let pair = PairB { value: 42u64 };
return total(pair); // diagnostic here: pair);
}
@@ -0,0 +1,16 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §7
module test.select_target_arity
fn f(tx: sender<u64>, x: u64) -> sender<u64> effects [task.wait] {
select {
send(tx, x) {
ok => {}
closed => {} // diagnostic here: closed =>
} cancelled(v) => {}
}
return move tx;
}
fn main() -> void effects [] {}
@@ -0,0 +1,18 @@
// expect: reject E0006
// phase: 6
// spec: docs/spec/04-concurrency-and-atomics.md §38.1; docs/spec/15-source-language.md §10
// AIR twin: phase3/reject/channels_endpoint_element.air
module test.channels_endpoint_element
fn f(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
match channel.make<sender<u64>>(1, heap) { // diagnostic here: channel.make
ok(tx, rx) => {
trap;
}
err(e) => {
trap;
}
}
}
fn main() -> void effects [] {}
@@ -0,0 +1,41 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16
// AIR twin: linear/swap_leak.air
module test.linear
enum Maybe {
some(own<u64>),
none
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let n = 42u64;
match own.new(n, heap) {
ok(owner) => {
let items = [move owner];
let (part) = array.unpack(move items);
var slot: Maybe = Maybe::some(move part);
let old = value.swap(mut slot, Maybe::none);
match move slot {
Maybe::some(extra_owner) => {
own.free(move extra_owner);
match move old {
Maybe::some(answer_owner) => {
return own.take(move answer_owner);
}
Maybe::none => {
return n;
}
}
}
Maybe::none => {
return n; // diagnostic here
}
}
}
err(e) => {
return n;
}
}
}
+75 -3
View File
@@ -167,6 +167,19 @@ class CoverageFailures(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'missing diagnostic-identity use witness'):
self.verify_fake(row)
def test_endpoint_rule_cannot_substitute_mutex_for_channel_creation(self):
row = self.fake_pair(source_path='source/reject_twins/channel_endpoint_element.aji',
air_path='phase3/reject/channels_endpoint_element.air')
self.verify_fake(row)
p = self.corpus / 's.aji'
p.write_text('// expect: reject E0006\n// AIR twin: a.air\n'
'module test.endpoint_mutex\n'
'fn f(tx: sender<u64>) -> void effects [] {\n'
' let m = mutex.make(move tx); // diagnostic here: mutex.make\n'
' trap;\n}\nfn main() -> void effects [] {}\n')
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def task_parameter_pair(self):
row = self.fake_pair(source_path='source/reject_twins/task_handle_parameter.aji',
air_path='phase3/reject/tasks_handle_as_parameter.air')
@@ -256,9 +269,7 @@ class CoverageFailures(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'mapping changed rule facts'):
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')
def pin_pair_context(self, row):
p = self.corpus / 's.aji'
canonical = twins.command(AJI, 'lower', p, status=0)
row['audited_context'] = {
@@ -268,6 +279,67 @@ class CoverageFailures(unittest.TestCase):
}
return row
def audited_cfg_pair(self, source='cfg_provenance_loan_br', air='cfg_provenance_loan_br'):
return self.pin_pair_context(self.fake_pair(
source_path=f'source/reject_twins/{source}.aji',
air_path=f'phase3/reject/{air}.air'))
def swap_pair(self):
return self.fake_pair(source_path='source/reject_twins/linear_swap_leak.aji',
air_path='linear/swap_leak.air')
def test_swapped_enum_nominal_family_cannot_change(self):
row = self.swap_pair()
self.verify_fake(row)
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('Maybe', 'OtherEnum'))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_swap_replacement_call_needs_a_separate_identity_audit(self):
row = self.swap_pair()
p = self.corpus / 's.aji'
text = p.read_text().replace('value.swap(mut slot, Maybe::none)',
'value.swap(mut slot, replacement())')
p.write_text(text + '\nfn replacement() -> Maybe effects [] { return Maybe::none; }\n')
self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002'])
with self.assertRaisesRegex(ValueError, 'swapped enum replacement lacks a named enum declaration'):
self.verify_fake(row)
def test_swap_leak_cannot_omit_audited_array_unpack(self):
row = self.swap_pair()
row['match_type_declarations'] = True
self.pin_pair_context(row)
self.verify_fake(row)
p = self.corpus / 's.aji'
text = p.read_text()
text = text.replace(' let items = [move owner];\n', '')
text = text.replace(' let (part) = array.unpack(move items);\n', '')
p.write_text(text.replace('Maybe::some(move part)', 'Maybe::some(move owner)'))
self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002'])
with self.assertRaisesRegex(ValueError, 'audited source changed'):
self.verify_fake(row)
def test_same_swap_leak_on_other_arm_cannot_replace_audited_branch(self):
row = self.swap_pair()
row['match_type_declarations'] = True
self.pin_pair_context(row)
self.verify_fake(row)
p = self.corpus / 's.aji'
text = p.read_text()
start = text.index(' match move old {')
end = text.index('\n }\n Maybe::none', start)
consuming = text[start:end]
text = text[:start] + ' return n; // diagnostic here' + text[end:]
leaking = ' return n; // diagnostic here\n }'
# Put the existing consumption on the none arm instead of the some arm.
index = text.index(' Maybe::none => {\n' + leaking)
text = text[:index] + text[index:].replace(leaking, consuming + '\n }', 1)
p.write_text(text)
self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002'])
with self.assertRaisesRegex(ValueError, 'audited source changed'):
self.verify_fake(row)
def test_straight_line_loan_cannot_replace_audited_handoff(self):
row = self.audited_cfg_pair()
self.verify_fake(row)