cmvr-visual/backend/tests/test_multishot_v3.py

247 lines
14 KiB
Python
Raw Normal View History

"""Variable story length without changing the short-clip model contract."""
import pytest
from pydantic import ValidationError
from sqlalchemy import select
from app.models import Job
from app.timeline import WorkflowSpec, compile_timeline
from test_timeline_v2 import spec as legacy_spec
from test_workflows_v2 import wf, run, publish_video
def story(count=12, durations=None):
durations = durations or [120] * count
return {'schema_version': 2, 'shots': [
{'key': f'shot_{i + 1}', 'prompt': f'镜头{i + 1}', 'duration_frames': frames,
'parameters': {'seed': i + 1}}
for i, frames in enumerate(durations)
], 'profile': 'landscape_1080_v1'}
def test_dynamic_timeline_derives_duration_and_accepts_late_audio_subtitles():
body = story(durations=[24] + [120] * 11)
body['render'] = {'audio': {'asset_id': 'voice', 'source_start_ms': 0,
'source_end_ms': 10000, 'offset_frame': 960},
'subtitles': [{'start_frame': 961, 'end_frame': 1344, 'text': '乘风南迁'}]}
plan = compile_timeline(body, {'voice': {'kind': 'audio', 'duration_seconds': 10}})
assert plan.frames == 1344
assert plan.shot_frames == (24,) + (120,) * 11
assert plan.spec['render']['total_frames'] == 1344
assert plan.generation_parameters['num_frames'] == 121
@pytest.mark.parametrize('change', ['keys', 'duplicate', 'zero', 'too_long', 'total', 'subtitle', 'audio'])
def test_dynamic_timeline_rejects_inconsistent_order_and_bounds(change):
body = story(4)
if change == 'keys': body['shots'][1]['key'] = 'shot_12'
elif change == 'duplicate': body['shots'][1]['key'] = 'shot_1'
elif change == 'zero': body['shots'][0]['duration_frames'] = 0
elif change == 'too_long': body['shots'][0]['duration_frames'] = 121
elif change == 'total': body['render'] = {'total_frames': 481}
elif change == 'subtitle': body['render'] = {'subtitles': [{'start_frame': 0, 'end_frame': 481, 'text': 'bad'}]}
else: body['render'] = {'audio': {'asset_id': 'a', 'source_start_ms': 0, 'source_end_ms': 20000, 'offset_frame': 1}}
with pytest.raises(ValidationError): WorkflowSpec.model_validate(body)
def test_legacy_normalized_spec_and_exact_length_stay_compatible():
plan = compile_timeline(legacy_spec(), {})
assert plan.frames == 360
assert all('duration_frames' not in shot for shot in plan.spec['shots'])
bad = legacy_spec(); bad['shots'].append({'key': 'shot_4', 'prompt': 'extra'})
with pytest.raises(ValidationError): WorkflowSpec.model_validate(bad)
@pytest.mark.asyncio
async def test_twelve_shot_run_uses_snapshot_order_then_compose(wf):
from app.workflow_engine import advance_workflows
response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story()})
assert response.status_code == 201, response.text
snapshot = await run(wf, response.json())
rid = snapshot['run']['id']
assert snapshot['run']['total_steps'] == 13
expected_keys = [f'shot_{i}' for i in range(1, 13)] + ['compose']
assert [step['step_key'] for step in snapshot['steps']] == expected_keys
ids = []
for key in expected_keys[:-1]:
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
async with wf.app.state.db.session() as session:
job = await session.scalar(select(Job).where(Job.run_id == rid, Job.state != 'succeeded'))
assert job.step_key == key
jid = job.id
ids.append(await publish_video(wf, jid))
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
async with wf.app.state.db.session() as session:
compose = await session.scalar(select(Job).where(Job.run_id == rid, Job.step_key == 'compose'))
assert compose.input_json['asset_ids'] == ids
assert compose.parameters['workflow_spec']['render']['total_frames'] == 1440
await publish_video(wf, compose.id, compose=True)
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
snapshot = (await wf.client.get('/api/workflow-runs/' + rid)).json()
assert snapshot['run']['state'] == 'succeeded'
assert snapshot['run']['completed_steps'] == snapshot['run']['total_steps'] == 13
@pytest.mark.asyncio
async def test_trim_only_revision_reuses_generated_shot(wf):
from app.workflow_engine import advance_workflows
response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(1)})
assert response.status_code == 201, response.text
draft = response.json(); first = await run(wf, draft)
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
first = (await wf.client.get('/api/workflow-runs/' + first['run']['id'])).json()
jid = first['steps'][0]['selected_job_id']
await publish_video(wf, jid)
await wf.client.post('/api/workflow-runs/' + first['run']['id'] + '/cancel', json={}, headers={'Idempotency-Key': 'cancel'})
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
draft = (await wf.client.get('/api/workflows/' + draft['id'])).json()
body = story(1); body['shots'][0]['duration_frames'] = 48
changed = await wf.client.patch('/api/workflows/' + draft['id'], json={'spec': body}, headers={'If-Match': str(draft['version'])})
assert changed.status_code == 200, changed.text
draft = changed.json()
response = await wf.client.post('/api/workflows/' + draft['id'] + '/runs', json={
'draft_revision': draft['revision'], 'expected_version': draft['version'],
'reuse_run_id': first['run']['id']}, headers={'Idempotency-Key': 'trim'})
assert response.status_code == 202, response.text
assert response.json()['steps'][0]['selected_job_id'] == jid
assert response.json()['steps'][0]['state'] == 'succeeded'
@pytest.mark.asyncio
async def test_config_cap_checks_new_save_run_but_not_frozen_children(wf, monkeypatch):
from app import workflows
from app import runtime_policy
from app.workflow_engine import advance_workflows
limit = [12]
monkeypatch.setattr(workflows, 'read_runtime_policy', lambda settings: {'workflow_max_shots': limit[0], 'configuration_error': None})
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', workflows.read_runtime_policy)
response = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(4)})
assert response.status_code == 201, response.text
draft = response.json(); accepted = await run(wf, draft)
limit[0] = 3
rejected = await wf.client.post('/api/workflows', json={'kind': 'multi_shot', 'spec': story(4)})
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
current = (await wf.client.get('/api/workflows/' + draft['id'])).json()
rejected = await wf.client.patch('/api/workflows/' + draft['id'], json={'spec': story(4)}, headers={'If-Match': str(current['version'])})
assert rejected.status_code == 422
rejected = await wf.client.post('/api/workflows/' + draft['id'] + '/runs', json={
'draft_revision': current['revision'], 'expected_version': current['version']}, headers={'Idempotency-Key': 'over-limit'})
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
rid = accepted['run']['id']
for i in range(4):
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
async with wf.app.state.db.session() as session:
job = await session.scalar(select(Job).where(Job.run_id == rid, Job.state != 'succeeded'))
assert job.step_key == f'shot_{i + 1}'
await publish_video(wf, job.id)
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
result = (await wf.client.get('/api/workflow-runs/' + rid)).json()
assert result['steps'][-1]['step_key'] == 'compose' and result['steps'][-1]['selected_job_id']
@pytest.mark.asyncio
async def test_new_manual_composition_uses_configured_clip_cap(system, monkeypatch):
from app import runtime_policy
limit = [4]
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: {
'workflow_max_shots': limit[0], 'configuration_error': None})
source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}})
aid = await publish_video(system, source.json()['jobs'][0]['id'])
body = {'task_type': 'video.compose', 'input': {'asset_ids': [aid] * 4},
'parameters': {'clips': [{'asset_id': aid}] * 4}}
accepted = await system.client.post('/api/jobs', json=body)
assert accepted.status_code == 202, accepted.text
limit[0] = 3
rejected = await system.client.post('/api/jobs', json=body)
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
@pytest.mark.asyncio
async def test_new_batch_composition_enforces_cap_and_rolls_back_atomically(system, monkeypatch):
from sqlalchemy import func
from app import runtime_policy
from app.v2_models import Batch
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: {
'workflow_max_shots': 3, 'configuration_error': None})
source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}})
aid = await publish_video(system, source.json()['jobs'][0]['id'])
job = {'task_type': 'video.compose', 'input': {'asset_ids': [aid] * 4},
'parameters': {'clips': [{'asset_id': aid}] * 4}}
direct = await system.client.post('/api/jobs', json=job)
assert direct.status_code == 422 and direct.json()['detail']['code'] == 'workflow_shot_limit'
batch = await system.client.post('/api/batches', json={'items': [
{'kind': 'job', 'task_type': 'math.solve', 'input': {'prompt': '2+2'}},
{'kind': 'job', **job}]}, headers={'Idempotency-Key': 'over-cap-batch'})
assert batch.status_code == 422 and batch.json()['detail']['code'] == 'workflow_shot_limit'
async with system.app.state.db.session() as session:
assert await session.scalar(select(func.count()).select_from(Batch)) == 0
assert await session.scalar(select(func.count()).select_from(Job)) == 1
@pytest.mark.asyncio
async def test_accepted_batch_replays_after_cap_reduction_but_new_batch_rejected(system, monkeypatch):
from app import runtime_policy
limit = [4]
monkeypatch.setattr(runtime_policy, 'read_runtime_policy', lambda settings: {
'workflow_max_shots': limit[0], 'configuration_error': None})
source = await system.client.post('/api/jobs', json={'task_type': 'video.generate', 'input': {'prompt': 'source'}})
aid = await publish_video(system, source.json()['jobs'][0]['id'])
body = {'items': [{'kind': 'job', 'task_type': 'video.compose',
'input': {'asset_ids': [aid] * 4}, 'parameters': {'clips': [{'asset_id': aid}] * 4}}]}
accepted = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'accepted-batch'})
assert accepted.status_code == 202, accepted.text
limit[0] = 3
replay = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'accepted-batch'})
assert replay.status_code == 202 and replay.json()['batch']['id'] == accepted.json()['batch']['id']
rejected = await system.client.post('/api/batches', json=body, headers={'Idempotency-Key': 'new-batch'})
assert rejected.status_code == 422 and rejected.json()['detail']['code'] == 'workflow_shot_limit'
@pytest.mark.asyncio
async def test_manual_composition_can_exceed_twenty_four_clips_and_thirty_minutes(tmp_path, monkeypatch):
from types import SimpleNamespace
from app import providers
source = tmp_path / 'source.mp4'; source.write_bytes(b'x')
work = tmp_path / 'work'; work.mkdir()
calls = []
async def inspect(path, settings):
return {'kind': 'video', 'has_audio': False,
'duration_seconds': 3600 if path.name == 'composition.mp4' else 120}
async def process(argv, **kwargs):
calls.append(argv); __import__('pathlib').Path(argv[-1]).write_bytes(b'x'); return b''
monkeypatch.setattr(providers, 'inspect_media', inspect)
monkeypatch.setattr(providers, 'run_process', process)
settings = SimpleNamespace(workspace_root=tmp_path, request_timeout_seconds=5,
ffmpeg_bin='ffmpeg', max_output_bytes=1000000)
provider = providers.Provider(settings)
try:
result = await provider._compose({'asset_ids': ['video'] * 30},
{'clips': [{'asset_id': 'video'}] * 30}, {'video': source}, work)
finally:
await provider.aclose()
assert len(calls) == 31
assert result.result['clip_count'] == 30 and result.result['duration_seconds'] == 3600
@pytest.mark.asyncio
async def test_media_variable_trims_and_total_frame_validation(tmp_path, monkeypatch):
from types import SimpleNamespace
from app import media
plan = compile_timeline(story(durations=[24, 120, 120, 120]), {})
sources = [tmp_path / f'{i}.mp4' for i in range(4)]
for p in sources: p.write_bytes(b'x')
calls = []
async def track(path, settings):
return {'frames': 384 if path.name == 'workflow.mp4' else 121, 'fps': 24,
'width': 1920, 'height': 1080 if path.name == 'workflow.mp4' else 1056,
'duration': 16 if path.name == 'workflow.mp4' else 121 / 24}
async def process(argv, **kwargs):
calls.append(argv); __import__('pathlib').Path(argv[-1]).write_bytes(b'x'); return b''
monkeypatch.setattr(media, 'inspect_video_track', track)
monkeypatch.setattr(media, 'run_process', process)
result = await media.compose_workflow(plan, tmp_path / 'work', settings=SimpleNamespace(
workspace_root=tmp_path, ffmpeg_bin='ffmpeg', max_output_bytes=1000000), sources=sources)
assert [int(c[c.index('-frames:v') + 1]) for c in calls] == [24, 120, 120, 120, 384]
assert 'atrim=duration=16' in calls[-1]
assert result.result['duration_seconds'] == 16
assert result.result['clip_count'] == 4