"""H3接入必须保持旧请求语义和真实视频帧数。""" from dataclasses import replace import json from pathlib import Path import sys import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from llm_services import runner from llm_services.store import Settings, Store, validate_request as validate_submission_request from llm_services.video_profiles import H3_PROFILE, LEGACY_PROFILE, native_frames, validate_submission @pytest.mark.parametrize(('requested', 'native'), [(25, 124), (121, 124), (193, 209), (337, 345)]) def test_h3_native_frames_cover_requested_without_freezing(requested, native): assert native_frames(requested) == native assert native >= requested and native % 17 == 5 def test_h3_rejects_fifteen_seconds_and_unknown_profile(tmp_path): with pytest.raises(ValueError, match='14|337'): native_frames(361) payload = {'task_type': 'video.generate', 'input': {'prompt': 'Bird flaps its wings'}, 'parameters': {'profile': 'unknown'}, 'output_dir': str(tmp_path / 'outputs' / 'job')} with pytest.raises(ValueError, match='profile'): runner.validate_request(payload, workspace=tmp_path) def test_h3_parameters_and_wan_legacy_remain_distinct(tmp_path): payload = {'task_type': 'video.generate', 'input': {'prompt': 'Bird flaps its wings'}, 'parameters': {'profile': H3_PROFILE}, 'output_dir': str(tmp_path / 'outputs' / 'job')} request = runner.validate_request(payload, workspace=tmp_path) assert request['parameters']['width'] == 1344 assert request['parameters']['height'] == 768 assert request['parameters']['num_frames'] == 121 assert 'guidance_scale' not in request['parameters'] assert not request['parameters']['upscale'] payload['parameters'] = {} old = runner.validate_request(payload, workspace=tmp_path)['parameters'] assert old['width'] == 1280 and old['guidance_scale'] == 5 assert 'profile' not in old # 旧原包保持旧语义。 payload['parameters'] = {'profile': LEGACY_PROFILE} assert runner.validate_request(payload, workspace=tmp_path)['parameters']['profile'] == LEGACY_PROFILE @pytest.mark.parametrize('parameters,inputs', [ ({'guidance_scale': 5}, {}), ({}, {'negative_prompt': 'blur'}), ({'width': 1280, 'height': 704}, {}), ({'width': 1344.0, 'height': 768.0}, {}), ({'fps': 30}, {}), ]) def test_h3_does_not_silently_ignore_unsupported_parameters(tmp_path, parameters, inputs): with pytest.raises(ValueError): runner.validate_request({'task_type': 'video.generate', 'input': {'prompt': 'Bird moves', **inputs}, 'parameters': {'profile': H3_PROFILE, **parameters}, 'output_dir': str(tmp_path / 'outputs' / 'job')}, workspace=tmp_path) def test_h3_submission_requires_certification_but_old_jobs_do_not(tmp_path): settings = Settings(tmp_path, tmp_path) with pytest.raises(ValueError, match='certified|enabled'): validate_submission(settings, {'profile': H3_PROFILE}) validate_submission(settings, {}) validate_submission(replace(settings, video_generation_poc_enabled=True), {'profile': H3_PROFILE}) def test_submission_validation_keeps_legacy_raw_body_for_idempotency(tmp_path): inputs, params = {'prompt': 'A bird moves'}, {'num_frames': 121} assert validate_submission_request('video.generate', inputs, params, tmp_path) == (inputs, params) def test_h3_output_checks_native_count_before_real_frame_crop(): from llm_services.h3 import select_video_frames frames = list(range(124)) assert select_video_frames(frames, requested=121, native=124) == list(range(121)) with pytest.raises(RuntimeError, match='frame'): select_video_frames(frames[:120], requested=121, native=124) def test_h3_memory_reservation_cannot_keep_wan_estimate(tmp_path): settings = Settings(tmp_path, tmp_path, video_generation_enabled=True) assert settings.memory_estimates_gib['video.generate'] >= 288 def test_http_legacy_idempotency_survives_enabling_h3(tmp_path): from fastapi.testclient import TestClient from llm_services.api import create_app settings = Settings(tmp_path / 'app', tmp_path) settings.key_file.parent.mkdir(parents=True) settings.key_file.write_text('fl2va-contract-test-key-0123456789') headers = {'Authorization': 'Bearer fl2va-contract-test-key-0123456789', 'Idempotency-Key': 'legacy-before-h3'} old = {'task_type': 'video.generate', 'input': {'prompt': 'A bird flaps its wings'}, 'parameters': {}} with TestClient(create_app(settings)) as client: original = client.post('/jobs', json=old, headers=headers) assert original.status_code == 202 h3 = {**old, 'parameters': {'profile': H3_PROFILE}} assert client.post('/jobs', json=h3, headers={**headers, 'Idempotency-Key': 'new-h3'}).status_code == 422 settings.video_generation_enabled = True replay = client.post('/jobs', json=old, headers=headers) assert replay.status_code == 202 and replay.json()['id'] == original.json()['id'] assert replay.json()['parameters'] == {} assert client.post('/jobs', json=h3, headers=headers).status_code == 409 created = client.post('/jobs', json=h3, headers={**headers, 'Idempotency-Key': 'new-h3'}) assert created.status_code == 202 assert created.json()['parameters'] == {'profile': H3_PROFILE} assert client.get('/capabilities', headers=headers).json()['video_generation']['available'] is True def test_h3_stage_never_calls_wan_engine(tmp_path, monkeypatch): from llm_services import adapters, h3 expected = ([tmp_path / 'video_raw.mp4'], {'profile': H3_PROFILE}) monkeypatch.setattr(h3, 'run', lambda request: expected) monkeypatch.setattr(adapters, '_omni_generate', lambda request: pytest.fail('H3 called Wan')) request = runner.validate_request({'task_type': 'video.generate', 'input': {'prompt': 'A bird moves'}, 'parameters': {'profile': H3_PROFILE}, 'output_dir': str(tmp_path / 'outputs' / 'job')}, workspace=tmp_path) assert adapters.run_stage(request, 'model') == expected def test_stage_preemption_is_not_lost_between_nested_runners(tmp_path, monkeypatch): from llm_services import adapters request = runner.validate_request({'task_type': 'video.generate', 'input': {'prompt': 'A bird moves'}, 'parameters': {'profile': H3_PROFILE}, 'output_dir': str(tmp_path / 'outputs' / 'job')}, workspace=tmp_path) monkeypatch.setattr(adapters, 'budgeted_child_environment', lambda path: {}) monkeypatch.setattr(adapters, 'admit_gpu', lambda: None) def preempted(command, env, log, timeout): result = Path(command[command.index('--result') + 1]) result.write_text(json.dumps({'outputs': [], 'error': {'type': 'GpuPreempted', 'message': 'external workload'}, 'metadata': {'completed': False}})) raise runner.StageProcessFailed('Model stage exited with code 1') monkeypatch.setattr(runner, '_run_child', preempted) with pytest.raises(adapters.GpuPreempted, match='external workload'): runner.execute(request) def test_stage_cleanup_failure_is_never_masked_as_preemption(tmp_path, monkeypatch): from llm_services import adapters request = runner.validate_request({'task_type': 'video.generate', 'input': {'prompt': 'A bird moves'}, 'parameters': {'profile': H3_PROFILE}, 'output_dir': str(tmp_path / 'outputs' / 'job')}, workspace=tmp_path) monkeypatch.setattr(adapters, 'budgeted_child_environment', lambda path: {}) monkeypatch.setattr(adapters, 'admit_gpu', lambda: None) def cleanup_failed(command, env, log, timeout): Path(command[command.index('--result') + 1]).write_text(json.dumps({ 'outputs': [], 'error': {'type': 'GpuPreempted', 'message': 'external workload'}, 'metadata': {'completed': False}})) raise RuntimeError('Model child processes could not be released') monkeypatch.setattr(runner, '_run_child', cleanup_failed) with pytest.raises(RuntimeError, match='could not be released') as caught: runner.execute(request) assert not isinstance(caught.value, adapters.GpuPreempted) def _make_h3_verified_checkpoint(tmp_path, *, official=True): from llm_services import h3 paths = ['model_index.json', 'modular_model_index.json', 'transformer/config.json', 'text_encoder/config.json', 'vae/config.json', 'audio_vae/config.json', 'audio_vae/diffusion_pytorch_model.safetensors', 'scheduler/scheduler_config.json', 'audio_scheduler/scheduler_config.json', 'tokenizer/tokenizer.json', 'tokenizer/tokenizer_config.json', 'processor/preprocessor_config.json'] for component, index_name in ( ('transformer', 'diffusion_pytorch_model.safetensors.index.json'), ('text_encoder', 'model.safetensors.index.json'), ('vae', 'diffusion_pytorch_model.safetensors.index.json'), ): paths.extend([f'{component}/shard.safetensors', f'{component}/{index_name}']) index = tmp_path / component / index_name index.parent.mkdir(parents=True, exist_ok=True) index.write_text(json.dumps({'weight_map': {'weight': 'shard.safetensors'}}), encoding='utf-8') for relative in paths: path = tmp_path / relative path.parent.mkdir(parents=True, exist_ok=True) if not path.exists(): path.write_bytes(b'{}') files = [] for relative in paths: size = (tmp_path / relative).stat().st_size files.append({'rfilename': relative, 'size': size, 'blobId': 'verified-git-object'} if official else {'path': relative, 'bytes': size}) manifest = {'repo': h3.MODEL_REPO, 'revision': h3.MODEL_REVISION, 'verified_at': 1, 'files': files} (tmp_path / '.deployment-manifest.json').write_text(json.dumps(manifest), encoding='utf-8') return manifest @pytest.mark.parametrize('official', [True, False]) def test_h3_manifest_supports_verified_official_and_legacy_file_formats(tmp_path, monkeypatch, official): from llm_services import h3, adapters _make_h3_verified_checkpoint(tmp_path, official=official) monkeypatch.setattr(adapters, '_require_model', lambda _: str(tmp_path)) assert h3._verified_model() == str(tmp_path) (tmp_path / 'transformer' / 'shard.safetensors').unlink() with pytest.raises(RuntimeError, match='missing|changed'): h3._verified_model() def test_h3_manifest_rejects_wrong_revision_and_unverified_files(tmp_path, monkeypatch): from llm_services import h3, adapters manifest = _make_h3_verified_checkpoint(tmp_path) monkeypatch.setattr(adapters, '_require_model', lambda _: str(tmp_path)) marker = tmp_path / '.deployment-manifest.json' manifest['revision'] = 'other-checkpoint' marker.write_text(json.dumps(manifest), encoding='utf-8') with pytest.raises(RuntimeError, match='repo/revision'): h3._verified_model() manifest['revision'] = h3.MODEL_REVISION manifest.pop('verified_at') marker.write_text(json.dumps(manifest), encoding='utf-8') with pytest.raises(RuntimeError, match='verification'): h3._verified_model() @pytest.mark.parametrize(('offload_key', 'expected'), [ ('use_stream', True), ('low_cpu_mem_usage', True), ('record_stream', False), ]) def test_h3_runtime_loads_local_components_and_encodes_only_real_silent_frames( tmp_path, monkeypatch, offload_key, expected): import contextlib import types from llm_services import adapters, h3 calls = [] class Frames: def __init__(self, count): self.shape, self.dtype = (count, 768, 1344, 3), 'float' def __len__(self): return self.shape[0] def __getitem__(self, item): return Frames(item.stop) def min(self): return 0.0 def max(self): return 1.0 class Component: model = object() def requires_grad_(self, value): assert value is False def to(self, device): calls.append(('resident', device)) def enable_group_offload(self, **kwargs): calls.append(('dit_offload', kwargs)) class Pipeline: def __init__(self): for name in ('transformer', 'text_encoder', 'vae', 'audio_vae', 'tokenizer', 'processor', 'scheduler', 'audio_scheduler'): setattr(self, name, Component()) @classmethod def from_pretrained(cls, path, **kwargs): calls.append(('from', path, kwargs)) return cls() def load_components(self, **kwargs): calls.append(('load', kwargs)) def __call__(self, **kwargs): calls.append(('generate', kwargs)) return {'videos': [Frames(124)]} class Generator: def __init__(self, device): assert device == 'cpu' def manual_seed(self, seed): assert seed == 42 return self numpy = types.ModuleType('numpy') numpy.floating, numpy.asarray = 'floating', lambda value: value numpy.issubdtype = lambda *_: True numpy.isfinite = lambda _: types.SimpleNamespace(all=lambda: True) torch = types.ModuleType('torch') torch.bfloat16, torch.device, torch.Generator = 'bf16', lambda device: device, Generator torch.inference_mode = contextlib.nullcontext torch.cuda = types.SimpleNamespace(empty_cache=lambda: None) diffusers = types.ModuleType('diffusers') diffusers.__path__, diffusers.__version__, diffusers.ModularPipeline = [], '0.40.0.dev0', Pipeline hooks = types.ModuleType('diffusers.hooks') hooks.apply_group_offloading = lambda *_, **kwargs: calls.append(('text_offload', kwargs)) utils = types.ModuleType('diffusers.utils') utils.__path__ = [] export = types.ModuleType('diffusers.utils.export_utils') export.encode_video = lambda frames, **kwargs: calls.append(('encode', len(frames), kwargs)) pil = types.ModuleType('PIL') pil.Image = object() for name, module in {'numpy': numpy, 'torch': torch, 'diffusers': diffusers, 'diffusers.hooks': hooks, 'diffusers.utils': utils, 'diffusers.utils.export_utils': export, 'PIL': pil}.items(): monkeypatch.setitem(sys.modules, name, module) monkeypatch.setattr(h3, '_verified_model', lambda: '/local/model') monkeypatch.setattr(adapters, 'admit_gpu', lambda: calls.append(('admit',))) paths, metadata = h3.run({'task_type': 'video.generate', 'input': {'prompt': 'Bird moves'}, 'output_dir': str(tmp_path), 'parameters': {'profile': H3_PROFILE, 'num_frames': 121, 'fps': 24, 'width': 1344, 'height': 768, 'num_inference_steps': 50, 'seed': 42}}) assert [path.name for path in paths] == ['video_raw.mp4'] load = next(call[1] for call in calls if call[0] == 'load') assert load['pretrained_model_name_or_path'] == '/local/model' and load['local_files_only'] assert load['workflow'] == 'fl2va' and load['dtype'] == 'bf16' dit_calls = [call[1] for call in calls if call[0] == 'dit_offload'] text_calls = [call[1] for call in calls if call[0] == 'text_offload'] assert len(dit_calls) == len(text_calls) == 1 dit, text = dit_calls[0], text_calls[0] assert dit['offload_type'] == 'block_level' and dit['num_blocks_per_group'] == 1 assert dit[offload_key] is expected assert text['offload_type'] == 'leaf_level' and text['use_stream'] is False assert text.get('low_cpu_mem_usage', False) is False assert text.get('record_stream', False) is False offload = metadata['cpu_offload'] assert offload['dit'] == 'block_level' and offload['text_encoder'] == 'leaf_level' assert offload['num_blocks_per_group'] == 1 and offload['use_stream'] is True assert offload['dit_options'][offload_key] is expected assert offload['text_encoder_options'] == { 'use_stream': False, 'low_cpu_mem_usage': False, 'record_stream': False, } generated = next(call[1] for call in calls if call[0] == 'generate') assert generated['num_frames'] == 124 and 'guidance_scale' not in generated encoded = next(call for call in calls if call[0] == 'encode') assert encoded[1] == 121 and encoded[2]['fps'] == 24 and 'audio' not in encoded[2] assert metadata['native_frames'] == 124 and metadata['requested_frames'] == 121 assert max(i for i, call in enumerate(calls) if call[0] == 'admit') < min( i for i, call in enumerate(calls) if call[0] == 'resident') def test_v2_preserves_native_tail_and_requires_separate_certificate(tmp_path): from llm_services.h3 import select_video_frames from llm_services.video_profiles import H3_V2_PROFILE params = {"profile": H3_V2_PROFILE, "conditioning_mode": "first_last_frame", "num_frames": 345} settings = Settings(tmp_path, tmp_path, video_generation_enabled=True) with pytest.raises(ValueError, match="certified"): validate_submission(settings, params) validate_submission(replace(settings, video_generation_v2_enabled=True), params) first, last = tmp_path / "first.png", tmp_path / "last.png" first.touch() last.touch() request = runner.validate_request({ "task_type": "video.generate", "parameters": params, "input": {"prompt": "shot", "image_path": str(first), "last_image_path": str(last)}, "output_dir": str(tmp_path / "outputs" / "job") }, workspace=tmp_path) count = request["parameters"]["num_frames"] assert select_video_frames(range(count), count, count)[-1] == 344 assert request["input"]["last_image_path"] == str(last) def test_v2_capability_declares_complete_adapter_contract(tmp_path): from llm_services.video_profiles import capabilities, H3_V2_PROFILE, H3_REVISION assert capabilities(Settings(tmp_path, tmp_path))["v2"] == { "available": False, "profile": H3_V2_PROFILE, "revision": H3_REVISION, "adapter_contract_version": "h3-fl2va-v2", "input_modes": ["first_frame", "first_last_frame"], "output_policy": "full_native", "native_frame_counts": list(range(124, 346, 17)), "fps": 24, "canvases": [[1344, 768], [768, 1344]], }