684 lines
29 KiB
Python
684 lines
29 KiB
Python
"""原生对白通过真实 ASGI、SQLite 与临时媒体验证,无真实模型。"""
|
||
|
||
from copy import deepcopy
|
||
import hashlib
|
||
import io
|
||
import json
|
||
import math
|
||
import subprocess
|
||
import wave
|
||
from pathlib import Path
|
||
from uuid import uuid4
|
||
|
||
from PIL import Image
|
||
import pytest
|
||
|
||
from sqlalchemy import select
|
||
|
||
from app.models import WorkflowRun, WorkflowStep, WorkflowDraft, Asset, AssetReference, Job
|
||
from app.domain.native_av import normalize_native_text
|
||
from test_dialogue_engine import story
|
||
from test_native_av_contract import certificate, alignment_certificate
|
||
|
||
|
||
async def native_story(system, *, multiple=False, reference=False):
|
||
created = await system.client.post("/api/stories", json=dict(name="原生对白", spec=story()))
|
||
assert created.status_code == 201, created.text
|
||
did = created.json()["id"]
|
||
enabled = await system.client.post(
|
||
f"/api/editors/{did}/dialogue/enable",
|
||
json=dict(expected_version=created.json()["version"]),
|
||
headers={"Idempotency-Key": "native-enable"},
|
||
)
|
||
assert enabled.status_code == 200, enabled.text
|
||
m = deepcopy(enabled.json()["manifest"])
|
||
assert m["spec"]["dialogue"]["generation"] == "native_av"
|
||
d = m["spec"]["dialogue"]
|
||
d["utterances"] = [dict(id="4" * 32, speaker_id=d["speakers"][0]["id"], text="你好。")]
|
||
d["sequences"][0]["utterance_ids"] = ["4" * 32]
|
||
if multiple:
|
||
second = deepcopy(m["spec"]["shots"][0])
|
||
second["id"] = "5" * 32
|
||
second["cast"][0]["id"] = "6" * 32
|
||
second["performance"]["native_utterance_ids"] = []
|
||
m["spec"]["shots"][0]["performance"]["native_utterance_ids"] = ["4" * 32]
|
||
m["spec"]["shots"].append(second)
|
||
m["shot_ids"].append(second["id"])
|
||
d["sequences"][0]["shot_ids"] = m["shot_ids"].copy()
|
||
if reference:
|
||
picture = io.BytesIO()
|
||
Image.new("RGB", (128, 128), "red").save(picture, format="PNG")
|
||
from test_dialogue_workflow import asset
|
||
|
||
async with system.app.state.db.session() as s:
|
||
owner = (await s.get(WorkflowDraft, did)).owner_id
|
||
ref = await asset(s, system, owner, "image", picture.getvalue())
|
||
m["spec"]["entities"][0]["reference_asset_ids"] = [ref.id]
|
||
await s.commit()
|
||
m["captions"] = dict(mode="script", cues=[])
|
||
saved = await system.client.post(
|
||
f"/api/editors/{did}/save",
|
||
json=dict(expected_version=enabled.json()["version"], manifest=m),
|
||
headers={"Idempotency-Key": "native-save"},
|
||
)
|
||
assert saved.status_code == 200, saved.text
|
||
return did, saved.json()
|
||
|
||
|
||
def capabilities(system):
|
||
system.settings.native_dialogue_enabled = True
|
||
system.settings.dialogue_quality_certified = True
|
||
system.settings.inference_base_url = "http://fake-inference"
|
||
system.settings.reference_generation_enabled = True
|
||
|
||
async def upstream():
|
||
return dict(
|
||
video_generation=dict(native_av=certificate()),
|
||
dialogue=dict(speech_inspect=dict(native_alignment=alignment_certificate())),
|
||
)
|
||
|
||
system.provider.upstream_capabilities = upstream
|
||
|
||
|
||
async def test_native_plan_has_no_tts_or_muse_and_missing_capability_is_closed(system):
|
||
did, draft = await native_story(system)
|
||
body = dict(expected_version=draft["version"], output_goal="film")
|
||
p = await system.client.post(f"/api/editors/{did}/plan", json=body)
|
||
assert p.status_code == 200, p.text
|
||
kinds = {r["kind"] for r in p.json()["steps"]}
|
||
assert not kinds.intersection(
|
||
{"audio.speech", "audio.dialogue.speech", "video.lipsync", "video.dialogue.analyze"}
|
||
)
|
||
assert {
|
||
"video.generate",
|
||
"audio.dialogue.extract",
|
||
"audio.dialogue.inspect",
|
||
"dialogue.accepted",
|
||
"video.compose",
|
||
} <= kinds
|
||
assert p.json()["issues"]
|
||
launched = await system.client.post(
|
||
f"/api/editors/{did}/runs",
|
||
json={**body, "expected_plan_hash": p.json()["plan_hash"]},
|
||
headers={"Idempotency-Key": "closed"},
|
||
)
|
||
assert launched.status_code == 422, launched.text
|
||
async with system.app.state.db.session() as s:
|
||
assert not (await s.scalars(select(WorkflowRun))).all()
|
||
|
||
|
||
async def test_native_first_frame_target_ignores_unselected_audio_capabilities(system, tmp_path):
|
||
did, draft = await native_story(system)
|
||
p = await system.client.post(
|
||
f"/api/editors/{did}/plan",
|
||
json=dict(
|
||
expected_version=draft["version"], output_goal="media", targets=["frame:" + "2" * 32]
|
||
),
|
||
)
|
||
assert p.status_code == 200, p.text
|
||
assert not p.json()["issues"], p.text
|
||
assert [r["kind"] for r in p.json()["steps"]] == ["image.generate"]
|
||
launched = await system.client.post(
|
||
f"/api/editors/{did}/runs",
|
||
json=dict(
|
||
expected_version=draft["version"],
|
||
output_goal="media",
|
||
targets=["frame:" + "2" * 32],
|
||
expected_plan_hash=p.json()["plan_hash"],
|
||
),
|
||
headers={"Idempotency-Key": "frame-only"},
|
||
)
|
||
assert launched.status_code == 202, launched.text
|
||
async with system.app.state.db.session() as s:
|
||
run = await s.get(WorkflowRun, launched.json()["run"]["id"])
|
||
assert (
|
||
run.result_manifest["spec"]["shots"][0]["edit"]
|
||
== draft["manifest"]["spec"]["shots"][0]["edit"]
|
||
)
|
||
rid = launched.json()["run"]["id"]
|
||
_, _, state, error, calls = await _drive(system, rid, tmp_path)
|
||
assert state == "succeeded", error
|
||
assert calls == {"image.generate": 1}
|
||
from app.services.dialogue import apply_pending_result
|
||
|
||
await apply_pending_result(system.app.state.db, rid, system.settings)
|
||
applied = await system.client.get(f"/api/editors/{did}")
|
||
assert (
|
||
applied.json()["manifest"]["spec"]["shots"][0]["edit"]
|
||
== draft["manifest"]["spec"]["shots"][0]["edit"]
|
||
)
|
||
|
||
|
||
async def test_native_start_freezes_full_graph_without_tts_preparation(system):
|
||
capabilities(system)
|
||
did, draft = await native_story(system)
|
||
body = dict(expected_version=draft["version"], output_goal="film")
|
||
p = await system.client.post(f"/api/editors/{did}/plan", json=body)
|
||
assert p.status_code == 200 and not p.json()["issues"], p.text
|
||
launched = await system.client.post(
|
||
f"/api/editors/{did}/runs",
|
||
json={**body, "expected_plan_hash": p.json()["plan_hash"]},
|
||
headers={"Idempotency-Key": "native-start"},
|
||
)
|
||
assert launched.status_code == 202, launched.text
|
||
async with system.app.state.db.session() as s:
|
||
run = await s.get(WorkflowRun, launched.json()["run"]["id"])
|
||
assert run.phase == "native_production"
|
||
assert run.prepared_plan["production_materialized"] is True
|
||
assert run.prepared_plan["utterances"] == []
|
||
|
||
|
||
async def test_native_rejects_legacy_preview_targets(system):
|
||
did, draft = await native_story(system)
|
||
p = await system.client.post(
|
||
f"/api/editors/{did}/plan",
|
||
json=dict(
|
||
expected_version=draft["version"], output_goal="media", targets=["speech:" + "4" * 32]
|
||
),
|
||
)
|
||
assert p.status_code == 422, p.text
|
||
|
||
|
||
async def _start(system, did, version, **options):
|
||
body = dict(expected_version=version, output_goal="film", execution_mode="batch", **options)
|
||
p = await system.client.post(f"/api/editors/{did}/plan", json=body)
|
||
assert p.status_code == 200 and not p.json()["issues"], p.text
|
||
response = await system.client.post(
|
||
f"/api/editors/{did}/runs",
|
||
json={**body, "expected_plan_hash": p.json()["plan_hash"]},
|
||
headers={"Idempotency-Key": uuid4().hex},
|
||
)
|
||
assert response.status_code == 202, response.text
|
||
return response.json()["run"]["id"]
|
||
|
||
|
||
async def _asset(session, system, job, path, kind, index=0, **metadata):
|
||
key = "native-fixtures/" + uuid4().hex + path.suffix
|
||
destination = system.settings.asset_root / key
|
||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||
data = path.read_bytes()
|
||
destination.write_bytes(data)
|
||
a = Asset(
|
||
owner_id=job.owner_id,
|
||
origin="generated",
|
||
library_scope="private",
|
||
name=path.name,
|
||
storage_key=key,
|
||
kind=kind,
|
||
mime_type={
|
||
"image": "image/png",
|
||
"video": "video/mp4",
|
||
"audio": "audio/wav",
|
||
"json": "application/json",
|
||
}[kind],
|
||
size_bytes=len(data),
|
||
sha256=hashlib.sha256(data).hexdigest(),
|
||
source_job_id=job.id,
|
||
source_output_index=index,
|
||
source_upstream_id="fake-" + job.id,
|
||
ready=True,
|
||
**metadata,
|
||
)
|
||
session.add(a)
|
||
await session.flush()
|
||
return a
|
||
|
||
|
||
def _wav(path, frames, rate=32000):
|
||
with wave.open(str(path), "wb") as w:
|
||
w.setparams((2, 2, rate, frames, "NONE", ""))
|
||
w.writeframes(b"\x10\x00\xf0\xff" * frames)
|
||
|
||
|
||
async def _drive(system, rid, work, *, bad_report=None, turn_inspector=None):
|
||
from app.services.orchestration.workflow_engine import advance_run
|
||
from app.adapters.provider.client import Provider
|
||
from test_dialogue_workflow import configure_media_tools
|
||
|
||
configure_media_tools(system.settings)
|
||
real = Provider(system.settings)
|
||
counter = {}
|
||
try:
|
||
for _ in range(40):
|
||
async with system.app.state.db.session() as s:
|
||
await advance_run(s, rid, system.settings)
|
||
await s.commit()
|
||
run = await s.get(WorkflowRun, rid)
|
||
if run.state in {"succeeded", "blocked", "cancelled"}:
|
||
return (
|
||
deepcopy(run.result_manifest),
|
||
deepcopy(run.prepared_plan),
|
||
run.state,
|
||
run.error_json,
|
||
counter,
|
||
)
|
||
pending = (
|
||
await s.scalars(
|
||
select(WorkflowStep).where(
|
||
WorkflowStep.run_id == rid,
|
||
WorkflowStep.selected_job_id.is_not(None),
|
||
WorkflowStep.state.in_({"ready", "running"}),
|
||
)
|
||
)
|
||
).all()
|
||
for step in pending:
|
||
job = await s.get(Job, step.selected_job_id)
|
||
if job.state == "succeeded":
|
||
continue
|
||
counter[step.kind] = counter.get(step.kind, 0) + 1
|
||
itemwork = system.settings.job_work_root / "native-fixtures" / job.id
|
||
itemwork.mkdir(parents=True, exist_ok=True)
|
||
p = job.parameters
|
||
if step.kind in {"image.generate", "image.reference.generate"}:
|
||
image = itemwork / "frame.png"
|
||
Image.new("RGB", (p["width"], p["height"]), "blue").save(image)
|
||
await _asset(
|
||
s, system, job, image, "image", width=p["width"], height=p["height"]
|
||
)
|
||
job.result_json = {}
|
||
elif step.kind == "video.generate":
|
||
frames = p["num_frames"]
|
||
video, audio = itemwork / "native.mp4", itemwork / "native.wav"
|
||
# 实际的小型 FFmpeg 媒体替代外部模型边界,DAG/Job/归档/验收均真实。
|
||
subprocess.run(
|
||
[
|
||
system.settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-y",
|
||
"-f",
|
||
"lavfi",
|
||
"-i",
|
||
f"testsrc2=size={p['width']}x{p['height']}:rate=24",
|
||
"-f",
|
||
"lavfi",
|
||
"-i",
|
||
"sine=frequency=330:sample_rate=32000",
|
||
"-frames:v",
|
||
str(frames),
|
||
"-c:v",
|
||
"libx264",
|
||
"-preset",
|
||
"ultrafast",
|
||
"-pix_fmt",
|
||
"yuv420p",
|
||
"-c:a",
|
||
"aac",
|
||
"-ac",
|
||
"2",
|
||
str(video),
|
||
],
|
||
check=True,
|
||
)
|
||
count = math.ceil(frames / 24 * 40) * 800
|
||
_wav(audio, count)
|
||
await _asset(
|
||
s,
|
||
system,
|
||
job,
|
||
video,
|
||
"video",
|
||
width=p["width"],
|
||
height=p["height"],
|
||
duration_seconds=frames / 24,
|
||
)
|
||
await _asset(
|
||
s, system, job, audio, "audio", 1, duration_seconds=count / 32000
|
||
)
|
||
job.result_json = dict(frames=frames, fps=24, audio=True)
|
||
elif step.kind in {
|
||
"audio.dialogue.extract",
|
||
"audio.normalize",
|
||
"audio.mix",
|
||
"video.compose",
|
||
}:
|
||
from app.services.jobs import input_ids
|
||
|
||
ids = input_ids(job.input_json, p)
|
||
assets = {
|
||
aid: system.settings.asset_root / (await s.get(Asset, aid)).storage_key
|
||
for aid in ids
|
||
}
|
||
result = await real.run_cpu(step.kind, job.input_json, p, assets, itemwork)
|
||
kind = "video" if step.kind == "video.compose" else "audio"
|
||
metadata = (
|
||
dict(duration_seconds=result.result.get("sample_count", 0) / 48000)
|
||
if kind == "audio"
|
||
else dict(
|
||
duration_seconds=run.prepared_plan["timing"]["total_frames"] / 24
|
||
)
|
||
)
|
||
await _asset(s, system, job, result.outputs[0], kind, **metadata)
|
||
job.result_json = result.result
|
||
elif step.kind == "audio.dialogue.inspect" and p.get("turn_policy"):
|
||
report = turn_inspector(step)
|
||
path = itemwork / "turns.json"
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
await _asset(s, system, job, path, "json")
|
||
job.result_json = {"decision":report["decision"]}
|
||
elif step.kind == "audio.dialogue.inspect":
|
||
audio = await s.get(Asset, job.input_json["audio_asset_id"])
|
||
with wave.open(
|
||
str(system.settings.asset_root / audio.storage_key), "rb"
|
||
) as w:
|
||
count = w.getnframes()
|
||
text = job.input_json["expected_text"]
|
||
report = dict(
|
||
decision="pass",
|
||
reasons=[],
|
||
speaker_id=job.input_json["speaker_id"],
|
||
expected_text=text,
|
||
transcript=text,
|
||
normalized_expected_text=normalize_native_text(text),
|
||
normalized_transcript=normalize_native_text(text),
|
||
content_error_rate=0,
|
||
content_verification_policy="whisper-sensevoice-consensus-v1",
|
||
content_decision_source="whisper_sensevoice_consensus",
|
||
secondary_status="completed",
|
||
secondary_transcript=text,
|
||
normalized_secondary_transcript=normalize_native_text(text),
|
||
secondary_content_error_rate=0,
|
||
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
|
||
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
|
||
audio_sha256=audio.sha256,
|
||
source_start_sample=0,
|
||
source_end_sample=count,
|
||
sample_rate=48000,
|
||
timestamp_origin="audio_asset",
|
||
timestamp_source="whisper-word-timestamps",
|
||
native_av_policy="native_av_v1",
|
||
asr_revision="41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
|
||
words=[dict(text=text, start_sample=12000, end_sample=48000)]
|
||
if text
|
||
else [],
|
||
)
|
||
if not text:
|
||
from test_native_verified_silence import silence_report
|
||
|
||
# 真业务静默分支必须保留第一路幻觉,不能假设 Whisper 空。
|
||
report.update(silence_report(audio_sha=audio.sha256, count=count))
|
||
if bad_report:
|
||
bad_report(report)
|
||
path = itemwork / "speech.json"
|
||
path.write_text(json.dumps(report, ensure_ascii=False), encoding="utf-8")
|
||
await _asset(s, system, job, path, "json")
|
||
job.result_json = report
|
||
elif step.kind == "video.dialogue.review":
|
||
end = job.input_json["expected"]["source_end_frame"]
|
||
report = dict(
|
||
decision="pass",
|
||
verdict="pass",
|
||
source_start_frame=0,
|
||
source_end_frame=end,
|
||
review_sampling_policy="dialogue-uniform-8-v1",
|
||
frame_evidence=dict(current_indices=[round(i * (end - 1) / 7) for i in range(8)]),
|
||
)
|
||
path = itemwork / "visual.json"
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
await _asset(s, system, job, path, "json")
|
||
job.result_json = report
|
||
else:
|
||
raise AssertionError(step.kind)
|
||
job.state = "succeeded"
|
||
await s.commit()
|
||
raise AssertionError("原生任务未收敛")
|
||
finally:
|
||
await real.aclose()
|
||
|
||
|
||
async def test_native_real_media_flow_and_caption_changes_reuse_h3(system, tmp_path):
|
||
capabilities(system)
|
||
did, draft = await native_story(system, multiple=True, reference=True)
|
||
rid = await _start(system, did, draft["version"])
|
||
m, prepared, state, error, calls = await _drive(system, rid, tmp_path)
|
||
assert state == "succeeded", error
|
||
assert calls["video.generate"] == 2
|
||
assert calls["audio.mix"] == 1
|
||
actual = prepared["utterances"][0]
|
||
assert (actual["start_sample"], actual["end_sample"]) == (12000, 48000)
|
||
async with system.app.state.db.session() as s:
|
||
run = await s.get(WorkflowRun, rid)
|
||
from app.services.orchestration.native_dialogue_engine import _review_context
|
||
|
||
for review in (
|
||
await s.scalars(
|
||
select(WorkflowStep).where(
|
||
WorkflowStep.run_id == rid, WorkflowStep.kind == "video.dialogue.review"
|
||
)
|
||
)
|
||
).all():
|
||
resolved = review.resolved_input_json
|
||
assert review.result_json["context_hash"] == _review_context(
|
||
resolved["input_sha256"][resolved["input"]["video_asset_id"]],
|
||
{
|
||
aid: resolved["input_sha256"][aid]
|
||
for aid in resolved["input"].get("reference_asset_ids", [])
|
||
},
|
||
resolved["input"]["expected"],
|
||
)
|
||
video = next(
|
||
step
|
||
for step in (
|
||
await s.scalars(select(WorkflowStep).where(WorkflowStep.run_id == rid))
|
||
).all()
|
||
if step.kind == "video.generate"
|
||
)
|
||
sidecar = video.result_json["native_source_audio_asset_id"]
|
||
assert await s.scalar(
|
||
select(AssetReference.id).where(
|
||
AssetReference.ref_kind == "run",
|
||
AssetReference.ref_id == rid,
|
||
AssetReference.asset_id == sidecar,
|
||
)
|
||
)
|
||
compose = await s.scalar(
|
||
select(Job).where(Job.run_id == rid, Job.task_type == "video.compose")
|
||
)
|
||
assert compose.parameters["story_spec"]["render"]["subtitles"][0]["start_frame"] == 6
|
||
assert compose.input_json["audio_asset_id"]
|
||
assert compose.parameters["story_spec"]["render"]["audio"]
|
||
from app.services.dialogue import apply_pending_result
|
||
|
||
await apply_pending_result(system.app.state.db, rid, system.settings)
|
||
loaded = await system.client.get(f"/api/editors/{did}")
|
||
m = loaded.json()["manifest"]
|
||
assert "native_alignment:" + "2" * 32 in m["bindings"]
|
||
m["captions"]["cues"][0].update(text="人工字幕", text_override=True)
|
||
saved = await system.client.post(
|
||
f"/api/editors/{did}/save",
|
||
json=dict(expected_version=loaded.json()["version"], manifest=m),
|
||
headers={"Idempotency-Key": "captions-only"},
|
||
)
|
||
assert saved.status_code == 200, saved.text
|
||
rid2 = await _start(system, did, saved.json()["version"])
|
||
_, _, state, error, calls = await _drive(system, rid2, tmp_path)
|
||
assert state == "succeeded", error
|
||
assert calls.get("video.generate", 0) == 0
|
||
assert calls.get("audio.dialogue.inspect", 0) == 0
|
||
# 对齐强制重测只重跑所选镜头 ASR,另外一镜头和 H3 原片继续复用。
|
||
await apply_pending_result(system.app.state.db, rid2, system.settings)
|
||
loaded = await system.client.get(f"/api/editors/{did}")
|
||
rid3 = await _start(
|
||
system,
|
||
did,
|
||
loaded.json()["version"],
|
||
force=["native_alignment:" + "2" * 32],
|
||
targets=["captions"],
|
||
)
|
||
_, _, state, error, calls = await _drive(system, rid3, tmp_path)
|
||
assert state == "succeeded", error
|
||
assert calls.get("video.generate", 0) == 0
|
||
assert calls.get("audio.dialogue.inspect", 0) == 1
|
||
await apply_pending_result(system.app.state.db, rid3, system.settings)
|
||
loaded = await system.client.get(f"/api/editors/{did}")
|
||
m = loaded.json()["manifest"]
|
||
# 背景音乐层独立于镜头原声,整片合成不会重新派发 H3 或语音识别。
|
||
m["audio"]["layers"] = [
|
||
dict(
|
||
id="7" * 32,
|
||
anchor="absolute",
|
||
role="bgm",
|
||
asset_id=m["bindings"]["native_audio:" + "2" * 32]["asset_id"],
|
||
source_end_sample=48000,
|
||
)
|
||
]
|
||
saved = await system.client.post(
|
||
f"/api/editors/{did}/save",
|
||
json=dict(expected_version=loaded.json()["version"], manifest=m),
|
||
headers={"Idempotency-Key": "bgm-only"},
|
||
)
|
||
assert saved.status_code == 200, saved.text
|
||
rid4 = await _start(system, did, saved.json()["version"])
|
||
_, _, state, error, calls = await _drive(system, rid4, tmp_path)
|
||
assert state == "succeeded", error
|
||
assert calls.get("audio.normalize") == 1
|
||
assert calls.get("video.generate", 0) == 0
|
||
assert calls.get("audio.dialogue.inspect", 0) == 0
|
||
await apply_pending_result(system.app.state.db, rid4, system.settings)
|
||
loaded = await system.client.get(f"/api/editors/{did}")
|
||
body = dict(
|
||
expected_version=loaded.json()["version"],
|
||
output_goal="media",
|
||
targets=["video:" + "2" * 32],
|
||
force=["video:" + "2" * 32],
|
||
)
|
||
p = await system.client.post(f"/api/editors/{did}/plan", json=body)
|
||
assert p.status_code == 200 and not p.json()["issues"], p.text
|
||
videos = [r for r in p.json()["steps"] if r["kind"] == "video.generate"]
|
||
assert [(v["unit_id"], v["status"]) for v in videos] == [("2" * 32, "generate")]
|
||
locked = loaded.json()["manifest"]
|
||
locked["bindings"]["video:" + "2" * 32]["locked"] = True
|
||
locked["spec"]["dialogue"]["speakers"][0]["native_voice"] = "低沉沙哑的声音"
|
||
saved = await system.client.post(
|
||
f"/api/editors/{did}/save",
|
||
json=dict(expected_version=loaded.json()["version"], manifest=locked),
|
||
headers={"Idempotency-Key": "lock-native"},
|
||
)
|
||
assert saved.status_code == 200, saved.text
|
||
body = dict(
|
||
expected_version=saved.json()["version"], output_goal="media", targets=["video:" + "2" * 32]
|
||
)
|
||
blocked = await system.client.post(f"/api/editors/{did}/plan", json=body)
|
||
assert blocked.status_code == 200, blocked.text
|
||
assert any(i["code"] == "locked_dependency_changed" for i in blocked.json()["issues"])
|
||
forced = await system.client.post(
|
||
f"/api/editors/{did}/plan", json={**body, "force": ["video:" + "2" * 32]}
|
||
)
|
||
assert forced.status_code == 200 and not forced.json()["issues"], forced.text
|
||
|
||
|
||
async def test_native_legacy_new_start_requires_explicit_upgrade(system):
|
||
did, draft = await native_story(system)
|
||
async with system.app.state.db.session() as s:
|
||
row = await s.get(WorkflowDraft, did)
|
||
m = deepcopy(row.editor_manifest)
|
||
m["spec"]["dialogue"].pop("generation")
|
||
m["spec"]["dialogue"].pop("language", None)
|
||
row.editor_manifest = m
|
||
row.spec = deepcopy(m["spec"])
|
||
await s.commit()
|
||
response = await system.client.post(
|
||
f"/api/editors/{did}/runs",
|
||
json=dict(expected_version=draft["version"], expected_plan_hash="a" * 64),
|
||
headers={"Idempotency-Key": "legacy-closed"},
|
||
)
|
||
assert response.status_code == 409, response.text
|
||
assert response.json()["detail"]["code"] == "native_dialogue_upgrade_required"
|
||
|
||
|
||
async def test_native_import_is_explicitly_blocked_until_forced(system, tmp_path):
|
||
from test_dialogue_workflow import asset, motion
|
||
|
||
capabilities(system)
|
||
did, draft = await native_story(system)
|
||
data = motion(system.settings, tmp_path)
|
||
m = draft["manifest"]
|
||
async with system.app.state.db.session() as s:
|
||
owner = (await s.get(WorkflowDraft, did)).owner_id
|
||
imported = await asset(s, system, owner, "video", data, 2)
|
||
m["bindings"]["video:" + "2" * 32] = dict(
|
||
asset_id=imported.id,
|
||
sha256=imported.sha256,
|
||
kind="video",
|
||
source="manual",
|
||
locked=False,
|
||
)
|
||
await s.commit()
|
||
saved = await system.client.post(
|
||
f"/api/editors/{did}/save",
|
||
json=dict(expected_version=draft["version"], manifest=m),
|
||
headers={"Idempotency-Key": "native-import"},
|
||
)
|
||
assert saved.status_code == 200, saved.text
|
||
body = dict(
|
||
expected_version=saved.json()["version"], output_goal="media", targets=["video:" + "2" * 32]
|
||
)
|
||
p = await system.client.post(f"/api/editors/{did}/plan", json=body)
|
||
assert p.status_code == 200, p.text
|
||
assert any(i["code"] == "native_import_unsupported" for i in p.json()["issues"])
|
||
p = await system.client.post(
|
||
f"/api/editors/{did}/plan", json={**body, "force": ["video:" + "2" * 32]}
|
||
)
|
||
assert p.status_code == 200 and not p.json()["issues"], p.text
|
||
|
||
|
||
async def test_native_cancel_and_version_conflict_keep_parent_safety(system):
|
||
from app.services.orchestration.workflow_engine import advance_run
|
||
|
||
capabilities(system)
|
||
did, draft = await native_story(system)
|
||
body = dict(
|
||
expected_version=draft["version"] - 1, output_goal="film", expected_plan_hash="a" * 64
|
||
)
|
||
conflict = await system.client.post(
|
||
f"/api/editors/{did}/runs", json=body, headers={"Idempotency-Key": "stale-native"}
|
||
)
|
||
assert conflict.status_code == 409, conflict.text
|
||
rid = await _start(system, did, draft["version"])
|
||
async with system.app.state.db.session() as s:
|
||
run = await s.get(WorkflowRun, rid)
|
||
run.desired_state = "cancel"
|
||
await advance_run(s, rid, system.settings)
|
||
await s.commit()
|
||
async with system.app.state.db.session() as s:
|
||
run = await s.get(WorkflowRun, rid)
|
||
assert run.state == "cancelled"
|
||
assert not (await s.scalars(select(Job).where(Job.run_id == rid))).all()
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"bad",
|
||
[
|
||
"missing_words",
|
||
"extra_words",
|
||
"wrong_sha",
|
||
"chunk_time",
|
||
"missing_consensus",
|
||
"secondary_mismatch",
|
||
],
|
||
)
|
||
async def test_native_gate_rejects_unusable_word_evidence(system, tmp_path, bad):
|
||
capabilities(system)
|
||
did, draft = await native_story(system)
|
||
rid = await _start(system, did, draft["version"])
|
||
|
||
def mutate(report):
|
||
if bad == "missing_words":
|
||
report["words"] = []
|
||
if bad == "extra_words":
|
||
report["words"].append(dict(text="多余", start_sample=50000, end_sample=60000))
|
||
if bad == "wrong_sha":
|
||
report["audio_sha256"] = "f" * 64
|
||
if bad == "chunk_time":
|
||
report["timestamp_source"] = "chunk"
|
||
if bad == "missing_consensus":
|
||
report.pop("content_verification_policy", None)
|
||
if bad == "secondary_mismatch":
|
||
report["secondary_transcript"] = "再见。"
|
||
report["normalized_secondary_transcript"] = "你好"
|
||
|
||
_, _, state, error, calls = await _drive(system, rid, tmp_path, bad_report=mutate)
|
||
assert state == "blocked"
|
||
assert error["code"] == "invalid_native_alignment", error
|
||
assert not calls.get("video.compose")
|