T-213: M2.4b — Add Python stockbot register_signal, batch feature runner, and M2 MarketDataStore methods
This commit is contained in:
parent
5859857ace
commit
0da283e67f
4 changed files with 649 additions and 63 deletions
|
|
@ -683,13 +683,13 @@ function validateFxPair(raw: unknown): (typeof FX_PAIR_MAP)[keyof typeof FX_PAIR
|
|||
);
|
||||
}
|
||||
|
||||
function validateUniverseRef(raw: unknown): readonly string[] {
|
||||
function validateUniverseRef(raw: unknown, field = 'ref'): readonly string[] {
|
||||
if (typeof raw === 'string' && Object.prototype.hasOwnProperty.call(UNIVERSE_CURRENCY_MAP, raw)) {
|
||||
return UNIVERSE_CURRENCY_MAP[raw as SupportedUniverseRef];
|
||||
}
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unsupported universe ref "${String(raw)}". Expected one of: ${UNIVERSE_REFS.join(', ')}.`,
|
||||
'ref'
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -2280,8 +2280,8 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
return mapTableRows(FX_1D_COLUMNS, FX_1D_SCHEMA, rawRows);
|
||||
},
|
||||
|
||||
crossSection(): Promise<Table> {
|
||||
return Promise.reject(new MarketDataStoreNotImplementedError('crossSection'));
|
||||
async crossSection(q: CrossSectionQuery): Promise<Table> {
|
||||
return executeCrossSection(q, planCtx, ensureBudgetInitialized, typedExecutor);
|
||||
},
|
||||
|
||||
async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise<Table> {
|
||||
|
|
@ -2303,3 +2303,246 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption
|
|||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type CrossSectionQuery = Parameters<MarketDataStore['crossSection']>[0];
|
||||
|
||||
const CROSS_SECTION_FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/;
|
||||
|
||||
interface ParsedCrossSectionFeatureRef {
|
||||
readonly canonical: string;
|
||||
readonly name: string;
|
||||
readonly version: number;
|
||||
}
|
||||
|
||||
function validateCrossSectionFeatures(
|
||||
raw: readonly string[],
|
||||
field = 'features'
|
||||
): ParsedCrossSectionFeatureRef[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a non-empty array of canonical "<name>@v<version>" feature refs.',
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const parsed: ParsedCrossSectionFeatureRef[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
if (!(i in raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid sparse feature ref at index ${i}. Expected canonical "<name>@v<version>".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
const item: unknown = raw[i];
|
||||
if (typeof item !== 'string') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature ref at index ${i}. Expected canonical "<name>@v<version>".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
const match = CROSS_SECTION_FEATURE_REF_RE.exec(item);
|
||||
if (match === null) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature ref "${item}". Expected canonical "<name>@v<version>".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
const name = match[1];
|
||||
const versionStr = match[2];
|
||||
if (name === undefined || versionStr === undefined) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature ref "${item}". Expected canonical "<name>@v<version>".`,
|
||||
field
|
||||
);
|
||||
}
|
||||
const version = Number(versionStr);
|
||||
if (!Number.isSafeInteger(version) || version < 1) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid feature version in ref "${item}". Expected a positive safe integer.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
const canonical = `${name}@v${version}`;
|
||||
if (!seen.has(canonical)) {
|
||||
seen.add(canonical);
|
||||
parsed.push({ canonical, name, version });
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
interface PlannedCrossSectionInternal {
|
||||
readonly planned: PlannedDuckDbQuery;
|
||||
readonly columns: readonly string[];
|
||||
readonly schema: readonly TableColumnSpec[];
|
||||
}
|
||||
|
||||
function planCrossSectionInternal(
|
||||
q: CrossSectionQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedCrossSectionInternal {
|
||||
const curatedRoot = validateContext(ctx);
|
||||
const lookbackDays = validateUniverseLookbackDays(ctx.universeLookbackDays);
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a crossSection query object.', 'query');
|
||||
}
|
||||
|
||||
const parsedRefs = validateCrossSectionFeatures(q.features, 'features');
|
||||
const currencies = validateUniverseRef(q.universe, 'universe');
|
||||
|
||||
if (typeof q.date !== 'string' || !DATE_ONLY_RE.test(q.date)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid crossSection date "${String(q.date)}". Expected a UTC calendar date in YYYY-MM-DD format.`,
|
||||
'date'
|
||||
);
|
||||
}
|
||||
if (q.asOf !== undefined && typeof q.asOf !== 'string') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Invalid crossSection asOf timestamp. Expected a UTC date or ISO-8601 instant string.',
|
||||
'asOf'
|
||||
);
|
||||
}
|
||||
|
||||
let fenced: FencedTimeRange;
|
||||
try {
|
||||
fenced = applyVaultFence(
|
||||
{
|
||||
from: q.date,
|
||||
to: q.date,
|
||||
...(q.asOf !== undefined ? { asOf: q.asOf } : {}),
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
}
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (
|
||||
err instanceof MarketDataStoreValidationError &&
|
||||
(err.field === 'from' || err.field === 'to')
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(err.message, 'date');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const lookbackStartMs = fenced.fromMs - lookbackDays * MS_PER_DAY;
|
||||
if (!Number.isSafeInteger(lookbackStartMs) || lookbackStartMs < MIN_ISO_DATE_EPOCH_MS) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid universeLookbackDays "${lookbackDays}". Lookback start precedes supported YYYY-MM-DD UTC date range.`,
|
||||
'universeLookbackDays'
|
||||
);
|
||||
}
|
||||
|
||||
const lookbackStartDate = formatUtcDate(lookbackStartMs);
|
||||
const endDate = formatUtcDate(fenced.toMs);
|
||||
const fromSubMs = resolveFromSubMsMicros(q.date);
|
||||
const toSubMs = resolveToSubMsMicros(q.date, fenced);
|
||||
const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.date, fenced);
|
||||
const fromIso = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs);
|
||||
const toIso = formatUtcIsoWithMicros(fenced.toMs, toSubMs);
|
||||
const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs);
|
||||
const universeKnownAtIso =
|
||||
fenced.toMs < fenced.asOfMs || (fenced.toMs === fenced.asOfMs && toSubMs <= asOfSubMs)
|
||||
? toIso
|
||||
: asOfIso;
|
||||
|
||||
const barsPath = joinCuratedPath(curatedRoot, 'bars_1d/year=*/part.parquet');
|
||||
const currencyPredicate =
|
||||
currencies.length === 1
|
||||
? 'b.currency = ?'
|
||||
: `b.currency IN (${buildPlaceholders(currencies.length)})`;
|
||||
|
||||
const ctes: string[] = [
|
||||
'u AS (' +
|
||||
'SELECT DISTINCT b.listing_id ' +
|
||||
`FROM read_parquet('${barsPath}', hive_partitioning = true) AS b ` +
|
||||
`WHERE ${currencyPredicate} ` +
|
||||
'AND b.session_date >= ? ' +
|
||||
'AND b.session_date <= ? ' +
|
||||
'AND b.ts <= CAST(? AS TIMESTAMPTZ) ' +
|
||||
'AND b.known_at <= CAST(? AS TIMESTAMPTZ))',
|
||||
];
|
||||
const params: DuckDbParam[] = [
|
||||
...currencies,
|
||||
lookbackStartDate,
|
||||
endDate,
|
||||
toIso,
|
||||
universeKnownAtIso,
|
||||
];
|
||||
const selectCols: string[] = ['CAST(u.listing_id AS INTEGER) AS listing_id'];
|
||||
const joins: string[] = [];
|
||||
const columns: string[] = ['listing_id'];
|
||||
const schema: TableColumnSpec[] = [{ name: 'listing_id', kind: 'int32', nullable: false }];
|
||||
|
||||
for (let i = 0; i < parsedRefs.length; i += 1) {
|
||||
const parsed = parsedRefs[i];
|
||||
if (parsed === undefined) {
|
||||
continue;
|
||||
}
|
||||
const alias = `f_${i}`;
|
||||
const featPath = joinCuratedPath(
|
||||
curatedRoot,
|
||||
`features/${parsed.name}/v${parsed.version}/year=*/part.parquet`
|
||||
);
|
||||
ctes.push(
|
||||
`${alias} AS (` +
|
||||
'SELECT listing_id, CAST(value AS DOUBLE) AS value ' +
|
||||
`FROM read_parquet('${featPath}', hive_partitioning = true) ` +
|
||||
'WHERE ts >= CAST(? AS TIMESTAMPTZ) ' +
|
||||
'AND ts <= CAST(? AS TIMESTAMPTZ) ' +
|
||||
'AND known_at <= CAST(? AS TIMESTAMPTZ) ' +
|
||||
'QUALIFY ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY ts DESC, known_at DESC) = 1)'
|
||||
);
|
||||
params.push(fromIso, toIso, asOfIso);
|
||||
const escapedCol = parsed.canonical.replace(/"/g, '""');
|
||||
selectCols.push(`${alias}.value AS "${escapedCol}"`);
|
||||
joins.push(`LEFT JOIN ${alias} ON u.listing_id = ${alias}.listing_id`);
|
||||
columns.push(parsed.canonical);
|
||||
schema.push({ name: parsed.canonical, kind: 'number', nullable: true });
|
||||
}
|
||||
|
||||
const sql =
|
||||
`WITH ${ctes.join(', ')} ` +
|
||||
`SELECT ${selectCols.join(', ')} ` +
|
||||
`FROM u ${joins.join(' ')} ` +
|
||||
'ORDER BY u.listing_id ASC';
|
||||
|
||||
return {
|
||||
planned: {
|
||||
sql,
|
||||
params,
|
||||
fenced: {
|
||||
...fenced,
|
||||
fromMs: lookbackStartMs,
|
||||
},
|
||||
},
|
||||
columns,
|
||||
schema,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Plans a Vault-fenced, survivorship-free cross-section DuckDB SQL query over
|
||||
* materialized feature Parquet partitions (`features/<name>/v<version>/year=*\/part.parquet`)
|
||||
* LEFT JOINed onto the active universe on `q.date`.
|
||||
*/
|
||||
export function planCrossSectionQuery(
|
||||
q: CrossSectionQuery,
|
||||
ctx: DuckDbPlanContext
|
||||
): PlannedDuckDbQuery {
|
||||
return planCrossSectionInternal(q, ctx).planned;
|
||||
}
|
||||
|
||||
async function executeCrossSection(
|
||||
q: CrossSectionQuery,
|
||||
planCtx: DuckDbPlanContext,
|
||||
ensureBudgetInitialized: () => Promise<void>,
|
||||
typedExecutor: DuckDbExecutor
|
||||
): Promise<Table> {
|
||||
const { planned, columns, schema } = planCrossSectionInternal(q, planCtx);
|
||||
await ensureBudgetInitialized();
|
||||
const rawRows = await typedExecutor.query(planned.sql, planned.params);
|
||||
return mapTableRows(columns, schema, rawRows);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
parseAdjFactorsSnapshotMetadata,
|
||||
planAdjFactorsMetadataQuery,
|
||||
planBars1dQuery,
|
||||
planCrossSectionQuery,
|
||||
planEventsQuery,
|
||||
planFundamentalsAsOfQuery,
|
||||
planFx1dQuery,
|
||||
|
|
@ -56,6 +57,7 @@ import {
|
|||
parseAdjFactorsSnapshotMetadata as subpathParseAdjFactorsSnapshotMetadata,
|
||||
planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery,
|
||||
planBars1dQuery as subpathPlanBars1dQuery,
|
||||
planCrossSectionQuery as subpathPlanCrossSectionQuery,
|
||||
planEventsQuery as subpathPlanEventsQuery,
|
||||
planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery,
|
||||
planFx1dQuery as subpathPlanFx1dQuery,
|
||||
|
|
@ -2418,15 +2420,6 @@ describe('createDuckDbMarketDataStore adapter behavior', () => {
|
|||
to: '2025-02-01',
|
||||
}),
|
||||
},
|
||||
{
|
||||
method: 'crossSection',
|
||||
run: () =>
|
||||
store.crossSection({
|
||||
features: ['ret_20d'],
|
||||
date: '2025-01-15',
|
||||
universe: 'US_EQ',
|
||||
}),
|
||||
},
|
||||
{
|
||||
method: 'macroAsOf',
|
||||
run: () =>
|
||||
|
|
@ -3277,3 +3270,86 @@ describe('fundamentalsAsOf hostile request inputs', () => {
|
|||
expect(afterCutoff.fenced.clampedAsOf).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('planCrossSectionQuery & createDuckDbMarketDataStore().crossSection()', () => {
|
||||
it('plans Vault-fenced survivorship-free crossSection SQL and maps nullable feature values', async () => {
|
||||
expect(subpathPlanCrossSectionQuery).toBe(planCrossSectionQuery);
|
||||
|
||||
const planned = planCrossSectionQuery(
|
||||
{
|
||||
features: ['ret_1d@v1', 'mom_diff@v1', 'ret_1d@v1'],
|
||||
date: '2025-01-02',
|
||||
universe: 'US_EQ',
|
||||
asOf: '2025-01-02T22:00:00Z',
|
||||
},
|
||||
DEFAULT_CTX
|
||||
);
|
||||
|
||||
expect(planned.sql).toContain(
|
||||
`FROM read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b`
|
||||
);
|
||||
expect(planned.sql).toContain(
|
||||
`FROM read_parquet('${CURATED_ROOT}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true)`
|
||||
);
|
||||
expect(planned.sql).toContain(
|
||||
`FROM read_parquet('${CURATED_ROOT}/features/mom_diff/v1/year=*/part.parquet', hive_partitioning = true)`
|
||||
);
|
||||
expect(planned.sql).toContain('ORDER BY u.listing_id ASC');
|
||||
expect(planned.params).toEqual([
|
||||
'USD',
|
||||
'2024-12-26',
|
||||
'2025-01-02',
|
||||
'2025-01-02T23:59:59.999999Z',
|
||||
'2025-01-02T22:00:00.000Z',
|
||||
'2025-01-02T00:00:00.000Z',
|
||||
'2025-01-02T23:59:59.999999Z',
|
||||
'2025-01-02T22:00:00.000Z',
|
||||
'2025-01-02T00:00:00.000Z',
|
||||
'2025-01-02T23:59:59.999999Z',
|
||||
'2025-01-02T22:00:00.000Z',
|
||||
]);
|
||||
|
||||
const fake = createRecordingExecutor({
|
||||
onQuery: () => [
|
||||
{ listing_id: 1, 'ret_1d@v1': 0.1, 'mom_diff@v1': 1.0 },
|
||||
{ listing_id: 2, 'ret_1d@v1': null, 'mom_diff@v1': -5.0 },
|
||||
],
|
||||
});
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: {},
|
||||
});
|
||||
|
||||
const table = await store.crossSection({
|
||||
features: ['ret_1d@v1', 'mom_diff@v1'],
|
||||
date: '2025-01-02',
|
||||
universe: 'US_EQ',
|
||||
asOf: '2025-01-02T22:00:00Z',
|
||||
});
|
||||
expect(table.columns).toEqual(['listing_id', 'ret_1d@v1', 'mom_diff@v1']);
|
||||
expect(table.rows).toEqual([
|
||||
{ listing_id: 1, 'ret_1d@v1': 0.1, 'mom_diff@v1': 1.0 },
|
||||
{ listing_id: 2, 'ret_1d@v1': null, 'mom_diff@v1': -5.0 },
|
||||
]);
|
||||
|
||||
// Rejects post-cutoff date and invalid feature refs with 0 additional executor calls
|
||||
const beforeCalls = fake.calls.length;
|
||||
await expect(
|
||||
store.crossSection({
|
||||
features: ['ret_1d@v1'],
|
||||
date: '2026-05-28',
|
||||
universe: 'US_EQ',
|
||||
})
|
||||
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
||||
await expect(
|
||||
store.crossSection({
|
||||
features: ['bad_ref'],
|
||||
date: '2025-01-02',
|
||||
universe: 'US_EQ',
|
||||
})
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(fake.calls).toHaveLength(beforeCalls);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1828,7 +1828,6 @@ def plan_feature_batch(
|
|||
vault_cutoff_date=vault_cutoff_date,
|
||||
)
|
||||
|
||||
known_at_upper_iso = format_utc_iso_micros(vault_ceiling_micros)
|
||||
writes: list[PlannedFeatureWrite] = []
|
||||
|
||||
for year in range(valid_from, last_planned_year + 1):
|
||||
|
|
@ -1838,6 +1837,7 @@ def plan_feature_batch(
|
|||
) * 1_000_000 + 999_999
|
||||
effective_ts_end_micros = min(year_end_micros, vault_ceiling_micros)
|
||||
ts_upper_iso = format_utc_iso_micros(effective_ts_end_micros)
|
||||
known_at_upper_iso = ts_upper_iso
|
||||
|
||||
output_path = _join_curated_path(
|
||||
valid_root, f"features/{defn.name}/v{defn.version}/year={year}/part.parquet"
|
||||
|
|
@ -1957,6 +1957,66 @@ def _validate_polars_feature_output(result: Any) -> pl.DataFrame:
|
|||
return df
|
||||
|
||||
|
||||
def _verify_or_persist_version_definition(
|
||||
*,
|
||||
version_dir: str,
|
||||
ref: str,
|
||||
definition_hash: str,
|
||||
defn: FeatureDefinition,
|
||||
persist: bool,
|
||||
) -> bool:
|
||||
"""Checks on-disk version immutability metadata and optionally persists it atomically.
|
||||
|
||||
Returns True when `_definition.json` is verified on disk with matching `definition_hash`.
|
||||
"""
|
||||
meta_path = os.path.join(version_dir, "_definition.json")
|
||||
if os.path.exists(meta_path):
|
||||
try:
|
||||
with open(meta_path, "r", encoding="utf-8") as fh:
|
||||
payload = json.load(fh)
|
||||
except Exception as exc:
|
||||
raise FeatureLibraryError(
|
||||
"FEATURE_VERSION_IMMUTABLE",
|
||||
f'Published feature "{ref}" has unreadable version metadata at "{meta_path}".',
|
||||
cause=exc,
|
||||
ref=ref,
|
||||
) from exc
|
||||
existing_hash = payload.get("definition_hash") if isinstance(payload, dict) else None
|
||||
if not isinstance(existing_hash, str) or existing_hash != definition_hash:
|
||||
raise FeatureLibraryError(
|
||||
"FEATURE_VERSION_IMMUTABLE",
|
||||
f'Feature "{ref}" is already published on disk with a different definition hash; bump the feature version instead of overwriting.',
|
||||
ref=ref,
|
||||
)
|
||||
return True
|
||||
|
||||
if not persist:
|
||||
return False
|
||||
|
||||
os.makedirs(version_dir, exist_ok=True)
|
||||
tmp_meta = os.path.join(version_dir, f"._definition.{os.getpid()}.{uuid.uuid4().hex}.tmp")
|
||||
metadata = {
|
||||
"ref": ref,
|
||||
"name": defn.name,
|
||||
"version": defn.version,
|
||||
"kind": defn.kind,
|
||||
"definition_hash": definition_hash,
|
||||
}
|
||||
try:
|
||||
with open(tmp_meta, "w", encoding="utf-8") as fh:
|
||||
json.dump(metadata, fh, sort_keys=True, separators=(",", ":"))
|
||||
fh.write("\n")
|
||||
os.replace(tmp_meta, meta_path)
|
||||
except Exception:
|
||||
if os.path.exists(tmp_meta):
|
||||
try:
|
||||
os.remove(tmp_meta)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
return True
|
||||
|
||||
|
||||
def run_feature_batch(
|
||||
defn: FeatureDefinition,
|
||||
*,
|
||||
|
|
@ -1970,6 +2030,8 @@ def run_feature_batch(
|
|||
|
||||
Creates parent `year=YYYY` directories, writes each year to a staging file in the same
|
||||
directory via a budgeted UTC DuckDB connection, and atomically publishes via `os.replace`.
|
||||
Persists and verifies `<curated_root>/features/<name>/v<version>/_definition.json` so a
|
||||
different definition cannot silently overwrite an already-published version across runs.
|
||||
Raises `FeatureLibraryError('BATCH_WRITE_FAILED')` with `failed_year`, `completed_years`,
|
||||
and `completed_writes` on failure.
|
||||
"""
|
||||
|
|
@ -1986,6 +2048,14 @@ def run_feature_batch(
|
|||
def_hash = feature_definition_hash(defn)
|
||||
sorted_inputs = tuple(sorted(validated.normalized_inputs))
|
||||
resolved_budget = budget or resolve_duckdb_budget()
|
||||
version_dir = _join_curated_path(valid_root, f"features/{defn.name}/v{defn.version}")
|
||||
definition_persisted = _verify_or_persist_version_definition(
|
||||
version_dir=version_dir,
|
||||
ref=ref,
|
||||
definition_hash=def_hash,
|
||||
defn=defn,
|
||||
persist=False,
|
||||
)
|
||||
|
||||
os.makedirs(resolved_budget.temp_directory, exist_ok=True)
|
||||
con = duckdb.connect(":memory:")
|
||||
|
|
@ -2038,6 +2108,15 @@ def run_feature_batch(
|
|||
finally:
|
||||
con.unregister("__polars_feature_out")
|
||||
|
||||
if not definition_persisted:
|
||||
definition_persisted = _verify_or_persist_version_definition(
|
||||
version_dir=version_dir,
|
||||
ref=ref,
|
||||
definition_hash=def_hash,
|
||||
defn=defn,
|
||||
persist=True,
|
||||
)
|
||||
|
||||
os.replace(tmp_path, write.output_path)
|
||||
except FeatureLibraryError as exc:
|
||||
if os.path.exists(tmp_path):
|
||||
|
|
@ -2045,7 +2124,12 @@ def run_feature_batch(
|
|||
os.remove(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
if exc.code in ("UNDECLARED_INPUT", "UNUSED_INPUT", "INVALID_SQL_PROJECTION"):
|
||||
if not completed_writes and exc.code in (
|
||||
"UNDECLARED_INPUT",
|
||||
"UNUSED_INPUT",
|
||||
"INVALID_SQL_PROJECTION",
|
||||
"FEATURE_VERSION_IMMUTABLE",
|
||||
):
|
||||
raise
|
||||
completed_years = [w.year for w in completed_writes]
|
||||
raise FeatureLibraryError(
|
||||
|
|
|
|||
|
|
@ -960,7 +960,7 @@ def test_sql_and_polars_batch_materialization_cross_section_and_events(tmp_path:
|
|||
assert ev.height == 2
|
||||
assert ev["kind"].to_list() == ["ceo_post", "filing"] # tie-breaker: kind ASC
|
||||
|
||||
# 5e. Cross-language Bun @stock-bot/duckdb read-back parity check
|
||||
# 5e. Cross-language Bun @stock-bot/duckdb read-back parity check (public MarketDataStore.crossSection)
|
||||
bun_bin = shutil.which("bun")
|
||||
assert bun_bin is not None, "bun is required for cross-language Parquet read-back check"
|
||||
script = f"""
|
||||
|
|
@ -971,57 +971,20 @@ const opened = await openDuckDbMarketDataStore({{
|
|||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
env: {{
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '512MB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB',
|
||||
STOCKBOT_DUCKDB_THREADS: '2',
|
||||
STOCKBOT_DUCKDB_TEMP_DIRECTORY: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))},
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: {json.dumps(str(tmp_path / 'ts_duckdb_tmp'))},
|
||||
}},
|
||||
}});
|
||||
try {{
|
||||
let mode = 'store';
|
||||
let result;
|
||||
try {{
|
||||
result = await opened.store.crossSection({{
|
||||
features: ['ret_1d@v1', 'mom_diff@v1'],
|
||||
date: '2025-01-02',
|
||||
universe: 'US_EQ',
|
||||
asOf: '2025-01-02T22:00:00Z',
|
||||
}});
|
||||
}} catch (err) {{
|
||||
if (err && typeof err === 'object' && err.name === 'MarketDataStoreNotImplementedError') {{
|
||||
mode = 'executor';
|
||||
const rows = await opened.executor.query(
|
||||
`WITH u AS (
|
||||
SELECT DISTINCT b.listing_id
|
||||
FROM read_parquet('${{curatedRoot}}/bars_1d/year=*/part.parquet', hive_partitioning = true) AS b
|
||||
WHERE b.currency = 'USD' AND b.session_date >= '2024-12-26' AND b.session_date <= '2025-01-02'
|
||||
AND b.ts <= CAST('2025-01-02T23:59:59.999999Z' AS TIMESTAMPTZ)
|
||||
AND b.known_at <= CAST('2025-01-02T22:00:00.000Z' AS TIMESTAMPTZ)
|
||||
),
|
||||
f0 AS (
|
||||
SELECT listing_id, CAST(value AS DOUBLE) AS value
|
||||
FROM read_parquet('${{curatedRoot}}/features/ret_1d/v1/year=*/part.parquet', hive_partitioning = true)
|
||||
WHERE ts >= CAST('2025-01-02T00:00:00.000Z' AS TIMESTAMPTZ)
|
||||
AND ts <= CAST('2025-01-02T23:59:59.999999Z' AS TIMESTAMPTZ)
|
||||
AND known_at <= CAST('2025-01-02T22:00:00.000Z' AS TIMESTAMPTZ)
|
||||
),
|
||||
f1 AS (
|
||||
SELECT listing_id, CAST(value AS DOUBLE) AS value
|
||||
FROM read_parquet('${{curatedRoot}}/features/mom_diff/v1/year=*/part.parquet', hive_partitioning = true)
|
||||
WHERE ts >= CAST('2025-01-02T00:00:00.000Z' AS TIMESTAMPTZ)
|
||||
AND ts <= CAST('2025-01-02T23:59:59.999999Z' AS TIMESTAMPTZ)
|
||||
AND known_at <= CAST('2025-01-02T22:00:00.000Z' AS TIMESTAMPTZ)
|
||||
)
|
||||
SELECT CAST(u.listing_id AS INTEGER) AS listing_id, f0.value AS "ret_1d@v1", f1.value AS "mom_diff@v1"
|
||||
FROM u LEFT JOIN f0 ON u.listing_id = f0.listing_id LEFT JOIN f1 ON u.listing_id = f1.listing_id
|
||||
ORDER BY u.listing_id ASC`,
|
||||
[]
|
||||
);
|
||||
result = {{ columns: ['listing_id', 'ret_1d@v1', 'mom_diff@v1'], rows }};
|
||||
}} else {{
|
||||
throw err;
|
||||
}}
|
||||
}}
|
||||
console.log(JSON.stringify({{ mode, ...result }}));
|
||||
const result = await opened.store.crossSection({{
|
||||
features: ['ret_1d@v1', 'mom_diff@v1'],
|
||||
date: '2025-01-02',
|
||||
universe: 'US_EQ',
|
||||
asOf: '2025-01-02T22:00:00Z',
|
||||
}});
|
||||
console.log(JSON.stringify(result));
|
||||
}} finally {{
|
||||
await opened.close();
|
||||
}}
|
||||
|
|
@ -1047,6 +1010,226 @@ try {{
|
|||
assert math.isclose(ts_row[col], py_row[col], rel_tol=1e-12, abs_tol=1e-12)
|
||||
|
||||
|
||||
def test_polars_batch_per_year_availability_ceiling_blocks_later_year_macro_leak(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
curated = tmp_path / "curated"
|
||||
_build_bars_and_events_fixtures(curated)
|
||||
budget = _make_budget(tmp_path)
|
||||
|
||||
# Macro releases across 2023 (prior history), 2024, 2025 pre-Vault, and 2025 post-Vault
|
||||
macro_df = pl.DataFrame(
|
||||
{
|
||||
"country_iso": ["US", "US", "US", "US"],
|
||||
"indicator": ["CPI", "CPI", "CPI", "CPI"],
|
||||
"period_date": [
|
||||
date(2023, 12, 1),
|
||||
date(2024, 6, 1),
|
||||
date(2025, 2, 1),
|
||||
date(2025, 7, 1),
|
||||
],
|
||||
"value": [1.0, 2.0, 99.0, 999.0],
|
||||
"unit": ["pct", "pct", "pct", "pct"],
|
||||
"known_at": [
|
||||
datetime(2023, 12, 15, 13, 30, 0, tzinfo=timezone.utc),
|
||||
datetime(2024, 7, 15, 13, 30, 0, tzinfo=timezone.utc),
|
||||
datetime(2025, 3, 15, 13, 30, 0, tzinfo=timezone.utc),
|
||||
datetime(2025, 8, 15, 13, 30, 0, tzinfo=timezone.utc),
|
||||
],
|
||||
"known_at_source": ["statutory_lag"] * 4,
|
||||
"has_estimated_lag": [True] * 4,
|
||||
},
|
||||
schema_overrides={
|
||||
"known_at": pl.Datetime("us", "UTC"),
|
||||
},
|
||||
)
|
||||
_write_parquet_via_duckdb(macro_df, curated / "macro" / "part.parquet")
|
||||
|
||||
seen_macro_counts: list[int] = []
|
||||
|
||||
def _latest_macro_regime_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame:
|
||||
macro_rows = inputs["macro"].sort("known_at").collect()
|
||||
seen_macro_counts.append(macro_rows.height)
|
||||
latest_val = float(macro_rows.get_column("value")[-1])
|
||||
bars = inputs["bars_1d"].collect()
|
||||
return bars.select(
|
||||
pl.col("listing_id"),
|
||||
pl.col("ts"),
|
||||
pl.col("ts").alias("known_at"),
|
||||
pl.lit(latest_val).cast(pl.Float64).alias("value"),
|
||||
)
|
||||
|
||||
defn = register_signal(
|
||||
name="macro_regime_latest",
|
||||
version=1,
|
||||
family="regime",
|
||||
kind="polars",
|
||||
inputs=("bars_1d", "macro"),
|
||||
warmup_bars=0,
|
||||
known_at_rule="max_input_known_at",
|
||||
polars_fn=_latest_macro_regime_fn,
|
||||
expression="latest(macro.value)",
|
||||
registry=create_feature_registry(),
|
||||
).definition
|
||||
|
||||
manifest = run_feature_batch(
|
||||
defn,
|
||||
curated_root=curated,
|
||||
from_year=2024,
|
||||
to_year=2025,
|
||||
vault_cutoff_date="2025-07-01",
|
||||
budget=budget,
|
||||
)
|
||||
assert [w.year for w in manifest.writes] == [2024, 2025]
|
||||
# 2024 sees 2023 + 2024 (2 rows, retaining prior-year history, excluding 2025 release);
|
||||
# 2025 sees 2023 + 2024 + 2025-03 (3 rows, excluding 2025-08 post-Vault release).
|
||||
assert seen_macro_counts == [2, 3]
|
||||
|
||||
out_2024 = pl.read_parquet(
|
||||
curated / "features" / "macro_regime_latest" / "v1" / "year=2024" / "part.parquet"
|
||||
)
|
||||
out_2025 = pl.read_parquet(
|
||||
curated / "features" / "macro_regime_latest" / "v1" / "year=2025" / "part.parquet"
|
||||
)
|
||||
assert out_2024.height > 0
|
||||
assert all(v == pytest.approx(2.0) for v in out_2024["value"].to_list())
|
||||
assert out_2025.height > 0
|
||||
assert all(v == pytest.approx(99.0) for v in out_2025["value"].to_list())
|
||||
|
||||
|
||||
def test_run_feature_batch_persists_definition_hash_and_blocks_cross_registry_overwrite(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
curated = tmp_path / "curated"
|
||||
_build_bars_and_events_fixtures(curated)
|
||||
budget = _make_budget(tmp_path)
|
||||
|
||||
def _fn_v1(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame:
|
||||
return inputs["bars_1d"].select(
|
||||
pl.col("listing_id"),
|
||||
pl.col("ts"),
|
||||
pl.col("ts").alias("known_at"),
|
||||
pl.col("close").cast(pl.Float64).alias("value"),
|
||||
)
|
||||
|
||||
reg_a = register_signal(
|
||||
name="close_level",
|
||||
version=1,
|
||||
family="technical",
|
||||
kind="polars",
|
||||
inputs=("bars_1d",),
|
||||
warmup_bars=0,
|
||||
known_at_rule="bar_close",
|
||||
polars_fn=_fn_v1,
|
||||
expression="close",
|
||||
registry=create_feature_registry(),
|
||||
)
|
||||
run_feature_batch(
|
||||
reg_a.definition,
|
||||
curated_root=curated,
|
||||
from_year=2025,
|
||||
to_year=2025,
|
||||
vault_cutoff_date="2025-07-01",
|
||||
budget=budget,
|
||||
)
|
||||
|
||||
out_2025 = curated / "features" / "close_level" / "v1" / "year=2025" / "part.parquet"
|
||||
meta_file = curated / "features" / "close_level" / "v1" / "_definition.json"
|
||||
assert meta_file.exists()
|
||||
original_bytes = out_2025.read_bytes()
|
||||
|
||||
# Fresh registry (simulating restarted notebook) with modified formula under same name + version
|
||||
def _fn_mutated(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame:
|
||||
return inputs["bars_1d"].select(
|
||||
pl.col("listing_id"),
|
||||
pl.col("ts"),
|
||||
pl.col("ts").alias("known_at"),
|
||||
(pl.col("close") * 2.0).cast(pl.Float64).alias("value"),
|
||||
)
|
||||
|
||||
reg_b = register_signal(
|
||||
name="close_level",
|
||||
version=1,
|
||||
family="technical",
|
||||
kind="polars",
|
||||
inputs=("bars_1d",),
|
||||
warmup_bars=0,
|
||||
known_at_rule="bar_close",
|
||||
polars_fn=_fn_mutated,
|
||||
expression="close * 2.0",
|
||||
registry=create_feature_registry(),
|
||||
)
|
||||
with pytest.raises(FeatureLibraryError) as err:
|
||||
run_feature_batch(
|
||||
reg_b.definition,
|
||||
curated_root=curated,
|
||||
from_year=2025,
|
||||
to_year=2025,
|
||||
vault_cutoff_date="2025-07-01",
|
||||
budget=budget,
|
||||
)
|
||||
assert err.value.code == "FEATURE_VERSION_IMMUTABLE"
|
||||
assert out_2025.read_bytes() == original_bytes
|
||||
|
||||
|
||||
def test_polars_batch_post_publication_failure_wraps_in_batch_write_failed_with_receipts(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
curated = tmp_path / "curated"
|
||||
_build_bars_and_events_fixtures(curated)
|
||||
budget = _make_budget(tmp_path)
|
||||
|
||||
call_count = 0
|
||||
|
||||
def _fail_second_year_fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame:
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
bars = inputs["bars_1d"].collect()
|
||||
if call_count == 2:
|
||||
# Return empty DataFrame missing required output columns on year 2025
|
||||
return pl.DataFrame()
|
||||
return bars.select(
|
||||
pl.col("listing_id"),
|
||||
pl.col("ts"),
|
||||
pl.col("ts").alias("known_at"),
|
||||
pl.col("close").cast(pl.Float64).alias("value"),
|
||||
)
|
||||
|
||||
defn = FeatureDefinition(
|
||||
name="fail_year2",
|
||||
version=1,
|
||||
family="technical",
|
||||
kind="polars",
|
||||
inputs=("bars_1d",),
|
||||
warmup_bars=0,
|
||||
known_at_rule="bar_close",
|
||||
polars_fn=_fail_second_year_fn,
|
||||
expression="close_fail_year2",
|
||||
)
|
||||
|
||||
with pytest.raises(FeatureLibraryError) as err:
|
||||
run_feature_batch(
|
||||
defn,
|
||||
curated_root=curated,
|
||||
from_year=2024,
|
||||
to_year=2025,
|
||||
vault_cutoff_date="2025-07-01",
|
||||
budget=budget,
|
||||
)
|
||||
|
||||
assert err.value.code == "BATCH_WRITE_FAILED"
|
||||
assert err.value.failed_year == 2025
|
||||
assert err.value.completed_years == (2024,)
|
||||
assert len(err.value.completed_writes) == 1
|
||||
assert err.value.completed_writes[0].year == 2024
|
||||
assert err.value.completed_writes[0].output_path.endswith(
|
||||
"features/fail_year2/v1/year=2024/part.parquet"
|
||||
)
|
||||
assert isinstance(err.value.cause, FeatureLibraryError)
|
||||
assert err.value.cause.code == "INVALID_SQL_PROJECTION"
|
||||
assert err.value.__cause__ is err.value.cause
|
||||
|
||||
|
||||
def test_sdk_exports() -> None:
|
||||
expected_exports = (
|
||||
"features",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue