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(workflows): index workflow graph lookups
joshistoast0b0793e21778
diff --git a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.tsindex ed68e240a2..49bdffde6c 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/buildGraph.ts@@ -3,9 +3,10 @@ import type { BackendGraphContract, GraphContract } from '@workbench/types';import type { InvocationTemplatesSnapshot } from './templates';import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState, WorkflowInvocationNode } from './types';-import { getResolvedWorkflowEdges } from './connectors';+import { getResolvedWorkflowEdgesIndexed } from './connectors';import { createWorkflowId } from './document';import { getWorkflowFieldInvalidReason } from './fields';+import { createWorkflowGraphIndex } from './graphIndex';import { isInvocationNode } from './types';import { hasAnyCycle } from './validation';@@ -70,6 +71,7 @@ export const getProjectGraphReadiness = (const templates = templatesSnapshot.templates;const executableNodes = getExecutableNodes(document);+ const index = createWorkflowGraphIndex(document.nodes, document.edges);if (executableNodes.length === 0) {return { canInvoke: false, reasons: ['The project graph has no nodes. Add nodes in the Workflow view.'] };@@ -77,7 +79,7 @@ export const getProjectGraphReadiness = (const reasons: string[] = [];const connectedInputs = new Set(- getResolvedWorkflowEdges(document.nodes, document.edges, templates)+ getResolvedWorkflowEdgesIndexed(document.edges, index, templates).filter((edge) => executableNodes.some((node) => node.id === edge.target)).map((edge) => `${edge.target}:${edge.targetHandle}`));@@ -143,6 +145,8 @@ export const compileProjectGraph = (document: ProjectGraphState, templates: Invoconst executableNodes = getExecutableNodes(document).filter((node) => templates[node.data.type] !== undefined);const executableNodeIds = new Set(executableNodes.map((node) => node.id));const backendGraph: BackendGraphContract = { edges: [], id: createWorkflowId('workflow-graph'), nodes: {} };+ const index = createWorkflowGraphIndex(document.nodes, document.edges);+ const resolvedEdges = getResolvedWorkflowEdgesIndexed(document.edges, index, templates);for (const node of executableNodes) {const template = templates[node.data.type] as NonNullable<(typeof templates)[string]>;@@ -172,7 +176,7 @@ export const compileProjectGraph = (document: ProjectGraphState, templates: Invoconst seenEdgeKeys = new Set<string>();- for (const edge of getResolvedWorkflowEdges(document.nodes, document.edges, templates)) {+ for (const edge of resolvedEdges) {if (!executableNodeIds.has(edge.source) || !executableNodeIds.has(edge.target)) {continue;}@@ -200,7 +204,7 @@ export const compileProjectGraph = (document: ProjectGraphState, templates: Invoreturn {backendGraph,- edges: getResolvedWorkflowEdges(document.nodes, document.edges, templates)+ edges: resolvedEdges.filter((edge) => executableNodeIds.has(edge.source) && executableNodeIds.has(edge.target)).map((edge) => ({id: edge.id,diff --git a/invokeai/frontend/webv2/src/workbench/workflows/connectorHandles.ts b/invokeai/frontend/webv2/src/workbench/workflows/connectorHandles.tsnew file mode 100644index 0000000000..b03e2347bb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/connectorHandles.ts@@ -0,0 +1,2 @@+export const CONNECTOR_INPUT_HANDLE = 'in';+export const CONNECTOR_OUTPUT_HANDLE = 'out';diff --git a/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts b/invokeai/frontend/webv2/src/workbench/workflows/connectors.tsindex e2ade4696a..c542800e2e 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/connectors.ts@@ -1,9 +1,10 @@import type { FieldType, InvocationTemplates, WorkflowEdge, WorkflowNode } from './types';+import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from './connectorHandles';+import { createWorkflowGraphIndex, type WorkflowGraphIndex } from './graphIndex';import { isConnectorNode, isInvocationNode } from './types';-export const CONNECTOR_INPUT_HANDLE = 'in';-export const CONNECTOR_OUTPUT_HANDLE = 'out';+export { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from './connectorHandles';export interface ResolvedConnectorSource {fieldName: string;@@ -27,50 +28,85 @@ export const getConnectorInputEdge = (connectorId: string, edges: WorkflowEdge[](edge) => edge.type === 'default' && edge.target === connectorId && edge.targetHandle === CONNECTOR_INPUT_HANDLE);+export const getConnectorInputEdgeIndexed = (+ connectorId: string,+ index: WorkflowGraphIndex+): WorkflowEdge | undefined => index.connectorInputById.get(connectorId);+export const getConnectorOutputEdges = (connectorId: string, edges: WorkflowEdge[]): WorkflowEdge[] =>edges.filter((edge) => edge.type === 'default' && edge.source === connectorId && edge.sourceHandle === CONNECTOR_OUTPUT_HANDLE);+export const getConnectorOutputEdgesIndexed = (connectorId: string, index: WorkflowGraphIndex): WorkflowEdge[] =>+ index.connectorOutputsById.get(connectorId) ?? [];+export const resolveConnectorSource = (connectorId: string,nodes: WorkflowNode[],edges: WorkflowEdge[],templates?: InvocationTemplates+): ResolvedConnectorSource | null =>+ resolveConnectorSourceIndexed(connectorId, createWorkflowGraphIndex(nodes, edges), templates);++export const resolveConnectorSourceIndexed = (+ connectorId: string,+ index: WorkflowGraphIndex,+ templates?: InvocationTemplates+): ResolvedConnectorSource | null => resolveConnectorSourceWithCache(connectorId, index, templates, new Map());++const resolveConnectorSourceWithCache = (+ connectorId: string,+ index: WorkflowGraphIndex,+ templates: InvocationTemplates | undefined,+ cache: Map<string, ResolvedConnectorSource | null>): ResolvedConnectorSource | null => {const visited = new Set<string>();const resolve = (nodeId: string): ResolvedConnectorSource | null => {+ if (cache.has(nodeId)) {+ return cache.get(nodeId) ?? null;+ }+if (visited.has(nodeId)) {return null;}visited.add(nodeId);- const inboundEdge = getConnectorInputEdge(nodeId, edges);+ const inboundEdge = getConnectorInputEdgeIndexed(nodeId, index);if (!inboundEdge) {+ cache.set(nodeId, null);return null;}- const sourceNode = nodes.find((node) => node.id === inboundEdge.source);+ const sourceNode = index.nodesById.get(inboundEdge.source);if (!sourceNode) {+ cache.set(nodeId, null);return null;}if (isInvocationNode(sourceNode)) {- return {+ const source = {fieldName: inboundEdge.sourceHandle,nodeId: sourceNode.id,type: templates?.[sourceNode.data.type]?.outputs[inboundEdge.sourceHandle]?.type ?? null,};++ cache.set(nodeId, source);+ return source;}if (isConnectorNode(sourceNode) && inboundEdge.sourceHandle === CONNECTOR_OUTPUT_HANDLE) {- return resolve(sourceNode.id);+ const source = resolve(sourceNode.id);++ cache.set(nodeId, source);+ return source;}+ cache.set(nodeId, null);return null;};@@ -91,10 +127,30 @@ export const resolveConnectorTargets = (nodes: WorkflowNode[],edges: WorkflowEdge[],templates?: InvocationTemplates+): ResolvedConnectorTarget[] =>+ resolveConnectorTargetsIndexed(connectorId, createWorkflowGraphIndex(nodes, edges), templates);++export const resolveConnectorTargetsIndexed = (+ connectorId: string,+ index: WorkflowGraphIndex,+ templates?: InvocationTemplates+): ResolvedConnectorTarget[] => resolveConnectorTargetsWithCache(connectorId, index, templates, new Map());++const resolveConnectorTargetsWithCache = (+ connectorId: string,+ index: WorkflowGraphIndex,+ templates: InvocationTemplates | undefined,+ cache: Map<string, ResolvedConnectorTarget[]>): ResolvedConnectorTarget[] => {const visited = new Set<string>();const resolve = (nodeId: string): ResolvedConnectorTarget[] => {+ const cached = cache.get(nodeId);++ if (cached) {+ return cached;+ }+if (visited.has(nodeId)) {return [];}@@ -103,8 +159,8 @@ export const resolveConnectorTargets = (const targets: ResolvedConnectorTarget[] = [];- for (const outboundEdge of getConnectorOutputEdges(nodeId, edges)) {- const targetNode = nodes.find((node) => node.id === outboundEdge.target);+ for (const outboundEdge of getConnectorOutputEdgesIndexed(nodeId, index)) {+ const targetNode = index.nodesById.get(outboundEdge.target);if (!targetNode) {continue;@@ -124,6 +180,7 @@ export const resolveConnectorTargets = (}}+ cache.set(nodeId, targets);return targets;};@@ -135,8 +192,16 @@ export const resolveWorkflowEdgeSource = (nodes: WorkflowNode[],edges: WorkflowEdge[],templates?: InvocationTemplates+): ResolvedConnectorSource | null =>+ resolveWorkflowEdgeSourceIndexed(edge, createWorkflowGraphIndex(nodes, edges), templates);++export const resolveWorkflowEdgeSourceIndexed = (+ edge: WorkflowEdge,+ index: WorkflowGraphIndex,+ templates?: InvocationTemplates,+ connectorSourceCache = new Map<string, ResolvedConnectorSource | null>()): ResolvedConnectorSource | null => {- const sourceNode = nodes.find((node) => node.id === edge.source);+ const sourceNode = index.nodesById.get(edge.source);if (!sourceNode) {return null;@@ -151,7 +216,7 @@ export const resolveWorkflowEdgeSource = (}if (isConnectorNode(sourceNode) && edge.sourceHandle === CONNECTOR_OUTPUT_HANDLE) {- return resolveConnectorSource(sourceNode.id, nodes, edges, templates);+ return resolveConnectorSourceWithCache(sourceNode.id, index, templates, connectorSourceCache);}return null;@@ -161,11 +226,18 @@ export const getResolvedWorkflowEdges = (nodes: WorkflowNode[],edges: WorkflowEdge[],templates?: InvocationTemplates+): ResolvedWorkflowEdge[] => getResolvedWorkflowEdgesIndexed(edges, createWorkflowGraphIndex(nodes, edges), templates);++export const getResolvedWorkflowEdgesIndexed = (+ edges: WorkflowEdge[],+ index: WorkflowGraphIndex,+ templates?: InvocationTemplates): ResolvedWorkflowEdge[] => {const resolved: ResolvedWorkflowEdge[] = [];+ const connectorSourceCache = new Map<string, ResolvedConnectorSource | null>();for (const edge of edges) {- const source = resolveWorkflowEdgeSource(edge, nodes, edges, templates);+ const source = resolveWorkflowEdgeSourceIndexed(edge, index, templates, connectorSourceCache);if (!source) {continue;diff --git a/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.test.ts b/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.test.tsnew file mode 100644index 0000000000..c86fa3475e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import type { WorkflowConnectorNode, WorkflowEdge, WorkflowInvocationNode } from './types';++import { createWorkflowGraphIndex } from './graphIndex';++const makeNode = (id: string): WorkflowInvocationNode => ({+ data: {+ inputs: {},+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'number',+ useCache: true,+ version: '1.0.0',+ },+ id,+ position: { x: 0, y: 0 },+ type: 'invocation',+});++const makeConnector = (id: string): WorkflowConnectorNode => ({+ data: { label: '' },+ id,+ position: { x: 0, y: 0 },+ type: 'connector',+});++const edge = (+ id: string,+ source: string,+ sourceHandle: string,+ target: string,+ targetHandle: string+): WorkflowEdge => ({+ id,+ source,+ sourceHandle,+ target,+ targetHandle,+ type: 'default',+});++describe('createWorkflowGraphIndex', () => {+ it('indexes nodes and connector edges for repeated lookup', () => {+ const source = makeNode('source');+ const target = makeNode('target');+ const connector = makeConnector('connector');+ const connectorInput = edge('connector-input', 'source', 'value', 'connector', 'in');+ const connectorOutput = edge('connector-output', 'connector', 'out', 'target', 'value');+ const index = createWorkflowGraphIndex([source, connector, target], [connectorInput, connectorOutput]);++ expect(index.nodesById.get('source')).toBe(source);+ expect(index.edgesBySource.get('connector')).toEqual([connectorOutput]);+ expect(index.edgesByTarget.get('connector')).toEqual([connectorInput]);+ expect(index.connectorInputById.get('connector')).toBe(connectorInput);+ expect(index.connectorOutputsById.get('connector')).toEqual([connectorOutput]);+ });++ it('preserves first-match connector input semantics for invalid duplicate inputs', () => {+ const sourceA = makeNode('source-a');+ const sourceB = makeNode('source-b');+ const connector = makeConnector('connector');+ const firstInput = edge('first-input', 'source-a', 'value', 'connector', 'in');+ const secondInput = edge('second-input', 'source-b', 'value', 'connector', 'in');+ const index = createWorkflowGraphIndex([sourceA, sourceB, connector], [firstInput, secondInput]);++ expect(index.connectorInputById.get('connector')).toBe(firstInput);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.ts b/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.tsnew file mode 100644index 0000000000..e7954742a9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/workflows/graphIndex.ts@@ -0,0 +1,57 @@+import type { WorkflowEdge, WorkflowNode } from './types';++import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from './connectorHandles';++export interface WorkflowGraphIndex {+ connectorInputById: Map<string, WorkflowEdge>;+ connectorOutputsById: Map<string, WorkflowEdge[]>;+ edgesBySource: Map<string, WorkflowEdge[]>;+ edgesByTarget: Map<string, WorkflowEdge[]>;+ nodesById: Map<string, WorkflowNode>;+}++const append = <K, V>(map: Map<K, V[]>, key: K, value: V): void => {+ const values = map.get(key);++ if (values) {+ values.push(value);+ return;+ }++ map.set(key, [value]);+};++export const createWorkflowGraphIndex = (nodes: WorkflowNode[], edges: WorkflowEdge[]): WorkflowGraphIndex => {+ const index: WorkflowGraphIndex = {+ connectorInputById: new Map(),+ connectorOutputsById: new Map(),+ edgesBySource: new Map(),+ edgesByTarget: new Map(),+ nodesById: new Map(),+ };++ for (const node of nodes) {+ index.nodesById.set(node.id, node);+ }++ for (const edge of edges) {+ append(index.edgesBySource, edge.source, edge);+ append(index.edgesByTarget, edge.target, edge);++ if (edge.type !== 'default') {+ continue;+ }++ if (edge.targetHandle === CONNECTOR_INPUT_HANDLE) {+ if (!index.connectorInputById.has(edge.target)) {+ index.connectorInputById.set(edge.target, edge);+ }+ }++ if (edge.sourceHandle === CONNECTOR_OUTPUT_HANDLE) {+ append(index.connectorOutputsById, edge.source, edge);+ }+ }++ return index;+};diff --git a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts b/invokeai/frontend/webv2/src/workbench/workflows/validation.tsindex 7f596ecf25..012ad26754 100644--- a/invokeai/frontend/webv2/src/workbench/workflows/validation.ts+++ b/invokeai/frontend/webv2/src/workbench/workflows/validation.ts@@ -12,9 +12,10 @@ import type {import {CONNECTOR_INPUT_HANDLE,CONNECTOR_OUTPUT_HANDLE,- resolveConnectorSource,- resolveConnectorTargets,+ resolveConnectorSourceIndexed,+ resolveConnectorTargetsIndexed,} from './connectors';+import { createWorkflowGraphIndex, type WorkflowGraphIndex } from './graphIndex';import { isConnectorNode, isInvocationNode } from './types';/**@@ -197,9 +198,10 @@ const isSameFieldType = (left: FieldType, right: FieldType): boolean =>const getCommonConnectorTargetType = (connectorId: string,document: Pick<ProjectGraphState, 'edges' | 'nodes'>,- templates: InvocationTemplates+ templates: InvocationTemplates,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): FieldType | null => {- const targets = resolveConnectorTargets(connectorId, document.nodes, document.edges, templates);+ const targets = resolveConnectorTargetsIndexed(connectorId, index, templates);if (targets.length === 0 || targets.some((target) => target.type === null)) {return null;@@ -216,16 +218,17 @@ const getSourceFieldType = (node: WorkflowNode,handle: string,document: Pick<ProjectGraphState, 'edges' | 'nodes'>,- templates: InvocationTemplates+ templates: InvocationTemplates,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): FieldType | null | undefined => {if (isInvocationNode(node)) {return templates[node.data.type]?.outputs[handle]?.type;}if (isConnectorNode(node) && handle === CONNECTOR_OUTPUT_HANDLE) {- const source = resolveConnectorSource(node.id, document.nodes, document.edges, templates);+ const source = resolveConnectorSourceIndexed(node.id, index, templates);- return source ? source.type : getCommonConnectorTargetType(node.id, document, templates);+ return source ? source.type : getCommonConnectorTargetType(node.id, document, templates, index);}return undefined;@@ -235,18 +238,20 @@ export const getWorkflowSourceFieldType = (document: Pick<ProjectGraphState, 'edges' | 'nodes'>,templates: InvocationTemplates,sourceNodeId: string,- sourceHandle: string+ sourceHandle: string,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): FieldType | null | undefined => {- const sourceNode = document.nodes.find((node) => node.id === sourceNodeId);+ const sourceNode = index.nodesById.get(sourceNodeId);- return sourceNode ? getSourceFieldType(sourceNode, sourceHandle, document, templates) : undefined;+ return sourceNode ? getSourceFieldType(sourceNode, sourceHandle, document, templates, index) : undefined;};const getTargetFieldType = (node: WorkflowNode,handle: string,document: Pick<ProjectGraphState, 'edges' | 'nodes'>,- templates: InvocationTemplates+ templates: InvocationTemplates,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): FieldType | null | undefined => {if (isInvocationNode(node)) {const inputTemplate = templates[node.data.type]?.inputs[handle];@@ -255,13 +260,13 @@ const getTargetFieldType = (}if (isConnectorNode(node) && handle === CONNECTOR_INPUT_HANDLE) {- const targetType = getCommonConnectorTargetType(node.id, document, templates);+ const targetType = getCommonConnectorTargetType(node.id, document, templates, index);if (targetType) {return targetType;}- return resolveConnectorSource(node.id, document.nodes, document.edges, templates)?.type ?? null;+ return resolveConnectorSourceIndexed(node.id, index, templates)?.type ?? null;}return undefined;@@ -271,11 +276,12 @@ export const getWorkflowTargetFieldType = (document: Pick<ProjectGraphState, 'edges' | 'nodes'>,templates: InvocationTemplates,targetNodeId: string,- targetHandle: string+ targetHandle: string,+ index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): FieldType | null | undefined => {- const targetNode = document.nodes.find((node) => node.id === targetNodeId);+ const targetNode = index.nodesById.get(targetNodeId);- return targetNode ? getTargetFieldType(targetNode, targetHandle, document, templates) : undefined;+ return targetNode ? getTargetFieldType(targetNode, targetHandle, document, templates, index) : undefined;};const hasValidSourceHandle = (node: WorkflowNode, handle: string, templates: InvocationTemplates): boolean => {@@ -293,13 +299,14 @@ export const validateConnection = (templates: InvocationTemplates): string | null => {const { sourceHandle, sourceNodeId, targetHandle, targetNodeId } = candidate;+ const index = createWorkflowGraphIndex(document.nodes, document.edges);if (sourceNodeId === targetNodeId) {return 'A node cannot connect to itself.';}- const sourceNode = document.nodes.find((node) => node.id === sourceNodeId);- const targetNode = document.nodes.find((node) => node.id === targetNodeId);+ const sourceNode = index.nodesById.get(sourceNodeId);+ const targetNode = index.nodesById.get(targetNodeId);if (!sourceNode || !targetNode) {return 'Both ends of a connection must be workflow nodes.';@@ -314,12 +321,12 @@ export const validateConnection = (return 'Connectors only accept input on their left handle.';}- if (document.edges.some((edge) => edge.target === targetNodeId && edge.targetHandle === targetHandle)) {+ if (index.edgesByTarget.get(targetNodeId)?.some((edge) => edge.targetHandle === targetHandle)) {return 'Connector already has an input.';}- const sourceFieldType = getSourceFieldType(sourceNode, sourceHandle, document, templates);- const targetFieldTypes = resolveConnectorTargets(targetNodeId, document.nodes, document.edges, templates)+ const sourceFieldType = getSourceFieldType(sourceNode, sourceHandle, document, templates, index);+ const targetFieldTypes = resolveConnectorTargetsIndexed(targetNodeId, index, templates).map((target) => target.type).filter((type): type is FieldType => type !== null);@@ -341,7 +348,7 @@ export const validateConnection = (}const targetTemplate = templates[targetNode.data.type];- const sourceFieldType = getSourceFieldType(sourceNode, sourceHandle, document, templates);+ const sourceFieldType = getSourceFieldType(sourceNode, sourceHandle, document, templates, index);const targetField = targetTemplate?.inputs[targetHandle];if (sourceFieldType === undefined || !targetField) {@@ -352,21 +359,21 @@ export const validateConnection = (return `${targetField.title} only accepts direct values, not connections.`;}- const isDuplicate = document.edges.some(- (edge) =>- edge.source === sourceNodeId &&- edge.sourceHandle === sourceHandle &&- edge.target === targetNodeId &&- edge.targetHandle === targetHandle- );+ const isDuplicate = index.edgesBySource+ .get(sourceNodeId)+ ?.some(+ (edge) =>+ edge.source === sourceNodeId &&+ edge.sourceHandle === sourceHandle &&+ edge.target === targetNodeId &&+ edge.targetHandle === targetHandle+ );if (isDuplicate) {return 'This connection already exists.';}- const hasInboundEdge = document.edges.some(- (edge) => edge.target === targetNodeId && edge.targetHandle === targetHandle- );+ const hasInboundEdge = index.edgesByTarget.get(targetNodeId)?.some((edge) => edge.targetHandle === targetHandle);if (hasInboundEdge && !allowsMultipleInboundEdges(targetNode, targetHandle)) {return `${targetField.title} already has a connection.`;