/** * 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', 'POSITIONAL', '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 hasTopLevelSetOperator(tokens: readonly SqlToken[], start: number, end: number): boolean { 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 === 'word' && (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') ) { return true; } } return false; } 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 ...), (WITH ...), or compound subquery ((SELECT ...) UNION ...); // reject DuckDB FROM-first / TABLE subqueries. 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')) || hasTopLevelSetOperator(tokens, i + 1, closeIdx) ) { validateQuerySlice(tokens, i + 1, closeIdx, inScopeCtes, false); i = closeIdx + 1; continue; } if ( innerFirst?.kind === 'word' && (innerFirst.upper === 'FROM' || innerFirst.upper === 'TABLE') ) { throw new FeatureLibraryError( 'INVALID_SQL_STATEMENT', `Unsupported subquery form "(${innerFirst.upper} ...)" in feature SQL; subqueries must begin with SELECT or WITH.` ); } i += 1; continue; } // Fail closed if an unparsed JOIN token appears inside an expression or clause tail. if (tok.kind === 'word' && tok.upper === 'JOIN') { throw new FeatureLibraryError( 'INVALID_SQL_STATEMENT', 'Unexpected JOIN outside a parsed FROM/JOIN clause in feature SQL.' ); } // 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 isJoinClauseStart(tokens: readonly SqlToken[], start: number, end: number): boolean { let pos = start; while (pos < end) { const tok = tokens[pos] as SqlToken; if (tok.kind !== 'word' || !JOIN_MODIFIER_KEYWORDS.has(tok.upper)) { return false; } if (tok.upper === 'JOIN') { return true; } pos += 1; } return false; } 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) || isJoinClauseStart(tokens, k, end)))) ) { condEnd = k; break; } } validateExpressionSlice(tokens, condStart, condEnd, inScopeCtes); pos = condEnd; } } continue; } break; } if (pos < end) { const afterFrom = tokens[pos] as SqlToken; if ( afterFrom.kind !== 'word' || !CLAUSE_TERMINATOR_KEYWORDS.has(afterFrom.upper) || afterFrom.upper === 'FROM' ) { throw new FeatureLibraryError( 'INVALID_SQL_STATEMENT', `Unexpected token "${afterFrom.raw}" after FROM/JOIN clause in feature SQL.` ); } } 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 (non-recursive CTEs only). if (tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'WITH') { pos += 1; if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'RECURSIVE') { throw new FeatureLibraryError( 'INVALID_SQL_STATEMENT', 'WITH RECURSIVE CTEs are not permitted in feature SQL; use non-recursive CTEs.' ); } 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); 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 listing_id, ts, known_at, value ' + 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value ' + `FROM (${expandedSql}) AS __feature_source) AS __feature_typed ` + '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.' ); } validateFeatureDefinitionInternal(def); const snapshot = cloneFeatureDefinition(def); const plannedWrites = planFeatureBatch(snapshot, options); const ref = featureRef(snapshot); const definitionHash = featureDefinitionHash(snapshot); const sortedInputs = [...new Set(snapshot.inputs)].sort(compareAscii); const { knownAtRule, warmupBars } = snapshot; 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, 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'), });