Skip to content

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

refactor(webv2): extract raster snapshot capture from the engine

joshistoast878f6c7ae1cb
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 0e20e71b06..e45bb48179 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -47,14 +47,12 @@ import type {
ExportBakedLayerPixelsOptions,
ExportLayerPixelsOptions,
ExtractMaskedAreaResult,
- LayerExportGuard,
MergeVisibleResult,
NewRasterLayerResult,
PsdExportResult,
} from '@workbench/canvas-engine/capabilities';
import type {
CanvasCompositeExecutorDeps,
- CanvasRasterSnapshot,
CaptureRasterSnapshotResult,
} from '@workbench/canvas-engine/rasterTransactions';
export type {
@@ -123,7 +121,10 @@ import {
import { PersistenceController } from '@workbench/canvas-engine/controllers/persistenceController';
import { PsdExportController } from '@workbench/canvas-engine/controllers/psdExportController';
import { RasterController, type RasterizationJob } from '@workbench/canvas-engine/controllers/rasterController';
-import { RasterExportController } from '@workbench/canvas-engine/controllers/rasterExportController';
+import {
+ RasterExportController,
+ type ExportLayerPixelsResult,
+} from '@workbench/canvas-engine/controllers/rasterExportController';
import { RenderController } from '@workbench/canvas-engine/controllers/renderController';
import { StagedResultController } from '@workbench/canvas-engine/controllers/stagedResultController';
import { StructuralLayerController } from '@workbench/canvas-engine/controllers/structuralLayerController';
@@ -195,6 +196,7 @@ import { createDocumentMirror, type DocumentMirror } from './document/documentMi
import { getSourceBounds, getSourceContentRect, isRenderableLayer, renderableSourceOf } from './document/sources';
import { createLayerExportGuards, isDeeplyEqual, isSupportedExportSource } from './layerExportGuards';
import { createPreviewPublisher } from './previewPublisher';
+import { createRasterSnapshotCapture } from './rasterSnapshotCapture';
import { createSelectObjectBridge } from './selectObjectBridge';
import { createStrokeCommit } from './strokeCommit';
import { createViewTool } from './tools/viewTool';
@@ -205,10 +207,12 @@ import { createViewTool } from './tools/viewTool';
* when the union bounds exceed the PSD dimension cap, and `'not-ready'` when a
* participant's cache is still decoding (nothing exported — surface feedback).
*/
-/** Opaque snapshot identity carried through async layer operations. */
-export type ExportLayerPixelsResult =
- | { status: 'ok'; surface: RasterSurface; rect: Rect; guard: LayerExportGuard; release(): void }
- | { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' | 'over-budget' | 'aborted' };
+/**
+ * Re-exported from the controller that produces it, so the many callers that
+ * name it off `canvas-engine/engine` keep resolving while there is only one
+ * definition to keep in step.
+ */
+export type { ExportLayerPixelsResult };
export type ExportBakedLayerPixelsResult = ExportLayerPixelsResult;
@@ -435,7 +439,6 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const cancelAllLayerRasterizations = (): void => rasterController.cancelAllRasterization();
let disposed = false;
- const activeRasterSnapshots = new Set<CanvasRasterSnapshot>();
let lifecycleState: 'active' | 'cooling' | 'cool' | 'disposed' = 'active';
let lifecycleGeneration = 0;
let cooldownPromise: Promise<'cooled' | 'dirty'> | null = null;
@@ -476,6 +479,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const getAdjustedSurface = (layer: CanvasLayerContract, entry: LayerCacheEntry): RasterSurface | null =>
rasterController.getAdjustedSurface(layer, entry);
+ /**
+ * Re-reads the live cache sizes into the memory budget. Both caches change
+ * outside the budget's knowledge (a rasterize grows one, an eviction shrinks
+ * the other), so every allocation decision has to re-sync first or it reserves
+ * against a stale total.
+ */
+ const syncMemoryBaselines = (): void => {
+ rasterController.memory.setBaseBytes(layerCache.byteSize());
+ rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ };
+
// Completed-stroke subscribers (persistence P2.2, history P2.3).
const strokeListeners = new Set<(event: StrokeCommittedEvent) => void>();
const toolChangeListeners = new Set<(change: { from: string; to: string; temporary: boolean }) => void>();
@@ -1224,8 +1238,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
layers: layerCache,
pin: (layerId) => rasterController.memory.pin(layerId, lifecycleGeneration),
reserve: (bytes) => {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
return rasterController.memory.reserve(bytes, { generation: lifecycleGeneration, purpose: 'raster-export' });
},
});
@@ -1496,8 +1509,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
transformOverrides: !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null,
});
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
const protectedIds = new Set([...activeFrameLayerIds, ...rasterController.memory.pinnedLayerIds()]);
const memory = rasterController.memory.snapshot();
const surfaceBudgetBytes = Math.max(
@@ -1511,8 +1523,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
surfaceBudgetBytes,
diagnostics
);
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
// Prune version-keyed dependents for every evicted id (mirrors dropLayer):
// the evicted layer's surface is gone, so its adjusted-surface memo and
// thumbnail state must not linger keyed to a version the re-rasterized entry
@@ -2365,212 +2376,31 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const mergeLayerDown = (upperLayerId: string): boolean => layerController.merge.mergeDown(upperLayerId);
const mergeVisibleRasterLayers = (): Promise<MergeVisibleResult> => layerController.merge.mergeVisible();
- const documentSnapshotSources = new WeakMap<
- CanvasDocumentSnapshot,
- {
- canvas: NonNullable<ReturnType<typeof mutationPort.getCanvasState>>;
- contentEpoch: number;
- lifecycleGeneration: number;
- }
- >();
- const isDocumentSnapshotCurrent = (snapshot: CanvasDocumentSnapshot): boolean => {
- const source = documentSnapshotSources.get(snapshot);
- return (
- !disposed &&
- source !== undefined &&
- source.canvas === mutationPort.getCanvasState() &&
- source.contentEpoch === rasterContentEpoch &&
- source.lifecycleGeneration === lifecycleGeneration &&
- snapshot.documentGeneration === rasterController.getDocumentGeneration()
- );
- };
- const captureRasterSnapshot = async (
- documentSnapshot: CanvasDocumentSnapshot,
- layerIds: readonly string[],
- options?: { signal?: AbortSignal; includeDisabled?: boolean }
- ): Promise<CaptureRasterSnapshotResult> => {
- if (options?.signal?.aborted) {
- return { status: 'aborted' };
- }
- if (!documentSnapshotSources.has(documentSnapshot)) {
- return { status: 'not-ready' };
- }
- if (!isDocumentSnapshotCurrent(documentSnapshot)) {
- return { status: 'stale' };
- }
- const snapshotSource = documentSnapshotSources.get(documentSnapshot)!;
- const captureLifecycleGeneration = snapshotSource.lifecycleGeneration;
-
- const uniqueLayerIds = [...new Set(layerIds)];
- const layerById = new Map(documentSnapshot.canvas.document.layers.map((layer) => [layer.id, layer]));
- let requestedBytes = 0;
- for (const layerId of uniqueLayerIds) {
- const layer = layerById.get(layerId);
- const source = layer ? renderableSourceOf(layer) : null;
- if (!layer || !source || !isSupportedExportSource(source)) {
- return { status: 'not-ready' };
- }
- if (source.type === 'image') {
- requestedBytes += source.image.width * source.image.height * 4;
- } else if (source.type === 'paint' && source.bitmap) {
- requestedBytes += source.bitmap.width * source.bitmap.height * 4;
- } else {
- const contentRect = getSourceContentRect(layer, documentSnapshot.canvas.document);
- requestedBytes += contentRect.width * contentRect.height * 4;
- }
- }
-
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
- const reservation = rasterController.memory.reserve(requestedBytes, {
- generation: captureLifecycleGeneration,
- purpose: 'background-snapshot',
- });
- if (reservation.status === 'over-budget') {
- return { status: 'over-budget' };
- }
- const reservationLeases: { release(): void }[] = [reservation.lease];
- const pinLeases = uniqueLayerIds.map((layerId) => rasterController.memory.pin(layerId, captureLifecycleGeneration));
- const layerSurfaces = new Map<string, { rect: Rect; surface: RasterSurface }>();
- const emptyLayerIds = new Set<string>();
- const capturedGuards: LayerExportGuard[] = [];
- let actualDetachedBytes = 0;
- try {
- for (const layerId of uniqueLayerIds) {
- if (options?.signal?.aborted) {
- return { status: 'aborted' };
- }
- if (!isDocumentSnapshotCurrent(documentSnapshot)) {
- return { status: 'stale' };
- }
- const liveResult = await rasterizeLayerPixels(layerId, {
- includeDisabled: options?.includeDisabled,
- signal: options?.signal,
- });
- if (options?.signal?.aborted) {
- return { status: 'aborted' };
- }
- if (!isDocumentSnapshotCurrent(documentSnapshot)) {
- return { status: 'stale' };
- }
- if (liveResult.status === 'empty') {
- emptyLayerIds.add(layerId);
- continue;
- }
- if (liveResult.status !== 'ok') {
- return {
- status:
- liveResult.status === 'aborted' || liveResult.status === 'over-budget' ? liveResult.status : 'not-ready',
- };
- }
- const live = liveResult;
- if (!isLayerExportGuardCurrent(live.guard)) {
- live.release();
- return { status: 'stale' };
- }
- capturedGuards.push(live.guard);
- try {
- const actualBytes = live.surface.width * live.surface.height * 4;
- const source = renderableSourceOf(layerById.get(layerId)!);
- const estimatedBytes =
- source?.type === 'image'
- ? source.image.width * source.image.height * 4
- : source?.type === 'paint' && source.bitmap
- ? source.bitmap.width * source.bitmap.height * 4
- : getSourceContentRect(layerById.get(layerId)!, documentSnapshot.canvas.document).width *
- getSourceContentRect(layerById.get(layerId)!, documentSnapshot.canvas.document).height *
- 4;
- const additionalBytes = Math.max(0, actualBytes - estimatedBytes);
- if (additionalBytes > 0) {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
- const additional = rasterController.memory.reserve(additionalBytes, {
- generation: captureLifecycleGeneration,
- purpose: 'background-snapshot',
- });
- if (additional.status === 'over-budget') {
- return { status: 'over-budget' };
- }
- reservationLeases.push(additional.lease);
- }
- const detached = backend.createSurface(live.surface.width, live.surface.height);
- detached.ctx.setTransform(1, 0, 0, 1, 0, 0);
- detached.ctx.clearRect(0, 0, detached.width, detached.height);
- detached.ctx.drawImage(live.surface.canvas, 0, 0);
- layerSurfaces.set(layerId, { rect: { ...live.rect }, surface: detached });
- actualDetachedBytes += actualBytes;
- } finally {
- live.release();
- }
- }
- if (
- !isDocumentSnapshotCurrent(documentSnapshot) ||
- capturedGuards.some((guard) => !isLayerExportGuardCurrent(guard))
- ) {
- return { status: 'stale' };
- }
-
- for (const lease of reservationLeases) {
- lease.release();
- }
- const detachedLease = rasterController.memory.trackDetached(actualDetachedBytes, captureLifecycleGeneration);
- let released = false;
- const snapshot: CanvasRasterSnapshot = {
- ...documentSnapshot,
- emptyLayerIds,
- layerSurfaces,
- release: () => {
- if (released) {
- return;
- }
- released = true;
- emptyLayerIds.clear();
- layerSurfaces.clear();
- detachedLease.release();
- activeRasterSnapshots.delete(snapshot);
- },
- };
- activeRasterSnapshots.add(snapshot);
- return { snapshot, status: 'ok' };
- } finally {
- for (const lease of reservationLeases) {
- lease.release();
- }
- for (const lease of pinLeases) {
- lease.release();
- }
- }
- };
- const captureDocumentSnapshot = (): CanvasDocumentSnapshot | null => {
- const canvas = mutationPort.getCanvasState();
- if (disposed || !canvas) {
- return null;
- }
- const snapshot: CanvasDocumentSnapshot = {
- canvas: structuredClone(canvas),
- documentGeneration: rasterController.getDocumentGeneration(),
- };
- documentSnapshotSources.set(snapshot, {
- canvas,
- contentEpoch: rasterContentEpoch,
- lifecycleGeneration,
+ const { captureDocumentSnapshot, captureRasterSnapshot, isDocumentSnapshotCurrent, releaseActiveSnapshots } =
+ createRasterSnapshotCapture({
+ createSurface: (width, height) => backend.createSurface(width, height),
+ getCanvasState: () => mutationPort.getCanvasState(),
+ getContentEpoch: () => rasterContentEpoch,
+ getDocumentGeneration: () => rasterController.getDocumentGeneration(),
+ getLifecycleGeneration: () => lifecycleGeneration,
+ isDisposed: () => disposed,
+ isGuardCurrent: isLayerExportGuardCurrent,
+ memory: rasterController.memory,
+ rasterizeLayerPixels,
+ syncMemoryBaselines,
});
- return snapshot;
- };
const psdExportController = new PsdExportController({
backend,
- captureDocumentSnapshot: () => captureDocumentSnapshot(),
- captureRasterSnapshot: (snapshot, layerIds, options) => captureRasterSnapshot(snapshot, layerIds, options),
+ captureDocumentSnapshot,
+ captureRasterSnapshot,
getAvailableBytes: () => {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
return rasterController.memory.getAvailableBytes();
},
- isDocumentSnapshotCurrent: (snapshot) => isDocumentSnapshotCurrent(snapshot),
+ isDocumentSnapshotCurrent,
reserve: (bytes) => {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
return rasterController.memory.reserve(bytes, { generation: lifecycleGeneration, purpose: 'psd-export' });
},
});
@@ -2703,9 +2533,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return;
}
disposed = true;
- for (const snapshot of activeRasterSnapshots) {
- snapshot.release();
- }
+ releaseActiveSnapshots();
rasterController.memory.releaseGeneration(lifecycleGeneration);
lifecycleGeneration += 1;
lifecycleState = 'disposed';
@@ -2833,8 +2661,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
backend,
getLayerSurface: requireLayerSurfaceForExport,
reserve: (bytes) => {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
return rasterController.memory.reserveOperation(bytes, { purpose: 'invocation-composite' });
},
uploadImage: (blob) => opts.uploadImage(blob),
@@ -2872,8 +2699,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
};
},
reserve: (bytes) => {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
return rasterController.memory.reserveOperation(bytes, { purpose: 'background-snapshot' });
},
});
@@ -3040,8 +2866,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
},
reserve: (bytes) => {
- rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ syncMemoryBaselines();
return rasterController.memory.reserve(bytes, { generation: lifecycleGeneration, purpose: 'thumbnail' });
},
setStatus: (layerId, status) => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
new file mode 100644
index 0000000000..7250ed778d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
@@ -0,0 +1,389 @@
+import type { CanvasDocumentSnapshot, LayerExportGuard } from '@workbench/canvas-engine/capabilities';
+import type { CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';
+import type { ExportLayerPixelsResult } from '@workbench/canvas-engine/controllers/rasterExportController';
+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
+
+import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createRasterSnapshotCapture, type CreateRasterSnapshotCaptureDeps } from './rasterSnapshotCapture';
+
+const surface = (width = 4, height = 4): RasterSurface =>
+ ({
+ canvas: {},
+ ctx: { clearRect: vi.fn(), drawImage: vi.fn(), setTransform: vi.fn() },
+ height,
+ width,
+ }) as unknown as RasterSurface;
+
+const imageLayer = (id: string, size = 4) => ({
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ source: { image: { height: size, imageName: `${id}.png`, width: size }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+});
+
+const canvasState = (layerIds: readonly string[] = ['a']): CanvasStateContractV2 =>
+ ({ document: { layers: layerIds.map((id) => imageLayer(id)) } }) as unknown as CanvasStateContractV2;
+
+const guard = (layerId: string): LayerExportGuard => ({ layerId }) as LayerExportGuard;
+
+const okPixels = (layerId: string, size = 4): ExportLayerPixelsResult => ({
+ guard: guard(layerId),
+ rect: { height: size, width: size, x: 0, y: 0 },
+ release: vi.fn(),
+ status: 'ok',
+ surface: surface(size, size),
+});
+
+/** Mutable so a test can advance engine state mid-capture, the way an edit does. */
+interface Harness {
+ deps: CreateRasterSnapshotCaptureDeps;
+ state: {
+ canvas: CanvasStateContractV2 | null;
+ contentEpoch: number;
+ disposed: boolean;
+ documentGeneration: number;
+ lifecycleGeneration: number;
+ };
+ currentGuards: Set<LayerExportGuard>;
+ rasterize: ReturnType<typeof vi.fn>;
+}
+
+let harness: Harness;
+
+const makeHarness = (overrides: Partial<CreateRasterSnapshotCaptureDeps> = {}): Harness => {
+ const state = {
+ canvas: canvasState() as CanvasStateContractV2 | null,
+ contentEpoch: 0,
+ disposed: false,
+ documentGeneration: 1,
+ lifecycleGeneration: 0,
+ };
+ const currentGuards = new Set<LayerExportGuard>();
+ const rasterize = vi.fn((layerId: string) => {
+ const result = okPixels(layerId);
+ currentGuards.add(result.status === 'ok' ? result.guard : guard(layerId));
+ return Promise.resolve(result);
+ });
+ const deps: CreateRasterSnapshotCaptureDeps = {
+ createSurface: (width, height) => surface(width, height),
+ getCanvasState: () => state.canvas,
+ getContentEpoch: () => state.contentEpoch,
+ getDocumentGeneration: () => state.documentGeneration,
+ getLifecycleGeneration: () => state.lifecycleGeneration,
+ isDisposed: () => state.disposed,
+ isGuardCurrent: (candidate) => currentGuards.has(candidate),
+ memory: new RasterMemoryBudgetController({ budgetBytes: 1_000_000 }),
+ rasterizeLayerPixels: rasterize as unknown as CreateRasterSnapshotCaptureDeps['rasterizeLayerPixels'],
+ syncMemoryBaselines: vi.fn(),
+ ...overrides,
+ };
+ return { currentGuards, deps, rasterize, state };
+};
+
+beforeEach(() => {
+ harness = makeHarness();
+});
+
+describe('captureDocumentSnapshot', () => {
+ it('clones the canvas rather than aliasing it', () => {
+ const snapshot = createRasterSnapshotCapture(harness.deps).captureDocumentSnapshot();
+ expect(snapshot?.canvas).not.toBe(harness.state.canvas);
+ expect(snapshot?.canvas.document.layers[0]?.id).toBe('a');
+ });
+
+ it('refuses once disposed, and when there is no canvas', () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ harness.state.disposed = true;
+ expect(capture.captureDocumentSnapshot()).toBeNull();
+ harness.state.disposed = false;
+ harness.state.canvas = null;
+ expect(capture.captureDocumentSnapshot()).toBeNull();
+ });
+});
+
+describe('isDocumentSnapshotCurrent', () => {
+ it('holds while nothing has moved', () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect(capture.isDocumentSnapshotCurrent(snapshot)).toBe(true);
+ });
+
+ it.each([
+ ['the canvas object is replaced', (h: Harness) => (h.state.canvas = canvasState())],
+ ['the raster content epoch advances', (h: Harness) => (h.state.contentEpoch += 1)],
+ ['the lifecycle generation advances', (h: Harness) => (h.state.lifecycleGeneration += 1)],
+ ['the document generation advances', (h: Harness) => (h.state.documentGeneration += 1)],
+ ['the engine is disposed', (h: Harness) => (h.state.disposed = true)],
+ ])('breaks once %s', (_label, mutate) => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ mutate(harness);
+ expect(capture.isDocumentSnapshotCurrent(snapshot)).toBe(false);
+ });
+
+ it('rejects a snapshot it never issued', () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const foreign = { canvas: canvasState(), documentGeneration: 1 } as CanvasDocumentSnapshot;
+ expect(capture.isDocumentSnapshotCurrent(foreign)).toBe(false);
+ });
+
+ it('rejects a replacement canvas that is structurally identical', () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ // Same layers, same generation — only the object identity differs, which is
+ // exactly what a reducer pass produces.
+ harness.state.canvas = canvasState();
+ expect(capture.isDocumentSnapshotCurrent(snapshot)).toBe(false);
+ });
+});
+
+describe('captureRasterSnapshot', () => {
+ it('detaches a surface per layer and reports the empty ones separately', async () => {
+ harness.state.canvas = canvasState(['a', 'b']);
+ harness.rasterize.mockImplementation((layerId: string) => {
+ if (layerId === 'b') {
+ return Promise.resolve({ status: 'empty' });
+ }
+ const result = okPixels(layerId);
+ harness.currentGuards.add(result.status === 'ok' ? result.guard : guard(layerId));
+ return Promise.resolve(result);
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ const result = await capture.captureRasterSnapshot(snapshot, ['a', 'b']);
+ expect(result.status).toBe('ok');
+ if (result.status !== 'ok') {
+ return;
+ }
+ expect([...result.snapshot.layerSurfaces.keys()]).toEqual(['a']);
+ expect([...result.snapshot.emptyLayerIds]).toEqual(['b']);
+ });
+
+ it('rasterizes a repeated layer id only once', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ await capture.captureRasterSnapshot(snapshot, ['a', 'a', 'a']);
+ expect(harness.rasterize).toHaveBeenCalledTimes(1);
+ });
+
+ it('copies the rect rather than aliasing the live one', async () => {
+ const live = okPixels('a');
+ harness.rasterize.mockImplementation(() => {
+ harness.currentGuards.add(live.status === 'ok' ? live.guard : guard('a'));
+ return Promise.resolve(live);
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ const result = await capture.captureRasterSnapshot(snapshot, ['a']);
+ expect(result.status).toBe('ok');
+ if (result.status !== 'ok' || live.status !== 'ok') {
+ return;
+ }
+ expect(result.snapshot.layerSurfaces.get('a')?.rect).not.toBe(live.rect);
+ });
+
+ it('releases the live surface even though it detached a copy', async () => {
+ const live = okPixels('a');
+ harness.rasterize.mockImplementation(() => {
+ harness.currentGuards.add(live.status === 'ok' ? live.guard : guard('a'));
+ return Promise.resolve(live);
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ await capture.captureRasterSnapshot(snapshot, ['a']);
+ expect(live.status === 'ok' && live.release).toHaveBeenCalled();
+ });
+
+ it('refuses a snapshot it never issued as not-ready, not stale', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const foreign = { canvas: canvasState(), documentGeneration: 1 } as CanvasDocumentSnapshot;
+ expect((await capture.captureRasterSnapshot(foreign, ['a'])).status).toBe('not-ready');
+ });
+
+ it('refuses a layer that is not in the snapshot', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['missing'])).status).toBe('not-ready');
+ expect(harness.rasterize).not.toHaveBeenCalled();
+ });
+
+ it('refuses a layer whose source cannot be exported', async () => {
+ harness.state.canvas = {
+ document: { layers: [{ ...imageLayer('a'), source: { kind: 'polygon', type: 'shape' } }] },
+ } as unknown as CanvasStateContractV2;
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'])).status).toBe('not-ready');
+ });
+
+ it('reports over-budget without rasterizing when the estimate does not fit', async () => {
+ const harnessTiny = makeHarness({ memory: new RasterMemoryBudgetController({ budgetBytes: 8 }) });
+ const capture = createRasterSnapshotCapture(harnessTiny.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'])).status).toBe('over-budget');
+ expect(harnessTiny.rasterize).not.toHaveBeenCalled();
+ });
+
+ it('reports over-budget when a surface rasterizes larger than its estimate', async () => {
+ // The 4x4 image estimates at 64 B; a 64x64 rasterized surface needs 16 KB more.
+ const tight = makeHarness({ memory: new RasterMemoryBudgetController({ budgetBytes: 128 }) });
+ tight.rasterize.mockImplementation(() => {
+ const result = { ...okPixels('a'), surface: surface(64, 64) } as ExportLayerPixelsResult;
+ tight.currentGuards.add(result.status === 'ok' ? result.guard : guard('a'));
+ return Promise.resolve(result);
+ });
+ const capture = createRasterSnapshotCapture(tight.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'])).status).toBe('over-budget');
+ });
+
+ it.each([
+ ['aborted', 'aborted'],
+ ['over-budget', 'over-budget'],
+ ['missing', 'not-ready'],
+ ['disabled', 'not-ready'],
+ ['unsupported', 'not-ready'],
+ ])('maps a %s rasterize to %s', async (rasterizeStatus, expected) => {
+ harness.rasterize.mockResolvedValue({ status: rasterizeStatus });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'])).status).toBe(expected);
+ });
+
+ it('aborts before doing any work when the signal is already aborted', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'], { signal: controller.signal })).status).toBe(
+ 'aborted'
+ );
+ expect(harness.rasterize).not.toHaveBeenCalled();
+ });
+
+ it('aborts when the signal fires during a rasterize', async () => {
+ const controller = new AbortController();
+ harness.rasterize.mockImplementation(() => {
+ controller.abort();
+ return Promise.resolve(okPixels('a'));
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'], { signal: controller.signal })).status).toBe(
+ 'aborted'
+ );
+ });
+
+ it('goes stale when the document changes mid-capture, before any surface is kept', async () => {
+ harness.state.canvas = canvasState(['a', 'b']);
+ harness.rasterize.mockImplementation((layerId: string) => {
+ if (layerId === 'b') {
+ harness.state.contentEpoch += 1;
+ }
+ const result = okPixels(layerId);
+ harness.currentGuards.add(result.status === 'ok' ? result.guard : guard(layerId));
+ return Promise.resolve(result);
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a', 'b'])).status).toBe('stale');
+ });
+
+ it('detaches nothing once it notices the document moved, rather than copying and discarding', async () => {
+ const createSurface = vi.fn((width: number, height: number) => surface(width, height));
+ const detaching = makeHarness({ createSurface });
+ detaching.state.canvas = canvasState(['a', 'b']);
+ detaching.rasterize.mockImplementation((layerId: string) => {
+ // The edit lands while the FIRST layer is still rasterizing.
+ detaching.state.contentEpoch += 1;
+ const result = okPixels(layerId);
+ detaching.currentGuards.add(result.status === 'ok' ? result.guard : guard(layerId));
+ return Promise.resolve(result);
+ });
+ const capture = createRasterSnapshotCapture(detaching.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a', 'b'])).status).toBe('stale');
+ expect(createSurface).not.toHaveBeenCalled();
+ });
+
+ it('goes stale when a layer rasterizes against an already-superseded guard', async () => {
+ harness.rasterize.mockResolvedValue(okPixels('a')); // never registered as current
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a'])).status).toBe('stale');
+ });
+
+ it('goes stale when an early guard is invalidated by a later layer', async () => {
+ harness.state.canvas = canvasState(['a', 'b']);
+ const guards: LayerExportGuard[] = [];
+ harness.rasterize.mockImplementation((layerId: string) => {
+ const result = okPixels(layerId);
+ if (result.status === 'ok') {
+ guards.push(result.guard);
+ harness.currentGuards.add(result.guard);
+ }
+ // Editing `a` while `b` rasterizes retires a's guard but not the document.
+ if (layerId === 'b' && guards[0]) {
+ harness.currentGuards.delete(guards[0]);
+ }
+ return Promise.resolve(result);
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const snapshot = capture.captureDocumentSnapshot()!;
+ expect((await capture.captureRasterSnapshot(snapshot, ['a', 'b'])).status).toBe('stale');
+ });
+});
+
+describe('snapshot lifetime', () => {
+ it('releases idempotently and empties what it held', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const documentSnapshot = capture.captureDocumentSnapshot()!;
+ const result = await capture.captureRasterSnapshot(documentSnapshot, ['a']);
+ expect(result.status).toBe('ok');
+ if (result.status !== 'ok') {
+ return;
+ }
+ result.snapshot.release();
+ result.snapshot.release();
+ expect(result.snapshot.layerSurfaces.size).toBe(0);
+ });
+
+ it('releases every outstanding snapshot on teardown', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const documentSnapshot = capture.captureDocumentSnapshot()!;
+ const first = await capture.captureRasterSnapshot(documentSnapshot, ['a']);
+ const second = await capture.captureRasterSnapshot(documentSnapshot, ['a']);
+ capture.releaseActiveSnapshots();
+ expect(first.status === 'ok' && first.snapshot.layerSurfaces.size).toBe(0);
+ expect(second.status === 'ok' && second.snapshot.layerSurfaces.size).toBe(0);
+ });
+
+ it('stops tracking a snapshot the caller already released', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const documentSnapshot = capture.captureDocumentSnapshot()!;
+ const result = await capture.captureRasterSnapshot(documentSnapshot, ['a']);
+ if (result.status !== 'ok') {
+ throw new Error('expected a captured snapshot');
+ }
+ result.snapshot.release();
+ // Teardown must not re-release, which would double-release the byte lease.
+ expect(() => capture.releaseActiveSnapshots()).not.toThrow();
+ });
+
+ it('frees the detached bytes it reserved once released', async () => {
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const documentSnapshot = capture.captureDocumentSnapshot()!;
+ const before = harness.deps.memory.getAvailableBytes();
+ const result = await capture.captureRasterSnapshot(documentSnapshot, ['a']);
+ expect(harness.deps.memory.getAvailableBytes()).toBeLessThan(before);
+ if (result.status === 'ok') {
+ result.snapshot.release();
+ }
+ expect(harness.deps.memory.getAvailableBytes()).toBe(before);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
new file mode 100644
index 0000000000..5b68741919
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -0,0 +1,277 @@
+import type { CanvasDocumentSnapshot, LayerExportGuard } from '@workbench/canvas-engine/capabilities';
+import type {
+ CanvasDocumentContractV2,
+ CanvasLayerContract,
+ CanvasStateContractV2,
+} from '@workbench/canvas-engine/contracts';
+import type { ExportLayerPixelsResult } from '@workbench/canvas-engine/controllers/rasterExportController';
+import type { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';
+import type { CanvasRasterSnapshot, CaptureRasterSnapshotResult } from '@workbench/canvas-engine/rasterTransactions';
+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
+import type { Rect } from '@workbench/canvas-engine/types';
+
+import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
+import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';
+
+const BYTES_PER_PIXEL = 4;
+
+/**
+ * What a layer is expected to cost once rasterized, from its source rather than
+ * from a raster pass. Reserved up front so a capture that cannot fit is refused
+ * before any work is done; the real cost is topped up per layer afterwards.
+ */
+const estimatedLayerBytes = (layer: CanvasLayerContract, document: CanvasDocumentContractV2): number => {
+ const source = renderableSourceOf(layer);
+ if (source?.type === 'image') {
+ return source.image.width * source.image.height * BYTES_PER_PIXEL;
+ }
+ if (source?.type === 'paint' && source.bitmap) {
+ return source.bitmap.width * source.bitmap.height * BYTES_PER_PIXEL;
+ }
+ const contentRect = getSourceContentRect(layer, document);
+ return contentRect.width * contentRect.height * BYTES_PER_PIXEL;
+};
+
+export interface CreateRasterSnapshotCaptureDeps {
+ readonly memory: RasterMemoryBudgetController;
+ /** Re-reads the live cache sizes into the budget before a reservation decision. */
+ readonly syncMemoryBaselines: () => void;
+ readonly createSurface: (width: number, height: number) => RasterSurface;
+ readonly getCanvasState: () => CanvasStateContractV2 | null;
+ readonly getDocumentGeneration: () => number;
+ readonly getContentEpoch: () => number;
+ readonly getLifecycleGeneration: () => number;
+ readonly isDisposed: () => boolean;
+ readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
+ readonly rasterizeLayerPixels: (
+ layerId: string,
+ options: { includeDisabled?: boolean; signal?: AbortSignal }
+ ) => Promise<ExportLayerPixelsResult>;
+}
+
+export interface RasterSnapshotCapture {
+ /** Clones the current canvas state and stamps it with the engine state it came from. */
+ captureDocumentSnapshot(): CanvasDocumentSnapshot | null;
+ /** Whether the engine has moved on from the state a snapshot was taken against. */
+ isDocumentSnapshotCurrent(snapshot: CanvasDocumentSnapshot): boolean;
+ /** Rasterizes the named layers into detached surfaces owned by the returned snapshot. */
+ captureRasterSnapshot(
+ documentSnapshot: CanvasDocumentSnapshot,
+ layerIds: readonly string[],
+ options?: { signal?: AbortSignal; includeDisabled?: boolean }
+ ): Promise<CaptureRasterSnapshotResult>;
+ /** Releases every snapshot still held, for engine teardown. */
+ releaseActiveSnapshots(): void;
+}
+
+/**
+ * Takes point-in-time copies of the canvas for long-running background work —
+ * PSD export, invocation composites — that must not see the document change
+ * underneath it.
+ *
+ * A document snapshot is a structural clone plus a private record of the engine
+ * state it was cloned from: the canvas object identity, the raster content
+ * epoch, the lifecycle generation, and the document generation. Currency is
+ * that whole tuple, so an edit that produces an identical-looking document
+ * still invalidates the snapshot. The record lives in a `WeakMap` keyed by the
+ * snapshot, which is also how a foreign object is rejected as `'not-ready'`
+ * rather than mistaken for a stale one.
+ *
+ * A raster snapshot then detaches real pixels. Because rasterizing is async and
+ * one capture covers many layers, currency is re-checked before and after every
+ * layer, and every guard captured along the way is re-checked once more before
+ * the snapshot is published — a capture that raced an edit is discarded whole
+ * rather than returning a mix of old and new pixels. Bytes are reserved up
+ * front from a source-based estimate and topped up per layer when a rasterized
+ * surface turns out larger, so a capture cannot overrun the budget mid-flight.
+ */
+export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDeps): RasterSnapshotCapture => {
+ const { isGuardCurrent, memory, syncMemoryBaselines } = deps;
+
+ const activeSnapshots = new Set<CanvasRasterSnapshot>();
+ const snapshotSources = new WeakMap<
+ CanvasDocumentSnapshot,
+ { canvas: CanvasStateContractV2; contentEpoch: number; lifecycleGeneration: number }
+ >();
+
+ const isDocumentSnapshotCurrent = (snapshot: CanvasDocumentSnapshot): boolean => {
+ const source = snapshotSources.get(snapshot);
+ return (
+ !deps.isDisposed() &&
+ source !== undefined &&
+ source.canvas === deps.getCanvasState() &&
+ source.contentEpoch === deps.getContentEpoch() &&
+ source.lifecycleGeneration === deps.getLifecycleGeneration() &&
+ snapshot.documentGeneration === deps.getDocumentGeneration()
+ );
+ };
+
+ const reserveBytes = (bytes: number, generation: number): ReturnType<RasterMemoryBudgetController['reserve']> => {
+ syncMemoryBaselines();
+ return memory.reserve(bytes, { generation, purpose: 'background-snapshot' });
+ };
+
+ const captureRasterSnapshot = async (
+ documentSnapshot: CanvasDocumentSnapshot,
+ layerIds: readonly string[],
+ options?: { signal?: AbortSignal; includeDisabled?: boolean }
+ ): Promise<CaptureRasterSnapshotResult> => {
+ if (options?.signal?.aborted) {
+ return { status: 'aborted' };
+ }
+ if (!snapshotSources.has(documentSnapshot)) {
+ return { status: 'not-ready' };
+ }
+ if (!isDocumentSnapshotCurrent(documentSnapshot)) {
+ return { status: 'stale' };
+ }
+ const captureLifecycleGeneration = snapshotSources.get(documentSnapshot)!.lifecycleGeneration;
+
+ const document = documentSnapshot.canvas.document;
+ const uniqueLayerIds = [...new Set(layerIds)];
+ const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));
+ let requestedBytes = 0;
+ for (const layerId of uniqueLayerIds) {
+ const layer = layerById.get(layerId);
+ const source = layer ? renderableSourceOf(layer) : null;
+ if (!layer || !source || !isSupportedExportSource(source)) {
+ return { status: 'not-ready' };
+ }
+ requestedBytes += estimatedLayerBytes(layer, document);
+ }
+
+ const reservation = reserveBytes(requestedBytes, captureLifecycleGeneration);
+ if (reservation.status === 'over-budget') {
+ return { status: 'over-budget' };
+ }
+ const reservationLeases: { release(): void }[] = [reservation.lease];
+ const pinLeases = uniqueLayerIds.map((layerId) => memory.pin(layerId, captureLifecycleGeneration));
+ const layerSurfaces = new Map<string, { rect: Rect; surface: RasterSurface }>();
+ const emptyLayerIds = new Set<string>();
+ const capturedGuards: LayerExportGuard[] = [];
+ let actualDetachedBytes = 0;
+ try {
+ for (const layerId of uniqueLayerIds) {
+ if (options?.signal?.aborted) {
+ return { status: 'aborted' };
+ }
+ if (!isDocumentSnapshotCurrent(documentSnapshot)) {
+ return { status: 'stale' };
+ }
+ const liveResult = await deps.rasterizeLayerPixels(layerId, {
+ includeDisabled: options?.includeDisabled,
+ signal: options?.signal,
+ });
+ if (options?.signal?.aborted) {
+ return { status: 'aborted' };
+ }
+ if (!isDocumentSnapshotCurrent(documentSnapshot)) {
+ return { status: 'stale' };
+ }
+ if (liveResult.status === 'empty') {
+ emptyLayerIds.add(layerId);
+ continue;
+ }
+ if (liveResult.status !== 'ok') {
+ return {
+ status:
+ liveResult.status === 'aborted' || liveResult.status === 'over-budget' ? liveResult.status : 'not-ready',
+ };
+ }
+ const live = liveResult;
+ if (!isGuardCurrent(live.guard)) {
+ live.release();
+ return { status: 'stale' };
+ }
+ capturedGuards.push(live.guard);
+ try {
+ const actualBytes = live.surface.width * live.surface.height * BYTES_PER_PIXEL;
+ // The up-front reservation was an estimate from the source; a surface
+ // that rasterized larger has to be paid for before it is detached.
+ const additionalBytes = Math.max(0, actualBytes - estimatedLayerBytes(layerById.get(layerId)!, document));
+ if (additionalBytes > 0) {
+ const additional = reserveBytes(additionalBytes, captureLifecycleGeneration);
+ if (additional.status === 'over-budget') {
+ return { status: 'over-budget' };
+ }
+ reservationLeases.push(additional.lease);
+ }
+ const detached = deps.createSurface(live.surface.width, live.surface.height);
+ detached.ctx.setTransform(1, 0, 0, 1, 0, 0);
+ detached.ctx.clearRect(0, 0, detached.width, detached.height);
+ detached.ctx.drawImage(live.surface.canvas, 0, 0);
+ layerSurfaces.set(layerId, { rect: { ...live.rect }, surface: detached });
+ actualDetachedBytes += actualBytes;
+ } finally {
+ live.release();
+ }
+ }
+ // One last check across the whole capture: an edit part-way through leaves
+ // earlier layers describing a document the later ones no longer match.
+ if (!isDocumentSnapshotCurrent(documentSnapshot) || capturedGuards.some((guard) => !isGuardCurrent(guard))) {
+ return { status: 'stale' };
+ }
+
+ // The reservations covered the capture; the published snapshot is tracked
+ // as detached bytes instead, for as long as the caller holds it.
+ for (const lease of reservationLeases) {
+ lease.release();
+ }
+ const detachedLease = memory.trackDetached(actualDetachedBytes, captureLifecycleGeneration);
+ let released = false;
+ const snapshot: CanvasRasterSnapshot = {
+ ...documentSnapshot,
+ emptyLayerIds,
+ layerSurfaces,
+ release: () => {
+ if (released) {
+ return;
+ }
+ released = true;
+ emptyLayerIds.clear();
+ layerSurfaces.clear();
+ detachedLease.release();
+ activeSnapshots.delete(snapshot);
+ },
+ };
+ activeSnapshots.add(snapshot);
+ return { snapshot, status: 'ok' };
+ } finally {
+ for (const lease of reservationLeases) {
+ lease.release();
+ }
+ for (const lease of pinLeases) {
+ lease.release();
+ }
+ }
+ };
+
+ return {
+ captureDocumentSnapshot: () => {
+ const canvas = deps.getCanvasState();
+ if (deps.isDisposed() || !canvas) {
+ return null;
+ }
+ const snapshot: CanvasDocumentSnapshot = {
+ canvas: structuredClone(canvas),
+ documentGeneration: deps.getDocumentGeneration(),
+ };
+ snapshotSources.set(snapshot, {
+ canvas,
+ contentEpoch: deps.getContentEpoch(),
+ lifecycleGeneration: deps.getLifecycleGeneration(),
+ });
+ return snapshot;
+ },
+
+ captureRasterSnapshot,
+
+ isDocumentSnapshotCurrent,
+
+ releaseActiveSnapshots: () => {
+ for (const snapshot of activeSnapshots) {
+ snapshot.release();
+ }
+ },
+ };
+};