tests: audit source rejections before AIR lowering

This commit is contained in:
dev committed 2026-10-09 18:49:28 +03:00
1 parent a491eba193
commit ba99ad6727
7 files changed
+192 -9

No files matched your search

+2
View File
@@ -393,6 +393,8 @@ The exhaustive inventory in `tools/source_reject_twins.py` keeps these rows visi
Proposed criterion, for owner decision: retain every AIR rejection test; for each source-authorable rule/context, require a compiled source twin with the same code or its spec-prescribed E7xxx translation, stable facts and independent positions. Generated-only contexts require an explicit governing source-policy audit. Every newly discovered public AIR rejection remains pending until audited. This proposal changes no language rule and does not count a matching code alone as a twin. It is not adopted; the literal gate and doing status remain unchanged.
2026-10-09: after the Q-058 size correction, all 205 public AIR rejection files are classified: 96 verified same-code pairs, 45 E7xxx analogues, 63 AIR-only cases and one `source_early` analogue. The last category retains an authorable cyclic-array declaration whose AIR budget rejects E5101 while source finite-layout validation rejects E1003 before lowering. Both codes, facts, declaration positions and reviewed artifact fingerprints are checked; it contributes no same-code coverage. The final criterion must also account explicitly for such earlier verifier-code rejections, rather than label their authorable shape AIR-only or change diagnostics for coverage. No policy is adopted; `--require-complete` still exits 1.
## Q-054 — Executable contract obligations and invariant boundaries
P6-6 requires contracts and their four audit statuses, but spec 13 §1/spec 08 §8 do not define predicate purity, snapshot/result lifetime, boundary coverage or a proof calculus. AIR has no contract table. Current probes at `94414da` show identical audit reports for mandatory/bypassable assertions, effects-empty mutation and ambient task.cancelled observation, and E3001 after consuming an observed owner. New contract headers also need an AIR0 rejected-code audit: an unfeatured header currently reports E0001, outside §8.7's E0004/E0006 exceptions; Q-055 records the conflict with §8.1.
+2
View File
@@ -335,6 +335,8 @@ Five Q-058 regression cases now have verified source/AIR twins with identical E5
One row remains pending: nested_size_cycle_overflow.air reports E5101 before finite-layout validation, while the same source declaration necessarily rejects earlier with E1003. A separate source fixture preserves that actual code; it is not falsely linked as an E5101 twin. The current inventory's E7xxx analogue category cannot represent this earlier verifier-code rejection. Q-053's literal completion decision remains open; no rejection rule or diagnostic is changed for coverage. Full conformance passes 1765/1765; sixteen nested-size cases also pass with collection before every instruction. All 62 checker regressions pass, and source construct coverage stays 121/121. No fresh Claude review was available for this increment. P6-7 remains doing.
The final size row is now explicitly classified as `source_early`, retaining its authorable cyclic-array shape and unlike E5101/E1003 codes. The inventory tool pins both reviewed artifacts, AIR budget facts and source type facts, checks independent declaration markers, and requires lower/check rejection parity without fabricated AIR coordinates. It does not infer cycle equivalence or waive the same-code completion gate. All 205 AIR rows are classified: 96 same-code, 45 E7xxx analogues, one source-early analogue and 63 AIR-only; zero pending. Eight new failure probes cover artifact/fact/position drift, lower/check disagreement and a category that cannot satisfy `--require-complete`. All 70 checker regressions and 16 focused GC conformance cases pass. No compiler/normative/bundle changes or fresh Claude review. Q-053 and P6-7 remain open.
## P6-1 source specification consistency (2026-10-09)
Spec 15's initial Phase 6A limits now point to its existing extensions. Its introductory diagnostic rule follows §10 and construct-specific codes; widening reports source E7005 while AIR retains E1002, including the corrected Quick Reference entry. Multi-result bindings include complete unpacking, byte escapes agree with the later exact list, and grammar comments locate graph access in §8. Old incremental limits link buffers/borrow returns to §17/§19. No grammar production, semantic rule or implementation changes. Six existing public fixtures confirm the reported code and deterministic successful AIR; Claude independently audited the corrections. The reference bundle rebuilds; source growth is +50/+47/+58 tokens across the three tokenizers, with unchanged Quick Reference token counts, AIR and std (docs/agent/README.md). P6-1/P6-5 remain open for their unimplemented surfaces.
+3 -1
View File
@@ -58,7 +58,9 @@ For lowered CFG cases whose diagnostic facts omit the handoff shape, `audited_co
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.
`--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), `source_early` (a different verifier code from source validation before lowering), `air_only` (not authorable in the implemented source) or `pending`. Only same-code pairs meet the criterion. A successful ordinary check verifies the audited pairs and analogues 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.
The currently supported `source_early` case is E5101 at an AIR type declaration versus E1003 at the corresponding source declaration. It requires `site: declaration`, `lowering: rejected`, one AIR budget diagnostic and analogue E1003/type facts. `air_fields` pins exactly kind/limit/max/found/type, while `early_context` pins the manually reviewed AIR and every source analogue. The checker executes both files, checks independent source markers and declaration positions, and requires lower to reproduce check's rejection without AIR coordinates. It does not compare unlike codes as though they were twins or infer the type-cycle shape. A new early-code category needs its own explicit support/audit; E7xxx analogue handling is unchanged. The cyclic-array size case retains E5101 in AIR and E1003 in source, counts zero same-code pairs, and keeps the completion gate failing.
`python3 tests/hosted/source_reject_twins.py` exercises false-pair detection, independent source markers, raw diagnostic projection, early declarations and automatic discovery of pending cases.
+32
View File
@@ -1763,6 +1763,38 @@
"site": "function",
"spec": "docs/spec/08-verifier.md \u00a77.1",
"rule": "A parameter of array<array<u8,1024>,1025> accounts 1049600 bytes in both artifacts, preserving the complete value-size budget facts."
},
"phase1/reject/nested_size_cycle_overflow.air": {
"kind": "source_early",
"site": "declaration",
"lowering": "rejected",
"spec": "docs/spec/15-source-language.md \u00a71/\u00a710; docs/spec/08-verifier.md \u00a77.1",
"rule": "Both declarations have u8 n and an array of 4294967296 A values by value. Source finite-layout validation rejects E1003 at A before emitting AIR; the AIR input budget reports E5101 with bounded size 4294967297 first. This is an earlier-stage analogue, not same-code coverage or an AIR-only source shape.",
"air_fields": {
"kind": "verifier.resource_limit",
"limit": "value size bytes",
"max": 1048576,
"found": 4294967297,
"type": "@A"
},
"analogues": [
{
"source": "source/size_limits/nested_size_cycle.aji",
"codes": [
"E1003"
],
"fields": {
"kind": "type.recursive",
"type": "A"
}
}
],
"early_context": {
"air": "c3eff4c2941ee59e32f9ae4a6aa5e68ef0986f5140301a88a81b86447dab4957",
"sources": {
"source/size_limits/nested_size_cycle.aji": "b549c862021856f209331a024ba419bf49cf3deb48989bb24c9147ae38e5fc6f"
}
}
}
}
}
@@ -4,5 +4,5 @@
// phase: 6
// spec: docs/spec/15-source-language.md §1
module test.nested_size_cycle
struct A { n: u8, x: [A; 4294967296] }
struct A { n: u8, x: [A; 4294967296] } // diagnostic here: struct A
fn main() -> void effects [] {}
+97
View File
@@ -2,6 +2,7 @@
"""Independent failure probes for the rejection-twin coverage check."""
import importlib.util
import hashlib
import io
import json
import re
from pathlib import Path
@@ -643,6 +644,102 @@ class CoverageFailures(unittest.TestCase):
self.assertEqual(row['site'], 'function')
twins.verify_pair(AJI, self.root, row, row['sources'][0])
def early_analogue(self):
air = self.corpus / 'a.air'
source = self.corpus / 's.aji'
air.write_text((REAL_CORPUS / 'phase1/reject/nested_size_cycle_overflow.air').read_text())
text = (REAL_CORPUS / 'source/size_limits/nested_size_cycle.aji').read_text()
text = re.sub(r' // diagnostic here.*$', '', text, flags=re.MULTILINE)
source.write_text(text.replace('struct A { n: u8, x: [A; 4294967296] }',
'struct A { n: u8, x: [A; 4294967296] } // diagnostic here: struct A'))
rule = {
'kind': 'source_early', 'site': 'declaration', 'lowering': 'rejected',
'spec': 'docs/spec/15-source-language.md §10',
'rule': 'The same cyclic array shape reaches different validation stages.',
'air_fields': {'kind': 'verifier.resource_limit', 'limit': 'value size bytes',
'max': 1048576, 'found': 4294967297, 'type': '@A'},
'analogues': [{'source': 's.aji', 'codes': ['E1003'],
'fields': {'kind': 'type.recursive', 'type': 'A'}}],
'early_context': {'air': hashlib.sha256(air.read_bytes()).hexdigest(),
'sources': {'s.aji': hashlib.sha256(source.read_bytes()).hexdigest()}},
}
self.manifest.write_text(json.dumps({'version': 1, 'cases': {'a.air': rule}}))
return {'air': 'a.air', 'sources': [], 'codes': ['E5101'], **rule}
def verify_early(self, row):
with patch.object(twins, 'CORPUS', self.corpus):
twins.verify_early_analogue(AJI, row)
def test_early_source_analogue_retains_different_codes_without_becoming_a_twin(self):
row = self.early_analogue()
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
found = twins.inventory()[0]
self.assertEqual(found['kind'], 'source_early')
self.assertEqual(found['sources'], [])
self.assertEqual(found['codes'], ['E5101'])
self.verify_early(row)
def test_early_source_analogue_cannot_complete_same_code_coverage(self):
row = self.early_analogue()
with patch.object(twins, 'inventory', return_value=[row]), \
patch.object(twins, 'verify_early_analogue'), \
patch.object(twins.sys, 'argv', ['twins', '--require-complete']), \
patch.object(twins.sys, 'stdout', io.StringIO()) as out:
self.assertEqual(twins.main(), 1)
self.assertIn('0/1 same-code', out.getvalue())
self.assertIn('1 source-early', out.getvalue())
def test_early_source_analogue_needs_reviewed_artifacts(self):
self.early_analogue()
manifest = json.loads(self.manifest.read_text())
del manifest['cases']['a.air']['early_context']
self.manifest.write_text(json.dumps(manifest))
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_direct_cycle_cannot_replace_early_size_analogue(self):
row = self.early_analogue()
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('[A; 4294967296]', 'A'))
with self.assertRaisesRegex(ValueError, 'audited early source changed'):
self.verify_early(row)
def test_different_size_cannot_replace_early_air_analogue(self):
row = self.early_analogue()
p = self.corpus / 'a.air'
p.write_text(p.read_text().replace('4294967296', '4294967295'))
with self.assertRaisesRegex(ValueError, 'audited early AIR changed'):
self.verify_early(row)
def test_wrong_air_budget_fact_cannot_hide_behind_source_cycle_code(self):
row = self.early_analogue()
row['air_fields']['found'] = 1048577
with self.assertRaisesRegex(ValueError, 'early AIR rule facts changed'):
self.verify_early(row)
def test_early_source_marker_must_point_to_rejected_declaration(self):
row = self.early_analogue()
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('diagnostic here: struct A', 'diagnostic here: x:'))
row['early_context']['sources']['s.aji'] = hashlib.sha256(p.read_bytes()).hexdigest()
with self.assertRaisesRegex(ValueError, 'analogue position changed'):
self.verify_early(row)
def test_early_source_check_and_lower_cannot_disagree(self):
row = self.early_analogue()
real_command = twins.command
def changed(aji, *args, status):
result = real_command(aji, *args, status=status)
if args[0] == 'lower':
ds = [json.loads(line) for line in result.splitlines()]
ds[0]['type'] = 'Wrong'
return '\n'.join(json.dumps(d) for d in ds) + '\n'
return result
with patch.object(twins, 'command', changed):
with self.assertRaisesRegex(ValueError, 'lower/check early errors differ'):
self.verify_early(row)
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')
+55 -7
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Inventory every public AIR rejection and verify audited source twins.
Pending, source-error analogues and AIR-only cases remain unmet P6-7 rows.
Pending, source-error/early analogues and AIR-only cases remain unmet P6-7 rows.
Default: verify declared pairs and report incomplete coverage. --inventory:
JSON inventory without running the compiler. --require-complete: also fail
unless every AIR rejection has a verified same-code source twin.
@@ -89,7 +89,7 @@ def inventory():
allowed = {'kind', 'rule', 'spec', 'site', 'lowering', 'analogues',
'required_ops', 'exact_ops', 'required_identity_uses',
'match_type_declarations', 'early_context', 'audited_context',
'feature_header_context'}
'feature_header_context', 'air_fields'}
if set(review) - allowed:
raise ValueError(f'{name}: unknown/reserved review keys: {sorted(set(review) - allowed)}')
witnesses = review.get('required_ops', {})
@@ -113,7 +113,7 @@ def inventory():
if 'feature_header_context' in review and (
review['feature_header_context'] is not True or expected != ['E0006']):
raise ValueError(f'{name}: feature-header context needs one E0006 rejection')
if review['kind'] not in {'same_code', 'source_error', 'air_only'}:
if review['kind'] not in {'same_code', 'source_error', 'source_early', 'air_only'}:
raise ValueError(f'{name}: invalid classification')
if ({'required_ops', 'exact_ops', 'required_identity_uses', 'match_type_declarations',
'audited_context', 'feature_header_context'} & review.keys()) and (
@@ -129,14 +129,25 @@ def inventory():
raise ValueError(f'{name}: missing source/site')
elif sources:
raise ValueError(f'{name}: analogue/inexpressible case cannot count as a twin')
if review['kind'] == 'source_error' and not review.get('analogues'):
if review['kind'] in {'source_error', 'source_early'} and not review.get('analogues'):
raise ValueError(f'{name}: source-error classification needs an analogue')
if review['kind'] == 'source_early':
if (expected != ['E5101'] or review.get('site') != 'declaration' or
review.get('lowering') != 'rejected' or
not isinstance(review.get('air_fields'), dict) or
set(review['air_fields']) != {'kind', 'limit', 'max', 'found', 'type'}):
raise ValueError(f'{name}: early source analogue needs declaration-budget facts')
elif 'air_fields' in review:
raise ValueError(f'{name}: early AIR facts require source_early')
if review.get('lowering') == 'rejected':
context = review.get('early_context')
if (review['kind'] != 'same_code' or not isinstance(context, dict) or
context_sources = (sources if review['kind'] == 'same_code' else
[a['source'] for a in review.get('analogues', [])])
if (review['kind'] not in {'same_code', 'source_early'} or
not isinstance(context, dict) or
set(context) != {'air', 'sources'} or
not isinstance(context['sources'], dict) or
set(context['sources']) != set(sources) or
set(context['sources']) != set(context_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')
@@ -152,7 +163,13 @@ def inventory():
*context['lowered'].values()])):
raise ValueError(f'{name}: lowered context needs audited AIR/source/lowered fingerprints')
for analogue in review.get('analogues', []):
if not analogue.get('codes') or any(not re.fullmatch(r'E7[0-9]{3}', c) for c in analogue['codes']):
if review['kind'] == 'source_early':
if (analogue.get('codes') != ['E1003'] or
not isinstance(analogue.get('fields'), dict) or
analogue['fields'].get('kind') != 'type.recursive' or
not isinstance(analogue['fields'].get('type'), str)):
raise ValueError(f'{name}: early source analogue must identify E1003/type')
elif 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')
p = corpus_path(analogue['source'], '.aji')
if Counter(codes(p) or []) != Counter(analogue['codes']):
@@ -562,6 +579,33 @@ def verify_analogue(aji, analogue):
for d in ds:
if any(d.get(k) != v for k, v in analogue.get('fields', {}).items()):
raise ValueError(f"{analogue['source']}: analogue rule facts changed")
return ds
def verify_early_analogue(aji, row):
air = CORPUS / row['air']
context = row['early_context']
if hashlib.sha256(air.read_bytes()).hexdigest() != context['air']:
raise ValueError('audited early AIR changed; a new context audit is required')
for analogue in row['analogues']:
source = CORPUS / analogue['source']
if hashlib.sha256(source.read_bytes()).hexdigest() != context['sources'][analogue['source']]:
raise ValueError('audited early source changed; a new context audit is required')
for d in errors(aji, air):
site_key(air.read_text(), d, 'declaration')
if any(d.get(k) != v for k, v in row['air_fields'].items()):
raise ValueError('early AIR rule facts changed')
for analogue in row['analogues']:
source = CORPUS / analogue['source']
ds = verify_analogue(aji, analogue)
lowered = [load_json(x) for x in command(aji, 'lower', source, status=1).splitlines()]
if lowered != ds:
raise ValueError('lower/check early errors differ')
for d in ds:
line = source.read_text().splitlines()[d['line'] - 1].strip()
if (not line.startswith(('struct ', 'enum ')) or d['file'] != str(source) or
'air_line' in d or 'air_col' in d):
raise ValueError('early source analogue lacks an unmapped declaration position')
def main():
@@ -581,12 +625,16 @@ def main():
else:
with tempfile.TemporaryDirectory(prefix='aji-reject-twins-') as directory:
for row in rows:
if row['kind'] == 'source_early':
verify_early_analogue(args.aji, row)
continue
for source in row['sources']:
verify_pair(args.aji, Path(directory), row, source)
for analogue in row.get('analogues', []):
verify_analogue(args.aji, analogue)
print(f"AIR rejection twins: {counts['same_code']}/{len(rows)} same-code cases verified; "
f"{counts['pending']} pending, {counts['source_error']} source-error analogues, "
f"{counts['source_early']} source-early analogues, "
f"{counts['air_only']} AIR-only. P6-7 complete: {report['complete']}.")
if args.require_complete and not report['complete']:
return 1