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
feat(workbench): record performance timings in diagnostics
joshistoast25a3716dba43
diff --git a/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts b/invokeai/frontend/webv2/src/workbench/performanceMarks.test.tsindex 71dd5b595b..e9ec506a91 100644--- a/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts+++ b/invokeai/frontend/webv2/src/workbench/performanceMarks.test.ts@@ -1,55 +1,60 @@-/* oxlint-disable no-console */-import { beforeEach, describe, expect, it, vi } from 'vitest';-import {- getWorkbenchPerfEntries,- markWorkbenchPerf,- measureWorkbenchPerf,- timeWorkbenchPerf,-} from './performanceMarks';--const storage = new Map<string, string>();--vi.stubGlobal('window', {- localStorage: {- getItem: (key: string): string | null => storage.get(key) ?? null,- },-});+import { clearProjectDiagnostics, configureDiagnostics, getProjectDiagnostics } from './diagnostics/logger';+import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from './performanceMarks';beforeEach(() => {- storage.clear();- window.__invokeaiWorkbenchPerf = [];+ clearProjectDiagnostics('project-a');+ configureDiagnostics({+ enabled: true,+ level: 'trace',+ namespaces: [],+ performanceTimingsEnabled: true,+ });vi.spyOn(performance, 'mark').mockImplementation((name: string) => ({ name }) as PerformanceMark);vi.spyOn(performance, 'measure').mockImplementation((name: string) => ({ duration: 12.34, name }) as PerformanceMeasure);- vi.spyOn(console, 'info').mockImplementation(() => undefined);+ vi.clearAllMocks();});describe('performanceMarks', () => {- it('does nothing when workbench perf logging is not enabled', () => {+ it('does nothing when no diagnostic source is provided', () => {markWorkbenchPerf('workflow:test');measureWorkbenchPerf('workflow:measure', 'workflow:test');expect(performance.mark).not.toHaveBeenCalled();expect(performance.measure).not.toHaveBeenCalled();- expect(console.info).not.toHaveBeenCalled();- expect(getWorkbenchPerfEntries()).toEqual([]);+ expect(getProjectDiagnostics('project-a')).toEqual([]);});- it('marks and measures when enabled', () => {- storage.set('invokeai:webv2:perf', '1');-- const result = timeWorkbenchPerf('workflow:build', () => 42);+ it('marks, measures and records timings for the provided diagnostic source', () => {+ const source = { area: 'test', kind: 'workbench' as const, projectId: 'project-a' };+ const result = timeWorkbenchPerf('workflow:build', source, () => 42);expect(result).toBe(42);expect(performance.mark).toHaveBeenCalledWith('workflow:build:start');expect(performance.mark).toHaveBeenCalledWith('workflow:build:end');expect(performance.measure).toHaveBeenCalledWith('workflow:build', 'workflow:build:start', 'workflow:build:end');- expect(console.info).toHaveBeenCalledWith('[workbench perf] workflow:build: 12.3ms');- expect(getWorkbenchPerfEntries()).toEqual([- { duration: 12.34, name: 'workflow:build', timestamp: expect.any(Number) },+ expect(getProjectDiagnostics('project-a')).toMatchObject([+ { durationMs: 12.34, message: 'workflow:build completed in 12.3ms', namespace: 'performance', source },]);});++ it('does not call the Performance API when timing collection is disabled', () => {+ configureDiagnostics({+ enabled: true,+ level: 'trace',+ namespaces: [],+ performanceTimingsEnabled: false,+ });++ const source = { area: 'test', kind: 'workbench' as const, projectId: 'project-a' };++ timeWorkbenchPerf('workflow:build', source, () => 42);++ expect(performance.mark).not.toHaveBeenCalled();+ expect(performance.measure).not.toHaveBeenCalled();+ expect(getProjectDiagnostics('project-a')).toEqual([]);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/performanceMarks.ts b/invokeai/frontend/webv2/src/workbench/performanceMarks.tsindex f220459e37..5cd9d59a6f 100644--- a/invokeai/frontend/webv2/src/workbench/performanceMarks.ts+++ b/invokeai/frontend/webv2/src/workbench/performanceMarks.ts@@ -1,99 +1,57 @@-/* oxlint-disable no-console */--const PERF_STORAGE_KEY = 'invokeai:webv2:perf';-const MAX_ENTRIES = 200;--interface WorkbenchPerfEntry {- duration: number;- name: string;- timestamp: number;-}--declare global {- interface Window {- __invokeaiWorkbenchPerf?: WorkbenchPerfEntry[];- }-}+import { canRecordDiagnosticTiming, recordDiagnosticTiming, type DiagnosticSource } from './diagnostics/logger';const hasPerformanceApi = (): boolean => typeof performance !== 'undefined' && typeof performance.mark === 'function';-const isPerfEnabled = (): boolean => {- if (!hasPerformanceApi()) {- return false;- }-- try {- return typeof window !== 'undefined' && window.localStorage.getItem(PERF_STORAGE_KEY) === '1';- } catch {- return false;- }-};+const canMeasurePerf = (source?: DiagnosticSource): source is DiagnosticSource =>+ hasPerformanceApi() && canRecordDiagnosticTiming(source);-export const markWorkbenchPerf = (name: string): void => {- if (!isPerfEnabled()) {+export const markWorkbenchPerf = (name: string, source?: DiagnosticSource): void => {+ if (!canMeasurePerf(source)) {return;}performance.mark(name);};-const recordWorkbenchPerfEntry = (entry: WorkbenchPerfEntry): void => {- if (typeof window === 'undefined') {- return;- }-- // TODO: Move benchmark collection out of a global window buffer when a real diagnostics surface exists.- const entries = window.__invokeaiWorkbenchPerf ?? [];-- entries.push(entry);-- if (entries.length > MAX_ENTRIES) {- entries.splice(0, entries.length - MAX_ENTRIES);- }-- window.__invokeaiWorkbenchPerf = entries;-};--export const measureWorkbenchPerf = (name: string, startMark: string, endMark?: string): void => {- if (!isPerfEnabled()) {+export const measureWorkbenchPerf = (+ name: string,+ startMark: string,+ source?: DiagnosticSource,+ endMark?: string+): void => {+ if (!canMeasurePerf(source)) {return;}try {const measure = endMark ? performance.measure(name, startMark, endMark) : performance.measure(name, startMark);- const entry = { duration: measure.duration, name: measure.name, timestamp: performance.now() };- recordWorkbenchPerfEntry(entry);+ recordDiagnosticTiming(source, measure.name, measure.duration);- // TODO: Replace console logging with a dedicated benchmark sink/export UI before keeping this long-term.- console.info(`[workbench perf] ${entry.name}: ${entry.duration.toFixed(1)}ms`);+ performance.clearMeasures?.(name);+ performance.clearMarks?.(startMark);+ if (endMark) {+ performance.clearMarks?.(endMark);+ }} catch {// A missing mark should never affect workflow behavior.}};-export const getWorkbenchPerfEntries = (): WorkbenchPerfEntry[] => {- if (typeof window === 'undefined') {- return [];- }-- return [...(window.__invokeaiWorkbenchPerf ?? [])];-};--export const timeWorkbenchPerf = <T>(name: string, callback: () => T): T => {- if (!isPerfEnabled()) {+export const timeWorkbenchPerf = <T>(name: string, source: DiagnosticSource | undefined, callback: () => T): T => {+ if (!canMeasurePerf(source)) {return callback();}const startMark = `${name}:start`;const endMark = `${name}:end`;- markWorkbenchPerf(startMark);+ markWorkbenchPerf(startMark, source);try {return callback();} finally {- markWorkbenchPerf(endMark);- measureWorkbenchPerf(name, startMark, endMark);+ markWorkbenchPerf(endMark, source);+ measureWorkbenchPerf(name, startMark, source, endMark);}};diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.tsindex c33e68d1f3..92bb472fe6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.ts@@ -103,7 +103,11 @@ const getSerializedProjectDocument = (project: Project): { document: Record<stri}const document = serializeProjectDocument(project);- const json = timeWorkbenchPerf('workbench:project-document-stringify', () => JSON.stringify(document));+ const json = timeWorkbenchPerf(+ 'workbench:project-document-stringify',+ { area: 'project-sync', kind: 'workbench', projectId: project.id },+ () => JSON.stringify(document)+ );const serialized = { document, json };projectDocumentJsonCache.set(project, serialized);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsxindex f869c8defc..8b9a7ce8f4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx@@ -1,3 +1,4 @@+import type { DiagnosticSource } from '@workbench/diagnostics/logger';/* eslint-disable react/react-compiler */import type { WidgetRuntimeApi } from '@workbench/types';import type { ProjectGraphState, XYPosition } from '@workbench/workflows/types';@@ -131,26 +132,28 @@ const buildWorkflowFlowModel = ({selectedNodeIds = new Set<string>(),isCompact = false,canUseCache = false,+ perfSource,}: {canUseCache?: boolean;document: ProjectGraphState;edgeType: FlowEdgeType;isCompact?: boolean;invocationTemplates?: Parameters<typeof toFlowNodes>[2];+ perfSource?: DiagnosticSource;previousEdges?: WorkflowFlowEdge[];previousNodes?: WorkflowFlowNode[];reduceMotion: boolean;selectedNodeIds?: Set<string>;}): WorkflowFlowModel => {- const index = timeWorkbenchPerf('workflow:create-graph-index', () =>+ const index = timeWorkbenchPerf('workflow:create-graph-index', perfSource, () =>createWorkflowGraphIndex(document.nodes, document.edges));- return timeWorkbenchPerf('workflow:build-flow-model', () => ({- edges: timeWorkbenchPerf('workflow:to-flow-edges', () =>+ return timeWorkbenchPerf('workflow:build-flow-model', perfSource, () => ({+ edges: timeWorkbenchPerf('workflow:to-flow-edges', perfSource, () =>toFlowEdges(document, previousEdges, edgeType, selectedNodeIds, invocationTemplates, reduceMotion, index)),- nodes: timeWorkbenchPerf('workflow:to-flow-nodes', () =>+ nodes: timeWorkbenchPerf('workflow:to-flow-nodes', perfSource, () =>toFlowNodes(document, previousNodes, invocationTemplates, index, isCompact, canUseCache)),}));@@ -250,6 +253,16 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {() => getWorkflowViewportKey(projectId, runtime.instanceId),[projectId, runtime.instanceId]);+ const perfSource = useMemo<DiagnosticSource>(+ () => ({+ instanceId: runtime.instanceId,+ kind: 'widget',+ projectId,+ region: runtime.region,+ typeId: runtime.typeId,+ }),+ [projectId, runtime.instanceId, runtime.region, runtime.typeId]+ );const defaultViewport = useMemo(() => getWorkflowViewport(viewportKey) ?? DEFAULT_VIEWPORT, [viewportKey]);const [flowModel, setFlowModel] = useState<WorkflowFlowModel | null>(() =>isLargeGraph@@ -260,6 +273,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {edgeType,invocationTemplates,isCompact: isLargeGraph,+ perfSource,reduceMotion,}));@@ -371,30 +385,36 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}, [isLargeGraph, projectId]);useEffect(() => {- markWorkbenchPerf(perfMountMarkRef.current);- }, []);+ markWorkbenchPerf(perfMountMarkRef.current, perfSource);+ }, [perfSource]);useEffect(() => {if (isPreparing) {return;}- markWorkbenchPerf(perfReadyMarkRef.current);- measureWorkbenchPerf('workflow:editor-mounted-to-ready', perfMountMarkRef.current, perfReadyMarkRef.current);- }, [isPreparing]);+ markWorkbenchPerf(perfReadyMarkRef.current, perfSource);+ measureWorkbenchPerf(+ 'workflow:editor-mounted-to-ready',+ perfMountMarkRef.current,+ perfSource,+ perfReadyMarkRef.current+ );+ }, [isPreparing, perfSource]);useEffect(() => {if (!isFullGraphMounted || !isLargeGraph) {return;}- markWorkbenchPerf('workflow:full-graph-mounted');+ markWorkbenchPerf('workflow:full-graph-mounted', perfSource);measureWorkbenchPerf('workflow:full-graph-expand','workflow:full-graph-expand-start',+ perfSource,'workflow:full-graph-mounted');- }, [isFullGraphMounted, isLargeGraph]);+ }, [isFullGraphMounted, isLargeGraph, perfSource]);useEffect(() => {if (!workflowShowMinimap) {@@ -414,12 +434,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {}const timeoutId = window.setTimeout(() => {- markWorkbenchPerf('workflow:minimap-ready');+ markWorkbenchPerf('workflow:minimap-ready', perfSource);setIsMinimapReady(true);}, WORKFLOW_MINIMAP_DELAY_MS);return () => window.clearTimeout(timeoutId);- }, [isLargeGraph, isPreparing, workflowShowMinimap]);+ }, [isLargeGraph, isPreparing, perfSource, workflowShowMinimap]);useEffect(() => {const pendingSelection = pendingSelectionRef.current;@@ -460,6 +480,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {canUseCache,isCompact: isLargeGraph,invocationTemplates,+ perfSource,previousEdges: current?.edges,previousNodes: current?.nodes,reduceMotion,@@ -491,6 +512,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {edgeType,invocationTemplates,isLargeGraph,+ perfSource,projectGraph,reduceMotion,selectedNodeIds,@@ -943,21 +965,31 @@ const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {(instance: WorkflowFlowInstance) => {const flowInitMark = 'workflow:react-flow-init';- markWorkbenchPerf(flowInitMark);- measureWorkbenchPerf('workflow:editor-ready-to-react-flow-init', perfReadyMarkRef.current, flowInitMark);- measureWorkbenchPerf('workflow:editor-mounted-to-react-flow-init', perfMountMarkRef.current, flowInitMark);+ markWorkbenchPerf(flowInitMark, perfSource);+ measureWorkbenchPerf(+ 'workflow:editor-ready-to-react-flow-init',+ perfReadyMarkRef.current,+ perfSource,+ flowInitMark+ );+ measureWorkbenchPerf(+ 'workflow:editor-mounted-to-react-flow-init',+ perfMountMarkRef.current,+ perfSource,+ flowInitMark+ );setFlowInstance(instance);if (isLargeGraph && !isFullGraphMounted && !hasScheduledFullGraphMountRef.current) {hasScheduledFullGraphMountRef.current = true;window.setTimeout(() => {- markWorkbenchPerf('workflow:full-graph-expand-start');+ markWorkbenchPerf('workflow:full-graph-expand-start', perfSource);setIsFullGraphMounted(true);}, 0);}},- [isFullGraphMounted, isLargeGraph]+ [isFullGraphMounted, isLargeGraph, perfSource]);const editorCss = useMemo(