Skip to content

fix(projects): keep media creation times across project file export, import and duplication - #10421

Open
Pfannkuchensack wants to merge 3 commits into
invoke-ai:mainfrom
Pfannkuchensack:fix/project-import-created-at
Open

Pfannkuchensack wants to merge 3 commits into
invoke-ai:mainfrom
Pfannkuchensack:fix/project-import-created-at

Conversation

@Pfannkuchensack

@Pfannkuchensack Pfannkuchensack commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Importing a .invk project 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 by starred, then created_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.json items carry an optional createdAt (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-snapshot returns created_at for each item.
  • POST /images/upload and POST /videos/upload take an optional created_at query parameter. The media services own the rules:
    • A time with a zone is converted to UTC. A time without a zone is read as UTC.
    • A time in the future is clamped to now.
    • A time before 1970, or one sent with is_intermediate=true, is refused with 422.
    • Without the parameter, nothing changes.
  • /images/copy and /videos/copy keep the source's creation time.
  • With 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_text zero-pads every field explicitly. glibc's %Y does not pad years below 1000.

Related Issues / Discussions

QA Instructions

  • Backend: 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 in tests/app/routers/test_app_info.py. They fail locally whenever invokeai/frontend/webv2/dist exists and pass on main under the same condition.
  • Frontend: pnpm exec vitest run src/workbench/projects passed 608. pnpm lint and node --test scripts/mock-backend-fixtures.test.mjs passed.
  • pnpm test:project-files passed. 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: regenerated openapi.json and schema.ts. pnpm lint and pnpm test passed.
  • Ruff check and format check are clean.
  • Manual: export a project with several images, import the file and duplicate the project, then compare gallery order with the source.
  • Not run: MySQL/MariaDB (INVOKEAI_TEST_DB_URL), the full check:release gate, 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:

  • An unpadded year on Linux could be stored and would sort above everything. Times before 1970 and timestamps that overflow during UTC conversion are refused.
  • The date subfolder used the current date while the record had the stated one.
  • tests/app/api/test_video_upload_limits.py called the upload route without created_at.
  • board.json no longer bumps its version; impossible dates such as Feb 30 are refused.
  • The rules have one owner, and each rule is tested at its owning layer.

Known limitations:

  • The project cover still follows when each item was placed on the board (board_images.created_at), so after an import it can differ from the source.
  • Items that share a millisecond can swap places, because ties fall back to the new names.
  • An upload with a refused created_at gets its 422 only after the body is read and, for video, ingested. Only API misuse reaches this; the temporary files are removed.
  • Ordinary uploads still choose the date folder from the host's local date, while stated times use UTC. That predates this PR and will get its own change.

Compatibility / Rollout

  • board.json stays at version 2. Older builds strip the optional createdAt and import as before. Files from older builds have no times; their items are stamped at upload, as today.
  • The API change is additive: an optional query parameter and a new response field. Generated artifacts are regenerated. No database migration is needed.

Checklist

  • The PR has a short but descriptive title, suitable for a changelog
  • Meaningful regression coverage added / updated where needed; obsolete tests/code removed
  • Persisted-state and API changes include required migrations / compatibility validation
  • Relevant performance/efficiency opportunities considered; material claims have evidence
  • Material review findings resolved and relevant checks rerun
  • Documentation added / updated (if applicable)
  • Updated What's New copy (if doing a release after this PR)

…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.
@github-actions github-actions Bot added api python PRs that change python files services PRs that change app services frontend PRs that change frontend files python-tests PRs that change python tests docs labels Nov 29, 2026
@lstein
lstein requested a review from joshistoast November 30, 2026 01:46
@lstein lstein added the 7.0.0 label Nov 30, 2026

@joshistoast joshistoast left a comment

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.

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

  1. The reason given for the board.json v3 bump is wrong (inline on project-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.
  2. Duplicate still scrambles gallery order. /images/copy and /videos/copy stamp each copy now, in name order, so a duplicated project shows the symptom this PR fixes for import. Passing the source record's created_at through backdated_moment into get_subfolder and save in both copy methods 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/api gave 4621 passed and the same 9 failures as CI. vitest run src/workbench/projects passed 611. Ruff is clean.
  • Sound: UTC conversion, the future clamp, the 1970 floor, offset overflow, the timestamp_text rewrite (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.

Comment thread invokeai/app/api/routers/videos.py Outdated
),
) -> VideoDTO:
"""Uploads a video for the current user."""
validate_upload_created_at(created_at, is_intermediate)

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

"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 createdAt on 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".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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().

Comment on lines +70 to +74
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' });

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added the round-trip refine. Feb 30 and T24:00 are now refused as damaged, with cases in board.test.ts.

Comment on lines +205 to +213
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'}`
);
}
}

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread invokeai/app/api/routers/_limits.py Outdated
Comment on lines +31 to +44
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

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +144 to +149
params={
"video_category": "general",
"is_intermediate": False,
"project_id": project_id,
"created_at": "2020-05-06T08:00:00Z",
},

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +148 to +149
const timedBoardShape = (items) =>
items.map((item) => `${item.kind}:${item.category}:${String(item.starred)}:${item.created_at}`).sort();

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +499 to +517
/**
* 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();
};

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.

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 injected clock.
  • 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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()

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@Pfannkuchensack Pfannkuchensack changed the title fix(projects): keep media creation times across project file export and import fix(projects): keep media creation times across project file export, import and duplication Dec 3, 2026
@Pfannkuchensack

Copy link
Copy Markdown
Member Author

Thanks for the review. Addressed in 8112e39, after merging main:

  • The blocking test_video_upload_limits.py failure is fixed.
  • board.json stays at version 2 with an optional createdAt per item, so older builds still open new exports.
  • Duplication now keeps the source creation times too: /images/copy and /videos/copy pass the source's created_at through the same rules into the subfolder and the record. The journey checks the duplicate's gallery order.
  • The minor points are answered inline. The UTC date folder for ordinary uploads will be a separate PR.

The PR description is updated to match.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

7.0.0 api docs frontend PRs that change frontend files python PRs that change python files python-tests PRs that change python tests services PRs that change app services

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants