From 54b9d6c428c7db6fc115fe4677af27387207d63e Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Mon, 23 Nov 2026 18:46:47 +0100 Subject: [PATCH 1/2] perf(ltx): compute the CRC-64 and the LZ4 blocks without BigInt Signed-off-by: marcopiraccini --- packages/sqlite-js-stream/src/ltx/crc64.ts | 49 ++-- packages/sqlite-js-stream/src/ltx/lz4.ts | 84 +++--- .../test/helpers/crc64-reference.ts | 47 ++++ .../test/helpers/lz4-reference.ts | 240 ++++++++++++++++++ .../sqlite-js-stream/test/ltx/crc64.test.ts | 24 ++ .../sqlite-js-stream/test/ltx/lz4.test.ts | 55 ++++ 6 files changed, 447 insertions(+), 52 deletions(-) create mode 100644 packages/sqlite-js-stream/test/helpers/crc64-reference.ts create mode 100644 packages/sqlite-js-stream/test/helpers/lz4-reference.ts diff --git a/packages/sqlite-js-stream/src/ltx/crc64.ts b/packages/sqlite-js-stream/src/ltx/crc64.ts index b5943b9..4557015 100644 --- a/packages/sqlite-js-stream/src/ltx/crc64.ts +++ b/packages/sqlite-js-stream/src/ltx/crc64.ts @@ -13,23 +13,34 @@ * `tab[byte(crc) ^ v] ^ (crc >> 8)` */ -const ISO_POLY = 0xd800000000000000n; -const MASK64 = 0xffffffffffffffffn; +// The 64-bit values are kept as two unsigned 32-bit halves: BigInt arithmetic +// allocates, and one checksum is computed for every byte of every page. +const ISO_POLY_HI = 0xd8000000; +const ISO_POLY_LO = 0x00000000; -/** Builds the 256-entry CRC table for a reflected polynomial. */ -function makeTable(poly: bigint): bigint[] { - const table: bigint[] = new Array(256); +/** Builds the 256-entry CRC table for a reflected polynomial, as its two halves. */ +function makeTable(polyHi: number, polyLo: number): [Uint32Array, Uint32Array] { + const hi = new Uint32Array(256); + const lo = new Uint32Array(256); for (let i = 0; i < 256; i++) { - let crc = BigInt(i); + let h = 0; + let l = i; for (let j = 0; j < 8; j++) { - crc = (crc & 1n) !== 0n ? (crc >> 1n) ^ poly : crc >> 1n; + const carry = l & 1; + l = ((l >>> 1) | (h << 31)) >>> 0; + h >>>= 1; + if (carry !== 0) { + h = (h ^ polyHi) >>> 0; + l = (l ^ polyLo) >>> 0; + } } - table[i] = crc; + hi[i] = h; + lo[i] = l; } - return table; + return [hi, lo]; } -const ISO_TABLE = makeTable(ISO_POLY); +const [ISO_TABLE_HI, ISO_TABLE_LO] = makeTable(ISO_POLY_HI, ISO_POLY_LO); /** * Crc64 is a streaming CRC-64 hasher, equivalent to Go's `hash/crc64` @@ -37,23 +48,29 @@ const ISO_TABLE = makeTable(ISO_POLY); * obtain the running checksum. `reset()` re-initializes the hasher. */ export class Crc64 { - private crc: bigint = MASK64; + private hi = 0xffffffff; + private lo = 0xffffffff; update(buf: Uint8Array): void { - let crc = this.crc; + let hi = this.hi; + let lo = this.lo; for (let i = 0; i < buf.length; i++) { - crc = ISO_TABLE[Number((crc ^ BigInt(buf[i])) & 0xffn)] ^ (crc >> 8n); + const index = (lo ^ buf[i]) & 0xff; + lo = (ISO_TABLE_LO[index] ^ ((lo >>> 8) | (hi << 24))) >>> 0; + hi = (ISO_TABLE_HI[index] ^ (hi >>> 8)) >>> 0; } - this.crc = crc; + this.hi = hi; + this.lo = lo; } reset(): void { - this.crc = MASK64; + this.hi = 0xffffffff; + this.lo = 0xffffffff; } /** Returns the digest of all data written so far. */ sum64(): bigint { - return this.crc ^ MASK64; + return (BigInt(~this.hi >>> 0) << 32n) | BigInt(~this.lo >>> 0); } } diff --git a/packages/sqlite-js-stream/src/ltx/lz4.ts b/packages/sqlite-js-stream/src/ltx/lz4.ts index e4347c8..e75b19d 100644 --- a/packages/sqlite-js-stream/src/ltx/lz4.ts +++ b/packages/sqlite-js-stream/src/ltx/lz4.ts @@ -27,9 +27,13 @@ const WIN_MASK = WIN_SIZE - 1; const MIN_MATCH = 4; const MF_LIMIT = 10 + MIN_MATCH; // Last match cannot start within the last 14 bytes. const ADAPT_SKIP_LOG = 7; -const PRIME6 = 227718039650203n; -const U64_MASK = 0xffffffffffffffffn; -const U32_MASK = 0xffffffffn; +// The 48-bit prime of the hash, 227718039650203, as its low 32 and high 16 bits: +// 64-bit values are handled as 32-bit halves, since BigInt arithmetic +// allocates and the scan below runs for every byte of every page. +const PRIME6_LO = 0xbcdcbf9b; +const PRIME6_LO0 = PRIME6_LO & 0xffff; +const PRIME6_LO1 = PRIME6_LO >>> 16; +const PRIME6_HI = 0xcf1b; // Hash table state. `inUse` is a bitmap so we can clear the table cheaply. const hashTable = new Uint16Array(HT_SIZE); @@ -43,31 +47,35 @@ export function compressBlockBound(n: number): number { return n + ((n / 255) | 0) + 16; } -/** Hashes the lower 6 bytes of a 64-bit little-endian value into a hash index. */ -function blockHash(x: bigint): number { - return Number((((x << 16n) * PRIME6) & U64_MASK) >> 48n); -} - -/** Reads the 64-bit little-endian value at `o` (used by the Fast scan). */ -function readU64(b: Uint8Array, o: number): bigint { - let x = 0n; - for (let i = 7; i >= 0; i--) x = (x << 8n) | BigInt(b[o + i]); - return x; -} - /** Reads the 32-bit little-endian value at `o`. */ function readU32(b: Uint8Array, o: number): number { return (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; } -/** Returns the number of leading zero bytes in a 64-bit little-endian value. */ -function trailingZeroBytes(x: bigint): number { - let n = 0; - while ((x & 0xffn) === 0n && n < 8) { - x >>= 8n; - n++; - } - return n; +/** + * Hashes the 6 bytes at `o` into a hash index. Mirrors `blockHash` of Go, + * `((x << 16) * prime6) >> 48` on the 64-bit little-endian value at `o`: the + * result is the bits 32 to 47 of the product of the lower 48 bits of `x` by + * the prime, computed here from 16-bit and 32-bit parts. + */ +function blockHash(b: Uint8Array, o: number): number { + const lo = readU32(b, o); + const hi = b[o + 4] | (b[o + 5] << 8); + const lo0 = lo & 0xffff; + const lo1 = lo >>> 16; + + // The bits 32 to 47 of lo * PRIME6_LO, a 64-bit product + const mid = lo1 * PRIME6_LO0 + ((lo0 * PRIME6_LO0) >>> 16); + const mid2 = lo0 * PRIME6_LO1 + (mid & 0xffff); + const carry = Math.floor(mid / 0x10000) + Math.floor(mid2 / 0x10000); + const high = Math.imul(lo1, PRIME6_LO1) + carry; + + return (high + Math.imul(lo, PRIME6_HI) + Math.imul(hi, PRIME6_LO)) & 0xffff; +} + +/** Returns the number of trailing zero bytes of a non-zero 32-bit value. */ +function trailingZeroBytes(x: number): number { + return (31 - Math.clz32(x & -x)) >>> 3; } /** @@ -112,9 +120,9 @@ function compressBlockInto(src: Uint8Array, dst: Uint8Array): number { if (sn > 0) { for (; si < sn;) { - const match = readU64(src, si); - let h = blockHash(match); - const h2 = blockHash(match >> 8n); + // The 8 bytes at si are looked at as three windows of 6, at si, si + 1 and si + 2 + let h = blockHash(src, si); + const h2 = blockHash(src, si + 1); const ref = tableGet(h, si); const ref2 = tableGet(h2, si + 1); tablePut(h, si); @@ -122,16 +130,16 @@ function compressBlockInto(src: Uint8Array, dst: Uint8Array): number { let offset = si - ref; - if (offset <= 0 || offset >= WIN_SIZE || (match & U32_MASK) !== BigInt(readU32(src, ref))) { - h = blockHash(match >> 16n); + if (offset <= 0 || offset >= WIN_SIZE || readU32(src, si) !== readU32(src, ref)) { + h = blockHash(src, si + 2); const ref3 = tableGet(h, si + 2); si += 1; offset = si - ref2; - if (offset <= 0 || offset >= WIN_SIZE || ((match >> 8n) & U32_MASK) !== BigInt(readU32(src, ref2))) { + if (offset <= 0 || offset >= WIN_SIZE || readU32(src, si) !== readU32(src, ref2)) { si += 1; offset = si - ref3; tablePut(h, si); - if (offset <= 0 || offset >= WIN_SIZE || ((match >> 16n) & U32_MASK) !== BigInt(readU32(src, ref3))) { + if (offset <= 0 || offset >= WIN_SIZE || readU32(src, si) !== readU32(src, ref3)) { si += 2 + ((si - anchor) >>> ADAPT_SKIP_LOG); continue; } @@ -158,13 +166,17 @@ function compressBlockInto(src: Uint8Array, dst: Uint8Array): number { // Find the longest match by comparing 8 bytes at a time. while (si + 8 <= sn) { - const x = readU64(src, si) ^ readU64(src, si - offset); - if (x === 0n) { - si += 8; - } else { - si += trailingZeroBytes(x); + const low = readU32(src, si) ^ readU32(src, si - offset); + if (low !== 0) { + si += trailingZeroBytes(low); + break; + } + const high = readU32(src, si + 4) ^ readU32(src, si + 4 - offset); + if (high !== 0) { + si += 4 + trailingZeroBytes(high); break; } + si += 8; } mLen = si - matchBase; @@ -214,7 +226,7 @@ function compressBlockInto(src: Uint8Array, dst: Uint8Array): number { if (si >= sn) break; // Hash match end-2. - h = blockHash(readU64(src, si - 2)); + h = blockHash(src, si - 2); tablePut(h, si - 2); } } diff --git a/packages/sqlite-js-stream/test/helpers/crc64-reference.ts b/packages/sqlite-js-stream/test/helpers/crc64-reference.ts new file mode 100644 index 0000000..2b466ff --- /dev/null +++ b/packages/sqlite-js-stream/test/helpers/crc64-reference.ts @@ -0,0 +1,47 @@ +/** + * The BigInt implementation of CRC-64 ISO the fast one replaced, kept as the + * reference the tests compare it with. + */ +const ISO_POLY = 0xd800000000000000n; +const MASK64 = 0xffffffffffffffffn; + +/** Builds the 256-entry CRC table for a reflected polynomial. */ +function makeTable(poly: bigint): bigint[] { + const table: bigint[] = new Array(256); + for (let i = 0; i < 256; i++) { + let crc = BigInt(i); + for (let j = 0; j < 8; j++) { + crc = (crc & 1n) !== 0n ? (crc >> 1n) ^ poly : crc >> 1n; + } + table[i] = crc; + } + return table; +} + +const ISO_TABLE = makeTable(ISO_POLY); + +/** + * Crc64 is a streaming CRC-64 hasher, equivalent to Go's `hash/crc64` + * (ISO table). Call `update()` with successive byte chunks and `sum64()` to + * obtain the running checksum. `reset()` re-initializes the hasher. + */ +export class ReferenceCrc64 { + private crc: bigint = MASK64; + + update(buf: Uint8Array): void { + let crc = this.crc; + for (let i = 0; i < buf.length; i++) { + crc = ISO_TABLE[Number((crc ^ BigInt(buf[i])) & 0xffn)] ^ (crc >> 8n); + } + this.crc = crc; + } + + reset(): void { + this.crc = MASK64; + } + + /** Returns the digest of all data written so far. */ + sum64(): bigint { + return this.crc ^ MASK64; + } +} diff --git a/packages/sqlite-js-stream/test/helpers/lz4-reference.ts b/packages/sqlite-js-stream/test/helpers/lz4-reference.ts new file mode 100644 index 0000000..8b00806 --- /dev/null +++ b/packages/sqlite-js-stream/test/helpers/lz4-reference.ts @@ -0,0 +1,240 @@ +/** + * The BigInt port of the Fast LZ4 block compressor the fast one replaced, kept + * as the reference the tests compare it with. + */ + +// Compressor constants, mirrored from `internal/lz4block/block.go`. +const HASH_LOG = 16; +const HT_SIZE = 1 << HASH_LOG; // 65536 hash-table entries. +const WIN_SIZE = 1 << 16; // 64 KiB window. +const WIN_MASK = WIN_SIZE - 1; +const MIN_MATCH = 4; +const MF_LIMIT = 10 + MIN_MATCH; // Last match cannot start within the last 14 bytes. +const ADAPT_SKIP_LOG = 7; +const PRIME6 = 227718039650203n; +const U64_MASK = 0xffffffffffffffffn; +const U32_MASK = 0xffffffffn; + +// Hash table state. `inUse` is a bitmap so we can clear the table cheaply. +const hashTable = new Uint16Array(HT_SIZE); +const inUse = new Uint32Array(HT_SIZE / 32); + +/** + * compressBlockBound returns the maximum compressed size for `n` input bytes + * using the Fast compressor (`n + n/255 + 16`). + */ +function compressBlockBound(n: number): number { + return n + ((n / 255) | 0) + 16; +} + +/** Hashes the lower 6 bytes of a 64-bit little-endian value into a hash index. */ +function blockHash(x: bigint): number { + return Number((((x << 16n) * PRIME6) & U64_MASK) >> 48n); +} + +/** Reads the 64-bit little-endian value at `o` (used by the Fast scan). */ +function readU64(b: Uint8Array, o: number): bigint { + let x = 0n; + for (let i = 7; i >= 0; i--) x = (x << 8n) | BigInt(b[o + i]); + return x; +} + +/** Reads the 32-bit little-endian value at `o`. */ +function readU32(b: Uint8Array, o: number): number { + return (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; +} + +/** Returns the number of leading zero bytes in a 64-bit little-endian value. */ +function trailingZeroBytes(x: bigint): number { + let n = 0; + while ((x & 0xffn) === 0n && n < 8) { + x >>= 8n; + n++; + } + return n; +} + +/** + * Look up the two 16-bit halves of a stored match offset for a hash. Mirrors + * `Compressor.get`: the table stores 16-bit offsets relative to a 64 KiB block + * boundary. Returns a position that may be before the start of the window (in + * which case `offset >= WIN_SIZE` short-circuits the candidate check). + */ +function tableGet(h: number, si: number): number { + h &= HT_SIZE - 1; + let i = 0; + if (inUse[h >>> 5] & (1 << (h & 31))) i = hashTable[h]; + i += si & ~WIN_MASK; + if (i >= si) i -= WIN_SIZE; + return i; +} + +function tablePut(h: number, si: number): void { + h &= HT_SIZE - 1; + hashTable[h] = si & 0xffff; + inUse[h >>> 5] |= 1 << (h & 31); +} + +/** + * Compresses `src` into `dst` as a Fast-mode LZ4 block, writing at offset 0. + * Mirrors `lz4block.Compressor.CompressBlock`. Returns the number of bytes + * written, or 0 if `dst` is too small (which happens only when the caller does + * not size `dst` with `compressBlockBound`). + */ +function compressBlockInto(src: Uint8Array, dst: Uint8Array): number { + // Clear the reused table so output is deterministic (issue #65). + inUse.fill(0); + + // In normal use `dst` is sized by `compressBlockBound`, so the compressor + // always emits a valid block (even for incompressible input). An undersized + // `dst` is caught by the `di >= dst.length` guards below and returns 0. + + let si = 0; + let di = 0; + let anchor = 0; + const sn = src.length - MF_LIMIT; + + if (sn > 0) { + for (; si < sn;) { + const match = readU64(src, si); + let h = blockHash(match); + const h2 = blockHash(match >> 8n); + const ref = tableGet(h, si); + const ref2 = tableGet(h2, si + 1); + tablePut(h, si); + tablePut(h2, si + 1); + + let offset = si - ref; + + if (offset <= 0 || offset >= WIN_SIZE || (match & U32_MASK) !== BigInt(readU32(src, ref))) { + h = blockHash(match >> 16n); + const ref3 = tableGet(h, si + 2); + si += 1; + offset = si - ref2; + if (offset <= 0 || offset >= WIN_SIZE || ((match >> 8n) & U32_MASK) !== BigInt(readU32(src, ref2))) { + si += 1; + offset = si - ref3; + tablePut(h, si); + if (offset <= 0 || offset >= WIN_SIZE || ((match >> 16n) & U32_MASK) !== BigInt(readU32(src, ref3))) { + si += 2 + ((si - anchor) >>> ADAPT_SKIP_LOG); + continue; + } + } + } + + // Match found. + let lLen = si - anchor; + let mLen = 4; + + // Extend backwards, reducing literals. + let tOff = si - offset - 1; + while (lLen > 0 && tOff >= 0 && src[si - 1] === src[tOff]) { + si--; + tOff--; + lLen--; + mLen++; + } + + // Continue search at the end of the match. `matchBase` is the position + // just past the first 4 matched bytes. + const matchBase = si + MIN_MATCH; + si = si + mLen; + + // Find the longest match by comparing 8 bytes at a time. + while (si + 8 <= sn) { + const x = readU64(src, si) ^ readU64(src, si - offset); + if (x === 0n) { + si += 8; + } else { + si += trailingZeroBytes(x); + break; + } + } + + mLen = si - matchBase; + + if (di >= dst.length) return 0; + if (mLen < 0xf) dst[di] = mLen; + else dst[di] = 0xf; + + // Encode literal length. + if (lLen < 0xf) { + dst[di] |= lLen << 4; + } else { + dst[di] |= 0xf0; + di++; + let l = lLen - 0xf; + while (l >= 0xff && di < dst.length) { + dst[di] = 0xff; + di++; + l -= 0xff; + } + if (di >= dst.length) return 0; + dst[di] = l; + } + di++; + + if (di + lLen > dst.length) return 0; + dst.set(src.subarray(anchor, anchor + lLen), di); + di += lLen + 2; + anchor = si; + + if (di > dst.length) return 0; + dst[di - 2] = offset & 0xff; + dst[di - 1] = (offset >> 8) & 0xff; + + // Encode match length part 2. + if (mLen >= 0xf) { + let m = mLen - 0xf; + while (m >= 0xff && di < dst.length) { + dst[di] = 0xff; + di++; + m -= 0xff; + } + if (di >= dst.length) return 0; + dst[di] = m; + di++; + } + if (si >= sn) break; + + // Hash match end-2. + h = blockHash(readU64(src, si - 2)); + tablePut(h, si - 2); + } + } + + // Last literals. + if (di >= dst.length) return 0; + const lLen = src.length - anchor; + if (lLen < 0xf) { + dst[di] = lLen << 4; + } else { + dst[di] = 0xf0; + di++; + let l = lLen - 0xf; + while (l >= 0xff && di < dst.length) { + dst[di] = 0xff; + di++; + l -= 0xff; + } + if (di >= dst.length) return 0; + dst[di] = l; + } + di++; + + if (di + (src.length - anchor) > dst.length) return 0; + dst.set(src.subarray(anchor), di); + di += src.length - anchor; + return di; +} + +/** + * compressBlock compresses `data` as a Fast-mode LZ4 block and returns the + * compressed bytes. The result is byte-identical to Go's `pierrec/lz4/v4` + * `CompressBlock` for the same input. + */ +export function referenceCompressBlock(data: Uint8Array): Uint8Array { + const dst = new Uint8Array(compressBlockBound(data.length)); + const n = compressBlockInto(data, dst); + return dst.slice(0, n); +} diff --git a/packages/sqlite-js-stream/test/ltx/crc64.test.ts b/packages/sqlite-js-stream/test/ltx/crc64.test.ts index 561f5ee..2aee25f 100644 --- a/packages/sqlite-js-stream/test/ltx/crc64.test.ts +++ b/packages/sqlite-js-stream/test/ltx/crc64.test.ts @@ -1,6 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; import { Crc64, crc64ISO } from '../../src/ltx/crc64.ts'; +import { ReferenceCrc64 } from '../helpers/crc64-reference.ts'; test('crc64 ISO matches the published check value for "123456789"', () => { assert.equal(crc64ISO(new TextEncoder().encode('123456789')), 0xb90956c775a41001n); @@ -29,3 +31,25 @@ test('crc64 reset returns to initial state', () => { test('crc64 of empty buffer is the init/xorout complement', () => { assert.equal(crc64ISO(new Uint8Array(0)), 0n); }); + +test('crc64 equals the BigInt reference on random buffers, whole and in chunks', () => { + for (const size of [1, 7, 8, 9, 255, 256, 4096, 65536]) { + const data = new Uint8Array(randomBytes(size)); + const reference = new ReferenceCrc64(); + reference.update(data); + assert.equal(crc64ISO(data), reference.sum64(), `size ${size}`); + + const h = new Crc64(); + const split = Math.floor(size / 3); + h.update(data.subarray(0, split)); + h.update(data.subarray(split)); + assert.equal(h.sum64(), reference.sum64(), `size ${size} in chunks`); + } + + for (const byte of [0x00, 0xff, 0x80]) { + const data = new Uint8Array(4096).fill(byte); + const reference = new ReferenceCrc64(); + reference.update(data); + assert.equal(crc64ISO(data), reference.sum64(), `byte ${byte}`); + } +}); diff --git a/packages/sqlite-js-stream/test/ltx/lz4.test.ts b/packages/sqlite-js-stream/test/ltx/lz4.test.ts index 276eed2..0a2db44 100644 --- a/packages/sqlite-js-stream/test/ltx/lz4.test.ts +++ b/packages/sqlite-js-stream/test/ltx/lz4.test.ts @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { randomBytes } from 'node:crypto'; import { compressBlock, decompressBlock } from '../../src/ltx/index.ts'; import { byteEq } from '../helpers/byte.ts'; +import { referenceCompressBlock } from '../helpers/lz4-reference.ts'; test('lz4 block round-trips compressible data', () => { const data = new Uint8Array(512); @@ -58,3 +59,57 @@ test('lz4 compressBlock is byte-identical to Go pierrec/lz4/v4', () => { assert.equal(toHex(compressed), expectedHex, `Go byte-identity for: ${JSON.stringify(input.slice(0, 24))}`); } }); + +test('lz4 compressBlock equals the BigInt reference, byte for byte', () => { + const inputs: Uint8Array[] = []; + + // Sizes around the limits of the scan, of random and of repeated bytes + for (const size of [0, 1, 13, 14, 15, 16, 22, 23, 64, 255, 256, 4095, 4096, 4097, 65535, 65536, 65537, 200000]) { + inputs.push(new Uint8Array(randomBytes(size))); + inputs.push(new Uint8Array(size).fill(0xab)); + inputs.push(new Uint8Array(size)); + } + + // Pages like those of a database: text, small integers, runs, and matches at every distance + let seed = 0x9e3779b9; + const next = (): number => { + seed ^= seed << 13; + seed ^= seed >>> 17; + seed ^= seed << 5; + return seed >>> 0; + }; + + for (let page = 0; page < 300; page++) { + const size = [512, 4096, 8192, 65536][page % 4]; + const data = new Uint8Array(size); + let i = 0; + + while (i < size) { + const kind = next() % 5; + const length = Math.min(1 + (next() % 300), size - i); + + if (kind === 0) { + data.fill(next() & 0xff, i, i + length); + } else if (kind === 1 && i > 0) { + const distance = 1 + (next() % Math.min(i, 70000)); + for (let j = 0; j < length; j++) data[i + j] = data[i + j - distance]; + } else if (kind === 2) { + for (let j = 0; j < length; j++) data[i + j] = 97 + (next() % 26); + } else if (kind === 3) { + for (let j = 0; j < length; j++) data[i + j] = next() % 4; + } else { + for (let j = 0; j < length; j++) data[i + j] = next() & 0xff; + } + + i += length; + } + + inputs.push(data); + } + + for (const [index, data] of inputs.entries()) { + const compressed = compressBlock(data); + assert.ok(byteEq(compressed, referenceCompressBlock(data)), `input ${index} of ${data.length} bytes`); + assert.ok(byteEq(decompressBlock(compressed, data.length), data), `round trip of input ${index}`); + } +}); From 2d7376151b94e20019a25f5051bbd8e92bd70ca8 Mon Sep 17 00:00:00 2001 From: marcopiraccini Date: Mon, 23 Nov 2026 19:08:47 +0100 Subject: [PATCH 2/2] test(ltx): add a benchmark of the page encoding Signed-off-by: marcopiraccini --- package.json | 1 + packages/sqlite-js-stream/README.md | 11 ++ .../bench/bench-ltx-encode.ts | 121 ++++++++++++++++++ packages/sqlite-js-stream/package.json | 3 +- 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 packages/sqlite-js-stream/bench/bench-ltx-encode.ts diff --git a/package.json b/package.json index 6b24d9e..62f51ca 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "test:all": "pnpm -r --filter '!@platformatic/sqlite-js-stream-paged-vfs' test", "test:paged-vfs": "pnpm --filter @platformatic/sqlite-js-stream-paged-vfs build:native && pnpm --filter @platformatic/sqlite-js-stream-paged-vfs build && pnpm --filter @platformatic/sqlite-js-stream-paged-vfs test && node --test packages/sqlite-js-stream/test/integration/paged-restore.test.ts", "bench": "pnpm --filter @platformatic/sqlite-js-stream bench", + "bench:encode": "pnpm --filter @platformatic/sqlite-js-stream bench:encode", "golden:go": "cd packages/sqlite-js-stream/tools/golden && go run ." }, "devDependencies": { diff --git a/packages/sqlite-js-stream/README.md b/packages/sqlite-js-stream/README.md index 3e95846..529e4db 100644 --- a/packages/sqlite-js-stream/README.md +++ b/packages/sqlite-js-stream/README.md @@ -646,6 +646,17 @@ Conditions are disclosed in the output (rows, batch/transactions, source WAL byt process-wide (it includes the Node baseline), so the meaningful claim is that it stays **flat** as the database grows — see the `SCALE` mode, which shows WAL bytes and peak RSS at two sizes. +[`bench/bench-ltx-encode.ts`](bench/bench-ltx-encode.ts) measures the CPU cost of writing a page to an +LTX file, i.e. its CRC-64 checksum and its LZ4 compression, on pages of text and on random pages: + +```bash +pnpm bench:encode +# compare with the BigInt implementations they replaced: +BASELINE=1 pnpm bench:encode +# another page size: +PAGE_SIZE=65536 PAGES=256 pnpm bench:encode +``` + ### Compaction & retention Over time `sync()` writes one level-0 LTX file per transaction. To keep the replica bounded and diff --git a/packages/sqlite-js-stream/bench/bench-ltx-encode.ts b/packages/sqlite-js-stream/bench/bench-ltx-encode.ts new file mode 100644 index 0000000..4ab6f3a --- /dev/null +++ b/packages/sqlite-js-stream/bench/bench-ltx-encode.ts @@ -0,0 +1,121 @@ +/** + * LTX page encoding benchmark. + * + * Every page written to an LTX file is checksummed (CRC-64 ISO) and compressed + * (LZ4 block): this measures the throughput of both, the CPU cost of a sync + * once the pages are read. Each is run on pages of text, which compress, and on + * random pages, which do not. + * + * With BASELINE=1 the BigInt implementations they replaced, kept as test + * helpers, are measured too, and the speedup is reported. + * + * Tunables (env): + * PAGES pages in each set (default 2048) + * PAGE_SIZE bytes of a page (default 4096) + * ROUNDS timed rounds, the best one is reported (default 5) + * BASELINE also measure the BigInt implementations (off by default) + * + * Run: + * pnpm bench:encode + * BASELINE=1 pnpm bench:encode + * PAGE_SIZE=65536 PAGES=256 pnpm bench:encode + */ + +import { randomBytes } from 'node:crypto'; + +import { Crc64 } from '../src/ltx/crc64.ts'; +import { compressBlock } from '../src/ltx/lz4.ts'; +import { ReferenceCrc64 } from '../test/helpers/crc64-reference.ts'; +import { referenceCompressBlock } from '../test/helpers/lz4-reference.ts'; + +const PAGES = Number(process.env.PAGES ?? 2048); +const PAGE_SIZE = Number(process.env.PAGE_SIZE ?? 4096); +const ROUNDS = Number(process.env.ROUNDS ?? 5); +const BASELINE = Boolean(process.env.BASELINE); + +/** Pages of lowercase text with repetitions at several distances. */ +function textPages(): Uint8Array[] { + const pages: Uint8Array[] = []; + for (let p = 0; p < PAGES; p++) { + const page = new Uint8Array(PAGE_SIZE); + for (let i = 0; i < PAGE_SIZE; i++) page[i] = 97 + ((i * 7 + p * 13 + (i >> 5)) % 26); + pages.push(page); + } + return pages; +} + +function randomPages(): Uint8Array[] { + const pages: Uint8Array[] = []; + for (let p = 0; p < PAGES; p++) pages.push(new Uint8Array(randomBytes(PAGE_SIZE))); + return pages; +} + +/** Returns the best throughput of `fn` over the rounds, in MB/s, after a warm-up. */ +function throughput(fn: () => void): number { + const megabytes = (PAGES * PAGE_SIZE) / (1024 * 1024); + let best = 0; + fn(); + for (let round = 0; round < ROUNDS; round++) { + const start = process.hrtime.bigint(); + fn(); + const seconds = Number(process.hrtime.bigint() - start) / 1e9; + best = Math.max(best, megabytes / seconds); + } + return best; +} + +interface Row { + operation: string; + pages: string; + 'MB/s': string; + 'BigInt MB/s'?: string; + speedup?: string; +} + +function row(operation: string, pages: string, current: number, baseline: number | null): Row { + const result: Row = { operation, pages, 'MB/s': current.toFixed(1) }; + if (baseline !== null) { + result['BigInt MB/s'] = baseline.toFixed(1); + result.speedup = `${(current / baseline).toFixed(1)}x`; + } + return result; +} + +/** The throughput of two steps run one after the other on the same bytes. */ +function combined(a: number, b: number): number { + return 1 / (1 / a + 1 / b); +} + +const rows: Row[] = []; + +for (const [name, pages] of [['text', textPages()], ['random', randomPages()]] as const) { + const crc = throughput(() => { + const h = new Crc64(); + for (const page of pages) h.update(page); + h.sum64(); + }); + const lz4 = throughput(() => { + for (const page of pages) compressBlock(page); + }); + + let crcBaseline: number | null = null; + let lz4Baseline: number | null = null; + + if (BASELINE) { + crcBaseline = throughput(() => { + const h = new ReferenceCrc64(); + for (const page of pages) h.update(page); + h.sum64(); + }); + lz4Baseline = throughput(() => { + for (const page of pages) referenceCompressBlock(page); + }); + } + + rows.push(row('CRC-64', name, crc, crcBaseline)); + rows.push(row('LZ4', name, lz4, lz4Baseline)); + rows.push(row('both', name, combined(crc, lz4), crcBaseline === null || lz4Baseline === null ? null : combined(crcBaseline, lz4Baseline))); +} + +console.log(`${PAGES} pages of ${PAGE_SIZE} bytes, best of ${ROUNDS} rounds, Node.js ${process.version}`); +console.table(rows); diff --git a/packages/sqlite-js-stream/package.json b/packages/sqlite-js-stream/package.json index a2780f2..bf3be93 100644 --- a/packages/sqlite-js-stream/package.json +++ b/packages/sqlite-js-stream/package.json @@ -44,7 +44,8 @@ "test": "node --test 'test/**/*.test.ts'", "build": "tsc -p tsconfig.build.json", "prepack": "pnpm build", - "bench": "node bench/bench-sync-restore.ts" + "bench": "node bench/bench-sync-restore.ts", + "bench:encode": "node bench/bench-ltx-encode.ts" }, "dependencies": { "lz4js": "^0.2.0"