<?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 Haroon Tahir on Medium]]></title>
        <description><![CDATA[Stories by Haroon Tahir on Medium]]></description>
        <link>https://medium.com/@haroontahirr100?source=rss-a6887f9a0cc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YZSkxYEQc-CSzwcA</url>
            <title>Stories by Haroon Tahir on Medium</title>
            <link>https://medium.com/@haroontahirr100?source=rss-a6887f9a0cc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:07:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@haroontahirr100/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[Build the Harness Before the Hypothesis]]></title>
            <link>https://medium.com/@haroontahirr100/build-the-harness-before-the-hypothesis-3fda7394ac64?source=rss-a6887f9a0cc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fda7394ac64</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Haroon Tahir]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 21:42:38 GMT</pubDate>
            <atom:updated>2026-08-09T22:06:37.849Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turning an Unexplained Crash Into a Number You Can Chase</h3><h4>How a segfault on the JavaScript thread turned out to be a memory leak in React Native itself, and the measurement method that found it</h4><p>If you write React Native, you will eventually get a crash report that opens with EXC_BAD_ACCESS. It will point at the JavaScript thread. It will say the app touched address zero. And you will spend a day looking for a null pointer that does not exist.</p><p>This is a full account of one of those. It ends in a bug in the framework, a patch, and an upstream pull request, but the fix is not really the point. The point is the method, because the method transfers. By the end you should be able to take an unexplained memory crash in your own app and turn it into a number you can chase.</p><p>I have written this so you can follow it without knowing anything about Hermes going in. If you already know how a generational garbage collector works, skim section 2.</p><p><strong>What you will get out of this:</strong></p><ul><li>How to read a Hermes crash report properly, and why the scary header lies</li><li>Enough of a mental model of the Hermes heap to reason about it</li><li>A measurement harness you can build in an hour, with no instrumentation in your app code</li><li>How to isolate a leak by holding everything constant except one variable</li><li>Why resident memory and JavaScript heap are different pools, and what happens when you confuse them</li><li>The actual root cause, a retain cycle whose teardown code exists in the library and was not running on the path that mattered</li><li>The traps, including the two leaks that were not real and the infinite loop that a silenced log had been hiding</li></ul><h3>1. The symptom</h3><p>The report was one sentence long: the app closes on its own. No error, no freeze, no spinner. It was there and then it was not.</p><p>That is genuinely all I had. Nobody had looked at a log, nobody had a theory, and there were no reproduction steps because there was no pattern anyone could see. The one extra detail I could get was that it sometimes happened while the app was sitting idle, phone on the desk, nobody touching it. That single observation sent my first day in the wrong direction, and I will come back to why.</p><p>Everything past this point is what I went and found. I pulled the crash log off the device, and it started like this:</p><pre>Exception Type:  EXC_BAD_ACCESS (SIGSEGV)<br>Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000000<br>Triggered by Thread: 6  com.facebook.react.runtime.JavaScript</pre><p>KERN_INVALID_ADDRESS at 0x0 is a null pointer dereference. The thread name says it happened on the JavaScript thread. So: some native module handed JavaScript a null and something dereferenced it.</p><p>That reading is wrong, and the crash report tells you so about six lines further down.</p><figure><img alt="Crash Report" src="https://cdn-images-1.medium.com/max/1024/1*ThueKcS3cbUGqEGfQqtE-g.png" /><figcaption>Crash report</figcaption></figure><h3>2. Read the whole stack, not the header</h3><p>Here are the crashing frames, trimmed:</p><pre>hermes::vm::GCBase::oom(std::error_code)<br>hermes::vm::HadesGC::OldGen::allocSlow(unsigned int)<br>hermes::vm::HadesGC::youngGenCollection(...)<br>...<br>hermes::vm::JSObject::create(...)<br>hermes::vm::Interpreter::...<br>drainMicrotasks</pre><p>Read that from the bottom up, because that is the order it happened in.</p><p>The app was draining its microtask queue. Some ordinary piece of JavaScript went to create an object. Creating an object needs memory, so Hermes ran a young generation collection to make room. The collection tried to promote surviving objects into the old generation. The old generation could not grow. And GCBase::oom is the function Hermes calls when it has decided it cannot continue.</p><p>The EXC_BAD_ACCESS at 0x0 is not the bug. It happens further along the same call chain, inside Hermes&#39;s fatal error path, after the runtime has already decided it cannot continue. Whether that final segfault is deliberate or incidental does not really matter. What matters is the ordering: the OOM caused the segfault, not the other way round. It is the last twitch, not the wound.</p><p><strong>This is the single most useful thing in the article, so I will say it plainly: a </strong>SIGSEGV<strong> on the Hermes thread is frequently an out of memory in disguise. Read down to </strong>GCBase::oom<strong> before you go looking for a null pointer.</strong></p><h3>A short detour: how Hermes uses memory</h3><p>You do not need the full design, but you need enough to know what “the old generation could not grow” means.</p><p>Hermes uses a garbage collector called Hades. It is generational, which means it splits the heap into two areas based on a simple observation about real programs: most objects die young. A response body parsed, mapped, rendered and dropped lives for milliseconds. A Redux store lives for the life of the app.</p><ul><li><strong>Young generation.</strong> Small. New objects are allocated here. Collected often and cheaply, because most of what is in there is already garbage by the time the collector looks. Anything still alive gets promoted.</li><li><strong>Old generation.</strong> Large. Holds objects that survived. Collected far less often, and largely on a background thread so it does not pause your JavaScript thread for long.</li></ul><p>Now the important part for this bug. <strong>Hermes runs with a configured maximum heap size, and the default is 3 GiB.</strong> It has not always been: the default was 512 MB, then 1 GB, before being raised to 3 GiB on the way to Hermes becoming React Native’s default engine, and React Native has overridden it on Android at various points. So check what your build actually uses instead of trusting a number from a blog post, including this one.</p><p>Whatever the value is, it is not the device’s memory. It is a limit the runtime imposes on itself. When the old generation needs to grow past it, there is no negotiation and no fallback. GCBase::oom, and the process dies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqwrWk3WkM1JBtHGGv0SFQ.png" /><figcaption>Hermes heap</figcaption></figure><p>So the crash tells us something quite specific: this app’s JavaScript heap grew toward <em>gigabytes</em>. That is not a temporary spike from decoding a big image. You do not accidentally allocate two and a half gigabytes of live JavaScript objects. Something was holding references to everything and never letting go.</p><h3>The detail that ruled out half the possibilities</h3><p>It also crashed on the iOS Simulator.</p><p>That sounds like a footnote and it is actually the strongest single piece of evidence in the whole investigation. A simulator app is an ordinary process on a Mac with a large amount of RAM and swap. iOS on a real device kills apps under physical memory pressure through a mechanism called jetsam, and jetsam does not exist on the simulator in any meaningful form.</p><p>So this was not “the phone ran out of memory.” It was Hermes hitting its own logical ceiling, on a machine with memory to spare. That rules out “the test device is too small,” it rules out image cache pressure from the OS, and it points at one thing: <strong>unbounded retention in JavaScript.</strong></p><p>When you get a memory crash, try to reproduce it on the simulator early. If it reproduces there, you have just eliminated an entire category of explanations.</p><h3>3. Build the harness before you theorize</h3><p>At this point I had a good story and zero numbers. This is the moment where most memory investigations go wrong, because a good story is extremely convincing and costs nothing to produce. I had three theories by lunchtime and all of them were plausible. Plausible is worthless here.</p><p>So, no theories yet. Two tools, both of which took under an hour to set up.</p><h3>Measuring memory</h3><p>Because a simulator app is a normal host process, macOS’s own tooling works on it. footprint reports phys_footprint, which is the same accounting metric iOS itself uses to decide whether your app is being greedy.</p><pre>#!/bin/bash<br># mem_sample.sh &lt;label&gt; - print phys_footprint of the running app<br>HPID=$(ps -Ao pid,comm | grep -i &quot;MyApp.app/MyApp&quot; | grep -v grep | awk &#39;{print $1}&#39;)<br>echo -n &quot;$1  &quot;<br>footprint &quot;$HPID&quot; | grep -iE &quot;phys_footprint:&quot;</pre><p>No SDK, no instrumentation in the app, nothing to accidentally ship. Run it in a loop and you have a time series.</p><h3>Making the interaction repeatable</h3><p>A memory number is meaningless unless the thing you did to produce it is repeatable. If I navigate by hand, I take a slightly different path every time, I pause for different lengths, and every measurement is contaminated.</p><p>So the UI gets driven by a script. I used <a href="https://maestro.dev/">Maestro</a>, which describes a flow in YAML:</p><pre>appId: com.example.myapp<br>---<br>- launchApp<br>- repeat:<br>    times: 10<br>    commands:<br>      - tapOn:<br>          id: &quot;open-detail-screen&quot;<br>      - waitForAnimationToEnd<br>      - tapOn:<br>          id: &quot;header-back-button&quot;<br>      - waitForAnimationToEnd</pre><p>One small gotcha if you copy this: Maestro’s back command is Android and web only, so on iOS you tap the back button rather than pressing a system key. Give it a test ID and the flow stays readable.</p><p>Now “open and close this one screen ten times” is something I can run at any point in the app’s life and compare against itself. Every delta becomes attributable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wt7eXA01WznCj5JOGwHdAg.png" /><figcaption>Harness</figcaption></figure><p><strong>The general principle:</strong> before you form a hypothesis about a leak, build the thing that can falsify it. Cheaply. If testing a theory costs you an afternoon, you will subconsciously start defending your theories instead of testing them.</p><h3>4. The first surprise: the suspects were not even loaded</h3><p>The test account I was measuring against turned out to be empty. No data behind any of the screens I was most suspicious of.</p><p>That instantly killed my two leading theories. A third-party SDK holding onto a growing cache could not be the leak, because there was nothing for it to cache. An endlessly scrolling list holding onto rendered rows could not be the leak, because there was nothing to scroll.</p><p>This was frustrating for about a minute and then it was excellent news. It meant the leak was in something more fundamental than feature data. And it forced a cleaner experiment: forget content, just navigate and watch.</p><p>I ran a loop over the whole app, thirty rounds, and sampled memory after each round.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dW5xI2Ay5qdGHDfuSYGCUg.png" /><figcaption>Linear growth</figcaption></figure><p>Memory grew about 14 MB per round. Linearly. No plateau, no sawtooth, no sign of the garbage collector ever winning anything back.</p><p>That shape matters. Learn to read it:</p><ul><li><strong>Rises and then flattens:</strong> a cache filling up to its bound. Normal.</li><li><strong>Sawtooth, rising and dropping:</strong> allocation and collection. Healthy.</li><li><strong>Straight line up, forever:</strong> a leak. Something is retained on every iteration and never released.</li></ul><p>We had a straight line.</p><h3>5. Isolate by holding everything else constant</h3><p>A whole-app loop tells you that you leak. It does not tell you where. So next: the same loop, one screen at a time, ten open-and-close cycles each, memory sampled before and after.</p><p><a href="https://gist.github.com/haroon-afzal-tahir/214f9a3f48fc3608b31f0064bd55cd46">https://gist.github.com/haroon-afzal-tahir/214f9a3f48fc3608b31f0064bd55cd46</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mAvlNy1TohK3Vx1bN53kw.png" /><figcaption>Isolation tests</figcaption></figure><p>Look at the split. It does not fall along feature lines. It falls along navigation lines.</p><p>Bottom tabs are mounted once and kept alive. They leak nothing meaningful. Screens pushed onto the navigation stack and then popped leak 5 to 6 MB every single time you open them.</p><p>Both of the leaking screens happened to be my original suspects, which is a good lesson in how easy it is to fool yourself. One had a virtualized list in it. The other had a heavy third-party SDK. If I had stopped here I would have written a confident postmortem about list virtualization and shipped a fix that did nothing.</p><p>So I kept going and removed things.</p><ul><li>Took the virtualized list out of the first one. Still leaked.</li><li>Took the third-party SDK out of the second one. Still leaked.</li><li>Took the animation library out of both. Still leaked.</li><li>Then I ran the same loop on the plainest pushed screen in the app. No list, no SDK, no animations, essentially some text and a few rows. <strong>It leaked the same amount.</strong></li></ul><p>That result is the hinge of the entire investigation. The leak is <strong>content-independent</strong>. Everything inside the screen can change, including removing almost all of it, and the number does not move.</p><p>The only property the leaking screens shared was structural: they were pushed onto the native stack and popped off it.</p><p><strong>When you can change everything inside a component and the leak does not change, stop looking inside the component.</strong> You are no longer debugging your app. You are debugging whatever mounts and unmounts it.</p><h3>6. Two things the data forced me to unlearn</h3><h3>“It crashes while idle” does not mean idle is leaking</h3><p>This was the first day’s wrong turn, and it came directly from taking the bug report’s most vivid detail as the most important one.</p><p>So I measured it. App in the foreground, untouched, sampled over a long stretch: about 0.7 MB per minute, drifting up and down. That is the garbage collector breathing, not a leak. The app has polling on an always-mounted header component that fires every 30 to 60 seconds, but the query cache overwrites the previous response in place, so it does not accumulate.</p><p>Here is what is actually happening. Navigation fills the heap over hours. Idle adds almost nothing. But the heap is now sitting just under the ceiling, and the next allocation of any size at all is the one that cannot be satisfied. A routine poll on a timer is the perfect candidate. So the crash <em>lands</em> during idle while having been <em>caused</em> entirely by navigation.</p><p>The crash stack said this all along. The fatal allocation is inside a microtask during a young generation collection, which is exactly what a background poll resolving a promise looks like.</p><p><strong>A crash’s timing tells you when the heap ran out. It does not tell you what filled it.</strong></p><h3>The leak accelerates, which is why it feels random</h3><p>I measured the same screen’s per-open cost at different points in the app’s life.</p><ul><li>At a 500 MB baseline: about 1.7 MB retained per open</li><li>At a 950 MB baseline: about 7.2 MB retained per open</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmZ3Zw-4eKztTJCFWFTG8Q.png" /><figcaption>Accelerating cost chart</figcaption></figure><p>The cost per iteration goes up as the heap grows. I did not chase down exactly why, and I want to be careful here because it would be easy to invent a satisfying explanation. Bigger heaps plausibly mean more expensive collections, more fragmentation and more retained structure to walk on each pass, but that is my hypothesis, not something I proved. The measurement itself is solid and it is reproducible, and it is the measurement that matters for what follows.</p><p>This explains the reporting pattern perfectly. “It crashes after a while” sounds like a threshold effect, and I had been treating it as one. It is not. The growth curve bends upward, so the last hour of a session is dramatically worse than the first, and the crash always arrives sooner than a linear extrapolation predicts.</p><h3>7. Resident memory is not the JavaScript heap</h3><p>Here is where a lot of people, including me for a couple of hours, tie themselves in knots.</p><p>phys_footprint tells you how much memory the <em>process</em> is using. A React Native process holds several distinct pools:</p><ul><li>The Hermes JavaScript heap, which is what throws GCBase::oom</li><li>Native heap allocations from C++ objects, via malloc</li><li>CoreAnimation layer backing stores and decoded images</li><li>Framework and binary mappings, thread stacks, and so on</li></ul><p>footprint gives you one number covering all of it. If that number goes up you know <em>something</em> leaked. You do not know <em>what</em>.</p><p>vmmap breaks the process down by region, and that is what localized this one. The growth was concentrated in MALLOC_SMALL. It was not in the CoreAnimation regions, so this was not leaked layers or image buffers. It was not dominated by the Hermes GC region either.</p><p>So the growing pool was <strong>native C++ objects allocated per screen mount and never freed.</strong></p><p>But the crash was a JavaScript heap OOM. Both statements are true at the same time, and the reason is that they are chained. A leaked native view keeps its React component instance alive. That component holds its props, its hooks, its closures, its children. So the JavaScript tree behind every leaked screen stays reachable forever too. Native memory and JS memory climb together, and the JS side is the one that has a hard ceiling to hit.</p><p>One thing I should be upfront about, because it is the first hole a careful reader will look for. My measured sessions never got anywhere near that ceiling. The isolation runs topped out around a gigabyte of total process footprint. The crashes happened after hours of real use, and I never sat and watched the JS heap cross 3 GB with my own eyes. What I had was a growth rate that never stops, a mechanism that explains it, and a crash stack that says where it ends up. That is enough to act on, but it is an inference and not a direct observation, and those are different things.</p><p><strong>If you want to read the pool that actually kills you, read it directly.</strong> HermesInternal.getInstrumentedStats() reports real JS heap numbers at runtime, including in release builds. It is an internal API, so treat it as something that can change under you and keep it behind a guard. global.gc() only exists in dev builds. Either way, do not infer your JS heap from resident memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjfyLt3IhinTRedD8kGd3Q.png" /><figcaption>Memory pools diagram</figcaption></figure><h3>8. Root cause: a teardown hook that nobody calls anymore</h3><p>Content-independent, structural, native, per screen push. With that description I went looking through the issue tracker for react-native-screens, the library that backs the native navigation stack, and found the shape of it already documented:</p><ul><li><a href="https://github.com/software-mansion/react-native-screens/issues/1379">#1379 (iOS)</a>: views not deallocating on pop</li><li><a href="https://github.com/software-mansion/react-native-screens/issues/3755">#3755 (Android, Fabric)</a>: destroyed fragments retained through Fabric’s view state map</li><li><a href="https://github.com/software-mansion/react-native-screens/issues/1754">#1754</a>: the iOS retain cycle described precisely</li></ul><p>The iOS mechanism is a textbook Objective-C retain cycle:</p><ul><li>RNSScreenView holds its view controller with a strong reference: @property (nonatomic, retain) RNSScreen *controller;</li><li>RNSScreen, being a UIViewController, holds its view strongly through UIViewController.view, and also keeps a second strong reference in an _initialView instance variable that is not marked __weak.</li></ul><p>Two objects, each holding the other. Under reference counting, neither one’s count ever reaches zero, so neither is ever freed, and everything they reference stays alive with them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zaBcvTyLguhWMhFIn3P7g.png" /><figcaption>Retain cycle diagram</figcaption></figure><p>Now the part that makes this genuinely interesting rather than just a bug.</p><p><strong>The library already contains the code that breaks this cycle.</strong> -[RNSScreenView invalidateImpl] sets _controller to nil, deferred onto the main queue. Cycle broken, both objects released. It exists. It works.</p><p>The problem is what triggers it. Inside the library, the only caller of invalidateImpl is -invalidate.</p><p>Here is where I have to be careful, because there is a tidy version of this story that I believed for a while and that turns out not to survive reading the source.</p><p>The tidy version goes: invalidate comes from RCTInvalidating, that protocol belongs to the old architecture, Fabric never calls it, so the teardown is dead code on the New Architecture. Clean, memorable, and not quite true.</p><p>Fabric has its own invalidate. RCTComponentViewProtocol declares it, with the comment &quot;called for unmounted components that won&#39;t be moved to a recycle pool.&quot; RCTComponentViewRegistry calls it when a deleted view is handed back and its class has opted out of recycling. And RNSScreenView does opt out, because +shouldBeRecycled returns NO. So the wiring exists on both sides, and the statement &quot;Fabric never calls invalidate&quot; is wrong as a general claim about the framework.</p><p>What is true is that it was not breaking the cycle here. Screens measurably survived being popped, and calling invalidateImpl from the Fabric unmount path made them transient again. Both halves of that are reproducible.</p><p>Why the existing path does not already do the job, I do not know for certain. The registry only invalidates on the Delete mutation, so the behavior is consistent with that delete not arriving, or not arriving while nilling the controller would still help. That is a hypothesis. I have not instrumented -invalidate on a pop to confirm it, and until I do, it stays labelled as one.</p><p>[FIGURE 9: where invalidate comes from on each architecture]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NT5aeVaizddSqGbs6Hsl6g.png" /><figcaption>Where invalidate comes from on each architecture</figcaption></figure><p>I would rather ship an article with a hole in it than a satisfying explanation I cannot defend. The practical lesson survives either way, and it is a more useful one than “Fabric broke it”: <strong>teardown code that depends on a hook you do not own is only as good as your evidence that the hook actually fires.</strong> Nothing throws when cleanup silently stops running. The only symptom is memory going up, slowly, in production, for months.</p><h3>9. The fix</h3><p>Native bug, so no amount of clever app code fixes it. The change goes into the library, applied with patch-package against the pinned version.</p><p><strong>iOS.</strong> Call the library’s existing teardown from the Fabric unmount path. In RNSScreenStack&#39;s unmountChildComponentView:, invoke invalidateImpl on the screen view being unmounted.</p><p>Two details make this safe, and both are the library’s own design rather than anything I invented. invalidateImpl nils the controller on a later main queue turn, not immediately. And the line directly above my patch is [screenChildComponent.controller setViewToSnapshot], so the pop animation that is still running is driving a snapshot, not the live view. By the time the deferred block runs, the pop has finished, the navigation controller has released the RNSScreen, the last strong reference is gone, and the whole screen deallocates. +shouldBeRecycled returning NO is what makes it safe to tear the view down at all: it is never coming back from a recycle pool.</p><p><strong>Android.</strong> Null Screen.fragmentWrapper so Fabric&#39;s view state map cannot keep a destroyed fragment alive, in ScreenFragment.onDestroy and again in ScreenViewManager.onDropViewInstance. This is a backport of the community&#39;s proposed fix in <a href="https://github.com/software-mansion/react-native-screens/pull/3855">#3855</a>.</p><p>The Android half is worth more than one line, because the naive version of it breaks things and I found that out the slow way. Nulling unconditionally in onDestroy also detaches a screen that is merely being hidden rather than dismissed, which blanks the screen on back navigation. Nulling unconditionally in onDropViewInstance catches screens that are only temporarily covered by a modal, and when the modal closes the library rebuilds the container and remounts the whole navigator subtree under it. So both sites need a gate that asks whether the screen is genuinely gone: an identity check that the wrapper still belongs to this fragment, and a container membership check rather than trusting isAdded, which is transiently false for a covered screen.</p><p>If you take one thing from this section, take that. “Free the thing on teardown” is easy. Working out which of the several events that look like teardown actually is teardown is where the real work is.</p><h3>Verifying it, and why not with a heap snapshot</h3><p>The obvious verification is a JavaScript heap snapshot before and after. I could not take one, for reasons covered in the next section. So I used <strong>Xcode Instruments</strong>, with the Leaks and Allocations templates.</p><p>Instruments is the right tool here anyway, because it reads the native side directly, which is where these objects live. Filter the allocation list to RNSScreen and RNSScreenView and the result is unambiguous.</p><p>Before the patch: the live count climbs with every push and pop and never comes back down.</p><p>After the patch: 4 created, 4 freed, 3 currently live, and the 3 are the screens actually on the stack. They show up as <strong>transient</strong> rather than persistent. Screens deallocate on pop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKLQIZ2i-6wK_X_KsgsE5A.png" /><figcaption>Instruments before and after</figcaption></figure><p>That is the whole verification. Not “memory looks better,” which is the kind of claim that survives a week and then quietly falls apart. A specific class, a specific count, matching a specific expectation.</p><h3>10. The traps, and two leaks that were not real</h3><p>Clean write-ups are a lie about how debugging works. These detours took real days and each one teaches something.</p><h3>The debugger crashed on attach</h3><p>The natural move when you suspect a JavaScript leak is to take a heap snapshot from React Native DevTools. Every attempt crashed the app:</p><pre>emitDebuggerSessionCreated<br>  -&gt; Debugger::runUntilValidPauseLocation<br>    -&gt; CodeBlock::getSourceLocation   (null dereference)</pre><p>This is inspector instability on a recent RN version with the New Architecture. It is not related to our leak. But it blocked the most obvious diagnostic path entirely and forced the whole investigation onto native tooling.</p><p>Worth naming, because “the standard tool is broken on this version” is a real condition and you should recognise it quickly instead of assuming your app is somehow at fault.</p><h3>Thousands of live network objects that were not a leak</h3><p>Instruments’ Allocations view showed thousands of live NSURLRequest and CFHTTPMessage objects. Alarming. It looks exactly like a networking layer that never releases responses.</p><p>It was React Native’s development-time network inspection. The interceptor that backs it lives under React Native’s dev support tree, it is installed only when you are debugging, and holding onto requests is the entire point of it: that is how they show up in a list you can click through. None of it is active in a release build. Application networking was clean.</p><p><strong>Do not chase a development tooling artifact as a production leak.</strong> Before filing a finding from a profiler, ask whether the thing you are looking at exists in a release build at all.</p><h3>The other leak, which was real but tiny</h3><p>The Leaks pass did find genuine leaks in the animation library, specifically MutationNode and some Fabric shadow nodes. Known upstream behavior, and real.</p><p>But: kilobytes. Roughly a thousandth of the screen leak. It looked significant only because a keyboard avoiding component was mounted on <em>every</em> screen in the app, so it was leaking constantly.</p><p>The app side fix was to make keyboard avoidance opt in, since only a couple of screens have text inputs at all. Which produced a small practical lesson: when you audit for “which screens have inputs,” grep for the abstraction your codebase actually uses. Ours wraps every input in a house component, so grepping for React Native’s TextInput found almost nothing and would have made me miss real screens.</p><p>Keep proportion. A confirmed leak that is 0.1% of your problem is not your problem.</p><h3>The silenced warning that was hiding an infinite loop</h3><p>This one is my favourite and it has nothing to do with memory.</p><p>While reading through startup code I found a suppressed warning from the push notification library. Somebody had silenced it a while back because it was noisy.</p><p>The warning was a symptom. The app was re-registering for push notifications <em>inside</em> the push token listener. Fetching the token internally re-fetches the device token, which makes the native module re-emit the token event, which triggers the listener, which re-registers. Fetch, emit, fetch, emit, forever, hammering an external service the entire time.</p><p>Silencing the log removed the evidence and left the loop running.</p><p>The fix was to compare the incoming token against the stored one and only re-register when it has genuinely changed. But the takeaway is the general form:</p><p><strong>If silencing a log “fixes” a problem, you did not fix anything. Find out what keeps re-triggering it.</strong></p><p>Also worth noting: the code already had a guard that should have prevented this loop. It was there, it looked correct on the page, and the loop was happening anyway. Observed behavior beats a guard that looks right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCUd4n1RGxi40hYEMi3uDw.png" /><figcaption>The push token loop</figcaption></figure><h3>11. Safety nets, and being honest about what they are</h3><p>The patch is the fix. These are separate and they exist to keep a long session honest, not to solve anything:</p><ul><li><strong>Pause background polling.</strong> Wire the query client’s focus manager to app state so timers stop when the app is backgrounded.</li><li><strong>Trim on memory pressure.</strong> On the iOS memoryWarning event, drop inactive query caches and decoded image caches. Inactive only, so a visible screen never blanks out.</li><li><strong>Clear deeply on background.</strong> A backgrounded app needs none of its cache. Clear at the moment of backgrounding, not on a timer, because iOS suspends the process within seconds and a “release after 20 minutes” JavaScript timer will simply never run.</li><li><strong>Watch the real heap.</strong> Sample HermesInternal.getInstrumentedStats() and trim when it crosses a high water mark. This is the one runtime reading of the pool that actually causes the crash.</li></ul><p>None of these fix a native leak. They buy headroom. I want to be clear about that because “we added memory pressure handling” is the kind of thing that gets written in a ticket and then read, later, as if the bug was solved.</p><h3>12. Sending it back</h3><p>The iOS fix was not in any stable release, so it went upstream as <a href="https://github.com/software-mansion/react-native-screens/pull/4433">react-native-screens#4433</a>, wiring the library’s existing invalidateImpl teardown into the Fabric unmount path. The Android half is tracked by the community&#39;s #3855.</p><p>When a stable release carries both, the local patch gets deleted. That is the whole point of a patch. It is a loan against upstream, not a fork.</p><p>If you are on a fast moving stack, this will keep happening to you. Libraries that support two React Native architectures at once accumulate code paths that are correct under one and dead under the other. Reporting what you find is a small amount of work and it is the difference between your team carrying a patch forever and everyone getting the fix.</p><h3>13. The method, extracted</h3><p>Strip out the specifics and this is a procedure you can run on any memory bug:</p><ol><li><strong>Read the entire crash stack.</strong> The exception header describes how the process died, not why. On Hermes, walk down to GCBase::oom.</li><li><strong>Try to reproduce on the simulator.</strong> If it reproduces, you have eliminated physical memory pressure and you are looking at logical retention.</li><li><strong>Build the harness before the hypothesis.</strong> Something that samples memory, something that drives the UI identically every time. An hour of work that pays for itself immediately.</li><li><strong>Get a growth curve.</strong> Flat, sawtooth, bounded rise or straight line up. Only the last one is a leak.</li><li><strong>Isolate by holding everything constant but one variable.</strong> One screen at a time, same number of iterations, same path.</li><li><strong>Try to make the leak go away by removing things.</strong> If removing the contents changes nothing, the leak is structural and you should stop reading your own code.</li><li><strong>Localize the pool.</strong> vmmap regions, or Instruments. Resident memory growing tells you nothing about which allocator is responsible.</li><li><strong>Search upstream with your symptom, not your guess.</strong> “Content-independent leak on screen push, Fabric” finds the issue. “React Native memory leak” does not.</li><li><strong>Patch, then verify with object counts.</strong> Created versus freed for a specific class. Not vibes.</li><li><strong>Send it upstream.</strong></li></ol><p>And the four things I would tell a past version of myself:</p><p><strong>The header of a crash report is the least reliable line in it.</strong> It describes the final moment. Everything explanatory is below it.</p><p><strong>Plausible theories are free, so treat them as worthless until measured.</strong> The list library was a great theory. So was the third-party SDK. I believed both of them, and both were wrong.</p><p><strong>A negative result is a real result.</strong> “Removing the list changed nothing” felt like a wasted afternoon at the time. It was the most informative measurement in the whole investigation, because it is what eliminated the app as a suspect.</p><p><strong>Silencing a warning is not fixing it.</strong> Somewhere in your codebase there is a suppressed log that is quietly telling the truth.</p><h3>14. Final notes</h3><h3>What this applies to</h3><p>React Native 0.86 on the New Architecture, with Hermes, and react-native-screens 4.26. Fabric matters here, Paper almost certainly does not have this problem, and the numbers in the isolation table came off the iOS Simulator. If you are on an older React Native or the old architecture, treat the method as transferable and the specific fix as probably irrelevant to you.</p><p>The measurements are from one app on one machine. The slope of the growth and the 5 to 6 MB per pushed screen will not be your numbers. The shape will be.</p><h3>What is still open</h3><p>The honest ledger, because an article that only lists what it solved is not much use to anyone:</p><p><strong>Why the existing invalidate path did not break the cycle.</strong> Covered in section 8. Fabric has an invalidate hook and calls it for views that opt out of recycling, which RNSScreenView does. My patch works and the object counts prove it works. The mechanism behind why it was needed at all is not nailed down. The next step is a breakpoint in -invalidate during a pop, which I have not run.</p><p><strong>The heap ceiling was inferred, not observed.</strong> My test sessions peaked around a gigabyte of process footprint. The crashes took hours of real use. I never watched the JS heap cross 3 GiB directly. Growth rate plus a crash stack is a strong argument, not a measurement.</p><p><strong>The upstream PR is open, not merged.</strong> Until it lands and ships in a stable release, this is a local patch, and local patches are a debt you pay on every upgrade.</p><p>If you can explain the invalidate behavior, I would genuinely like to know. That is the one loose end I would most like closed, and I would rather be corrected in public than be quietly wrong.</p><h3>Running this on your own app</h3><p>The whole harness is two things and neither takes long:</p><ol><li>A loop that reads phys_footprint for your process. On a simulator that is just footprint &lt;pid&gt; on the host Mac.</li><li>Something that drives the same UI path every time. I used Maestro. Anything deterministic works, including a script tapping fixed coordinates.</li></ol><p>Then: baseline, run the loop 10 times, measure again. Repeat per screen. If a number grows and never comes back, you have a leak and you already know which screen owns it. Everything else in this article is what I did after that point.</p><h3>Credit</h3><p>The retain cycle was described in the react-native-screens issue tracker before I went looking, in <a href="https://github.com/software-mansion/react-native-screens/issues/1379">#1379</a>, <a href="https://github.com/software-mansion/react-native-screens/issues/1754">#1754</a> and <a href="https://github.com/software-mansion/react-native-screens/issues/3755">#3755</a>, and the Android fix is a backport of the community’s <a href="https://github.com/software-mansion/react-native-screens/pull/3855">#3855</a>. I did not discover this cycle. I found it in my app, measured its cost, worked out why the library’s existing teardown was not running on the pop path, and wired it into the path Fabric takes. The people who wrote those issues did the hard part first.</p><p>Also worth saying plainly: the teardown code I “fixed” was already correct and already in the library. Most of what looks like clever debugging in hindsight was just measuring carefully enough to find the one line that was not being reached.</p><h3>One thing I would do differently</h3><p>I spent the first day on the idle observation because it was the most vivid detail in the report. Vividness is not evidence. The right first move was the one I made on day two: build the harness, get a growth curve, and let the shape of the curve tell me where to look.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fda7394ac64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>