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
feat(projects): bound project document persistence
Josh Corbettcfc4e7d2b174
diff --git a/invokeai/app/api/routers/projects.py b/invokeai/app/api/routers/projects.pyindex c9946ac653..a76bbcd873 100644--- a/invokeai/app/api/routers/projects.py+++ b/invokeai/app/api/routers/projects.py@@ -8,12 +8,15 @@ from invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.project_records.project_records_common import (DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,+ PROJECT_DOCUMENT_MAX_BYTES,ProjectBoardNotFoundError,ProjectBoardSnapshotDTO,ProjectBoardTooLargeError,ProjectBoardUnavailableError,ProjectCanvasSchemaDowngradeError,ProjectCanvasSchemaUnsupportedError,+ ProjectDocumentInvalidError,+ ProjectDocumentTooLargeError,ProjectRecordConflictError,ProjectRecordDTO,ProjectRecordExistsError,@@ -23,6 +26,12 @@ from invokeai.app.services.project_records.project_records_common import (projects_router = APIRouter(prefix="/v1/projects", tags=["projects"])+PROJECT_WRITE_REQUEST_MAX_BYTES = PROJECT_DOCUMENT_MAX_BYTES + 2 * 1024 * 1024+MAX_CONCURRENT_PROJECT_WRITES = 2+MAX_CONCURRENT_PROJECT_WRITES_PER_USER = 1+PROJECT_WRITE_IDLE_TIMEOUT_SECONDS = 30.0+PROJECT_WRITE_MAX_DURATION_SECONDS = 120.0+class ProjectCreateRequest(BaseModel):"""Request body for creating a project."""@@ -82,6 +91,25 @@ def _schema_precondition_failed(error: ProjectCanvasSchemaUnsupportedError) -> H)+def _document_too_large(error: ProjectDocumentTooLargeError) -> HTTPException:+ return HTTPException(+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ detail={+ "code": "project_document_too_large",+ "message": str(error),+ "max_bytes": error.max_bytes,+ "actual_bytes": error.actual_bytes,+ },+ )+++def _document_invalid(error: ProjectDocumentInvalidError) -> HTTPException:+ return HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,+ detail={"code": "project_document_invalid", "message": str(error)},+ )++@projects_router.get("/", operation_id="list_projects", response_model=list[ProjectSummaryDTO])def list_projects(current_user: CurrentUserOrDefault) -> list[ProjectSummaryDTO]:"""Lists the current user's projects as lightweight summaries (no documents)."""@@ -112,6 +140,10 @@ def create_project(raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))except ProjectCanvasSchemaUnsupportedError as e:raise _schema_precondition_failed(e)+ except ProjectDocumentTooLargeError as e:+ raise _document_too_large(e)+ except ProjectDocumentInvalidError as e:+ raise _document_invalid(e)@projects_router.get("/{project_id}", operation_id="get_project", response_model=ProjectRecordDTO)@@ -171,6 +203,10 @@ def update_project()except ProjectCanvasSchemaUnsupportedError as e:raise _schema_precondition_failed(e)+ except ProjectDocumentTooLargeError as e:+ raise _document_too_large(e)+ except ProjectDocumentInvalidError as e:+ raise _document_invalid(e)@projects_router.get(diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.pyindex 8b42e6b91b..2a476a0b27 100644--- a/invokeai/app/api_app.py+++ b/invokeai/app/api_app.py@@ -343,35 +343,34 @@ async def _identify_video_upload_user_async(scope: Scope) -> tuple[bool, str | Nreturn await run_in_threadpool(_identify_video_upload_user, scope)-class VideoUploadLimitASGIMiddleware:- """Bound video-upload ingress *before* FastAPI's multipart parser runs.-- The upload route's own MAX_UPLOAD_SIZE check only fires after the multipart body has- been fully parsed (and spooled to temp storage), so oversized, chunked, or many- concurrent uploads could exhaust temp space before ever being rejected. This- middleware rejects oversized requests from the Content-Length header, aborts- chunked bodies that exceed the cap mid-stream, and bounds concurrent uploads- both globally and per user (so one tenant's slow uploads cannot starve the- others into 429s).- """+class RequestBodyLimitASGIMiddleware:+ """Bound selected request bodies before framework parsing and buffering."""def __init__(self,app: ASGIApp,+ matches_request: Callable[[str, str], bool],+ too_large_detail: Callable[[int, int], str | dict[str, object]],+ capacity_refusal_detail: Callable[[bool], str | dict[str, object]],max_body_bytes: int,max_concurrent: int,max_concurrent_per_user: int | None = None,identify_user: Callable[[Scope], tuple[bool, str | None] | Awaitable[tuple[bool, str | None]]] | None = None,idle_timeout_seconds: float = 120.0,max_upload_duration_seconds: float = 30 * 60,+ retry_after_seconds: int = 5,) -> None:self.app = app+ self.matches_request = matches_request+ self.too_large_detail = too_large_detail+ self.capacity_refusal_detail = capacity_refusal_detailself.max_body_bytes = max_body_bytesself.max_concurrent = max_concurrentself.max_concurrent_per_user = max_concurrent_per_userself.identify_user = identify_userself.idle_timeout_seconds = idle_timeout_secondsself.max_upload_duration_seconds = max_upload_duration_seconds+ self.retry_after_seconds = retry_after_secondsself._active = 0self._active_by_user: dict[str, int] = {}@@ -380,7 +379,7 @@ class VideoUploadLimitASGIMiddleware:return await self.app(scope, receive, send)# Behind a sub-path proxy the public path carries the prefix (see SubPathASGIMiddleware).route_path: str = scope.get("path", "").removeprefix(scope.get("root_path", ""))- if not (scope.get("method") == "POST" and route_path == "/api/v1/videos/upload"):+ if not self.matches_request(scope.get("method", ""), route_path):return await self.app(scope, receive, send)per_user_key: str | None = None@@ -398,36 +397,38 @@ class VideoUploadLimitASGIMiddleware:return await response(scope, receive, send)content_length = Headers(scope=scope).get("content-length")- if content_length is not None and content_length.isdigit() and int(content_length) > self.max_body_bytes:+ content_length_bytes = int(content_length) if content_length is not None and content_length.isdigit() else None+ if content_length_bytes is not None and content_length_bytes > self.max_body_bytes:response = JSONResponse(- {"detail": f"Video upload exceeds maximum request size ({self.max_body_bytes} bytes)"},+ {"detail": self.too_large_detail(content_length_bytes, self.max_body_bytes)},status_code=413,)return await response(scope, receive, send)+ def has_capacity() -> bool:+ return self._active < self.max_concurrent and (+ per_user_key is None+ or self.max_concurrent_per_user is None+ or self._active_by_user.get(per_user_key, 0) < self.max_concurrent_per_user+ )+if self._active >= self.max_concurrent:response = JSONResponse(- {"detail": "Too many concurrent video uploads; try again shortly"},+ {"detail": self.capacity_refusal_detail(False)},status_code=429,- headers={"Retry-After": "5"},+ headers={"Retry-After": str(self.retry_after_seconds)},)return await response(scope, receive, send)- if (- per_user_key is not None- and self.max_concurrent_per_user is not None- and self._active_by_user.get(per_user_key, 0) >= self.max_concurrent_per_user- ):+ if not has_capacity():response = JSONResponse(- {"detail": "Too many concurrent video uploads for this user; try again shortly"},+ {"detail": self.capacity_refusal_detail(True)},status_code=429,- headers={"Retry-After": "5"},+ headers={"Retry-After": str(self.retry_after_seconds)},)return await response(scope, receive, send)- self._active += 1- if per_user_key is not None:- self._active_by_user[per_user_key] = self._active_by_user.get(per_user_key, 0) + 1+ self._claim_capacity(per_user_key)received = 0upload_started_at = asyncio.get_running_loop().time()@@ -455,13 +456,97 @@ class VideoUploadLimitASGIMiddleware:try:await self.app(scope, limited_receive, send)finally:- self._active -= 1- if per_user_key is not None:- remaining = self._active_by_user.get(per_user_key, 0) - 1- if remaining > 0:- self._active_by_user[per_user_key] = remaining- else:- self._active_by_user.pop(per_user_key, None)+ self._release_capacity(per_user_key)++ def _claim_capacity(self, per_user_key: str | None) -> None:+ self._active += 1+ if per_user_key is not None:+ self._active_by_user[per_user_key] = self._active_by_user.get(per_user_key, 0) + 1++ def _release_capacity(self, per_user_key: str | None) -> None:+ self._active -= 1+ if per_user_key is None:+ return+ remaining = self._active_by_user.get(per_user_key, 0) - 1+ if remaining > 0:+ self._active_by_user[per_user_key] = remaining+ else:+ self._active_by_user.pop(per_user_key, None)+++class VideoUploadLimitASGIMiddleware(RequestBodyLimitASGIMiddleware):+ """Bound video-upload ingress before FastAPI's multipart parser runs."""++ def __init__(+ self,+ app: ASGIApp,+ max_body_bytes: int,+ max_concurrent: int,+ max_concurrent_per_user: int | None = None,+ identify_user: Callable[[Scope], tuple[bool, str | None] | Awaitable[tuple[bool, str | None]]] | None = None,+ idle_timeout_seconds: float = 120.0,+ max_upload_duration_seconds: float = 30 * 60,+ ) -> None:+ super().__init__(+ app=app,+ matches_request=lambda method, path: method == "POST" and path == "/api/v1/videos/upload",+ too_large_detail=lambda _actual, limit: f"Video upload exceeds maximum request size ({limit} bytes)",+ capacity_refusal_detail=lambda per_user: (+ "Too many concurrent video uploads for this user; try again shortly"+ if per_user+ else "Too many concurrent video uploads; try again shortly"+ ),+ max_body_bytes=max_body_bytes,+ max_concurrent=max_concurrent,+ max_concurrent_per_user=max_concurrent_per_user,+ identify_user=identify_user,+ idle_timeout_seconds=idle_timeout_seconds,+ max_upload_duration_seconds=max_upload_duration_seconds,+ )+++def _is_project_write(method: str, path: str) -> bool:+ if method == "POST":+ return path == "/api/v1/projects/"+ if method != "PUT" or not path.startswith("/api/v1/projects/"):+ return False+ project_id = path.removeprefix("/api/v1/projects/")+ return bool(project_id) and "/" not in project_id+++class ProjectWriteLimitASGIMiddleware(RequestBodyLimitASGIMiddleware):+ """Bound project writes before FastAPI parses their JSON documents."""++ def __init__(+ self,+ app: ASGIApp,+ max_body_bytes: int,+ max_concurrent: int,+ max_concurrent_per_user: int | None = None,+ identify_user: Callable[[Scope], tuple[bool, str | None] | Awaitable[tuple[bool, str | None]]] | None = None,+ idle_timeout_seconds: float = 30.0,+ max_upload_duration_seconds: float = 120.0,+ ) -> None:+ super().__init__(+ app=app,+ matches_request=_is_project_write,+ too_large_detail=lambda actual, limit: {+ "actual_bytes": actual,+ "code": "project_request_too_large",+ "max_bytes": limit,+ },+ capacity_refusal_detail=lambda _per_user: {+ "code": "project_write_busy",+ "message": "Too many project saves are in progress; retry shortly",+ },+ max_body_bytes=max_body_bytes,+ max_concurrent=max_concurrent,+ max_concurrent_per_user=max_concurrent_per_user,+ identify_user=identify_user,+ idle_timeout_seconds=idle_timeout_seconds,+ max_upload_duration_seconds=max_upload_duration_seconds,+ retry_after_seconds=1,+ )class SubPathASGIMiddleware:@@ -514,6 +599,15 @@ app.add_middleware(max_concurrent_per_user=videos.MAX_CONCURRENT_VIDEO_UPLOADS_PER_USER,identify_user=_identify_video_upload_user_async,)+app.add_middleware(+ ProjectWriteLimitASGIMiddleware,+ max_body_bytes=projects.PROJECT_WRITE_REQUEST_MAX_BYTES,+ max_concurrent=projects.MAX_CONCURRENT_PROJECT_WRITES,+ max_concurrent_per_user=projects.MAX_CONCURRENT_PROJECT_WRITES_PER_USER,+ identify_user=_identify_video_upload_user_async,+ idle_timeout_seconds=projects.PROJECT_WRITE_IDLE_TIMEOUT_SECONDS,+ max_upload_duration_seconds=projects.PROJECT_WRITE_MAX_DURATION_SECONDS,+)# Add event handlerdiff --git a/invokeai/app/services/project_records/project_records_base.py b/invokeai/app/services/project_records/project_records_base.pyindex 70f09c7d3a..eb2db222cd 100644--- a/invokeai/app/services/project_records/project_records_base.py+++ b/invokeai/app/services/project_records/project_records_base.py@@ -53,6 +53,8 @@ class ProjectRecordsStorageBase(ABC):ProjectBoardNotFoundError: `board_id` is missing or belongs to another user.ProjectBoardUnavailableError: The board is public, shared, or already claimed.ProjectCanvasSchemaUnsupportedError: The caller cannot safely edit the requested schema.+ ProjectDocumentInvalidError: The document is not standards-compliant UTF-8 JSON.+ ProjectDocumentTooLargeError: The project document exceeds the storage limit."""pass@@ -96,6 +98,8 @@ class ProjectRecordsStorageBase(ABC):ProjectRecordConflictError: The stored revision differs from expected_revision.ProjectCanvasSchemaUnsupportedError: The caller cannot safely edit the stored or requested schema.ProjectCanvasSchemaDowngradeError: The save tries to lower the stored compatibility floor.+ ProjectDocumentInvalidError: The document is not standards-compliant UTF-8 JSON.+ ProjectDocumentTooLargeError: The project document exceeds the storage limit."""passdiff --git a/invokeai/app/services/project_records/project_records_common.py b/invokeai/app/services/project_records/project_records_common.pyindex 679605f156..f6dd4b864b 100644--- a/invokeai/app/services/project_records/project_records_common.py+++ b/invokeai/app/services/project_records/project_records_common.py@@ -38,6 +38,26 @@ class ProjectRecordConflictError(Exception):)+PROJECT_DOCUMENT_MAX_BYTES = 32 * 1024 * 1024+"""Maximum compact UTF-8 JSON size accepted for a project document."""+++class ProjectDocumentTooLargeError(Exception):+ """Raised before an oversized project document is written."""++ def __init__(self, actual_bytes: int, max_bytes: int = PROJECT_DOCUMENT_MAX_BYTES) -> None:+ self.actual_bytes = actual_bytes+ self.max_bytes = max_bytes+ super().__init__(f"Project document is {actual_bytes} bytes; the limit is {max_bytes} bytes")+++class ProjectDocumentInvalidError(Exception):+ """Raised when a project document cannot be represented as standards-compliant UTF-8 JSON."""++ def __init__(self) -> None:+ super().__init__("Project document must contain valid UTF-8 JSON values")++class ProjectCanvasSchemaUnsupportedError(Exception):"""Raised before an incapable client may read or write a project document."""diff --git a/invokeai/app/services/project_records/project_records_sqlite.py b/invokeai/app/services/project_records/project_records_sqlite.pyindex 0116d1b4bb..8bc9e4cc92 100644--- a/invokeai/app/services/project_records/project_records_sqlite.py+++ b/invokeai/app/services/project_records/project_records_sqlite.py@@ -10,6 +10,7 @@ from invokeai.app.services.project_records.project_records_base import ProjectRefrom invokeai.app.services.project_records.project_records_common import (DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,PROJECT_BOARD_SNAPSHOT_MAX_ITEMS,+ PROJECT_DOCUMENT_MAX_BYTES,ProjectBoardItemDTO,ProjectBoardNotFoundError,ProjectBoardSnapshotDTO,@@ -17,6 +18,8 @@ from invokeai.app.services.project_records.project_records_common import (ProjectBoardUnavailableError,ProjectCanvasSchemaDowngradeError,ProjectCanvasSchemaUnsupportedError,+ ProjectDocumentInvalidError,+ ProjectDocumentTooLargeError,ProjectRecordConflictError,ProjectRecordDTO,ProjectRecordExistsError,@@ -34,6 +37,19 @@ _VISIBLE_BOARD_CATEGORIES = tuple(category.value for category in (*IMAGE_CATEGOR_VISIBLE_CATEGORY_PLACEHOLDERS = ", ".join("?" for _ in _VISIBLE_BOARD_CATEGORIES)+def _serialize_project_document(data: dict[str, Any]) -> tuple[str, int]:+ try:+ document_json = json.dumps(data, ensure_ascii=False, allow_nan=False, separators=(",", ":"))+ return document_json, len(document_json.encode("utf-8"))+ except (TypeError, ValueError, UnicodeEncodeError) as error:+ raise ProjectDocumentInvalidError from error+++def _require_project_document_size(actual_bytes: int) -> None:+ if actual_bytes > PROJECT_DOCUMENT_MAX_BYTES:+ raise ProjectDocumentTooLargeError(actual_bytes=actual_bytes, max_bytes=PROJECT_DOCUMENT_MAX_BYTES)++class ProjectRecordsSqlite(ProjectRecordsStorageBase):"""SQLite implementation of per-user project document storage.@@ -69,6 +85,8 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):minimum_version=minimum_canvas_schema_version,client_maximum_version=max_canvas_schema_version,)+ document_json, document_bytes = _serialize_project_document(data)+ _require_project_document_size(document_bytes)try:with self._db.transaction() as cursor:@@ -89,7 +107,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):project_id,user_id,name,- json.dumps(data),+ document_json,resolved_board_id,minimum_canvas_schema_version,),@@ -168,6 +186,8 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):minimum_canvas_schema_version: int | None = None,max_canvas_schema_version: int = DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,) -> ProjectRecordDTO:+ document_json, document_bytes = _serialize_project_document(data)+with self._db.transaction() as cursor:cursor.execute("""--sql@@ -208,6 +228,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):minimum_version=next_minimum_version,client_maximum_version=max_canvas_schema_version,)+ _require_project_document_size(document_bytes)cursor.execute("""--sql@@ -217,7 +238,7 @@ class ProjectRecordsSqlite(ProjectRecordsStorageBase):""",(name,- json.dumps(data),+ document_json,next_minimum_version,user_id,project_id,diff --git a/invokeai/frontend/webv2/src/platform/transport/http.test.ts b/invokeai/frontend/webv2/src/platform/transport/http.test.tsindex b3c6802980..d5a5d40e4d 100644--- a/invokeai/frontend/webv2/src/platform/transport/http.test.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.test.ts@@ -6,6 +6,7 @@ vi.mock('./deploymentBase', () => ({}));import {+ ApiError,absolutizeApiUrl,apiFetch,apiFetchJson,@@ -38,6 +39,25 @@ describe('deployment-aware backend URLs', () => {});describe('request identity ownership', () => {+ it('preserves response headers on API errors for Retry-After handling', async () => {+ const identity = {};+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response('{"detail":{"code":"project_write_busy"}}', {+ headers: { 'Retry-After': '1' },+ status: 429,+ })+ )+ );+ configureHttpAuth({ getIdentity: () => identity, getToken: () => null, onUnauthorized: vi.fn() });++ const error = await apiFetch('/api/v1/projects/').catch((error: unknown) => error);++ expect(error).toBeInstanceOf(ApiError);+ expect((error as ApiError).headers.get('Retry-After')).toBe('1');+ });+it('does not expire a newer account when an older request returns 401', async () => {let token: string | null = 'token-a';let identity = {};diff --git a/invokeai/frontend/webv2/src/platform/transport/http.ts b/invokeai/frontend/webv2/src/platform/transport/http.tsindex b183ab2ad3..8531649f9f 100644--- a/invokeai/frontend/webv2/src/platform/transport/http.ts+++ b/invokeai/frontend/webv2/src/platform/transport/http.ts@@ -67,11 +67,13 @@ export const absolutizeApiUrl = (url: string): string => {};export class ApiError extends Error {+ readonly headers: Headers;readonly status: number;- constructor(message: string, status: number) {+ constructor(message: string, status: number, headers?: HeadersInit) {super(message);this.name = 'ApiError';+ this.headers = new Headers(headers);this.status = status;}}@@ -138,7 +140,7 @@ export const assertOk = async (response: Response): Promise<Response> => {}const text = await response.text();- throw new ApiError(text || `${response.status} ${response.statusText}`, response.status);+ throw new ApiError(text || `${response.status} ${response.statusText}`, response.status, response.headers);};const fetchWithAuthToken = (path: string, init: RequestInit | undefined, token: string | null): Promise<Response> => {@@ -267,10 +269,10 @@ export const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>}const onAbort = (): void => {- window.clearTimeout(timeoutId);+ globalThis.clearTimeout(timeoutId);reject(signal?.reason);};- const timeoutId = window.setTimeout(() => {+ const timeoutId = globalThis.setTimeout(() => {signal?.removeEventListener('abort', onAbort);resolve();}, ms);diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts b/invokeai/frontend/webv2/src/workbench/projects/api.test.tsindex ccdd1b9cfb..d8d5f169cf 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.test.ts@@ -18,6 +18,7 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({import {createProject,createProjectSettled,+ getProjectWriteSizeRefusal,getProject,isProjectCanvasSchemaUnsupportedError,ProjectCreateAbsentError,@@ -113,6 +114,52 @@ describe('createProjectSettled', () => {await expect(createProjectSettled(request, captureAccountScope())).rejects.toBe(failure);});+ it('treats exhausted ingress capacity as proof that an initial create did not run', async () => {+ vi.useFakeTimers();+ const busy = new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '0' }));+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);+ transport.apiFetchJson.mockRejectedValue(busy);++ const settled = expect(createProjectSettled(request, captureAccountScope())).rejects.toBeInstanceOf(+ ProjectCreateAbsentError+ );+ await vi.runAllTimersAsync();+ await settled;++ expect(transport.apiFetchJson).toHaveBeenCalledTimes(9);+ vi.useRealTimers();+ random.mockRestore();+ });++ it('does not treat exhausted settlement capacity as proof that a prior create did not commit', async () => {+ vi.useFakeTimers();+ const unknown = new TypeError('response lost');+ const busy = new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '0' }));+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);+ let serializedValueReads = 0;+ const settlementRequest = {+ data: {+ get value() {+ serializedValueReads += 1;+ return 'value';+ },+ },+ name: 'Imported',+ project_id: 'project-1',+ };+ transport.apiFetchJson.mockRejectedValueOnce(unknown).mockRejectedValue(busy);++ const settled = expect(createProjectSettled(settlementRequest, captureAccountScope())).rejects.toBe(unknown);+ await vi.runAllTimersAsync();+ await settled;++ expect(transport.apiFetchJson).toHaveBeenCalledTimes(9);+ expect(serializedValueReads).toBe(1);+ expect(new Set(transport.apiFetchJson.mock.calls.map((call) => (call[1] as RequestInit).body)).size).toBe(1);+ vi.useRealTimers();+ random.mockRestore();+ });+it('does not retry a create whose id the server would choose', async () => {const failure = new TypeError('network error');@@ -187,6 +234,70 @@ describe('canvas schema compatibility declarations', () => {});});+ it('retries a project write refused by the ingress concurrency guard', async () => {+ let serializedValueReads = 0;+ const data = {+ get value() {+ serializedValueReads += 1;+ return 'value';+ },+ };+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);+ transport.apiFetchJson+ .mockRejectedValueOnce(+ new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '0' }))+ )+ .mockResolvedValueOnce({ project_id: 'project-1' });++ await expect(updateProject('project-1', { data, expected_revision: 1, name: 'Project' })).resolves.toMatchObject({+ project_id: 'project-1',+ });+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(2);+ expect(serializedValueReads).toBe(1);+ random.mockRestore();+ });++ it('does not retry unrelated 429 responses', async () => {+ const refusal = new ApiError('{"detail":{"code":"other"}}', 429, new Headers({ 'Retry-After': '0' }));+ transport.apiFetchJson.mockRejectedValueOnce(refusal);++ await expect(updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' })).rejects.toBe(refusal);+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('reserves the final attempt until the server can release its longest-held slot', async () => {+ vi.useFakeTimers();+ const busy = new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '1' }));+ const random = vi.spyOn(Math, 'random').mockReturnValue(0);+ transport.apiFetchJson.mockRejectedValueOnce(busy).mockRejectedValueOnce(busy).mockRejectedValueOnce(busy);+ transport.apiFetchJson.mockRejectedValueOnce(busy).mockRejectedValueOnce(busy).mockRejectedValueOnce(busy);+ transport.apiFetchJson.mockRejectedValueOnce(busy).mockRejectedValueOnce(busy).mockResolvedValueOnce({+ project_id: 'project-1',+ });++ const write = updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' });+ await vi.advanceTimersByTimeAsync(123_999);+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(8);+ await vi.advanceTimersByTimeAsync(1);+ await expect(write).resolves.toMatchObject({ project_id: 'project-1' });+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(9);+ vi.useRealTimers();+ random.mockRestore();+ });++ it('stops retrying when the owning account scope expires during backoff', async () => {+ const owner = captureAccountScope();+ const busy = new ApiError('{"detail":{"code":"project_write_busy"}}', 429, new Headers({ 'Retry-After': '60' }));+ transport.apiFetchJson.mockRejectedValue(busy);++ const write = updateProject('project-1', { data: {}, expected_revision: 1, name: 'Project' }, owner.signal);+ await vi.waitFor(() => expect(transport.apiFetchJson).toHaveBeenCalledTimes(1));+ accountLifecycle.invalidate();++ await expect(write).rejects.toBe(owner.signal.reason);+ expect(transport.apiFetchJson).toHaveBeenCalledTimes(1);+ });+it('recognizes server-side schema refusals without conflating them with revision conflicts', () => {const refusal = new ApiError(JSON.stringify({@@ -227,3 +338,63 @@ describe('canvas schema compatibility declarations', () => {).toBe(false);});});++describe('project write size refusals', () => {+ it('parses document and request limits as distinct refusals', () => {+ const refusal = new ApiError(+ JSON.stringify({+ detail: {+ actual_bytes: 33_554_433,+ code: 'project_document_too_large',+ max_bytes: 33_554_432,+ },+ }),+ 413+ );++ expect(getProjectWriteSizeRefusal(refusal)).toEqual({+ actualBytes: 33_554_433,+ kind: 'document',+ maxBytes: 33_554_432,+ });+ expect(+ getProjectWriteSizeRefusal(+ new ApiError(+ JSON.stringify({+ detail: { actual_bytes: 35_651_585, code: 'project_request_too_large', max_bytes: 35_651_584 },+ }),+ 413+ )+ )+ ).toEqual({ actualBytes: 35_651_585, kind: 'request', maxBytes: 35_651_584 });+ });++ it.each([+ ['plain message', new ApiError('too large', 413)],+ ['wrong status', new ApiError('{"detail":{"code":"project_document_too_large"}}', 409)],+ ['wrong code', new ApiError('{"detail":{"actual_bytes":17,"code":"other","max_bytes":16}}', 413)],+ [+ 'equal bounds',+ new ApiError('{"detail":{"actual_bytes":16,"code":"project_document_too_large","max_bytes":16}}', 413),+ ],+ [+ 'fractional bound',+ new ApiError('{"detail":{"actual_bytes":17.5,"code":"project_document_too_large","max_bytes":16}}', 413),+ ],+ [+ 'negative bound',+ new ApiError('{"detail":{"actual_bytes":17,"code":"project_document_too_large","max_bytes":-1}}', 413),+ ],+ [+ 'unsafe bound',+ new ApiError(+ JSON.stringify({+ detail: { actual_bytes: Number.MAX_SAFE_INTEGER + 1, code: 'project_document_too_large', max_bytes: 16 },+ }),+ 413+ ),+ ],+ ])('rejects %s', (_name, error) => {+ expect(getProjectWriteSizeRefusal(error)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/api.ts b/invokeai/frontend/webv2/src/workbench/projects/api.tsindex 5bc9ad4ea7..0cce0f4189 100644--- a/invokeai/frontend/webv2/src/workbench/projects/api.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/api.ts@@ -1,7 +1,7 @@import type { AccountScope } from '@platform/state/accountLifecycle';import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';-import { ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';+import { ApiError, apiFetch, apiFetchJson, sleep } from '@platform/transport/http';import {DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,@@ -15,6 +15,8 @@ import {*/const PROJECTS_BASE = '/api/v1/projects';+const PROJECT_WRITE_MAX_ATTEMPTS = 9;+const PROJECT_WRITE_RETRY_WINDOW_MS = 125_000;// The path's queue segment is ignored by the backend (kept for compatibility).const CLIENT_STATE_BASE = '/api/v1/client_state/default';@@ -80,27 +82,115 @@ export const getProject = (projectId: string, signal?: AbortSignal): Promise<Pro{ signal });-export const createProject = (request: ProjectCreateRequest, signal?: AbortSignal): Promise<ProjectRecordDTO> =>- apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/`, {- body: JSON.stringify({- ...request,- max_canvas_schema_version: MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,- minimum_canvas_schema_version: request.minimum_canvas_schema_version ?? DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,- }),- method: 'POST',- signal,+const isProjectWriteBusyError = (error: unknown): error is ApiError => {+ if (!(error instanceof ApiError) || error.status !== 429) {+ return false;+ }+ try {+ return (JSON.parse(error.message) as { detail?: { code?: unknown } }).detail?.code === 'project_write_busy';+ } catch {+ return false;+ }+};++const getRetryDelayMs = (error: ApiError): number => {+ const raw = error.headers.get('Retry-After');+ if (raw === null) {+ return 1_000;+ }+ const seconds = Number(raw);+ if (Number.isFinite(seconds) && seconds >= 0) {+ return seconds * 1_000;+ }+ const date = Date.parse(raw);+ return Number.isFinite(date) ? Math.max(date - Date.now(), 0) : 1_000;+};++interface ProjectWriteRetryBudget {+ attempts: number;+ readonly deadline: number;+}++const createProjectWriteRetryBudget = (): ProjectWriteRetryBudget => ({+ attempts: 0,+ deadline: Date.now() + PROJECT_WRITE_RETRY_WINDOW_MS,+});++const requestProjectWrite = async <T>(+ request: () => Promise<T>,+ signal: AbortSignal | undefined,+ budget: ProjectWriteRetryBudget = createProjectWriteRetryBudget()+): Promise<T> => {+ while (budget.attempts < PROJECT_WRITE_MAX_ATTEMPTS) {+ budget.attempts += 1;+ try {+ return await request();+ } catch (error) {+ if (!isProjectWriteBusyError(error) || budget.attempts >= PROJECT_WRITE_MAX_ATTEMPTS) {+ throw error;+ }+ const retryAfterMs = getRetryDelayMs(error);+ const backoffCeilingMs = Math.min(1_000 * 2 ** (budget.attempts - 1), 30_000);+ const remainingMs = budget.deadline - Date.now();+ const delayMs =+ budget.attempts === PROJECT_WRITE_MAX_ATTEMPTS - 1+ ? Math.max(retryAfterMs, remainingMs - 1_000)+ : retryAfterMs + Math.random() * backoffCeilingMs;++ if (delayMs > remainingMs) {+ throw error;+ }+ await sleep(delayMs, signal);+ }+ }++ throw new Error('Project write retry budget exhausted');+};++const serializeCreateProjectRequest = (request: ProjectCreateRequest): string =>+ JSON.stringify({+ ...request,+ max_canvas_schema_version: MAX_SUPPORTED_CANVAS_SCHEMA_VERSION,+ minimum_canvas_schema_version: request.minimum_canvas_schema_version ?? DEFAULT_PROJECT_CANVAS_SCHEMA_VERSION,});+const createProjectFromBody = (+ body: string,+ signal: AbortSignal | undefined,+ budget: ProjectWriteRetryBudget+): Promise<ProjectRecordDTO> =>+ requestProjectWrite(+ () =>+ apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/`, {+ body,+ method: 'POST',+ signal,+ }),+ signal,+ budget+ );++export const createProject = (request: ProjectCreateRequest, signal?: AbortSignal): Promise<ProjectRecordDTO> =>+ createProjectFromBody(serializeCreateProjectRequest(request), signal, createProjectWriteRetryBudget());+export const updateProject = (projectId: string,request: ProjectUpdateRequest,signal?: AbortSignal-): Promise<ProjectRecordDTO> =>- apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, {- body: JSON.stringify({ ...request, max_canvas_schema_version: MAX_SUPPORTED_CANVAS_SCHEMA_VERSION }),- method: 'PUT',+): Promise<ProjectRecordDTO> => {+ const body = JSON.stringify({ ...request, max_canvas_schema_version: MAX_SUPPORTED_CANVAS_SCHEMA_VERSION });++ return requestProjectWrite(+ () =>+ apiFetchJson<ProjectRecordDTO>(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, {+ body,+ method: 'PUT',+ signal,+ }),signal,- });+ createProjectWriteRetryBudget()+ );+};export const deleteProject = async (projectId: string, signal?: AbortSignal): Promise<void> => {await apiFetch(`${PROJECTS_BASE}/${encodeURIComponent(projectId)}`, { method: 'DELETE', signal });@@ -166,6 +256,45 @@ export const getProjectCanvasSchemaCompatibilityRefusal = (export const isProjectCanvasSchemaUnsupportedError = (error: unknown): boolean =>getProjectCanvasSchemaCompatibilityRefusal(error) !== null;+export interface ProjectWriteSizeRefusal {+ actualBytes: number;+ kind: 'document' | 'request';+ maxBytes: number;+}++export const getProjectWriteSizeRefusal = (error: unknown): ProjectWriteSizeRefusal | null => {+ if (!(error instanceof ApiError) || error.status !== 413) {+ return null;+ }++ try {+ const body = JSON.parse(error.message) as {+ detail?: { actual_bytes?: unknown; code?: unknown; max_bytes?: unknown };+ };+ const actualBytes = body.detail?.actual_bytes;+ const maxBytes = body.detail?.max_bytes;++ const kind =+ body.detail?.code === 'project_document_too_large'+ ? 'document'+ : body.detail?.code === 'project_request_too_large'+ ? 'request'+ : null;++ return kind !== null &&+ typeof actualBytes === 'number' &&+ Number.isSafeInteger(actualBytes) &&+ typeof maxBytes === 'number' &&+ Number.isSafeInteger(maxBytes) &&+ maxBytes > 0 &&+ actualBytes > maxBytes+ ? { actualBytes, kind, maxBytes }+ : null;+ } catch {+ return null;+ }+};+/*** A create that never reached the server, and is therefore safe to compensate for.*@@ -203,6 +332,8 @@ export const createProjectSettled = async (owner: AccountScope): Promise<ProjectRecordDTO> => {const projectId = request.project_id;+ const body = serializeCreateProjectRequest(request);+ const writeBudget = createProjectWriteRetryBudget();/*** A 409 says the id or the board is spoken for, without saying by whom. Because the server has@@ -232,7 +363,7 @@ export const createProjectSettled = async (};try {- return await createProject(request, owner.signal);+ return await createProjectFromBody(body, owner.signal, writeBudget);} catch (error) {assertAccountScopeCurrent(owner);@@ -243,13 +374,13 @@ export const createProjectSettled = async (}try {- return await createProject(request, owner.signal);+ return await createProjectFromBody(body, owner.signal, writeBudget);} catch (retryError) {assertAccountScopeCurrent(owner);// Still no answer. Unknown must not authorize deletion, so the original failure stands and// the uploads are left where they are: clutter is recoverable, a gutted project is not.- if (isIndeterminate(retryError)) {+ if (isIndeterminate(retryError) || isProjectWriteBusyError(retryError)) {throw error;}diff --git a/tests/app/api/test_project_write_limits.py b/tests/app/api/test_project_write_limits.pynew file mode 100644index 0000000000..b6336e21c7--- /dev/null+++ b/tests/app/api/test_project_write_limits.py@@ -0,0 +1,151 @@+import asyncio+from typing import Any++from fastapi import FastAPI+from fastapi.testclient import TestClient++from invokeai.app.api.routers import projects+from invokeai.app.api_app import ProjectWriteLimitASGIMiddleware, SubPathASGIMiddleware++MAX_BODY = 128+MAX_CONCURRENT = 2+++def _build_app() -> tuple[FastAPI, list[str]]:+ app = FastAPI()+ calls: list[str] = []++ @app.post("/api/v1/projects/")+ async def create_project() -> dict[str, bool]:+ calls.append("create")+ return {"ok": True}++ @app.put("/api/v1/projects/{project_id}")+ async def update_project(project_id: str) -> dict[str, bool]:+ calls.append(f"update:{project_id}")+ return {"ok": True}++ @app.post("/api/v1/projects/import")+ async def unrelated_project_route() -> dict[str, bool]:+ calls.append("import")+ return {"ok": True}++ return app, calls+++def _client(base_path: str | None = None) -> tuple[TestClient, list[str]]:+ app, calls = _build_app()+ wrapped = ProjectWriteLimitASGIMiddleware(app, max_body_bytes=MAX_BODY, max_concurrent=MAX_CONCURRENT)+ if base_path is not None:+ wrapped = SubPathASGIMiddleware(wrapped, base_path)+ return TestClient(wrapped, base_url=f"http://testserver{base_path}"), calls+ return TestClient(wrapped), calls+++def test_create_is_rejected_before_json_parsing_when_request_is_oversized() -> None:+ client, calls = _client()++ response = client.post("/api/v1/projects/", content=b" " * (MAX_BODY + 1))++ assert response.status_code == 413+ assert response.json()["detail"] == {+ "actual_bytes": MAX_BODY + 1,+ "code": "project_request_too_large",+ "max_bytes": MAX_BODY,+ }+ assert calls == []+++def test_update_is_rejected_before_json_parsing_when_request_is_oversized() -> None:+ client, calls = _client()++ response = client.put("/api/v1/projects/project-1", content=b" " * (MAX_BODY + 1))++ assert response.status_code == 413+ assert calls == []+++def test_project_write_at_the_ingress_limit_passes_through() -> None:+ client, calls = _client()++ response = client.post(+ "/api/v1/projects/",+ content=b"{}" + b" " * (MAX_BODY - 2),+ headers={"Content-Type": "application/json"},+ )++ assert response.status_code == 200+ assert calls == ["create"]+++def test_non_document_project_routes_are_not_limited() -> None:+ client, calls = _client()++ response = client.post("/api/v1/projects/import", content=b"x" * (MAX_BODY + 1))++ assert response.status_code == 200+ assert calls == ["import"]+++def test_project_write_limit_is_root_path_aware() -> None:+ client, calls = _client("/invoke")++ response = client.put("/api/v1/projects/project-1", content=b"x" * (MAX_BODY + 1))++ assert response.status_code == 413+ assert calls == []+++def test_project_write_concurrency_refusal_is_retryable() -> None:+ app, calls = _build_app()+ middleware = ProjectWriteLimitASGIMiddleware(app, max_body_bytes=MAX_BODY, max_concurrent=1)+ middleware._active = 1+ client = TestClient(middleware)++ response = client.post("/api/v1/projects/", content=b"{}")++ assert response.status_code == 429+ assert response.headers["retry-after"] == "1"+ assert response.json()["detail"]["code"] == "project_write_busy"+ assert calls == []+++def test_project_write_limits_bound_peak_memory_and_slow_clients() -> None:+ assert projects.MAX_CONCURRENT_PROJECT_WRITES == 2+ assert projects.MAX_CONCURRENT_PROJECT_WRITES_PER_USER == 1+ assert projects.PROJECT_WRITE_IDLE_TIMEOUT_SECONDS <= 30+ assert projects.PROJECT_WRITE_MAX_DURATION_SECONDS <= 120+++def test_chunked_project_write_is_cut_off_at_the_ingress_limit() -> None:+ seen: list[dict[str, Any]] = []++ async def app(scope: Any, receive: Any, send: Any) -> None:+ while True:+ message = await receive()+ seen.append(message)+ if message["type"] != "http.request" or not message.get("more_body"):+ break++ middleware = ProjectWriteLimitASGIMiddleware(app, max_body_bytes=MAX_BODY, max_concurrent=MAX_CONCURRENT)+ scope = {+ "type": "http",+ "method": "POST",+ "path": "/api/v1/projects/",+ "root_path": "",+ "headers": [],+ }+ chunks = [b"x" * 80, b"x" * 80]++ async def receive() -> dict[str, Any]:+ if chunks:+ return {"type": "http.request", "body": chunks.pop(0), "more_body": bool(chunks)}+ return {"type": "http.disconnect"}++ async def send(_message: dict[str, Any]) -> None:+ pass++ asyncio.run(middleware(scope, receive, send)) # type: ignore[arg-type]++ assert seen[-1]["type"] == "http.disconnect"+ assert sum(len(message.get("body", b"")) for message in seen) == 80diff --git a/tests/app/routers/test_projects.py b/tests/app/routers/test_projects.pyindex 661825d305..34e25fda5d 100644--- a/tests/app/routers/test_projects.py+++ b/tests/app/routers/test_projects.py@@ -12,6 +12,7 @@ from fastapi import statusfrom fastapi.testclient import TestClientfrom invokeai.app.services.invoker import Invoker+from invokeai.app.services.project_records import project_records_sqlitefrom tests.app.routers.conftest import _auth, _create_board@@ -32,6 +33,50 @@ def test_creating_a_project_creates_and_returns_its_board(client: TestClient, usassert board.json()["board_visibility"] == "private"+def test_oversized_project_documents_return_a_structured_413(+ client: TestClient, user1_token: str, monkeypatch: pytest.MonkeyPatch+):+ monkeypatch.setattr(project_records_sqlite, "PROJECT_DOCUMENT_MAX_BYTES", 16)++ response = _create_project(client, user1_token, data={"value": "x" * 32})++ assert response.status_code == status.HTTP_413_CONTENT_TOO_LARGE+ assert response.json()["detail"] == {+ "actual_bytes": 44,+ "code": "project_document_too_large",+ "max_bytes": 16,+ "message": "Project document is 44 bytes; the limit is 16 bytes",+ }+++def test_oversized_project_updates_return_a_structured_413(+ client: TestClient, user1_token: str, monkeypatch: pytest.MonkeyPatch+):+ created = _create_project(client, user1_token).json()+ monkeypatch.setattr(project_records_sqlite, "PROJECT_DOCUMENT_MAX_BYTES", 16)++ response = client.put(+ f"/api/v1/projects/{created['project_id']}",+ json={"data": {"value": "x" * 32}, "expected_revision": created["revision"], "name": "Too large"},+ headers=_auth(user1_token),+ )++ assert response.status_code == status.HTTP_413_CONTENT_TOO_LARGE+ assert response.json()["detail"]["code"] == "project_document_too_large"+ assert response.json()["detail"]["actual_bytes"] == 44+++def test_non_finite_project_values_return_a_structured_422(client: TestClient, user1_token: str) -> None:+ response = client.post(+ "/api/v1/projects/",+ content=b'{"name":"Invalid","data":{"value":NaN}}',+ headers={**_auth(user1_token), "Content-Type": "application/json"},+ )++ assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT+ assert response.json()["detail"]["code"] == "project_document_invalid"++def test_project_canvas_schema_negotiation_defaults_legacy_clients_to_v2(client: TestClient, user1_token: str):created = _create_project(client, user1_token)diff --git a/tests/app/services/project_records/test_project_records.py b/tests/app/services/project_records/test_project_records.pyindex b2a9779d00..3872809dd1 100644--- a/tests/app/services/project_records/test_project_records.py+++ b/tests/app/services/project_records/test_project_records.py@@ -3,11 +3,14 @@import pytestfrom invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.project_records import project_records_sqlitefrom invokeai.app.services.project_records.project_records_common import (ProjectBoardNotFoundError,ProjectBoardUnavailableError,ProjectCanvasSchemaDowngradeError,ProjectCanvasSchemaUnsupportedError,+ ProjectDocumentInvalidError,+ ProjectDocumentTooLargeError,ProjectRecordConflictError,ProjectRecordExistsError,ProjectRecordNotFoundError,@@ -55,6 +58,74 @@ def test_create_and_get_roundtrip(project_records: ProjectRecordsSqlite) -> Noneassert fetched == created+def test_oversized_documents_are_rejected_before_a_board_is_created(+ project_records: ProjectRecordsSqlite, db: SqliteDatabase, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(project_records_sqlite, "PROJECT_DOCUMENT_MAX_BYTES", 16)++ with pytest.raises(ProjectDocumentTooLargeError) as exc_info:+ project_records.create(SYSTEM_USER_ID, "Too large", {"value": "x" * 32})++ assert exc_info.value.max_bytes == 16+ with db.transaction() as cursor:+ cursor.execute("SELECT COUNT(*) FROM boards WHERE board_name = ?", ("Too large",))+ assert cursor.fetchone()[0] == 0+++def test_oversized_updates_preserve_the_acknowledged_revision(+ project_records: ProjectRecordsSqlite, monkeypatch: pytest.MonkeyPatch+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Project", {"value": "small"})+ monkeypatch.setattr(project_records_sqlite, "PROJECT_DOCUMENT_MAX_BYTES", 16)++ with pytest.raises(ProjectDocumentTooLargeError):+ project_records.update(+ SYSTEM_USER_ID,+ created.project_id,+ expected_revision=created.revision,+ name="Too large",+ data={"value": "x" * 32},+ )++ stored = project_records.get(SYSTEM_USER_ID, created.project_id)+ assert stored.name == "Project"+ assert stored.revision == created.revision+ assert stored.data == {"value": "small"}+++def test_document_limit_counts_compact_utf8_bytes(+ project_records: ProjectRecordsSqlite, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(project_records_sqlite, "PROJECT_DOCUMENT_MAX_BYTES", 14)++ created = project_records.create(SYSTEM_USER_ID, "Exact", {"value": "é"})+ assert created.data == {"value": "é"}++ with pytest.raises(ProjectDocumentTooLargeError) as exc_info:+ project_records.create(SYSTEM_USER_ID, "Over", {"value": "éa"})++ assert exc_info.value.actual_bytes == 15++[email protected]("value", [float("nan"), float("inf"), float("-inf"), "\ud800"])+def test_non_json_safe_document_values_are_rejected(project_records: ProjectRecordsSqlite, value: object) -> None:+ with pytest.raises(ProjectDocumentInvalidError):+ project_records.create(SYSTEM_USER_ID, "Invalid", {"value": value})+++def test_oversized_legacy_documents_remain_readable_and_deletable(+ project_records: ProjectRecordsSqlite, monkeypatch: pytest.MonkeyPatch+) -> None:+ created = project_records.create(SYSTEM_USER_ID, "Legacy", {"value": "x" * 32})+ monkeypatch.setattr(project_records_sqlite, "PROJECT_DOCUMENT_MAX_BYTES", 16)++ assert project_records.get(SYSTEM_USER_ID, created.project_id).data == {"value": "x" * 32}+ project_records.delete(SYSTEM_USER_ID, created.project_id)++ with pytest.raises(ProjectRecordNotFoundError):+ project_records.get(SYSTEM_USER_ID, created.project_id)++def test_create_with_client_id_and_duplicate_rejected(project_records: ProjectRecordsSqlite) -> None:created = project_records.create(SYSTEM_USER_ID, "Imported", {"x": 1}, project_id="project-abc")assert created.project_id == "project-abc"