tests: audit buffer and error-value rejection twins

This commit is contained in:
dev committed 2026-10-08 21:21:42 +03:00
1 parent 2742867ef7
commit 5371eb7a2f
14 files changed
+273 -17

No files matched your search

+3 -3
View File
@@ -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 74/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. The legacy reserved_feature comment describes its actual missing_dependency rejection; its body and permanent name are unchanged. The inventory retains 82 pending, 17 E7xxx analogues and 26 AIR-only cases, all still unmet under Q-053. P6-7 remains doing.
Verified same-code coverage is 77/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. The legacy reserved_feature comment describes its actual missing_dependency rejection; its body and permanent name are unchanged. The inventory retains 68 pending, 23 E7xxx analogues and 31 AIR-only cases, all still unmet under 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. These are explicit fixture witnesses, not a second type/layout evaluator or proof of the manual audit.
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.
Validation: full conformance is 1,677/1,677; unit tests, Zig formatting, all 37 checker regressions and the 74-pair source/AIR position check pass. All 35 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 pairs, the ten additional E7xxx analogues and undefined-SSA classification, including their exact codes, fields, markers and normative basis. Renamed-worker, distinct-type and corrupted-identity probes supplement the earlier context regressions. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes.
Validation: full conformance is 1,680/1,680; unit tests, Zig formatting, all 41 checker regressions and the 77-pair source/AIR position check pass. All 38 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 new buffer pairs, six E7xxx analogues and five AIR-only cases. Its exclusive-view, ended-view and other-buffer decoy findings are covered by regressions and the opcode/operand witnesses. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes.
+1 -1
View File
@@ -48,7 +48,7 @@ A key is a single lowercase word; header lines without a `key:` prefix are free-
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.
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. `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.
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.
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.
+154
View File
@@ -895,6 +895,160 @@
"site": "instruction",
"spec": "docs/spec/06-resources-and-errors.md \u00a76.3",
"rule": "selected returns without consuming its owning parameter; source also invokes it through explicit specialization."
},
"buffers/reserve_missing_effect.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/15-source-language.md \u00a717",
"rule": "buffer.reserve requires explicit mem.alloc even when both outcomes trap."
},
"buffers/wrong_capability.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/15-source-language.md \u00a717",
"rule": "buffer.reserve is supplied cap<io.write> instead of the required cap<mem.alloc>."
},
"buffers/readonly_view_push.air": {
"kind": "same_code",
"site": "instruction",
"spec": "docs/spec/15-source-language.md \u00a717",
"rule": "buffer.push mutates a buffer while its shared buffer.view borrow is live, even when both outcomes trap.",
"required_ops": {
"borrow.ref": 1,
"buffer.view": 1,
"buffer.push": 1,
"const.u64": 1,
"trap": 2
},
"exact_ops": true,
"required_identity_uses": {
"conflicts_with": "buffer.view"
}
},
"error_values/no_authority.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "An error value cannot supply capability authority; the result type mismatch is source-decided E7005.",
"analogues": [
{
"source": "source/error_values/no_authority.aji",
"codes": [
"E7005"
],
"fields": {
"expected": "cap<mem.alloc>",
"found": "alloc_error"
}
}
]
},
"error_values/wrong_family.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "Returning alloc_error where io_error is declared rejects before AIR as E7005.",
"analogues": [
{
"source": "source/error_values/wrong_family.aji",
"codes": [
"E7005"
],
"fields": {
"expected": "io_error",
"found": "alloc_error"
}
}
]
},
"error_values/unknown_variant.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a76",
"rule": "An unknown built-in error variant is E7002 under the source error-construction rule.",
"analogues": [
{
"source": "source/error_values/unknown_variant.aji",
"codes": [
"E7002"
],
"fields": {
"enum": "alloc_error",
"variant": "invalid"
}
}
]
},
"error_values/payload.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a76",
"rule": "Built-in error variants reject payload arguments with E7005. This non-empty source payload is an analogue of the AIR empty argument list; empty source () instead rejects E7001.",
"analogues": [
{
"source": "source/error_values/payload.aji",
"codes": [
"E7005"
],
"fields": {
"variant": "budget_exceeded"
}
}
]
},
"buffers/borrowed_element.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "A borrowed buffer element violates member-position rules. AIR checks a parameter while this source analogue checks the buffer.new type argument, both before the operation.",
"analogues": [
{
"source": "source/buffers/borrowed_element.aji",
"codes": [
"E7005"
],
"fields": {
"position": "member",
"type_constructor": "ref"
}
}
]
},
"linear/borrow_array.air": {
"kind": "source_error",
"spec": "docs/spec/15-source-language.md \u00a710",
"rule": "Borrowed inferred array elements reject E7006 invalid_literal before AIR. The source list has two elements and AIR has one; element count does not decide this member-position rule.",
"analogues": [
{
"source": "source/array_literals/list_ref.aji",
"codes": [
"E7006"
],
"fields": {
"reason": "invalid_literal"
}
}
]
},
"buffers/undeclared.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "The missing AIR feature or dependency header cannot be authored in source: lowering generates the used features and their full dependency closure."
},
"linear/without_feature.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "The missing AIR feature or dependency header cannot be authored in source: lowering generates the used features and their full dependency closure."
},
"error_values/undeclared.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "The missing AIR feature or dependency header cannot be authored in source: lowering generates the used features and their full dependency closure."
},
"error_values/dependency.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a79",
"rule": "The missing AIR feature or dependency header cannot be authored in source: lowering generates the used features and their full dependency closure."
},
"phase0/reject/float_reserved.air": {
"kind": "air_only",
"spec": "docs/spec/15-source-language.md \u00a73",
"rule": "Source has no built-in f32/f64 type (spec 07 \u00a78.4). An undeclared f64 spelling is an ordinary E7002 unknown name; a user nominal f64 lowers to @f64 and cannot produce the reserved AIR primitive f64. Neither tests the reserved_type rule. Spec 15 \u00a71 restricts source to published features."
}
}
}
@@ -2,5 +2,5 @@
// phase: 6
// spec: docs/spec/15-source-language.md §5/§10; docs/spec/07-air.md §8.8
module test.array_literals
fn unused(p: ref<u64>) -> void effects [] { let a = [p, p]; }
fn unused(p: ref<u64>) -> void effects [] { let a = [p, p]; } // diagnostic here: p, p]
fn main() -> void effects [] {}
@@ -5,7 +5,7 @@
// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17
module test.buffers
fn bad(heap: cap<mem.alloc>, value: ref<u64>) -> void effects [mem.alloc] {
let data = buffer.new<ref<u64>>(1, heap) or trap;
let data = buffer.new<ref<u64>>(1, heap) or trap; // diagnostic here: ref<u64>>(1
buffer.free(move data) or trap;
}
fn main() -> u64 effects [] { return 42; }
@@ -2,4 +2,4 @@
// phase: 6
// spec: docs/spec/05-effects-and-capabilities.md §14
module test.errors
fn main() -> cap<mem.alloc> effects [] { return alloc_error::budget_exceeded; }
fn main() -> cap<mem.alloc> effects [] { return alloc_error::budget_exceeded; } // diagnostic here: alloc_error::budget_exceeded;
@@ -2,4 +2,4 @@
// phase: 6
// spec: docs/spec/05-effects-and-capabilities.md §14
module test.errors
fn main() -> alloc_error effects [] { return alloc_error::budget_exceeded(1u64); }
fn main() -> alloc_error effects [] { return alloc_error::budget_exceeded(1u64); } // diagnostic here: alloc_error::budget_exceeded(1u64)
@@ -2,4 +2,4 @@
// phase: 6
// spec: docs/spec/05-effects-and-capabilities.md §14
module test.errors
fn main() -> alloc_error effects [] { return alloc_error::invalid; }
fn main() -> alloc_error effects [] { return alloc_error::invalid; } // diagnostic here: alloc_error::invalid
@@ -2,4 +2,4 @@
// phase: 6
// spec: docs/spec/05-effects-and-capabilities.md §14
module test.errors
fn main() -> io_error effects [] { return alloc_error::budget_exceeded; }
fn main() -> io_error effects [] { return alloc_error::budget_exceeded; } // diagnostic here: alloc_error::budget_exceeded;
@@ -0,0 +1,11 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/15-source-language.md §17
// AIR twin: buffers/readonly_view_push.air
module test.readonly_view_push
fn bad(b: mut<buffer<u64>>) -> void effects [] {
ref view = buffer.view(b);
buffer.push(b, 42u64) or trap; // diagnostic here
trap;
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,10 @@
// expect: reject E3101
// phase: 6
// spec: docs/spec/15-source-language.md §17
// AIR twin: buffers/reserve_missing_effect.air
module test.reserve_missing_effect
fn bad(b: mut<buffer<u64>>, heap: cap<mem.alloc>) -> void effects [] {
buffer.reserve(b, 2usize, heap) or trap; // diagnostic here
trap;
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,10 @@
// expect: reject E3201
// phase: 6
// spec: docs/spec/15-source-language.md §17
// AIR twin: buffers/wrong_capability.air
module test.buffer_wrong_capability
fn bad(b: mut<buffer<u64>>, cap: cap<io.write>) -> void effects [mem.alloc] {
buffer.reserve(b, 0usize, cap) or trap; // diagnostic here
trap;
}
fn main() -> u64 effects [] { return 42; }
+52
View File
@@ -115,6 +115,58 @@ class CoverageFailures(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'missing required operation witness'):
self.verify_fake(row)
def test_mutable_view_cannot_replace_shared_view_push_regression(self):
row = self.fake_pair(source_path='source/reject_twins/buffer_readonly_view_push.aji',
air_path='buffers/readonly_view_push.air')
row['required_ops'] = {'borrow.ref': 1, 'buffer.view': 1, 'buffer.push': 1}
self.verify_fake(row)
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('ref view =', 'mut view ='))
with self.assertRaisesRegex(ValueError, 'missing required operation witness'):
self.verify_fake(row)
def test_ended_shared_decoy_cannot_hide_exclusive_view_conflict(self):
row = self.fake_pair(source_path='source/reject_twins/buffer_readonly_view_push.aji',
air_path='buffers/readonly_view_push.air')
row['required_ops'] = {'borrow.ref': 1, 'buffer.view': 1, 'buffer.push': 1}
row['required_ops'].update({'const.u64': 1, 'trap': 2})
row['exact_ops'] = True
self.verify_fake(row)
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('ref view = buffer.view(b);',
'{ ref decoy = buffer.view(b); }\n mut view = buffer.view(b);'))
with self.assertRaisesRegex(ValueError, 'different exact operation witness'):
self.verify_fake(row)
def test_dead_view_cannot_replace_live_view_with_plain_shared_borrow(self):
row = self.fake_pair(source_path='source/reject_twins/buffer_readonly_view_push.aji',
air_path='buffers/readonly_view_push.air')
row['required_ops'] = {'borrow.ref': 1, 'buffer.view': 1, 'buffer.push': 1,
'const.u64': 1, 'trap': 2}
row['exact_ops'] = True
self.verify_fake(row)
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('ref view = buffer.view(b);',
'{ ref decoy = buffer.view(b); }\n ref r = b;'))
with self.assertRaisesRegex(ValueError, 'different exact operation witness'):
self.verify_fake(row)
def test_view_of_another_buffer_cannot_replace_conflicting_buffer_view(self):
row = self.fake_pair(source_path='source/reject_twins/buffer_readonly_view_push.aji',
air_path='buffers/readonly_view_push.air')
row['required_ops'] = {'borrow.ref': 1, 'buffer.view': 1, 'buffer.push': 1,
'const.u64': 1, 'trap': 2}
row['exact_ops'] = True
row['required_identity_uses'] = {'conflicts_with': 'buffer.view'}
self.verify_fake(row)
p = self.corpus / 's.aji'
text = p.read_text().replace('b: mut<buffer<u64>>',
'b: mut<buffer<u64>>, other: ref<buffer<u64>>')
p.write_text(text.replace('ref view = buffer.view(b);',
'ref view = buffer.view(other);\n ref r = b;'))
with self.assertRaisesRegex(ValueError, 'missing diagnostic-identity use witness'):
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'):
+26 -7
View File
@@ -87,7 +87,8 @@ def inventory():
row = {'air': name, 'codes': expected, 'kind': 'pending', 'sources': []}
else:
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues',
'required_ops', 'match_type_declarations', 'early_context'}
'required_ops', 'exact_ops', 'required_identity_uses',
'match_type_declarations', 'early_context'}
if set(review) - allowed:
raise ValueError(f'{name}: unknown/reserved review keys: {sorted(set(review) - allowed)}')
witnesses = review.get('required_ops', {})
@@ -96,13 +97,21 @@ def inventory():
not isinstance(n, int) or isinstance(n, bool) or n < 1
for op, n in witnesses.items()):
raise ValueError(f'{name}: operation witness counts must be positive integers')
if 'exact_ops' in review and (review['exact_ops'] is not True or not witnesses):
raise ValueError(f'{name}: exact operation witness needs nonempty required_ops')
uses = review.get('required_identity_uses', {})
if not isinstance(uses, dict) or any(
field not in IDENTITIES - {'function', 'block', 'inst', 'callee', 'task_function'} or
not isinstance(op, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_.]*', op)
for field, op in uses.items()):
raise ValueError(f'{name}: invalid diagnostic-identity use witness')
if review.get('lowering') not in {None, 'rejected'}:
raise ValueError(f'{name}: invalid lowering mode')
if 'match_type_declarations' in review and review['match_type_declarations'] is not True:
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' in review or 'match_type_declarations' in review) and (
if ({'required_ops', 'exact_ops', 'required_identity_uses', 'match_type_declarations'} & 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'):
@@ -304,18 +313,27 @@ def annotation_map(annotated):
return '\n'.join(lines) + '\n', mapping
def operation_witnesses(air, diagnostics, required):
def operation_witnesses(air, diagnostics, required, exact=False, identity_uses=None):
for d in diagnostics:
function = re.search(r'^fn @' + re.escape(d['function']) + r'\(.*?(?=^fn @|\Z)', air, re.MULTILINE | re.DOTALL)
if not function:
raise ValueError('operation witness has no diagnostic function')
counts = Counter()
operands = {}
for line in function[0].splitlines():
line = line.split(';', 1)[0].strip()
if line and not line.startswith(('fn ', 'effects ')) and not line.endswith(':'):
counts[operation(line)] += 1
op = operation(line)
counts[op] += 1
rhs = line.split('=', 1)[1] if line.startswith('%') and '=' in line else line
operands.setdefault(op, set()).update(re.findall(r'%[A-Za-z_][\w.]*', rhs))
if any(counts[op] < minimum for op, minimum in required.items()):
raise ValueError('missing required operation witness in diagnostic function')
if exact and counts != Counter(required):
raise ValueError('different exact operation witness in diagnostic function')
if any(d.get(field) not in operands.get(op, set())
for field, op in (identity_uses or {}).items()):
raise ValueError('missing diagnostic-identity use witness')
def header_origin(air_line, source, path, site):
@@ -437,9 +455,10 @@ def verify_pair(aji, root, row, source):
raise ValueError(f'{source}: incorrect related source position')
if (related['air_line'], related['air_col']) != (rr['line'], rr['col']):
raise ValueError(f'{source}: incorrect related AIR position')
if row.get('required_ops'):
operation_witnesses(original, air_ds, row['required_ops'])
operation_witnesses(canonical, projected, row['required_ops'])
if row.get('required_ops') or row.get('required_identity_uses'):
for air, diagnostics in ((original, air_ds), (canonical, projected)):
operation_witnesses(air, diagnostics, row.get('required_ops', {}),
row.get('exact_ops', False), row.get('required_identity_uses'))
if Counter(signature(original, d, row['site']) for d in air_ds) != Counter(signature(canonical, d, row['site']) for d in projected):
raise ValueError(f'{source}: same codes but different offending operation/rule facts')
if any(d['code'] == 'E5101' and ('limit' not in d or 'max' not in d) for d in ds):