T-145: tests
This commit is contained in:
parent
dd8dc692af
commit
8f1bfbe9f1
2 changed files with 257 additions and 0 deletions
|
|
@ -729,3 +729,203 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
interface FundamentalsFixtureRow {
|
||||
readonly listingId: number;
|
||||
readonly effectiveKnownAt: string;
|
||||
readonly hasEstimatedLag?: boolean;
|
||||
readonly periodEnd: string;
|
||||
readonly fiscalPeriod: string;
|
||||
readonly periodKnownAt?: string;
|
||||
readonly revenue: number | null;
|
||||
readonly ttmRevenue: number | null;
|
||||
readonly ttmHasEstimatedLag: boolean | null;
|
||||
}
|
||||
|
||||
function fundamentalsRowSql(r: FundamentalsFixtureRow): string {
|
||||
const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`);
|
||||
const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`);
|
||||
const ttmMissing = r.ttmRevenue === null;
|
||||
return `(
|
||||
${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)},
|
||||
DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}',
|
||||
${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE,
|
||||
${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`},
|
||||
${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)}
|
||||
)`;
|
||||
}
|
||||
|
||||
async function writeFundamentalsPartition(
|
||||
curatedRoot: string,
|
||||
year: number,
|
||||
rows: readonly FundamentalsFixtureRow[]
|
||||
): Promise<void> {
|
||||
const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`);
|
||||
await mkdir(dir, { recursive: true });
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).join(', ')}) AS t(
|
||||
listing_id, effective_known_at, known_at_source, has_estimated_lag,
|
||||
period_end, fiscal_period, currency, period_known_at,
|
||||
revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding,
|
||||
ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag
|
||||
)
|
||||
) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => {
|
||||
async function openFundamentalsStore(): Promise<Awaited<ReturnType<typeof openDuckDbMarketDataStore>>> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-'));
|
||||
tempDirs.push(root);
|
||||
const curatedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
// Partition directory does not drive ranking: listing 7's newest snapshot sits in
|
||||
// year=2023 while its older one sits in year=2024; listing 8 is the reverse.
|
||||
await writeFundamentalsPartition(curatedRoot, 2023, [
|
||||
{ listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false },
|
||||
{ listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false },
|
||||
]);
|
||||
await writeFundamentalsPartition(curatedRoot, 2024, [
|
||||
{ listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false },
|
||||
{ listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false },
|
||||
// Sub-millisecond neighbours: only the microsecond distinguishes them.
|
||||
{ listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false },
|
||||
{ listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false },
|
||||
// Verified Q1, then estimated Q2.
|
||||
{ listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false },
|
||||
{ listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true },
|
||||
// TTM-only estimated lag.
|
||||
{ listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true },
|
||||
// No TTM yet (fewer than four quarters): TTM values and flag are NULL.
|
||||
{ listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null },
|
||||
]);
|
||||
|
||||
return openDuckDbMarketDataStore({
|
||||
curatedRoot,
|
||||
vaultCutoffTs: computeVaultCutoffTs('2025-08-13'),
|
||||
env: {
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => {
|
||||
const opened = await openFundamentalsStore();
|
||||
try {
|
||||
const result = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [8, 7],
|
||||
fields: ['revenue'],
|
||||
asOf: '2024-06-01',
|
||||
});
|
||||
expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([
|
||||
[7, 'Q1', 70],
|
||||
[8, 'Q4', 85],
|
||||
]);
|
||||
|
||||
const earlier = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [7, 8],
|
||||
fields: ['revenue'],
|
||||
asOf: '2024-01-01',
|
||||
});
|
||||
expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => {
|
||||
const opened = await openFundamentalsStore();
|
||||
try {
|
||||
const at = async (asOf: string): Promise<unknown[]> =>
|
||||
(await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map(
|
||||
r => r.revenue
|
||||
);
|
||||
expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]);
|
||||
expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]);
|
||||
expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]);
|
||||
expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => {
|
||||
const opened = await openFundamentalsStore();
|
||||
try {
|
||||
const beforeEstimate = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [10],
|
||||
fields: ['revenue'],
|
||||
asOf: '2024-07-31',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]);
|
||||
|
||||
const afterEstimate = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [10],
|
||||
fields: ['revenue'],
|
||||
asOf: '2024-08-02',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(afterEstimate.rows).toEqual([]);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => {
|
||||
const opened = await openFundamentalsStore();
|
||||
try {
|
||||
const noTtm = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [11],
|
||||
fields: ['revenue'],
|
||||
asOf: '2024-06-01',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(noTtm.columns).not.toContain('ttm_has_estimated_lag');
|
||||
expect(noTtm.rows).toEqual([
|
||||
expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }),
|
||||
]);
|
||||
expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]);
|
||||
|
||||
const nullTtm = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [12, 11],
|
||||
fields: ['ttm_revenue'],
|
||||
asOf: '2024-06-01',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([
|
||||
[11, null, null, null, true],
|
||||
[12, null, null, null, null],
|
||||
]);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('returns only requested listings and is reproducible across repeated identical queries', async () => {
|
||||
const opened = await openFundamentalsStore();
|
||||
try {
|
||||
const q = {
|
||||
listingIds: [12, 999, 7],
|
||||
fields: ['ttm_revenue', 'revenue'],
|
||||
asOf: '2024-09-01T00:00:00.000001Z',
|
||||
};
|
||||
const first = await opened.store.fundamentalsAsOf(q);
|
||||
const second = await opened.store.fundamentalsAsOf(q);
|
||||
expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]);
|
||||
expect(second).toEqual(first);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3220,3 +3220,60 @@ describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentals
|
|||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fundamentalsAsOf hostile request inputs', () => {
|
||||
it('fails closed with zero executor calls for JSON-decoded object, symbol, and sparse field entries', async () => {
|
||||
const fake = createRecordingExecutor();
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
|
||||
const hostileFields: unknown[] = [
|
||||
JSON.parse('[{"toString": 1}]'),
|
||||
[Object.create(null)],
|
||||
[Symbol('revenue')],
|
||||
// eslint-disable-next-line no-sparse-arrays
|
||||
[, 'revenue'],
|
||||
['REVENUE'],
|
||||
[' revenue'],
|
||||
];
|
||||
for (const fields of hostileFields) {
|
||||
await expect(
|
||||
store.fundamentalsAsOf({ listingIds: [1], fields: fields as string[], asOf: '2025-06-15' })
|
||||
).rejects.toThrow();
|
||||
}
|
||||
|
||||
const hostileLag = JSON.parse('{"toString": 1}');
|
||||
await expect(
|
||||
store.fundamentalsAsOf({
|
||||
listingIds: [1],
|
||||
fields: ['revenue'],
|
||||
asOf: '2025-06-15',
|
||||
allowEstimatedLag: hostileLag as boolean,
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
expect(fake.runCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('plans a request asOf with an offset that crosses the cutoff as a clamped bound', () => {
|
||||
// 2026-05-28T01:00:00+02:00 === 2026-05-27T23:00:00Z, i.e. before the cutoff: not clamped.
|
||||
const beforeCutoff = planFundamentalsAsOfQuery(
|
||||
{ listingIds: [1], fields: ['revenue'], asOf: '2026-05-28T01:00:00+02:00' },
|
||||
DEFAULT_CTX
|
||||
);
|
||||
expect(Date.parse(beforeCutoff.params[2] as string)).toBe(Date.UTC(2026, 4, 27, 23, 0, 0, 0));
|
||||
expect(beforeCutoff.fenced.clampedAsOf).toBe(false);
|
||||
|
||||
// 2026-05-27T23:00:00-02:00 === 2026-05-28T01:00:00Z, i.e. after the cutoff: clamped.
|
||||
const afterCutoff = planFundamentalsAsOfQuery(
|
||||
{ listingIds: [1], fields: ['revenue'], asOf: '2026-05-27T23:00:00-02:00' },
|
||||
DEFAULT_CTX
|
||||
);
|
||||
expect(afterCutoff.params[2]).toBe(MAX_ALLOWED_ISO_MICROS);
|
||||
expect(afterCutoff.fenced.clampedAsOf).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue