fix: release replaced pierre snippet mounts and isolate benchmark backends

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-04 19:44:32 +01:00
co-authored by Claude Opus 5.5
parent 2684c08c8d
commit 3aff744bfa
5 changed files with 134 additions and 56 deletions
@@ -1,27 +1,65 @@
import { mount, unmount, type Snippet } from 'svelte'
import SnippetHost from './SnippetHost.svelte'
type Entry = { target: HTMLElement; component?: Record<string, any>; seen: boolean; frames: number }
// Pierre may build an element and drop it in the same pass without inserting it.
const MAX_UNSEEN_FRAMES = 10
/**
* Pierre's render callbacks return detached DOM nodes. This mounts a Svelte snippet into one
* and keeps every mount so the owner can unmount them all when it is destroyed.
* Pierre's render callbacks return detached DOM nodes and later remove them without telling
* the caller. This mounts a Svelte snippet into each one and unmounts it once its node has
* left the document, checked on the frame after a render so a node Pierre detaches and
* reinserts within one render is kept.
*/
export function snippetElements() {
const mounted: Record<string, any>[] = []
const entries = new Set<Entry>()
let destroyed = false
let sweepScheduled = false
function drop(entry: Entry) {
if (entry.component) unmount(entry.component)
entries.delete(entry)
}
function sweep() {
sweepScheduled = false
if (destroyed) return
let pending = false
for (const entry of entries) {
if (entry.target.isConnected) {
entry.seen = true
} else if (entry.seen || ++entry.frames > MAX_UNSEEN_FRAMES) {
drop(entry)
} else {
pending = true
}
}
if (pending) scheduleSweep()
}
function scheduleSweep() {
if (sweepScheduled) return
sweepScheduled = true
requestAnimationFrame(sweep)
}
return {
render<T>(snippet: Snippet<[T]>, arg: T, tag: 'div' | 'span' = 'div'): HTMLElement {
const target = document.createElement(tag)
const entry: Entry = { target: document.createElement(tag), seen: false, frames: 0 }
entries.add(entry)
// Pierre re-renders synchronously when an edit session ends, which can be inside an
// effect teardown, where Svelte refuses to create the mounted component's effects.
queueMicrotask(() => {
if (destroyed) return
mounted.push(mount(SnippetHost<T>, { target, props: { snippet, arg } }))
if (destroyed || !entries.has(entry)) return
entry.component = mount(SnippetHost<T>, { target: entry.target, props: { snippet, arg } })
})
return target
scheduleSweep()
return entry.target
},
destroy() {
destroyed = true
for (const m of mounted.splice(0)) unmount(m)
for (const entry of entries) drop(entry)
}
}
}
@@ -10,7 +10,16 @@
import { countNodes, formatMs, observeLongTasks, sleep, waitForSelector } from './measure'
import { diffOptions, settingsPool, type PierreSettings } from './pierreSettings'
let { diffCase, settings }: { diffCase: ComparisonCase; settings: PierreSettings } = $props()
let {
diffCase,
settings,
onRunningChange
}: {
diffCase: ComparisonCase
settings: PierreSettings
/** Other Pierre views must unmount while running: switching backends disposes theirs. */
onRunningChange?: (running: boolean) => void
} = $props()
type Renderer = {
id: string
@@ -81,6 +90,8 @@
async function runAll(rounds: number) {
running = true
onRunningChange?.(true)
await tick()
results = []
for (let run = 1; run <= rounds; run++) {
for (const r of renderers) {
@@ -107,7 +118,9 @@
}
}
current = undefined
await tick()
running = false
onRunningChange?.(false)
}
</script>
@@ -115,10 +128,12 @@
<div class="flex items-center gap-2">
<h2 class="text-sm font-semibold">Benchmark</h2>
<span class="text-2xs text-hint">
Mounts each renderer alone on the current case. Run 1 includes loading code, grammars and
workers; run 2 is warm. Long tasks are main-thread blocks over 50 ms (Chromium only). "–"
under Highlighted means no colors within 10 s: the native view skips highlighting past 2,000
lines.
Mounts each renderer alone on the current case, twice. Run 1 pays for the first load of
whatever this page has not used yet (code, grammars, workers); run 2 has those cached. A
main-thread Pierre backend is rebuilt every time it is picked, since only one exists at a
time, so its rows include loading that backend's languages and theme. Long tasks are
main-thread blocks over 50 ms (Chromium only). "–" under Highlighted means no colors within 10
s: the native view skips highlighting past 2,000 lines.
</span>
</div>
<div class="flex gap-2">
@@ -145,7 +160,7 @@
<tbody>
{#each results as r (`${r.run}:${r.label}`)}
<tr class="border-t border-gray-200 dark:border-gray-700">
<td class="py-1">{r.run === 1 ? 'cold' : 'warm'}</td>
<td class="py-1">{r.run}</td>
<td>{r.label}</td>
<td class="text-right">{formatMs(r.painted)}</td>
<td class="text-right">{formatMs(r.highlighted)}</td>
@@ -14,6 +14,7 @@
let settings = $state({ ...DEFAULT_SETTINGS })
let virtualized = $state(false)
let benchmarking = $state(false)
let workspaceCase: ComparisonCase | undefined = $state()
let activeCaseId = $state(cases[0].id)
const activeCase = $derived(
@@ -83,14 +84,18 @@
<div class="h-[400px] overflow-auto border">
<!-- A component's worker pool is fixed at construction. -->
{#key `${settings.useWorkers}:${settings.highlighter}:${virtualized}`}
{#await settings.useWorkers ? undefined : switchMainThreadHighlighter(settings.highlighter) then}
{@render pierre()}
{/await}
{#if benchmarking}
<p class="p-4 text-xs text-hint">Hidden while the benchmark runs.</p>
{:else}
{#await settings.useWorkers ? undefined : switchMainThreadHighlighter(settings.highlighter) then}
{@render pierre()}
{/await}
{/if}
{/key}
</div>
</section>
<Benchmark diffCase={activeCase} {settings} />
<Benchmark diffCase={activeCase} {settings} onRunningChange={(r) => (benchmarking = r)} />
</div>
{#snippet pierre()}
@@ -5,6 +5,7 @@
import Select from '$lib/components/select/Select.svelte'
import DiffEditor from '$lib/components/DiffEditor.svelte'
import PierreCodeView from '$lib/components/pierre/PierreCodeView.svelte'
import { switchMainThreadHighlighter } from '$lib/components/pierre/pierre'
import { countNodes, formatMs, observeLongTasks, sleep, waitForSelector } from './measure'
import { DEFAULT_SETTINGS, diffOptions, settingsPool } from './pierreSettings'
import PierreSettingsBar from './PierreSettingsBar.svelte'
@@ -54,6 +55,9 @@
stats[side] = undefined
shown = undefined
await tick()
if (side === 'pierre' && !settings.useWorkers) {
await switchMainThreadHighlighter(settings.highlighter)
}
await sleep(300)
const longTasks = observeLongTasks()
const start = performance.now()
@@ -105,12 +109,14 @@
<div bind:this={box} class="h-[640px] overflow-auto border">
{#if shown === 'pierre'}
{#key `${settings.useWorkers}:${settings.highlighter}`}
<PierreCodeView
class="h-full overflow-auto"
{items}
options={diffOptions(settings)}
workerPool={pool}
/>
{#await settings.useWorkers ? undefined : switchMainThreadHighlighter(settings.highlighter) then}
<PierreCodeView
class="h-full overflow-auto"
{items}
options={diffOptions(settings)}
workerPool={pool}
/>
{/await}
{/key}
{:else if shown === 'monaco'}
{#each files.slice(0, MONACO_MAX) as f (f.name)}
@@ -14,44 +14,57 @@
let toHash: string | undefined = $state()
let error: string | undefined = $state()
const fail = (e: unknown) => (error = e instanceof Error ? e.message : String(e))
$effect(() => {
const workspace = $workspaceStore
if (!workspace) return
ScriptService.listScriptPaths({ workspace })
.then((p) => (paths = p))
.catch((e) => (error = e.message))
.catch(fail)
})
$effect(() => {
function selectPath(p: string | undefined) {
path = p
history = []
fromHash = undefined
toHash = undefined
const workspace = $workspaceStore
if (!workspace || !path) return
ScriptService.getScriptHistoryByPath({ workspace, path }).then((h) => {
history = h
toHash = h[0]?.script_hash
fromHash = h[1]?.script_hash ?? h[0]?.script_hash
})
})
$effect(() => {
const workspace = $workspaceStore
if (!workspace || !path || !fromHash || !toHash) return
const p = path
Promise.all([
ScriptService.getScriptByHash({ workspace, hash: fromHash }),
ScriptService.getScriptByHash({ workspace, hash: toHash })
]).then(([from, to]) => {
onLoaded({
id: `workspace:${p}:${from.hash}:${to.hash}`,
label: p,
filename: p.split('/').pop() ?? p,
diff: {
lang: scriptLangToEditorLang(to.language),
beforeLang: scriptLangToEditorLang(from.language),
before: from.content,
after: to.content
}
if (!workspace || !p) return
ScriptService.getScriptHistoryByPath({ workspace, path: p })
.then((h) => {
if (path !== p) return
history = h
toHash = h[0]?.script_hash
fromHash = h[1]?.script_hash ?? h[0]?.script_hash
})
})
.catch(fail)
}
$effect(() => {
const workspace = $workspaceStore
const [p, from, to] = [path, fromHash, toHash]
if (!workspace || !p || !from || !to) return
Promise.all([
ScriptService.getScriptByHash({ workspace, hash: from }),
ScriptService.getScriptByHash({ workspace, hash: to })
])
.then(([before, after]) => {
// A later selection may have resolved first.
if (path !== p || fromHash !== from || toHash !== to) return
onLoaded({
id: `workspace:${p}:${from}:${to}`,
label: p,
filename: p.split('/').pop() ?? p,
diff: {
lang: scriptLangToEditorLang(after.language),
beforeLang: scriptLangToEditorLang(before.language),
before: before.content,
after: after.content
}
})
})
.catch(fail)
})
const versionItems = $derived(
@@ -66,19 +79,20 @@
<span class="text-secondary">Workspace script</span>
{#if !$workspaceStore}
<span class="text-hint">Log in and pick a workspace to diff real script versions</span>
{:else if error}
<span class="text-red-600">{error}</span>
{:else}
<Select
size="sm"
placeholder="Script path"
items={paths.map((p) => ({ value: p, label: p }))}
bind:value={path}
bind:value={() => path, selectPath}
/>
{#if history.length > 0}
<Select size="sm" items={versionItems} bind:value={fromHash} />
<span class="text-hint">→</span>
<Select size="sm" items={versionItems} bind:value={toHash} />
{/if}
{#if error}
<span class="text-red-600">{error}</span>
{/if}
{/if}
</div>