test_integrity.py 22.8 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
import json
import sqlite3
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from types import SimpleNamespace

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

from core.search_engine import ImageSearchEngine
from core.vector_index import VectorIndex
from data_sync import DesignDataSync, MySQLSource, primary_url
from database import DatabaseManager

BASE = datetime(2026, 11, 12, 10)
VECTOR = np.eye(1, 1152, dtype=np.float32)[0]


def record(i, url='A', eps=2, modified=BASE, deleted='0'):
    return dict(id=i, eps_id=eps, design_no='D' + str(i),
                images=json.dumps([{'url': 'https://image/' + url}]) if url else None,
                utc_modified=modified, delete_key=deleted)


class Source:
    def __init__(self):
        self.rows = []
        self.fail = False

    def fetch_batch(self, eps_ids, modified, last_id, limit):
        return sorted((r for r in self.rows if r['eps_id'] in eps_ids and
                       (r['utc_modified'], r['id']) > (modified, last_id)),
                      key=lambda r: (r['utc_modified'], r['id']))[:limit]

    def fetch_active(self, eps_ids):
        if self.fail:
            def broken():
                yield self.rows[0]
                raise RuntimeError('source disconnected mid-query')
            return broken()
        return [r for r in self.rows if r['eps_id'] in eps_ids and r['delete_key'] in ('0', None)]


class Extractor:
    def __init__(self):
        self.calls = []
        self.ransac_calls = []

    def extract_all_features(self, path):
        self.calls.append(path)
        return dict(cnn_vector=VECTOR.copy(), orb_kp=np.zeros((16, 2), np.float32),
                    orb_desc=np.zeros((16, 32), np.uint8))

    def compute_orb_ransac_score(self, query, candidate, **kwargs):
        self.ransac_calls.append(kwargs)
        return 17


@pytest.fixture
def env(tmp_path):
    config = dict(database={'sqlite': {'path': str(tmp_path / 'features.db')}},
                  sync={'eps_ids': [1, 2], 'overlap_seconds': 120, 'batch_size': 2},
                  search={'threads': 2, 'max_concurrent': 2},
                  jwt={'secret': 'offline-test-secret', 'algorithm': 'HS256', 'subject': 'test'},
                  upload={'allowed_formats': ['png'], 'max_file_size': 1024,
                          'temp_dir': str(tmp_path / 'uploads')})
    db = DatabaseManager(config['database']['sqlite']['path'])
    index, source, extractor, failed = VectorIndex(), Source(), Extractor(), set()
    def download(url):
        if url in failed:
            raise IOError('offline simulated failure')
        return url
    sync = DesignDataSync(config, index, db, source, download, extractor)
    engine = ImageSearchEngine(config=config, index=index, db_manager=db, extractor=extractor)
    return SimpleNamespace(config=config, db=db, index=index, source=source,
                           extractor=extractor, sync=sync, engine=engine, failed=failed)


def test_new_upsert_restart_and_metadata(env):
    env.source.rows = [record(2)]
    env.sync.sync_once()
    assert env.engine.search('query', 2)[0]['img_id'] == 2
    env.source.rows = [record(2, 'B')]
    env.sync.sync_once()
    assert env.index.stats()['total_vectors'] == 1
    assert len(env.engine.search('query', 2)) == 1
    version = env.db.get_features([2])[2]['feat_version']
    env.source.rows[0]['design_no'] = None
    env.sync.sync_once()
    assert len(env.extractor.calls) == 4
    assert env.db.get_features([2])[2]['design_no'] is None
    restored = ImageSearchEngine(db_path=env.db.db_path, config=env.config, extractor=env.extractor)
    assert restored.search('query', 2)[0]['image_url'].endswith('/B')
    next_sync = DesignDataSync(env.config, db_manager=env.db, source=env.source,
                               downloader=lambda url: url, extractor=env.extractor)
    env.source.rows[0]['images'] = record(2, 'C')['images']
    next_sync.sync_once()
    assert env.db.get_features([2])[2]['feat_version'] > version


@pytest.mark.parametrize('images', [None, '', '[]', '{}', 'bad json', '[{}]'])
def test_no_image_removal(env, images):
    env.source.rows = [record(1)]
    env.sync.sync_once()
    env.source.rows[0]['images'] = images
    env.sync.sync_once()
    assert not env.db.metadata() and not env.index.stats()['total_vectors']


def test_deleted_and_physical_removal_and_scope_shrink(env):
    env.source.rows = [record(1), record(2, eps=1), record(3)]
    env.sync.sync_once()
    env.source.rows[0]['delete_key'] = '1234567890123456789'
    env.sync.sync_once()
    assert 1 not in env.db.metadata()
    env.sync.eps_ids = [2]
    env.source.rows = [record(4)]
    env.sync.reconcile()
    assert set(env.db.metadata()) == {4}


def test_same_second_keyset_and_overlap(env):
    env.source.rows = [record(i) for i in range(1, 8)]
    assert env.sync.sync_once()['total_processed'] == 7
    env.source.rows.append(record(8, modified=BASE - timedelta(seconds=60)))
    env.source.rows[0] = record(1, 'B')
    env.sync.sync_once()
    assert len(env.db.metadata()) == 8
    assert env.db.metadata()[1]['image_url'].endswith('/B')
    env.source.rows.append(record(9, modified=BASE - timedelta(seconds=121)))
    env.sync.sync_once()
    assert 9 not in env.db.metadata()
    env.sync.reconcile()
    assert 9 in env.db.metadata()


@pytest.mark.parametrize('existing', [False, True])
def test_download_failure_preserves_old_until_reconciliation(env, existing):
    if existing:
        env.source.rows = [record(1)]
        env.sync.sync_once()
    env.source.rows = [record(1, 'B')]
    env.failed.add('https://image/B')
    env.sync.sync_once()
    assert env.db.state()['cursor_modified'] is not None
    if existing:
        assert env.db.metadata()[1]['image_url'].endswith('/A')
    else:
        assert not env.db.metadata()
    env.failed.clear()
    env.sync.reconcile()
    assert env.db.metadata()[1]['image_url'].endswith('/B')


def test_reconcile_source_failure_never_removes(env):
    env.source.rows = [record(1), record(2)]
    env.sync.sync_once()
    env.source.rows = [record(1)]
    env.source.fail = True
    with pytest.raises(RuntimeError):
        env.sync.reconcile()
    assert set(env.db.metadata()) == {1, 2}
    assert env.db.state()['last_reconcile_at'] is None


@pytest.mark.parametrize('remove', [False, True])
def test_stale_candidate_dropped(env, monkeypatch, remove):
    env.source.rows = [record(1)]
    env.sync.sync_once()
    original = env.index.search
    def race(*args):
        recalled = original(*args)
        env.source.rows = [record(1, None if remove else 'B')]
        env.sync.sync_once()
        return recalled
    monkeypatch.setattr(env.index, 'search', race)
    assert env.engine.search('query', 2) == []


def test_stable_ties_tenant_filter_and_windows(env):
    env.source.rows = [record(i, eps=1 if i < 3 else 2) for i in [7, 6, 5, 4, 3, 2, 1]]
    env.sync.sync_once()
    env.engine.max_candidates = 3
    env.engine.ransac_top_k = 2
    for _ in range(4):
        env.extractor.ransac_calls.clear()
        assert [r['img_id'] for r in env.engine.search('query', 2)] == [3, 4, 5]
        assert len(env.extractor.ransac_calls) == 2
    assert [r['img_id'] for r in env.engine.search('query', 1)] == [1, 2]


def token(env, **claims):
    return {'Authorization': 'Bearer ' + jwt.encode(
        {'sub': 'test', 'exp': int(time.time()) + 3600, **claims},
        env.config['jwt']['secret'], algorithm='HS256')}


def test_api_tenant_claim_and_contract(env):
    from app import create_app
    env.source.rows = [record(1, eps=1), record(2)]
    env.sync.sync_once()
    with TestClient(create_app(env.config, env.engine, env.sync)) as client:
        for claims in ({}, {'eps_id': '2'}, {'eps_id': True}, {'eps_id': 2.0}, {'eps_id': None}):
            assert client.post('/images/search', headers=token(env, **claims),
                               files={'file': ('q.png', b'fake')}).status_code == 401
        result = client.post('/images/search', headers=token(env, eps_id=1),
                             files={'file': ('q.png', b'fake')}, data={'eps_id': '2'}).json()
        assert set(result) == {'results', 'total_found', 'query_time_ms'}
        assert result['results'] == [dict(design_id='1', design_no='D1', image_url='https://image/A',
                                          similarity=3360.0, confidence='high',
                                          details={'cnn_sim': 1.0, 'ransac_inliers': 17})]
        assert client.get('/health').status_code == 200
        assert client.get('/admin/rebuild-status', headers=token(env)).status_code == 200
        assert client.get('/admin/rebuild-status').status_code == 401
        assert client.post('/sync/trigger', headers=token(env)).status_code == 200


def test_rebuild_mutex_and_health_during_search(env, monkeypatch):
    from app import create_app
    entered, release = threading.Event(), threading.Event()
    def blocked(*args):
        entered.set()
        assert release.wait(5)
        return None
    monkeypatch.setattr(env.source, 'fetch_batch', blocked)
    with TestClient(create_app(env.config, env.engine, env.sync)) as client:
        assert client.post('/admin/rebuild-all', headers=token(env)).json()['status'] == 'started'
        assert entered.wait(2)
        try:
            assert client.post('/admin/rebuild-all', headers=token(env)).json()['status'] == 'in_progress'
            assert client.post('/sync/trigger', headers=token(env)).json()['status'] == 'in_progress'
            assert env.sync.reconcile()['status'] == 'in_progress'
        finally:
            release.set()
            env.sync.worker.join(3)
        assert client.get('/admin/rebuild-status', headers=token(env)).json()['status'] == 'completed'
        entered.clear()
        release.clear()
        monkeypatch.setattr(env.extractor, 'extract_all_features', blocked)
        # 48 个并发搜索超过框架默认 40 个工作线程:排队的搜索占满线程池时健康检查仍须响应
        with ThreadPoolExecutor(max_workers=48) as executor:
            pending = [executor.submit(client.post, '/images/search', headers=token(env, eps_id=2),
                                       files={'file': ('q.png', b'fake')}) for _ in range(48)]
            assert entered.wait(2)
            time.sleep(0.8)  # 等其余搜索全部排到信号量上,把工作线程池占满
            try:
                start = time.perf_counter()
                assert client.get('/health').status_code == 200
                assert time.perf_counter() - start < 1
            finally:
                release.set()
            assert all(f.result().status_code == 200 for f in pending)


def test_old_schema_rejected(tmp_path):
    path = tmp_path / 'old.db'
    with sqlite3.connect(path) as conn:
        conn.execute('CREATE TABLE images(id TEXT PRIMARY KEY, cnn_vector BLOB)')
    with pytest.raises(RuntimeError, match='Old images schema'):
        DatabaseManager(path)


def test_index_swap_delete_and_duplicate():
    index = VectorIndex()
    for i in [8, 2, 5]:
        index.upsert(i, 2, VECTOR, 1)
    index.remove(8)
    index.upsert(5, 1, VECTOR, 2)
    index.remove(999)
    assert index.search(VECTOR, 2, 20) == [(2, 1.0, 1)]
    assert index.search(VECTOR, 1, 20) == [(5, 1.0, 2)]


def test_primary_image_and_null_semantics(env):
    assert primary_url('[{"url":"https://a"},{"score":1,"imgUrl":"https://b"}]') == 'https://b'
    assert primary_url('{"main":"https://a"}') == 'https://a'
    assert primary_url('{"first":{"src":"https://b"}}') == 'https://b'
    env.source.rows = [record(1, deleted=None)]
    env.sync.sync_once()
    assert 1 in env.db.metadata()
    assert env.sync._process_design(record(3, eps=None)) is False


def test_mysql_query_keyset_contract(monkeypatch):
    import pymysql
    connection_calls = []
    class Cursor:
        def __enter__(self):
            return self
        def __exit__(self, *args):
            pass
        def execute(self, sql, params):
            assert sql == 'SELECT 1' and params == ()
        def fetchall(self):
            return []
    class Connection(Cursor):
        def cursor(self):
            return Cursor()
    def connect(**kwargs):
        connection_calls.append(kwargs)
        return Connection()
    monkeypatch.setattr(pymysql, 'connect', connect)
    live_source = MySQLSource(dict(host='offline', port=3306, username='test',
                                   password='unused', database='test'))
    assert live_source._query('SELECT 1', ()) == []
    assert connection_calls[0]['connect_timeout'] == 10
    assert connection_calls[0]['read_timeout'] == 60
    assert connection_calls[0]['write_timeout'] == 60
    source = MySQLSource({})
    calls = []
    source._query = lambda sql, params: calls.append((sql, params)) or []
    source.fetch_batch([2], BASE, 7, 5)
    sql, params = calls[-1]
    assert 'utc_modified = %s AND id > %s' in sql
    assert 'ORDER BY utc_modified ASC, id ASC' in sql
    assert params == (2, BASE, BASE, 7, 5)
    source.fetch_active([2])
    assert "delete_key='0'" in calls[-1][0]


def test_background_rebuild_mutex_without_http(env, monkeypatch):
    entered, release = threading.Event(), threading.Event()
    def blocked(*args):
        entered.set()
        assert release.wait(5)
        return []
    monkeypatch.setattr(env.source, 'fetch_batch', blocked)
    assert env.sync.start_rebuild()['status'] == 'started'
    assert entered.wait(2)
    try:
        assert env.sync.start_rebuild()['status'] == 'in_progress'
        assert env.sync.sync_once()['status'] == 'in_progress'
        assert env.sync.reconcile()['status'] == 'in_progress'
    finally:
        release.set()
        env.sync.worker.join(3)
    assert env.sync.rebuild_status()['status'] == 'completed'


def test_failed_rebuild_releases_mutex(env, monkeypatch):
    def fail(*args):
        raise RuntimeError('query failed')
    monkeypatch.setattr(env.source, 'fetch_batch', fail)
    env.sync.start_rebuild()
    env.sync.worker.join(3)
    assert env.sync.rebuild_status()['status'] == 'failed'
    assert env.sync.mutex.acquire(blocking=False)
    env.sync.mutex.release()


def test_incremental_query_failure_does_not_advance_cursor(env, monkeypatch):
    env.source.rows = [record(1)]
    env.sync.sync_once()
    before = env.db.state()
    def fail(*args):
        raise RuntimeError('query failed')
    monkeypatch.setattr(env.source, 'fetch_batch', fail)
    with pytest.raises(RuntimeError):
        env.sync.sync_once()
    assert env.db.state() == before


def test_reconciliation_metadata_only_and_scope_shrink(env):
    env.source.rows = [record(1), record(2, eps=1)]
    env.sync.sync_once()
    count = len(env.extractor.calls)
    env.source.rows[0]['design_no'] = 'new number'
    env.sync.eps_ids = [2]
    env.sync.reconcile()
    assert env.db.metadata()[1]['design_no'] == 'new number'
    assert set(env.db.metadata()) == {1}
    assert len(env.extractor.calls) == count


def test_empty_reconciliation_source_preserves_local_store(env):
    env.source.rows = [record(1)]
    env.sync.sync_once()
    env.sync.reconcile()
    previous = env.db.state()['last_reconcile_at']
    env.source.rows = []
    with pytest.raises(RuntimeError, match='Empty reconciliation source'):
        env.sync.reconcile()
    assert set(env.db.metadata()) == {1}
    assert env.index.search(VECTOR, 2, 10) == [(1, 1.0, 1)]
    assert env.db.state()['last_reconcile_at'] == previous
    assert env.sync.mutex.acquire(blocking=False)
    env.sync.mutex.release()


def test_direct_recall_ties_and_truncation_with_shuffled_rows():
    index = VectorIndex()
    for design_id in (9, 3, 7):
        index.upsert(design_id, 2, VECTOR, 1)
    index.remove(3)
    index.upsert(3, 2, VECTOR, 2)
    for _ in range(3):
        assert [r[0] for r in index.search(VECTOR, 2, 3)] == [3, 7, 9]
        assert [r[0] for r in index.search(VECTOR, 2, 2)] == [3, 7]
        assert [r[0] for r in index.search(VECTOR, 2, 1)] == [3]
    for design_id in (3, 7, 9):
        index.remove(design_id)
    assert index.stats() == {'total_vectors': 0, 'by_eps_id': {}}
    assert index.search(VECTOR, 2, 10) == []


def test_bulk_load_and_amortized_appends():
    rng = np.random.RandomState(25)
    vectors = rng.normal(size=(22000, 1152)).astype(np.float32)
    index = VectorIndex()
    start = time.perf_counter()
    index.bulk_load(dict(id=i, eps_id=2, cnn_vector=vectors[i], feat_version=i + 1)
                    for i in range(20000))
    index.upsert(20000, 2, vectors[20000], 20001)
    storage = index.vectors
    for i in range(20001, 22000):
        index.upsert(i, 2, vectors[i], i + 1)
    assert time.perf_counter() - start < 20
    assert index.vectors is storage  # no further copies until the doubled capacity is full
    assert len(index.ids) == 40000
    assert index.stats() == {'total_vectors': 22000, 'by_eps_id': {'2': 22000}}
    normalized = vectors / np.linalg.norm(vectors, axis=1)[:, None]
    scores = normalized @ normalized[-1]
    expected = np.lexsort((np.arange(22000), -scores))[:10]
    actual = index.search(vectors[-1], 2, 10)
    assert [r[0] for r in actual] == expected.tolist()
    np.testing.assert_allclose([r[1] for r in actual], scores[expected], atol=2e-6)
    index.remove(21999)
    assert index.stats()['total_vectors'] == 21999
    assert 21999 not in [r[0] for r in index.search(vectors[-1], 2, 22000)]


def test_shared_constructors_never_rebuild_index(env, monkeypatch):
    def forbidden():
        raise AssertionError('Shared index must not be rebuilt or read ORB blobs')
    monkeypatch.setattr(env.db, 'all_features', forbidden)
    monkeypatch.setattr(env.db, 'iter_index_rows', forbidden)
    env.source.rows = [record(1)]
    env.sync.sync_once()
    engine = ImageSearchEngine(config=env.config, index=env.index,
                               db_manager=env.db, extractor=env.extractor)
    sync = DesignDataSync(env.config, index=env.index, db_manager=env.db,
                          source=env.source, downloader=lambda url: url, extractor=env.extractor)
    assert engine.index is sync.index is env.index
    assert sync.version == 1


def test_startup_builds_index_once_with_vector_only_stream(env, monkeypatch):
    import app as api
    import core.search_engine as search_module
    from contextlib import contextmanager
    env.source.rows = [record(1)]
    env.sync.sync_once()
    queries, builds = [], []
    connection = env.db.get_connection
    @contextmanager
    def traced_connection():
        with connection() as conn:
            conn.set_trace_callback(queries.append)
            yield conn
    monkeypatch.setattr(env.db, 'get_connection', traced_connection)
    bulk_load = VectorIndex.bulk_load
    def load(index, rows):
        builds.append(index)
        bulk_load(index, rows)
    monkeypatch.setattr(VectorIndex, 'bulk_load', load)
    monkeypatch.setattr(api, 'DatabaseManager', lambda path: env.db)
    monkeypatch.setattr(search_module, 'FeatureExtractor', lambda **kwargs: env.extractor)
    monkeypatch.setattr(DesignDataSync, 'run_forever', lambda sync: sync.stop_event.wait(5))
    def forbidden():
        raise AssertionError('Startup must not select ORB blobs')
    monkeypatch.setattr(env.db, 'all_features', forbidden)
    application = api.create_app(dict(env.config, mysql={}))
    with TestClient(application) as client:
        assert len(builds) == 1
        assert application.state.engine.index is application.state.sync.index
        assert application.state.sync.version == 1
        health = client.get('/health').json()
        assert health['database'] == {'total_images': 1}
        assert health['sync']['status'] == 'active'
    selects = [q for q in queries if q.startswith('SELECT')]
    assert selects.count('SELECT id, eps_id, cnn_vector, feat_version FROM images') == 1
    assert selects.count('SELECT COALESCE(MAX(feat_version), 0) FROM images') == 1
    assert not any('SELECT * FROM images' in q or 'orb_' in q for q in selects)


def test_health_reports_sqlite_counts_timestamps_and_rebuild(env):
    from app import create_app
    env.source.rows = [record(1)]
    env.sync.sync_once()
    env.sync.reconcile()
    env.index.remove(1)  # distinguish SQLite's row count from the derived index count
    with TestClient(create_app(env.config, env.engine, env.sync)) as client:
        health = client.get('/health').json()
    state = env.db.state()
    assert health['database'] == {'total_images': 1}
    assert health['index']['total_vectors'] == 0
    assert health['sync'] == {'status': 'inactive', 'last_sync': state['last_sync_at'],
                              'last_reconcile': state['last_reconcile_at']}
    assert health['rebuild'] == {'status': 'idle'}


@pytest.mark.parametrize('stage', ['download', 'feature extraction'])
def test_refresh_failure_logs_diagnostic_without_secrets(env, monkeypatch, caplog, stage):
    env.source.rows = [record(1)]
    env.config['mysql'] = {'password': 'private-password'}
    def fail(*args):
        raise OSError("broken input private-password https://user:pass@example/a?token=hidden b'IMAGEBYTES'")
    if stage == 'download':
        monkeypatch.setattr(env.sync, 'downloader', fail)
    else:
        monkeypatch.setattr(env.extractor, 'extract_all_features', fail)
    env.sync.sync_once()
    assert stage + ' failed for design 1: OSError: broken input' in caplog.text
    assert all(secret not in caplog.text for secret in ('private-password', 'user:pass', 'hidden', 'IMAGEBYTES'))


def test_sync_summary_logs_once_only_for_nonempty_round(env, caplog):
    import logging
    caplog.set_level(logging.INFO, logger='data_sync')
    env.sync.sync_once()
    assert not caplog.records
    env.source.rows = [record(i) for i in range(1, 6)]
    env.sync.sync_once()
    summaries = [r.getMessage() for r in caplog.records if r.name == 'data_sync' and r.levelno == logging.INFO]
    assert summaries == ['Sync round processed=5 succeeded=5 failed=0']


def test_image_change_replaces_vector(env):
    """改图后索引里必须是新图的向量:按旧图向量搜不再满分,按新图向量搜满分。"""
    vectors = {'A': np.eye(1, 1152, 0, dtype=np.float32)[0], 'B': np.eye(1, 1152, 1, dtype=np.float32)[0]}
    current = {}

    def extract(path):
        current['path'] = path
        return dict(cnn_vector=vectors[path[-1]].copy(), orb_kp=None, orb_desc=None)

    env.extractor.extract_all_features = extract
    env.source.rows = [record(5, 'A')]
    env.sync.sync_once()
    assert env.index.search(vectors['A'], 2, 5)[0][:2] == (5, pytest.approx(1.0))
    env.source.rows = [record(5, 'B')]
    env.sync.sync_once()
    assert env.index.stats()['total_vectors'] == 1
    assert env.index.search(vectors['B'], 2, 5)[0][:2] == (5, pytest.approx(1.0))
    assert env.index.search(vectors['A'], 2, 5)[0][1] == pytest.approx(0.0)
    stored = env.db.get_features([5])[5]
    np.testing.assert_array_equal(stored['cnn_vector'], vectors['B'])
    restored = ImageSearchEngine(db_path=env.db.db_path, config=env.config, extractor=env.extractor)
    assert restored.index.search(vectors['B'], 2, 5)[0][:2] == (5, pytest.approx(1.0))