Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.

perf(upgrade): vectorize bspatch diff-add with SWAR (4x faster apply) - #1280

Merged
BYK merged 2 commits into
mainfrom
perf/bspatch-swar-diff-add
Jul 22, 2026
Merged

BYK merged 2 commits into
mainfrom
perf/bspatch-swar-diff-add

Conversation

@BYK

@BYK BYK commented Jul 22, 2026

Copy link
Copy Markdown
Member

What

The diff-add step (output[i] = (old[i] + diff[i]) % 256) is the hot inner loop of bspatch 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.

How

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

Carry-less: each byte lane sums independently mod 256. A short tail loop handles the trailing n % 4 bytes. 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 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 implementation across all 256 byte values and every 4-byte alignment.
  • Wrap-around at 0xff in every lane — a 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.

Verification

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.
@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://cli.sentry.dev/_preview/pr-1280/

Built to branch gh-pages at 2026-07-22 21:33 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Codecov Results 📊

✅ Patch coverage is 100.00%. Project has 5486 uncovered lines.
✅ Project coverage is 81.7%. Comparing base (base) to head (head).

Files with missing lines (1)
File Patch % Lines
src/lib/bspatch.ts 100.00% ⚠️ 3 partials
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        +2

Generated 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
BYK merged commit 9b0e23b into main Jul 22, 2026
34 checks passed
@BYK
BYK deleted the perf/bspatch-swar-diff-add branch July 22, 2026 22:05
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.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant