maninak

I Shoved a Whole P2P Git Node in a Browser Tab. It Fought Back.

My in-browser node took all night to list one repo's issues. These are my trials and tribulations while working on it.

Published
Reading time
16 minutes
Contents
Replies
join in

The Grove Build Log, chapter 1. Previously, I explained why I put a whole Radicle node inside a browser tab. This is the chapter where the tab fought back.

So here’s a thing I built. You open a URL, and the tab clones a full git repo, way beyond just the code. Packfiles over the wire, delta resolution, signature verification, refs, issues, patches, all of it running inside the tab, with no backend anywhere to ask for help.

It (eventually…) worked fine on small repos. Then I pointed it at heartwood, Radicle’s own reference implementation. Back in July it had about 2,300 refs from 54 peers, 948 patches, 236 issues and years of collaboration history. The clone finished. The issues list didn’t show. I left the computer on overnight, and the next day there they were, slow as a teenager on Saturday morning. Today those same lists show up in about a minute.

Grove in dark mode with heartwood open: its Issues tab reads 269 and its Patches tab 1085. Below them, heartwood's file tree. On the right, the repo's name and description, its languages (98.9% Rust) and facts: three delegates, 84.1K lines of code and 3,368 commits. (open full size)
Heartwood in Grove today. Those two numbers on the Issues and Patches tabs are the ones that used to take all night.

Why a tab has to do all of this

Grove is a browser client for Radicle, a peer-to-peer network for code collaboration built on plain git. There’s no center to that code forge. That’s the whole point. A repository lives on whichever nodes choose to seed it, and your identity is a keypair you hold yourself on your device. No centralized database crutches here. The things a forge keeps in its database (issues, patches, review comments) are stored inside git itself, as chains of signed operations, and they replicate from peer to peer along with the code.

So a Radicle client can’t call GET /api/issues, because nobody is holding that answer for it. To show an issues list you gotta clone the repo, replay each issue’s history of operations, verify every signature and compute the list yourself. Every client is its own backend. In Grove’s case the client lives in a browser tab. It dials other heartwood (a.k.a. reference Radicle implementation) nodes through a small WebSocket relay, speaks the real binary Radicle protocol, verifies everything that arrives and keeps it in the browser’s private filesystem (OPFS), so your repos are still there after you close the tab.

So when the issues list is slow, there’s no “someone’s server” I could blame (🥲). My code is to blame. I suck. Mom, I’m a failure.

My four theories, down the drain

I was so confident in each, up until it crumbled before me.

First, though, I built a benchmark. Do this. Whatever you’re chasing, build a fast feedback loop first. The benchmark runs in Node.js instead of the browser, reuses Grove’s own code, does a real clone of a repo from a local node, and then times every step of turning raw git data into a pretty and cute issues list. On heartwood one attempt took about 40 minutes, so I pointed it at a small repo first and got a feedback loop measured in seconds allowing me to iterate a tad faster.

Theory one: it’s the network. After the main clone, Grove fetches each peer’s namespace (their own copy of the repo’s refs) separately, to pick up their issues and patches. I pictured hundreds of round trips piling up, and “batch those fetches” sat at the top of my to-do list. On the benchmark, the clone plus every per-peer fetch came to 21 packfiles, written in about four minutes. There were never hundreds of round trips. The fix I was about to build was aimed at a cost that didn’t exist.

Theory two: those fetches are thin packs. Git doesn’t send objects one by one. It squeezes them into a packfile, where every object is compressed and many are stored only as a delta, a diff against some other object. Before Grove can show you a single issue, every object in those packs has to be inflated and every delta rebuilt into the full object. That’s real CPU work, so Grove hands it to a pool of up to eight WebAssembly decode workers running side by side.

On the per-peer packfiles, those workers kept failing, with errors that said “inflate failed” and “output exceeds size cap”. Each pack they choked on fell back to a slower JavaScript path that decoded it fine in the end, so the packs still landed, just slower. My explanation was that the per-peer fetches had to be thin packs. In a thin pack, a delta can point at an object the receiver already has, outside the pack itself. I figured the pool couldn’t handle those because of I/O overhead, so I should give up on decoding them in parallel.

Wrong on every count. Grove never even asks a peer for a thin pack, and git doesn’t send one unasked. The failures were a decoder bug, and once it was fixed those fetches decoded in parallel just fine, with all eight workers engaged, about 330% CPU at the peak! Now we’re talking!

Theory three: replaying the operations is just expensive. Every Radicle issue and patch is a log of operations (its init, a comment, an edit). Grove replays each issue’s or patch’s log to work out its current state. Over a thousand of them, signatures everywhere… of course it’s slow, that’s what correctness costs.

Then I profiled the patch pass, the code that works out every patch’s current state. Replaying the operations took 0.1% of the time. Reading objects from storage took about 47%, and verifying ed25519 signatures in pure JavaScript took 36.4%.

One long bar split into where the patch pass spent its time, with a curly brace under each part pointing at its label. Reading objects from storage takes the first 47%, checking ed25519 signatures the next 36.4%, and everything else the last 16.5%. Between the signatures and everything else sits a single thin highlighted line, the 0.1% spent replaying the operations, with an arrow pointing at it from its label.

Where the patch pass spent its time. “Everything else” is every other line of the profile added together. The part I was sure was slow is the highlighted sliver, and even that is drawn about three times wider than it really is, or you’d never see it. What is this, a bar for ants?

Every operation is stored as a git commit plus a few small files, so replaying one takes a few reads and one signature check. That should be cheap. Yet the profile said Grove was reading and verifying way more than its operations needed, and I had no idea why.

Theory four: verifying signatures one at a time holds up the clone. Grove was checking signatures one after another, so I suspected the clone was stuck waiting on them. An earlier investigation of mine showed as much when cloning FreeBSD’s multi-GiB repo in Node.js.

But a browser trace of the heartwood clone showed the node’s SharedWorker (a worker all tabs share) and my “pack-io” (the worker that deals with the packfiles) sitting idle for much of the first five or so seconds.

A Chrome DevTools Performance flame chart, about 29 seconds of a heartwood clone in Grove. Near the top, a long bar labeled grove:clone-fetch runs for about 11 seconds, with a shorter grove:gossip-drain bar after it. Below are rows of tasks for pack-io, eight pack-resolver decode workers and the SharedWorker. Early in the clone, pack-io and the SharedWorker rows are mostly empty. Later they fill with dense stacks of tasks, while the eight decoder rows show only a short burst each and stay mostly empty. (open full size)
The July 17 trace of one heartwood clone in Grove. Recorded with the profiler on, on a dev build, so every bar here runs slower than it would untraced. The long bar near the top is the clone. The gaps early in the pack-io row (the first worker row, about a third of the way down) and in the SharedWorker row at the bottom are the waiting.

Both were waiting on the network, on a node running on the same machine. Spreading verification across workers was still worth doing (chapter 2 has that one), but it wasn’t the wait I was chasing.

All this time, days of perf debugging, wasted on three bugs strutting inside the same trench coat.

Who let the walker out?

To show a patch, Grove has to collect all of its operations, so it starts from the patch’s latest ones and walks from each commit to its parent, and off we go, all the way back to the first one.

That works as long as every parent is another operation. On older heartwood patches, it isn’t. Patches from around June 2024 also list the code commits they refer to as extra git parents.

The reference implementation stops walking at any commit that isn’t a patch operation. It tells them apart by looking in the commit’s files for a manifest, a small file that every operation carries and ordinary code commits don’t. My walker had no such leash. It followed those parents out of the patch and into the repository’s actual git history. All of it.

The worst patch had just 9 operations of its own. My walker visited 2,000 commits for it, and 1,935 of those carried ssh signatures. So… naturally it ran 1,935 signature checks. 🤷‍♂️ Each one failed, because those commits aren’t patch operations, and each failure cost about 2.4ms of pure-JavaScript crypto.

Multiply that by 1,935 and you get… *checks notes*… 4,644ms. Over four and a half seconds of failing crypto, for one patch with nine operations.

One pass over all 948 patches did 1,228,075 object reads, and 98.3% of them were repeats. The 192 patches whose walk escaped like this were 20% of the patches and 89% of the time.

Time runs left to right. Across the top, nine highlighted dots joined in a chain: one patch's nine operations. Underneath, a longer chain of grey dots: the repository's code history, from older on the left to newer on the right. An arrow labeled a code commit as parent runs from the patch's first operation down to a code commit in that history. From there a dashed line runs left along the history to its start, labeled my walker's detour: 1,991 commits.

The worst patch. Each operation’s parent is the one before it. The first one should have no parent at all, yet it lists the code commits it refers to as parents. My walker took that as an invitation to visit the rest of the repository’s history.

The fix is the reference implementation’s rule. A commit without a manifest isn’t a patch operation, so don’t count it and don’t follow its parents. A stray commit now costs one read and the walk stops right there.

That fixed the speed. But 142 patches, 15% of all of them, had never shown up in Grove at all, and the stop rule alone brought back just one.

Once Grove has a patch’s operations, it replays them in order, starting from the one that opened the patch. My rule for finding that one was “the first operation with no parents”. Those legacy patches list the code commits as parents of their very first operation too, so the rule found nothing, and the whole patch vanished. Not slow. Gone. And nobody noticed. A list of 806 patches looks just as complete as a list of 948.

The reference implementation doesn’t guess where a patch begins. A patch’s id is the id of its first operation, so it starts from the patch id it was asked for. Once Grove did the same, all 142 came back, and the restored “merged” ones line up with commits that really landed in heartwood. For the 806 patches that already worked, I hashed each one’s full output before and after the fix. Every one matched bit for bit. Hey, cryptography works, who woulda thought!

The write path had a twin of this bug. To comment on a patch, Grove works out the patch’s id by walking back to its first operation. On those legacy patches, that first operation has code commits as parents too, so the walk didn’t stop there. It kept going down the code’s git history and took whatever old commit it ended on as the patch’s id. So your comment got filed under a patch that doesn’t exist, and vanished. That walk now stops at the patch’s first operation.

Scouring the profiler’s flamegraphs turned up two smaller potholes. The repo’s identity document (it says who the maintainers are, and is itself a signed log of changes) was being recomputed once per patch. And checking whether a patch was merged re-walked the repo’s whole history for every patch. All told, the patch pass went from… ahem… 666 seconds to somewhere between 23 and 44, depending on the run.

That 666 is the patch pass alone, because the issues pass never finished at all lol. Before the fixes, the whole benchmark burned over 80 CPU-minutes without completing, and CPU-minutes add up across parallel workers, so that isn’t 80 minutes on the clock.

Not gonna lie. Given the kind of hell I’ve been feeling stuck in for weeks, seeing that 666 drop made me challenge some life choices. Yet here we are, me writing this (and you reading it! Thanks! And apologies! Carry on!).

Famous last words in a code comment

Remember those “inflate failed” and “output exceeds size cap” errors? Me too, regrettably. Those back then read like a corrupted pack or an attack when in fact they were a bug in my decoder.

A packfile stores each object compressed. The object’s header says how big it is once decompressed, not how big it is compressed. To decode one object without holding the whole pack in memory, my WebAssembly decoder reads a window of the compressed bytes, so it has to guess how big that window should be. The guess was “the compressed form of N bytes can’t be bigger than N + N/8192 + 64, so read that much.” Here’s the code comment, as I found it:

/// A guaranteed upper bound on the zlib stream that compresses `size` uncompressed bytes:
/// DEFLATE's worst case (all stored blocks) adds ~5 bytes per 64 KiB plus a 6-byte zlib
/// wrapper, so `size + size/8192 + 64` always covers it. Reading this many bytes lets one
/// object inflate from a single ranged read; an inflate failure within it is genuine
/// corruption, not truncation.
fn zlib_stream_bound(size: u64) -> u64 {
    size + size / 8192 + 64
}

Sike! DEFLATE (the compression inside every git pack) lets an encoder pad a stream with sync flushes, five bytes of nothing each, as many as it likes. A perfectly legal stream can outrun that window, and real packs from a real node did. With the end of the stream sitting past the window, the decoder saw a cut-off stream and called it corruption.

My WebAssembly decoder was ported from a TypeScript one, which had always handled this by doubling the window and trying again, and my port had dropped the retry. Putting the retry back got rid of both errors and fixed the failing worker pool. It also fixed some slow object reads after the clone, which had been silently falling back to the slower JavaScript path.

Everyone talks at once

So what was the tab doing that night I left the computer on? Mostly starting over.

The UI refreshes the issue and patch lists whenever Grove’s node says something changed. During a clone, the node says so once for every peer namespace it finishes fetching, and heartwood had 54 peers. Each refresh is a full pass over every issue and patch. Yes, the slow pass from earlier. In the benchmark it needed 666 seconds for the patches alone.

Nothing stopped a new refresh from starting while one was already running. So every one of those signals started another full pass on top of the ones still going, and they all shared one worker thread. Each new pass slowed down every pass before it.

Do the math. 54 passes at the benchmark’s 666 seconds each is ten hours of work, and the tab is slower than the benchmark. That’s where my night went.

The fix lets one refresh run at a time and merges every signal that arrives meanwhile into a single follow-up. Its test fires one refresh, then twenty change events while that refresh is still running. Without the fix, that launches 21 overlapping passes. With it, exactly 2. One running, and one queued to catch up on whatever changed in the meantime.

Oh, and it was a security hole too

The fix for where a patch begins, from the walker story above, also deleted a behavior I’m glad never shipped. Before the fix, any peer could forge a parentless “first operation”, point their copy of your issue at it, and the real issue would fail to show up for everyone. A heckler’s veto over other people’s bug trackers. My own test suite was asserting that behavior as correct. It now asserts that the forgery is ignored and the real issue survives.

Scouring heartwood’s source to port it over to TypeScript line by line has surfaced plenty more problems. And it’s how I ran into a much bigger one, in Radicle’s transport itself.

The browser has opinions

One more stop before the numbers, because it explains the gap between the tab and the benchmark. The browser side of things is its own adventure, because often the platform “vetoes” your architecture again and again, and the design you end up with is the sum of those hard nos you had to adapt to:

  • The node would naturally run in a Web Worker. Buuut… the user may open multiple Grove tabs at the same time, which lets all hell of sync and storage issues loose. Hence now it lives in a SharedWorker so that the five new Radicle patches you’ll middle-click to open in new tabs share one node instead. Knock knock. Who’s there? Concurrent read/writes. *slams door shut till a future blog post*
  • Buuut… SharedWorkers can’t open OPFS sync file handles, the fast kind of file access. Only dedicated workers, which belong to the one page or worker that started them, can. So one dedicated worker owns the packfiles and does every packfile write, and the node reaches them through it over a MessageChannel (a pair of linked ports that lets two workers message each other directly).
  • Buuut… Chrome’s SharedWorkers can’t start workers of their own either. So one of the tabs starts that packfile worker (which tab gets to is a story for a later chapter 🗳), and the packfile worker starts the decode workers, one per spare CPU core, up to eight. Workers starting workers, because the worker that wanted them isn’t allowed to have any.
    The Xzibit “Yo dawg” meme photo: Xzibit laughing at the camera. (open full size)
    Yo dawg, I heard you like workers.
  • The cache that makes reopening a list instant is IndexedDB, not SQLite compiled to WebAssembly. SQLite’s OPFS layer needs the sync handles, buuut… the SharedWorker doesn’t have them. 🤷‍♂️

Grove's insides in three rows. At the top, the user's browser tabs running Grove, drawn as a stack of windows. In the middle, three workers as rounded boxes: the node (a SharedWorker), pack-io (the packfile worker) and up to 8 decoders. At the bottom, two storage cylinders, IndexedDB under the node and OPFS, the disk, under pack-io. The tabs link down to the node. The node links to IndexedDB, to OPFS and across to pack-io. Pack-io and the decoders each link to OPFS. An arrow labeled "starts" runs from the tabs to pack-io, and another runs from pack-io to the decoders.

Grove’s insides. A plain line means the two talk. Both arrows are detours around Chrome, whose SharedWorker can’t start workers, so a tab starts pack‑io, the packfile worker, and pack‑io starts the decoders. The node and pack‑io talk over a MessageChannel.

Show me the numbers

The lists that once took a whole night now show up in about a minute. In early August I timed a fresh clone of heartwood in Chrome, on a quiet machine, from a local node. The issues and patches lists showed up in about 48 seconds after the clone finished. Not instant, and I’ll get to why. But at least I get to turn the computer off at night now.

The numbers below come from the isolated Node-based perf benchmark I described at the start, which I ran on July 17, the day the last of these fixes landed. That way they show what my issue and patch code costs without any “browser parts” in the way.

beforeafter
patches that show up806 of 948948 of 948
time to show issues and patches lists after a clone666s for the patches alone, and the issues never finished~0.13s for both issues and patches, once the background step (about 35s) has filled the cache
time to re-show a lista full recompute every time, 22.6s for the patches even after the fixes above~60-70ms

In the “after” column, the last two rows come from one saved cache of the computed issues and patches. Grove saves each result so it can skip replaying operations that haven’t changed. At the time, each entry was keyed on the exact refs it was computed from, plus the repo’s identity document, plus, for a patch that’s still open, the tips of the maintainers’ branches. The branch tips were in the key because moving a tip can turn an open patch into a merged one.

That 0.13s is a cache read, and the work behind it now happens earlier, before anyone opens the list. While the clone ran, the node noted every issue and patch whose refs changed. Once the fetching was done, it computed just those in the background and saved them, the way the reference implementation does at fetch time. These days it starts as soon as each fetch’s refs land.

In the benchmark, that background step took about 35.5 seconds, and every saved result matched a fresh computation byte for byte.

If that background step ever fails, nothing is lost. The clone still succeeds, and Grove falls back to computing those issues and patches when someone opens the list.

So why 48 seconds for heartwood’s lists in the tab? In Node, the benchmark works on sixteen issues or patches at once, in the same process, each reading objects straight off disk.

In the tab, every read of an object stored in a packfile goes through the one dedicated worker that owns the packfiles, and that worker serves the reads one at a time. The reads have been batched since July, but each batch still has to cross between workers, an I/O cost the benchmark doesn’t have to pay. Whether the one-at-a-time serving or the crossing costs more in the tab I haven’t measured yet, and getting the tab closer to the benchmark is still open as I write this.

What I learned

Both the escaped walk and the decoder’s “guaranteed” window were correctness bugs that presented as slowness, and the pile of overlapping refreshes was slowness I’d built myself. I found every one of them the same way, by benchmarking against real data, on a small repo first, and insisting on measurements before believing anything I hoped was true.

What I’m keeping from all this:

  • When 98.3% of the object reads are repeats, look for a walk gone wrong before reaching for a cache.
  • If every change event starts a full refresh, let one run at a time and merge the rest into a single follow-up.

Slowness is a symptom. Profile before you theorize, and when the profile contradicts your beautiful theory, the profile, my friend, is right.

And I haven’t even told you about the clone itself, which was its own fight. The tab isn’t allowed to open a TCP socket, and it still has to catch a packfile too big to hold in memory. That’s chapter 2, “Honey, I Shrunk the Repo Clone”, and it joins the series soon.

I Shoved a Whole P2P Git Node in a Browser Tab. It Fought Back.

Thank you for your attention.

Replies

Send me your comments on social media or by email to maninak@pm.me. Those replies may show up here (unless you request against it).