test_migrate_v3.py
12.4 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
from contextlib import closing
from hashlib import sha1
from io import BytesIO
import json
import os
from pathlib import Path
import sqlite3
import numpy as np
from PIL import Image
import pytest
from database import DatabaseManager
from filesystem_files import FilePaths
from tools import migrate_v3 as migration
CNN = np.eye(1, 1152, dtype=np.float32)[0]
POINTS = np.array([[12, 34, 56, 78]], dtype=np.float32)
DESCRIPTORS = np.arange(32, dtype=np.uint8)[None, :]
FEATURES = {'cnn_vector': CNN, 'orb_kp': POINTS[:, :2], 'orb_desc': DESCRIPTORS}
# V3 table shape from indexer.py, including the legacy damaged table's missing mtime/size.
SCHEMA = '''
CREATE TABLE images(
id INTEGER PRIMARY KEY AUTOINCREMENT, path TEXT UNIQUE NOT NULL,
mtime REAL NOT NULL, size INTEGER NOT NULL, sha1 TEXT NOT NULL, phash TEXT,
edge_phash TEXT, orb_desc BLOB, orb_keypoints BLOB, cnn_vector BLOB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE damaged_files(path TEXT PRIMARY KEY, sha1 TEXT, error_type TEXT,
last_attempt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, attempt_count INTEGER DEFAULT 1);
'''
class Extractor:
def extract_all_features(self, stream):
with Image.open(stream) as decoded:
decoded.load()
if decoded.getpixel((0, 0)) == (0, 0, 0):
return dict(FEATURES, orb_kp=None, orb_desc=None)
return FEATURES
def create_source(tmp_path, schema=SCHEMA):
etsy = tmp_path / 'etsy'
etsy.mkdir()
(etsy / '.image-search-root').write_text('Etsy', encoding='utf-8')
paths = FilePaths({str(etsy): 'Etsy'}, {str(etsy): r'\\nas\Etsy'})
conn = sqlite3.connect(tmp_path / 'v3.db')
conn.execute('PRAGMA journal_mode=WAL')
conn.executescript(schema)
return conn, etsy, paths
def insert(conn, etsy, legacy_path, *, color='red', exists=True, bad_cnn=False,
changed_sha=False, month='2026-09', wrong_points=False, padded_size=0):
path = Path(migration.convert_path(legacy_path, str(etsy)))
fmt = 'JPEG' if path.suffix == '.jpg' else 'PNG'
data = BytesIO()
Image.new('RGB', (8, 8), color).save(data, fmt)
content = data.getvalue() + b'\0' * padded_size
mtime = 1000
if exists:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(content)
os.utime(path, (mtime, mtime))
mtime = path.stat().st_mtime
conn.execute('''INSERT INTO images(path, mtime, size, sha1, orb_desc, orb_keypoints,
cnn_vector, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)''',
(legacy_path, mtime, len(content), sha1(b'stale' if changed_sha else content).hexdigest(),
None if color == 'black' else DESCRIPTORS.tobytes(),
b'' if color == 'black' else (POINTS + int(wrong_points)).tobytes(),
None if bad_cnn else CNN.tobytes(), month + '-01 00:00:00'))
return path
def run_import(tmp_path, etsy, paths, **options):
snapshot, target, report = [tmp_path / p for p in ('snapshot.db', 'target.db', 'gate.json')]
result = migration.import_snapshot(snapshot, target, report, paths, str(etsy), Extractor(), **options)
assert json.loads(report.read_text(encoding='utf-8')) == result
return result, DatabaseManager(target)
def test_backup_snapshot_path_gate_and_offline_import(tmp_path, monkeypatch):
connection, etsy, paths = create_source(tmp_path)
with closing(connection) as conn:
kept = insert(conn, etsy, '/data/guangzhou/中文.jpg')
blank = insert(conn, etsy, '/data/baidusync/blank.png', color='black', padded_size=256 * 1024)
malformed = insert(conn, etsy, '/data/baidusync/bad.jpg', bad_cnn=True)
missing = insert(conn, etsy, '/data/guangzhou/deleted.jpg', exists=False)
changed = insert(conn, etsy, '/data/guangzhou/changed.jpg', changed_sha=True)
os.utime(changed, (2000, 2000))
legacy_damage = '/data/guangzhou/old-damage.jpg'
damaged = migration.convert_path(legacy_damage, str(etsy))
conn.execute('INSERT INTO damaged_files(path, sha1, error_type) VALUES(?, ?, ?)',
(legacy_damage, 'old-hash', 'old-error'))
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
(etsy / 'new.tif').write_bytes(b'new file')
publish = migration.publish_file
def gate_written_first(path, writer):
if path == tmp_path / 'target.db':
persisted = json.loads((tmp_path / 'gate.json').read_text(encoding='utf-8'))
assert persisted['gate'] == 'passed' and persisted['counts']['keep'] == 2
assert not path.exists()
publish(path, writer)
monkeypatch.setattr(migration, 'publish_file', gate_written_first)
report, db = run_import(tmp_path, etsy, paths, minimum_samples=2)
assert report['counts'] == dict(keep=2, reextract=2, delete=1, imported_images=4, new=1,
imported_damaged=1, damaged_missing=1)
assert report['pending_delete'] == [str(missing)]
assert report['structure_failures'] == [{'path': str(malformed), 'reason': 'cnn_dimension'}]
assert len(report['sample']['by_batch']) == 2
assert report['sample']['stale_replaced'] == 1
rows = {row['path']: row for row in db.all_features()}
assert set(rows) == {str(kept), str(blank), str(changed), str(missing)}
assert rows[str(kept)]['image_url'] == r'\\nas\Etsy\YANQING\H\广州数据共享\中文.jpg'
with db.get_connection() as dest:
raw = dest.execute('SELECT * FROM images WHERE path=?', (str(kept),)).fetchone()
assert raw['cnn_vector'] == CNN.tobytes() and raw['orb_desc'] == DESCRIPTORS.tobytes()
assert raw['orb_pts'] == POINTS[:, :2].tobytes()
assert raw['frame_ms'] == -1 and raw['eps_id'] == 2
assert raw['mtime'] == kept.stat().st_mtime and raw['size'] == kept.stat().st_size
assert raw['sha1'] == sha1(kept.read_bytes()).hexdigest()
assert db.damaged_metadata() == {damaged: (None, None)}
with pytest.raises(FileExistsError):
migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
with pytest.raises(FileExistsError):
run_import(tmp_path, etsy, paths, minimum_samples=2)
@pytest.mark.parametrize('table, legacy', [('images', '/data/guangzhou-extra/a.jpg'),
('damaged_files', '/data/unknown/a.jpg'),
('damaged_files', '/data/baidusync/../escape.jpg')])
def test_path_gate_rejects_unknown_and_traversal_before_target(tmp_path, table, legacy):
connection, etsy, paths = create_source(tmp_path)
with closing(connection) as conn:
insert(conn, etsy, '/data/guangzhou/ok.jpg')
if table == 'images':
conn.execute('INSERT INTO images(path,mtime,size,sha1) VALUES(?,0,0,?)', (legacy, 'invalid'))
else:
conn.execute('INSERT INTO damaged_files(path) VALUES(?)', (legacy,))
conn.commit()
migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
with pytest.raises(ValueError, match='Unknown or unsafe V3 path'):
run_import(tmp_path, etsy, paths, minimum_samples=1)
assert not (tmp_path / 'target.db').exists()
assert json.loads((tmp_path / 'gate.json').read_text(encoding='utf-8'))['gate'] == 'failed'
def test_path_gate_checks_unique_even_with_legacy_constraint_absent(tmp_path):
connection, etsy, paths = create_source(tmp_path, SCHEMA.replace(' UNIQUE', ''))
with closing(connection) as conn:
for _ in range(2):
insert(conn, etsy, '/data/guangzhou/duplicate.jpg')
conn.commit()
migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
with pytest.raises(ValueError, match='Duplicate converted images path'):
run_import(tmp_path, etsy, paths, minimum_samples=1)
assert not (tmp_path / 'target.db').exists()
def test_full_structure_and_precise_sample_comparisons():
row = dict(cnn_vector=CNN.tobytes(), orb_desc=DESCRIPTORS.tobytes(), orb_keypoints=POINTS.tobytes())
assert migration.validate_features(row) is None
for invalid, reason in [({'cnn_vector': b'bad'}, 'cnn_dimension'),
({'cnn_vector': bytes(1152 * 4)}, 'cnn_value'),
({'cnn_vector': np.full(1152, np.nan, np.float32).tobytes()}, 'cnn_value'),
({'orb_desc': b'bad'}, 'orb_shape'), ({'orb_desc': b''}, 'orb_shape'),
({'orb_keypoints': POINTS.tobytes() * 2}, 'orb_shape'),
({'orb_keypoints': np.full(4, np.nan, np.float32).tobytes()}, 'orb_value')]:
assert migration.validate_features(dict(row, **invalid)) == reason
assert migration.compare_features(row, FEATURES) == []
for cosine, passed in [(0.99995, True), (0.99989, False)]:
vector = CNN.copy()
vector[:2] = [cosine, np.sqrt(1 - cosine ** 2)]
assert (migration.compare_features(row, dict(FEATURES, cnn_vector=vector)) == []) == passed
assert migration.compare_features(row, dict(FEATURES, orb_kp=POINTS[:, :2] + 1)) == ['orb_coordinates']
assert migration.compare_features(row, dict(FEATURES, orb_desc=DESCRIPTORS + 1)) == ['orb_descriptors']
empty = dict(row, orb_keypoints=b'', orb_desc=None)
assert migration.validate_features(empty) is None
assert migration.compare_features(empty, dict(FEATURES, orb_kp=None, orb_desc=None)) == []
assert migration.compare_features(empty, FEATURES) == ['orb_empty']
def test_mismatch_blocks_target_until_explicit_batch_is_approved(tmp_path):
connection, etsy, paths = create_source(tmp_path)
with closing(connection) as conn:
rejected = insert(conn, etsy, '/data/guangzhou/reorb.jpg', wrong_points=True, month='2026-01')
accepted = insert(conn, etsy, '/data/baidusync/keep.png', month='2026-02')
conn.commit()
migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
with pytest.raises(ValueError, match='Sample comparison gate failed'):
run_import(tmp_path, etsy, paths, minimum_samples=1)
report_path = tmp_path / 'gate.json'
report = json.loads(report_path.read_text(encoding='utf-8'))
assert not (tmp_path / 'target.db').exists()
assert report['sample']['checked'] == 2
mismatch, = report['sample']['mismatches']
assert mismatch['path'] == str(rejected) and mismatch['failures'] == ['orb_coordinates']
report_path.unlink()
updated, db = run_import(tmp_path, etsy, paths, minimum_samples=1, reextract_batches=[mismatch['batch']])
assert updated['counts']['reextract'] == 1
assert set(db.file_metadata()) == {str(accepted)}
def test_default_sample_gate_requires_300_unchanged_and_covers_both_legacy_roots(tmp_path):
connection, etsy, paths = create_source(tmp_path)
with closing(connection) as conn:
for i in range(300):
prefix = 'guangzhou' if i % 2 else 'baidusync'
insert(conn, etsy, f'/data/{prefix}/{i}.png', changed_sha=i == 0)
conn.commit()
migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
with pytest.raises(ValueError, match='Sample comparison gate failed'):
run_import(tmp_path, etsy, paths)
report_path = tmp_path / 'gate.json'
report = json.loads(report_path.read_text(encoding='utf-8'))
assert report['sample']['checked'] == 299 and report['sample']['stale_replaced'] == 1
assert not (tmp_path / 'target.db').exists()
report_path.unlink()
(tmp_path / 'snapshot.db').unlink()
insert(conn, etsy, '/data/guangzhou/extra.jpg', month='2025-01')
conn.commit()
migration.take_snapshot(tmp_path / 'v3.db', tmp_path / 'snapshot.db')
report, db = run_import(tmp_path, etsy, paths)
assert report['sample']['checked'] == 300
assert len(report['sample']['by_batch']) == 3
changed = migration.convert_path('/data/baidusync/0.png', str(etsy))
assert report['sample']['same_metadata_reextract'] == [changed]
assert report['counts']['reextract'] == 1
assert changed not in db.file_metadata()