From 3aafd0abaf8ce6916cea5a1f59f5459329528c04 Mon Sep 17 00:00:00 2001 From: Barkly1te Date: Wed, 2 Dec 2026 12:24:36 +0800 Subject: [PATCH 1/7] [bugfix] creation: validate atomic prompt references together --- .../application/creation_canvas.py | 138 ++++++++++-------- tests/test_creation_canvas_service.py | 60 ++++++++ 2 files changed, 134 insertions(+), 64 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 844c5cfa3..4d6c5aabb 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -13,7 +13,7 @@ from opendirector.domain.creation.assets import AssetRef from opendirector.domain.creation.base import CanvasItemVersion, ObjectVersion, Point -from opendirector.domain.creation.commands import CanvasShow, Query, ReferenceWrite, SpecWrite +from opendirector.domain.creation.commands import CanvasShow, Query, SpecWrite from opendirector.domain.creation.generation import FollowingSource, ResolvedReference from opendirector.domain.creation.canvas import CanvasReferenceSources, canvas_origin, FollowingReferenceSource, PinnedReferenceSource, media_card_size, node_capabilities, VideoCanvasItem from opendirector.domain.creation.models import ModelConfigPublic @@ -504,6 +504,69 @@ def _publish_render(self, data, payload): editorDocumentId=str(doc.id), editorRevision=doc.revision, sources=[ref.model_dump(mode='json') for ref in sources]) + def _write_reference(self, data, kind, reference) -> str | None: + ref = reference.model_dump(mode='json') + changed_source = False + if str(ref['projectId']) != str(data['project']['id']): + raise ContractError('invalid_input', '参考不属于当前工程。') + spec = self._get(data, 'generation_spec', reference.targetSpecId) + for item in data['canvasItems']: + binding_ref = item['binding'].get('objectRef') or item['binding'].get('draftSpec') + if binding_ref and binding_ref.get('id') == spec['id']: + self._editable(data, item['id']) + if kind == 'reference.add': + if not reference.active: + raise ContractError('invalid_input', '新增参考必须为有效关系。', reference.id) + duplicate = next((r for r in data['references'] if r['active'] and (r['targetSpecId'], r['binding'], r['source']) == (ref['targetSpecId'], ref['binding'], ref['source'])), None) + if duplicate: + return None + if any(r['id'] == ref['id'] for r in data['references']): + raise ContractError('invalid_input', '参考标识已使用。', reference.id) + spec['purpose'] = 'generation' + for item in data['canvasItems']: + if (item['binding'].get('draftSpec') or {}).get('id') == spec['id']: + item['binding'] = {'role': 'generation', 'objectRef': {'objectType': 'generation_spec', 'id': spec['id']}} + data['references'].append(ref) + else: + old = self._get(data, 'reference', reference.id) + changed_source = (old['binding'], old['source']) != (ref['binding'], ref['source']) + if kind == 'reference.restore': + if old['revision'] != ref['revision']: + raise ContractError('revision_conflict', '参考已发生变化,请重新读取后恢复。', reference.id) + if old['active'] or not ref['active']: + raise ContractError('invalid_input', '仅能恢复已移除的参考关系。', reference.id) + if (old['targetSpecId'], old['binding'], old['source']) != (ref['targetSpecId'], ref['binding'], ref['source']): + raise ContractError('invalid_input', '恢复参考不能改变原有来源和目标。', reference.id) + elif old['active'] != ref['active']: + raise ContractError('role_restricted', '参考的移除与恢复需使用对应生命周期命令。', reference.id) + if old['targetSpecId'] != ref['targetSpecId']: + raise ContractError('invalid_input', '不能转移参考的目标配置。', reference.id) + if any(other['id'] != old['id'] and other['active'] and (other['targetSpecId'], other['binding'], other['source']) == (ref['targetSpecId'], ref['binding'], ref['source']) for other in data['references']): + raise ContractError('reference_invalid', '该参考来源已连接到目标配置。', reference.id) + old.update(ref) + if 'frameTimeMs' not in ref: + old.pop('frameTimeMs', None) + if reference.binding == 'follow_current': + if kind in {'reference.add', 'reference.restore'} or changed_source: + self._editable(data, reference.source.id) + else: + self._get(data, 'canvas_item', reference.source.id) + return spec['kind'] + + def _validate_reference_source(self, snapshot, reference, target_kind): + source_item = None + if reference.binding == 'follow_current': + source_item = next(item for item in snapshot.canvasItems if item.id == reference.source.id) + allowed = downstream_kinds(snapshot, source_item) + else: + allowed = DOWNSTREAM.get(reference.source.kind, set()) + if target_kind not in allowed: + raise ContractError('reference_invalid', '该节点类型不能作为目标节点的参考。', reference.id) + if source_item is not None and source_item.binding.role == 'generation' and current_asset(snapshot, source_item) is None: + return + for value in resolve_reference(snapshot, reference): + self._available(next(asset for asset in snapshot.assets if asset.id == value.asset.assetId)) + def _mutate(self, data, kind, payload): value = payload.model_dump(mode='json', exclude_unset=True) if kind in {'editor.create', 'editor.save'} and payload.document.kind == 'timeline': @@ -516,8 +579,14 @@ def _mutate(self, data, kind, payload): elif kind == 'canvas.createGeneration': self._mutate(data, 'generationSpec.create', SpecWrite(spec=payload.spec)) self._mutate(data, 'canvas.show', CanvasShow(item=payload.item, positionSpace=payload.positionSpace)) + added_references = [] for reference in payload.references: - self._mutate(data, 'reference.add', ReferenceWrite(reference=reference)) + if self._write_reference(data, 'reference.add', reference) is not None: + added_references.append(reference) + if added_references: + snapshot = ProjectSnapshot.model_validate(data) + for reference in added_references: + self._validate_reference_source(snapshot, reference, payload.spec.kind) elif kind in {'generationSpec.create', 'editor.create'}: key, collection = ('spec', 'generationSpecs') if kind.startswith('generation') else ('document', 'editorDocuments') obj = getattr(payload, key).model_dump(mode='json') @@ -676,68 +745,9 @@ def _mutate(self, data, kind, payload): raise ContractError('role_restricted', '仅媒体节点可解除附属编辑器。', payload.itemId) item['editors'] = [ref for ref in item['editors'] if ref['id'] != str(payload.editorId)] elif kind in {'reference.add', 'reference.update', 'reference.restore'}: - ref = payload.reference.model_dump(mode='json') - changed_source = False - if str(ref['projectId']) != str(data['project']['id']): - raise ContractError('invalid_input', '参考不属于当前工程。') - spec = self._get(data, 'generation_spec', payload.reference.targetSpecId) - for item in data['canvasItems']: - binding_ref = item['binding'].get('objectRef') or item['binding'].get('draftSpec') - if binding_ref and binding_ref.get('id') == spec['id']: - self._editable(data, item['id']) - if kind == 'reference.add': - if not payload.reference.active: - raise ContractError('invalid_input', '新增参考必须为有效关系。', payload.reference.id) - duplicate = next((r for r in data['references'] if r['active'] and (r['targetSpecId'], r['binding'], r['source']) == (ref['targetSpecId'], ref['binding'], ref['source'])), None) - if duplicate: - return - if any(r['id'] == ref['id'] for r in data['references']): - raise ContractError('invalid_input', '参考标识已使用。', payload.reference.id) - spec['purpose'] = 'generation' - for item in data['canvasItems']: - # An empty binding serialises draftSpec as null, not absent. - if (item['binding'].get('draftSpec') or {}).get('id') == spec['id']: - item['binding'] = {'role': 'generation', 'objectRef': {'objectType': 'generation_spec', 'id': spec['id']}} - data['references'].append(ref) - else: - old = self._get(data, 'reference', payload.reference.id) - changed_source = (old['binding'], old['source']) != (ref['binding'], ref['source']) - if kind == 'reference.restore': - if old['revision'] != ref['revision']: - raise ContractError('revision_conflict', '参考已发生变化,请重新读取后恢复。', payload.reference.id) - if old['active'] or not ref['active']: - raise ContractError('invalid_input', '仅能恢复已移除的参考关系。', payload.reference.id) - if (old['targetSpecId'], old['binding'], old['source']) != (ref['targetSpecId'], ref['binding'], ref['source']): - raise ContractError('invalid_input', '恢复参考不能改变原有来源和目标。', payload.reference.id) - elif old['active'] != ref['active']: - raise ContractError('role_restricted', '参考的移除与恢复需使用对应生命周期命令。', payload.reference.id) - if old['targetSpecId'] != ref['targetSpecId']: - raise ContractError('invalid_input', '不能转移参考的目标配置。', payload.reference.id) - if any(other['id'] != old['id'] and other['active'] and (other['targetSpecId'], other['binding'], other['source']) == (ref['targetSpecId'], ref['binding'], ref['source']) for other in data['references']): - raise ContractError('reference_invalid', '该参考来源已连接到目标配置。', payload.reference.id) - old.update(ref) - if 'frameTimeMs' not in ref: - old.pop('frameTimeMs', None) - if ref['binding'] == 'follow_current': - source = self._get(data, 'canvas_item', ref['source']['id']) - source_kind = source['kind'] - if kind in {'reference.add', 'reference.restore'} or changed_source: - self._editable(data, source['id']) - else: - source_kind = ref['source']['kind'] - snapshot = ProjectSnapshot.model_validate(data) - source_item = next((item for item in snapshot.canvasItems if str(item.id) == ref['source'].get('id')), None) - allowed = downstream_kinds(snapshot, source_item) if source_item else DOWNSTREAM.get(source_kind, set()) - if spec['kind'] not in allowed: - raise ContractError('reference_invalid', '该节点类型不能作为目标节点的参考。', payload.reference.id) - pending_generation = ( - ref['binding'] == 'follow_current' and source_item is not None - and source_item.binding.role == 'generation' - and current_asset(snapshot, source_item) is None - ) - if not pending_generation: - for value in resolve_reference(snapshot, payload.reference): - self._available(next(asset for asset in snapshot.assets if asset.id == value.asset.assetId)) + target_kind = self._write_reference(data, kind, payload.reference) + if target_kind is not None: + self._validate_reference_source(ProjectSnapshot.model_validate(data), payload.reference, target_kind) elif kind == 'reference.remove': ref = self._get(data, 'reference', payload.referenceId) spec = self._get(data, 'generation_spec', ref['targetSpecId']) diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index 7e28ccb92..fce7d5a92 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -392,6 +392,66 @@ def test_create_generation_connects_existing_reference(project): assert not snapshot.jobs +@pytest.mark.parametrize('batched', [False, True], ids=['direct', 'batch']) +@pytest.mark.parametrize('source_problem', [None, 'missing', 'locked', 'blank'], + ids=['valid', 'missing', 'locked', 'blank']) +def test_create_generation_with_two_prompt_references(project, batched, source_problem): + store, pid, session = project + first, first_asset = text_material(project, title='First') + second, second_asset = text_material(project, title='Second', text=' ' if source_problem == 'blank' else 'v2') + second_id = uuid4() if source_problem == 'missing' else second.id + if source_problem == 'locked': + locked = send(store, pid, 'canvas.update', session=session, versions=[ver('canvas_item', second)], + itemId=second.id, locked=True) + assert locked.status == 'applied', locked.issues + + spec_id, item_id = uuid4(), uuid4() + reference_ids = [uuid4(), uuid4()] + payload = dict( + spec=dict(id=spec_id, projectId=pid, kind='image', purpose='generation', promptContent=[ + dict(type='reference', referenceId=reference_ids[0]), + dict(type='text', text=' and '), + dict(type='reference', referenceId=reference_ids[1]), + ]), + item=dict(id=item_id, projectId=pid, kind='image', + binding=dict(role='generation', objectRef=dict(id=spec_id))), + references=[dict(id=ref_id, projectId=pid, targetSpecId=spec_id, order=order, + binding='follow_current', source=dict(id=source_id)) + for order, (ref_id, source_id) in enumerate(zip(reference_ids, [first.id, second_id]))], + ) + before = store.snapshot(pid) + if batched: + receipt = send(store, pid, 'creation.batch', session=session, operations=[ + dict(type='canvas.show', payload=dict(item=dict(id=uuid4(), projectId=pid, kind='group'))), + dict(type='canvas.createGeneration', payload=payload), + ]) + else: + receipt = send(store, pid, 'canvas.createGeneration', session=session, **payload) + + snapshot = CreationProjects(LocalProjects(store.local.repository)).snapshot(pid) + assert not snapshot.jobs and not receipt.jobIds + if source_problem is not None: + expected_issue = { + 'missing': ('missing_object', second_id), + 'locked': ('role_restricted', second_id), + 'blank': ('reference_invalid', second_asset.id), + }[source_problem] + assert receipt.status == 'rejected' + assert [(issue.code, issue.objectId) for issue in receipt.issues] == [expected_issue] + assert snapshot == before + return + + assert receipt.status == 'applied', receipt.issues + item = next(item for item in snapshot.canvasItems if item.id == item_id) + assert item.visible and item.binding.objectRef.id == spec_id + spec = next(spec for spec in snapshot.generationSpecs if spec.id == spec_id) + assert spec.prompt == '@First and @Second' + assert [part.referenceId for part in spec.promptContent if part.type == 'reference'] == reference_ids + assert [(ref.referenceId, ref.asset.assetId) for ref in resolved_inputs(snapshot, spec_id)] == [ + (reference_ids[0], first_asset.id), (reference_ids[1], second_asset.id), + ] + + def test_canvas_item_status_is_scoped_and_read_only(project): store, pid, session = project item, _ = text_material(project) From 8dcc33bd8efba1ccb62cdfba5b06219af5bc63ef Mon Sep 17 00:00:00 2001 From: Barkly1te Date: Wed, 2 Dec 2026 14:38:31 +0800 Subject: [PATCH 2/7] [bugfix] creation: fill omitted reference orders by position Fill omitted orders while parsing canvas.createGeneration so CLI serialization and other entry points use the same effective order. Preserve explicit values and let project validation reject collisions. The focused direct and batch suite had 8 failures and 10 passes before the change. All 18 pass after it, including persisted order, mixed media, replay, and rollback. --- .../opendirector/domain/creation/commands.py | 10 +- tests/test_creation_canvas_service.py | 99 ++++++++++++------- 2 files changed, 74 insertions(+), 35 deletions(-) diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index b1ccad39a..0452fff42 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -2,7 +2,7 @@ from typing import Annotated, Literal, Union from uuid import UUID -from pydantic import ConfigDict, Field, TypeAdapter, create_model, model_validator +from pydantic import ConfigDict, Field, TypeAdapter, create_model, field_validator, model_validator from .assets import AssetRef, MediaMetadata from .base import CanvasColor, Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique @@ -115,6 +115,14 @@ class CanvasCreateGeneration(CanvasPlacement): item: CanvasItem = Field(description='Visible item bound to spec.id with role=generation.') references: tuple[Reference, ...] = Field(default=(), description='Input references. Every canvas-derived reference must retain its source node: source.id for follow_current, sourceVersion for pinned. Never replace a canvas reference with an asset-only binding.') + @field_validator('references') + @classmethod + def fill_reference_orders(cls, references: tuple[Reference, ...]) -> tuple[Reference, ...]: + return tuple( + reference if 'order' in reference.model_fields_set else reference.model_copy(update={'order': position}) + for position, reference in enumerate(references) + ) + @model_validator(mode='after') def bindings(self): if not self.item.visible: diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index fce7d5a92..9b95f58ba 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -58,6 +58,24 @@ def text_material(project, title='Source', text='v1'): return store.snapshot(project_id).canvasItems[-1], asset +def image_material(project, title): + store, project_id, session = project + image = BytesIO() + Image.new('RGB', (16, 16), 'blue').save(image, 'PNG') + handle = uuid4() + name = f'{title}.png' + writer = CreationAssets(store).uploads.begin(project_id, handle, session, name, expected_kind='image') + writer.write(image.getvalue()) + writer.finish() + assert send(store, project_id, 'asset.import', session=session, uploadHandle=handle, + name=name, expectedKind='image').status == 'applied' + asset = store.snapshot(project_id).assets[-1] + assert send(store, project_id, 'canvas.show', session=session, item=dict(id=uuid4(), + projectId=project_id, kind='image', title=title, + binding=dict(role='material', objectRef=asset_ref(asset)))).status == 'applied' + return store.snapshot(project_id).canvasItems[-1], asset + + def test_hidden_follow_source_reopens_with_stable_identity_and_duplicate_reference_is_noop(project): store, pid, session = project source, asset = text_material(project) @@ -393,51 +411,73 @@ def test_create_generation_connects_existing_reference(project): @pytest.mark.parametrize('batched', [False, True], ids=['direct', 'batch']) -@pytest.mark.parametrize('source_problem', [None, 'missing', 'locked', 'blank'], - ids=['valid', 'missing', 'locked', 'blank']) -def test_create_generation_with_two_prompt_references(project, batched, source_problem): +@pytest.mark.parametrize(('orders', 'saved_orders', 'problem'), [ + pytest.param((0, 1), (0, 1), None, id='explicit'), + pytest.param((None, None), (0, 1), None, id='omitted'), + pytest.param((0, None), (0, 1), None, id='mixed-zero'), + pytest.param((None, 7), (0, 7), None, id='mixed-custom'), + pytest.param((None, 0), None, 'order_conflict', id='order-conflict'), + pytest.param((None, None), None, 'missing', id='missing'), + pytest.param((None, None), None, 'locked', id='locked'), + pytest.param((None, None), None, 'blank', id='blank'), + pytest.param((None, None), None, 'incompatible', id='incompatible'), +]) +def test_create_generation_with_two_prompt_references(project, batched, orders, saved_orders, problem): store, pid, session = project - first, first_asset = text_material(project, title='First') - second, second_asset = text_material(project, title='Second', text=' ' if source_problem == 'blank' else 'v2') - second_id = uuid4() if source_problem == 'missing' else second.id - if source_problem == 'locked': + first, first_asset = image_material(project, title='First') + second, second_asset = text_material(project, title='Second', text=' ' if problem == 'blank' else 'v2') + second_id = uuid4() if problem == 'missing' else second.id + if problem == 'locked': locked = send(store, pid, 'canvas.update', session=session, versions=[ver('canvas_item', second)], itemId=second.id, locked=True) assert locked.status == 'applied', locked.issues spec_id, item_id = uuid4(), uuid4() reference_ids = [uuid4(), uuid4()] + kind = 'audio' if problem == 'incompatible' else 'image' + references = [ + dict(id=ref_id, projectId=pid, targetSpecId=spec_id, binding='follow_current', source=dict(id=source_id)) + for ref_id, source_id in zip(reference_ids, [first.id, second_id]) + ] + for reference, order in zip(references, orders): + if order is not None: + reference['order'] = order payload = dict( - spec=dict(id=spec_id, projectId=pid, kind='image', purpose='generation', promptContent=[ + spec=dict(id=spec_id, projectId=pid, kind=kind, purpose='generation', promptContent=[ dict(type='reference', referenceId=reference_ids[0]), dict(type='text', text=' and '), dict(type='reference', referenceId=reference_ids[1]), ]), - item=dict(id=item_id, projectId=pid, kind='image', + item=dict(id=item_id, projectId=pid, kind=kind, binding=dict(role='generation', objectRef=dict(id=spec_id))), - references=[dict(id=ref_id, projectId=pid, targetSpecId=spec_id, order=order, - binding='follow_current', source=dict(id=source_id)) - for order, (ref_id, source_id) in enumerate(zip(reference_ids, [first.id, second_id]))], + references=references, ) - before = store.snapshot(pid) + command_args = dict(type='canvas.createGeneration', payload=payload) if batched: - receipt = send(store, pid, 'creation.batch', session=session, operations=[ + command_args = dict(type='creation.batch', payload=dict(operations=[ dict(type='canvas.show', payload=dict(item=dict(id=uuid4(), projectId=pid, kind='group'))), - dict(type='canvas.createGeneration', payload=payload), - ]) - else: - receipt = send(store, pid, 'canvas.createGeneration', session=session, **payload) + command_args, + ])) + command = parse_command(dict(commandId=uuid4(), projectId=pid, **command_args)) + received = parse_command(command.model_dump(mode='json')) + before = store.snapshot(pid) + receipt = store.execute(received, session=session) - snapshot = CreationProjects(LocalProjects(store.local.repository)).snapshot(pid) + reloaded = CreationProjects(LocalProjects(store.local.repository)) + snapshot = reloaded.snapshot(pid) assert not snapshot.jobs and not receipt.jobIds - if source_problem is not None: + if problem is not None: expected_issue = { + 'order_conflict': ('invalid_input', None), 'missing': ('missing_object', second_id), 'locked': ('role_restricted', second_id), 'blank': ('reference_invalid', second_asset.id), - }[source_problem] + 'incompatible': ('reference_invalid', reference_ids[1]), + }[problem] assert receipt.status == 'rejected' assert [(issue.code, issue.objectId) for issue in receipt.issues] == [expected_issue] + if problem == 'order_conflict': + assert 'Reference order is duplicated for its target' in receipt.issues[0].message assert snapshot == before return @@ -447,9 +487,11 @@ def test_create_generation_with_two_prompt_references(project, batched, source_p spec = next(spec for spec in snapshot.generationSpecs if spec.id == spec_id) assert spec.prompt == '@First and @Second' assert [part.referenceId for part in spec.promptContent if part.type == 'reference'] == reference_ids + assert {ref.id: ref.order for ref in snapshot.references if ref.targetSpecId == spec_id} == dict(zip(reference_ids, saved_orders)) assert [(ref.referenceId, ref.asset.assetId) for ref in resolved_inputs(snapshot, spec_id)] == [ (reference_ids[0], first_asset.id), (reference_ids[1], second_asset.id), ] + assert reloaded.execute(command, session=session) == receipt def test_canvas_item_status_is_scoped_and_read_only(project): @@ -483,19 +525,8 @@ def test_canvas_item_wait_returns_on_change_and_timeout(project, monkeypatch): @pytest.mark.parametrize('binding', ['follow_current', 'pinned']) def test_canvas_reference_sources_create_a_connected_video_node(project, binding): store, pid, session = project - assets = CreationAssets(store) - image = BytesIO() - Image.new('RGB', (16, 16), 'blue').save(image, 'PNG') - handle = uuid4() - writer = assets.uploads.begin(pid, handle, session, 'reference.png', expected_kind='image') - writer.write(image.getvalue()) - writer.finish() - assert send(store, pid, 'asset.import', session=session, uploadHandle=handle, - name='reference.png', expectedKind='image').status == 'applied' - asset = store.snapshot(pid).assets[-1] - source_id = uuid4() - assert send(store, pid, 'canvas.show', session=session, item=dict(id=source_id, - projectId=pid, kind='image', binding=dict(role='material', objectRef=asset_ref(asset)))).status == 'applied' + source_item, asset = image_material(project, title='reference') + source_id = source_item.id canvas = CreationCanvas(store) before = store.snapshot(pid) sources = canvas.item_status(pid, source_id)['referenceSources'] From 3ed47cdc593c7b08460da2d5e5185d2eaff97a40 Mon Sep 17 00:00:00 2001 From: Barkly1te Date: Wed, 2 Dec 2026 15:10:48 +0800 Subject: [PATCH 3/7] [bugfix] creation: replay existing reference order receipts Keep omitted orders through command serialization. Match legacy receipts with their original fingerprint rule and use position-based orders for new commands. Separate the fingerprint formats so a changed order still conflicts on a new command ID replay. The new legacy direct and batch replay tests reproduced command_conflict before the change. Both pass now, and both current-record conflict cases still pass. --- .../application/creation_canvas.py | 2 +- .../src/opendirector/domain/creation/base.py | 4 +- .../opendirector/domain/creation/commands.py | 30 ++++++++--- .../infrastructure/creation_publication.py | 2 +- .../infrastructure/creation_records.py | 9 +++- tests/test_creation_canvas_service.py | 50 +++++++++++++++++++ 6 files changed, 85 insertions(+), 12 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 4d6c5aabb..6f650353d 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -580,7 +580,7 @@ def _mutate(self, data, kind, payload): self._mutate(data, 'generationSpec.create', SpecWrite(spec=payload.spec)) self._mutate(data, 'canvas.show', CanvasShow(item=payload.item, positionSpace=payload.positionSpace)) added_references = [] - for reference in payload.references: + for reference in payload.ordered_references(): if self._write_reference(data, 'reference.add', reference) is not None: added_references.append(reference) if added_references: diff --git a/packages/core/src/opendirector/domain/creation/base.py b/packages/core/src/opendirector/domain/creation/base.py index 42c5108cd..e92d5713f 100644 --- a/packages/core/src/opendirector/domain/creation/base.py +++ b/packages/core/src/opendirector/domain/creation/base.py @@ -67,9 +67,9 @@ class Point(Contract): y: Number = Field(default=0, description='Vertical coordinate.') -def digest(value: Contract, *, exclude=None) -> str: +def digest(value: Contract, *, exclude=None, context=None) -> str: """Stable normalized JSON identity. Persistence/idempotent replay is C03.""" - encoded = json.dumps(value.model_dump(mode='json', exclude=exclude), ensure_ascii=False, sort_keys=True, + encoded = json.dumps(value.model_dump(mode='json', exclude=exclude, context=context), ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode() return hashlib.sha256(encoded).hexdigest() diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 0452fff42..2c171f262 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -1,8 +1,9 @@ """Shared HTTP/Agent command and query schemas. No operation is executed here.""" +from hashlib import sha256 from typing import Annotated, Literal, Union from uuid import UUID -from pydantic import ConfigDict, Field, TypeAdapter, create_model, field_validator, model_validator +from pydantic import ConfigDict, Field, TypeAdapter, create_model, field_serializer, model_validator from .assets import AssetRef, MediaMetadata from .base import CanvasColor, Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique @@ -115,14 +116,24 @@ class CanvasCreateGeneration(CanvasPlacement): item: CanvasItem = Field(description='Visible item bound to spec.id with role=generation.') references: tuple[Reference, ...] = Field(default=(), description='Input references. Every canvas-derived reference must retain its source node: source.id for follow_current, sourceVersion for pinned. Never replace a canvas reference with an asset-only binding.') - @field_validator('references') - @classmethod - def fill_reference_orders(cls, references: tuple[Reference, ...]) -> tuple[Reference, ...]: + def ordered_references(self) -> tuple[Reference, ...]: return tuple( reference if 'order' in reference.model_fields_set else reference.model_copy(update={'order': position}) - for position, reference in enumerate(references) + for position, reference in enumerate(self.references) ) + @field_serializer('references', mode='wrap', when_used='json') + def serialize_reference_orders(self, references, serialize, info): + order_rule = (info.context or {}).get('reference_order') + if order_rule == 'position': + return serialize(self.ordered_references()) + values = serialize(references) + if order_rule != 'legacy': + for reference, value in zip(references, values): + if 'order' not in reference.model_fields_set: + value.pop('order', None) + return values + @model_validator(mode='after') def bindings(self): if not self.item.visible: @@ -507,8 +518,13 @@ def parse_command(value) -> Command: return COMMAND_ADAPTER.validate_python(value) -def command_fingerprint(command: Command) -> str: - return digest(command) +def command_fingerprint(command: Command, *, legacy: bool = False) -> str: + operations = command.payload.operations if command.type == 'creation.batch' else (command,) + if not legacy and any(operation.type == 'canvas.createGeneration' and len(operation.payload.references) > 1 + for operation in operations): + fingerprint = digest(command, context={'reference_order': 'position'}) + return sha256(f'reference-order-by-position:{fingerprint}'.encode()).hexdigest() + return digest(command, context={'reference_order': 'legacy'}) from opendirector.domain.timeline_errors import TimelineIssueCode diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index 0c7e57357..1c6d053c3 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -63,7 +63,7 @@ def _replay(records, command): record = next((item for item in records if item.command.commandId == command.commandId), None) if record is None: return None - if record.receipt.inputFingerprint != command_fingerprint(command): + if not record.matches_command(command): raise ProjectError('该 commandId 已用于不同输入,请使用新的命令标识。', 409, code='command_conflict') return record.receipt.model_copy(deep=True) diff --git a/packages/core/src/opendirector/infrastructure/creation_records.py b/packages/core/src/opendirector/infrastructure/creation_records.py index edc401c0a..241687378 100644 --- a/packages/core/src/opendirector/infrastructure/creation_records.py +++ b/packages/core/src/opendirector/infrastructure/creation_records.py @@ -37,6 +37,13 @@ class CommitRecord(Contract): receipt: CommandReceipt = Field(description='Immutable command execution receipt.') event: ProjectEvent | None = Field(description='Project change event, if emitted.') + def matches_command(self, command: Command) -> bool: + fingerprint = self.receipt.inputFingerprint + if fingerprint == command_fingerprint(command): + return True + return (fingerprint == command_fingerprint(command, legacy=True) + and fingerprint == command_fingerprint(self.command, legacy=True)) + def history_entry(self): """Detached user-history metadata. A source created off-canvas has no display edit to undo.""" if self.event is None: @@ -58,7 +65,7 @@ def consistent(self): if (self.command.projectId != self.snapshot.project.id or self.receipt.projectId != self.command.projectId or self.receipt.commandId != self.command.commandId - or self.receipt.inputFingerprint != command_fingerprint(self.command) + or not self.matches_command(self.command) or self.receipt.eventCursor != self.snapshot.eventCursor): raise ValueError('Commit identity is inconsistent') applied = self.receipt.status in {'applied', 'accepted'} diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index 9b95f58ba..9b9509de6 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -1,5 +1,6 @@ """Real committed commands: no alternate graph and no visible execution nodes.""" from io import BytesIO +import json from uuid import uuid4 from PIL import Image @@ -7,7 +8,9 @@ from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_canvas import CreationCanvas, asset_ref, resolved_inputs +from opendirector.domain.creation.base import digest from opendirector.domain.creation.commands import parse_command +from opendirector.domain.projects import ProjectError from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.infrastructure.local_projects import LocalProjects @@ -494,6 +497,53 @@ def test_create_generation_with_two_prompt_references(project, batched, orders, assert reloaded.execute(command, session=session) == receipt +@pytest.mark.parametrize('batched', [False, True], ids=['direct', 'batch']) +@pytest.mark.parametrize('legacy', [False, True], ids=['current', 'legacy']) +def test_create_generation_replay_uses_the_recorded_order_rule(project, batched, legacy): + store, pid, session = project + source, _ = image_material(project, 'Image') + text, _ = text_material(project) + spec_id = uuid4() + references = [ + dict(id=uuid4(), projectId=pid, targetSpecId=spec_id, order=order, + binding='follow_current', source=dict(id=item.id)) + for order, item in [(7, source), (0, text)] + ] + operation = dict(type='canvas.createGeneration', payload=dict( + spec=dict(id=spec_id, projectId=pid, kind='image', purpose='generation', prompt='Use these sources'), + item=dict(id=uuid4(), projectId=pid, kind='image', + binding=dict(role='generation', objectRef=dict(id=spec_id))), + references=references, + )) + arguments = dict(commandId=uuid4(), projectId=pid, **( + dict(type='creation.batch', payload=dict(operations=[operation])) if batched else operation + )) + command = parse_command(arguments) + receipt = store.execute(command, session=session) + assert receipt.status == 'applied', receipt.issues + before = store.snapshot(pid) + assert [ref.order for ref in before.references] == [7, 0] + if legacy: + path = store.root / 'Unified' / 'commits' / f'{command.commandId}.json' + record = json.loads(path.read_text(encoding='utf-8')) + record['receipt']['inputFingerprint'] = digest(command) + path.write_text(json.dumps(record), encoding='utf-8') + receipt = receipt.model_copy(update={'inputFingerprint': digest(command)}) + + store = CreationProjects(LocalProjects(store.local.repository)) + del references[1]['order'] + omitted = parse_command(arguments) + retry = parse_command(omitted.model_dump(mode='json')) + if legacy: + assert store.execute(retry) == receipt + references[1]['order'] = 1 + retry = parse_command(arguments) + with pytest.raises(ProjectError) as conflict: + store.execute(retry) + assert conflict.value.code == 'command_conflict' + assert store.snapshot(pid) == before + + def test_canvas_item_status_is_scoped_and_read_only(project): store, pid, session = project item, _ = text_material(project) From 2f7ac187c196300e1af856d08a95e6e931aec617 Mon Sep 17 00:00:00 2001 From: Barkly1te Date: Wed, 2 Dec 2026 17:18:24 +0800 Subject: [PATCH 4/7] [bugfix] creation: limit positional reference fingerprints Keep legacy fingerprints when every reference after the first has a nonzero order. A zero at any later position can represent an omitted value or an explicit zero under the old rule. Keep those inputs distinct and preserve replay of positional receipts. --- .../opendirector/domain/creation/commands.py | 18 ++++++++++++------ .../infrastructure/creation_records.py | 5 +++-- tests/test_creation_canvas_service.py | 6 ++++++ 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 2c171f262..3877f1298 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -518,13 +518,19 @@ def parse_command(value) -> Command: return COMMAND_ADAPTER.validate_python(value) -def command_fingerprint(command: Command, *, legacy: bool = False) -> str: - operations = command.payload.operations if command.type == 'creation.batch' else (command,) - if not legacy and any(operation.type == 'canvas.createGeneration' and len(operation.payload.references) > 1 - for operation in operations): - fingerprint = digest(command, context={'reference_order': 'position'}) +def command_fingerprint(command: Command, *, order_rule: Literal['legacy', 'position'] | None = None) -> str: + if order_rule is None: + operations = command.payload.operations if command.type == 'creation.batch' else (command,) + ambiguous_legacy_order = any( + operation.type == 'canvas.createGeneration' + and any(reference.order == 0 for reference in operation.payload.references[1:]) + for operation in operations + ) + order_rule = 'position' if ambiguous_legacy_order else 'legacy' + fingerprint = digest(command, context={'reference_order': order_rule}) + if order_rule == 'position': return sha256(f'reference-order-by-position:{fingerprint}'.encode()).hexdigest() - return digest(command, context={'reference_order': 'legacy'}) + return fingerprint from opendirector.domain.timeline_errors import TimelineIssueCode diff --git a/packages/core/src/opendirector/infrastructure/creation_records.py b/packages/core/src/opendirector/infrastructure/creation_records.py index 241687378..02be68341 100644 --- a/packages/core/src/opendirector/infrastructure/creation_records.py +++ b/packages/core/src/opendirector/infrastructure/creation_records.py @@ -41,8 +41,9 @@ def matches_command(self, command: Command) -> bool: fingerprint = self.receipt.inputFingerprint if fingerprint == command_fingerprint(command): return True - return (fingerprint == command_fingerprint(command, legacy=True) - and fingerprint == command_fingerprint(self.command, legacy=True)) + if fingerprint == command_fingerprint(command, order_rule='legacy'): + return fingerprint == command_fingerprint(self.command, order_rule='legacy') + return fingerprint == command_fingerprint(command, order_rule='position') def history_entry(self): """Detached user-history metadata. A source created off-canvas has no display edit to undo.""" diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index 9b9509de6..db78c0b9f 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -494,7 +494,13 @@ def test_create_generation_with_two_prompt_references(project, batched, orders, assert [(ref.referenceId, ref.asset.assetId) for ref in resolved_inputs(snapshot, spec_id)] == [ (reference_ids[0], first_asset.id), (reference_ids[1], second_asset.id), ] + if orders in ((0, 1), (None, 7)): + assert receipt.inputFingerprint == digest(received, context={'reference_order': 'legacy'}) assert reloaded.execute(command, session=session) == receipt + if orders[1] is None: + references[1]['order'] = saved_orders[1] + explicit_retry = parse_command(dict(commandId=command.commandId, projectId=pid, **command_args)) + assert reloaded.execute(explicit_retry, session=session) == receipt @pytest.mark.parametrize('batched', [False, True], ids=['direct', 'batch']) From 08d7ce936840a68f6f7c048d017072ec14db1bbc Mon Sep 17 00:00:00 2001 From: Barkly1te Date: Wed, 2 Dec 2026 18:02:39 +0800 Subject: [PATCH 5/7] [bugfix] creation: keep rejected reference receipts readable on rollback Persist effective orders and a legacy digest for ambiguous rejected commands. Keep the positional replay rule in the compatible commit envelope. A version 2 pending journal keeps older builds from rewriting that envelope during recovery. --- docs/development/lessons.md | 1 + .../opendirector/domain/creation/commands.py | 21 ++++-- .../infrastructure/creation_publication.py | 18 +++-- .../infrastructure/creation_records.py | 27 +++++-- tests/test_creation_canvas_service.py | 72 +++++++++++++++++++ 5 files changed, 124 insertions(+), 15 deletions(-) diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 9b06bfa4f..5c178f8aa 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -170,6 +170,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Trigger:** Adding defaulted fields to a model nested inside immutable job inputs or commands. - **Lesson:** [PR #563](https://github.com/ThinkFlowLab/OpenDirector/pull/563) added video and audio codec facts. Serialization inserted null codec fields into historical job inputs, changing their fingerprints and blocking project reads. - **Check:** Validate saved snapshots and command receipts from both sides of the schema change. Preserve the distinction between absent fields and explicitly stored nulls when either form is already part of a fingerprint. Verify that changed contents still fail integrity checks. +- **Rejected receipt follow-up:** [PR #636 review](https://github.com/ThinkFlowLab/OpenDirector/pull/636#discussion_r4767630305) found that a rejected command can write a fingerprint the older reader cannot verify even when the project snapshot stays unchanged. Test rollback with the rejection as the latest record, and verify same-ID replay and changed-input conflicts after reopening. For legacy-compatible rejections with materialized reference orders, finish recovery of a pending version 2 journal on the patched build before switching to an older build. ## A harness's own sandbox can block the CLI's path back to the app diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 3877f1298..577e533c9 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -518,15 +518,22 @@ def parse_command(value) -> Command: return COMMAND_ADAPTER.validate_python(value) +def has_ambiguous_reference_orders(command: Command) -> bool: + operations = command.payload.operations if command.type == 'creation.batch' else (command,) + return any( + operation.type == 'canvas.createGeneration' + and any(reference.order == 0 for reference in operation.payload.references[1:]) + for operation in operations + ) + + +def materialize_reference_orders(command: Command) -> Command: + return parse_command(command.model_dump(mode='json', context={'reference_order': 'position'})) + + def command_fingerprint(command: Command, *, order_rule: Literal['legacy', 'position'] | None = None) -> str: if order_rule is None: - operations = command.payload.operations if command.type == 'creation.batch' else (command,) - ambiguous_legacy_order = any( - operation.type == 'canvas.createGeneration' - and any(reference.order == 0 for reference in operation.payload.references[1:]) - for operation in operations - ) - order_rule = 'position' if ambiguous_legacy_order else 'legacy' + order_rule = 'position' if has_ambiguous_reference_orders(command) else 'legacy' fingerprint = digest(command, context={'reference_order': order_rule}) if order_rule == 'position': return sha256(f'reference-order-by-position:{fingerprint}'.encode()).hexdigest() diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index 1c6d053c3..cb07a7e71 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -13,7 +13,10 @@ from opendirector.domain.creation.base import Point, digest from opendirector.domain.creation.canvas import canvas_origin -from opendirector.domain.creation.commands import CanvasPlacementReceipt, Command, CommandReceipt, ProjectEvent, command_fingerprint +from opendirector.domain.creation.commands import ( + CanvasPlacementReceipt, Command, CommandReceipt, ProjectEvent, command_fingerprint, + has_ambiguous_reference_orders, materialize_reference_orders, +) from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.run_layout import reflow_runs from opendirector.domain.creation.validation import ContractError, validate_command, validate_published_plans @@ -137,6 +140,7 @@ def _commit(self, command, apply, session, source, files, deletes, with_history) record = self._make_record(command, manifest.head, snapshot, changed, source, issue, placements=placements) to_name = snapshot.project.name if command.type == 'project.rename' and changed else path.name intent = CommitIntent( + schemaVersion=2 if record.legacy_compatible_rejection else 1, fromName=path.name, toName=to_name, beforeFingerprint=digest(before), record=record, files=files if changed and issue is None else (), deletes=deletes if changed and issue is None else ()) @@ -149,15 +153,20 @@ def _commit(self, command, apply, session, source, files, deletes, with_history) @staticmethod def _make_record(command, head, snapshot, changed, source, issue=None, *, placements=()): + legacy_compatible_rejection = issue is not None and has_ambiguous_reference_orders(command) + if legacy_compatible_rejection: + command = materialize_reference_orders(command) job_ids = tuple(item['version'].id for item in changed if item['version'].objectType == 'job' and item['change'] == 'created' and next(job for job in snapshot.jobs if job.id == item['version'].id).status == 'queued') event = ProjectEvent(projectId=command.projectId, cursor=snapshot.eventCursor, commandId=command.commandId, source=source, changed=changed, jobIds=job_ids) if changed else None receipt = CommandReceipt(commandId=command.commandId, projectId=command.projectId, - inputFingerprint=command_fingerprint(command), status='rejected' if issue else 'accepted' if job_ids else 'applied' if changed else 'noop', + inputFingerprint=command_fingerprint(command, order_rule='legacy' if legacy_compatible_rejection else None), + status='rejected' if issue else 'accepted' if job_ids else 'applied' if changed else 'noop', changed=[item['version'] for item in changed], jobIds=job_ids, issues=[issue] if issue else [], eventCursor=snapshot.eventCursor, canvasPlacements=placements) - return CommitRecord(command=command, previousHead=head, snapshot=snapshot, receipt=receipt, event=event) + version = {} if legacy_compatible_rejection else {'schemaVersion': 1} + return CommitRecord(command=command, previousHead=head, snapshot=snapshot, receipt=receipt, event=event, **version) def _journal(self, project_id): base = directory(self.intents).resolve() @@ -265,7 +274,8 @@ def _finish(self, intent, *, validated_history=False): sync_directory(path) file = child(commits, f'{record.command.commandId}.json') if file.exists(): - if self._record(path, record.command.commandId) != record: + stored = self._record(path, record.command.commandId) + if stored != record or stored.legacy_compatible_rejection != record.legacy_compatible_rejection: raise ProjectError('已存在不同内容的提交记录,未覆盖。', 409, code='storage_unavailable') else: durable_json(file, record.model_dump(mode='json')) diff --git a/packages/core/src/opendirector/infrastructure/creation_records.py b/packages/core/src/opendirector/infrastructure/creation_records.py index 02be68341..aa2605e07 100644 --- a/packages/core/src/opendirector/infrastructure/creation_records.py +++ b/packages/core/src/opendirector/infrastructure/creation_records.py @@ -8,9 +8,9 @@ from typing import Literal from uuid import UUID -from pydantic import Field, model_validator +from pydantic import Field, model_serializer, model_validator -from opendirector.domain.creation.base import Contract, Digest, ObjectVersion +from opendirector.domain.creation.base import Contract, Digest, ObjectVersion, digest from opendirector.domain.creation.commands import Command, CommandReceipt, ProjectEvent, command_fingerprint from opendirector.domain.creation.index import object_index from opendirector.domain.creation.project import ProjectSnapshot @@ -30,15 +30,29 @@ class Manifest(Contract): class CommitRecord(Contract): - schemaVersion: Literal[1] = Field(default=1, description='Record schema version.') + schemaVersion: Literal[1] = Field(default=1, + description='Record schema version. An omitted version on a rejected receipt denotes stored effective orders.') command: Command = Field(description='Immutable command recorded in this commit.') previousHead: UUID | None = Field(description='Previous commit ID, or null for project creation.') snapshot: ProjectSnapshot = Field(description='Authoritative project snapshot.') receipt: CommandReceipt = Field(description='Immutable command execution receipt.') event: ProjectEvent | None = Field(description='Project change event, if emitted.') + @property + def legacy_compatible_rejection(self) -> bool: + return self.receipt.status == 'rejected' and 'schemaVersion' not in self.model_fields_set + + @model_serializer(mode='wrap', when_used='json') + def serialize_record(self, serialize): + value = serialize(self) + if self.legacy_compatible_rejection: + value.pop('schemaVersion', None) + return value + def matches_command(self, command: Command) -> bool: fingerprint = self.receipt.inputFingerprint + if self.legacy_compatible_rejection: + return fingerprint == digest(command, context={'reference_order': 'position'}) if fingerprint == command_fingerprint(command): return True if fingerprint == command_fingerprint(command, order_rule='legacy'): @@ -67,6 +81,8 @@ def consistent(self): or self.receipt.projectId != self.command.projectId or self.receipt.commandId != self.command.commandId or not self.matches_command(self.command) + or (self.legacy_compatible_rejection + and self.receipt.inputFingerprint != command_fingerprint(self.command, order_rule='legacy')) or self.receipt.eventCursor != self.snapshot.eventCursor): raise ValueError('Commit identity is inconsistent') applied = self.receipt.status in {'applied', 'accepted'} @@ -81,7 +97,8 @@ def consistent(self): class CommitIntent(Contract): - schemaVersion: Literal[1] = Field(default=1, description='Record schema version.') + schemaVersion: Literal[1, 2] = Field(default=1, + description='Journal schema version. Version 2 requires a reader that preserves the rejection replay rule.') fromName: str | None = Field(description='Original project directory name.') toName: str = Field(description='Destination project directory name.') beforeFingerprint: Digest | None = Field(description='Fingerprint of the project before this commit.') @@ -91,6 +108,8 @@ class CommitIntent(Contract): @model_validator(mode='after') def consistent(self): + if (self.schemaVersion == 2) != self.record.legacy_compatible_rejection: + raise ValueError('Journal version does not match the record replay rule') project_name(self.toName) if self.fromName is not None: project_name(self.fromName) diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index db78c0b9f..c925715fa 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -5,6 +5,7 @@ from PIL import Image import pytest +from pydantic import ValidationError from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_canvas import CreationCanvas, asset_ref, resolved_inputs @@ -12,6 +13,7 @@ from opendirector.domain.creation.commands import parse_command from opendirector.domain.projects import ProjectError from opendirector.infrastructure.creation_projects import CreationProjects +from opendirector.infrastructure.creation_records import CommitRecord from opendirector.infrastructure.local_projects import LocalProjects @@ -550,6 +552,76 @@ def test_create_generation_replay_uses_the_recorded_order_rule(project, batched, assert store.snapshot(pid) == before +@pytest.mark.parametrize('interrupted_at', [None, 'journaled', 'bundle_written'], ids=['saved', 'journal', 'bundle']) +@pytest.mark.parametrize('explicit_zero', [False, True], ids=['omitted', 'explicit-zero']) +@pytest.mark.parametrize('batched', [False, True], ids=['direct', 'batch']) +def test_rejected_generation_preserves_old_reader_and_strict_replay(project, monkeypatch, batched, + explicit_zero, interrupted_at): + store, pid, session = project + first, _ = text_material(project) + spec_id, command_id = uuid4(), uuid4() + references = [ + dict(id=uuid4(), projectId=pid, targetSpecId=spec_id, order=7, + binding='follow_current', source=dict(id=first.id)), + dict(id=uuid4(), projectId=pid, targetSpecId=spec_id, + binding='follow_current', source=dict(id=uuid4())), + ] + if explicit_zero: + references[1]['order'] = 0 + operation = dict(type='canvas.createGeneration', payload=dict( + spec=dict(id=spec_id, projectId=pid, kind='image', purpose='generation', prompt='Use both sources'), + item=dict(id=uuid4(), projectId=pid, kind='image', + binding=dict(role='generation', objectRef=dict(id=spec_id))), + references=references, + )) + arguments = dict(commandId=command_id, projectId=pid, **( + dict(type='creation.batch', payload=dict(operations=[operation])) if batched else operation + )) + command = parse_command(arguments) + before = store.snapshot(pid) + if interrupted_at is None: + receipt = store.execute(command, session=session) + else: + def interrupt(stage): + if stage == interrupted_at: + raise OSError('interrupted publication') + monkeypatch.setattr(store, '_checkpoint', interrupt) + with pytest.raises(OSError, match='interrupted publication'): + store.execute(command, session=session) + journal = json.loads((store.intents / f'{pid}.json').read_text(encoding='utf-8')) + assert journal['schemaVersion'] == 2 + assert 'schemaVersion' not in journal['record'] + store = CreationProjects(LocalProjects(store.local.repository)) + receipt = store.receipt(pid, command_id) + assert receipt.status == 'rejected' and receipt.issues[0].code == 'missing_object' + assert receipt.eventCursor == before.eventCursor and not receipt.jobIds + assert store.snapshot(pid) == before + + file = store.root / 'Unified' / 'commits' / f'{command_id}.json' + record = json.loads(file.read_text(encoding='utf-8')) + assert 'schemaVersion' not in record + assert receipt.inputFingerprint == digest(parse_command(record['command']), context={'reference_order': 'legacy'}) + stored = record['command']['payload'] + if batched: + stored = stored['operations'][0]['payload'] + assert [ref['order'] for ref in stored['references']] == [7, 0 if explicit_zero else 1] + + reloaded = CreationProjects(LocalProjects(store.local.repository)) + assert reloaded.execute(command) == receipt + if explicit_zero: + del references[1]['order'] + else: + references[1]['order'] = 0 + with pytest.raises(ProjectError) as conflict: + reloaded.execute(parse_command(arguments)) + assert conflict.value.code == 'command_conflict' + assert reloaded.snapshot(pid) == before + + del stored['references'][1]['order'] + with pytest.raises(ValidationError, match='Commit identity is inconsistent'): + CommitRecord.model_validate(record) + + def test_canvas_item_status_is_scoped_and_read_only(project): store, pid, session = project item, _ = text_material(project) From be2f312dc083a4bbbe946ee0fcdacf1b0d4a58a4 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 4 Dec 2026 13:05:29 +0800 Subject: [PATCH 6/7] [test] agent: cover atomic prompt reference creation ## summary Exercise two omitted reference orders through the Agent tool gateway. Verify that a missing source rejects the request without changing the project or creating jobs. --- tests/test_agent_gateway.py | 57 +++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/test_agent_gateway.py b/tests/test_agent_gateway.py index 6c984357a..431a7112d 100644 --- a/tests/test_agent_gateway.py +++ b/tests/test_agent_gateway.py @@ -9,6 +9,7 @@ from opendirector.agent.context import RunContext from opendirector.agent.gateway import ToolGateway, ToolResult from opendirector.agent.tools import AgentTools +from opendirector.domain.creation.commands import parse_command from opendirector.domain.projects import ProjectError from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.infrastructure.local_projects import LocalProjects @@ -50,6 +51,62 @@ def gateway(tmp_path): return ToolGateway(business, run) +@pytest.mark.anyio +async def test_agent_creates_two_prompt_references_with_omitted_orders(gateway): + projects, run = gateway.business.projects, gateway.run + project_id = str(run.project_id) + projects.execute(parse_command(dict(type='project.create', projectId=project_id, + commandId=uuid4(), payload={'name': 'Atomic references'}))) + projects.open(run.project_id, run.session) + + async def command(call_id, kind, payload): + return await gateway.call(call_id, 'execute_command', {'type': kind, 'payload': payload}) + + sources = [] + for name in ('Character', 'Setting'): + written = await command(name, 'asset.writeText', {'name': f'{name}.md', 'text': name}) + assert not written.error, written.value + asset = projects.snapshot(run.project_id).assets[-1] + source_id = str(uuid4()) + shown = await command(f'show-{name}', 'canvas.show', {'item': { + 'id': source_id, 'projectId': project_id, 'kind': 'text', 'title': name, + 'binding': {'role': 'material', 'objectRef': { + 'assetId': str(asset.id), 'revision': asset.revision, 'fingerprint': asset.fingerprint, 'kind': 'text', + }}, + }}) + assert not shown.error, shown.value + sources.append(source_id) + + def generation(second_source): + spec_id, item_id = str(uuid4()), str(uuid4()) + references = [ + {'id': str(uuid4()), 'projectId': project_id, 'targetSpecId': spec_id, + 'binding': 'follow_current', 'source': {'id': source_id}} + for source_id in (sources[0], second_source) + ] + return { + 'spec': {'id': spec_id, 'projectId': project_id, 'kind': 'text', 'purpose': 'generation', + 'promptContent': [{'type': 'reference', 'referenceId': ref['id']} for ref in references]}, + 'item': {'id': item_id, 'projectId': project_id, 'kind': 'text', + 'binding': {'role': 'generation', 'objectRef': {'id': spec_id}}}, + 'references': references, + } + + payload = generation(sources[1]) + applied = await command('create-with-references', 'canvas.createGeneration', payload) + assert applied.value['status'] == 'applied', applied.value + saved = projects.snapshot(run.project_id) + assert [(str(ref.id), ref.order) for ref in saved.references] == [ + (ref['id'], index) for index, ref in enumerate(payload['references']) + ] + assert any(str(item.id) == payload['item']['id'] for item in saved.canvasItems) + rejected = await command('missing-reference-source', 'canvas.createGeneration', generation(str(uuid4()))) + assert rejected.value['status'] == 'rejected' + assert rejected.value['issues'][0]['code'] == 'missing_object' + assert not saved.jobs + assert projects.snapshot(run.project_id) == saved + + @pytest.mark.anyio async def test_concurrent_replay_executes_once_and_conflicting_input_is_rejected(gateway, monkeypatch): entered, release = asyncio.Event(), asyncio.Event() From 44ef6d952ee02fddd106c358323aae00b401d9e0 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 4 Dec 2026 15:33:10 +0800 Subject: [PATCH 7/7] [refactor] storage: select replay rule from stored record ## summary Derive replay identity from the stored command and receipt. Use the same rule to validate a commit and compare retries while preserving existing fingerprints and journal formats. --- .../infrastructure/creation_records.py | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/packages/core/src/opendirector/infrastructure/creation_records.py b/packages/core/src/opendirector/infrastructure/creation_records.py index aa2605e07..114399af7 100644 --- a/packages/core/src/opendirector/infrastructure/creation_records.py +++ b/packages/core/src/opendirector/infrastructure/creation_records.py @@ -49,15 +49,27 @@ def serialize_record(self, serialize): value.pop('schemaVersion', None) return value - def matches_command(self, command: Command) -> bool: + def _replay_rule(self) -> Literal['legacy', 'position', 'legacy_compatible_rejection'] | None: fingerprint = self.receipt.inputFingerprint + legacy = command_fingerprint(self.command, order_rule='legacy') if self.legacy_compatible_rejection: - return fingerprint == digest(command, context={'reference_order': 'position'}) - if fingerprint == command_fingerprint(command): - return True - if fingerprint == command_fingerprint(command, order_rule='legacy'): - return fingerprint == command_fingerprint(self.command, order_rule='legacy') - return fingerprint == command_fingerprint(command, order_rule='position') + effective = digest(self.command, context={'reference_order': 'position'}) + return 'legacy_compatible_rejection' if fingerprint == legacy == effective else None + if fingerprint == legacy: + return 'legacy' + if fingerprint == command_fingerprint(self.command, order_rule='position'): + return 'position' + return None + + def matches_command(self, command: Command) -> bool: + rule = self._replay_rule() + if rule is None: + return False + if rule == 'legacy_compatible_rejection': + fingerprint = digest(command, context={'reference_order': 'position'}) + else: + fingerprint = command_fingerprint(command, order_rule=rule) + return self.receipt.inputFingerprint == fingerprint def history_entry(self): """Detached user-history metadata. A source created off-canvas has no display edit to undo.""" @@ -80,10 +92,8 @@ def consistent(self): if (self.command.projectId != self.snapshot.project.id or self.receipt.projectId != self.command.projectId or self.receipt.commandId != self.command.commandId - or not self.matches_command(self.command) - or (self.legacy_compatible_rejection - and self.receipt.inputFingerprint != command_fingerprint(self.command, order_rule='legacy')) - or self.receipt.eventCursor != self.snapshot.eventCursor): + or self.receipt.eventCursor != self.snapshot.eventCursor + or self._replay_rule() is None): raise ValueError('Commit identity is inconsistent') applied = self.receipt.status in {'applied', 'accepted'} if applied != (self.event is not None):