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
refactor(api): tighten the board and project record seams
Josh Corbett8c5bf8a68abb
diff --git a/invokeai/app/api/routers/_access.py b/invokeai/app/api/routers/_access.pyindex 2edf21fd36..117ff6ef5a 100644--- a/invokeai/app/api/routers/_access.py+++ b/invokeai/app/api/routers/_access.py@@ -99,6 +99,57 @@ def assert_board_write_access(board_id: str | None, current_user: CurrentUserOrDraise HTTPException(status_code=403, detail="Not authorized to modify this board")+def assert_video_read_access(video_name: str, current_user: CurrentUserOrDefault) -> None:+ """Raise 403 if the current user may not view the video.++ Deliberately identical in shape to `assert_image_read_access`, and delegating to+ `assert_board_read_access` for the same reason: the video twin used to inline a narrower rule+ that recognized only Shared and Public visibility, so a video on a board explicitly shared with+ you was unreadable while the image beside it was fine. Two media kinds on one board should not+ disagree about who can see them.+ """+ if current_user.is_admin:+ return++ owner = ApiDependencies.invoker.services.video_records.get_user_id(video_name)+ if owner is not None and owner == current_user.user_id:+ return++ board_id = ApiDependencies.invoker.services.board_video_records.get_board_for_video(video_name)+ if board_id is not None:+ assert_board_read_access(board_id, current_user)+ return++ raise HTTPException(status_code=403, detail="Not authorized to access this video")+++def assert_video_owner(video_name: str, current_user: CurrentUserOrDefault) -> None:+ """Raise 403 if the current user may not mutate the video.++ The mutation twin of `assert_image_owner`: the direct owner, the owner of the board it sits on,+ or a Public board, which grants contribution rights.+ """+ if current_user.is_admin:+ return++ owner = ApiDependencies.invoker.services.video_records.get_user_id(video_name)+ if owner is not None and owner == current_user.user_id:+ return++ board_id = ApiDependencies.invoker.services.board_video_records.get_board_for_video(video_name)+ if board_id is not None:+ try:+ board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)+ if board.user_id == current_user.user_id:+ return+ if board.board_visibility == BoardVisibility.Public:+ return+ except Exception:+ pass++ raise HTTPException(status_code=403, detail="Not authorized to modify this video")++def assert_board_read_access(board_id: str, current_user: CurrentUserOrDefault) -> None:"""Raise 403 if the current user may not read images from this board.diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.pyindex a600b6a849..1d003b3117 100644--- a/invokeai/app/api/routers/images.py+++ b/invokeai/app/api/routers/images.py@@ -606,6 +606,11 @@ def copy_images_to_board(A sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and aboard's worth of them on the event loop would stall every other request for the duration.++ Read access is enough to copy, which means an image on a board shared with you can be copied+ into something you own, and the copy outlives the share. That is deliberate — it is what makes+ a shared board usable as a source — but it is a real widening of what "read-only" means, so it+ is stated rather than left to be discovered."""_assert_board_write_access(board_id, current_user)assert_image_move_maintenance_inactive()diff --git a/invokeai/app/api/routers/projects.py b/invokeai/app/api/routers/projects.pyindex 284944fd03..8869bf11a7 100644--- a/invokeai/app/api/routers/projects.py+++ b/invokeai/app/api/routers/projects.py@@ -9,6 +9,7 @@ from invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.project_records.project_records_common import (ProjectBoardNotFoundError,ProjectBoardSnapshotDTO,+ ProjectBoardTooLargeError,ProjectBoardUnavailableError,ProjectRecordConflictError,ProjectRecordDTO,@@ -122,13 +123,17 @@ async def get_project_board_snapshot("""Lists everything on the project's board that the gallery would show.Intermediates and the canvas's private `other` category are excluded. Unpaginated: the caller- that needs this — exporting a project — has to hold the whole list anyway, and enforces its own- archive limits over it.+ that needs this — exporting a project — has to hold the whole list anyway. It is still bounded,+ because the answer is built entirely in memory and any client with a project id can ask for it;+ a board past the ceiling is one an export could not have packed either, so it is refused as a+ 413 rather than paged."""try:return ApiDependencies.invoker.services.project_records.get_board_snapshot(current_user.user_id, project_id)except ProjectRecordNotFoundError as e:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))+ except ProjectBoardTooLargeError as e:+ raise HTTPException(status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail=str(e))@projects_router.delete("/{project_id}", operation_id="delete_project", status_code=status.HTTP_204_NO_CONTENT)@@ -136,5 +141,12 @@ async def delete_project(current_user: CurrentUserOrDefault,project_id: str = Path(description="The id of the project to delete"),) -> None:- """Deletes one of the current user's projects. Idempotent."""+ """Deletes one of the current user's projects, and the board it owns, in one transaction.++ Idempotent. The media survives: deleting the board drops its memberships, so the images and+ videos on it return to Uncategorized, exactly as they would if the board were deleted without+ `include_images`. There is deliberately no option to take them with it — a project is a+ workspace, and emptying someone's gallery is not what deleting one should be able to mean.+ Nothing is reported back for the same reason: nothing was destroyed to report.+ """ApiDependencies.invoker.services.project_records.delete(current_user.user_id, project_id)diff --git a/invokeai/app/api/routers/videos.py b/invokeai/app/api/routers/videos.pyindex 57d627f4f1..3307f0f4a9 100644--- a/invokeai/app/api/routers/videos.py+++ b/invokeai/app/api/routers/videos.py@@ -16,11 +16,20 @@ from starlette.concurrency import run_in_threadpoolfrom invokeai.app.api.auth_dependencies import CurrentMediaUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.routers._access import (+ assert_board_read_access as _assert_board_read_access,+)from invokeai.app.api.routers._access import (assert_board_write_access as _assert_board_write_access,)+from invokeai.app.api.routers._access import (+ assert_video_owner as _assert_video_owner,+)+from invokeai.app.api.routers._access import (+ assert_video_read_access as _assert_video_read_access,+)from invokeai.app.api.routers._limits import MAX_COPY_BATCH_SIZE-from invokeai.app.api.routers.images import WorkflowAndGraphResponse, _assert_board_read_access+from invokeai.app.api.routers.images import WorkflowAndGraphResponsefrom invokeai.app.invocations.fields import MetadataField, MetadataFieldValidatorfrom invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.shared.pagination import MAX_PAGE_SIZE, OffsetPaginatedResults@@ -84,30 +93,6 @@ def _get_video_cache_control() -> str:return f"max-age={VIDEO_MAX_AGE}"-def _assert_video_owner(video_name: str, current_user: CurrentUserOrDefault) -> None:- """Raise 403 if the current user does not own the video and is not an admin."""- from invokeai.app.services.board_records.board_records_common import BoardVisibility-- if current_user.is_admin:- return- owner = ApiDependencies.invoker.services.video_records.get_user_id(video_name)- if owner is not None and owner == current_user.user_id:- return-- board_id = ApiDependencies.invoker.services.board_video_records.get_board_for_video(video_name)- if board_id is not None:- try:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)- if board.user_id == current_user.user_id:- return- if board.board_visibility == BoardVisibility.Public:- return- except Exception:- pass-- raise HTTPException(status_code=403, detail="Not authorized to modify this video")--def _assert_video_direct_owner(video_name: str, current_user: CurrentUserOrDefault) -> None:"""Raise 403 if the current user is not the direct owner of the video.@@ -124,28 +109,6 @@ def _assert_video_direct_owner(video_name: str, current_user: CurrentUserOrDefauraise HTTPException(status_code=403, detail="Not authorized to move this video")-def _assert_video_read_access(video_name: str, current_user: CurrentUserOrDefault) -> None:- """Raise 403 if the current user may not view the video."""- from invokeai.app.services.board_records.board_records_common import BoardVisibility-- if current_user.is_admin:- return- owner = ApiDependencies.invoker.services.video_records.get_user_id(video_name)- if owner is not None and owner == current_user.user_id:- return-- board_id = ApiDependencies.invoker.services.board_video_records.get_board_for_video(video_name)- if board_id is not None:- try:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)- if board.board_visibility in (BoardVisibility.Shared, BoardVisibility.Public):- return- except Exception:- pass-- raise HTTPException(status_code=403, detail="Not authorized to access this video")--def _read_video_thumbnail(video_name: str) -> Optional[PILImage.Image]:"""The video's stored first-frame thumbnail, or None if it has none.@@ -793,6 +756,11 @@ def copy_videos_to_board(`move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,because every other caller hands it a temp file. Here the path is the *source's own* file.++ Read access is enough to copy, which means a video on a board shared with you can be copied+ into something you own, and the copy outlives the share. That is deliberate — it is what makes+ a shared board usable as a source — but it is a real widening of what "read-only" means, so it+ is stated rather than left to be discovered."""_assert_board_write_access(board_id, current_user)@@ -827,6 +795,15 @@ def copy_videos_to_board(first_frame=_read_video_thumbnail(video_name),move_source=False,)++ # `create` treats board attachment as best-effort — losing a freshly generated video+ # over a categorization problem would be worse than losing its board. A copy is the+ # other way round: the caller asked for a copy *on a board* and is about to remap a+ # document onto the name we return, so a copy that landed uncategorized is a failure+ # reported as one, not a success with a surprise in it.+ if board_id is not None and video_dto.board_id != board_id:+ raise RuntimeError(f"Copy of {video_name} did not reach board {board_id}")+copied.append(CopiedVideo(source_video_name=video_name, video_name=video_dto.video_name))except Exception:ApiDependencies.invoker.services.logger.error(f"Failed to copy video {video_name}", exc_info=True)diff --git a/invokeai/app/services/board_records/board_records_base.py b/invokeai/app/services/board_records/board_records_base.pyindex 3493a4b4e7..377f6a70b5 100644--- a/invokeai/app/services/board_records/board_records_base.py+++ b/invokeai/app/services/board_records/board_records_base.py@@ -1,4 +1,5 @@from abc import ABC, abstractmethod+from typing import Optionalfrom invokeai.app.services.board_records.board_records_common import BoardChanges, BoardRecord, BoardRecordOrderByfrom invokeai.app.services.shared.pagination import OffsetPaginatedResults@@ -8,11 +9,6 @@ from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionclass BoardRecordStorageBase(ABC):"""Low-level service responsible for interfacing with the board record store."""- @abstractmethod- def delete(self, board_id: str) -> None:- """Deletes a board record."""- pass-@abstractmethoddef delete_if_unclaimed(self, board_id: str) -> bool:"""Delete a board only if no project owns it. Returns whether it was deleted.@@ -28,10 +24,16 @@ class BoardRecordStorageBase(ABC):"""Map board id to owning project id, for the boards that a project owns.Boards with no project are absent from the result. Bulk because board listings would- otherwise issue one lookup per row.+ otherwise issue one lookup per row; chunked internally, because a listing can name every+ board on the install and the query is parameterized per id."""pass+ @abstractmethod+ def get_with_project_id(self, board_id: str) -> tuple[BoardRecord, Optional[str]]:+ """The board record and the id of the project that claims it, if any, in one query."""+ pass+@abstractmethoddef save(self,diff --git a/invokeai/app/services/board_records/board_records_common.py b/invokeai/app/services/board_records/board_records_common.pyindex b263f264cb..9eefe43b50 100644--- a/invokeai/app/services/board_records/board_records_common.py+++ b/invokeai/app/services/board_records/board_records_common.py@@ -78,8 +78,19 @@ def deserialize_board_record(board_dict: dict) -> BoardRecord:)+BOARD_NAME_MAX_LENGTH = 300+"""The longest board name the API accepts.++Lives here because `BoardChanges` is what enforces it. A project's board takes the project's name,+and project names are unbounded, so both the claim path and the migration truncate to this — they+must agree with the generic route or they would write names it then refuses to touch.+"""++class BoardChanges(BaseModel, extra="forbid"):- board_name: Optional[str] = Field(default=None, description="The board's new name.", max_length=300)+ board_name: Optional[str] = Field(+ default=None, description="The board's new name.", max_length=BOARD_NAME_MAX_LENGTH+ )cover_image_name: Optional[str] = Field(default=None, description="The name of the board's new cover image.")archived: Optional[bool] = Field(default=None, description="Whether or not the board is archived")board_visibility: Optional[BoardVisibility] = Field(default=None, description="The visibility of the board.")diff --git a/invokeai/app/services/board_records/board_records_sqlite.py b/invokeai/app/services/board_records/board_records_sqlite.pyindex d545d18130..b3089f58d2 100644--- a/invokeai/app/services/board_records/board_records_sqlite.py+++ b/invokeai/app/services/board_records/board_records_sqlite.py@@ -1,5 +1,5 @@import sqlite3-from typing import Union, cast+from typing import Optional, Union, castfrom invokeai.app.services.board_records.board_records_base import BoardRecordStorageBasefrom invokeai.app.services.board_records.board_records_common import (@@ -16,25 +16,16 @@ from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirectionfrom invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabasefrom invokeai.app.util.misc import uuid_string+# Board ids per `IN (...)`. Well under SQLITE_MAX_VARIABLE_NUMBER on every build, including the+# 999-variable default of older SQLite.+_BOARD_ID_QUERY_CHUNK = 500+class SqliteBoardRecordStorage(BoardRecordStorageBase):def __init__(self, db: SqliteDatabase) -> None:super().__init__()self._db = db- def delete(self, board_id: str) -> None:- with self._db.transaction() as cursor:- try:- cursor.execute(- """--sql- DELETE FROM boards- WHERE board_id = ?;- """,- (board_id,),- )- except Exception as e:- raise BoardRecordDeleteException from e-def delete_if_unclaimed(self, board_id: str) -> bool:with self._db.transaction() as cursor:try:@@ -56,15 +47,49 @@ class SqliteBoardRecordStorage(BoardRecordStorageBase):if not board_ids:return {}- placeholders = ", ".join("?" for _ in board_ids)+ # Chunked because the caller is a board *listing*: an admin's `GET /boards/?all=true`+ # passes every board on the install at once, and one bind parameter per board runs into+ # SQLITE_MAX_VARIABLE_NUMBER — which fails the whole listing rather than degrading.+ claimed: dict[str, str] = {}with self._db.transaction() as cursor:- cursor.execute(- f"""--sql- SELECT board_id, project_id FROM projects WHERE board_id IN ({placeholders});- """,- tuple(board_ids),- )- return {row[0]: row[1] for row in cursor.fetchall()}+ for start in range(0, len(board_ids), _BOARD_ID_QUERY_CHUNK):+ chunk = board_ids[start : start + _BOARD_ID_QUERY_CHUNK]+ placeholders = ", ".join("?" for _ in chunk)+ cursor.execute(+ f"""--sql+ SELECT board_id, project_id FROM projects WHERE board_id IN ({placeholders});+ """,+ tuple(chunk),+ )+ claimed.update({row[0]: row[1] for row in cursor.fetchall()})+ return claimed++ def get_with_project_id(self, board_id: str) -> tuple[BoardRecord, Optional[str]]:+ """The board and the project that claims it, in one query.++ `get_dto` needs both and is called on every authorization check, so asking for them+ separately doubled the round trips — and the transactions, which take a re-entrant lock —+ on the hottest read in the API.+ """+ with self._db.transaction() as cursor:+ try:+ cursor.execute(+ """--sql+ SELECT boards.*, projects.project_id AS claimed_by_project_id+ FROM boards+ LEFT JOIN projects ON projects.board_id = boards.board_id+ WHERE boards.board_id = ?;+ """,+ (board_id,),+ )+ result = cast(Union[sqlite3.Row, None], cursor.fetchone())+ except sqlite3.Error as e:+ raise BoardRecordNotFoundException from e+ if result is None:+ raise BoardRecordNotFoundException+ row = dict(result)+ project_id = row.pop("claimed_by_project_id", None)+ return BoardRecord(**row), project_iddef save(self,diff --git a/invokeai/app/services/boards/boards_base.py b/invokeai/app/services/boards/boards_base.pyindex 5d5ac344f2..4f1d36fb8f 100644--- a/invokeai/app/services/boards/boards_base.py+++ b/invokeai/app/services/boards/boards_base.py@@ -35,20 +35,18 @@ class BoardServiceABC(ABC):"""Updates a board."""pass- @abstractmethod- def delete(- self,- board_id: str,- ) -> None:- """Deletes a board."""- pass-@abstractmethoddef delete_if_unclaimed(self,board_id: str,) -> bool:- """Delete a board only if no project owns it. Returns whether it was deleted."""+ """Delete a board only if no project owns it. Returns whether it was deleted.++ The only deletion there is. An unconditional `delete` used to sit beside this one with no+ callers, which made "a project's board cannot be deleted out from under it" true by+ coincidence rather than by construction — the next caller to reach for the obvious name+ would have silently given it up.+ """pass@abstractmethoddiff --git a/invokeai/app/services/boards/boards_default.py b/invokeai/app/services/boards/boards_default.pyindex d8b2eebff5..2048fcc322 100644--- a/invokeai/app/services/boards/boards_default.py+++ b/invokeai/app/services/boards/boards_default.py@@ -54,11 +54,11 @@ class BoardService(BoardServiceABC):board_record = self.__invoker.services.board_records.save(board_name, user_id)return board_record_to_dto(board_record, None, 0, 0)- def _get_project_id(self, board_id: str) -> Optional[str]:- return self.__invoker.services.board_records.get_project_ids_for_boards([board_id]).get(board_id)-def get_dto(self, board_id: str) -> BoardDTO:- board_record = self.__invoker.services.board_records.get(board_id)+ # One query for the record and its claiming project. `get_dto` is what every authorization+ # check resolves through, so a second lookup here is a second transaction — and the lock it+ # takes — on the most-travelled read in the API.+ board_record, project_id = self.__invoker.services.board_records.get_with_project_id(board_id)cover_image_name, cover_video_name = self._resolve_cover(board_record.board_id)image_count, video_count, asset_count = self._get_counts(board_id)return board_record_to_dto(@@ -68,7 +68,7 @@ class BoardService(BoardServiceABC):asset_count,cover_video_name=cover_video_name,video_count=video_count,- project_id=self._get_project_id(board_id),+ project_id=project_id,)def update(@@ -76,21 +76,11 @@ class BoardService(BoardServiceABC):board_id: str,changes: BoardChanges,) -> BoardDTO:- board_record = self.__invoker.services.board_records.update(board_id, changes)- cover_image_name, cover_video_name = self._resolve_cover(board_record.board_id)- image_count, video_count, asset_count = self._get_counts(board_id)- return board_record_to_dto(- board_record,- cover_image_name,- image_count,- asset_count,- cover_video_name=cover_video_name,- video_count=video_count,- project_id=self._get_project_id(board_id),- )-- def delete(self, board_id: str) -> None:- self.__invoker.services.board_records.delete(board_id)+ self.__invoker.services.board_records.update(board_id, changes)+ # Re-read through `get_dto` rather than shaping the update's own return: it is the one+ # place that resolves cover, counts and claiming project together, and an update that+ # dropped `project_id` would tell the gallery a project's board is an ordinary one.+ return self.get_dto(board_id)def delete_if_unclaimed(self, board_id: str) -> bool:return self.__invoker.services.board_records.delete_if_unclaimed(board_id)diff --git a/invokeai/app/services/project_records/project_records_common.py b/invokeai/app/services/project_records/project_records_common.pyindex b3b0615e20..2d014a00c5 100644--- a/invokeai/app/services/project_records/project_records_common.py+++ b/invokeai/app/services/project_records/project_records_common.py@@ -51,6 +51,24 @@ class ProjectBoardUnavailableError(Exception):super().__init__(f"Board {board_id} is not available to be claimed by a project")+PROJECT_BOARD_SNAPSHOT_MAX_ITEMS = 20_000+"""The largest board the snapshot route will enumerate.++The snapshot is unpaginated on purpose — the caller that needs it, exporting a project, has to hold+the whole list anyway. That is a reason not to page it, not a reason to have no ceiling: the answer+is built entirely in memory and any client with a project id can ask for it. Matched to the+archive's own `INVK_MAX_ENTRIES`, so a board this route refuses is one the export could not have+packed either.+"""+++class ProjectBoardTooLargeError(Exception):+ """Raised when a project's board holds more than the snapshot route will enumerate."""++ def __init__(self, project_id: str, limit: int) -> None:+ super().__init__(f"Project {project_id} has more than {limit} items on its board")++class ProjectSummaryDTO(BaseModel):"""Lightweight project listing entry; the document payload is omitted."""diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.pyindex 2350474756..668a9208ae 100644--- a/invokeai/app/services/project_records/project_records_sqlite.py+++ b/invokeai/app/services/project_records/project_records_sqlite.py@@ -3,13 +3,16 @@ import sqlite3import uuidfrom typing import Any, Optional-from invokeai.app.services.board_records.board_records_common import BoardVisibility+from invokeai.app.services.board_records.board_records_common import BOARD_NAME_MAX_LENGTH, BoardVisibility+from invokeai.app.services.image_records.image_records_common import ASSETS_CATEGORIES, IMAGE_CATEGORIESfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.project_records.project_records_base import ProjectRecordsStorageBasefrom invokeai.app.services.project_records.project_records_common import (+ PROJECT_BOARD_SNAPSHOT_MAX_ITEMS,ProjectBoardItemDTO,ProjectBoardNotFoundError,ProjectBoardSnapshotDTO,+ ProjectBoardTooLargeError,ProjectBoardUnavailableError,ProjectRecordConflictError,ProjectRecordDTO,@@ -20,9 +23,12 @@ from invokeai.app.services.project_records.project_records_common import (from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabasefrom invokeai.app.util.misc import uuid_string-# `BoardChanges.board_name` caps names at 300 characters. Project names are unbounded, so the board-# carrying a project's name is truncated to stay inside what the generic board API would accept.-BOARD_NAME_MAX_LENGTH = 300+# The categories a board view lists, straight from the gallery's own definition of them. Spelling+# them out in the SQL below would put a fourth copy of this list in the least discoverable place+# there is: `other` — the canvas's private category — is in neither, which is exactly why the+# snapshot must not carry it, and that reasoning belongs with the constants that encode it.+_VISIBLE_BOARD_CATEGORIES = tuple(category.value for category in (*IMAGE_CATEGORIES, *ASSETS_CATEGORIES))+_VISIBLE_CATEGORY_PLACEHOLDERS = ", ".join("?" for _ in _VISIBLE_BOARD_CATEGORIES)class ProjectRecordsSqlite(ProjectRecordsStorageBase):@@ -74,7 +80,11 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):except sqlite3.IntegrityError as e:# The board insert/rename rolls back with the project insert, so a rejected create never# leaves an orphan board behind.- raise self._classify_integrity_error(e, project_id=project_id, board_id=board_id) from e+ classified = self._classify_integrity_error(e, project_id=project_id, board_id=board_id)++ if classified is None:+ raise+ raise classified from ereturn self.get(user_id, project_id)@@ -216,21 +226,24 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):# One union over both namespaces, shaped like `get_board_media_summaries`. The filters# are what make the result match what the gallery shows for this board: intermediates- # are hidden, and `other` — the canvas's private category — is in neither- # IMAGE_CATEGORIES nor ASSETS_CATEGORIES and so appears in no board view.+ # are hidden, and the categories come from IMAGE_CATEGORIES/ASSETS_CATEGORIES, which+ # `other` — the canvas's private category — is deliberately in neither of.## `deleted_at` is deliberately *not* filtered. Soft delete is unused and no other# board query consults it, so filtering here would make the snapshot disagree with the# counts shown beside the board.+ #+ # Bounded, unlike the counts: the caller holds the whole answer in memory and so does+ # this, and the route is reachable by anyone with a project id.cursor.execute(- """--sql+ f"""--sqlSELECT 'image' AS kind, images.image_name AS name,images.image_category AS category, images.starred AS starredFROM board_imagesINNER JOIN images ON board_images.image_name = images.image_nameWHERE board_images.board_id = ?AND images.is_intermediate = FALSE- AND images.image_category IN ('general', 'control', 'mask', 'user')+ AND images.image_category IN ({_VISIBLE_CATEGORY_PLACEHOLDERS})UNION ALLSELECT 'video' AS kind, videos.video_name AS name,videos.video_category AS category, videos.starred AS starred@@ -238,13 +251,23 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):INNER JOIN videos ON board_videos.video_name = videos.video_nameWHERE board_videos.board_id = ?AND videos.is_intermediate = FALSE- AND videos.video_category IN ('general', 'control', 'mask', 'user')- ORDER BY kind ASC, name ASC;+ AND videos.video_category IN ({_VISIBLE_CATEGORY_PLACEHOLDERS})+ ORDER BY kind ASC, name ASC+ LIMIT ?;""",- (row[0], row[0]),+ (+ row[0],+ *_VISIBLE_BOARD_CATEGORIES,+ row[0],+ *_VISIBLE_BOARD_CATEGORIES,+ PROJECT_BOARD_SNAPSHOT_MAX_ITEMS + 1,+ ),)rows = cursor.fetchall()+ if len(rows) > PROJECT_BOARD_SNAPSHOT_MAX_ITEMS:+ raise ProjectBoardTooLargeError(project_id, PROJECT_BOARD_SNAPSHOT_MAX_ITEMS)+return ProjectBoardSnapshotDTO(items=[ProjectBoardItemDTO(kind=r[0], name=r[1], category=r[2], starred=bool(r[3])) for r in rows])@@ -315,13 +338,22 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):@staticmethoddef _classify_integrity_error(error: sqlite3.IntegrityError, *, project_id: str, board_id: Optional[str]- ) -> Exception:- """Name which uniqueness a rejected insert violated.+ ) -> Optional[Exception]:+ """Name which constraint a rejected insert violated, or `None` to let it through unchanged.++ Two are expected: the composite primary key, meaning the user already has this project id,+ and `projects.board_id`, meaning another project claimed the board between `_claim_board`+ looking and this insert committing.- Two constraints can reject the same statement: the composite primary key, meaning the user- already has this project id, and `projects.board_id`, meaning another project claimed the- board after `_claim_board` looked.+ Decided on `sqlite_errorname` rather than on the message text. A substring match would call+ a foreign-key failure — a user row that vanished, say — "project already exists", sending+ the client to pick a new id forever over a problem no new id can fix. Anything unrecognized+ is re-raised as itself rather than guessed at."""- if board_id is not None and "projects.board_id" in str(error):+ errorname = getattr(error, "sqlite_errorname", "")++ if errorname == "SQLITE_CONSTRAINT_UNIQUE" and board_id is not None:return ProjectBoardUnavailableError(board_id)- return ProjectRecordExistsError(project_id)+ if errorname == "SQLITE_CONSTRAINT_PRIMARYKEY":+ return ProjectRecordExistsError(project_id)+ return Nonediff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.pyindex 5b54209278..b7a9c6c08e 100644--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_08_06_add_project_boards.py@@ -9,7 +9,7 @@ exist there.This migration moves the relationship into the schema: `projects.board_id` becomes `NOT NULL UNIQUE`with a foreign key to `boards`. The `UNIQUE` makes "a board belongs to at most one project" a-database fact, and the FK's default `RESTRICT` makes "a claimed board cannot be deleted" one too,+database fact, and the FK makes "a claimed board cannot be deleted" one too,backing the application's 409 rather than merely agreeing with it.Existing projects keep the board they were already using **only when that is unambiguously safe**.@@ -27,6 +27,7 @@ and a new name.import jsonimport sqlite3+from logging import Loggerfrom typing import Any, Optionalfrom invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration@@ -34,38 +35,85 @@ from invokeai.app.util.misc import uuid_string# `BoardChanges.board_name` caps names at 300 characters. Project names are unbounded, so a board# adopting a project's name is truncated to stay inside what the generic board API would accept.+#+# Pinned here rather than imported from `board_records_common`, deliberately: a migration has to+# keep doing what it did on the day it shipped, and a database migrated at 300 does not un-migrate+# itself if that ceiling later moves.BOARD_NAME_MAX_LENGTH = 300class AddProjectBoardsMigrationCallback:+ def __init__(self, logger: Logger) -> None:+ self._logger = logger+def __call__(self, cursor: sqlite3.Cursor) -> None:+ self._drop_orphaned_projects(cursor)assignments = self._assign_boards(cursor)self._rebuild_projects_table(cursor, assignments)+ def _drop_orphaned_projects(self, cursor: sqlite3.Cursor) -> None:+ """Remove project rows whose owner no longer exists.++ The rebuilt table re-inserts every row under `FOREIGN KEY (user_id) REFERENCES users`, with+ `PRAGMA foreign_keys = ON` and no way to turn it off inside the migrator's transaction. The+ old table tolerated an orphan; the new one aborts on it, which would take the whole+ migration — and with it the app's ability to open the database — over a row nothing can+ reach. They are unreachable already: every project query filters by `user_id`.+ """+ cursor.execute(+ """--sql+ SELECT project_id, user_id FROM projects+ WHERE user_id NOT IN (SELECT user_id FROM users);+ """+ )+ orphans = cursor.fetchall()++ if not orphans:+ return++ for project_id, user_id in orphans:+ self._logger.warning(+ f"Project boards migration: dropping project {project_id}, whose owner {user_id} no longer exists."+ )++ cursor.execute(+ """--sql+ DELETE FROM projects WHERE user_id NOT IN (SELECT user_id FROM users);+ """+ )+def _assign_boards(self, cursor: sqlite3.Cursor) -> list[tuple[int, str]]:"""Resolve one board per project, creating boards as needed.Returns (rowid, board_id) pairs. Projects are visited in `rowid` order so that when two ofthem name the same board the earlier one wins, deterministically and repeatably.++ Read one row at a time, through a cursor of its own. `data` is a whole project document —+ canvas layers, queue history, the lot — so a `fetchall()` here would hold every project on+ the install in memory at once, and this runs at startup on a machine that is about to load+ models. The second cursor is what makes that safe: the writes below run on `cursor`, and+ issuing them on the cursor being iterated would discard the result set out from under it."""- cursor.execute(+ reader = cursor.connection.cursor()+ reader.execute("""--sql- SELECT rowid, user_id, name, data FROM projects ORDER BY rowid ASC;+ SELECT rowid, project_id, user_id, name, data FROM projects ORDER BY rowid ASC;""")- projects = cursor.fetchall()assignments: list[tuple[int, str]] = []# Boards claimed earlier in this run. The column does not exist yet, so this set is the only# record of what has already been spoken for.claimed: set[str] = set()+ adopted = 0- for rowid, user_id, name, data in projects:- board_id = self._adopt_board(cursor, user_id=user_id, data=data, claimed=claimed)+ for rowid, project_id, user_id, name, data in reader:+ board_id = self._adopt_board(cursor, project_id=project_id, user_id=user_id, data=data, claimed=claimed)if board_id is None:board_id = self._insert_board(cursor, user_id=user_id, name=name)else:+ adopted += 1# Un-archived as well as renamed, and for the same reason the claim path does it:# a project's board follows the project, and the generic board API refuses to# change `archived` on a claimed board. Someone who had archived their project's@@ -81,20 +129,36 @@ class AddProjectBoardsMigrationCallback:claimed.add(board_id)assignments.append((rowid, board_id))+ reader.close()+ self._logger.info(+ f"Project boards migration: {len(assignments)} project(s), {adopted} kept the board they were using."+ )+return assignments- def _adopt_board(self, cursor: sqlite3.Cursor, *, user_id: str, data: str, claimed: set[str]) -> Optional[str]:- """Return the project's existing board if exactly one candidate is safe to adopt."""+ def _adopt_board(+ self, cursor: sqlite3.Cursor, *, project_id: str, user_id: str, data: str, claimed: set[str]+ ) -> Optional[str]:+ """Return the project's existing board if exactly one candidate is safe to adopt.++ Every refusal is logged. A project that adopts nothing starts on a fresh empty board and its+ old gallery contents stay where they are — the right way to be wrong, but invisible: the+ person sees a project that has apparently lost its images, and without this an operator has+ no way to find out which projects were affected or why.+ """candidates = _collect_board_candidates(data)# Two gallery widgets disagreeing about which board is the project's leaves no way to pick# correctly, and guessing would hand a project someone else's media.if len(candidates) != 1:+ if candidates:+ self._log_refusal(project_id, f"its document names {len(candidates)} boards")return Noneboard_id = next(iter(candidates))if board_id in claimed:+ self._log_refusal(project_id, f"board {board_id} was already claimed by an earlier project")return Nonecursor.execute(@@ -111,21 +175,31 @@ class AddProjectBoardsMigrationCallback:row = cursor.fetchone()if row is None:+ self._log_refusal(project_id, f"board {board_id} no longer exists")return Noneboard_user_id, board_visibility, is_shared = rowif board_user_id != user_id:+ self._log_refusal(project_id, f"board {board_id} belongs to another account")return None# A project board is private by definition; adopting a shared or public one would lock a# board other people can see into a single project's lifecycle.if board_visibility != "private":+ self._log_refusal(project_id, f"board {board_id} is {board_visibility}, not private")return Noneif is_shared:+ self._log_refusal(project_id, f"board {board_id} is shared with other accounts")return Nonereturn board_id+ def _log_refusal(self, project_id: str, reason: str) -> None:+ self._logger.warning(+ f"Project boards migration: project {project_id} starts on a new empty board because {reason}."+ " Its previous board and everything on it are untouched."+ )+def _insert_board(self, cursor: sqlite3.Cursor, *, user_id: str, name: str) -> str:board_id = uuid_string()cursor.execute(@@ -159,8 +233,9 @@ class AddProjectBoardsMigrationCallback:-- Opaque client-owned project document (JSON).data TEXT NOT NULL,-- The project's private board. UNIQUE is what makes "at most one project per board"- -- a schema fact; the FK's default RESTRICT is what stops a claimed board being- -- deleted through the generic board API.+ -- a schema fact; RESTRICT is what stops a claimed board being deleted through the+ -- generic board API. Spelled out rather than left to the default: SQLite's default+ -- is NO ACTION, which behaves identically only while the constraint is immediate.board_id TEXT NOT NULL UNIQUE,-- Incremented on every update; used for optimistic concurrency.revision INTEGER NOT NULL DEFAULT 1,@@ -168,7 +243,7 @@ class AddProjectBoardsMigrationCallback:updated_at DATETIME NOT NULL DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')),PRIMARY KEY (user_id, project_id),FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE,- FOREIGN KEY (board_id) REFERENCES boards(board_id)+ FOREIGN KEY (board_id) REFERENCES boards(board_id) ON DELETE RESTRICT);""")@@ -248,12 +323,16 @@ def _add_candidate(candidates: set[str], values: Any) -> None:candidates.add(board_id)-def build_migration() -> Migration:- """Build the migration that gives every project its own board."""+def build_migration(logger: Logger) -> Migration:+ """Build the migration that gives every project its own board.++ Takes the logger because this migration can decline to adopt a board, and a project that+ silently starts on an empty one looks to its owner like a project that lost its images.+ """return Migration(id="2026_08_06_add_project_boards",# The repair migration is what guarantees `projects` exists at all on databases that were# ever opened by an upstream build; it transitively guarantees `boards` and `shared_boards`.depends_on="2026_07_30_repair_projects_table",- callback=AddProjectBoardsMigrationCallback(),+ callback=AddProjectBoardsMigrationCallback(logger),)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex a445e0fc16..5c0138fae8 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -5775,7 +5775,7 @@"post": {"tags": ["images"],"summary": "Copy Images To Board",- "description": "Copies images, optionally onto a board, and returns the new names.\n\nEach copy is a genuinely new image with its own name, because `board_images` keys on\n`image_name` \u2014 one image can sit on exactly one board, so sharing a name between two boards is\nnot representable. Duplicating a project needs that: its copy must own its media outright.\n\nThe pixels never leave the server, and never leave the disk either: `images.copy` clones the\nrecord and copies the file byte for byte, so the embedded metadata, workflow and graph travel\nwithout being parsed and rewritten. Category and origin travel; the originating session and\nnode do not. Starring is not copied \u2014 callers that want it use `POST /images/star`, the same\npath an import uses.\n\nPer-image failures are reported rather than raised, so one unreadable source cannot cost the\ncaller the whole batch.\n\nA sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and a\nboard's worth of them on the event loop would stall every other request for the duration.",+ "description": "Copies images, optionally onto a board, and returns the new names.\n\nEach copy is a genuinely new image with its own name, because `board_images` keys on\n`image_name` \u2014 one image can sit on exactly one board, so sharing a name between two boards is\nnot representable. Duplicating a project needs that: its copy must own its media outright.\n\nThe pixels never leave the server, and never leave the disk either: `images.copy` clones the\nrecord and copies the file byte for byte, so the embedded metadata, workflow and graph travel\nwithout being parsed and rewritten. Category and origin travel; the originating session and\nnode do not. Starring is not copied \u2014 callers that want it use `POST /images/star`, the same\npath an import uses.\n\nPer-image failures are reported rather than raised, so one unreadable source cannot cost the\ncaller the whole batch.\n\nA sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and a\nboard's worth of them on the event loop would stall every other request for the duration.\n\nRead access is enough to copy, which means an image on a board shared with you can be copied\ninto something you own, and the copy outlives the share. That is deliberate \u2014 it is what makes\na shared board usable as a source \u2014 but it is a real widening of what \"read-only\" means, so it\nis stated rather than left to be discovered.","operationId": "copy_images_to_board","requestBody": {"content": {@@ -7238,7 +7238,7 @@"post": {"tags": ["videos"],"summary": "Copy Videos To Board",- "description": "Copies videos, optionally onto a board, and returns the new names.\n\nThe image twin of this route explains why copies rather than shared references: `board_videos`\nkeys on `video_name`, so one video sits on exactly one board.\n\nBlocking work (the service copies the file off disk) runs on FastAPI's threadpool by virtue of\nthis being a sync `def`, so a large batch cannot stall the event loop.\n\n`move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,\nbecause every other caller hands it a temp file. Here the path is the *source's own* file.",+ "description": "Copies videos, optionally onto a board, and returns the new names.\n\nThe image twin of this route explains why copies rather than shared references: `board_videos`\nkeys on `video_name`, so one video sits on exactly one board.\n\nBlocking work (the service copies the file off disk) runs on FastAPI's threadpool by virtue of\nthis being a sync `def`, so a large batch cannot stall the event loop.\n\n`move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,\nbecause every other caller hands it a temp file. Here the path is the *source's own* file.\n\nRead access is enough to copy, which means a video on a board shared with you can be copied\ninto something you own, and the copy outlives the share. That is deliberate \u2014 it is what makes\na shared board usable as a source \u2014 but it is a real widening of what \"read-only\" means, so it\nis stated rather than left to be discovered.","operationId": "copy_videos_to_board","requestBody": {"content": {@@ -12870,7 +12870,7 @@"delete": {"tags": ["projects"],"summary": "Delete Project",- "description": "Deletes one of the current user's projects. Idempotent.",+ "description": "Deletes one of the current user's projects, and the board it owns, in one transaction.\n\nIdempotent. The media survives: deleting the board drops its memberships, so the images and\nvideos on it return to Uncategorized, exactly as they would if the board were deleted without\n`include_images`. There is deliberately no option to take them with it \u2014 a project is a\nworkspace, and emptying someone's gallery is not what deleting one should be able to mean.\nNothing is reported back for the same reason: nothing was destroyed to report.","operationId": "delete_project","security": [{@@ -12911,7 +12911,7 @@"get": {"tags": ["projects"],"summary": "Get Project Board Snapshot",- "description": "Lists everything on the project's board that the gallery would show.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway, and enforces its own\narchive limits over it.",+ "description": "Lists everything on the project's board that the gallery would show.\n\nIntermediates and the canvas's private `other` category are excluded. Unpaginated: the caller\nthat needs this \u2014 exporting a project \u2014 has to hold the whole list anyway. It is still bounded,\nbecause the answer is built entirely in memory and any client with a project id can ask for it;\na board past the ceiling is one an export could not have packed either, so it is refused as a\n413 rather than paged.","operationId": "get_project_board_snapshot","security": [{diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex f40ea1e6b3..aa9d1d02dc 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1390,6 +1390,11 @@ export type paths = {** A sync `def`, so FastAPI runs the batch on its threadpool: file copies are blocking, and a* board's worth of them on the event loop would stall every other request for the duration.+ *+ * Read access is enough to copy, which means an image on a board shared with you can be copied+ * into something you own, and the copy outlives the share. That is deliberate — it is what makes+ * a shared board usable as a source — but it is a real widening of what "read-only" means, so it+ * is stated rather than left to be discovered.*/post: operations["copy_images_to_board"];delete?: never;@@ -1754,6 +1759,11 @@ export type paths = {** `move_source=False` is load-bearing, not defensive: `create` consumes the path it is given,* because every other caller hands it a temp file. Here the path is the *source's own* file.+ *+ * Read access is enough to copy, which means a video on a board shared with you can be copied+ * into something you own, and the copy outlives the share. That is deliberate — it is what makes+ * a shared board usable as a source — but it is a real widening of what "read-only" means, so it+ * is stated rather than left to be discovered.*/post: operations["copy_videos_to_board"];delete?: never;@@ -3330,7 +3340,13 @@ export type paths = {post?: never;/*** Delete Project- * @description Deletes one of the current user's projects. Idempotent.+ * @description Deletes one of the current user's projects, and the board it owns, in one transaction.+ *+ * Idempotent. The media survives: deleting the board drops its memberships, so the images and+ * videos on it return to Uncategorized, exactly as they would if the board were deleted without+ * `include_images`. There is deliberately no option to take them with it — a project is a+ * workspace, and emptying someone's gallery is not what deleting one should be able to mean.+ * Nothing is reported back for the same reason: nothing was destroyed to report.*/delete: operations["delete_project"];options?: never;@@ -3350,8 +3366,10 @@ export type paths = {* @description Lists everything on the project's board that the gallery would show.** Intermediates and the canvas's private `other` category are excluded. Unpaginated: the caller- * that needs this — exporting a project — has to hold the whole list anyway, and enforces its own- * archive limits over it.+ * that needs this — exporting a project — has to hold the whole list anyway. It is still bounded,+ * because the answer is built entirely in memory and any client with a project id can ask for it;+ * a board past the ceiling is one an export could not have packed either, so it is refused as a+ * 413 rather than paged.*/get: operations["get_project_board_snapshot"];put?: never;diff --git a/tests/app/routers/test_media_copy.py b/tests/app/routers/test_media_copy.pyindex 5b64da9ca4..b5fa1441ca 100644--- a/tests/app/routers/test_media_copy.py+++ b/tests/app/routers/test_media_copy.py@@ -263,6 +263,8 @@ def test_copying_a_video_preserves_its_shape_and_provenance(videos.get_graph.return_value = Nonecreated = MagicMock()created.video_name = "copy-001.mp4"+ # The route checks the copy actually landed where it was told, so the double has to say so.+ created.board_id = board_idvideos.create.return_value = createdmock_invoker.services.videos = videos@@ -286,6 +288,35 @@ def test_copying_a_video_preserves_its_shape_and_provenance(assert kwargs["move_source"] is False+def test_a_video_copy_that_missed_its_board_is_reported_as_failed(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ """`create` treats board attachment as best-effort, which is right for a generation and wrong+ here: the caller is about to remap a document onto the name we return."""+ user_id = _owner_id(client, user1_token)+ board_id = _create_board(client, user1_token, "Video+Target")+ _insert_video_record(mock_invoker, "src.mp4", user_id)++ videos = MagicMock()+ videos.get_path.return_value = "/tmp/source.mp4"+ videos.get_metadata.return_value = None+ videos.get_workflow.return_value = None+ videos.get_graph.return_value = None+ created = MagicMock()+ created.video_name = "copy-001.mp4"+ created.board_id = None # The attachment silently did not happen.+ videos.create.return_value = created+ mock_invoker.services.videos = videos++ response = client.post(+ "/api/v1/videos/copy",+ json={"video_names": ["src.mp4"], "board_id": board_id},+ headers=_auth(user1_token),+ )++ assert response.json() == {"copied": [], "failed": ["src.mp4"]}++def test_copying_someone_elses_video_is_refused_per_name(client: TestClient, mock_invoker: Invoker, user1_token: str):_owner_id(client, user1_token)_insert_video_record(mock_invoker, "theirs.mp4", "somebody-else")diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.pyindex 759c16515c..610c1b9da5 100644--- a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py@@ -145,8 +145,11 @@ def _board_of(db: sqlite3.Connection, project_id: str, user_id: str = "u1") -> sreturn row[0]-def _run(db: sqlite3.Connection) -> None:- AddProjectBoardsMigrationCallback()(db.cursor())+def _run(db: sqlite3.Connection) -> AddProjectBoardsMigrationCallback:+ """Run the migration, handing back the callback so a test can inspect what it reported."""+ callback = AddProjectBoardsMigrationCallback(Logger("migration-test"))+ callback(db.cursor())+ return callback# --- adoption -------------------------------------------------------------------------------@@ -303,6 +306,50 @@ def test_an_adopted_board_is_un_archived() -> None:assert archived == 0+def test_a_refused_adoption_is_logged_with_its_reason() -> None:+ """A project that adopts nothing looks, to its owner, like a project that lost its images.+ Nothing else records which projects were affected or why."""+ db = _make_db()+ _add_user(db, "u1")+ _add_user(db, "u2")+ _add_board(db, "theirs", user_id="u2")+ _add_project(db, "p1", name="Mine", data=_gallery_document("theirs"))++ logger = Logger("migration-test")+ warnings: list[str] = []+ logger.warning = warnings.append # type: ignore[method-assign]+ AddProjectBoardsMigrationCallback(logger)(db.cursor())++ assert len(warnings) == 1+ assert "p1" in warnings[0]+ assert "another account" in warnings[0]+++def test_a_project_whose_owner_is_gone_is_dropped_rather_than_failing_the_migration() -> None:+ """The rebuilt table enforces the users foreign key that the old one did not. An orphan would+ abort the migration, and with it the app's ability to open the database at all."""+ db = _make_db()+ _add_user(db, "u1")+ _add_project(db, "kept", name="Kept")+ # Straight past the foreign key, the way a database that once ran without enforcement would.+ # The commit matters: the pragma is a no-op inside a transaction, and the insert above opened+ # one implicitly.+ db.commit()+ db.execute("PRAGMA foreign_keys = OFF;")+ _add_project(db, "orphan", user_id="gone", name="Orphan")+ db.commit()+ db.execute("PRAGMA foreign_keys = ON;")++ logger = Logger("migration-test")+ warnings: list[str] = []+ logger.warning = warnings.append # type: ignore[method-assign]+ AddProjectBoardsMigrationCallback(logger)(db.cursor())++ assert _board_of(db, "kept")+ assert db.execute("SELECT COUNT(*) FROM projects;").fetchone()[0] == 1+ assert any("orphan" in warning for warning in warnings)++def test_a_long_project_name_is_truncated_to_what_the_board_api_accepts() -> None:db = _make_db()_add_user(db, "u1")@@ -442,7 +489,7 @@ def test_an_empty_projects_table_migrates_cleanly() -> None:def test_migration_has_a_dated_id_and_depends_on_the_projects_repair() -> None:- migration = build_migration()+ migration = build_migration(Logger("test"))assert migration.id == MIGRATION_IDassert migration.depends_on == "2026_07_30_repair_projects_table"assert migration.from_version is Nonediff --git a/tests/app/services/test_sql_injection_protection.py b/tests/app/services/test_sql_injection_protection.pyindex 4efd7b0b8d..bf5867f217 100644--- a/tests/app/services/test_sql_injection_protection.py+++ b/tests/app/services/test_sql_injection_protection.py@@ -49,7 +49,9 @@ def test_sql_injection_payload_in_delete_does_not_delete_other_rows() -> None:second = storage.save("second board", "0")payload = f"{first.board_id}' OR '1'='1"- storage.delete(payload)+ # `delete_if_unclaimed` is the only deletion there is; the unconditional `delete` beside it had+ # no callers and bypassed the project guard, so it went.+ assert storage.delete_if_unclaimed(payload) is Falseremaining = storage.get_many(order_by=BoardRecordOrderBy.CreatedAt,