<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Miz Causevic on Medium]]></title>
        <description><![CDATA[Stories by Miz Causevic on Medium]]></description>
        <link>https://medium.com/@mizcausevic?source=rss-3ec8a5bb5f04------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KAtkxHS2JnjNRxOcqKzp_Q.jpeg</url>
            <title>Stories by Miz Causevic on Medium</title>
            <link>https://medium.com/@mizcausevic?source=rss-3ec8a5bb5f04------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:33:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mizcausevic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Array(3).fill({}) Gives You One Object Three Times]]></title>
            <link>https://medium.com/@mizcausevic/array-3-fill-gives-you-one-object-three-times-5a33c8fa6578?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a33c8fa6578</guid>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-11-20T14:01:03.482Z</atom:updated>
            <content:encoded><![CDATA[<h3>fill takes a value, not a factory, and for objects the value is a reference.</h3><figure><img alt="Diagram. Left: Array(3).fill({v:0}) gives three slots that all point to one object, which reads {v: 9} after rows[0].v = 9. Right: Array.from with a function gives three separate objects; only the first reads {v: 9}." src="https://cdn-images-1.medium.com/max/1024/0*lBFgelW6QS-nUnnP.png" /></figure><p>Two ways to build an array of three objects. They are not the same.</p><pre>const rows = Array(3).fill({ v: 0 });<br>rows[0].v = 9;<br>// [{&quot;v&quot;:9},{&quot;v&quot;:9},{&quot;v&quot;:9}]</pre><pre>const ok = Array.from({ length: 3 }, () =&gt; ({ v: 0 }));<br>ok[0].v = 9;<br>// [{&quot;v&quot;:9},{&quot;v&quot;:0},{&quot;v&quot;:0}]</pre><p>Both outputs come from one run on Node v22.23.4.</p><h3>Why</h3><p>fill takes a value and writes it into every slot. The object literal is evaluated once, before fill is called, so there is one object and three references to it. Writing through any of them is writing to the same object.</p><p>Array.from with a map function calls that function once per index, so the literal is evaluated three times and there are three objects.</p><p>This is not a quirk. It is what “a value” means for a reference type, and fill is behaving exactly as specified. The confusion comes from reading Array(3).fill({v:0}) as an instruction to build three of something, which is what it looks like and not what it says.</p><h3>Where it hides</h3><p>It is invisible for primitives, which covers the common uses:</p><pre>Array(5).fill(0)      // fine, numbers are copied by value<br>Array(5).fill(&quot;&quot;)     // fine<br>Array(5).fill(null)   // fine</pre><p>So the idiom gets learned on the safe cases and then applied to an object, and the bug appears far from the line that caused it. The symptom is usually a form or a grid where editing one row edits all of them, which reads like a state management problem and is not.</p><p>Nested arrays have the same shape and bite harder, because the aliasing survives a level of indexing:</p><pre>const grid = Array(3).fill(Array(3).fill(0));<br>grid[0][0] = 9;   // every row now starts with 9</pre><figure><img alt="Diagram. Left: Array(3).fill(Array(3).fill(0)) gives three row slots that all point to one inner array, which reads [9, 0, 0] after grid[0][0] = 9. Right: nested Array.from gives three separate inner arrays; only the first reads [9, 0, 0]." src="https://cdn-images-1.medium.com/max/1024/1*hAgWAij7fkgdXQxZyexLeQ.png" /></figure><h3>The fix, and when each form is right</h3><pre>Array.from({ length: n }, () =&gt; ({ v: 0 }))       // n fresh objects<br>Array.from({ length: n }, (_, i) =&gt; ({ id: i }))  // with the index</pre><p>The map function is what matters: it runs once per slot. If you are reaching for fill with anything that is not a primitive, you want Array.from instead.</p><p>For a grid:</p><pre>Array.from({ length: rows }, () =&gt; Array.from({ length: cols }, () =&gt; 0));</pre><p>Verbose, and every cell is its own.</p><h3>The general rule</h3><p>An API that takes a value gives you one evaluation. An API that takes a function gives you one evaluation each time it calls that function. Whenever the thing you are duplicating is mutable, that distinction is the whole behavior, and the names rarely signal it.</p><p>The same pattern shows up in shallow object spread of nested structures, and in Python’s [[0]*3]*3, which produces the identical aliasing for the identical reason.</p><p>JavaScript default parameters do not belong on that list. An earlier draft included them, which imported Python&#39;s mutable-default behavior into a language that does not have it. In function f(bag = []), the literal is evaluated on every call, so each call gets its own array. If the function pushes an item and returns the length, three calls of f() return 1, 1, 1. The copy idiom that fails in the opposite direction is the JSON round trip: it shares nothing, but it turns a Date into a string and a Map into an empty object.</p><h3>A note on Array(n) itself</h3><p>Array(3) creates three empty slots rather than three undefined values, and empty slots are skipped by map, forEach and filter:</p><pre>Array(3).map((_, i) =&gt; i)                    // [ &lt;3 empty items&gt; ]<br>Array.from({ length: 3 }, (_, i) =&gt; i)       // [0, 1, 2]</pre><p>This is why Array(n).fill(...) is so common: the fill is what makes the slots real. Array.from with a map function never creates the holes in the first place, which is a second reason to prefer it.</p><h3>Spotting it in review</h3><p>The tell is fill with anything other than a primitive inside the parentheses: braces, brackets or new. fill(0), fill(&quot;&quot;) and fill(null) are fine. fill({}), fill([]) and fill(new Thing()) are all one object shared n ways.</p><p><em>Every output above came from a fixture written for this article and run on the versions named in the evidence block. These are demonstrations rather than incident reports: the code was written to show the behavior, not encountered in the wild.</em></p><h3>Working on something like this</h3><p>If you maintain a system like this and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>Each checkable claim above maps to an entry below. Observed means I inspected it directly. Executed means a command ran and produced the result shown. Verified means acceptance evidence passed.</p><ul><li><strong>Executed</strong>: after const rows = Array(3).fill({v:0}) and rows[0].v = 9, all three entries read {v:9} <em>node v22.23.4, printed [{&quot;v&quot;:9},{&quot;v&quot;:9},{&quot;v&quot;:9}]</em></li><li><strong>Executed</strong>: the same mutation on Array.from({length:3}, () =&gt; ({v:0})) changes only the first entry <em>same script, printed [{&quot;v&quot;:9},{&quot;v&quot;:0},{&quot;v&quot;:0}]</em></li><li><strong>Executed</strong>: a JavaScript default parameter is evaluated per call: a function with bag = [] that pushes and returns the length returns 1 on each of three calls <em>node v22.23.4, three consecutive calls printed together</em></li><li><strong>Executed</strong>: after const grid = Array(3).fill(Array(3).fill(0)) and grid[0][0] = 9, every row starts with 9; the nested Array.from version changes only the first row <em>node v22.23.4, printed [[9,0,0],[9,0,0],[9,0,0]] and [[9,0,0],[0,0,0],[0,0,0]]</em></li><li><strong>Executed</strong>: Array(3).map((_, i) =&gt; i) printed [ &lt;3 empty items&gt; ] and Array.from({length:3}, (_, i) =&gt; i) printed [ 0, 1, 2 ] <em>node v22.23.4, same script</em></li><li><strong>Executed</strong>: in Python, g = [[0]*3]*3 then g[0][0] = 9 printed [[9, 0, 0], [9, 0, 0], [9, 0, 0]] <em>Python 3.13.18</em></li><li><strong>Executed</strong>: JSON.parse(JSON.stringify({d: new Date(0), m: new Map([[1, 2]])})) printed {&quot;d&quot;:&quot;1970-01-01T00:00:00.000Z&quot;,&quot;m&quot;:{}} <em>node v22.23.4, same script</em></li></ul><p><em>Written by Mirza (Miz) Causevic. I run Kinetic Gain LLC and write about the systems I actually maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a33c8fa6578" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Tests Pass. Have You Checked They Can Fail?]]></title>
            <link>https://medium.com/@mizcausevic/your-tests-pass-have-you-checked-they-can-fail-215acc81dfbd?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/215acc81dfbd</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-11-18T17:34:42.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Twenty-two build gates, each one proven to reject the specific defect it claims to catch.</h3><figure><img alt="Checklist of all 22 build gates, each marked as rejecting its injected defect, from Bluesky post over 300 characters to visual with no alt text, plus a negative control showing the unmodified canonical builds clean." src="https://cdn-images-1.medium.com/max/1024/0*TxFYubwGSoXdE3Ro.png" /></figure><p>A gate that has never rejected anything is indistinguishable from a gate that cannot reject anything. Both produce green builds. The only way to tell them apart is to hand one a defect and watch.</p><p>My content build has twenty-two gates. Each has a control: inject the exact defect it claims to catch, run the build, confirm it fails with the right message.</p><p>It had twelve controls when I first wrote this, against nineteen failure conditions and three post-emission assertions. A reviewer counted them: the article had been claiming full coverage of a build nearly twice that size. The ten without controls were the ones I considered too obvious to test, which is the same reasoning that leaves a gate unable to fail.</p><h3>What a control looks like</h3><pre>def trial(name, mutate, expect):<br>    D = copy.deepcopy(BASE); mutate(D)<br>    write(D)<br>    rc, out = run_build()<br>    ok = rc != 0 and expect in out<br>    print(f&quot;{&#39;PASS&#39; if ok else &#39;FAIL&#39;}  {name}  rc={rc}&quot;)<br>    return ok</pre><p>Two conditions, both required. A non-zero exit says something failed. The message match says the thing that failed is the gate you were testing, rather than a different gate catching your mutation first.</p><p>The second condition is the one I had been skipping, and it is where the value is. My “banned word in social copy” mutation also lengthened a field past its platform limit. Without the message match it would have passed on the length gate’s rejection and told me nothing about the gate I meant to test.</p><h3>What the twenty-two cover</h3><p>A composed post over the Bluesky limit, and one over the X limit. A post identical across two platforms. Each of the three required social fields (Bluesky, X, Medium tags) missing, one trial apiece. A literal escape in prose, in social copy and in an evidence claim. An avoid-list word in the body and again in social copy. An em-dash in prose. A banned transition. A meta description below the stated band and another above it. A body under the word floor. A duplicate id. An unknown cluster. An undeclared evidence label. An evidence item with no source. A missing visual file. A visual with no alt text.</p><p>Twenty-two rejected. Then the unmodified canonical as a negative control, which builds clean. Without that last trial I would not know the gates accept clean input. Twenty-two rejections say nothing about false positives.</p><h3>The exemption that had to be declared</h3><p>One gate rejects literal escape sequences in shipped copy, because an escape that reaches a reader renders as visible backslash characters. That defect shipped once, through a find-and-replace, before the gate existed. One article is about escape sequences and quotes them deliberately throughout.</p><p>The tempting fix is to loosen the rule until that article passes. That weakens the gate for the other thirty-five.</p><pre>{&quot;allows_literal_escapes&quot;: true,<br> &quot;allows_literal_escapes_reason&quot;: &quot;the article&#39;s subject is \\uXXXX escaping; escape sequences appear as quoted text by design&quot;}</pre><p>A declared, reviewable, per-article exemption with a stated reason. The gate stays strict everywhere else and the exception is visible in the data instead of hidden in a loosened regex. Anyone reading the canonical can see which article is exempt and judge whether the reason is good.</p><h3>The one I would not have thought to write</h3><p>The gate catching a composed post over its platform limit originally measured the body field. The generator appends a link before anything ships, so the string that goes out is eight characters longer than the string the gate was checking.</p><figure><img alt="Diagram: the body field of n characters passes through the generator, which appends an 8-character link, producing an emitted post of n plus 8 characters. The old gate checked n against 300; the moved gate checks n plus 8. Bodies of 293 to 300 characters passed the old gate but would be refused by Bluesky." src="https://cdn-images-1.medium.com/max/1024/1*XXX8AjolHSSVfwWMeF84jA.png" /></figure><p>It is the same failure as a validator that agrees with itself while disagreeing with the world. The gate was lenient by exactly the length of the suffix, eight characters that still decide whether a post goes out or the platform refuses it.</p><p>The assertion moved after emission:</p><pre>_bs = max(len(bluesky(a)) for a in ARTICLES)<br>assert _bs &lt;= 300, f&quot;emitted bluesky post {_bs} chars exceeds 300&quot;</pre><p>Measure the artifact, not the input that produces it. A control injecting a 301-character body would have passed against the old gate, while a 295-character body would have gone out at 303 and been refused.</p><h3>What the controls do not prove</h3><p>These controls prove each gate rejects the defect I thought to write a control for. They say nothing about defects I have not imagined, and that set is larger. A passing control suite is evidence the gates work, not evidence the work is correct.</p><p>What it buys is narrower and still worth having: when the build goes green, I know each gate is able to fail, because I have watched it fail. Everything beyond that is still on me.</p><h3>Working on something like this</h3><p>If you maintain a system like this and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>Each claim below carries a label. Observed means I inspected it directly. Executed means a command ran and produced the result shown. Verified means acceptance evidence passed.</p><ul><li><strong>Executed</strong>: each of twenty-two build gates was tested by injecting the specific defect it claims to catch into a copy of the canonical and confirming a non-zero exit with the expected message. Source: <em>control_suite-Claude.py, which mutates a deep copy per trial, runs the generator, and matches the error text; 22 of 22 rejected</em></li><li><strong>Executed</strong>: the unmodified canonical builds clean as a negative control in the same harness. Source: <em>same harness, baseline trial, exit 0 with the expected emit summary</em></li><li><strong>Observed</strong>: one gate needed a declared exemption because one article quotes escape sequences as its subject matter. Source: <em>the allows_literal_escapes flag and its recorded reason on that one article</em></li></ul><p><em>Written by Mirza (Miz) Causevic. I run Kinetic Gain LLC and write about the systems I actually maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215acc81dfbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go 1.22 Fixed Loop Variable Capture. Which Semantics Does Your Code Use?]]></title>
            <link>https://medium.com/@mizcausevic/the-go-loop-variable-bug-is-fixed-your-go-mod-decides-whether-you-get-the-fix-8c5e4c2f59da?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c5e4c2f59da</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 14:01:07 GMT</pubDate>
            <atom:updated>2026-11-16T15:55:39.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>One compiler, one source file, two different outputs, chosen by a single line of configuration.</h3><figure><img alt="Table: with go1.24.7 installed, go.mod directives go 1.20 and go 1.21 print 3 3 3 (shared loop variable); go 1.22, go 1.23 and go 1.24.7 print 0 1 2 (per-iteration)." src="https://cdn-images-1.medium.com/max/1024/1*oFJ9IdIfkIJWLX-eaeRezA.png" /></figure><p>Most Go tutorials written before 2024 warn you about this:</p><pre>funcs := []func(){}<br>for i := 0; i &lt; 3; i++ {<br>    funcs = append(funcs, func() { fmt.Print(i, &quot; &quot;) })<br>}<br>for _, f := range funcs { f() }</pre><p>Under the old semantics, this prints 3 3 3 because every closure captures the same variable. Go 1.22, released in February 2024, gives each iteration its own instance of variables declared by the loop. Assigning to an existing variable still reuses it.</p><p>So which do you get? I ran the same file five times on one machine, changing only the go directive in go.mod between runs.</p><pre>go directive in go.mod  output<br>----------------------  ------<br>go 1.20                 3 3 3<br>go 1.21                 3 3 3<br>go 1.22                 0 1 2<br>go 1.23                 0 1 2<br>go 1.24.7               0 1 2</pre><p>The toolchain never changed: go version reported go1.24.7 linux/amd64 before and after each run.</p><h3>What the directive actually is</h3><p>Since Go 1.21, the go directive specifies the minimum toolchain version required by the module. With GOTOOLCHAIN=auto, the go command can select a newer toolchain, using one already available or downloading it when permitted. The directive also sets the module’s default language version.</p><p>Installing a newer toolchain alone leaves that default in place. For example, a module declaring go 1.21 still uses the old loop scoping unless a qualifying file-level build constraint changes the language version.</p><h3>Why this is worse than a plain bug</h3><p>The difference surfaces when code keeps referring to a loop variable after the iteration ends, for example by storing a callback or taking the variable’s address. A module can carry the old directive for years before one of those patterns exposes the difference.</p><p>The callback example compiles under both language versions and gives different results. The go vet loopclosure analyzer catches certain patterns under the old semantics, including captures in goroutines and deferred calls in the last statement of a loop body. The analyzer misses the callback slice in this example.</p><h3>What to check</h3><pre>grep &#39;^go &#39; go.mod<br>rg -n -g &#39;*.go&#39; &#39;^//go:build\b&#39;</pre><p>Check the go directive in the module that owns the package, then read the file’s full build constraint. If the constraint implies a minimum of Go 1.21 or later, that minimum sets the file’s language version. A file tagged //go:build go1.21 can therefore use the old semantics inside a module declaring go 1.24.7. A version tag can appear anywhere in a compound expression, so search all //go:build lines. When raising the module directive, review the new minimum toolchain requirement and test code that stores callbacks or pointers.</p><p>This is worth running across a monorepo. The modules nobody has touched in a while are the ones most likely to carry old directives, and the ones least likely to be re-read.</p><figure><img alt="For the example for i := 0; i &lt; 3; i++, the file’s effective Go language version determines the result. The go.mod directive sets the default, and a build constraint that implies Go 1.21 or later can override it. Before Go 1.22, callbacks share i and print 3 3 3. From Go 1.22, they capture separate iteration variables and print 0 1 2. Assigning to an existing i reuses it under either version." src="https://cdn-images-1.medium.com/max/1024/1*6NaH1lObKgzezOIKAdyFBw.png" /></figure><h3>How to migrate without losing test coverage</h3><p>If you need to keep the older language version, add i := i inside the loop body before appending the callback. The closure then captures the copy created in that iteration. This also works if the loop assigns to a predeclared i, which remains shared under either language version.</p><p>If you can raise the module’s go directive, run the full module test suite before and after the change. Pay particular attention to table-driven tests that call t.Parallel. With the old scoping, those subtests can all read the final case and pass even though an earlier case should fail. For callback-producing code, invoke the callbacks after the loop and assert the full sequence, such as 0, 1, 2. That checks the behavior directly even when go vet reports nothing.</p><p><em>Every figure above came from a fixture written for this article and run with the toolchain named in the Evidence section. These are demonstrations rather than incident reports: the code was written to show the behavior, not encountered in the wild.</em></p><h3>Working on something like this</h3><p>If you maintain a system like this and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>Each test result below carries a label. Executed means a command ran and produced the result shown. Claims about toolchain and vet behavior that are not listed here come from the <a href="https://go.dev/doc/toolchain">Go toolchain documentation</a> and the <a href="https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/loopclosure">loopclosure analyzer documentation</a>.</p><ul><li><strong>Executed</strong>: directives 1.20 and 1.21 print 3 3 3; directives 1.22, 1.23 and 1.24.7 print 0 1 2, placing the boundary at 1.22.<em> One source file, only the go.mod directive edited between runs, go version go1.24.7 linux/amd64 for all five runs.</em></li><li>Executed (file-level runtime test). In a module declaring go 1.24.7, the same callback fixture printed 3 3 3 with //go:build go1.21 and 0 1 2 without the constraint.</li><li>Executed (vet test). On a separate goroutine-capture fixture, go vet reported the loop capture with the module set to go 1.21. It did not report that capture with the module set to go 1.24.7.</li></ul><p><em>I run Kinetic Gain LLC and write about the systems I actually maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c5e4c2f59da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How People Actually Scan a Page: F, Z, Marking and Layer-Cake Patterns]]></title>
            <link>https://medium.com/@mizcausevic/how-people-actually-scan-a-page-f-z-marking-and-layer-cake-patterns-d2e24eefaedf?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2e24eefaedf</guid>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 01:13:33 GMT</pubDate>
            <atom:updated>2026-11-15T01:13:33.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcoJynYGYImKvUGI6dNLgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaPEZjQbC5YJf8jfIqcs-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YahdHkZ7JmQUSch1HnW5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4vzFhwL50xl1brHkE37Pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dZnf2KtdLDBomsq5i_7mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1CqWJdny7FqlD8sEOrCXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-t_PdDMS-HMH35qDNMdH2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7jeLB7-1i8ckIDQAFbzFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXcQbhh9B9POJ234y1sU9w.png" /></figure><p>Most visitors do not read your page. They sample it, and the way they sample depends on the layout. Dense text gets an F-shaped scan, sparse single-goal pages get a Z, repeated lists get a parked gaze while the page scrolls, and long articles with clear headings get skimmed layer by layer. Match the layout to the pattern and the content that matters gets seen.</p><h3>Why scanning happens at all</h3><p>Only a small central patch of your vision, the fovea, sees sharply. To read, the eye jumps in quick movements called saccades and pauses in short fixations. Nielsen Norman Group (NN/g) notes that during the jumps the reader is virtually blind, so everything you learn from a page comes from the fixations.</p><p>Fixations cost effort. People ration them, spending them where the page promises the most information for the least work. Every pattern below is a different answer to the same question: where is the cheapest place to look next?</p><p>One honesty note before the patterns. The F, layer-cake and marking patterns are documented in NN/g eye-tracking research. The Z-pattern is a widely used layout heuristic and does not appear among the patterns NN/g reports. It is still useful, and it is labeled as a heuristic below.</p><h3>1. The F-pattern: dense text, weak cues</h3><p><strong>What the eye does.</strong> It sweeps across the first lines, drops down and makes a shorter second pass, then moves down the left edge in a vertical scan. NN/g first reported this in 2006 and found it still appears on desktop and mobile. Readers of right-to-left languages such as Arabic show a mirrored F.</p><p><strong>Why it happens.</strong> The F is what scanning looks like when nothing on the page gives the eye a better target. With no subheadings, bullets or bold terms to land on, readers fall back on the start of the line, because that is where a sentence reveals its subject. It is rarely a perfect F, and it is a symptom to design against, not a goal.</p><p><strong>Best on.</strong> Articles, search results, documentation and other text-heavy pages.</p><p><strong>Design move.</strong> Put the point in the first two lines, and start each paragraph with the word a skimmer needs. Anything buried at the right end of a line, or deep in the middle of a paragraph, is likely to be skipped.</p><h3>2. The Z-pattern: sparse pages with one job</h3><p><strong>What the eye does.</strong> On a sparse layout the gaze crosses the top from left to right, cuts diagonally to the lower left, then crosses the bottom to finish at the lower right.</p><p><strong>Why it happens.</strong> With little text and few competing elements, there is no dense content for an F-style scan to feed on. Reading habits in left-to-right languages supply the direction: start top left, end bottom right. The idea echoes the Gutenberg diagram from print design, which treats the top left as the entry point and the bottom right as the terminal area. Treat it as a starting composition and check it against analytics or testing, because a strong visual element out of place will pull the eye off the path.</p><p><strong>Best on.</strong> Landing pages, posters, ads and simple slides.</p><p><strong>Design move.</strong> Logo top left, navigation top right, and the main call to action at the end of the Z. Keep the middle quiet so the diagonal has a clear run.3. The marking pattern: a parked gaze on a moving page</p><p><strong>What the eye does.</strong> The eyes stay fixed on one spot while the page scrolls or swipes past. NN/g compares it to a dancer fixing on an object to keep balance during a spin, and reports that it happens more on mobile than on desktop.</p><p><strong>Why it happens.</strong> Scrolling moves the content for free. If the useful part of each item sits in the same place, the reader can hold still and let the page deliver the next candidate to the same spot, which saves them from hunting. A column of thumbnails or prices works as that anchor.</p><p><strong>Best on.</strong> Lists, directories, product grids and feeds where items repeat in a column.</p><p><strong>Design move.</strong> Make every row structurally identical, and put the deciding detail (name, price, status) in the same position each time. If row three keeps its price in a different place, the reader&#39;s parked gaze misses it.</p><h3>4. The layer-cake pattern: headings first, body on demand</h3><p><strong>What the eye does.</strong> Fixations land on headings and subheadings with few in between. A heatmap shows horizontal bands, like layers of cake and frosting. When a heading matches what the reader wants, they stop skimming and read the text beneath it. NN/g describes this as the most effective scanning behavior short of reading everything.</p><p><strong>Why it happens.</strong> Clear headings make the cheapest fixation also the most informative one. The reader can judge a whole section from a handful of words, so they skip the body until a heading earns it. This only works when headings are styled to stand out and actually describe the section below them.</p><p><strong>Best on.</strong> Blogs, long articles, documentation and reference pages.</p><p><strong>Design move.</strong> Write headings that carry a claim, not a label. &quot;Setup takes ten minutes&quot; beats &quot;Setup&quot;. If a reader skims only the headings, they should still come away with the argument.</p><h3>Three more patterns from the same research</h3><p>NN/g documents more than these four. Three others are worth knowing because they explain what the main four miss.</p><p><strong>Spotted pattern.</strong> Fixations jump to words that stand out, such as links, bold or colored text, bullets, numbers and capitalized terms, or words that match what the reader is hunting for. Emphasis works only while it is rare, so bold sparingly.</p><p><strong>Commitment pattern.</strong> Fixations land on nearly every content word, which is plain reading. NN/g ties it to high motivation, such as following instructions or trusting the source. You cannot force it, but you can make sure a committed reader meets text that is easy to read in full.</p><p><strong>Bypassing pattern.</strong> When several list lines open with the same words, readers deliberately skip those words and land on what differs. Lead each item with its distinguishing word.</p><h3>Which pattern should you design for?</h3><p>Real pages mix these. A landing page can open as a Z and become a layer-cake below the fold, so treat the patterns as a toolkit and not a complete map.</p><p>The practical test is simple: squint at your page, or scroll it at speed, and see what survives. If the answer is not what you wanted seen, change the layout before you change the words.</p><h4>Sources</h4><p>Nielsen Norman Group, <a href="https://www.nngroup.com/articles/f-shaped-pattern-reading-web-content/">F-Shaped Pattern of Reading on the Web</a></p><p>Nielsen Norman Group, <a href="https://www.nngroup.com/articles/text-scanning-patterns-eyetracking/">Text Scanning Patterns: Eyetracking Evidence</a></p><p>Nielsen Norman Group, <a href="https://www.nngroup.com/alertbox/reading_pattern.html">F-Shaped Pattern For Reading Web Content (original)</a></p><p>Envato Tuts+, <a href="https://webdesign.tutsplus.com/understanding-the-z-layout-in-web-design--webdesign-28a">Understanding the Z-Layout in Web Design</a></p><p>Creative Bloq, <a href="https://www.creativebloq.com/web-design/design-jargon-explained-z-pattern-71515717">Design jargon explained: the Z-Pattern</a></p><p><em>Illustrations are original diagrams. Heat and gaze paths are illustrative, not measured data.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2e24eefaedf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Catches a Typo in Two Positions and Misses It in Two More]]></title>
            <link>https://medium.com/@mizcausevic/typescript-catches-a-typo-in-two-positions-and-misses-it-in-two-more-c1cc662507d1?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1cc662507d1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-11-11T14:01:03.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Excess property checking applies to fresh object literals, which means a variable or a spread turns it off.</h3><figure><img alt="Table: the same misspelled property in four positions. Direct annotated literal: TS2561. Literal stored in a variable, then assigned: no error. Literal passed to connect(): TS2561. Variable spread into a new literal: no error." src="https://cdn-images-1.medium.com/max/1024/1*kq_eCQ5OVFAb-K700lzSmQ.png" /></figure><p>One type, one typo, four ways of writing it:</p><pre>type Opts = { host: string; port?: number };<br>declare function connect(o: Opts): void;</pre><pre>const direct: Opts = { host: &quot;h&quot;, prt: 8080 };    // error TS2561<br>const tmp = { host: &quot;h&quot;, prt: 8080 };<br>const indirect: Opts = tmp;                       // no error<br>connect({ host: &quot;h&quot;, prt: 8080 });                // error TS2561<br>const viaSpread: Opts = { ...tmp };               // no error</pre><p>The compiler reported exactly two errors, on the first and third. Strict mode, tsc 7.0.2; TypeScript 5.9.3 gives the same result.</p><h3>What the rule actually is</h3><p>TypeScript is structurally typed, so an object with extra properties is assignable to a type that does not mention them. That is by design and it is what makes the type system usable with real data.</p><p>Excess property checking is a narrower rule layered on top, and it works per property rather than per object. A property is checked when its declaration sits directly inside the literal being assigned. Two things defeat that, for two different reasons.</p><p><strong>A variable loses freshness.</strong> Assigning the object to a name strips the compiler’s internal fresh-literal marker, and the check no longer applies to anything in it.</p><p><strong>A spread keeps freshness and still skips the spread-in properties</strong>, because those properties were declared in a different literal. An earlier version of this article said a spread loses freshness too. That was wrong, and one line shows it:</p><pre>const s1: Opts = { ...tmp };            // clean<br>const s2: Opts = { ...tmp, extra: 1 };  // error TS2353 on &#39;extra&#39;</pre><p>If the spread had removed freshness, extra could not be flagged. It is flagged because it is written in this literal. prt is not, because it arrived through the spread.</p><h3>Why the spread case is the one that gets you</h3><p>{ ...tmp } looks like it should be checked. It is an object literal, written at the assignment, with braces. But none of its properties were written between those braces, so none of them get the check.</p><p>Configuration code is built almost entirely out of spreads:</p><pre>const config: ServerOpts = { ...defaults, ...fromEnv, ...overrides };</pre><p>Not one property in that line is checked for excess. A misspelled key in fromEnv reaches runtime as a silently ignored setting: the server starts, looks healthy, and is not configured the way you wrote it down.</p><figure><img alt="Diagram of const config: ServerOpts = { …defaults, …fromEnv, …overrides, timeout: 30 }. The three spreads are marked not checked; the written property timeout is marked checked." src="https://cdn-images-1.medium.com/max/1024/1*AtUqRQMr7ypRNKwj5V6e8g.png" /></figure><h3>The fix is at the source</h3><p>Check the object where it is created, not where it is consumed. Either an annotation or satisfies works:</p><pre>const defaults = { host: &quot;h&quot;, prt: 8080 } satisfies Opts;<br>//                                ^^^ error TS2561 here</pre><p>Both catch the typo. satisfies is usually the better choice because it checks the object against the type while keeping its inferred type. An annotation widens defaults to Opts, so downstream code sees port as optional and loses the object&#39;s specific shape.</p><p>The rule that generalizes: validate objects where they are written. Once a value has passed through a variable, an unannotated function return, or a spread, the only check left is structural assignability, and structural assignability is happy with extra keys.</p><h3>What this is not</h3><p>It is not a hole in the type system. Allowing extra properties is correct structural typing, and it is what lets TypeScript work with ordinary JavaScript. Excess property checking is a heuristic for catching typos in the one place they are most likely.</p><p>The trouble is that it is narrow in a way few people internalize. Developers come to believe their object shapes are checked everywhere, then write configuration code that is checked nowhere. It is the same failure as a validator looser than the rule it enforces: a check exists, it runs, and it is not checking what you think.</p><p><em>Every compiler result above came from a fixture written for this article and run on the versions named in the evidence block. These are demonstrations, not incident reports: the code was written to show the behaviour, not encountered in the wild.</em></p><h3>Working on something like this</h3><p>If you maintain a system like this and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>Every factual claim in this piece carries a label. Observed means I inspected it directly. Executed means a command ran and produced the result shown. Verified means acceptance evidence passed.</p><ul><li><strong>Executed:</strong> with strict mode on tsc 7.0.2, a literal with a misspelled property errors with TS2561 when assigned directly and when passed as a function argument, and passes when routed through a variable or a spread. With all four in one file, the compiler reported errors only on the two literal positions. TypeScript 5.9.3 reported the same errors.</li><li><strong>Executed:</strong> applying satisfies to the source object catches the same typo at the declaration. tsc --ignoreConfig --strict --noEmit on a file using satisfies reported TS2561 on that line.</li><li><strong>Executed:</strong> a literal combining a spread with an explicitly written excess property still errors on the written one, so a spread does not remove freshness; the check applies per property, to those declared in that literal. On tsc 7.0.2 strict, { ...tmp } compiles clean while { ...tmp, extra: 1 } reports TS2353 on extra.</li><li><strong>Executed:</strong> an object returned from a function without a return-type annotation and then assigned to Opts passes with the typo; the same literal returned from a function annotated (): Opts reports TS2561. Same result on tsc 7.0.2 and 5.9.3.</li></ul><p><em>Written by Mirza (Miz) Causevic. I run Kinetic Gain LLC and write about the systems I actually maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1cc662507d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Runs Your Effect Twice, and That Is the Feature]]></title>
            <link>https://medium.com/@mizcausevic/react-runs-your-effect-twice-and-that-is-the-feature-685094df97ae?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/685094df97ae</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-11-09T14:16:45.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>In development, StrictMode runs every effect’s setup, cleanup and setup again on mount, which finds exactly the cleanup you forgot to write.</h3><figure><img alt="Two log panels. Inside StrictMode: render #1, render #2, effect setup, interval created, effect cleanup, interval cleared, effect setup, interval created. Without StrictMode: render #1, effect setup, interval created; the cleanup never runs." src="https://cdn-images-1.medium.com/max/1024/1*OvPtHH6f6KOP_qoKv9UCXA.png" /></figure><p>A component with an effect that starts an interval, run two ways: once inside StrictMode, once without it. These are the logs it produced.</p><p>Without StrictMode:</p><pre>render #1<br>effect setup<br>interval created</pre><p>With StrictMode:</p><pre>render #1<br>render #2<br>effect setup<br>interval created<br>effect cleanup<br>interval cleared<br>effect setup<br>interval created</pre><p>Both runs used the React 19.3.1 development build in headless Chromium.</p><h3>Read the second log carefully</h3><p>Two renders, then setup, then a full cleanup, then setup again. React is deliberately simulating the component being unmounted and remounted, immediately, before anyone can see it.</p><p>That is a test, and it has a pass condition: after the sequence, exactly one interval should be live. In the log, interval created appears twice and interval cleared once, which is correct: the first interval was cleared, and the second is the one still running.</p><p>Now delete the cleanup and run it again. The log loses its effect cleanup and interval cleared lines, two intervals are live, and the component leaks one timer per mount. In production there is no StrictMode remount, but the same component still leaks one interval every time it unmounts, on a route change for example.</p><figure><img alt="Chart of intervals still running after mount. Without StrictMode, cleanup present: 1. StrictMode, cleanup present: 1, the first interval cleared. StrictMode, cleanup deleted: 2, one leaked." src="https://cdn-images-1.medium.com/max/1024/1*sU8rhF0xMgdt0WDTDWGVBA.png" /></figure><h3>What it is actually checking</h3><p>Whether your effect survives a remount. An effect that subscribes must unsubscribe. One that opens a connection must close it. One that starts a timer must clear it. One that awaits a result must ignore it once the component is gone or its inputs have changed.</p><p>In a long-lived single-page app, each missing cleanup becomes a real bug: a timer that never stops, a subscription that doubles, a stale response that overwrites a fresh one. <a href="https://github.com/facebook/react/pull/22114">Since React 18</a>, setting state on an unmounted component is a silent no-op rather than a warning, so the stale response is the hazard, not the setState call. All of these can stay hidden in development until something forces an unmount. StrictMode forces one on the first mount, where you will see it.</p><h3>Why it feels like a bug</h3><p>Because the symptom is doubled side effects, and the most common side effect people put in an effect is a fetch. Two network requests on mount looks broken, so the instinct is to suppress the second one with a ref guard:</p><pre>const done = useRef(false);<br>useEffect(() =&gt; {<br>  if (done.current) return;      // do not do this<br>  done.current = true;<br>  fetchThing();<br>}, []);</pre><p>That silences the symptom and keeps the defect. The effect is still not safe to re-run, so it is still not safe to unmount and remount, and that will happen for real. <a href="https://react.dev/learn/synchronizing-with-effects">The React docs</a> single out this exact pattern: a ref guard makes the effect run once in development, but it does not fix the bug.</p><p>The version that passes the test cancels:</p><pre>useEffect(() =&gt; {<br>  const ac = new AbortController();<br>  fetchThing({ signal: ac.signal });<br>  return () =&gt; ac.abort();<br>}, []);</pre><p>Now the double invocation does what it should: the first request is aborted, the second lands, and the component behaves the same whether it is mounted once or ten times. Two requests still appear in the Network tab in development, which the React docs describe as expected. In production there is one. One detail the snippet hides: an aborted fetch rejects with an AbortError, so fetchThing has to treat that as a normal outcome, not report it as a failure.</p><figure><img alt="Sequence diagram: setup 1 starts request 1, cleanup calls ac.abort() so request 1 ends in AbortError, setup 2 starts request 2 whose response is used. Development only; in production only one setup happens." src="https://cdn-images-1.medium.com/max/1024/1*U64o1dcJUd7D6HFzIY8S_g.png" /></figure><h3>What it does not catch</h3><p>StrictMode remounts once, immediately, at mount. It does not exercise a component that mounts, runs for a while, accumulates state and then unmounts, which is where slower leaks live.</p><p>It is also development-only by design, so it says nothing about the build you ship. A cleanup bug introduced after you stop reading the development log ships unexamined.</p><p>That is the case for writing cleanup as a reflex instead of waiting for StrictMode to catch it. An effect that creates something returns a function that destroys it. An effect with nothing to destroy is either fire-and-forget work, such as an analytics call the React docs say to leave as is, or a sign that the logic may not need to be an effect at all.</p><h3>The rule of thumb</h3><p>Read your effect and ask what it would leave behind if it were set up, cleaned up and set up again. If the answer is anything other than nothing, that is the cleanup you owe, and StrictMode is about to show you.</p><p><em>Every log above came from a fixture written for this article and run on the React 19.3.1 development build in headless Chromium. These are demonstrations, not incident reports: the code was written to show the behavior, not found in the wild.</em></p><h3>Working on something like this</h3><p>If you maintain a system like this and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>Every measured claim in this piece carries a label. Executed means a command ran and produced the result shown.</p><ul><li><strong>Executed</strong>: under StrictMode the component logged render, render, effect setup, interval created, effect cleanup, interval cleared, effect setup, interval created, with one interval live after mount. <em>React 19.3.1 development build in headless Chromium 153, log array and live-interval count read from the page after mount, run on 9 November 2026</em></li><li><strong>Executed</strong>: the same component rendered without StrictMode logged one render, one effect setup and one interval created, with one interval live after mount. <em>Same bundle and page, StrictMode wrapper removed, run on 9 November 2026</em></li><li><strong>Executed</strong>: with the cleanup function deleted, the StrictMode run logged two effect setups and two interval created lines, no cleanup lines, and two intervals were live after mount. <em>Same bundle, React 19.3.1 development build in headless Chromium 153, run on 9 November 2026</em></li></ul><p><em>Written by Mirza (Miz) Causevic. I run Kinetic Gain LLC and write about the systems I actually maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685094df97ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSON.parse(JSON.stringify(x)) Returned Four Keys and Changed Every One]]></title>
            <link>https://medium.com/@mizcausevic/json-parse-json-stringify-x-returned-four-keys-and-changed-every-one-a3e13050a10b?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e13050a10b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-11-06T15:41:55.883Z</atom:updated>
            <content:encoded><![CDATA[<h3>The deep-copy idiom everyone uses is a serializer. It silently drops or rewrites most of what JSON cannot represent.</h3><figure><img alt="Comparison of one test object copied two ways on Node v22.23.4. JSON.parse(JSON.stringify(x)) turns Date into a string, Set and Map into empty objects, removes the undefined key, turns NaN into null, and throws on BigInt. structuredClone keeps all six as their original types." src="https://cdn-images-1.medium.com/max/1024/1*PesBB3M3_idq3aP7LH5l8w.png" /></figure><p>This is the deep copy most JavaScript codebases use:</p><pre>const copy = JSON.parse(JSON.stringify(original));</pre><p>Here is what it did to a test object on Node 22:</p><pre>{&quot;when&quot;:&quot;1970-01-01T00:00:00.000Z&quot;,&quot;tags&quot;:{},&quot;m&quot;:{},&quot;n&quot;:null}</pre><p>The input had six fields: a Date, a Set, a Map, an undefined, a NaN and a BigInt. The BigInt made JSON.stringify throw, so I removed it before the round trip would run at all. Of the five fields left, four keys came back, and none of them came back as the type that went in.</p><ul><li>Date became a string. JSON.stringify calls Date.prototype.toJSON, which returns the ISO string, and JSON.parse has no way to know that string was ever a date. It still looks like one, which is the dangerous kind of wrong.</li><li>Set became {}. The serializer walks own enumerable string-keyed properties, and a Set keeps its entries in internal slots, so there is nothing to walk.</li><li>Map became {}. Same reason.</li><li>undefined was dropped, so the key no longer exists rather than holding undefined.</li><li>NaN became null. JSON has no representation for NaN or Infinity.</li><li>BigInt threw a TypeError (&quot;Do not know how to serialize a BigInt&quot;), which is why it had to come out first.</li></ul><h3>structuredClone, same object</h3><pre>Date preserved: true   Set: true   Map: true   NaN: true</pre><p>structuredClone is a built-in global, available since Node 17.0 and in Chrome 98, Firefox 94 and Safari 15.4 onward. It implements the structured clone algorithm, which copies Date, RegExp, Map, Set, BigInt, ArrayBuffer and typed arrays as themselves, and it preserves cyclic references, which JSON cannot represent at all. The BigInt I had to remove for the JSON version comes through intact.</p><pre>const copy = structuredClone(original);</pre><p>It is the same one line. I assumed it would also be faster, and had that backwards:</p><pre>JSON round-trip (json-safe object)   379 ms per 200,000 copies<br>structuredClone (json-safe object)   802 ms per 200,000 copies</pre><p>On an object JSON can represent, the round trip was roughly twice as fast. Reach for structuredClone for correctness, not speed.</p><figure><img alt="Bar chart: 200,000 copies of a JSON-safe object on Node v22.23.4 took 379 ms with the JSON round trip and 802 ms with structuredClone." src="https://cdn-images-1.medium.com/max/1024/1*h-RorwDbdbnchED84xB_LA.png" /><figcaption>200,000 copies each, one run on one machine, Node v22.23.4. Your absolute numbers will differ.</figcaption></figure><h3>What it will not do</h3><p>It does not copy everything, and it does not fail the same way on everything it cannot carry:</p><figure><img alt="Table of what structuredClone cannot carry on Node v22.23.4: a function and a symbol value throw DataCloneError (loud); a symbol-keyed property is skipped and a class instance comes back as a plain object with its prototype lost (silent)." src="https://cdn-images-1.medium.com/max/1024/1*T4VUAneUYe66tJiULtyMXg.png" /><figcaption>Node v22.23.4. DataCloneError is the DOMException name structuredClone uses.</figcaption></figure><p>In a draft I had the first row and guessed the other three. All three guesses were wrong. A symbol value throws, the same as a function. Class instances do not throw; they come back as plain objects with the prototype gone. Symbol-keyed properties disappear without a sound, the same silent loss the JSON round trip has.</p><p>The two throws are a feature. JSON.stringify drops function-valued and symbol-valued properties without complaint, and a copy that is quietly missing a field is worse than an exception at the copy site.</p><h3>Where the JSON version is still correct</h3><p>When the data came from JSON and is going back to JSON. If it holds only JSON types, the round trip is close to exact; one gap is that -0 comes back as 0. Do not treat it as validation, though. If something non-JSON slips in, it throws on BigInt and on cycles but drops undefined, functions and symbols silently, so it will not reliably tell you.</p><p>What it is not is a general deep copy, which is the job it has been given in most of the code I have read.</p><h3>The migration</h3><p>The replacement is one line per call site, but it is not a blind find and replace. Three behaviours change. Dates stay Dates, so any code that relied on the copy holding a string breaks. An object carrying a method, which the JSON version copied minus the method, now throws a DataCloneError, and so does a symbol value. And undefined keys survive, so Object.keys(copy) and the in operator now see keys the JSON version deleted.</p><pre>// before: copy.when is a string<br>// after:  copy.when is a Date</pre><p>So grep for JSON.parse(JSON.stringify and read each call site. The ones where a Date goes in are the highest-value finds, because the old copy still looks correct: a date-shaped string passes most eyeball checks and fails the moment something calls a Date method on it.</p><h3>Cycles</h3><p>structuredClone keeps cycles intact:</p><pre>const a = { name: &quot;a&quot; };<br>a.self = a;<br>structuredClone(a);              // fine<br>JSON.stringify(a);               // TypeError: Converting circular structure to JSON</pre><p>Here the JSON version throws instead of silently losing the reference. Cycles and BigInt are the two cases in this piece where it fails loudly.</p><p><em>Every figure above came from a fixture written for this article and run on the versions named in the evidence block. These are demonstrations rather than incident reports: the code was written to show the behaviour, not encountered in the wild.</em></p><h3>Working on something like this</h3><p>If you maintain a system like this and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>Each claim below carries a label. Observed means I inspected it directly. Executed means a command ran and produced the result shown.</p><ul><li><strong>Executed</strong>: a JSON round trip turned a Date into a string, a Set and a Map each into {}, dropped an undefined key entirely, and converted NaN to null. <em>Node v22.23.4; the printed result kept only when, tags, m and n, with when a string and tags and m both empty objects</em></li><li><strong>Executed</strong>: structuredClone preserved Date, Set, Map and NaN as their original types in the same run. <em>Same script: instanceof checks returned true for Date, Set and Map, and Number.isNaN returned true</em></li><li><strong>Executed</strong>: structuredClone throws a DOMException when given a function. <em>Same script, caught and printed the constructor name</em></li><li><strong>Executed</strong>: on a JSON-representable object, 200,000 JSON round trips took 379 ms against 802 ms for structuredClone. A process.hrtime loop<em> on Node v22.23.4 over a four-key JSON-safe object, one warm-up call before timing, one run</em></li><li><strong>Executed</strong>: structuredClone throws on a function and on a symbol value, silently skips a symbol-keyed property, and returns a class instance as a plain object with the prototype lost. <em>Four separate calls on Node v22.23.4, each wrapped in try/catch, with getOwnPropertySymbols used to confirm the skip</em></li><li><strong>Executed</strong>: JSON.stringify throws a TypeError on a BigInt while structuredClone copies it; JSON.stringify drops a method-valued property while structuredClone throws DataCloneError on it; -0 comes back from a JSON round trip as 0. <em>Node v22.23.4, one script, Object.is used for the -0 check</em></li><li><strong>Executed</strong>: structuredClone copies a self-referencing object with the cycle intact; JSON.stringify throws a TypeError on it. <em>Node v22.23.4</em></li><li><strong>Observed</strong>: structuredClone shipped in Node 17.0.0, Chrome 98, Firefox 94 and Safari 15.4. <em>MDN browser-compat-data, api/_globals/structuredClone.json</em></li></ul><p><em>Written by Mirza (Miz) Causevic. I run Kinetic Gain LLC and write about the systems I maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e13050a10b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python’s sum() Is More Accurate Than the Loop You Would Write]]></title>
            <link>https://medium.com/@mizcausevic/pythons-sum-is-more-accurate-than-the-loop-you-would-write-1acd46328f64?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/1acd46328f64</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 14:01:03 GMT</pubDate>
            <atom:updated>2026-11-04T17:48:29.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>On four test cases the hand-written accumulator was wrong every time and lost the answer entirely twice. On CPython 3.12+, sum() matched fsum on all four.</h3><figure><img alt="Table: four float sums, three ways of adding them, on CPython 3.13.18. For [0.1]*10, [1e16, 1.0, -1e16], [1.0, 1e100, 1.0, -1e100] and [0.1]*100, the manual += loop gives 0.9999999999999999, 0.0, 0.0 and 9.99999999999998, while sum() and math.fsum both give 1.0, 1.0, 2.0 and 10.0." src="https://cdn-images-1.medium.com/max/1024/0*DIvoapSLzGaF4hgy.png" /></figure><p>The received wisdom is that sum() on floats is naive, that you should reach for math.fsum when precision matters, and that a hand-rolled accumulator is equivalent to sum().</p><p>On CPython 3.12 and later, the first and last parts are no longer true. Measured on 3.13.18:</p><pre>input                      manual += loop       sum()   math.fsum<br>-------------------------  ------------------   -----   ---------<br>[0.1]*10                   0.9999999999999999   1.0     1.0<br>[1e16, 1.0, -1e16]         0.0                  1.0     1.0<br>[1.0, 1e100, 1.0, -1e100]  0.0                  2.0     2.0<br>[0.1]*100                  9.99999999999998     10.0    10.0</pre><p>The loop under test is the obvious one:</p><pre>acc = 0.0<br>for v in values:<br>    acc += v</pre><p>The reference throughout is the exact sum of the floats as stored, rounded once to the nearest double. (The stored 0.1 is slightly more than one tenth; that is a representation issue, and no summation method fixes it.) On rows one and four the loop misses that reference. On rows two and three it loses the entire value. Near 1e16, adjacent doubles are 2.0 apart, so 1e16 + 1 lands exactly halfway between two representable values. Under IEEE 754’s default rounding mode, the tie goes to the neighbour whose last significand bit is 0, which is 1e16, and the 1.0 is gone before -1e16 arrives. Row three is a related failure: at 1e100 the 1.0 is far less than half the spacing between neighbouring doubles, so it is absorbed outright, no tie needed.</p><figure><img alt="Number line of the doubles near 1e16, which are 2.0 apart. The exact value 1e16 + 1.0 sits exactly halfway between 1e16 and 1e16 + 2, and the tie rounds to the even neighbour, 1e16, so the 1.0 is lost before -1e16 is subtracted." src="https://cdn-images-1.medium.com/max/1024/1*SK_smSuvy7rC29KCCGGEtA.png" /><figcaption>The tie that costs the loop its 1.0.</figcaption></figure><h3>What sum() is doing</h3><p>Since CPython 3.12, sum() uses Neumaier&#39;s variant of Kahan summation on its float fast path. Alongside the running total it keeps a compensation term that collects the low-order bits each addition rounds away, and adds it back at the end. On 3.11 and earlier you get the naive answer and nothing warns you, so the version floor is part of the advice rather than a footnote.</p><figure><img alt="Table tracing [1e16, 1.0, -1e16] in three steps. The loop’s total goes 1e16, 1e16, 0.0, losing the 1.0 at step 2. sum() keeps the same running total but stores the lost 1.0 in its compensation term, so it returns 0.0 + 1.0 = 1.0." src="https://cdn-images-1.medium.com/max/1024/1*AYzqPxLuAWOATTRKVggR8g.png" /><figcaption>Same running total, one extra term: the 1.0 survives in sum()’s compensation.</figcaption></figure><p>The fast path has conditions, and they are stricter than “the values are numbers”. Once the first exact float has put sum() on it:</p><ul><li>Exact floats are compensated on every version from 3.12.</li><li>On 3.12 and 3.13, an int that fits in a C long (64 bits on 64-bit Linux and macOS, 32 on Windows) is added to the total without updating the compensation term, so its rounding error is never recovered and the int itself can vanish. Floats after it are still compensated. sum([1e16, 1, -1e16]) returns 0.0 on 3.13.18 and 1.0 on 3.14.6, which compensates ints too.</li><li>Anything else ends the fast path for good: that item and everything after it are added naively. That covers float subclasses such as numpy.float64, numpy integer scalars and Fraction. sum([1e16, Fraction(0), 1.0, -1e16]) returns 0.0 on 3.12, 3.13 and 3.14, although the Fraction adds nothing. Complex numbers leave the float path too, but 3.14 gives them a compensated path of their own.</li><li>Mixing floats with Decimal raises TypeError, because float + Decimal is not supported.</li></ul><p>Ints before the first float are summed exactly as ints, then joined to the first float with one plain addition whose rounding error is not recovered: sum([1, 1e16, 1.0, -1e16]) returns 1.0, not 2.0, on 3.12, 3.13 and 3.14. Passing start=0.0 sends those ints through the float path instead, which returns 2.0 here; on 3.12 and 3.13 that path does not compensate ints, so it is not a general fix there. Very large ints, bools, plain float subclasses and a few other rare cases are covered with examples in EDGE_CASES.md in the gist linked at the end.</p><p>All four cases in the table are plain floats, and on all four sum() matched fsum.</p><figure><img alt="Grid of which items CPython sum() compensates, by version: 3.11.18, 3.12.3, 3.13.18, 3.14.6. 3.11 compensates nothing. Exact float: yes on 3.12 and later. Int that fits a C long: item only on 3.12 and 3.13, yes on 3.14. Larger int such as 2**70: drops out on 3.12 and 3.13, yes on 3.14. Float subclass including numpy.float64, numpy integer, Fraction: drop out on all three. Complex: drops out on 3.12 and 3.13, own compensated path on 3.14. Decimal: TypeError on all four." src="https://cdn-images-1.medium.com/max/1024/1*LC6hAVjBbc_BV1VDDe8JGA.png" /><figcaption>What sum() compensates depends on the item type, its position and the Python version.</figcaption></figure><p>math.fsum still gives the stronger guarantee. It tracks the sum exactly in a list of non-overlapping partial sums and rounds once at the end, so on standard IEEE 754 builds its result is correctly rounded: the nearest double to the true sum. The documentation states two conditions: it relies on IEEE 754 arithmetic with round-half-even, and some non-Windows builds that use extended-precision addition can occasionally be off in the last bit. fsum is the one to reach for when you need correctly rounded results rather than merely good ones. On the four inputs in the table, sum() and fsum agree exactly, while the loop people write to replace sum() is wrong on all four.</p><h3>Why anyone writes the loop</h3><p>Usually because they are doing something else in the same pass:</p><pre>total = 0.0<br>for row in rows:<br>    if row.active:<br>        total += row.amount</pre><p>That is a filter and a sum fused together, and it quietly opts out of the compensation.</p><pre>total = sum(row.amount for row in rows if row.active)</pre><p>The generator version reads the same, does the same filtering, and goes through the compensated path, provided every amount is an exact float (on 3.14.6, ints after the first float are fine too, and start=0.0 covers leading ones). Over many rows that is a real difference rather than a stylistic one.</p><figure><img alt="Log-log chart of error in ulps against n, the number of 0.1s summed, from 10 to 100,000 on CPython 3.13.18. The += loop’s error climbs unevenly from under 1 ulp to about 10,362 ulps. sum() and math.fsum are identical at every n, between 0 and 0.5 ulp, not growing, and equal to the loop at n = 13. The one exact zero, at n = 32, cannot sit on a log axis, so the line is broken there and the point is drawn at the 0.01 floor." src="https://cdn-images-1.medium.com/max/1024/1*-PNOXR6KqXB8_HDfGchncg.png" /><figcaption>Over many rows the gap is measurable: about 10,000 ulps for the loop at n = 100,000, at most half an ulp for sum() at every n shown.</figcaption></figure><p>One behavioural difference: if no row matches, sum() returns the int 0, not 0.0. If the type matters, pass a float start, sum((row.amount for row in rows if row.active), 0.0), which keeps the compensation.</p><p>Check the types first. json.loads turns 5 into an int and 5.0 into a float, so a column of amounts parsed from JSON can be mostly floats with a few ints. On 3.12 and 3.13 that is enough to switch the correction off for those items. If the amounts are numpy scalars, float or integer, see the exception below.</p><h3>When none of this saves you</h3><p>Money. Compensated summation reduces error in binary floating point; it does not make 0.1 representable. If you are adding currency, the answer is decimal.Decimal or integer minor units, and no summation algorithm substitutes for the right type. Decimal addition is exact as long as the result fits the context precision, 28 significant digits by default; rounding rules for division, tax and currency conversion are still yours to set.</p><pre>from decimal import Decimal<br>total = sum(Decimal(s) for s in amounts)  # amounts kept as strings, e.g. &quot;19.99&quot;</pre><p>Keep the values out of float entirely. For JSON, json.loads(text, parse_float=Decimal) does that at parse time. If you are already holding floats, Decimal(str(x)) is a rescue rather than a fix: str() gives the shortest decimal that round-trips, so a float typed in as 0.1 comes back as &quot;0.1&quot;, but a float produced by arithmetic, such as 0.1 + 0.2, comes back as &quot;0.30000000000000004&quot;. Decimal(0.1) is worse still: it captures the binary value exactly, 0.1000000000000000055511151231257827021181583404541015625.</p><h3>Where sum() and fsum part company</h3><p>An earlier draft of this article said I had searched for a disagreement and not found one: 20,000 random lists, nothing. A reviewer found one in three elements.</p><pre>&gt;&gt;&gt; v = [1e-20, 1.0, 1e16]<br>&gt;&gt;&gt; sum(v), math.fsum(v)<br>(1e+16, 1.0000000000000002e+16)</pre><p>Rounded to 50 significant digits, the exact sum is 10000000000000001.000000000000000000010000000000000. The two nearest doubles are 1e16 and 1e16 + 2, and the true value sits just above the midpoint between them, by about 1e-20. fsum returns the nearer one, the upper. sum() returns the lower. Both results are about 1.0 from the true value, but only fsum&#39;s is correctly rounded; sum()&#39;s is one unit in the last place below fsum&#39;s. The mechanism: the compensation term ends up holding 1e-20 + 1.0, which rounds to 1.0, so the 1e-20 is lost. Without it, the final 1e16 + 1.0 is an exact tie, and the tie goes to the even neighbour, 1e16.</p><figure><img alt="Number line of the doubles near 1e16, 2.0 apart. For [1e-20, 1.0, 1e16] the exact sum sits about 1e-20 past the midpoint between 1e16 and 1e16 + 2 (offset drawn larger than life). math.fsum returns the nearer double, 1e16 + 2. sum() returns 1e16, one double too low." src="https://cdn-images-1.medium.com/max/1024/1*sTgycY9k44fzhywQvz8qyg.png" /><figcaption>A near-tie decided by 1e-20: fsum rounds the right way, sum() does not.</figcaption></figure><p>A single compensation term can also lose everything when it has to hold values of very different sizes at once:</p><pre>&gt;&gt;&gt; v = [1e100, 1e16, 1.0, -1e16, -1e100]<br>&gt;&gt;&gt; sum(v), math.fsum(v)<br>(0.0, 1.0)</pre><p>Here the compensation term has to carry 1e16 and 1.0 together, which is the same problem the naive loop had with its running total, one level down. Both examples mix values many orders of magnitude apart. My original search used twelve-element lists of similar magnitude, a shape that rarely produces that. Its script did not survive; a reconstruction, now in the gist, finds no disagreement on 3.12, 3.13 or 3.14 in 20,000 such lists, run once with positive values and once with random signs, and thousands on 3.11, which has no compensation.</p><p>The same weakness can make sum() worse than the plain loop:</p><pre>&gt;&gt;&gt; v = [1e100, 1e16, 1.0, -1e16, -1.0, -1e100]<br>&gt;&gt;&gt; sum(v), math.fsum(v)<br>(-1.0, 0.0)</pre><p>The exact sum is 0.0, and the += loop returns 0.0 too. While the compensation term holds 1e16, the +1.0 lands on a tie and is rounded away; once 1e16 has cancelled, the -1.0 arrives and is kept in full. The loop absorbs everything between 1e100 and -1e100, both 1.0s included, so its errors cancel and it lands on the right answer by luck. The error is not confined to answers near zero: append 5.0, and the loop and fsum return 5.0 while sum() returns 4.0. Inputs like these are rare. In 200,000 random lists, sum() was never less accurate than the loop, more accurate in about one in five (40,182), and equal in the rest.</p><p>There is a behavioural split too:</p><pre>&gt;&gt;&gt; sum([1e308, 1e308, -1e308, -1e308])<br>inf<br>&gt;&gt;&gt; math.fsum([1e308, 1e308, -1e308, -1e308])<br>OverflowError: intermediate overflow in fsum</pre><p>The true sum is 0.0. sum() overflows to inf when it adds the second 1e308, and inf minus a finite number stays inf; the compensation term turns into NaN along the way, and CPython discards a non-finite compensation at the end. fsum detects the intermediate overflow and raises instead of returning a wrong answer.</p><p>So the title’s claim is a tendency, not a guarantee: sum() is usually as accurate as the loop or better, and much better on long sums, but inputs that defeat its single compensation term can make it worse, by more than an ulp. fsum is still the more accurate tool. Neumaier&#39;s algorithm carries one compensation term and is not correctly rounded. Where you need the correctly rounded result rather than a close one, use fsum.</p><h3>The exception that matters most in practice</h3><p>The compensated path checks for an exact float with PyFloat_CheckExact, so a float subclass that reaches it ends it, and every float after that is added naively. numpy.float64 is a float subclass:</p><pre>&gt;&gt;&gt; issubclass(np.float64, float)<br>True<br>&gt;&gt;&gt; sum([np.float64(1e16), np.float64(1.0), np.float64(-1e16)])<br>np.float64(0.0)<br>&gt;&gt;&gt; sum([1e16, 1.0, -1e16])<br>1.0</pre><p>Same three values, same function, naive answer. numpy integer scalars such as np.int64 are not int subclasses at all, so on every version one of them ends the fast path too: sum([1e16, np.int64(1), 1.0, -1e16]) returns np.float64(0.0). An earlier draft of this article recommended the generator rewrite for &quot;financial or scientific data&quot;, which is exactly where the values are most likely to be numpy scalars and the compensation most likely to be absent.</p><p>np.sum is not the fix either. It uses partial pairwise summation, which slows error growth on long arrays but is not compensated, and np.sum(np.array([1e16, 1.0, -1e16])) also returns 0.0. For accuracy on numpy data use math.fsum, which accepts numpy float64 values and returns 1.0 here, or convert to plain floats first, sum(float(x) for x in values), to get sum()&#39;s compensation back. That conversion is safe for float64; for wider types such as longdouble it would discard precision.</p><h3>Checking it on your own interpreter</h3><p>The compensation is an implementation detail of CPython rather than a language guarantee; even the documentation’s 3.12 change note promises higher accuracy only “on most builds”. It is worth confirming on whatever you actually run:</p><pre>print(sum([1e16, 1.0, -1e16]))  # 1.0 if compensated, 0.0 if naive</pre><p>Treat it as a smoke test: 1.0 shows this example kept the small value, not which algorithm kept it, and says nothing about other input types. Another implementation, or an older CPython, may give the naive answer, and code that depends on the accuracy should either pin the behaviour with math.fsum or carry this as a test.</p><h3>The thing to take away</h3><p>Two of the three pieces of received wisdom from the opening have gone stale. sum() on floats is no longer naive, and a hand-written loop is no longer equivalent to it: on 3.12 and later, the loop can lose data that sum() keeps, far more often than the reverse. The second still holds: when you need the correctly rounded result, use fsum.</p><p>The broader lesson, as I read it: a hand-written replacement for a standard library function gives up whatever fixes the library has accumulated. This one shows up in a four-row table, which is unusual. More often the loss is invisible until two totals that should match do not.</p><p>Every result shown above came from the scripts in the gist linked in the evidence block, run on the interpreters named there. These are demonstrations rather than incident reports: the code was written to show the behaviour, not encountered in the wild.</p><h3>Working on something like this</h3><p>If you maintain code where this kind of numerical error matters and want a second pair of eyes on it, I take a small number of engagements.</p><h3>Evidence</h3><p>The claims this piece rests on are listed below, each with a label. Observed means I inspected it directly. Executed means a command ran and produced the result shown.</p><p>The scripts that produce every result, and their raw output on each interpreter, are public in <a href="https://gist.github.com/mizcausevic-dev/a09f8537b1081f8cd1e938a5b0cd5d62">this gist</a>: sum_audit.py for the Executed claims below except the reconstruction, earlier_search_reconstruction.py for the reconstructed search, and figures_data.py for the figures, except the version grid, which is transcribed from sum_audit.py’s logs. EDGE_CASES.md collects the rarer cases with their results from the same logs.</p><ul><li><strong>Executed:</strong> the four-row table (manual loop, sum(), math.fsum) on CPython 3.13.18, repr of each result printed side by side; sum() matched fsum on all four.</li><li><strong>Executed:</strong> on the same four rows, sum() on CPython 3.11.18 returns the same result as the naive loop; 3.12.3 and 3.14.6 match the 3.13.18 table.</li><li><strong>Executed:</strong> 1e16 + 1.0 == 1e16 is True on all four interpreters.</li><li><strong>Observed:</strong> Python/bltinmodule.c at tags v3.12.3 and v3.13.18: the float fast path compensates only items that pass PyFloat_CheckExact(item); items passing PyLong_Check that fit a C long are added with f_result += (double)value and no compensation update; anything else leaves the float loop for the generic loop, which runs to the end of the sum. sum() starts on an integer loop that adds exact ints and bools exactly while the total fits, joins that total to the first item that does not qualify with one PyNumber_Add, and enters the float loop only if the result is an exact float. At tag v3.14.6, items passing PyLong_Check go through the same compensated add, and exact complex results have their own compensated path.</li><li><strong>Observed:</strong> the math.fsum documentation (Doc/library/math.rst at v3.14.6) states the round-half-even assumption and the double-rounding caveat for some non-Windows builds; the sum() documentation (Doc/library/functions.rst) carries the 3.12 change note &quot;higher accuracy … on most builds&quot;. On overflow, 3.12 and 3.13 skip a non-finite compensation (Py_IS_FINITE(c)), and 3.14&#39;s cs_to_double does the same.</li><li><strong>Executed:</strong> sum([1e16, 1, -1e16]) returns 0.0 on 3.12.3 and 3.13.18, 1.0 on 3.14.6; the same holds for the JSON-parsed version of those values.</li><li><strong>Executed:</strong> sum([1e16, Fraction(1), -1e16]) returns 0.0 on 3.12.3, 3.13.18 and 3.14.6.</li><li><strong>Executed:</strong> with a later 1.0, [1e16, 1, 1.0, -1e16] sums to 1.0 on 3.12.3 and 3.13.18 (the int is lost, the 1.0 is kept) and 2.0 on 3.14.6; [1e16, Fraction(0), 1.0, -1e16] sums to 0.0 on 3.12.3, 3.13.18 and 3.14.6.</li><li><strong>Executed:</strong> [1, 1e16, 1.0, -1e16] sums to 1.0 on 3.12.3, 3.13.18 and 3.14.6, and to 2.0 with start=0.0; [2**53, 1, 1, 0.5] sums to 9007199254740994.0, and with start=0.0 to 9007199254740992.0 on 3.12.3 and 3.13.18 and 9007199254740994.0 on 3.14.6.</li><li><strong>Executed:</strong> an empty filtered generator sums to int 0 by default and to 0.0 with start=0.0; with start=0.0, [1e16, 1.0, -1e16] still sums to 1.0 on 3.12.3 and later.</li><li><strong>Executed:</strong> sum([1.0, Decimal(&quot;1&quot;)]) raises TypeError on all four interpreters.</li><li><strong>Executed:</strong> [1e-20, 1.0, 1e16]: sum() returns 1e+16, fsum returns 1.0000000000000002e+16, exact value computed with Fraction and shown to 50 significant digits; sum() is about 1.00000000000000000001 below the exact value and fsum about 0.99999999999999999999 above it (printed to 40 digits in the log); ulp at 1e16 is 2.0.</li><li><strong>Executed:</strong> [1e100, 1e16, 1.0, -1e16, -1e100]: sum() returns 0.0, fsum returns 1.0, on all four interpreters.</li><li><strong>Executed:</strong> with random.seed(1), 200,000 random lists of 2 to 12 floats with magnitudes from 1e-20 to 1e20 and random signs, exact reference computed with Fraction: sum() was less accurate than the manual loop on 0 lists and more accurate on 40,182, on 3.12.3, 3.13.18 and 3.14.6.</li><li><strong>Executed:</strong> a reconstruction of the earlier draft’s search (the original script was not kept), with random.seed(1): 20,000 twelve-element lists of similar magnitude, positive and mixed-sign variants. Zero sum()/fsum disagreements on 3.12.3, 3.13.18 and 3.14.6; 8,833 and 11,991 on 3.11.18.</li><li><strong>Executed:</strong> json.loads(&#39;[1.10, 2.20, 3]&#39;, parse_float=Decimal) sums to Decimal 6.30.</li><li><strong>Executed:</strong> [1e100, 1e16, 1.0, -1e16, -1.0, -1e100]: the loop and fsum return 0.0, the exact sum, and sum() returns -1.0; with 5.0 appended, the loop and fsum return 5.0 and sum() returns 4.0; on 3.12.3, 3.13.18 and 3.14.6 (3.11.18 returns the exact values).</li><li><strong>Executed:</strong> [1e308, 1e308, -1e308, -1e308]: sum() returns inf, math.fsum raises &quot;OverflowError: intermediate overflow in fsum&quot;, on all four interpreters.</li><li><strong>Executed:</strong> NumPy 2.5.3 on CPython 3.13.18: issubclass(np.float64, float) is True; sum() of the three values as numpy scalars returns np.float64(0.0); np.sum of the same array returns 0.0; math.fsum returns 1.0; issubclass(np.int64, int) is False and sum([1e16, np.int64(1), 1.0, -1e16]) returns np.float64(0.0).</li></ul><p><em>Written by Mirza (Miz) Causevic. I run Kinetic Gain LLC and write about the systems I actually maintain, including the parts that break.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1acd46328f64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three Web Performance Fixes, Measured: Hero Image, Stylesheet and JavaScript Bundle]]></title>
            <link>https://medium.com/@mizcausevic/three-web-performance-fixes-measured-hero-image-stylesheet-and-javascript-bundle-db29a304ac6e?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/db29a304ac6e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[core-web-vitals]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 02:06:03 GMT</pubDate>
            <atom:updated>2026-10-29T19:42:20.056Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One generated page per fix, nine loads per version, a simulated slow phone link. Right-sizing the image and compressing the stylesheet moved the paint by more than a second. A priority hint, minification and a module build moved nothing we could measure.</em></p><p>Performance advice usually arrives as a list of things to do. This article checks three of them, one at a time, on a page built for the purpose, and reports what each change did to the number it is supposed to improve. It also reports the changes that did nothing, because on a different page some of them would.</p><p>The three videos in the series are embedded in the section each one covers. Each video runs about six minutes and shows the code, the waterfall and real frames from the test loads.</p><h3>How to read the evidence labels</h3><ul><li><strong>Verified (source)</strong>: stated in the documentation named in the sources.</li><li><strong>Observed</strong>: measured by us in Chrome 155 on a generated page. The scope is named each time.</li><li><strong>Inferred</strong>: a reading of the evidence that the evidence does not prove.</li><li><strong>Proposed</strong>: a recommendation. Nothing was measured for it unless the text says so.</li></ul><h3>The test</h3><p>Every version of every page was loaded nine times, each time in a fresh browser context with the cache disabled, and each list below reports the median. The link is simulated inside the browser: each request costs 150 ms, all transfers share one 1.6 Mbps pipe, text files are charged at their gzip size (except the uncompressed stylesheet in Part 2), and the CPU runs at a 4x slowdown on a 412 pixel wide phone viewport.</p><p><strong>Observed:</strong> a first attempt used a local web server with throttling in the browser’s developer tools. It was discarded, because an ad blocker on the test machine injected its own requests into every page and added a fixed delay that hid the effect of small changes. Intercepting requests inside the browser avoids that layer.</p><p>Two limits of the simulated link matter below. It gives every transfer in flight an equal share of the pipe, so it ignores request priority. And it hands the browser each response whole, so a picture never paints progressively from the top.</p><p>A change counts as “no change” here only when the nine runs of the two versions overlap and the medians sit within 0.06 seconds of each other.</p><h3>Part 1: a hero image that paints late</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEp23FHVq4tY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEp23FHVq4tY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEp23FHVq4tY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/042287e3f5056d6921d756ca7297f747/href">https://medium.com/media/042287e3f5056d6921d756ca7297f747/href</a></iframe><p><strong>Verified (source):</strong> Largest Contentful Paint (LCP) reports when the largest image, text block or video in view finishes rendering. Google rates an LCP of 2.5 seconds or less as good and more than 4.0 seconds as poor, judged at the 75th percentile of real page loads. Our numbers are lab runs on one page, not that.</p><p>The page has a headline, a few lines of text and a hero image that a script inserts into the page. The image is a synthetic picture, 408 KB as a 1920 pixel wide JPEG.</p><p><strong>Observed:</strong> LCP, median of nine loads.</p><ul><li><strong>Hero inserted by JavaScript:</strong> 2.82 s. The image request started at 0.56 s, after the script had run. The wait before the request was 0.39 s and the download took 2.22 s.</li><li><strong>Preload hint in the head:</strong> 2.57 s. The request started at 0.19 s.</li><li><strong>Image written in the HTML:</strong> 2.57 s. The request started at 0.20 s. One of its nine runs took 2.88 s, above the slow version’s 2.82 s median, so the two ranges overlap.</li><li><strong>Right-sized with </strong><strong>srcset and </strong><strong>sizes:</strong> 1.32 s. The file for this phone is 119 KB, 71 percent smaller.</li><li><strong>WebP offered with the JPEG as fallback:</strong> 1.06 s. The file is 93 KB, 22 percent smaller again.</li><li><strong>fetchpriority=&quot;high&quot; added:</strong> 1.05 s.</li></ul><p>Discovery bought 0.25 seconds. Both ways of making the image visible to the browser early, a preload hint and a plain &lt;img&gt; in the HTML, started the request about 0.37 seconds sooner and landed on the same median. The download itself got slightly longer, 2.34 s against 2.22 s, most likely because the image now shares the pipe with the script.</p><p>Size bought the most. Right-sizing saved 1.25 seconds and moved the page from the needs-improvement band to well inside the good one. WebP saved another 0.26 seconds.</p><p><strong>Observed:</strong> the priority hint changed nothing we could measure, 1.06 s to 1.05 s with overlapping ranges. <strong>Inferred:</strong> that result says little about priority hints in general. The simulated link ignores priority, and the image request already started at 0.2 seconds. <strong>Verified (source):</strong> web.dev describes the attribute as a hint, says images start at low priority by default, and says it matters more where resources compete for bandwidth. <strong>Proposed:</strong> test it on a real connection before you rely on it.</p><p>The WebP and JPEG files were encoded with different settings and were not matched for visual quality, so the 22 percent applies to those two settings only.</p><h3>Part 2: a stylesheet that blocks the first paint</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBFVs-gT200k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBFVs-gT200k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBFVs-gT200k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a4d1ea25b019b60271e72bee63cb7f/href">https://medium.com/media/f9a4d1ea25b019b60271e72bee63cb7f/href</a></iframe><p><strong>Verified (source):</strong> First Contentful Paint (FCP) is when the browser first draws content: text, an image, an SVG or a non-white canvas. An FCP of 1.8 seconds or less is rated good and more than 3.0 seconds poor, at the 75th percentile. By default, CSS is a render-blocking resource, so the browser holds the first paint until the stylesheet has arrived.</p><p>The page is a generated article layout built on Bootstrap 5.3.8 (MIT). The stylesheet is 280 KB before compression, and the page uses a small part of it.</p><p><strong>Observed:</strong> FCP, median of nine loads.</p><ul><li><strong>Full stylesheet, no compression:</strong> 1.89 s.</li><li><strong>Gzip:</strong> 0.67 s. The stylesheet is 33.3 KB on the wire.</li><li><strong>Gzip and minified:</strong> 0.65 s. 30.5 KB.</li><li><strong>Unused rules removed:</strong> 0.52 s. 5.2 KB.</li><li><strong>Stylesheet inlined in the HTML:</strong> 0.34 s. No stylesheet request.</li><li><strong>Minified, loaded through an </strong><strong>@import rule:</strong> 0.82 s.</li></ul><p>Compression took 1.22 seconds off and nothing else came close. Minification changed the file by about 3 KB and the median by 0.02 seconds, inside the spread of the runs, so on a compressed site it was not what moved the paint. Removing unused rules saved 0.13 seconds, and inlining saved another 0.18.</p><p><strong>Observed:</strong> about 90 percent of the stylesheet’s rule bytes matched nothing on the page. We compared screenshots of the purged page at 412 and 1280 pixels wide, and they were identical pixel for pixel. <strong>Inferred:</strong> that check covers the first render only. A menu, a modal or a class added by a script would need its own check before you ship a purged stylesheet.</p><p><strong>Observed:</strong> behind an @import rule, the imported file did not start until 0.38 seconds, when the file importing it had finished. Loaded directly, the same minified file had finished at 0.52 s. Through the import it finished at 0.70 s, and FCP went from 0.65 s to 0.82 s, a cost of 0.17 seconds.</p><p><strong>Inferred:</strong> inlining saved 0.18 seconds, about the 0.15 seconds each request costs in this model, which suggests the request itself is most of what remains once the file is small. The model fixes that cost by construction, so a real network may differ. An inlined stylesheet also cannot be cached on its own, so inlining suits a small stylesheet.</p><h3>Part 3: JavaScript that ships more than the page uses</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg5UTaOBFD5U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg5UTaOBFD5U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg5UTaOBFD5U%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0afbaf2f36bb2586e7ebd83eea8d8a8/href">https://medium.com/media/a0afbaf2f36bb2586e7ebd83eea8d8a8/href</a></iframe><p>The widget groups 6,000 generated orders by region, totals and ranks them with lodash 4.17.21, and formats dates with moment 2.30.1. Everything is bundled with Rolldown.</p><p><strong>Observed:</strong> built alone and gzipped, lodash is 26 KB, moment is 20 KB and the widget’s own code is 0.3 KB. Together the two libraries are 99 percent of the combined bytes.</p><p>The metric is the time until the table is on screen, the first frame painted after the script has drawn it. It is our own marker, not a Core Web Vital.</p><p><strong>Observed:</strong> table on screen, median of nine loads.</p><ul><li><strong>All of lodash and moment:</strong> 0.72 s. The script is 46.2 KB on the wire.</li><li><strong>One lodash function at a time:</strong> 0.58 s. 27.9 KB.</li><li><strong>lodash-es, the module build:</strong> 0.58 s. 26.9 KB.</li><li><strong>Built-in </strong><strong>Intl.DateTimeFormat instead of moment:</strong> 0.50 s. 7.2 KB.</li><li><strong>Widget loaded when the visitor opens it:</strong> 0.2 KB at page load, then 0.29 s after the click.</li></ul><p>Importing the five functions the page calls saved 0.14 seconds. The module build changed nothing we could measure, and the likely reason is that the single-function imports had already removed most of lodash. Dropping moment saved another 0.08 seconds and 19.7 KB against the module build. Overall the script fell 84 percent, from 46.2 KB to 7.2 KB, and the table appeared 0.22 seconds sooner. The 39 KB removed takes about 0.2 seconds to download at 1.6 Mbps, which accounts for most of that gain.</p><p><strong>Observed:</strong> bytes did not predict CPU time. Main-thread time after the script arrived went from 0.12 s to 0.07 s with per-function lodash imports, then rose to 0.09 s when moment was replaced. We did not isolate the cause. Median Total Blocking Time stayed under 0.05 seconds in every version, and the worst single run reached 0.06. <strong>Verified (source):</strong> web.dev recommends a Total Blocking Time under 200 milliseconds on average mobile hardware.</p><p><strong>Observed:</strong> neither LCP nor FCP moved. Both sat at about a quarter of a second in every version, because the heading paints before the script runs, so the gain shows only in our own marker.</p><p>The last row is a trade, not a saving. Loading the widget on demand takes the script off the page load, and the cost reappears at the click.</p><h3>What to check on your own page</h3><ul><li><strong>Which element is your LCP element, and when does its request start?</strong> Log it:</li></ul><pre>new PerformanceObserver((list) =&gt; {<br>  const e = list.getEntries().at(-1);<br>  console.log(e.element, e.url, e.startTime);<br>}).observe({type: &#39;largest-contentful-paint&#39;, buffered: true});</pre><ul><li><strong>Is the response compressed?</strong> Look for a content-encoding header on the stylesheet and script responses.</li><li><strong>How much of the CSS runs?</strong> The Coverage panel in Chrome DevTools reports unused bytes.</li><li><strong>How big is the script on the wire?</strong> Compress the built file the way your host does:</li></ul><pre>gzip -c dist/app.js | wc -c</pre><ul><li><strong>Do you import a whole library for a few functions?</strong> Search the imports:</li></ul><pre>grep -rnE &quot;(from |require\()[&#39;\&quot;](lodash|moment)[&#39;\&quot;]&quot; src</pre><ul><li><strong>Does the first screen need this code?</strong> If not, load it on demand and measure the click.</li></ul><h3>Limits</h3><ul><li>One generated page per fix, one browser, one simulated link. The picture, stylesheet use and widget are synthetic or generated, so your file sizes and your results will differ.</li><li>Lab runs, median of nine, not field data. Real visitors vary by device and network.</li><li>The link ignores request priority and delivers each response whole.</li><li>The WebP and JPEG files were not matched for visual quality.</li><li>Removing unused CSS was checked on the first render only.</li><li>Replacing moment with the built-in formatter covers one date format. Check your own output.</li><li>Each saving is measured after the earlier ones, so the order changes the shares.</li></ul><h3>Sources</h3><ul><li>web.dev, Largest Contentful Paint (LCP): <a href="https://web.dev/articles/lcp">https://web.dev/articles/lcp</a></li><li>web.dev, Optimize Largest Contentful Paint: <a href="https://web.dev/articles/optimize-lcp">https://web.dev/articles/optimize-lcp</a></li><li>web.dev, Optimize resource loading with the Fetch Priority API: <a href="https://web.dev/articles/fetch-priority">https://web.dev/articles/fetch-priority</a></li><li>web.dev, First Contentful Paint (FCP): <a href="https://web.dev/articles/fcp">https://web.dev/articles/fcp</a></li><li>web.dev, Render-blocking CSS: <a href="https://web.dev/articles/critical-rendering-path/render-blocking-css">https://web.dev/articles/critical-rendering-path/render-blocking-css</a></li><li>web.dev, Total Blocking Time (TBT): <a href="https://web.dev/articles/tbt">https://web.dev/articles/tbt</a></li><li>Chrome for Developers, Find unused JavaScript and CSS with the Coverage panel: <a href="https://developer.chrome.com/docs/devtools/coverage">https://developer.chrome.com/docs/devtools/coverage</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db29a304ac6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The CSS Cascade, Measured: 26 Contests in Chrome Show Which Rule Wins]]></title>
            <link>https://medium.com/@mizcausevic/the-css-cascade-measured-26-contests-in-chrome-show-which-rule-wins-0d5b6175f16f?source=rss-3ec8a5bb5f04------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d5b6175f16f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Miz Causevic]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 20:32:49 GMT</pubDate>
            <atom:updated>2026-11-06T16:21:18.639Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Order of appearance, specificity, inline styles, important, cascade layers, browser defaults and inheritance, each tested in a real browser. A model of the specification’s sort order named all 26 winners.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4k4BrFLKYhc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4k4BrFLKYhc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4k4BrFLKYhc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d63621ff43cbd91008b5e204579078d/href">https://medium.com/media/6d63621ff43cbd91008b5e204579078d/href</a></iframe><p>When two CSS rules set the same property on the same element, the browser does not simply take the last one written. It sorts the competing declarations in a fixed order and uses the winner of that sort. CSS Cascading and Inheritance Level 5 defines six steps, in this order: origin and importance, context, element-attached styles, cascade layers, specificity, and order of appearance. The first step that finds a difference decides the winner, and the later steps are never consulted.</p><p>This article checks that order in Chrome with 26 small contests, then covers what the contests do not show. The video above (6:19) shows 25 of the 26 contests; the universal-versus-tag contest appears only here.</p><h3>How to read the evidence labels</h3><ul><li><strong>Verified (spec)</strong>: stated in the W3C document named in the sources.</li><li><strong>Observed</strong>: measured by us in Chrome 155 on a generated page. The scope is named each time.</li><li><strong>Inferred</strong>: a reading of the evidence that the evidence does not prove.</li><li><strong>Proposed</strong>: a recommendation. Nothing was measured for it unless the text says so.</li></ul><h3>The test</h3><p>Each contest is a tiny page with one element and two or more rules that set the same property. Every rule uses a different color, so the computed color tells us which rule won. The page is loaded in Chrome 155 (155.0.8059.85, headless, 1280 by 800), and the answer is read with getComputedStyle.</p><p>You can run one contest yourself:</p><pre>&lt;style&gt;<br>  .x { color: rgb(20, 0, 0) }<br>  #t { color: rgb(40, 0, 0) }<br>&lt;/style&gt;<br>&lt;p id=&quot;t&quot; class=&quot;x&quot;&gt;text&lt;/p&gt;<br>&lt;script&gt;<br>  console.log(getComputedStyle(document.getElementById(&#39;t&#39;)).color);<br>&lt;/script&gt;</pre><p><strong>Observed:</strong> Chrome 155 printed rgb(40, 0, 0), so the #t rule won. Because #t is also written second, this pair alone cannot separate specificity from order of appearance. Swap the two rules and run it again: the id rule still wins, which rules out order. The contests below separate the steps the same way.</p><p>Alongside the browser, a predictor applied the sort order to each contest and named a winner from the rules alone. The predictor was written from the specification before the first run and was not changed afterward. It models five of the six steps and leaves out context (shadow trees), which was not tested. One limit matters here: each rule’s specificity score was entered by hand, not computed by a parser, so the predictor tests the sort order and does not test a score calculator.</p><h3>Order of appearance breaks ties, and only ties</h3><p><strong>Verified (spec):</strong> in Level 5, order of appearance is the last step in the sort. A later declaration wins only when everything above it is equal.</p><p><strong>Observed:</strong> four contests.</p><ul><li><strong>Tag against tag:</strong> p written second beat p written first.</li><li><strong>Class against class:</strong> .x written second beat .x written first.</li><li><strong>Attribute selector against a class:</strong> .x written second beat [data-k] written first.</li><li><strong>Universal selector written later, against a tag selector:</strong> p written first beat * written second.</li></ul><p>The first three have equal specificity, so the later rule won. In the fourth, the tag selector outranks the universal selector, and being written first did not matter.</p><h3>Specificity is three columns, compared from the left</h3><p><strong>Verified (spec):</strong> Selectors Level 4 scores a selector as (A, B, C). A counts ids. B counts classes, attribute selectors and pseudo-classes. C counts type selectors and pseudo-elements. The universal selector adds nothing. Scores are compared column by column from A, and a large count in one column does not carry into the next. Implementations may cap each column at a size limit; values above the cap are clamped rather than overflowing.</p><p><strong>Observed:</strong> nine contests.</p><ul><li><strong>Class written first, tag written later:</strong> .x beat p.</li><li><strong>Id written first, class written later:</strong> #t beat .x.</li><li><strong>Two classes against one:</strong> .x.y beat .x.</li><li><strong>Three tag names against one:</strong> body div p beat p.</li><li><strong>11 classes against one id:</strong> #t beat 11 classes.</li><li><strong>300 classes against one id:</strong> #t beat 300 classes.</li><li><strong>:where() against a class:</strong> .x beat :where(#t).</li><li><strong>:is(#t, .q) against two classes:</strong> :is(#t, .q) beat .x.y.</li><li><strong>p:not(#z) against two classes:</strong> p:not(#z) beat .x.y.</li></ul><p>In every case the higher score won, including the two where it was written first. <strong>Inferred:</strong> this shows only that the columns did not spill over at 300 classes in Chrome 155. It does not find the clamp point the specification permits, and we did not look for one.</p><p><strong>Verified (spec):</strong> :where() counts as zero, while :is(), :not() and :has() take the score of the most specific selector in their argument, whichever argument actually matched. The three pseudo-class contests match that text. :has() was not tested.</p><h3>Inline styles and important</h3><p><strong>Verified (spec):</strong> important declarations form a higher group than normal ones, and a style attribute beats style-rule declarations of the same importance.</p><p><strong>Observed:</strong> five contests.</p><ul><li><strong>Style attribute against an id rule:</strong> style attribute beat #t rule.</li><li><strong>Style attribute against a class rule marked important:</strong> .x important beat style attribute.</li><li><strong>Both marked important:</strong> style attribute beat #t rule.</li><li><strong>Tag rule marked important against a plain id rule:</strong> p important beat #t.</li><li><strong>Two important rules, id written first:</strong> #t important beat .x important.</li></ul><p>Importance outranked specificity in the fourth contest. In the fifth both rules were important, so specificity decided and the id won. Importance is its own group above specificity; it does not replace it.</p><h3>Cascade layers rank groups of rules before specificity</h3><p><strong>Verified (spec):</strong> for normal declarations, a later layer beats an earlier one, and unlayered declarations count as a final layer, so they beat layered ones. For important declarations the order reverses: the earliest layer wins, and unlayered important declarations lose to layered ones.</p><p><strong>Observed:</strong> five contests.</p><ul><li><strong>Unlayered class against an id inside a layer:</strong> .x (unlayered) beat @layer base { #t }.</li><li><strong>Later layer with a class, against an earlier layer with an id:</strong> layer two’s .x beat layer one’s #t.</li><li><strong>Layer order set by where each layer is first named, not by where its rules are written:</strong> the layer named second beat the layer named first.</li><li><strong>Important in layer one against important in layer two:</strong> layer one beat layer two.</li><li><strong>Layered important against unlayered important:</strong> layered beat unlayered.</li></ul><p><strong>Chrome matched the specification in all five. Inferred:</strong> a team that mixes layers with important declarations will see priority run the opposite way from normal rules, which is a likely source of confusing results.</p><h3>Browser defaults lose to author rules</h3><p><strong>Observed:</strong> three contests. A universal selector, which scores zero, removed the default top margin from an h1 and replaced the default link color, although the browser&#39;s own selectors score higher. A rule inside a layer replaced the browser&#39;s default heading weight. The author rule won all three.</p><p><strong>Verified (spec):</strong> origin and importance is the first step in the sort, and author rules beat user-agent rules for normal declarations regardless of specificity. For important declarations the order reverses, and a user-agent important declaration beats an author one. We did not test that case.</p><h3>The scoreboard</h3><ul><li><strong>Order of appearance only:</strong> 9 of 26</li><li><strong>Specificity, then order:</strong> 16 of 26</li><li><strong>The sort order from the specification:</strong> 26 of 26</li></ul><p><strong>Observed:</strong> each added step explained contests that the previous model got wrong. The specificity-then-order model, which knows nothing about importance, inline styles, layers or origin, missed 10 contests: the inline style against an id rule, the important style attribute against an important id rule, the important tag rule against an id, all five layer contests, and the browser-default margin and link-color contests.</p><p><strong>Inferred:</strong> the 26 contests were designed to probe each step, so this is a coverage check of the sort order. It says nothing about how often each step decides a result in a real stylesheet.</p><h3>When no rule sets a property: inheritance</h3><p>The cascade chooses only among declarations that match the element. When it produces no value for a property, an inherited property takes the parent’s computed value, and any other property takes its initial value.</p><p><strong>Observed:</strong> we set 14 properties on a parent and read them on its child.</p><ul><li><strong>Passed to the child (8):</strong> color, font-family, font-size, line-height, text-align, visibility, cursor, letter-spacing.</li><li><strong>Did not (6):</strong> margin-top, padding-top, border-top-width, background-color, opacity, width.</li></ul><p>These are only the 14 we tested. Each property&#39;s definition states whether it inherits.</p><p><strong>Three keywords override this behavior.Observed:</strong> with a solid border style set on the child, border-top-width: inherit gave it the parent&#39;s 7px. We set the style because getComputedStyle reports a border width of 0px when the border style is none. color: initial gave the child black, ignoring the parent&#39;s color (the initial value is CanvasText, which is black in the default light scheme). unset behaved as inherit for color, which inherits, and as initial for margin-top, which does not: on an inline-block child, the margin went to 0px.</p><h3>Debugging a style that does not apply</h3><p><strong>Proposed</strong>, and common practice rather than something we measured: work down the cascade in order. Is anything marked important? Is there a style attribute? Which layer is each rule in? What is each selector’s score? Which rule is written last? The Styles tab in Chrome’s developer tools lists the declarations that were overridden, which gives you the shortlist.</p><h3>Limits</h3><ul><li>One browser, Chrome 155, and one property per contest.</li><li>26 contests we chose. They cover each step of the sort except context, and they do not sample real stylesheets.</li><li>Selector scores entered by hand, so the predictor checks the sort order and not a score calculator.</li><li>Not tested: shadow trees (the context step), the scope proximity rule, transitions, animations, user-origin styles and other browsers.</li></ul><h3>What to do with this</h3><ol><li><strong>Keep selectors low and flat.</strong> <strong>Proposed.</strong> When scores stay equal, order decides, and order is the easiest tiebreaker to track.</li><li><strong>Put third-party CSS in a layer.</strong> <strong>Proposed, resting on one observed contest:</strong> an unlayered class beat a layered id, so your own plain rules win over layered third-party rules without a specificity fight. The exception is important: layered important beat unlayered important, so a third-party important declaration inside a layer will beat your unlayered important one.</li><li><strong>Reserve important for cases you have tested.</strong> <strong>Proposed.</strong> It forms its own group above specificity and flips the layer order.</li><li><strong>Run your own contest when you doubt a rule.</strong> Edit the two rules in the snippet under The test, and it prints what your browser does.</li></ol><h3>Sources</h3><ul><li>W3C, CSS Cascading and Inheritance Level 5 (Candidate Recommendation Snapshot, 13 January 2022): <a href="https://www.w3.org/TR/css-cascade-5/">https://www.w3.org/TR/css-cascade-5/</a></li><li>W3C, Selectors Level 4, section 15, Calculating a selector’s specificity (Working Draft, 22 January 2026): <a href="https://www.w3.org/TR/selectors-4/">https://www.w3.org/TR/selectors-4/</a></li><li>Chrome for Developers, CSS features reference (the Styles tab lists overridden declarations): <a href="https://developer.chrome.com/docs/devtools/css/reference">https://developer.chrome.com/docs/devtools/css/reference</a></li><li>Chromium blink-dev, Intent to Ship: Decouple border-width, outline-width and column-rule-width values from their corresponding style values (getComputedStyle still reports 0px when the border style is none): https://groups.google.com/a/chromium.org/g/blink-dev/c/_50sVoTmZ3I</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d5b6175f16f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>