AI-native design editor. Open-source Figma alternative.
perf(canvas): bound the vector path caches and free uncached stroke outlines (#1217)
LarryBambelled9c0caacd074
diff --git a/changes/1217/performance.md b/changes/1217/performance.mdnew file mode 100644index 000000000..061b78eb4--- /dev/null+++ b/changes/1217/performance.md@@ -0,0 +1 @@+- Large documents keep a bounded amount of vector path memory, and drawing vectors no longer leaks memory on every edit or frame.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex c06663021..f8be4f99d 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -78,6 +78,8 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.- Bounded rendering caches share `packages/core/src/cache/resource.ts` for recency, count/weight accounting, and removal disposal. Domain adapters own keys, font/page/dependency invalidation, and sizing units; use non-touching `peek()` for FIFO or planning reads. Rejected insertions leave ownership with the caller.- Keep weak memos, async request registries, pools, and dependency-owned picture/path maps on their distinct lifetime policies.+- CanvasKit path caches are built with `createPathCache` and weighed by points; node paths live in the renderer's `NodePathCaches`, whose `store` keeps a path too large to cache until the next frame or export starts (`packages/core/tests/canvas/paths/cache.test.ts`).+- Set fill types on the detached `Path`, never on a `PathBuilder`: in CanvasKit 0.41 `PathBuilder.setFillType` returns an undeleted copy of the builder (`packages/core/src/vector/index.ts`).- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph/inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.- Text lays out through `buildParagraph` into a `TextLayout` (`packages/core/src/canvas/text/layout/`): one native paragraph for plain text, or one per paragraph with its list indent, marker, and spacing, since Skia has no hanging indent. Drawing, measurement, the text editor, saved glyphs (`shapeText`), and text outlines all read that layout rather than laying text out again (`packages/core/tests/canvas/text/lists.test.ts`).diff --git a/packages/core/src/cache/resource.ts b/packages/core/src/cache/resource.tsindex bef9e22ae..f19e37165 100644--- a/packages/core/src/cache/resource.ts+++ b/packages/core/src/cache/resource.ts@@ -120,6 +120,14 @@ export class ResourceCache<K, V> {return true}+ /** Deletes every entry `predicate` selects, disposing each as a delete. */+ deleteWhere(predicate: (value: V, key: K) => boolean): void {+ const selected: number[] = []+ for (const [key, index] of this.index)+ if (predicate(this.slot(index).value, key)) selected.push(index)+ this.dispose(selected.map((index) => ({ slot: this.remove(index), reason: 'delete' as const })))+ }+clear(): void {const slots = this.slotsthis.index.clear()diff --git a/packages/core/src/canvas/paths/cache.ts b/packages/core/src/canvas/paths/cache.tsnew file mode 100644index 000000000..6f3e27b3c--- /dev/null+++ b/packages/core/src/canvas/paths/cache.ts@@ -0,0 +1,101 @@+import type { Path } from 'canvaskit-wasm'++import { ResourceCache } from '#core/cache/resource'++/**+ * Points one node path cache keeps, about 64 MB of CanvasKit heap. A page of 20,000 icons with 100+ * points each takes half of it; a page larger than the cache rebuilds every path on each recording.+ */+export const PATH_CACHE_POINTS = 4_000_000+export const PATH_CACHE_ENTRIES = 65_536+/** Weight of a path beyond its points, so many tiny paths still count against the budget. */+const PATH_OVERHEAD_POINTS = 8++export interface PathCacheLimits {+ maxPoints?: number+ maxEntries?: number+}++type CachedPaths = Path | Path[]++function pathWeight(value: CachedPaths): number {+ if (!Array.isArray(value)) return value.countPoints() + PATH_OVERHEAD_POINTS+ let weight = 0+ for (const path of value) weight += path.countPoints() + PATH_OVERHEAD_POINTS+ return weight+}++function deletePaths(value: CachedPaths): void {+ if (!Array.isArray(value)) value.delete()+ else for (const path of value) path.delete()+}++/** Owns cached paths, weighed by point count; evicted, replaced, and deleted entries delete them. */+export function createPathCache<K = string, V extends CachedPaths = Path[]>({+ maxPoints = PATH_CACHE_POINTS,+ maxEntries = PATH_CACHE_ENTRIES+}: PathCacheLimits = {}): ResourceCache<K, V> {+ return new ResourceCache<K, V>({+ maxEntries,+ maxWeight: maxPoints,+ weight: pathWeight,+ dispose: deletePaths+ })+}++export type NodePathCache = ResourceCache<string, Path[]>++/**+ * The paths a renderer builds for each node, keyed by node id (stroke outlines by `<nodeId>|…`).+ * Paths a cache rejects as larger than its whole budget stay here until `releaseUncached`, which+ * runs when a frame or an export starts, so callers can draw them now without leaking them.+ */+export class NodePathCaches {+ readonly vector: NodePathCache+ readonly vectorStroke: NodePathCache+ readonly strokeOutline: NodePathCache+ readonly fillGeometry: NodePathCache+ readonly strokeGeometry: NodePathCache+ private readonly caches: readonly NodePathCache[]+ private uncached: Path[][] = []++ constructor(limits: PathCacheLimits = {}) {+ this.vector = createPathCache(limits)+ this.vectorStroke = createPathCache(limits)+ this.strokeOutline = createPathCache(limits)+ this.fillGeometry = createPathCache(limits)+ this.strokeGeometry = createPathCache(limits)+ this.caches = [+ this.vector,+ this.vectorStroke,+ this.strokeOutline,+ this.fillGeometry,+ this.strokeGeometry+ ]+ }++ /** Stores paths built for drawing; the caller borrows them until the next `releaseUncached`. */+ store(cache: NodePathCache, key: string, paths: Path[]): void {+ if (!cache.set(key, paths)) this.uncached.push(paths)+ }++ /** Deletes every path built for a node. */+ invalidate(nodeId: string): void {+ for (const cache of this.caches) cache.delete(nodeId)+ const outlinePrefix = `${nodeId}|`+ this.strokeOutline.deleteWhere((_, key) => key.startsWith(outlinePrefix))+ }++ /** Deletes the paths `store` could not cache. */+ releaseUncached(): void {+ const uncached = this.uncached+ if (uncached.length === 0) return+ this.uncached = []+ for (const paths of uncached) deletePaths(paths)+ }++ clear(): void {+ for (const cache of this.caches) cache.clear()+ this.releaseUncached()+ }+}diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex ea8a3a16e..393a2c271 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -30,6 +30,7 @@ import { LabelCache } from './labels/cache'import * as LabelHitTest from './labels/hit-test'import { LabelParagraphCache } from './labels/paragraph-cache'import { labelHitOptions } from './labels/style'+import { NodePathCaches } from './paths/cache'import * as RenderColors from './renderer/colors'import * as RendererFonts from './renderer/fonts'import { destroyRenderer, releaseLiveImages } from './renderer/lifecycle'@@ -142,11 +143,7 @@ export class SkiaRenderer {imageMemoryPage: string | null = nullonImagePreviewReady: (() => void) | null = nullreadonly imagePreviews = new ImagePreviewCache(() => this.onImagePreviewReady?.())- vectorPathCache = new Map<string, Path[]>()- vectorStrokePathCache = new Map<string, Path[]>()- vectorStrokeOutlineCache = new Map<string, Path[]>()- fillGeometryCache = new Map<string, Path[]>()- strokeGeometryCache = new Map<string, Path[]>()+ nodePaths = new NodePathCaches()/** Path-text glyph silhouettes (stroke-and-union, font units) keyed by blob hash + relative weight. */glyphSilhouetteCache = createGlyphSilhouetteCache()derivedGlyphPathCache = createDerivedGlyphPathCache()@@ -759,24 +756,7 @@ export class SkiaRenderer {}invalidateVectorPath(nodeId: string): void {- for (const cache of [this.vectorPathCache, this.vectorStrokePathCache]) {- const old = cache.get(nodeId)- if (!old) continue- for (const p of old) p.delete()- cache.delete(nodeId)- }- for (const [key, paths] of this.vectorStrokeOutlineCache) {- if (!key.startsWith(`${nodeId}|`)) continue- for (const p of paths) p.delete()- this.vectorStrokeOutlineCache.delete(key)- }- for (const cache of [this.fillGeometryCache, this.strokeGeometryCache]) {- const oldGeom = cache.get(nodeId)- if (oldGeom) {- for (const p of oldGeom) p.delete()- cache.delete(nodeId)- }- }+ this.nodePaths.invalidate(nodeId)}measureTextNode(node: SceneNode, maxWidth?: number): { width: number; height: number } | null {diff --git a/packages/core/src/canvas/renderer/effect-raster-cache.ts b/packages/core/src/canvas/renderer/effect-raster-cache.tsindex ace53d505..435e06fc3 100644--- a/packages/core/src/canvas/renderer/effect-raster-cache.ts+++ b/packages/core/src/canvas/renderer/effect-raster-cache.ts@@ -32,9 +32,7 @@ export class EffectRasterCache extends ResourceCache<string, EffectRasterCacheEn}deleteDependencies(nodeId: string): void {- for (const [ownerId, entry] of this) {- if (entry.dependencyIds.includes(nodeId)) this.delete(ownerId)- }+ this.deleteWhere((entry) => entry.dependencyIds.includes(nodeId))}}diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.tsindex 103ac9fa0..04f579819 100644--- a/packages/core/src/canvas/renderer/lifecycle.ts+++ b/packages/core/src/canvas/renderer/lifecycle.ts@@ -11,18 +11,7 @@ function clearRetainedSceneState(r: SkiaRenderer): void {}function disposePathCaches(r: SkiaRenderer): void {- for (const cache of [- r.vectorPathCache,- r.vectorStrokePathCache,- r.vectorStrokeOutlineCache,- r.fillGeometryCache,- r.strokeGeometryCache- ]) {- for (const paths of cache.values()) {- for (const p of paths) p.delete()- }- cache.clear()- }+ r.nodePaths.clear()r.glyphSilhouetteCache.clear()r.derivedGlyphPathCache.clear()}diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex be3562690..073a2a443 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -14,11 +14,12 @@ import { renderSceneBacking, updateSceneBackingPreviewState } from './retained-bimport { hasTransientPreviews, renderPageWithPreviews } from './transient-previews'export function renderSceneToCanvas(- r: Pick<SkiaRenderer, 'worldViewport' | 'viewportImageRendering' | 'renderNode'>,+ r: Pick<SkiaRenderer, 'worldViewport' | 'viewportImageRendering' | 'renderNode' | 'nodePaths'>,canvas: Canvas,graph: SceneGraph,pageId: string): void {+ r.nodePaths.releaseUncached()const prevViewport = r.worldViewportconst previewMode = r.viewportImageRenderingr.viewportImageRendering = false@@ -234,6 +235,7 @@ export function render(zoom: r.zoom})r.syncFontGeneration()+ r.nodePaths.releaseUncached()const p = r.profilerp.beginFrame()p.setScenePictureDrawTime(0)diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex df2bfc19c..537ea028a 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -655,7 +655,7 @@ function drawVectorStrokeGeometry(function vectorStrokePaths(r: SkiaRenderer, node: SceneNode): Path[] | null {if (!node.vectorNetwork) return null- const cached = r.vectorStrokePathCache.get(node.id)+ const cached = r.nodePaths.vectorStroke.get(node.id)if (cached) return cached// A path per run, so the corners inside a run join and only its open ends take caps.@@ -667,10 +667,19 @@ function vectorStrokePaths(r: SkiaRenderer, node: SceneNode): Path[] | null {})if (paths.length === 0) return null- r.vectorStrokePathCache.set(node.id, paths)+ r.nodePaths.store(r.nodePaths.vectorStroke, node.id, paths)return paths}+/** Stroke outlines are cached under `<nodeId>|…`, which `NodePathCaches.invalidate` removes. */+function strokeOutlineKey(+ node: SceneNode,+ stroke: SceneNode['strokes'][0],+ source: 'runs' | 'regions'+): string {+ return `${node.id}|${source}|${stroke.weight}|${stroke.cap ?? node.strokeCap}|${stroke.join ?? node.strokeJoin}|${node.strokeMiterLimit}`+}+function drawVectorPathStrokes(r: SkiaRenderer,canvas: Canvas,@@ -704,16 +713,20 @@ function drawVectorPathStrokes(r.fillPaint.setColor(r.ck.Color4f(sc.r, sc.g, sc.b, sc.a))r.fillPaint.setAlphaf(stroke.opacity)- let outlines = outlineCacheKey ? r.vectorStrokeOutlineCache.get(outlineCacheKey) : undefined- if (!outlines) {- outlines = []- for (const vp of vectorPaths) {- const outline = vp.makeStroked(strokeOpts)- if (outline) outlines.push(outline)- }- if (outlineCacheKey) r.vectorStrokeOutlineCache.set(outlineCacheKey, outlines)+ const cached = outlineCacheKey ? r.nodePaths.strokeOutline.get(outlineCacheKey) : undefined+ if (cached) {+ for (const outline of cached) canvas.drawPath(outline, r.fillPaint)+ return+ }+ const outlines: Path[] = []+ for (const vp of vectorPaths) {+ const outline = vp.makeStroked(strokeOpts)+ if (outline) outlines.push(outline)}for (const outline of outlines) canvas.drawPath(outline, r.fillPaint)+ // Drawing copies the outline, so one without a cache key is done with here.+ if (outlineCacheKey) r.nodePaths.store(r.nodePaths.strokeOutline, outlineCacheKey, outlines)+ else for (const outline of outlines) outline.delete()}function drawRegularStroke(@@ -758,13 +771,14 @@ function drawNodeStroke(node.type === 'VECTOR' &&!node.fills.some((fill) => fill.visible)if (shouldStrokeVectorCenterline) {- const outlineKey = `${node.id}|${stroke.weight}|${stroke.cap ?? node.strokeCap}|${stroke.join ?? node.strokeJoin}|${node.strokeMiterLimit}`+ const outlineKey = strokeOutlineKey(node, stroke, 'runs')drawVectorPathStrokes(r, canvas, vectorStroke, stroke, sc, node.strokeMiterLimit, outlineKey)return}if (!sg) {if (vectorPaths) {- drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, node.strokeMiterLimit)+ const outlineKey = strokeOutlineKey(node, stroke, 'regions')+ drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, node.strokeMiterLimit, outlineKey)} else drawRegularStroke(r, canvas, node, rect, hasRadius, stroke, sc)return}diff --git a/packages/core/src/canvas/shapes.ts b/packages/core/src/canvas/shapes.tsindex a9d8ef593..bdf2301cf 100644--- a/packages/core/src/canvas/shapes.ts+++ b/packages/core/src/canvas/shapes.ts@@ -526,31 +526,31 @@ export function clipNodeShape(export function getVectorPaths(r: SkiaRenderer, node: SceneNode): Path[] | null {if (!node.vectorNetwork) return null- const cached = r.vectorPathCache.get(node.id)+ const cached = r.nodePaths.vector.get(node.id)if (cached) return cachedconst paths = vectorNetworkToPath(r.ck, node.vectorNetwork)- r.vectorPathCache.set(node.id, paths)+ r.nodePaths.store(r.nodePaths.vector, node.id, paths)return paths}export function getFillGeometry(r: SkiaRenderer, node: SceneNode): Path[] | null {if (node.fillGeometry.length === 0) return null- const cached = r.fillGeometryCache.get(node.id)+ const cached = r.nodePaths.fillGeometry.get(node.id)if (cached) return cachedconst paths = node.fillGeometry.map((g) =>geometryBlobToPath(r.ck, g.commandsBlob, g.windingRule))- r.fillGeometryCache.set(node.id, paths)+ r.nodePaths.store(r.nodePaths.fillGeometry, node.id, paths)return paths}export function getStrokeGeometry(r: SkiaRenderer, node: SceneNode): Path[] | null {if (node.strokeGeometry.length === 0) return null- const cached = r.strokeGeometryCache.get(node.id)+ const cached = r.nodePaths.strokeGeometry.get(node.id)if (cached) return cachedconst paths = node.strokeGeometry.map((g) =>geometryBlobToPath(r.ck, g.commandsBlob, g.windingRule))- r.strokeGeometryCache.set(node.id, paths)+ r.nodePaths.store(r.nodePaths.strokeGeometry, node.id, paths)return paths}diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.tsindex c31ba89c1..5920cab9a 100644--- a/packages/core/src/canvas/text/derived.ts+++ b/packages/core/src/canvas/text/derived.ts@@ -13,7 +13,8 @@ import {type TextParagraphRange} from '@open-pencil/scene-graph'-import { ResourceCache } from '#core/cache/resource'+import type { ResourceCache } from '#core/cache/resource'+import { createPathCache } from '#core/canvas/paths/cache'import type { SkiaRenderer } from '#core/canvas/renderer'import {drawTextDecorations,@@ -28,10 +29,7 @@ const MAX_DERIVED_GLYPH_PATHS = 16384/** Decoded saved glyph outlines, by the glyph's command bytes, which a node keeps until it changes. */export function createDerivedGlyphPathCache(): ResourceCache<Uint8Array, Path> {- return new ResourceCache({- maxEntries: MAX_DERIVED_GLYPH_PATHS,- dispose: (path) => path.delete()- })+ return createPathCache({ maxEntries: MAX_DERIVED_GLYPH_PATHS })}/** A saved glyph's outline, decoded once and borrowed from the renderer's cache. */@@ -44,7 +42,7 @@ function derivedGlyphPath(r: SkiaRenderer, blob: Uint8Array): Path {}export function createGlyphSilhouetteCache(): ResourceCache<string, Path> {- return new ResourceCache({ maxEntries: MAX_GLYPH_SILHOUETTES, dispose: (path) => path.delete() })+ return createPathCache({ maxEntries: MAX_GLYPH_SILHOUETTES })}export function snapDerivedGlyphBaseline(y: number): number {diff --git a/packages/core/src/vector/index.ts b/packages/core/src/vector/index.tsindex 663b258a1..d15317991 100644--- a/packages/core/src/vector/index.ts+++ b/packages/core/src/vector/index.ts@@ -28,6 +28,14 @@ export { vectorNetworkToCenterlinePath, fitCircleArc, isClosedThinCrescent } froexport { regenerateFillGeometry } from './fill-geometry'export { addStrokeRunToPath, strokeRuns, type StrokeRun } from './path-helpers'+/**+ * Fill types go on the detached `Path`: CanvasKit 0.41's `PathBuilder.setFillType` returns an+ * undeleted copy of the builder, which leaks about 860 bytes per call.+ */+function fillType(ck: CanvasKit, windingRule: WindingRule) {+ return windingRule === 'EVENODD' ? ck.FillType.EvenOdd : ck.FillType.Winding+}+export function vectorNetworkToPath(ck: CanvasKit, network: VectorNetwork): Path[] {const { vertices, segments, regions } = network@@ -40,10 +48,9 @@ export function vectorNetworkToPath(ck: CanvasKit, network: VectorNetwork): Pathfor (const segmentIndex of loop) regionSegmentIndexes.add(segmentIndex)addLoopToPath(regionPath, loop, segments, vertices)}- regionPath.setFillType(- region.windingRule === 'EVENODD' ? ck.FillType.EvenOdd : ck.FillType.Winding- )- paths.push(regionPath.detachAndDelete())+ const path = regionPath.detachAndDelete()+ path.setFillType(fillType(ck, region.windingRule))+ paths.push(path)}const openSegments = segments.filter((_, index) => !regionSegmentIndexes.has(index))@@ -121,6 +128,7 @@ export function geometryBlobToPath(}}- path.setFillType(windingRule === 'EVENODD' ? ck.FillType.EvenOdd : ck.FillType.Winding)- return path.detachAndDelete()+ const result = path.detachAndDelete()+ result.setFillType(fillType(ck, windingRule))+ return result}diff --git a/packages/core/tests/canvas/paths/cache.test.ts b/packages/core/tests/canvas/paths/cache.test.tsnew file mode 100644index 000000000..5d09baf96--- /dev/null+++ b/packages/core/tests/canvas/paths/cache.test.ts@@ -0,0 +1,161 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'+import type { Path } from 'canvaskit-wasm'++import { SceneGraph, type Stroke } from '@open-pencil/scene-graph'++import { SkiaRenderer } from '#core/canvas'+import { createPathCache, NodePathCaches } from '#core/canvas/paths/cache'+import { render, renderSceneToCanvas } from '#core/canvas/renderer/pipeline'+import { initCanvasKit } from '#core/io'++const ck = await initCanvasKit()++function linePath(points: number): Path {+ const builder = new ck.PathBuilder()+ builder.moveTo(0, 0)+ for (let i = 1; i < points; i++) builder.lineTo(i, i % 2)+ return builder.detachAndDelete()+}++const STROKE: Stroke = {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ weight: 1,+ opacity: 1,+ visible: true,+ align: 'CENTER'+}++function triangles(count: number, strokes: Stroke[] = []) {+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0], 'default page')+ const ids: string[] = []+ for (let i = 0; i < count; i++) {+ const node = graph.createNode('VECTOR', page.id, {+ x: (i % 20) * 10,+ y: Math.floor(i / 20) * 10,+ width: 8,+ height: 8,+ fills: [+ { type: 'SOLID', color: { r: 0.2, g: 0.4, b: 0.8, a: 1 }, opacity: 1, visible: true }+ ],+ strokes,+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: 8, y: 0 },+ { x: 8, y: 8 }+ ],+ segments: [0, 1, 2].map((start) => ({+ start,+ end: (start + 1) % 3,+ tangentStart: { x: 0, y: 0 },+ tangentEnd: { x: 0, y: 0 }+ })),+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]] }]+ }+ })+ ids.push(node.id)+ }+ return { graph, pageId: page.id, ids }+}++function withRenderer(pageId: string, run: (renderer: SkiaRenderer) => void) {+ const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(256, 256), 'surface'))+ renderer.viewportWidth = 256+ renderer.viewportHeight = 256+ renderer.pageId = pageId+ renderer.pageColor = { r: 1, g: 1, b: 1, a: 1 }+ try {+ run(renderer)+ } finally {+ renderer.destroy()+ }+}++describe('path cache', () => {+ test('evicts the least recently used paths by point count and deletes them', () => {+ const cache = createPathCache({ maxPoints: 40 })+ const [a, b, c] = [linePath(10), linePath(10), linePath(10)]+ cache.set('a', [a])+ cache.set('b', [b])+ cache.get('a')+ cache.set('c', [c])+ expect(cache.weight).toBeLessThanOrEqual(40)+ expect([...cache].map(([key]) => key)).toEqual(['a', 'c'])+ expect(b.isDeleted()).toBe(true)+ expect(a.isDeleted()).toBe(false)+ cache.clear()+ expect(a.isDeleted() && c.isDeleted()).toBe(true)+ })++ test('keeps paths larger than a cache until they are released', () => {+ const paths = new NodePathCaches({ maxPoints: 20 })+ const huge = linePath(50)+ paths.store(paths.vector, 'huge', [huge])+ expect(paths.vector.has('huge')).toBe(false)+ expect(huge.isDeleted()).toBe(false)+ paths.releaseUncached()+ expect(huge.isDeleted()).toBe(true)+ })+})++describe('renderer path caches', () => {+ test('stay within their point budget however many vectors are drawn', () => {+ const { graph, pageId } = triangles(200)+ withRenderer(pageId, (renderer) => {+ renderer.nodePaths = new NodePathCaches({ maxPoints: 400 })+ const earliest = [linePath(4)]+ renderer.nodePaths.vector.set('earliest', earliest)+ render(renderer, graph, new Set(), {}, 1, 'scene', true)+ expect(renderer.nodePaths.vector.size).toBeGreaterThan(0)+ expect(renderer.nodePaths.vector.weight).toBeLessThanOrEqual(400)+ expect(earliest.every((path) => path.isDeleted())).toBe(true)+ })+ })++ test('invalidating a vector deletes every path built for it and keeps the others', () => {+ const { pageId, ids } = triangles(2, [STROKE])+ const [edited, other] = ids+ withRenderer(pageId, (renderer) => {+ const { vector, vectorStroke, strokeOutline, fillGeometry, strokeGeometry } =+ renderer.nodePaths+ const caches = [vector, vectorStroke, strokeOutline, fillGeometry, strokeGeometry]+ const built = caches.map((cache) => {+ const paths = [linePath(3)]+ cache.set(cache === strokeOutline ? `${edited}|runs|1|NONE` : edited, paths)+ cache.set(other, [linePath(3)])+ return paths+ })+ renderer.invalidateVectorPath(edited)+ for (const cache of caches) expect([...cache].map(([key]) => key)).toEqual([other])+ expect(built.flat().every((path) => path.isDeleted())).toBe(true)+ })+ })++ test('stroke outlines of filled vectors are built once and reused by later frames', () => {+ const { graph, pageId } = triangles(3, [STROKE])+ withRenderer(pageId, (renderer) => {+ render(renderer, graph, new Set(), {}, 1, 'scene', true)+ const outlines = [...renderer.nodePaths.strokeOutline.values()].flat()+ expect(outlines).toHaveLength(3)+ renderer.invalidateAllPictures()+ render(renderer, graph, new Set(), {}, 2, 'scene', true)+ expect([...renderer.nodePaths.strokeOutline.values()].flat()).toEqual(outlines)+ expect(outlines.some((path) => path.isDeleted())).toBe(false)+ })+ })++ test('an export releases the paths earlier drawing could not cache', () => {+ const { graph, pageId } = triangles(1)+ withRenderer(pageId, (renderer) => {+ renderer.nodePaths = new NodePathCaches({ maxPoints: 20 })+ const huge = linePath(50)+ renderer.nodePaths.store(renderer.nodePaths.fillGeometry, 'huge', [huge])+ renderSceneToCanvas(renderer, renderer.surface.getCanvas(), graph, pageId)+ expect(huge.isDeleted()).toBe(true)+ })+ })+})diff --git a/tests/engine/core/cache/resource.test.ts b/tests/engine/core/cache/resource.test.tsindex 27ebd6bce..7af403214 100644--- a/tests/engine/core/cache/resource.test.ts+++ b/tests/engine/core/cache/resource.test.ts@@ -8,6 +8,33 @@ interface Resource {}describe('ResourceCache', () => {+ test('deleteWhere disposes the selected entries as deletes and keeps the rest', () => {+ const removed: Array<[string, CacheRemovalReason]> = []+ const cache = new ResourceCache<string, Resource>({+ maxEntries: 4,+ dispose: (_, key, reason) => removed.push([key, reason])+ })+ for (const [id, key] of ['a|1', 'a|2', 'b|1'].entries()) cache.set(key, { id, units: 1 })+ cache.deleteWhere((_, key) => key.startsWith('a|'))+ expect([...cache].map(([key]) => key)).toEqual(['b|1'])+ expect(removed).toEqual([+ ['a|1', 'delete'],+ ['a|2', 'delete']+ ])+ })++ test('deleteWhere removes every selected entry even when a disposal throws', () => {+ const cache = new ResourceCache<string, Resource>({+ maxEntries: 4,+ dispose: (value) => {+ if (value.id === 0) throw new Error('dispose failed')+ }+ })+ for (const [id, key] of ['a|1', 'a|2', 'b|1'].entries()) cache.set(key, { id, units: 1 })+ expect(() => cache.deleteWhere((_, key) => key.startsWith('a|'))).toThrow(AggregateError)+ expect([...cache].map(([key]) => key)).toEqual(['b|1'])+ })+test('touches hits but not peeks or iteration, and disposes every removal', () => {const removed: Array<[number, CacheRemovalReason]> = []const cache = new ResourceCache<string, Resource>({diff --git a/tests/engine/render/canvas/raster-export.test.ts b/tests/engine/render/canvas/raster-export.test.tsindex 403fcb9be..89a1b82e1 100644--- a/tests/engine/render/canvas/raster-export.test.ts+++ b/tests/engine/render/canvas/raster-export.test.ts@@ -6,6 +6,7 @@ import { renderNodesToImage, SceneGraph, SkiaRenderer } from '@open-pencil/core'import { getWorldMatrix } from '@open-pencil/scene-graph'import { initCanvasKit } from '#cli/headless'+import { NodePathCaches } from '#core/canvas/paths/cache'import { renderSceneToCanvas } from '#core/canvas/renderer/pipeline'import { prepareSelectionRenderGraph } from '#core/io/formats/raster/render'import { extractExportGraph } from '#core/io/subgraph'@@ -48,6 +49,7 @@ describe('raster export', () => {const renderer = {viewportImageRendering: true,worldViewport: viewport,+ nodePaths: new NodePathCaches(),renderNode() {expect(this.viewportImageRendering).toBe(false)throw new Error('drawing failed')diff --git a/tests/engine/render/canvas/renderer-lifecycle.test.ts b/tests/engine/render/canvas/renderer-lifecycle.test.tsindex b6ab918a6..2d4fb93ba 100644--- a/tests/engine/render/canvas/renderer-lifecycle.test.ts+++ b/tests/engine/render/canvas/renderer-lifecycle.test.ts@@ -4,6 +4,7 @@ import type { Font, Paint, Surface } from 'canvaskit-wasm'import { createImageCache } from '#core/canvas/images/cache'import { ImagePreviewCache } from '#core/canvas/images/previews'+import { NodePathCaches } from '#core/canvas/paths/cache'import type { SkiaRenderer } from '#core/canvas/renderer'import { EffectRasterCache } from '#core/canvas/renderer/effect-raster-cache'import { destroyRenderer } from '#core/canvas/renderer/lifecycle'@@ -25,11 +26,7 @@ function createRenderer() {liveImages: new Map(),imagePreviews: new ImagePreviewCache(() => undefined),onImagePreviewReady: null,- vectorPathCache: new Map(),- vectorStrokePathCache: new Map(),- vectorStrokeOutlineCache: new Map(),- fillGeometryCache: new Map(),- strokeGeometryCache: new Map(),+ nodePaths: new NodePathCaches(),glyphSilhouetteCache: createGlyphSilhouetteCache(),derivedGlyphPathCache: createDerivedGlyphPathCache(),fillPaint: deletable<Paint>(),diff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.tsindex a2b36a4fa..c391a6fd1 100644--- a/tests/engine/render/canvas/text.test.ts+++ b/tests/engine/render/canvas/text.test.ts@@ -86,6 +86,7 @@ function createMockRenderer(overrides: Partial<Record<string, unknown>> = {}) {setFillType = mock(() => this)delete = mock(() => undefined)detachAndDelete = mock(() => ({+ countPoints: mock(() => 0),delete: mock(() => undefined),setFillType: mock(() => undefined)}))