Repository navigation
fix(projects): keep media creation times across project file export, import and duplication - #10421
Pfannkuchensack wants to merge 3 commits into
Conversation
…nd import board.json v3 records each item's created_at; upload takes an optional created_at (UTC, future clamped, pre-1970 refused). The date subfolder strategy files backdated media under its stated date; timestamp_text pads years on every platform.
joshistoast
left a comment
There was a problem hiding this comment.
The approach is right: a stated created_at on the upload routes keeps the real dates, which ordered uploads would not. I found no production defect for files the real exporter writes. One thing blocks the merge, and two points need a decision.
Blocking
Nine existing tests fail on four py3.12 jobs (linux-cpu, macos-default, windows-cpu, windows-arm64). _run_upload in tests/app/api/test_video_upload_limits.py calls upload_video(...) directly without created_at, so the new validation receives FastAPI's Query default and raises AttributeError: 'Query' object has no attribute 'tzinfo'. Passing created_at=None there takes the file from 9 failed / 50 passed to 59 passed. Production is unaffected. The QA list ran tests/app/routers but not tests/app/api.
Needs a decision
- The reason given for the
board.jsonv3 bump is wrong (inline onproject-files.mdx). Item objects are not strict, so older builds would read an optional v2 field and drop it. With v3, every new export is refused by beta.3 and earlier. - Duplicate still scrambles gallery order.
/images/copyand/videos/copystamp each copy now, in name order, so a duplicated project shows the symptom this PR fixes for import. Passing the source record'screated_atthroughbackdated_momentintoget_subfolderandsavein bothcopymethods closes it with no API change. Project duplication is the only webv2 caller. A tracked follow-up is fine.
Minor
Inline, none blocking: impossible dates pass the reader, the export self-check message, where the created_at rules live, three test points, and the mock's rules.
Checked
- Local: the PR's listed backend suites plus
tests/app/apigave 4621 passed and the same 9 failures as CI.vitest run src/workbench/projectspassed 611. Ruff is clean. - Sound: UTC conversion, the future clamp, the 1970 floor, offset overflow, the
timestamp_textrewrite (identical for years 1000 and up), intermediates cleanup, v1/v2 import, and the generated API artifacts. - Not verified: import on a real backend followed by a gallery order comparison. The chain is covered piece by piece only.
The branch is also behind main.
| ), | ||
| ) -> VideoDTO: | ||
| """Uploads a video for the current user.""" | ||
| validate_upload_created_at(created_at, is_intermediate) |
There was a problem hiding this comment.
Blocking. This is where the nine test_video_upload_limits.py tests fail. They call upload_video(...) directly and omit created_at, so it arrives here as the Query default object. Pass created_at=None in the test's _run_upload.
There was a problem hiding this comment.
Fixed in 8112e39: _run_upload passes created_at=None. tests/app/api is part of the local run now.
| The v2 and v3 manifests may carry `minimumCanvasSchemaVersion`. This is the source project's monotonic compatibility floor, not merely the version of its live canvas. It may conservatively retain a higher requirement inherited from a legacy server record whose queue history is removed during canonical export. Export copies the acknowledged server floor, and import creates the new project with the greater of that floor and the requirement derived from the canonical imported document. An archive above this client's maximum is refused as soon as its manifest is read, before any other entry is parsed and before a staging board or any media upload exists. Older v2 archives omit the field and continue to derive their requirement from their document. | ||
|
|
||
| A malformed `board.json` is a different matter and is refused as `damaged`: half an enumeration is not a board. The entry carries its own `version: 1`, which is the *file's* version and not the API's — the snapshot endpoint returns `{items}` and nothing else, so neither format is pinned to the other. | ||
| A malformed `board.json` is a different matter and is refused as `damaged`: half an enumeration is not a board. The entry carries its own version (currently 3), which is the *file's* version and not the API's — the snapshot endpoint is unversioned, so neither format is pinned to the other. The entry is strict, so a field added to an existing version would make older readers refuse it as damaged; a new version makes them report it as newer than the app, which is what it is. |
There was a problem hiding this comment.
"The entry is strict, so a field added to an existing version would make older readers refuse it as damaged" does not hold for item fields. Only the entry and board objects are .strict(). zBoardItem is a plain z.object on main and at v7.0.0-beta.3, so an older reader would drop an optional createdAt and import with today's ordering.
Two options:
- An optional
createdAton v2 items. Old builds still open new exports. - Keep v3 as policy (never widen an existing version) and state the real reason and cost here and in the PR body: beta.3 and earlier refuse every new export.
Either way, the user guide (Users Guide/02.Projects/introduction.mdx) still says a file imports "on any Invoke installation".
There was a problem hiding this comment.
Went with the optional field: board.json stays at version 2, and items carry an optional createdAt. Older builds strip it and import as before. The docs now give the real reason (entry and boards are strict, items are not) and say that a file-level change still takes a new version. The user guide sentence holds again. A test in board.test.ts pins that item objects accept unknown keys, and zBoardItem has a comment saying why it must not become .strict().
| const zCreatedAt = z | ||
| .string() | ||
| .regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/, 'must be an ISO 8601 UTC timestamp') | ||
| // The server refuses a time before 1970, so no source can have one. | ||
| .refine((value) => Date.parse(value) >= 0, { message: 'must be a real timestamp, not before 1970' }); |
There was a problem hiding this comment.
Date.parse rolls impossible dates forward: 2026-02-30T00:00:00Z and …T24:00:00Z both pass here, and pydantic refuses both with 422. A damaged file then gets past the up-front check. Each bad item is dropped as upload-failed and the rest imports, where the docs promise a damaged refusal. Only hand-edited or corrupted files can hit this.
Suggest a round-trip refine, new Date(v).toISOString().slice(0, 19) === v.slice(0, 19), and one Feb 30 case in the refusal test.
There was a problem hiding this comment.
Added the round-trip refine. Feb 30 and T24:00 are now refused as damaged, with cases in board.test.ts.
| for (const item of boards.flatMap((board) => board.items)) { | ||
| const checked = zBoardItemV3.safeParse(item); | ||
|
|
||
| if (!checked.success) { | ||
| throw new Error( | ||
| `The project's board item ${item.name} does not fit board.json: ${checked.error.issues[0]?.message ?? 'malformed'}` | ||
| ); | ||
| } | ||
| } |
There was a problem hiding this comment.
One item that fails the schema aborts the whole export with a plain Error, and its English text ("…does not fit board.json…") becomes the toast. It is near-unreachable with a matching server, but a legacy row dated before 1970 (the CLI image importer writes file mtimes) would block export of that project. Suggest a typed error mapped to a translated string, or writing that item without a time.
There was a problem hiding this comment.
The exporter now writes createdAt only when it passes the reader's zCreatedAt, and writes the item without a time otherwise, so a legacy pre-1970 row no longer blocks the export. The plain Error is gone.
| def validate_upload_created_at(created_at: Optional[datetime], is_intermediate: bool) -> None: | ||
| """Refuses a stated creation time the server could not store, or one that has no purpose on an intermediate. | ||
| An intermediate is cleaned up by age, so a backdated one would skip the grace window it is owed; the time exists | ||
| to keep a gallery's order, and an intermediate is in no gallery. | ||
| """ | ||
| if created_at is None: | ||
| return | ||
| if is_intermediate: | ||
| raise HTTPException(status_code=422, detail="created_at cannot be set on an intermediate upload") | ||
| try: | ||
| backdated_moment(created_at) | ||
| except ValueError as error: | ||
| raise HTTPException(status_code=422, detail=f"created_at: {error}") from error |
There was a problem hiding this comment.
The rules run three times: here (result discarded), in the service (backdated_moment) and in the record store (backdated_timestamp_text). The clamp is idempotent, so this is harmless but redundant. The "no time on an intermediate" rule exists only here, in a module documented as request-size ceilings, and the service accepts the combination.
Suggest the service as the single owner: it normalises once and raises a typed error that the router maps to 422. The store then takes the normalised moment and calls timestamp_text, and backdated_timestamp_text can go. Not blocking.
There was a problem hiding this comment.
Done: services/shared/created_at.py is the single owner. The image and video services call resolve_created_at once, before anything is written, and raise InvalidCreatedAtError, which the routers map to 422. The intermediate rule lives there too. The record stores take the normalised moment and call timestamp_text. backdated_timestamp_text and the _limits.py check are gone. One consequence: a video with a refused time gets its 422 only after the body has been read and ingested. Only API misuse reaches that, and the temp files are removed in finally, so I kept one owner rather than adding an early call whose result is discarded.
| params={ | ||
| "video_category": "general", | ||
| "is_intermediate": False, | ||
| "project_id": project_id, | ||
| "created_at": "2020-05-06T08:00:00Z", | ||
| }, |
There was a problem hiding this comment.
This test covered project_id on an intermediate video upload, which is what the parameter is documented for. Switching it to is_intermediate: False removes the only router check of that path. Suggest restoring it and adding a separate video pass-through test that mirrors the image one.
Related: the clamp, the UTC conversion and "no time means now" are each asserted at three or four layers. The new test_videos_default.py::TestCreate cases reach _VideoService__invoker and assert only mock call arguments. One test per rule at its owning layer would cover the same regressions.
There was a problem hiding this comment.
Restored the project_id intermediate video test and added a separate video pass-through test. Each rule is now tested at its owning layer: the rules in test_created_at.py, placement and forwarding through the real image service, the stores only for "stores the given moment", and the router only for pass-through and the 422 mapping. The record-level sort tests and the extra "now" copies are removed. The video service has no real-storage fixture, so its two forwarding checks stay as mock tests.
| const timedBoardShape = (items) => | ||
| items.map((item) => `${item.kind}:${item.category}:${String(item.starred)}:${item.created_at}`).sort(); |
There was a problem hiding this comment.
This compares a sorted multiset of kind:category:starred:created_at. The source board has two image:general:false items, so swapping their times still passes. The check proves times survive, not that order does. Comparing the imported gallery's order with the source's would cover the bug this PR fixes.
There was a problem hiding this comment.
The journey now reads /gallery/items/ per board and compares the ordered sequences with the source's, for the import and for the duplicate. The fixture times are distinct, so swapping the two general images fails it.
| /** | ||
| * An upload's `created_at` as the server records it: UTC ISO text (a time without a zone is UTC, the future is clamped | ||
| * to now), undefined when absent, null when the server would refuse it with 422 (unparseable, or before 1970). | ||
| */ | ||
| const uploadCreatedAt = (url) => { | ||
| const stated = url.searchParams.get('created_at'); | ||
|
|
||
| if (stated === null) { | ||
| return undefined; | ||
| } | ||
|
|
||
| const moment = new Date(/^\d{4}-\d{2}-\d{2}T[\d:.]+$/.test(stated) ? `${stated}Z` : stated); | ||
|
|
||
| if (Number.isNaN(moment.getTime()) || moment.getTime() < 0) { | ||
| return null; | ||
| } | ||
|
|
||
| return new Date(Math.min(moment.getTime(), Date.now())).toISOString(); | ||
| }; |
There was a problem hiding this comment.
The mock differs from the server here:
- It accepts Feb 30.
- It does not refuse a time on an intermediate upload.
- It reads a space-separated naive time as local, not UTC.
- It clamps against real
Date.now()rather than the injectedclock. - It always emits three fraction digits; the server emits none or six.
Nothing exercises the 422 branch. Suggest matching the server on these, or dropping the validation, since Python owns the rules.
There was a problem hiding this comment.
Dropped the validation from the mock, since Python owns the rules. It stores the given created_at as is. Its copy endpoints keep the source time now, matching the server.
| is_intermediate: bool, | ||
| created_at: Optional[datetime] = None, | ||
| ) -> str: | ||
| moment = created_at or datetime.now() |
There was a problem hiding this comment.
Pre-existing, but now two clocks in one line. A stated time is filed under its UTC date, as the move planner computes. An ordinary upload still uses the host's local date, so near midnight on a non-UTC host it lands where the planner later wants to move it. datetime.now(timezone.utc) fixes it. It changes folders for new media, so a separate small PR is reasonable.
There was a problem hiding this comment.
Agreed. I left it out of this PR and will open a separate small one for datetime.now(timezone.utc).
…created-at # Conflicts: # invokeai/app/services/images/images_default.py # invokeai/app/services/videos/videos_default.py # tests/app/services/videos/test_videos_default.py
Items carry an optional createdAt in board.json v2; older builds ignore it. Copies keep the source time. The media services own the created_at rules and raise a typed error the upload routes answer with 422.
|
Thanks for the review. Addressed in 8112e39, after merging main:
The PR description is updated to match. |
Summary
Importing a
.invkproject file scrambled the gallery order of its boards. Duplicating a project did the same. The export recorded no creation time, the import uploaded every item concurrently, and the server stamped each upload or copy with the time it arrived. The gallery sorts bystarred, thencreated_at, so the new project showed its media in effectively random order.Board media now keeps its source creation time across export, import and duplication:
board.jsonitems carry an optionalcreatedAt(ISO 8601 UTC) in version 2. Item objects ignore unknown fields, so older builds still import these files, just without the times. The exporter writes a time only when the importer would accept it. An item with a legacy time (before 1970) is written without one instead of failing the export.GET /projects/{id}/board-snapshotreturnscreated_atfor each item.POST /images/uploadandPOST /videos/uploadtake an optionalcreated_atquery parameter. The media services own the rules:is_intermediate=true, is refused with 422./images/copyand/videos/copykeep the source's creation time.image_subfolder_strategy: date, media created with a stated time (an upload or a copy) is filed under that UTC date, so the move planner finds nothing to move.timestamp_textzero-pads every field explicitly. glibc's%Ydoes not pad years below 1000.Related Issues / Discussions
QA Instructions
uv run --no-sync pytest tests/app/api tests/app/routers tests/app/services/{images,videos,image_records,video_records,image_files,image_moves,project_records,shared,intermediates,gallery}passed. The only 3 failures were intests/app/routers/test_app_info.py. They fail locally wheneverinvokeai/frontend/webv2/distexists and pass on main under the same condition.pnpm exec vitest run src/workbench/projectspassed 608.pnpm lintandnode --test scripts/mock-backend-fixtures.test.mjspassed.pnpm test:project-filespassed. The journey now compares the gallery order of each board after import, and of each duplicated board, with the source's order.invokeai/frontend/api: regeneratedopenapi.jsonandschema.ts.pnpm lintandpnpm testpassed.INVOKEAI_TEST_DB_URL), the fullcheck:releasegate, or an import against a real backend followed by a gallery order comparison. That chain is covered piece by piece by the tests.Review
Resolved:
tests/app/api/test_video_upload_limits.pycalled the upload route withoutcreated_at.board.jsonno longer bumps its version; impossible dates such as Feb 30 are refused.Known limitations:
board_images.created_at), so after an import it can differ from the source.created_atgets its 422 only after the body is read and, for video, ingested. Only API misuse reaches this; the temporary files are removed.Compatibility / Rollout
board.jsonstays at version 2. Older builds strip the optionalcreatedAtand import as before. Files from older builds have no times; their items are stamped at upload, as today.Checklist
What's Newcopy (if doing a release after this PR)