cmvr-visual/inference/tests/test_fl2va_download.py

462 lines
21 KiB
Python

import importlib.util
import hashlib
import json
import os
from pathlib import Path
import subprocess
import types
import pytest
spec = importlib.util.spec_from_file_location('fl2va_download', Path(__file__).parents[1] / 'scripts/download_fl2va_models.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def test_download_selects_one_official_diffusers_partition_only():
names = ['transformer/weights.safetensors', 'text_encoder/model.safetensors',
'vae/model.safetensors', 'audio_vae/model.safetensors', 'modular_model_index.json',
'FL2VA/transformer/model.safetensors', 'Ref2VA/transformer/model.safetensors',
'transformer_ref/weights.safetensors', 'assets/sample.mp4']
selected = module.select_files([{'rfilename': name} for name in names])
assert [item['rfilename'] for item in selected] == names[:5]
def test_download_refuses_unpinned_or_malformed_metadata():
with pytest.raises(ValueError, match='revision'):
module.validate_metadata({'repo': module.H3_REPO, 'revision': 'main', 'files': []})
with pytest.raises(ValueError, match='path'):
module.select_files([{'rfilename': 'transformer/../../outside.safetensors'}])
def checkpoint(name, data=b'official checkpoint'):
return {'rfilename': name, 'size': len(data),
'lfs': {'sha256': hashlib.sha256(data).hexdigest(), 'size': len(data)}}
def helper():
source = Path(__file__).parents[1] / 'scripts/download_models.py'
spec = importlib.util.spec_from_file_location('fl2va_integrity_helper', source)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
def destination(command):
directory = next(value.split('=', 1)[1] for value in command if value.startswith('--dir='))
name = next(value.split('=', 1)[1] for value in command if value.startswith('--out='))
return Path(directory) / name
def test_cli_defaults_to_two_transfers_and_a_total_eight_mib_limit():
args = module.parse_args([])
assert args.workers == 2 and args.max_total_mib == 8 and args.attempts == 3
for values in (['--workers', '0'], ['--workers', '9'],
['--max-total-mib', '0'], ['--max-total-mib', '9']):
with pytest.raises(SystemExit):
module.parse_args(values)
def test_cli_accepts_explicit_progress_state_and_total_limit(tmp_path):
path = tmp_path / 'deployment' / 'progress-limited.json'
args = module.parse_args(['--state', str(path), '--total-limit', '4'])
assert args.state == path and args.max_total_mib == 4
def test_progress_can_be_written_outside_the_checkpoint_directory(tmp_path, monkeypatch):
state_path = tmp_path / 'deployment' / 'progress.json'
def run(command, *, timeout):
destination(command).write_bytes(b'official checkpoint')
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
assert module.download_files([checkpoint('transformer/shard.safetensors')],
tmp_path / 'models', helper(), state_path=state_path, aria_binary='aria2c') == 0
assert json.loads(state_path.read_text())['state'] == 'ready'
def test_unfinished_control_file_is_preserved_even_after_an_unexpected_zero_exit(tmp_path, monkeypatch):
path = tmp_path / 'transformer' / 'shard.safetensors'
path.parent.mkdir()
path.write_bytes(b'partial')
control = path.with_name(path.name + '.aria2')
control.write_bytes(b'resume map')
calls = []
def run(command, *, timeout):
calls.append(command)
assert control.read_bytes() == b'resume map'
assert path.read_bytes() == b'partial'
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
monkeypatch.setattr(module, 'retry_sleep', lambda _: None)
assert module.download_files([checkpoint('transformer/shard.safetensors')], tmp_path,
helper(), aria_binary='aria2c') == 1
assert len(calls) == 3
assert control.read_bytes() == b'resume map' and path.read_bytes() == b'partial'
@pytest.mark.parametrize(('workers', 'total_mib', 'want'), [(2, 8, 4194304),
(3, 8, 2796202), (4, 8, 2097152), (4, 4, 1048576), (8, 1, 131072), (1, 8, 8388608)])
def test_all_aria_transfers_share_the_total_limit_without_global_patches(
tmp_path, monkeypatch, workers, total_mib, want):
downloader = helper()
original_run, original_get = subprocess.run, downloader.requests.get
commands = []
def run(command, *, timeout):
commands.append(command)
path = destination(command)
path.write_bytes(b'official checkpoint')
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
files = [checkpoint('transformer/shard.safetensors'), checkpoint('tokenizer/tokenizer.json')]
assert module.download_files(files, tmp_path, downloader, workers=workers,
total_mib=total_mib, aria_binary='aria2c') == 0
assert len(commands) == 2 # Small files use the same capped transport.
for command in commands:
assert f'--max-overall-download-limit={want}' in command
assert '--max-tries=1' in command
assert '--split=16' in command
assert '--max-connection-per-server=16' in command
assert '--checksum=sha-256=' + files[0]['lfs']['sha256'] in command
assert want * workers <= total_mib * 1024**2
assert subprocess.run is original_run and downloader.requests.get is original_get
state = json.loads((tmp_path / '.download-state.json').read_text())
assert state['state'] == 'ready' and state['verified_files'] == 2
manifest = json.loads((tmp_path / '.deployment-manifest.json').read_text())
assert manifest['repo'] == module.H3_REPO and manifest['revision'] == module.H3_REVISION
assert manifest['files'] == files and manifest['verified_at'] > 0
def test_resume_keeps_aria_control_and_rechecks_canonical_checksum(tmp_path, monkeypatch):
path = tmp_path / 'transformer' / 'shard.safetensors'
path.parent.mkdir()
path.write_bytes(b'partial')
control = path.with_name(path.name + '.aria2')
control.write_bytes(b'existing chunk map')
def run(command, *, timeout):
assert control.read_bytes() == b'existing chunk map'
assert path.read_bytes() == b'partial'
assert '--continue=true' in command
path.write_bytes(b'official checkpoint')
control.unlink()
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
assert module.download_files([checkpoint('transformer/shard.safetensors')], tmp_path,
helper(), aria_binary='aria2c') == 0
assert path.read_bytes() == b'official checkpoint'
def test_transient_dns_and_tls_failures_alternate_replica_and_pinned_canonical(tmp_path, monkeypatch):
calls, waits = [], []
def run(command, *, timeout):
calls.append(command)
if len(calls) == 1:
raise OSError('temporary DNS failure')
if len(calls) == 2:
return types.SimpleNamespace(returncode=1)
destination(command).write_bytes(b'official checkpoint')
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
monkeypatch.setattr(module, 'retry_sleep', waits.append)
assert module.download_files([checkpoint('transformer/shard.safetensors')], tmp_path,
helper(), aria_binary='aria2c') == 0
assert len(calls) == 3 and len(waits) == 2
assert calls[0][-1].startswith('https://modelscope.cn/')
assert f'/{module.H3_REPO}/resolve/{module.H3_REVISION}/' in calls[1][-1]
assert calls[2][-1].startswith('https://modelscope.cn/')
state = json.loads((tmp_path / '.download-state.json').read_text())
assert state['files']['transformer/shard.safetensors']['attempt'] == 3
def test_all_five_weight_attempts_alternate_sources_without_dropping_resume_state(tmp_path, monkeypatch):
path = tmp_path / 'transformer' / 'shard.safetensors'
path.parent.mkdir()
path.write_bytes(b'partial')
control = path.with_name(path.name + '.aria2')
control.write_bytes(b'existing resume map')
commands = []
def run(command, *, timeout):
commands.append(command)
assert '--continue=true' in command and '--check-integrity=true' in command
assert control.read_bytes() == b'existing resume map'
assert path.read_bytes() == b'partial'
if len(commands) < 5:
return types.SimpleNamespace(returncode=1)
path.write_bytes(b'official checkpoint')
control.unlink()
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
monkeypatch.setattr(module, 'retry_sleep', lambda _: None)
item = checkpoint('transformer/shard.safetensors')
assert module.download_files([item], tmp_path, helper(), attempts=5, aria_binary='aria2c') == 0
assert len(commands) == 5
for attempt, command in enumerate(commands, 1):
if attempt % 2:
assert command[-1] == 'https://modelscope.cn/models/MiniMax/MiniMax-H3/resolve/master/transformer/shard.safetensors'
else:
assert f'/{module.H3_REPO}/resolve/{module.H3_REVISION}/' in command[-1]
assert not command[-1].startswith('https://modelscope.cn/')
assert '--checksum=sha-256=' + item['lfs']['sha256'] in command
assert path.read_bytes() == b'official checkpoint'
def test_small_configuration_retries_always_use_pinned_canonical_source(tmp_path, monkeypatch):
data = b'{"config": "official"}'
item = {'rfilename': 'tokenizer/tokenizer.json', 'size': len(data),
'blobId': hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()}
weight = checkpoint('transformer/verified.safetensors')
local_weight = tmp_path / weight['rfilename']
local_weight.parent.mkdir()
local_weight.write_bytes(b'official checkpoint')
commands = []
def run(command, *, timeout):
commands.append(command)
if len(commands) < 5:
return types.SimpleNamespace(returncode=1)
destination(command).write_bytes(data)
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
monkeypatch.setattr(module, 'retry_sleep', lambda _: None)
assert module.download_files([item, weight], tmp_path, helper(), workers=1,
attempts=5, aria_binary='aria2c') == 0
assert len(commands) == 5
assert len({command[-1] for command in commands}) == 1
assert all(f'/{module.H3_REPO}/resolve/{module.H3_REVISION}/' in command[-1]
and not command[-1].startswith('https://modelscope.cn/') for command in commands)
assert (tmp_path / item['rfilename']).read_bytes() == data
def test_four_workers_keep_four_mib_aggregate_cap_with_sixteen_connections_each(tmp_path, monkeypatch):
import threading
barrier, lock = threading.Barrier(4), threading.Lock()
active, peak, commands = 0, 0, []
def run(command, *, timeout):
nonlocal active, peak
with lock:
active += 1
peak = max(peak, active)
commands.append(command)
try:
barrier.wait(timeout=5)
destination(command).write_bytes(b'official checkpoint')
return types.SimpleNamespace(returncode=0)
finally:
with lock:
active -= 1
monkeypatch.setattr(module, 'run_aria', run)
files = [checkpoint(f'transformer/shard_{index}.safetensors') for index in range(4)]
assert module.download_files(files, tmp_path, helper(), workers=4, total_mib=4,
attempts=1, aria_binary='aria2c') == 0
assert peak == 4 and len(commands) == 4
limits = []
for command in commands:
assert '--split=16' in command and '--max-connection-per-server=16' in command
assert '--max-concurrent-downloads=1' in command
limits.append(int(next(value.split('=', 1)[1] for value in command
if value.startswith('--max-overall-download-limit='))))
assert limits == [module.MIB] * 4
assert sum(limits) == 4 * module.MIB
state = json.loads((tmp_path / '.download-state.json').read_text())
assert state['per_worker_limit_bytes'] == module.MIB
assert state['effective_total_limit_bytes'] == 4 * module.MIB
@pytest.mark.skipif(os.name != 'nt', reason='Windows extended-path resolution race')
def test_path_validation_does_not_race_shared_parent_creation(tmp_path, monkeypatch):
import concurrent.futures
import threading
parent = tmp_path / 'transformer'
creating, finished, raced = threading.Event(), threading.Event(), threading.Event()
state_lock = threading.Lock()
owner = None
original_resolve, original_mkdir = Path.resolve, Path.mkdir
def resolve(path, *args, **kwargs):
nonlocal owner
if path.parent == parent and path.suffix == '.safetensors':
with state_lock:
if owner is None:
owner = threading.get_ident()
if threading.get_ident() != owner and not finished.is_set():
assert creating.wait(timeout=2)
# ntpath.realpath can retain this prefix if another thread creates
# the parent between its initial lookup and prefix-removal check.
if creating.is_set():
raced.set()
return Path('\\\\?\\' + str(original_resolve(path, *args, **kwargs)))
return original_resolve(path, *args, **kwargs)
def mkdir(path, *args, **kwargs):
if path == parent and threading.get_ident() == owner and not finished.is_set():
creating.set()
try:
raced.wait(timeout=.2)
return original_mkdir(path, *args, **kwargs)
finally:
creating.clear()
finished.set()
return original_mkdir(path, *args, **kwargs)
monkeypatch.setattr(Path, 'resolve', resolve)
monkeypatch.setattr(Path, 'mkdir', mkdir)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
paths = list(pool.map(lambda index: module._path(tmp_path,
f'transformer/shard_{index}.safetensors'), range(4)))
assert paths == [parent / f'shard_{index}.safetensors' for index in range(4)]
assert not raced.is_set()
@pytest.mark.parametrize('kind', ['leaf', '.aria2', '.incomplete', 'parent', 'junction'])
def test_path_guard_still_refuses_links_and_external_parents(tmp_path, kind):
target, outside = tmp_path / 'models', tmp_path / 'outside'
target.mkdir()
outside.mkdir()
parent = target / 'transformer'
if kind in {'parent', 'junction'}:
if kind == 'junction':
if os.name != 'nt':
pytest.skip('Windows directory junction')
result = subprocess.run(['cmd.exe', '/c', 'mklink', '/J', str(parent), str(outside)],
capture_output=True, check=False)
assert result.returncode == 0, result.stderr.decode(errors='replace')
else:
try:
parent.symlink_to(outside, target_is_directory=True)
except OSError as exc:
pytest.skip(f'Directory symlink unavailable: {exc}')
name = 'transformer/new_directory/shard.safetensors'
else:
parent.mkdir()
source = outside / 'source'
source.write_bytes(b'external data')
link = parent / ('shard.safetensors' + ('' if kind == 'leaf' else kind))
try:
link.symlink_to(source)
except OSError as exc:
pytest.skip(f'File symlink unavailable: {exc}')
name = 'transformer/shard.safetensors'
with pytest.raises(ValueError, match='symlink|escapes'):
module._path(target, name)
assert not (outside / 'new_directory').exists()
assert not (parent / 'shard.safetensors').exists() or kind == 'leaf'
def test_path_guard_still_refuses_traversal_before_creating_directories(tmp_path):
target = tmp_path / 'models'
target.mkdir()
with pytest.raises(ValueError, match='escapes'):
module._path(target, '../outside/new_directory/shard.safetensors')
assert not (tmp_path / 'outside').exists()
def test_one_failed_future_does_not_hide_other_successes_or_write_ready_manifest(tmp_path, monkeypatch, capsys):
(tmp_path / '.deployment-manifest.json').write_text('{"verified_at": 1}')
attempts = []
def run(command, *, timeout):
path = destination(command)
attempts.append(path.name)
if path.name == 'bad.safetensors':
return types.SimpleNamespace(returncode=1)
path.write_bytes(b'official checkpoint')
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
monkeypatch.setattr(module, 'retry_sleep', lambda _: None)
files = [checkpoint('transformer/bad.safetensors'), checkpoint('tokenizer/ok.json')]
assert module.download_files(files, tmp_path, helper(), workers=1, aria_binary='aria2c') == 1
assert attempts.count('bad.safetensors') == 3 and attempts.count('ok.json') == 1
state = json.loads((tmp_path / '.download-state.json').read_text())
assert state['state'] == 'failed' and state['verified_files'] == 1 and state['failed_files'] == 1
assert state['verified_bytes'] == len(b'official checkpoint')
assert 'VERIFIED' in capsys.readouterr().out
assert not (tmp_path / '.deployment-manifest.json').exists()
def test_zero_exit_with_wrong_canonical_bytes_never_becomes_ready(tmp_path, monkeypatch):
calls = []
def run(command, *, timeout):
calls.append(command)
destination(command).write_bytes(b'incorrect payload!!')
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
monkeypatch.setattr(module, 'retry_sleep', lambda _: None)
assert module.download_files([checkpoint('transformer/shard.safetensors')], tmp_path,
helper(), aria_binary='aria2c') == 1
assert len(calls) == 3
assert not (tmp_path / '.deployment-manifest.json').exists()
def test_complete_local_files_are_hashed_and_reused_without_network(tmp_path, monkeypatch):
path = tmp_path / 'transformer' / 'shard.safetensors'
path.parent.mkdir()
path.write_bytes(b'official checkpoint')
def unexpected(*args, **kwargs):
pytest.fail('A canonically verified file must not be downloaded again')
monkeypatch.setattr(module, 'run_aria', unexpected)
assert module.download_files([checkpoint('transformer/shard.safetensors')], tmp_path,
helper(), aria_binary='aria2c') == 0
def test_metadata_rejects_duplicate_paths_and_invalid_canonical_checksums():
item = checkpoint('transformer/shard.safetensors')
for files in ([item, item], [{**item, 'lfs': {'sha256': 'not-a-hash'}}]):
with pytest.raises(ValueError):
module.validate_metadata({'repo': module.H3_REPO, 'revision': module.H3_REVISION, 'files': files})
def test_metadata_stream_is_rate_limited_and_bounded():
class Clock:
now = 0
def sleep(self, seconds):
self.now += seconds
class Response:
def iter_content(self, chunk_size):
assert chunk_size <= 64 * 1024
yield b'a' * (64 * 1024)
yield b'b' * (64 * 1024)
clock = Clock()
data = module.read_limited_response(Response(), 1024 * 1024,
clock=lambda: clock.now, sleep=clock.sleep, maximum=128 * 1024)
assert data == b'a' * (64 * 1024) + b'b' * (64 * 1024)
assert clock.now >= .125
with pytest.raises(ValueError, match='large'):
module.read_limited_response(Response(), 1024 * 1024,
clock=lambda: clock.now, sleep=clock.sleep, maximum=64 * 1024)
def test_pending_download_emits_heartbeats_until_remaining_future_finishes(tmp_path, monkeypatch, capsys):
import concurrent.futures
import threading
import time
release, entered = threading.Event(), threading.Event()
def run(command, *, timeout):
entered.set()
assert release.wait(timeout=5)
destination(command).write_bytes(b'official checkpoint')
return types.SimpleNamespace(returncode=0)
monkeypatch.setattr(module, 'run_aria', run)
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(module.download_files, [checkpoint('transformer/shard.safetensors')],
tmp_path, helper(), aria_binary='aria2c', progress_seconds=.01)
try:
assert entered.wait(timeout=2)
first = json.loads((tmp_path / '.download-state.json').read_text())
deadline = time.monotonic() + 2
while time.monotonic() < deadline:
later = json.loads((tmp_path / '.download-state.json').read_text())
if later['updated_at'] > first['updated_at']:
break
time.sleep(.01)
assert later['updated_at'] > first['updated_at']
assert later['state'] == 'downloading' and later['verified_files'] == 0
finally:
release.set()
assert future.result(timeout=3) == 0
assert 'PROGRESS' in capsys.readouterr().out