migrate_v3.py 14.6 KB
"""Validate and import a V3 database. Run from the worktree with python -m tools.migrate_v3."""
import argparse
from collections import Counter, defaultdict, deque
from contextlib import ExitStack, closing
import json
import math
import os
from pathlib import Path
import random
import sqlite3
import tempfile

import numpy as np

from core.feature_extractor import CNN_VECTOR_DIM, FeatureExtractor
from database import DatabaseManager
from filesystem_files import FilePaths, staged_image
from filesystem_sync import ScanInventory

LEGACY_PREFIXES = {
    '/data/guangzhou': ('YANQING', 'H', '广州数据共享'),
    '/data/baidusync': ('YANQING', 'G', 'BaiduSyncdisk'),
}
MIN_SAMPLES = 300
COSINE_MIN = 0.9999


def read_only(path):
    conn = sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True)
    conn.row_factory = sqlite3.Row
    return conn


def publish_file(path, write):
    """Publish a complete new file without replacing an existing pathname."""
    path = Path(path)
    if os.path.lexists(path):
        raise FileExistsError(path)
    with tempfile.TemporaryDirectory(prefix='.migration-', dir=path.parent) as directory:
        staged = Path(directory) / path.name
        write(staged)
        os.link(staged, path)


def take_snapshot(source, snapshot):
    def backup(staged):
        with closing(read_only(source)) as before, closing(sqlite3.connect(staged)) as after:
            before.backup(after)
            # publish_file links only the database; the snapshot must open without WAL sidecars.
            if after.execute('PRAGMA journal_mode=DELETE').fetchone()[0] != 'delete':
                raise RuntimeError('Could not make a standalone SQLite snapshot')
    publish_file(snapshot, backup)


def convert_path(old, etsy_root):
    if isinstance(old, str):
        for prefix, subdir in LEGACY_PREFIXES.items():
            if old.startswith(prefix + '/'):
                parts = old[len(prefix) + 1:].split('/')
                if all(p and p not in {'.', '..'} and '\\' not in p and '\0' not in p for p in parts):
                    path = os.path.join(etsy_root, *subdir, *parts)
                    if os.path.normpath(path) == path:
                        return path
                break
    raise ValueError(f'Unknown or unsafe V3 path: {old!r}')


def validate_features(row):
    cnn, desc, pts = (row[name] for name in ('cnn_vector', 'orb_desc', 'orb_keypoints'))
    if not isinstance(cnn, bytes) or len(cnn) != 4 * CNN_VECTOR_DIM:
        return 'cnn_dimension'
    vector = np.frombuffer(cnn, np.float32)
    if not np.isfinite(vector).all() or not np.any(vector):
        return 'cnn_value'
    if any(blob is not None and not isinstance(blob, bytes) for blob in (desc, pts)):
        return 'orb_type'
    if not desc and not pts:
        return None
    if not desc or not pts or len(desc) % 32 or len(pts) % 16 or len(desc) // 32 != len(pts) // 16:
        return 'orb_shape'
    if not np.isfinite(np.frombuffer(pts, np.float32)).all():
        return 'orb_value'
    return None


def orb_points(row):
    pts = row['orb_keypoints']
    return np.frombuffer(pts, np.float32).reshape(-1, 4)[:, :2] if pts else None


def compare_features(row, features):
    if not features or features.get('cnn_vector') is None:
        return ['extraction']
    actual = np.asarray(features['cnn_vector'], np.float64)
    expected = np.frombuffer(row['cnn_vector'], np.float32).astype(np.float64)
    failures = []
    if actual.shape != expected.shape or not np.isfinite(actual).all() or not np.any(actual):
        failures.append('cnn_value')
    else:
        cosine = (actual @ expected) / (np.linalg.norm(actual) * np.linalg.norm(expected))
        if cosine < COSINE_MIN:
            failures.append('cnn_cosine')
    actual_pts, actual_desc = features.get('orb_kp'), features.get('orb_desc')
    expected_pts = orb_points(row)
    if expected_pts is None:
        if any(value is not None and len(value) for value in (actual_pts, actual_desc)):
            failures.append('orb_empty')
    else:
        if actual_pts is None or not np.array_equal(expected_pts, actual_pts):
            failures.append('orb_coordinates')
        if (actual_desc is None or actual_desc.dtype != np.uint8
                or actual_desc.shape != (len(expected_pts), 32)
                or actual_desc.tobytes() != row['orb_desc']):
            failures.append('orb_descriptors')
    return failures


def stratum(row, path):
    size = row['size']
    if type(size) is not int or size < 0:
        band = 'unknown'
    else:
        band = 'small' if size < 256 * 1024 else 'medium' if size < 2 * 1024 * 1024 else 'large'
    month = str(row['created_at'] or row['updated_at'] or 'unknown')[:7]
    legacy_root = '/' + '/'.join(row['path'].split('/')[1:3])
    return json.dumps([legacy_root, Path(path).suffix.casefold(), band, month], ensure_ascii=False)


def validate_metadata(row):
    size, mtime, sha = row['size'], row['mtime'], row['sha1']
    if (type(size) is not int or size < 0 or type(mtime) not in (int, float) or not math.isfinite(mtime)
            or not isinstance(sha, str) or len(sha) != 40 or any(c not in '0123456789abcdef' for c in sha)):
        return 'file_metadata'
    return None


def validate_paths(conn, paths, etsy_root):
    converted = []
    for table in ('images', 'damaged_files'):
        mapped = {}
        for row in conn.execute(f'SELECT path FROM {table}'):
            old = row['path']
            path = convert_path(old, etsy_root)
            if path in mapped:
                raise ValueError(f'Duplicate converted {table} path: {path}')
            if paths.root_for(path) is None:
                raise ValueError(f'Converted path outside scan roots: {path}')
            paths.unc(path)
            mapped[path] = old
        converted.append(mapped)
    return converted


def validate_samples(conn, strata, paths, inventory, extractor, minimum, report):
    rng = random.Random(0)
    work = deque()
    for batch, samples in sorted(strata.items()):
        rng.shuffle(samples)
        work.append((batch, samples))
    checked = stale = 0
    by_batch = Counter()
    mismatches = []
    changed = {}
    untested = set(strata)
    while work and (checked < minimum or untested):
        batch, samples = work.popleft()
        if checked >= minimum and batch not in untested:
            continue
        image_id, path = samples.pop()
        if samples:
            work.append((batch, samples))
        row = conn.execute('SELECT * FROM images WHERE id=?', (image_id,)).fetchone()
        with ExitStack() as sample:
            try:
                staged, digest = sample.enter_context(staged_image(path, paths.root_for(path),
                                                                   inventory.files[path]))
            except OSError:
                stale += 1
                continue
            if digest != row['sha1']:
                stale += 1
                changed[path] = (row['mtime'], row['size'])
                continue
            checked += 1
            by_batch[batch] += 1
            untested.discard(batch)
            failures = compare_features(row, extractor.extract_all_features(staged))
        if failures:
            mismatches.append({'path': path, 'batch': batch, 'failures': failures})
    report['sample'] = {'checked': checked, 'stale_replaced': stale, 'by_batch': dict(by_batch),
                        'untested_batches': sorted(untested), 'mismatches': mismatches}
    if checked < minimum or mismatches:
        raise ValueError('Sample comparison gate failed; see sample counts and mismatches')
    return changed


def import_snapshot(snapshot, target, report_path, paths, etsy_root, extractor,
                    reextract_batches=(), minimum_samples=MIN_SAMPLES):
    for output in (target, report_path):
        if os.path.lexists(output):
            raise FileExistsError(output)
    if Path(target).resolve() == Path(report_path).resolve():
        raise ValueError('Target database and report must be distinct')
    if type(minimum_samples) is not int or minimum_samples < 1:
        raise ValueError('Invalid minimum samples')
    report = {'counts': {}, 'structure_failures': [], 'pending_delete': [], 'reextract_batches': list(reextract_batches)}

    def write_report():
        publish_file(report_path, lambda path: path.write_text(
            json.dumps(report, indent=2, ensure_ascii=False) + '\n', encoding='utf-8'))

    with closing(read_only(snapshot)) as conn:
        conn.execute('BEGIN')
        try:
            if [row[0] for row in conn.execute('PRAGMA integrity_check')] != ['ok']:
                raise ValueError('V3 snapshot failed SQLite integrity_check')
            images, damaged = validate_paths(conn, paths, etsy_root)
            inventory = ScanInventory(paths, False, images)
            if inventory.failures:
                raise ValueError('Path gate requires a complete filesystem inventory')
            counts = Counter(keep=0, reextract=0, delete=0, imported_images=0,
                             new=len(inventory.files.keys() - images.keys() - damaged.keys()),
                             imported_damaged=len(damaged), damaged_missing=len(damaged.keys() - inventory.files.keys()))
            excluded = set()
            strata = defaultdict(list)
            encountered = set()
            for row in conn.execute('SELECT * FROM images'):
                path = convert_path(row['path'], etsy_root)
                current = inventory.files.get(path)
                failure = validate_features(row) or validate_metadata(row)
                batch = stratum(row, path)
                encountered.add(batch)
                if failure:
                    report['structure_failures'].append({'path': path, 'reason': failure})
                if current is None:
                    counts['delete'] += 1
                    report['pending_delete'].append(path)
                elif failure or batch in reextract_batches or current != (row['mtime'], row['size']):
                    counts['reextract'] += 1
                else:
                    counts['keep'] += 1
                if failure or batch in reextract_batches:
                    excluded.add(path)
                elif current is not None:
                    strata[batch].append((row['id'], path))
            unknown_batches = set(reextract_batches) - encountered
            if unknown_batches:
                raise ValueError(f'Unknown re-extraction batches: {sorted(unknown_batches)}')
            counts['imported_images'] = len(images) - len(excluded)
            counts['imported_damaged'] = len(damaged.keys() - excluded)
            report['counts'] = dict(counts)
            hashed_changes = validate_samples(conn, strata, paths, inventory, extractor, minimum_samples, report)
            # A SHA mismatch can expose a change that the scanner's metadata shortcut cannot see.
            forced = {path for path, old in hashed_changes.items() if inventory.files[path] == old}
            excluded.update(forced)
            counts['keep'] -= len(forced)
            counts['reextract'] += len(forced)
            counts['imported_images'] = len(images) - len(excluded)
            counts['imported_damaged'] = len(damaged.keys() - excluded)
            report['counts'] = dict(counts)
            report['sample']['same_metadata_reextract'] = sorted(forced)
            inventory.verify_markers()
            if inventory.failures:
                raise ValueError('Scan root identity changed during validation')
        except Exception as error:
            report['gate'] = 'failed'
            report['reason'] = str(error)
            write_report()
            raise

        report['gate'] = 'passed'
        write_report()

        def write_target(staged):
            # Bulk import publishes a standalone DB; the file-source runtime enables WAL.
            db = DatabaseManager(staged)
            with db.get_connection() as dest:
                for version, row in enumerate(conn.execute('SELECT * FROM images'), 1):
                    path = convert_path(row['path'], etsy_root)
                    if path in excluded:
                        continue
                    points = orb_points(row)
                    db.insert_file(dest, path, paths.unc(path), row['mtime'], row['size'], row['sha1'], -1,
                                   (row['cnn_vector'], row['orb_desc'], points.tobytes() if points is not None else None),
                                   version)
                for row in conn.execute('SELECT * FROM damaged_files'):
                    old = dict(row)
                    path = convert_path(row['path'], etsy_root)
                    if path not in excluded:
                        db.record_damage(dest, path, old.get('mtime'), old.get('size'), old.get('sha1'),
                                         old.get('error_type'), old.get('updated_at') or old.get('last_attempt'))
                actual = tuple(dest.execute('SELECT (SELECT COUNT(*) FROM images), '
                                            '(SELECT COUNT(*) FROM damaged_files)').fetchone())
                if actual != (counts['imported_images'], counts['imported_damaged']):
                    raise RuntimeError('SQLite import counts differ from the path gate report')
        publish_file(target, write_target)
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', type=Path, required=True, help='Existing V3 SQLite database')
    parser.add_argument('--snapshot', type=Path, required=True, help='New backup API snapshot')
    parser.add_argument('--target', type=Path, required=True, help='New offline filesystem SQLite database')
    parser.add_argument('--report', type=Path, required=True, help='New path/sample gate JSON report')
    parser.add_argument('--etsy-root', default='/data/etsy', help='Base Etsy scan root')
    parser.add_argument('--reextract-batch', action='append', default=[],
                        help='Reviewed batch ID from a prior failed sample report; repeat per batch')
    args = parser.parse_args()
    if len({p.resolve() for p in (args.source, args.snapshot, args.target, args.report)}) != 4:
        parser.error('Source, snapshot, target and report must be distinct')
    if any(os.path.lexists(p) for p in (args.snapshot, args.target, args.report)):
        parser.error('Snapshot, target and report must be new paths')

    from app import load_config
    config = load_config()['filesystem']
    paths = FilePaths(config['roots'], config['unc_prefixes'])
    take_snapshot(args.source, args.snapshot)
    import_snapshot(args.snapshot, args.target, args.report, paths, args.etsy_root,
                    FeatureExtractor(), args.reextract_batch)


if __name__ == '__main__':
    main()