"""原生MP4和PCM侧车必须经过正式下载、检查与发布,不用手工插入最终Assets。""" import asyncio from copy import deepcopy import hashlib import shutil from types import SimpleNamespace import wave import pytest from sqlalchemy import select from app.adapters.media import run_process from app.domain.video_generation import H3_NATIVE_AV_TP2_PROFILE, defaults from app.models import Asset, AssetReference, Execution from app.services.assets import validate_workflow_output from test_native_av_contract import certificate @pytest.fixture async def native_files(system, tmp_path): ffmpeg = shutil.which("ffmpeg") ffprobe = shutil.which("ffprobe") if not ffmpeg or not ffprobe: pytest.skip("real FFmpeg/ffprobe required") system.settings.ffmpeg_bin, system.settings.ffprobe_bin = ffmpeg, ffprobe frames, count = 158, 210400 video = tmp_path / "video_raw.mp4" await run_process( [ ffmpeg, "-v", "error", "-f", "lavfi", "-i", "color=c=blue:s=1344x768:r=24", "-f", "lavfi", "-i", "anullsrc=r=32000:cl=stereo", "-frames:v", str(frames), "-af", "atrim=end_sample=" + str(count), "-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "32000", "-ac", "2", str(video), ], timeout=30, ) audio = tmp_path / "audio_native.wav" write_wave(audio, count) p = defaults(H3_NATIVE_AV_TP2_PROFILE) | dict(num_frames=frames) meta = dict( final_output_indices=[0, 1], native_av=dict( sample_rate=32000, channels=2, audio_samples=count, audio_duration=count / 32000, video_duration=frames / 24, video_frames=frames, fps=24, start_sample=0, end_sample=count, av_duration_delta=count / 32000 - frames / 24, output_policy="full_native", audio_trimmed=False, audio_format="pcm_s16le", ), ) outputs = [dict(path="video_raw.mp4"), dict(path="audio_native.wav")] job = SimpleNamespace( task_type="video.generate", parameters=p, upstream_result=dict(outputs=outputs, metadata=meta), ) return SimpleNamespace( video=video, audio=audio, job=job, metadata=meta, outputs=outputs, count=count ) def write_wave(path, count, *, channels=2, rate=32000, width=2): with wave.open(str(path), "wb") as stream: stream.setnchannels(channels) stream.setframerate(rate) stream.setsampwidth(width) stream.writeframes(bytes(count * channels * width)) def legacy_tp2_metadata(files): from app.adapters.provider.native_av import TP2_RUNTIME_REVISION metadata = deepcopy(files.metadata) metadata.pop("final_output_indices") metadata.update( profile=H3_NATIVE_AV_TP2_PROFILE, engine="diffusers-modular-tp2", diffusers_source_revision=TP2_RUNTIME_REVISION, parallelism={"tensor_parallel_degree": 2}, parameters=deepcopy(files.job.parameters), ) return metadata async def test_completed_native_tp2_without_indices_keeps_full_evidence_and_frozen_result( system, native_files ): metadata = legacy_tp2_metadata(native_files) native_files.job.upstream_result["metadata"] = metadata original = deepcopy(native_files.job.upstream_result) await validate_workflow_output( native_files.job, native_files.video, system.settings, output_index=0 ) await validate_workflow_output( native_files.job, native_files.audio, system.settings, output_index=1 ) assert native_files.job.upstream_result == original @pytest.mark.parametrize("indices", [None, [], [0], [1], [1, 0], [0, True], [0, 1, 2]]) async def test_native_legacy_compat_never_overrides_explicit_bad_indices( system, native_files, indices ): metadata = legacy_tp2_metadata(native_files) metadata["final_output_indices"] = indices native_files.job.upstream_result["metadata"] = metadata with pytest.raises(ValueError, match="[Nn]ative|原生"): await validate_workflow_output( native_files.job, native_files.video, system.settings, output_index=0 ) @pytest.mark.parametrize("bad", ["mono", "missing_evidence", "wrong_runtime", "wrong_engine"]) async def test_native_legacy_compat_does_not_waive_audio_or_runtime_proof( system, native_files, bad ): metadata = legacy_tp2_metadata(native_files) if bad == "mono": write_wave(native_files.audio, native_files.count, channels=1) elif bad == "missing_evidence": metadata.pop("native_av") elif bad == "wrong_runtime": metadata["diffusers_source_revision"] = "0" * 40 else: metadata["engine"] = "unknown" native_files.job.upstream_result["metadata"] = metadata with pytest.raises(ValueError, match="[Nn]ative|原生"): await validate_workflow_output( native_files.job, native_files.audio, system.settings, output_index=1 ) async def test_native_wav_is_accepted_as_audio_not_as_upscaled_video(system, native_files): await validate_workflow_output( native_files.job, native_files.video, system.settings, output_index=0 ) await validate_workflow_output( native_files.job, native_files.audio, system.settings, output_index=1 ) @pytest.mark.parametrize( "bad", ["mono", "wrong_rate", "wrong_width", "short", "truncated", "metadata", "index"] ) async def test_native_sidecar_rejects_wrong_actual_audio_or_metadata(system, native_files, bad): f = native_files if bad == "mono": write_wave(f.audio, f.count, channels=1) elif bad == "wrong_rate": write_wave(f.audio, f.count, rate=48000) elif bad == "wrong_width": write_wave(f.audio, f.count, width=1) elif bad == "short": write_wave(f.audio, f.count - 6400) elif bad == "truncated": f.audio.write_bytes(f.audio.read_bytes()[:-80]) elif bad == "metadata": f.job.upstream_result["metadata"]["native_av"]["audio_samples"] -= 1 with pytest.raises(ValueError, match="[Nn]ative|原生"): await validate_workflow_output( f.job, f.audio, system.settings, output_index=2 if bad == "index" else 1 ) async def test_native_video_requires_an_embedded_stereo_audio_track(system, native_files, tmp_path): silent = tmp_path / "silent.mp4" await run_process( [ system.settings.ffmpeg_bin, "-v", "error", "-i", str(native_files.video), "-map", "0:v:0", "-c:v", "copy", "-an", str(silent), ] ) with pytest.raises(ValueError, match="[Nn]ative|原生"): await validate_workflow_output(native_files.job, silent, system.settings, output_index=0) @pytest.mark.parametrize("bad", ["profile", "requested_frames", "reported_parameters"]) async def test_native_reported_generation_contract_cannot_differ_from_job( system, native_files, bad ): metadata = native_files.job.upstream_result["metadata"] if bad == "profile": metadata["profile"] = "minimax-h3-fl2va-bf16-v2" elif bad == "requested_frames": metadata["requested_frames"] = 141 else: metadata["parameters"] = {**native_files.job.parameters, "seed": 999} with pytest.raises(ValueError, match="[Nn]ative|原生"): await validate_workflow_output( native_files.job, native_files.video, system.settings, output_index=0 ) @pytest.mark.parametrize("bad", ["missing_wav", "dropped_wav", "extra_index"]) async def test_native_pair_is_required_even_for_standalone_job(system, native_files, bad): f = native_files if bad == "missing_wav": f.job.upstream_result["outputs"] = f.outputs[:1] elif bad == "dropped_wav": f.job.upstream_result["metadata"]["final_output_indices"] = [0] else: f.job.upstream_result["outputs"].append(dict(path="extra.wav")) with pytest.raises(ValueError, match="[Nn]ative|原生"): await validate_workflow_output(f.job, f.video, system.settings, output_index=0) @pytest.mark.parametrize("candidate_key", [False, True]) @pytest.mark.parametrize("legacy_no_indices", [False, True]) async def test_http_native_job_downloads_and_publishes_both_assets_through_real_coordinator( system, native_files, png_bytes, candidate_key, legacy_no_indices ): f = native_files if legacy_no_indices: f.metadata = legacy_tp2_metadata(f) system.settings.native_dialogue_tp2_enabled = True system.settings.inference_base_url = "http://fake-native" async def caps(): return dict(video_generation=dict(native_av_tp2=certificate(H3_NATIVE_AV_TP2_PROFILE))) system.provider.upstream_capabilities = caps frame = await system.client.post( "/api/assets", files={"file": ("frame.png", png_bytes, "image/png")} ) assert frame.status_code == 201, frame.text response = await system.client.post( "/api/jobs", json=dict( task_type="video.generate", input=dict(prompt="native speaking", first_frame_asset_id=frame.json()["id"]), parameters=f.job.parameters, ), headers={ "Idempotency-Key": "candidate:native-publication" if candidate_key else "native-publication" }, ) assert response.status_code == 202, response.text jid = response.json()["jobs"][0]["id"] coordinator = system.app.state.coordinator async with asyncio.timeout(12): while True: await coordinator.run_once(force=True) current = (await system.client.get("/api/jobs/" + jid)).json() if current["upstream_id"]: break await asyncio.sleep(0.01) upstream = current["upstream_id"] downloads = [] async def download(remote, index, target): assert remote == upstream downloads.append(index) target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(f.video if index == 0 else f.audio, target) system.provider.download = download system.provider.remote[upstream] = dict( id=upstream, state="running", stage="executing", attempt_count=1, execution_id=upstream + ":1", runner_pid=77, ) await coordinator.run_once(force=True) outputs = [ dict(path=path.name, sha256=hashlib.sha256(path.read_bytes()).hexdigest()) for path in (f.video, f.audio) ] system.provider.remote[upstream] = { **system.provider.remote[upstream], "state": "succeeded", "runner_pid": None, "result": dict(outputs=outputs, metadata=deepcopy(f.metadata)), } async with asyncio.timeout(20): while True: await coordinator.run_once(force=True) current = (await system.client.get("/api/jobs/" + jid)).json() if current["state"] == "succeeded" or current["sync_warning"]: break await asyncio.sleep(0.01) assert current["state"] == "succeeded", current assert downloads == [0, 1] assert [a["kind"] for a in current["result_assets"]] == ["video", "audio"] async with system.app.state.db.session() as session: assets = ( await session.scalars( select(Asset).where(Asset.source_job_id == jid).order_by(Asset.source_output_index) ) ).all() assert [(a.kind, a.source_output_index, a.ready) for a in assets] == [ ("video", 0, True), ("audio", 1, True), ] sidecar = assets[1] assert ( system.settings.asset_root / sidecar.storage_key ).read_bytes() == f.audio.read_bytes() refs = ( await session.scalars( select(AssetReference).where( AssetReference.asset_id.in_([a.id for a in assets]), AssetReference.ref_kind == "execution", ) ) ).all() assert len(refs) == 2 assert len({r.ref_id for r in refs}) == 1 assert (await session.get(Execution, refs[0].ref_id)).state == "results_ready" served = await system.client.get("/api/assets/" + sidecar.id + "/content") assert served.status_code == 200 and served.content == f.audio.read_bytes() await coordinator._collect_gpu(await coordinator._job(jid)) assert downloads == [0, 1] async with system.app.state.db.session() as session: assets = (await session.scalars(select(Asset).where(Asset.source_job_id == jid))).all() assert len(assets) == 2 and all(a.ready for a in assets)