291 lines
15 KiB
Python
291 lines
15 KiB
Python
|
|
"""Native per-shot source lengths remain frozen across revisions and retries."""
|
||
|
|
import copy
|
||
|
|
import hashlib
|
||
|
|
from pathlib import Path
|
||
|
|
from types import SimpleNamespace
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
from pydantic import ValidationError
|
||
|
|
from sqlalchemy import select
|
||
|
|
|
||
|
|
from app.models import Asset, Job, new_id
|
||
|
|
from app.timeline import Render, WorkflowSpec, compile_timeline
|
||
|
|
from app.v2_models import WorkflowRun, WorkflowStep
|
||
|
|
from app.workflow_engine import advance_workflows
|
||
|
|
from app.workflows import digest
|
||
|
|
from test_multishot_v3 import story
|
||
|
|
from test_timeline_v2 import spec
|
||
|
|
from test_workflows_v2 import wf, run, publish_video
|
||
|
|
|
||
|
|
|
||
|
|
def test_mixed_native_generation_lengths_are_per_shot():
|
||
|
|
plan = compile_timeline(story(durations=[120, 240, 360]), {})
|
||
|
|
assert plan.frames == 720 and plan.shot_frames == (120, 240, 360)
|
||
|
|
assert plan.generation_parameters['num_frames'] == 121
|
||
|
|
assert [plan.shot_generation_parameters[f'shot_{i}']['num_frames'] for i in (1, 2, 3)] == [121, 241, 361]
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize('frames,source', [(24,121),(48,121),(120,121),(121,125),(122,125),(240,241),(360,361)])
|
||
|
|
def test_native_source_frame_rounding(frames, source):
|
||
|
|
plan = compile_timeline(story(durations=[frames]), {})
|
||
|
|
assert plan.shot_generation_parameters['shot_1']['num_frames'] == source
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize('frames', [23, 361])
|
||
|
|
def test_duration_bounds_remain_explicit(frames):
|
||
|
|
with pytest.raises(ValidationError):
|
||
|
|
WorkflowSpec.model_validate(story(durations=[frames]))
|
||
|
|
|
||
|
|
|
||
|
|
def test_v1_still_freezes_three_five_second_shots():
|
||
|
|
plan = compile_timeline(spec(), {})
|
||
|
|
assert plan.frames == 360 and plan.clip_frames == 120
|
||
|
|
assert plan.shot_frames == (120, 120, 120)
|
||
|
|
assert all('duration_frames' not in shot for shot in plan.spec['shots'])
|
||
|
|
assert all(p['num_frames'] == 121 for p in plan.shot_generation_parameters.values())
|
||
|
|
invalid = spec(); invalid['shots'][0]['duration_frames'] = 360
|
||
|
|
with pytest.raises(ValidationError):
|
||
|
|
WorkflowSpec.model_validate(invalid)
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize('count',[334,1000])
|
||
|
|
@pytest.mark.parametrize('explicit',[False,True])
|
||
|
|
def test_long_story_total_frames_roundtrips_with_or_without_explicit_total(count,explicit):
|
||
|
|
body=story(durations=[360]*count)
|
||
|
|
if explicit:body['render']={'total_frames':count*360}
|
||
|
|
accepted=WorkflowSpec.model_validate(body)
|
||
|
|
assert accepted.render.total_frames==count*360
|
||
|
|
encoded=accepted.model_dump(mode='json')
|
||
|
|
reloaded=WorkflowSpec.model_validate(encoded)
|
||
|
|
assert reloaded.model_dump(mode='json')==encoded
|
||
|
|
|
||
|
|
|
||
|
|
def test_total_frames_above_maximum_story_is_rejected():
|
||
|
|
with pytest.raises(ValidationError):
|
||
|
|
Render.model_validate({'total_frames':360001})
|
||
|
|
|
||
|
|
|
||
|
|
async def start(wf, durations, key='start'):
|
||
|
|
response = await wf.client.post('/api/workflows', json={'spec': story(durations=durations)})
|
||
|
|
assert response.status_code == 201, response.text
|
||
|
|
draft = response.json()
|
||
|
|
snapshot = await run(wf, draft, key)
|
||
|
|
return draft, snapshot
|
||
|
|
|
||
|
|
|
||
|
|
async def tick(wf):
|
||
|
|
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
|
||
|
|
|
||
|
|
|
||
|
|
async def test_mixed_children_freeze_independent_native_frame_counts(wf):
|
||
|
|
_, snapshot = await start(wf, [120,240,360])
|
||
|
|
rid = snapshot['run']['id']
|
||
|
|
await tick(wf)
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
parent = await session.get(WorkflowRun, rid)
|
||
|
|
parameters = parent.spec_snapshot['compiled']['shot_generation_parameters']
|
||
|
|
assert [parameters[f'shot_{i}']['num_frames'] for i in (1,2,3)] == [121,241,361]
|
||
|
|
jobs = (await session.scalars(select(Job).where(Job.run_id==rid).order_by(Job.step_key))).all()
|
||
|
|
assert [job.parameters['num_frames'] for job in jobs] == [121,241,361]
|
||
|
|
first = parent.spec_snapshot['shots'][0]
|
||
|
|
legacy_shot = {key:value for key,value in first.items() if key != 'duration_frames'}
|
||
|
|
legacy_hash = digest({'shot':legacy_shot,
|
||
|
|
'generation_parameters':parent.spec_snapshot['compiled']['generation_parameters'], 'source_sha256':None})
|
||
|
|
step = await session.scalar(select(WorkflowStep).where(WorkflowStep.run_id==rid,WorkflowStep.step_key=='shot_1'))
|
||
|
|
assert step.semantic_input_hash == legacy_hash
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize('before,after', [(120,360),(360,240),(240,360)])
|
||
|
|
async def test_source_length_revision_invalidates_reuse(wf, before, after):
|
||
|
|
draft, first = await start(wf, [before])
|
||
|
|
rid = first['run']['id']
|
||
|
|
await tick(wf)
|
||
|
|
snapshot = (await wf.client.get('/api/workflow-runs/'+rid)).json()
|
||
|
|
jid = snapshot['steps'][0]['selected_job_id']
|
||
|
|
assert jid is not None
|
||
|
|
await publish_video(wf, jid)
|
||
|
|
await wf.client.post('/api/workflow-runs/'+rid+'/cancel', json={}, headers={'Idempotency-Key':'cancel'})
|
||
|
|
await tick(wf)
|
||
|
|
current = (await wf.client.get('/api/workflows/'+draft['id'])).json()
|
||
|
|
changed = await wf.client.patch('/api/workflows/'+draft['id'], json={'spec':story(durations=[after])},
|
||
|
|
headers={'If-Match':str(current['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':rid},
|
||
|
|
headers={'Idempotency-Key':'new-source-length'})
|
||
|
|
assert response.status_code == 202, response.text
|
||
|
|
second = response.json()
|
||
|
|
assert second['steps'][0]['selected_job_id'] is None
|
||
|
|
assert second['steps'][0]['semantic_input_hash'] != first['steps'][0]['semantic_input_hash']
|
||
|
|
await tick(wf)
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
child = await session.scalar(select(Job).where(Job.run_id==second['run']['id']))
|
||
|
|
assert child.parameters['num_frames'] == max(121, ((after+3)//4)*4+1)
|
||
|
|
|
||
|
|
|
||
|
|
async def test_long_step_retry_keeps_frozen_length_after_draft_edit(wf):
|
||
|
|
draft, first = await start(wf, [360])
|
||
|
|
rid = first['run']['id']
|
||
|
|
await tick(wf)
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
old = await session.scalar(select(Job).where(Job.run_id==rid))
|
||
|
|
old.state='failed'; jid=old.id
|
||
|
|
await session.commit()
|
||
|
|
current = (await wf.client.get('/api/workflows/'+draft['id'])).json()
|
||
|
|
changed = await wf.client.patch('/api/workflows/'+draft['id'], json={'spec':story(durations=[240])},
|
||
|
|
headers={'If-Match':str(current['version'])})
|
||
|
|
assert changed.status_code == 200
|
||
|
|
await tick(wf)
|
||
|
|
snapshot = (await wf.client.get('/api/workflow-runs/'+rid)).json()
|
||
|
|
response = await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry', json={
|
||
|
|
'expected_run_version':snapshot['run']['version'], 'target_job_id':jid},
|
||
|
|
headers={'Idempotency-Key':'retry-frozen-long'})
|
||
|
|
assert response.status_code == 202, response.text
|
||
|
|
selected = response.json()['steps'][0]['selected_job_id']
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
assert (await session.get(Job, selected)).parameters['num_frames'] == 361
|
||
|
|
assert response.json()['steps'][0]['semantic_input_hash'] == first['steps'][0]['semantic_input_hash']
|
||
|
|
|
||
|
|
|
||
|
|
async def test_legacy_snapshot_without_map_keeps_original_source_parameters(wf):
|
||
|
|
response = await wf.client.post('/api/workflows', json={'spec':spec()})
|
||
|
|
draft = response.json(); first = await run(wf, draft)
|
||
|
|
rid = first['run']['id']
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
parent = await session.get(WorkflowRun, rid)
|
||
|
|
frozen = copy.deepcopy(parent.spec_snapshot)
|
||
|
|
frozen['compiled'].pop('shot_generation_parameters', None)
|
||
|
|
parent.spec_snapshot = frozen
|
||
|
|
await session.commit()
|
||
|
|
await tick(wf)
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
jobs = (await session.scalars(select(Job).where(Job.run_id==rid))).all()
|
||
|
|
assert len(jobs)==3 and all(job.parameters['num_frames']==121 for job in jobs)
|
||
|
|
assert (await session.get(WorkflowRun,rid)).spec_snapshot == frozen
|
||
|
|
|
||
|
|
|
||
|
|
async def test_present_but_incomplete_generation_map_never_admits_child(wf):
|
||
|
|
_, first = await start(wf, [120])
|
||
|
|
rid = first['run']['id']
|
||
|
|
async with wf.app.state.db.session() as session:
|
||
|
|
parent = await session.get(WorkflowRun,rid)
|
||
|
|
frozen = copy.deepcopy(parent.spec_snapshot)
|
||
|
|
frozen['compiled']['shot_generation_parameters'] = {}
|
||
|
|
parent.spec_snapshot = frozen
|
||
|
|
await session.commit()
|
||
|
|
await tick(wf)
|
||
|
|
snapshot = (await wf.client.get('/api/workflow-runs/'+rid)).json()
|
||
|
|
assert snapshot['run']['state']=='blocked'
|
||
|
|
assert snapshot['jobs']==[]
|
||
|
|
|
||
|
|
|
||
|
|
async def output_job(system, source_frames):
|
||
|
|
owner = (await system.client.get('/api/auth/me')).json()['user']['id']
|
||
|
|
job = Job(id=new_id(),owner_id=owner,task_type='video.generate',state='collecting',phase='importing_outputs',
|
||
|
|
run_id='fixture-run',step_key='shot_1',input_json={'prompt':'fixture'},
|
||
|
|
parameters={'num_frames':source_frames,'upscale_width':1920,'upscale_height':1056},
|
||
|
|
request_hash='fixture',upstream_key=new_id())
|
||
|
|
async with system.app.state.db.session() as session:
|
||
|
|
session.add(job); await session.commit()
|
||
|
|
return job
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize('source_frames,decoded,accept', [(121,119,False),(121,120,True),
|
||
|
|
(241,239,False),(241,240,True),(361,121,False),(361,359,False),(361,360,True)])
|
||
|
|
async def test_new_workflow_output_checks_frozen_decoded_length(system, monkeypatch, source_frames, decoded, accept):
|
||
|
|
from app import assets, media
|
||
|
|
job = await output_job(system, source_frames)
|
||
|
|
source = system.settings.job_work_root/job.id/'source.mp4'
|
||
|
|
source.parent.mkdir(); source.write_bytes(b'fixture-native-video')
|
||
|
|
async def track(*args):
|
||
|
|
return {'frames':decoded,'fps':24,'width':1920,'height':1056,'duration':decoded/24}
|
||
|
|
async def build(settings,owner,identifier,path,name,**fields):
|
||
|
|
data=path.read_bytes()
|
||
|
|
return Asset(id=identifier,owner_id=owner,name=name,storage_key=path.relative_to(settings.asset_root).as_posix(),
|
||
|
|
kind='video',mime_type='video/mp4',size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(),
|
||
|
|
width=1920,height=1056,duration_seconds=decoded/24,**fields)
|
||
|
|
monkeypatch.setattr(media,'inspect_video_track',track)
|
||
|
|
monkeypatch.setattr(assets,'build_asset',build)
|
||
|
|
if accept:
|
||
|
|
output=await assets.import_output(system.app.state.db,system.settings,job,source,0)
|
||
|
|
assert output.source_job_id==job.id
|
||
|
|
else:
|
||
|
|
with pytest.raises(ValueError,match='frozen decoded video specification'):
|
||
|
|
await assets.import_output(system.app.state.db,system.settings,job,source,0)
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize('source_frames,decoded,accept', [(121,120,True),(361,121,False),(361,360,True)])
|
||
|
|
async def test_existing_output_recovery_rechecks_frozen_decoded_length(system,monkeypatch,source_frames,decoded,accept):
|
||
|
|
from app import assets, media
|
||
|
|
job=await output_job(system,source_frames)
|
||
|
|
identifier=new_id(); path=system.settings.asset_root/job.owner_id/identifier/'original.mp4'
|
||
|
|
path.parent.mkdir(parents=True); data=b'previously-imported';path.write_bytes(data)
|
||
|
|
asset=Asset(id=identifier,owner_id=job.owner_id,name='output.mp4',storage_key=path.relative_to(system.settings.asset_root).as_posix(),
|
||
|
|
kind='video',mime_type='video/mp4',size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(),
|
||
|
|
width=1920,height=1056,duration_seconds=decoded/24,source_job_id=job.id,source_output_index=0,ready=False)
|
||
|
|
async with system.app.state.db.session() as session:
|
||
|
|
session.add(asset);await session.commit()
|
||
|
|
async def track(*args):return {'frames':decoded,'fps':24,'width':1920,'height':1056,'duration':decoded/24}
|
||
|
|
monkeypatch.setattr(media,'inspect_video_track',track)
|
||
|
|
if accept:
|
||
|
|
result=await assets.import_output(system.app.state.db,system.settings,job,path,0)
|
||
|
|
assert result.id==identifier
|
||
|
|
else:
|
||
|
|
with pytest.raises(ValueError,match='frozen decoded video specification'):
|
||
|
|
await assets.import_output(system.app.state.db,system.settings,job,path,0)
|
||
|
|
|
||
|
|
|
||
|
|
async def test_gpu_existing_output_recovery_rejects_short_source_for_long_job(system,monkeypatch):
|
||
|
|
from app import media
|
||
|
|
job=await output_job(system,361)
|
||
|
|
identifier=new_id();path=system.settings.asset_root/job.owner_id/identifier/'original.mp4'
|
||
|
|
path.parent.mkdir(parents=True);data=b'previously-imported-short-video';path.write_bytes(data)
|
||
|
|
async with system.app.state.db.session() as session:
|
||
|
|
saved=await session.get(Job,job.id)
|
||
|
|
saved.upstream_result={'outputs':[{'path':'remote.mp4'}],'metadata':{'final_output_indices':[0]}}
|
||
|
|
session.add(Asset(id=identifier,owner_id=job.owner_id,name='short.mp4',
|
||
|
|
storage_key=path.relative_to(system.settings.asset_root).as_posix(),kind='video',mime_type='video/mp4',
|
||
|
|
size_bytes=len(data),sha256=hashlib.sha256(data).hexdigest(),width=1920,height=1056,
|
||
|
|
duration_seconds=121/24,source_job_id=job.id,source_output_index=0,ready=False))
|
||
|
|
await session.commit()
|
||
|
|
job=saved
|
||
|
|
async def track(*args):return {'frames':121,'fps':24,'width':1920,'height':1056,'duration':121/24}
|
||
|
|
published=[]
|
||
|
|
async def complete(*args,**kwargs):published.append(True)
|
||
|
|
monkeypatch.setattr(media,'inspect_video_track',track)
|
||
|
|
monkeypatch.setattr(system.app.state.coordinator,'_complete',complete)
|
||
|
|
with pytest.raises(ValueError,match='frozen decoded video specification'):
|
||
|
|
await system.app.state.coordinator._collect_gpu(job)
|
||
|
|
assert not published
|
||
|
|
assert system.provider.download_count==0
|
||
|
|
|
||
|
|
|
||
|
|
async def test_mixed_composition_uses_exact_selected_frames_without_extension(tmp_path,monkeypatch):
|
||
|
|
from app import media
|
||
|
|
plan=compile_timeline(story(durations=[120,240,360]),{})
|
||
|
|
sources=[tmp_path/f'source-{index}.mp4' for index in range(3)]
|
||
|
|
for path in sources:path.write_bytes(b'fixture')
|
||
|
|
calls=[]
|
||
|
|
async def track(path,settings):
|
||
|
|
frames=720 if path.name=='workflow.mp4' else [121,241,361][sources.index(path)]
|
||
|
|
return {'frames':frames,'fps':24,'width':1920,'height':1080 if path.name=='workflow.mp4' else 1056,'duration':frames/24}
|
||
|
|
async def process(argv,**kwargs):
|
||
|
|
calls.append(argv);Path(argv[-1]).write_bytes(b'rendered');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=10**6),sources=sources)
|
||
|
|
assert [int(call[call.index('-frames:v')+1]) for call in calls]==[120,240,360,720]
|
||
|
|
assert result.result['frames']==720 and result.result['duration_seconds']==30
|
||
|
|
assert all('tpad' not in ' '.join(call) and '-stream_loop' not in call for call in calls)
|
||
|
|
|
||
|
|
|
||
|
|
async def test_composition_rejects_short_native_source_instead_of_extending(tmp_path,monkeypatch):
|
||
|
|
from app import media
|
||
|
|
plan=compile_timeline(story(durations=[360]),{})
|
||
|
|
source=tmp_path/'source.mp4';source.write_bytes(b'fixture')
|
||
|
|
async def track(*args):return {'frames':121,'fps':24,'width':1920,'height':1056,'duration':121/24}
|
||
|
|
monkeypatch.setattr(media,'inspect_video_track',track)
|
||
|
|
with pytest.raises(media.MediaError,match='360'):
|
||
|
|
await media.compose_workflow(plan,tmp_path/'work',settings=SimpleNamespace(workspace_root=tmp_path),sources=[source])
|