Repository navigation
[lit-html] Fix removePart() end-marker leak (#5298) - #5299
graynorton wants to merge 4 commits into
Conversation
Adds a test that uses `insertPart()` to create a ChildPart with a non-null `_$endNode` marker and verifies that `removePart()` removes both the start and end markers. This test fails against the current `removePart()` implementation, which only removes the start marker and leaks the end marker comment — causing unbounded DOM accumulation under sustained churn (e.g., virtualizer scrolling that removes items at one edge and adds at the other). The fix follows in the next commit. The existing `'removePart removes the start marker'` test does not catch this case because it uses a directive at the end of a `<div>`, where the part's `_$endNode` is `null`.
`removePart()` in `directive-helpers.js` only removed the part's start marker, leaving the end marker (`<!---->`) orphaned in the DOM. Parts created via `insertPart()` own two unique marker comments, and both must be removed. Under sustained churn — notably `@lit-labs/virtualizer` scrolling, which removes items at one edge and adds at the other — the leaked end markers accumulated without bound, causing a steady per-operation cost climb (e.g. `node.remove()` grew more expensive as the container filled with orphan comments). Regression was introduced in #4975 (released in `[email protected]`). The existing `'removePart removes the start marker'` test did not catch this because it uses a directive at the end of a `<div>`, where `_$endNode` is `null`. The regression test added in the prior commit uses `insertPart()` to exercise the `_$endNode !== null` path. Local tachometer A/B (15 samples, Chromium, local build): - lit-html/repeat update: 595.28ms -> 63.08ms (-89.4%) - lit-html/repeat-full remove: 54.90ms -> 0.23ms (-99.6%) - reverse / shuffle / replace: -98.8% / -98.3% / -97.5% - all other benchmarks: neutral to slightly faster
🦋 Changeset detectedLatest commit: bd2a2ac The changes in this PR will be included in the next version bump. This PR includes changesets to release 2 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
📊 Tachometer Benchmark ResultsSummarynop-update
render
update
update-reflect
Resultsthis-change
render
update
update-reflect
this-change, tip-of-tree, previous-release
render
update
nop-update
this-change, tip-of-tree, previous-release
render
update
this-change, tip-of-tree, previous-release
render
update
update-reflect
|
|
The size of lit-html.js and lit-core.min.js are as expected. |
rubencarvalho
left a comment
There was a problem hiding this comment.
Left a couple of nits, otherwise this LGTM 😄
| /** | ||
| * Removes a ChildPart from the DOM, including any of its content and markers. | ||
| * | ||
| * Note: The only difference between this and clearPart() is that this also |
There was a problem hiding this comment.
nit: the blurb still reads like we only strip the start node. Worth a line that we take the end marker too when it exists.
| // marker (the part's end marker), causing unbounded DOM accumulation | ||
| // under sustained churn (e.g., virtualizer scrolling that removes items | ||
| // at one edge and adds at the other). | ||
| (part._$endNode as (ChildNode & {remove: () => void}) | null)?.remove(); |
There was a problem hiding this comment.
nit: could we get rid of this cast?
| (part._$endNode as (ChildNode & {remove: () => void}) | null)?.remove(); | |
| part._$endNode?.remove(); |
|
Thanks for the review, @rubencarvalho! (And hello, great to see you here! 😊) You're right on both counts—will update the PR shortly. |
- Update JSDoc to mention that removePart now also removes the end marker, if present. - Drop unnecessary type cast on _$endNode?.remove() — ChildNode's remove() is visible through the _$LH export.
| export const removePart = (part: ChildPart) => { | ||
| part._$clear(); | ||
| part._$startNode.remove(); | ||
| // Without this, every removePart call leaves behind a `<!---->` comment |
There was a problem hiding this comment.
I don't think this comment is really necessary of if we want something here maybe just.
// A part's end node is optional, but if it exists, remove it.
There was a problem hiding this comment.
Will reduce to something minimal.
There was a problem hiding this comment.
I'm not sure it needs a comment at all. In retrospect, removing owned end nodes is as obvious as removing owned start nodes. The doc comment makes this clear enough, IMO.
justinfagnani
left a comment
There was a problem hiding this comment.
Thank you @graynorton!
Sorry for introducing this bug!!
| * removes the part's start node (and its end marker, if present). This means | ||
| * that the ChildPart must own its start node, ie it must be a marker node | ||
| * specifically for this part and not an anchor from surrounding content. |
There was a problem hiding this comment.
| * removes the part's start node (and its end marker, if present). This means | |
| * that the ChildPart must own its start node, ie it must be a marker node | |
| * specifically for this part and not an anchor from surrounding content. | |
| * removes the part's start node and end node, if present. This means that the | |
| * ChildPart must own its start and end nodes, ie they must be a marker node | |
| * specifically for this part and not an anchor from surrounding content. | |
| * | |
| * In practice, this means that this function should only be used with | |
| * parts dynamically created with `insertPart()`. |
| export const removePart = (part: ChildPart) => { | ||
| part._$clear(); | ||
| part._$startNode.remove(); | ||
| // Without this, every removePart call leaves behind a `<!---->` comment |
There was a problem hiding this comment.
I'm not sure it needs a comment at all. In retrospect, removing owned end nodes is as obvious as removing owned start nodes. The doc comment makes this clear enough, IMO.
…ge as they found it (#1425) Three corpus checks join the scroll check in `test_render_gate.py`. Each runs on every corpus page, read on a `still_page` (reduced motion, a stopped clock), so what changes is what the test did: - **`test_a_page_at_rest_does_nothing`**: untouched for five seconds, the page and every document it frames write nothing, ask for no frame, move no focus, and run no endless animation (`at_rest`). - **`test_a_closed_surface_leaves_the_page_as_it_found_it`**: each surface a page key opens (composer, target picker, search, Go-to, thread card, Threads panel, Asks and Leaves drawers, Page Map, versions, Draw and Design modes, shortcut bar, command reference), opened and closed four times, returns the page the first round trip left (`page_state`), and neither its nodes nor its event listeners climb on every trip (`live_counts`, CDP metrics after a forced collection). - **`test_a_resized_page_comes_back_as_it_was`**: a page opened at 1200px or 480px and resized to the other end and back says at each width what it said there on the way out. `page_state` reads an inline style as its sorted declarations, so a property removed and set again at another width, which lands last in the text, reads the same. ## What they found, fixed at the cause - **Every open and close of a surface left comment nodes behind**, 4 to 23 a time, in the shortcut bar and other lists, for as long as the page was open. lit-html 3.3.1 made `repeat` leave each removed item's end marker behind ([lit/lit#5298](lit/lit#5298), open; fix in [lit/lit#5299](lit/lit#5299)). lit-html is held at 3.3.0; `build/AGENTS.md` says when to lift it. - **Under reduced motion the working dot flickered on every frame**: the theme's rule shortened its endless pulse to .01ms, so each frame showed a random point of it. That rule now also runs each animation once. - **Samples with an open thread panel took the focus from each other and from the page on every frame**. The covering boundary moves focus in only while its document holds the focus, and recovers it a render after the document regains it. - **Two let-gos in one gesture**: a thread card closed by a let-go landed the user twice, and a Page Map opened from nowhere took the body's stop and gave it back while still modal. A release now lets go once, and the layer stack's let-go at a close is for popovers; a modal's owner lands the user. - **Scroll boxes kept stale keyboard stops.** A box that stopped overflowing kept `tabindex="-1"`, which made it click-focusable; one whose content rewrapped inside a fixed box kept its old answer; nested scrollers took and put back an outer stop. The reach pass now takes back only the `0` it lent (to the author's value, or to focus.js's lent `-1`), watches the children each candidate holds now (a watch ends only when no reason to keep it holds), and settles nested scrollers deepest first. focus.js gives back only its own `-1`. - **"None" was spelled two ways**, so a page's attributes depended on the widths it had passed through (`data-lf-margin` empty or absent, annotations `shown` or absent). `keeps(node, name, null)` now removes the attribute, and every keeps-or-remove branch says "none" that way. - **The visual review resized its frames a pass after its host without saying so**, leaving a scroll-edge fade on frames that fitted. It announces the layout change. - **A margin marker's spoken position ("37 percent down") was taken at the last render** and kept through a resize. A layout pass that changes the column's size names the markers again from the column it read. ## Worth a look - `test_render_margin`'s annotations round trip now expects the attribute's absence rather than `shown`. - The thread panel gallery's own script still clicks each sample's toggle at load, which leaves the keyboard in the last sample; the surface check releases focus to the page first. > _This was written by Claude Code on behalf of max-sixty_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@pierre/diffs 1.7.1 replaces DiffHunksRenderer's `unifiedContentAST` with row specs in `columns`, and drops `comparator` and the positional `throwOnError` from its parse options. lf-diff renders from that AST, so every diff failed to draw. Porting lf-diff to the row model is its own change, so this keeps 1.6.1. lit-html 3.3.3 no longer matches the move and ref seams litModule adapts, and the pin holds 3.3.0 until a release carries lit/lit#5299, which this bump doesn't establish. Keep 3.3.0. SnapDOM 3.8.3 now fetches with `credentials: "same-origin"`, which the browser judges against the document's origin, so a sample's opaque-origin child sends no credentials and reads Leaf's `Access-Control-Allow-Origin: *`. Leaf's `self.origin` adaptation did the same and no longer matches the source, so it goes.
Bumps five of the dependencies group's seven updates and holds back two whose new versions break the build or the diff widget. With those two held, `pnpm run build:browser` and `pnpm run check` pass locally. The SnapDOM capture tests pass in a sandboxed sample and on the page, and so does the diff word-mark test. | Package | From | To | | --- | --- | --- | | [@openai/codex](https://github.com/openai/codex/tree/HEAD/codex-cli) | `0.171.0` | `0.172.0` | | [@openai/codex-sdk](https://github.com/openai/codex/tree/HEAD/sdk/typescript) | `0.171.0` | `0.172.0` | | [@cloudflare/workers-types](https://github.com/cloudflare/workerd) | `5.20261123.1` | `5.20261124.1` | | [@zumer/snapdom](https://github.com/zumerlab/snapdom) | `3.8.2` | `3.8.3` | | [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler) | `4.167.0` | `4.168.0` | Held back: - **`@pierre/diffs` stays at 1.6.1.** 1.7.1 replaces the renderer's `unifiedContentAST` with row specs, and `lf-diff` renders from that AST, so every diff failed to draw. Porting `lf-diff` is its own change, tracked in #7430. - **`lit-html` stays at 3.3.0.** 3.3.3 no longer matches the move and ref seams `litModule` in `build/browser/build.mjs` adapts. The pin's comment holds it until a release carries lit/lit#5299, and this bump doesn't establish that. SnapDOM 3.8.3 now fetches with `credentials: "same-origin"`, which the browser judges against the document's origin. A live sample's opaque-origin child therefore sends no credentials and can read Leaf's `Access-Control-Allow-Origin: *`. Leaf's `self.origin` adaptation in `build/vendor.mjs` did the same thing and no longer matches the source, so this removes it and rebuilds the SnapDOM bundle. --------- Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: leaf-agent <[email protected]>
Summary
Fixes #5298.
removePart()inlit-html/directive-helpers.jsonly removed the part's start marker, leaving the end marker (<!---->) orphaned in the DOM. Parts created viainsertPart()own two unique marker comments, and both must be removed.Each call leaked one
<!---->node. Under sustained churn — notably@lit-labs/virtualizerscrolling, which removes items at one edge and adds at the other — the leaked markers accumulated without bound, causing a steady per-operation cost climb (e.g.node.remove()grew more expensive as the container filled with orphan comments).Regression was introduced in #4975 (released in
[email protected]). The pre-regression implementation walked sibling nodes up to (and including) the end marker, correctly removing both.Changes
packages/lit-html/src/directive-helpers.ts— one-line fix: also call_$endNode?.remove()after removing the start marker.packages/lit-html/src/test/directive-helpers_test.ts— regression test (committed separately, before the fix) usinginsertPart()to create a ChildPart with a non-null_$endNodeand asserting that both markers are removed..changeset/fix-removepart-end-marker-leak.md— patch changeset forlit-htmlandlit.The existing
'removePart removes the start marker'test (added alongside #4975) did not catch this because it uses a directive at the end of a<div>, where_$endNodeisnull. The new test exercises the_$endNode !== nullpath and fails cleanly against the buggy implementation.Performance impact
Local tachometer A/B (15 samples, Chromium, local build):
lit-html/repeatupdatelit-html/repeat-fullremoveAlllit-html/repeat-fullreverselit-html/repeat-fullshufflelit-html/repeat-fullreplaceAll other benchmarks (
lit-html/kitchen-sink,lit-html/template-heavy,lit-element/list,reactive-element/list) were neutral to slightly faster (−2% to −10%).Test plan
npm run test --workspace=packages/lit-html— 7,239 passed, 0 failed (Chromium, Firefox, Webkit)removePart()and passes with the fixnpm run test --workspace=packages/lit— 726 passed, 0 failednpm run test --workspace=packages/labs/virtualizer— 204 passed, 0 failed