Skip to content

Stop copying the whole drawing on every stroke - #5

Open
Sehaan-1 wants to merge 1 commit into
junosapollo:mainfrom
Sehaan-1:main
Open

Sehaan-1 wants to merge 1 commit into
junosapollo:mainfrom
Sehaan-1:main

Conversation

@Sehaan-1

@Sehaan-1 Sehaan-1 commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

What this does

Every time you committed a stroke, the store was calling structuredClone on the entire drawing document and pushing a full copy onto the undo stack — capped at 500 full-document snapshots. On a document with 200 long strokes the undo stack was holding roughly 100× the raw stroke payload.

This PR replaces that with structural sharing: each history entry records only what changed (the new operation, the layer settings that were updated, the layer that was cleared, etc.), and untouched layers are reused by reference. The document object is still recreated on every commit — autosave and React reactivity are unchanged — but sibling layers, their operation arrays, and every individual operation object are shared across the version chain.


The numbers

Benchmark: 200 strokes × 500 points each, run in Vitest on the updated implementation.

Metric Before After
Per-commit allocation structuredClone(document) ≈ 141 ms × 200 ≈ 28 s of clone work ~0.01 ms/commit
Total commit time (200 strokes) — 3.6 ms
Retained undo memory ~100× raw stroke payload (grows quadratically) 1.0× raw payload (linear)
p95 commit time — 0.034 ms

What changed

New file — apps/web/src/state/documentHistory.ts
Pure helper module with no dependency on the store. Defines the HistoryEntry union (one variant per action kind), byte-weight estimators for budget tracking, �pplyHistoryEntry for applying or reversing any entry, and rimPast / rimFuture which enforce the 500-entry and 32 MiB budgets.

Rewritten — apps/web/src/state/documentStore.ts
past and future now hold HistoryEntry instead of DrawingDocument. A new commitEntry helper applies an entry forward and pushes it; undo/
edo apply it in reverse/forward and move it between stacks. structuredClone now appears in exactly two places:
eplaceDocument (an ownership boundary — the incoming document may be shared with import code) and the onCommand snapshot, which is now gated so normal drawing pays zero clone cost.

apps/web/src/components/CanvasStage.tsx
The append-detection logic used to build an operationIds: string[] array per layer per render and compare IDs. With immutable, structurally-shared operations, object identity is stable and meaningful, so we now compare references directly (operations[index] === operation). No allocation, and the comment that explained why IDs were needed has been updated to explain why they no longer are.

apps/web/src/services/rasterAssets.ts

esolveRasterImages was flat-mapping all operations in every layer on every document.layers change — including pure-vector commits that touch no raster data. Added a WeakMap<DrawingOperation[], string[]> cache keyed by the operations array. A commit changes only the active layer's array, so three of the four layers get cache hits and only the changed layer is scanned.


Tests

  • ** all passing**
  • TypeScript clean
  • New documentHistory.test.ts — 12 tests covering every entry kind, byte estimates, trimming edge cases
  • documentStore.test.ts extended with structural-sharing invariant tests and round-trip equivalence (40-action sequence, undo all, redo all, new edit clears future) and a store-vs-replay equivalence test
  • New documentStore.perf.test.ts — deterministic byte/reference assertions (not timing-flaky); logs p50/p95/total/bytes on every CI run
  • All existing CanvasStage.test.tsx and
    RecordingValidation.test.ts assertions stay green without weakening

What this doesn't change

  • Autosave still writes a full document to IndexedDB — incremental persistence is a separate follow-up
  • Search snapshots still post the whole document to the worker — another follow-up
  • The recorder's DocumentCommand semantics are unchanged; replay produces identical results
  • The 500-entry count cap is preserved; a 32 MiB soft byte budget is added on top

Replace full-document undo snapshots with reversible history entries and
stop cloning the document on every commit. Retained history now tracks
changed layers only, with 500-entry and 32 MiB budgets.

- add documentHistory with entry model, apply/trim helpers
- rewrite documentStore actions around entries; gate recorder clone
- compare operation references in CanvasStage append detection
- cache raster asset ids per operations array
- add history, perf, and raster asset tests
@Sehaan-1
Sehaan-1 requested a review from junosapollo November 1, 2026 10:49
@Sehaan-1 Sehaan-1 self-assigned this Nov 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant