T-139: M2.4a — Versioned Feature Library core: declarative DuckDB SQL feature definitions + registerSignal registry + versioned Parquet batch-plan runner over an injected DuckDbExecutor in libs/research/src/feature-library.ts (pure, no new deps)
This commit is contained in:
parent
26e305f5e6
commit
7ef16d0bc3
3 changed files with 20 additions and 24 deletions
|
|
@ -235,7 +235,7 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/feature-librar
|
|||
|
||||
### API & Immutability
|
||||
|
||||
- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:<dataset>}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared.
|
||||
- **`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 non-recursive `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects `WITH RECURSIVE`, semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:<dataset>}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope non-recursive CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared.
|
||||
- **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `<name>@v<version>` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`).
|
||||
- **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration.
|
||||
- **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `<name>@v<version>` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation.
|
||||
|
|
|
|||
|
|
@ -1432,13 +1432,14 @@ function validateQuerySlice(
|
|||
const inScopeCtes = new Set<string>(outerCtes);
|
||||
let pos = start;
|
||||
|
||||
// Optional leading WITH clause.
|
||||
// Optional leading WITH clause (non-recursive CTEs only).
|
||||
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;
|
||||
throw new FeatureLibraryError(
|
||||
'INVALID_SQL_STATEMENT',
|
||||
'WITH RECURSIVE CTEs are not permitted in feature SQL; use non-recursive CTEs.'
|
||||
);
|
||||
}
|
||||
|
||||
while (pos < end) {
|
||||
|
|
@ -1484,9 +1485,6 @@ function validateQuerySlice(
|
|||
);
|
||||
}
|
||||
const bodyClose = findMatchingParen(tokens, pos, end);
|
||||
if (isRecursive) {
|
||||
inScopeCtes.add(cteName);
|
||||
}
|
||||
validateQuerySlice(tokens, pos + 1, bodyClose, inScopeCtes, false);
|
||||
inScopeCtes.add(cteName);
|
||||
pos = bodyClose + 1;
|
||||
|
|
|
|||
|
|
@ -1447,32 +1447,30 @@ describe('QA round 3: WITH RECURSIVE cannot shadow an undeclared catalog relatio
|
|||
const recursiveShadowProbes: readonly string[] = [
|
||||
'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s',
|
||||
'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl UNION ALL SELECT * FROM staging_tbl WHERE 1 = 0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s',
|
||||
'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.close FROM {{input:bars_1d}} AS b, staging_tbl AS s) AS b',
|
||||
'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT 1 FROM staging_tbl)',
|
||||
];
|
||||
|
||||
it('rejects a RECURSIVE CTE whose body reads a same-named catalog table, with no executor call', async () => {
|
||||
it('rejects top-level and nested WITH RECURSIVE CTEs with INVALID_SQL_STATEMENT and zero executor calls', async () => {
|
||||
for (const sql of recursiveShadowProbes) {
|
||||
const def = makeSimpleDef({ name: 'leak', sql });
|
||||
|
||||
let validateError: unknown;
|
||||
try {
|
||||
validateFeatureDefinition(def);
|
||||
} catch (error) {
|
||||
validateError = error;
|
||||
}
|
||||
expect(validateError).toBeInstanceOf(FeatureLibraryError);
|
||||
expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain(
|
||||
(validateError as FeatureLibraryError).code
|
||||
);
|
||||
expect(() => createFeatureRegistry().registerSignal(def)).toThrow(FeatureLibraryError);
|
||||
expectFeatureErrorCode(() => validateFeatureDefinition(def), 'INVALID_SQL_STATEMENT');
|
||||
expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'INVALID_SQL_STATEMENT');
|
||||
|
||||
const fake = createRecordingFakeExecutor();
|
||||
await expect(
|
||||
runFeatureBatch(
|
||||
let execError: unknown;
|
||||
try {
|
||||
await runFeatureBatch(
|
||||
def,
|
||||
{ curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' },
|
||||
fake.executor
|
||||
)
|
||||
).rejects.toBeInstanceOf(FeatureLibraryError);
|
||||
);
|
||||
} catch (error) {
|
||||
execError = error;
|
||||
}
|
||||
expect(execError).toBeInstanceOf(FeatureLibraryError);
|
||||
expect((execError as FeatureLibraryError).code).toBe('INVALID_SQL_STATEMENT');
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue