Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
11 changes: 11 additions & 0 deletions packages/sqlite-js-stream/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
121 changes: 121 additions & 0 deletions packages/sqlite-js-stream/bench/bench-ltx-encode.ts
Original file line number Diff line number Diff line change
@@ -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);
3 changes: 2 additions & 1 deletion packages/sqlite-js-stream/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
49 changes: 33 additions & 16 deletions packages/sqlite-js-stream/src/ltx/crc64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,47 +13,64 @@
* `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`
* (ISO table). Call `update()` with successive byte chunks and `sum64()` to
* 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);
}
}

Expand Down
84 changes: 48 additions & 36 deletions packages/sqlite-js-stream/src/ltx/lz4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
}

/**
Expand Down Expand Up @@ -112,26 +120,26 @@ 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);
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);
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;
}
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}
}
Expand Down
Loading
Loading