test_filesystem_source.py 25.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
from base64 import b64decode
from contextlib import contextmanager
from hashlib import sha1
from io import BytesIO
import os
from pathlib import Path
import sqlite3
import threading
import time
from types import SimpleNamespace

import cv2
from fastapi.testclient import TestClient
from jose import jwt
import numpy as np
from PIL import Image
import pytest

import app
from core.search_engine import ImageSearchEngine
from core.vector_index import VectorIndex
from database import DatabaseManager
import filesystem_files
from filesystem_files import FilePaths, frame_times
import filesystem_sync
from filesystem_sync import FileSystemSync

PROD = 'p' * 32
DAILY = 'd' * 32
VECTOR = np.arange(1, 1153, dtype=np.float32)
ORB_KP = np.array([[1, 2]], np.float32)
ORB_DESC = np.ones((1, 32), np.uint8)


def image_bytes(format='JPEG', color='red'):
    output = BytesIO()
    Image.new('RGB', (360, 240), color).save(output, format)
    return output.getvalue()


def image(path, color='red'):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(image_bytes(color=color))
    return str(path)


class Extractor:
    def __init__(self):
        self.contents = []
        self.verifications = 0

    def extract_all_features(self, source):
        if isinstance(source, BytesIO):
            self.contents.append(source.getvalue())
            try:
                with Image.open(source) as opened:
                    opened.load()
            except OSError:
                return None
        return {'cnn_vector': VECTOR, 'orb_kp': ORB_KP, 'orb_desc': ORB_DESC}

    def compute_orb_ransac_score(self, *args, **kwargs):
        self.verifications += 1
        return 15


def build(tmp_path, capacity=32, video=False):
    left, right = tmp_path / 'a', tmp_path / 'ab'
    for root in (left, right):
        root.mkdir()
        (root / '.image-search-root').write_text(root.name, encoding='utf-8')
    config = {'source': {'type': 'filesystem'}, 'upload': {},
              'filesystem': {'roots': {str(left): 'a', str(right): 'ab'},
                             'unc_prefixes': {str(left): r'\\nas\a', str(right): r'\\nas\ab'},
                             'sqlite_path': str(tmp_path / 'files.db'),
                             'index_min_capacity': capacity, 'batch_size': 1,
                             'jwt': {'prod_secret': PROD, 'daily_secret': DAILY, 'subject': 'nas-image-search'}},
              'video': {'enabled': video}}
    db = DatabaseManager(config['filesystem']['sqlite_path'])
    extractor = Extractor()
    index = VectorIndex()
    db.file_index_snapshot(index, capacity, video)
    sync = FileSystemSync(config, index, db, extractor)
    engine = ImageSearchEngine(config=config, index=index, db_manager=db, extractor=extractor)
    return SimpleNamespace(left=left, right=right, config=config, db=db, extractor=extractor,
                           index=index, sync=sync, engine=engine)


def test_two_phase_filtering_and_raw_path_mapping(tmp_path, monkeypatch):
    env = build(tmp_path)
    expected = {image(env.left / name) for name in ('Thé.TIF', 'x.tiff', 'a.JPG', 'b.jpeg', 'c.png', 'd.bmp', 'e.webp')}
    expected.add(image(env.right / 'Thé.TIF'))
    for name in ('@EADIR/x.jpg', '#RECYCLE/x.jpg', '$RECYCLE.BIN/x.jpg', '__MACOSX/x.jpg',
                 'nested/THUMBS.DB/x.jpg', 'Thumbs.db', 'a.psd', 'x.MOV', '._cache.png'):
        image(env.left / name)
    enumerate_walk = os.walk
    completed = []

    def walk(root, **kwargs):
        assert kwargs['followlinks'] is False
        yield from enumerate_walk(root, **kwargs)
        assert not env.db.file_metadata()
        completed.append(root)

    original = env.extractor.extract_all_features

    def extract(data):
        assert len(completed) == 2
        return original(data)

    monkeypatch.setattr(filesystem_sync.os, 'walk', walk)
    monkeypatch.setattr(env.extractor, 'extract_all_features', extract)
    assert env.sync.scan_once()['complete']
    assert set(env.db.file_metadata()) == expected
    assert {r['image_url'] for r in env.db.all_features()} >= {r'\\nas\a\Thé.TIF', r'\\nas\ab\Thé.TIF'}


@pytest.mark.parametrize('case', ['missing_marker', 'wrong_marker', 'unreadable', 'walk_error',
                                  'stat_error', 'empty_root', 'marker_changed_at_commit'])
def test_incomplete_scan_never_deletes(tmp_path, monkeypatch, case):
    env = build(tmp_path)
    lost = Path(image(env.left / 'lost.jpg'))
    keep = Path(image(env.left / 'keep.jpg'))
    image(env.right / 'reachable.jpg')
    env.sync.scan_once()
    lost.unlink()
    assert env.sync.scan_once()['pending_delete'] == 1
    marker = env.left / '.image-search-root'
    if case == 'missing_marker':
        marker.unlink()
    elif case == 'wrong_marker':
        marker.write_text('unexpected')
    elif case == 'empty_root':
        keep.unlink()
    elif case in ('unreadable', 'walk_error'):
        walk = os.walk

        def broken(root, *, followlinks, onerror):
            if root == str(env.left) and case == 'unreadable':
                onerror(PermissionError(root))
                return
            yield from walk(root, followlinks=followlinks, onerror=onerror)
            if root == str(env.left):
                onerror(OSError('subdirectory gone'))

        monkeypatch.setattr(filesystem_sync.os, 'walk', broken)
    elif case == 'stat_error':
        lstat = os.lstat

        def broken_stat(path, *args, **kwargs):
            if path == str(keep):
                raise PermissionError(path)
            return lstat(path, *args, **kwargs)

        monkeypatch.setattr(filesystem_sync.os, 'lstat', broken_stat)
    else:
        identity = filesystem_sync.marker_identity
        calls = 0

        def switched(root, name):
            nonlocal calls
            if root == str(env.left):
                calls += 1
                if calls == 3:
                    marker.write_text('unexpected')
            return identity(root, name)

        monkeypatch.setattr(filesystem_sync, 'marker_identity', switched)
    status = env.sync.scan_once()
    assert not status['complete'] and status['deletion_skipped'] and status['pending_delete'] == 0
    assert str(lost) in env.db.file_metadata()
    if case == 'stat_error':
        assert status['stat_failures'] == 1
    monkeypatch.undo()
    marker.write_text('a')
    image(keep)
    assert env.sync.scan_once()['pending_delete'] == 1
    assert str(lost) in env.db.file_metadata()
    assert env.sync.scan_once()['pending_delete'] == 0
    assert str(lost) not in env.db.file_metadata()


@pytest.mark.parametrize('direction', ['a', 'ab'])
def test_move_between_roots_converges_without_losing_search(tmp_path, monkeypatch, direction):
    env = build(tmp_path)
    origin, dest = (env.left, env.right) if direction == 'a' else (env.right, env.left)
    original = Path(image(origin / 'move.jpg'))
    moved = dest / original.name
    for root in (env.left, env.right):
        image(root / 'keep.jpg')
    env.sync.scan_once()
    walk = os.walk
    moved_once = False

    def move_mid_scan(root, **kwargs):
        nonlocal moved_once
        yield from walk(root, **kwargs)
        if root == str(env.left) and not moved_once:
            original.rename(moved)
            moved_once = True

    with monkeypatch.context() as patch:
        patch.setattr(filesystem_sync.os, 'walk', move_mid_scan)
        env.sync.scan_once()
    assert str(original) in env.db.file_metadata()
    env.sync.scan_once()
    assert str(moved) in env.db.file_metadata()
    env.sync.scan_once()
    assert {p for p in env.db.file_metadata() if p.endswith('move.jpg')} == {str(moved)}


def test_hash_uses_extracted_bytes_unchanged_sha_and_damage_retry(tmp_path):
    env = build(tmp_path)
    path = Path(image(env.left / 'valid.jpg'))
    bad = env.left / 'bad.jpg'
    bad.write_bytes(b'broken')
    assert env.sync.scan_once()['failures'] == 1
    row = env.db.all_features()[0]
    assert row['sha1'] == sha1(path.read_bytes()).hexdigest()
    assert path.read_bytes() in env.extractor.contents
    calls = len(env.extractor.contents)
    env.sync.scan_once()
    assert len(env.extractor.contents) == calls
    original_mtime = path.stat().st_mtime
    os.utime(path, (original_mtime + 2, original_mtime + 2))
    env.sync.scan_once()
    unchanged = env.db.all_features()[0]
    assert unchanged['mtime'] != row['mtime'] and unchanged['feat_version'] == row['feat_version']
    assert len(env.extractor.contents) == calls
    # A size change alone permits retry even if mtime matches the damaged row.
    bad_mtime = bad.stat().st_mtime
    image(bad)
    os.utime(bad, (bad_mtime, bad_mtime))
    env.sync.scan_once()
    assert str(bad) in env.db.file_metadata() and not env.db.damaged_metadata()


def test_changed_during_read_skips_and_retries(tmp_path, monkeypatch):
    env = build(tmp_path)
    path = Path(image(env.left / 'changing.jpg'))
    env.sync.scan_once()
    old = env.db.all_features()[0]
    path.write_bytes(image_bytes(color='green') + b'changed')
    check = filesystem_files.check_open_file
    calls = 0

    def race(src, name, root, initial):
        nonlocal calls
        if name == str(path):
            calls += 1
            if calls == 2:
                os.utime(path, (initial.st_mtime + 2,) * 2)
        check(src, name, root, initial)

    with monkeypatch.context() as patch:
        patch.setattr(filesystem_files, 'check_open_file', race)
        assert not env.sync.scan_once()['complete']
    assert env.db.all_features()[0]['feat_version'] == old['feat_version']
    assert not env.db.damaged_metadata()
    assert env.sync.scan_once()['complete']
    assert env.db.all_features()[0]['sha1'] == sha1(path.read_bytes()).hexdigest()


def test_symlink_and_directory_escape_are_rejected(tmp_path, monkeypatch):
    env = build(tmp_path)
    target = Path(image(tmp_path / 'outside' / 'escape.jpg'))
    link = env.left / target.name
    directory_link = env.left / 'out'
    if os.name == 'nt':
        import _winapi
        import stat

        _winapi.CreateJunction(str(target.parent), str(directory_link))
        link.write_bytes(target.read_bytes())
        lstat = os.lstat

        def report_link(path, *args, **kwargs):
            if os.fspath(path) == str(link):
                return SimpleNamespace(st_mode=stat.S_IFLNK)
            return lstat(path, *args, **kwargs)

        monkeypatch.setattr(filesystem_files.os, 'lstat', report_link)
    else:
        link.symlink_to(target)
        directory_link.symlink_to(target.parent, target_is_directory=True)
    assert env.sync.scan_once()['eligible_files'] == 0
    for path in (link, directory_link / target.name):
        with pytest.raises(OSError):
            with filesystem_files.open_checked(str(path), str(env.left)):
                pytest.fail('opened a symlink')


def test_path_mapping_rejects_conflicts(tmp_path):
    a, ab = str(tmp_path / 'a'), str(tmp_path / 'ab')
    roots = {a: 'a', ab: 'ab'}
    with pytest.raises(ValueError, match='UNC destinations'):
        FilePaths(roots, {a: r'\\nas\share', ab: r'\\NAS\SHARE\ab'})
    with pytest.raises(ValueError, match='Overlapping path prefix'):
        FilePaths({a: 'a', str(Path(a) / 'nested'): 'nested'}, {a: r'\\nas\a'})
    paths = FilePaths(roots, {a: r'\\nas\a', ab: r'\\nas\ab'})
    assert paths.root_for(str(Path(ab) / '中文.jpg')) == ab
    assert paths.root_for(str(tmp_path / 'abc' / '中文.jpg')) is None


def auth(key=PROD, **overrides):
    claims = dict(sub='nas-image-search', eps_id=2, exp=int(time.time()) + 600)
    claims.update(overrides)
    claims = {k: v for k, v in claims.items() if v is not None}
    return {'Authorization': 'Bearer ' + jwt.encode(claims, key, algorithm='HS256')}


def post(client, name='query.jpeg', payload=None, headers=None):
    return client.post('/images/search', files={'file': (name, image_bytes() if payload is None else payload)},
                       headers=auth() if headers is None else headers)


def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch):
    env = build(tmp_path)
    monkeypatch.setattr(app, 'check_search_features', lambda *args: None)
    monkeypatch.setattr('core.search_engine.FeatureExtractor', lambda **kwargs: env.extractor)
    ran = threading.Event()

    def worker(sync):
        sync.scan_once()
        ran.set()
        sync.stop_event.wait()

    monkeypatch.setattr(FileSystemSync, 'run_forever', worker)
    image(env.left / 'searchable.jpg')
    application = app.create_app(env.config)
    assert {(route.path, frozenset(route.methods)) for route in application.routes} == {
        ('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'}))}
    with TestClient(application) as client:
        assert ran.wait(5)
        assert client.get('/health').json()['scan']['complete']
        assert application.state.engine.index is application.state.sync.index
        assert post(client).json()['total_found'] == 1
        assert client.get('/images/search', params={'path': 'stored.jpg'}).status_code == 405
        assert client.get('/admin/rebuild-status').status_code == 404
    assert not application.state.sync_thread.is_alive()


@pytest.mark.parametrize('jwt_settings', [{'prod_secret': None}, {'prod_secret': ''}, {'prod_secret': 'x' * 31},
                                         {'prod_secret': ' ' * 32}, {'daily_secret': ''}, {'daily_secret': 'short'}])
def test_filesystem_jwt_short_or_empty_refuses_start(tmp_path, jwt_settings):
    env = build(tmp_path)
    env.config['filesystem']['jwt'].update(jwt_settings)
    with pytest.raises(ValueError, match='JWT secrets'):
        with TestClient(app.create_app(env.config, env.engine, env.sync)):
            pytest.fail('started with invalid key')


def test_filesystem_jwt_claims_and_both_keys(tmp_path):
    env = build(tmp_path)
    with TestClient(app.create_app(env.config, env.engine, env.sync)) as client:
        for headers in (auth(), auth(DAILY)):
            assert post(client, headers=headers).status_code == 200
        for headers in ({}, auth('x' * 32), auth(sub=None), auth(sub='other'), auth(exp=None),
                        auth(exp=1), auth(exp='9000000000'), auth(eps_id=True), auth(eps_id=2.0),
                        auth(eps_id='2'), auth(eps_id=3), auth(eps_id=None)):
            assert post(client, headers=headers).status_code == 401
    env.config['filesystem']['jwt']['daily_secret'] = None
    with TestClient(app.create_app(env.config, env.engine, env.sync)) as client:
        assert post(client, headers=auth()).status_code == 200
        assert post(client, headers=auth(DAILY)).status_code == 401


def test_upload_formats_decode_and_real_size_limit(tmp_path):
    env = build(tmp_path)
    with TestClient(app.create_app(env.config, env.engine, env.sync)) as client:
        for suffix, fmt in [('jpeg', 'JPEG'), ('png', 'PNG'), ('webp', 'WEBP'), ('avif', 'AVIF')]:
            assert post(client, 'query.' + suffix, image_bytes(fmt)).status_code == 200
        assert post(client, payload=b'garbage').json()['detail'] == 'Image decode failed'
        assert post(client, payload=b'').json()['detail'] == 'Empty image file'
        assert post(client, 'wrong.bmp', image_bytes('BMP')).json()['detail'] == 'Unsupported file format'
        assert post(client, payload=image_bytes('TIFF')).json()['detail'] == 'Image decode failed'
        limit = 45 * 1024 * 1024
        exact = image_bytes().ljust(limit, b'\0')
        assert post(client, payload=exact).status_code == 200
        assert post(client, payload=exact + b'\0').json()['detail'] == 'File too large'


def test_inline_thumbnail_checks_same_fd_and_returns_stale(tmp_path, monkeypatch):
    env = build(tmp_path)
    first = Path(image(env.left / 'first.jpg'))
    image(env.left / 'second.jpg')
    env.sync.scan_once()
    results = env.engine.search(None, 2)
    assert set(results[0]) == {'path', 'score', 'confidence', 'details', 'thumbnail'}
    with Image.open(BytesIO(b64decode(results[0]['thumbnail']))) as thumb:
        assert thumb.format == 'JPEG' and thumb.size == (180, 120)
    fstat = os.fstat
    decode = Image.open
    checked = set()

    def record(fd):
        checked.add(fd)
        return fstat(fd)

    def swap_after_fd_check(src, *args, **kwargs):
        assert src.fileno() in checked
        if first.exists():
            first.write_bytes(image_bytes(color='blue') + b'changed')
        return decode(src, *args, **kwargs)

    monkeypatch.setattr(filesystem_files.os, 'fstat', record)
    monkeypatch.setattr(filesystem_files.Image, 'open', swap_after_fd_check)
    results = {r['path']: r for r in env.engine.search(None, 2)}
    assert results[r'\\nas\a\first.jpg']['thumbnail'] is None
    assert results[r'\\nas\a\first.jpg']['stale'] is True
    assert results[r'\\nas\a\second.jpg']['thumbnail'] is not None


@pytest.mark.parametrize('field, new_value', [('feat_version', 999), ('eps_id', 3), ('id', 919)])
def test_orb_second_read_bounded_and_rechecks_identity(tmp_path, monkeypatch, field, new_value):
    env = build(tmp_path)
    env.engine.ransac_top_k = 2
    for i in range(5):
        image(env.left / f'{i}.jpg')
    env.sync.scan_once()
    recall = env.index.search(VECTOR, 2, 5)
    ids = [row[0] for row in recall]
    query_log = []
    connection = env.db.get_connection

    @contextmanager
    def traced():
        with connection() as conn:
            conn.set_trace_callback(query_log.append)
            yield conn

    original = env.db.file_search_orb

    def change_after_metadata(requested):
        assert requested == ids[:2]
        with connection() as conn:
            conn.execute(f'UPDATE images SET {field}=? WHERE id=?', (new_value, requested[0]))
        return original(requested)

    monkeypatch.setattr(env.db, 'get_connection', traced)
    monkeypatch.setattr(env.db, 'file_search_orb', change_after_metadata)
    assert len(env.engine.search(None, 2)) == 4
    assert env.extractor.verifications == 1
    reads = [sql for sql in query_log if sql.startswith('SELECT')]
    assert len(reads) == 2 and 'orb_' not in reads[0] and 'cnn_vector' not in ''.join(reads)
    assert 'orb_pts, orb_desc' in reads[1]


def test_index_scores_on_matrix_view_and_filters_tenant():
    class Matrix(np.ndarray):
        def __getitem__(self, key):
            assert self.ndim != 2 or isinstance(key, slice), 'gathered a matrix copy'
            return super().__getitem__(key)

    index = VectorIndex()
    index.upsert(3, 2, VECTOR, 1)
    index.upsert(1, 5, VECTOR, 2)
    index.upsert(2, 2, VECTOR, 3)
    index.vectors = index.vectors.view(Matrix)
    assert [row[0] for row in index.search(VECTOR, 2, 5)] == [2, 3]
    assert [row[0] for row in index.search(VECTOR, 5, 5)] == [1]


def test_fixed_index_load_normalizes_finite_nonzero_vectors(tmp_path):
    db = DatabaseManager(tmp_path / 'index.db')
    for version, value in enumerate((np.finfo(np.float32).max, np.nextafter(np.float32(0), np.float32(1))), 1):
        vector = np.full(1152, value, dtype=np.float32)
        with db.get_connection() as conn:
            db.insert_file(conn, str(version), 'unc', 1.0, 1, 'hash', -1,
                           (vector.tobytes(), None, None), version)
    index = VectorIndex()
    db.file_index_snapshot(index, 0)
    assert len(index.ids) == 3
    np.testing.assert_allclose(np.linalg.norm(index.vectors[:2], axis=1), [1, 1])


def make_video(path, seconds=5):
    writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*'mp4v'), 10, (64, 48))
    assert writer.isOpened()
    try:
        for i in range(seconds * 10):
            writer.write(np.full((48, 64, 3), i % 255, np.uint8))
    finally:
        writer.release()


def test_video_intervals_defaults_replacement_and_two_scan_deletion(tmp_path):
    assert frame_times(60, 8) == [0, 7500, 15000, 22500, 30000, 37500, 45000, 52500]
    assert frame_times(60, 4) == [0, 15000, 30000, 45000]
    assert frame_times(4, 8) == [0, 1500, 3000]
    env = build(tmp_path, video=True)
    assert env.sync.frame_cap == 8
    movie = env.left / 'v.MOV'
    make_video(movie, 5)
    image(env.left / 'keep.jpg')
    env.sync.scan_once()
    old = [r for r in env.db.all_features() if r['path'] == str(movie)]
    assert [r['frame_ms'] for r in old] == [0, 1500, 3000, 4500]
    assert all(r['sha1'] == sha1(movie.read_bytes()).hexdigest() for r in old)
    movie.unlink()
    make_video(movie, 3)
    env.sync.scan_once()
    new = [r for r in env.db.all_features() if r['path'] == str(movie)]
    assert [r['frame_ms'] for r in new] == [0, 1500]
    assert {r['id'] for r in old}.isdisjoint(r['id'] for r in new)
    assert all(r['feat_version'] > old[-1]['feat_version'] for r in new)
    with pytest.raises(sqlite3.IntegrityError):
        with env.db.get_connection() as conn:
            conn.execute('UPDATE images SET frame_ms=0 WHERE path=?', (str(movie),))
    movie.unlink()
    assert env.sync.scan_once()['pending_delete'] == 1
    assert len(env.db.all_features()) == 3
    env.sync.scan_once()
    assert len(env.db.all_features()) == env.index.stats()['total_vectors'] == 1


def test_full_index_keeps_entire_old_group_and_restart_retries(tmp_path):
    env = build(tmp_path, capacity=4, video=True)
    movie = env.left / 'grow.mp4'
    make_video(movie, 3)
    image(env.left / 'one.jpg')
    image(env.right / 'two.jpg')
    assert env.sync.scan_once()['index_full'] == 0
    old = env.index.search(VECTOR, 2, 4)
    before = env.db.file_metadata()
    matrix = env.index.vectors
    movie.unlink()
    make_video(movie, 5)
    assert env.sync.scan_once()['index_full'] == 1
    assert env.index.vectors is matrix
    assert env.index.search(VECTOR, 2, 4) == old
    assert env.db.file_metadata() == before
    index = VectorIndex()
    # The regular 15% headroom grants one slot. Provision one more for this two-slot refresh.
    env.db.file_index_snapshot(index, 6, True)
    assert FileSystemSync(env.config, index, env.db, env.extractor).scan_once()['index_full'] == 0
    assert index.stats()['total_vectors'] == len(env.db.all_features()) == 6


def test_failed_video_group_write_rolls_back_db_and_index(tmp_path, monkeypatch):
    env = build(tmp_path, video=True)
    movie = env.left / 'group.mp4'
    make_video(movie, 3)
    env.sync.scan_once()
    before = env.index.search(VECTOR, 2, 20)
    original = env.db.insert_file

    def fail_middle(conn, path, url, mtime, size, digest, frame_ms, blobs, version):
        if frame_ms == 1500:
            raise sqlite3.OperationalError('simulated write failure')
        return original(conn, path, url, mtime, size, digest, frame_ms, blobs, version)

    movie.unlink()
    make_video(movie, 5)
    monkeypatch.setattr(env.db, 'insert_file', fail_middle)
    with pytest.raises(sqlite3.OperationalError, match='simulated'):
        env.sync.scan_once()
    assert env.index.search(VECTOR, 2, 20) == before
    assert [r['id'] for r in env.db.all_features()] == [r[0] for r in before]


def test_video_aggregates_before_top_n_and_returns_best_frame_thumbnail(tmp_path, monkeypatch):
    env = build(tmp_path, video=True)
    movie = env.left / 'best.mp4'
    make_video(movie, 5)
    image(env.left / 'photo.jpg')
    env.sync.scan_once()

    def score(_query, candidate, **_):
        return int(candidate[1][0][0])

    with env.db.get_connection() as conn:
        conn.execute('UPDATE images SET orb_desc=? WHERE path=? AND frame_ms=3000', (bytes([25]) * 32, str(movie)))
    monkeypatch.setattr(env.extractor, 'compute_orb_ransac_score', score)
    matches = env.engine.search(None, 2, top_k=2)
    assert [r['path'] for r in matches] == [r'\\nas\a\best.mp4', r'\\nas\a\photo.jpg']
    assert matches[0]['frame_ms'] == 3000
    assert Image.open(BytesIO(b64decode(matches[0]['thumbnail']))).getpixel((0, 0))[0] in range(20, 36)
    movie.unlink()
    first = env.engine.search(None, 2, top_k=2)[0]
    assert first['thumbnail'] is None and first['stale']


def test_disabling_video_preserves_frames_without_serving_them(tmp_path):
    env = build(tmp_path, video=True)
    movie = env.left / 'video.mp4'
    make_video(movie, 3)
    image(env.left / 'photo.jpg')
    env.sync.scan_once()
    assert len(env.db.all_features()) == 3
    env.config.pop('video')
    index = VectorIndex()
    env.db.file_index_snapshot(index, 0)
    sync = FileSystemSync(env.config, index, env.db, env.extractor)
    engine = ImageSearchEngine(config=env.config, index=index, db_manager=env.db, extractor=env.extractor)
    assert not sync.video_enabled
    assert sync.scan_once()['pending_delete'] == sync.scan_once()['pending_delete'] == 0
    assert len(env.db.all_features()) == 3
    assert [r['path'] for r in engine.search(None, 2)] == [r'\\nas\a\photo.jpg']


def test_existing_design_schema_reads_back_unchanged(tmp_path):
    path = tmp_path / 'legacy.db'
    with sqlite3.connect(path) as conn:
        conn.execute('''CREATE TABLE images(id INTEGER PRIMARY KEY, eps_id INTEGER NOT NULL,
            design_no TEXT, image_url TEXT NOT NULL, cnn_vector BLOB NOT NULL, orb_desc BLOB,
            orb_pts BLOB, feat_version INTEGER NOT NULL, source_modified TEXT, updated_at TEXT)''')
        conn.execute('INSERT INTO images VALUES(1,2,?, ?, ?,NULL,NULL,7,NULL,NULL)',
                     ('D1', 'https://host/1.jpg', VECTOR.tobytes()))
    db = DatabaseManager(path)
    db.require_design_source()
    row = db.get_features([1])[1]
    assert row['design_no'] == 'D1' and row['feat_version'] == 7
    assert row['path'] is None and row['frame_ms'] == -1
    np.testing.assert_array_equal(row['cnn_vector'], VECTOR)
    with pytest.raises(ValueError, match='separate SQLite file'):
        db.file_index_snapshot(VectorIndex(), 0)