Skip to content

core(unused-css): clamp used bytes to avoid negative wasted bytes - #17131

Open
NickNojiri wants to merge 3 commits into
GoogleChrome:mainfrom
NickNojiri:fix/unused-css-negative-waste
Open

core(unused-css): clamp used bytes to avoid negative wasted bytes#17131
NickNojiri wants to merge 3 commits into
GoogleChrome:mainfrom
NickNojiri:fix/unused-css-negative-waste

Conversation

@NickNojiri

@NickNojiri NickNojiri commented Jul 13, 2026

Copy link
Copy Markdown

Summary

computeUsage in core/computed/unused-css.js sums each used rule's byte range with no clamping. CSS coverage can report overlapping ranges (a nested rule lives inside its parent's range) or the same rule twice, so summed used bytes can exceed the stylesheet size — producing negative wastedBytes/wastedPercent (verified: -4 for overlapping ranges, -8 for a duplicate rule) and NaN for empty stylesheets.

This is the overlap concern raised in #14718, complementing #17127: the smoke test proves current correctness; this makes the computation robust to a regression. The sibling unused-javascript-summary already avoids this via a per-byte bitmap.
Fix

Clamp usedUncompressedBytes to the stylesheet size and guard the zero-length case, keeping usage within [0, 100]%. Regression tests added for overlapping ranges, duplicate used rules, and empty stylesheets.
Testing

unused-css computed tests (8) + dependent audit tests (5) pass; eslint clean

computeUsage sums (endOffset - startOffset) across every used rule
reported by CSS coverage, then derives wasted bytes from
totalBytes - usedBytes. Coverage can report overlapping ranges (a
nested rule lives inside its parent rule's range) or the same rule
more than once, so the summed used bytes can exceed the stylesheet
size, producing a negative wastedBytes/wastedPercent. A 0-length
(empty inline) stylesheet also made percentUnused NaN.

Clamp usedUncompressedBytes to the stylesheet size and guard the
zero-length case so usage stays within [0, 100]%. Relates to the
nested-rule range-overlap concern in GoogleChrome#14718.

Add regression tests for overlapping ranges, duplicate used rules,
and empty stylesheets.
@NickNojiri
NickNojiri requested a review from a team as a code owner July 13, 2026 23:25
@NickNojiri
NickNojiri requested review from paulirish and removed request for a team July 13, 2026 23:25
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