test_migrate_v3.py 12.4 KB
from contextlib import closing
from hashlib import sha1
from io import BytesIO
import json
import os
from pathlib import Path
import sqlite3

import numpy as np
from PIL import Image
import pytest

from database import DatabaseManager
from filesystem_files import FilePaths
from tools import migrate_v3 as migration


CNN = np.eye(1, 1152, dtype=np.float32)[0]
POINTS = np.array([[12, 34, 56, 78]], dtype=np.float32)
DESCRIPTORS = np.arange(32, dtype=np.uint8)[None, :]
FEATURES = {'cnn_vector': CNN, 'orb_kp': POINTS[:, :2], 'orb_desc': DESCRIPTORS}

# V3 table shape from indexer.py, including the legacy damaged table's missing mtime/size.
SCHEMA = '''
    CREATE TABLE images(
        id INTEGER PRIMARY KEY AUTOINCREMENT, path TEXT UNIQUE NOT NULL,
        mtime REAL NOT NULL, size INTEGER NOT NULL, sha1 TEXT NOT NULL, phash TEXT,
        edge_phash TEXT, orb_desc BLOB, orb_keypoints BLOB, cnn_vector BLOB,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
    CREATE TABLE damaged_files(path TEXT PRIMARY KEY, sha1 TEXT, error_type TEXT,
        last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, attempt_count INTEGER DEFAULT 1);
'''


class Extractor:
    def extract_all_features(self, stream):
        with Image.open(stream) as decoded:
            decoded.load()
            if decoded.getpixel((0, 0)) == (0, 0, 0):
                return dict(FEATURES, orb_kp=None, orb_desc=None)
        return FEATURES


def create_source(tmp_path, schema=SCHEMA):
    etsy = tmp_path / 'etsy'
    etsy.mkdir()
    (etsy / '.image-search-root').write_text('Etsy', encoding='utf-8')
    paths = FilePaths({str(etsy): 'Etsy'}, {str(etsy): r'\\nas\Etsy'})
    conn = sqlite3.connect(tmp_path / 'v3.db')
    conn.execute('PRAGMA journal_mode=WAL')
    conn.executescript(schema)
    return conn, etsy, paths


def insert(conn, etsy, legacy_path, *, color='red', exists=True, bad_cnn=False,
           changed_sha=False, month='2026-09', wrong_points=False, padded_size=0):
    path = Path(migration.convert_path(legacy_path, str(etsy)))
    fmt = 'JPEG' if path.suffix == '.jpg' else 'PNG'
    data = BytesIO()
    Image.new('RGB', (8, 8), color).save(data, fmt)
    content = data.getvalue() + b'\0' * padded_size
    mtime = 1000
    if exists:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(content)
        os.utime(path, (mtime, mtime))
        mtime = path.stat().st_mtime
    conn.execute('''INSERT INTO images(path, mtime, size, sha1, orb_desc, orb_keypoints,
        cnn_vector, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)''',
                 (legacy_path, mtime, len(content), sha1(b'stale' if changed_sha else content).hexdigest(),
                  None if color == 'black' else DESCRIPTORS.tobytes(),
                  b'' if color == 'black' else (POINTS + int(wrong_points)).tobytes(),
                  None if bad_cnn else CNN.tobytes(), month + '-01 00:00:00'))
    return path


def run_import(tmp_path, etsy, paths, **options):
    snapshot, target, report = [tmp_path / p for p in ('snapshot.db', 'target.db', 'gate.json')]
    result = migration.import_snapshot(snapshot, target, report, paths, str(etsy), Extractor(), **options)
    assert json.loads(report.read_text(encoding='utf-8')) == result
    return result, DatabaseManager(target)


def test_backup_snapshot_path_gate_and_offline_import(tmp_path, monkeypatch):
    connection, etsy, paths = create_source(tmp_path)
    with closing(connection) as conn:
        kept = insert(conn, etsy, '/data/guangzhou/中文.jpg')
        blank = insert(conn, etsy, '/data/baidusync/blank.png', color='black', padded_size=256 * 1024)
        malformed = insert(conn, etsy, '/data/baidusync/bad.jpg', bad_cnn=True)
        missing = insert(conn, etsy, '/data/guangzhou/deleted.jpg', exists=False)
        changed = insert(conn, etsy, '/data/guangzhou/changed.jpg', changed_sha=True)
        os.utime(changed, (2000, 2000))
        legacy_damage = '/data/guangzhou/old-damage.jpg'
        damaged = migration.convert_path(legacy_damage, str(etsy))
        conn.execute('INSERT INTO damaged_files(path, sha1, error_type) VALUES(?, ?, ?)',
                     (legacy_damage, 'old-hash', 'old-error'))
        conn.commit()
        assert (tmp_path / 'v3.db-wal').exists()
        migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
        with closing(migration.read_only(tmp_path / 'snapshot.db')) as snapshot:
            assert snapshot.execute('PRAGMA journal_mode').fetchone()[0] == 'delete'
            assert snapshot.execute('SELECT COUNT(*) FROM images').fetchone()[0] == 5
        conn.execute('DELETE FROM images')
        conn.commit()
        assert conn.execute('SELECT COUNT(*) FROM images').fetchone()[0] == 0
    (etsy / 'new.tif').write_bytes(b'new file')
    publish = migration.publish_file

    def gate_written_first(path, writer):
        if path == tmp_path / 'target.db':
            persisted = json.loads((tmp_path / 'gate.json').read_text(encoding='utf-8'))
            assert persisted['gate'] == 'passed' and persisted['counts']['keep'] == 2
            assert not path.exists()
        publish(path, writer)

    monkeypatch.setattr(migration, 'publish_file', gate_written_first)
    report, db = run_import(tmp_path, etsy, paths, minimum_samples=2)
    assert report['counts'] == dict(keep=2, reextract=2, delete=1, imported_images=4, new=1,
                                    imported_damaged=1, damaged_missing=1)
    assert report['pending_delete'] == [str(missing)]
    assert report['structure_failures'] == [{'path': str(malformed), 'reason': 'cnn_dimension'}]
    assert len(report['sample']['by_batch']) == 2
    assert report['sample']['stale_replaced'] == 1
    rows = {row['path']: row for row in db.all_features()}
    assert set(rows) == {str(kept), str(blank), str(changed), str(missing)}
    assert rows[str(kept)]['image_url'] == r'\\nas\Etsy\YANQING\H\广州数据共享\中文.jpg'
    with db.get_connection() as dest:
        raw = dest.execute('SELECT * FROM images WHERE path=?', (str(kept),)).fetchone()
        assert raw['cnn_vector'] == CNN.tobytes() and raw['orb_desc'] == DESCRIPTORS.tobytes()
        assert raw['orb_pts'] == POINTS[:, :2].tobytes()
        assert raw['frame_ms'] == -1 and raw['eps_id'] == 2
        assert raw['mtime'] == kept.stat().st_mtime and raw['size'] == kept.stat().st_size
        assert raw['sha1'] == sha1(kept.read_bytes()).hexdigest()
    assert db.damaged_metadata() == {damaged: (None, None)}
    with pytest.raises(FileExistsError):
        migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
    with pytest.raises(FileExistsError):
        run_import(tmp_path, etsy, paths, minimum_samples=2)


@pytest.mark.parametrize('table, legacy', [('images', '/data/guangzhou-extra/a.jpg'),
                                         ('damaged_files', '/data/unknown/a.jpg'),
                                         ('damaged_files', '/data/baidusync/../escape.jpg')])
def test_path_gate_rejects_unknown_and_traversal_before_target(tmp_path, table, legacy):
    connection, etsy, paths = create_source(tmp_path)
    with closing(connection) as conn:
        insert(conn, etsy, '/data/guangzhou/ok.jpg')
        if table == 'images':
            conn.execute('INSERT INTO images(path,mtime,size,sha1) VALUES(?,0,0,?)', (legacy, 'invalid'))
        else:
            conn.execute('INSERT INTO damaged_files(path) VALUES(?)', (legacy,))
        conn.commit()
    migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
    with pytest.raises(ValueError, match='Unknown or unsafe V3 path'):
        run_import(tmp_path, etsy, paths, minimum_samples=1)
    assert not (tmp_path / 'target.db').exists()
    assert json.loads((tmp_path / 'gate.json').read_text(encoding='utf-8'))['gate'] == 'failed'


def test_path_gate_checks_unique_even_with_legacy_constraint_absent(tmp_path):
    connection, etsy, paths = create_source(tmp_path, SCHEMA.replace(' UNIQUE', ''))
    with closing(connection) as conn:
        for _ in range(2):
            insert(conn, etsy, '/data/guangzhou/duplicate.jpg')
        conn.commit()
    migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
    with pytest.raises(ValueError, match='Duplicate converted images path'):
        run_import(tmp_path, etsy, paths, minimum_samples=1)
    assert not (tmp_path / 'target.db').exists()


def test_full_structure_and_precise_sample_comparisons():
    row = dict(cnn_vector=CNN.tobytes(), orb_desc=DESCRIPTORS.tobytes(), orb_keypoints=POINTS.tobytes())
    assert migration.validate_features(row) is None
    for invalid, reason in [({'cnn_vector': b'bad'}, 'cnn_dimension'),
                            ({'cnn_vector': bytes(1152 * 4)}, 'cnn_value'),
                            ({'cnn_vector': np.full(1152, np.nan, np.float32).tobytes()}, 'cnn_value'),
                            ({'orb_desc': b'bad'}, 'orb_shape'), ({'orb_desc': b''}, 'orb_shape'),
                            ({'orb_keypoints': POINTS.tobytes() * 2}, 'orb_shape'),
                            ({'orb_keypoints': np.full(4, np.nan, np.float32).tobytes()}, 'orb_value')]:
        assert migration.validate_features(dict(row, **invalid)) == reason
    assert migration.compare_features(row, FEATURES) == []
    for cosine, passed in [(0.99995, True), (0.99989, False)]:
        vector = CNN.copy()
        vector[:2] = [cosine, np.sqrt(1 - cosine ** 2)]
        assert (migration.compare_features(row, dict(FEATURES, cnn_vector=vector)) == []) == passed
    assert migration.compare_features(row, dict(FEATURES, orb_kp=POINTS[:, :2] + 1)) == ['orb_coordinates']
    assert migration.compare_features(row, dict(FEATURES, orb_desc=DESCRIPTORS + 1)) == ['orb_descriptors']
    empty = dict(row, orb_keypoints=b'', orb_desc=None)
    assert migration.validate_features(empty) is None
    assert migration.compare_features(empty, dict(FEATURES, orb_kp=None, orb_desc=None)) == []
    assert migration.compare_features(empty, FEATURES) == ['orb_empty']


def test_mismatch_blocks_target_until_explicit_batch_is_approved(tmp_path):
    connection, etsy, paths = create_source(tmp_path)
    with closing(connection) as conn:
        rejected = insert(conn, etsy, '/data/guangzhou/reorb.jpg', wrong_points=True, month='2026-01')
        accepted = insert(conn, etsy, '/data/baidusync/keep.png', month='2026-02')
        conn.commit()
    migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
    with pytest.raises(ValueError, match='Sample comparison gate failed'):
        run_import(tmp_path, etsy, paths, minimum_samples=1)
    report_path = tmp_path / 'gate.json'
    report = json.loads(report_path.read_text(encoding='utf-8'))
    assert not (tmp_path / 'target.db').exists()
    assert report['sample']['checked'] == 2
    mismatch, = report['sample']['mismatches']
    assert mismatch['path'] == str(rejected) and mismatch['failures'] == ['orb_coordinates']
    report_path.unlink()
    updated, db = run_import(tmp_path, etsy, paths, minimum_samples=1, reextract_batches=[mismatch['batch']])
    assert updated['counts']['reextract'] == 1
    assert set(db.file_metadata()) == {str(accepted)}


def test_default_sample_gate_requires_300_unchanged_and_covers_both_legacy_roots(tmp_path):
    connection, etsy, paths = create_source(tmp_path)
    with closing(connection) as conn:
        for i in range(300):
            prefix = 'guangzhou' if i % 2 else 'baidusync'
            insert(conn, etsy, f'/data/{prefix}/{i}.png', changed_sha=i == 0)
        conn.commit()
        migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
        with pytest.raises(ValueError, match='Sample comparison gate failed'):
            run_import(tmp_path, etsy, paths)
        report_path = tmp_path / 'gate.json'
        report = json.loads(report_path.read_text(encoding='utf-8'))
        assert report['sample']['checked'] == 299 and report['sample']['stale_replaced'] == 1
        assert not (tmp_path / 'target.db').exists()
        report_path.unlink()
        (tmp_path / 'snapshot.db').unlink()
        insert(conn, etsy, '/data/guangzhou/extra.jpg', month='2025-01')
        conn.commit()
        migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
    report, db = run_import(tmp_path, etsy, paths)
    assert report['sample']['checked'] == 300
    assert len(report['sample']['by_batch']) == 3
    changed = migration.convert_path('/data/baidusync/0.png', str(etsy))
    assert report['sample']['same_metadata_reextract'] == [changed]
    assert report['counts']['reextract'] == 1
    assert changed not in db.file_metadata()