Skip to content
Open
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
1 change: 1 addition & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,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

Expand Down
144 changes: 76 additions & 68 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -512,6 +512,70 @@ 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')
source_key = reference_source_key(ref)
connected = [r for r in data['references'] if r['active'] and r['targetSpecId'] == ref['targetSpecId']
and reference_source_key(r) == source_key]
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)
if connected:
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 = reference_source_key(old) != source_key
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'] != ref['targetSpecId'] or changed_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'] for other in connected):
raise ContractError('reference_invalid', '该参考来源已连接到目标配置。', reference.id)
old.clear()
old.update(ref)
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':
Expand All @@ -524,8 +588,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))
for reference in payload.references:
self._mutate(data, 'reference.add', ReferenceWrite(reference=reference))
added_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:
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')
Expand Down Expand Up @@ -684,71 +754,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')
source_key = reference_source_key(ref)
connected = [r for r in data['references'] if r['active'] and r['targetSpecId'] == ref['targetSpecId']
and reference_source_key(r) == source_key]
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)
if connected:
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 = reference_source_key(old) != source_key
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'] != ref['targetSpecId'] or changed_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'] for other in connected):
raise ContractError('reference_invalid', '该参考来源已连接到目标配置。', payload.reference.id)
old.clear()
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'])
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/opendirector/domain/creation/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
43 changes: 40 additions & 3 deletions packages/core/src/opendirector/domain/creation/commands.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Shared HTTP/Agent command and query schemas. No operation is executed here."""
import json
import shlex
from hashlib import sha256
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_serializer, model_validator
from pydantic_core import PydanticCustomError

from .assets import AssetRef, MediaMetadata
Expand Down Expand Up @@ -129,6 +130,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.')

def ordered_references(self) -> tuple[Reference, ...]:
return tuple(
reference if 'order' in reference.model_fields_set else reference.model_copy(update={'order': position})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里在解析时就补了顺序,旧版已成功的原始请求重试同一个 command ID 时,可能在读回执前就变了指纹。PR 正文的 7, 0 例子已经观察到这个差异。能否让旧回执仍认原始请求,只对新命令应用位置默认值?建议回归同时断言旧重试返回原回执、新命令仍保存位置顺序。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3ed47cdc. The original request now keeps its omitted order through JSON serialization, and receipt lookup uses the fingerprint rule under which the command was recorded.

I retried the same request and command ID against one project created on ae5003b6. 8dcc33bd returned command_conflict. 3ed47cdc returns the exact original receipt and leaves the saved [7, 0] unchanged. A new command with the same order pattern saves [7, 1]. Changing the second order to explicit 0 on that new command’s ID still returns command_conflict. CLI inputs, before and after receipts, and canvas screenshots

The direct and batch replay regressions pass, along with all 22 focused cases and 586 related Python tests. The PR description also records that older builds cannot verify a new multi-reference record written by the patched build.

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:
Expand Down Expand Up @@ -588,8 +607,26 @@ def parse_command(value) -> Command:
return COMMAND_ADAPTER.validate_python(value)


def command_fingerprint(command: Command) -> str:
return digest(command)
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:
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()
return fingerprint


from opendirector.domain.timeline_errors import TimelineIssueCode
Expand Down
Loading
Loading