Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(api): add content revisions and reserved ids to workflow records

Josh Corbett2314a66c2383
diff --git a/invokeai/app/api/routers/workflows.py b/invokeai/app/api/routers/workflows.py
index 93e44bcd02..d366f13e17 100644
--- a/invokeai/app/api/routers/workflows.py
+++ b/invokeai/app/api/routers/workflows.py
@@ -15,12 +15,16 @@ from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
from invokeai.app.services.shared.workflow_call_compatibility import get_workflow_call_compatibility
from invokeai.app.services.workflow_records.workflow_records_common import (
Workflow,
+ WorkflowAccessDeniedError,
WorkflowCategory,
+ WorkflowIdConflictError,
+ WorkflowImmutableError,
WorkflowNotFoundError,
WorkflowRecordDTO,
WorkflowRecordListItemWithThumbnailDTO,
WorkflowRecordOrderBy,
WorkflowRecordWithThumbnailDTO,
+ WorkflowRevisionConflictError,
WorkflowWithoutID,
)
from invokeai.app.services.workflow_thumbnails.workflow_thumbnails_common import WorkflowThumbnailFileNotFoundException
@@ -73,24 +77,61 @@ def get_workflow(
operation_id="update_workflow",
responses={
200: {"model": WorkflowRecordDTO},
+ 400: {"description": "The body's workflow id does not match the URL, or the update is malformed"},
+ 403: {"description": "The workflow is bundled or belongs to another account"},
+ 404: {"description": "The workflow does not exist"},
+ 409: {"description": "The workflow's content revision no longer matches `expected_revision`"},
},
)
def update_workflow(
current_user: CurrentUserOrDefault,
+ workflow_id: str = Path(description="The workflow to update"),
workflow: Workflow = Body(description="The updated workflow", embed=True),
+ expected_revision: Optional[int] = Body(
+ default=None,
+ embed=True,
+ description="The content revision the client last observed; when set, a different stored revision refuses "
+ "the write with 409 instead of overwriting newer content.",
+ ),
) -> WorkflowRecordDTO:
- """Updates a workflow"""
+ """Updates a workflow's content and advances its revision."""
+ if workflow.id != workflow_id:
+ raise HTTPException(status_code=400, detail="The workflow id in the body does not match the URL")
+
try:
- existing = ApiDependencies.invoker.services.workflow_records.get(workflow.id)
+ existing = ApiDependencies.invoker.services.workflow_records.get(workflow_id)
except WorkflowNotFoundError:
raise HTTPException(status_code=404, detail="Workflow not found")
+ if existing.workflow.meta.category is WorkflowCategory.Default:
+ raise HTTPException(status_code=403, detail="Bundled workflows cannot be modified")
config = ApiDependencies.invoker.services.configuration
if config.multiuser:
if not current_user.is_admin and existing.user_id != current_user.user_id:
raise HTTPException(status_code=403, detail="Not authorized to update this workflow")
user_id = None if current_user.is_admin else current_user.user_id
- updated = ApiDependencies.invoker.services.workflow_records.update(workflow=workflow, user_id=user_id)
+ try:
+ updated = ApiDependencies.invoker.services.workflow_records.update(
+ workflow=workflow, user_id=user_id, expected_revision=expected_revision
+ )
+ except WorkflowNotFoundError:
+ raise HTTPException(status_code=404, detail="Workflow not found")
+ except WorkflowImmutableError:
+ raise HTTPException(status_code=403, detail="Bundled workflows cannot be modified")
+ except WorkflowAccessDeniedError:
+ raise HTTPException(status_code=403, detail="Not authorized to update this workflow")
+ except WorkflowRevisionConflictError as e:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "message": str(e),
+ "reason": "revision-conflict",
+ "current_revision": e.current_revision,
+ "expected_revision": e.expected_revision,
+ },
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
ApiDependencies.invoker.services.events.emit_workflow_updated(
workflow_id=updated.workflow_id,
user_id=updated.user_id,
@@ -114,6 +155,8 @@ def delete_workflow(
except WorkflowNotFoundError:
raise HTTPException(status_code=404, detail="Workflow not found")
+ if existing.workflow.meta.category is WorkflowCategory.Default:
+ raise HTTPException(status_code=403, detail="Bundled workflows cannot be deleted")
config = ApiDependencies.invoker.services.configuration
if config.multiuser:
if not current_user.is_admin and existing.user_id != current_user.user_id:
@@ -124,7 +167,14 @@ def delete_workflow(
# It's OK if the workflow has no thumbnail file. We can still delete the workflow.
pass
user_id = None if current_user.is_admin else current_user.user_id
- ApiDependencies.invoker.services.workflow_records.delete(workflow_id, user_id=user_id)
+ try:
+ ApiDependencies.invoker.services.workflow_records.delete(workflow_id, user_id=user_id)
+ except WorkflowNotFoundError:
+ raise HTTPException(status_code=404, detail="Workflow not found")
+ except WorkflowImmutableError:
+ raise HTTPException(status_code=403, detail="Bundled workflows cannot be deleted")
+ except WorkflowAccessDeniedError:
+ raise HTTPException(status_code=403, detail="Not authorized to delete this workflow")
ApiDependencies.invoker.services.events.emit_workflow_deleted(
workflow_id=existing.workflow_id,
user_id=existing.user_id,
@@ -137,25 +187,49 @@ def delete_workflow(
operation_id="create_workflow",
responses={
200: {"model": WorkflowRecordDTO},
+ 400: {"description": "The workflow or the reserved id is malformed"},
+ 409: {"description": "The reserved id already names a different workflow"},
},
)
def create_workflow(
current_user: CurrentUserOrDefault,
workflow: WorkflowWithoutID = Body(description="The workflow to create", embed=True),
+ workflow_id: Optional[str] = Body(
+ default=None,
+ embed=True,
+ description="A client-reserved UUID for the new record. Retrying the same creation with the same id returns "
+ "the record already created for it; another owner's record or different content under that id is a 409.",
+ ),
) -> WorkflowRecordDTO:
"""Creates a workflow"""
# In single-user mode, workflows are owned by 'system' and shared by default so all legacy/single-user
# workflows remain visible. In multiuser mode, workflows are private to the creator by default.
config = ApiDependencies.invoker.services.configuration
is_public = not config.multiuser
- created = ApiDependencies.invoker.services.workflow_records.create(
- workflow=workflow, user_id=current_user.user_id, is_public=is_public
- )
- ApiDependencies.invoker.services.events.emit_workflow_created(
- workflow_id=created.workflow_id,
- user_id=created.user_id,
- is_public=created.is_public,
- )
+ # A retried creation that finds its record already made emits no second event: the first write emitted one.
+ is_retry = False
+ if workflow_id is not None:
+ try:
+ ApiDependencies.invoker.services.workflow_records.get(workflow_id)
+ is_retry = True
+ except WorkflowNotFoundError:
+ pass
+ try:
+ created = ApiDependencies.invoker.services.workflow_records.create(
+ workflow=workflow, user_id=current_user.user_id, is_public=is_public, workflow_id=workflow_id
+ )
+ except WorkflowIdConflictError:
+ raise HTTPException(
+ status_code=409, detail={"message": "The workflow id is already in use", "reason": "id-conflict"}
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ if not is_retry:
+ ApiDependencies.invoker.services.events.emit_workflow_created(
+ workflow_id=created.workflow_id,
+ user_id=created.user_id,
+ is_public=created.is_public,
+ )
return created
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_26_add_workflow_revision.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_26_add_workflow_revision.py
new file mode 100644
index 0000000000..3dabd93365
--- /dev/null
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_26_add_workflow_revision.py
@@ -0,0 +1,20 @@
+"""Give every library workflow a monotonic content revision so explicit template updates can refuse stale writes."""
+
+import sqlite3
+
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+
+
+def _add_workflow_revision(cursor: sqlite3.Cursor) -> None:
+ cursor.execute("PRAGMA table_info(workflow_library);")
+ columns = {row[1] for row in cursor.fetchall()}
+ if "revision" not in columns:
+ cursor.execute("ALTER TABLE workflow_library ADD COLUMN revision INTEGER NOT NULL DEFAULT 1;")
+
+
+def build_migration() -> Migration:
+ return Migration(
+ id="2026_09_26_add_workflow_revision",
+ depends_on="2026_09_24_drop_intermediates_operations",
+ callback=_add_workflow_revision,
+ )
diff --git a/invokeai/app/services/workflow_records/workflow_records_base.py b/invokeai/app/services/workflow_records/workflow_records_base.py
index eca954a0d5..d7c3196f1f 100644
--- a/invokeai/app/services/workflow_records/workflow_records_base.py
+++ b/invokeai/app/services/workflow_records/workflow_records_base.py
@@ -28,13 +28,28 @@ class WorkflowRecordsStorageBase(ABC):
workflow: WorkflowWithoutID,
user_id: str = WORKFLOW_LIBRARY_DEFAULT_USER_ID,
is_public: bool = False,
+ workflow_id: Optional[str] = None,
) -> WorkflowRecordDTO:
- """Creates a workflow."""
+ """Creates a workflow at revision 1.
+
+ `workflow_id` is an optional client-reserved UUID that makes creation retry-safe: a record that already
+ carries it is returned as-is when the same owner submitted the same content, and any other collision raises
+ `WorkflowIdConflictError`.
+ """
pass
@abstractmethod
- def update(self, workflow: Workflow, user_id: Optional[str] = None) -> WorkflowRecordDTO:
- """Updates a workflow. When user_id is provided, the UPDATE is scoped to that user."""
+ def update(
+ self, workflow: Workflow, user_id: Optional[str] = None, expected_revision: Optional[int] = None
+ ) -> WorkflowRecordDTO:
+ """Replaces a workflow's content and increments its revision, atomically with authorization and reference
+ indexing.
+
+ When `user_id` is provided the write is refused (`WorkflowAccessDeniedError`) unless that user owns the
+ record. When `expected_revision` is provided the write is refused (`WorkflowRevisionConflictError`) unless
+ the stored revision still matches. Bundled workflows raise `WorkflowImmutableError` regardless of the
+ submitted category.
+ """
pass
@abstractmethod
diff --git a/invokeai/app/services/workflow_records/workflow_records_common.py b/invokeai/app/services/workflow_records/workflow_records_common.py
index c0d0b87a26..b9db4e5a5f 100644
--- a/invokeai/app/services/workflow_records/workflow_records_common.py
+++ b/invokeai/app/services/workflow_records/workflow_records_common.py
@@ -23,6 +23,42 @@ class WorkflowNotFoundError(Exception):
"""Raised when a workflow is not found"""
+class WorkflowImmutableError(Exception):
+ """Raised when a write targets a bundled (default) workflow, which the server never lets anyone modify."""
+
+ def __init__(self, workflow_id: str) -> None:
+ self.workflow_id = workflow_id
+ super().__init__(f"Workflow {workflow_id} is a bundled workflow and cannot be modified")
+
+
+class WorkflowAccessDeniedError(Exception):
+ """Raised when a scoped write targets a workflow another account owns."""
+
+ def __init__(self, workflow_id: str) -> None:
+ self.workflow_id = workflow_id
+ super().__init__(f"Workflow {workflow_id} is owned by another account")
+
+
+class WorkflowRevisionConflictError(Exception):
+ """Raised when an update carries a stale content revision (another writer saved first)."""
+
+ def __init__(self, workflow_id: str, expected_revision: int, current_revision: int) -> None:
+ self.workflow_id = workflow_id
+ self.expected_revision = expected_revision
+ self.current_revision = current_revision
+ super().__init__(
+ f"Workflow {workflow_id} is at revision {current_revision}; the update expected revision {expected_revision}"
+ )
+
+
+class WorkflowIdConflictError(Exception):
+ """Raised when a client-reserved workflow id already names a record that is not the same request."""
+
+ def __init__(self, workflow_id: str) -> None:
+ self.workflow_id = workflow_id
+ super().__init__(f"Workflow id {workflow_id} is already in use")
+
+
class WorkflowRecordOrderBy(str, Enum, metaclass=MetaEnum):
"""The order by options for workflow records"""
@@ -127,6 +163,7 @@ class WorkflowRecordDTOBase(BaseModel):
)
user_id: str = Field(description="The id of the user who owns this workflow.")
is_public: bool = Field(description="Whether this workflow is shared with all users.")
+ revision: int = Field(description="Monotonic content revision; every write of the workflow document increments it.")
class WorkflowRecordDTO(WorkflowRecordDTOBase):
diff --git a/invokeai/app/services/workflow_records/workflow_records_sqlite.py b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
index 29e4dc43e0..1e028a3e48 100644
--- a/invokeai/app/services/workflow_records/workflow_records_sqlite.py
+++ b/invokeai/app/services/workflow_records/workflow_records_sqlite.py
@@ -1,4 +1,5 @@
import sqlite3
+import uuid
from pathlib import Path
from typing import Optional
@@ -15,12 +16,16 @@ from invokeai.app.services.workflow_records.workflow_records_base import Workflo
from invokeai.app.services.workflow_records.workflow_records_common import (
WORKFLOW_LIBRARY_DEFAULT_USER_ID,
Workflow,
+ WorkflowAccessDeniedError,
WorkflowCategory,
+ WorkflowIdConflictError,
+ WorkflowImmutableError,
WorkflowNotFoundError,
WorkflowRecordDTO,
WorkflowRecordListItemDTO,
WorkflowRecordListItemDTOValidator,
WorkflowRecordOrderBy,
+ WorkflowRevisionConflictError,
WorkflowValidator,
WorkflowWithoutID,
)
@@ -28,6 +33,10 @@ from invokeai.app.util.misc import uuid_string
SQL_TIME_FORMAT = "%Y-%m-%d %H:%M:%f"
+_RECORD_COLUMNS = (
+ "workflow_id, workflow, name, created_at, updated_at, opened_at, last_run_at, user_id, is_public, revision"
+)
+
class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
def __init__(self, db: SqliteDatabase) -> None:
@@ -39,17 +48,18 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
self._sync_default_workflows()
def get(self, workflow_id: str) -> WorkflowRecordDTO:
- """Gets a workflow by ID. Updates the opened_at column."""
+ """Gets a workflow by ID."""
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- SELECT workflow_id, workflow, name, created_at, updated_at, opened_at, last_run_at, user_id, is_public
- FROM workflow_library
- WHERE workflow_id = ?;
- """,
- (workflow_id,),
- )
- row = cursor.fetchone()
+ return self._get_on_cursor(cursor, workflow_id)
+
+ @staticmethod
+ def _get_on_cursor(cursor: sqlite3.Cursor, workflow_id: str) -> WorkflowRecordDTO:
+ """Reads one record on the caller's transaction; `get()` on an open transaction would commit it early."""
+ cursor.execute(
+ f"SELECT {_RECORD_COLUMNS} FROM workflow_library WHERE workflow_id = ?;",
+ (workflow_id,),
+ )
+ row = cursor.fetchone()
if row is None:
raise WorkflowNotFoundError(f"Workflow with id {workflow_id} not found")
return WorkflowRecordDTO.from_dict(dict(row))
@@ -59,91 +69,129 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
workflow: WorkflowWithoutID,
user_id: str = WORKFLOW_LIBRARY_DEFAULT_USER_ID,
is_public: bool = False,
+ workflow_id: Optional[str] = None,
) -> WorkflowRecordDTO:
if workflow.meta.category is WorkflowCategory.Default:
raise ValueError("Default workflows cannot be created via this method")
+ if workflow_id is not None:
+ try:
+ uuid.UUID(workflow_id)
+ except ValueError as e:
+ raise ValueError("A reserved workflow id must be a UUID") from e
- workflow_with_id = Workflow(**workflow.model_dump(), id=uuid_string())
+ workflow_with_id = Workflow(**workflow.model_dump(), id=workflow_id or uuid_string())
document_json = workflow_with_id.model_dump_json()
references = extract_media_references_from_json(document_json)
with self._db.transaction() as cursor:
- cursor.execute(
- """--sql
- INSERT OR IGNORE INTO workflow_library (
- workflow_id,
- workflow,
- user_id,
- is_public
+ if workflow_id is not None:
+ existing = self._match_reserved_record(cursor, workflow_with_id, user_id)
+ if existing is not None:
+ return existing
+ try:
+ cursor.execute(
+ """--sql
+ INSERT INTO workflow_library (
+ workflow_id,
+ workflow,
+ user_id,
+ is_public,
+ revision
+ )
+ VALUES (?, ?, ?, ?, 1);
+ """,
+ (workflow_with_id.id, document_json, user_id, is_public),
)
- VALUES (?, ?, ?, ?);
- """,
- (workflow_with_id.id, document_json, user_id, is_public),
- )
+ except sqlite3.IntegrityError as e:
+ # Only a reserved id can collide; a generated one is unique for practical purposes.
+ raise WorkflowIdConflictError(workflow_with_id.id) from e
self._index_references(cursor, workflow_with_id.id, references, user_id=user_id)
- return self.get(workflow_with_id.id)
+ return self._get_on_cursor(cursor, workflow_with_id.id)
- def update(self, workflow: Workflow, user_id: Optional[str] = None) -> WorkflowRecordDTO:
+ @staticmethod
+ def _match_reserved_record(cursor: sqlite3.Cursor, workflow: Workflow, user_id: str) -> Optional[WorkflowRecordDTO]:
+ """A retried creation is accepted only when the record it finds is this owner's identical submission.
+
+ Any other record under the id is a conflict; its content and owner are not revealed to the caller.
+ """
+ cursor.execute(
+ f"SELECT {_RECORD_COLUMNS} FROM workflow_library WHERE workflow_id = ?;",
+ (workflow.id,),
+ )
+ row = cursor.fetchone()
+ if row is None:
+ return None
+ existing = WorkflowRecordDTO.from_dict(dict(row))
+ if existing.user_id != user_id or existing.workflow.model_dump() != workflow.model_dump():
+ raise WorkflowIdConflictError(workflow.id)
+ return existing
+
+ def update(
+ self, workflow: Workflow, user_id: Optional[str] = None, expected_revision: Optional[int] = None
+ ) -> WorkflowRecordDTO:
if workflow.meta.category is WorkflowCategory.Default:
- raise ValueError("Default workflows cannot be updated")
+ raise ValueError("A workflow cannot be updated into the default category")
document_json = workflow.model_dump_json()
references = extract_media_references_from_json(document_json)
with self._db.transaction() as cursor:
- if user_id is not None:
- cursor.execute(
- """--sql
- UPDATE workflow_library
- SET workflow = ?
- WHERE workflow_id = ? AND category = 'user' AND user_id = ?;
- """,
- (document_json, workflow.id, user_id),
- )
- else:
- cursor.execute(
- """--sql
- UPDATE workflow_library
- SET workflow = ?
- WHERE workflow_id = ? AND category = 'user';
- """,
- (document_json, workflow.id),
- )
- if cursor.rowcount:
- self._index_references(
- cursor,
- workflow.id,
- references,
- user_id=user_id if user_id is not None else self._owner_of(cursor, workflow.id),
- )
- return self.get(workflow.id)
+ # `category` is generated from the stored JSON, so it still describes the record as it is, not as
+ # the request would rewrite it.
+ cursor.execute(
+ "SELECT category, user_id, revision FROM workflow_library WHERE workflow_id = ?;",
+ (workflow.id,),
+ )
+ row = cursor.fetchone()
+ if row is None:
+ raise WorkflowNotFoundError(f"Workflow with id {workflow.id} not found")
+ stored_category, owner_id, current_revision = row
+ if stored_category == WorkflowCategory.Default.value:
+ raise WorkflowImmutableError(workflow.id)
+ owner = str(owner_id) if owner_id is not None else WORKFLOW_LIBRARY_DEFAULT_USER_ID
+ if user_id is not None and owner != user_id:
+ raise WorkflowAccessDeniedError(workflow.id)
+ if expected_revision is not None and current_revision != expected_revision:
+ raise WorkflowRevisionConflictError(workflow.id, expected_revision, current_revision)
- def delete(self, workflow_id: str, user_id: Optional[str] = None) -> None:
- if self.get(workflow_id).workflow.meta.category is WorkflowCategory.Default:
- raise ValueError("Default workflows cannot be deleted")
+ cursor.execute(
+ """--sql
+ UPDATE workflow_library
+ SET workflow = ?, revision = revision + 1
+ WHERE workflow_id = ? AND revision = ?;
+ """,
+ (document_json, workflow.id, current_revision),
+ )
+ if cursor.rowcount == 0:
+ # Another connection won between the read and this compare-and-swap.
+ cursor.execute("SELECT revision FROM workflow_library WHERE workflow_id = ?;", (workflow.id,))
+ raced = cursor.fetchone()
+ if raced is None:
+ raise WorkflowNotFoundError(f"Workflow with id {workflow.id} not found")
+ raise WorkflowRevisionConflictError(workflow.id, expected_revision or current_revision, raced[0])
+ self._index_references(cursor, workflow.id, references, user_id=owner)
+ return self._get_on_cursor(cursor, workflow.id)
+ def delete(self, workflow_id: str, user_id: Optional[str] = None) -> None:
with self._db.transaction() as cursor:
- if user_id is not None:
- cursor.execute(
- """--sql
- DELETE from workflow_library
- WHERE workflow_id = ? AND category = 'user' AND user_id = ?;
- """,
- (workflow_id, user_id),
- )
- else:
- cursor.execute(
- """--sql
- DELETE from workflow_library
- WHERE workflow_id = ? AND category = 'user';
- """,
- (workflow_id,),
- )
- if cursor.rowcount:
- # The row is gone, so its owner is the only fact left to delete by; every owner's
- # rows for this id are dropped since workflow ids are globally unique.
- cursor.execute(
- "DELETE FROM media_references WHERE owner_kind = 'workflow' AND owner_id = ?;",
- (workflow_id,),
- )
+ cursor.execute(
+ "SELECT category, user_id FROM workflow_library WHERE workflow_id = ?;",
+ (workflow_id,),
+ )
+ row = cursor.fetchone()
+ if row is None:
+ raise WorkflowNotFoundError(f"Workflow with id {workflow_id} not found")
+ stored_category, owner_id = row
+ if stored_category == WorkflowCategory.Default.value:
+ raise WorkflowImmutableError(workflow_id)
+ owner = str(owner_id) if owner_id is not None else WORKFLOW_LIBRARY_DEFAULT_USER_ID
+ if user_id is not None and owner != user_id:
+ raise WorkflowAccessDeniedError(workflow_id)
+ cursor.execute("DELETE from workflow_library WHERE workflow_id = ?;", (workflow_id,))
+ # The row is gone, so its owner is the only fact left to delete by; every owner's
+ # rows for this id are dropped since workflow ids are globally unique.
+ cursor.execute(
+ "DELETE FROM media_references WHERE owner_kind = 'workflow' AND owner_id = ?;",
+ (workflow_id,),
+ )
return None
def update_is_public(self, workflow_id: str, is_public: bool, user_id: Optional[str] = None) -> WorkflowRecordDTO:
@@ -170,6 +218,8 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
elif not is_public and "shared" in tags_list:
tags_list.remove("shared")
updated_workflow = workflow.model_copy(update={"tags": ", ".join(tags_list)})
+ # Visibility is bookkeeping: the `shared` tag rewrite does not advance the content revision, so
+ # an editor holding the previous revision is not asked to resolve a conflict it cannot see.
cursor.execute(
"""--sql
UPDATE workflow_library
@@ -177,7 +227,7 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
""",
(updated_workflow.model_dump_json(), is_public, workflow_id),
)
- return self.get(workflow_id)
+ return self._get_on_cursor(cursor, workflow_id)
@staticmethod
def _index_references(
@@ -188,12 +238,6 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
cursor, owner_kind="workflow", user_id=user_id, owner_id=workflow_id, references=references
)
- @staticmethod
- def _owner_of(cursor: sqlite3.Cursor, workflow_id: str) -> str:
- cursor.execute("SELECT user_id FROM workflow_library WHERE workflow_id = ?;", (workflow_id,))
- row = cursor.fetchone()
- return str(row[0]) if row is not None and row[0] is not None else WORKFLOW_LIBRARY_DEFAULT_USER_ID
-
def get_many(
self,
order_by: WorkflowRecordOrderBy,
@@ -227,7 +271,8 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
last_run_at,
tags,
user_id,
- is_public
+ is_public,
+ revision
FROM workflow_library
"""
count_query = "SELECT COUNT(*) FROM workflow_library"
@@ -589,41 +634,36 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
workflows_from_file.append(workflow_from_file)
- try:
- workflow_from_db = self.get(workflow_from_file.id).workflow
- if workflow_from_file != workflow_from_db:
- self._invoker.services.logger.debug(
- f"Updating library workflow {workflow_from_file.name} ({workflow_from_file.id})"
- )
- workflows_to_update.append(workflow_from_file)
- continue
- except WorkflowNotFoundError:
+ # Read on this cursor: `get()` would open a nested transaction and commit this one early.
+ cursor.execute("SELECT workflow FROM workflow_library WHERE workflow_id = ?;", (workflow_from_file.id,))
+ row = cursor.fetchone()
+ if row is None:
self._invoker.services.logger.debug(
f"Adding missing default workflow {workflow_from_file.name} ({workflow_from_file.id})"
)
workflows_to_add.append(workflow_from_file)
continue
+ if workflow_from_file != WorkflowValidator.validate_json(row[0]):
+ self._invoker.services.logger.debug(
+ f"Updating library workflow {workflow_from_file.name} ({workflow_from_file.id})"
+ )
+ workflows_to_update.append(workflow_from_file)
- library_workflows_from_db = self.get_many(
- order_by=WorkflowRecordOrderBy.Name,
- direction=SQLiteDirection.Ascending,
- categories=[WorkflowCategory.Default],
- ).items
+ cursor.execute("SELECT workflow_id, name FROM workflow_library WHERE category = 'default';")
+ library_workflows_from_db = cursor.fetchall()
workflows_from_file_ids = [w.id for w in workflows_from_file]
- for w in library_workflows_from_db:
- if w.workflow_id not in workflows_from_file_ids:
- self._invoker.services.logger.debug(
- f"Deleting obsolete default workflow {w.name} ({w.workflow_id})"
- )
+ for workflow_id, name in library_workflows_from_db:
+ if workflow_id not in workflows_from_file_ids:
+ self._invoker.services.logger.debug(f"Deleting obsolete default workflow {name} ({workflow_id})")
# We cannot use the `delete` method here, as it only deletes non-default workflows
cursor.execute(
"""--sql
DELETE from workflow_library
WHERE workflow_id = ?;
""",
- (w.workflow_id,),
+ (workflow_id,),
)
for w in workflows_to_add:
@@ -632,19 +672,21 @@ class SqliteWorkflowRecordsStorage(WorkflowRecordsStorageBase):
"""--sql
INSERT INTO workflow_library (
workflow_id,
- workflow
+ workflow,
+ revision
)
- VALUES (?, ?);
+ VALUES (?, ?, 1);
""",
(w.id, w.model_dump_json()),
)
for w in workflows_to_update:
- # We cannot use the `update` method here, as it only updates non-default workflows
+ # We cannot use the `update` method here, as it refuses default workflows. A changed bundle is
+ # new content, so its revision advances like any other write.
cursor.execute(
"""--sql
UPDATE workflow_library
- SET workflow = ?
+ SET workflow = ?, revision = revision + 1
WHERE workflow_id = ?;
""",
(w.model_dump_json(), w.id),
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 7eec53dab2..486f482401 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -13092,13 +13092,26 @@
"patch": {
"tags": ["workflows"],
"summary": "Update Workflow",
- "description": "Updates a workflow",
+ "description": "Updates a workflow's content and advances its revision.",
"operationId": "update_workflow",
"security": [
{
"HTTPBearer": []
}
],
+ "parameters": [
+ {
+ "name": "workflow_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "The workflow to update",
+ "title": "Workflow Id"
+ },
+ "description": "The workflow to update"
+ }
+ ],
"requestBody": {
"required": true,
"content": {
@@ -13120,6 +13133,18 @@
}
}
},
+ "400": {
+ "description": "The body's workflow id does not match the URL, or the update is malformed"
+ },
+ "403": {
+ "description": "The workflow is bundled or belongs to another account"
+ },
+ "404": {
+ "description": "The workflow does not exist"
+ },
+ "409": {
+ "description": "The workflow's content revision no longer matches `expected_revision`"
+ },
"422": {
"description": "Validation Error",
"content": {
@@ -13209,6 +13234,12 @@
}
}
},
+ "400": {
+ "description": "The workflow or the reserved id is malformed"
+ },
+ "409": {
+ "description": "The reserved id already names a different workflow"
+ },
"422": {
"description": "Validation Error",
"content": {
@@ -19565,6 +19596,18 @@
"workflow": {
"$ref": "#/components/schemas/WorkflowWithoutID",
"description": "The workflow to create"
+ },
+ "workflow_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Workflow Id",
+ "description": "A client-reserved UUID for the new record. Retrying the same creation with the same id returns the record already created for it; another owner's record or different content under that id is a 409."
}
},
"type": "object",
@@ -19907,6 +19950,18 @@
"workflow": {
"$ref": "#/components/schemas/Workflow",
"description": "The updated workflow"
+ },
+ "expected_revision": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expected Revision",
+ "description": "The content revision the client last observed; when set, a different stored revision refuses the write with 409 instead of overwriting newer content."
}
},
"type": "object",
@@ -107923,13 +107978,18 @@
"title": "Is Public",
"description": "Whether this workflow is shared with all users."
},
+ "revision": {
+ "type": "integer",
+ "title": "Revision",
+ "description": "Monotonic content revision; every write of the workflow document increments it."
+ },
"workflow": {
"$ref": "#/components/schemas/Workflow",
"description": "The workflow."
}
},
"type": "object",
- "required": ["workflow_id", "name", "created_at", "updated_at", "user_id", "is_public", "workflow"],
+ "required": ["workflow_id", "name", "created_at", "updated_at", "user_id", "is_public", "revision", "workflow"],
"title": "WorkflowRecordDTO"
},
"WorkflowRecordListItemWithThumbnailDTO": {
@@ -108012,6 +108072,11 @@
"title": "Is Public",
"description": "Whether this workflow is shared with all users."
},
+ "revision": {
+ "type": "integer",
+ "title": "Revision",
+ "description": "Monotonic content revision; every write of the workflow document increments it."
+ },
"description": {
"type": "string",
"title": "Description",
@@ -108058,6 +108123,7 @@
"updated_at",
"user_id",
"is_public",
+ "revision",
"description",
"category",
"tags"
@@ -108150,6 +108216,11 @@
"title": "Is Public",
"description": "Whether this workflow is shared with all users."
},
+ "revision": {
+ "type": "integer",
+ "title": "Revision",
+ "description": "Monotonic content revision; every write of the workflow document increments it."
+ },
"workflow": {
"$ref": "#/components/schemas/Workflow",
"description": "The workflow."
@@ -108179,7 +108250,7 @@
}
},
"type": "object",
- "required": ["workflow_id", "name", "created_at", "updated_at", "user_id", "is_public", "workflow"],
+ "required": ["workflow_id", "name", "created_at", "updated_at", "user_id", "is_public", "revision", "workflow"],
"title": "WorkflowRecordWithThumbnailDTO"
},
"WorkflowReturnGetInvocation": {
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.ts
index 769de694a0..f24f606d16 100644
--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.ts
@@ -55,6 +55,7 @@ const buildWorkflowResponse = (overrides?: {
opened_at: null,
user_id: 'user-1',
is_public: false,
+ revision: 1,
thumbnail_url: null,
workflow: {
id: 'workflow-1',
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.ts
index 67ff2fdb27..f116e260c7 100644
--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.ts
@@ -24,6 +24,7 @@ const workflows: WorkflowRecordListItemWithThumbnailDTO[] = [
description: '',
tags: '',
is_public: false,
+ revision: 1,
thumbnail_url: null,
category: 'user',
user_id: 'user-a',
@@ -42,6 +43,7 @@ const workflows: WorkflowRecordListItemWithThumbnailDTO[] = [
description: '',
tags: '',
is_public: true,
+ revision: 1,
thumbnail_url: null,
category: 'default',
user_id: 'system',
@@ -121,6 +123,7 @@ describe('savedWorkflowFieldUtils', () => {
opened_at: null,
user_id: 'user-z',
is_public: true,
+ revision: 1,
thumbnail_url: null,
call_saved_workflow_compatibility: {
is_callable: true,
@@ -188,6 +191,7 @@ describe('savedWorkflowFieldUtils', () => {
workflow_id: 'workflow-shared',
name: 'Shared Workflow',
is_public: true,
+ revision: 1,
};
expect(mergeSavedWorkflowPickerItems([ownedWorkflow], [defaultWorkflow, sharedWorkflow], [ownedWorkflow])).toEqual([
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.ts
index 6bd38a76b4..a64407fde4 100644
--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.ts
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.ts
@@ -98,6 +98,7 @@ export const getSavedWorkflowListItemFromRecord = (
opened_at: workflow.opened_at,
user_id: workflow.user_id,
is_public: workflow.is_public,
+ revision: workflow.revision,
description: workflow.workflow.description,
category: workflow.workflow.meta.category,
tags: workflow.workflow.tags,
diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts
index 7d5abf34e5..c0f4edfa21 100644
--- a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts
@@ -544,6 +544,7 @@ describe('validateWorkflow', () => {
opened_at: null,
user_id: 'user-1',
is_public: false,
+ revision: 1,
thumbnail_url: null,
workflow: {
id: 'saved-workflow-1',
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 411e539cda..0a95e55f18 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -3376,7 +3376,7 @@ export type paths = {
head?: never;
/**
* Update Workflow
- * @description Updates a workflow
+ * @description Updates a workflow's content and advances its revision.
*/
patch: operations["update_workflow"];
trace?: never;
@@ -5931,6 +5931,11 @@ export type components = {
Body_create_workflow: {
/** @description The workflow to create */
workflow: components["schemas"]["WorkflowWithoutID"];
+ /**
+ * Workflow Id
+ * @description A client-reserved UUID for the new record. Retrying the same creation with the same id returns the record already created for it; another owner's record or different content under that id is a 409.
+ */
+ workflow_id?: string | null;
};
/** Body_delete_images_from_list */
Body_delete_images_from_list: {
@@ -6113,6 +6118,11 @@ export type components = {
Body_update_workflow: {
/** @description The updated workflow */
workflow: components["schemas"]["Workflow"];
+ /**
+ * Expected Revision
+ * @description The content revision the client last observed; when set, a different stored revision refuses the write with 409 instead of overwriting newer content.
+ */
+ expected_revision?: number | null;
};
/** Body_update_workflow_is_public */
Body_update_workflow_is_public: {
@@ -48961,6 +48971,11 @@ export type components = {
* @description Whether this workflow is shared with all users.
*/
is_public: boolean;
+ /**
+ * Revision
+ * @description Monotonic content revision; every write of the workflow document increments it.
+ */
+ revision: number;
/** @description The workflow. */
workflow: components["schemas"]["Workflow"];
};
@@ -49006,6 +49021,11 @@ export type components = {
* @description Whether this workflow is shared with all users.
*/
is_public: boolean;
+ /**
+ * Revision
+ * @description Monotonic content revision; every write of the workflow document increments it.
+ */
+ revision: number;
/**
* Description
* @description The description of the workflow.
@@ -49074,6 +49094,11 @@ export type components = {
* @description Whether this workflow is shared with all users.
*/
is_public: boolean;
+ /**
+ * Revision
+ * @description Monotonic content revision; every write of the workflow document increments it.
+ */
+ revision: number;
/** @description The workflow. */
workflow: components["schemas"]["Workflow"];
/**
@@ -56685,7 +56710,10 @@ export interface operations {
parameters: {
query?: never;
header?: never;
- path?: never;
+ path: {
+ /** @description The workflow to update */
+ workflow_id: string;
+ };
cookie?: never;
};
requestBody: {
@@ -56703,6 +56731,34 @@ export interface operations {
"application/json": components["schemas"]["WorkflowRecordDTO"];
};
};
+ /** @description The body's workflow id does not match the URL, or the update is malformed */
+ 400: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description The workflow is bundled or belongs to another account */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description The workflow does not exist */
+ 404: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description The workflow's content revision no longer matches `expected_revision` */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
/** @description Validation Error */
422: {
headers: {
@@ -56786,6 +56842,20 @@ export interface operations {
"application/json": components["schemas"]["WorkflowRecordDTO"];
};
};
+ /** @description The workflow or the reserved id is malformed */
+ 400: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description The reserved id already names a different workflow */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
/** @description Validation Error */
422: {
headers: {
diff --git a/tests/app/invocations/test_call_saved_workflows.py b/tests/app/invocations/test_call_saved_workflows.py
index a0bb4533fd..78d8979908 100644
--- a/tests/app/invocations/test_call_saved_workflows.py
+++ b/tests/app/invocations/test_call_saved_workflows.py
@@ -46,6 +46,7 @@ def build_workflow_record_dto(
opened_at=None,
user_id=user_id,
is_public=is_public,
+ revision=1,
)
diff --git a/tests/app/routers/test_workflows_revisions.py b/tests/app/routers/test_workflows_revisions.py
new file mode 100644
index 0000000000..0f1b892cb1
--- /dev/null
+++ b/tests/app/routers/test_workflows_revisions.py
@@ -0,0 +1,178 @@
+"""The workflow endpoints expose content revisions, refuse stale updates, and make creation retry-safe."""
+
+import uuid
+from typing import Any
+
+import pytest
+from fastapi.testclient import TestClient
+
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
+from invokeai.app.services.workflow_records.workflow_records_common import WorkflowCategory, WorkflowRecordOrderBy
+from tests.app.routers.test_workflows_multiuser import WORKFLOW_BODY, create_workflow
+
+pytest_plugins = ("tests.app.routers.test_workflows_multiuser",)
+
+
[email protected](autouse=True)
+def _no_thumbnails(enable_multiuser: Any, mock_invoker: Invoker) -> None:
+ # The routers conftest also provides `enable_multiuser`; whichever wins, single-record reads need a real URL or None.
+ mock_invoker.services.workflow_thumbnails.get_url.return_value = None
+
+
+def _auth(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}"}
+
+
+def _update(client: TestClient, token: str, workflow_id: str, name: str, expected_revision: int | None = None):
+ body: dict[str, Any] = {"workflow": {**WORKFLOW_BODY, "id": workflow_id, "name": name}}
+ if expected_revision is not None:
+ body["expected_revision"] = expected_revision
+ return client.patch(f"/api/v1/workflows/i/{workflow_id}", json=body, headers=_auth(token))
+
+
+def test_records_report_their_revision(client: TestClient, user1_token: str) -> None:
+ created = client.post("/api/v1/workflows/", json={"workflow": WORKFLOW_BODY}, headers=_auth(user1_token))
+ assert created.status_code == 200, created.text
+ assert created.json()["revision"] == 1
+ workflow_id = created.json()["workflow_id"]
+
+ updated = _update(client, user1_token, workflow_id, "Second", expected_revision=1)
+ assert updated.status_code == 200, updated.text
+ assert updated.json()["revision"] == 2
+
+ fetched = client.get(f"/api/v1/workflows/i/{workflow_id}", headers=_auth(user1_token))
+ assert fetched.json()["revision"] == 2
+ listed = client.get("/api/v1/workflows/?categories=user", headers=_auth(user1_token))
+ assert next(item["revision"] for item in listed.json()["items"] if item["workflow_id"] == workflow_id) == 2
+
+
+def test_a_stale_update_is_a_structured_conflict(client: TestClient, user1_token: str, mock_invoker: Invoker) -> None:
+ workflow_id = create_workflow(client, user1_token)
+ assert _update(client, user1_token, workflow_id, "Second", expected_revision=1).status_code == 200
+ events_before = len(mock_invoker.services.events.events)
+
+ stale = _update(client, user1_token, workflow_id, "Stale", expected_revision=1)
+
+ assert stale.status_code == 409, stale.text
+ assert stale.json()["detail"] == {
+ "message": stale.json()["detail"]["message"],
+ "reason": "revision-conflict",
+ "current_revision": 2,
+ "expected_revision": 1,
+ }
+ assert len(mock_invoker.services.events.events) == events_before
+ assert client.get(f"/api/v1/workflows/i/{workflow_id}", headers=_auth(user1_token)).json()["name"] == "Second"
+
+
+def test_legacy_updates_without_an_expected_revision_still_write(client: TestClient, user1_token: str) -> None:
+ workflow_id = create_workflow(client, user1_token)
+ assert _update(client, user1_token, workflow_id, "Second", expected_revision=1).status_code == 200
+
+ legacy = _update(client, user1_token, workflow_id, "Third")
+
+ assert legacy.status_code == 200, legacy.text
+ assert legacy.json()["revision"] == 3
+ assert legacy.json()["name"] == "Third"
+
+
+def test_the_url_and_body_must_name_the_same_workflow(client: TestClient, user1_token: str) -> None:
+ first = create_workflow(client, user1_token)
+ second = create_workflow(client, user1_token)
+
+ response = client.patch(
+ f"/api/v1/workflows/i/{first}",
+ json={"workflow": {**WORKFLOW_BODY, "id": second, "name": "Crossed"}},
+ headers=_auth(user1_token),
+ )
+
+ assert response.status_code == 400
+ for workflow_id in (first, second):
+ assert (
+ client.get(f"/api/v1/workflows/i/{workflow_id}", headers=_auth(user1_token)).json()["name"]
+ == (WORKFLOW_BODY["name"])
+ )
+
+
+def test_bundled_workflows_refuse_updates_even_from_admins(
+ client: TestClient, admin_token: str, mock_invoker: Invoker
+) -> None:
+ bundled = mock_invoker.services.workflow_records.get_many(
+ order_by=WorkflowRecordOrderBy.Name,
+ direction=SQLiteDirection.Ascending,
+ categories=[WorkflowCategory.Default],
+ page=0,
+ per_page=1,
+ query=None,
+ tags=None,
+ has_been_opened=None,
+ ).items[0]
+
+ response = _update(client, admin_token, bundled.workflow_id, "Hijacked")
+
+ assert response.status_code == 403, response.text
+ assert client.delete(f"/api/v1/workflows/i/{bundled.workflow_id}", headers=_auth(admin_token)).status_code == 403
+ assert mock_invoker.services.workflow_records.get(bundled.workflow_id).name == bundled.name
+
+
+def test_bundled_workflows_answer_immutability_before_ownership(
+ client: TestClient, user1_token: str, mock_invoker: Invoker
+) -> None:
+ bundled = mock_invoker.services.workflow_records.get_many(
+ order_by=WorkflowRecordOrderBy.Name,
+ direction=SQLiteDirection.Ascending,
+ categories=[WorkflowCategory.Default],
+ page=0,
+ per_page=1,
+ query=None,
+ tags=None,
+ has_been_opened=None,
+ ).items[0]
+
+ response = _update(client, user1_token, bundled.workflow_id, "Hijacked")
+
+ assert response.status_code == 403, response.text
+ assert response.json()["detail"] == "Bundled workflows cannot be modified"
+ deleted = client.delete(f"/api/v1/workflows/i/{bundled.workflow_id}", headers=_auth(user1_token))
+ assert deleted.status_code == 403
+ assert deleted.json()["detail"] == "Bundled workflows cannot be deleted"
+
+
+def test_creation_with_a_reserved_id_is_idempotent(client: TestClient, user1_token: str, mock_invoker: Invoker) -> None:
+ reserved = str(uuid.uuid4())
+ body = {"workflow": WORKFLOW_BODY, "workflow_id": reserved}
+
+ first = client.post("/api/v1/workflows/", json=body, headers=_auth(user1_token))
+ retried = client.post("/api/v1/workflows/", json=body, headers=_auth(user1_token))
+
+ assert first.status_code == 200, first.text
+ assert retried.status_code == 200, retried.text
+ assert first.json()["workflow_id"] == reserved
+ assert retried.json()["workflow_id"] == reserved
+ created_events = [e for e in mock_invoker.services.events.events if e.__event_name__ == "workflow_created"]
+ assert [e.workflow_id for e in created_events].count(reserved) == 1
+
+
+def test_a_reserved_id_never_exposes_another_accounts_record(
+ client: TestClient, user1_token: str, user2_token: str
+) -> None:
+ reserved = str(uuid.uuid4())
+ body = {"workflow": WORKFLOW_BODY, "workflow_id": reserved}
+ assert client.post("/api/v1/workflows/", json=body, headers=_auth(user1_token)).status_code == 200
+
+ stolen = client.post("/api/v1/workflows/", json=body, headers=_auth(user2_token))
+ changed = client.post(
+ "/api/v1/workflows/",
+ json={"workflow": {**WORKFLOW_BODY, "name": "Different"}, "workflow_id": reserved},
+ headers=_auth(user1_token),
+ )
+ malformed = client.post(
+ "/api/v1/workflows/", json={"workflow": WORKFLOW_BODY, "workflow_id": "nope"}, headers=_auth(user1_token)
+ )
+
+ assert stolen.status_code == 409
+ assert stolen.json()["detail"]["reason"] == "id-conflict"
+ assert "user1" not in stolen.text
+ assert changed.status_code == 409
+ assert malformed.status_code == 400
+ assert client.get(f"/api/v1/workflows/i/{reserved}", headers=_auth(user2_token)).status_code == 403
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_26_add_workflow_revision.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_26_add_workflow_revision.py
new file mode 100644
index 0000000000..08d9a1477d
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_26_add_workflow_revision.py
@@ -0,0 +1,25 @@
+"""Existing library workflows start at revision 1 and the column is added once."""
+
+import sqlite3
+
+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_26_add_workflow_revision import (
+ build_migration,
+)
+
+
+def test_existing_workflows_start_at_revision_one() -> None:
+ connection = sqlite3.connect(":memory:")
+ cursor = connection.cursor()
+ cursor.execute("CREATE TABLE workflow_library (workflow_id TEXT NOT NULL PRIMARY KEY, workflow TEXT NOT NULL);")
+ cursor.execute("INSERT INTO workflow_library VALUES ('wf-1', '{}');")
+
+ build_migration().callback(cursor)
+ build_migration().callback(cursor)
+
+ cursor.execute("SELECT revision FROM workflow_library WHERE workflow_id = 'wf-1';")
+ assert cursor.fetchone() == (1,)
+ cursor.execute("INSERT INTO workflow_library (workflow_id, workflow) VALUES ('wf-2', '{}');")
+ cursor.execute("SELECT revision FROM workflow_library WHERE workflow_id = 'wf-2';")
+ assert cursor.fetchone() == (1,)
+ cursor.execute("PRAGMA table_info(workflow_library);")
+ assert [row[1] for row in cursor.fetchall()].count("revision") == 1
diff --git a/tests/app/services/workflow_records/test_workflow_media_references.py b/tests/app/services/workflow_records/test_workflow_media_references.py
index f7edb6945f..1dd5d8a81a 100644
--- a/tests/app/services/workflow_records/test_workflow_media_references.py
+++ b/tests/app/services/workflow_records/test_workflow_media_references.py
@@ -3,12 +3,11 @@
import pytest
from invokeai.app.services.invoker import Invoker
-from invokeai.app.services.shared.media_references import extract_media_references
from invokeai.app.services.workflow_records.workflow_records_common import (
Workflow,
+ WorkflowAccessDeniedError,
WorkflowCategory,
WorkflowMeta,
- WorkflowRecordDTO,
WorkflowWithoutID,
)
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
@@ -58,27 +57,22 @@ def test_create_update_and_delete_keep_the_index_current(workflow_records: Sqlit
def test_an_update_refused_by_ownership_leaves_the_index_alone(workflow_records: SqliteWorkflowRecordsStorage) -> None:
created = workflow_records.create(_workflow("input.png"), user_id="user-1")
- workflow_records.update(Workflow(**_workflow("stolen.png").model_dump(), id=created.workflow_id), user_id="user-2")
+ with pytest.raises(WorkflowAccessDeniedError):
+ workflow_records.update(
+ Workflow(**_workflow("stolen.png").model_dump(), id=created.workflow_id), user_id="user-2"
+ )
assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "input.png")}
def test_visibility_change_keeps_the_reference_index_of_the_document_it_writes(
- workflow_records: SqliteWorkflowRecordsStorage, monkeypatch: pytest.MonkeyPatch
+ workflow_records: SqliteWorkflowRecordsStorage,
) -> None:
created = workflow_records.create(_workflow("old.png"), user_id="user-1")
- original_get = workflow_records.get
-
- def concurrent_edit(workflow_id: str) -> WorkflowRecordDTO:
- previous = original_get(workflow_id)
- monkeypatch.setattr(workflow_records, "get", original_get)
- workflow_records.update(Workflow(**_workflow("new.png").model_dump(), id=workflow_id), user_id="user-1")
- return previous
- monkeypatch.setattr(workflow_records, "get", concurrent_edit)
- workflow_records.update_is_public(created.workflow_id, True, user_id="user-1")
- actual = original_get(created.workflow_id)
+ shared = workflow_records.update_is_public(created.workflow_id, True, user_id="user-1")
- assert _references(workflow_records, created.workflow_id) == {
- ("user-1", "image", name) for name in extract_media_references(actual.workflow.model_dump()).images
- }
+ assert shared.is_public is True
+ assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "old.png")}
+ workflow_records.update(Workflow(**_workflow("new.png").model_dump(), id=created.workflow_id), user_id="user-1")
+ assert _references(workflow_records, created.workflow_id) == {("user-1", "image", "new.png")}
diff --git a/tests/app/services/workflow_records/test_workflow_revisions.py b/tests/app/services/workflow_records/test_workflow_revisions.py
new file mode 100644
index 0000000000..36f15ce0b8
--- /dev/null
+++ b/tests/app/services/workflow_records/test_workflow_revisions.py
@@ -0,0 +1,236 @@
+"""Library workflows carry a content revision; explicit template updates and retried creations lean on it."""
+
+import uuid
+
+import pytest
+
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
+from invokeai.app.services.workflow_records.workflow_records_common import (
+ Workflow,
+ WorkflowAccessDeniedError,
+ WorkflowCategory,
+ WorkflowIdConflictError,
+ WorkflowImmutableError,
+ WorkflowMeta,
+ WorkflowNotFoundError,
+ WorkflowRecordOrderBy,
+ WorkflowRevisionConflictError,
+ WorkflowWithoutID,
+)
+from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
+
+
+def records(mock_invoker: Invoker) -> SqliteWorkflowRecordsStorage:
+ return mock_invoker.services.workflow_records
+
+
+def _workflow(name: str = "Template", image_name: str | None = None) -> WorkflowWithoutID:
+ inputs = {"image": {"value": {"image_name": image_name}}} if image_name else {}
+ return WorkflowWithoutID(
+ name=name,
+ author="",
+ description="",
+ version="1.0.0",
+ contact="",
+ tags="",
+ notes="",
+ exposedFields=[],
+ meta=WorkflowMeta(version="3.0.0", category=WorkflowCategory.User),
+ nodes=[{"id": "n1", "data": {"inputs": inputs}}],
+ edges=[],
+ )
+
+
+def _with_id(workflow: WorkflowWithoutID, workflow_id: str) -> Workflow:
+ return Workflow(**workflow.model_dump(), id=workflow_id)
+
+
+def _references(records: SqliteWorkflowRecordsStorage, workflow_id: str) -> set[str]:
+ with records._db.transaction() as cursor:
+ cursor.execute(
+ "SELECT media_name FROM media_references WHERE owner_kind = 'workflow' AND owner_id = ?;",
+ (workflow_id,),
+ )
+ return {row[0] for row in cursor.fetchall()}
+
+
+def _bundled_id(records: SqliteWorkflowRecordsStorage) -> str:
+ bundled = records.get_many(
+ order_by=WorkflowRecordOrderBy.Name,
+ direction=SQLiteDirection.Ascending,
+ categories=[WorkflowCategory.Default],
+ page=0,
+ per_page=1,
+ query=None,
+ tags=None,
+ has_been_opened=None,
+ ).items
+ assert bundled, "the default workflows are synced on start"
+ return bundled[0].workflow_id
+
+
+def test_every_content_write_advances_the_revision(records: SqliteWorkflowRecordsStorage) -> None:
+ created = records.create(_workflow(), user_id="user-1")
+ assert created.revision == 1
+
+ first = records.update(_with_id(_workflow("Edited"), created.workflow_id), user_id="user-1")
+ assert first.revision == 2
+
+ # Legacy callers that carry no expected revision still write, and still advance it.
+ second = records.update(_with_id(_workflow("Edited again"), created.workflow_id))
+ assert second.revision == 3
+ assert records.get(created.workflow_id).workflow.name == "Edited again"
+
+ listed = records.get_many(
+ order_by=WorkflowRecordOrderBy.CreatedAt,
+ direction=SQLiteDirection.Descending,
+ categories=[WorkflowCategory.User],
+ page=0,
+ per_page=10,
+ query=None,
+ tags=None,
+ has_been_opened=None,
+ ).items
+ assert next(item.revision for item in listed if item.workflow_id == created.workflow_id) == 3
+
+
+def test_a_stale_expected_revision_is_refused_and_writes_nothing(records: SqliteWorkflowRecordsStorage) -> None:
+ created = records.create(_workflow(image_name="v1.png"), user_id="user-1")
+ records.update(_with_id(_workflow(image_name="v2.png"), created.workflow_id), user_id="user-1")
+
+ with pytest.raises(WorkflowRevisionConflictError) as conflict:
+ records.update(
+ _with_id(_workflow(image_name="stale.png"), created.workflow_id),
+ user_id="user-1",
+ expected_revision=1,
+ )
+
+ assert conflict.value.current_revision == 2
+ assert conflict.value.expected_revision == 1
+ current = records.get(created.workflow_id)
+ assert current.revision == 2
+ assert _references(records, created.workflow_id) == {"v2.png"}
+
+ accepted = records.update(
+ _with_id(_workflow(image_name="v3.png"), created.workflow_id), user_id="user-1", expected_revision=2
+ )
+ assert accepted.revision == 3
+ assert _references(records, created.workflow_id) == {"v3.png"}
+
+
+def test_bookkeeping_writes_leave_the_revision_alone(records: SqliteWorkflowRecordsStorage) -> None:
+ created = records.create(_workflow(image_name="in.png"), user_id="user-1")
+
+ records.update_opened_at(created.workflow_id, user_id="user-1")
+ records.update_last_run_at(created.workflow_id, user_id="user-1")
+ shared = records.update_is_public(created.workflow_id, True, user_id="user-1")
+
+ assert shared.revision == 1
+ assert shared.is_public is True
+ assert "shared" in shared.workflow.tags
+ assert _references(records, created.workflow_id) == {"in.png"}
+ # An editor holding revision 1 is therefore not asked to resolve a conflict it cannot see.
+ assert records.update(_with_id(_workflow(), created.workflow_id), expected_revision=1).revision == 2
+
+
+def test_ownership_is_enforced_atomically_with_the_write(records: SqliteWorkflowRecordsStorage) -> None:
+ created = records.create(_workflow(image_name="mine.png"), user_id="user-1")
+
+ with pytest.raises(WorkflowAccessDeniedError):
+ records.update(_with_id(_workflow(image_name="stolen.png"), created.workflow_id), user_id="user-2")
+ with pytest.raises(WorkflowAccessDeniedError):
+ records.delete(created.workflow_id, user_id="user-2")
+
+ current = records.get(created.workflow_id)
+ assert current.revision == 1
+ assert _references(records, created.workflow_id) == {"mine.png"}
+
+ with pytest.raises(WorkflowNotFoundError):
+ records.update(_with_id(_workflow(), "missing"), user_id="user-1")
+
+
+def test_bundled_workflows_are_immutable_whatever_the_request_claims(records: SqliteWorkflowRecordsStorage) -> None:
+ bundled_id = _bundled_id(records)
+ before = records.get(bundled_id)
+
+ # The body says "user"; the stored record decides.
+ with pytest.raises(WorkflowImmutableError):
+ records.update(_with_id(_workflow("Hijacked"), bundled_id))
+ with pytest.raises(WorkflowImmutableError):
+ records.update(_with_id(_workflow("Hijacked"), bundled_id), user_id=before.user_id, expected_revision=1)
+ with pytest.raises(WorkflowImmutableError):
+ records.delete(bundled_id)
+
+ after = records.get(bundled_id)
+ assert after.workflow == before.workflow
+ assert after.revision == before.revision
+
+
+def test_bundled_sync_advances_the_revision_only_when_content_changes(
+ records: SqliteWorkflowRecordsStorage,
+) -> None:
+ bundled_id = _bundled_id(records)
+ assert records.get(bundled_id).revision == 1
+
+ # A second start with unchanged bundles is a no-op for every record.
+ records._sync_default_workflows()
+ assert records.get(bundled_id).revision == 1
+
+ with records._db.transaction() as cursor:
+ cursor.execute(
+ "UPDATE workflow_library SET workflow = json_set(workflow, '$.notes', 'stale copy') WHERE workflow_id = ?;",
+ (bundled_id,),
+ )
+ records._sync_default_workflows()
+ resynced = records.get(bundled_id)
+ assert resynced.revision == 2
+ assert resynced.workflow.notes != "stale copy"
+
+
+def test_a_reserved_id_makes_creation_retry_safe(records: SqliteWorkflowRecordsStorage) -> None:
+ reserved = str(uuid.uuid4())
+ workflow = _workflow(image_name="first.png")
+
+ created = records.create(workflow, user_id="user-1", workflow_id=reserved)
+ retried = records.create(workflow, user_id="user-1", workflow_id=reserved)
+
+ assert created.workflow_id == reserved
+ assert retried.workflow_id == reserved
+ assert retried.revision == 1
+ assert _references(records, reserved) == {"first.png"}
+ listed = records.get_many(
+ order_by=WorkflowRecordOrderBy.CreatedAt,
+ direction=SQLiteDirection.Descending,
+ categories=[WorkflowCategory.User],
+ page=0,
+ per_page=None,
+ query=None,
+ tags=None,
+ has_been_opened=None,
+ )
+ assert [item.workflow_id for item in listed.items].count(reserved) == 1
+
+
+def test_a_reserved_id_that_names_something_else_is_a_conflict(records: SqliteWorkflowRecordsStorage) -> None:
+ reserved = str(uuid.uuid4())
+ records.create(_workflow(image_name="first.png"), user_id="user-1", workflow_id=reserved)
+
+ with pytest.raises(WorkflowIdConflictError):
+ records.create(_workflow(image_name="other.png"), user_id="user-1", workflow_id=reserved)
+ with pytest.raises(WorkflowIdConflictError):
+ records.create(_workflow(image_name="first.png"), user_id="user-2", workflow_id=reserved)
+ with pytest.raises(ValueError):
+ records.create(_workflow(), user_id="user-1", workflow_id="not-a-uuid")
+
+ assert records.get(reserved).user_id == "user-1"
+ assert _references(records, reserved) == {"first.png"}
+
+
+def test_creation_without_a_reserved_id_keeps_generating_ids(records: SqliteWorkflowRecordsStorage) -> None:
+ first = records.create(_workflow(), user_id="user-1")
+ second = records.create(_workflow(), user_id="user-1")
+
+ assert first.workflow_id != second.workflow_id
+ assert uuid.UUID(first.workflow_id)