diff --git a/libs/data/questdb/test/ilp-v2-writer-edges.test.ts b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts new file mode 100644 index 00000000..d43bd8ae --- /dev/null +++ b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts @@ -0,0 +1,426 @@ +import { describe, expect, it } from 'bun:test'; +import { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Bar1mSession, + type Fx1mIlpV2Row, + type IlpV2BatchSink, +} from '../src/index'; + +const encoder = new TextEncoder(); + +function asciiBytes(text: string): number[] { + return Array.from(encoder.encode(text)); +} + +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { + const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { + return { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_000_000n, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: 'RTH', + source: 'eod_unadj', + ...overrides, + }; +} + +function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { + return { + pair: 'USD.CAD', + source: 'eod', + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + ts: 1_736_951_400_000_000n, + ...overrides, + }; +} + +function expectEncodeError(fn: () => unknown, kind: IlpV2EncodeError['kind'], field: string) { + let caught: unknown; + try { + fn(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(IlpV2EncodeError); + expect((caught as IlpV2EncodeError).kind).toBe(kind); + expect((caught as IlpV2EncodeError).field).toBe(field); +} + +describe('ILP v2 encoder edge cases', () => { + it('matches golden_bytes_literal_ieee754_little_endian_without_to_le_bytes with hand-written bytes', () => { + // Mirrors `golden_bytes_literal_ieee754_little_endian_without_to_le_bytes` + // in `tools/curate-etl/src/ilp_tests.rs` (key 7, source eod_unadj). + const actual = encodeBar1mIlpV2({ + listing_id: 7, + ts: 1_700_000_000_000_000n, + known_at: 1_700_000_060_000_000n, + open: 1.0, + high: 2.0, + low: 0.5, + close: 1.5, + volume: 0.0, + session: 'RTH', + source: 'eod_unadj', + }); + + const expected = new Uint8Array([ + ...asciiBytes('bars_1m,listing_id=7,session=RTH,source=eod_unadj '), + ...asciiBytes('open=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf0, + 0x3f, + ...asciiBytes(',high=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x40, + ...asciiBytes(',low=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xe0, + 0x3f, + ...asciiBytes(',close=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf8, + 0x3f, + ...asciiBytes(',volume=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ...asciiBytes(',known_at=1700000060000000t 1700000000000000t\n'), + ]); + + expect(actual).toEqual(expected); + }); + + it('preserves the negative-zero sign bit like Rust f64::to_le_bytes and emits -0 listing_id as 0', () => { + const bytes = encodeBar1mIlpV2(sampleBar({ listing_id: -0, volume: -0 })); + + expect(Array.from(bytes.slice(0, 22))).toEqual(asciiBytes('bars_1m,listing_id=0,s')); + const volumePrefix = encoder.encode(',volume=='); + const suffix = encoder.encode(',known_at=1736951460000000t 1736951400000000t\n'); + const volStart = bytes.byteLength - suffix.byteLength - 9 - volumePrefix.byteLength; + expect(bytes.slice(volStart, volStart + volumePrefix.byteLength)).toEqual(volumePrefix); + expect( + Array.from( + bytes.slice(volStart + volumePrefix.byteLength, volStart + volumePrefix.byteLength + 9) + ) + ).toEqual([0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]); + }); + + it('encodes extreme finite doubles (MAX_VALUE, MIN_VALUE subnormal, negative) without rejection', () => { + const bytes = encodeFx1mIlpV2( + sampleFx({ open: Number.MAX_VALUE, high: Number.MIN_VALUE, low: -1.5, close: 0 }) + ); + const head = encoder.encode('fx_1m,pair=USD.CAD,source=eod open=='); + expect(bytes.slice(0, head.byteLength)).toEqual(head); + let o = head.byteLength; + // MAX_VALUE = 0x7fefffffffffffff + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f, + ]); + o += 9 + ',high=='.length; + // MIN_VALUE = 0x0000000000000001 + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]); + o += 9 + ',low=='.length; + // -1.5 = 0xbff8000000000000 + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf, + ]); + }); + + it('returns a fresh buffer per call so mutating one encoding cannot corrupt another', () => { + const row = sampleFx(); + const a = encodeFx1mIlpV2(row); + const b = encodeFx1mIlpV2(row); + a.fill(0); + expect(b).toEqual(encodeFx1mIlpV2(row)); + expect(b[0]).toBe(0x66); // 'f' + }); + + it('escapes a symbol consisting only of special characters', () => { + const bytes = encodeFx1mIlpV2(sampleFx({ pair: ' ,=\\\n\r' })); + const expected = encoder.encode('fx_1m,pair=\\ \\,\\=\\\\\\\n\\\r,source=eod open=='); + expect(bytes.slice(0, expected.byteLength)).toEqual(expected); + }); + + it('rejects invalid or empty session tags with a typed error', () => { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: 'rth' as Bar1mSession })), + 'invalid-session', + 'session' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: 'RTH ' as Bar1mSession })), + 'invalid-session', + 'session' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: '' as Bar1mSession })), + 'empty-symbol', + 'session' + ); + }); + + it('rejects non-bigint timestamps (JS number) instead of silently encoding them', () => { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: 1_700_000_000_000_000 as unknown as bigint })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: 5 as unknown as bigint })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ ts: 0 as unknown as bigint })), + 'timestamp-out-of-range', + 'ts' + ); + }); + + it('accepts the fx_1m designated timestamp at INT64_MAX', () => { + const max = 2n ** 63n - 1n; + const bytes = encodeFx1mIlpV2(sampleFx({ ts: max })); + const suffix = encoder.encode(` ${max.toString(10)}t\n`); + expect(bytes.slice(bytes.byteLength - suffix.byteLength)).toEqual(suffix); + }); +}); + +describe('createIlpV2BatchWriter edge cases', () => { + it('rejects construction without a usable sink and rejects unsafe-integer limits', () => { + expect(() => createIlpV2BatchWriter(undefined as never)).toThrow(TypeError); + expect(() => createIlpV2BatchWriter({} as never)).toThrow(TypeError); + expect(() => createIlpV2BatchWriter({ sink: {} as IlpV2BatchSink })).toThrow(TypeError); + const sink: IlpV2BatchSink = { write: async () => {} }; + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 2 ** 53 })).toThrow(RangeError); + expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: '5' as unknown as number })).toThrow( + RangeError + ); + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 1, maxBatchRows: 1 })).not.toThrow(); + }); + + it('flushes at DEFAULT_ILP_MAX_BATCH_ROWS when no limits are supplied', async () => { + const batches: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ sink: { write: async b => void batches.push(b) } }); + const row = sampleFx({ ts: 0n }); + const rowLen = encodeFx1mIlpV2(row).byteLength; + // Row size keeps 10_000 rows well below the 1 MiB default, so only the row limit triggers. + expect(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS).toBeLessThan(DEFAULT_ILP_MAX_BATCH_BYTES); + + for (let i = 0; i < DEFAULT_ILP_MAX_BATCH_ROWS - 1; i++) { + await writer.writeFx1m(row); + } + expect(batches).toHaveLength(0); + await writer.writeFx1m(row); + expect(batches).toHaveLength(1); + expect(batches[0]!.byteLength).toBe(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS); + + await writer.writeFx1m(row); + const stats = await writer.finish(); + expect(stats).toEqual({ + rows: DEFAULT_ILP_MAX_BATCH_ROWS + 1, + batches: 2, + bytes: rowLen * (DEFAULT_ILP_MAX_BATCH_ROWS + 1), + }); + }); + + it('hands the sink a fresh batch buffer per flush so retained batches are never overwritten', async () => { + const retained: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ + sink: { write: async b => void retained.push(b) }, + maxBatchRows: 1, + }); + const r1 = sampleBar({ listing_id: 1 }); + const r2 = sampleBar({ listing_id: 2 }); + await writer.writeBar1m(r1); + await writer.writeBar1m(r2); + await writer.finish(); + expect(retained[0]).not.toBe(retained[1]); + expect(retained[0]!.buffer).not.toBe(retained[1]!.buffer); + expect(retained).toEqual([encodeBar1mIlpV2(r1), encodeBar1mIlpV2(r2)]); + }); + + it('a rejected row in the middle of overlapping writes does not block or reorder later queued rows', async () => { + const batches: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ + sink: { write: async b => void batches.push(b.slice()) }, + maxBatchRows: 2, + maxBatchBytes: 100_000, + }); + const a = sampleBar({ listing_id: 1 }); + const c = sampleFx({ pair: 'EUR.USD' }); + const d = sampleBar({ listing_id: 4 }); + + const pa = writer.writeBar1m(a); + const pb = writer.writeBar1m(sampleBar({ high: Number.NaN })); + const pc = writer.writeFx1m(c); + const pd = writer.writeBar1m(d); + const pFinish = writer.finish(); + + await pa; + await expect(pb).rejects.toBeInstanceOf(IlpV2EncodeError); + await pc; + await pd; + const stats = await pFinish; + + const expected = [encodeBar1mIlpV2(a), encodeFx1mIlpV2(c), encodeBar1mIlpV2(d)]; + expect(batches).toEqual([concatBytes(expected.slice(0, 2)), expected[2]!]); + expect(stats).toEqual({ + rows: 3, + batches: 2, + bytes: expected.reduce((s, e) => s + e.byteLength, 0), + }); + }); + + it('treats a synchronously throwing sink like a rejected write and fails closed', async () => { + const boom = new Error('sync sink failure'); + let calls = 0; + const sink: IlpV2BatchSink = { + write(): Promise { + calls += 1; + throw boom; + }, + }; + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1 }); + + await expect(writer.writeBar1m(sampleBar())).rejects.toBe(boom); + await expect(writer.writeBar1m(sampleBar())).rejects.toThrow(/sink write failure/i); + await expect(writer.flush()).rejects.toThrow(/sink write failure/i); + expect(calls).toBe(1); + }); + + it('propagates a sink failure on the finish() tail flush, excludes it from stats, and stays closed', async () => { + const boom = new Error('tail failure'); + let calls = 0; + const sink: IlpV2BatchSink = { + async write(): Promise { + calls += 1; + if (calls === 2) { + throw boom; + } + }, + }; + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); + await writer.writeBar1m(sampleBar({ listing_id: 1 })); + await writer.writeBar1m(sampleBar({ listing_id: 2 })); // batch 1 OK + await writer.writeBar1m(sampleBar({ listing_id: 3 })); // pending tail + + await expect(writer.finish()).rejects.toBe(boom); + expect(calls).toBe(2); + + const err = await writer.finish().then( + () => null, + (e: unknown) => e as Error + ); + expect(err).toBeInstanceOf(Error); + expect(err!.message).toMatch(/sink write failure/i); + // The original sink error is preserved as the cause for diagnostics. + expect(err!.cause).toBe(boom); + expect(calls).toBe(2); + }); + + it('flush() on an explicit call propagates sink failure and blocks the tail on finish()', async () => { + const boom = new Error('flush failure'); + let calls = 0; + const writer = createIlpV2BatchWriter({ + sink: { + async write(): Promise { + calls += 1; + throw boom; + }, + }, + }); + await writer.writeFx1m(sampleFx()); + await expect(writer.flush()).rejects.toBe(boom); + await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); + await expect(writer.finish()).rejects.toThrow(/sink write failure/i); + expect(calls).toBe(1); + }); + + it('serializes an overlapping explicit flush() behind in-flight writes', async () => { + const order: string[] = []; + let release: (() => void) | null = null; + const writer = createIlpV2BatchWriter({ + sink: { + write(b: Uint8Array): Promise { + order.push(`write:${b.byteLength}`); + if (release === null) { + return new Promise(resolve => { + release = resolve; + }); + } + return Promise.resolve(); + }, + }, + maxBatchRows: 1, + }); + const row = sampleFx(); + const len = encodeFx1mIlpV2(row).byteLength; + + const p1 = writer.writeFx1m(row); + const pFlush = writer.flush().then(() => order.push('flushed')); + const p2 = writer.writeFx1m(row); + + await Promise.resolve(); + expect(order).toEqual([`write:${len}`]); + release!(); + await Promise.all([p1, pFlush, p2]); + expect(order).toEqual([`write:${len}`, 'flushed', `write:${len}`]); + }); +});