Skip to content

Commit 764f1ea

Browse files
author
Kevin Arthur
committed
fix(memory): ignore stale image decode completions
1 parent 862dd38 commit 764f1ea

5 files changed

Lines changed: 92 additions & 0 deletions

File tree

‎docs/audits/canvas-perf-2026-08-01-part3.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,5 +224,16 @@ worker process or completion result. Only the owned session was interrupted.
224224
That teardown defect remains open as P3-14; the discovery fix must not be
225225
misrepresented as a successful full benchmark run.
226226

227+
## Pending image decode invalidation
228+
229+
Three deterministic async tests reproduced a decoded-image retention race. A
230+
load cancelled before decode completion returned to `loaded` when its stale
231+
promise resolved; `clear()` behaved the same way; and a cancelled first attempt
232+
could overwrite a newer successful retry for the same URL. Each load now owns a
233+
unique identity, and completion/error handlers mutate cache state only while
234+
that identity is still current. Stale callers may still observe their promise
235+
settle, but stale work cannot repopulate the cache or change retained-byte
236+
accounting. All eleven image-cache tests pass.
237+
227238
The live status, risk, evidence, and commit reference for each finding are kept
228239
in [`../perf/findings.md`](../perf/findings.md).

‎docs/perf/findings.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ proposed change has been approved.
2121
| P3-12 | Raw Canvas2D replay becomes the limit only at high visible counts | five current browser runs | rendering | measured | prioritize culling/work reduction before backend replacement | low | p50 0.7/3.6/34.7/138.0 ms at 100/1K/10K/50K | `ff4d5ea9` baseline |
2222
| P3-13 | `pnpm bench` rediscovers benchmark suites under unrelated `.worktrees` | live benchmark run entered `.worktrees/export-infrastructure` after root suites | benchmark/QA | verified | exclude `.worktrees` in shared Vitest discovery | low | normal/bench collection: 891/898 files, zero worktree files | benchmark-isolation milestone |
2323
| P3-14 | `pnpm bench` can hang during runner teardown after benchmark CPU work stops | isolated rerun remained attached with no matching worker or CPU process | benchmark/QA | reproducing | isolate the suite and runner lifecycle responsible before changing timeouts | low | session required owned-session interrupt after root-only discovery | — |
24+
| P3-15 | Cancelled or cleared image decodes can finish late and repopulate retained cache memory | three failing async race tests | memory | verified | bind cache mutation to the current per-URL load identity | low | cancel, retry race, and clear retain zero stale bytes | image-cache race milestone |
2425

2526
## Rejected or constrained hypotheses
2627

‎docs/perf/ledger.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,8 @@ configuration. Normal and benchmark-config collection report 891 and 898 files
263263
respectively, with zero worktree paths. The subsequent root-only `pnpm bench`
264264
run stopped consuming CPU but did not return from runner teardown; that is
265265
tracked separately and the full command is not recorded as passing.
266+
267+
Pending image decode invalidation was also hardened. Failing tests demonstrated
268+
that cancel, clear, and cancel-then-retry could all be undone by late promise
269+
completion. Per-load identities now prevent stale completions from mutating the
270+
cache or retained-byte accounting; the focused image-cache suite passes 11/11.

‎packages/engine/src/imageCache.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,68 @@ describe('ImageCache memory budget', () => {
165165
expect(cache.has('large')).toBe(false);
166166
});
167167
});
168+
169+
describe('ImageCache pending-load invalidation', () => {
170+
let originalImage: typeof Image;
171+
172+
beforeEach(() => {
173+
originalImage = globalThis.Image;
174+
globalThis.Image = MockImage as unknown as typeof Image;
175+
});
176+
177+
afterEach(() => {
178+
globalThis.Image = originalImage;
179+
});
180+
181+
it('does not repopulate the cache when a cancelled decode finishes late', async () => {
182+
const created: MockImage[] = [];
183+
MockImage.dispatch = (img) => created.push(img);
184+
185+
const cache = new ImageCache();
186+
const pending = cache.load('data:image/png;base64,cancelled');
187+
await Promise.resolve();
188+
189+
cache.cancel('data:image/png;base64,cancelled');
190+
created[0]?.onload?.();
191+
await pending;
192+
193+
expect(cache.isLoaded('data:image/png;base64,cancelled')).toBe(false);
194+
expect(cache.stats.bytes).toBe(0);
195+
});
196+
197+
it('does not let an older cancelled decode overwrite a successful retry', async () => {
198+
const created: MockImage[] = [];
199+
MockImage.dispatch = (img) => created.push(img);
200+
201+
const cache = new ImageCache();
202+
const first = cache.load('data:image/png;base64,retry');
203+
await Promise.resolve();
204+
cache.cancel('data:image/png;base64,retry');
205+
206+
const second = cache.load('data:image/png;base64,retry');
207+
await Promise.resolve();
208+
created[1]?.onload?.();
209+
const secondImage = await second;
210+
created[0]?.onload?.();
211+
await first;
212+
213+
expect(cache.getImage('data:image/png;base64,retry')).toBe(secondImage);
214+
expect(cache.stats.bytes).toBe(100 * 100 * 4);
215+
});
216+
217+
it('does not repopulate the cache when clear races a pending decode', async () => {
218+
const created: MockImage[] = [];
219+
MockImage.dispatch = (img) => created.push(img);
220+
221+
const cache = new ImageCache();
222+
const pending = cache.load('data:image/png;base64,cleared');
223+
await Promise.resolve();
224+
225+
cache.clear();
226+
created[0]?.onload?.();
227+
await pending;
228+
229+
expect(cache.has('data:image/png;base64,cleared')).toBe(false);
230+
expect(cache.stats.bytes).toBe(0);
231+
});
232+
});

‎packages/engine/src/imageCache.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const DEFAULT_MAX_BYTES = 256 * 1024 * 1024;
3636
export class ImageCache {
3737
private cache = new Map<string, ImageCacheEntry>();
3838
private pending = new Map<string, Promise<HTMLImageElement>>();
39+
private loadTokens = new Map<string, symbol>();
3940
private listeners = new Map<string, Set<() => void>>();
4041
private globalListeners = new Set<() => void>();
4142
private maxEntries: number;
@@ -183,6 +184,8 @@ export class ImageCache {
183184

184185
// Mark as loading
185186
this.cache.set(url, { state: 'loading', image: null });
187+
const loadToken = Symbol(url);
188+
this.loadTokens.set(url, loadToken);
186189

187190
const isInline = url.startsWith('data:') || url.startsWith('blob:');
188191

@@ -204,9 +207,11 @@ export class ImageCache {
204207
// Inline data:/blob: URLs are always same-origin, so skip the CORS dance.
205208
const promise = (isInline ? attempt(false) : attempt(true).catch(() => attempt(false)))
206209
.then((img) => {
210+
if (this.loadTokens.get(url) !== loadToken) return img;
207211
const bytes = this.estimateBytes(img);
208212
this.cache.set(url, { state: 'loaded', image: img });
209213
this.pending.delete(url);
214+
this.loadTokens.delete(url);
210215
this.touch(url);
211216
this.entryBytes.set(url, bytes);
212217
this.retainedBytes += bytes;
@@ -222,9 +227,11 @@ export class ImageCache {
222227
return img;
223228
})
224229
.catch((error: Error) => {
230+
if (this.loadTokens.get(url) !== loadToken) throw error;
225231
this.cache.set(url, { state: 'error', image: null, error });
226232
this.evictIfNeeded();
227233
this.pending.delete(url);
234+
this.loadTokens.delete(url);
228235
this.touch(url);
229236
this.notifyListeners(url);
230237
throw error;
@@ -253,6 +260,7 @@ export class ImageCache {
253260
*/
254261
cancel(url: string): void {
255262
this.pending.delete(url);
263+
this.loadTokens.delete(url);
256264
const existing = this.cache.get(url);
257265
if (existing?.state === 'loading') {
258266
this.cache.set(url, { state: 'idle', image: null });
@@ -262,13 +270,15 @@ export class ImageCache {
262270
/** Remove an entry from the cache. */
263271
evict(url: string): void {
264272
this.pending.delete(url);
273+
this.loadTokens.delete(url);
265274
this.remove(url, false);
266275
}
267276

268277
/** Clear all cached images. */
269278
clear(): void {
270279
this.cache.clear();
271280
this.pending.clear();
281+
this.loadTokens.clear();
272282
this.entryBytes.clear();
273283
this.accessTimes.clear();
274284
this.retainedBytes = 0;

0 commit comments

Comments
 (0)