Skip to content

perf(eventstream): use Bun native CRC32 for Kiro frame validation - #755

Closed
luvs01 wants to merge 1 commit into
devfrom
perf/bun144-native-eventstream-crc32
Closed

luvs01 wants to merge 1 commit into
devfrom
perf/bun144-native-eventstream-crc32

Conversation

@luvs01

@luvs01 luvs01 commented Oct 23, 2026

Copy link
Copy Markdown
Owner

Summary

Kiro's production receive path validates two CRC32 checksums for every AWS EventStream frame. The decoder currently builds a 256-entry lookup table and walks every byte in JavaScript. Replace that loop with Bun.hash.crc32(bytes, seed >>> 0), preserving the exported helper, unsigned IEEE CRC32 result, seed continuation/coercion, and the exact offset byte view.

The framing and corruption/size checks stay in place. Fixed vectors, independently generated wire bytes, offset views, incremental seeds, and malformed-frame tests cover the contract. The transport inventory documents the native checksum dependency, and the original framing-code attribution is retained.

Bun 1.4.4's release notes describe faster native hash paths. CRC32 was already available in 1.4.3; this is an application-level replacement of a custom implementation, not a claim that the API is new in 1.4.4. The measurements below use byte frames from this repository instead of extrapolating the blog's short-string benchmark.

Measured effect

Linux x86_64, official Bun 1.4.4 (38afee6c8), baseline c4d4bb2da2162e23c314befafc5ec104292902a0. The benchmark imports the actual baseline and final PR modules separately, checks identical wire bytes and decoded values, warms each operation, alternates execution order, and reports the median of seven runs.

Payload Frames per run Baseline decode Native decode Decode speedup
256 B 100,000 181.78 ms 95.35 ms 1.91x
4 KiB 12,000 141.22 ms 13.74 ms 10.28x
64 KiB 1,000 191.15 ms 3.15 ms 60.73x

These are synthetic EventStream framing measurements, not end-to-end request or model-response improvements. Kiro is the current production decoder consumer. encodeMessage is a test/fixture helper; its measured speedups (1.43x, 3.35x, 16.06x for the same sizes) are not production upload gains. There are no timing assertions in the test suite.

Verification

Using the official executables, with the matching binary directory on PATH:

  • Bun 1.4.3: bun scripts/test.ts ./tests/responses/eventstream-decoder.test.ts ./tests/providers/kiro/kiro-stream.test.ts ./tests/providers/kiro/kiro-transport-parity.test.ts — 150 pass, 0 fail, 536 assertions.
  • Bun 1.4.4: bun test ./tests/responses/eventstream-decoder.test.ts ./tests/providers/kiro/kiro-stream.test.ts ./tests/providers/kiro/kiro-transport-parity.test.ts — 150 pass, 0 fail, 536 assertions.
  • Pinned Bun 1.4.3 wrapper: bun run test:changed --parallel=2 ./tests/providers/kiro/ — 350 pass, 0 fail across 13 selected files, 1,391 assertions.
  • Deterministic comparison against the original loop — 6,000 byte-view/seed combinations agree.
  • bun run typecheck, bun run structure:check, bun run privacy:scan, bun scripts/file-size-ratchet.ts, and git diff --cached --check — passed.

Full-suite scope exception: the approximately 2,600-file repository suite was not run locally because of the constrained shared environment and concurrent worktrees. Focused codec regressions and import-connected Kiro behavior were run instead, as allowed by AGENTS.md. Repository-wide and macOS/Windows execution remain for CI/maintainer validation. Public wire behavior and configuration are unchanged; no docs-site workflow update is required.

Reproduce the framing benchmark

Save the following as a temporary TypeScript file. Run it with Bun 1.4.4, passing absolute paths to src/lib/eventstream-decoder.ts in a baseline checkout at the commit above and in this PR checkout:

bun /tmp/eventstream-benchmark.ts /absolute/base/src/lib/eventstream-decoder.ts /absolute/pr/src/lib/eventstream-decoder.ts
import assert from "node:assert/strict";

const sourcePath = Bun.argv[2];
if (!sourcePath || !Bun.argv[3]) throw new Error("pass absolute baseline and PR decoder module paths");
const old = await import(sourcePath);
const native = await import(Bun.argv[3]);

let checksum = 0;
const median = (xs: number[]) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]!;
function measure(fn: () => number, n: number) {
  const start = performance.now();
  let value = 0;
  for (let i = 0; i < n; i++) value ^= fn();
  checksum ^= value;
  return performance.now() - start;
}

const rows = [];
for (const [payloadBytes, n] of [[256, 100_000], [4096, 12_000], [65536, 1000]] as const) {
  const payload = Uint8Array.from({ length: payloadBytes }, (_, i) => (i * 97 + 13) % 256);
  const headers = { ":event-type": "assistantResponseEvent", ":message-type": "event" };
  const frame = old.encodeMessage(headers, payload);
  const nativeFrame = native.encodeMessage(headers, payload);
  assert.deepEqual(nativeFrame, frame);
  const padded = new Uint8Array(frame.length + 16);
  padded.set(frame, 5);
  const slicedFrame = padded.subarray(5, frame.length + 5);
  assert.deepEqual(native.decodeMessage(slicedFrame), old.decodeMessage(slicedFrame));
  for (const operation of ["decode", "encode"] as const) {
    const oldFn = operation === "decode" ? () => old.decodeMessage(slicedFrame).payload.length : () => old.encodeMessage(headers, payload).length;
    const nativeFn = operation === "decode" ? () => native.decodeMessage(slicedFrame).payload.length : () => native.encodeMessage(headers, payload).length;
    measure(oldFn, Math.min(1000, n)); measure(nativeFn, Math.min(1000, n));
    const a: number[] = [], b: number[] = [];
    for (let i = 0; i < 7; i++) {
      if (i % 2) { b.push(measure(nativeFn, n)); a.push(measure(oldFn, n)); }
      else { a.push(measure(oldFn, n)); b.push(measure(nativeFn, n)); }
    }
    const oldMs = median(a), nativeMs = median(b);
    rows.push({ operation, payloadBytes, frameBytes: frame.length, iterations: n, oldMs, nativeMs, ratio: oldMs / nativeMs });
  }
}

const vector = new TextEncoder().encode("123456789");
assert.equal(native.crc32(vector), 0xcbf43926);
let parity = 0;
for (let n = 0; n < 1000; n++) {
  const bytes = Uint8Array.from({ length: n + 8 }, (_, i) => (i * 97 + 13) % 256).subarray(3, n + 3);
  for (const seed of [0, 1, 0x12345678, 0xffffffff, -1, 0x100000001]) {
    assert.equal(native.crc32(bytes, seed), old.crc32(bytes, seed)); parity++;
  }
}
console.log(JSON.stringify({ version: Bun.version, revision: Bun.revision, rows, parity, checksum }, null, 2));

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Security review: checksum validation still rejects corrupt input, frame/header bounds remain intact, and no authentication, credential handling, network destinations, or logging were added.

Co-authored-by: luvs01 [email protected]

Replace the EventStream JavaScript CRC32 loop with the native Bun primitive while preserving wire validation and seeded byte-view semantics.

Co-authored-by: luvs01 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 23, 2026

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

✅ Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the enhancement New feature or request label Oct 23, 2026

luvs01 commented Oct 23, 2026

Copy link
Copy Markdown
Owner Author

The reviewed change at commit ce6fa6da2429f6ac55f65e90950c3bb19062a4a6 has been submitted for maintainer review with its three-file patch unchanged. The submitted head/base and file changes were verified. Independent review and the Windows Bun 1.4.4 decoder suite passed (16 tests, 85 assertions); benchmark numbers remain author measurements. Closing this staging proposal to avoid duplicate tracking while preserving its branch and commit history.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant