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.

fix(canvas): crop generation snapshots to the frame

Josh Corbette968e67ebaba
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 43dafeb518..ca05ebf096 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -99,7 +99,9 @@ Snapshots create a deliberate transaction boundary:
2. After successful invocation detachment, ordinary editing may continue. Composite, upload, graph compilation, queue submission read only frozen contract and detached surfaces.
3. Wholesale canvas replacement stays a separate session, identified by `documentRevision`; completed results from an older session are dropped.
-Canvas invocation first crosses paint-flush barrier, then captures post-flush document, plans every raster/control/regional composite, and detaches exactly the contributing layers. Composite dedupe writes stage in transaction-local maps. They publish to persistent per-engine dedupe cache only after all frozen compositing, uploads, compilation, and queue dispatch complete; stale or failed captures leave no persistent dedupe entries.
+Canvas invocation first crosses paint-flush barrier, then captures post-flush document, plans every raster/control/regional composite, and detaches exactly the contributing layers. It passes the generation bbox as the capture's optional document-space `region`. For unrotated layers at native resolution (signed unit scales, including reflections), capture copies only intersecting source pixels plus one pixel of sampling margin, rounded outward on the source's pixel grid. Translation and paint offsets remain layer-local. The snapshot keeps each layer's actual whole-source `sourceRect` for content bounds and mode detection; its `rect` places the detached pixels. Disjoint sources keep a transparent one-pixel surface and an empty detached rect. Reservations estimate these bounded copies and top up actual extents before allocation, so a small frame on a resident large map does not require a second map-sized surface.
+
+Rotation or rescaling retains whole-source capture: changing a Canvas2D source's origin can change transformed sampling, so these paths preserve the original source grid exactly. Spatial layer stacks and all members of a spatial raster group also retain whole sources because their adjustments depend on that context. Callers omitting `region` (including PSD) retain whole-layer capture. This bounds detached generation inputs, not initial source rasterization: an uncached large source, a transformed layer, or spatial adjustment work can still exceed the unchanged 512 MiB budget. Composite dedupe writes stage in transaction-local maps. They publish to persistent per-engine dedupe cache only after all frozen compositing, uploads, compilation, and queue dispatch complete; stale or failed captures leave no persistent dedupe entries.
`submitCanvasInvocationSnapshot` carries exact cloned canvas state used for compilation. `enqueueCompiledSnapshot` extracts its bounding box, dimensions, document revision instead of reading live project canvas. Generated candidates are placed from `queueItem.snapshot.canvas.document.bbox`, so later bbox edits do not move result. `documentRevision` still keeps results from a replaced canvas session out of current staging.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index d661663b5f..ac3b7a3cba 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -39,6 +39,7 @@ import type {
} from '@workbench/canvas-engine/capabilities';
import type {
CanvasCompositeExecutorDeps,
+ CaptureRasterSnapshotOptions,
CaptureRasterSnapshotResult,
RasterReadLease,
} from '@workbench/canvas-engine/rasterTransactions';
@@ -316,7 +317,7 @@ export interface CanvasEngineInternalExportCapability extends CanvasEngineExport
captureRasterSnapshot(
documentSnapshot: CanvasDocumentSnapshot,
layerIds: readonly string[],
- options?: { signal?: AbortSignal; includeDisabled?: boolean }
+ options?: CaptureRasterSnapshotOptions
): Promise<CaptureRasterSnapshotResult>;
exportBakedLayerPixels(
layerId: string,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts
new file mode 100644
index 0000000000..fa2c15d946
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.browser.test.ts
@@ -0,0 +1,348 @@
+import {
+ createCompositeDedupeCache,
+ executeControlComposite,
+ executeMaskComposite,
+ executeRegionalMaskComposite,
+} from '@workbench/canvas-operations/compositeForGeneration';
+import {
+ planComposites,
+ planControlComposites,
+ planRegionalMaskComposites,
+} from '@workbench/canvas-operations/generationCompositePlan';
+import { describe, expect, it } from 'vitest';
+
+import type { LayerExportGuard } from './capabilities';
+import type {
+ CanvasAdjustmentsContract,
+ CanvasLayerContract,
+ CanvasRasterLayerContractV2,
+ CanvasStateContractV3,
+} from './contracts';
+import type { CanvasRasterSnapshot } from './rasterTransactions';
+import type { Rect } from './types';
+
+import { RasterMemoryBudgetController } from './controllers/rasterMemoryBudgetController';
+import { groupContract, stacksFrom } from './document-model/documentFixtures.testStub';
+import { createRasterSnapshotCapture } from './rasterSnapshotCapture';
+import { createDomRasterBackend } from './render/raster';
+import { planBaseRasterComposite, renderRasterComposite } from './render/rasterComposite';
+import { createSpatialAdjustmentService } from './render/spatial/spatialAdjustmentService';
+
+const noise: CanvasAdjustmentsContract = [
+ {
+ amount: 0.15,
+ distribution: 'gaussian',
+ grain: 'color',
+ id: 'noise',
+ isEnabled: true,
+ response: 'flat',
+ seed: 7,
+ size: 3,
+ type: 'noise',
+ },
+];
+const color: CanvasAdjustmentsContract = [
+ {
+ brightness: 0.1,
+ contrast: 0.1,
+ id: 'color',
+ isEnabled: true,
+ type: 'brightness-contrast',
+ },
+];
+const spatial: CanvasAdjustmentsContract = [
+ {
+ amount: 70,
+ id: 'clarity',
+ isEnabled: true,
+ size: 12,
+ type: 'clarity',
+ },
+];
+const identity = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };
+const transforms = [
+ ['translated', { ...identity, x: 13.25, y: -7.5 }],
+ ['rotated', { ...identity, rotation: Math.PI / 7, x: 45, y: -3 }],
+ ['flipped', { ...identity, scaleX: -1.2, scaleY: 0.8, x: 90, y: 3 }],
+ ['downscaled', { ...identity, scaleX: 0.2, scaleY: 0.3, x: 30, y: 15 }],
+] as const;
+const origin = { x: -19, y: -11 };
+const content = { ...origin, width: 240, height: 180 };
+const bbox: Rect = { x: 37, y: 24, width: 18, height: 20 };
+
+const scene = (
+ transform = identity,
+ adjustments?: CanvasAdjustmentsContract,
+ groupAdjustments?: CanvasAdjustmentsContract,
+ sourceRect = content
+) => {
+ const backend = createDomRasterBackend();
+ const surface = backend.createSurface(content.width, content.height);
+ const pixels = surface.ctx.createImageData(content.width, content.height);
+ for (let y = 0; y < content.height; y++) {
+ for (let x = 0; x < content.width; x++) {
+ const i = (y * content.width + x) * 4;
+ pixels.data.set(
+ [(x * 17 + y * 11) % 256, (x * 3 + y * 7) % 256, (x * 5 + y * 13) % 256, (x + y) % 7 === 0 ? 100 : 255],
+ i
+ );
+ }
+ }
+ surface.ctx.putImageData(pixels, 0, 0);
+ const layer: CanvasRasterLayerContractV2 = {
+ id: 'map',
+ name: 'Map',
+ type: 'raster',
+ isEnabled: true,
+ isLocked: false,
+ blendMode: 'normal',
+ opacity: 0.8,
+ source: {
+ type: 'paint',
+ bitmap: { width: content.width, height: content.height, imageName: 'map.png' },
+ offset: { x: sourceRect.x, y: sourceRect.y },
+ },
+ transform,
+ adjustments,
+ };
+ const document = {
+ background: 'transparent' as const,
+ bbox,
+ width: 256,
+ height: 256,
+ selectedLayerId: null,
+ version: 3 as const,
+ stacks: stacksFrom(
+ groupAdjustments ? [groupContract('group', [layer], { adjustments: groupAdjustments })] : [layer]
+ ),
+ };
+ const canvas = { document } as CanvasStateContractV3;
+ const memory = new RasterMemoryBudgetController();
+ const capture = createRasterSnapshotCapture({
+ memory,
+ createSurface: backend.createSurface,
+ getCanvasState: () => canvas,
+ getDirectPixelEpoch: () => 0,
+ getDocumentGeneration: () => 0,
+ getLifecycleGeneration: () => 0,
+ isDisposed: () => false,
+ isGuardCurrent: () => true,
+ rasterizeLayerPixels: () =>
+ Promise.resolve({
+ status: 'ok',
+ surface,
+ rect: sourceRect,
+ guard: { layerId: layer.id } as LayerExportGuard,
+ release: () => undefined,
+ }),
+ });
+ const service = createSpatialAdjustmentService({
+ reserve: (bytes) => memory.reserveOperation(bytes, { purpose: 'spatial-adjustment' }),
+ });
+ const render = (snapshot: CanvasRasterSnapshot) =>
+ renderRasterComposite(planBaseRasterComposite(document, bbox), {
+ backend,
+ getLayerSurface: (id) => Promise.resolve({ ...snapshot.layerSurfaces.get(id)!, release: () => undefined }),
+ runSpatial: (request) => service.run(request),
+ });
+ return { capture, surface, render, service, memory, canvas, backend, layer, content: sourceRect };
+};
+
+const compare = async (s: ReturnType<typeof scene>, fullSource: boolean) => {
+ const { content } = s;
+ const document = s.capture.captureDocumentSnapshot()!;
+ const full = await s.capture.captureRasterSnapshot(document, ['map']);
+ const cropped = await s.capture.captureRasterSnapshot(document, ['map'], { region: bbox });
+ expect(full.status).toBe('ok');
+ expect(cropped.status).toBe('ok');
+ if (full.status !== 'ok' || cropped.status !== 'ok') {
+ throw new Error('capture failed');
+ }
+ try {
+ const detached = cropped.snapshot.layerSurfaces.get('map')!;
+ expect(detached.surface).not.toBe(s.surface);
+ expect(detached.sourceRect).toEqual(content);
+ if (fullSource) {
+ expect(detached.rect).toEqual(content);
+ } else {
+ expect(detached.surface.width * detached.surface.height).toBeLessThan(content.width * content.height);
+ }
+ // Edits after detachment must not alter either frozen generation input.
+ s.surface.ctx.clearRect(0, 0, content.width, content.height);
+ const a = await s.render(full.snapshot);
+ const b = await s.render(cropped.snapshot);
+ const expected = a.ctx.getImageData(0, 0, bbox.width, bbox.height).data;
+ const actual = b.ctx.getImageData(0, 0, bbox.width, bbox.height).data;
+ expect(expected.some((value) => value !== 0)).toBe(true);
+ expect(actual).toEqual(expected);
+ } finally {
+ full.snapshot.release();
+ cropped.snapshot.release();
+ s.service.dispose();
+ }
+ expect(s.memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0 });
+};
+
+describe('region snapshots through real Canvas2D compositing', () => {
+ it.each(transforms)('preserves %s pixels from a nonzero paint origin', async (_name, transform) => {
+ await compare(
+ scene(transform),
+ transform.rotation !== 0 || Math.abs(transform.scaleX) !== 1 || Math.abs(transform.scaleY) !== 1
+ );
+ });
+ it.each([
+ ['color', color],
+ ['noise', noise],
+ ] as const)('preserves %s adjustment sampling', async (_name, stack) => {
+ await compare(scene(identity, [...stack]), false);
+ await compare(scene(transforms[3][1], [...stack]), true);
+ });
+ it('preserves layer noise inside an adjusted group', async () => {
+ await compare(scene(identity, noise, color), false);
+ });
+ it.each([-2, -1.2, -1, -0.7, 0.2, 0.3, 0.8, 1, 1.2, 2])('keeps source sampling at scale %s', async (scale) => {
+ const t = { rotation: 0, scaleX: scale, scaleY: 0.7, x: bbox.x - 60 * scale, y: bbox.y - 30 };
+ await compare(scene(t), true);
+ await compare(scene(t, color), true);
+ });
+ it.each([-Math.PI / 3, -Math.PI / 8, 0, Math.PI / 8, Math.PI / 3, Math.PI / 2])(
+ 'keeps rotated sampling on its original source at %s',
+ async (rotation) => {
+ await compare(
+ scene({
+ rotation,
+ scaleX: -1,
+ scaleY: 1,
+ x: 46 + 60 * Math.cos(rotation) + 50 * Math.sin(rotation),
+ y: 34 + 60 * Math.sin(rotation) - 50 * Math.cos(rotation),
+ }),
+ rotation !== 0
+ );
+ }
+ );
+ it.each([0, 0.1, 0.2, 0.5, 0.7, 0.99])('crops fractional translation %s with either reflection', async (fraction) => {
+ for (const scaleX of [-1, 1]) {
+ for (const scaleY of [-1, 1]) {
+ await compare(
+ scene({ rotation: 0, scaleX, scaleY, x: 46 - 60 * scaleX + fraction, y: 34 - 50 * scaleY + fraction }),
+ false
+ );
+ }
+ }
+ });
+ it.each([
+ { x: -19.4, y: -11 },
+ { x: -19, y: -11.6 },
+ { x: -19.4, y: -11.6 },
+ ])('preserves fractional source origin $x, $y through sampled adjustments', async (offset) => {
+ for (const stack of [undefined, color, noise]) {
+ await compare(scene(transforms[0][1], stack, undefined, { ...content, ...offset }), false);
+ await compare(
+ scene({ rotation: 0, scaleX: -1, scaleY: -1, x: 107.2, y: 75.7 }, stack, undefined, { ...content, ...offset }),
+ false
+ );
+ }
+ });
+ it('keeps a spatial layer stack on its full source', async () => {
+ await compare(scene(identity, [...noise, ...spatial, ...color]), true);
+ });
+ it('keeps members of a spatial group on their full sources', async () => {
+ await compare(scene(identity, noise, spatial), true);
+ });
+});
+
+it.each([origin, { x: -19.4, y: -11.6 }])(
+ 'keeps control, regional and inpaint-mask uploads pixel-identical at $x, $y',
+ async (offset) => {
+ const s = scene({ rotation: 0, scaleX: -1, scaleY: 1, x: 107.2, y: -15.7 }, undefined, undefined, {
+ ...content,
+ ...offset,
+ });
+ const common = {
+ isEnabled: true,
+ isLocked: false,
+ blendMode: 'normal' as const,
+ opacity: 1,
+ transform: s.layer.transform,
+ };
+ const mask = {
+ bitmap: { width: content.width, height: content.height, imageName: 'mask.png' },
+ offset,
+ fill: { color: '#ff0000', style: 'solid' as const },
+ };
+ const layers: CanvasLayerContract[] = [
+ { ...common, type: 'inpaint_mask', id: 'mask', name: 'Mask', mask },
+ {
+ ...common,
+ type: 'regional_guidance',
+ id: 'region',
+ name: 'Region',
+ mask,
+ autoNegative: false,
+ positivePrompt: 'region',
+ negativePrompt: null,
+ referenceImages: [],
+ },
+ {
+ ...common,
+ type: 'control',
+ id: 'control',
+ name: 'Control',
+ source: s.layer.source,
+ withTransparencyEffect: true,
+ adapter: { kind: 'controlnet', model: null, beginEndStepPct: [0, 1], controlMode: 'balanced', weight: 1 },
+ },
+ ];
+ s.canvas.document.stacks = stacksFrom(layers);
+ const document = s.capture.captureDocumentSnapshot()!;
+ const full = await s.capture.captureRasterSnapshot(
+ document,
+ layers.map((layer) => layer.id)
+ );
+ const cropped = await s.capture.captureRasterSnapshot(
+ document,
+ layers.map((layer) => layer.id),
+ { region: bbox }
+ );
+ if (full.status !== 'ok' || cropped.status !== 'ok') {
+ throw new Error('capture failed');
+ }
+ const execute = async (snapshot: CanvasRasterSnapshot) => {
+ const uploads: Uint8ClampedArray[] = [];
+ const deps = {
+ backend: s.backend,
+ dedupe: createCompositeDedupeCache(),
+ getLayerSurface: (id: string) =>
+ Promise.resolve({ ...snapshot.layerSurfaces.get(id)!, release: () => undefined }),
+ hashBlob: () => Promise.resolve(String(uploads.length)),
+ uploadImage: async (blob: Blob) => {
+ const bitmap = await s.backend.createImageBitmap(blob);
+ const decoded = s.backend.createSurface(bbox.width, bbox.height);
+ decoded.ctx.drawImage(bitmap, 0, 0);
+ bitmap.close();
+ uploads.push(decoded.ctx.getImageData(0, 0, bbox.width, bbox.height).data);
+ return { imageName: String(uploads.length), width: bbox.width, height: bbox.height };
+ },
+ };
+ await executeControlComposite(planControlComposites(document.canvas.document, bbox)[0]!.entry, deps);
+ await executeRegionalMaskComposite(planRegionalMaskComposites(document.canvas.document, bbox)[0]!.entry, deps);
+ await executeMaskComposite(
+ planComposites(document.canvas.document, bbox).entries.find((entry) => entry.kind === 'inpaint-mask')!,
+ deps
+ );
+ return uploads;
+ };
+ try {
+ s.surface.ctx.clearRect(0, 0, content.width, content.height);
+ const expected = await execute(full.snapshot);
+ const actual = await execute(cropped.snapshot);
+ expect(expected).toHaveLength(3);
+ expect(actual).toEqual(expected);
+ } finally {
+ full.snapshot.release();
+ cropped.snapshot.release();
+ s.service.dispose();
+ }
+ expect(s.memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0 });
+ }
+);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
index 008526e815..7927dff05a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.test.ts
@@ -422,3 +422,87 @@ describe('snapshot lifetime', () => {
expect(harness.memory.getAvailableBytes()).toBe(before);
});
});
+
+describe('region capture accounting and cleanup', () => {
+ it.each(['stale', 'aborted'] as const)('releases a read lease returned after capture becomes %s', async (status) => {
+ const controller = new AbortController();
+ const live = okPixels('a');
+ const pin = harness.memory.pin('a');
+ if (live.status !== 'ok') {
+ throw new Error('expected live pixels');
+ }
+ live.release = vi.fn(() => pin.release());
+ harness.rasterize.mockImplementation(() => {
+ if (status === 'stale') {
+ harness.state.directPixelEpoch++;
+ } else {
+ controller.abort();
+ }
+ return Promise.resolve(live);
+ });
+ const capture = createRasterSnapshotCapture(harness.deps);
+ const result = await capture.captureRasterSnapshot(capture.captureDocumentSnapshot()!, ['a'], {
+ region: { x: 0, y: 0, width: 1, height: 1 },
+ signal: controller.signal,
+ });
+ expect(result.status).toBe(status);
+ expect(live.release).toHaveBeenCalledOnce();
+ expect(harness.memory.isPinned('a')).toBe(false);
+ expect(harness.memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0 });
+ });
+
+ it.each([100, 1000])(
+ 'tops up an underestimated source before allocating a cropped surface with a %i byte budget',
+ async (budget) => {
+ const memory = new RasterMemoryBudgetController({ budgetBytes: budget });
+ const createSurface = vi.fn((width: number, height: number) => surface(width, height));
+ const h = makeHarness({ createSurface }, memory);
+ const live = okPixels('a', 20);
+ if (live.status !== 'ok') {
+ throw new Error('expected live pixels');
+ }
+ h.currentGuards.add(live.guard);
+ h.rasterize.mockResolvedValue(live);
+ const capture = createRasterSnapshotCapture(h.deps);
+ const result = await capture.captureRasterSnapshot(capture.captureDocumentSnapshot()!, ['a', 'a'], {
+ region: { x: 10, y: 10, width: 8, height: 8 },
+ });
+ expect(h.rasterize).toHaveBeenCalledOnce();
+ if (budget === 100) {
+ expect(result.status).toBe('over-budget');
+ expect(createSurface).not.toHaveBeenCalled();
+ } else {
+ expect(result.status).toBe('ok');
+ if (result.status !== 'ok') {
+ throw new Error('expected captured pixels');
+ }
+ expect(result.snapshot.layerSurfaces.get('a')?.rect).toEqual({ x: 9, y: 9, width: 10, height: 10 });
+ expect(memory.snapshot().detachedBytes).toBe(400);
+ result.snapshot.release();
+ }
+ expect(live.release).toHaveBeenCalledOnce();
+ expect(memory.isPinned('a')).toBe(false);
+ expect(memory.snapshot()).toMatchObject({ reservedBytes: 0, detachedBytes: 0 });
+ }
+ );
+
+ it('represents a disjoint layer without copying its pixels or losing its original bounds', async () => {
+ const createSurface = vi.fn((width: number, height: number) => surface(width, height));
+ const h = makeHarness({ createSurface });
+ const capture = createRasterSnapshotCapture(h.deps);
+ const result = await capture.captureRasterSnapshot(capture.captureDocumentSnapshot()!, ['a'], {
+ region: { x: 100, y: 100, width: 10, height: 10 },
+ });
+ expect(result.status).toBe('ok');
+ if (result.status !== 'ok') {
+ throw new Error('expected captured pixels');
+ }
+ const layer = result.snapshot.layerSurfaces.get('a')!;
+ expect(layer.rect).toEqual({ x: 0, y: 0, width: 0, height: 0 });
+ expect(layer.sourceRect).toEqual({ x: 0, y: 0, width: 4, height: 4 });
+ expect(createSurface).toHaveBeenCalledWith(1, 1);
+ expect(layer.surface.ctx.drawImage).not.toHaveBeenCalled();
+ expect(h.memory.snapshot().detachedBytes).toBe(4);
+ result.snapshot.release();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
index a1c156cc82..f0c9ed4e18 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterSnapshotCapture.ts
@@ -1,34 +1,47 @@
import type { CanvasDocumentSnapshot, LayerExportGuard } from '@workbench/canvas-engine/capabilities';
-import type {
- CanvasDocumentContractV3,
- CanvasLayerContract,
- CanvasStateContractV3,
-} from '@workbench/canvas-engine/contracts';
+import type { CanvasStateContractV3 } 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 {
+ CanvasDetachedLayerSurface,
+ CanvasRasterSnapshot,
+ CaptureRasterSnapshotOptions,
+ CaptureRasterSnapshotResult,
+} from '@workbench/canvas-engine/rasterTransactions';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
import { lookupDocumentLayer } from '@workbench/canvas-engine/document-model/documentModel';
+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { isSupportedExportSource } from '@workbench/canvas-engine/layerExportGuards';
+import { fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';
+import { expand, intersect, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';
+import { hasSpatialAdjustments } from '@workbench/canvas-engine/render/adjustments';
const BYTES_PER_PIXEL = 4;
-/** Reserve source-estimated raster bytes before capture; top up with actual layer costs after rasterization. */
-const estimatedLayerBytes = (layer: CanvasLayerContract, document: CanvasDocumentContractV3): 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;
+/** Select whole source pixels, preserving their grid even when the layer-local content origin is fractional. */
+const captureRect = (content: Rect, region: Rect | undefined): Rect => {
+ if (!region) {
+ return { ...content };
}
- const contentRect = getSourceContentRect(layer, document);
- return contentRect.width * contentRect.height * BYTES_PER_PIXEL;
+ // Adjustments sample an outward-rounded layer-local region; cover it before snapping to the source pixel grid.
+ const local = roundOut(expand(region, 1));
+ const sampled = intersect(roundOut({ ...local, x: local.x - content.x, y: local.y - content.y }), {
+ x: 0,
+ y: 0,
+ width: content.width,
+ height: content.height,
+ });
+ return sampled
+ ? { ...sampled, x: sampled.x + content.x, y: sampled.y + content.y }
+ : { x: content.x, y: content.y, width: 0, height: 0 };
};
+// A disjoint layer keeps a transparent pixel so downstream Canvas2D drawing remains valid.
+const rectBytes = (rect: Rect): number => Math.max(1, rect.width) * Math.max(1, rect.height) * BYTES_PER_PIXEL;
+
export interface CreateRasterSnapshotCaptureDeps {
readonly memory: Pick<RasterMemoryBudgetController, 'pin' | 'reserve' | 'trackDetached'>;
readonly createSurface: (width: number, height: number) => RasterSurface;
@@ -53,7 +66,7 @@ export interface RasterSnapshotCapture {
captureRasterSnapshot(
documentSnapshot: CanvasDocumentSnapshot,
layerIds: readonly string[],
- options?: { signal?: AbortSignal; includeDisabled?: boolean }
+ options?: CaptureRasterSnapshotOptions
): Promise<CaptureRasterSnapshotResult>;
/** Releases every snapshot still held, for engine teardown. */
releaseActiveSnapshots(): void;
@@ -93,7 +106,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
const captureRasterSnapshot = async (
documentSnapshot: CanvasDocumentSnapshot,
layerIds: readonly string[],
- options?: { signal?: AbortSignal; includeDisabled?: boolean }
+ options?: CaptureRasterSnapshotOptions
): Promise<CaptureRasterSnapshotResult> => {
if (options?.signal?.aborted) {
return { status: 'aborted' };
@@ -108,6 +121,9 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
const document = documentSnapshot.canvas.document;
const uniqueLayerIds = [...new Set(layerIds)];
+ const regions = new Map<string, Rect>();
+ const estimatedBytes = new Map<string, number>();
+ const index = getDocumentIndex(document);
let requestedBytes = 0;
for (const layerId of uniqueLayerIds) {
const layer = lookupDocumentLayer(document, layerId);
@@ -115,7 +131,29 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
if (!layer || !source || !isSupportedExportSource(source)) {
return { status: 'not-ready' };
}
- requestedBytes += estimatedLayerBytes(layer, document);
+ if (options?.region) {
+ // Spatial stacks need the owner's whole source, including every member of a spatial group.
+ const spatial =
+ layer.type === 'raster' &&
+ (hasSpatialAdjustments(layer.adjustments) ||
+ index.byId.get(layerId)!.path.some((id) => {
+ const ancestor = index.byId.get(id)!.node;
+ return ancestor.type === 'group' && hasSpatialAdjustments(ancestor.adjustments);
+ }));
+ const t = layer.transform;
+ // Rotating or scaling a cropped Canvas2D source can change sampling; retain the original pixel grid.
+ const unitScale = Math.abs(t.scaleX) === 1 && Math.abs(t.scaleY) === 1;
+ const inverse = !spatial && unitScale && t.rotation === 0 && invert(fromTRS(t, t.rotation, t.scaleX, t.scaleY));
+ if (inverse) {
+ regions.set(layerId, transformBounds(inverse, options.region));
+ }
+ }
+ const content = getSourceContentRect(layer, document);
+ const bytes = regions.has(layerId)
+ ? rectBytes(captureRect(content, regions.get(layerId)))
+ : content.width * content.height * BYTES_PER_PIXEL;
+ estimatedBytes.set(layerId, bytes);
+ requestedBytes += bytes;
}
const reservation = reserveBytes(requestedBytes, captureLifecycleGeneration);
@@ -125,7 +163,7 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
const reservationLeases: { release(): void }[] = [reservation.lease];
// Earlier layers stay resident while later ones rasterize, so the final guard check cannot fail spuriously.
const pinLeases = uniqueLayerIds.map((layerId) => memory.pin(layerId));
- const layerSurfaces = new Map<string, { rect: Rect; surface: RasterSurface }>();
+ const layerSurfaces = new Map<string, CanvasDetachedLayerSurface>();
const emptyLayerIds = new Set<string>();
const capturedGuards: LayerExportGuard[] = [];
let actualDetachedBytes = 0;
@@ -142,9 +180,15 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
signal: options?.signal,
});
if (options?.signal?.aborted) {
+ if (liveResult.status === 'ok') {
+ liveResult.release();
+ }
return { status: 'aborted' };
}
if (!isDocumentSnapshotCurrent(documentSnapshot)) {
+ if (liveResult.status === 'ok') {
+ liveResult.release();
+ }
return { status: 'stale' };
}
if (liveResult.status === 'empty') {
@@ -167,11 +211,12 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
}
capturedGuards.push(live.guard);
try {
- const actualBytes = live.surface.width * live.surface.height * BYTES_PER_PIXEL;
+ const region = regions.get(layerId);
+ const rect = captureRect({ ...live.rect, width: live.surface.width, height: live.surface.height }, region);
+ const actualBytes = rectBytes(rect);
// 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 snapshotLayer = lookupDocumentLayer(document, layerId)!;
- const additionalBytes = Math.max(0, actualBytes - estimatedLayerBytes(snapshotLayer, document));
+ const additionalBytes = Math.max(0, actualBytes - estimatedBytes.get(layerId)!);
if (additionalBytes > 0) {
const additional = reserveBytes(additionalBytes, captureLifecycleGeneration);
if (additional.status === 'over-budget') {
@@ -179,11 +224,17 @@ export const createRasterSnapshotCapture = (deps: CreateRasterSnapshotCaptureDep
}
reservationLeases.push(additional.lease);
}
- const detached = deps.createSurface(live.surface.width, live.surface.height);
+ const detached = deps.createSurface(Math.max(1, rect.width), Math.max(1, rect.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 });
+ if (rect.width > 0 && rect.height > 0) {
+ detached.ctx.drawImage(live.surface.canvas, live.rect.x - rect.x, live.rect.y - rect.y);
+ }
+ layerSurfaces.set(layerId, {
+ rect: region ? rect : { ...live.rect },
+ ...(options?.region ? { sourceRect: { ...live.rect } } : {}),
+ surface: detached,
+ });
actualDetachedBytes += actualBytes;
} finally {
live.release();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
index ca65d614f7..cea1ee54da 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/rasterTransactions.ts
@@ -17,7 +17,16 @@ export interface RasterReadLease {
release(): void;
}
+export interface CaptureRasterSnapshotOptions {
+ signal?: AbortSignal;
+ includeDisabled?: boolean;
+ /** Document-space output region. Rotated/scaled layers and spatial stacks retain their full source context. */
+ region?: Rect;
+}
+
export interface CanvasDetachedLayerSurface {
+ /** Whole source extent before optional region capture; authoritative for content bounds. */
+ readonly sourceRect?: Rect;
readonly rect: Rect;
readonly surface: RasterSurface;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.budget.test.ts
new file mode 100644
index 0000000000..570143ae2a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.budget.test.ts
@@ -0,0 +1,131 @@
+import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
+import type { CanvasStateContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+
+import { RasterMemoryBudgetController } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';
+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createRasterSnapshotCapture } from '@workbench/canvas-engine/rasterSnapshotCapture';
+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
+import { createCompositeDedupeCache } from '@workbench/canvas-operations/compositeForGeneration';
+import { composeForGeneration } from '@workbench/canvas-operations/generationComposite';
+import { describe, it, expect, vi } from 'vitest';
+
+const cases = [
+ { width: 8192, height: 8192, bbox: 512 },
+ { width: 8192, height: 8192, bbox: 1024 },
+ { width: 12000, height: 8000, bbox: 512 },
+ { width: 12000, height: 8000, bbox: 1024 },
+];
+
+describe('large map small bbox through real generation capture and memory budget', () => {
+ it.each(cases)('$width x $height / bbox $bbox', async ({ width, height, bbox }) => {
+ const backend = createTestStubRasterBackend();
+ const memory = new RasterMemoryBudgetController();
+ const layers = createLayerCacheStore(backend, { onBytesChange: (bytes) => memory.setCategoryBytes('base', bytes) });
+ const shared = {
+ blendMode: 'normal' as const,
+ isEnabled: true,
+ isLocked: false,
+ opacity: 1,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ };
+ const map: CanvasLayerContract = {
+ ...shared,
+ id: 'map',
+ name: 'Map',
+ source: { type: 'image', image: { width, height, imageName: 'map.png' } },
+ type: 'raster',
+ };
+ const maskLayer: CanvasLayerContract = {
+ ...shared,
+ transform: { ...shared.transform, x: width / 2, y: height / 2 },
+ id: 'mask',
+ name: 'Mask',
+ mask: {
+ bitmap: { width: bbox, height: bbox, imageName: 'mask.png' },
+ fill: { color: '#ff0000', style: 'solid' },
+ },
+ type: 'inpaint_mask',
+ };
+ const state = {
+ document: {
+ background: 'transparent',
+ bbox: { x: width / 2, y: height / 2, width: bbox, height: bbox },
+ width,
+ height,
+ stacks: stacksFrom([map, maskLayer]),
+ selectedLayerId: 'map',
+ version: 3,
+ },
+ documentRevision: 0,
+ snapshots: [],
+ stagingArea: {
+ areThumbnailsVisible: true,
+ autoSwitchMode: 'off',
+ isVisible: false,
+ pendingImageIds: [],
+ pendingImages: [],
+ selectedImageIndex: 0,
+ },
+ version: 3,
+ } as CanvasStateContractV3;
+ layers.getOrCreate('map', width, height);
+ layers.getOrCreate('mask', bbox, bbox);
+ // Steady-state caches: decoded images have already released their final lease.
+ const initial = memory.snapshot();
+ let peakBytes = initial.totalBytes;
+ const allocations: number[] = [];
+ const createSurface = (w: number, h: number) => {
+ peakBytes = Math.max(peakBytes, memory.snapshot().totalBytes);
+ allocations.push(w * h * 4);
+ return backend.createSurface(w, h);
+ };
+ const capture = createRasterSnapshotCapture({
+ createSurface,
+ getCanvasState: () => state,
+ getDirectPixelEpoch: () => 0,
+ getDocumentGeneration: () => 0,
+ getLifecycleGeneration: () => 0,
+ isDisposed: () => false,
+ isGuardCurrent: () => true,
+ memory,
+ rasterizeLayerPixels: (layerId) => {
+ const entry = layers.get(layerId)!;
+ return Promise.resolve({
+ status: 'ok' as const,
+ guard: { layerId } as LayerExportGuard,
+ rect: entry.rect,
+ surface: entry.surface,
+ release() {},
+ });
+ },
+ });
+ const detectMode = vi.fn(() => 'inpaint' as const);
+ const result = await composeForGeneration(
+ {
+ ...capture,
+ dedupe: createCompositeDedupeCache(),
+ getCompositeExecutorDeps: () => ({
+ backend: { ...backend, createSurface },
+ hashBlob: () => Promise.resolve('hash'),
+ uploadImage: () => Promise.resolve({ imageName: 'composite.png', width: bbox, height: bbox }),
+ reserve: (bytes) => memory.reserveOperation(bytes, { purpose: 'invocation-composite' }),
+ }),
+ },
+ { signal: new AbortController().signal, detectMode }
+ );
+ expect(result.status).toBe('ok');
+ expect(detectMode).toHaveBeenCalledWith(
+ expect.objectContaining({ contentBounds: { x: 0, y: 0, width, height }, hasActiveInpaintMask: true })
+ );
+ expect(peakBytes).toBeLessThan(memory.budgetBytes);
+ // Two detached inputs plus the mask compositor's output/readback and scratch/readback.
+ expect(peakBytes - initial.totalBytes).toBeLessThanOrEqual(((bbox + 2) ** 2 + 5 * bbox ** 2) * 4);
+ expect(Math.max(...allocations)).toBeLessThanOrEqual((bbox + 2) ** 2 * 4);
+ expect(memory.snapshot().totalBytes).toBe(initial.totalBytes);
+ expect(memory.isPinned('map')).toBe(false);
+ expect(memory.isPinned('mask')).toBe(false);
+ expect(memory.snapshot().reservedBytes).toBe(0);
+ expect(memory.snapshot().detachedBytes).toBe(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
index 44cd51879f..bdba8164db 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/generationComposite.ts
@@ -91,7 +91,7 @@ export interface GenerationCompositeHost {
captureRasterSnapshot(
snapshot: CanvasDocumentSnapshot,
layerIds: readonly string[],
- options: { signal: AbortSignal }
+ options: { signal: AbortSignal; region: Rect }
): Promise<CaptureRasterSnapshotResult>;
/** The engine's composite executor deps (backend, upload, reserve, ...). */
getCompositeExecutorDeps(): GenerationCompositeExecutorDeps;
@@ -175,6 +175,7 @@ export const composeForGeneration = async (
const capture = await host.captureRasterSnapshot(documentSnapshot, [...requiredLayerIds], {
signal: options.signal,
+ region: bbox,
});
if (capture.status !== 'ok') {
return capture;
@@ -221,7 +222,7 @@ export const composeForGeneration = async (
// edges do not overlap and need no base upload.
const actualLayerRects = new Map<string, Rect>();
for (const [layerId, detached] of rasterSnapshot.layerSurfaces) {
- actualLayerRects.set(layerId, detached.rect);
+ actualLayerRects.set(layerId, detached.sourceRect ?? detached.rect);
}
const contentBounds = computeCompositeContentBounds(plan, actualLayerRects);