️ perf: NAS 文件源检索提速与 TIFF 大标签内存上界
- 文件源 ransac_top_k 500→200:D6 实测保留 k=500 召回覆盖的 721/725(99.4%),单请求重排 P50 9.2s→3.7s - 文件源 SQLite 启用 WAL:扫描写入不再阻塞检索读元数据(并发下最大 18.3s→1.8s) - TIFF 读取跳过 >16MiB 的 37724/34377 标签载荷(Pillow 10.1.0 IFD 解析前过滤,版本变更即启动失败);像素不变,1GB 图层标签文件峰值 RSS 3.1GB→0.28GB - 迁移快照转回单文件 journal,备份说明区分在线快照与停机归档 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Showing
10 changed files
with
123 additions
and
12 deletions
| ... | @@ -162,10 +162,10 @@ docker-compose logs > logs/docker.log | ... | @@ -162,10 +162,10 @@ docker-compose logs > logs/docker.log |
| 162 | ### 备份数据 | 162 | ### 备份数据 |
| 163 | 163 | ||
| 164 | ```bash | 164 | ```bash |
| 165 | # 备份SQLite数据库和FAISS索引 | 165 | # 停止服务后归档整个 data/。运行中的 WAL 数据库用 SQLite backup API,不能只复制 .db。 |
| 166 | tar -czf backup-$(date +%Y%m%d).tar.gz data/ | 166 | tar -czf backup-$(date +%Y%m%d).tar.gz data/ |
| 167 | 167 | ||
| 168 | # 恢复 | 168 | # 保持服务停止,恢复整个 data/。 |
| 169 | tar -xzf backup-20231217.tar.gz | 169 | tar -xzf backup-20231217.tar.gz |
| 170 | ``` | 170 | ``` |
| 171 | 171 | ... | ... |
| ... | @@ -98,9 +98,8 @@ def create_app(config=None, search_engine=None, data_sync=None): | ... | @@ -98,9 +98,8 @@ def create_app(config=None, search_engine=None, data_sync=None): |
| 98 | raise ValueError('Filesystem JWT subject is required') | 98 | raise ValueError('Filesystem JWT subject is required') |
| 99 | if app.state.engine is None: | 99 | if app.state.engine is None: |
| 100 | settings = app.state.config | 100 | settings = app.state.config |
| 101 | db_path = (settings['filesystem']['sqlite_path'] if filesystem else | 101 | db = (DatabaseManager(settings['filesystem']['sqlite_path'], wal=True) if filesystem else |
| 102 | settings['database']['sqlite']['path']) | 102 | DatabaseManager(settings['database']['sqlite']['path'])) |
| 103 | db = DatabaseManager(db_path) | ||
| 104 | dimension = configured_dimension(settings) | 103 | dimension = configured_dimension(settings) |
| 105 | index = VectorIndex(dimension) | 104 | index = VectorIndex(dimension) |
| 106 | if filesystem: | 105 | if filesystem: | ... | ... |
| ... | @@ -30,7 +30,7 @@ filesystem: | ... | @@ -30,7 +30,7 @@ filesystem: |
| 30 | subject: nas-image-search | 30 | subject: nas-image-search |
| 31 | search: | 31 | search: |
| 32 | max_candidates: 2000 | 32 | max_candidates: 2000 |
| 33 | ransac_top_k: 500 | 33 | ransac_top_k: 200 # D6: keeps 721/725 (99.4%) of k=500 recall coverage; single rerank 3.7s vs 9.2s. |
| 34 | ransac: | 34 | ransac: |
| 35 | min_inliers: 8 | 35 | min_inliers: 8 |
| 36 | reproj_threshold: 6.0 | 36 | reproj_threshold: 6.0 | ... | ... |
| ... | @@ -13,6 +13,8 @@ import numpy as np | ... | @@ -13,6 +13,8 @@ import numpy as np |
| 13 | from PIL import Image | 13 | from PIL import Image |
| 14 | import pillow_avif # Registers AVIF with Pillow. | 14 | import pillow_avif # Registers AVIF with Pillow. |
| 15 | 15 | ||
| 16 | from filesystem_files import open_nas_image | ||
| 17 | |||
| 16 | CNN_VECTOR_DIM = 1152 | 18 | CNN_VECTOR_DIM = 1152 |
| 17 | ORB_MAX_SIDE = 1024 | 19 | ORB_MAX_SIDE = 1024 |
| 18 | MAX_DECODE_PIXELS = 40_000_000 | 20 | MAX_DECODE_PIXELS = 40_000_000 |
| ... | @@ -100,7 +102,7 @@ class FeatureExtractor: | ... | @@ -100,7 +102,7 @@ class FeatureExtractor: |
| 100 | 102 | ||
| 101 | @staticmethod | 103 | @staticmethod |
| 102 | def _read_rgb(image): | 104 | def _read_rgb(image): |
| 103 | source = nullcontext(image) if isinstance(image, Image.Image) else Image.open(image) | 105 | source = nullcontext(image) if isinstance(image, Image.Image) else open_nas_image(image) |
| 104 | with source as decoded: | 106 | with source as decoded: |
| 105 | width, height = decoded.size | 107 | width, height = decoded.size |
| 106 | pixels = width * height | 108 | pixels = width * height | ... | ... |
| ... | @@ -24,7 +24,7 @@ class ImageSearchEngine: | ... | @@ -24,7 +24,7 @@ class ImageSearchEngine: |
| 24 | settings = self.config['filesystem'] | 24 | settings = self.config['filesystem'] |
| 25 | self.file_paths = FilePaths(settings['roots'], settings['unc_prefixes']) | 25 | self.file_paths = FilePaths(settings['roots'], settings['unc_prefixes']) |
| 26 | self.thumbnail_top_n = settings.get('thumbnail_top_n', 20) | 26 | self.thumbnail_top_n = settings.get('thumbnail_top_n', 20) |
| 27 | self.db = db_manager if db_manager is not None else DatabaseManager(db_path) | 27 | self.db = db_manager if db_manager is not None else DatabaseManager(db_path, wal=self.filesystem) |
| 28 | self.index = index if index is not None else VectorIndex(configured_dimension(self.config)) | 28 | self.index = index if index is not None else VectorIndex(configured_dimension(self.config)) |
| 29 | if index is None and self.filesystem: | 29 | if index is None and self.filesystem: |
| 30 | self.db.file_index_snapshot(self.index, settings.get('index_min_capacity', 1024), | 30 | self.db.file_index_snapshot(self.index, settings.get('index_min_capacity', 1024), | ... | ... |
| ... | @@ -8,7 +8,7 @@ import numpy as np | ... | @@ -8,7 +8,7 @@ import numpy as np |
| 8 | 8 | ||
| 9 | 9 | ||
| 10 | class DatabaseManager: | 10 | class DatabaseManager: |
| 11 | def __init__(self, db_path): | 11 | def __init__(self, db_path, *, wal=False): |
| 12 | self.db_path = str(db_path) | 12 | self.db_path = str(db_path) |
| 13 | Path(self.db_path).parent.mkdir(parents=True, exist_ok=True) | 13 | Path(self.db_path).parent.mkdir(parents=True, exist_ok=True) |
| 14 | with self.get_connection() as conn: | 14 | with self.get_connection() as conn: |
| ... | @@ -40,6 +40,8 @@ class DatabaseManager: | ... | @@ -40,6 +40,8 @@ class DatabaseManager: |
| 40 | conn.execute('''CREATE TABLE IF NOT EXISTS damaged_files( | 40 | conn.execute('''CREATE TABLE IF NOT EXISTS damaged_files( |
| 41 | path TEXT PRIMARY KEY, mtime REAL, size INTEGER, sha1 TEXT, | 41 | path TEXT PRIMARY KEY, mtime REAL, size INTEGER, sha1 TEXT, |
| 42 | error_type TEXT, updated_at TEXT)''') | 42 | error_type TEXT, updated_at TEXT)''') |
| 43 | if wal and conn.execute('PRAGMA journal_mode=WAL').fetchone()[0] != 'wal': | ||
| 44 | raise RuntimeError('File source requires SQLite WAL mode') | ||
| 43 | 45 | ||
| 44 | @contextmanager | 46 | @contextmanager |
| 45 | def get_connection(self): | 47 | def get_connection(self): | ... | ... |
| 1 | """Path mapping, checked file descriptors and media decoding for the file source.""" | 1 | """Path mapping, checked file descriptors and media decoding for the file source.""" |
| 2 | from contextlib import contextmanager | 2 | from contextlib import contextmanager |
| 3 | from contextvars import ContextVar | ||
| 3 | from hashlib import sha1 | 4 | from hashlib import sha1 |
| 4 | from io import BytesIO | 5 | from io import BytesIO |
| 6 | import inspect | ||
| 5 | import math | 7 | import math |
| 6 | import os | 8 | import os |
| 7 | from pathlib import Path | 9 | from pathlib import Path |
| 8 | import stat | 10 | import stat |
| 9 | import tempfile | 11 | import tempfile |
| 12 | from textwrap import dedent | ||
| 10 | 13 | ||
| 11 | import cv2 | 14 | import cv2 |
| 12 | from PIL import Image | 15 | from PIL import Image, TiffImagePlugin |
| 13 | 16 | ||
| 14 | 17 | ||
| 15 | IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'} | 18 | IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'} |
| ... | @@ -18,6 +21,38 @@ IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaorig | ... | @@ -18,6 +21,38 @@ IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaorig |
| 18 | '@eadir', '#recycle', '$recycle.bin', 'system volume information'} | 21 | '@eadir', '#recycle', '$recycle.bin', 'system volume information'} |
| 19 | IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'} | 22 | IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'} |
| 20 | IMAGE_SPOOL_BYTES = 32 * 1024 * 1024 | 23 | IMAGE_SPOOL_BYTES = 32 * 1024 * 1024 |
| 24 | MAX_TIFF_METADATA_BYTES = 16 * 1024 * 1024 | ||
| 25 | _skip_large_tiff_metadata = ContextVar('skip_large_tiff_metadata', default=False) | ||
| 26 | |||
| 27 | |||
| 28 | def _install_tiff_metadata_filter(): | ||
| 29 | # Use Pillow 10.1.0's IFD parser and bypass the two payloads before _safe_read. | ||
| 30 | directory = TiffImagePlugin.ImageFileDirectory_v2 | ||
| 31 | source = dedent(inspect.getsource(directory.load)) | ||
| 32 | marker = ' size = count * unit_size\n' | ||
| 33 | if source.count(marker) != 1: | ||
| 34 | raise RuntimeError('Pillow TIFF parser changed; review the metadata filter') | ||
| 35 | guard = (' if (_skip_large_tiff_metadata.get() and tag in (34377, 37724)\n' | ||
| 36 | ' and size > MAX_TIFF_METADATA_BYTES):\n' | ||
| 37 | ' continue\n') | ||
| 38 | scope = dict(vars(TiffImagePlugin), _skip_large_tiff_metadata=_skip_large_tiff_metadata, | ||
| 39 | MAX_TIFF_METADATA_BYTES=MAX_TIFF_METADATA_BYTES) | ||
| 40 | exec(compile(source.replace(marker, marker + guard), inspect.getsourcefile(directory.load), 'exec'), scope) | ||
| 41 | directory.load = scope['load'] | ||
| 42 | |||
| 43 | |||
| 44 | _install_tiff_metadata_filter() | ||
| 45 | |||
| 46 | |||
| 47 | @contextmanager | ||
| 48 | def open_nas_image(source): | ||
| 49 | """Keep the TIFF filter active through decoding and scoped to this reader.""" | ||
| 50 | token = _skip_large_tiff_metadata.set(True) | ||
| 51 | try: | ||
| 52 | with Image.open(source) as image: | ||
| 53 | yield image | ||
| 54 | finally: | ||
| 55 | _skip_large_tiff_metadata.reset(token) | ||
| 21 | 56 | ||
| 22 | 57 | ||
| 23 | def below(path, root): | 58 | def below(path, root): |
| ... | @@ -222,7 +257,7 @@ def jpeg_thumbnail(path, root, expected, frame_ms): | ... | @@ -222,7 +257,7 @@ def jpeg_thumbnail(path, root, expected, frame_ms): |
| 222 | output = BytesIO() | 257 | output = BytesIO() |
| 223 | with open_checked(path, root, expected) as src: | 258 | with open_checked(path, root, expected) as src: |
| 224 | if frame_ms == -1: | 259 | if frame_ms == -1: |
| 225 | with Image.open(src) as decoded: | 260 | with open_nas_image(src) as decoded: |
| 226 | decoded.thumbnail((180, 180)) | 261 | decoded.thumbnail((180, 180)) |
| 227 | image = decoded.convert('RGB') | 262 | image = decoded.convert('RGB') |
| 228 | else: | 263 | else: | ... | ... |
| ... | @@ -13,10 +13,11 @@ import cv2 | ... | @@ -13,10 +13,11 @@ import cv2 |
| 13 | from fastapi.testclient import TestClient | 13 | from fastapi.testclient import TestClient |
| 14 | from jose import jwt | 14 | from jose import jwt |
| 15 | import numpy as np | 15 | import numpy as np |
| 16 | from PIL import Image | 16 | from PIL import Image, ImageFile, TiffImagePlugin, TiffTags |
| 17 | import pytest | 17 | import pytest |
| 18 | 18 | ||
| 19 | import app | 19 | import app |
| 20 | from core.feature_extractor import FeatureExtractor | ||
| 20 | from core.search_engine import ImageSearchEngine | 21 | from core.search_engine import ImageSearchEngine |
| 21 | from core.vector_index import VectorIndex | 22 | from core.vector_index import VectorIndex |
| 22 | from database import DatabaseManager | 23 | from database import DatabaseManager |
| ... | @@ -83,6 +84,69 @@ def test_large_tiff_spools_the_same_bytes_used_for_sha1_and_decode(tmp_path, mon | ... | @@ -83,6 +84,69 @@ def test_large_tiff_spools_the_same_bytes_used_for_sha1_and_decode(tmp_path, mon |
| 83 | assert decoded.getpixel((0, 0)) == (255, 0, 0) | 84 | assert decoded.getpixel((0, 0)) == (255, 0, 0) |
| 84 | 85 | ||
| 85 | 86 | ||
| 87 | @pytest.mark.parametrize('tag', [37724, 34377]) | ||
| 88 | def test_large_tiff_metadata_is_not_read_by_extract_or_thumbnail(tmp_path, monkeypatch, tag): | ||
| 89 | tags = TiffImagePlugin.ImageFileDirectory_v2() | ||
| 90 | tags.tagtype[tag] = TiffTags.UNDEFINED | ||
| 91 | payload_size = 16 * 1024 * 1024 + 1 | ||
| 92 | tags[tag] = b'x' * payload_size | ||
| 93 | pixels = Image.linear_gradient('L').convert('RGB') | ||
| 94 | plain, tagged = tmp_path / 'plain.tiff', tmp_path / 'tagged.tiff' | ||
| 95 | pixels.save(plain) | ||
| 96 | pixels.save(tagged, tiffinfo=tags) | ||
| 97 | assert tagged.stat().st_size > payload_size | ||
| 98 | reads = [] | ||
| 99 | safe_read = ImageFile._safe_read | ||
| 100 | |||
| 101 | def record_read(stream, size): | ||
| 102 | reads.append(size) | ||
| 103 | return safe_read(stream, size) | ||
| 104 | |||
| 105 | monkeypatch.setattr(ImageFile, '_safe_read', record_read) | ||
| 106 | |||
| 107 | def thumbnail(path): | ||
| 108 | return filesystem_files.jpeg_thumbnail(str(path), str(tmp_path), | ||
| 109 | filesystem_files.file_metadata(path.stat()), -1) | ||
| 110 | |||
| 111 | assert np.array_equal(FeatureExtractor._read_rgb(tagged), FeatureExtractor._read_rgb(plain)) | ||
| 112 | assert thumbnail(tagged) == thumbnail(plain) | ||
| 113 | assert payload_size not in reads | ||
| 114 | with Image.open(tagged) as decoded: | ||
| 115 | assert tag in decoded.tag_v2 | ||
| 116 | assert payload_size in reads | ||
| 117 | |||
| 118 | |||
| 119 | def test_nas_tiff_keeps_small_metadata_orientation_and_icc(): | ||
| 120 | profile = b'test ICC profile' | ||
| 121 | small_tag = b'small metadata' | ||
| 122 | buffer = BytesIO() | ||
| 123 | Image.new('RGB', (8, 4)).save(buffer, 'TIFF', icc_profile=profile, tiffinfo={274: 6, 37724: small_tag}) | ||
| 124 | buffer.seek(0) | ||
| 125 | with filesystem_files.open_nas_image(buffer) as image: | ||
| 126 | assert image.tag_v2[37724] == small_tag | ||
| 127 | assert image.info['icc_profile'] == profile | ||
| 128 | image.load() | ||
| 129 | assert image.size == (4, 8) | ||
| 130 | |||
| 131 | |||
| 132 | def test_filesystem_engine_uses_default_config_k_and_wal(tmp_path): | ||
| 133 | config = app.load_config() | ||
| 134 | config['source']['type'] = 'filesystem' | ||
| 135 | config['filesystem'].update(roots={str(tmp_path): 'test'}, | ||
| 136 | unc_prefixes={str(tmp_path): r'\\nas\test'}) | ||
| 137 | path = tmp_path / 'files.db' | ||
| 138 | engine = ImageSearchEngine(db_path=path, config=config, extractor=Extractor()) | ||
| 139 | assert engine.ransac_top_k == 200 | ||
| 140 | with engine.db.get_connection() as conn: | ||
| 141 | assert conn.execute('PRAGMA journal_mode').fetchone()[0] == 'wal' | ||
| 142 | |||
| 143 | |||
| 144 | def test_design_database_keeps_default_journal_mode(tmp_path): | ||
| 145 | db = DatabaseManager(tmp_path / 'design.db') | ||
| 146 | with db.get_connection() as conn: | ||
| 147 | assert conn.execute('PRAGMA journal_mode').fetchone()[0] == 'delete' | ||
| 148 | |||
| 149 | |||
| 86 | def build(tmp_path, capacity=32, video=False): | 150 | def build(tmp_path, capacity=32, video=False): |
| 87 | left, right = tmp_path / 'a', tmp_path / 'ab' | 151 | left, right = tmp_path / 'a', tmp_path / 'ab' |
| 88 | for root in (left, right): | 152 | for root in (left, right): |
| ... | @@ -351,6 +415,8 @@ def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch | ... | @@ -351,6 +415,8 @@ def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch |
| 351 | ('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'}))} | 415 | ('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'}))} |
| 352 | with TestClient(application) as client: | 416 | with TestClient(application) as client: |
| 353 | assert ran.wait(5) | 417 | assert ran.wait(5) |
| 418 | with application.state.engine.db.get_connection() as conn: | ||
| 419 | assert conn.execute('PRAGMA journal_mode').fetchone()[0] == 'wal' | ||
| 354 | assert client.get('/health').json()['scan']['complete'] | 420 | assert client.get('/health').json()['scan']['complete'] |
| 355 | assert application.state.engine.index is application.state.sync.index | 421 | assert application.state.engine.index is application.state.sync.index |
| 356 | assert post(client).json()['total_found'] == 1 | 422 | assert post(client).json()['total_found'] == 1 | ... | ... |
| ... | @@ -98,6 +98,9 @@ def test_backup_snapshot_path_gate_and_offline_import(tmp_path, monkeypatch): | ... | @@ -98,6 +98,9 @@ def test_backup_snapshot_path_gate_and_offline_import(tmp_path, monkeypatch): |
| 98 | conn.commit() | 98 | conn.commit() |
| 99 | assert (tmp_path / 'v3.db-wal').exists() | 99 | assert (tmp_path / 'v3.db-wal').exists() |
| 100 | migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db') | 100 | migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db') |
| 101 | with closing(migration.read_only(tmp_path / 'snapshot.db')) as snapshot: | ||
| 102 | assert snapshot.execute('PRAGMA journal_mode').fetchone()[0] == 'delete' | ||
| 103 | assert snapshot.execute('SELECT COUNT(*) FROM images').fetchone()[0] == 5 | ||
| 101 | conn.execute('DELETE FROM images') | 104 | conn.execute('DELETE FROM images') |
| 102 | conn.commit() | 105 | conn.commit() |
| 103 | assert conn.execute('SELECT COUNT(*) FROM images').fetchone()[0] == 0 | 106 | assert conn.execute('SELECT COUNT(*) FROM images').fetchone()[0] == 0 | ... | ... |
| ... | @@ -46,6 +46,9 @@ def take_snapshot(source, snapshot): | ... | @@ -46,6 +46,9 @@ def take_snapshot(source, snapshot): |
| 46 | def backup(staged): | 46 | def backup(staged): |
| 47 | with closing(read_only(source)) as before, closing(sqlite3.connect(staged)) as after: | 47 | with closing(read_only(source)) as before, closing(sqlite3.connect(staged)) as after: |
| 48 | before.backup(after) | 48 | before.backup(after) |
| 49 | # publish_file links only the database; the snapshot must open without WAL sidecars. | ||
| 50 | if after.execute('PRAGMA journal_mode=DELETE').fetchone()[0] != 'delete': | ||
| 51 | raise RuntimeError('Could not make a standalone SQLite snapshot') | ||
| 49 | publish_file(snapshot, backup) | 52 | publish_file(snapshot, backup) |
| 50 | 53 | ||
| 51 | 54 | ||
| ... | @@ -269,6 +272,7 @@ def import_snapshot(snapshot, target, report_path, paths, etsy_root, extractor, | ... | @@ -269,6 +272,7 @@ def import_snapshot(snapshot, target, report_path, paths, etsy_root, extractor, |
| 269 | write_report() | 272 | write_report() |
| 270 | 273 | ||
| 271 | def write_target(staged): | 274 | def write_target(staged): |
| 275 | # Bulk import publishes a standalone DB; the file-source runtime enables WAL. | ||
| 272 | db = DatabaseManager(staged) | 276 | db = DatabaseManager(staged) |
| 273 | with db.get_connection() as dest: | 277 | with db.get_connection() as dest: |
| 274 | for version, row in enumerate(conn.execute('SELECT * FROM images'), 1): | 278 | for version, row in enumerate(conn.execute('SELECT * FROM images'), 1): | ... | ... |
-
Please register or sign in to post a comment