Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u

- **Shared model catalog follow-up:** [Nightly run 45309310680](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45309310680/job/138160760923) reached the empty-video-selector test after an earlier script saved a video model. A new page still reads the shared server's catalog. For a UI test of an empty category, scope that catalog response to the test page and verify the flow with a model already present on the shared server.

## A pending checkpoint can race with accepted cancellation

- **Evidence:** The generation-feedback test in [Nightly run 45734069088](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45734069088/job/139622924333) timed out waiting for durable cancellation. Holding the initial running checkpoint until cancellation committed reproduced an accepted cancel that ended in `failed`.
- **Check:** Drain the in-flight write and preserve explicit cancellation when that write loses its revision check. Verify the original job reaches `cancelled` and that the provider was never called when cancellation wins before submission.

## Canvas media readiness depends on the viewport

- Browser checks that inspect a canvas image or video after reopening a project or placing a result should bring the target node into view first.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,9 @@ def apply(current):
return current.model_copy(update={'jobs': tuple(updated if j.id == job.id else j for j in current.jobs)})
receipt = self.projects.commit(command, apply, source='background')
if receipt.status == 'rejected':
raise ProjectError('任务状态发生并发修改,请重新读取原任务。', 409)
code = 'revision_conflict' if receipt.issues and all(
issue.code == 'revision_conflict' for issue in receipt.issues) else None
raise ProjectError('任务状态发生并发修改,请重新读取原任务。', 409, code=code)

def _result_asset(self, task, directory):
job = self.get_job(task['projectId'], task['id'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,30 @@ async def _run(self, task, pinned, config, mode='submit'):
cache = gateway().results(pinned, task['id'])
trace_token = MODEL_JOB_CONTEXT.set((str(task['projectId']), str(task['id'])))
async def save():
async def write_checkpoint():
try:
await asyncio.to_thread(self.checkpoint, task['projectId'], dict(task), pinned)
except ProjectError as error:
if error.code != 'revision_conflict':
raise
return error
return None

# Cancelling to_thread does not stop the underlying write. Drain it
# before saving the terminal state so an old running receipt cannot
# overwrite a later cancellation.
pending = asyncio.create_task(asyncio.to_thread(self.checkpoint, task["projectId"], dict(task), pinned))
pending = asyncio.create_task(write_checkpoint())
try:
await asyncio.shield(pending)
conflict = await asyncio.shield(pending)
except asyncio.CancelledError:
await pending
conflict = await pending
# An accepted cancel advances the job revision. A stale
# checkpoint must not replace cancellation with failure.
if conflict is not None and task['id'] not in self.cancelled:
raise conflict
raise
if conflict is not None:
raise conflict

async def submitted(external_id):
nonlocal stage
Expand Down
51 changes: 51 additions & 0 deletions tests/test_creation_generation_service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Provider doubles exercise the real durable runtime, files and restart path."""
import asyncio
from threading import Event
from uuid import UUID, uuid4

import pytest
Expand Down Expand Up @@ -51,6 +52,56 @@ def configure(project, config):
return target, store.snapshot(pid).generationSpecs[-1]


@pytest.mark.anyio
async def test_cancel_wins_over_an_in_flight_running_checkpoint(project, monkeypatch):
store, pid, session = project
provider = Provider()
runner, config = runtime(project, provider)
target, spec = configure(project, config)
started = asyncio.Event()
release = Event()
loop = asyncio.get_running_loop()
commit = store.commit
cancel = runner.cancel
conflicts = []

def hold_running_checkpoint(command, *args, **kwargs):
if command.type == 'job.checkpoint' and command.payload.job.status == 'running':
loop.call_soon_threadsafe(started.set)
assert release.wait(10)
receipt = commit(command, *args, **kwargs)
conflicts.extend(issue.code for issue in receipt.issues)
return receipt
return commit(command, *args, **kwargs)

async def release_after_cancelling(project_id, job_id, edit_session):
# cancel() sends the worker's cancellation before it yields.
loop.call_soon(release.set)
await cancel(project_id, job_id, edit_session)

monkeypatch.setattr(store, 'commit', hold_running_checkpoint)
monkeypatch.setattr(runner, 'cancel', release_after_cancelling)
try:
submit = parse_command(dict(commandId=uuid4(), projectId=pid, type='generation.submit',
expectedVersions=[ver('canvas_item', target), ver('generation_spec', spec)],
payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=target.id)))
assert (await runner.execute(submit, session=session)).status == 'accepted'
await asyncio.wait_for(started.wait(), 5)
job = store.snapshot(pid).jobs[0]
command = parse_command(dict(commandId=uuid4(), projectId=pid, type='job.cancel',
expectedVersions=[ver('job', job)], payload=dict(jobId=job.id)))
assert (await runner.execute(command, session=session)).status == 'applied'
final = store.snapshot(pid).jobs[0]
assert conflicts == ['revision_conflict']
assert final.id == job.id and final.cancelRequested
assert final.status == 'cancelled'
assert not final.resumeAllowed
assert not provider.calls
finally:
release.set()
await runner.close()


@pytest.mark.anyio
@pytest.mark.parametrize('title', ['Output.md', 'Output.md.md'])
async def test_result_registration_uses_one_extension_when_the_node_title_has_one(project, title):
Expand Down
Loading