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.

perf(canvas): derive the index and answer eligibility without materializing edits

Josh Corbetta68b8401da00
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts
index 99cf0c7f49..7ca1415e51 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts
@@ -3,8 +3,9 @@ import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationCon
import type { Project } from '@workbench/projectContracts';
import { createDocumentModel, type CanvasDocumentModel } from '@workbench/canvas-engine/document-model/documentModel';
-import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
+import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
+import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';
import { createHistory } from '@workbench/canvas-engine/history/history';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
@@ -322,3 +323,64 @@ describe('StructuralLayerController', () => {
expect(controller.nudge(1, 0)).toEqual({ status: 'dispatch-rejected' });
});
});
+
+describe('hierarchy recovery', () => {
+ it('reverts a reparent whose postconditions fail and leaves the tree, selection and history untouched', () => {
+ const { controller, ctx, document, history, projectId } = createHarness();
+ const inner = createEmptyPaintLayer('Inner', 'inner');
+ const group = {
+ children: [inner],
+ id: 'g',
+ isEnabled: true,
+ isLocked: false,
+ name: 'Group',
+ type: 'group' as const,
+ };
+ ctx.dispatch(
+ {
+ add: [{ anchor: stackTopAnchor(projectId), nodes: [group] }],
+ enabledUpdates: [],
+ type: 'applyCanvasLayerStackMutation',
+ },
+ 'system'
+ );
+ const before = document();
+ const parentOf = (id: string) => getDocumentIndex(document()).byId.get(id)?.parentId;
+ expect(parentOf('layer')).toBeNull();
+
+ const model = createDocumentModel(before, { editRevision: ctx.getEditRevision(), projectId });
+ const result = model.prepare({ beforeId: null, ids: ['layer'], parentId: 'g', type: 'reparent' });
+ if (result.status !== 'prepared') {
+ throw new Error(result.status);
+ }
+ // Fault injection: the edit lands but claims an order the reducer did not produce.
+ const tampered = {
+ ...result.edit,
+ postconditions: [
+ { kind: 'sibling-order' as const, orderedIds: ['layer', 'inner'], parentId: 'g', stack: 'raster' as const },
+ ],
+ };
+ expect(controller.commitPrepared('Reparent', tampered)).toEqual({
+ recovered: 'reverted',
+ status: 'postcondition-failed',
+ });
+ expect(haveSameStructure(document().stacks, before.stacks)).toBe(true);
+ expect(document().selectedLayerId).toBe(before.selectedLayerId);
+ expect(history.canUndo()).toBe(false);
+
+ // Prepared afresh against the reverted document, the same edit lands and undoes exactly.
+ const fresh = createDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }).prepare({
+ beforeId: null,
+ ids: ['layer'],
+ parentId: 'g',
+ type: 'reparent',
+ });
+ if (fresh.status !== 'prepared') {
+ throw new Error(fresh.status);
+ }
+ expect(controller.commitPrepared('Reparent', fresh.edit)).toEqual({ status: 'committed' });
+ expect(parentOf('layer')).toBe('g');
+ history.undo();
+ expect(haveSameStructure(document().stacks, before.stacks)).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
index 664f2656e8..2770654fdc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
@@ -4,6 +4,8 @@ import {
getDocumentIndex,
getDocumentIndexBuildCount,
getDocumentIndexDerivationCount,
+ getDocumentIndexMaterializationCount,
+ getDocumentIndexVisitCount,
resetDocumentIndexBuildCount,
} from '@workbench/canvas-engine/document/documentIndex';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
@@ -17,6 +19,8 @@ import {
compileDocumentLeaves,
compileDocumentNodes,
createDocumentModel,
+ lookupDocumentLeaf,
+ lookupDocumentNodeState,
getDocumentModelDiagnostics,
resetDocumentModelDiagnostics,
} from './documentModel';
@@ -32,8 +36,10 @@ const resetCounters = (): void => {
const counters = () => ({
...getDocumentModelDiagnostics(),
+ entriesVisited: getDocumentIndexVisitCount(),
indexBuilds: getDocumentIndexBuildCount(),
indexDerivations: getDocumentIndexDerivationCount(),
+ nodesMaterialized: getDocumentIndexMaterializationCount(),
});
/** Runs the reducer over a fixture so the next document is the one production consumers see. */
@@ -273,3 +279,110 @@ describe(`value edits over ${NODE_COUNT} nodes`, () => {
expect(counters()).toMatchObject({ indexBuilds: 0, indexDerivations: 0, leavesCompiled: 0 });
});
});
+
+describe('value edits at the 10,000-node limit', () => {
+ const LIMIT_COUNT = 10_000;
+ beforeEach(resetCounters);
+
+ it('costs one entry per changed path, and nothing else, per value edit', () => {
+ const fixture = createLargeTreeDocument(LIMIT_COUNT);
+ const initial = createInitialWorkbenchState().projects[0]!;
+ const project = applyCanvasProjectMutation(initial, { document: fixture, type: 'replaceCanvasDocument' });
+ const before = project.canvas.document;
+ compileDocumentNodes(before);
+ compileDocumentLeaves(before);
+ lookupDocumentLeaf(before, 'l5');
+ const depth = getDocumentIndex(before).byId.get('l5')!.path.length;
+ resetCounters();
+
+ const next = applyCanvasProjectMutation(project, {
+ id: 'l5',
+ patch: { transform: { x: 40 } },
+ type: 'updateCanvasLayer',
+ }).canvas.document;
+ expect(counters()).toMatchObject({ entriesVisited: depth + 1, indexBuilds: 0, indexDerivations: 1 });
+ expect(lookupDocumentLeaf(next, 'l5')?.layer.transform.x).toBe(40);
+ expect(lookupDocumentNodeState(next, 'l5')?.node).toBe(getDocumentIndex(next).byId.get('l5')!.node);
+ expect(lookupDocumentNodeState(next, 'l6')).toBe(lookupDocumentNodeState(before, 'l6'));
+ expect(counters()).toMatchObject({ leavesCompiled: 1, nodesCompiled: depth + 1, nodesMaterialized: 0 });
+ // The ancestors compiled again kept their counts without walking their subtrees.
+ const parentId = getDocumentIndex(next).byId.get('l5')!.parentId!;
+ expect(lookupDocumentNodeState(next, parentId)?.leafCount).toBe(
+ lookupDocumentNodeState(before, parentId)?.leafCount
+ );
+ });
+
+ it('costs the subtree, and only the subtree, for a group flag flip', () => {
+ const fixture = createLargeTreeDocument(LIMIT_COUNT);
+ const initial = createInitialWorkbenchState().projects[0]!;
+ const project = applyCanvasProjectMutation(initial, { document: fixture, type: 'replaceCanvasDocument' });
+ const before = project.canvas.document;
+ const subtree = getDocumentIndex(before).nodes.filter((entry) => entry.path.includes('g0')).length;
+ compileDocumentNodes(before);
+ resetCounters();
+ const next = applyCanvasProjectMutation(project, {
+ type: 'setCanvasLayersEnabled',
+ updates: [{ id: 'g0', isEnabled: false }],
+ }).canvas.document;
+ expect(counters()).toMatchObject({ entriesVisited: subtree + 1, indexBuilds: 0, indexDerivations: 1 });
+ expect(getDocumentIndex(next).leaves).toBe(getDocumentIndex(before).leaves);
+ compileDocumentNodes(next);
+ expect(counters()).toMatchObject({ nodesCompiled: subtree + 1, nodesMaterialized: 0 });
+ });
+
+ it('flattens the derivation chain so lookups stay bounded and compiles stay incremental across many edits', () => {
+ const fixture = createLargeTreeDocument(LIMIT_COUNT);
+ const initial = createInitialWorkbenchState().projects[0]!;
+ let project = applyCanvasProjectMutation(initial, { document: fixture, type: 'replaceCanvasDocument' });
+ compileDocumentNodes(project.canvas.document);
+ resetCounters();
+ let deepest = 0;
+ let compiledMost = 0;
+ for (let step = 0; step < 20; step += 1) {
+ const id = `l${step}`;
+ const depth = getDocumentIndex(project.canvas.document).byId.get(id)!.path.length;
+ project = applyCanvasProjectMutation(project, { id, patch: { opacity: 0.5 }, type: 'updateCanvasLayer' });
+ const before = counters().nodesCompiled;
+ compileDocumentNodes(project.canvas.document);
+ compiledMost = Math.max(compiledMost, (counters().nodesCompiled - before) / (depth + 1));
+ let chain = 0;
+ for (
+ let index = getDocumentIndex(project.canvas.document);
+ index.derivedFrom;
+ index = index.derivedFrom.previous
+ ) {
+ chain += 1;
+ }
+ deepest = Math.max(deepest, chain);
+ }
+ expect(deepest).toBeLessThanOrEqual(9);
+ // The flattening step recompiles what the chain touched, never the document.
+ expect(compiledMost).toBeLessThanOrEqual(9);
+ expect(counters()).toMatchObject({ indexBuilds: 0, nodesMaterialized: 0 });
+ expect(getDocumentIndex(project.canvas.document).byId.get('l19')!.node).toMatchObject({ opacity: 0.5 });
+ expect(getDocumentIndex(project.canvas.document).byId.size).toBe(LIMIT_COUNT);
+ });
+});
+
+describe('eligibility without materialization', () => {
+ beforeEach(resetCounters);
+
+ it('answers reparent, group, ungroup and remove eligibility without building an edit', () => {
+ const document = createLargeTreeDocument(NODE_COUNT);
+ const model = createDocumentModel(document, context);
+ const index = getDocumentIndex(document);
+ const stack = index.byId.get('l0')!.stack;
+ const groupId = index.nodes.find((entry) => entry.node.type === 'group' && entry.stack === stack)!.node.id;
+ resetCounters();
+ expect(model.refusalFor({ beforeId: null, ids: ['l0'], parentId: groupId, type: 'reparent' })).toBeNull();
+ expect(model.refusalFor({ beforeId: null, ids: [groupId], parentId: groupId, type: 'reparent' })).toMatchObject({
+ reason: 'cycle',
+ });
+ expect(model.refusalFor({ groupId: '\0probe', ids: ['l0', 'l1'], name: '', type: 'group' })).toBeDefined();
+ expect(model.refusalFor({ ids: [groupId], type: 'ungroup' })).toBeNull();
+ expect(model.refusalFor({ ids: ['l0'], type: 'remove' })).toBeNull();
+ expect(counters().editsMaterialized).toBe(0);
+ expect(model.prepare({ ids: ['l0'], type: 'remove' }).status).toBe('prepared');
+ expect(counters().editsMaterialized).toBe(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts
index 5f7f9dcc9a..ab6921b461 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.fuzz.test.ts
@@ -1,7 +1,7 @@
import type { CanvasDocumentContractV3, CanvasNodeContract } from '@workbench/canvas-engine/contracts';
import type { Project } from '@workbench/projectContracts';
-import { CANVAS_MAX_NODE_DEPTH, LAYER_STACK_ORDER } from '@workbench/canvas-engine/contracts';
+import { CANVAS_MAX_NODE_COUNT, CANVAS_MAX_NODE_DEPTH, LAYER_STACK_ORDER } from '@workbench/canvas-engine/contracts';
import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
import { collectSubtree, isGroupNode } from '@workbench/canvas-engine/document/documentTree';
import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';
@@ -369,3 +369,54 @@ describe('document model fuzzing', () => {
expect(refusals.insert).toBeGreaterThan(0);
});
});
+
+describe('node-count boundary', () => {
+ it('refuses every insert, duplicate and group that would pass 10,000 nodes and agrees with the reducer', () => {
+ const random = rng(7);
+ created = 0;
+ const nodes = Array.from({ length: CANVAS_MAX_NODE_COUNT - 3 }, (_, index) =>
+ layerContract(`b${index}`, index % 2 === 0 ? 'raster' : 'control')
+ );
+ let project = projectFor({ ...createEmptyCanvasDocument(), selectedLayerId: 'b0', stacks: stacksFrom(nodes) });
+ const refusals = { duplicate: 0, group: 0, insert: 0 };
+ let applied = 0;
+ for (let step = 0; step < 40; step += 1) {
+ const model = createDocumentModel(project.canvas.document, { editRevision: step, projectId: project.id });
+ const roll = random();
+ const count = 1 + Math.floor(random() * 5);
+ const command: DocumentCommand =
+ roll < 0.4
+ ? {
+ aboveId: null,
+ nodes: Array.from({ length: count }, () => layerContract(nextId(), 'raster')),
+ stack: 'raster',
+ type: 'insert',
+ }
+ : roll < 0.8
+ ? { createId: nextId, ids: Array.from({ length: count }, (_, i) => `b${i}`), type: 'duplicate' }
+ : { groupId: nextId(), ids: ['b0', 'b2'], name: 'g', type: 'group' };
+ const result = model.prepare(command);
+ const size = getDocumentIndex(project.canvas.document).byId.size;
+ const added =
+ command.type === 'insert' ? command.nodes.length : command.type === 'duplicate' ? command.ids.length : 1;
+ if (size + added > CANVAS_MAX_NODE_COUNT) {
+ expect(result).toMatchObject({ reason: 'node-limit', status: 'invalid-target' });
+ refusals[command.type as keyof typeof refusals] += 1;
+ continue;
+ }
+ if (result.status !== 'prepared') {
+ continue;
+ }
+ const next = applyCanvasProjectMutation(project, result.edit.forward);
+ expect(next.canvas.document, `${command.type} was prepared but the reducer refused it`).not.toBe(
+ project.canvas.document
+ );
+ expect(getDocumentIndex(next.canvas.document).byId.size).toBeLessThanOrEqual(CANVAS_MAX_NODE_COUNT);
+ project = next;
+ applied += 1;
+ }
+ expect(applied).toBeGreaterThan(0);
+ expect(refusals.insert + refusals.duplicate + refusals.group).toBeGreaterThan(10);
+ expect(getDocumentIndex(project.canvas.document).byId.size).toBe(CANVAS_MAX_NODE_COUNT);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
index 9c44a92788..30159d478c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
@@ -91,14 +91,17 @@ export interface DocumentModelDiagnostics {
readonly leavesCompiled: number;
/** Semantic nodes built rather than reused across compilations. */
readonly nodesCompiled: number;
+ /** Prepared edits built with their inverse and postconditions; eligibility checks never add one. */
+ readonly editsMaterialized: number;
}
-const diagnostics = { leafCompilations: 0, leavesCompiled: 0, nodesCompiled: 0 };
+const diagnostics = { editsMaterialized: 0, leafCompilations: 0, leavesCompiled: 0, nodesCompiled: 0 };
/** Immutable snapshot for deterministic budget tests and diagnostics. */
export const getDocumentModelDiagnostics = (): DocumentModelDiagnostics => ({ ...diagnostics });
export const resetDocumentModelDiagnostics = (): void => {
+ diagnostics.editsMaterialized = 0;
diagnostics.leafCompilations = 0;
diagnostics.leavesCompiled = 0;
diagnostics.nodesCompiled = 0;
@@ -106,16 +109,43 @@ export const resetDocumentModelDiagnostics = (): void => {
const leavesByIndex = new WeakMap<CanvasDocumentIndex, readonly SemanticLeaf[]>();
const leavesByLayer = new WeakMap<CanvasLayerContract, SemanticLeaf>();
-const leafByIdByIndex = new WeakMap<CanvasDocumentIndex, ReadonlyMap<string, SemanticLeaf>>();
+const contributingByIndex = new WeakMap<CanvasDocumentIndex, readonly CanvasLayerContract[]>();
const nodesByIndex = new WeakMap<CanvasDocumentIndex, readonly SemanticNode[]>();
const nodeByContract = new WeakMap<CanvasNodeContract, SemanticNode>();
-const nodeByIdByIndex = new WeakMap<CanvasDocumentIndex, ReadonlyMap<string, SemanticNode>>();
+/** Leaf id → position in `index.leaves`; a derived index shares its previous index's map. */
+const leafPositionsByIndex = new WeakMap<CanvasDocumentIndex, ReadonlyMap<string, number>>();
+
+const leafPositions = (index: CanvasDocumentIndex): ReadonlyMap<string, number> => {
+ const cached = leafPositionsByIndex.get(index);
+ if (cached) {
+ return cached;
+ }
+ const positions = index.derivedFrom
+ ? leafPositions(index.derivedFrom.previous)
+ : new Map(index.leaves.map((leaf, position) => [leaf.id, position]));
+ leafPositionsByIndex.set(index, positions);
+ return positions;
+};
const compileNodes = (index: CanvasDocumentIndex): readonly SemanticNode[] => {
const cached = nodesByIndex.get(index);
if (cached) {
return cached;
}
+ // After a value edit only the replaced entries compile; every other node is the previous one.
+ const inherited = index.derivedFrom ? nodesByIndex.get(index.derivedFrom.previous) : undefined;
+ if (index.derivedFrom && inherited) {
+ const nodes = inherited.slice();
+ for (const id of index.derivedFrom.changedIds) {
+ const entry = index.byId.get(id)!;
+ diagnostics.nodesCompiled += 1;
+ const semantic = compileSemanticNode(entry, inherited[entry.order]);
+ nodeByContract.set(entry.node, semantic);
+ nodes[entry.order] = semantic;
+ }
+ nodesByIndex.set(index, nodes);
+ return nodes;
+ }
const nodes = index.nodes.map((entry) => {
const previous = nodeByContract.get(entry.node);
if (previous && isSemanticNodeCurrent(previous, entry)) {
@@ -129,7 +159,6 @@ const compileNodes = (index: CanvasDocumentIndex): readonly SemanticNode[] => {
nodesByIndex.set(index, nodes);
return nodes;
};
-const contributingByIndex = new WeakMap<CanvasDocumentIndex, readonly CanvasLayerContract[]>();
const compileLeaves = (index: CanvasDocumentIndex): readonly SemanticLeaf[] => {
const cached = leavesByIndex.get(index);
@@ -137,6 +166,24 @@ const compileLeaves = (index: CanvasDocumentIndex): readonly SemanticLeaf[] => {
return cached;
}
diagnostics.leafCompilations += 1;
+ const inherited = index.derivedFrom ? leavesByIndex.get(index.derivedFrom.previous) : undefined;
+ if (index.derivedFrom && inherited) {
+ const leaves = inherited.slice();
+ const positions = leafPositions(index);
+ for (const id of index.derivedFrom.changedIds) {
+ const position = positions.get(id);
+ if (position === undefined) {
+ continue;
+ }
+ const entry = index.byId.get(id)!;
+ diagnostics.leavesCompiled += 1;
+ const leaf = compileSemanticLeaf(entry.node as CanvasLayerContract, entry);
+ leavesByLayer.set(entry.node as CanvasLayerContract, leaf);
+ leaves[position] = leaf;
+ }
+ leavesByIndex.set(index, leaves);
+ return leaves;
+ }
const leaves: SemanticLeaf[] = [];
for (const entry of index.nodes) {
if (isGroupNode(entry.node)) {
@@ -183,12 +230,8 @@ export const lookupDocumentNodeState = (document: DocumentView, id: string): Sem
return null;
}
const index = getDocumentIndex(document);
- let byId = nodeByIdByIndex.get(index);
- if (!byId) {
- byId = new Map(compileNodes(index).map((semantic) => [semantic.id, semantic]));
- nodeByIdByIndex.set(index, byId);
- }
- return byId.get(id) ?? null;
+ const entry = index.byId.get(id);
+ return entry ? (compileNodes(index)[entry.order] ?? null) : null;
};
/** The layers of every contributing leaf, in leaf order; the same array while the forests are unchanged. */
@@ -211,12 +254,8 @@ export const lookupDocumentLeaf = (document: DocumentView, id: string): Semantic
return null;
}
const index = getDocumentIndex(document);
- let byId = leafByIdByIndex.get(index);
- if (!byId) {
- byId = new Map(compileLeaves(index).map((leaf) => [leaf.id, leaf]));
- leafByIdByIndex.set(index, byId);
- }
- return byId.get(id) ?? null;
+ const position = leafPositions(index).get(id);
+ return position === undefined ? null : (compileLeaves(index)[position] ?? null);
};
/** The sibling directly below `id` when it is a leaf; `null` at the bottom, below a group, or when absent. */
@@ -414,20 +453,23 @@ export const createDocumentModel = (
inverse: CanvasProjectMutation,
detail: Partial<Pick<PreparedDocumentEdit, 'createdIds' | 'history'>> &
Pick<PreparedDocumentEdit, 'postconditions' | 'selectionAfter' | 'touchedIds' | 'touchedStacks'>
- ): PrepareEditResult => ({
- edit: {
- createdIds: [],
- history: 'record',
- ...detail,
- expectedRevision: context.editRevision,
- forward,
- inverse,
- projectId: context.projectId,
- rasterWork: null,
- selectionBefore: selectedLayerId,
- },
- status: 'prepared',
- });
+ ): PrepareEditResult => {
+ diagnostics.editsMaterialized += 1;
+ return {
+ edit: {
+ createdIds: [],
+ history: 'record',
+ ...detail,
+ expectedRevision: context.editRevision,
+ forward,
+ inverse,
+ projectId: context.projectId,
+ rasterWork: null,
+ selectionBefore: selectedLayerId,
+ },
+ status: 'prepared',
+ };
+ };
const structural = (
mutation: Omit<Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>, 'type' | 'enabledUpdates'>
@@ -439,7 +481,7 @@ export const createDocumentModel = (
alreadyAdded: number
): DocumentRefusal | null => {
const addedNodes = added.flatMap((node) => collectSubtree(node));
- if (index.nodes.length + alreadyAdded + addedNodes.length > CANVAS_MAX_NODE_COUNT) {
+ if (index.byId.size + alreadyAdded + addedNodes.length > CANVAS_MAX_NODE_COUNT) {
return { reason: 'node-limit', status: 'invalid-target', targetId: added[0]?.id ?? '' };
}
const deepest = added.reduce((depth, node) => Math.max(depth, levelsBelow(node)), 0);
@@ -543,7 +585,10 @@ export const createDocumentModel = (
);
};
- const prepareRemove = (command: Extract<DocumentCommand, { type: 'remove' }>): PrepareEditResult => {
+ /** Everything `remove` refuses, decided without building the edit. */
+ const checkRemove = (
+ command: Extract<DocumentCommand, { type: 'remove' }>
+ ): DocumentRefusal | { outer: CanvasNodeEntry[] } => {
const ids = unique(command.ids);
if (ids.length === 0) {
return { operation: 'remove nothing', status: 'unsupported' };
@@ -557,6 +602,15 @@ export const createDocumentModel = (
if (locked.length > 0) {
return { ids: locked, status: 'locked' };
}
+ return { outer };
+ };
+
+ const prepareRemove = (command: Extract<DocumentCommand, { type: 'remove' }>): PrepareEditResult => {
+ const checked = checkRemove(command);
+ if ('status' in checked) {
+ return checked;
+ }
+ const { outer } = checked;
const removedIds = outer.flatMap((entry) => collectSubtree(entry.node).map((node) => node.id));
const removedSet = new Set(removedIds);
const remaining = { ...stacks };
@@ -740,7 +794,20 @@ export const createDocumentModel = (
return orders.length === 0 ? { status: 'unchanged' } : prepareReorder(orders, new Set(ids));
};
- const prepareReparent = (command: Extract<DocumentCommand, { type: 'reparent' }>): PrepareEditResult => {
+ interface ReparentPlacement {
+ outer: CanvasNodeEntry[];
+ parent: CanvasNodeEntry | null;
+ stack: LayerStackKind;
+ moving: Set<string>;
+ targetChildren: CanvasNodeContract[];
+ position: number;
+ orderedIds: string[];
+ }
+
+ /** Everything `reparent` refuses, and where the block would land, decided without building the edit. */
+ const checkReparent = (
+ command: Extract<DocumentCommand, { type: 'reparent' }>
+ ): DocumentRefusal | { status: 'unchanged' } | ReparentPlacement => {
const ids = unique(command.ids);
if (ids.length === 0) {
return { operation: 'reparent nothing', status: 'unsupported' };
@@ -801,6 +868,15 @@ export const createDocumentModel = (
if (sameValue(orderedIds, siblingOrderOf(stack, command.parentId).orderedIds)) {
return { status: 'unchanged' };
}
+ return { moving, orderedIds, outer, parent, position, stack, targetChildren };
+ };
+
+ const prepareReparent = (command: Extract<DocumentCommand, { type: 'reparent' }>): PrepareEditResult => {
+ const checked = checkReparent(command);
+ if ('status' in checked) {
+ return checked;
+ }
+ const { moving, orderedIds, outer, parent, position, stack, targetChildren } = checked;
const anchor: CanvasNodeInsertionAnchor = {
afterId: targetChildren[position - 1]?.id ?? null,
beforeId: targetChildren[position]?.id ?? null,
@@ -842,7 +918,10 @@ export const createDocumentModel = (
);
};
- const prepareGroup = (command: Extract<DocumentCommand, { type: 'group' }>): PrepareEditResult => {
+ /** Everything `group` refuses, decided without building the edit. */
+ const checkGroup = (
+ command: Extract<DocumentCommand, { type: 'group' }>
+ ): DocumentRefusal | { outer: CanvasNodeEntry[]; first: CanvasNodeEntry } => {
const ids = unique(command.ids);
if (ids.length === 0) {
return { operation: 'group nothing', status: 'unsupported' };
@@ -868,9 +947,18 @@ export const createDocumentModel = (
if (first.path.length + 1 + deepest > CANVAS_MAX_NODE_DEPTH) {
return { reason: 'depth-exceeded', status: 'invalid-target', targetId: first.node.id };
}
- if (index.nodes.length + 1 > CANVAS_MAX_NODE_COUNT) {
+ if (index.byId.size + 1 > CANVAS_MAX_NODE_COUNT) {
return { reason: 'node-limit', status: 'invalid-target', targetId: command.groupId };
}
+ return { first, outer };
+ };
+
+ const prepareGroup = (command: Extract<DocumentCommand, { type: 'group' }>): PrepareEditResult => {
+ const checked = checkGroup(command);
+ if ('status' in checked) {
+ return checked;
+ }
+ const { first, outer } = checked;
const group: CanvasGroupContract = {
children: [],
id: command.groupId,
@@ -919,7 +1007,10 @@ export const createDocumentModel = (
);
};
- const prepareUngroup = (command: Extract<DocumentCommand, { type: 'ungroup' }>): PrepareEditResult => {
+ /** Everything `ungroup` refuses, decided without building the edit. */
+ const checkUngroup = (
+ command: Extract<DocumentCommand, { type: 'ungroup' }>
+ ): DocumentRefusal | { groups: CanvasNodeEntry[] } => {
const ids = unique(command.ids);
if (ids.length === 0) {
return { operation: 'ungroup nothing', status: 'unsupported' };
@@ -938,6 +1029,15 @@ export const createDocumentModel = (
if (locked.length > 0) {
return { ids: locked, status: 'locked' };
}
+ return { groups };
+ };
+
+ const prepareUngroup = (command: Extract<DocumentCommand, { type: 'ungroup' }>): PrepareEditResult => {
+ const checked = checkUngroup(command);
+ if ('status' in checked) {
+ return checked;
+ }
+ const { groups } = checked;
const forward: CanvasNodeMove[] = [];
const inverseAdd: CanvasNodeInsertion[] = [];
const inverseMove: CanvasNodeMove[] = [];
@@ -1362,6 +1462,20 @@ export const createDocumentModel = (
}
},
refusalFor: (command) => {
+ // The hot paths (drag hover, toolbar enablement) validate without materializing an edit.
+ const checked =
+ command.type === 'reparent'
+ ? checkReparent(command)
+ : command.type === 'group'
+ ? checkGroup(command)
+ : command.type === 'ungroup'
+ ? checkUngroup(command)
+ : command.type === 'remove'
+ ? checkRemove(command)
+ : null;
+ if (checked) {
+ return 'status' in checked && checked.status !== 'unchanged' ? (checked as DocumentRefusal) : null;
+ }
const result = model.prepare(command);
return result.status === 'prepared' || result.status === 'unchanged' ? null : result;
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts
index be6b0fb2d1..3d8dd07a35 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/semanticNode.ts
@@ -35,9 +35,14 @@ export interface SemanticNode {
readonly subtreeDepth: number;
}
-export const compileSemanticNode = (entry: CanvasNodeEntry): SemanticNode => {
+/**
+ * Compiles the node for `entry`. `previous` is the node compiled for the same id before a value
+ * edit: structure is unchanged then, so its counts and depth carry over instead of a subtree walk.
+ */
+export const compileSemanticNode = (entry: CanvasNodeEntry, previous?: SemanticNode): SemanticNode => {
const { node } = entry;
const group = isGroupNode(node);
+ const reuse = previous && previous.id === node.id && (previous.kind === 'group') === group ? previous : null;
return {
ancestorsEnabled: entry.ancestorsEnabled,
ancestorsHidden: entry.ancestorsHidden,
@@ -49,13 +54,13 @@ export const compileSemanticNode = (entry: CanvasNodeEntry): SemanticNode => {
effectiveLocked: entry.ancestorsLocked || node.isLocked,
id: node.id,
kind: group ? 'group' : 'leaf',
- leafCount: group ? collectSubtreeLeaves(node).length : 1,
+ leafCount: reuse ? reuse.leafCount : group ? collectSubtreeLeaves(node).length : 1,
node,
parentId: entry.parentId,
parentIds: entry.path,
siblingIndex: entry.siblingIndex,
stack: entry.stack,
- subtreeDepth: group ? Math.max(1, subtreeDepth(node)) : 0,
+ subtreeDepth: reuse ? reuse.subtreeDepth : group ? Math.max(1, subtreeDepth(node)) : 0,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts
index 21a04f7e8e..fce65b8b97 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentIndex.ts
@@ -9,7 +9,7 @@ import type {
import { LAYER_STACKS_TOP_FIRST } from '@workbench/canvas-engine/contracts';
-import { isGroupNode } from './documentTree';
+import { collectSubtree, isGroupNode } from './documentTree';
/** Document facts about one node's place in its forest. */
export interface CanvasNodeEntry {
@@ -34,23 +34,186 @@ export interface CanvasNodeEntry {
export interface CanvasDocumentIndex {
readonly stacks: CanvasStackForests;
readonly byId: ReadonlyMap<string, CanvasNodeEntry>;
- /** Every node, stacks top first, each in preorder. */
+ /** Every node, stacks top first, each in preorder. A derived index materializes this on first read. */
readonly nodes: readonly CanvasNodeEntry[];
/** Every leaf, in the same order. */
readonly leaves: readonly CanvasLayerContract[];
readonly maxDepth: number;
+ /** Set on an index derived from a value edit: the index it extends and the ids whose entries changed. */
+ readonly derivedFrom?: { readonly previous: CanvasDocumentIndex; readonly changedIds: ReadonlySet<string> };
}
-const diagnostics = { indexBuilds: 0, indexDerivations: 0 };
+const diagnostics = { entriesVisited: 0, indexBuilds: 0, indexDerivations: 0, nodesMaterialized: 0 };
export const getDocumentIndexBuildCount = (): number => diagnostics.indexBuilds;
/** Indexes derived from a previous one after a value edit, without walking the forests. */
export const getDocumentIndexDerivationCount = (): number => diagnostics.indexDerivations;
+/** Entries constructed, by a build or a derivation: the work an edit actually costs. */
+export const getDocumentIndexVisitCount = (): number => diagnostics.entriesVisited;
+
+/** Times a derived index had to materialize its full `nodes` array for a consumer. */
+export const getDocumentIndexMaterializationCount = (): number => diagnostics.nodesMaterialized;
+
export const resetDocumentIndexBuildCount = (): void => {
+ diagnostics.entriesVisited = 0;
diagnostics.indexBuilds = 0;
diagnostics.indexDerivations = 0;
+ diagnostics.nodesMaterialized = 0;
+};
+
+/** How many derivations may chain before the next one flattens onto the plain root. */
+const MAX_DERIVATION_DEPTH = 8;
+/** Overrides may cover this fraction of the root before flattening rebuilds a plain index instead. */
+const MAX_OVERRIDE_RATIO = 0.25;
+
+/**
+ * A map that reads through to the previous index's map for every entry a value edit did not touch.
+ * Lookups cost one extra step per derivation; iteration substitutes overrides on the fly.
+ */
+class LayeredEntryMap implements ReadonlyMap<string, CanvasNodeEntry> {
+ readonly [Symbol.toStringTag] = 'LayeredEntryMap';
+
+ constructor(
+ private readonly base: ReadonlyMap<string, CanvasNodeEntry>,
+ private readonly overrides: ReadonlyMap<string, CanvasNodeEntry>
+ ) {}
+
+ get size(): number {
+ return this.base.size;
+ }
+
+ get(key: string): CanvasNodeEntry | undefined {
+ return this.overrides.get(key) ?? this.base.get(key);
+ }
+
+ has(key: string): boolean {
+ return this.base.has(key);
+ }
+
+ forEach(
+ callback: (value: CanvasNodeEntry, key: string, map: ReadonlyMap<string, CanvasNodeEntry>) => void,
+ thisArg?: unknown
+ ): void {
+ for (const [key, value] of this) {
+ callback.call(thisArg, value, key, this);
+ }
+ }
+
+ *entries(): MapIterator<[string, CanvasNodeEntry]> {
+ for (const [key, value] of this.base) {
+ yield [key, this.overrides.get(key) ?? value];
+ }
+ }
+
+ keys(): MapIterator<string> {
+ return this.base.keys();
+ }
+
+ *values(): MapIterator<CanvasNodeEntry> {
+ for (const [, value] of this) {
+ yield value;
+ }
+ }
+
+ [Symbol.iterator](): MapIterator<[string, CanvasNodeEntry]> {
+ return this.entries();
+ }
+}
+
+/**
+ * An index that extends a source index by the entries a value edit replaced; the rest reads through.
+ * Chains read through their predecessors; every ninth derivation flattens onto the plain root so
+ * lookups stay bounded and nothing older than the root is retained.
+ */
+class DerivedIndex implements CanvasDocumentIndex {
+ readonly byId: ReadonlyMap<string, CanvasNodeEntry>;
+ readonly derivedFrom: { readonly previous: CanvasDocumentIndex; readonly changedIds: ReadonlySet<string> };
+ readonly maxDepth: number;
+ private nodesCache: readonly CanvasNodeEntry[] | null = null;
+ private leavesCache: readonly CanvasLayerContract[] | null = null;
+
+ constructor(
+ readonly stacks: CanvasStackForests,
+ private readonly source: CanvasDocumentIndex,
+ readonly overrides: ReadonlyMap<string, CanvasNodeEntry>,
+ readonly leafChanged: boolean
+ ) {
+ this.byId = new LayeredEntryMap(source.byId, overrides);
+ this.derivedFrom = { changedIds: new Set(overrides.keys()), previous: source };
+ this.maxDepth = source.maxDepth;
+ }
+
+ get nodes(): readonly CanvasNodeEntry[] {
+ if (this.nodesCache === null) {
+ diagnostics.nodesMaterialized += 1;
+ this.nodesCache = this.patchedNodes();
+ }
+ return this.nodesCache;
+ }
+
+ /** The same content as a plain index; building it is part of flattening, not a consumer read. */
+ plain(): CanvasDocumentIndex {
+ return {
+ byId: new Map(this.byId),
+ leaves: this.leaves,
+ maxDepth: this.maxDepth,
+ nodes: this.nodesCache ?? this.patchedNodes(),
+ stacks: this.stacks,
+ };
+ }
+
+ private patchedNodes(): readonly CanvasNodeEntry[] {
+ const nodes = this.source.nodes.slice();
+ for (const entry of this.overrides.values()) {
+ nodes[entry.order] = entry;
+ }
+ return nodes;
+ }
+
+ get leaves(): readonly CanvasLayerContract[] {
+ if (!this.leafChanged) {
+ return this.source.leaves;
+ }
+ if (this.leavesCache === null) {
+ this.leavesCache = this.source.leaves.map(
+ (leaf) => (this.overrides.get(leaf.id)?.node as CanvasLayerContract | undefined) ?? leaf
+ );
+ }
+ return this.leavesCache;
+ }
+}
+
+const derivationDepth = (index: CanvasDocumentIndex): number => {
+ let depth = 0;
+ let current: CanvasDocumentIndex | undefined = index;
+ while (current?.derivedFrom) {
+ depth += 1;
+ current = current.derivedFrom.previous;
+ }
+ return depth;
+};
+
+/**
+ * Folds a chain onto its plain root: one override layer holding the newest entry of every id the
+ * chain touched. Once overrides cover too much of the root, a plain index is cheaper than the layer.
+ */
+const flatten = (index: DerivedIndex): CanvasDocumentIndex => {
+ const overrides = new Map<string, CanvasNodeEntry>();
+ let leafChanged = false;
+ let current: CanvasDocumentIndex = index;
+ while (current instanceof DerivedIndex) {
+ for (const [id, entry] of current.overrides) {
+ if (!overrides.has(id)) {
+ overrides.set(id, entry);
+ }
+ }
+ leafChanged ||= current.leafChanged;
+ current = current.derivedFrom.previous;
+ }
+ const flat = new DerivedIndex(index.stacks, current, overrides, leafChanged);
+ return overrides.size <= current.byId.size * MAX_OVERRIDE_RATIO ? flat : flat.plain();
};
type DocumentView = Pick<CanvasDocumentContractV3, 'stacks'> | null | undefined;
@@ -76,6 +239,7 @@ const build = (stacks: CanvasStackForests): CanvasDocumentIndex => {
): void => {
maxDepth = Math.max(maxDepth, path.length);
children.forEach((node, siblingIndex) => {
+ diagnostics.entriesVisited += 1;
const entry: CanvasNodeEntry = {
ancestorsEnabled,
ancestorsHidden,
@@ -120,10 +284,10 @@ const flagsChanged = (previous: CanvasNodeContract, next: CanvasNodeContract): b
/**
* Registers the index of `nextStacks` as a derivation of `previousStacks`' index after a value edit
* that rewrote exactly the nodes in `changed` (and, through structural sharing, their ancestors).
- * Structure is untouched, so every entry keeps its place and every unaffected entry, and the leaves
- * array when no leaf changed, keep their identity; only a group whose flags changed re-derives the
- * ancestor-effective flags of its subtree. Returns `null` when no previous index exists or the edit
- * was not a value edit, leaving the next lookup to build from scratch.
+ * Structure is untouched, so every entry keeps its place; only the replaced nodes, their ancestors,
+ * and the subtree under a group whose flags changed get new entries. Everything else reads through
+ * to the previous index, so the cost is the changed paths, never the document. Returns `null` when
+ * no previous index exists or the edit was not a value edit, leaving the next lookup to build.
*/
export const deriveIndexForValueEdit = (
previousStacks: CanvasStackForests,
@@ -138,16 +302,16 @@ export const deriveIndexForValueEdit = (
if (!previous || previousStacks === nextStacks) {
return null;
}
- const replaced = new Map<string, CanvasNodeContract>();
- const reflagged = new Set<string>();
+ const replacedNodes = new Map<string, CanvasNodeContract>();
+ const reflagged: CanvasGroupContract[] = [];
for (const [id, node] of changed) {
const entry = previous.byId.get(id);
if (!entry || entry.node.id !== node.id || isGroupNode(entry.node) !== isGroupNode(node)) {
return null;
}
- replaced.set(id, node);
- if (flagsChanged(entry.node, node)) {
- reflagged.add(id);
+ replacedNodes.set(id, node);
+ if (flagsChanged(entry.node, node) && isGroupNode(node)) {
+ reflagged.push(node);
}
}
// Ancestors were rebuilt along each changed path; find their new objects from the new roots.
@@ -155,49 +319,54 @@ export const deriveIndexForValueEdit = (
const entry = previous.byId.get(id)!;
let siblings: readonly CanvasNodeContract[] = nextStacks[entry.stack];
for (const ancestorId of entry.path) {
- const known = replaced.get(ancestorId);
+ const known = replacedNodes.get(ancestorId);
const ancestor = known ?? siblings.find((node) => node.id === ancestorId);
if (!ancestor || !isGroupNode(ancestor)) {
return null;
}
- replaced.set(ancestorId, ancestor);
+ replacedNodes.set(ancestorId, ancestor);
siblings = ancestor.children;
}
}
diagnostics.indexDerivations += 1;
- const nodeOf = (id: string): CanvasNodeContract => replaced.get(id) ?? previous.byId.get(id)!.node;
+ const nodeOf = (id: string): CanvasNodeContract => replacedNodes.get(id) ?? previous.byId.get(id)!.node;
+ const replaced = new Map<string, CanvasNodeEntry>();
let leafChanged = false;
- const nodes = previous.nodes.map((entry) => {
- const node = replaced.get(entry.node.id);
- const underReflagged = reflagged.size > 0 && entry.path.some((ancestorId) => reflagged.has(ancestorId));
- if (!node && !underReflagged) {
- return entry;
- }
- if (node && !isGroupNode(node)) {
+ const replaceEntry = (id: string, node: CanvasNodeContract, reflag: boolean): void => {
+ const entry = previous.byId.get(id)!;
+ diagnostics.entriesVisited += 1;
+ if (node !== entry.node && !isGroupNode(node)) {
leafChanged = true;
}
- const ancestors = underReflagged ? entry.path.map(nodeOf) : null;
- return {
+ const ancestors = reflag ? entry.path.map(nodeOf) : null;
+ replaced.set(id, {
...entry,
ancestorsEnabled: ancestors ? ancestors.every((ancestor) => ancestor.isEnabled) : entry.ancestorsEnabled,
ancestorsHidden: ancestors
? ancestors.some((ancestor) => isGroupNode(ancestor) && ancestor.isHidden === true)
: entry.ancestorsHidden,
ancestorsLocked: ancestors ? ancestors.some((ancestor) => ancestor.isLocked) : entry.ancestorsLocked,
- node: node ?? entry.node,
- };
- });
- const derived: CanvasDocumentIndex = {
- byId: new Map(nodes.map((entry) => [entry.node.id, entry])),
- leaves: leafChanged
- ? previous.leaves.map((leaf) => (replaced.get(leaf.id) as CanvasLayerContract | undefined) ?? leaf)
- : previous.leaves,
- maxDepth: previous.maxDepth,
- nodes,
- stacks: nextStacks,
+ node,
+ });
};
- indexes.set(nextStacks, derived);
- return derived;
+ // Only the subtree under a group whose flags changed re-derives its ancestor-effective flags;
+ // a replaced node inside such a subtree is entered there once, with the new ancestors.
+ for (const group of reflagged) {
+ for (const member of collectSubtree(group)) {
+ if (member.id !== group.id) {
+ replaceEntry(member.id, member, true);
+ }
+ }
+ }
+ for (const [id, node] of replacedNodes) {
+ if (!replaced.has(id)) {
+ replaceEntry(id, node, false);
+ }
+ }
+ const derived = new DerivedIndex(nextStacks, previous, replaced, leafChanged);
+ const registered = derivationDepth(derived) > MAX_DERIVATION_DEPTH ? flatten(derived) : derived;
+ indexes.set(nextStacks, registered);
+ return registered;
};
export const indexStacks = (stacks: CanvasStackForests): CanvasDocumentIndex => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
index d6df80849c..264ad1e5ff 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
@@ -129,7 +129,7 @@ const withStacks = (document: CanvasDocumentContractV3, stacks: CanvasStackFores
const withinLimits = (stacks: CanvasStackForests): boolean => {
const index = indexStacks(stacks);
- return index.maxDepth <= CANVAS_MAX_NODE_DEPTH && index.nodes.length <= CANVAS_MAX_NODE_COUNT;
+ return index.maxDepth <= CANVAS_MAX_NODE_DEPTH && index.byId.size <= CANVAS_MAX_NODE_COUNT;
};
/** Value edits keep the structure, so the next forests inherit the index instead of rebuilding it. */