"""Adversarial publication-7 audit tests: no generator imports or production writes."""
import copy
import hashlib
import json
import sqlite3

import pytest

from scripts import verify_mask_quota_100 as audit


POLYGON = [[1, 1], [20, 1], [20, 10], [15, 10], [15, 5], [5, 5], [5, 10], [1, 10]]


def row(key='human', cls=10):
    return dict(target_key=key, target_id=key+'::box:0000', frame_id='frame-'+key,
        final_class_id=cls, split='train', policy_id='camera', viewpoint_candidate='front',
        group_id='group', box_index=0, bbox=dict(x=1, y=1, width=19, height=9),
        size=[24, 16], source_pcd_sha256='pcd')


def store(current, events=()):
    return dict(path=audit.Path('readonly.sqlite3'), metadata={}, current=current,
        events=list(events), history_keys={e[1] for e in events})


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(audit.canonical(value)+b'\n')


def write_jsonl(path, values):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(b''.join(audit.canonical(v)+b'\n' for v in values))


@pytest.fixture
def manual_fixture():
    r = row()
    human = dict(target_key='human', source=r, polygon=copy.deepcopy(POLYGON), revision=4,
        state='draft', **dict.fromkeys(audit.FALSE_FLAGS, False))
    current = dict(human, revision=5, event_kind='axes_normalization')
    raw = json.dumps(human, indent=2)
    pose = store({'human': current}, [(1, 'human', 4, raw), (2, 'human', 5, json.dumps(current))])
    direct = audit.v1.independent_pose_templates(pose, {'human': r})
    t = direct['human']
    template = dict(t, origin=audit.POSE_ORIGIN, pose_review=audit.v1.pose_provenance(t, 'snapshot'))
    request = dict(target_key='human', class_id=10, pose_annotation_url='https://example.test/?target=human',
        source=dict(r, formal_manifest_sha256='formal'), requested_required_vertex_count=None)
    p = dict(target_key='human', class_id=10, source=r, polygon=copy.deepcopy(POLYGON), vertex_count=8,
        schema='saved_pose_mask_gallery_entry_v1', origin=audit.POSE_ORIGIN,
        human_edited=True, status='human_edited_draft_pending_confirmation',
        source_label_kind='human_mask_source_manual_template_draft',
        manual_source_kind='completed_manual_request',
        **dict.fromkeys(audit.FALSE_FLAGS, False), pose_snapshot_saved=True,
        pose_store_written=False, gallery_store_written=False, machine_transfer_performed=False,
        new_human_edit_created=False, manual_request_sha256=audit.sha(request),
        original_pose_url=request['pose_annotation_url'], rendering_id='quota100_generation:human',
        snapshot_sha256='snapshot', target_expected_revision=5, target_snapshot_payload_sha256=audit.sha(current),
        formal_manifest_sha256='formal', class_assignments_sha256='classes',
        template=audit.template_binding(template), metrics={}, flags=['manual_source_not_machine_transfer'])
    return p, request, pose, direct, r, 'snapshot', 'formal', 'classes'


def test_actual_saved_manual_topology_is_not_forced_to_twelve_vertices(manual_fixture):
    audit.check_manual(*manual_fixture)
    assert manual_fixture[0]['vertex_count'] == 8
    assert manual_fixture[0]['template']['human_polygon_revision'] == 4
    assert manual_fixture[0]['template']['snapshot_revision'] == 5
    assert manual_fixture[0]['template']['human_event_sha256'] != audit.sha(json.loads(manual_fixture[2]['events'][0][3]))


@pytest.mark.parametrize('attack', ['polygon', 'vertices', 'class', 'split', 'source', 'event_hash', 'current_hash',
    'revision', 'snapshot', 'request_hash', 'request_url', 'self_source', 'origin', 'namespace', 'status',
    'human', 'GT', 'training', 'robot', 'confirmation', 'source_confirmation', 'source_gt', 'transfer_metrics',
    'continuation', 'write', 'deleted', 'deferred', 'flag'])
def test_manual_provenance_cannot_be_stale_transferred_or_confirmed(manual_fixture, attack):
    p, request, pose, *_ = manual_fixture
    if attack == 'polygon':
        p['polygon'][0][0] += 1
    elif attack == 'vertices':
        p['vertex_count'] = 12
    elif attack == 'class':
        p['class_id'] = 2
    elif attack == 'split':
        request['source'] = dict(request['source'], split='test')
    elif attack == 'source':
        p['source'] = dict(p['source'], frame_id='another-frame')
    elif attack == 'event_hash':
        p['template']['human_event_sha256'] = audit.sha(json.loads(pose['events'][0][3]))
    elif attack == 'current_hash':
        p['target_snapshot_payload_sha256'] = 'stale'
    elif attack == 'revision':
        p['target_expected_revision'] -= 1
    elif attack == 'snapshot':
        p['snapshot_sha256'] = 'historical-snapshot'
    elif attack == 'request_hash':
        p['manual_request_sha256'] = 'unrequested'
    elif attack == 'request_url':
        p['original_pose_url'] = 'https://example.test/?target=another'
    elif attack == 'self_source':
        p['template']['target_key'] = 'another'
    elif attack == 'origin':
        p['template']['origin'] = 'machine'
    elif attack == 'namespace':
        p['rendering_id'] = 'quota_generation:human'
    elif attack == 'status':
        p['status'] = 'machine_draft_pending_visual_review'
    elif attack == 'human':
        p['human_edited'] = False
    elif attack in ('GT', 'training', 'robot', 'confirmation'):
        p[dict(GT='ground_truth_eligible', training='automatic_training_eligible',
            robot='robot_command_eligible', confirmation='human_mask_confirmed')[attack]] = True
    elif attack in ('source_confirmation', 'source_gt'):
        pose['current']['human']['human_mask_confirmed' if attack == 'source_confirmation' else 'ground_truth_eligible'] = True
    elif attack == 'transfer_metrics':
        p['metrics'] = {'ecc': 1.0}
    elif attack == 'continuation':
        p['continuation'] = {'batch': 7}
    elif attack == 'write':
        p['gallery_store_written'] = True
    elif attack in ('deleted', 'deferred'):
        pose['current']['human']['state'] = attack
    else:
        p['flags'] = []
    with pytest.raises(ValueError):
        audit.check_manual(*manual_fixture)


def candidate(key, cls=1, frame=None, group='group', quality=.9):
    r = row(key, cls)
    r['group_id'] = group
    if frame is not None:
        r['frame_id'] = frame
    return dict(target_key=key, class_id=cls, source=r, metrics=dict(boundary_ncc=quality, ecc=.95))


def test_hundred_cap_is_independent_of_historical_fifty_cap():
    values = [candidate(str(i)) for i in range(100)]
    assert audit.count_frames(values)['1'] == dict(proposals=100, distinct_frames=100, shortfall=0)
    with pytest.raises(ValueError, match='exceeds 100'):
        audit.count_frames(values+[candidate('overflow')])
    values[0]['source']['frame_id'] = values[1]['source']['frame_id']
    with pytest.raises(ValueError, match='Repeated frame'):
        audit.count_frames(values)


def quota_fixture():
    old, old_manual, gallery = {}, {}, {'current': {}}
    # Exact publication-6 class counts; saved gallery 164 + inherited manual 30.
    gallery_counts = {1: 27, 2: 42, 9: 29, 10: 23, 15: 43}
    manual_counts = {1: 2, 2: 8, 9: 3, 10: 14, 15: 3}
    for cls in audit.CLASSES:
        for i in range(37 if cls == 10 else 50):
            key = f'{cls}-{i}'
            old[key] = candidate(key, cls)
            if i < gallery_counts[cls]:
                gallery['current'][key] = dict(polygon=POLYGON)
            elif i < gallery_counts[cls]+manual_counts[cls]:
                old_manual[key] = old[key]
    manual = {f'newhuman-{i}': candidate(f'newhuman-{i}', 10) for i in range(13)}
    return old, old_manual, manual, gallery


def test_baseline_is_250_with_207_humans_and_43_unreviewed_not_fake_250_humans():
    old, old_manual, manual, gallery = quota_fixture()
    classes, counts = audit.expected_counts(old, old_manual, manual, {}, gallery)
    assert len(old) == 237 and len(old_manual) == 30 and len(manual) == 13
    assert all(c['distinct_frames'] == 50 for c in counts.values())
    assert sum(c['saved_human'] for c in classes.values()) == 207
    assert sum(c['prior_machine_pending'] for c in classes.values()) == 43
    assert sum(c['saved_pose_human'] for c in classes.values()) == 43
    assert sum(c['saved_gallery_human'] for c in classes.values()) == 164
    assert all(c['missing'] == 50 and c['goal'] == 100 for c in classes.values())


def test_authorized_44_reuse_gives_294_base_251_saved_and_no_invented_new_edits():
    old, old_manual, manual, gallery = quota_fixture()
    for cls, count in {1: 5, 2: 2, 9: 8, 15: 29}.items():
        manual.update({f'reuse-{cls}-{i}': candidate(f'reuse-{cls}-{i}', cls) for i in range(count)})
    classes, counts = audit.expected_counts(old, old_manual, manual, {}, gallery)
    assert len(manual) == 57
    assert {c: v['distinct_frames'] for c, v in counts.items()} == {'1': 55, '2': 52, '9': 58, '10': 50, '15': 79}
    assert sum(c['saved_human'] for c in classes.values()) == 251
    assert sum(c['prior_machine_pending'] for c in classes.values()) == 43
    assert sum(c['saved_pose_human'] for c in classes.values()) == 87


@pytest.fixture
def reused_fixture(manual_fixture):
    p, _, pose, direct, r, *rest = manual_fixture
    p.pop('manual_request_sha256')
    p.update(manual_source_kind='existing_saved_human_reuse_for_100_goal', machine_transfer_performed=False, new_human_edit_created=False,
        manual_reuse_authorization='Explicit user authorization to count existing genuine saved '
            'original-pose human masks toward the 100-per-class goal; no synthetic request')
    p['flags'].append('existing_human_reuse_not_new_edit')
    return p, None, pose, direct, r, *rest


def test_existing_saved_reuse_has_self_source_without_fake_request(reused_fixture):
    audit.check_manual(*reused_fixture)
    assert reused_fixture[0]['metrics'] == {}
    assert 'manual_request_sha256' not in reused_fixture[0]


@pytest.mark.parametrize('attack', ['fake_request', 'new_edit', 'transfer', 'source_kind', 'source_url',
    'current_raw_hash', 'human_event_hash', 'not_draft', 'source_pcd', 'confirmation'])
def test_existing_reuse_cannot_be_claimed_as_requested_new_machine_or_confirmed(reused_fixture, attack):
    p, _, pose, *_ = reused_fixture
    if attack == 'fake_request':
        p['manual_request_sha256'] = 'fabricated'
    elif attack == 'new_edit':
        p['new_human_edit_created'] = True
    elif attack == 'transfer':
        p['machine_transfer_performed'] = True
    elif attack == 'source_kind':
        p['manual_source_kind'] = 'completed_class10_manual_request'
    elif attack == 'source_url':
        p['original_pose_url'] = 'https://example.test/?target=another'
    elif attack == 'current_raw_hash':
        p['template']['current_payload_sha256'] = 'stale'
    elif attack == 'human_event_hash':
        p['template']['human_event_sha256'] = 'stale'
    elif attack == 'not_draft':
        pose['current']['human']['state'] = 'confirmed'
    elif attack == 'source_pcd':
        pose['current']['human']['source'] = dict(pose['current']['human']['source'], source_pcd_sha256='other')
    else:
        p['human_pose_confirmed'] = True
    with pytest.raises(ValueError):
        audit.check_manual(*reused_fixture)


def test_reuse_universe_comes_from_actual_human_events_not_every_pose_save():
    keys = ('genuine', 'machine', 'rectangle', 'deleted', 'deferred', 'confirmed', 'other-class', 'parent', 'parent-frame', 'requested')
    rows, current, events = {}, {}, []
    for i, key in enumerate(keys, 1):
        r = row(key, 15 if key != 'other-class' else 3)
        if key == 'parent-frame':
            r['frame_id'] = 'frame-parent'
        rows[key] = r
        value = dict(target_key=key, source=r, revision=1, state='draft', polygon=copy.deepcopy(POLYGON),
            **dict.fromkeys(audit.FALSE_FLAGS, False))
        if key == 'machine':
            value['event_kind'] = 'mask_template_proposal'
        elif key == 'rectangle':
            value['polygon'] = [[1, 1], [20, 1], [20, 10], [1, 10]]
        elif key in ('deleted', 'deferred'):
            value['state'] = key
        elif key == 'confirmed':
            value['human_mask_confirmed'] = True
        current[key] = value
        events.append((i, key, 1, json.dumps(value)))
    pose = store(current, events)
    direct = audit.v1.independent_pose_templates(pose, rows)
    result = audit.independent_reuse_keys(pose, direct, rows, {'parent': candidate('parent', 15)},
        {'requested': dict(source=rows['requested'])})
    assert result == {'genuine'}


def test_reuse_source_identity_and_distinct_frames_are_independently_checked(manual_fixture):
    _, _, pose, direct, r, *_ = manual_fixture
    pose['current']['human']['source'] = dict(r, frame_id='stale-image')
    with pytest.raises(ValueError, match='original source frame_id'):
        audit.independent_reuse_keys(pose, direct, {'human': r}, {}, {})


def test_partition_preserves_all_237_objects_and_only_new_machine_sidecar():
    old, old_manual, manual, _ = quota_fixture()
    new = {'machine': candidate('machine')}
    combined = {**old, **manual, **new}
    args = (old, old_manual, manual, new, combined, new, {**old_manual, **manual})
    audit.check_partition(*args)
    combined['1-0'] = dict(combined['1-0'], changed=True)
    with pytest.raises(ValueError, match='canonical object'):
        audit.check_partition(*args)


def test_manual_self_sources_and_pending_parent_cannot_be_accepted_transfers():
    old, old_manual, manual, _ = quota_fixture()
    combined = {**old, **manual}
    with pytest.raises(ValueError, match='treated as accepted transfer'):
        audit.check_partition(old, old_manual, manual, {}, combined, manual, {**old_manual, **manual})
    with pytest.raises(ValueError, match='treated as accepted transfer'):
        audit.check_partition(old, old_manual, manual, {}, combined, old, {**old_manual, **manual})


def test_selection_counts_manual_frames_and_excludes_duplicate_frames():
    base = {str(i): candidate(str(i)) for i in range(99)}
    base['human'] = candidate('human')
    accepted = {'dup': candidate('dup', frame='frame-human'), 'fresh': candidate('fresh')}
    outcomes = dict(dup=dict(reason='accepted_duplicate_frame_not_selected'), fresh=dict(reason='accepted_quota_full_not_selected'))
    audit.check_diversity(base, accepted, {}, outcomes)
    with pytest.raises(ValueError, match='Diversity disposition'):
        audit.check_diversity({k: p for k, p in base.items() if k != 'human'}, accepted, {}, outcomes)


def test_selection_prefers_new_group_before_quality_and_keeps_honest_shortfall():
    base = {str(i): candidate(str(i)) for i in range(99)}
    accepted = {'strong': candidate('strong', quality=.99), 'diverse': candidate('diverse', group='new', quality=.8)}
    outcomes = dict(strong=dict(reason='accepted_quota_full_not_selected'), diverse=dict(reason='new_proposal'))
    audit.check_diversity(base, accepted, {'diverse': accepted['diverse']}, outcomes)
    audit.check_diversity({}, {}, {}, {})  # No forced fill when registration finds nothing.


def test_seed_union_keeps_full_latest_pose_gallery_union_with_gallery_preferred(manual_fixture):
    _, _, pose, _, r, *_ = manual_fixture
    latest = dict(row=r, polygon=POLYGON[:-1], origin=audit.GALLERY_ORIGIN)
    direct, templates = audit.independent_seed_union(pose, {'human': latest}, {'human': r}, 'snap', {}, {})
    assert direct['human']['polygon'] == POLYGON
    assert templates == {'human': latest}
    _, templates = audit.independent_seed_union(pose, {}, {'human': r}, 'snap', {'human': {}}, {'human': {}})
    assert templates['human']['origin'] == audit.POSE_ORIGIN
    with pytest.raises(ValueError, match='Unreviewed historical machine'):
        audit.independent_seed_union(pose, {}, {'human': r}, 'snap', {'human': {}}, {})


class Evidence:
    def patch(self, key):
        return key

    def image(self, frame):
        return frame


@pytest.fixture
def attempt_fixture(tmp_path, monkeypatch):
    r = row('target', 2)
    t = dict(row=row('seed', 2), polygon=POLYGON)
    trial = dict(target_key='target', class_id=2, template_key='seed', metrics=dict(rejection='affine_registration_failed'))
    write_jsonl(tmp_path/'registration_attempts.jsonl', [trial])
    write_jsonl(tmp_path/'new_proposals.jsonl', [])
    monkeypatch.setattr(audit, 'correlate', lambda *_: .9)
    monkeypatch.setattr(audit, 'transfer', lambda *_: (None, copy.deepcopy(trial['metrics'])))
    outcome = dict(target_key='target', class_id=2, reason='registration_or_boundary_rejected')
    args = (tmp_path, {'target': r}, {'target': 'eligible'}, {'history_keys': set()}, {}, {},
            {'seed': t}, {}, {'target': outcome}, Evidence())
    return args, trial


def test_rejected_attempts_are_recomputed_not_just_trusted(attempt_fixture, monkeypatch):
    args, _ = attempt_fixture
    assert audit.audit_attempts(*args) == ({'target'}, 1)
    monkeypatch.setattr(audit, 'transfer', lambda *_: (None, dict(rejection='different-reason')))
    with pytest.raises(ValueError, match='value differs'):
        audit.audit_attempts(*args)


def test_falsely_rejected_passing_attempt_is_detected(attempt_fixture, monkeypatch):
    args, _ = attempt_fixture
    monkeypatch.setattr(audit, 'transfer', lambda *_: (POLYGON, {}))
    monkeypatch.setattr(audit, 'affine_reference', lambda *_: None)
    monkeypatch.setattr(audit, 'beam_boundary_audit', lambda *_: {'state': 'passed'})
    with pytest.raises(ValueError, match='falsely rejected'):
        audit.audit_attempts(*args)


def test_all_compatible_templates_must_be_attempted_in_rank_order(attempt_fixture):
    args, _ = attempt_fixture
    args[6]['second'] = dict(row=row('second', 2), polygon=POLYGON)
    with pytest.raises(ValueError, match='coverage/order'):
        audit.audit_attempts(*args)


@pytest.mark.parametrize('protection', ['manual', 'old', 'gallery', 'human_history', 'deleted', 'deferred'])
def test_protected_targets_must_never_have_machine_attempts(attempt_fixture, protection):
    args, _ = attempt_fixture
    if protection == 'manual':
        args[5]['target'] = {}
        reason = 'saved_manual_source_counted'
    elif protection == 'old':
        args[4]['target'] = {}
        reason = 'already_published'
    elif protection == 'gallery':
        args[3]['history_keys'].add('target')
        reason = 'gallery_history_protected'
    else:
        reason = {'human_history': 'human_mask_history_protected', 'deleted': 'deleted', 'deferred': 'deferred_or_confirmed_protected'}[protection]
        args[2]['target'] = reason
    args[-2]['target']['reason'] = reason
    with pytest.raises(ValueError, match='Protected outcome/attempt'):
        audit.audit_attempts(*args)


def test_first_success_rank_batch_and_unselected_acceptance_are_audited(attempt_fixture):
    args, trial = attempt_fixture
    args[7]['target'] = dict(template={'target_key': 'seed'}, metrics=trial['metrics'], continuation=dict(
        batch=7, template_rank=1, all_compatible_targets_scanned=True, recursive_candidate_propagation=False))
    args[-2]['target']['reason'] = 'accepted_quota_full_not_selected'
    assert audit.audit_attempts(*args) == ({'target'}, 1)
    args[7]['target']['continuation']['batch'] = 6
    with pytest.raises(ValueError, match='continuation/rank'):
        audit.audit_attempts(*args)


def test_original_forward_backward_gate_is_still_one_point_five(monkeypatch):
    p = dict(target_key='target', source=row('target'), polygon=POLYGON, metrics={})
    t = dict(row=row('seed'), polygon=POLYGON)
    monkeypatch.setattr(audit.prior, 'transfer', lambda *_: (POLYGON, dict(initial_ncc=.9, ecc=.9,
        boundary_ncc=.9, forward_backward_error_patch_pixels=[1.50001])))
    with pytest.raises(ValueError, match='Original quality gates failed'):
        audit.prior.recompute(p, t, Evidence())


@pytest.fixture
def machine_fixture(manual_fixture, monkeypatch):
    _, _, pose, direct, _, *_ = manual_fixture
    source = direct['human']
    t = dict(source, origin=audit.POSE_ORIGIN, pose_review=audit.v1.pose_provenance(source, 'snapshot'))
    r = row('machine')
    p = dict(target_key='machine', class_id=10, source=r, polygon=copy.deepcopy(POLYGON), vertex_count=8,
        **dict.fromkeys(audit.FALSE_FLAGS, False), production_saved=False,
        status='machine_draft_pending_visual_review', formal_manifest_sha256='formal', class_assignments_sha256='classes',
        snapshot_sha256='snapshot', target_expected_revision=0, target_snapshot_payload_sha256=None,
        template=audit.template_binding(t), generation_method=dict(name='original', version='attempt_target_v1',
            code_sha256=audit.ORIGINAL_CODE['pallet/mask_template_continue.py']))
    calls = []
    monkeypatch.setattr(audit.prior, 'recompute', lambda *args: calls.append(args))
    args = (p, pose, {'human': t}, {'machine': r}, {'machine': 'eligible'}, {'history_keys': set(), 'current': {}},
        {}, {}, 'snapshot', 'formal', 'classes', Evidence())
    return args, calls


def test_accepted_machine_is_recomputed_even_without_any_selected_assets(machine_fixture):
    args, calls = machine_fixture
    audit.check_machine(*args)
    assert len(calls) == 1
    assert calls[0][0]['target_key'] == 'machine'


@pytest.mark.parametrize('attack', ['class', 'split', 'policy', 'view', 'same_frame', 'count', 'event_hash',
    'snapshot', 'history', 'gallery', 'manual', 'parent', 'GT', 'training', 'robot', 'human', 'multiscale'])
def test_machine_cannot_cross_original_compatibility_or_provenance_contract(machine_fixture, attack):
    args, calls = machine_fixture
    p, _, templates, _, status, gallery, old, manual, *_ = args
    t = templates['human']
    if attack in ('class', 'split', 'policy', 'view', 'same_frame'):
        field, value = {'class': ('final_class_id', 2), 'split': ('split', 'test'), 'policy': ('policy_id', 'other'),
            'view': ('viewpoint_candidate', 'back'), 'same_frame': ('frame_id', p['source']['frame_id'])}[attack]
        t['row'][field] = value
    elif attack == 'count':
        p['vertex_count'] = 12
    elif attack == 'event_hash':
        p['template']['human_event_sha256'] = 'machine-instead-of-human-event'
    elif attack == 'snapshot':
        p['snapshot_sha256'] = 'older'
    elif attack == 'history':
        status['machine'] = 'human_mask_history_protected'
    elif attack == 'gallery':
        gallery['history_keys'].add('machine')
    elif attack == 'manual':
        manual['machine'] = {}
    elif attack == 'parent':
        old['machine'] = {}
    elif attack in ('GT', 'training', 'robot', 'human'):
        p[dict(GT='ground_truth_eligible', training='automatic_training_eligible', robot='robot_command_eligible', human='human_mask_confirmed')[attack]] = True
    else:
        p['generation_method']['name'] = 'multiscale'
    with pytest.raises(ValueError):
        audit.check_machine(*args)
    assert calls == []


def test_template_namespaces_are_not_conflated_when_human_key_is_duplicated(tmp_path):
    t = dict(row=row('seed'), polygon=POLYGON, origin=audit.POSE_ORIGIN)
    historical = [dict(t, rendering_id=ns+':seed', polygon=[[1, 1]])
                  for ns in ('historical', 'refined', 'generation', 'quota_generation')]
    parent = dict(templates=historical, rendering_by_target={'old': 'quota_generation:seed'})
    inventory = dict(templates=copy.deepcopy(historical)+[dict(t, rendering_id='quota100_generation:seed')],
        rendering_by_target={'old': 'quota_generation:seed', 'human': 'quota100_generation:seed'},
        historical_templates=4, generation_template_namespace='quota100_generation', generation_template_keys=['seed'],
        generation_templates=1, generation_templates_by_origin={audit.POSE_ORIGIN: 1})
    write_json(tmp_path/'quota100_generation/templates/seed.json', t)
    args = (tmp_path, inventory, parent, {'seed': t}, {'old': {}}, {'human': dict(template={'target_key': 'seed'})}, {})
    audit.check_rendering(*args)
    inventory['rendering_by_target']['old'] = 'quota100_generation:seed'
    with pytest.raises(ValueError, match='rendering/source mapping'):
        audit.check_rendering(*args)
    inventory['rendering_by_target']['old'] = 'quota_generation:seed'
    inventory['templates'][0]['polygon'] = ['changed old seed']
    with pytest.raises(ValueError, match='Historical rendering namespace/payload'):
        audit.check_rendering(*args)


def create_source_db(path, manual_fixture):
    p, _, pose, *_ = manual_fixture
    raw = json.dumps(pose['current']['human'], indent=1)
    event_id, key, event_revision, event_raw = pose['events'][0]
    with sqlite3.connect(path) as db:
        db.executescript('CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);'
                        'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)', (key, 5, raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)', (event_id, key, event_revision, event_raw))
    record = dict(schema='saved_pose_mask_source_freeze_v1', target_key=key, snapshot_sha256='snapshot',
        current_revision=5, current_payload_sha256=audit.sha(json.loads(raw)), current_payload_raw=raw,
        current_payload=json.loads(raw), current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
        human_event_id=event_id, human_polygon_revision=event_revision, human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(),
        human_event_payload_raw=event_raw, human_event_payload=json.loads(event_raw), polygon_sha256=audit.sha(p['polygon']))
    return {'human': record}


@pytest.mark.parametrize('field', ['human_event_payload_raw', 'current_payload_raw', 'snapshot_sha256', 'human_event_sha256', 'current_payload_raw_sha256'])
def test_exact_source_record_rejects_even_semantically_equal_sqlite_byte_changes(tmp_path, manual_fixture, field):
    snapshot = tmp_path/'snapshot.sqlite3'
    records = create_source_db(snapshot, manual_fixture)
    before = snapshot.read_bytes()
    audit.check_new_manual_records(records, {'human': manual_fixture[0]}, snapshot, 'snapshot')
    assert snapshot.read_bytes() == before
    records['human'][field] += ' '
    with pytest.raises(ValueError, match='exact raw SQLite payload/event'):
        audit.check_new_manual_records(records, {'human': manual_fixture[0]}, snapshot, 'snapshot')


@pytest.fixture
def inherited_overlay_fixture(tmp_path, monkeypatch, manual_fixture):
    p, _, pose, direct, *_ = manual_fixture
    manual, historical, overlays, audits = {}, {}, {}, {}
    snapshot = tmp_path/'current.sqlite3'
    create_source_db(snapshot, manual_fixture)
    for i in range(30):
        key = f'old-human-{i}'
        manual[key] = dict(copy.deepcopy(p), target_key=key, snapshot_sha256='historical-snapshot')
        value = copy.deepcopy(pose['current']['human'])
        value['target_key'] = key
        value['source'] = row(key)
        historical[key] = dict(current_payload={'polygon': p['polygon']}, snapshot_sha256='historical-snapshot',
            current_payload_sha256=p['target_snapshot_payload_sha256'], human_event_sha256=p['template']['human_event_sha256'])
        pose['current'][key] = value
        direct[key] = dict(copy.deepcopy(direct['human']), row=row(key), current_payload_sha256=audit.sha(value))
        current_audit = dict(target_key=key, original_proposal_sha256=audit.sha(manual[key]),
            historical_revision=5, current_revision=5, current_payload_sha256=audit.sha(value),
            latest_active_direct_human=True, source_changed=audit.sha(value) != p['target_snapshot_payload_sha256'],
            polygon_changed=False, historical_assets_preserved=True)
        audits[key] = current_audit
        overlays[key] = dict(target_key=key, snapshot_sha256='new-snapshot', inherited_manual_source=True,
            legacy_source_audit=current_audit)
    monkeypatch.setattr(audit, 'read_jsonl', lambda path: list(audits.values()) if path.name == 'inherited_manual_source_audit.jsonl' else
        [dict(r, target_key=k) for k, r in historical.items()])
    calls = []
    monkeypatch.setattr(audit, 'check_new_manual_records', lambda *args: calls.append(args))
    return (tmp_path, manual, snapshot, pose, direct, 'new-snapshot', overlays), calls


def test_inherited_manual_keeps_historical_binding_but_current_source_has_explicit_overlay(inherited_overlay_fixture):
    args, calls = inherited_overlay_fixture
    original = copy.deepcopy(args[1])
    records, changed = audit.check_inherited_manual(*args)
    assert len(records) == len(changed) == 30
    assert args[1] == original  # No canonical rewrite or force-binding to the new snapshot.
    assert all(p['snapshot_sha256'] == 'historical-snapshot' for p in args[1].values())
    assert calls[0][3] == 'new-snapshot'
    assert all(r['snapshot_sha256'] == 'new-snapshot' for r in records.values())


@pytest.mark.parametrize('attack', ['hide_change', 'no_overlay', 'stale_current', 'stale_human', 'historical_rebind'])
def test_inherited_manual_cannot_silently_claim_fresh_unchanged_provenance(inherited_overlay_fixture, attack):
    args, _ = inherited_overlay_fixture
    _, manual, _, pose, direct, _, overlays = args
    key = next(iter(manual))
    if attack == 'hide_change':
        overlays[key]['legacy_source_audit']['source_changed'] = False
    elif attack == 'no_overlay':
        overlays[key]['inherited_manual_source'] = False
    elif attack == 'stale_current':
        pose['current'][key]['revision'] += 1
    elif attack == 'stale_human':
        direct.pop(key)
    else:
        manual[key]['snapshot_sha256'] = 'new-snapshot'
    with pytest.raises(ValueError):
        audit.check_inherited_manual(*args)


@pytest.mark.parametrize('version', [3, 4, 5, 6])
def test_saved_gallery_seed_resolves_actual_frozen_publication_not_current_binding(tmp_path, monkeypatch, version):
    from pallet.mask_gallery_review import VERSION as editor_version
    key, r = 'gallery', row('gallery')
    pub, parent = tmp_path/'historical', tmp_path/'parent'
    for root in (pub, parent):
        (root/'images').mkdir(parents=True)
        (root/'images'/f'{key}.png').write_bytes(b'frozen native image')
    (pub/'proposals.jsonl').write_text('frozen proposal bytes')
    proposal = dict(source=r, polygon=POLYGON, template={'old': 'source'})
    source = {field: r[field] for field in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
    source.update(formal_manifest_sha256='formal', image_sha256=audit.digest(pub/'images'/f'{key}.png'))
    value = dict(target_key=key, revision=2, proposal_publication=version, base_proposal_id=audit.sha(proposal),
        proposal_polygon=POLYGON, template_provenance=proposal['template'], source=source, source_binding=audit.sha(source),
        binding=audit.sha(dict(formal='formal', proposals=audit.digest(pub/'proposals.jsonl'), editor_version=editor_version)),
        event_kind='human_mask_gallery_revision', human_edited=True, polygon=POLYGON, vertex_count=8, pose=None,
        **dict.fromkeys(audit.FALSE_FLAGS, False), pose_store_written=False, original_proposal_modified=False)
    monkeypatch.setattr(audit, 'PARENT', parent)
    args = (store({}), store({key: value}), {key: r}, {key: proposal}, 'formal', 'gallery-snap',
            {version: dict(path=pub, proposals={key: proposal})})
    result = audit.independent_gallery_templates(*args)
    assert result[key]['origin'] == audit.GALLERY_ORIGIN
    assert result[key]['gallery_review']['proposal_publication'] == version
    value['binding'] = 'new-current-publication-binding-not-source-binding'
    with pytest.raises(ValueError, match='historical publication binding'):
        audit.independent_gallery_templates(*args)


def test_frozen_parent_and_worklist_hashes_are_real_and_algorithm_pins_are_original():
    for name, value in audit.PARENT_PINS.items():
        assert audit.digest(audit.PARENT/name) == value
    for name, value in audit.REQUEST_PINS.items():
        assert audit.digest(audit.REQUESTS/name) == value
    for name, value in audit.ORIGINAL_CODE.items():
        assert audit.digest(audit.PROJECT/name) == value
    assert len(audit.REQUEST_KEYS) == 13


def test_failed_audit_never_creates_success_seal(tmp_path, monkeypatch):
    out = tmp_path/'candidate'
    out.mkdir()
    write_json(out/'manifest.json', {})
    monkeypatch.setattr(audit, 'OUTPUT', out)
    def fail(*_):
        raise ValueError('unverified human source')
    monkeypatch.setattr(audit, 'audit', fail)
    with pytest.raises(ValueError, match='unverified human source'):
        audit.main(['--output', str(out)])
    assert not (out/'verification.json').exists()
    assert audit.read_json(out/'validation_report.json')['state'] == 'failed'


def test_success_seal_has_pub7_gallery_contract_and_is_exclusive(tmp_path, monkeypatch):
    out = tmp_path/'candidate'
    out.mkdir()
    write_json(out/'manifest.json', {})
    monkeypatch.setattr(audit, 'OUTPUT', out)
    result = dict(state='passed', publication_version=7, proposals_verified=400, proposals_sha256='sealed',
        extra_public_images=['vertex2_before_after.png'])
    monkeypatch.setattr(audit, 'audit', lambda *_: dict(result))
    audit.main(['--output', str(out)])
    seal = audit.read_json(out/'verification.json')
    assert seal['publication_version'] == 7 and seal['proposals_verified'] == 400
    assert seal['extra_public_images'] == ['vertex2_before_after.png']
    assert seal['validation_report_sha256'] == audit.digest(out/'validation_report.json')
    before = (out/'verification.json').read_bytes()
    with pytest.raises(ValueError, match='overwrite a frozen verification'):
        audit.main(['--output', str(out)])
    assert (out/'verification.json').read_bytes() == before


def test_symlink_output_cannot_overwrite_parent_report(tmp_path, monkeypatch):
    parent, link = tmp_path/'parent', tmp_path/'candidate'
    parent.mkdir()
    (parent/'manifest.json').write_text('{}')
    (parent/'validation_report.json').write_text('keep immutable report')
    link.symlink_to(parent, target_is_directory=True)
    monkeypatch.setattr(audit, 'OUTPUT', link)
    with pytest.raises(ValueError, match='publication-7 quota-100 outputs directory only'):
        audit.main(['--output', str(link)])
    assert (parent/'validation_report.json').read_text() == 'keep immutable report'
