346 lines
12 KiB
TypeScript
346 lines
12 KiB
TypeScript
import { describe, expect, it } from 'bun:test';
|
|
import {
|
|
createQuestDbIntradayBarsReader,
|
|
MarketDataStoreValidationError,
|
|
planBars1mQuery,
|
|
VaultScopeNotAuthorizedError,
|
|
type BarBatch,
|
|
type QuestDbBars1mQuery,
|
|
type QuestDbQueryExecutor,
|
|
} from '@stock-bot/research';
|
|
|
|
// QA edge cases for T-146 (QuestDB `bars_1m` reader) beyond the programmer suite.
|
|
|
|
const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0);
|
|
|
|
type QueryResult = { readonly rows: readonly Record<string, unknown>[] };
|
|
|
|
class ScriptedExecutor implements QuestDbQueryExecutor {
|
|
readonly calls: Array<{ sql: string; params: unknown[] }> = [];
|
|
constructor(private readonly respond: () => Promise<QueryResult>) {}
|
|
async query(sql: string, params: readonly unknown[]): Promise<QueryResult> {
|
|
this.calls.push({ sql, params: [...params] });
|
|
return this.respond();
|
|
}
|
|
}
|
|
|
|
function executorReturning(result: unknown): ScriptedExecutor {
|
|
return new ScriptedExecutor(async () => result as QueryResult);
|
|
}
|
|
|
|
async function collect(iterable: AsyncIterable<BarBatch>): Promise<BarBatch[]> {
|
|
const out: BarBatch[] = [];
|
|
for await (const batch of iterable) {
|
|
out.push(batch);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function us(ms: number, extraMicros = 0n): string {
|
|
return (BigInt(ms) * 1000n + extraMicros).toString();
|
|
}
|
|
|
|
function row(overrides: Record<string, unknown>): Record<string, unknown> {
|
|
return {
|
|
listing_id: '7',
|
|
open: 10,
|
|
high: 11,
|
|
low: 9,
|
|
close: 10.5,
|
|
volume: 100,
|
|
vwap: 10.2,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
const sessionQuery: QuestDbBars1mQuery = {
|
|
listingIds: [7],
|
|
timeframe: '1m',
|
|
from: '2024-03-01T14:30:00Z',
|
|
to: '2024-03-01T21:00:00Z',
|
|
asOf: '2024-03-01T21:00:00Z',
|
|
adjustment: 'raw',
|
|
};
|
|
|
|
describe('QuestDB bars_1m reader QA: planner purity and param binding', () => {
|
|
it('is deterministic and binds INT32_MAX as a decimal SYMBOL string only in params', () => {
|
|
const q: QuestDbBars1mQuery = { ...sessionQuery, listingIds: [2_147_483_647, 1] };
|
|
const a = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
const b = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
|
|
expect(a).toEqual(b);
|
|
expect(a.params).toEqual([
|
|
'2024-03-01T14:30:00.000Z',
|
|
'2024-03-01T21:00:00.000Z',
|
|
'1',
|
|
'2147483647',
|
|
'2024-03-01T21:00:00.000Z',
|
|
]);
|
|
expect(a.sql).not.toContain('2147483647');
|
|
expect(a.sql).toContain('listing_id IN ($3, $4) AND known_at <= $5');
|
|
// Only ordinal placeholders and fixed identifiers: no quotes or digits outside `$n` tokens.
|
|
expect(a.sql.replace(/\$\d+/g, '').replace('bars_1m', '')).not.toMatch(/[0-9'";]/);
|
|
});
|
|
|
|
it('normalizes offset timestamps to UTC ISO-8601 params', () => {
|
|
const planned = planBars1mQuery(
|
|
{
|
|
...sessionQuery,
|
|
from: '2024-03-01T09:30:00-05:00',
|
|
to: '2024-03-01T16:00:00.250-05:00',
|
|
asOf: '2024-03-01T17:00:00-05:00',
|
|
},
|
|
{ vaultCutoffTs: VAULT_CUTOFF_TS }
|
|
);
|
|
expect(planned.params).toEqual([
|
|
'2024-03-01T14:30:00.000Z',
|
|
'2024-03-01T21:00:00.250Z',
|
|
'7',
|
|
'2024-03-01T22:00:00.000Z',
|
|
]);
|
|
});
|
|
|
|
it('passes the executor a copy of params so executor mutation cannot alter later plans', async () => {
|
|
const executor = new ScriptedExecutor(async () => ({ rows: [] }));
|
|
const mutating: QuestDbQueryExecutor = {
|
|
async query(sql, params) {
|
|
(params as unknown[]).splice(0, params.length, 'tampered');
|
|
return executor.query(sql, params);
|
|
},
|
|
};
|
|
const reader = createQuestDbIntradayBarsReader({
|
|
executor: mutating,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
await collect(reader.bars(sessionQuery));
|
|
await collect(reader.bars(sessionQuery));
|
|
|
|
expect(executor.calls).toHaveLength(2);
|
|
expect(executor.calls[1]?.params).toEqual(['tampered']);
|
|
expect(planBars1mQuery(sessionQuery, { vaultCutoffTs: VAULT_CUTOFF_TS }).params).toHaveLength(
|
|
4
|
|
);
|
|
});
|
|
|
|
it('rejects numeric-looking string listing IDs and non-array listingIds before querying', async () => {
|
|
const executor = executorReturning({ rows: [] });
|
|
const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
const bad: unknown[] = [
|
|
{ ...sessionQuery, listingIds: ['7'] },
|
|
{ ...sessionQuery, listingIds: [7n] },
|
|
{ ...sessionQuery, listingIds: 7 },
|
|
{ ...sessionQuery, listingIds: undefined },
|
|
{ ...sessionQuery, listingIds: [7, Number.POSITIVE_INFINITY] },
|
|
null,
|
|
];
|
|
for (const q of bad) {
|
|
await expect(collect(reader.bars(q as QuestDbBars1mQuery))).rejects.toThrow(
|
|
MarketDataStoreValidationError
|
|
);
|
|
}
|
|
expect(executor.calls).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe('QuestDB bars_1m reader QA: Vault and trusted context', () => {
|
|
it('planner ignores a vaultOperatorAuthorized flag smuggled on the query object', () => {
|
|
const spoofed = {
|
|
...sessionQuery,
|
|
from: '2025-07-02',
|
|
to: '2025-07-03',
|
|
asOf: undefined,
|
|
scope: 'vault_evaluation_only',
|
|
vaultOperatorAuthorized: true,
|
|
} as unknown as QuestDbBars1mQuery;
|
|
expect(() => planBars1mQuery(spoofed, { vaultCutoffTs: VAULT_CUTOFF_TS })).toThrow(
|
|
VaultScopeNotAuthorizedError
|
|
);
|
|
});
|
|
|
|
it('rejects non-boolean truthy vaultOperatorAuthorized in factory options', () => {
|
|
for (const flag of ['true', 1, {}]) {
|
|
expect(() =>
|
|
createQuestDbIntradayBarsReader({
|
|
executor: executorReturning({ rows: [] }),
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
vaultOperatorAuthorized: flag as unknown as boolean,
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
}
|
|
});
|
|
|
|
it('rejects a non-object planner context', () => {
|
|
expect(() =>
|
|
planBars1mQuery(sessionQuery, null as unknown as { vaultCutoffTs: number })
|
|
).toThrow(MarketDataStoreValidationError);
|
|
});
|
|
|
|
it('rejects unknown scope values before querying', async () => {
|
|
const executor = executorReturning({ rows: [] });
|
|
const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
await expect(
|
|
collect(reader.bars({ ...sessionQuery, scope: 'all' } as unknown as QuestDbBars1mQuery))
|
|
).rejects.toThrow(MarketDataStoreValidationError);
|
|
expect(executor.calls).toHaveLength(0);
|
|
});
|
|
|
|
it('a row known one microsecond before a clamped asOf maps to knownAt exactly at the fence, never past it', async () => {
|
|
const executor = executorReturning({
|
|
rows: [
|
|
row({
|
|
ts_us: us(VAULT_CUTOFF_TS - 60_000),
|
|
known_at_us: us(VAULT_CUTOFF_TS - 1, -1n),
|
|
}),
|
|
],
|
|
});
|
|
const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
const rows = (
|
|
await collect(
|
|
reader.bars({
|
|
...sessionQuery,
|
|
from: '2025-06-30T23:00:00Z',
|
|
to: '2025-12-31',
|
|
asOf: '2025-12-31',
|
|
})
|
|
)
|
|
).flatMap(b => b.rows);
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0]?.knownAt).toBe(VAULT_CUTOFF_TS - 1);
|
|
expect(rows[0]!.knownAt).toBeLessThan(VAULT_CUTOFF_TS);
|
|
});
|
|
});
|
|
|
|
describe('QuestDB bars_1m reader QA: executor result and row defence-in-depth', () => {
|
|
it('rejects malformed executor results with a validation error', async () => {
|
|
for (const result of [
|
|
null,
|
|
undefined,
|
|
{},
|
|
{ rows: null },
|
|
{ rows: 'x' },
|
|
[],
|
|
{ rows: [null] },
|
|
{ rows: [[1]] },
|
|
]) {
|
|
const reader = createQuestDbIntradayBarsReader({
|
|
executor: executorReturning(result),
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
await expect(collect(reader.bars(sessionQuery))).rejects.toThrow(
|
|
MarketDataStoreValidationError
|
|
);
|
|
}
|
|
});
|
|
|
|
it('propagates executor failures unchanged and yields nothing', async () => {
|
|
const boom = new Error('pgwire connection reset');
|
|
const reader = createQuestDbIntradayBarsReader({
|
|
executor: new ScriptedExecutor(async () => {
|
|
throw boom;
|
|
}),
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
await expect(collect(reader.bars(sessionQuery))).rejects.toBe(boom);
|
|
});
|
|
|
|
it('does not call the executor until iteration starts (lazy plan + query)', async () => {
|
|
const executor = executorReturning({ rows: [] });
|
|
const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
const iterable = reader.bars(sessionQuery);
|
|
expect(executor.calls).toHaveLength(0);
|
|
await collect(iterable);
|
|
expect(executor.calls).toHaveLength(1);
|
|
});
|
|
|
|
it('maps multi-listing rows, undefined vwap to null, and -0 to 0', async () => {
|
|
const t0 = Date.UTC(2024, 2, 1, 14, 30);
|
|
const executor = executorReturning({
|
|
rows: [
|
|
row({ listing_id: '3', ts_us: us(t0), known_at_us: us(t0 + 60_000), vwap: undefined }),
|
|
row({ listing_id: '7', ts_us: us(t0), known_at_us: us(t0 + 60_000), volume: -0, vwap: 0 }),
|
|
],
|
|
});
|
|
const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
const rows = (await collect(reader.bars({ ...sessionQuery, listingIds: [7, 3] }))).flatMap(
|
|
b => b.rows
|
|
);
|
|
expect(rows.map(r => r.listingId)).toEqual([3, 7]);
|
|
expect(rows[0]?.vwap).toBeNull();
|
|
expect(Object.is(rows[1]?.volume, 0)).toBe(true);
|
|
expect(rows[1]?.vwap).toBe(0);
|
|
expect(executor.calls[0]?.params.slice(2, 4)).toEqual(['3', '7']);
|
|
});
|
|
|
|
it('rejects timestamp wire values that are unsafe numbers, padded strings, or missing', async () => {
|
|
const t0 = Date.UTC(2024, 2, 1, 14, 30);
|
|
const bad: Record<string, unknown>[] = [
|
|
row({ ts_us: Number.MAX_SAFE_INTEGER + 2, known_at_us: us(t0) }),
|
|
row({ ts_us: ` ${us(t0)}`, known_at_us: us(t0) }),
|
|
row({ ts_us: `+${us(t0)}`, known_at_us: us(t0) }),
|
|
row({ ts_us: us(t0) }),
|
|
row({ ts_us: new Date(t0), known_at_us: us(t0) }),
|
|
];
|
|
for (const r of bad) {
|
|
const reader = createQuestDbIntradayBarsReader({
|
|
executor: executorReturning({ rows: [r] }),
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
await expect(collect(reader.bars(sessionQuery))).rejects.toThrow(
|
|
MarketDataStoreValidationError
|
|
);
|
|
}
|
|
});
|
|
|
|
it('floors sub-millisecond ts and ceils sub-millisecond known_at for pre-1970 instants', async () => {
|
|
// ts = -1.5 ms -> floor -2 ms; known_at = -1.5 ms -> ceil -1 ms.
|
|
const executor = executorReturning({
|
|
rows: [row({ ts_us: '-1500', known_at_us: -1500n })],
|
|
});
|
|
const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS });
|
|
const rows = (
|
|
await collect(
|
|
reader.bars({
|
|
...sessionQuery,
|
|
from: '1969-12-31T23:59:59.000Z',
|
|
to: '1970-01-01T00:00:00.000Z',
|
|
asOf: '1970-01-01T00:00:00.000Z',
|
|
})
|
|
)
|
|
).flatMap(b => b.rows);
|
|
expect(rows).toEqual([
|
|
{
|
|
listingId: 7,
|
|
ts: -2,
|
|
open: 10,
|
|
high: 11,
|
|
low: 9,
|
|
close: 10.5,
|
|
volume: 100,
|
|
vwap: 10.2,
|
|
knownAt: -1,
|
|
},
|
|
]);
|
|
});
|
|
|
|
it('batch size equal to row count yields one batch; batch size 1 yields one row per batch in order', async () => {
|
|
const t0 = Date.UTC(2024, 2, 1, 14, 30);
|
|
const rows = Array.from({ length: 4 }, (_, i) =>
|
|
row({ ts_us: us(t0 + i * 60_000), known_at_us: us(t0 + (i + 1) * 60_000), open: 10 + i })
|
|
);
|
|
const exact = createQuestDbIntradayBarsReader({
|
|
executor: executorReturning({ rows }),
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
batchSize: 4,
|
|
});
|
|
expect((await collect(exact.bars(sessionQuery))).map(b => b.rows.length)).toEqual([4]);
|
|
|
|
const single = createQuestDbIntradayBarsReader({
|
|
executor: executorReturning({ rows }),
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
batchSize: 1,
|
|
});
|
|
const batches = await collect(single.bars(sessionQuery));
|
|
expect(batches.map(b => b.rows.length)).toEqual([1, 1, 1, 1]);
|
|
expect(batches.map(b => b.rows[0]?.open)).toEqual([10, 11, 12, 13]);
|
|
});
|
|
});
|