T-119: M1.3e — @stock-bot/research: DuckDB SQL planner + injected-executor MarketDataStore adapter for curated daily Parquet (bars 1d, events, shortsAsOf, fx 1d) with mandatory Vault / known_at predicates, tests and local benchmark (no new dependencies)
This commit is contained in:
parent
57b398694f
commit
1d4717c48e
4 changed files with 1718 additions and 152 deletions
|
|
@ -81,31 +81,33 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st
|
|||
|
||||
### API
|
||||
|
||||
- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`.
|
||||
- **`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`.
|
||||
- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and ISO-8601 `known_at <= ?`.
|
||||
- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs - 1`) over `<curatedRoot>/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`.
|
||||
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, 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), maps validated rows into `BarBatch` / `Table`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`, `universe`) with `MarketDataStoreNotImplementedError` and zero executor calls.
|
||||
- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`. For `'split'` and `'total'`, requires a verified `point_in_time_fenced` `ctx.adjFactorsSnapshot` matching the query's effective `asOf` and Vault fence, and binds `read_parquet(...)` directly to `ctx.adjFactorsSnapshot.path`.
|
||||
- **`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 <= ?`.
|
||||
- **`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`.
|
||||
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, adjFactorsPath?, 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), verifies `parquet_kv_metadata` on the exact `adj_factors` file before every `'split'` / `'total'` `bars` query, validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`, `universe`) with `MarketDataStoreNotImplementedError` and zero executor calls.
|
||||
|
||||
### Mandatory Vault, PIT & Boundary Validation Rules
|
||||
### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules
|
||||
|
||||
- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp to `vaultCutoffTs - 1`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`).
|
||||
- `curatedRoot` is the only value embedded in SQL text and must be an absolute POSIX path free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`).
|
||||
- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp strictly below `vaultCutoffTs`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`).
|
||||
- **Microsecond upper-bound precision:** Curated Parquet `ts` and `known_at` columns store UTC microseconds (`curate_fx_1d` stamps `23:59:59.999999Z`). Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped Vault upper bounds expand to the last included Parquet microsecond (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day bounds preserve their caller-specified precision. Under `'vault_fenced'`, every planned upper bound remains strictly `< vaultCutoffTs`.
|
||||
- `curatedRoot` (and optional `adjFactorsPath`) are the only values embedded in SQL text and must be absolute POSIX paths free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`).
|
||||
- All caller values (`listingIds` as `INT32` safe integers, allow-listed `kinds`, `'USD.CAD' -> 'USDCAD'`, and UTC date/timestamp bounds) are validated upfront and passed strictly as bound `?` parameters.
|
||||
|
||||
### `bars` 1d Adjustment Formulas & `asOf` Anchoring Caveat
|
||||
### `bars` 1d Adjustment Formulas & Verified Fenced `adj_factors` Requirement
|
||||
|
||||
`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. For `'split'` and `'total'`, `bars_1d` is joined via `ASOF LEFT JOIN` against `<curatedRoot>/adj_factors/part.parquet` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`):
|
||||
`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. Because `adj_factors` stores right-to-left cumulative suffix products (`cum_split_factor`, `cum_total_factor`), slicing a retrospective `adj_factors` file with `known_at <= asOf` would still embed future or held-out Vault splits/dividends into earlier cumulative factors.
|
||||
|
||||
- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted.
|
||||
- **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
- **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
|
||||
> **Point-in-time `asOf` anchoring caveat:** `tools/curate-etl` writes full-horizon curation-time suffix products into `cum_split_factor` and `cum_total_factor`. Filtering `adj_factors` by `known_at <= asOf` excludes post-`asOf` corporate-action rows (so bars on/after the last visible `ex_date` fall back to `1.0`), while earlier surviving rows still carry the curation-time suffix product (introducing a scale jump across the last visible `ex_date` if an excluded future split or dividend exists). Full historical re-anchoring to `asOf` requires a separate `curate-etl` schema/query enhancement.
|
||||
- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted (`adj_factors` is not read).
|
||||
- **`'split'` / `'total'`**: Require a verified `point_in_time_fenced` `adj_factors` Parquet artifact (published by `curate_and_write_adj_factors_as_of` with `stock_bot.adj_factors.*` footer metadata) whose effective inclusive microsecond fence matches the query's effective `asOf` and Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected with `AdjFactorsSnapshotError` before any `bars` query runs, and `read_parquet(...)` is bound directly to the verified file path.
|
||||
- Against the verified `adj_factors` file, `bars_1d` is joined via `ASOF LEFT JOIN` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`):
|
||||
- **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
- **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
|
||||
### Local Query-Planner Benchmark
|
||||
|
||||
Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d with no database dependency:
|
||||
Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d with no database dependency (full SQL text and ordered parameter values are verified against the pinned checksum outside the timed section):
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 178.15 ms`, `queriesPerSec = 673,600 queries/s` (`120,000` queries, `758,061` bound params, deterministic checksum `0d85763b`)
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 218.55 ms`, `queriesPerSec = 549,073 queries/s` (`120,000` queries, `758,061` bound params, pinned checksum `8606c98c`)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import {
|
||||
type AdjFactorsSnapshotMetadata,
|
||||
BARS_ADJUSTMENTS,
|
||||
type BarsQuery,
|
||||
type DuckDbParam,
|
||||
type DuckDbPlanContext,
|
||||
EVENT_KINDS,
|
||||
type EventsQuery,
|
||||
|
|
@ -12,13 +14,17 @@ import {
|
|||
planFx1dQuery,
|
||||
planShortsAsOfQuery,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import { applyVaultFence } from '../src/market-data-store';
|
||||
|
||||
const SEED = 20261129;
|
||||
const QUERY_COUNT = 120_000;
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`;
|
||||
const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0);
|
||||
const VAULT_CUTOFF_MICROS = VAULT_CUTOFF_TS * 1000;
|
||||
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
const CTX: DuckDbPlanContext = {
|
||||
const BASE_CTX: DuckDbPlanContext = {
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
};
|
||||
|
|
@ -34,7 +40,7 @@ function createMulberry32(seed: number): () => number {
|
|||
}
|
||||
|
||||
type WorkloadItem =
|
||||
| { readonly kind: 'bars'; readonly q: BarsQuery }
|
||||
| { readonly kind: 'bars'; readonly q: BarsQuery; readonly ctx: DuckDbPlanContext }
|
||||
| { readonly kind: 'events'; readonly q: EventsQuery }
|
||||
| { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery }
|
||||
| { readonly kind: 'fx'; readonly q: FxQuery };
|
||||
|
|
@ -58,6 +64,30 @@ function randomListingIds(): number[] {
|
|||
return ids;
|
||||
}
|
||||
|
||||
function buildVerifiedSnapshotForBarsQuery(
|
||||
from: string,
|
||||
to: string,
|
||||
asOf: string | undefined
|
||||
): AdjFactorsSnapshotMetadata {
|
||||
const fenced = applyVaultFence(
|
||||
{ from, to, asOf, scope: 'vault_fenced' },
|
||||
{ vaultCutoffTs: VAULT_CUTOFF_TS }
|
||||
);
|
||||
const subMs = fenced.clampedAsOf || asOf === undefined || DATE_ONLY_RE.test(asOf) ? 999 : 0;
|
||||
const effectiveAsOfMicros = fenced.asOfMs * 1000 + subMs;
|
||||
return {
|
||||
path: ADJ_PATH,
|
||||
formatVersion: 1,
|
||||
snapshotKind: 'point_in_time_fenced',
|
||||
fence: {
|
||||
asOfMicros: effectiveAsOfMicros,
|
||||
vaultCutoffMicros: VAULT_CUTOFF_MICROS,
|
||||
},
|
||||
rowsWritten: 1000,
|
||||
snapshotChecksum: '0x024ec73a1afe7e6b',
|
||||
};
|
||||
}
|
||||
|
||||
const workload: WorkloadItem[] = new Array(QUERY_COUNT);
|
||||
for (let i = 0; i < QUERY_COUNT; i += 1) {
|
||||
const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs);
|
||||
|
|
@ -74,6 +104,13 @@ for (let i = 0; i < QUERY_COUNT; i += 1) {
|
|||
const slot = i % 7;
|
||||
if (slot < 3) {
|
||||
const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw';
|
||||
const ctx: DuckDbPlanContext =
|
||||
adjustment === 'raw'
|
||||
? BASE_CTX
|
||||
: {
|
||||
...BASE_CTX,
|
||||
adjFactorsSnapshot: buildVerifiedSnapshotForBarsQuery(from, to, asOf),
|
||||
};
|
||||
workload[i] = {
|
||||
kind: 'bars',
|
||||
q: {
|
||||
|
|
@ -84,6 +121,7 @@ for (let i = 0; i < QUERY_COUNT; i += 1) {
|
|||
adjustment,
|
||||
asOf,
|
||||
},
|
||||
ctx,
|
||||
};
|
||||
} else if (slot === 3 || slot === 4) {
|
||||
const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing';
|
||||
|
|
@ -121,41 +159,78 @@ for (let i = 0; i < QUERY_COUNT; i += 1) {
|
|||
}
|
||||
}
|
||||
|
||||
function mixFnv1a(hash: number, value: number): number {
|
||||
let h = (hash ^ (value >>> 0)) >>> 0;
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
function planWorkloadItem(item: WorkloadItem): PlannedDuckDbQuery {
|
||||
switch (item.kind) {
|
||||
case 'bars':
|
||||
return planBars1dQuery(item.q, item.ctx);
|
||||
case 'events':
|
||||
return planEventsQuery(item.q, BASE_CTX);
|
||||
case 'shorts':
|
||||
return planShortsAsOfQuery(item.q, BASE_CTX);
|
||||
case 'fx':
|
||||
return planFx1dQuery(item.q, BASE_CTX);
|
||||
}
|
||||
}
|
||||
|
||||
function fnv1aByte(hash: number, byte: number): number {
|
||||
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
|
||||
function fnv1aString(hash: number, str: string): number {
|
||||
let h = fnv1aByte(hash, str.length & 0xff);
|
||||
h = fnv1aByte(h, (str.length >>> 8) & 0xff);
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
const code = str.charCodeAt(i);
|
||||
h = fnv1aByte(h, code & 0xff);
|
||||
if (code > 0xff) {
|
||||
h = fnv1aByte(h, (code >>> 8) & 0xff);
|
||||
}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
let checksum = 0x811c9dc5;
|
||||
let totalParams = 0;
|
||||
function fnv1aParam(hash: number, param: DuckDbParam): number {
|
||||
if (param === null) {
|
||||
return fnv1aByte(hash, 0x00);
|
||||
}
|
||||
if (typeof param === 'string') {
|
||||
return fnv1aString(fnv1aByte(hash, 0x01), param);
|
||||
}
|
||||
if (typeof param === 'number') {
|
||||
return fnv1aString(fnv1aByte(hash, 0x02), String(param));
|
||||
}
|
||||
return fnv1aByte(fnv1aByte(hash, 0x03), param ? 1 : 0);
|
||||
}
|
||||
|
||||
// Timed section: pure query planning only (no checksum hashing overhead).
|
||||
let totalParams = 0;
|
||||
const started = performance.now();
|
||||
for (const item of workload) {
|
||||
let planned: PlannedDuckDbQuery;
|
||||
switch (item.kind) {
|
||||
case 'bars':
|
||||
planned = planBars1dQuery(item.q, CTX);
|
||||
break;
|
||||
case 'events':
|
||||
planned = planEventsQuery(item.q, CTX);
|
||||
break;
|
||||
case 'shorts':
|
||||
planned = planShortsAsOfQuery(item.q, CTX);
|
||||
break;
|
||||
case 'fx':
|
||||
planned = planFx1dQuery(item.q, CTX);
|
||||
break;
|
||||
}
|
||||
const planned = planWorkloadItem(item);
|
||||
totalParams += planned.params.length;
|
||||
checksum = mixFnv1a(checksum, planned.sql.length);
|
||||
checksum = mixFnv1a(checksum, planned.params.length);
|
||||
checksum = mixFnv1a(checksum, Math.trunc(planned.fenced.toMs / 1000));
|
||||
checksum = mixFnv1a(checksum, Math.trunc(planned.fenced.asOfMs / 1000));
|
||||
}
|
||||
const elapsedMs = performance.now() - started;
|
||||
const queriesPerSec = Math.round(QUERY_COUNT / (elapsedMs / 1000));
|
||||
|
||||
// Untimed verification pass: hash full SQL text and ordered parameter values for all queries.
|
||||
let checksum = 0x811c9dc5;
|
||||
for (const item of workload) {
|
||||
const planned = planWorkloadItem(item);
|
||||
checksum = fnv1aString(checksum, planned.sql);
|
||||
checksum = fnv1aByte(checksum, planned.params.length);
|
||||
for (const param of planned.params) {
|
||||
checksum = fnv1aParam(checksum, param);
|
||||
}
|
||||
}
|
||||
const checksumHex = checksum.toString(16).padStart(8, '0');
|
||||
|
||||
const EXPECTED_CHECKSUM = '8606c98c';
|
||||
if (checksumHex !== EXPECTED_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
|
|
@ -164,7 +239,7 @@ console.log(
|
|||
totalParams,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
queriesPerSec,
|
||||
checksum: checksum.toString(16).padStart(8, '0'),
|
||||
checksum: checksumHex,
|
||||
},
|
||||
null,
|
||||
2
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue