"""Independent round-4 source-laundering, replay, quota and seal attacks."""
import ast
from collections import Counter
import copy
import json
import sqlite3

import pytest

from scripts import verify_mask_remaining_round4 as audit


FOUR = [[20, 20], [85, 21], [83, 43], [19, 42]]
FINE = [[20, 20], [85, 20], [85, 44], [65, 44], [65, 35], [40, 35], [40, 44], [20, 44]]


def row(key='human', cls=4, frame=None):
    return dict(target_key=key, target_id=key+'::box:0000', frame_id=frame or 'frame-'+key,
        final_class_id=cls, split='train', group_id='group', box_index=0,
        bbox=dict(x=18, y=18, width=70, height=28), size=[120, 80], policy_id='camera',
        source_pcd_sha256='pcd', image='images/'+key+'.png', viewpoint_candidate='front')


def value(r, polygon=FOUR, revision=1, **extra):
    return dict(target_key=r['target_key'], revision=revision, source=copy.deepcopy(r),
        state='draft', polygon=copy.deepcopy(polygon), **extra)


def event(v, event_id=None):
    return (event_id or v['revision'], v['target_key'], v['revision'], json.dumps(v, indent=2, ensure_ascii=False))


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


def proposal(r, polygon=FOUR):
    return dict(target_key=r['target_key'], source=copy.deepcopy(r), class_id=r['final_class_id'], polygon=copy.deepcopy(polygon), vertex_count=len(polygon))


def snapshot(path, kind, events, metadata=None):
    table = 'annotations' if kind == 'pose' else 'reviews'
    latest = {key: (revision, raw) for _, key, revision, raw in events}
    with sqlite3.connect(path) as db:
        db.executescript(f'CREATE TABLE {table}(target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE metadata(key TEXT,value TEXT);')
        db.executemany(f'INSERT INTO {table} VALUES (?,?,?)', ((k, *v) for k, v in latest.items()))
        db.executemany('INSERT INTO events VALUES (?,?,?,?)', events)
        db.executemany('INSERT INTO metadata VALUES (?,?)', (metadata or {}).items())
    return audit.helpers.read_store(path, kind, frozen=True)


def honest_manifest():
    return dict(publication_version=14, method='original', target_per_class=100,
        generation_template_namespace=audit.NAMESPACE, production_database_writes=0,
        configuration_writes=0, service_writes=0, new_human_edits_created=0,
        thresholds_relaxed=False, forced_fill=False, recursive_candidate_propagation=False,
        automatic_human_confirmation=False, automatic_training_eligible=False,
        robot_command_eligible=False, ground_truth_eligible=False,
        original_splits_preserved=True, classification_is_candidate_not_truth=True)


def test_policy_has1515_base_and_old_two_original_rectangles_remain_unreviewed():
    assert audit.PUBLICATION == 14 and audit.NAMESPACE == 'remaining_round4_generation'
    assert sum(audit.BASE_COUNTS.values()) == 1515
    assert 8 in audit.COMPLETED and len(audit.ORIGINAL_REVIEWS) == 5 and len(audit.PENDING_RECTANGLES) == 2
    assert audit.USER_STATEMENT == '完成复核和修正，继续'
    assert audit.PARENT_PINS['verification.json'].startswith('7d234a89')
    assert audit.REQUEST_PINS['verification.json'].startswith('8403c2f9')


@pytest.mark.parametrize('field,bad', [('publication_version', 13), ('method', 'research'), ('target_per_class', 99),
    ('generation_template_namespace', 'remaining_round3_generation'), ('production_database_writes', False),
    ('configuration_writes', 1), ('service_writes', '0'), ('new_human_edits_created', 1), ('thresholds_relaxed', True),
    ('forced_fill', True), ('recursive_candidate_propagation', True), ('automatic_human_confirmation', True),
    ('automatic_training_eligible', True), ('robot_command_eligible', True), ('ground_truth_eligible', True),
    ('human_confirmation_inferred', True), ('published', True), ('human_requests_created', 37), ('assistant_prelabels_created', 1)])
def test_manifest_rejects_writes_relaxed_gates_or_new_drafts_in_strict_output(field, bad):
    manifest = honest_manifest()
    audit.check_claims(manifest)
    manifest[field] = bad
    with pytest.raises(ValueError): audit.check_claims(manifest)


@pytest.fixture
def partition():
    tasks = {f'task-{c}-{i}': dict(target_key=f'task-{c}-{i}', class_id=c, source=row(f'task-{c}-{i}', c))
        for c, n in ((4, 10), (5, 7), (7, 10), (14, 10)) for i in range(n)}
    manual = {k: proposal(r['source']) for k, r in tasks.items()}
    manual_counts = Counter(p['class_id'] for p in manual.values())
    old = {f'old-{c}-{i}': proposal(row(f'old-{c}-{i}', c)) for c, n in audit.BASE_COUNTS.items()
        for i in range(n-manual_counts[c])}
    for i, (key, (cls, _)) in enumerate(audit.ORIGINAL_REVIEWS.items()):
        old.pop(f'old-{cls}-{i}')
        old[key] = dict(proposal(row(key, cls)), schema=audit.previous.previous.REVIEW_SCHEMA)
    new = {'machine': proposal(row('machine', 19), FINE)}
    combined = copy.deepcopy({**old, **manual, **new})
    return old, tasks, manual, new, combined, copy.deepcopy(new)


def test_exact1478_plus37_plus_n_counts_true_gallery_saves_not_pose_edits(partition):
    counts = audit.check_partition(*partition)
    assert len(partition[4]) == 1516 and counts['19']['proposals'] == 38


@pytest.mark.parametrize('attack', ['pending', 'lost_old', 'rewrite_old', 'missing_manual', 'fake_manual', 'machine_completed8',
    'accepted_manual', 'accepted_rewrite', 'frame_reuse', 'crossclass_frame', 'overquota', 'assistant_draft', 'lost_old_review'])
def test_partition_rejects_human_laundering_duplicate_frames_and_draft_contamination(partition, attack):
    old, tasks, manual, new, combined, accepted = partition
    if attack == 'pending':
        key = next(iter(audit.PENDING_RECTANGLES)); combined[key] = proposal(row(key))
    elif attack == 'lost_old': combined.pop(next(iter(old)))
    elif attack == 'rewrite_old': combined[next(iter(old))]['comment'] = 'modified'
    elif attack == 'missing_manual': manual.pop(next(iter(manual)))
    elif attack == 'fake_manual': manual['extra'] = proposal(row('extra'))
    elif attack == 'machine_completed8':
        for d in (new, combined, accepted): d['machine']['class_id'] = 8
    elif attack == 'accepted_manual':
        key = next(iter(manual)); accepted[key] = copy.deepcopy(manual[key])
    elif attack == 'accepted_rewrite': accepted['machine']['polygon'].reverse()
    elif attack == 'frame_reuse':
        for d in (new, combined, accepted): d['machine']['source']['frame_id'] = next(iter(old.values()))['source']['frame_id']
    elif attack == 'crossclass_frame':
        manual['task-5-1']['source']['frame_id'] = manual['task-7-1']['source']['frame_id']; combined['task-5-1'] = copy.deepcopy(manual['task-5-1'])
    elif attack == 'overquota':
        for i in range(100):
            key = 'extra'+str(i); new[key] = combined[key] = accepted[key] = proposal(row(key, 19), FINE)
    elif attack == 'lost_old_review':
        key = next(iter(audit.ORIGINAL_REVIEWS)); old[key].pop('schema'); combined[key] = copy.deepcopy(old[key])
    else: combined['assistant'] = proposal(row('assistant'))
    with pytest.raises(ValueError): audit.check_partition(*partition)


@pytest.fixture
def gallery(tmp_path, monkeypatch):
    root, pub = tmp_path/'tasks', tmp_path/'parent'
    root.mkdir(); pub.mkdir(); (root/'images').mkdir(); (pub/'images').mkdir()
    (root/'manifest.json').write_text('{"real":"sealed task manifest"}')
    (pub/'proposals.jsonl').write_text('{"real":"main publication canonical inventory"}\n')
    (root/'images/human.png').write_bytes(b'native-task-bytes')
    (pub/'images/historical.png').write_bytes(b'native-historical-bytes')
    monkeypatch.setattr(audit, 'REQUESTS', root)
    monkeypatch.setattr(audit, 'PARENT', pub)
    r = row()
    proof = dict(author_role='AI_assistant', human_saved=False, crop_inspected=True, full_image_inspected=True,
        method='assistant_direct_native_image_contour_not_template_transfer', image_sha256=audit.digest(root/'images/human.png'),
        polygon_sha256=audit.sha(FOUR), note_zh='原图直接预标注')
    draft = dict(proposal(r), schema='assistant_visual_preannotation_v1', origin='assistant_visual_preannotation',
        status='assistant_preannotated_draft_pending_human_review', formal_manifest_sha256='formal',
        target_expected_revision=0, target_snapshot_payload_sha256=None, preannotation=proof,
        draft_source=dict(target_key='human', origin='assistant_visual_preannotation', snapshot_revision=0, current_payload_sha256=None),
        **dict.fromkeys(('human_edited', 'human_mask_confirmed', 'human_pose_confirmed', 'ground_truth_eligible',
            'automatic_training_eligible', 'robot_command_eligible', 'production_saved', 'counts_as_completed_annotation',
            'accepted_candidate', 'propagation_seed_eligible'), False))
    task = dict(target_key='human', class_id=4, source=copy.deepcopy(r), assistant_polygon=copy.deepcopy(FOUR), preannotation=copy.deepcopy(proof),
        status='preannotated_awaiting_human_review', counts_as_completed_annotation=False,
        preserve_existing_pose_until_intentional_human_edit=True, existing_pose_revision=0, existing_pose_payload_sha256=None)
    from pallet.mask_gallery_review import VERSION
    binding = audit.sha(dict(formal='formal', proposals=audit.digest(pub/'proposals.jsonl'), editor_version=VERSION))
    def saved(p, image_path, polygon):
        identity = {f: p['source'][f] for f in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
        identity.update(formal_manifest_sha256='formal', image_sha256=audit.digest(image_path))
        return dict(target_key=p['target_key'], revision=1, event_kind='human_mask_gallery_revision', human_edited=True,
            pose=None, vertex_count=len(polygon), polygon=copy.deepcopy(polygon), source=identity, source_binding=audit.sha(identity),
            base_proposal_id=audit.sha(p), proposal_polygon=copy.deepcopy(p['polygon']), proposal_publication=13, binding=binding,
            pose_store_written=False, original_proposal_modified=False,
            **dict.fromkeys(('human_mask_confirmed', 'human_pose_confirmed', 'automatic_training_eligible', 'robot_command_eligible', 'ground_truth_eligible'), False))
    v = saved(draft, root/'images/human.png', [[21, 20], [85, 21], [83, 43], [19, 42]])
    v.update(template_provenance=None, human_source_provenance=None,
        preannotation_provenance=dict(assistant_draft=copy.deepcopy(proof), assistant_draft_not_human_edit=True,
            proposal_sha256=audit.sha(draft), worklist_manifest_sha256=audit.digest(root/'manifest.json')))
    historical = dict(proposal(row('historical', 19), FINE), template=dict(target_key='original-template'))
    oldvalue = saved(historical, pub/'images/historical.png', FINE)
    oldvalue['template_provenance'] = copy.deepcopy(historical['template'])
    rows = {'human': r, 'historical': historical['source']}
    events = [event(oldvalue, 1), event(v, 2)]
    return store({'human': v, 'historical': oldvalue}, events), store(), rows, {'historical': historical}, {
        13: dict(path=pub, proposals={'historical': historical})}, {'human': draft}, {'human': task}, 'formal', 'gallery-sha'


def test_gallery37_binding_is_mainpub13_but_base_and_image_are_sealed_independent_task(gallery):
    sources = audit.independent_gallery(*gallery)
    assert set(sources) == {'human', 'historical'}
    assert sources['human']['origin'] == audit.GALLERY_ORIGIN and len(sources['human']['polygon']) == 4
    assert sources['human']['gallery_review']['publication_proposals_sha256'] == audit.digest(gallery[4][13]['path']/'proposals.jsonl')


def test_saved_unchanged_prelabel_is_genuine_human_gallery_review_not_new_modification(gallery):
    gallery[0]['current']['human']['polygon'] = copy.deepcopy(FOUR)
    gallery[0]['events'][-1] = event(gallery[0]['current']['human'], 2)
    sources = audit.independent_gallery(*gallery)
    assert sources['human']['polygon'] == gallery[5]['human']['polygon']


@pytest.mark.parametrize('attack', ['base_mainpub', 'binding_taskpub', 'wrong_pub', 'foreign_image', 'foreign_source', 'wrong_split',
    'draft_polygon', 'draft_manifest', 'draft_proof', 'fake_template', 'fake_pose_provenance', 'missing_human_save', 'pose_event',
    'five_vertices', 'fake_confirmed', 'stale_current', 'rewrite_historical_event', 'duplicate_revision', 'pose_deleted', 'draft_is_human'])
def test_all_gallery_event_sources_reject_prelabel_laundering_or_stale_history(gallery, attack):
    saved, pose, rows, old, pubs, drafts, tasks, *_ = gallery
    v = saved['current']['human']
    if attack == 'base_mainpub': v['base_proposal_id'] = audit.sha(old['historical'])
    elif attack == 'binding_taskpub': v['binding'] = 'independent-task-proposals-not-main-editor-binding'
    elif attack == 'wrong_pub': v['proposal_publication'] = 12
    elif attack == 'foreign_image': v['source']['image_sha256'] = 'foreign'
    elif attack == 'foreign_source': v['source']['frame_id'] = 'foreign'
    elif attack == 'wrong_split': drafts['human']['source']['split'] = 'test'
    elif attack == 'draft_polygon': v['proposal_polygon'] = copy.deepcopy(v['polygon'])
    elif attack == 'draft_manifest': v['preannotation_provenance']['worklist_manifest_sha256'] = 'other'
    elif attack == 'draft_proof': v['preannotation_provenance']['assistant_draft']['note_zh'] = 'changed'
    elif attack == 'fake_template': v['template_provenance'] = dict(target_key='fake')
    elif attack == 'fake_pose_provenance': v['human_source_provenance'] = dict(pose_review={})
    elif attack == 'missing_human_save': v['human_edited'] = False
    elif attack == 'pose_event': v['event_kind'] = 'human_pose_revision'
    elif attack == 'five_vertices': v['polygon'].append([40, 30]); v['vertex_count'] = 5
    elif attack == 'fake_confirmed': v['ground_truth_eligible'] = True
    elif attack == 'stale_current':
        later = copy.deepcopy(v); later['revision'] = 2; saved['events'].append(event(later, 3))
    elif attack == 'rewrite_historical_event':
        changed = json.loads(saved['events'][0][3]); changed['base_proposal_id'] = 'changed'; saved['events'][0] = event(changed, 1)
    elif attack == 'duplicate_revision': saved['events'].append(event(v, 3))
    elif attack == 'pose_deleted':
        pose['current']['human'] = value(rows['human']); pose['current']['human']['state'] = 'deleted'
    else: drafts['human']['human_edited'] = True
    if attack not in ('stale_current', 'rewrite_historical_event', 'duplicate_revision'):
        saved['events'][-1] = event(v, 2)
    with pytest.raises(ValueError): audit.independent_gallery(*gallery)


def test_manual_gallery_quad_exact_self_binding_is_not_a_pose_revision(gallery):
    source = audit.independent_gallery(*gallery)['human']
    v = gallery[0]['current']['human']
    record = dict(revision=1, current_payload=v, current_payload_raw_sha256=audit.raw_sha(gallery[0]['events'][-1][3]),
        human_event_id=2, human_event_sha256=audit.raw_sha(gallery[0]['events'][-1][3]))
    p = dict(proposal(gallery[2]['human'], v['polygon']), schema='saved_gallery_mask_entry_v1', origin=audit.GALLERY_ORIGIN,
        status='saved_gallery_human_contour_draft_pending_confirmation', human_edited=True, saved_gallery_manual_source=True,
        human_source=audit.manual_gallery_binding(gallery[2]['human'], record, 'gallery-sha',
            audit.digest(audit.PARENT/'proposals.jsonl'), audit.digest(audit.REQUESTS/'manifest.json')),
        manual_four_point_source=True, propagation_seed_eligible=False, formal_manifest_sha256='formal', class_assignments_sha256='classes',
        manual_request_sha256=audit.sha(gallery[6]['human']), metrics={}, pose_store_written=False, gallery_store_written=False,
        machine_transfer_performed=False, new_human_edit_created=False, gallery_snapshot_sha256='gallery-sha',
        rendering_id=audit.NAMESPACE+':manual_source:human', assistant_draft_proposal_sha256=audit.sha(gallery[5]['human']),
        preannotation_provenance=v['preannotation_provenance'], polygon_changed_from_assistant_draft=True,
        target_expected_revision=0, target_snapshot_payload_sha256=None)
    args = p, gallery[6]['human'], gallery[5]['human'], gallery[2]['human'], source, record, 'gallery-sha', 'formal', 'classes'
    audit.check_manual(*args)
    for field, bad in [('origin', audit.POSE_ORIGIN), ('schema', 'saved_pose_mask_gallery_entry_v1'),
            ('propagation_seed_eligible', True), ('template', {}), ('human_source', dict(pose_review={})), ('pose_store_written', True),
            ('polygon', FOUR), ('metrics', {'ecc': 1}), ('ground_truth_eligible', True)]:
        attacked = copy.deepcopy(p); attacked[field] = bad
        with pytest.raises(ValueError): audit.check_manual(attacked, *args[1:])


def test_seed_set_parent650_plus29_excludes37_quads_even_when_saved_unchanged():
    r = row('pose', 19); v = value(r, FINE)
    recovered = audit.sources.recover_pose_sources(store({'pose': v}, [event(v)]), {'pose': r})
    galleries = {k: dict(row=row(k, c), polygon=copy.deepcopy(poly), origin=audit.GALLERY_ORIGIN)
        for k, c, poly in [('oldgallery', 19, FINE), ('saved-unchanged29', 8, FINE), ('manual37', 4, FOUR), ('oldfive', 1, FINE)]}
    result = audit.independent_seeds(recovered, recovered, galleries, {'pose', 'oldgallery'}, {'saved-unchanged29': {}}, 'snapshot', {'manual37'})
    assert set(result) == {'pose', 'oldgallery', 'saved-unchanged29'}
    galleries['unreviewed'] = dict(row=row('unreviewed', 19), polygon=FINE, origin=audit.GALLERY_ORIGIN)
    with pytest.raises(ValueError, match='exact parent650'):
        audit.independent_seeds(recovered, recovered, galleries, {'pose', 'oldgallery'}, {'saved-unchanged29': {}}, 'snapshot', {'manual37'})


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


@pytest.fixture
def attempts(monkeypatch):
    rows = {k: row(k, 19) for k in ('selected', 'unselected', 'rejected', 'low')}
    templates = {k: dict(row=row(k, 19), polygon=copy.deepcopy(FINE)) for k in ('best', 'second', 'below')}
    scores = {'best': .8, 'second': .7, 'below': .549999}
    monkeypatch.setattr(audit, 'correlate', lambda source, target: .549999 if target == 'low' else scores[source])
    metrics = dict(initial_ncc=.7, ecc=.84, boundary_ncc=.78, forward_backward_error_patch_pixels=[1.5]*8,
        boundary_guard=dict(state='passed', all_beams=[True, 2, .1]))
    calls = []
    def replay(template, target, evidence):
        source, key = template['row']['target_key'], target['target_key']; calls.append((source, key))
        if source == 'second' and key in ('selected', 'unselected'): return copy.deepcopy(FINE), copy.deepcopy(metrics)
        return None, dict(rejection='image_registration_failed', initial_ncc=scores[source])
    monkeypatch.setattr(audit, 'replay', replay)
    trials = [dict(target_key=k, class_id=19, template_key=s, metrics=replay(templates[s], rows[k], None)[1])
        for k in ('selected', 'unselected', 'rejected') for s in ('best', 'second')]
    calls.clear()
    accepted = {k: dict(proposal(rows[k], FINE), template=dict(target_key='second'), metrics=copy.deepcopy(metrics),
        continuation=dict(batch=14, template_rank=2, all_compatible_templates_considered=True, recursive_candidate_propagation=False))
        for k in ('selected', 'unselected')}
    outcomes = {k: dict(target_key=k, class_id=19, reason=reason) for k, reason in [
        ('selected', 'new_proposal'), ('unselected', 'accepted_duplicate_frame_not_selected'),
        ('rejected', 'registration_or_boundary_rejected'), ('low', 'image_similarity_below_gate')]}
    return trials, rows, templates, accepted, outcomes, Evidence(), calls


def test_replay_recomputes_all_rejections_and_accepted_but_unselected(attempts):
    assert audit.audit_attempts(*attempts[:6]) == set(attempts[1])
    assert len(attempts[6]) == 6


@pytest.mark.parametrize('attack', ['missing_rejection', 'omit_unselected', 'wrong_order', 'wrong_rank', 'rejected_metric',
    'unselected_metric', 'vertex_order', 'relaxed_ecc', 'relaxed_boundary', 'relaxed_fb', 'beam',
    'protected_key', 'protected_frame', 'completed8', 'missing_outcome', 'cross_split', 'policy', 'view'])
def test_replay_rejects_omissions_gate_relaxation_and_unsafe_transfers(attempts, monkeypatch, attack):
    trials, rows, templates, accepted, outcomes, evidence, _ = attempts
    extra = {}
    if attack == 'missing_rejection': trials.pop(4)
    elif attack == 'omit_unselected': trials[:] = [t for t in trials if t['target_key'] != 'unselected']
    elif attack == 'wrong_order': trials[0], trials[1] = trials[1], trials[0]
    elif attack == 'wrong_rank': accepted['selected']['continuation']['template_rank'] = 1
    elif attack == 'rejected_metric': trials[4]['metrics']['initial_ncc'] += .01
    elif attack == 'unselected_metric': accepted['unselected']['metrics']['ecc'] += .01
    elif attack == 'vertex_order': accepted['selected']['polygon'].reverse()
    elif attack.startswith('relaxed_') or attack == 'beam':
        field, bad = {'relaxed_ecc': ('ecc', .83999), 'relaxed_boundary': ('boundary_ncc', .77999),
            'relaxed_fb': ('forward_backward_error_patch_pixels', [1.50001]*8), 'beam': ('boundary_guard', dict(state='review_required'))}[attack]
        accepted['selected']['metrics'][field] = bad; trials[1]['metrics'][field] = bad
        saved = audit.replay
        def bad_replay(template, target, evidence):
            polygon, metrics = saved(template, target, evidence)
            if polygon is not None and target['target_key'] == 'selected': metrics[field] = bad
            return polygon, metrics
        monkeypatch.setattr(audit, 'replay', bad_replay)
    elif attack == 'protected_key': extra['protected_keys'] = {'selected'}
    elif attack == 'protected_frame': extra['protected_frames'] = {'frame-selected'}
    elif attack == 'completed8':
        rows['selected']['final_class_id'] = outcomes['selected']['class_id'] = 8
        for trial in trials[:2]: trial['class_id'] = 8
    elif attack == 'missing_outcome': outcomes.pop('low')
    else: templates['second']['row'][{'cross_split': 'split', 'policy': 'policy_id', 'view': 'viewpoint_candidate'}[attack]] = 'other'
    with pytest.raises((ValueError, AssertionError)): audit.audit_attempts(trials, rows, templates, accepted, outcomes, evidence, **extra)


def test_pose_history_returned_rectangle_and_pending_old_task_protect_sibling_frame():
    key = next(iter(audit.PENDING_RECTANGLES)); r = row(key)
    pose = store({key: value(r, audit.sources.rectangle(r), 2)}, [event(value(r, FOUR)), event(value(r, audit.sources.rectangle(r), 2))])
    sibling = row('sibling', 19, r['frame_id']); rows = {key: r, 'sibling': sibling}
    outcomes = {key: dict(class_id=4, reason='pose_mask_or_state_history_protected', registration_attempts=0),
        'sibling': dict(class_id=19, reason='no_compatible_template', registration_attempts=0)}
    for pending, (cls, _) in audit.PENDING_RECTANGLES.items():
        if pending not in rows:
            rows[pending] = row(pending, cls)
            outcomes[pending] = dict(class_id=cls, reason='pending_original_rectangle_frame_reserved', registration_attempts=0)
    excluded, keys, frames, _, _ = audit.scan_inventory(rows, pose, store(), {}, set(), outcomes, {key}, {r['frame_id']})
    assert key in keys and r['frame_id'] in frames and 'sibling' in excluded


@pytest.fixture
def deltas(tmp_path):
    old_pose = [event(value(row('oldpose')), 1)]
    old_gallery = [event(value(row('oldgallery'), FINE), 1)]
    tasks = {f'task-{i}': {} for i in range(37)}
    old_new = {f'review-{i}': {} for i in range(29)}
    added = [event(value(row(key), FOUR if key in tasks else FINE), i+2)
        for i, key in enumerate([*tasks, *old_new])]
    added.extend(event(value(row(f'task-{i}'), FOUR, 2), i+68) for i in range(5))
    before_paths = {kind: tmp_path/('before-'+kind+'.sqlite3') for kind in ('pose', 'gallery')}
    after_paths = {kind: tmp_path/('after-'+kind+'.sqlite3') for kind in ('pose', 'gallery')}
    before = {kind: snapshot(before_paths[kind], kind, events) for kind, events in (('pose', old_pose), ('gallery', old_gallery))}
    after = {kind: snapshot(after_paths[kind], kind, events) for kind, events in (('pose', old_pose), ('gallery', old_gallery+added))}
    return before_paths, after_paths, before, after, tasks, old_new


def test_exact_delta_is_no_pose_events_plus66_gallery_keys_and71_real_events(deltas):
    result = audit.check_store_delta(*deltas)
    assert result['pose']['new_events'] == 0 and not result['pose']['current_changed_keys']
    assert result['gallery']['new_events'] == 71 and len(result['gallery']['current_changed_keys']) == 66


@pytest.mark.parametrize('attack', ['pose_new_event', 'gallery_missing_event', 'gallery_foreign_event',
    'rewritten_prefix', 'json_equivalent_pose_bytes', 'json_equivalent_gallery_bytes', 'gallery_removed_current'])
def test_delta_rejects_unrelated_writes_fake_pose_and_raw_byte_rewrites(deltas, attack):
    before_paths, after_paths, before, after, tasks, old_new = deltas
    if attack == 'pose_new_event':
        v = value(row('oldpose'), FOUR, 2); after['pose']['events'].append(event(v, 2))
    elif attack == 'gallery_missing_event': after['gallery']['events'].pop()
    elif attack == 'gallery_foreign_event':
        _, _, revision, raw = after['gallery']['events'][-1]
        v = json.loads(raw); v['target_key'] = 'foreign'
        after['gallery']['events'][-1] = (72, 'foreign', revision, json.dumps(v))
    elif attack == 'rewritten_prefix':
        event_id, key, revision, raw = after['gallery']['events'][0]
        after['gallery']['events'][0] = event_id, key, revision, json.dumps(json.loads(raw))
    else:
        kind, table = ('pose', 'annotations') if attack == 'json_equivalent_pose_bytes' else ('gallery', 'reviews')
        with sqlite3.connect(after_paths[kind]) as db:
            if attack == 'gallery_removed_current': db.execute("DELETE FROM reviews WHERE target_key='task-0'")
            else:
                key, raw = db.execute(f'SELECT target_key,payload FROM {table} LIMIT 1').fetchone()
                db.execute(f'UPDATE {table} SET payload=? WHERE target_key=?', (json.dumps(json.loads(raw)), key))
    with pytest.raises(ValueError): audit.check_store_delta(*deltas)


def test_gallery_source_records_require_exact_latest_utf8_not_canonical_json(tmp_path):
    r = row(); v = value(r, revision=2, note='真实保存，不能规范化替换原始字节')
    path = tmp_path/'gallery.sqlite3'
    current = snapshot(path, 'gallery', [event(value(r), 1), event(v, 2)])
    raw = current['events'][-1][3]
    record = dict(target_key='human', revision=2, current_payload_raw=raw, current_payload_raw_sha256=audit.raw_sha(raw),
        current_payload=v, current_payload_sha256=audit.sha(v), human_event_id=2, human_event_payload_raw=raw,
        human_event_sha256=audit.raw_sha(raw), snapshot_sha256='snapshot')
    output = tmp_path/'records'; output.mkdir()
    records = output/'gallery_source_records.jsonl'
    records.write_text(json.dumps(record, ensure_ascii=False)+'\n')
    audit.history.check_gallery_records(output, path, current, 'snapshot')
    for field, bad in [('human_event_sha256', audit.sha(v)), ('current_payload_raw', json.dumps(v)),
            ('human_event_id', 1), ('revision', 1)]:
        changed = copy.deepcopy(record); changed[field] = bad; records.write_text(json.dumps(changed)+'\n')
        with pytest.raises(ValueError): audit.history.check_gallery_records(output, path, current, 'snapshot')
    records.write_text(json.dumps(record)+'\n')
    with sqlite3.connect(path) as db:
        db.execute('UPDATE reviews SET payload=? WHERE target_key=?', (json.dumps(v), 'human'))
    with pytest.raises(ValueError): audit.history.check_gallery_records(output, path, current, 'snapshot')


@pytest.fixture
def gallery_assets(tmp_path):
    from PIL import Image
    import numpy as np
    key = '0123456789abcdef01234567'; r = row(key)
    p = dict(proposal(r, [[21, 21], [85, 21], [83, 43], [19, 42]]), origin=audit.GALLERY_ORIGIN,
        human_source=dict(target_key=key, origin=audit.GALLERY_ORIGIN, gallery_review=dict(target_key=key)))
    for folder, _ in audit.ASSETS: (tmp_path/folder).mkdir()
    native = np.arange(120*80, dtype=np.uint8).reshape(80, 120)
    Image.fromarray(native).save(tmp_path/'images'/f'{key}.png')
    Image.fromarray(audit.raster_mask(p['polygon'], *r['size']).astype(np.uint8)*255).save(tmp_path/'masks'/f'{key}.png')
    panel = Image.new('RGB', (1480, 305), '#121923')
    panel.paste(audit.overlay(native, r, p['polygon'], '#55ceff'), (0, 30)); panel.save(tmp_path/'cases'/f'{key}.png')
    flags = dict(human_confirmed=False, human_edited=True, machine_draft=False, automatic_training_eligible=False,
        robot_command_eligible=False, ground_truth_eligible=False, propagation_seed_eligible=False, pose_snapshot_saved=False)
    label = dict(imageWidth=120, imageHeight=80, imagePath=f'../images/{key}.png', imageData=None,
        mask_gallery_provenance=p, saved_gallery_source=p['human_source'], annotation_scope='single_target_mask_review_not_full_frame',
        other_objects_unchanged=True, flags=flags, shapes=[dict(points=p['polygon'], shape_type='polygon', group_id=0, label='pallet', flags=flags)])
    (tmp_path/'labelme'/f'{key}.json').write_text(json.dumps(label))
    class Native:
        def image(self, frame): return native
    return tmp_path, p, r, Native()


def test_saved_gallery_native_mask_numbered_preview_and_labelme_are_latest_real_polygon(gallery_assets):
    audit.check_gallery_assets(*gallery_assets)


@pytest.mark.parametrize('attack', ['initial_assistant_mask', 'initial_assistant_preview', 'initial_assistant_labelme',
    'image_pixels', 'pose_save_claim', 'seed_claim', 'confirmation_claim', 'symlink'])
def test_saved_gallery_assets_cannot_reuse_initial_draft_or_claim_pose_seed_truth(gallery_assets, attack):
    from PIL import Image
    import numpy as np
    root, p, r, evidence = gallery_assets; key = p['target_key']
    if attack == 'initial_assistant_mask':
        Image.fromarray(audit.raster_mask(FOUR, *r['size']).astype(np.uint8)*255).save(root/'masks'/f'{key}.png')
    elif attack == 'initial_assistant_preview':
        panel = Image.new('RGB', (1480, 305)); panel.paste(audit.overlay(evidence.image(''), r, FOUR, '#55ceff'), (0, 30))
        panel.save(root/'cases'/f'{key}.png')
    elif attack == 'image_pixels': Image.new('L', tuple(r['size'])).save(root/'images'/f'{key}.png')
    elif attack == 'symlink':
        image = root/'images'/f'{key}.png'; target = root/'other.png'; image.rename(target); image.symlink_to(target)
    else:
        path = root/'labelme'/f'{key}.json'; label = json.loads(path.read_text())
        if attack == 'initial_assistant_labelme': label['shapes'][0]['points'] = FOUR
        else: label['flags'][{'pose_save_claim': 'pose_snapshot_saved', 'seed_claim': 'propagation_seed_eligible',
            'confirmation_claim': 'human_confirmed'}[attack]] = True
        path.write_text(json.dumps(label))
    with pytest.raises((ValueError, AssertionError)): audit.check_gallery_assets(*gallery_assets)


@pytest.fixture
def seal_output(tmp_path, monkeypatch):
    project = tmp_path/'project'; output = project/'outputs/pallet_mask_remaining_round4_v1'
    output.mkdir(parents=True); (output/'manifest.json').write_text('{}')
    monkeypatch.setattr(audit, 'PROJECT', project)
    return output


def test_failed_audit_keeps_prior_failure_raw_and_writes_no_seal(seal_output):
    def fail(_): raise ValueError('invalid gallery source')
    for _ in range(2):
        prior = (seal_output/audit.REPORT).read_text() if (seal_output/audit.REPORT).exists() else None
        with pytest.raises(ValueError, match='invalid gallery'): audit.seal(seal_output, fail)
        result = audit.read_json(seal_output/audit.REPORT)
        if prior is not None:
            assert result['previous_failed_validation_report_raw'] == prior
            assert result['previous_failed_validation_report_sha256'] == audit.raw_sha(prior)
    assert not (seal_output/audit.SEAL).exists()
    assert {p.name for p in seal_output.iterdir()} == {'manifest.json', audit.REPORT}


def test_success_seal_exclusive_and_report_hash_bound(seal_output):
    result = audit.seal(seal_output, lambda _: dict(state='passed', publication_version=14, proposals_verified=1515))
    raw = (seal_output/audit.SEAL).read_bytes()
    assert result['validation_report_sha256'] == audit.digest(seal_output/audit.REPORT)
    with pytest.raises(ValueError, match='overwrite'): audit.seal(seal_output, lambda _: dict(state='passed'))
    assert (seal_output/audit.SEAL).read_bytes() == raw


def test_unsafe_symlink_output_or_report_and_unfinished_generation_rejected(seal_output):
    link = seal_output.parent/'pallet_mask_remaining_round4_v2'; link.symlink_to(seal_output, target_is_directory=True)
    with pytest.raises(ValueError, match='Only a new'): audit.seal(link, lambda _: dict(state='passed'))
    protected = seal_output.parent/'private.json'; protected.write_text('untouched')
    (seal_output/audit.REPORT).symlink_to(protected)
    with pytest.raises(ValueError, match='Unsafe'): audit.seal(seal_output, lambda _: dict(state='passed'))
    assert protected.read_text() == 'untouched'
    (seal_output/'manifest.json').unlink()
    with pytest.raises(ValueError, match='not complete'): audit.seal(seal_output, lambda _: dict(state='passed'))


def test_no_new_generator_helper_import_writer_polling_assert_or_old_module_mutation():
    tree = ast.parse(audit.Path(audit.__file__).read_text())
    forbidden = {'pallet.mask_remaining_round4', 'pallet.mask_gallery_saved_source', 'pallet.mask_saved_preannotations'}
    for node in ast.walk(tree):
        assert not isinstance(node, ast.Assert)
        if isinstance(node, ast.ImportFrom): assert node.module not in forbidden
        if isinstance(node, ast.Import): assert not forbidden & {n.name for n in node.names}
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('backup', 'generate', 'save_review', 'save_annotation', 'setattr', 'sleep')
        if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
            for target in node.targets if isinstance(node, ast.Assign) else [node.target]:
                assert not (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)
                    and target.value.id in ('previous', 'history', 'matching', 'sources', 'helpers', 'baseline'))
