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
6 changes: 6 additions & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
22 changes: 20 additions & 2 deletions packages/core/src/opendirector/domain/creation/assets.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.')
Expand All @@ -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):
Expand Down
4 changes: 1 addition & 3 deletions src/contracts/creation.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -28344,9 +28344,7 @@
"frameRate",
"hasAudio",
"sampleRate",
"channels",
"videoCodec",
"audioCodecs"
"channels"
],
"title": "MediaMetadata",
"type": "object"
Expand Down
4 changes: 2 additions & 2 deletions src/contracts/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> | null;
readonly videoCodec?: string | null;
readonly audioCodecs?: ReadonlyArray<string> | null;
}

export interface MediaPublicationOutput extends Contract {
Expand Down
24 changes: 6 additions & 18 deletions tests/fixtures/creation-project.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@
"frameRate": null,
"hasAudio": null,
"sampleRate": null,
"channels": null,
"videoCodec": null,
"audioCodecs": null
"channels": null
},
"provenance": {
"source": "upload",
Expand Down Expand Up @@ -61,9 +59,7 @@
"frameRate": null,
"hasAudio": null,
"sampleRate": null,
"channels": null,
"videoCodec": null,
"audioCodecs": null
"channels": null
},
"provenance": {
"source": "upload",
Expand Down Expand Up @@ -98,9 +94,7 @@
"frameRate": null,
"hasAudio": null,
"sampleRate": null,
"channels": null,
"videoCodec": null,
"audioCodecs": null
"channels": null
},
"provenance": {
"source": "upload",
Expand Down Expand Up @@ -135,9 +129,7 @@
"frameRate": null,
"hasAudio": null,
"sampleRate": null,
"channels": null,
"videoCodec": null,
"audioCodecs": null
"channels": null
},
"provenance": {
"source": "upload",
Expand Down Expand Up @@ -172,9 +164,7 @@
"frameRate": null,
"hasAudio": null,
"sampleRate": null,
"channels": null,
"videoCodec": null,
"audioCodecs": null
"channels": null
},
"provenance": {
"source": "upload",
Expand Down Expand Up @@ -209,9 +199,7 @@
"frameRate": null,
"hasAudio": null,
"sampleRate": null,
"channels": null,
"videoCodec": null,
"audioCodecs": null
"channels": null
},
"provenance": {
"source": "generated",
Expand Down
54 changes: 54 additions & 0 deletions tests/test_creation_contracts.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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'
Expand Down
Loading