T-139: M2.4a — Versioned Feature Library core: declarative DuckDB SQL feature definitions + registerSignal registry + versioned Parquet batch-plan runner over an injected DuckDbExecutor in libs/research/src/feature-library.ts (pure, no new deps)

This commit is contained in:
Studio 2026-12-01 07:52:40 -05:00
parent 470b0a4bd9
commit d6d6bc8c8b
7 changed files with 3200 additions and 100 deletions

View file

@ -0,0 +1,953 @@
import { describe, expect, it } from 'bun:test';
import {
type DuckDbExecutor,
type DuckDbParam,
FEATURE_FAMILIES,
FEATURE_INPUT_DATASETS,
FEATURE_KINDS,
FEATURE_KNOWN_AT_RULES,
FEATURE_OUTPUT_COLUMNS,
type FeatureDefinition,
FeatureLibraryError,
type FeatureLibraryErrorCode,
RET_1D_V1,
type TableRow,
createFeatureRegistry,
featureDefinitionHash,
featureRef,
parseFeatureRef,
planFeatureBatch,
runFeatureBatch,
validateFeatureDefinition,
} from '@stock-bot/research';
import {
FEATURE_FAMILIES as subpathFeatureFamilies,
FEATURE_INPUT_DATASETS as subpathFeatureInputDatasets,
FEATURE_KINDS as subpathFeatureKinds,
FEATURE_KNOWN_AT_RULES as subpathFeatureKnownAtRules,
FEATURE_OUTPUT_COLUMNS as subpathFeatureOutputColumns,
FeatureLibraryError as SubpathFeatureLibraryError,
RET_1D_V1 as subpathRet1dV1,
createFeatureRegistry as subpathCreateFeatureRegistry,
featureDefinitionHash as subpathFeatureDefinitionHash,
featureRef as subpathFeatureRef,
parseFeatureRef as subpathParseFeatureRef,
planFeatureBatch as subpathPlanFeatureBatch,
runFeatureBatch as subpathRunFeatureBatch,
validateFeatureDefinition as subpathValidateFeatureDefinition,
} from '@stock-bot/research/feature-library';
interface RecordedQuery {
readonly sql: string;
readonly params: readonly DuckDbParam[];
}
interface RecordingFakeExecutor {
readonly executor: DuckDbExecutor;
readonly calls: RecordedQuery[];
readonly runCalls: string[];
}
function createRecordingFakeExecutor(opts?: {
onQuery?: (sql: string, params: readonly DuckDbParam[], callIndex: number) => Promise<void> | void;
}): RecordingFakeExecutor {
const calls: RecordedQuery[] = [];
const runCalls: string[] = [];
const executor: DuckDbExecutor = {
async run(sql: string): Promise<void> {
runCalls.push(sql);
},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
const idx = calls.length;
calls.push({ sql, params: [...params] });
if (opts?.onQuery !== undefined) {
await opts.onQuery(sql, params, idx);
}
return [];
},
};
return { executor, calls, runCalls };
}
function expectFeatureErrorCode(fn: () => unknown, expectedCode: FeatureLibraryErrorCode): FeatureLibraryError {
try {
fn();
} catch (error) {
expect(error).toBeInstanceOf(FeatureLibraryError);
const typed = error as FeatureLibraryError;
expect(typed.code).toBe(expectedCode);
return typed;
}
throw new Error(`Expected FeatureLibraryError(${expectedCode}) to be thrown, but succeeded.`);
}
function makeSimpleDef(overrides: Partial<FeatureDefinition> = {}): FeatureDefinition {
return {
name: 'close_raw',
version: 1,
family: 'technical',
kind: 'duckdb_sql',
inputs: ['bars_1d'],
warmupBars: 0,
knownAtRule: 'bar_close',
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
...overrides,
};
}
describe('feature-library barrel and subpath exports', () => {
it('exposes identical symbols from @stock-bot/research and @stock-bot/research/feature-library', () => {
expect(FEATURE_FAMILIES).toBe(subpathFeatureFamilies);
expect(FEATURE_INPUT_DATASETS).toBe(subpathFeatureInputDatasets);
expect(FEATURE_KINDS).toBe(subpathFeatureKinds);
expect(FEATURE_KNOWN_AT_RULES).toBe(subpathFeatureKnownAtRules);
expect(FEATURE_OUTPUT_COLUMNS).toBe(subpathFeatureOutputColumns);
expect(FeatureLibraryError).toBe(SubpathFeatureLibraryError);
expect(RET_1D_V1).toBe(subpathRet1dV1);
expect(createFeatureRegistry).toBe(subpathCreateFeatureRegistry);
expect(featureDefinitionHash).toBe(subpathFeatureDefinitionHash);
expect(featureRef).toBe(subpathFeatureRef);
expect(parseFeatureRef).toBe(subpathParseFeatureRef);
expect(planFeatureBatch).toBe(subpathPlanFeatureBatch);
expect(runFeatureBatch).toBe(subpathRunFeatureBatch);
expect(validateFeatureDefinition).toBe(subpathValidateFeatureDefinition);
});
});
describe('featureRef and parseFeatureRef', () => {
it('round-trips canonical refs such as ret_1d@v1', () => {
const ref = featureRef(RET_1D_V1);
expect(ref).toBe('ret_1d@v1');
expect(parseFeatureRef(ref)).toEqual({ name: 'ret_1d', version: 1 });
expect(parseFeatureRef('rsi_14@v12')).toEqual({ name: 'rsi_14', version: 12 });
});
it('rejects malformed, non-canonical, and unsafe refs', () => {
const invalidRefs = [
'',
'ret_1d',
'ret_1d@1',
'ret_1d@v0',
'ret_1d@v01',
'ret_1d@v-1',
'ret_1d@v1.5',
'RSI-14@v1',
'1abc@v1',
`${'a'.repeat(64)}@v1`,
'ret_1d@v9007199254740992',
];
for (const bad of invalidRefs) {
expectFeatureErrorCode(() => parseFeatureRef(bad), 'INVALID_FEATURE_REF');
}
expectFeatureErrorCode(() => parseFeatureRef(null as unknown as string), 'INVALID_FEATURE_REF');
expectFeatureErrorCode(() => featureRef({ name: 'RSI-14', version: 1 }), 'INVALID_NAME');
expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 0 }), 'INVALID_VERSION');
expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 1.5 }), 'INVALID_VERSION');
expectFeatureErrorCode(
() => featureRef({ name: 'ret_1d', version: Number.MAX_SAFE_INTEGER + 1 }),
'INVALID_VERSION'
);
});
});
describe('validateFeatureDefinition', () => {
it('accepts RET_1D_V1, CTE + window expressions, subqueries, and multi-input joins', () => {
expect(() => validateFeatureDefinition(RET_1D_V1)).not.toThrow();
const joinedDef: FeatureDefinition = {
name: 'cad_scaled_close',
version: 1,
family: 'fx',
kind: 'duckdb_sql',
inputs: ['bars_1d', 'fx_1d'],
warmupBars: 0,
knownAtRule: 'max_input_known_at',
sql: `
WITH base AS (
SELECT b.listing_id, b.ts, b.session_date, b.close, b.known_at
FROM {{input:bars_1d}} AS b
)
SELECT
base.listing_id,
base.ts,
GREATEST(base.known_at, f.known_at) AS known_at,
base.close / f.close AS value
FROM base
INNER JOIN (
SELECT session_date, close, known_at
FROM {{input:fx_1d}}
WHERE pair = 'USDCAD'
) AS f ON base.session_date = f.session_date
`,
};
expect(() => validateFeatureDefinition(joinedDef)).not.toThrow();
});
it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => {
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: 'RSI-14' })), 'INVALID_NAME');
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '' })), 'INVALID_NAME');
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '1ret' })), 'INVALID_NAME');
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ name: 'a'.repeat(64) })),
'INVALID_NAME'
);
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 0 })), 'INVALID_VERSION');
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: -2 })), 'INVALID_VERSION');
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 1.5 })), 'INVALID_VERSION');
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ version: Number.NaN })),
'INVALID_VERSION'
);
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ family: 'macro' as FeatureDefinition['family'] })),
'INVALID_FAMILY'
);
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ kind: 'polars' as FeatureDefinition['kind'] })),
'INVALID_KIND'
);
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ warmupBars: -1 })),
'INVALID_WARMUP_BARS'
);
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ warmupBars: 0.5 })),
'INVALID_WARMUP_BARS'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({ knownAtRule: 'end_of_month' as FeatureDefinition['knownAtRule'] })
),
'INVALID_KNOWN_AT_RULE'
);
});
it('rejects empty SQL, semicolons/multi-statement SQL, comments, bind markers, and malformed placeholders', () => {
expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ sql: ' ' })), 'INVALID_SQL_STATEMENT');
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; SELECT 1',
})
),
'INVALID_SQL_STATEMENT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment',
})
),
'INVALID_SQL_STATEMENT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: '/* block */ SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
})
),
'INVALID_SQL_STATEMENT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > ?',
})
),
'INVALID_SQL_STATEMENT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > $1',
})
),
'INVALID_SQL_STATEMENT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > :min_close',
})
),
'INVALID_SQL_STATEMENT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{bad:bars_1d}}',
})
),
'INVALID_SQL_STATEMENT'
);
});
it('rejects prohibited DDL/DML/admin SQL commands with PROHIBITED_SQL_OPERATION', () => {
const prohibitedSqls = [
"COPY (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) TO '/tmp/out.parquet'",
"ATTACH '/tmp/evil.db' AS evil",
'INSERT INTO t VALUES (1)',
'CREATE TABLE t (x INT)',
'PRAGMA database_list',
"SET memory_limit = '100GB'",
'INSTALL httpfs',
'LOAD httpfs',
'DROP TABLE bars_1d',
'DELETE FROM bars_1d',
'UPDATE bars_1d SET close = 0',
];
for (const sql of prohibitedSqls) {
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ sql })),
'PROHIBITED_SQL_OPERATION'
);
}
});
it('rejects direct/mixed-case readers, quoted paths, catalog relations, table functions, and disallowed functions', () => {
const externalSqls = [
"SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/etc/x')",
"SELECT listing_id, ts, ts AS known_at, close AS value FROM ReAd_PaRqUeT('/etc/x.parquet')",
"SELECT listing_id, ts, ts AS known_at, close AS value FROM read_csv('/tmp/a.csv')",
"SELECT listing_id, ts, ts AS known_at, close AS value FROM glob('/mnt/*')",
"SELECT listing_id, ts, ts AS known_at, close AS value FROM '/etc/x.parquet'",
"SELECT listing_id, ts, ts AS known_at, '/etc/passwd' AS value FROM {{input:bars_1d}}",
'SELECT listing_id, ts, ts AS known_at, close AS value FROM information_schema.tables',
'SELECT listing_id, ts, ts AS known_at, close AS value FROM pg_catalog.pg_tables',
'SELECT listing_id, ts, ts AS known_at, close AS value FROM raw_table_not_a_cte',
"SELECT listing_id, ts, ts AS known_at, getenv('HOME') AS value FROM {{input:bars_1d}}",
'SELECT listing_id, ts, ts AS known_at, custom_evil_fn(close) AS value FROM {{input:bars_1d}}',
];
for (const sql of externalSqls) {
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ sql })),
'EXTERNAL_DATA_ACCESS'
);
}
});
it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => {
const badProjections = [
'SELECT * FROM {{input:bars_1d}}',
'SELECT listing_id, ts, close AS value FROM {{input:bars_1d}}',
'SELECT listing_id, ts, ts AS known_at, close AS value, volume AS extra FROM {{input:bars_1d}}',
'SELECT ts, listing_id, ts AS known_at, close AS value FROM {{input:bars_1d}}',
'SELECT listing_id, ts, ts AS known_at, close AS ret FROM {{input:bars_1d}}',
'SELECT listing_id, ts, ts AS known_at, close + 1 FROM {{input:bars_1d}}',
];
for (const sql of badProjections) {
expectFeatureErrorCode(
() => validateFeatureDefinition(makeSimpleDef({ sql })),
'INVALID_SQL_PROJECTION'
);
}
});
it('rejects unsupported, undeclared, and unused input datasets with distinct codes', () => {
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
inputs: ['macro' as FeatureDefinition['inputs'][number]],
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}',
})
),
'UNSUPPORTED_INPUT_DATASET'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
inputs: ['bars_1d'],
sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id',
})
),
'UNDECLARED_INPUT'
);
expectFeatureErrorCode(
() =>
validateFeatureDefinition(
makeSimpleDef({
inputs: ['bars_1d', 'fx_1d'],
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
})
),
'UNUSED_INPUT'
);
});
});
describe('featureDefinitionHash', () => {
it('is stable across inter-token whitespace, object key order, input order, and metadata', () => {
const defA: FeatureDefinition = {
name: 'fx_ratio',
version: 1,
family: 'fx',
kind: 'duckdb_sql',
inputs: ['fx_1d', 'bars_1d'],
warmupBars: 2,
knownAtRule: 'max_input_known_at',
description: 'First description',
sql: "SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date WHERE f.pair = 'USD CAD'",
};
const defB: FeatureDefinition = {
sql: [
'SELECT',
' b.listing_id,',
' b.ts,',
' GREATEST(b.known_at, f.known_at) AS known_at,',
' b.close / f.close AS value',
'FROM {{input:bars_1d}} AS b',
'INNER JOIN {{input:fx_1d}} AS f',
' ON b.session_date = f.session_date',
"WHERE f.pair = 'USD CAD'",
].join('\n\t'),
knownAtRule: 'max_input_known_at',
warmupBars: 2,
inputs: ['bars_1d', 'fx_1d'],
kind: 'duckdb_sql',
family: 'technical',
version: 1,
name: 'fx_ratio',
description: 'Different metadata description',
};
const hashA = featureDefinitionHash(defA);
const hashB = featureDefinitionHash(defB);
expect(hashA).toMatch(/^[0-9a-f]{64}$/);
expect(hashA).toBe(hashB);
});
it('changes when string literal whitespace, SQL semantics, inputs, warmupBars, or knownAtRule change', () => {
const base = makeSimpleDef({
sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}",
});
const baseHash = featureDefinitionHash(base);
// Whitespace inside string literal changes hash.
const changedLiteral = makeSimpleDef({
sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}",
});
expect(featureDefinitionHash(changedLiteral)).not.toBe(baseHash);
// Substantive SQL change.
const changedSql = makeSimpleDef({
sql: 'SELECT listing_id, ts, ts AS known_at, open AS value FROM {{input:bars_1d}}',
});
expect(featureDefinitionHash(changedSql)).not.toBe(baseHash);
// Valid input dataset change.
const changedInput = makeSimpleDef({
inputs: ['events'],
sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}',
});
expect(featureDefinitionHash(changedInput)).not.toBe(baseHash);
// warmupBars change.
expect(featureDefinitionHash({ ...base, warmupBars: 5 })).not.toBe(baseHash);
// knownAtRule change.
expect(featureDefinitionHash({ ...base, knownAtRule: 'source_known_at' })).not.toBe(baseHash);
});
});
describe('createFeatureRegistry', () => {
it('supports idempotent re-registration, enforces FEATURE_VERSION_IMMUTABLE, allows version bumps, and isolates mutations', () => {
const registry = createFeatureRegistry();
const mutableInputs: FeatureDefinition['inputs'][number][] = ['bars_1d'];
const initial: FeatureDefinition = {
...RET_1D_V1,
inputs: mutableInputs,
};
const first = registry.registerSignal(initial);
expect(first.ref).toBe('ret_1d@v1');
expect(first.definitionHash).toBe(featureDefinitionHash(RET_1D_V1));
// Mutate caller input after registration; stored definition must be unaffected.
mutableInputs.push('fx_1d');
expect(registry.get('ret_1d@v1')?.inputs).toEqual(['bars_1d']);
// Idempotent re-registration with whitespace-only SQL difference.
const sameSemantic: FeatureDefinition = {
...RET_1D_V1,
sql: RET_1D_V1.sql.replace(/\n/g, ' '),
description: 'Updated description ignored for hash',
};
const second = registry.registerSignal(sameSemantic);
expect(second.definitionHash).toBe(first.definitionHash);
expect(registry.list()).toEqual(['ret_1d@v1']);
// Semantic changes at v1 must throw FEATURE_VERSION_IMMUTABLE.
const changedSql: FeatureDefinition = {
...RET_1D_V1,
sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}',
};
const errSql = expectFeatureErrorCode(
() => registry.registerSignal(changedSql),
'FEATURE_VERSION_IMMUTABLE'
);
expect(errSql.ref).toBe('ret_1d@v1');
const changedInputs: FeatureDefinition = {
...RET_1D_V1,
inputs: ['bars_1d', 'fx_1d'],
sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date',
};
expectFeatureErrorCode(
() => registry.registerSignal(changedInputs),
'FEATURE_VERSION_IMMUTABLE'
);
expectFeatureErrorCode(
() => registry.registerSignal({ ...RET_1D_V1, warmupBars: 2 }),
'FEATURE_VERSION_IMMUTABLE'
);
expectFeatureErrorCode(
() => registry.registerSignal({ ...RET_1D_V1, knownAtRule: 'source_known_at' }),
'FEATURE_VERSION_IMMUTABLE'
);
// Same change under version 2 succeeds and both refs are listed.
const v2 = registry.registerSignal({ ...changedSql, version: 2 });
expect(v2.ref).toBe('ret_1d@v2');
expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']);
expect(registry.get('ret_1d@v2')?.version).toBe(2);
expect(registry.get('missing@v1')).toBeUndefined();
// Mutating returned list array does not affect registry.
const listed = registry.list() as string[];
listed.push('evil@v99');
expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']);
});
});
describe('planFeatureBatch', () => {
it('plans 3 yearly Parquet COPY statements for RET_1D_V1 across 2020–2022', () => {
const writes = planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2020,
toYear: 2022,
vaultCutoffDate: '2025-06-01',
});
expect(writes).toHaveLength(3);
expect(writes.map(w => w.year)).toEqual([2020, 2021, 2022]);
expect(writes.map(w => w.outputPath)).toEqual([
'/c/features/ret_1d/v1/year=2020/part.parquet',
'/c/features/ret_1d/v1/year=2021/part.parquet',
'/c/features/ret_1d/v1/year=2022/part.parquet',
]);
for (const write of writes) {
expect(write.sql).toStartWith(
'COPY (SELECT CAST(listing_id AS INTEGER) AS listing_id, ts, known_at, CAST(value AS DOUBLE) AS value FROM ('
);
expect(write.sql).toContain(
"read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?"
);
expect(write.sql).toContain(
'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)'
);
expect(write.sql).toEndWith(
`TO '${write.outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`
);
const expectedTsEnd = `${write.year}-12-31T23:59:59.999999Z`;
const expectedKnownAtCeiling = '2025-05-31T23:59:59.999999Z';
expect(write.params).toEqual([
expectedTsEnd,
expectedKnownAtCeiling,
write.year,
expectedTsEnd,
expectedKnownAtCeiling,
]);
// Verify scan predicate is embedded inside the FROM subquery of the lagged CTE
// (evaluated before LAG) and outer year(ts) filter follows the authored query.
const lagIdx = write.sql.indexOf('LAG ( close )');
const scanIdx = write.sql.indexOf(
"FROM (SELECT * FROM read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?)"
);
const outerYearIdx = write.sql.indexOf('WHERE year(ts) = ?');
expect(lagIdx).toBeGreaterThan(-1);
expect(scanIdx).toBeGreaterThan(lagIdx);
expect(outerYearIdx).toBeGreaterThan(scanIdx);
}
});
it('expands all six allow-listed dataset path shapes and predicates, normalizes roots, and rejects unsafe roots', () => {
const allSixDef: FeatureDefinition = {
name: 'all_six_check',
version: 1,
family: 'fundamental',
kind: 'duckdb_sql',
inputs: ['bars_1d', 'adj_factors', 'events', 'shorts', 'fx_1d', 'fundamentals_pit'],
warmupBars: 0,
knownAtRule: 'max_input_known_at',
sql: `
SELECT
b.listing_id,
b.ts,
GREATEST(b.known_at, a.known_at, e.known_at, s.known_at, f.known_at, p.effective_known_at) AS known_at,
b.close AS value
FROM {{input:bars_1d}} AS b
INNER JOIN {{input:adj_factors}} AS a ON b.listing_id = a.listing_id
INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id
INNER JOIN {{input:shorts}} AS s ON b.listing_id = s.listing_id
INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date
INNER JOIN {{input:fundamentals_pit}} AS p ON b.listing_id = p.listing_id
`,
};
const [write] = planFeatureBatch(allSixDef, {
curatedRoot: '/data///',
fromYear: 2021,
toYear: 2021,
vaultCutoffDate: '2024-01-01',
});
expect(write).toBeDefined();
expect(write?.outputPath).toBe('/data/features/all_six_check/v1/year=2021/part.parquet');
expect(write?.sql).toContain(
"read_parquet('/data/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?"
);
expect(write?.sql).toContain(
"read_parquet('/data/adj_factors/part.parquet') WHERE known_at <= ?"
);
expect(write?.sql).toContain(
"read_parquet('/data/events/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?"
);
expect(write?.sql).toContain(
"read_parquet('/data/shorts/part.parquet') WHERE known_at <= ?"
);
expect(write?.sql).toContain(
"read_parquet('/data/fx_1d/part.parquet') WHERE ts <= ? AND known_at <= ?"
);
expect(write?.sql).toContain(
"read_parquet('/data/fundamentals_pit/year=*/part.parquet', hive_partitioning = true) WHERE effective_known_at <= ?"
);
const ts2021 = '2021-12-31T23:59:59.999999Z';
const vaultCeiling = '2023-12-31T23:59:59.999999Z';
expect(write?.params).toEqual([
ts2021,
vaultCeiling, // bars_1d
vaultCeiling, // adj_factors
ts2021,
vaultCeiling, // events
vaultCeiling, // shorts
ts2021,
vaultCeiling, // fx_1d
vaultCeiling, // fundamentals_pit
2021,
ts2021,
vaultCeiling, // outer filter
]);
// Root '/' normalization (no double leading slash).
const [rootWrite] = planFeatureBatch(RET_1D_V1, {
curatedRoot: '/',
fromYear: 2020,
toYear: 2020,
vaultCutoffDate: '2025-01-01',
});
expect(rootWrite?.outputPath).toBe('/features/ret_1d/v1/year=2020/part.parquet');
expect(rootWrite?.sql).toContain("read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true)");
// Unsafe curated roots rejected.
for (const badRoot of ['', 'relative/path', "/tmp/o'reilly", '/tmp/a;b', '/tmp/a*b', '/tmp/\n']) {
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: badRoot,
fromYear: 2020,
toYear: 2020,
vaultCutoffDate: '2025-01-01',
}),
'INVALID_BATCH_OPTIONS'
);
}
});
it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => {
// Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z.
const midyear = planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2020,
toYear: 2024,
vaultCutoffDate: '2022-06-15',
});
expect(midyear.map(w => w.year)).toEqual([2020, 2021, 2022]);
expect(midyear[2]?.params).toEqual([
'2022-06-14T23:59:59.999999Z',
'2022-06-14T23:59:59.999999Z',
2022,
'2022-06-14T23:59:59.999999Z',
'2022-06-14T23:59:59.999999Z',
]);
// January 1 cutoff: 2022-01-01 -> excludes 2022 completely.
const jan1 = planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2020,
toYear: 2023,
vaultCutoffDate: '2022-01-01',
});
expect(jan1.map(w => w.year)).toEqual([2020, 2021]);
expect(jan1[1]?.params).toEqual([
'2021-12-31T23:59:59.999999Z',
'2021-12-31T23:59:59.999999Z',
2021,
'2021-12-31T23:59:59.999999Z',
'2021-12-31T23:59:59.999999Z',
]);
// Entirely held-out ranges throw VAULT_RANGE_VIOLATION.
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2023,
toYear: 2025,
vaultCutoffDate: '2022-06-15',
}),
'VAULT_RANGE_VIOLATION'
);
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2022,
toYear: 2022,
vaultCutoffDate: '2022-01-01',
}),
'VAULT_RANGE_VIOLATION'
);
// Invalid calendar dates and year ranges throw INVALID_BATCH_OPTIONS.
for (const badDate of ['2025-02-29', '2025-13-01', '2025-04-31', '2025-06-01T00:00:00Z', 'not-a-date']) {
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2020,
toYear: 2021,
vaultCutoffDate: badDate,
}),
'INVALID_BATCH_OPTIONS'
);
}
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2022,
toYear: 2020,
vaultCutoffDate: '2025-01-01',
}),
'INVALID_BATCH_OPTIONS'
);
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 999,
toYear: 2020,
vaultCutoffDate: '2025-01-01',
}),
'INVALID_BATCH_OPTIONS'
);
expectFeatureErrorCode(
() =>
planFeatureBatch(RET_1D_V1, {
curatedRoot: '/c',
fromYear: 2020.5,
toYear: 2021,
vaultCutoffDate: '2025-01-01',
}),
'INVALID_BATCH_OPTIONS'
);
});
});
describe('runFeatureBatch', () => {
it('executes deterministically in sequential year order and returns a complete manifest', async () => {
const opts = {
curatedRoot: '/c',
fromYear: 2020,
toYear: 2022,
vaultCutoffDate: '2025-06-01',
};
const orderLog: string[] = [];
const fakeA = createRecordingFakeExecutor({
async onQuery(_sql, params) {
const year = params[2];
orderLog.push(`start:${String(year)}`);
await Promise.resolve();
orderLog.push(`end:${String(year)}`);
},
});
const fakeB = createRecordingFakeExecutor();
const manifestA = await runFeatureBatch(RET_1D_V1, opts, fakeA.executor);
const manifestB = await runFeatureBatch(RET_1D_V1, opts, fakeB.executor);
expect(orderLog).toEqual([
'start:2020',
'end:2020',
'start:2021',
'end:2021',
'start:2022',
'end:2022',
]);
expect(fakeA.runCalls).toHaveLength(0);
expect(fakeA.calls).toEqual(fakeB.calls);
expect(manifestA).toEqual(manifestB);
expect(manifestA).toEqual({
ref: 'ret_1d@v1',
definitionHash: featureDefinitionHash(RET_1D_V1),
knownAtRule: 'bar_close',
warmupBars: 1,
inputs: ['bars_1d'],
writes: [
{ year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' },
{ year: 2021, outputPath: '/c/features/ret_1d/v1/year=2021/part.parquet' },
{ year: 2022, outputPath: '/c/features/ret_1d/v1/year=2022/part.parquet' },
],
});
});
it('stops on second-year executor error, preserves cause, and reports only first year as completed', async () => {
const rootCause = new Error('disk full on year 2021');
const fake = createRecordingFakeExecutor({
onQuery(_sql, _params, callIndex) {
if (callIndex === 1) {
throw rootCause;
}
},
});
let caught: unknown;
try {
await runFeatureBatch(
RET_1D_V1,
{
curatedRoot: '/c',
fromYear: 2020,
toYear: 2022,
vaultCutoffDate: '2025-06-01',
},
fake.executor
);
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(FeatureLibraryError);
const typed = caught as FeatureLibraryError;
expect(typed.code).toBe('BATCH_WRITE_FAILED');
expect(typed.cause).toBe(rootCause);
expect(typed.failedYear).toBe(2021);
expect(typed.completedYears).toEqual([2020]);
expect(typed.completedWrites).toEqual([
{ year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' },
]);
expect(fake.calls).toHaveLength(2);
});
it('issues zero executor calls when definition or batch options are invalid', async () => {
const fake = createRecordingFakeExecutor();
let caught: unknown;
try {
await runFeatureBatch(
RET_1D_V1,
{
curatedRoot: '/c',
fromYear: 2025,
toYear: 2026,
vaultCutoffDate: '2025-01-01',
},
fake.executor
);
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(FeatureLibraryError);
expect((caught as FeatureLibraryError).code).toBe('VAULT_RANGE_VIOLATION');
expect(fake.calls).toHaveLength(0);
expect(fake.runCalls).toHaveLength(0);
});
});
describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixture, no Parquet execution)', () => {
it('matches listing-partitioned LAG raw-close return semantics across prior-year warm-up and raw split discontinuity', () => {
// Verify SQL structure enforces listing-partitioned LAG, bar-close known_at, and positive prior close guard.
expect(RET_1D_V1.sql).toContain('LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close');
expect(RET_1D_V1.sql).toContain('ts AS known_at');
expect(RET_1D_V1.sql).toContain('(close / prev_close) - 1.0 AS value');
expect(RET_1D_V1.sql).toContain('WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0');
// Hand-calculated reference fixture (does not evaluate DuckDB Parquet):
// Listing 101: 2019-12-31 close 100 -> 2020-01-02 close 110 (+10%) -> 2020-01-03 2-for-1 raw split close 55 (-50% raw).
// Listing 202: 2020-01-02 close 50 (no prior close -> omitted) -> 2020-01-03 close 52 (+4%).
const bars = [
{ listing_id: 101, ts: '2019-12-31T21:00:00Z', close: 100 },
{ listing_id: 101, ts: '2020-01-02T21:00:00Z', close: 110 },
{ listing_id: 101, ts: '2020-01-03T21:00:00Z', close: 55 },
{ listing_id: 202, ts: '2020-01-02T21:00:00Z', close: 50 },
{ listing_id: 202, ts: '2020-01-03T21:00:00Z', close: 52 },
];
const lastCloseByListing = new Map<number, number>();
const targetYearRows: Array<{ listing_id: number; ts: string; known_at: string; value: number }> = [];
for (const bar of bars) {
const prevClose = lastCloseByListing.get(bar.listing_id);
lastCloseByListing.set(bar.listing_id, bar.close);
if (prevClose === undefined || prevClose <= 0 || bar.close <= 0) {
continue;
}
if (bar.ts.startsWith('2020-')) {
targetYearRows.push({
listing_id: bar.listing_id,
ts: bar.ts,
known_at: bar.ts,
value: bar.close / prevClose - 1.0,
});
}
}
expect(targetYearRows).toHaveLength(3);
expect(targetYearRows[0]).toEqual({
listing_id: 101,
ts: '2020-01-02T21:00:00Z',
known_at: '2020-01-02T21:00:00Z',
value: 0.10000000000000009,
});
expect(targetYearRows[1]).toEqual({
listing_id: 101,
ts: '2020-01-03T21:00:00Z',
known_at: '2020-01-03T21:00:00Z',
value: -0.5,
});
expect(targetYearRows[2]?.listing_id).toBe(202);
expect(targetYearRows[2]?.value).toBeCloseTo(0.04, 12);
});
});