#!/usr/bin/env python3 """Independent failure probes for the rejection-twin coverage check.""" import importlib.util import hashlib import io 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>', 'b: mut>, other: ref>') 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 atomic_load_pair(self): row = self.fake_pair(source_path='source/reject_twins/ordinary_atomic_field_load.aji', air_path='phase5/reject/ordinary_load.air') row['required_ops'] = {'atomic.new': 1, 'load': 1, 'atomic.take': 1} return row def test_atomic_operand_identity_survives_field_and_ssa_renaming(self): row = self.atomic_load_pair() self.verify_fake(row) p = self.corpus / 's.aji' p.write_text(re.sub(r'\bcell\b', 'item', p.read_text()).replace('Holder', 'Wrapper')) self.verify_fake(row) def test_atomic_load_facts_preserve_scalar_and_borrow_mode(self): original = (REAL_CORPUS / 'source/reject_twins/ordinary_atomic_field_load.aji').read_text() for changed in (original.replace('u64', 'u8'), original.replace('u64', 'bool').replace('0bool', 'false'), original.replace('ref r = holder', 'mut r = holder')): with self.subTest(source=changed): row = self.atomic_load_pair() p = self.corpus / 's.aji' p.write_text(changed) with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): self.verify_fake(row) def test_another_atomic_borrow_cannot_replace_the_offending_operand(self): row = self.atomic_load_pair() p = self.corpus / 'a.air' p.write_text(p.read_text().replace('%r = borrow.ref %c', '%r = borrow.ref %c\n %other = borrow.ref %c\n borrow.end %other')) 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()] ds[0]['operand'] = '%other' return '\n'.join(json.dumps(d) for d in ds) + '\n' return result with patch.object(twins, 'command', changed): with self.assertRaisesRegex(ValueError, 'atomic operand is not the offending load operand'): self.verify_fake(row) def test_atomic_source_raw_identity_mapping_stays_exact(self): row = self.atomic_load_pair() 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]['operand'] = '%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_endpoint_rule_cannot_substitute_mutex_for_channel_creation(self): row = self.fake_pair(source_path='source/reject_twins/channel_endpoint_element.aji', air_path='phase3/reject/channels_endpoint_element.air') self.verify_fake(row) p = self.corpus / 's.aji' p.write_text('// expect: reject E0006\n// AIR twin: a.air\n' 'module test.endpoint_mutex\n' 'fn f(tx: sender) -> void effects [] {\n' ' let m = mutex.make(move tx); // diagnostic here: mutex.make\n' ' trap;\n}\nfn main() -> void effects [] {}\n') with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): self.verify_fake(row) def task_parameter_pair(self): row = self.fake_pair(source_path='source/reject_twins/task_handle_parameter.aji', air_path='phase3/reject/tasks_handle_as_parameter.air') row.update(site='function', feature_header_context=True) return row def test_feature_pair_keeps_rule_with_different_unrelated_features(self): row = self.task_parameter_pair() air = self.corpus / 'a.air' original = air.read_text() for header in ('features [ownership, tasks]', 'features [arrays, effects, ownership, tasks] ; inline context'): with self.subTest(header=header): air.write_text(original.replace('features [arrays, ownership, tasks]', header)) self.verify_fake(row) def test_task_result_cannot_replace_task_parameter_feature_rule(self): row = self.task_parameter_pair() source = self.corpus / 's.aji' source.write_text(source.read_text().replace('fn f(t: task) -> void', 'fn f() -> task')) with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): self.verify_fake(row) def test_additional_missing_feature_cannot_reuse_single_error_pair(self): row = self.task_parameter_pair() air = self.corpus / 'a.air' air.write_text(air.read_text().replace('features [arrays, ownership, tasks]', 'features [arrays, ownership]')) with self.assertRaisesRegex(ValueError, 'diagnostics do not match rejection header'): self.verify_fake(row) def test_same_feature_error_cannot_hide_a_larger_missing_closure(self): row = self.task_parameter_pair() air = self.corpus / 'a.air' air.write_text(air.read_text().replace('features [arrays, ownership, tasks]', 'features [arrays, ownership]')) real_command = twins.command def changed(aji, *args, status): result = real_command(aji, *args, status=status) if args[0] == 'check' and Path(args[1]) == air: ds = [json.loads(line) for line in result.splitlines()] # Isolate task_transfer so diagnostic count cannot mask the closure check. return '\n'.join(json.dumps(d) for d in ds if d.get('feature') == 'task_transfer') + '\n' return result with patch.object(twins, 'command', changed): with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): self.verify_fake(row) def test_invalid_feature_repair_facts_fail_closed(self): row = self.task_parameter_pair() real_command = twins.command changes = [ {'canonical_header': 'features [arrays, task_transfer, tasks]'}, {'canonical_header': 'features [arrays, heap, ownership, task_transfer, tasks]'}, {'canonical_header': 'features [tasks, task_transfer, ownership, arrays]'}, {'closure': 'ownership, task_transfer, task_transfer, tasks'}, {'closure': 'ownership, , task_transfer, tasks'}, {'closure': 'ownership, tasks'}, {'closure': None}, {'canonical_header': None}, {'reason': 'missing_dependency'}, ] for fields in changes: with self.subTest(fields=fields): def changed(aji, *args, status): result = real_command(aji, *args, status=status) if args[0] == 'check' and Path(args[1]) == self.corpus / 'a.air': ds = [json.loads(line) for line in result.splitlines()] ds[0].update(fields) return '\n'.join(json.dumps(d) for d in ds) + '\n' return result with patch.object(twins, 'command', changed): with self.assertRaisesRegex(ValueError, 'feature.*(context|header|rule)'): self.verify_fake(row) def test_feature_context_does_not_relax_source_raw_payload_mapping(self): row = self.task_parameter_pair() 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]['canonical_header'] = 'features [ownership, task_transfer, tasks]' 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 rule facts'): self.verify_fake(row) def pin_pair_context(self, row): p = self.corpus / 's.aji' canonical = twins.command(AJI, 'lower', p, status=0) row['audited_context'] = { 'air': hashlib.sha256((self.corpus / 'a.air').read_bytes()).hexdigest(), 'sources': {'s.aji': hashlib.sha256(p.read_bytes()).hexdigest()}, 'lowered': {'s.aji': hashlib.sha256(canonical.encode('utf-8')).hexdigest()}, } return row def audited_cfg_pair(self, source='cfg_provenance_loan_br', air='cfg_provenance_loan_br'): return self.pin_pair_context(self.fake_pair( source_path=f'source/reject_twins/{source}.aji', air_path=f'phase3/reject/{air}.air')) def swap_pair(self): return self.fake_pair(source_path='source/reject_twins/linear_swap_leak.aji', air_path='linear/swap_leak.air') def test_swapped_enum_nominal_family_cannot_change(self): row = self.swap_pair() self.verify_fake(row) p = self.corpus / 's.aji' p.write_text(p.read_text().replace('Maybe', 'OtherEnum')) with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): self.verify_fake(row) def test_swap_replacement_call_needs_a_separate_identity_audit(self): row = self.swap_pair() p = self.corpus / 's.aji' text = p.read_text().replace('value.swap(mut slot, Maybe::none)', 'value.swap(mut slot, replacement())') p.write_text(text + '\nfn replacement() -> Maybe effects [] { return Maybe::none; }\n') self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002']) with self.assertRaisesRegex(ValueError, 'swapped enum replacement lacks a named enum declaration'): self.verify_fake(row) def test_swap_leak_cannot_omit_audited_array_unpack(self): row = self.swap_pair() row['match_type_declarations'] = True self.pin_pair_context(row) self.verify_fake(row) p = self.corpus / 's.aji' text = p.read_text() text = text.replace(' let items = [move owner];\n', '') text = text.replace(' let (part) = array.unpack(move items);\n', '') p.write_text(text.replace('Maybe::some(move part)', 'Maybe::some(move owner)')) self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002']) with self.assertRaisesRegex(ValueError, 'audited source changed'): self.verify_fake(row) def test_same_swap_leak_on_other_arm_cannot_replace_audited_branch(self): row = self.swap_pair() row['match_type_declarations'] = True self.pin_pair_context(row) self.verify_fake(row) p = self.corpus / 's.aji' text = p.read_text() start = text.index(' match move old {') end = text.index('\n }\n Maybe::none', start) consuming = text[start:end] text = text[:start] + ' return n; // diagnostic here' + text[end:] leaking = ' return n; // diagnostic here\n }' # Put the existing consumption on the none arm instead of the some arm. index = text.index(' Maybe::none => {\n' + leaking) text = text[:index] + text[index:].replace(leaking, consuming + '\n }', 1) p.write_text(text) self.assertEqual([d['code'] for d in twins.errors(AJI, p)], ['E3002']) with self.assertRaisesRegex(ValueError, 'audited source changed'): self.verify_fake(row) def test_straight_line_loan_cannot_replace_audited_handoff(self): row = self.audited_cfg_pair() self.verify_fake(row) text = (REAL_CORPUS / 'source/cfg_provenance/tasks_end_lent_borrow.aji').read_text() text = re.sub(r'^// AIR twin: .+$', '// AIR twin: a.air', text, flags=re.MULTILINE) (self.corpus / 's.aji').write_text(text) with self.assertRaisesRegex(ValueError, 'audited source changed'): self.verify_fake(row) def test_single_handoff_cannot_replace_audited_loop_or_merge(self): for air in ('cfg_provenance_loan_backedge', 'cfg_provenance_loan_join'): with self.subTest(air=air): row = self.audited_cfg_pair(source=air, air=air) self.verify_fake(row) text = (REAL_CORPUS / 'source/reject_twins/cfg_provenance_loan_br.aji').read_text() text = re.sub(r'^// AIR twin: .+$', '// AIR twin: a.air', text, flags=re.MULTILINE) (self.corpus / 's.aji').write_text(text) with self.assertRaisesRegex(ValueError, 'audited source changed'): self.verify_fake(row) def test_changed_audited_air_requires_a_fresh_review(self): row = self.audited_cfg_pair() self.verify_fake(row) (self.corpus / 'a.air').write_text( (REAL_CORPUS / 'phase3/reject/tasks_end_lent_borrow.air').read_text()) with self.assertRaisesRegex(ValueError, 'audited AIR changed'): self.verify_fake(row) def test_deterministic_lowering_drift_requires_a_fresh_review(self): row = self.audited_cfg_pair() self.verify_fake(row) real_command = twins.command def changed(aji, *args, status): result = real_command(aji, *args, status=status) if args[0] == 'lower' and '--annotate' not in args: return result.replace('module test.cfg', 'module changed.cfg') return result with patch.object(twins, 'command', changed): with self.assertRaisesRegex(ValueError, 'audited lowering changed'): self.verify_fake(row) def test_lowered_context_cannot_omit_one_artifact(self): row = self.audited_cfg_pair() del row['audited_context']['lowered']['s.aji'] self.manifest.write_text(json.dumps({'version': 1, 'cases': {'a.air': row}})) # Manifest rows contain review facts, not computed inventory columns. data = json.loads(self.manifest.read_text()) for field in ('air', 'sources', 'codes'): del data['cases']['a.air'][field] self.manifest.write_text(json.dumps(data)) with patch.object(twins, 'CORPUS', self.corpus), patch.object(twins, 'MANIFEST', self.manifest): with self.assertRaisesRegex(ValueError, 'lowered context needs audited'): twins.inventory() def test_guard_parent_end_cannot_replace_guard_unlock(self): row = self.fake_pair(source_path='source/borrow_returns/lock_escape.aji', air_path='phase3/reject/sync_unlock_live_borrow.air') self.verify_fake(row) (self.corpus / 'a.air').write_text( (REAL_CORPUS / 'phase3/reject/cfg_provenance_guard_parent.air').read_text()) with self.assertRaisesRegex(ValueError, 'different offending operation/rule facts'): 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', 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 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') 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()