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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(boards): make project claims atomic
Josh Corbettd34dcceef30c
diff --git a/invokeai/app/api/routers/boards.py b/invokeai/app/api/routers/boards.pyindex 273dfffe5c..41c51087a7 100644--- a/invokeai/app/api/routers/boards.py+++ b/invokeai/app/api/routers/boards.py@@ -8,7 +8,11 @@ from invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers._access import assert_board_read_access as _assert_board_read_accessfrom invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactive-from invokeai.app.services.board_records.board_records_common import BoardChanges, BoardRecordOrderBy+from invokeai.app.services.board_records.board_records_common import (+ BoardChanges,+ BoardRecordOrderBy,+ BoardRecordProjectOwnedException,+)from invokeai.app.services.boards.boards_common import BoardDTOfrom invokeai.app.services.image_records.image_records_common import ImageCategoryfrom invokeai.app.services.shared.pagination import OffsetPaginatedResults@@ -116,6 +120,11 @@ async def update_board(try:result = ApiDependencies.invoker.services.boards.update(board_id=board_id, changes=changes)return result+ except BoardRecordProjectOwnedException:+ raise HTTPException(+ status_code=409,+ detail="This board belongs to a project; rename or archive the project instead",+ )except Exception:raise HTTPException(status_code=500, detail="Failed to update board")diff --git a/invokeai/app/services/board_records/board_records_common.py b/invokeai/app/services/board_records/board_records_common.pyindex 9eefe43b50..6a3ff50844 100644--- a/invokeai/app/services/board_records/board_records_common.py+++ b/invokeai/app/services/board_records/board_records_common.py@@ -117,6 +117,13 @@ class BoardRecordSaveException(Exception):super().__init__(message)+class BoardRecordProjectOwnedException(BoardRecordSaveException):+ """Raised when a generic board update would change project-owned state."""++ def __init__(self, message="Board belongs to a project"):+ super().__init__(message)++class BoardRecordDeleteException(Exception):"""Raised when an board record cannot be deleted."""diff --git a/invokeai/app/services/board_records/board_records_sqlite.py b/invokeai/app/services/board_records/board_records_sqlite.pyindex b3089f58d2..5737062548 100644--- a/invokeai/app/services/board_records/board_records_sqlite.py+++ b/invokeai/app/services/board_records/board_records_sqlite.py@@ -8,6 +8,7 @@ from invokeai.app.services.board_records.board_records_common import (BoardRecordDeleteException,BoardRecordNotFoundException,BoardRecordOrderBy,+ BoardRecordProjectOwnedException,BoardRecordSaveException,deserialize_board_record,)@@ -152,49 +153,43 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):) -> BoardRecord:with self._db.transaction() as cursor:try:- # Change the name of a board- if changes.board_name is not None:- cursor.execute(- """--sql- UPDATE boards- SET board_name = ?- WHERE board_id = ?;- """,- (changes.board_name, board_id),- )-- # Change the cover image of a board- if changes.cover_image_name is not None:- cursor.execute(- """--sql- UPDATE boards- SET cover_image_name = ?- WHERE board_id = ?;- """,- (changes.cover_image_name, board_id),- )-- # Change the archived status of a board- if changes.archived is not None:- cursor.execute(- """--sql- UPDATE boards- SET archived = ?- WHERE board_id = ?;- """,- (changes.archived, board_id),- )-- # Change the visibility of a board- if changes.board_visibility is not None:- cursor.execute(- """--sql- UPDATE boards- SET board_visibility = ?- WHERE board_id = ?;- """,- (changes.board_visibility.value, board_id),- )+ changes_project_owned_state = (+ changes.board_name is not None+ or changes.archived is not None+ or changes.board_visibility is not None+ )+ # One conditional write, not a read followed by a write. A project claim racing+ # this statement either commits first and makes rowcount zero, or waits until this+ # update has committed; there is no stale DTO window in which project-owned state+ # can be renamed, archived or published.+ cursor.execute(+ """--sql+ UPDATE boards+ SET board_name = COALESCE(?, board_name),+ cover_image_name = COALESCE(?, cover_image_name),+ archived = COALESCE(?, archived),+ board_visibility = COALESCE(?, board_visibility)+ WHERE board_id = ?+ AND (+ ? = FALSE+ OR NOT EXISTS (SELECT 1 FROM projects WHERE projects.board_id = boards.board_id)+ );+ """,+ (+ changes.board_name,+ changes.cover_image_name,+ changes.archived,+ changes.board_visibility.value if changes.board_visibility is not None else None,+ board_id,+ changes_project_owned_state,+ ),+ )++ if cursor.rowcount == 0:+ cursor.execute("SELECT 1 FROM boards WHERE board_id = ?;", (board_id,))+ if cursor.fetchone() is None:+ raise BoardRecordNotFoundException+ raise BoardRecordProjectOwnedExceptionexcept sqlite3.Error as e:raise BoardRecordSaveException from ediff --git a/tests/app/routers/test_boards_multiuser.py b/tests/app/routers/test_boards_multiuser.pyindex e3c67e9e12..b184c61deb 100644--- a/tests/app/routers/test_boards_multiuser.py+++ b/tests/app/routers/test_boards_multiuser.py@@ -1017,6 +1017,62 @@ def test_setting_only_the_cover_of_a_project_board_is_still_allowed(assert response.status_code == status.HTTP_201_CREATED+ ("changes", "unchanged"),+ [+ ({"board_name": "Raced rename"}, {"board_name": "Claimed during PATCH"}),+ ({"archived": True}, {"archived": False}),+ ({"board_visibility": "public"}, {"board_visibility": "private"}),+ ],+)+def test_board_update_cannot_race_a_project_claim(+ client: TestClient,+ mock_invoker: Invoker,+ monkeypatch: pytest.MonkeyPatch,+ user1_token: str,+ changes: dict[str, Any],+ unchanged: dict[str, Any],+):+ """The claimed-board check and mutation must be one database decision.++ Returning an unclaimed DTO and claiming the board immediately afterwards pins the race without+ sleeps or threads: an unconditional update sees stale state, while a conditional write cannot.+ """+ created = client.post(+ "/api/v1/boards/?board_name=Unclaimed",+ headers={"Authorization": f"Bearer {user1_token}"},+ ).json()+ board_id = created["board_id"]+ original_get_dto = mock_invoker.services.boards.get_dto+ did_claim = False++ def get_then_claim(*, board_id: str):+ nonlocal did_claim+ board = original_get_dto(board_id)+ if not did_claim:+ did_claim = True+ mock_invoker.services.project_records.create(+ user_id=created["user_id"],+ name="Claimed during PATCH",+ data={},+ board_id=board_id,+ )+ return board++ monkeypatch.setattr(mock_invoker.services.boards, "get_dto", get_then_claim)++ response = client.patch(+ f"/api/v1/boards/{board_id}",+ json=changes,+ headers={"Authorization": f"Bearer {user1_token}"},+ )++ assert response.status_code == status.HTTP_409_CONFLICT+ board = original_get_dto(board_id)+ for field, value in unchanged.items():+ assert getattr(board, field) == value++@pytest.mark.parametrize("include_images", [False, True])def test_generic_deletion_of_a_project_board_is_refused_without_touching_media(client: TestClient, mock_invoker: Invoker, user1_token: str, admin_token: str, include_images: bool