Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(workbench): verify graph history byte sizes

joshistoastc5a1b254cbdc
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 97c3384ed2..b6f727f4ee 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -11,7 +11,7 @@ import type { GraphContract } from '@workbench/graphContracts';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { MAX_PROMPT_HISTORY } from '@features/generation/settings';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import type { CanvasProjectMutation } from './canvasProjectMutations';
@@ -1503,23 +1503,82 @@ describe('workbenchReducer Phase 5 generation flow', () => {
expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);
});
- it('normalizes graph history within count and UTF-8 retained-byte budgets', () => {
+ it('keeps the newest graph-history entries within the count limit and recomputes retained bytes', () => {
const entries = Array.from({ length: 50 }, (_, index) => ({
createdAt: `2026-07-19T00:00:${String(index).padStart(2, '0')}.000Z`,
document: { edges: [], nodes: [], version: 1 as const },
id: `snapshot-${index}`,
label: `Snapshot ${index}`,
- retainedBytes: 2 * 1024 * 1024,
+ retainedBytes: 0,
}));
const normalized = normalizeGraphHistory(entries);
- expect(normalized).toHaveLength(32);
- expect(normalized.reduce((total, entry) => total + (entry.retainedBytes ?? 0), 0)).toBeLessThanOrEqual(
- GRAPH_HISTORY_BYTE_BUDGET
- );
+ expect(normalized).toHaveLength(40);
+ expect(normalized.map((entry) => entry.id)).toEqual(entries.slice(0, 40).map((entry) => entry.id));
+ expect(normalized.every((entry) => (entry.retainedBytes ?? 0) > 0)).toBe(true);
+ });
+
+ it('measures loaded graph-history entries instead of trusting forged retained-byte metadata', () => {
+ const encode = vi.spyOn(TextEncoder.prototype, 'encode').mockImplementation((input) => {
+ const byteLength = String(input).includes('"id":"oversized"') ? GRAPH_HISTORY_BYTE_BUDGET + 1 : 128;
+
+ return Object.defineProperty(new Uint8Array(0), 'byteLength', { value: byteLength });
+ });
+
+ try {
+ const normalized = normalizeGraphHistory([
+ {
+ createdAt: '2026-07-19T00:00:00.000Z',
+ document: { edges: [], nodes: [], version: 1 as const },
+ id: 'oversized',
+ label: 'Forged low byte count',
+ retainedBytes: 0,
+ },
+ {
+ createdAt: '2026-07-19T00:00:01.000Z',
+ document: { edges: [], nodes: [], version: 1 as const },
+ id: 'within-budget',
+ label: 'Forged high byte count',
+ retainedBytes: GRAPH_HISTORY_BYTE_BUDGET + 1,
+ },
+ ]);
- const legacy = normalizeGraphHistory([{ ...entries[0], retainedBytes: undefined }]);
- expect(legacy[0]?.retainedBytes).toBeGreaterThan(0);
+ expect(normalized).toHaveLength(1);
+ expect(normalized[0]).toMatchObject({ id: 'within-budget', retainedBytes: 128 });
+ } finally {
+ encode.mockRestore();
+ }
+ });
+
+ it('admits newest graph-history entries without exceeding the cumulative byte budget', () => {
+ const halfBudgetPlusOne = Math.floor(GRAPH_HISTORY_BYTE_BUDGET / 2) + 1;
+ const encode = vi.spyOn(TextEncoder.prototype, 'encode').mockImplementation((input) => {
+ const byteLength = String(input).includes('"id":"small"') ? 128 : halfBudgetPlusOne;
+
+ return Object.defineProperty(new Uint8Array(0), 'byteLength', { value: byteLength });
+ });
+
+ try {
+ const createEntry = (id: string) => ({
+ createdAt: '2026-07-19T00:00:00.000Z',
+ document: { edges: [], nodes: [], version: 1 as const },
+ id,
+ label: id,
+ retainedBytes: 0,
+ });
+ const normalized = normalizeGraphHistory([
+ createEntry('newest-large'),
+ createEntry('older-large'),
+ createEntry('small'),
+ ]);
+
+ expect(normalized.map((entry) => entry.id)).toEqual(['newest-large', 'small']);
+ expect(normalized.reduce((total, entry) => total + (entry.retainedBytes ?? 0), 0)).toBeLessThanOrEqual(
+ GRAPH_HISTORY_BYTE_BUDGET
+ );
+ } finally {
+ encode.mockRestore();
+ }
});
it('does not queue Upscale while its required settings are incomplete', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 266be41b4e..e0ac5798b6 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -841,21 +841,48 @@ const getGraphHistorySnapshotBytes = (snapshot: GraphHistorySnapshot): number =>
}
};
-const withRetainedBytes = (snapshot: GraphHistorySnapshot): GraphHistorySnapshot => ({
+type MeasuredGraphHistorySnapshot = GraphHistorySnapshot & { retainedBytes: number };
+
+const withRetainedBytes = (snapshot: GraphHistorySnapshot): MeasuredGraphHistorySnapshot => ({
...snapshot,
retainedBytes: getGraphHistorySnapshotBytes(snapshot),
});
+/** Trims state-owned snapshots without reserializing retained history. */
+const trimMeasuredGraphHistory = (snapshots: readonly GraphHistorySnapshot[]): GraphHistorySnapshot[] => {
+ const history: GraphHistorySnapshot[] = [];
+ let retainedBytes = 0;
+
+ for (const snapshot of snapshots) {
+ if (history.length >= HISTORY_LIMIT) {
+ break;
+ }
+
+ const snapshotBytes = snapshot.retainedBytes;
+ if (typeof snapshotBytes !== 'number' || !Number.isFinite(snapshotBytes) || snapshotBytes < 0) {
+ continue;
+ }
+
+ if (snapshotBytes > GRAPH_HISTORY_BYTE_BUDGET || retainedBytes + snapshotBytes > GRAPH_HISTORY_BYTE_BUDGET) {
+ continue;
+ }
+
+ retainedBytes += snapshotBytes;
+ history.push(snapshot);
+ }
+
+ return history;
+};
+
export const normalizeGraphHistory = (value: unknown): GraphHistorySnapshot[] => {
if (!Array.isArray(value)) {
return [];
}
- const history: GraphHistorySnapshot[] = [];
- let retainedBytes = 0;
+ const measuredHistory: MeasuredGraphHistorySnapshot[] = [];
for (const item of value) {
- if (history.length >= HISTORY_LIMIT || !item || typeof item !== 'object') {
+ if (!item || typeof item !== 'object') {
continue;
}
@@ -868,31 +895,21 @@ export const normalizeGraphHistory = (value: unknown): GraphHistorySnapshot[] =>
continue;
}
- const normalized =
- typeof snapshot.retainedBytes === 'number' &&
- Number.isFinite(snapshot.retainedBytes) &&
- snapshot.retainedBytes >= 0
- ? snapshot
- : withRetainedBytes(snapshot);
- const snapshotBytes = normalized.retainedBytes ?? 0;
-
- if (snapshotBytes > GRAPH_HISTORY_BYTE_BUDGET || retainedBytes + snapshotBytes > GRAPH_HISTORY_BYTE_BUDGET) {
- continue;
- }
-
- retainedBytes += snapshotBytes;
- history.push(normalized);
+ // Persisted metadata is untrusted. Always derive the retained size from the
+ // actual snapshot so a forged low count cannot bypass the load-time budget
+ // and a stale high count cannot discard valid history.
+ measuredHistory.push(withRetainedBytes(snapshot));
}
- return history;
+ return trimMeasuredGraphHistory(measuredHistory);
};
const prependGraphHistory = (
history: readonly GraphHistorySnapshot[],
- snapshot: GraphHistorySnapshot
-): GraphHistorySnapshot[] => normalizeGraphHistory([snapshot, ...history]);
+ snapshot: MeasuredGraphHistorySnapshot
+): GraphHistorySnapshot[] => trimMeasuredGraphHistory([snapshot, ...history]);
-const createGraphHistorySnapshot = (label: string, graph: GraphContract): GraphHistorySnapshot =>
+const createGraphHistorySnapshot = (label: string, graph: GraphContract): MeasuredGraphHistorySnapshot =>
withRetainedBytes({
createdAt: now(),
graph: cloneGraph(graph),
@@ -905,7 +922,7 @@ const createDocumentHistorySnapshot = (
label: string,
document: ProjectGraphState,
cloneDocument = true
-): GraphHistorySnapshot =>
+): MeasuredGraphHistorySnapshot =>
withRetainedBytes({
createdAt: now(),
document: cloneDocument ? cloneProjectGraph(document) : document,