From be0b14d0fb0d43d39c1215b9c3bc344d55aecc04 Mon Sep 17 00:00:00 2001 From: wangtiance Date: Mon, 30 Nov 2026 15:38:35 +0800 Subject: [PATCH] [bugfix] storage: preserve saved canvas fingerprints ## summary - Preserve missing codec fields when serializing historical metadata. - Keep explicit nulls and verified codec values in saved fingerprints. - Regress old job inputs and checkpoint receipts without rewriting existing projects. ## validation - Passed 111 Python tests, eight frontend tests, TypeScript checking, and generated contract verification. - Validated 1,146 local commit records and opened three affected project copies through the canvas API. Refs: #563 --- docs/development/lessons.md | 6 +++ .../opendirector/domain/creation/assets.py | 22 +++++++- src/contracts/creation.schema.json | 4 +- src/contracts/generated.ts | 4 +- tests/fixtures/creation-project.json | 24 +++------ tests/test_creation_contracts.py | 54 +++++++++++++++++++ 6 files changed, 89 insertions(+), 25 deletions(-) diff --git a/docs/development/lessons.md b/docs/development/lessons.md index daa78424b..f6785090e 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -156,3 +156,9 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Trigger:** Adding a nested input model to an Agent query. - **Lesson:** [PR #565](https://github.com/ThinkFlowLab/OpenDirector/pull/565) added Pipeline scopes to the query schema. Removing host-provided IDs from every definition raised `KeyError: 'queryId'` on a scope definition and prevented Agent turns from starting. - **Check:** Project host-owned fields out of the root query branches. Verify that the exposed tool schema preserves nested discriminators and required fields, and that an Agent turn can initialize its tool gateway. + +## Optional fields can change persisted fingerprints + +- **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. diff --git a/packages/core/src/opendirector/domain/creation/assets.py b/packages/core/src/opendirector/domain/creation/assets.py index 2dc056a0e..95ce2563b 100644 --- a/packages/core/src/opendirector/domain/creation/assets.py +++ b/packages/core/src/opendirector/domain/creation/assets.py @@ -1,8 +1,8 @@ """Stable file identities and frozen content references, without browser URLs.""" -from typing import Literal +from typing import ClassVar, Literal from uuid import UUID -from pydantic import Field, model_validator +from pydantic import Field, model_serializer, model_validator from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH from .base import Contract, Fingerprint, MediaKind, NonNegative, Positive, PositiveInt, ProjectEntity, Revision @@ -17,6 +17,8 @@ class AssetRef(Contract): class MediaMetadata(Contract): + _codec_fields: ClassVar[frozenset[str]] = frozenset({'videoCodec', 'audioCodecs'}) + mimeType: str = Field(min_length=1, max_length=255, description='Verified media MIME type.') size: int = Field(ge=0, strict=True, description='Content size in bytes.') width: PositiveInt | None = Field(default=None, description='Width in pixels.') @@ -29,6 +31,22 @@ class MediaMetadata(Contract): videoCodec: str | None = Field(default=None, min_length=1, max_length=64, description='Primary video stream codec name.') audioCodecs: tuple[str, ...] | None = Field(default=None, description='Audio stream codec names in stream order.') + @classmethod + def __get_pydantic_json_schema__(cls, core_schema, handler): + schema = super().__get_pydantic_json_schema__(core_schema, handler) + if handler.mode == 'serialization': + schema['required'] = [name for name in schema.get('required', ()) if name not in cls._codec_fields] + return schema + + @model_serializer(mode='wrap') + def preserve_codec_field_presence(self, serialize): + # Frozen job and command fingerprints include this metadata. Older + # records omit these keys, while newer records may store explicit nulls. + data = serialize(self) + for name in self._codec_fields - self.model_fields_set: + data.pop(name, None) + return data + @model_validator(mode='after') def dimensions(self): if (self.width is None) != (self.height is None): diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 62bccdf6a..886819cef 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -28344,9 +28344,7 @@ "frameRate", "hasAudio", "sampleRate", - "channels", - "videoCodec", - "audioCodecs" + "channels" ], "title": "MediaMetadata", "type": "object" diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 8b7e370a4..61f7ddf52 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -2853,8 +2853,8 @@ export interface MediaMetadata extends Contract { readonly hasAudio: boolean | null; readonly sampleRate: number | null; readonly channels: number | null; - readonly videoCodec: string | null; - readonly audioCodecs: ReadonlyArray | null; + readonly videoCodec?: string | null; + readonly audioCodecs?: ReadonlyArray | null; } export interface MediaPublicationOutput extends Contract { diff --git a/tests/fixtures/creation-project.json b/tests/fixtures/creation-project.json index a3fe9020b..a040daa0c 100644 --- a/tests/fixtures/creation-project.json +++ b/tests/fixtures/creation-project.json @@ -24,9 +24,7 @@ "frameRate": null, "hasAudio": null, "sampleRate": null, - "channels": null, - "videoCodec": null, - "audioCodecs": null + "channels": null }, "provenance": { "source": "upload", @@ -61,9 +59,7 @@ "frameRate": null, "hasAudio": null, "sampleRate": null, - "channels": null, - "videoCodec": null, - "audioCodecs": null + "channels": null }, "provenance": { "source": "upload", @@ -98,9 +94,7 @@ "frameRate": null, "hasAudio": null, "sampleRate": null, - "channels": null, - "videoCodec": null, - "audioCodecs": null + "channels": null }, "provenance": { "source": "upload", @@ -135,9 +129,7 @@ "frameRate": null, "hasAudio": null, "sampleRate": null, - "channels": null, - "videoCodec": null, - "audioCodecs": null + "channels": null }, "provenance": { "source": "upload", @@ -172,9 +164,7 @@ "frameRate": null, "hasAudio": null, "sampleRate": null, - "channels": null, - "videoCodec": null, - "audioCodecs": null + "channels": null }, "provenance": { "source": "upload", @@ -209,9 +199,7 @@ "frameRate": null, "hasAudio": null, "sampleRate": null, - "channels": null, - "videoCodec": null, - "audioCodecs": null + "channels": null }, "provenance": { "source": "generated", diff --git a/tests/test_creation_contracts.py b/tests/test_creation_contracts.py index 041a98355..422e012ac 100644 --- a/tests/test_creation_contracts.py +++ b/tests/test_creation_contracts.py @@ -1,4 +1,5 @@ """C02 boundary tests: roles, detached execution, retained editors and shared schemas.""" +from hashlib import sha256 import json from pathlib import Path import subprocess @@ -273,6 +274,59 @@ def test_frozen_execution_identity_excludes_presentation_and_ui_state(): ProjectSnapshot.model_validate(data) +@pytest.mark.parametrize('codecs', [ + pytest.param({}, id='before-codec-fields'), + pytest.param({'videoCodec': None, 'audioCodecs': None}, id='explicit-null-codecs'), + pytest.param({'videoCodec': 'h264', 'audioCodecs': ['aac']}, id='verified-codecs'), +]) +def test_saved_job_and_checkpoint_fingerprints_preserve_codec_field_presence(codecs): + from opendirector.infrastructure.creation_records import CommitRecord + + def stored_digest(data): + return sha256(json.dumps(data, ensure_ascii=False, sort_keys=True, + separators=(',', ':')).encode()).hexdigest() + + example = project_example() + saved = example.model_dump(mode='json') + job = saved['jobs'][0] + video = next(a for a in example.assets if a.kind == 'video') + snapshot = InputSnapshot.model_validate({ + **job['inputSnapshot'], + 'references': [{**resolved('video'), 'asset': asset_ref(video)}], + }) + raw = snapshot.model_dump(mode='json') + metadata = raw['references'][0]['metadata'] + metadata.pop('videoCodec', None) + metadata.pop('audioCodecs', None) + metadata.update(codecs) + next(a for a in saved['assets'] if a['kind'] == 'video')['metadata'].update(codecs) + canonical = snapshot.model_dump(mode='json', exclude={ + 'spec': {'revision', 'currentResultId'}, + 'references': {'__all__': {'name': True, 'sourceTitle': True, 'asset': {'revision'}, + 'sourceVersion': {'revision'}, 'documentVersion': {'revision'}}}, + }) + canonical['references'][0]['metadata'] = metadata + fingerprint = stored_digest(canonical) + job.update(inputSnapshot=raw, inputFingerprint=fingerprint) + saved['results'][0]['inputFingerprint'] = fingerprint + saved['assets'][-1]['provenance']['inputFingerprint'] = fingerprint + checkpoint = command('job.checkpoint', {'job': example.jobs[0]}).model_dump(mode='json') + checkpoint['payload']['job'] = job + receipt = CommandReceipt(projectId=PROJECT, commandId=uid(90), status='noop', + eventCursor=saved['eventCursor'], inputFingerprint=stored_digest(checkpoint)) + original = dict(command=checkpoint, previousHead=str(uid(89)), snapshot=saved, + receipt=receipt.model_dump(mode='json'), event=None) + + restored = CommitRecord.model_validate_json(json.dumps(original)) + assert restored.snapshot.jobs[0].inputFingerprint == fingerprint + assert restored.model_dump(mode='json')['command']['payload']['job']['inputSnapshot'] == raw + assert CommitRecord.model_validate_json(restored.model_dump_json()) == restored + + metadata['videoCodec'] = 'vp9' + with pytest.raises(ValidationError, match='Job input fingerprint differs'): + CommitRecord.model_validate_json(json.dumps(original)) + + def test_snapshot_excludes_selection_credentials_and_wrong_model(): snapshot = project_example().jobs[0].inputSnapshot.model_dump(mode='json') snapshot['model']['apiKey'] = 'private-key'