diff --git a/libs/research/README.md b/libs/research/README.md index 03973ff5..939d7fda 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -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:}}` 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 `@v` 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 `@v` 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 `/features//v/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:}}` 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 (`/features//v/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. diff --git a/libs/research/package.json b/libs/research/package.json index fb865726..e5cf853d 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -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", diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts new file mode 100644 index 00000000..658eaffb --- /dev/null +++ b/libs/research/src/feature-library.ts @@ -0,0 +1,2119 @@ +/** + * Versioned Feature Library core: declarative DuckDB SQL feature definitions, + * immutable `registerSignal` registry, and Vault-fenced yearly Parquet + * batch-plan runner (`design/PLATFORM-PLAN.md` §8 & D11, + * `design/DATA-CONTRACTS.md` §3.A). + * + * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero DuckDB + * driver dependency, zero bare `process` access. SQL execution is injected via + * {@link DuckDbExecutor} from `./market-data-store-duckdb`. + * + * Output Parquet contract (`design/DATA-CONTRACTS.md` §3.A): + * - `/features//v/year=YYYY/part.parquet` + * - Columns: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)` + * - Compression: `ZSTD`, ordered by `(listing_id, ts)`. + * + * Point-in-time & `adj_factors` note: + * - Each expanded `{{input:}}` scan binds upper availability + * predicates strictly below `vaultCutoffDate` before authored SQL executes, + * while preserving earlier history for SQL-owned warm-up windows. + * - Feature definitions own per-observation availability (`knownAtRule` and + * projected `known_at`). Because `adj_factors` stores cumulative suffix + * products, any feature consuming `{{input:adj_factors}}` requires a + * caller-verified, immutable point-in-time snapshot compatible with the job + * cutoff. + * + * Economic ownership & research evidence: + * - The Quant research role owns the economic specification of each feature + * definition. + * - {@link RET_1D_V1} is a built-in 1-session raw-close return example using a + * zero-return comparison baseline and no execution or transaction cost model. + * - Any future research result claim built on materialized features must retain + * the feature ref and `definitionHash`, immutable dataset identifier, sample + * window, Vault cutoff, baseline, and execution assumptions. + */ + +import { + MarketDataStoreValidationError, + VaultHoldoutFenceError, + applyVaultFence, +} from './market-data-store'; +import { + type DuckDbExecutor, + type DuckDbParam, + validateCuratedRoot, +} from './market-data-store-duckdb'; +import { sha256HexUtf8 } from './sha256'; + +export const FEATURE_FAMILIES = [ + 'technical', + 'cross_sectional', + 'fundamental', + 'event', + 'fx', + 'regime', +] as const; +export type FeatureFamily = (typeof FEATURE_FAMILIES)[number]; + +export const FEATURE_KINDS = ['duckdb_sql'] as const; +export type FeatureKind = (typeof FEATURE_KINDS)[number]; + +export const FEATURE_INPUT_DATASETS = [ + 'bars_1d', + 'adj_factors', + 'events', + 'shorts', + 'fx_1d', + 'fundamentals_pit', +] as const; +export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number]; + +export const FEATURE_KNOWN_AT_RULES = [ + 'bar_close', + 'source_known_at', + 'max_input_known_at', +] as const; +export type FeatureKnownAtRule = (typeof FEATURE_KNOWN_AT_RULES)[number]; + +export const FEATURE_OUTPUT_COLUMNS = ['listing_id', 'ts', 'known_at', 'value'] as const; + +const FEATURE_FAMILY_SET: ReadonlySet = new Set(FEATURE_FAMILIES); +const FEATURE_INPUT_SET: ReadonlySet = new Set(FEATURE_INPUT_DATASETS); +const FEATURE_KNOWN_AT_RULE_SET: ReadonlySet = new Set(FEATURE_KNOWN_AT_RULES); + +const FEATURE_NAME_RE = /^[a-z][a-z0-9_]{0,62}$/; +const FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; +const PLACEHOLDER_INNER_RE = /^input:([a-z][a-z0-9_]*)$/; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; + +const MIN_FOUR_DIGIT_YEAR = 1000; +const MAX_FOUR_DIGIT_YEAR = 9999; + +export type FeatureLibraryErrorCode = + | 'INVALID_DEFINITION' + | 'INVALID_NAME' + | 'INVALID_VERSION' + | 'INVALID_FAMILY' + | 'INVALID_KIND' + | 'INVALID_WARMUP_BARS' + | 'INVALID_KNOWN_AT_RULE' + | 'INVALID_FEATURE_REF' + | 'INVALID_SQL_STATEMENT' + | 'PROHIBITED_SQL_OPERATION' + | 'EXTERNAL_DATA_ACCESS' + | 'INVALID_SQL_PROJECTION' + | 'UNSUPPORTED_INPUT_DATASET' + | 'UNDECLARED_INPUT' + | 'UNUSED_INPUT' + | 'FEATURE_VERSION_IMMUTABLE' + | 'INVALID_BATCH_OPTIONS' + | 'VAULT_RANGE_VIOLATION' + | 'BATCH_WRITE_FAILED'; + +export interface FeatureBatchWriteReceipt { + readonly year: number; + readonly outputPath: string; +} + +export interface FeatureLibraryErrorDetails { + readonly cause?: unknown; + readonly failedYear?: number; + readonly completedYears?: readonly number[]; + readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; + readonly ref?: string; +} + +/** Typed fail-closed error thrown by the Feature Library SDK. */ +export class FeatureLibraryError extends Error { + override readonly name = 'FeatureLibraryError'; + readonly code: FeatureLibraryErrorCode; + readonly failedYear?: number; + readonly completedYears?: readonly number[]; + readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; + readonly ref?: string; + + constructor( + code: FeatureLibraryErrorCode, + message: string, + details?: FeatureLibraryErrorDetails + ) { + super(message, details?.cause !== undefined ? { cause: details.cause } : undefined); + this.code = code; + this.failedYear = details?.failedYear; + this.completedYears = + details?.completedYears !== undefined + ? Object.freeze([...details.completedYears]) + : undefined; + this.completedWrites = + details?.completedWrites !== undefined + ? Object.freeze(details.completedWrites.map(w => Object.freeze({ ...w }))) + : undefined; + this.ref = details?.ref; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export interface FeatureDefinition { + readonly name: string; + readonly version: number; + readonly family: FeatureFamily; + readonly kind: FeatureKind; + readonly sql: string; + readonly inputs: readonly FeatureInputDataset[]; + readonly warmupBars: number; + readonly knownAtRule: FeatureKnownAtRule; + readonly description?: string; +} + +export interface FeatureRefParts { + readonly name: string; + readonly version: number; +} + +export interface RegisteredFeature { + readonly ref: string; + readonly definitionHash: string; + readonly definition: FeatureDefinition; +} + +export interface FeatureRegistry { + registerSignal(def: FeatureDefinition): RegisteredFeature; + get(ref: string): FeatureDefinition | undefined; + list(): readonly string[]; +} + +export interface PlanFeatureBatchOptions { + readonly curatedRoot: string; + readonly fromYear: number; + readonly toYear: number; + readonly vaultCutoffDate: string; +} + +export interface PlannedFeatureWrite { + readonly year: number; + readonly outputPath: string; + readonly sql: string; + readonly params: readonly DuckDbParam[]; +} + +export interface FeatureBatchManifest { + readonly ref: string; + readonly definitionHash: string; + readonly knownAtRule: FeatureKnownAtRule; + readonly warmupBars: number; + readonly inputs: readonly FeatureInputDataset[]; + readonly writes: readonly FeatureBatchWriteReceipt[]; +} + +const PROHIBITED_SQL_KEYWORDS: ReadonlySet = new Set([ + 'ALTER', + 'ANALYZE', + 'ATTACH', + 'BEGIN', + 'CALL', + 'CHECKPOINT', + 'COMMIT', + 'COPY', + 'CREATE', + 'DEALLOCATE', + 'DELETE', + 'DESCRIBE', + 'DETACH', + 'DROP', + 'EXECUTE', + 'EXPLAIN', + 'EXPORT', + 'GRANT', + 'IMPORT', + 'INSERT', + 'INSTALL', + 'LOAD', + 'MERGE', + 'PIVOT', + 'PRAGMA', + 'PREPARE', + 'RESET', + 'REVOKE', + 'ROLLBACK', + 'SET', + 'SHOW', + 'SUMMARIZE', + 'TRUNCATE', + 'UNPIVOT', + 'UPDATE', + 'UPSERT', + 'USE', + 'VACUUM', +]); + +const EXTERNAL_READER_IDENTIFIERS: ReadonlySet = new Set([ + 'CURRENT_SETTING', + 'DELTA_SCAN', + 'DUCKDB_COLUMNS', + 'DUCKDB_CONSTRAINTS', + 'DUCKDB_DATABASES', + 'DUCKDB_DEPENDENCIES', + 'DUCKDB_EXTENSIONS', + 'DUCKDB_FUNCTIONS', + 'DUCKDB_INDEXES', + 'DUCKDB_KEYWORDS', + 'DUCKDB_MEMORY', + 'DUCKDB_OPTIMIZERS', + 'DUCKDB_SCHEMAS', + 'DUCKDB_SECRETS', + 'DUCKDB_SEQUENCES', + 'DUCKDB_SETTINGS', + 'DUCKDB_TABLES', + 'DUCKDB_TEMPORARY_FILES', + 'DUCKDB_TYPES', + 'DUCKDB_VIEWS', + 'GETENV', + 'GLOB', + 'HTTP_GET', + 'ICEBERG_SCAN', + 'MYSQL_SCAN', + 'PARQUET_FILE_METADATA', + 'PARQUET_KV_METADATA', + 'PARQUET_METADATA', + 'PARQUET_SCAN', + 'PARQUET_SCHEMA', + 'POSTGRES_SCAN', + 'PRAGMA_DATABASE_LIST', + 'PRAGMA_STORAGE_INFO', + 'PRAGMA_TABLE_INFO', + 'READ_BLOB', + 'READ_CSV', + 'READ_CSV_AUTO', + 'READ_EXCEL', + 'READ_JSON', + 'READ_JSON_AUTO', + 'READ_NDJSON', + 'READ_NDJSON_AUTO', + 'READ_PARQUET', + 'READ_STAT', + 'READ_TEXT', + 'SQLITE_SCAN', + 'ST_READ', +]); + +/** + * Pure built-in scalar, aggregate, window, date/time, string, and type-cast + * functions permitted in declarative feature SQL. Excludes all file, network, + * catalog, secret, and system-inspection functions. + */ +const ALLOWED_SQL_FUNCTIONS: ReadonlySet = new Set([ + // Casting & type constructors + 'BIT', + 'CAST', + 'CHAR', + 'CHARACTER', + 'DECIMAL', + 'INTERVAL', + 'NUMERIC', + 'TIME', + 'TIMESTAMP', + 'TIMESTAMPTZ', + 'TRY_CAST', + 'TYPEOF', + 'VARCHAR', + // Null / conditional + 'COALESCE', + 'GREATEST', + 'IF', + 'IFNULL', + 'ISFINITE', + 'ISINF', + 'ISNAN', + 'LEAST', + 'NULLIF', + // Math + 'ABS', + 'ACOS', + 'ASIN', + 'ATAN', + 'ATAN2', + 'CBRT', + 'CEIL', + 'CEILING', + 'COS', + 'COT', + 'DEGREES', + 'EXP', + 'FLOOR', + 'LN', + 'LOG', + 'LOG10', + 'LOG2', + 'MOD', + 'PI', + 'POW', + 'POWER', + 'RADIANS', + 'ROUND', + 'SIGN', + 'SIN', + 'SQRT', + 'TAN', + 'TRUNC', + // Aggregate + 'ANY_VALUE', + 'ARG_MAX', + 'ARG_MIN', + 'AVG', + 'CORR', + 'COUNT', + 'COVAR_POP', + 'COVAR_SAMP', + 'FIRST', + 'GEOMEAN', + 'KURTOSIS', + 'LAST', + 'MAD', + 'MAX', + 'MEDIAN', + 'MIN', + 'MODE', + 'PERCENTILE_CONT', + 'PERCENTILE_DISC', + 'PRODUCT', + 'QUANTILE', + 'QUANTILE_CONT', + 'QUANTILE_DISC', + 'REGR_INTERCEPT', + 'REGR_R2', + 'REGR_SLOPE', + 'SKEWNESS', + 'STDDEV', + 'STDDEV_POP', + 'STDDEV_SAMP', + 'SUM', + 'VAR_POP', + 'VAR_SAMP', + 'VARIANCE', + // Window + 'CUME_DIST', + 'DENSE_RANK', + 'FIRST_VALUE', + 'LAG', + 'LAST_VALUE', + 'LEAD', + 'NTH_VALUE', + 'NTILE', + 'PERCENT_RANK', + 'RANK', + 'ROW_NUMBER', + // Date / time + 'DATE_ADD', + 'DATE_DIFF', + 'DATE_PART', + 'DATE_SUB', + 'DATE_TRUNC', + 'DATEDIFF', + 'DAY', + 'DAYOFWEEK', + 'DAYOFYEAR', + 'EPOCH', + 'EPOCH_MS', + 'EPOCH_NS', + 'EPOCH_US', + 'EXTRACT', + 'HOUR', + 'LAST_DAY', + 'MAKE_DATE', + 'MAKE_TIMESTAMP', + 'MINUTE', + 'MONTH', + 'QUARTER', + 'SECOND', + 'STRFTIME', + 'STRPTIME', + 'TIME_BUCKET', + 'WEEK', + 'YEAR', + // String & pure JSON + 'CONCAT', + 'CONCAT_WS', + 'CONTAINS', + 'ENDS_WITH', + 'JSON_EXTRACT', + 'JSON_EXTRACT_PATH', + 'JSON_EXTRACT_PATH_TEXT', + 'JSON_EXTRACT_STRING', + 'LEFT', + 'LENGTH', + 'LOWER', + 'LTRIM', + 'POSITION', + 'RIGHT', + 'RTRIM', + 'SPLIT_PART', + 'STARTS_WITH', + 'STRLEN', + 'STRPOS', + 'SUBSTR', + 'SUBSTRING', + 'TRIM', + 'UPPER', +]); + +/** SQL keywords that can syntactically precede `(` without being a function call. */ +const KEYWORD_BEFORE_LPAREN: ReadonlySet = new Set([ + 'ALL', + 'AND', + 'ANY', + 'AS', + 'ASC', + 'BETWEEN', + 'BY', + 'CASE', + 'DESC', + 'DISTINCT', + 'ELSE', + 'EXISTS', + 'FILTER', + 'FIRST', + 'FROM', + 'HAVING', + 'IN', + 'IS', + 'JOIN', + 'LAST', + 'NOT', + 'NULLS', + 'ON', + 'OR', + 'ORDER', + 'OVER', + 'PARTITION', + 'QUALIFY', + 'SELECT', + 'SOME', + 'THEN', + 'USING', + 'VALUES', + 'WHEN', + 'WHERE', + 'WITHIN', +]); + +const CLAUSE_TERMINATOR_KEYWORDS: ReadonlySet = new Set([ + 'EXCEPT', + 'FETCH', + 'FROM', + 'GROUP', + 'HAVING', + 'INTERSECT', + 'LIMIT', + 'OFFSET', + 'ORDER', + 'QUALIFY', + 'UNION', + 'WHERE', + 'WINDOW', +]); + +const JOIN_MODIFIER_KEYWORDS: ReadonlySet = new Set([ + 'ANTI', + 'ASOF', + 'CROSS', + 'FULL', + 'INNER', + 'JOIN', + 'LEFT', + 'NATURAL', + 'OUTER', + 'RIGHT', + 'SEMI', +]); + +const NON_ALIAS_KEYWORDS: ReadonlySet = new Set([ + ...CLAUSE_TERMINATOR_KEYWORDS, + ...JOIN_MODIFIER_KEYWORDS, + 'ON', + 'USING', +]); + +const PATH_OR_URI_PREFIX_RE = /^(?:\/|\.\/|\.\.\/|~\/|(?:s3|gs|http|https|file|hf|az|r2):\/\/)/i; +const PATH_EXTENSION_RE = /\.(?:parquet|csv|tsv|json|jsonl|ndjson|duckdb|db|sqlite|txt|gz|zst)$/i; +const PATH_GLOB_OR_TRAVERSAL_RE = /(?:^|\/)\.\.(?:\/|$)|\/\*|\*\./; + +type SqlToken = + | { readonly kind: 'word'; readonly value: string; readonly upper: string; readonly raw: string } + | { readonly kind: 'quoted_ident'; readonly value: string; readonly raw: string } + | { readonly kind: 'string'; readonly value: string; readonly raw: string } + | { readonly kind: 'number'; readonly raw: string } + | { readonly kind: 'placeholder'; readonly dataset: string; readonly raw: string } + | { readonly kind: 'lparen'; readonly raw: '(' } + | { readonly kind: 'rparen'; readonly raw: ')' } + | { readonly kind: 'comma'; readonly raw: ',' } + | { readonly kind: 'dot'; readonly raw: '.' } + | { readonly kind: 'op'; readonly raw: string }; + +interface DatasetScanSpec { + readonly relativePath: string; + readonly hivePartitioning: boolean; + readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at'; +} + +const DATASET_SCAN_SPECS: Readonly> = { + bars_1d: { + relativePath: 'bars_1d/year=*/part.parquet', + hivePartitioning: true, + predicateKind: 'ts_and_known_at', + }, + adj_factors: { + relativePath: 'adj_factors/part.parquet', + hivePartitioning: false, + predicateKind: 'known_at', + }, + events: { + relativePath: 'events/year=*/part.parquet', + hivePartitioning: true, + predicateKind: 'ts_and_known_at', + }, + shorts: { + relativePath: 'shorts/part.parquet', + hivePartitioning: false, + predicateKind: 'known_at', + }, + fx_1d: { + relativePath: 'fx_1d/part.parquet', + hivePartitioning: false, + predicateKind: 'ts_and_known_at', + }, + fundamentals_pit: { + relativePath: 'fundamentals_pit/year=*/part.parquet', + hivePartitioning: true, + predicateKind: 'effective_known_at', + }, +}; + +function isPlainRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function compareAscii(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c; +} + +function isIdentStart(code: number): boolean { + return ( + (code >= 0x41 && code <= 0x5a) || // A-Z + (code >= 0x61 && code <= 0x7a) || // a-z + code === 0x5f // _ + ); +} + +function isIdentContinue(code: number): boolean { + return isIdentStart(code) || (code >= 0x30 && code <= 0x39); +} + +function isDigit(code: number): boolean { + return code >= 0x30 && code <= 0x39; +} + +function looksLikeExternalPath(value: string): boolean { + return ( + PATH_OR_URI_PREFIX_RE.test(value) || + PATH_EXTENSION_RE.test(value) || + PATH_GLOB_OR_TRAVERSAL_RE.test(value) + ); +} + +/** + * Quote-aware SQL tokenizer shared by validation, canonical hashing, and + * `{{input:}}` placeholder expansion. + */ +function tokenizeFeatureSql(sql: string): SqlToken[] { + const tokens: SqlToken[] = []; + const len = sql.length; + let i = 0; + + while (i < len) { + const code = sql.charCodeAt(i); + if (isAsciiWhitespace(code)) { + i += 1; + continue; + } + + // Reject SQL comments (-- or /* ... */). + if (code === 0x2d && i + 1 < len && sql.charCodeAt(i + 1) === 0x2d) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'SQL line comments ("--") are not permitted in feature definitions.' + ); + } + if (code === 0x2f && i + 1 < len && sql.charCodeAt(i + 1) === 0x2a) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'SQL block comments ("/* ... */") are not permitted in feature definitions.' + ); + } + if (code === 0x2a && i + 1 < len && sql.charCodeAt(i + 1) === 0x2f) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unexpected SQL block comment terminator ("*/") in feature definition.' + ); + } + + // Reject statement separators (;). + if (code === 0x3b) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Multiple SQL statements or semicolons (";") are not permitted in feature definitions.' + ); + } + + // Reject caller-supplied bind markers (?, $1, $name, :name). + if (code === 0x3f) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Caller-supplied bind markers ("?") are not permitted in feature definitions.' + ); + } + if (code === 0x24) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Dollar-prefixed parameters or dollar-quoted strings ("$") are not permitted in feature definitions.' + ); + } + + // Placeholder: {{input:}} + if (code === 0x7b && i + 1 < len && sql.charCodeAt(i + 1) === 0x7b) { + const closeIdx = sql.indexOf('}}', i + 2); + if (closeIdx === -1) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unterminated placeholder "{{" in feature SQL.' + ); + } + const inner = sql.slice(i + 2, closeIdx); + const match = PLACEHOLDER_INNER_RE.exec(inner); + if (match === null) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Malformed input placeholder "{{${inner}}}". Expected "{{input:}}".` + ); + } + const dataset = match[1] as string; + const raw = sql.slice(i, closeIdx + 2); + tokens.push({ kind: 'placeholder', dataset, raw }); + i = closeIdx + 2; + continue; + } + + // Single-quoted string literal ('...'). + if (code === 0x27) { + const start = i; + i += 1; + let value = ''; + let closed = false; + while (i < len) { + const c = sql.charCodeAt(i); + if (c === 0x27) { + if (i + 1 < len && sql.charCodeAt(i + 1) === 0x27) { + value += "'"; + i += 2; + continue; + } + i += 1; + closed = true; + break; + } + value += sql[i] as string; + i += 1; + } + if (!closed) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unterminated single-quoted string literal in feature SQL.' + ); + } + tokens.push({ kind: 'string', value, raw: sql.slice(start, i) }); + continue; + } + + // Double-quoted identifier ("..."). + if (code === 0x22) { + const start = i; + i += 1; + let value = ''; + let closed = false; + while (i < len) { + const c = sql.charCodeAt(i); + if (c === 0x22) { + if (i + 1 < len && sql.charCodeAt(i + 1) === 0x22) { + value += '"'; + i += 2; + continue; + } + i += 1; + closed = true; + break; + } + value += sql[i] as string; + i += 1; + } + if (!closed || value.length === 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unterminated or empty double-quoted identifier in feature SQL.' + ); + } + tokens.push({ kind: 'quoted_ident', value, raw: sql.slice(start, i) }); + continue; + } + + // Unquoted word (keyword or identifier). + if (isIdentStart(code)) { + const start = i; + i += 1; + while (i < len && isIdentContinue(sql.charCodeAt(i))) { + i += 1; + } + const value = sql.slice(start, i); + tokens.push({ kind: 'word', value, upper: value.toUpperCase(), raw: value }); + continue; + } + + // Numeric literal (digits or .digits). + if (isDigit(code) || (code === 0x2e && i + 1 < len && isDigit(sql.charCodeAt(i + 1)))) { + const start = i; + let hasDot = false; + if (code === 0x2e) { + hasDot = true; + i += 1; + } + while (i < len && isDigit(sql.charCodeAt(i))) { + i += 1; + } + if (!hasDot && i < len && sql.charCodeAt(i) === 0x2e) { + i += 1; + while (i < len && isDigit(sql.charCodeAt(i))) { + i += 1; + } + } + if (i < len && (sql.charCodeAt(i) === 0x65 || sql.charCodeAt(i) === 0x45)) { + const expPos = i; + i += 1; + if (i < len && (sql.charCodeAt(i) === 0x2b || sql.charCodeAt(i) === 0x2d)) { + i += 1; + } + if (i >= len || !isDigit(sql.charCodeAt(i))) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Malformed numeric exponent at offset ${expPos} in feature SQL.` + ); + } + while (i < len && isDigit(sql.charCodeAt(i))) { + i += 1; + } + } + tokens.push({ kind: 'number', raw: sql.slice(start, i) }); + continue; + } + + // Punctuation. + if (code === 0x28) { + tokens.push({ kind: 'lparen', raw: '(' }); + i += 1; + continue; + } + if (code === 0x29) { + tokens.push({ kind: 'rparen', raw: ')' }); + i += 1; + continue; + } + if (code === 0x2c) { + tokens.push({ kind: 'comma', raw: ',' }); + i += 1; + continue; + } + if (code === 0x2e) { + tokens.push({ kind: 'dot', raw: '.' }); + i += 1; + continue; + } + + // Two-character operators. + if (i + 1 < len) { + const two = sql.slice(i, i + 2); + if ( + two === '<>' || + two === '!=' || + two === '<=' || + two === '>=' || + two === '||' || + two === '::' + ) { + tokens.push({ kind: 'op', raw: two }); + i += 2; + continue; + } + } + + // Reject single ':' (named bind marker). + if (code === 0x3a) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Colon-prefixed bind markers (":name") are not permitted in feature definitions.' + ); + } + + // Single-character operators. + if ( + code === 0x2b || // + + code === 0x2d || // - + code === 0x2a || // * + code === 0x2f || // / + code === 0x25 || // % + code === 0x3d || // = + code === 0x3c || // < + code === 0x3e // > + ) { + tokens.push({ kind: 'op', raw: sql[i] as string }); + i += 1; + continue; + } + + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Unsupported token character "${sql[i] as string}" at offset ${i} in feature SQL.` + ); + } + + return tokens; +} + +function findMatchingParen(tokens: readonly SqlToken[], openIndex: number, end: number): number { + let depth = 0; + for (let i = openIndex; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + if (depth === 0) { + return i; + } + } + } + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unbalanced parentheses in feature SQL.' + ); +} + +function assertBalancedParens(tokens: readonly SqlToken[]): void { + let depth = 0; + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + if (depth < 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unbalanced closing parenthesis ")" in feature SQL.' + ); + } + } + } + if (depth !== 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Unbalanced opening parenthesis "(" in feature SQL.' + ); + } +} + +function extractIdentifierText(tok: SqlToken | undefined): string | null { + if (tok === undefined) { + return null; + } + if (tok.kind === 'word') { + return tok.value.toLowerCase(); + } + if (tok.kind === 'quoted_ident') { + return tok.value; + } + return null; +} + +function extractProjectionOutputName(tokens: readonly SqlToken[], start: number, end: number): string { + if (start >= end) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Empty projection expression in final SELECT list.' + ); + } + + // Reject wildcard projections (* or alias.*) at top level of the projection item. + let depth = 0; + for (let i = start; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if (depth === 0 && tok.kind === 'op' && tok.raw === '*') { + const prev = i > start ? tokens[i - 1] : undefined; + if (prev === undefined || prev.kind === 'dot') { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Wildcard projections ("*" / "alias.*") are not permitted; final SELECT must explicitly project listing_id, ts, known_at, value.' + ); + } + } + } + + // Case 1: explicit `... AS ` at top level. + if (end - start >= 3) { + const asTok = tokens[end - 2]; + const aliasTok = tokens[end - 1]; + if (asTok?.kind === 'word' && asTok.upper === 'AS') { + const alias = extractIdentifierText(aliasTok); + if (alias === null) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Expected an output column identifier after AS in final SELECT projection.' + ); + } + return alias; + } + } + + // Case 2: simple column reference `` or `.`. + if (end - start === 1) { + const name = extractIdentifierText(tokens[start]); + if (name !== null) { + return name; + } + } + if (end - start === 3 && tokens[start + 1]?.kind === 'dot') { + const qual = extractIdentifierText(tokens[start]); + const col = extractIdentifierText(tokens[start + 2]); + if (qual !== null && col !== null) { + return col; + } + } + + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'Every expression in the final SELECT list must be a direct column reference or use an explicit AS alias matching (listing_id, ts, known_at, value).' + ); +} + +function validateExpressionSlice( + tokens: readonly SqlToken[], + start: number, + end: number, + inScopeCtes: ReadonlySet +): void { + let i = start; + while (i < end) { + const tok = tokens[i] as SqlToken; + + // Nested subquery: (SELECT ...) or (WITH ...) + if (tok.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, i, end); + const innerFirst = tokens[i + 1]; + if ( + innerFirst?.kind === 'word' && + (innerFirst.upper === 'SELECT' || innerFirst.upper === 'WITH') + ) { + validateQuerySlice(tokens, i + 1, closeIdx, inScopeCtes, false); + i = closeIdx + 1; + continue; + } + i += 1; + continue; + } + + // Callable function check: followed by '('. + if ( + (tok.kind === 'word' || tok.kind === 'quoted_ident') && + i + 1 < end && + tokens[i + 1]?.kind === 'lparen' + ) { + const upper = tok.kind === 'word' ? tok.upper : tok.value.toUpperCase(); + if (tok.kind === 'word' && KEYWORD_BEFORE_LPAREN.has(upper)) { + i += 1; + continue; + } + // Reject schema-qualified function calls (e.g. main.read_parquet(...)). + if (i > start && tokens[i - 1]?.kind === 'dot') { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Schema-qualified function call ".${tok.raw}(...)" is not permitted in feature SQL.` + ); + } + if (!ALLOWED_SQL_FUNCTIONS.has(upper)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Unsupported or prohibited SQL function "${tok.raw}(...)" in feature SQL.` + ); + } + } + + i += 1; + } +} + +function parseTableReference( + tokens: readonly SqlToken[], + start: number, + end: number, + inScopeCtes: ReadonlySet +): number { + if (start >= end) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Expected a relation source after FROM or JOIN in feature SQL.' + ); + } + + let pos = start; + const tok = tokens[pos] as SqlToken; + + if (tok.kind === 'placeholder') { + pos += 1; + } else if (tok.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, pos, end); + const innerFirst = tokens[pos + 1]; + if ( + innerFirst === undefined || + innerFirst.kind !== 'word' || + (innerFirst.upper !== 'SELECT' && innerFirst.upper !== 'WITH') + ) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + 'Parenthesized relation source must be a SELECT or WITH subquery.' + ); + } + validateQuerySlice(tokens, pos + 1, closeIdx, inScopeCtes, false); + pos = closeIdx + 1; + } else if (tok.kind === 'word' || tok.kind === 'quoted_ident') { + // Reject table functions (`fn(...)`) and qualified catalog relations (`schema.table`). + const next = pos + 1 < end ? tokens[pos + 1] : undefined; + if (next?.kind === 'lparen') { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Table function "${tok.raw}(...)" is not permitted as a relation source in feature SQL.` + ); + } + if (next?.kind === 'dot') { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Catalog or schema-qualified relation "${tok.raw}...." is not permitted; use {{input:}} placeholders.` + ); + } + const cteName = tok.value.toLowerCase(); + if (!inScopeCtes.has(cteName)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Direct table reference "${tok.raw}" is not an in-scope CTE; use {{input:}} placeholders.` + ); + } + pos += 1; + } else { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Unsupported relation source "${tok.raw}" in feature SQL; use {{input:}}, an in-scope CTE, or a subquery.` + ); + } + + // Optional table alias: `[AS] [(col1, col2, ...)]`. + if (pos < end) { + const maybeAs = tokens[pos] as SqlToken; + if (maybeAs.kind === 'word' && maybeAs.upper === 'AS') { + pos += 1; + if (pos >= end || (tokens[pos]?.kind !== 'word' && tokens[pos]?.kind !== 'quoted_ident')) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Expected table alias identifier after AS.' + ); + } + pos += 1; + } else if ( + (maybeAs.kind === 'word' && !NON_ALIAS_KEYWORDS.has(maybeAs.upper)) || + maybeAs.kind === 'quoted_ident' + ) { + pos += 1; + } + + // Optional column alias list `(c1, c2)`. + if (pos < end && tokens[pos]?.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, pos, end); + pos = closeIdx + 1; + } + } + + return pos; +} + +function validateSelectBranch( + tokens: readonly SqlToken[], + start: number, + end: number, + inScopeCtes: ReadonlySet, + requireContractProjection: boolean +): void { + if (start >= end) { + throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SELECT branch in feature SQL.'); + } + + // Parenthesized SELECT branch: `(SELECT ...)` + if (tokens[start]?.kind === 'lparen') { + const closeIdx = findMatchingParen(tokens, start, end); + if (closeIdx === end - 1) { + validateQuerySlice(tokens, start + 1, closeIdx, inScopeCtes, requireContractProjection); + return; + } + } + + const first = tokens[start]; + if (first?.kind !== 'word' || first.upper !== 'SELECT') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Expected SELECT statement, got "${first?.raw ?? ''}".` + ); + } + + let pos = start + 1; + if ( + pos < end && + tokens[pos]?.kind === 'word' && + ((tokens[pos] as { upper: string }).upper === 'DISTINCT' || + (tokens[pos] as { upper: string }).upper === 'ALL') + ) { + pos += 1; + } + + // Find end of SELECT projection list (first top-level FROM or other clause terminator). + let depth = 0; + let projEnd = end; + for (let i = pos; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if (depth === 0 && tok.kind === 'word' && CLAUSE_TERMINATOR_KEYWORDS.has(tok.upper)) { + projEnd = i; + break; + } + } + + if (projEnd === pos) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + 'SELECT clause has an empty projection list.' + ); + } + + // Validate expressions inside projection list. + validateExpressionSlice(tokens, pos, projEnd, inScopeCtes); + + if (requireContractProjection) { + const itemBounds: Array<{ start: number; end: number }> = []; + let itemStart = pos; + depth = 0; + for (let i = pos; i < projEnd; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if (depth === 0 && tok.kind === 'comma') { + itemBounds.push({ start: itemStart, end: i }); + itemStart = i + 1; + } + } + itemBounds.push({ start: itemStart, end: projEnd }); + + if (itemBounds.length !== FEATURE_OUTPUT_COLUMNS.length) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + `Final SELECT must project exactly ${FEATURE_OUTPUT_COLUMNS.length} columns (${FEATURE_OUTPUT_COLUMNS.join(', ')}), got ${itemBounds.length}.` + ); + } + + for (let idx = 0; idx < FEATURE_OUTPUT_COLUMNS.length; idx += 1) { + const bound = itemBounds[idx] as { start: number; end: number }; + const actualName = extractProjectionOutputName(tokens, bound.start, bound.end); + const expectedName = FEATURE_OUTPUT_COLUMNS[idx] as string; + if (actualName !== expectedName) { + throw new FeatureLibraryError( + 'INVALID_SQL_PROJECTION', + `Final SELECT column #${idx + 1} must be named "${expectedName}", got "${actualName}".` + ); + } + } + } + + // Scan FROM / JOIN clauses and remaining clauses at paren depth 0. + pos = projEnd; + while (pos < end) { + const tok = tokens[pos] as SqlToken; + + if (tok.kind === 'word' && tok.upper === 'FROM') { + pos += 1; + // Parse one or more comma-separated table references, plus any chained JOINs. + pos = parseTableReference(tokens, pos, end, inScopeCtes); + while (pos < end) { + const nextTok = tokens[pos] as SqlToken; + if (nextTok.kind === 'comma') { + pos += 1; + pos = parseTableReference(tokens, pos, end, inScopeCtes); + continue; + } + if (nextTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(nextTok.upper)) { + // Consume join modifiers up to and including JOIN. + let foundJoin = false; + while (pos < end) { + const jTok = tokens[pos] as SqlToken; + if (jTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(jTok.upper)) { + pos += 1; + if (jTok.upper === 'JOIN') { + foundJoin = true; + break; + } + } else { + break; + } + } + if (!foundJoin) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Malformed JOIN clause in feature SQL.' + ); + } + pos = parseTableReference(tokens, pos, end, inScopeCtes); + + // Optional ON or USING (...) before next JOIN or clause terminator. + if (pos < end && tokens[pos]?.kind === 'word') { + const condKw = (tokens[pos] as { upper: string }).upper; + if (condKw === 'ON' || condKw === 'USING') { + const condStart = pos + 1; + let condEnd = end; + let cDepth = 0; + for (let k = condStart; k < end; k += 1) { + const ct = tokens[k] as SqlToken; + if (ct.kind === 'lparen') { + cDepth += 1; + } else if (ct.kind === 'rparen') { + cDepth -= 1; + } else if ( + cDepth === 0 && + (ct.kind === 'comma' || + (ct.kind === 'word' && + (CLAUSE_TERMINATOR_KEYWORDS.has(ct.upper) || + JOIN_MODIFIER_KEYWORDS.has(ct.upper)))) + ) { + condEnd = k; + break; + } + } + validateExpressionSlice(tokens, condStart, condEnd, inScopeCtes); + pos = condEnd; + } + } + continue; + } + break; + } + continue; + } + + // Remaining clause expressions (WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, ORDER BY, LIMIT, OFFSET). + const exprStart = pos; + let exprEnd = end; + let eDepth = 0; + for (let k = exprStart + 1; k < end; k += 1) { + const et = tokens[k] as SqlToken; + if (et.kind === 'lparen') { + eDepth += 1; + } else if (et.kind === 'rparen') { + eDepth -= 1; + } else if (eDepth === 0 && et.kind === 'word' && et.upper === 'FROM') { + exprEnd = k; + break; + } + } + validateExpressionSlice(tokens, exprStart, exprEnd, inScopeCtes); + pos = exprEnd; + } +} + +function validateQuerySlice( + tokens: readonly SqlToken[], + start: number, + end: number, + outerCtes: ReadonlySet, + requireContractProjection: boolean +): void { + if (start >= end) { + throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SQL query in feature definition.'); + } + + const inScopeCtes = new Set(outerCtes); + let pos = start; + + // Optional leading WITH clause. + if (tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'WITH') { + pos += 1; + let isRecursive = false; + if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'RECURSIVE') { + isRecursive = true; + pos += 1; + } + + while (pos < end) { + const nameTok = tokens[pos]; + if (nameTok === undefined || (nameTok.kind !== 'word' && nameTok.kind !== 'quoted_ident')) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Expected CTE name identifier after WITH in feature SQL.' + ); + } + const cteName = nameTok.value.toLowerCase(); + pos += 1; + + // Optional CTE column list `(col1, col2)`. + if (pos < end && tokens[pos]?.kind === 'lparen') { + pos = findMatchingParen(tokens, pos, end) + 1; + } + + if (pos >= end || tokens[pos]?.kind !== 'word' || (tokens[pos] as { upper: string }).upper !== 'AS') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Expected AS after CTE name "${nameTok.raw}" in feature SQL.` + ); + } + pos += 1; + + // Optional `[NOT] MATERIALIZED`. + if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'NOT') { + pos += 1; + } + if ( + pos < end && + tokens[pos]?.kind === 'word' && + (tokens[pos] as { upper: string }).upper === 'MATERIALIZED' + ) { + pos += 1; + } + + if (pos >= end || tokens[pos]?.kind !== 'lparen') { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Expected "(" opening CTE body for "${nameTok.raw}" in feature SQL.` + ); + } + const bodyClose = findMatchingParen(tokens, pos, end); + if (isRecursive) { + inScopeCtes.add(cteName); + } + validateQuerySlice(tokens, pos + 1, bodyClose, inScopeCtes, false); + inScopeCtes.add(cteName); + pos = bodyClose + 1; + + if (pos < end && tokens[pos]?.kind === 'comma') { + pos += 1; + continue; + } + break; + } + } + + // Split remaining query by top-level set operators (UNION [ALL|DISTINCT], INTERSECT, EXCEPT). + const branches: Array<{ start: number; end: number }> = []; + let branchStart = pos; + let depth = 0; + for (let i = pos; i < end; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'lparen') { + depth += 1; + } else if (tok.kind === 'rparen') { + depth -= 1; + } else if ( + depth === 0 && + tok.kind === 'word' && + (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') + ) { + branches.push({ start: branchStart, end: i }); + let nextPos = i + 1; + if ( + nextPos < end && + tokens[nextPos]?.kind === 'word' && + ((tokens[nextPos] as { upper: string }).upper === 'ALL' || + (tokens[nextPos] as { upper: string }).upper === 'DISTINCT') + ) { + nextPos += 1; + } + branchStart = nextPos; + i = nextPos - 1; + } + } + branches.push({ start: branchStart, end }); + + for (let b = 0; b < branches.length; b += 1) { + const branch = branches[b] as { start: number; end: number }; + validateSelectBranch(tokens, branch.start, branch.end, inScopeCtes, requireContractProjection); + } +} + +interface ValidatedFeatureInternal { + readonly def: FeatureDefinition; + readonly tokens: readonly SqlToken[]; + readonly normalizedInputs: readonly FeatureInputDataset[]; +} + +function validateName(name: unknown): string { + if (typeof name !== 'string' || !FEATURE_NAME_RE.test(name)) { + throw new FeatureLibraryError( + 'INVALID_NAME', + `Invalid feature name "${String(name)}". Expected ^[a-z][a-z0-9_]{0,62}$.` + ); + } + return name; +} + +function validateVersion(version: unknown): number { + if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) { + throw new FeatureLibraryError( + 'INVALID_VERSION', + `Invalid feature version "${String(version)}". Expected a positive safe integer.` + ); + } + return version; +} + +function validateFeatureDefinitionInternal(def: FeatureDefinition): ValidatedFeatureInternal { + if (!isPlainRecord(def)) { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Feature definition must be a plain object.' + ); + } + + validateName(def.name); + validateVersion(def.version); + + if (typeof def.family !== 'string' || !FEATURE_FAMILY_SET.has(def.family)) { + throw new FeatureLibraryError( + 'INVALID_FAMILY', + `Invalid feature family "${String(def.family)}". Expected one of: ${FEATURE_FAMILIES.join(', ')}.` + ); + } + + if (def.kind !== 'duckdb_sql') { + throw new FeatureLibraryError( + 'INVALID_KIND', + `Invalid feature kind "${String(def.kind)}". Expected 'duckdb_sql'.` + ); + } + + if (typeof def.warmupBars !== 'number' || !Number.isSafeInteger(def.warmupBars) || def.warmupBars < 0) { + throw new FeatureLibraryError( + 'INVALID_WARMUP_BARS', + `Invalid warmupBars "${String(def.warmupBars)}". Expected a non-negative safe integer.` + ); + } + + if (typeof def.knownAtRule !== 'string' || !FEATURE_KNOWN_AT_RULE_SET.has(def.knownAtRule)) { + throw new FeatureLibraryError( + 'INVALID_KNOWN_AT_RULE', + `Invalid knownAtRule "${String(def.knownAtRule)}". Expected one of: ${FEATURE_KNOWN_AT_RULES.join(', ')}.` + ); + } + + if (def.description !== undefined && typeof def.description !== 'string') { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Feature description must be a string when provided.' + ); + } + + if (!Array.isArray(def.inputs) || def.inputs.length === 0) { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Feature definition must declare a non-empty inputs array.' + ); + } + + const declaredSet = new Set(); + const normalizedInputs: FeatureInputDataset[] = []; + for (let i = 0; i < def.inputs.length; i += 1) { + const rawInput: unknown = def.inputs[i]; + if (typeof rawInput !== 'string' || !FEATURE_INPUT_SET.has(rawInput)) { + throw new FeatureLibraryError( + 'UNSUPPORTED_INPUT_DATASET', + `Unsupported input dataset "${String(rawInput)}". Allowed datasets: ${FEATURE_INPUT_DATASETS.join(', ')}.` + ); + } + const ds = rawInput as FeatureInputDataset; + if (!declaredSet.has(ds)) { + declaredSet.add(ds); + normalizedInputs.push(ds); + } + } + + if (typeof def.sql !== 'string' || def.sql.trim().length === 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Feature SQL must be a non-empty string.' + ); + } + + const tokens = tokenizeFeatureSql(def.sql); + if (tokens.length === 0) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + 'Feature SQL must contain a SELECT or WITH statement.' + ); + } + + // Pass 1: check prohibited statement/operation keywords. + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'word' && PROHIBITED_SQL_KEYWORDS.has(tok.upper)) { + throw new FeatureLibraryError( + 'PROHIBITED_SQL_OPERATION', + `Prohibited SQL operation "${tok.raw}" is not permitted in feature definitions.` + ); + } + } + + // Pass 2: check external readers and quoted file paths/URIs. + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'word' && EXTERNAL_READER_IDENTIFIERS.has(tok.upper)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Direct external reader "${tok.raw}" is not permitted; reference datasets via {{input:}}.` + ); + } + if (tok.kind === 'quoted_ident' && EXTERNAL_READER_IDENTIFIERS.has(tok.value.toUpperCase())) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Direct external reader ${tok.raw} is not permitted; reference datasets via {{input:}}.` + ); + } + if ((tok.kind === 'string' || tok.kind === 'quoted_ident') && looksLikeExternalPath(tok.value)) { + throw new FeatureLibraryError( + 'EXTERNAL_DATA_ACCESS', + `Quoted file path or URI ${tok.raw} is not permitted in feature SQL; reference datasets via {{input:}}.` + ); + } + } + + // Pass 3: check leading statement keyword and balanced parentheses. + const firstTok = tokens[0] as SqlToken; + if (firstTok.kind !== 'word' || (firstTok.upper !== 'SELECT' && firstTok.upper !== 'WITH')) { + throw new FeatureLibraryError( + 'INVALID_SQL_STATEMENT', + `Feature SQL must begin with SELECT or WITH, got "${firstTok.raw}".` + ); + } + assertBalancedParens(tokens); + + // Pass 4: structural validation of CTEs, FROM/JOIN sources, functions, and final projection. + validateQuerySlice(tokens, 0, tokens.length, new Set(), true); + + // Pass 5: verify placeholder declarations and usage. + const usedInputs = new Set(); + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind !== 'placeholder') { + continue; + } + if (!declaredSet.has(tok.dataset as FeatureInputDataset)) { + throw new FeatureLibraryError( + 'UNDECLARED_INPUT', + `SQL placeholder "{{input:${tok.dataset}}}" is not declared in definition.inputs.` + ); + } + usedInputs.add(tok.dataset as FeatureInputDataset); + } + + for (let i = 0; i < normalizedInputs.length; i += 1) { + const declared = normalizedInputs[i] as FeatureInputDataset; + if (!usedInputs.has(declared)) { + throw new FeatureLibraryError( + 'UNUSED_INPUT', + `Declared input dataset "${declared}" is not referenced via "{{input:${declared}}}" in feature SQL.` + ); + } + } + + return { def, tokens, normalizedInputs }; +} + +/** + * Validates a declarative feature definition and throws a typed + * {@link FeatureLibraryError} on any contract, SQL safety, projection, or + * input-declaration violation. + */ +export function validateFeatureDefinition(def: FeatureDefinition): void { + validateFeatureDefinitionInternal(def); +} + +/** + * Formats the canonical versioned feature reference `'@v'`. + */ +export function featureRef(def: Pick): string { + if (!isPlainRecord(def)) { + throw new FeatureLibraryError( + 'INVALID_DEFINITION', + 'Expected an object with name and version for featureRef.' + ); + } + const name = validateName(def.name); + const version = validateVersion(def.version); + return `${name}@v${version}`; +} + +/** + * Parses a canonical versioned feature reference `'@v'`, + * rejecting non-canonical forms such as `'ret_1d@v01'` or `'RSI-14@v1'`. + */ +export function parseFeatureRef(ref: string): FeatureRefParts { + if (typeof ref !== 'string') { + throw new FeatureLibraryError( + 'INVALID_FEATURE_REF', + `Invalid feature ref "${String(ref)}". Expected "@v".` + ); + } + const match = FEATURE_REF_RE.exec(ref); + if (match === null) { + throw new FeatureLibraryError( + 'INVALID_FEATURE_REF', + `Invalid feature ref "${ref}". Expected "@v" with lowercase name and canonical positive integer version.` + ); + } + const name = match[1] as string; + const version = Number(match[2]); + if (!Number.isSafeInteger(version) || version < 1) { + throw new FeatureLibraryError( + 'INVALID_FEATURE_REF', + `Invalid feature version in ref "${ref}". Expected a positive safe integer.` + ); + } + return Object.freeze({ name, version }); +} + +function canonicalizeSqlTokens(tokens: readonly SqlToken[]): string { + const parts = new Array(tokens.length); + for (let i = 0; i < tokens.length; i += 1) { + parts[i] = (tokens[i] as SqlToken).raw; + } + return parts.join(' '); +} + +/** + * Computes a deterministic 64-character lowercase SHA-256 hex digest over the + * semantic specification of a validated feature definition (name, version, + * kind, canonicalized SQL tokens, sorted inputs, `warmupBars`, and + * `knownAtRule`). Inter-token whitespace, object key order, and input array + * order do not affect the hash; literal whitespace and semantic changes do. + */ +export function featureDefinitionHash(def: FeatureDefinition): string { + const validated = validateFeatureDefinitionInternal(def); + const sortedInputs = [...validated.normalizedInputs].sort(compareAscii); + const canonicalPayload = JSON.stringify({ + name: def.name, + version: def.version, + kind: def.kind, + sql: canonicalizeSqlTokens(validated.tokens), + inputs: sortedInputs, + warmupBars: def.warmupBars, + knownAtRule: def.knownAtRule, + }); + return sha256HexUtf8(canonicalPayload); +} + +function cloneFeatureDefinition(def: FeatureDefinition): FeatureDefinition { + const copy: FeatureDefinition = { + name: def.name, + version: def.version, + family: def.family, + kind: def.kind, + sql: def.sql, + inputs: Object.freeze([...def.inputs]), + warmupBars: def.warmupBars, + knownAtRule: def.knownAtRule, + ...(def.description !== undefined ? { description: def.description } : {}), + }; + return Object.freeze(copy); +} + +/** + * Creates an in-memory immutable versioned feature registry (`registerSignal` + * SDK entrypoint, D11). Re-registering an identical definition hash is + * idempotent; re-registering the same `@v` with a different + * semantic hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. + */ +export function createFeatureRegistry(): FeatureRegistry { + const entries = new Map(); + + return { + registerSignal(def: FeatureDefinition): RegisteredFeature { + validateFeatureDefinitionInternal(def); + const ref = featureRef(def); + const definitionHash = featureDefinitionHash(def); + const existing = entries.get(ref); + if (existing !== undefined) { + if (existing.definitionHash === definitionHash) { + return Object.freeze({ + ref: existing.ref, + definitionHash: existing.definitionHash, + definition: cloneFeatureDefinition(existing.definition), + }); + } + throw new FeatureLibraryError( + 'FEATURE_VERSION_IMMUTABLE', + `Feature "${ref}" is already registered with hash ${existing.definitionHash}; cannot overwrite with ${definitionHash}. Bump version to register a changed definition.`, + { ref } + ); + } + + const stored: RegisteredFeature = Object.freeze({ + ref, + definitionHash, + definition: cloneFeatureDefinition(def), + }); + entries.set(ref, stored); + return Object.freeze({ + ref: stored.ref, + definitionHash: stored.definitionHash, + definition: cloneFeatureDefinition(stored.definition), + }); + }, + + get(ref: string): FeatureDefinition | undefined { + if (typeof ref !== 'string') { + return undefined; + } + const existing = entries.get(ref); + return existing !== undefined ? cloneFeatureDefinition(existing.definition) : undefined; + }, + + list(): readonly string[] { + return Array.from(entries.keys()); + }, + }; +} + +function joinCuratedPath(normalizedRoot: string, relativePath: string): string { + return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; +} + +function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { + const isoMs = new Date(epochMs).toISOString(); + if (subMsMicros === 0) { + return isoMs; + } + const extra = String(subMsMicros).padStart(3, '0'); + return `${isoMs.slice(0, -1)}${extra}Z`; +} + +function validateFourDigitYear(value: unknown, field: string): number { + if ( + typeof value !== 'number' || + !Number.isSafeInteger(value) || + value < MIN_FOUR_DIGIT_YEAR || + value > MAX_FOUR_DIGIT_YEAR + ) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid "${field}": "${String(value)}". Expected a four-digit integer year (${MIN_FOUR_DIGIT_YEAR}..${MAX_FOUR_DIGIT_YEAR}).` + ); + } + return value; +} + +function parseVaultCutoffDateMs(raw: unknown): number { + if (typeof raw !== 'string' || !DATE_ONLY_RE.test(raw)) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid "vaultCutoffDate": "${String(raw)}". Expected strict UTC YYYY-MM-DD date string.` + ); + } + try { + const parsed = applyVaultFence( + { from: raw, to: raw, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + return parsed.fromMs; + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid "vaultCutoffDate": ${error.message}`, + { cause: error } + ); + } + throw error; + } +} + +function expandSqlForYear( + tokens: readonly SqlToken[], + curatedRoot: string, + tsUpperIso: string, + knownAtUpperIso: string +): { sql: string; scanParams: DuckDbParam[] } { + const scanParams: DuckDbParam[] = []; + const parts: string[] = []; + + for (let i = 0; i < tokens.length; i += 1) { + const tok = tokens[i] as SqlToken; + if (tok.kind === 'placeholder') { + const ds = tok.dataset as FeatureInputDataset; + const spec = DATASET_SCAN_SPECS[ds]; + const fullPath = joinCuratedPath(curatedRoot, spec.relativePath); + const readCall = spec.hivePartitioning + ? `read_parquet('${fullPath}', hive_partitioning = true)` + : `read_parquet('${fullPath}')`; + + if (spec.predicateKind === 'ts_and_known_at') { + parts.push(`(SELECT * FROM ${readCall} WHERE ts <= ? AND known_at <= ?)`); + scanParams.push(tsUpperIso, knownAtUpperIso); + } else if (spec.predicateKind === 'effective_known_at') { + parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`); + scanParams.push(knownAtUpperIso); + } else { + parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`); + scanParams.push(knownAtUpperIso); + } + continue; + } + + parts.push(tok.raw); + } + + return { + sql: parts.join(' '), + scanParams, + }; +} + +/** + * Plans ordered yearly Vault-fenced DuckDB `COPY ... TO ... (FORMAT PARQUET, + * COMPRESSION ZSTD)` statements for a validated feature definition. + */ +export function planFeatureBatch( + def: FeatureDefinition, + options: PlanFeatureBatchOptions +): readonly PlannedFeatureWrite[] { + const validated = validateFeatureDefinitionInternal(def); + + if (!isPlainRecord(options)) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + 'Feature batch options must be a plain object.' + ); + } + + let curatedRoot: string; + try { + curatedRoot = validateCuratedRoot(options.curatedRoot); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); + } + throw error; + } + + const fromYear = validateFourDigitYear(options.fromYear, 'fromYear'); + const toYear = validateFourDigitYear(options.toYear, 'toYear'); + if (fromYear > toYear) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + `Invalid year range: fromYear (${fromYear}) must not exceed toYear (${toYear}).` + ); + } + + const cutoffMs = parseVaultCutoffDateMs(options.vaultCutoffDate); + const rangeFrom = `${String(fromYear).padStart(4, '0')}-01-01`; + const rangeTo = `${String(toYear).padStart(4, '0')}-12-31`; + + let fenced; + try { + fenced = applyVaultFence( + { from: rangeFrom, to: rangeTo, scope: 'vault_fenced' }, + { vaultCutoffTs: cutoffMs } + ); + } catch (error) { + if (error instanceof VaultHoldoutFenceError) { + throw new FeatureLibraryError( + 'VAULT_RANGE_VIOLATION', + `Requested year range [${fromYear}, ${toYear}] falls on or after vaultCutoffDate "${options.vaultCutoffDate}".`, + { cause: error } + ); + } + if (error instanceof MarketDataStoreValidationError) { + throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); + } + throw error; + } + + const lastPlannedYear = Math.min(toYear, new Date(fenced.toMs).getUTCFullYear()); + if (lastPlannedYear < fromYear) { + throw new FeatureLibraryError( + 'VAULT_RANGE_VIOLATION', + `No pre-cutoff years remain in [${fromYear}, ${toYear}] for vaultCutoffDate "${options.vaultCutoffDate}".` + ); + } + + // Last included Parquet microsecond strictly before vaultCutoffDate (00:00:00.000Z). + const vaultCeilingMs = cutoffMs - 1; + const knownAtUpperIso = formatUtcIsoWithMicros(vaultCeilingMs, 999); + + const writes: PlannedFeatureWrite[] = []; + for (let year = fromYear; year <= lastPlannedYear; year += 1) { + const yearEndMs = Date.UTC(year, 11, 31, 23, 59, 59, 999); + const effectiveTsEndMs = Math.min(yearEndMs, vaultCeilingMs); + const tsUpperIso = formatUtcIsoWithMicros(effectiveTsEndMs, 999); + + const { sql: expandedSql, scanParams } = expandSqlForYear( + validated.tokens, + curatedRoot, + tsUpperIso, + knownAtUpperIso + ); + + const outputPath = joinCuratedPath( + curatedRoot, + `features/${def.name}/v${def.version}/year=${year}/part.parquet` + ); + + const sql = + 'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value ' + + `FROM (${expandedSql}) AS __feature_source ` + + 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ' + + `ORDER BY listing_id, ts) TO '${outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`; + + const params: DuckDbParam[] = [...scanParams, year, tsUpperIso, knownAtUpperIso]; + + writes.push( + Object.freeze({ + year, + outputPath, + sql, + params: Object.freeze(params), + }) + ); + } + + return Object.freeze(writes); +} + +/** + * Validates and plans a feature batch upfront, executes each yearly Parquet + * `COPY` sequentially via `executor.query(sql, params)`, and returns a + * manifest. Stops on the first executor failure and throws + * `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, + * `completedYears`, and `completedWrites`. + */ +export async function runFeatureBatch( + def: FeatureDefinition, + options: PlanFeatureBatchOptions, + executor: DuckDbExecutor +): Promise { + if ( + typeof executor !== 'object' || + executor === null || + typeof (executor as { query?: unknown }).query !== 'function' + ) { + throw new FeatureLibraryError( + 'INVALID_BATCH_OPTIONS', + 'Expected a DuckDbExecutor object with a query(sql, params) method.' + ); + } + + const plannedWrites = planFeatureBatch(def, options); + const ref = featureRef(def); + const definitionHash = featureDefinitionHash(def); + const sortedInputs = [...new Set(def.inputs)].sort(compareAscii); + + const completedWrites: FeatureBatchWriteReceipt[] = []; + for (let i = 0; i < plannedWrites.length; i += 1) { + const write = plannedWrites[i] as PlannedFeatureWrite; + try { + await executor.query(write.sql, write.params); + } catch (cause) { + const completedYears = completedWrites.map(w => w.year); + throw new FeatureLibraryError( + 'BATCH_WRITE_FAILED', + `Feature batch write failed for "${ref}" on year ${write.year} (completed years: ${completedYears.length > 0 ? completedYears.join(', ') : 'none'}).`, + { + cause, + failedYear: write.year, + completedYears, + completedWrites, + ref, + } + ); + } + completedWrites.push( + Object.freeze({ + year: write.year, + outputPath: write.outputPath, + }) + ); + } + + return Object.freeze({ + ref, + definitionHash, + knownAtRule: def.knownAtRule, + warmupBars: def.warmupBars, + inputs: Object.freeze(sortedInputs), + writes: Object.freeze(completedWrites), + }); +} + +/** + * Built-in example feature definition (`ret_1d@v1`): 1-day simple raw-close + * return per listing with bar-close availability (`known_at = ts`) and 1-bar + * warm-up. Omits rows without a usable positive prior close. + * + * Comparison baseline: zero return (`0.0`); no execution or transaction cost + * model is included. + */ +export const RET_1D_V1: FeatureDefinition = Object.freeze({ + name: 'ret_1d', + version: 1, + family: 'technical', + kind: 'duckdb_sql', + inputs: Object.freeze(['bars_1d'] as const), + warmupBars: 1, + knownAtRule: 'bar_close', + description: + '1-day simple raw-close return per listing with bar-close availability; comparison baseline is 0 return with no execution or cost model.', + sql: [ + 'WITH lagged AS (', + ' SELECT', + ' listing_id,', + ' ts,', + ' close,', + ' LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close', + ' FROM {{input:bars_1d}}', + ')', + 'SELECT', + ' listing_id,', + ' ts,', + ' ts AS known_at,', + ' (close / prev_close) - 1.0 AS value', + 'FROM lagged', + 'WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0', + ].join('\n'), +}); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 3d57d822..0a9f6987 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -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'; diff --git a/libs/research/src/sha256.ts b/libs/research/src/sha256.ts new file mode 100644 index 00000000..d4c6febc --- /dev/null +++ b/libs/research/src/sha256.ts @@ -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') + ); +} diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts index bc89a636..fedddfbc 100644 --- a/libs/research/src/trial-ledger.ts +++ b/libs/research/src/trial-ledger.ts @@ -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; } diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts new file mode 100644 index 00000000..564cf376 --- /dev/null +++ b/libs/research/test/feature-library.test.ts @@ -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; +}): RecordingFakeExecutor { + const calls: RecordedQuery[] = []; + const runCalls: string[] = []; + + const executor: DuckDbExecutor = { + async run(sql: string): Promise { + runCalls.push(sql); + }, + async query(sql: string, params: readonly DuckDbParam[]): Promise { + 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 { + 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(); + 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); + }); +});