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
perf(webv2): refresh adjusted surfaces over the written band only
joshistoast1e11b848d7b0
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.tsindex 7f4b687091..4817216523 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.ts@@ -70,7 +70,9 @@ export class RasterController {this.getLayerImageName = options.getLayerImageName ?? (() => null);this.imageResolver = options.imageResolver ?? null;this.derived = createDerivedSurfaceCache(options.diagnostics);- this.adjustments = createAdjustedSurfaceCache(options.backend, this.derived);+ this.adjustments = createAdjustedSurfaceCache(options.backend, this.derived, (layerId, version) =>+ this.layers.damageSince(layerId, version)+ );}async decodeImage(diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.tsindex 741d8f5351..ced7c323f6 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceCache.ts@@ -1,4 +1,7 @@import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';+import type { Rect } from '@workbench/canvas-engine/types';++import { intersect, roundOut } from '@workbench/canvas-engine/math/rect';import type { LayerCacheEntry } from './layerCache';import type { RasterBackend, RasterSurface } from './raster';@@ -32,8 +35,25 @@ export interface AdjustedSurfaceCache {/** Creates an {@link AdjustedSurfaceCache} backed by the given {@link RasterBackend}. */export const createAdjustedSurfaceCache = (backend: RasterBackend,- cache: DerivedSurfaceCache = createDerivedSurfaceCache()+ cache: DerivedSurfaceCache = createDerivedSurfaceCache(),+ /**+ * Reports the surface-local region a layer's cache was written in since a+ * given version — {@link LayerCacheStore.damageSince}. Omit it and every+ * rebuild is wholesale, which is what callers without a layer cache (tests,+ * one-off derivations) want.+ */+ layerDamageSince?: (layerId: string, version: number) => Rect | null): AdjustedSurfaceCache => {+ /** The damaged region clamped to the surface, or `null` to rebuild in full. */+ const damageSince = (layerId: string, version: number, width: number, height: number): Rect | null => {+ const damaged = layerDamageSince?.(layerId, version) ?? null;+ if (!damaged) {+ return null;+ }+ const clamped = intersect(roundOut(damaged), { height, width, x: 0, y: 0 });+ return clamped && clamped.width > 0 && clamped.height > 0 ? clamped : null;+ };+const get = (layerId: string,entry: LayerCacheEntry,@@ -51,20 +71,41 @@ export const createAdjustedSurfaceCache = (}const key = adjustmentsKey(adjustments);return cache.get({- create: (target) => {+ create: (target, reusableFromVersion) => {const surface = target ?? backend.createSurface(width, height);- if (surface.width !== width || surface.height !== height) {+ const resized = surface.width !== width || surface.height !== height;+ if (resized) {surface.resize(width, height);}+ // Rebuilding this costs a full-surface readback plus a per-pixel JS pass+ // — 35ms on a 2600x2100 layer, which is where a live stroke on an+ // adjusted layer spends its entire frame. A stroke bumps the source+ // version every tick, so the memo misses every frame; refreshing only+ // the region the stroke actually wrote turns that into a fraction of the+ // work. A resize invalidates the retained pixels, so it forces the full+ // path regardless of what the trail says.+ const refresh =+ resized || reusableFromVersion === null ? null : damageSince(layerId, reusableFromVersion, width, height);+ const region = refresh ?? { height, width, x: 0, y: 0 };const ctx = surface.ctx;ctx.setTransform(1, 0, 0, 1, 0, 0);- ctx.clearRect(0, 0, width, height);+ ctx.clearRect(region.x, region.y, region.width, region.height);ctx.globalAlpha = 1;ctx.globalCompositeOperation = 'source-over';- ctx.drawImage(entry.surface.canvas, 0, 0);- const imageData = ctx.getImageData(0, 0, width, height);+ ctx.drawImage(+ entry.surface.canvas,+ region.x,+ region.y,+ region.width,+ region.height,+ region.x,+ region.y,+ region.width,+ region.height+ );+ const imageData = ctx.getImageData(region.x, region.y, region.width, region.height);applyAdjustments(imageData, adjustments);- ctx.putImageData(imageData, 0, 0);+ ctx.putImageData(imageData, region.x, region.y);return surface;},kind: 'adjustments',diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.tsnew file mode 100644index 0000000000..462574a836--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/adjustedSurfaceDamage.browser.test.ts@@ -0,0 +1,179 @@+/**+ * The correctness guard for partially-refreshed adjusted surfaces.+ *+ * A live stroke bumps its layer's cache version every tick, which defeats the+ * adjusted-surface memo — so on an adjusted raster layer the surface was being+ * rebuilt from the whole layer every frame: a full readback plus a per-pixel JS+ * pass, 35 ms on a 2600×2100 layer. It now refreshes only the band the stroke+ * reported writing.+ *+ * That is only safe if a partial refresh is indistinguishable from a rebuild, so+ * these tests drive real canvases and compare the two pixel for pixel.+ */++import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';+import type { Rect } from '@workbench/canvas-engine/types';++import { createAdjustedSurfaceCache } from '@workbench/canvas-engine/render/adjustedSurfaceCache';+import { createDerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { describe, expect, it } from 'vitest';++const WIDTH = 320;+const HEIGHT = 240;+const ADJUSTMENTS = {+ brightness: 0.25,+ contrast: 0.15,+ hue: 0,+ saturation: -0.2,+} as unknown as CanvasAdjustmentsContract;++/** A layer cache seeded with a gradient, plus an adjusted cache over it. */+const setup = (withDamageTracking: boolean) => {+ const backend = createDomRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreate('L', WIDTH, HEIGHT);+ const entry = layers.get('L')!;+ const gradient = entry.surface.ctx.createLinearGradient(0, 0, WIDTH, HEIGHT);+ gradient.addColorStop(0, '#1d4ed8');+ gradient.addColorStop(1, '#f59e0b');+ entry.surface.ctx.fillStyle = gradient;+ entry.surface.ctx.fillRect(0, 0, WIDTH, HEIGHT);+ layers.publishPixels('L');+ const adjusted = createAdjustedSurfaceCache(+ backend,+ createDerivedSurfaceCache(),+ withDamageTracking ? (layerId, version) => layers.damageSince(layerId, version) : undefined+ );+ return { adjusted, entry, layers };+};++/** Paints a rect of the layer cache and publishes it with (or without) damage. */+const paint = (+ layers: ReturnType<typeof createLayerCacheStore>,+ rect: Rect,+ color: string,+ reportDamage: boolean+): void => {+ const entry = layers.get('L')!;+ const ctx = entry.surface.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.fillStyle = color;+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height);+ layers.publishPixels('L', reportDamage ? rect : null);+};++const pixelsOf = (surface: { ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D }) =>+ surface.ctx.getImageData(0, 0, WIDTH, HEIGHT).data;++const worstDifference = (a: Uint8ClampedArray, b: Uint8ClampedArray): number => {+ let worst = 0;+ for (let i = 0; i < a.length; i++) {+ worst = Math.max(worst, Math.abs(a[i]! - b[i]!));+ }+ return worst;+};++/**+ * Runs `steps` against two independent caches — one refreshing partially, one+ * always rebuilding — and returns both results.+ */+const compare = (steps: { rect: Rect; color: string }[], reportDamage = true) => {+ const partial = setup(true);+ const wholesale = setup(false);+ let partialPixels = new Uint8ClampedArray();+ let wholesalePixels = new Uint8ClampedArray();+ for (const { color, rect } of steps) {+ paint(partial.layers, rect, color, reportDamage);+ paint(wholesale.layers, rect, color, reportDamage);+ partialPixels = pixelsOf(partial.adjusted.get('L', partial.layers.get('L')!, ADJUSTMENTS)!);+ wholesalePixels = pixelsOf(wholesale.adjusted.get('L', wholesale.layers.get('L')!, ADJUSTMENTS)!);+ }+ return { partialPixels, wholesalePixels };+};++describe('partially-refreshed adjusted surfaces match a full rebuild', () => {+ it('tracks a single painted band', () => {+ const { partialPixels, wholesalePixels } = compare([+ { color: '#22c55e', rect: { height: 60, width: 80, x: 40, y: 30 } },+ ]);+ expect(worstDifference(partialPixels, wholesalePixels)).toBe(0);+ });++ it('tracks many successive bands across the surface', () => {+ const steps = Array.from({ length: 10 }, (_, i) => ({+ color: i % 2 === 0 ? '#22c55e' : '#ef4444',+ rect: { height: 40, width: 50, x: 10 + i * 28, y: 20 + i * 18 },+ }));+ const { partialPixels, wholesalePixels } = compare(steps);+ expect(worstDifference(partialPixels, wholesalePixels)).toBe(0);+ });++ it('tracks overlapping bands', () => {+ const { partialPixels, wholesalePixels } = compare([+ { color: '#22c55e', rect: { height: 90, width: 90, x: 50, y: 50 } },+ { color: '#a855f7', rect: { height: 90, width: 90, x: 90, y: 80 } },+ { color: '#facc15', rect: { height: 40, width: 200, x: 20, y: 100 } },+ ]);+ expect(worstDifference(partialPixels, wholesalePixels)).toBe(0);+ });++ it('tracks a band touching the surface edges', () => {+ const { partialPixels, wholesalePixels } = compare([+ { color: '#22c55e', rect: { height: HEIGHT, width: 30, x: 0, y: 0 } },+ { color: '#ef4444', rect: { height: 25, width: WIDTH, x: 0, y: HEIGHT - 25 } },+ ]);+ expect(worstDifference(partialPixels, wholesalePixels)).toBe(0);+ });++ it('rebuilds in full when a later write does not report its damage', () => {+ // The case that matters is MIXED: a reported write followed by an unreported+ // one. Treating the unreported write as "nothing changed there" would refresh+ // only the first band and leave the second one's pixels unadjusted, so this+ // is what pins `damageSince` bailing out rather than skipping the step.+ // Two writes have to follow the build for this to bite: one reported, one+ // not. With only the unreported one there is nothing to refresh either way,+ // so the bail-out and a "skip the unknown step" bug look identical.+ const partial = setup(true);+ const wholesale = setup(false);+ const built = { height: 60, width: 80, x: 40, y: 30 };+ const reported = { height: 50, width: 60, x: 20, y: 150 };+ const unreported = { height: 70, width: 120, x: 140, y: 120 };+ for (const scene of [partial, wholesale]) {+ paint(scene.layers, built, '#22c55e', true);+ scene.adjusted.get('L', scene.layers.get('L')!, ADJUSTMENTS);+ paint(scene.layers, reported, '#0ea5e9', true);+ paint(scene.layers, unreported, '#a855f7', false);+ }+ const a = pixelsOf(partial.adjusted.get('L', partial.layers.get('L')!, ADJUSTMENTS)!);+ const b = pixelsOf(wholesale.adjusted.get('L', wholesale.layers.get('L')!, ADJUSTMENTS)!);+ expect(worstDifference(a, b)).toBe(0);+ });++ it('rebuilds in full when the surface is reallocated under it', () => {+ // Growth moves the surface origin, so every recorded band is void.+ const { adjusted, layers } = setup(true);+ paint(layers, { height: 60, width: 80, x: 40, y: 30 }, '#22c55e', true);+ adjusted.get('L', layers.get('L')!, ADJUSTMENTS);+ layers.growToRect('L', { height: HEIGHT + 80, width: WIDTH + 60, x: -30, y: -40 });+ const grown = layers.get('L')!;+ grown.surface.ctx.fillStyle = '#0ea5e9';+ grown.surface.ctx.fillRect(0, 0, 60, 40);+ layers.publishPixels('L', { height: 40, width: 60, x: 0, y: 0 });++ const reference = setup(false);+ reference.layers.growToRect('L', { height: HEIGHT + 80, width: WIDTH + 60, x: -30, y: -40 });+ const referenceEntry = reference.layers.get('L')!;+ referenceEntry.surface.ctx.drawImage(grown.surface.canvas, 0, 0);+ reference.layers.publishPixels('L');++ const after = adjusted.get('L', grown, ADJUSTMENTS)!;+ const expected = reference.adjusted.get('L', referenceEntry, ADJUSTMENTS)!;+ const size = grown.surface.width * grown.surface.height * 4;+ const a = after.ctx.getImageData(0, 0, grown.surface.width, grown.surface.height).data;+ const b = expected.ctx.getImageData(0, 0, grown.surface.width, grown.surface.height).data;+ expect(a.length).toBe(size);+ expect(worstDifference(a, b)).toBe(0);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex 0fd13c91dd..eb6cbdb78b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -181,7 +181,11 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF// that actually changed; `null` repaints the whole viewport.damage: isolatedGuard ? null : damage,// Memoized adjusted surfaces for raster layers with brightness/contrast/- // saturation/curves (not recomputed per frame — see adjustedSurfaceCache).+ // saturation/curves. Memoized on the layer's cache version, so an idle+ // frame costs nothing — but a live stroke bumps that version every tick,+ // and the memo misses. What keeps that affordable is that the miss then+ // refreshes only the band the stroke reported writing, rather than+ // re-deriving from the whole layer (see adjustedSurfaceCache).adjustedSurface: deps.getAdjustedSurface,// The raster backend + mask fill tile resolver drive the mask colorize// path (alpha stencil → source-in fill colour/pattern, above all layers).diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 9ec8b68246..b825149645 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -441,7 +441,10 @@ const drawCachedLayer = (ctx.drawImage(effect.canvas, origin.x, origin.y);} else {// Raster layers may carry non-destructive adjustments; the engine supplies a- // memoized adjusted surface (never recomputed per frame). Fall back to the raw+ // memoized adjusted surface. The memo is keyed on the layer's cache version,+ // so it holds across idle frames but is deliberately missed on every tick of+ // a live stroke — that is what makes the stroke visible through the+ // adjustments. The miss refreshes only the written band. Fall back to the raw// cache when there are no adjustments or no provider.const adjusted = layer.type === 'raster' && opts.adjustedSurface ? opts.adjustedSurface(layer, entry) : null;ctx.drawImage((adjusted ?? entry.surface).canvas, origin.x, origin.y);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.tsindex 70c36b1517..fbeb5fbba3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/derivedSurfaceCache.ts@@ -10,7 +10,16 @@ export interface DerivedSurfaceRequest {kind: DerivedSurfaceKind;paramsKey: string;source: RasterSurface;- create(target: RasterSurface | null): RasterSurface;+ /**+ * Builds the derived surface.+ *+ * `target` is the previous surface when it can be reused (same source), else+ * `null`. `reusableFromVersion` is the source version `target` was built at,+ * or `null` when there is nothing to refresh from — which is the signal that+ * the build must be wholesale. Given both, an implementation may ask the+ * layer cache what changed since that version and refresh only that region.+ */+ create(target: RasterSurface | null, reusableFromVersion: number | null): RasterSurface;}export interface DerivedSurfaceCache {@@ -58,7 +67,11 @@ export const createDerivedSurfaceCache = (diagnostics?: CanvasDiagnostics): Deridiagnostics?.increment('derivedCacheMisses');const canReuse = existing?.source === request.source;- const surface = request.create(canReuse ? existing.surface : null);+ // Only a reusable surface built with the SAME parameters can be refreshed in+ // part; different parameters mean every pixel is wrong, not just the changed+ // ones.+ const reusableFromVersion = canReuse && existing.paramsKey === request.paramsKey ? existing.sourceVersion : null;+ const surface = request.create(canReuse ? existing.surface : null, reusableFromVersion);if (!canReuse) {diagnostics?.add('allocatedDerivedBytes', surfaceBytes(surface));}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.tsindex 9f15ec753e..12e6605b18 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts@@ -302,3 +302,76 @@ describe('growToRect (paint caches grow with strokes)', () => {expect(log.some((e) => e.op === 'putImageData')).toBe(false);});});++describe('damageSince', () => {+ const seeded = () => {+ const store = createLayerCacheStore(createTestStubRasterBackend());+ store.getOrCreate('a', 100, 100);+ return store;+ };+ const rect = (x: number, y: number, size = 10) => ({ height: size, width: size, x, y });++ it('unions the regions written since a version', () => {+ const store = seeded();+ const base = store.version('a');+ store.publishPixels('a', rect(10, 10));+ store.publishPixels('a', rect(50, 40));+ expect(store.damageSince('a', base)).toEqual({ height: 40, width: 50, x: 10, y: 10 });+ });++ it('reports only what changed after the asked-for version', () => {+ const store = seeded();+ store.publishPixels('a', rect(10, 10));+ const mid = store.version('a');+ store.publishPixels('a', rect(60, 60));+ expect(store.damageSince('a', mid)).toEqual(rect(60, 60));+ });++ it('gives up when any write in the span did not name its damage', () => {+ // Skipping such a write would refresh a stale surface only where the OTHER+ // writes landed, silently leaving the unreported region wrong.+ const store = seeded();+ const base = store.version('a');+ store.publishPixels('a', rect(10, 10));+ store.publishPixels('a', null);+ store.publishPixels('a', rect(60, 60));+ expect(store.damageSince('a', base)).toBeNull();+ });++ it('gives up when the trail no longer reaches back to the version', () => {+ const store = seeded();+ const base = store.version('a');+ for (let i = 0; i < 40; i++) {+ store.publishPixels('a', rect(i, i, 5));+ }+ expect(store.damageSince('a', base)).toBeNull();+ // ...but a recent version is still answerable.+ const recent = store.version('a') - 2;+ expect(store.damageSince('a', recent)).not.toBeNull();+ });++ it('gives up after a reallocation moves the surface origin', () => {+ const store = seeded();+ store.publishPixels('a', rect(10, 10));+ const before = store.version('a');+ store.growToRect('a', { height: 200, width: 200, x: -50, y: -50 });+ store.publishPixels('a', rect(0, 0));+ expect(store.damageSince('a', before)).toBeNull();+ });++ it('gives up after an invalidate', () => {+ const store = seeded();+ store.publishPixels('a', rect(10, 10));+ const before = store.version('a');+ store.invalidate('a');+ store.publishPixels('a', rect(20, 20));+ expect(store.damageSince('a', before)).toBeNull();+ });++ it('returns null for an unknown layer or an already-current version', () => {+ const store = seeded();+ store.publishPixels('a', rect(10, 10));+ expect(store.damageSince('missing', 0)).toBeNull();+ expect(store.damageSince('a', store.version('a'))).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.tsindex fa15e7599c..66dedaded3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts@@ -14,12 +14,30 @@import type { Rect } from '@workbench/canvas-engine/types';+import { union } from '@workbench/canvas-engine/math/rect';+import type { RasterBackend, RasterSurface } from './raster';/** Default cache budget: ~512 MB of surface pixels before hidden caches are evicted. */export const DEFAULT_CACHE_BUDGET_BYTES = 512 * 1024 * 1024;const BYTES_PER_PIXEL = 4;++/**+ * How many recent writes a layer's damage trail retains.+ *+ * A derived surface asks what changed since the version it was built at, so the+ * trail only has to span the gap between two composites — normally one write.+ * The cap keeps a long stroke from growing the trail without bound; overrunning+ * it just means derived surfaces rebuild wholesale, which is the old behaviour.+ */+const DAMAGE_TRAIL_LIMIT = 16;++/** One recorded write: the version it produced, and where it landed (`null` = everywhere). */+interface DamageStep {+ version: number;+ rect: Rect | null;+}const READBACK_SURFACE_OPTIONS = { willReadFrequently: true } as const;/** A single layer's cache entry. */@@ -96,8 +114,23 @@ export interface LayerCacheStore {prepareReplacement(layerId: string, rect: Rect, pixels: RasterSurface): PreparedLayerCacheReplacement;/** Publishes a detached replacement without allocating, resizing, or drawing. */installReplacement(prepared: PreparedLayerCacheReplacement): LayerCacheEntry;- /** Marks directly-written pixels current, bumps the version, and notifies observers. */- publishPixels(layerId: string): LayerCacheEntry | undefined;+ /**+ * Marks directly-written pixels current, bumps the version, and notifies+ * observers.+ *+ * `damage` is the surface-local rect the write touched. Supplying it lets+ * surfaces DERIVED from this cache (adjusted, mask-fill) refresh just that+ * rect instead of rebuilding wholesale — see {@link damageSince}. Omitting it+ * declares the whole surface changed, which is always safe.+ */+ publishPixels(layerId: string, damage?: Rect | null): LayerCacheEntry | undefined;+ /**+ * The union of the regions written to `layerId` since `version`, or `null` if+ * that cannot be established — because some write did not name its damage,+ * because the trail is older than the retained window, or because the surface+ * was reallocated. `null` means "assume everything changed".+ */+ damageSince(layerId: string, version: number): Rect | null;/** Marks a layer's cache stale and bumps its `version`. */invalidate(layerId: string): void;/** Drops a layer's cache entry entirely. */@@ -124,6 +157,22 @@ export const createLayerCacheStore = (options: LayerCacheStoreOptions = {}): LayerCacheStore => {const entries = new Map<string, LayerCacheEntry>();+ /** Per-layer trail of recent writes, oldest first. See {@link DAMAGE_TRAIL_LIMIT}. */+ const damageTrails = new Map<string, DamageStep[]>();++ /**+ * Appends a write to a layer's damage trail. A `null` rect is recorded rather+ * than dropped: it is what tells {@link damageSince} that a write of unknown+ * extent happened, so a derived surface spanning it must rebuild in full.+ */+ const recordDamage = (entry: LayerCacheEntry, rect: Rect | null): void => {+ const trail = damageTrails.get(entry.layerId) ?? [];+ trail.push({ rect, version: entry.version });+ if (trail.length > DAMAGE_TRAIL_LIMIT) {+ trail.splice(0, trail.length - DAMAGE_TRAIL_LIMIT);+ }+ damageTrails.set(entry.layerId, trail);+ };// Per-id version FLOOR: the highest version each layer id has ever reached,// retained across delete/recreate (delete, LRU eviction). A recreated entry// (undo→redo, transform bake, merge, evict→re-show) starts ABOVE this floor@@ -181,6 +230,7 @@ export const createLayerCacheStore = (const hadPublishedPixels = existing.hasPublishedPixels;if (existing.surface.width !== width || existing.surface.height !== height) {existing.surface.resize(width, height);+ damageTrails.delete(layerId);existing.hasPublishedPixels = false;existing.stale = true;}@@ -276,6 +326,10 @@ export const createLayerCacheStore = (if (!curEmpty && cur.width > 0 && cur.height > 0) {snapshot = surface.ctx.getImageData(0, 0, cur.width, cur.height);}+ // The surface origin moves with the grown rect, so every surface-local rect+ // recorded so far is void. Dropping the trail makes derived surfaces rebuild+ // wholesale for one frame rather than refresh the wrong pixels.+ damageTrails.delete(layerId);surface.resize(newRect.width, newRect.height);if (snapshot) {surface.ctx.putImageData(snapshot, cur.x - newRect.x, cur.y - newRect.y);@@ -321,12 +375,13 @@ export const createLayerCacheStore = (version: initialVersion(prepared.layerId) + 1,};touch(entry);+ damageTrails.delete(prepared.layerId);entries.set(prepared.layerId, entry);notifyVersionChange(prepared.layerId);return entry;};- const publishPixels = (layerId: string): LayerCacheEntry | undefined => {+ const publishPixels = (layerId: string, damage?: Rect | null): LayerCacheEntry | undefined => {const entry = entries.get(layerId);if (!entry) {return undefined;@@ -334,13 +389,39 @@ export const createLayerCacheStore = (entry.hasPublishedPixels = true;entry.stale = false;entry.version += 1;+ recordDamage(entry, damage ?? null);notifyVersionChange(layerId);return entry;};+ const damageSince = (layerId: string, version: number): Rect | null => {+ const entry = entries.get(layerId);+ if (!entry || version >= entry.version) {+ return null;+ }+ const trail = damageTrails.get(layerId);+ // The trail must reach back far enough to account for EVERY version since+ // the caller's: a gap means an unrecorded write, so nothing can be assumed.+ if (!trail || trail.length === 0 || trail[0]!.version > version + 1) {+ return null;+ }+ let accumulated: Rect | null = null;+ for (const step of trail) {+ if (step.version <= version) {+ continue;+ }+ if (!step.rect) {+ return null;+ }+ accumulated = accumulated ? union(accumulated, step.rect) : step.rect;+ }+ return accumulated;+ };+const invalidate = (layerId: string): void => {const entry = entries.get(layerId);if (entry) {+ damageTrails.delete(layerId);entry.version += 1;entry.stale = true;notifyVersionChange(layerId);@@ -352,6 +433,7 @@ export const createLayerCacheStore = (if (entry) {rememberFloor(entry);entries.delete(layerId);+ damageTrails.delete(layerId);notifyVersionChange(layerId);}};@@ -386,6 +468,7 @@ export const createLayerCacheStore = (// thumbnail caches would serve stale pixels keyed to the recycled version.rememberFloor(entry);entries.delete(entry.layerId);+ damageTrails.delete(entry.layerId);evicted.push(entry.layerId);total -= surfaceBytes(entry.surface);notifyVersionChange(entry.layerId);@@ -395,6 +478,7 @@ export const createLayerCacheStore = (const dispose = (): void => {entries.clear();+ damageTrails.clear();};return {@@ -407,6 +491,7 @@ export const createLayerCacheStore = (getOrCreateRect,growToRect,installReplacement,+ damageSince,invalidate,peek,prepareReplacement,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 8e76fa53f5..43a3a700c3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -453,14 +453,23 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessiontargetCtx.drawImage(scratch.canvas, region.x - ox, region.y - oy);targetCtx.restore();- // The cache pixels changed THIS frame — bump the version so a version-keyed- // dependent (the memoized adjusted-surface cache) recomputes over the live- // stroke. Without this the compositor would keep serving the pre-stroke+ // The cache pixels changed THIS frame — bump the version, WITH the band they+ // changed in, so a version-keyed dependent (the memoized adjusted-surface+ // cache) recomputes over the live stroke without rebuilding from the whole+ // layer. Without the bump the compositor would keep serving the pre-stroke// adjusted surface, and the live stroke would be invisible on an adjusted- // raster layer until pointer-up (and jump on rect growth). This does NOT+ // raster layer until pointer-up (and jump on rect growth). The band is in+ // SURFACE-local coordinates, the space a derived surface is built in. Note+ // it is the derived surfaces that need this — the stroke's own scratch and+ // cache writes are already bounded above. This does NOT// touch `thumbnailVersion` (only `notifyLayerPainted`/rasterize do), so// thumbnails don't churn mid-stroke.- layers.publishPixels(layerId);+ layers.publishPixels(layerId, {+ height: changed.height,+ width: changed.width,+ x: changed.x - ox,+ y: changed.y - oy,+ });// Report the region as damage so the frame repaints only these pixels// instead of re-resampling every doc-sized layer to screen scale — the cost// that grows with zoom. `region` is layer-local, which is exactly what the@@ -483,7 +492,14 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// Bump the version so the adjusted-surface memo (which recomputed over the// live stroke) re-derives from the RESTORED pixels — otherwise an adjusted// raster layer would keep showing the cancelled stroke's adjusted preview.- layers.publishPixels(layerId);+ // The restore spans everything the gesture touched, so this reports the+ // whole accumulated rect rather than any one frame's band.+ layers.publishPixels(layerId, {+ height: accumRect.height,+ width: accumRect.width,+ x: accumRect.x - entry.rect.x,+ y: accumRect.y - entry.rect.y,+ });ctx.invalidate({ layers: [layerId] });}},