This repository was archived by the owner on Oct 23, 2026. It is now read-only.
Repository navigation
perf(upgrade): vectorize bspatch diff-add with SWAR (4x faster apply) - #1280
Merged
Merged
Conversation
The diff-add step (`output[i] = (old[i] + diff[i]) % 256`) is the hot inner loop of patch apply. Doing it byte-at-a-time in JS — two typed-array property reads + a `% 256` per byte — dominates CPU time when reconstructing a large binary. Extracts the loop into `addDiffChunk` and processes 4 bytes per iteration with a SWAR (SIMD-within-a-register) add on Uint32Array: lows = (a & 0x7f7f7f7f) + (b & 0x7f7f7f7f) // top bit cleared → carries stay in-lane highs = (a ^ b) & 0x80808080 // per-lane high-bit sum result = lows ^ highs // per-byte sum mod 256 This is carry-less: each byte lane sums independently mod 256. A short tail loop handles the trailing n % 4 bytes. On the Lore gateway (~310 MB binary, where this was first landed) the diff-add dropped from ~883 ms to ~221 ms (4x). INVARIANT documented in the code: the carry masks must match the word width. A wider-word (BigUint64Array) variant must widen BOTH masks to 64-bit; pairing 64-bit words with the 32-bit mask silently drops carries in the upper 4 bytes. Tests (exhaustive): matches a per-byte reference across all 256 byte values and every 4-byte alignment; wrap-around at 0xff in every lane (cross-lane carry detector); tail lengths 0-3 across many window sizes. Mutation-verified: a mask/word-width mismatch turns all three SWAR tests RED.
Contributor
|
Contributor
Codecov Results 📊✅ Patch coverage is 100.00%. Project has 5486 uncovered lines. Files with missing lines (1)
Coverage diff@@ Coverage Diff @@
## main #PR +/-##
==========================================
+ Coverage 81.69% 81.70% +0.01%
==========================================
Files 426 426 —
Lines 29971 29986 +15
Branches 19499 19510 +11
==========================================
+ Hits 24485 24500 +15
- Misses 5486 5486 —
- Partials 2045 2047 +2Generated by Codecov Action |
Adversarial review noted that the Uint32Array SWAR fast path relies on an undocumented invariant — every buffer passed to addDiffChunk has a 4-byte aligned byteOffset. It holds for all current callers (fresh new Uint8Array / Buffer.alloc allocations, offset 0), but a future caller passing a pooled or subarray view would hit `RangeError: start offset ... multiple of 4`. Rather than throw (this is a perf detail that must never break apply), fall back to the byte loop when any of output/old/diff is misaligned. Correct for all inputs; the SWAR path stays a pure optimization. addDiffChunk is now exported so it can be unit-tested directly. New test drives every offset combination (0-3 on each buffer) against the per-byte reference — mutation-verified: removing the guard makes the misaligned case throw RangeError (RED).
BYK
added a commit
that referenced
this pull request
Jul 22, 2026
…1281) ## What `sentry upgrade` gives no feedback during its slow phases. This adds two byte-driven progress bars. - **Apply phase** (the slow part of a delta upgrade): a determinate bar — `Applying 3 patch(es) [███████░░░░░░░░░] 22.1 MB / 45.0 MB`. Total is the **final binary size** (the last patch's declared `newSize`), i.e. the real output the user gets — not the sum of intermediate hop writes. Progress is byte-driven across the whole chain, so it advances smoothly rather than stalling per hop. - **Full-binary download**: an indeterminate byte counter — `Downloading 38.0 MB`. The decompressed size isn't known ahead of time (`Content-Length` covers only the compressed stream), so it shows an honest live byte count, not a fake fraction. Both bars are gated on interactive output via the existing `isPlainOutput()`, so they self-suppress under `NO_COLOR`, piped stdout, and CI. ## How - New `src/lib/progress.ts` — `makeByteProgress(label, totalBytes)`. Reuses the existing `formatBytes` (`formatters/numbers`) and `isPlainOutput` (`formatters/plain-detect`) helpers. Cosmetic-only: a render failure never aborts the upgrade, and **both** `onProgress` and `done()` are guarded against throwing streams. - An optional `onBytes` callback is threaded through `applyReaderToMemory` / `applyReaderToFile` → `applyPatchChainInMemory` → `applyPatchChain`, reporting bytes-written per output chunk. Purely additive — no behavior change to the apply/verify logic. - Apply bar created in `applyChainAndReturn`; download bar in `streamDecompressToFile`. ## Tests `test/lib/progress.test.ts` (7): determinate/indeterminate rendering, plain-output and non-TTY header-only behavior, byte accumulation, full-bar clamping, and the never-throws contract — **mutation-verified**: an unguarded `done()` turns the never-throws test RED. ## Verification - 22/22 (`progress` + `bspatch`) pass, `tsc --noEmit` clean, `biome check` clean. - Independent of #1279 (`MAX_OUTPUT_SIZE`) and #1280 (SWAR) — separate file regions, no overlap.
5 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
The diff-add step (
output[i] = (old[i] + diff[i]) % 256) is the hot inner loop ofbspatchapply. Doing it byte-at-a-time in JS — two typed-array property reads + a% 256per byte — dominates CPU time when reconstructing a large binary.How
Extracts the loop into
addDiffChunkand processes 4 bytes per iteration with a SWAR (SIMD-within-a-register) add onUint32Array:Carry-less: each byte lane sums independently mod 256. A short tail loop handles the trailing
n % 4bytes. Behavior is identical to the byte loop it replaces.On the Lore gateway's ported copy of this file (~310 MB binary, where this optimization was first landed and reviewed) the diff-add dropped from ~883 ms to ~221 ms (4×). sentry-cli binaries are smaller so the absolute win is smaller, but it's free.
The code documents the load-bearing INVARIANT: the carry masks must match the word width. A
BigUint64Arrayvariant must widen both masks to 64-bit; pairing 64-bit words with the 32-bit mask silently drops carries in the upper 4 bytes.Tests (exhaustive)
0xffin every lane — a cross-lane carry detector.Verification
test/lib/bspatch.test.tspass,tsc --noEmitclean,biome checkclean.MAX_OUTPUT_SIZEsecurity fix) — separate file regions, no overlap.