cmvr-visual/inference/tests/test_h3_tp2_state.py

193 lines
9.4 KiB
Python
Raw Normal View History

"""阶段文件拒绝对象、跨作业复用、篡改与目录逃逸;CPU 上也可验证。"""
import hashlib
import importlib
import importlib.util
import json
import sys
from types import SimpleNamespace
import pytest
def codec():
assert importlib.util.find_spec('llm_services.h3_tp2_state') is not None, 'TP2 state codec is missing'
return importlib.import_module('llm_services.h3_tp2_state')
def test_state_round_trip_keeps_tuple_and_scalar_types(tmp_path, monkeypatch):
monkeypatch.delenv('LLM_TP2_REQUEST_SHA256', raising=False)
monkeypatch.delenv('LLM_TP2_GROUP_TOKEN', raising=False)
state = {'values': {'nested': [(7, None, True, 1.25)], 'word': '首帧'}, 'kwargs_mapping': {}}
codec().save_state(tmp_path, 'prepared', state)
assert codec().load_state(tmp_path, 'prepared') == state
@pytest.mark.parametrize('name', ['../prepared', '/prepared', 'a/b', 'a\\b', '', '.hidden'])
def test_state_names_cannot_escape_directory(tmp_path, name):
with pytest.raises(ValueError, match='state|name'):
codec().save_state(tmp_path, name, {})
@pytest.mark.parametrize('value', [{'object': object()}, {'number': float('nan')}, {1: 'not a string key'}])
def test_state_rejects_unsafe_values_before_writing(tmp_path, value):
with pytest.raises(ValueError, match='Unsupported|finite|key'):
codec().save_state(tmp_path, 'prepared', value)
assert list(tmp_path.iterdir()) == []
def test_state_is_bound_to_request_and_group(tmp_path, monkeypatch):
monkeypatch.setenv('LLM_TP2_REQUEST_SHA256', 'a' * 64)
monkeypatch.setenv('LLM_TP2_GROUP_TOKEN', '1' * 32)
codec().save_state(tmp_path, 'prepared', {'values': {}, 'kwargs_mapping': {}})
monkeypatch.setenv('LLM_TP2_REQUEST_SHA256', 'b' * 64)
with pytest.raises(ValueError, match='binding|request'):
codec().load_state(tmp_path, 'prepared')
def test_state_refuses_existing_output(tmp_path):
codec().save_state(tmp_path, 'prepared', {'values': {}, 'kwargs_mapping': {}})
with pytest.raises(ValueError, match='exists|overwrite'):
codec().save_state(tmp_path, 'prepared', {'values': {'changed': True}})
def test_state_rejects_manifest_with_unexpected_fields(tmp_path):
codec().save_state(tmp_path, 'prepared', {'values': {}, 'kwargs_mapping': {}})
path = tmp_path / 'prepared.json'
data = json.loads(path.read_text())
data['pickle_path'] = '../../secret'
path.write_text(json.dumps(data))
with pytest.raises(ValueError, match='manifest|schema'):
codec().load_state(tmp_path, 'prepared')
def test_state_rejects_non_cpu_tensor_storage_tampering(tmp_path):
torch = pytest.importorskip('torch')
pytest.importorskip('safetensors')
codec().save_state(tmp_path, 'prepared', {'values': {'x': torch.tensor([1., 2.])}})
path = tmp_path / 'prepared.safetensors'
content = path.read_bytes()
path.write_bytes(content[:-1] + bytes([content[-1] ^ 1]))
with pytest.raises(ValueError, match='integrity|hash'):
codec().load_state(tmp_path, 'prepared')
def test_phase_state_restoration_preserves_layout_category():
assert importlib.util.find_spec('llm_services.h3_tp2_phase') is not None, 'TP2 phase is missing'
phase = importlib.import_module('llm_services.h3_tp2_phase')
class State:
def __init__(self):
self.values, self.kwargs_mapping = {}, {}
def set(self, name, value, kwargs_type=None):
self.values[name] = value
if kwargs_type:
self.kwargs_mapping.setdefault(kwargs_type, []).append(name)
restored = phase.restore_pipeline_state(
{'values': {'position_ids': [1], 'latents': [2]},
'kwargs_mapping': {'denoiser_input_fields': ['position_ids']}}, State)
assert restored.values == {'position_ids': [1], 'latents': [2]}
assert restored.kwargs_mapping == {'denoiser_input_fields': ['position_ids']}
with pytest.raises(ValueError, match='mapping|missing'):
phase.restore_pipeline_state({'values': {}, 'kwargs_mapping': {'x': ['absent']}}, State)
def test_phase_publishes_typed_preemption_without_starting_cuda(tmp_path, monkeypatch):
from llm_services import h3_tp2_phase as phase
from llm_services.adapters import GpuPreempted
request = {'task_type': 'video.generate', 'input': {'prompt': 'test', 'image_path': '/workspace/anchor.png'},
'output_dir': str(tmp_path), 'parameters': {'profile': phase.PROFILE, 'upscale': False,
'fps': 24, 'width': 1344, 'height': 768, 'num_frames': 145, 'num_inference_steps': 2, 'seed': 7}}
request_file = tmp_path / 'request.json'
request_file.write_text(json.dumps(request))
monkeypatch.setenv('LLM_TP2_REQUEST_SHA256', hashlib.sha256(json.dumps(request,
sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False).encode()).hexdigest())
monkeypatch.setattr(phase, '_members', lambda _: [{'uuid': 'primary'}, {'uuid': 'second'}])
monkeypatch.setattr(phase, '_identity', lambda *args: {'pid': 123})
def preempt(*args):
raise GpuPreempted('External user on rank one')
monkeypatch.setattr(phase, '_configure', preempt)
assert phase.main(['--phase', 'prepare', '--request', str(request_file), '--directory', str(tmp_path)]) == 1
typed = json.loads((tmp_path / 'phase-prepare-error-0.json').read_text())
assert typed == {'type': 'GpuPreempted', 'message': 'External user on rank one'}
assert json.loads((tmp_path / 'phase-prepare.json').read_text())['completed'] is False
@pytest.fixture
def runtime_install(tmp_path, monkeypatch):
"""替代包导入/metadata读取,不运行模型;真实文件用于核对环境边界。"""
from llm_services import h3_tp2_phase as phase
prefix = tmp_path / 'isolated'
source = prefix / 'lib' / 'site-packages' / 'diffusers' / '__init__.py'
source.parent.mkdir(parents=True)
source.write_text('# installed package fixture\n')
data = {'direct_url': None}
monkeypatch.setattr(sys, 'prefix', str(prefix))
monkeypatch.setitem(sys.modules, 'diffusers', SimpleNamespace(__version__='0.43.0', __file__=str(source)))
monkeypatch.setattr(phase.importlib.metadata, 'distribution', lambda _: SimpleNamespace(
read_text=lambda name: json.dumps(data['direct_url']) if data['direct_url'] is not None else None,
locate_file=lambda name: source))
lock = {'diffusers_source_revision': '423ab90580b2847998591669b8326f47b6d14d8b',
'archive_sha256': 'c5ae262ee572007f4fa7ae0ecd53692204c3940cc0d0ff4a72b9db03f7352340',
'new_runtime': {'diffusers': '0.43.0', 'source': str(source)}}
return phase, prefix, source, data, lock
def test_runtime_version_alone_is_not_source_revision_evidence(runtime_install):
phase, *_ = runtime_install
with pytest.raises(RuntimeError, match='provenance|lock|source revision'):
phase._runtime()
def test_runtime_accepts_verified_archive_lock(runtime_install):
phase, prefix, _, _, lock = runtime_install
(prefix / 'cmvr-runtime-lock.json').write_text(json.dumps(lock))
result = phase._runtime()
assert result['installed_source_revision'] == '423ab90580b2847998591669b8326f47b6d14d8b'
assert result['provenance_type'] == 'archive_lock'
@pytest.mark.parametrize('field,value', [('diffusers_source_revision', '0' * 40), ('archive_sha256', '0' * 64)])
def test_runtime_rejects_wrong_archive_identity(runtime_install, field, value):
phase, prefix, _, _, lock = runtime_install
lock[field] = value
(prefix / 'cmvr-runtime-lock.json').write_text(json.dumps(lock))
with pytest.raises(RuntimeError, match='lock|revision|hash'):
phase._runtime()
def test_runtime_archive_source_must_match_imported_package(runtime_install):
phase, prefix, _, _, lock = runtime_install
lock['new_runtime']['source'] = str(prefix / 'different' / '__init__.py')
(prefix / 'cmvr-runtime-lock.json').write_text(json.dumps(lock))
with pytest.raises(RuntimeError, match='source|lock'):
phase._runtime()
def test_runtime_accepts_official_git_full_commit(runtime_install):
phase, _, _, data, _ = runtime_install
data['direct_url'] = {'url': 'https://github.com/huggingface/diffusers.git',
'vcs_info': {'vcs': 'git', 'commit_id': '423ab90580b2847998591669b8326f47b6d14d8b'}}
result = phase._runtime()
assert result['installed_source_revision'] == '423ab90580b2847998591669b8326f47b6d14d8b'
assert result['provenance_type'] == 'git_direct_url'
@pytest.mark.parametrize('commit', ['423ab905', '0' * 40])
def test_runtime_rejects_unqualified_git_commit(runtime_install, commit):
phase, _, _, data, _ = runtime_install
data['direct_url'] = {'url': 'https://github.com/huggingface/diffusers.git',
'vcs_info': {'vcs': 'git', 'commit_id': commit}}
with pytest.raises(RuntimeError, match='revision|commit'):
phase._runtime()
def test_runtime_rejects_import_from_outside_current_environment(runtime_install, tmp_path, monkeypatch):
phase, _, _, data, _ = runtime_install
source = tmp_path / 'shared' / '__init__.py'
source.parent.mkdir()
source.write_text('# foreign runtime\n')
monkeypatch.setitem(sys.modules, 'diffusers', SimpleNamespace(__version__='0.43.0', __file__=str(source)))
data['direct_url'] = {'url': 'https://github.com/huggingface/diffusers.git',
'vcs_info': {'vcs': 'git', 'commit_id': '423ab90580b2847998591669b8326f47b6d14d8b'}}
with pytest.raises(RuntimeError, match='environment|prefix|source'):
phase._runtime()