Files
aji/tests/hosted/source_reject_twins.py
T

417 lines
23 KiB
Python

#!/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
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location('source_reject_twins', ROOT / 'tools/source_reject_twins.py')
twins = importlib.util.module_from_spec(spec)
spec.loader.exec_module(twins)
AJI = ROOT / 'zig-out/bin/aji'
REAL_CORPUS = twins.CORPUS
class CoverageFailures(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='aji-twin-oracle-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.corpus = self.root / 'corpus'
self.corpus.mkdir()
self.manifest = self.corpus / 'reject-twins.json'
def fake_pair(self, source_name='fence_relaxed', air_name='fence_relaxed', source_path=None, air_path=None):
air = REAL_CORPUS / (air_path or f'phase5/reject/{air_name}.air')
source = REAL_CORPUS / (source_path or f'source/reject_twins/{source_name}.aji')
(self.corpus / 'a.air').write_text(air.read_text())
source_text = source.read_text()
source_text = re.sub(r'^// AIR twin: .+$', '// AIR twin: a.air', source_text, flags=re.MULTILINE)
(self.corpus / 's.aji').write_text(source_text)
rule = {'kind': 'same_code', 'site': 'instruction',
'spec': 'docs/spec/04-concurrency-and-atomics.md §24',
'rule': 'Test audit; the executable check must still reject mismatched rules.'}
self.manifest.write_text(json.dumps({'version': 1, 'cases': {'a.air': rule}}))
return {'air': 'a.air', 'sources': ['s.aji'], 'codes': twins.codes(air), **rule}
def verify_fake(self, row):
with patch.object(twins, 'CORPUS', self.corpus):
twins.verify_pair(AJI, self.root, row, 's.aji')
def test_valid_pair_survives_changed_file_and_ssa_identity(self):
self.verify_fake(self.fake_pair())
def test_share_pair_survives_worker_and_argument_renaming(self):
row = self.fake_pair(source_path='source/layer7/reject/not_share.aji',
air_path='phase3/reject/tasks_not_share.air')
p = self.corpus / 's.aji'
text = p.read_text().replace('look', 'inspect_region')
p.write_text(re.sub(r'\br\b', 'arena_owner', text))
self.verify_fake(row)
def test_same_share_code_does_not_hide_a_different_parameter_type(self):
row = self.fake_pair(source_path='source/layer9/reject/lend_island.aji',
air_path='phase3/reject/tasks_not_share.air')
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_same_send_code_does_not_hide_a_different_task_handle_type(self):
row = self.fake_pair(source_path='source/reject_twins/task_handle_not_send.aji',
air_path='phase3/reject/tasks_not_send.air')
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('u8', 'u64'))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_changed_argument_identity_cannot_survive_source_mapping(self):
row = self.fake_pair(source_path='source/layer7/reject/not_share.aji',
air_path='phase3/reject/tasks_not_share.air')
real_command = twins.command
def changed(aji, *args, status):
result = real_command(aji, *args, status=status)
if args[0] == 'check' and Path(args[1]) == self.corpus / 's.aji':
ds = [json.loads(line) for line in result.splitlines()]
ds[0]['argument'] = '%wrong'
return '\n'.join(json.dumps(d) for d in ds) + '\n'
return result
with patch.object(twins, 'command', changed):
with self.assertRaisesRegex(ValueError, 'mapping changed diagnostic identities'):
self.verify_fake(row)
def test_changed_related_value_cannot_survive_source_mapping(self):
row = self.fake_pair(source_path='source/layer34/reject/borrow_conflict.aji',
air_path='phase1/reject/mut_and_shared.air')
real_command = twins.command
def changed(aji, *args, status):
result = real_command(aji, *args, status=status)
if args[0] == 'check' and Path(args[1]) == self.corpus / 's.aji':
ds = [json.loads(line) for line in result.splitlines()]
ds[0]['related_locations'][0]['value'] = '%wrong'
return '\n'.join(json.dumps(d) for d in ds) + '\n'
return result
with patch.object(twins, 'command', changed):
with self.assertRaisesRegex(ValueError, 'mapping changed related identity'):
self.verify_fake(row)
def test_graph_borrow_pair_survives_renamed_bindings(self):
row = self.fake_pair(source_path='source/layer9/reject/two_mut_access.aji',
air_path='phase4/reject/island_two_mut.air')
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('mut x =', 'mut first =').replace('mut y =', 'mut second ='))
self.verify_fake(row)
def test_container_only_conflict_cannot_replace_live_child_regression(self):
row = self.fake_pair(source_path='source/layer9/reject/destroy_while_borrowed.aji',
air_path='phase4/reject/island_destroy_while_borrowed.air')
row['required_ops'] = {'island.borrow': 1, 'load': 1}
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('island.destroy(move isl);',
'island.destroy(move isl); // diagnostic here'))
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'):
self.verify_fake(row)
def test_same_operation_different_invalid_order_is_not_a_twin(self):
row = self.fake_pair(air_name='load_release', source_name='load_release')
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('ref c, release', 'ref c, acq_rel'))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_comment_cannot_spoof_a_leaked_resources_type(self):
row = self.fake_pair(source_path='source/reject_twins/frozen_leak.aji',
air_path='phase2/reject/region_leak.air')
p = self.corpus / 'a.air'
d, = twins.errors(AJI, p)
p.write_text(p.read_text().replace('entry:', 'entry:\n ; ' + d['borrow'] + ': frozen<u64>', 1))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_changed_related_role_cannot_survive_source_mapping(self):
row = self.fake_pair(source_path='source/layer34/reject/borrow_conflict.aji',
air_path='phase1/reject/mut_and_shared.air')
real_command = twins.command
def changed(aji, *args, status):
result = real_command(aji, *args, status=status)
if args[0] == 'check' and Path(args[1]) == self.corpus / 's.aji':
ds = [json.loads(line) for line in result.splitlines()]
ds[0]['related_locations'][0]['role'] = 'task_spawn'
return '\n'.join(json.dumps(d) for d in ds) + '\n'
return result
with patch.object(twins, 'command', changed):
with self.assertRaisesRegex(ValueError, 'mapping changed related roles'):
self.verify_fake(row)
def test_a_plain_loan_error_cannot_replace_a_cancelled_join_regression(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase3/reject/cancel_join_keeps_loans.air')
with self.assertRaisesRegex(ValueError, 'missing required operation witness'):
twins.verify_pair(AJI, self.root, row, 'source/cfg_provenance/tasks_end_lent_borrow.aji')
def test_changed_analogue_reason_is_detected_independently(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase1/reject/borrow_return_without_from.air')
analogue = {**row['analogues'][0], 'fields': {'reason': 'move_copy'}}
with self.assertRaisesRegex(ValueError, 'analogue rule facts changed'):
twins.verify_analogue(AJI, analogue)
def test_same_ret_and_leak_code_different_resource_family_is_not_a_twin(self):
row = self.fake_pair(source_path='source/reject_twins/frozen_leak.aji',
air_path='phase2/reject/region_leak.air')
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_two_source_locations_cannot_be_dropped_as_one_raw_error(self):
row = self.fake_pair()
p = self.corpus / 's.aji'
text = p.read_text()
line = next(line for line in text.splitlines() if 'atomic.fence(relaxed)' in line)
p.write_text(text.replace(line, line + '\n' + line).replace('reject E4201', 'reject E4201 E4201'))
with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'):
self.verify_fake(row)
def test_block_site_cannot_pass_an_instruction_twin(self):
row = self.fake_pair()
row['site'] = 'block'
with self.assertRaisesRegex(ValueError, 'expected block label'):
self.verify_fake(row)
def test_ambiguous_marker_is_rejected_instead_of_selecting_first_token(self):
with self.assertRaisesRegex(ValueError, 'unique code fragment'):
twins.positions(' let x = x; // diagnostic here: x')
def test_markers_in_comments_are_not_source_sites(self):
self.assertEqual(twins.positions('// note // diagnostic here: note'), [])
def test_wrong_independent_source_marker_is_rejected(self):
row = self.fake_pair()
p = self.corpus / 's.aji'
p.write_text(p.read_text().replace('here: atomic.fence', 'here: relaxed'))
with self.assertRaisesRegex(ValueError, 'marked source positions'):
self.verify_fake(row)
def test_new_rejection_is_pending_without_any_manual_inventory_update(self):
self.fake_pair()
(self.corpus / 'new.air').write_text((self.corpus / 'a.air').read_text())
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
rows = twins.inventory()
self.assertEqual([(r['air'], r['kind']) for r in rows], [('a.air', 'same_code'), ('new.air', 'pending')])
def test_air_only_cannot_hide_a_declared_source_twin(self):
self.fake_pair()
data = json.loads(self.manifest.read_text())
data['cases']['a.air']['kind'] = 'air_only'
self.manifest.write_text(json.dumps(data))
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
with self.assertRaisesRegex(ValueError, 'lacks a same-code rule audit'):
twins.inventory()
def test_manual_review_cannot_override_discovered_pair_identity(self):
self.fake_pair()
data = json.loads(self.manifest.read_text())
data['cases']['a.air']['sources'] = []
self.manifest.write_text(json.dumps(data))
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
with self.assertRaisesRegex(ValueError, 'reserved review keys'):
twins.inventory()
def test_deleted_air_rejection_is_not_silently_removed(self):
self.fake_pair()
(self.corpus / 'a.air').unlink()
with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest):
with self.assertRaisesRegex(ValueError, 'invalid corpus path'):
twins.inventory()
def test_duplicate_json_fields_do_not_survive_last_key_wins(self):
with self.assertRaisesRegex(ValueError, 'duplicate JSON member'):
twins.load_json('{"code":"E4201","code":"E7005"}')
def test_early_recursive_declaration_is_checked_without_claiming_lowered_air(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase0/reject/recursive_type.air')
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')
twins.verify_pair(AJI, self.root, row, row['sources'][0])
def test_budget_header_uses_marked_function_not_instruction_annotation(self):
rows = twins.inventory()
row = next(r for r in rows if r['air'] == 'phase1/reject/frame_too_large.air')
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()