T-145: M2.2d — fundamentalsAsOf in the DuckDB MarketDataStore: Vault-fenced point-in-time read of fundamentals_pit/year=*/part.parquet with a real-DuckDB restatement fixture test (no new deps)
This commit is contained in:
parent
1a318f0773
commit
dd8dc692af
4 changed files with 1096 additions and 13 deletions
|
|
@ -247,4 +247,485 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => {
|
|||
await opened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-'));
|
||||
tempDirs.push(root);
|
||||
const curatedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
|
||||
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true });
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
// Vault cutoff = 2025-02-13T00:00:00.000Z
|
||||
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
|
||||
const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z
|
||||
const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z
|
||||
const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z
|
||||
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
// year=2023 partition: listing 50 (only exists in 2023 partition)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(
|
||||
50::INTEGER,
|
||||
TIMESTAMPTZ '2023-11-05 20:00:00+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2023-09-30',
|
||||
'Q3'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2023-11-05 20:00:00+00',
|
||||
80.0::DOUBLE,
|
||||
8.0::DOUBLE,
|
||||
12.0::DOUBLE,
|
||||
500.0::DOUBLE,
|
||||
250.0::DOUBLE,
|
||||
10.0::DOUBLE,
|
||||
DATE '2023-09-30',
|
||||
'USD'::VARCHAR,
|
||||
310.0::DOUBLE,
|
||||
31.0::DOUBLE,
|
||||
46.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
)
|
||||
) 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(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// year=2024 partition:
|
||||
// - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes)
|
||||
// - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback)
|
||||
// - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(
|
||||
101::INTEGER,
|
||||
TIMESTAMPTZ '2024-05-01 20:00:00+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-03-31',
|
||||
'Q1'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2024-05-01 20:00:00+00',
|
||||
100.0::DOUBLE,
|
||||
10.0::DOUBLE,
|
||||
15.0::DOUBLE,
|
||||
1000.0::DOUBLE,
|
||||
500.0::DOUBLE,
|
||||
50.0::DOUBLE,
|
||||
DATE '2024-03-31',
|
||||
'USD'::VARCHAR,
|
||||
380.0::DOUBLE,
|
||||
38.0::DOUBLE,
|
||||
55.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
101::INTEGER,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-06-30',
|
||||
'Q2'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
120.0::DOUBLE,
|
||||
14.0::DOUBLE,
|
||||
20.0::DOUBLE,
|
||||
1050.0::DOUBLE,
|
||||
520.0::DOUBLE,
|
||||
50.0::DOUBLE,
|
||||
DATE '2024-06-30',
|
||||
'USD'::VARCHAR,
|
||||
420.0::DOUBLE,
|
||||
44.0::DOUBLE,
|
||||
65.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
101::INTEGER,
|
||||
TIMESTAMPTZ '2024-09-15 20:00:00+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-06-30',
|
||||
'Q2'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
120.0::DOUBLE,
|
||||
14.0::DOUBLE,
|
||||
20.0::DOUBLE,
|
||||
1050.0::DOUBLE,
|
||||
520.0::DOUBLE,
|
||||
50.0::DOUBLE,
|
||||
DATE '2024-06-30',
|
||||
'USD'::VARCHAR,
|
||||
415.0::DOUBLE,
|
||||
42.0::DOUBLE,
|
||||
63.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
201::INTEGER,
|
||||
TIMESTAMPTZ '2024-05-01 20:00:00+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-03-31',
|
||||
'Q1'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2024-05-01 20:00:00+00',
|
||||
50.0::DOUBLE,
|
||||
5.0::DOUBLE,
|
||||
7.0::DOUBLE,
|
||||
400.0::DOUBLE,
|
||||
200.0::DOUBLE,
|
||||
20.0::DOUBLE,
|
||||
DATE '2024-03-31',
|
||||
'USD'::VARCHAR,
|
||||
190.0::DOUBLE,
|
||||
19.0::DOUBLE,
|
||||
27.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
201::INTEGER,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
'estimated_lag'::VARCHAR,
|
||||
TRUE::BOOLEAN,
|
||||
DATE '2024-06-30',
|
||||
'Q2'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
60.0::DOUBLE,
|
||||
6.0::DOUBLE,
|
||||
8.0::DOUBLE,
|
||||
420.0::DOUBLE,
|
||||
210.0::DOUBLE,
|
||||
20.0::DOUBLE,
|
||||
DATE '2024-06-30',
|
||||
'USD'::VARCHAR,
|
||||
210.0::DOUBLE,
|
||||
21.0::DOUBLE,
|
||||
30.0::DOUBLE,
|
||||
TRUE::BOOLEAN
|
||||
),
|
||||
(
|
||||
202::INTEGER,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-06-30',
|
||||
'Q2'::VARCHAR,
|
||||
'CAD'::VARCHAR,
|
||||
TIMESTAMPTZ '2024-08-01 20:00:00+00',
|
||||
75.0::DOUBLE,
|
||||
9.0::DOUBLE,
|
||||
11.0::DOUBLE,
|
||||
600.0::DOUBLE,
|
||||
300.0::DOUBLE,
|
||||
30.0::DOUBLE,
|
||||
DATE '2024-06-30',
|
||||
'CAD'::VARCHAR,
|
||||
300.0::DOUBLE,
|
||||
30.0::DOUBLE,
|
||||
45.0::DOUBLE,
|
||||
TRUE::BOOLEAN
|
||||
)
|
||||
) 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(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// year=2025 partition: Vault microsecond boundary rows
|
||||
// - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded)
|
||||
// - listing 103: exact cutoff only (must return 0 rows)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(
|
||||
102::INTEGER,
|
||||
TIMESTAMPTZ '2025-02-12 23:59:59.999999+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-12-31',
|
||||
'Q4'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2025-02-12 23:59:59.999999+00',
|
||||
210.0::DOUBLE,
|
||||
21.0::DOUBLE,
|
||||
31.0::DOUBLE,
|
||||
1500.0::DOUBLE,
|
||||
750.0::DOUBLE,
|
||||
60.0::DOUBLE,
|
||||
DATE '2024-12-31',
|
||||
'USD'::VARCHAR,
|
||||
800.0::DOUBLE,
|
||||
80.0::DOUBLE,
|
||||
120.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
102::INTEGER,
|
||||
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-12-31',
|
||||
'Q4'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
|
||||
999.0::DOUBLE,
|
||||
99.0::DOUBLE,
|
||||
99.0::DOUBLE,
|
||||
9999.0::DOUBLE,
|
||||
4999.0::DOUBLE,
|
||||
60.0::DOUBLE,
|
||||
DATE '2024-12-31',
|
||||
'USD'::VARCHAR,
|
||||
9999.0::DOUBLE,
|
||||
999.0::DOUBLE,
|
||||
999.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
102::INTEGER,
|
||||
TIMESTAMPTZ '2025-02-14 12:00:00.000000+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2025-03-31',
|
||||
'Q1'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2025-02-14 12:00:00.000000+00',
|
||||
1111.0::DOUBLE,
|
||||
111.0::DOUBLE,
|
||||
111.0::DOUBLE,
|
||||
11111.0::DOUBLE,
|
||||
5555.0::DOUBLE,
|
||||
60.0::DOUBLE,
|
||||
DATE '2025-03-31',
|
||||
'USD'::VARCHAR,
|
||||
11111.0::DOUBLE,
|
||||
1111.0::DOUBLE,
|
||||
1111.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
),
|
||||
(
|
||||
103::INTEGER,
|
||||
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
|
||||
'filing_date'::VARCHAR,
|
||||
FALSE::BOOLEAN,
|
||||
DATE '2024-12-31',
|
||||
'Q4'::VARCHAR,
|
||||
'USD'::VARCHAR,
|
||||
TIMESTAMPTZ '2025-02-13 00:00:00.000000+00',
|
||||
777.0::DOUBLE,
|
||||
77.0::DOUBLE,
|
||||
77.0::DOUBLE,
|
||||
7777.0::DOUBLE,
|
||||
3333.0::DOUBLE,
|
||||
40.0::DOUBLE,
|
||||
DATE '2024-12-31',
|
||||
'USD'::VARCHAR,
|
||||
7777.0::DOUBLE,
|
||||
777.0::DOUBLE,
|
||||
777.0::DOUBLE,
|
||||
FALSE::BOOLEAN
|
||||
)
|
||||
) 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(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
|
||||
const opened = await openDuckDbMarketDataStore({
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
env: {
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// 1. Before S1: no row for listing 101
|
||||
const beforeS1 = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [101],
|
||||
fields: ['revenue', 'ttm_revenue'],
|
||||
asOf: '2024-04-30T23:59:59Z',
|
||||
});
|
||||
expect(beforeS1.rows).toEqual([]);
|
||||
|
||||
// 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380)
|
||||
const betweenS1S2 = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [101],
|
||||
fields: ['revenue', 'ttm_revenue'],
|
||||
asOf: '2024-06-15',
|
||||
});
|
||||
expect(betweenS1S2.rows).toHaveLength(1);
|
||||
expect(betweenS1S2.rows[0]).toEqual({
|
||||
listing_id: 101,
|
||||
effective_known_at: s1KnownMs,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-03-31',
|
||||
fiscal_period: 'Q1',
|
||||
currency: 'USD',
|
||||
period_known_at: s1KnownMs,
|
||||
revenue: 100,
|
||||
ttm_revenue: 380,
|
||||
ttm_period_end: '2024-03-31',
|
||||
ttm_currency: 'USD',
|
||||
ttm_has_estimated_lag: false,
|
||||
});
|
||||
|
||||
// 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420)
|
||||
const betweenS2S3 = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [101],
|
||||
fields: ['revenue', 'ttm_revenue'],
|
||||
asOf: '2024-08-15',
|
||||
});
|
||||
expect(betweenS2S3.rows).toHaveLength(1);
|
||||
expect(betweenS2S3.rows[0]).toEqual({
|
||||
listing_id: 101,
|
||||
effective_known_at: s2KnownMs,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'USD',
|
||||
period_known_at: s2KnownMs,
|
||||
revenue: 120,
|
||||
ttm_revenue: 420,
|
||||
ttm_period_end: '2024-06-30',
|
||||
ttm_currency: 'USD',
|
||||
ttm_has_estimated_lag: false,
|
||||
});
|
||||
|
||||
// 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415
|
||||
for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) {
|
||||
const afterS3 = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [101],
|
||||
fields: ['revenue', 'ttm_revenue'],
|
||||
asOf,
|
||||
});
|
||||
expect(afterS3.rows).toHaveLength(1);
|
||||
expect(afterS3.rows[0]).toEqual({
|
||||
listing_id: 101,
|
||||
effective_known_at: s3KnownMs,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'USD',
|
||||
period_known_at: s2KnownMs,
|
||||
revenue: 120,
|
||||
ttm_revenue: 415,
|
||||
ttm_period_end: '2024-06-30',
|
||||
ttm_currency: 'USD',
|
||||
ttm_has_estimated_lag: false,
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns
|
||||
const multiYear = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [101, 50],
|
||||
fields: ['revenue'],
|
||||
asOf: '2024-10-01',
|
||||
});
|
||||
expect(multiYear.columns).toEqual([
|
||||
'listing_id',
|
||||
'effective_known_at',
|
||||
'known_at_source',
|
||||
'has_estimated_lag',
|
||||
'period_end',
|
||||
'fiscal_period',
|
||||
'currency',
|
||||
'period_known_at',
|
||||
'revenue',
|
||||
]);
|
||||
expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]);
|
||||
expect(multiYear.rows[0]!.period_end).toBe('2023-09-30');
|
||||
expect(multiYear.rows[0]!.revenue).toBe(80);
|
||||
expect(multiYear.rows[1]!.revenue).toBe(120);
|
||||
|
||||
// 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded
|
||||
for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) {
|
||||
const fenced = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [103, 102],
|
||||
fields: ['revenue'],
|
||||
asOf,
|
||||
});
|
||||
expect(fenced.rows).toHaveLength(1);
|
||||
expect(fenced.rows[0]!.listing_id).toBe(102);
|
||||
expect(fenced.rows[0]!.revenue).toBe(210);
|
||||
expect(fenced.rows[0]!.period_end).toBe('2024-12-31');
|
||||
}
|
||||
|
||||
// 7. allowEstimatedLag default (true) vs strict (false):
|
||||
// - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row
|
||||
// - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved
|
||||
const lagAllowed = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [202, 201],
|
||||
fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'],
|
||||
asOf: '2024-09-01',
|
||||
});
|
||||
expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]);
|
||||
expect(lagAllowed.rows[0]!.revenue).toBe(60);
|
||||
expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true);
|
||||
expect(lagAllowed.rows[1]!.revenue).toBe(75);
|
||||
expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300);
|
||||
expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30);
|
||||
expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45);
|
||||
expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30');
|
||||
expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD');
|
||||
expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true);
|
||||
|
||||
const lagStrict = await opened.store.fundamentalsAsOf({
|
||||
listingIds: [202, 201],
|
||||
fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'],
|
||||
asOf: '2024-09-01',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(lagStrict.rows).toHaveLength(1);
|
||||
expect(lagStrict.rows[0]).toEqual({
|
||||
listing_id: 202,
|
||||
effective_known_at: s2KnownMs,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'CAD',
|
||||
period_known_at: s2KnownMs,
|
||||
revenue: 75,
|
||||
ttm_revenue: null,
|
||||
ttm_net_income: null,
|
||||
ttm_operating_cash_flow: null,
|
||||
ttm_period_end: null,
|
||||
ttm_currency: null,
|
||||
ttm_has_estimated_lag: true,
|
||||
});
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -85,9 +85,10 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st
|
|||
- **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('<adjPath>')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`).
|
||||
- **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`.
|
||||
- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`.
|
||||
- **`planFundamentalsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` point-in-time query over `<curatedRoot>/fundamentals_pit/year=*/part.parquet` (`hive_partitioning = true`) selecting at most one latest snapshot (`effective_known_at <= asOf`, clamped strictly below `vaultCutoffTs`) per requested `listing_id` across allow-listed `FUNDAMENTALS_PIT_VALUE_FIELDS`, with `allowEstimatedLag` (default `true`) failing closed on snapshot-level `has_estimated_lag` without fallback and masking `ttm_*` values/date/currency when `ttm_has_estimated_lag` is `true`.
|
||||
- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `<curatedRoot>/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`.
|
||||
- **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`).
|
||||
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `<curatedRoot>/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls.
|
||||
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `<curatedRoot>/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls.
|
||||
|
||||
### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@
|
|||
* - `<curatedRoot>/events/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||
* - `<curatedRoot>/shorts/part.parquet`
|
||||
* - `<curatedRoot>/fx_1d/part.parquet`
|
||||
* - `<curatedRoot>/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`)
|
||||
*
|
||||
* `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`):
|
||||
* - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share
|
||||
|
|
@ -74,6 +75,7 @@ import {
|
|||
type Table,
|
||||
type TableCell,
|
||||
type TableRow,
|
||||
VaultHoldoutFenceError,
|
||||
applyVaultFence,
|
||||
resolveDuckDbConnectionBudget,
|
||||
} from './market-data-store';
|
||||
|
|
@ -155,7 +157,29 @@ export const FX_1D_COLUMNS = [
|
|||
'known_at',
|
||||
] as const;
|
||||
|
||||
type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string';
|
||||
export const FUNDAMENTALS_PIT_VALUE_FIELDS = [
|
||||
'revenue',
|
||||
'net_income',
|
||||
'operating_cash_flow',
|
||||
'total_assets',
|
||||
'total_equity',
|
||||
'shares_outstanding',
|
||||
'ttm_revenue',
|
||||
'ttm_net_income',
|
||||
'ttm_operating_cash_flow',
|
||||
] as const;
|
||||
export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number];
|
||||
|
||||
const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap<string, FundamentalsPitValueField> = new Map(
|
||||
FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field])
|
||||
);
|
||||
const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet<FundamentalsPitValueField> = new Set([
|
||||
'ttm_revenue',
|
||||
'ttm_net_income',
|
||||
'ttm_operating_cash_flow',
|
||||
]);
|
||||
|
||||
type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean';
|
||||
|
||||
interface TableColumnSpec {
|
||||
readonly name: string;
|
||||
|
|
@ -195,6 +219,23 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [
|
|||
{ name: 'known_at', kind: 'safe_int', nullable: false },
|
||||
];
|
||||
|
||||
const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [
|
||||
{ name: 'listing_id', kind: 'int32', nullable: false },
|
||||
{ name: 'effective_known_at', kind: 'safe_int', nullable: false },
|
||||
{ name: 'known_at_source', kind: 'string', nullable: false },
|
||||
{ name: 'has_estimated_lag', kind: 'boolean', nullable: false },
|
||||
{ name: 'period_end', kind: 'string', nullable: false },
|
||||
{ name: 'fiscal_period', kind: 'string', nullable: false },
|
||||
{ name: 'currency', kind: 'string', nullable: false },
|
||||
{ name: 'period_known_at', kind: 'safe_int', nullable: false },
|
||||
];
|
||||
|
||||
const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [
|
||||
{ name: 'ttm_period_end', kind: 'string', nullable: true },
|
||||
{ name: 'ttm_currency', kind: 'string', nullable: true },
|
||||
{ name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true },
|
||||
];
|
||||
|
||||
/** Scalar parameter value bound separately from SQL text. */
|
||||
export type DuckDbParam = string | number | boolean | null;
|
||||
|
||||
|
|
@ -357,6 +398,7 @@ export type EventsQuery = Parameters<MarketDataStore['events']>[0];
|
|||
export type ShortsAsOfQuery = Parameters<MarketDataStore['shortsAsOf']>[0];
|
||||
export type FxQuery = Parameters<MarketDataStore['fx']>[0];
|
||||
export type UniverseQuery = Parameters<MarketDataStore['universe']>[0];
|
||||
export type FundamentalsAsOfQuery = Parameters<MarketDataStore['fundamentalsAsOf']>[0];
|
||||
|
||||
/**
|
||||
* Thrown when a `MarketDataStore` method or timeframe is outside the curated
|
||||
|
|
@ -577,6 +619,50 @@ function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKi
|
|||
return normalized;
|
||||
}
|
||||
|
||||
function validateFundamentalsFields(
|
||||
raw: readonly string[],
|
||||
field = 'fields'
|
||||
): FundamentalsPitValueField[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected a non-empty array of fundamentals value fields for "${field}".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<FundamentalsPitValueField>();
|
||||
const normalized: FundamentalsPitValueField[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const name: unknown = raw[i];
|
||||
const canonical =
|
||||
typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined;
|
||||
if (canonical === undefined) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
if (!seen.has(canonical)) {
|
||||
seen.add(canonical);
|
||||
normalized.push(canonical);
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function validateAllowEstimatedLag(raw: unknown): boolean {
|
||||
if (raw === undefined) {
|
||||
return true;
|
||||
}
|
||||
if (typeof raw !== 'boolean') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`,
|
||||
'allowEstimatedLag'
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] {
|
||||
if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
|
|
@ -1575,6 +1661,158 @@ export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): Pla
|
|||
};
|
||||
}
|
||||
|
||||
interface PlannedFundamentalsAsOfInternal {
|
||||
readonly planned: PlannedDuckDbQuery;
|
||||
readonly columns: readonly string[];
|
||||
readonly schema: readonly TableColumnSpec[];
|
||||
}
|
||||
|
||||
function planFundamentalsAsOfInternal(
|
||||
q: FundamentalsAsOfQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedFundamentalsAsOfInternal {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a fundamentalsAsOf query object.',
|
||||
'query'
|
||||
);
|
||||
}
|
||||
|
||||
const listingIds = validateListingIds(q.listingIds);
|
||||
const fields = validateFundamentalsFields(q.fields);
|
||||
const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag);
|
||||
|
||||
let fenced: FencedTimeRange;
|
||||
try {
|
||||
fenced = applyVaultFence(
|
||||
{
|
||||
from: q.asOf,
|
||||
to: q.asOf,
|
||||
asOf: q.asOf,
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof VaultHoldoutFenceError) {
|
||||
const maxAllowedMs = ctx.vaultCutoffTs - 1;
|
||||
fenced = {
|
||||
fromMs: maxAllowedMs,
|
||||
toMs: maxAllowedMs,
|
||||
asOfMs: maxAllowedMs,
|
||||
scope: 'vault_fenced',
|
||||
clampedTo: true,
|
||||
clampedAsOf: true,
|
||||
};
|
||||
} else if (
|
||||
err instanceof MarketDataStoreValidationError &&
|
||||
(err.field === 'from' || err.field === 'to')
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(err.message, 'asOf');
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced);
|
||||
const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs);
|
||||
const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet');
|
||||
const listingPlaceholders = buildPlaceholders(listingIds.length);
|
||||
|
||||
let hasTtmField = false;
|
||||
for (const field of fields) {
|
||||
if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) {
|
||||
hasTtmField = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const innerCols: string[] = [
|
||||
'f.listing_id',
|
||||
'f.effective_known_at',
|
||||
'f.known_at_source',
|
||||
'f.has_estimated_lag',
|
||||
'f.period_end',
|
||||
'f.fiscal_period',
|
||||
'f.currency',
|
||||
'f.period_known_at',
|
||||
];
|
||||
const outerCols: string[] = [
|
||||
's.listing_id',
|
||||
'epoch_ms(s.effective_known_at) AS effective_known_at',
|
||||
's.known_at_source',
|
||||
's.has_estimated_lag',
|
||||
'CAST(s.period_end AS VARCHAR) AS period_end',
|
||||
's.fiscal_period',
|
||||
's.currency',
|
||||
'epoch_ms(s.period_known_at) AS period_known_at',
|
||||
];
|
||||
const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA];
|
||||
|
||||
for (const field of fields) {
|
||||
innerCols.push(`f.${field}`);
|
||||
if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) {
|
||||
outerCols.push(
|
||||
`CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}`
|
||||
);
|
||||
} else {
|
||||
outerCols.push(`s.${field}`);
|
||||
}
|
||||
schema.push({ name: field, kind: 'number', nullable: true });
|
||||
}
|
||||
|
||||
if (hasTtmField) {
|
||||
innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag');
|
||||
outerCols.push(
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end',
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency',
|
||||
's.ttm_has_estimated_lag'
|
||||
);
|
||||
schema.push(...FUNDAMENTALS_TTM_META_SCHEMA);
|
||||
}
|
||||
|
||||
const columns = schema.map(spec => spec.name);
|
||||
const sql =
|
||||
`WITH latest AS (SELECT ${innerCols.join(', ')} ` +
|
||||
'FROM read_parquet(?, hive_partitioning = true) AS f ' +
|
||||
`WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` +
|
||||
'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' +
|
||||
`SELECT ${outerCols.join(', ')} ` +
|
||||
'FROM latest AS s ' +
|
||||
'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' +
|
||||
'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' +
|
||||
'ORDER BY s.listing_id ASC';
|
||||
const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag];
|
||||
|
||||
return {
|
||||
planned: { sql, params, fenced },
|
||||
columns,
|
||||
schema,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a Vault-fenced point-in-time DuckDB SQL query over curated
|
||||
* `fundamentals_pit/year=*\/part.parquet` snapshots.
|
||||
*
|
||||
* Selects at most one snapshot per requested `listing_id` — the latest with
|
||||
* `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When
|
||||
* `allowEstimatedLag` is `false`, listings whose selected snapshot has
|
||||
* `has_estimated_lag = true` are omitted without falling back to an older
|
||||
* snapshot, and requested `ttm_*` value fields plus `ttm_period_end` /
|
||||
* `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true`
|
||||
* while preserving `ttm_has_estimated_lag`.
|
||||
*/
|
||||
export function planFundamentalsAsOfQuery(
|
||||
q: FundamentalsAsOfQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedDuckDbQuery {
|
||||
return planFundamentalsAsOfInternal(q, ctx).planned;
|
||||
}
|
||||
|
||||
function readRequiredInt32(row: Record<string, unknown>, key: string, rowIndex: number): number {
|
||||
const val = row[key];
|
||||
if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) {
|
||||
|
|
@ -1712,6 +1950,14 @@ function readValidatedTableCell(
|
|||
);
|
||||
}
|
||||
return val;
|
||||
case 'boolean':
|
||||
if (typeof val !== 'boolean') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`,
|
||||
spec.name
|
||||
);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2038,8 +2284,11 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return Promise.reject(new MarketDataStoreNotImplementedError('crossSection'));
|
||||
},
|
||||
|
||||
fundamentalsAsOf(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf'));
|
||||
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
||||
const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(columns, schema, rawRows);
|
||||
},
|
||||
|
||||
macroAsOf(): Promise<Table> {
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
type DuckDbPlanContext,
|
||||
EVENT_KINDS,
|
||||
EVENTS_COLUMNS,
|
||||
FUNDAMENTALS_PIT_VALUE_FIELDS,
|
||||
FX_1D_COLUMNS,
|
||||
FX_PAIR_MAP,
|
||||
MarketDataStoreNotImplementedError,
|
||||
|
|
@ -28,6 +29,7 @@ import {
|
|||
planAdjFactorsMetadataQuery,
|
||||
planBars1dQuery,
|
||||
planEventsQuery,
|
||||
planFundamentalsAsOfQuery,
|
||||
planFx1dQuery,
|
||||
planShortsAsOfQuery,
|
||||
planUniverseQuery,
|
||||
|
|
@ -44,6 +46,7 @@ import {
|
|||
DEFAULT_UNIVERSE_LOOKBACK_DAYS as subpathDefaultUniverseLookbackDays,
|
||||
EVENT_KINDS as subpathEventKinds,
|
||||
EVENTS_COLUMNS as subpathEventsColumns,
|
||||
FUNDAMENTALS_PIT_VALUE_FIELDS as subpathFundamentalsPitValueFields,
|
||||
FX_1D_COLUMNS as subpathFx1dColumns,
|
||||
FX_PAIR_MAP as subpathFxPairMap,
|
||||
MarketDataStoreNotImplementedError as SubpathNotImplementedError,
|
||||
|
|
@ -54,6 +57,7 @@ import {
|
|||
planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery,
|
||||
planBars1dQuery as subpathPlanBars1dQuery,
|
||||
planEventsQuery as subpathPlanEventsQuery,
|
||||
planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery,
|
||||
planFx1dQuery as subpathPlanFx1dQuery,
|
||||
planShortsAsOfQuery as subpathPlanShortsAsOfQuery,
|
||||
planUniverseQuery as subpathPlanUniverseQuery,
|
||||
|
|
@ -215,6 +219,8 @@ describe('market-data-store-duckdb exports', () => {
|
|||
expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery);
|
||||
expect(planFx1dQuery).toBe(subpathPlanFx1dQuery);
|
||||
expect(planUniverseQuery).toBe(subpathPlanUniverseQuery);
|
||||
expect(planFundamentalsAsOfQuery).toBe(subpathPlanFundamentalsAsOfQuery);
|
||||
expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toBe(subpathFundamentalsPitValueFields);
|
||||
expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery);
|
||||
expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata);
|
||||
expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore);
|
||||
|
|
@ -2421,15 +2427,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => {
|
|||
universe: 'US_EQ',
|
||||
}),
|
||||
},
|
||||
{
|
||||
method: 'fundamentalsAsOf',
|
||||
run: () =>
|
||||
store.fundamentalsAsOf({
|
||||
listingIds: [1],
|
||||
fields: ['revenue'],
|
||||
asOf: '2025-01-15',
|
||||
}),
|
||||
},
|
||||
{
|
||||
method: 'macroAsOf',
|
||||
run: () =>
|
||||
|
|
@ -2868,3 +2865,358 @@ describe('planUniverseQuery & createDuckDbMarketDataStore().universe()', () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentalsAsOf()', () => {
|
||||
const EXPECTED_GLOB = `${CURATED_ROOT}/fundamentals_pit/year=*/part.parquet`;
|
||||
|
||||
it('exports the exact 9 allow-listed FUNDAMENTALS_PIT_VALUE_FIELDS and plans parameterized Hive Parquet SQL', () => {
|
||||
expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toEqual([
|
||||
'revenue',
|
||||
'net_income',
|
||||
'operating_cash_flow',
|
||||
'total_assets',
|
||||
'total_equity',
|
||||
'shares_outstanding',
|
||||
'ttm_revenue',
|
||||
'ttm_net_income',
|
||||
'ttm_operating_cash_flow',
|
||||
]);
|
||||
|
||||
const nonTtm = planFundamentalsAsOfQuery(
|
||||
{
|
||||
listingIds: [202, 101, 202],
|
||||
fields: ['net_income', 'revenue', 'net_income'],
|
||||
asOf: '2025-06-15',
|
||||
},
|
||||
DEFAULT_CTX
|
||||
);
|
||||
|
||||
expect(nonTtm.sql).toBe(
|
||||
'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.net_income, f.revenue ' +
|
||||
'FROM read_parquet(?, hive_partitioning = true) AS f ' +
|
||||
'WHERE f.listing_id IN (?, ?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' +
|
||||
'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' +
|
||||
'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.net_income, s.revenue ' +
|
||||
'FROM latest AS s ' +
|
||||
'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' +
|
||||
'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' +
|
||||
'ORDER BY s.listing_id ASC'
|
||||
);
|
||||
expect(nonTtm.params).toEqual([
|
||||
EXPECTED_GLOB,
|
||||
202,
|
||||
101,
|
||||
'2025-06-15T23:59:59.999999Z',
|
||||
true,
|
||||
]);
|
||||
expect(nonTtm.fenced).toEqual({
|
||||
fromMs: Date.UTC(2025, 5, 15, 0, 0, 0, 0),
|
||||
toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999),
|
||||
asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999),
|
||||
scope: 'vault_fenced',
|
||||
clampedTo: false,
|
||||
clampedAsOf: false,
|
||||
});
|
||||
expect(nonTtm.sql).not.toContain(CURATED_ROOT);
|
||||
expect(nonTtm.sql).not.toContain('2025-06-15');
|
||||
expect(nonTtm.sql).not.toContain('ttm_period_end');
|
||||
expect(nonTtm.sql).not.toContain('ttm_currency');
|
||||
expect(nonTtm.sql).not.toContain('ttm_has_estimated_lag');
|
||||
|
||||
const withTtm = planFundamentalsAsOfQuery(
|
||||
{
|
||||
listingIds: [101],
|
||||
fields: ['revenue', 'ttm_revenue', 'ttm_operating_cash_flow', 'revenue', 'ttm_revenue'],
|
||||
asOf: '2025-06-15T14:30:00.123456+02:00',
|
||||
allowEstimatedLag: false,
|
||||
},
|
||||
DEFAULT_CTX
|
||||
);
|
||||
|
||||
expect(withTtm.sql).toBe(
|
||||
'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.revenue, f.ttm_revenue, f.ttm_operating_cash_flow, f.ttm_period_end, f.ttm_currency, f.ttm_has_estimated_lag ' +
|
||||
'FROM read_parquet(?, hive_partitioning = true) AS f ' +
|
||||
'WHERE f.listing_id IN (?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' +
|
||||
'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' +
|
||||
'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.revenue, ' +
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_revenue ELSE NULL END AS ttm_revenue, ' +
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_operating_cash_flow ELSE NULL END AS ttm_operating_cash_flow, ' +
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end, ' +
|
||||
'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency, ' +
|
||||
's.ttm_has_estimated_lag ' +
|
||||
'FROM latest AS s ' +
|
||||
'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' +
|
||||
'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' +
|
||||
'ORDER BY s.listing_id ASC'
|
||||
);
|
||||
expect(withTtm.params).toEqual([
|
||||
EXPECTED_GLOB,
|
||||
101,
|
||||
'2025-06-15T12:30:00.123456Z',
|
||||
false,
|
||||
]);
|
||||
expect(withTtm.fenced.asOfMs).toBe(Date.UTC(2025, 5, 15, 12, 30, 0, 123));
|
||||
expect(withTtm.fenced.clampedAsOf).toBe(false);
|
||||
});
|
||||
|
||||
it('clamps asOf at or after vaultCutoffTs to vaultCutoffTs * 1000 - 1 micros even when vaultOperatorAuthorized is true', () => {
|
||||
const authorizedCtx: DuckDbPlanContext = {
|
||||
...DEFAULT_CTX,
|
||||
vaultOperatorAuthorized: true,
|
||||
};
|
||||
|
||||
for (const clampedAsOf of [
|
||||
'2026-05-28',
|
||||
'2026-05-28T00:00:00.000Z',
|
||||
'2026-05-28T00:00:00.000001Z',
|
||||
'2026-09-01T15:00:00Z',
|
||||
]) {
|
||||
const planned = planFundamentalsAsOfQuery(
|
||||
{ listingIds: [1], fields: ['revenue'], asOf: clampedAsOf },
|
||||
authorizedCtx
|
||||
);
|
||||
expect(planned.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]);
|
||||
expect(planned.fenced).toEqual({
|
||||
fromMs: CUTOFF_MS - 1,
|
||||
toMs: CUTOFF_MS - 1,
|
||||
asOfMs: CUTOFF_MS - 1,
|
||||
scope: 'vault_fenced',
|
||||
clampedTo: true,
|
||||
clampedAsOf: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Mid-day cutoff with a date-only asOf on the cutoff date clamps cleanly to 1 microsecond before cutoff.
|
||||
const midDayCutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0);
|
||||
const midDayClamped = planFundamentalsAsOfQuery(
|
||||
{ listingIds: [1], fields: ['revenue'], asOf: '2026-05-28' },
|
||||
{ curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs }
|
||||
);
|
||||
expect(midDayClamped.params).toEqual([EXPECTED_GLOB, 1, '2026-05-28T11:59:59.999999Z', true]);
|
||||
expect(midDayClamped.fenced.clampedAsOf).toBe(true);
|
||||
expect(midDayClamped.fenced.clampedTo).toBe(true);
|
||||
expect(midDayClamped.fenced.asOfMs).toBe(midDayCutoffMs - 1);
|
||||
|
||||
// One microsecond before cutoff stays unclamped and preserves exact micros.
|
||||
const preCutoffMicros = planFundamentalsAsOfQuery(
|
||||
{ listingIds: [1], fields: ['revenue'], asOf: MAX_ALLOWED_ISO_MICROS },
|
||||
DEFAULT_CTX
|
||||
);
|
||||
expect(preCutoffMicros.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]);
|
||||
expect(preCutoffMicros.fenced.clampedAsOf).toBe(false);
|
||||
});
|
||||
|
||||
it('validates fields allow-list, allowEstimatedLag, listingIds, and asOf with zero executor calls on invalid input', async () => {
|
||||
const fake = createRecordingExecutor();
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
|
||||
const invalidFieldsCases: unknown[] = [
|
||||
[],
|
||||
'revenue',
|
||||
null,
|
||||
undefined,
|
||||
['unknown_field'],
|
||||
['revenue', 'period_end'],
|
||||
['toString'],
|
||||
['revenue; DROP TABLE x'],
|
||||
[123],
|
||||
];
|
||||
for (const badFields of invalidFieldsCases) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await store.fundamentalsAsOf({
|
||||
listingIds: [1],
|
||||
fields: badFields as string[],
|
||||
asOf: '2025-06-15',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect((caught as MarketDataStoreValidationError).field).toBe('fields');
|
||||
}
|
||||
|
||||
const invalidLagCases: unknown[] = [null, 1, 0, 'true', 'false', {}];
|
||||
for (const badLag of invalidLagCases) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await store.fundamentalsAsOf({
|
||||
listingIds: [1],
|
||||
fields: ['revenue'],
|
||||
asOf: '2025-06-15',
|
||||
allowEstimatedLag: badLag as boolean,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect((caught as MarketDataStoreValidationError).field).toBe('allowEstimatedLag');
|
||||
}
|
||||
|
||||
const invalidAsOfCases: unknown[] = ['', 'not-a-date', '2024-02-30', '2025-06-15T12:00:00', null, undefined];
|
||||
for (const badAsOf of invalidAsOfCases) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await store.fundamentalsAsOf({
|
||||
listingIds: [1],
|
||||
fields: ['revenue'],
|
||||
asOf: badAsOf as string,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect((caught as MarketDataStoreValidationError).field).toBe('asOf');
|
||||
}
|
||||
|
||||
await expect(
|
||||
store.fundamentalsAsOf({ listingIds: [], fields: ['revenue'], asOf: '2025-06-15' })
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
await expect(
|
||||
store.fundamentalsAsOf(null as unknown as Parameters<typeof store.fundamentalsAsOf>[0])
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('initializes DuckDB budget once and maps fundamentalsAsOf columns in exact projection order with strict scalar validation', async () => {
|
||||
const t1 = Date.UTC(2024, 7, 1, 20, 0, 0, 0);
|
||||
const t2 = Date.UTC(2024, 7, 15, 20, 0, 0, 0);
|
||||
let callIndex = 0;
|
||||
const fake = createRecordingExecutor({
|
||||
onQuery: () => {
|
||||
callIndex += 1;
|
||||
if (callIndex === 1) {
|
||||
return [
|
||||
{
|
||||
listing_id: 101,
|
||||
effective_known_at: t1,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'USD',
|
||||
period_known_at: t1,
|
||||
total_assets: null,
|
||||
revenue: 120.5,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [
|
||||
{
|
||||
listing_id: 101,
|
||||
effective_known_at: t2,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'USD',
|
||||
period_known_at: t1,
|
||||
revenue: 120.5,
|
||||
ttm_revenue: 450.25,
|
||||
ttm_period_end: '2024-06-30',
|
||||
ttm_currency: 'USD',
|
||||
ttm_has_estimated_lag: false,
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
const expectedBudget = resolveDuckDbConnectionBudget().statements;
|
||||
|
||||
const first = await store.fundamentalsAsOf({
|
||||
listingIds: [101],
|
||||
fields: ['total_assets', 'revenue', 'total_assets'],
|
||||
asOf: '2024-08-05',
|
||||
});
|
||||
expect(first.columns).toEqual([
|
||||
'listing_id',
|
||||
'effective_known_at',
|
||||
'known_at_source',
|
||||
'has_estimated_lag',
|
||||
'period_end',
|
||||
'fiscal_period',
|
||||
'currency',
|
||||
'period_known_at',
|
||||
'total_assets',
|
||||
'revenue',
|
||||
]);
|
||||
expect(first.rows).toEqual([
|
||||
{
|
||||
listing_id: 101,
|
||||
effective_known_at: t1,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: false,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'USD',
|
||||
period_known_at: t1,
|
||||
total_assets: null,
|
||||
revenue: 120.5,
|
||||
},
|
||||
]);
|
||||
expect(fake.runCalls).toEqual(expectedBudget);
|
||||
|
||||
const second = await store.fundamentalsAsOf({
|
||||
listingIds: [101],
|
||||
fields: ['revenue', 'ttm_revenue'],
|
||||
asOf: '2024-08-20',
|
||||
allowEstimatedLag: false,
|
||||
});
|
||||
expect(second.columns).toEqual([
|
||||
'listing_id',
|
||||
'effective_known_at',
|
||||
'known_at_source',
|
||||
'has_estimated_lag',
|
||||
'period_end',
|
||||
'fiscal_period',
|
||||
'currency',
|
||||
'period_known_at',
|
||||
'revenue',
|
||||
'ttm_revenue',
|
||||
'ttm_period_end',
|
||||
'ttm_currency',
|
||||
'ttm_has_estimated_lag',
|
||||
]);
|
||||
expect(second.rows).toHaveLength(1);
|
||||
expect(second.rows[0]?.ttm_revenue).toBe(450.25);
|
||||
expect(second.rows[0]?.ttm_has_estimated_lag).toBe(false);
|
||||
// Budget SET statements must not re-run on second query.
|
||||
expect(fake.runCalls).toHaveLength(3);
|
||||
expect(fake.queryCalls).toHaveLength(2);
|
||||
|
||||
// Rejects non-boolean has_estimated_lag from a misbehaving executor.
|
||||
const badBoolFake = createRecordingExecutor({
|
||||
onQuery: () => [
|
||||
{
|
||||
listing_id: 101,
|
||||
effective_known_at: t1,
|
||||
known_at_source: 'filing_date',
|
||||
has_estimated_lag: 'false' as unknown as boolean,
|
||||
period_end: '2024-06-30',
|
||||
fiscal_period: 'Q2',
|
||||
currency: 'USD',
|
||||
period_known_at: t1,
|
||||
revenue: 120.5,
|
||||
},
|
||||
],
|
||||
});
|
||||
const badStore = createDuckDbMarketDataStore({
|
||||
executor: badBoolFake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
await expect(
|
||||
badStore.fundamentalsAsOf({ listingIds: [101], fields: ['revenue'], asOf: '2024-08-05' })
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue