dd1fec07 by 柴进

:zap:️ 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>
1 parent f3dcd391
......@@ -162,10 +162,10 @@ docker-compose logs > logs/docker.log
### 备份数据
```bash
# 备份SQLite数据库和FAISS索引
# 停止服务后归档整个 data/。运行中的 WAL 数据库用 SQLite backup API,不能只复制 .db。
tar -czf backup-$(date +%Y%m%d).tar.gz data/
# 恢复
# 保持服务停止,恢复整个 data/。
tar -xzf backup-20231217.tar.gz
```
......
......@@ -98,9 +98,8 @@ def create_app(config=None, search_engine=None, data_sync=None):
raise ValueError('Filesystem JWT subject is required')
if app.state.engine is None:
settings = app.state.config
db_path = (settings['filesystem']['sqlite_path'] if filesystem else
settings['database']['sqlite']['path'])
db = DatabaseManager(db_path)
db = (DatabaseManager(settings['filesystem']['sqlite_path'], wal=True) if filesystem else
DatabaseManager(settings['database']['sqlite']['path']))
dimension = configured_dimension(settings)
index = VectorIndex(dimension)
if filesystem:
......
......@@ -30,7 +30,7 @@ filesystem:
subject: nas-image-search
search:
max_candidates: 2000
ransac_top_k: 500
ransac_top_k: 200 # D6: keeps 721/725 (99.4%) of k=500 recall coverage; single rerank 3.7s vs 9.2s.
ransac:
min_inliers: 8
reproj_threshold: 6.0
......
......@@ -13,6 +13,8 @@ import numpy as np
from PIL import Image
import pillow_avif # Registers AVIF with Pillow.
from filesystem_files import open_nas_image
CNN_VECTOR_DIM = 1152
ORB_MAX_SIDE = 1024
MAX_DECODE_PIXELS = 40_000_000
......@@ -100,7 +102,7 @@ class FeatureExtractor:
@staticmethod
def _read_rgb(image):
source = nullcontext(image) if isinstance(image, Image.Image) else Image.open(image)
source = nullcontext(image) if isinstance(image, Image.Image) else open_nas_image(image)
with source as decoded:
width, height = decoded.size
pixels = width * height
......
......@@ -24,7 +24,7 @@ class ImageSearchEngine:
settings = self.config['filesystem']
self.file_paths = FilePaths(settings['roots'], settings['unc_prefixes'])
self.thumbnail_top_n = settings.get('thumbnail_top_n', 20)
self.db = db_manager if db_manager is not None else DatabaseManager(db_path)
self.db = db_manager if db_manager is not None else DatabaseManager(db_path, wal=self.filesystem)
self.index = index if index is not None else VectorIndex(configured_dimension(self.config))
if index is None and self.filesystem:
self.db.file_index_snapshot(self.index, settings.get('index_min_capacity', 1024),
......
......@@ -8,7 +8,7 @@ import numpy as np
class DatabaseManager:
def __init__(self, db_path):
def __init__(self, db_path, *, wal=False):
self.db_path = str(db_path)
Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
with self.get_connection() as conn:
......@@ -40,6 +40,8 @@ class DatabaseManager:
conn.execute('''CREATE TABLE IF NOT EXISTS damaged_files(
path TEXT PRIMARY KEY, mtime REAL, size INTEGER, sha1 TEXT,
error_type TEXT, updated_at TEXT)''')
if wal and conn.execute('PRAGMA journal_mode=WAL').fetchone()[0] != 'wal':
raise RuntimeError('File source requires SQLite WAL mode')
@contextmanager
def get_connection(self):
......
"""Path mapping, checked file descriptors and media decoding for the file source."""
from contextlib import contextmanager
from contextvars import ContextVar
from hashlib import sha1
from io import BytesIO
import inspect
import math
import os
from pathlib import Path
import stat
import tempfile
from textwrap import dedent
import cv2
from PIL import Image
from PIL import Image, TiffImagePlugin
IMAGE_FORMATS = {'.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp'}
......@@ -18,6 +21,38 @@ IGNORE_DIRS = {'__macosx', '.ds_store', 'thumbs.db', '.thumbnails', '.picasaorig
'@eadir', '#recycle', '$recycle.bin', 'system volume information'}
IGNORE_FILES = {'thumbs.db', '.ds_store', 'desktop.ini', '.picasa.ini'}
IMAGE_SPOOL_BYTES = 32 * 1024 * 1024
MAX_TIFF_METADATA_BYTES = 16 * 1024 * 1024
_skip_large_tiff_metadata = ContextVar('skip_large_tiff_metadata', default=False)
def _install_tiff_metadata_filter():
# Use Pillow 10.1.0's IFD parser and bypass the two payloads before _safe_read.
directory = TiffImagePlugin.ImageFileDirectory_v2
source = dedent(inspect.getsource(directory.load))
marker = ' size = count * unit_size\n'
if source.count(marker) != 1:
raise RuntimeError('Pillow TIFF parser changed; review the metadata filter')
guard = (' if (_skip_large_tiff_metadata.get() and tag in (34377, 37724)\n'
' and size > MAX_TIFF_METADATA_BYTES):\n'
' continue\n')
scope = dict(vars(TiffImagePlugin), _skip_large_tiff_metadata=_skip_large_tiff_metadata,
MAX_TIFF_METADATA_BYTES=MAX_TIFF_METADATA_BYTES)
exec(compile(source.replace(marker, marker + guard), inspect.getsourcefile(directory.load), 'exec'), scope)
directory.load = scope['load']
_install_tiff_metadata_filter()
@contextmanager
def open_nas_image(source):
"""Keep the TIFF filter active through decoding and scoped to this reader."""
token = _skip_large_tiff_metadata.set(True)
try:
with Image.open(source) as image:
yield image
finally:
_skip_large_tiff_metadata.reset(token)
def below(path, root):
......@@ -222,7 +257,7 @@ def jpeg_thumbnail(path, root, expected, frame_ms):
output = BytesIO()
with open_checked(path, root, expected) as src:
if frame_ms == -1:
with Image.open(src) as decoded:
with open_nas_image(src) as decoded:
decoded.thumbnail((180, 180))
image = decoded.convert('RGB')
else:
......
......@@ -13,10 +13,11 @@ import cv2
from fastapi.testclient import TestClient
from jose import jwt
import numpy as np
from PIL import Image
from PIL import Image, ImageFile, TiffImagePlugin, TiffTags
import pytest
import app
from core.feature_extractor import FeatureExtractor
from core.search_engine import ImageSearchEngine
from core.vector_index import VectorIndex
from database import DatabaseManager
......@@ -83,6 +84,69 @@ def test_large_tiff_spools_the_same_bytes_used_for_sha1_and_decode(tmp_path, mon
assert decoded.getpixel((0, 0)) == (255, 0, 0)
@pytest.mark.parametrize('tag', [37724, 34377])
def test_large_tiff_metadata_is_not_read_by_extract_or_thumbnail(tmp_path, monkeypatch, tag):
tags = TiffImagePlugin.ImageFileDirectory_v2()
tags.tagtype[tag] = TiffTags.UNDEFINED
payload_size = 16 * 1024 * 1024 + 1
tags[tag] = b'x' * payload_size
pixels = Image.linear_gradient('L').convert('RGB')
plain, tagged = tmp_path / 'plain.tiff', tmp_path / 'tagged.tiff'
pixels.save(plain)
pixels.save(tagged, tiffinfo=tags)
assert tagged.stat().st_size > payload_size
reads = []
safe_read = ImageFile._safe_read
def record_read(stream, size):
reads.append(size)
return safe_read(stream, size)
monkeypatch.setattr(ImageFile, '_safe_read', record_read)
def thumbnail(path):
return filesystem_files.jpeg_thumbnail(str(path), str(tmp_path),
filesystem_files.file_metadata(path.stat()), -1)
assert np.array_equal(FeatureExtractor._read_rgb(tagged), FeatureExtractor._read_rgb(plain))
assert thumbnail(tagged) == thumbnail(plain)
assert payload_size not in reads
with Image.open(tagged) as decoded:
assert tag in decoded.tag_v2
assert payload_size in reads
def test_nas_tiff_keeps_small_metadata_orientation_and_icc():
profile = b'test ICC profile'
small_tag = b'small metadata'
buffer = BytesIO()
Image.new('RGB', (8, 4)).save(buffer, 'TIFF', icc_profile=profile, tiffinfo={274: 6, 37724: small_tag})
buffer.seek(0)
with filesystem_files.open_nas_image(buffer) as image:
assert image.tag_v2[37724] == small_tag
assert image.info['icc_profile'] == profile
image.load()
assert image.size == (4, 8)
def test_filesystem_engine_uses_default_config_k_and_wal(tmp_path):
config = app.load_config()
config['source']['type'] = 'filesystem'
config['filesystem'].update(roots={str(tmp_path): 'test'},
unc_prefixes={str(tmp_path): r'\\nas\test'})
path = tmp_path / 'files.db'
engine = ImageSearchEngine(db_path=path, config=config, extractor=Extractor())
assert engine.ransac_top_k == 200
with engine.db.get_connection() as conn:
assert conn.execute('PRAGMA journal_mode').fetchone()[0] == 'wal'
def test_design_database_keeps_default_journal_mode(tmp_path):
db = DatabaseManager(tmp_path / 'design.db')
with db.get_connection() as conn:
assert conn.execute('PRAGMA journal_mode').fetchone()[0] == 'delete'
def build(tmp_path, capacity=32, video=False):
left, right = tmp_path / 'a', tmp_path / 'ab'
for root in (left, right):
......@@ -351,6 +415,8 @@ def test_routes_startup_and_health_expose_only_file_source(tmp_path, monkeypatch
('/health', frozenset({'GET'})), ('/images/search', frozenset({'POST'}))}
with TestClient(application) as client:
assert ran.wait(5)
with application.state.engine.db.get_connection() as conn:
assert conn.execute('PRAGMA journal_mode').fetchone()[0] == 'wal'
assert client.get('/health').json()['scan']['complete']
assert application.state.engine.index is application.state.sync.index
assert post(client).json()['total_found'] == 1
......
......@@ -98,6 +98,9 @@ def test_backup_snapshot_path_gate_and_offline_import(tmp_path, monkeypatch):
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
......
......@@ -46,6 +46,9 @@ 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)
......@@ -269,6 +272,7 @@ def import_snapshot(snapshot, target, report_path, paths, etsy_root, extractor,
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):
......