From 75a79d9214c2092c4d3482a9c7f97046c664ad58 Mon Sep 17 00:00:00 2001 From: Tiance Wang Date: Thu, 26 Nov 2026 15:04:44 +0800 Subject: [PATCH] [bugfix] Preserve generation cancellation through a checkpoint conflict --- docs/development/lessons.md | 5 ++ .../application/creation_generation.py | 4 +- .../application/generation_runtime.py | 21 ++++++-- tests/test_creation_generation_service.py | 51 +++++++++++++++++++ 4 files changed, 77 insertions(+), 4 deletions(-) diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 906dded6b..a49f2f31a 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -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. diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 5efb958a8..c645007c3 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -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']) diff --git a/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index 1b4c9102a..a9135ba40 100644 --- a/packages/core/src/opendirector/application/generation_runtime.py +++ b/packages/core/src/opendirector/application/generation_runtime.py @@ -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 diff --git a/tests/test_creation_generation_service.py b/tests/test_creation_generation_service.py index 104988ed9..24f7fb5d4 100644 --- a/tests/test_creation_generation_service.py +++ b/tests/test_creation_generation_service.py @@ -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 @@ -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):