tests: preserve rejection contexts and normalize callee effects
This commit is contained in:
1 parent
06d8a1a76a
commit
fd92604f36
11 files changed
+344
-35
No files matched your search
@@ -320,6 +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 65/199. Audited pairs cover owner/file/receiver leaks, use after transfer, authority/effects, unsafe calls, 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 early-declaration positions. A new island-destroy fixture retains a child object borrow and its subsequent load; witnesses also preserve discarded-unpack and returned-buffer-failure contexts. The producer lookup now recognizes the specified island.borrow result as a borrow, with renamed-binding and missing-child regression probes. The legacy reserved_feature fixture's comment describes its actual missing_dependency rejection; its body and permanent name are unchanged. The inventory retains 103 pending, seven E7xxx analogues and 24 AIR-only cases, all still unmet under Q-053. P6-7 remains doing.
|
||||
Verified same-code coverage is 71/199. Audited pairs cover owner/file/receiver leaks, use after transfer, authority/effects, unsafe calls, 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. A new island-destroy fixture retains a child object borrow and its subsequent load; witnesses also preserve discarded-unpack and returned-buffer-failure contexts. Failed-send closed/cancelled edges now converge at one source error, matching AIR's merged failure path. E3101 callee identities resolve to their explicit flat effect sets, preserving effect facts without requiring the same name or irrelevant parameter types. 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 96 pending, seven E7xxx analogues and 25 AIR-only cases, all still unmet under Q-053. P6-7 remains doing.
|
||||
|
||||
Validation: full conformance is 1,666/1,666; unit tests, Zig formatting, all 23 checker regressions and the 65-pair source/AIR position check pass. All 24 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 and reviewed generated-only classifications, failure paths, static contracts, markers and witnesses. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes.
|
||||
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.
|
||||
|
||||
Validation: full conformance is 1,671/1,671; unit tests, Zig formatting, all 32 checker regressions and the 71-pair source/AIR position check pass. All 29 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 and reviewed generated-only classifications, failure paths, effect contracts, markers and witnesses. Its flat-array and substituted-cycle findings are covered by negative probes, as are incorrect declaration projections and changed callee effect sets. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes.
|
||||
@@ -46,9 +46,11 @@ 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. The small declaration/producer lookup fails closed on unsupported forms; it 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. Several raw diagnostics at one source construct use the first-per-code/location projection required by spec 15 §10. Budget headers use the marked source declaration and matching canonical function name, since `--annotate` exposes block/instruction spans. 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. Other callee-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. 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. 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. `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.
|
||||
|
||||
`--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.
|
||||
|
||||
|
||||
@@ -21,7 +21,13 @@
|
||||
"site": "declaration",
|
||||
"spec": "docs/spec/15-source-language.md \u00a715",
|
||||
"rule": "The non-generic Node recursively contains an array of itself by value, retaining E1003 before source lowering.",
|
||||
"lowering": "rejected"
|
||||
"lowering": "rejected",
|
||||
"early_context": {
|
||||
"air": "9ab84709f2349a215db70a0cad5cb3d8255dac91170c45cc3183972ad5a68b79",
|
||||
"sources": {
|
||||
"source/generics/monomorphic_layout_cycle.aji": "0e1495cfc4cee39827f3946b269583db945034470785b65b8cde5a6956c6818f"
|
||||
}
|
||||
}
|
||||
},
|
||||
"linear/field.air": {
|
||||
"kind": "same_code",
|
||||
@@ -43,7 +49,20 @@
|
||||
"site": "declaration",
|
||||
"spec": "docs/spec/15-source-language.md \u00a71",
|
||||
"rule": "The N0 through N40 by-value cycle is rejected as E1003 at N0 before source lowering. Pure by-value cycles retain E1003 (Q-043/Q-044; AIR type rules in spec 07).",
|
||||
"lowering": "rejected"
|
||||
"lowering": "rejected",
|
||||
"early_context": {
|
||||
"air": "38bd028b4851500690cfa0f3022e726f86075cf304582d970f849d0b3c13ecd0",
|
||||
"sources": {
|
||||
"source/nominal_queries/cycle.aji": "29d2fd93a85456a73cd935190516622525bd0432570cf4977b9a5ac2b71fc620"
|
||||
}
|
||||
}
|
||||
},
|
||||
"nominal_queries/diamond_21_u64.air": {
|
||||
"kind": "same_code",
|
||||
"site": "declaration",
|
||||
"spec": "docs/spec/08-verifier.md \u00a77",
|
||||
"rule": "The N0\u2013N3 shared diamond value layouts exceed max_value_size at their type declarations; all four limit/max/found/type facts agree after successful lowering.",
|
||||
"match_type_declarations": true
|
||||
},
|
||||
"phase0/reject/block_argument_type.air": {
|
||||
"kind": "air_only",
|
||||
@@ -127,8 +146,14 @@
|
||||
"kind": "same_code",
|
||||
"site": "declaration",
|
||||
"spec": "docs/spec/15-source-language.md \u00a71",
|
||||
"rule": "Node contains itself by value; source declaration validation retains E1003 (Q-043/Q-044).",
|
||||
"lowering": "rejected"
|
||||
"rule": "Node contains itself by value; source declaration validation retains E1003 (Q-043/Q-044). The scalar value field is u8 in AIR and u64 in source; its width does not decide the by-value self-cycle rule.",
|
||||
"lowering": "rejected",
|
||||
"early_context": {
|
||||
"air": "2014f05595edd77a7840d910eff8e26f338b7724fc25701cdb62f9f0dd359524",
|
||||
"sources": {
|
||||
"source/layer2/reject/verifier_recursive.aji": "c88b9db00d9d382adfd0282f650ff248c7613d0b0e0b83c8ec4b6493e1fff73a"
|
||||
}
|
||||
}
|
||||
},
|
||||
"phase0/reject/reserved_feature.air": {
|
||||
"kind": "air_only",
|
||||
@@ -274,6 +299,18 @@
|
||||
"spec": "docs/spec/05-effects-and-capabilities.md",
|
||||
"rule": "own.new lacks mem.alloc; the missing effect and complete suggested list agree."
|
||||
},
|
||||
"phase2/reject/alloc_wrong_capability.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
"spec": "docs/spec/05-effects-and-capabilities.md \u00a710.5",
|
||||
"rule": "own.new receives cap<fs.read> instead of mem.alloc authority; ok consumes the owner and err returns normally."
|
||||
},
|
||||
"phase2/reject/flat_effects.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
"spec": "docs/spec/05-effects-and-capabilities.md \u00a79.2/\u00a79.3",
|
||||
"rule": "A call lacks atomic.weak despite atomic being declared; effect sets are flat and callee effect sets agree."
|
||||
},
|
||||
"phase2/reject/intrinsic_effect.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
@@ -304,6 +341,11 @@
|
||||
"spec": "docs/spec/06-resources-and-errors.md \u00a76.2",
|
||||
"rule": "An owner transferred to a consuming call is subsequently borrowed."
|
||||
},
|
||||
"phase2/reject/region_allocation_outlives_borrow.air": {
|
||||
"kind": "air_only",
|
||||
"spec": "docs/spec/15-source-language.md \u00a78/\u00a79",
|
||||
"rule": "The explicit region borrow lexically outlives its derived allocation borrow. Source generates reverse-order ends and forbids yielding a borrow out of an arm/block, so parent-before-allocation-end cannot be authored."
|
||||
},
|
||||
"phase2/reject/region_destroy_with_live_reference.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
@@ -352,6 +394,21 @@
|
||||
"spec": "docs/spec/06-resources-and-errors.md",
|
||||
"rule": "A closed/freed resource is borrowed again."
|
||||
},
|
||||
"phase2/reject/resource_use_after_move.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
"spec": "docs/spec/06-resources-and-errors.md \u00a76.2",
|
||||
"rule": "An opened file<read> is transferred to a consuming call and then borrowed again.",
|
||||
"required_ops": {
|
||||
"call": 1
|
||||
}
|
||||
},
|
||||
"phase2/reject/undeclared_effect.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
"spec": "docs/spec/05-effects-and-capabilities.md \u00a79.3",
|
||||
"rule": "A call lacks the callee io.write effect; callee identities may differ but declared effect sets agree."
|
||||
},
|
||||
"phase2/reject/unsafe_call_from_safe.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
@@ -400,6 +457,15 @@
|
||||
"spec": "docs/spec/04-concurrency-and-atomics.md \u00a737.4/\u00a738",
|
||||
"rule": "channel.recv lacks task.wait on a borrowed receiver parameter; no allocation adds another missing effect."
|
||||
},
|
||||
"phase3/reject/channels_use_after_send.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
"spec": "docs/spec/04-concurrency-and-atomics.md \u00a738",
|
||||
"rule": "The old owner is borrowed after failed send returns its ownership under a new name; closed and cancelled both merge to the same error site, as in AIR.",
|
||||
"required_ops": {
|
||||
"channel.send": 1
|
||||
}
|
||||
},
|
||||
"phase3/reject/sync_call_waiting_function.air": {
|
||||
"kind": "same_code",
|
||||
"site": "instruction",
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
// phase: 6
|
||||
// spec: docs/spec/08-verifier.md §7; docs/spec/15-source-language.md §10
|
||||
module test.nominal_queries
|
||||
struct N0 { a: N1, b: N1 }
|
||||
struct N1 { a: N2, b: N2 }
|
||||
struct N2 { a: N3, b: N3 }
|
||||
struct N3 { a: N4, b: N4 }
|
||||
// AIR twin: nominal_queries/diamond_21_u64.air
|
||||
struct N0 { a: N1, b: N1 } // diagnostic here
|
||||
struct N1 { a: N2, b: N2 } // diagnostic here
|
||||
struct N2 { a: N3, b: N3 } // diagnostic here
|
||||
struct N3 { a: N4, b: N4 } // diagnostic here
|
||||
struct N4 { a: N5, b: N5 }
|
||||
struct N5 { a: N6, b: N6 }
|
||||
struct N6 { a: N7, b: N7 }
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// own.new receives cap<fs.read> where the allocation needs cap<mem.alloc>.
|
||||
// phase: 6
|
||||
// spec: docs/spec/05-effects-and-capabilities.md §10.5
|
||||
// expect: reject E3201
|
||||
// AIR twin: phase2/reject/alloc_wrong_capability.air
|
||||
module test.source_alloc_wrong_capability
|
||||
fn f(heap: cap<fs.read>) -> void effects [mem.alloc] {
|
||||
match own.new(1u64, heap) { // diagnostic here: own.new
|
||||
ok(o) => { own.free(move o); }
|
||||
err(e) => {}
|
||||
}
|
||||
}
|
||||
fn main() -> u64 effects [] { return 0u64; }
|
||||
@@ -0,0 +1,16 @@
|
||||
// Failed send returns the owner under a new name on both failure edges.
|
||||
// phase: 6
|
||||
// spec: docs/spec/04-concurrency-and-atomics.md §38
|
||||
// AIR twin: phase3/reject/channels_use_after_send.air
|
||||
// expect: reject E2001
|
||||
module test.source_use_after_failed_send
|
||||
fn f(tx: mut<sender<own<u64>>>, o: own<u64>) -> u64 effects [task.wait] {
|
||||
let back = match channel.send(tx, move o) {
|
||||
ok => { return 0u64; }
|
||||
closed(value) => move value,
|
||||
cancelled(value) => move value,
|
||||
};
|
||||
{ ref old = o; } // diagnostic here: ref old
|
||||
return own.take(move back);
|
||||
}
|
||||
fn main() -> u64 effects [] { return 0u64; }
|
||||
@@ -0,0 +1,11 @@
|
||||
// atomic does not imply atomic.weak: effect sets are flat.
|
||||
// phase: 6
|
||||
// spec: docs/spec/05-effects-and-capabilities.md §9.2/§9.3
|
||||
// expect: reject E3101
|
||||
// AIR twin: phase2/reject/flat_effects.air
|
||||
module test.source_flat_effects
|
||||
fn relaxed_work() -> void effects [atomic.weak] {}
|
||||
fn f() -> void effects [atomic] {
|
||||
relaxed_work(); // diagnostic here
|
||||
}
|
||||
fn main() -> u64 effects [] { return 0u64; }
|
||||
@@ -0,0 +1,19 @@
|
||||
// An opened file is moved into a consuming call and then borrowed.
|
||||
// phase: 6
|
||||
// spec: docs/spec/06-resources-and-errors.md §6.2
|
||||
// expect: reject E2001
|
||||
// AIR twin: phase2/reject/resource_use_after_move.air
|
||||
module test.source_resource_use_after_move
|
||||
fn take(file: file<read>) -> void effects [] {
|
||||
fs.close(move file) or trap;
|
||||
}
|
||||
fn f(c: cap<fs.read>, p: slice<u8>) -> void effects [fs.read] {
|
||||
match fs.open_read(c, p) {
|
||||
ok(file) => {
|
||||
take(move file);
|
||||
{ mut m = file; } // diagnostic here: mut m
|
||||
}
|
||||
err(e) => {}
|
||||
}
|
||||
}
|
||||
fn main() -> u64 effects [] { return 0u64; }
|
||||
@@ -0,0 +1,11 @@
|
||||
// The caller does not declare the effect of its callee.
|
||||
// phase: 6
|
||||
// spec: docs/spec/05-effects-and-capabilities.md §9.3
|
||||
// expect: reject E3101
|
||||
// AIR twin: phase2/reject/undeclared_effect.air
|
||||
module test.source_undeclared_effect
|
||||
fn emit() -> void effects [io.write] {}
|
||||
fn f() -> void effects [] {
|
||||
emit(); // diagnostic here
|
||||
}
|
||||
fn main() -> u64 effects [] { return 0u64; }
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Independent failure probes for the rejection-twin coverage check."""
|
||||
import importlib.util
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
@@ -188,6 +189,53 @@ class CoverageFailures(unittest.TestCase):
|
||||
self.assertEqual(row['lowering'], 'rejected')
|
||||
twins.verify_pair(AJI, self.root, row, row['sources'][0])
|
||||
|
||||
def test_self_loop_cannot_replace_audited_long_cycle(self):
|
||||
row = self.fake_pair(source_path='source/nominal_queries/cycle.aji',
|
||||
air_path='nominal_queries/cycle.air')
|
||||
source = self.corpus / 's.aji'
|
||||
row.update(site='declaration', lowering='rejected', early_context={
|
||||
'air': hashlib.sha256((self.corpus / 'a.air').read_bytes()).hexdigest(),
|
||||
'sources': {'s.aji': hashlib.sha256(source.read_bytes()).hexdigest()}})
|
||||
source.write_text(source.read_text().replace('struct N0 { a: N1, b: N1 }',
|
||||
'struct N0 { a: N0, b: N0 }'))
|
||||
with self.assertRaisesRegex(ValueError, 'audited early source changed'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_direct_cycle_cannot_replace_audited_array_cycle(self):
|
||||
row = self.fake_pair(source_path='source/generics/monomorphic_layout_cycle.aji',
|
||||
air_path='generics/recursive_array.air')
|
||||
source = self.corpus / 's.aji'
|
||||
row.update(site='declaration', lowering='rejected', early_context={
|
||||
'air': hashlib.sha256((self.corpus / 'a.air').read_bytes()).hexdigest(),
|
||||
'sources': {'s.aji': hashlib.sha256(source.read_bytes()).hexdigest()}})
|
||||
source.write_text(source.read_text().replace('[Node; 1]', 'Node'))
|
||||
with self.assertRaisesRegex(ValueError, 'audited early source changed'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_changed_early_air_cannot_reuse_the_old_source_audit(self):
|
||||
row = self.fake_pair(source_path='source/generics/monomorphic_layout_cycle.aji',
|
||||
air_path='generics/recursive_array.air')
|
||||
air, source = self.corpus / 'a.air', self.corpus / 's.aji'
|
||||
row.update(site='declaration', lowering='rejected', early_context={
|
||||
'air': hashlib.sha256(air.read_bytes()).hexdigest(),
|
||||
'sources': {'s.aji': hashlib.sha256(source.read_bytes()).hexdigest()}})
|
||||
original = air.read_text()
|
||||
changed = original.replace('array<@Node, 1>', '@Node')
|
||||
self.assertNotEqual(changed, original)
|
||||
air.write_text(changed)
|
||||
with self.assertRaisesRegex(ValueError, 'audited early AIR changed'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_early_mode_cannot_omit_its_context_audit(self):
|
||||
row = self.fake_pair(source_path='source/generics/monomorphic_layout_cycle.aji',
|
||||
air_path='generics/recursive_array.air')
|
||||
review = {k: v for k, v in row.items() if k not in {'air', 'sources', 'codes'}}
|
||||
review.update(site='declaration', lowering='rejected')
|
||||
self.manifest.write_text(json.dumps({'version': 1, 'cases': {'a.air': review}}))
|
||||
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
|
||||
with self.assertRaisesRegex(ValueError, 'early rejection needs audited'):
|
||||
twins.inventory()
|
||||
|
||||
def test_one_source_array_borrow_keeps_first_raw_error_per_location(self):
|
||||
rows = twins.inventory()
|
||||
row = next(r for r in rows if r['air'] == 'phase1/reject/mut_and_shared.air')
|
||||
@@ -199,6 +247,66 @@ class CoverageFailures(unittest.TestCase):
|
||||
self.assertEqual(row['site'], 'function')
|
||||
twins.verify_pair(AJI, self.root, row, row['sources'][0])
|
||||
|
||||
def test_four_type_budget_headers_use_exact_marked_declarations(self):
|
||||
rows = twins.inventory()
|
||||
row = next(r for r in rows if r['air'] == 'nominal_queries/diamond_21_u64.air')
|
||||
self.assertEqual(row['site'], 'declaration')
|
||||
self.assertNotIn('lowering', row)
|
||||
twins.verify_pair(AJI, self.root, row, row['sources'][0])
|
||||
|
||||
def test_consistent_but_wrong_type_header_projection_is_rejected(self):
|
||||
row = self.fake_pair(source_path='source/nominal_queries/diamond_21_u64.aji',
|
||||
air_path='nominal_queries/diamond_21_u64.air')
|
||||
row['site'] = 'declaration'
|
||||
p = self.corpus / 's.aji'
|
||||
lines = p.read_text().splitlines()
|
||||
marked = [i for i, line in enumerate(lines) if '// diagnostic here' in line]
|
||||
for i in marked:
|
||||
lines[i] = lines[i].replace(' // diagnostic here', '')
|
||||
lines[i + 4] += ' // diagnostic here'
|
||||
p.write_text('\n'.join(lines) + '\n')
|
||||
real_command = twins.command
|
||||
def changed(aji, *args, status):
|
||||
result = real_command(aji, *args, status=status)
|
||||
if args[0] == 'check' and Path(args[1]) == p:
|
||||
ds = [json.loads(line) for line in result.splitlines()]
|
||||
for d in ds:
|
||||
d['line'] += 4
|
||||
return '\n'.join(json.dumps(d) for d in ds) + '\n'
|
||||
return result
|
||||
with patch.object(twins, 'command', changed):
|
||||
with self.assertRaisesRegex(ValueError, 'incorrect source position'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_flat_array_sizes_cannot_replace_nominal_diamond_context(self):
|
||||
row = self.fake_pair(source_path='source/nominal_queries/diamond_21_u64.aji',
|
||||
air_path='nominal_queries/diamond_21_u64.air')
|
||||
row.update(site='declaration', match_type_declarations=True)
|
||||
p = self.corpus / 's.aji'
|
||||
lines = [line for line in p.read_text().splitlines() if not line.startswith('struct ')]
|
||||
index = next(i for i, line in enumerate(lines) if line.startswith('module ')) + 1
|
||||
lines[index:index] = [f'struct N{i} {{ a: [u64; {2097152 >> i}] }} // diagnostic here'
|
||||
for i in range(4)]
|
||||
p.write_text('\n'.join(lines) + '\n')
|
||||
with self.assertRaisesRegex(ValueError, 'different type-declaration context'):
|
||||
self.verify_fake(row)
|
||||
|
||||
def test_effect_pair_survives_a_renamed_callee(self):
|
||||
self.verify_fake(self.fake_pair(source_path='source/reject_twins/undeclared_effect.aji',
|
||||
air_path='phase2/reject/undeclared_effect.air'))
|
||||
|
||||
def test_same_missing_effect_does_not_hide_different_callee_effect_sets(self):
|
||||
row = self.fake_pair(source_path='source/reject_twins/undeclared_effect.aji',
|
||||
air_path='phase2/reject/undeclared_effect.air')
|
||||
air = self.corpus / 'a.air'
|
||||
air.write_text(air.read_text().replace('effects []', 'effects [atomic]', 1)
|
||||
.replace('effects [io.write]', 'effects [atomic, io.write]'))
|
||||
source = self.corpus / 's.aji'
|
||||
source.write_text(source.read_text().replace('fn f() -> void effects []',
|
||||
'fn f() -> void effects [atomic]'))
|
||||
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
|
||||
self.verify_fake(row)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -8,6 +8,7 @@ unless every AIR rejection has a verified same-code source twin.
|
||||
"""
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
@@ -19,7 +20,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
CORPUS = ROOT / 'tests/conformance'
|
||||
MANIFEST = CORPUS / 'reject-twins.json'
|
||||
IDENTITIES = {'function', 'block', 'inst', 'borrow', 'resource', 'task',
|
||||
'conflicts_with', 'scope', 'guard', 'child', 'inner', 'local', 'from'}
|
||||
'conflicts_with', 'scope', 'guard', 'child', 'inner', 'local', 'from', 'callee'}
|
||||
ENVELOPE = {'code', 'kind', 'severity', 'file', 'line', 'col', 'air_line',
|
||||
'air_col', 'message', 'related_locations'}
|
||||
|
||||
@@ -84,7 +85,8 @@ def inventory():
|
||||
if review is None:
|
||||
row = {'air': name, 'codes': expected, 'kind': 'pending', 'sources': []}
|
||||
else:
|
||||
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues', 'required_ops'}
|
||||
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues',
|
||||
'required_ops', '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', {})
|
||||
@@ -95,8 +97,13 @@ def inventory():
|
||||
raise ValueError(f'{name}: operation witness counts must be positive integers')
|
||||
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 (
|
||||
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'):
|
||||
raise ValueError(f'{name}: missing rule/spec evidence')
|
||||
spec = (ROOT / review['spec'].split(' §')[0]).resolve()
|
||||
@@ -109,6 +116,17 @@ def inventory():
|
||||
raise ValueError(f'{name}: analogue/inexpressible case cannot count as a twin')
|
||||
if review['kind'] == 'source_error' and not review.get('analogues'):
|
||||
raise ValueError(f'{name}: source-error classification needs an analogue')
|
||||
if review.get('lowering') == 'rejected':
|
||||
context = review.get('early_context')
|
||||
if (review['kind'] != 'same_code' or not isinstance(context, dict) or
|
||||
set(context) != {'air', 'sources'} or
|
||||
not isinstance(context['sources'], dict) or
|
||||
set(context['sources']) != set(sources) or
|
||||
any(not isinstance(x, str) or not re.fullmatch(r'[0-9a-f]{64}', x)
|
||||
for x in [context['air'], *context['sources'].values()])):
|
||||
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')
|
||||
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')
|
||||
@@ -231,9 +249,23 @@ def positions(source):
|
||||
return marked
|
||||
|
||||
|
||||
def callee_effects(air, d):
|
||||
# For E3101, the callee's explicit flat effect set is the rule-relevant
|
||||
# contract. Parameter/return types do not decide this effect rule.
|
||||
if d['code'] != 'E3101':
|
||||
raise ValueError('unsupported callee identity rule')
|
||||
name = d['callee']
|
||||
declaration = re.search(r'^fn @' + re.escape(name) +
|
||||
r'\(([^)]*)\)([^\n]*)\n\s*effects \[([^]]*)\]', air, re.MULTILINE)
|
||||
if not declaration:
|
||||
raise ValueError(f'callee lacks an audited declaration: {name}')
|
||||
return tuple(sorted(x.strip() for x in declaration[3].split(',') if x.strip()))
|
||||
|
||||
|
||||
def signature(air, d, site):
|
||||
return (d['code'], d['kind'], site_key(air, d, site),
|
||||
tuple(sorted((k, identity_class(air, d, d[k])) for k in (IDENTITIES - {'function', 'block', 'inst'}) & d.keys())),
|
||||
tuple(sorted((k, callee_effects(air, d) if k == 'callee' else identity_class(air, d, d[k]))
|
||||
for k in (IDENTITIES - {'function', 'block', 'inst'}) & d.keys())),
|
||||
tuple(x['role'] for x in d.get('related_locations', [])),
|
||||
json.dumps(payload(d), sort_keys=True))
|
||||
|
||||
@@ -265,6 +297,37 @@ def operation_witnesses(air, diagnostics, required):
|
||||
raise ValueError('missing required operation witness in diagnostic function')
|
||||
|
||||
|
||||
def header_origin(air_line, source, path, site):
|
||||
# --annotate contains instruction/block spans only. For non-generic
|
||||
# headers, resolve the exact canonical name to one source declaration.
|
||||
air_pattern, source_pattern = (
|
||||
(r'fn @(\w+)\(', r'fn ')
|
||||
if site == 'function' else
|
||||
(r'type @(\w+)\s*=', r'(?:struct|enum) '))
|
||||
name = re.match(air_pattern, air_line)
|
||||
declarations = [(i, line) for i, line in enumerate(source.splitlines(), 1)
|
||||
if name and re.match(r'\s*' + source_pattern + re.escape(name[1]) + r'\b', line)]
|
||||
if len(declarations) != 1:
|
||||
raise ValueError(f'{path}: budget header lacks a unique matching source declaration')
|
||||
i, line = declarations[0]
|
||||
return str(path), i, len(line[:len(line) - len(line.lstrip())].encode('utf-8')) + 1
|
||||
|
||||
|
||||
def type_declarations(air):
|
||||
# A fixture-context witness, not a type/layout evaluator. Preserve the
|
||||
# complete named declaration table, ignoring only comments/whitespace.
|
||||
declarations = {}
|
||||
for line in air.splitlines():
|
||||
line = line.split(';', 1)[0].strip()
|
||||
if not line.startswith('type '):
|
||||
continue
|
||||
declaration = re.fullmatch(r'type @([\w.]+)\s*=\s*(.+)', line)
|
||||
if not declaration or declaration[1] in declarations:
|
||||
raise ValueError('unsupported/duplicate type declaration witness')
|
||||
declarations[declaration[1]] = re.sub(r'\s+', '', declaration[2])
|
||||
return declarations
|
||||
|
||||
|
||||
def verify_pair(aji, root, row, source):
|
||||
air_path = CORPUS / row['air']
|
||||
src_path = CORPUS / source
|
||||
@@ -278,6 +341,13 @@ def verify_pair(aji, root, row, source):
|
||||
if row.get('lowering') == 'rejected':
|
||||
if row['site'] != 'declaration':
|
||||
raise ValueError('early rejection mode requires a declaration-site audit')
|
||||
# No canonical AIR exists. Pin both manually audited artifacts rather
|
||||
# than inventing a second source parser to compare cycle shapes.
|
||||
context = row['early_context']
|
||||
if hashlib.sha256(air_path.read_bytes()).hexdigest() != context['air']:
|
||||
raise ValueError('audited early AIR changed; a new context audit is required')
|
||||
if hashlib.sha256(src_path.read_bytes()).hexdigest() != context['sources'][source]:
|
||||
raise ValueError('audited early source changed; a new context audit is required')
|
||||
lowered = [load_json(x) for x in command(aji, 'lower', src_path, status=1).splitlines()]
|
||||
if lowered != ds:
|
||||
raise ValueError(f'{source}: lower/check early errors differ')
|
||||
@@ -294,6 +364,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 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:
|
||||
raise ValueError(f'{source}: nondeterministic lowering')
|
||||
annotated, mapping = annotation_map(command(aji, 'lower', '--annotate', src_path, status=0))
|
||||
@@ -308,14 +380,9 @@ def verify_pair(aji, root, row, source):
|
||||
projected, seen = [], set()
|
||||
for rd in raw_ds:
|
||||
origin = mapping[rd['line']]
|
||||
if origin is None and row['site'] == 'function':
|
||||
raw_name = re.match(r'fn @(\w+)', canonical.splitlines()[rd['line'] - 1])
|
||||
declarations = [(i, line) for i, line in enumerate(source_text.splitlines(), 1)
|
||||
if raw_name and re.match(r'\s*fn ' + re.escape(raw_name[1]) + r'\(', line)]
|
||||
if len(declarations) != 1:
|
||||
raise ValueError(f'{source}: budget header lacks a source declaration')
|
||||
i, line = declarations[0]
|
||||
origin = (str(src_path), i, len(line) - len(line.lstrip()) + 1)
|
||||
if origin is None and row['site'] in {'function', 'declaration'}:
|
||||
origin = header_origin(canonical.splitlines()[rd['line'] - 1],
|
||||
source_text, src_path, row['site'])
|
||||
if origin is None:
|
||||
raise ValueError(f'{source}: raw diagnostic lacks a source mapping')
|
||||
key = rd['code'], origin[0] or str(src_path), origin[1], origin[2]
|
||||
@@ -328,17 +395,10 @@ def verify_pair(aji, root, row, source):
|
||||
if (d['air_line'], d['air_col'], d['code']) != (rd['line'], rd['col'], rd['code']):
|
||||
raise ValueError(f'{source}: incorrect primary AIR position')
|
||||
origin = mapping[d['air_line']]
|
||||
if row['site'] == 'function':
|
||||
# --annotate exposes block/instruction spans, not header spans.
|
||||
# Budget sites instead have an independent marked declaration
|
||||
# and must identify that same function in canonical AIR.
|
||||
raw_line = canonical.splitlines()[d['air_line'] - 1]
|
||||
source_line = source_text.splitlines()[d['line'] - 1]
|
||||
raw_name = re.match(r'fn @(\w+)', raw_line)
|
||||
source_name = re.match(r'\s*fn (\w+)', source_line)
|
||||
if not raw_name or not source_name or raw_name[1] != source_name[1]:
|
||||
raise ValueError(f'{source}: budget error names a different function')
|
||||
elif origin is None or (d['line'], d['col']) != origin[1:]:
|
||||
if origin is None and row['site'] in {'function', 'declaration'}:
|
||||
origin = header_origin(canonical.splitlines()[d['air_line'] - 1],
|
||||
source_text, src_path, row['site'])
|
||||
if origin is None or (d['line'], d['col']) != origin[1:]:
|
||||
raise ValueError(f'{source}: missing/incorrect source position')
|
||||
if d['file'] != str(src_path):
|
||||
raise ValueError(f'{source}: wrong source file')
|
||||
@@ -357,7 +417,7 @@ def verify_pair(aji, root, row, source):
|
||||
operation_witnesses(canonical, projected, row['required_ops'])
|
||||
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 row['site'] == 'function' and any('limit' not in d or 'max' not in d for d in ds):
|
||||
if any(d['code'] == 'E5101' and ('limit' not in d or 'max' not in d) for d in ds):
|
||||
raise ValueError(f'{source}: budget twin lacks stable limit facts')
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user