T-139: M2.4a — Versioned Feature Library core: declarative DuckDB SQL feature definitions + registerSignal registry + versioned Parquet batch-plan runner over an injected DuckDbExecutor in libs/research/src/feature-library.ts (pure, no new deps)
This commit is contained in:
parent
470b0a4bd9
commit
d6d6bc8c8b
7 changed files with 3200 additions and 100 deletions
|
|
@ -228,3 +228,23 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
|
||||
- SSE/HTTP transport wrapper in `apps/stock/web-api`.
|
||||
- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters.
|
||||
|
||||
## Versioned Feature Library
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/feature-library` (`libs/research/src/feature-library.ts`). The module is pure, dependency-free, and browser-safe (zero `node:*` imports, zero DuckDB driver dependency); SQL execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`).
|
||||
|
||||
### API & Immutability
|
||||
|
||||
- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:<dataset>}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared.
|
||||
- **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `<name>@v<version>` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`).
|
||||
- **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration.
|
||||
- **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `<name>@v<version>` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation.
|
||||
- **`planFeatureBatch(def, { curatedRoot, fromYear, toYear, vaultCutoffDate })`** — Validates `curatedRoot`, four-digit ordered years, and strict UTC `YYYY-MM-DD` `vaultCutoffDate` via `applyVaultFence`. Plans one yearly ZSTD Parquet write to `<curatedRoot>/features/<name>/v<version>/year=YYYY/part.parquet` through the last year with any pre-cutoff time (a January 1 cutoff excludes that calendar year; an entirely post-cutoff range throws `VAULT_RANGE_VIOLATION`). Expands `{{input:<dataset>}}` scans with bound upper availability predicates (`ts <= ? AND known_at <= ?`, `known_at <= ?`, or `effective_known_at <= ?` for `fundamentals_pit`) strictly `< vaultCutoffDate` (last included microsecond `.999999Z`) before authored SQL runs, preserving earlier history for SQL-owned warm-up.
|
||||
- **`runFeatureBatch(def, opts, executor)`** — Validates and plans upfront (0 executor calls on invalid inputs), awaits `executor.query(sql, params)` sequentially in year order, and returns `{ ref, definitionHash, knownAtRule, warmupBars, inputs, writes }`. On write failure, stops immediately and throws `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, `completedYears`, and `completedWrites` (earlier completed files may remain on disk for operator inspection before retry).
|
||||
- **`RET_1D_V1`** — Built-in `ret_1d@v1` example computing 1-day listing-partitioned raw-close return `(close / LAG(close)) - 1.0` with `known_at = ts` and `warmupBars: 1` (omitting rows without a positive prior close).
|
||||
|
||||
### Operational & Research Governance Notes
|
||||
|
||||
- **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`<curatedRoot>/features/<name>/v<version>/year=YYYY/`) exist before executing `COPY`.
|
||||
- **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`.
|
||||
- **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions.
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"./dataset-contracts": "./src/dataset-contracts.ts",
|
||||
"./datasets": "./src/datasets.ts",
|
||||
"./event-panel": "./src/event-panel.ts",
|
||||
"./feature-library": "./src/feature-library.ts",
|
||||
"./market-data-store": "./src/market-data-store.ts",
|
||||
"./market-data-store-duckdb": "./src/market-data-store-duckdb.ts",
|
||||
"./mcp": "./src/mcp/index.ts",
|
||||
|
|
|
|||
2119
libs/research/src/feature-library.ts
Normal file
2119
libs/research/src/feature-library.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,7 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
export * from './event-panel';
|
||||
export * from './feature-library';
|
||||
export * from './market-data-store';
|
||||
export * from './market-data-store-duckdb';
|
||||
export * from './signal-panel';
|
||||
|
|
|
|||
105
libs/research/src/sha256.ts
Normal file
105
libs/research/src/sha256.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
/**
|
||||
* Browser-safe, dependency-free FIPS 180-4 SHA-256 hex digest helper.
|
||||
*
|
||||
* Internal module shared by `trial-ledger.ts` and `feature-library.ts`.
|
||||
*/
|
||||
|
||||
// FIPS 180-4 SHA-256 round constants.
|
||||
const SHA256_K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const UTF8_ENCODER = new TextEncoder();
|
||||
|
||||
export function sha256HexUtf8(text: string): string {
|
||||
const bytes = UTF8_ENCODER.encode(text);
|
||||
const byteLen = bytes.length;
|
||||
const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0;
|
||||
const buffer = new Uint8Array(paddedLen);
|
||||
buffer.set(bytes);
|
||||
buffer[byteLen] = 0x80;
|
||||
|
||||
const view = new DataView(buffer.buffer);
|
||||
const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000);
|
||||
const bitLenLow = (byteLen * 8) >>> 0;
|
||||
view.setUint32(paddedLen - 8, bitLenHigh, false);
|
||||
view.setUint32(paddedLen - 4, bitLenLow, false);
|
||||
|
||||
let h0 = 0x6a09e667;
|
||||
let h1 = 0xbb67ae85;
|
||||
let h2 = 0x3c6ef372;
|
||||
let h3 = 0xa54ff53a;
|
||||
let h4 = 0x510e527f;
|
||||
let h5 = 0x9b05688c;
|
||||
let h6 = 0x1f83d9ab;
|
||||
let h7 = 0x5be0cd19;
|
||||
|
||||
const w = new Uint32Array(64);
|
||||
|
||||
for (let offset = 0; offset < paddedLen; offset += 64) {
|
||||
for (let i = 0; i < 16; i += 1) {
|
||||
w[i] = view.getUint32(offset + i * 4, false);
|
||||
}
|
||||
for (let i = 16; i < 64; i += 1) {
|
||||
const w15 = w[i - 15] as number;
|
||||
const w2 = w[i - 2] as number;
|
||||
const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
|
||||
const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
|
||||
w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0;
|
||||
}
|
||||
|
||||
let a = h0;
|
||||
let b = h1;
|
||||
let c = h2;
|
||||
let d = h3;
|
||||
let e = h4;
|
||||
let f = h5;
|
||||
let g = h6;
|
||||
let h = h7;
|
||||
|
||||
for (let i = 0; i < 64; i += 1) {
|
||||
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
||||
const ch = (e & f) ^ (~e & g);
|
||||
const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0;
|
||||
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
||||
const maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
const temp2 = (s0 + maj) | 0;
|
||||
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = (d + temp1) | 0;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = (temp1 + temp2) | 0;
|
||||
}
|
||||
|
||||
h0 = (h0 + a) >>> 0;
|
||||
h1 = (h1 + b) >>> 0;
|
||||
h2 = (h2 + c) >>> 0;
|
||||
h3 = (h3 + d) >>> 0;
|
||||
h4 = (h4 + e) >>> 0;
|
||||
h5 = (h5 + f) >>> 0;
|
||||
h6 = (h6 + g) >>> 0;
|
||||
h7 = (h7 + h) >>> 0;
|
||||
}
|
||||
|
||||
return (
|
||||
h0.toString(16).padStart(8, '0') +
|
||||
h1.toString(16).padStart(8, '0') +
|
||||
h2.toString(16).padStart(8, '0') +
|
||||
h3.toString(16).padStart(8, '0') +
|
||||
h4.toString(16).padStart(8, '0') +
|
||||
h5.toString(16).padStart(8, '0') +
|
||||
h6.toString(16).padStart(8, '0') +
|
||||
h7.toString(16).padStart(8, '0')
|
||||
);
|
||||
}
|
||||
|
|
@ -18,6 +18,7 @@ import {
|
|||
VaultHoldoutFenceError,
|
||||
applyVaultFence,
|
||||
} from './market-data-store';
|
||||
import { sha256HexUtf8 } from './sha256';
|
||||
|
||||
export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const;
|
||||
export type TrialStage = (typeof TRIAL_STAGES)[number];
|
||||
|
|
@ -222,106 +223,6 @@ const SELECT_TRIAL_COLUMNS = `
|
|||
kurtosis,
|
||||
daily_series`;
|
||||
|
||||
// FIPS 180-4 SHA-256 round constants.
|
||||
const SHA256_K = new Uint32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const UTF8_ENCODER = new TextEncoder();
|
||||
|
||||
function sha256HexUtf8(text: string): string {
|
||||
const bytes = UTF8_ENCODER.encode(text);
|
||||
const byteLen = bytes.length;
|
||||
const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0;
|
||||
const buffer = new Uint8Array(paddedLen);
|
||||
buffer.set(bytes);
|
||||
buffer[byteLen] = 0x80;
|
||||
|
||||
const view = new DataView(buffer.buffer);
|
||||
const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000);
|
||||
const bitLenLow = (byteLen * 8) >>> 0;
|
||||
view.setUint32(paddedLen - 8, bitLenHigh, false);
|
||||
view.setUint32(paddedLen - 4, bitLenLow, false);
|
||||
|
||||
let h0 = 0x6a09e667;
|
||||
let h1 = 0xbb67ae85;
|
||||
let h2 = 0x3c6ef372;
|
||||
let h3 = 0xa54ff53a;
|
||||
let h4 = 0x510e527f;
|
||||
let h5 = 0x9b05688c;
|
||||
let h6 = 0x1f83d9ab;
|
||||
let h7 = 0x5be0cd19;
|
||||
|
||||
const w = new Uint32Array(64);
|
||||
|
||||
for (let offset = 0; offset < paddedLen; offset += 64) {
|
||||
for (let i = 0; i < 16; i += 1) {
|
||||
w[i] = view.getUint32(offset + i * 4, false);
|
||||
}
|
||||
for (let i = 16; i < 64; i += 1) {
|
||||
const w15 = w[i - 15] as number;
|
||||
const w2 = w[i - 2] as number;
|
||||
const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
|
||||
const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
|
||||
w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0;
|
||||
}
|
||||
|
||||
let a = h0;
|
||||
let b = h1;
|
||||
let c = h2;
|
||||
let d = h3;
|
||||
let e = h4;
|
||||
let f = h5;
|
||||
let g = h6;
|
||||
let h = h7;
|
||||
|
||||
for (let i = 0; i < 64; i += 1) {
|
||||
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
||||
const ch = (e & f) ^ (~e & g);
|
||||
const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0;
|
||||
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
||||
const maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
const temp2 = (s0 + maj) | 0;
|
||||
|
||||
h = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = (d + temp1) | 0;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = (temp1 + temp2) | 0;
|
||||
}
|
||||
|
||||
h0 = (h0 + a) >>> 0;
|
||||
h1 = (h1 + b) >>> 0;
|
||||
h2 = (h2 + c) >>> 0;
|
||||
h3 = (h3 + d) >>> 0;
|
||||
h4 = (h4 + e) >>> 0;
|
||||
h5 = (h5 + f) >>> 0;
|
||||
h6 = (h6 + g) >>> 0;
|
||||
h7 = (h7 + h) >>> 0;
|
||||
}
|
||||
|
||||
return (
|
||||
h0.toString(16).padStart(8, '0') +
|
||||
h1.toString(16).padStart(8, '0') +
|
||||
h2.toString(16).padStart(8, '0') +
|
||||
h3.toString(16).padStart(8, '0') +
|
||||
h4.toString(16).padStart(8, '0') +
|
||||
h5.toString(16).padStart(8, '0') +
|
||||
h6.toString(16).padStart(8, '0') +
|
||||
h7.toString(16).padStart(8, '0')
|
||||
);
|
||||
}
|
||||
|
||||
function compareAscii(a: string, b: string): number {
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
}
|
||||
|
|
|
|||
953
libs/research/test/feature-library.test.ts
Normal file
953
libs/research/test/feature-library.test.ts
Normal file
|
|
@ -0,0 +1,953 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
FEATURE_FAMILIES,
|
||||
FEATURE_INPUT_DATASETS,
|
||||
FEATURE_KINDS,
|
||||
FEATURE_KNOWN_AT_RULES,
|
||||
FEATURE_OUTPUT_COLUMNS,
|
||||
type FeatureDefinition,
|
||||
FeatureLibraryError,
|
||||
type FeatureLibraryErrorCode,
|
||||
RET_1D_V1,
|
||||
type TableRow,
|
||||
createFeatureRegistry,
|
||||
featureDefinitionHash,
|
||||
featureRef,
|
||||
parseFeatureRef,
|
||||
planFeatureBatch,
|
||||
runFeatureBatch,
|
||||
validateFeatureDefinition,
|
||||
} from '@stock-bot/research';
|
||||
import {
|
||||
FEATURE_FAMILIES as subpathFeatureFamilies,
|
||||
FEATURE_INPUT_DATASETS as subpathFeatureInputDatasets,
|
||||
FEATURE_KINDS as subpathFeatureKinds,
|
||||
FEATURE_KNOWN_AT_RULES as subpathFeatureKnownAtRules,
|
||||
FEATURE_OUTPUT_COLUMNS as subpathFeatureOutputColumns,
|
||||
FeatureLibraryError as SubpathFeatureLibraryError,
|
||||
RET_1D_V1 as subpathRet1dV1,
|
||||
createFeatureRegistry as subpathCreateFeatureRegistry,
|
||||
featureDefinitionHash as subpathFeatureDefinitionHash,
|
||||
featureRef as subpathFeatureRef,
|
||||
parseFeatureRef as subpathParseFeatureRef,
|
||||
planFeatureBatch as subpathPlanFeatureBatch,
|
||||
runFeatureBatch as subpathRunFeatureBatch,
|
||||
validateFeatureDefinition as subpathValidateFeatureDefinition,
|
||||
} from '@stock-bot/research/feature-library';
|
||||
|
||||
interface RecordedQuery {
|
||||
readonly sql: string;
|
||||
readonly params: readonly DuckDbParam[];
|
||||
}
|
||||
|
||||
interface RecordingFakeExecutor {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly calls: RecordedQuery[];
|
||||
readonly runCalls: string[];
|
||||
}
|
||||
|
||||
function createRecordingFakeExecutor(opts?: {
|
||||
onQuery?: (sql: string, params: readonly DuckDbParam[], callIndex: number) => Promise<void> | void;
|
||||
}): RecordingFakeExecutor {
|
||||
const calls: RecordedQuery[] = [];
|
||||
const runCalls: string[] = [];
|
||||
|
||||
const executor: DuckDbExecutor = {
|
||||
async run(sql: string): Promise<void> {
|
||||
runCalls.push(sql);
|
||||
},
|
||||
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
||||
const idx = calls.length;
|
||||
calls.push({ sql, params: [...params] });
|
||||
if (opts?.onQuery !== undefined) {
|
||||
await opts.onQuery(sql, params, idx);
|
||||
}
|
||||
return [];
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, calls, runCalls };
|
||||
}
|
||||
|
||||
function expectFeatureErrorCode(fn: () => unknown, expectedCode: FeatureLibraryErrorCode): FeatureLibraryError {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(FeatureLibraryError);
|
||||
const typed = error as FeatureLibraryError;
|
||||
expect(typed.code).toBe(expectedCode);
|
||||
return typed;
|
||||
}
|
||||
throw new Error(`Expected FeatureLibraryError(${expectedCode}) to be thrown, but succeeded.`);
|
||||
}
|
||||
|
||||
function makeSimpleDef(overrides: Partial<FeatureDefinition> = {}): FeatureDefinition {
|
||||
return {
|
||||
name: 'close_raw',
|
||||
version: 1,
|
||||
family: 'technical',
|
||||
kind: 'duckdb_sql',
|
||||
inputs: ['bars_1d'],
|
||||
warmupBars: 0,
|
||||
knownAtRule: 'bar_close',
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('feature-library barrel and subpath exports', () => {
|
||||
it('exposes identical symbols from @stock-bot/research and @stock-bot/research/feature-library', () => {
|
||||
expect(FEATURE_FAMILIES).toBe(subpathFeatureFamilies);
|
||||
expect(FEATURE_INPUT_DATASETS).toBe(subpathFeatureInputDatasets);
|
||||
expect(FEATURE_KINDS).toBe(subpathFeatureKinds);
|
||||
expect(FEATURE_KNOWN_AT_RULES).toBe(subpathFeatureKnownAtRules);
|
||||
expect(FEATURE_OUTPUT_COLUMNS).toBe(subpathFeatureOutputColumns);
|
||||
expect(FeatureLibraryError).toBe(SubpathFeatureLibraryError);
|
||||
expect(RET_1D_V1).toBe(subpathRet1dV1);
|
||||
expect(createFeatureRegistry).toBe(subpathCreateFeatureRegistry);
|
||||
expect(featureDefinitionHash).toBe(subpathFeatureDefinitionHash);
|
||||
expect(featureRef).toBe(subpathFeatureRef);
|
||||
expect(parseFeatureRef).toBe(subpathParseFeatureRef);
|
||||
expect(planFeatureBatch).toBe(subpathPlanFeatureBatch);
|
||||
expect(runFeatureBatch).toBe(subpathRunFeatureBatch);
|
||||
expect(validateFeatureDefinition).toBe(subpathValidateFeatureDefinition);
|
||||
});
|
||||
});
|
||||
|
||||
describe('featureRef and parseFeatureRef', () => {
|
||||
it('round-trips canonical refs such as ret_1d@v1', () => {
|
||||
const ref = featureRef(RET_1D_V1);
|
||||
expect(ref).toBe('ret_1d@v1');
|
||||
expect(parseFeatureRef(ref)).toEqual({ name: 'ret_1d', version: 1 });
|
||||
expect(parseFeatureRef('rsi_14@v12')).toEqual({ name: 'rsi_14', version: 12 });
|
||||
});
|
||||
|
||||
it('rejects malformed, non-canonical, and unsafe refs', () => {
|
||||
const invalidRefs = [
|
||||
'',
|
||||
'ret_1d',
|
||||
'ret_1d@1',
|
||||
'ret_1d@v0',
|
||||
'ret_1d@v01',
|
||||
'ret_1d@v-1',
|
||||
'ret_1d@v1.5',
|
||||
'RSI-14@v1',
|
||||
'1abc@v1',
|
||||
`${'a'.repeat(64)}@v1`,
|
||||
'ret_1d@v9007199254740992',
|
||||
];
|
||||
for (const bad of invalidRefs) {
|
||||
expectFeatureErrorCode(() => parseFeatureRef(bad), 'INVALID_FEATURE_REF');
|
||||
}
|
||||
expectFeatureErrorCode(() => parseFeatureRef(null as unknown as string), 'INVALID_FEATURE_REF');
|
||||
expectFeatureErrorCode(() => featureRef({ name: 'RSI-14', version: 1 }), 'INVALID_NAME');
|
||||
expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 0 }), 'INVALID_VERSION');
|
||||
expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 1.5 }), 'INVALID_VERSION');
|
||||
expectFeatureErrorCode(
|
||||
() => featureRef({ name: 'ret_1d', version: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
'INVALID_VERSION'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateFeatureDefinition', () => {
|
||||
it('accepts RET_1D_V1, CTE + window expressions, subqueries, and multi-input joins', () => {
|
||||
expect(() => validateFeatureDefinition(RET_1D_V1)).not.toThrow();
|
||||
|
||||
const joinedDef: FeatureDefinition = {
|
||||
name: 'cad_scaled_close',
|
||||
version: 1,
|
||||
family: 'fx',
|
||||
kind: 'duckdb_sql',
|
||||
inputs: ['bars_1d', 'fx_1d'],
|
||||
warmupBars: 0,
|
||||
knownAtRule: 'max_input_known_at',
|
||||
sql: `
|
||||
WITH base AS (
|
||||
SELECT b.listing_id, b.ts, b.session_date, b.close, b.known_at
|
||||
FROM {{input:bars_1d}} AS b
|
||||
)
|
||||
SELECT
|
||||
base.listing_id,
|
||||
base.ts,
|
||||
GREATEST(base.known_at, f.known_at) AS known_at,
|
||||
base.close / f.close AS value
|
||||
FROM base
|
||||
INNER JOIN (
|
||||
SELECT session_date, close, known_at
|
||||
FROM {{input:fx_1d}}
|
||||
WHERE pair = 'USDCAD'
|
||||
) AS f ON base.session_date = f.session_date
|
||||
`,
|
||||
};
|
||||
expect(() => validateFeatureDefinition(joinedDef)).not.toThrow();
|
||||
});
|
||||
|
||||
it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => {
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: 'RSI-14' })), 'INVALID_NAME');
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '' })), 'INVALID_NAME');
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '1ret' })), 'INVALID_NAME');
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ name: 'a'.repeat(64) })),
|
||||
'INVALID_NAME'
|
||||
);
|
||||
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 0 })), 'INVALID_VERSION');
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: -2 })), 'INVALID_VERSION');
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 1.5 })), 'INVALID_VERSION');
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ version: Number.NaN })),
|
||||
'INVALID_VERSION'
|
||||
);
|
||||
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ family: 'macro' as FeatureDefinition['family'] })),
|
||||
'INVALID_FAMILY'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ kind: 'polars' as FeatureDefinition['kind'] })),
|
||||
'INVALID_KIND'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ warmupBars: -1 })),
|
||||
'INVALID_WARMUP_BARS'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ warmupBars: 0.5 })),
|
||||
'INVALID_WARMUP_BARS'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({ knownAtRule: 'end_of_month' as FeatureDefinition['knownAtRule'] })
|
||||
),
|
||||
'INVALID_KNOWN_AT_RULE'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects empty SQL, semicolons/multi-statement SQL, comments, bind markers, and malformed placeholders', () => {
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ sql: ' ' })), 'INVALID_SQL_STATEMENT');
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; SELECT 1',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: '/* block */ SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > ?',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > $1',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > :min_close',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{bad:bars_1d}}',
|
||||
})
|
||||
),
|
||||
'INVALID_SQL_STATEMENT'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects prohibited DDL/DML/admin SQL commands with PROHIBITED_SQL_OPERATION', () => {
|
||||
const prohibitedSqls = [
|
||||
"COPY (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) TO '/tmp/out.parquet'",
|
||||
"ATTACH '/tmp/evil.db' AS evil",
|
||||
'INSERT INTO t VALUES (1)',
|
||||
'CREATE TABLE t (x INT)',
|
||||
'PRAGMA database_list',
|
||||
"SET memory_limit = '100GB'",
|
||||
'INSTALL httpfs',
|
||||
'LOAD httpfs',
|
||||
'DROP TABLE bars_1d',
|
||||
'DELETE FROM bars_1d',
|
||||
'UPDATE bars_1d SET close = 0',
|
||||
];
|
||||
for (const sql of prohibitedSqls) {
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ sql })),
|
||||
'PROHIBITED_SQL_OPERATION'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects direct/mixed-case readers, quoted paths, catalog relations, table functions, and disallowed functions', () => {
|
||||
const externalSqls = [
|
||||
"SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/etc/x')",
|
||||
"SELECT listing_id, ts, ts AS known_at, close AS value FROM ReAd_PaRqUeT('/etc/x.parquet')",
|
||||
"SELECT listing_id, ts, ts AS known_at, close AS value FROM read_csv('/tmp/a.csv')",
|
||||
"SELECT listing_id, ts, ts AS known_at, close AS value FROM glob('/mnt/*')",
|
||||
"SELECT listing_id, ts, ts AS known_at, close AS value FROM '/etc/x.parquet'",
|
||||
"SELECT listing_id, ts, ts AS known_at, '/etc/passwd' AS value FROM {{input:bars_1d}}",
|
||||
'SELECT listing_id, ts, ts AS known_at, close AS value FROM information_schema.tables',
|
||||
'SELECT listing_id, ts, ts AS known_at, close AS value FROM pg_catalog.pg_tables',
|
||||
'SELECT listing_id, ts, ts AS known_at, close AS value FROM raw_table_not_a_cte',
|
||||
"SELECT listing_id, ts, ts AS known_at, getenv('HOME') AS value FROM {{input:bars_1d}}",
|
||||
'SELECT listing_id, ts, ts AS known_at, custom_evil_fn(close) AS value FROM {{input:bars_1d}}',
|
||||
];
|
||||
for (const sql of externalSqls) {
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ sql })),
|
||||
'EXTERNAL_DATA_ACCESS'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => {
|
||||
const badProjections = [
|
||||
'SELECT * FROM {{input:bars_1d}}',
|
||||
'SELECT listing_id, ts, close AS value FROM {{input:bars_1d}}',
|
||||
'SELECT listing_id, ts, ts AS known_at, close AS value, volume AS extra FROM {{input:bars_1d}}',
|
||||
'SELECT ts, listing_id, ts AS known_at, close AS value FROM {{input:bars_1d}}',
|
||||
'SELECT listing_id, ts, ts AS known_at, close AS ret FROM {{input:bars_1d}}',
|
||||
'SELECT listing_id, ts, ts AS known_at, close + 1 FROM {{input:bars_1d}}',
|
||||
];
|
||||
for (const sql of badProjections) {
|
||||
expectFeatureErrorCode(
|
||||
() => validateFeatureDefinition(makeSimpleDef({ sql })),
|
||||
'INVALID_SQL_PROJECTION'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects unsupported, undeclared, and unused input datasets with distinct codes', () => {
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
inputs: ['macro' as FeatureDefinition['inputs'][number]],
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}',
|
||||
})
|
||||
),
|
||||
'UNSUPPORTED_INPUT_DATASET'
|
||||
);
|
||||
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
inputs: ['bars_1d'],
|
||||
sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id',
|
||||
})
|
||||
),
|
||||
'UNDECLARED_INPUT'
|
||||
);
|
||||
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
validateFeatureDefinition(
|
||||
makeSimpleDef({
|
||||
inputs: ['bars_1d', 'fx_1d'],
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
|
||||
})
|
||||
),
|
||||
'UNUSED_INPUT'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('featureDefinitionHash', () => {
|
||||
it('is stable across inter-token whitespace, object key order, input order, and metadata', () => {
|
||||
const defA: FeatureDefinition = {
|
||||
name: 'fx_ratio',
|
||||
version: 1,
|
||||
family: 'fx',
|
||||
kind: 'duckdb_sql',
|
||||
inputs: ['fx_1d', 'bars_1d'],
|
||||
warmupBars: 2,
|
||||
knownAtRule: 'max_input_known_at',
|
||||
description: 'First description',
|
||||
sql: "SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date WHERE f.pair = 'USD CAD'",
|
||||
};
|
||||
|
||||
const defB: FeatureDefinition = {
|
||||
sql: [
|
||||
'SELECT',
|
||||
' b.listing_id,',
|
||||
' b.ts,',
|
||||
' GREATEST(b.known_at, f.known_at) AS known_at,',
|
||||
' b.close / f.close AS value',
|
||||
'FROM {{input:bars_1d}} AS b',
|
||||
'INNER JOIN {{input:fx_1d}} AS f',
|
||||
' ON b.session_date = f.session_date',
|
||||
"WHERE f.pair = 'USD CAD'",
|
||||
].join('\n\t'),
|
||||
knownAtRule: 'max_input_known_at',
|
||||
warmupBars: 2,
|
||||
inputs: ['bars_1d', 'fx_1d'],
|
||||
kind: 'duckdb_sql',
|
||||
family: 'technical',
|
||||
version: 1,
|
||||
name: 'fx_ratio',
|
||||
description: 'Different metadata description',
|
||||
};
|
||||
|
||||
const hashA = featureDefinitionHash(defA);
|
||||
const hashB = featureDefinitionHash(defB);
|
||||
expect(hashA).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(hashA).toBe(hashB);
|
||||
});
|
||||
|
||||
it('changes when string literal whitespace, SQL semantics, inputs, warmupBars, or knownAtRule change', () => {
|
||||
const base = makeSimpleDef({
|
||||
sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}",
|
||||
});
|
||||
const baseHash = featureDefinitionHash(base);
|
||||
|
||||
// Whitespace inside string literal changes hash.
|
||||
const changedLiteral = makeSimpleDef({
|
||||
sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}",
|
||||
});
|
||||
expect(featureDefinitionHash(changedLiteral)).not.toBe(baseHash);
|
||||
|
||||
// Substantive SQL change.
|
||||
const changedSql = makeSimpleDef({
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, open AS value FROM {{input:bars_1d}}',
|
||||
});
|
||||
expect(featureDefinitionHash(changedSql)).not.toBe(baseHash);
|
||||
|
||||
// Valid input dataset change.
|
||||
const changedInput = makeSimpleDef({
|
||||
inputs: ['events'],
|
||||
sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}',
|
||||
});
|
||||
expect(featureDefinitionHash(changedInput)).not.toBe(baseHash);
|
||||
|
||||
// warmupBars change.
|
||||
expect(featureDefinitionHash({ ...base, warmupBars: 5 })).not.toBe(baseHash);
|
||||
|
||||
// knownAtRule change.
|
||||
expect(featureDefinitionHash({ ...base, knownAtRule: 'source_known_at' })).not.toBe(baseHash);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createFeatureRegistry', () => {
|
||||
it('supports idempotent re-registration, enforces FEATURE_VERSION_IMMUTABLE, allows version bumps, and isolates mutations', () => {
|
||||
const registry = createFeatureRegistry();
|
||||
const mutableInputs: FeatureDefinition['inputs'][number][] = ['bars_1d'];
|
||||
const initial: FeatureDefinition = {
|
||||
...RET_1D_V1,
|
||||
inputs: mutableInputs,
|
||||
};
|
||||
|
||||
const first = registry.registerSignal(initial);
|
||||
expect(first.ref).toBe('ret_1d@v1');
|
||||
expect(first.definitionHash).toBe(featureDefinitionHash(RET_1D_V1));
|
||||
|
||||
// Mutate caller input after registration; stored definition must be unaffected.
|
||||
mutableInputs.push('fx_1d');
|
||||
expect(registry.get('ret_1d@v1')?.inputs).toEqual(['bars_1d']);
|
||||
|
||||
// Idempotent re-registration with whitespace-only SQL difference.
|
||||
const sameSemantic: FeatureDefinition = {
|
||||
...RET_1D_V1,
|
||||
sql: RET_1D_V1.sql.replace(/\n/g, ' '),
|
||||
description: 'Updated description ignored for hash',
|
||||
};
|
||||
const second = registry.registerSignal(sameSemantic);
|
||||
expect(second.definitionHash).toBe(first.definitionHash);
|
||||
expect(registry.list()).toEqual(['ret_1d@v1']);
|
||||
|
||||
// Semantic changes at v1 must throw FEATURE_VERSION_IMMUTABLE.
|
||||
const changedSql: FeatureDefinition = {
|
||||
...RET_1D_V1,
|
||||
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
|
||||
};
|
||||
const errSql = expectFeatureErrorCode(
|
||||
() => registry.registerSignal(changedSql),
|
||||
'FEATURE_VERSION_IMMUTABLE'
|
||||
);
|
||||
expect(errSql.ref).toBe('ret_1d@v1');
|
||||
|
||||
const changedInputs: FeatureDefinition = {
|
||||
...RET_1D_V1,
|
||||
inputs: ['bars_1d', 'fx_1d'],
|
||||
sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date',
|
||||
};
|
||||
expectFeatureErrorCode(
|
||||
() => registry.registerSignal(changedInputs),
|
||||
'FEATURE_VERSION_IMMUTABLE'
|
||||
);
|
||||
|
||||
expectFeatureErrorCode(
|
||||
() => registry.registerSignal({ ...RET_1D_V1, warmupBars: 2 }),
|
||||
'FEATURE_VERSION_IMMUTABLE'
|
||||
);
|
||||
|
||||
expectFeatureErrorCode(
|
||||
() => registry.registerSignal({ ...RET_1D_V1, knownAtRule: 'source_known_at' }),
|
||||
'FEATURE_VERSION_IMMUTABLE'
|
||||
);
|
||||
|
||||
// Same change under version 2 succeeds and both refs are listed.
|
||||
const v2 = registry.registerSignal({ ...changedSql, version: 2 });
|
||||
expect(v2.ref).toBe('ret_1d@v2');
|
||||
expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']);
|
||||
expect(registry.get('ret_1d@v2')?.version).toBe(2);
|
||||
expect(registry.get('missing@v1')).toBeUndefined();
|
||||
|
||||
// Mutating returned list array does not affect registry.
|
||||
const listed = registry.list() as string[];
|
||||
listed.push('evil@v99');
|
||||
expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('planFeatureBatch', () => {
|
||||
it('plans 3 yearly Parquet COPY statements for RET_1D_V1 across 2020–2022', () => {
|
||||
const writes = planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020,
|
||||
toYear: 2022,
|
||||
vaultCutoffDate: '2025-06-01',
|
||||
});
|
||||
|
||||
expect(writes).toHaveLength(3);
|
||||
expect(writes.map(w => w.year)).toEqual([2020, 2021, 2022]);
|
||||
expect(writes.map(w => w.outputPath)).toEqual([
|
||||
'/c/features/ret_1d/v1/year=2020/part.parquet',
|
||||
'/c/features/ret_1d/v1/year=2021/part.parquet',
|
||||
'/c/features/ret_1d/v1/year=2022/part.parquet',
|
||||
]);
|
||||
|
||||
for (const write of writes) {
|
||||
expect(write.sql).toStartWith(
|
||||
'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value FROM ('
|
||||
);
|
||||
expect(write.sql).toContain(
|
||||
"read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?"
|
||||
);
|
||||
expect(write.sql).toContain(
|
||||
'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)'
|
||||
);
|
||||
expect(write.sql).toEndWith(
|
||||
`TO '${write.outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`
|
||||
);
|
||||
const expectedTsEnd = `${write.year}-12-31T23:59:59.999999Z`;
|
||||
const expectedKnownAtCeiling = '2025-05-31T23:59:59.999999Z';
|
||||
expect(write.params).toEqual([
|
||||
expectedTsEnd,
|
||||
expectedKnownAtCeiling,
|
||||
write.year,
|
||||
expectedTsEnd,
|
||||
expectedKnownAtCeiling,
|
||||
]);
|
||||
|
||||
// Verify scan predicate is embedded inside the FROM subquery of the lagged CTE
|
||||
// (evaluated before LAG) and outer year(ts) filter follows the authored query.
|
||||
const lagIdx = write.sql.indexOf('LAG ( close )');
|
||||
const scanIdx = write.sql.indexOf(
|
||||
"FROM (SELECT * FROM read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?)"
|
||||
);
|
||||
const outerYearIdx = write.sql.indexOf('WHERE year(ts) = ?');
|
||||
expect(lagIdx).toBeGreaterThan(-1);
|
||||
expect(scanIdx).toBeGreaterThan(lagIdx);
|
||||
expect(outerYearIdx).toBeGreaterThan(scanIdx);
|
||||
}
|
||||
});
|
||||
|
||||
it('expands all six allow-listed dataset path shapes and predicates, normalizes roots, and rejects unsafe roots', () => {
|
||||
const allSixDef: FeatureDefinition = {
|
||||
name: 'all_six_check',
|
||||
version: 1,
|
||||
family: 'fundamental',
|
||||
kind: 'duckdb_sql',
|
||||
inputs: ['bars_1d', 'adj_factors', 'events', 'shorts', 'fx_1d', 'fundamentals_pit'],
|
||||
warmupBars: 0,
|
||||
knownAtRule: 'max_input_known_at',
|
||||
sql: `
|
||||
SELECT
|
||||
b.listing_id,
|
||||
b.ts,
|
||||
GREATEST(b.known_at, a.known_at, e.known_at, s.known_at, f.known_at, p.effective_known_at) AS known_at,
|
||||
b.close AS value
|
||||
FROM {{input:bars_1d}} AS b
|
||||
INNER JOIN {{input:adj_factors}} AS a ON b.listing_id = a.listing_id
|
||||
INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id
|
||||
INNER JOIN {{input:shorts}} AS s ON b.listing_id = s.listing_id
|
||||
INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date
|
||||
INNER JOIN {{input:fundamentals_pit}} AS p ON b.listing_id = p.listing_id
|
||||
`,
|
||||
};
|
||||
|
||||
const [write] = planFeatureBatch(allSixDef, {
|
||||
curatedRoot: '/data///',
|
||||
fromYear: 2021,
|
||||
toYear: 2021,
|
||||
vaultCutoffDate: '2024-01-01',
|
||||
});
|
||||
expect(write).toBeDefined();
|
||||
expect(write?.outputPath).toBe('/data/features/all_six_check/v1/year=2021/part.parquet');
|
||||
expect(write?.sql).toContain(
|
||||
"read_parquet('/data/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?"
|
||||
);
|
||||
expect(write?.sql).toContain(
|
||||
"read_parquet('/data/adj_factors/part.parquet') WHERE known_at <= ?"
|
||||
);
|
||||
expect(write?.sql).toContain(
|
||||
"read_parquet('/data/events/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?"
|
||||
);
|
||||
expect(write?.sql).toContain(
|
||||
"read_parquet('/data/shorts/part.parquet') WHERE known_at <= ?"
|
||||
);
|
||||
expect(write?.sql).toContain(
|
||||
"read_parquet('/data/fx_1d/part.parquet') WHERE ts <= ? AND known_at <= ?"
|
||||
);
|
||||
expect(write?.sql).toContain(
|
||||
"read_parquet('/data/fundamentals_pit/year=*/part.parquet', hive_partitioning = true) WHERE effective_known_at <= ?"
|
||||
);
|
||||
|
||||
const ts2021 = '2021-12-31T23:59:59.999999Z';
|
||||
const vaultCeiling = '2023-12-31T23:59:59.999999Z';
|
||||
expect(write?.params).toEqual([
|
||||
ts2021,
|
||||
vaultCeiling, // bars_1d
|
||||
vaultCeiling, // adj_factors
|
||||
ts2021,
|
||||
vaultCeiling, // events
|
||||
vaultCeiling, // shorts
|
||||
ts2021,
|
||||
vaultCeiling, // fx_1d
|
||||
vaultCeiling, // fundamentals_pit
|
||||
2021,
|
||||
ts2021,
|
||||
vaultCeiling, // outer filter
|
||||
]);
|
||||
|
||||
// Root '/' normalization (no double leading slash).
|
||||
const [rootWrite] = planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/',
|
||||
fromYear: 2020,
|
||||
toYear: 2020,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
expect(rootWrite?.outputPath).toBe('/features/ret_1d/v1/year=2020/part.parquet');
|
||||
expect(rootWrite?.sql).toContain("read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true)");
|
||||
|
||||
// Unsafe curated roots rejected.
|
||||
for (const badRoot of ['', 'relative/path', "/tmp/o'reilly", '/tmp/a;b', '/tmp/a*b', '/tmp/\n']) {
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: badRoot,
|
||||
fromYear: 2020,
|
||||
toYear: 2020,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'INVALID_BATCH_OPTIONS'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => {
|
||||
// Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z.
|
||||
const midyear = planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020,
|
||||
toYear: 2024,
|
||||
vaultCutoffDate: '2022-06-15',
|
||||
});
|
||||
expect(midyear.map(w => w.year)).toEqual([2020, 2021, 2022]);
|
||||
expect(midyear[2]?.params).toEqual([
|
||||
'2022-06-14T23:59:59.999999Z',
|
||||
'2022-06-14T23:59:59.999999Z',
|
||||
2022,
|
||||
'2022-06-14T23:59:59.999999Z',
|
||||
'2022-06-14T23:59:59.999999Z',
|
||||
]);
|
||||
|
||||
// January 1 cutoff: 2022-01-01 -> excludes 2022 completely.
|
||||
const jan1 = planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020,
|
||||
toYear: 2023,
|
||||
vaultCutoffDate: '2022-01-01',
|
||||
});
|
||||
expect(jan1.map(w => w.year)).toEqual([2020, 2021]);
|
||||
expect(jan1[1]?.params).toEqual([
|
||||
'2021-12-31T23:59:59.999999Z',
|
||||
'2021-12-31T23:59:59.999999Z',
|
||||
2021,
|
||||
'2021-12-31T23:59:59.999999Z',
|
||||
'2021-12-31T23:59:59.999999Z',
|
||||
]);
|
||||
|
||||
// Entirely held-out ranges throw VAULT_RANGE_VIOLATION.
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2023,
|
||||
toYear: 2025,
|
||||
vaultCutoffDate: '2022-06-15',
|
||||
}),
|
||||
'VAULT_RANGE_VIOLATION'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2022,
|
||||
toYear: 2022,
|
||||
vaultCutoffDate: '2022-01-01',
|
||||
}),
|
||||
'VAULT_RANGE_VIOLATION'
|
||||
);
|
||||
|
||||
// Invalid calendar dates and year ranges throw INVALID_BATCH_OPTIONS.
|
||||
for (const badDate of ['2025-02-29', '2025-13-01', '2025-04-31', '2025-06-01T00:00:00Z', 'not-a-date']) {
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020,
|
||||
toYear: 2021,
|
||||
vaultCutoffDate: badDate,
|
||||
}),
|
||||
'INVALID_BATCH_OPTIONS'
|
||||
);
|
||||
}
|
||||
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2022,
|
||||
toYear: 2020,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'INVALID_BATCH_OPTIONS'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 999,
|
||||
toYear: 2020,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'INVALID_BATCH_OPTIONS'
|
||||
);
|
||||
expectFeatureErrorCode(
|
||||
() =>
|
||||
planFeatureBatch(RET_1D_V1, {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020.5,
|
||||
toYear: 2021,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'INVALID_BATCH_OPTIONS'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runFeatureBatch', () => {
|
||||
it('executes deterministically in sequential year order and returns a complete manifest', async () => {
|
||||
const opts = {
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020,
|
||||
toYear: 2022,
|
||||
vaultCutoffDate: '2025-06-01',
|
||||
};
|
||||
|
||||
const orderLog: string[] = [];
|
||||
const fakeA = createRecordingFakeExecutor({
|
||||
async onQuery(_sql, params) {
|
||||
const year = params[2];
|
||||
orderLog.push(`start:${String(year)}`);
|
||||
await Promise.resolve();
|
||||
orderLog.push(`end:${String(year)}`);
|
||||
},
|
||||
});
|
||||
const fakeB = createRecordingFakeExecutor();
|
||||
|
||||
const manifestA = await runFeatureBatch(RET_1D_V1, opts, fakeA.executor);
|
||||
const manifestB = await runFeatureBatch(RET_1D_V1, opts, fakeB.executor);
|
||||
|
||||
expect(orderLog).toEqual([
|
||||
'start:2020',
|
||||
'end:2020',
|
||||
'start:2021',
|
||||
'end:2021',
|
||||
'start:2022',
|
||||
'end:2022',
|
||||
]);
|
||||
expect(fakeA.runCalls).toHaveLength(0);
|
||||
expect(fakeA.calls).toEqual(fakeB.calls);
|
||||
expect(manifestA).toEqual(manifestB);
|
||||
expect(manifestA).toEqual({
|
||||
ref: 'ret_1d@v1',
|
||||
definitionHash: featureDefinitionHash(RET_1D_V1),
|
||||
knownAtRule: 'bar_close',
|
||||
warmupBars: 1,
|
||||
inputs: ['bars_1d'],
|
||||
writes: [
|
||||
{ year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' },
|
||||
{ year: 2021, outputPath: '/c/features/ret_1d/v1/year=2021/part.parquet' },
|
||||
{ year: 2022, outputPath: '/c/features/ret_1d/v1/year=2022/part.parquet' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('stops on second-year executor error, preserves cause, and reports only first year as completed', async () => {
|
||||
const rootCause = new Error('disk full on year 2021');
|
||||
const fake = createRecordingFakeExecutor({
|
||||
onQuery(_sql, _params, callIndex) {
|
||||
if (callIndex === 1) {
|
||||
throw rootCause;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await runFeatureBatch(
|
||||
RET_1D_V1,
|
||||
{
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2020,
|
||||
toYear: 2022,
|
||||
vaultCutoffDate: '2025-06-01',
|
||||
},
|
||||
fake.executor
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(FeatureLibraryError);
|
||||
const typed = caught as FeatureLibraryError;
|
||||
expect(typed.code).toBe('BATCH_WRITE_FAILED');
|
||||
expect(typed.cause).toBe(rootCause);
|
||||
expect(typed.failedYear).toBe(2021);
|
||||
expect(typed.completedYears).toEqual([2020]);
|
||||
expect(typed.completedWrites).toEqual([
|
||||
{ year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' },
|
||||
]);
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('issues zero executor calls when definition or batch options are invalid', async () => {
|
||||
const fake = createRecordingFakeExecutor();
|
||||
let caught: unknown;
|
||||
try {
|
||||
await runFeatureBatch(
|
||||
RET_1D_V1,
|
||||
{
|
||||
curatedRoot: '/c',
|
||||
fromYear: 2025,
|
||||
toYear: 2026,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
},
|
||||
fake.executor
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(FeatureLibraryError);
|
||||
expect((caught as FeatureLibraryError).code).toBe('VAULT_RANGE_VIOLATION');
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
expect(fake.runCalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixture, no Parquet execution)', () => {
|
||||
it('matches listing-partitioned LAG raw-close return semantics across prior-year warm-up and raw split discontinuity', () => {
|
||||
// Verify SQL structure enforces listing-partitioned LAG, bar-close known_at, and positive prior close guard.
|
||||
expect(RET_1D_V1.sql).toContain('LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close');
|
||||
expect(RET_1D_V1.sql).toContain('ts AS known_at');
|
||||
expect(RET_1D_V1.sql).toContain('(close / prev_close) - 1.0 AS value');
|
||||
expect(RET_1D_V1.sql).toContain('WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0');
|
||||
|
||||
// Hand-calculated reference fixture (does not evaluate DuckDB Parquet):
|
||||
// Listing 101: 2019-12-31 close 100 -> 2020-01-02 close 110 (+10%) -> 2020-01-03 2-for-1 raw split close 55 (-50% raw).
|
||||
// Listing 202: 2020-01-02 close 50 (no prior close -> omitted) -> 2020-01-03 close 52 (+4%).
|
||||
const bars = [
|
||||
{ listing_id: 101, ts: '2019-12-31T21:00:00Z', close: 100 },
|
||||
{ listing_id: 101, ts: '2020-01-02T21:00:00Z', close: 110 },
|
||||
{ listing_id: 101, ts: '2020-01-03T21:00:00Z', close: 55 },
|
||||
{ listing_id: 202, ts: '2020-01-02T21:00:00Z', close: 50 },
|
||||
{ listing_id: 202, ts: '2020-01-03T21:00:00Z', close: 52 },
|
||||
];
|
||||
|
||||
const lastCloseByListing = new Map<number, number>();
|
||||
const targetYearRows: Array<{ listing_id: number; ts: string; known_at: string; value: number }> = [];
|
||||
for (const bar of bars) {
|
||||
const prevClose = lastCloseByListing.get(bar.listing_id);
|
||||
lastCloseByListing.set(bar.listing_id, bar.close);
|
||||
if (prevClose === undefined || prevClose <= 0 || bar.close <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (bar.ts.startsWith('2020-')) {
|
||||
targetYearRows.push({
|
||||
listing_id: bar.listing_id,
|
||||
ts: bar.ts,
|
||||
known_at: bar.ts,
|
||||
value: bar.close / prevClose - 1.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
expect(targetYearRows).toHaveLength(3);
|
||||
expect(targetYearRows[0]).toEqual({
|
||||
listing_id: 101,
|
||||
ts: '2020-01-02T21:00:00Z',
|
||||
known_at: '2020-01-02T21:00:00Z',
|
||||
value: 0.10000000000000009,
|
||||
});
|
||||
expect(targetYearRows[1]).toEqual({
|
||||
listing_id: 101,
|
||||
ts: '2020-01-03T21:00:00Z',
|
||||
known_at: '2020-01-03T21:00:00Z',
|
||||
value: -0.5,
|
||||
});
|
||||
expect(targetYearRows[2]?.listing_id).toBe(202);
|
||||
expect(targetYearRows[2]?.value).toBeCloseTo(0.04, 12);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue