T-200: M2.1t (retry of T-197) — Land the PostgreSQL executor factory for the MCP copilot stdio host: openResearchCopilotExecutor(config) in libs/data/postgres/src/research-copilot-executor.ts, reusing the finished T-197 branch work and completing QA sign-off (no new deps, no DuckDB, no bin, no curate-etl changes)
This commit is contained in:
commit
ccb37b793b
10 changed files with 3648 additions and 14 deletions
|
|
@ -59,6 +59,8 @@ const STRIPPED_TIMEOUT_PARAMS: ReadonlySet<string> = new Set([
|
|||
'connectiontimeoutmillis',
|
||||
]);
|
||||
|
||||
const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i;
|
||||
const PORT_DIGITS_RE = /^\d+$/;
|
||||
const CONTROL_CHAR_RE = /[\r\n\0]/;
|
||||
|
||||
/**
|
||||
|
|
@ -112,13 +114,28 @@ function invalidConfigError(): ResearchCopilotExecutorError {
|
|||
return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG);
|
||||
}
|
||||
|
||||
function assertValidPort(rawPort: string): void {
|
||||
if (!PORT_DIGITS_RE.test(rawPort)) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
const portNum = Number(rawPort);
|
||||
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
}
|
||||
|
||||
function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): PoolConfig {
|
||||
if (typeof config !== 'object' || config === null || typeof config.postgresUrl !== 'string') {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
const rawUrl = config.postgresUrl;
|
||||
if (rawUrl.length === 0 || rawUrl !== rawUrl.trim() || CONTROL_CHAR_RE.test(rawUrl)) {
|
||||
if (
|
||||
rawUrl.length === 0 ||
|
||||
rawUrl !== rawUrl.trim() ||
|
||||
CONTROL_CHAR_RE.test(rawUrl) ||
|
||||
!POSTGRES_URL_PREFIX_RE.test(rawUrl)
|
||||
) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
|
||||
|
|
@ -160,10 +177,15 @@ function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): Poo
|
|||
}
|
||||
|
||||
if (parsed.port.length > 0) {
|
||||
const portNum = Number(parsed.port);
|
||||
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
assertValidPort(parsed.port);
|
||||
}
|
||||
|
||||
const portQueryParams = parsed.searchParams.getAll('port');
|
||||
if (portQueryParams.length > 1) {
|
||||
throw invalidConfigError();
|
||||
}
|
||||
if (portQueryParams.length === 1) {
|
||||
assertValidPort((portQueryParams[0] as string).trim());
|
||||
}
|
||||
|
||||
if (!parsed.pathname.startsWith('/') || parsed.pathname.length <= 1) {
|
||||
|
|
|
|||
|
|
@ -62,6 +62,9 @@ function assertNoSecretsLeaked(error: unknown): void {
|
|||
expect(error).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const typed = error as ResearchCopilotExecutorError;
|
||||
expect((typed as { cause?: unknown }).cause).toBeUndefined();
|
||||
expect('cause' in typed).toBe(false);
|
||||
expect('detail' in typed).toBe(false);
|
||||
expect('extraDiag' in typed).toBe(false);
|
||||
const message = typed.message;
|
||||
for (const needle of [
|
||||
VALID_URL,
|
||||
|
|
@ -162,13 +165,21 @@ describe('openResearchCopilotExecutor', () => {
|
|||
'not-a-url',
|
||||
`http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
|
||||
`mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`,
|
||||
'postgres:/research_db?host=%2Ftmp',
|
||||
'postgresql:/research_db?host=%2Ftmp',
|
||||
'postgres:///research_db',
|
||||
'postgres:///research_db?host=',
|
||||
'postgres:///research_db?host=%20%20',
|
||||
'postgres:///research_db?host=/var/run/postgresql&host=/tmp',
|
||||
'postgres:///research_db?HOST=/var/run/postgresql',
|
||||
'postgres://copilot@db.example/?dbname=research',
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=0`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=70000`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=abc`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=5432&port=5433`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`,
|
||||
|
|
@ -288,8 +299,9 @@ describe('openResearchCopilotExecutor', () => {
|
|||
await handle.close();
|
||||
});
|
||||
|
||||
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors', async () => {
|
||||
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors without leaking cause or driver fields', async () => {
|
||||
let callCount = 0;
|
||||
const rawCause = new Error(`nested pgpass secret ${SECRET_PASS}`);
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
callCount += 1;
|
||||
|
|
@ -297,8 +309,14 @@ describe('openResearchCopilotExecutor', () => {
|
|||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
const pgErr = Object.assign(
|
||||
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`),
|
||||
{ code: '23505', detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})` }
|
||||
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`, {
|
||||
cause: rawCause,
|
||||
}),
|
||||
{
|
||||
code: '23505',
|
||||
detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})`,
|
||||
extraDiag: 'sensitive-driver-field',
|
||||
}
|
||||
);
|
||||
throw pgErr;
|
||||
},
|
||||
|
|
@ -321,8 +339,9 @@ describe('openResearchCopilotExecutor', () => {
|
|||
await handle.close();
|
||||
});
|
||||
|
||||
test('sanitizes generic query errors to QUERY_FAILED with no cause or raw text', async () => {
|
||||
test('sanitizes generic query errors to QUERY_FAILED with no cause, extra fields, or raw text', async () => {
|
||||
let callCount = 0;
|
||||
const rawCause = new Error(`nested env PGPASSWORD=${SECRET_PASS}`);
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
callCount += 1;
|
||||
|
|
@ -330,8 +349,10 @@ describe('openResearchCopilotExecutor', () => {
|
|||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
throw Object.assign(
|
||||
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`),
|
||||
{ code: '42P01' }
|
||||
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, {
|
||||
cause: rawCause,
|
||||
}),
|
||||
{ code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' }
|
||||
);
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -271,7 +271,7 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () =>
|
|||
expect(listed[0]?.id).toBe('finding-pgoptions-0001');
|
||||
});
|
||||
|
||||
test('supports migrated findings writes, reads, and idempotent same-ID 23505 replay', async () => {
|
||||
test('supports migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;
|
||||
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName);
|
||||
|
|
@ -306,7 +306,7 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () =>
|
|||
createdAt: FIXED_TS,
|
||||
});
|
||||
|
||||
// Same ID + same idempotency key collides on PK (23505) and must replay cleanly.
|
||||
// Same-ID, same-key replay must return the original finding and timestamp.
|
||||
const replay = await writePort.appendFinding(record, 'idem-key-0001');
|
||||
expect(replay).toEqual({
|
||||
status: 'replayed',
|
||||
|
|
@ -314,6 +314,19 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () =>
|
|||
createdAt: FIXED_TS,
|
||||
});
|
||||
|
||||
// Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly;
|
||||
// verify the executor preserves SQLSTATE 23505 without leaking driver fields.
|
||||
let pkCollisionErr: unknown;
|
||||
try {
|
||||
await writePort.appendFinding(record);
|
||||
} catch (err) {
|
||||
pkCollisionErr = err;
|
||||
}
|
||||
expect(pkCollisionErr).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((pkCollisionErr as ResearchCopilotExecutorError).code).toBe('23505');
|
||||
expect('cause' in (pkCollisionErr as object)).toBe(false);
|
||||
expect('detail' in (pkCollisionErr as object)).toBe(false);
|
||||
|
||||
const listed = await readers.listFindings({ query: 'Executor integration' });
|
||||
expect(listed).toHaveLength(1);
|
||||
expect(listed[0]?.id).toBe('finding-exec-0001');
|
||||
|
|
|
|||
|
|
@ -1571,6 +1571,59 @@ Inputs, defaults, and output rules:
|
|||
|
||||
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr.
|
||||
|
||||
## `curate-fundamentals` Command (`M2.2r`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_fundamentals.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming concatenated raw BSON `qmFinancials` and `qmFilings` dumps alongside `provider_mapping.tsv` and `listing_venues.tsv` into atomically published `<out>/fundamentals_pit/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (**file mode only** — `--from-mongo` and `--mongo-uri*` are not supported and are rejected as unknown flags).
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-fundamentals \
|
||||
--qm-financials qmFinancials.bson \
|
||||
--qm-filings qmFilings.bson \
|
||||
--provider-mapping provider_mapping.tsv \
|
||||
--listing-venues listing_venues.tsv \
|
||||
--out ./out \
|
||||
--currency-field currency \
|
||||
--filings-form-type-field formType \
|
||||
--k 4 \
|
||||
--quarterly-tokens Q1,Q2,Q3,Q4 \
|
||||
--annual-tokens FY \
|
||||
--revenue-field IncomeStatement.revenue \
|
||||
--net-income-field IncomeStatement.netIncome \
|
||||
--operating-cash-flow-field CashFlow.operatingCashFlow \
|
||||
--total-assets-field BalanceSheet.totalAssets \
|
||||
--total-equity-field BalanceSheet.totalEquity \
|
||||
--shares-outstanding-field BalanceSheet.sharesOutstanding
|
||||
```
|
||||
|
||||
Inputs, explicit configuration, defaults, and output rules:
|
||||
- **Required flags (no defaults, because live `qmFinancials`/`qmFilings` field names and token strings are unverified in the repository):**
|
||||
- `--qm-financials <path>`: concatenated raw BSON (`mongodump` `qmFinancials.bson`).
|
||||
- `--qm-filings <path>`: concatenated raw BSON (`mongodump` `qmFilings.bson`).
|
||||
- `--provider-mapping <path>`: headerless 5-column TSV (`source<TAB>provider_key<TAB>effective_from<TAB>effective_to<TAB>listing_id`, same format as `curate-bars-1d`).
|
||||
- `--listing-venues <path>`: headerless 2-column TSV (`listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII integer and `venue` is exact `us_tsx` or `tsxv_cse`).
|
||||
- `--out <dir>`: dataset root where `<out>/fundamentals_pit/year=YYYY/part.parquet` is atomically published.
|
||||
- `--currency-field <name>`: dotted BSON path to the reporting currency in `qmFinancials`.
|
||||
- `--filings-form-type-field <name>`: BSON field name for periodic filing form type in `qmFilings`.
|
||||
- `--k <N>`: strict positive integer (`>= 1`) snapshot period limit.
|
||||
- **Fiscal-period mode (mutually exclusive; supply exactly one mode):**
|
||||
- `--fiscal-period <quarterly|annual>` to assign a fixed period to every decoded document, **or**
|
||||
- `--quarterly-tokens <a,b,..>` and/or `--annual-tokens <a,b,..>` (comma-separated exact tokens preserving spelling and whitespace; empty/blank or overlapping tokens fail closed).
|
||||
- **Optional flags with verified defaults:**
|
||||
- `--financials-key-field` (default `qmSearchCode`)
|
||||
- `--period-end-field` (default `periodEndDate`)
|
||||
- `--report-date-field` (default `reportDate`)
|
||||
- `--report-period-field` (default `reportPeriod`)
|
||||
- `--filings-key-field` (default `symbol`)
|
||||
- `--filings-timefiled-field` (default `timefiled`)
|
||||
- `--mapping-source` (default `qm`)
|
||||
- **Optional flags defaulting to `None` (unconfigured metrics emit `NULL` in Parquet):**
|
||||
- `--revenue-field <path>`, `--net-income-field <path>`, `--operating-cash-flow-field <path>`, `--total-assets-field <path>`, `--total-equity-field <path>`, `--shares-outstanding-field <path>`
|
||||
- `--filings-filing-id-field <name>`, `--filings-url-field <name>`
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, combining or omitting fiscal-period modes, invalid `--k` (`0`, signs, non-digits, overflow), duplicate flags, unknown flags (including `--from-mongo` and `--mongo-uri*`), positional arguments, malformed dotted paths, overlapping `qmFilings` field names, or blank/overlapping fiscal tokens fail closed before touching `--out`, exiting non-zero with a single-line diagnostic error and usage on stderr. On success, stdout prints `format_curate_fundamentals_report`.
|
||||
|
||||
## Read-Only MongoDB URI Safety Guard (`M1.2ak`)
|
||||
|
||||
Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection.
|
||||
|
|
@ -1780,7 +1833,7 @@ curate-etl send-ilp \
|
|||
- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`).
|
||||
- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`).
|
||||
- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
|
||||
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: file-to-file runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access.
|
||||
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: CLI command (`curate-macro`), `macroAsOf` DuckDB reader, and live MongoDB access.
|
||||
|
||||
## Zero-Copy `teData` BSON Decoder (`M2.2p`)
|
||||
|
||||
|
|
@ -1796,3 +1849,11 @@ curate-etl send-ilp \
|
|||
|
||||
- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option<MacroSeriesTarget { country_iso, indicator, lag_class }>`; unmapped points are dropped into `dropped_unmapped_series` with no default lag, and conflicting lag classes targeting the same `(country_iso, indicator)` fail closed with `CurateMacroError::ConflictingLagClass` independent of input order before writing.
|
||||
- **Delegated builder & atomic publish:** Delegates filtering, sorting, deduplication, and `known_at` calculation unchanged to `build_macro_rows`, emits strictly ascending unique `MacroParquetRow`s with reconciling `CurateMacroStats` (`points_in == dropped_unmapped_series + builder.input`, `rows_out == builder.emitted`), and leaves `<out_dir>/macro/part.parquet` untouched on empty/all-unmapped input or any curation error.
|
||||
|
||||
## `run_curate_macro` File-to-File Runner (`M2.2s`)
|
||||
|
||||
`run_curate_macro` and `run_curate_macro_with_readers` (`src/run_curate_macro.rs`, tested in `src/run_curate_macro_tests.rs`) connect a concatenated length-prefixed raw BSON `teData` dump (`te_data`) and a caller-supplied series-map TSV (`series_map`) through `decode_te_data_buffer` and `curate_and_write_macro` into `<out_dir>/macro/part.parquet`:
|
||||
|
||||
- **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbol<TAB>country<TAB>category<TAB>country_iso<TAB>indicator<TAB>lag_class` (LF or CRLF line endings). Each data row must have 6 nonempty tab-separated columns with verbatim `(te_symbol, country, category)` keys (no trimming, no case folding), unique key triples (duplicates fail closed even when targets match), and an exact `lag_class` token in `policy_rate`, `monthly_release`, `gdp65`, or `gdp90`. There is no hardcoded default mapping or default lag class.
|
||||
- **Buffering, decode & fail-closed behavior:** Validates the full series map first, buffers the concatenated `teData` BSON input in memory (memory grows with dump size), counts per-document/per-point semantic rejects in `BsonTeDataDecodeStats`, and fails closed on the first structural BSON error (`TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`, `CorruptPointBson`) before publishing. Any I/O, TSV, structural BSON, or curation error (such as `ConflictingLagClass`) returns a single-line `RunCurateMacroError` and leaves `out_dir` and any pre-existing `<out_dir>/macro/part.parquet` byte-identical. Empty or all-unmapped inputs preserve `curate_and_write_macro`'s zero-row no-op.
|
||||
- **Governance, provenance & reproducibility:** Quant Research owns the coarse regime-use policy and the caller owns the mapping. Because `teData` carries final-revised `{d, v}` values without verified release timestamps or historical vintages, observations become available strictly at the estimated `known_at` (`00:00:00 UTC` of `period_date + lag_days`, `known_at_source = "publication_lag_estimate"`) for coarse regime use. For reproducible checks, pin the `teData` BSON dump and series-map TSV together against the pure stage and fixed expected rows. Real QA `teData` provider-label verification remains a manual host check, and `curate-macro` CLI / `--from-mongo` wiring are separate follow-ups.
|
||||
|
|
|
|||
|
|
@ -41,8 +41,13 @@ use crate::bson_qm_events::{
|
|||
DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD,
|
||||
DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD,
|
||||
};
|
||||
use crate::bson_qm_financials::{
|
||||
DEFAULT_QM_FINANCIALS_KEY_FIELD, DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD,
|
||||
DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD,
|
||||
};
|
||||
use crate::bson_stream::BsonStreamOptions;
|
||||
use crate::curate_adj::AdjPointInTimeFence;
|
||||
use crate::fundamentals::FiscalPeriod;
|
||||
use crate::ilp::IlpWriterOptions;
|
||||
use crate::ilp_send::SendIlpArgs;
|
||||
use crate::mongo_stream::{
|
||||
|
|
@ -56,6 +61,9 @@ use crate::run_curate_bars::{
|
|||
use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE};
|
||||
use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
|
||||
use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE};
|
||||
use crate::run_curate_fundamentals::{
|
||||
CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
|
||||
};
|
||||
use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL};
|
||||
use crate::run_curate_fx_1m::CurateFx1mArgs;
|
||||
use crate::run_curate_posts::{
|
||||
|
|
@ -88,6 +96,7 @@ pub enum CliAction {
|
|||
CurateBars1m(CurateBars1mArgs),
|
||||
CurateFx1m(CurateFx1mArgs),
|
||||
CuratePosts(CuratePostsArgs),
|
||||
CurateFundamentals(CurateFundamentalsArgs),
|
||||
SendIlp(SendIlpArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
|
|
@ -156,6 +165,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-<NN>.ilp\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
Curate ceoPosts from BSON + provider_mapping TSV into <out>/events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\
|
||||
{name} curate-fundamentals --qm-financials <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\n\
|
||||
Curate point-in-time fundamentals from qmFinancials + qmFilings BSON + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (file mode only; defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\n\
|
||||
Stream published ILP v2 shard files to an explicit QuestDB TCP endpoint (no default address; success means bytes were accepted by local sockets, not rows committed — verify row counts via PGWire; ILP v2 binary doubles over TCP on QuestDB 10.2.0 are unverified until the manual quant load check)\n\
|
||||
{name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
|
||||
|
|
@ -209,6 +220,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
|
||||
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-fundamentals --qm-financials <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
|
|
@ -1295,6 +1307,325 @@ fn parse_curate_posts_args(args: &[&str]) -> Result<CliAction, String> {
|
|||
Ok(CliAction::CuratePosts(parsed))
|
||||
}
|
||||
|
||||
fn sanitize_single_line(s: &str) -> String {
|
||||
s.replace('\r', "\\r").replace('\n', "\\n")
|
||||
}
|
||||
|
||||
fn set_token_list(
|
||||
slot: &mut Option<Vec<String>>,
|
||||
flag_name: &str,
|
||||
raw: &str,
|
||||
) -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate flag '{flag_name}'"));
|
||||
}
|
||||
if raw.is_empty() {
|
||||
return Err(format!("empty value for flag '{flag_name}'"));
|
||||
}
|
||||
*slot = Some(raw.split(',').map(str::to_string).collect());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_curate_fundamentals_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
parse_curate_fundamentals_args_inner(args).map_err(|e| sanitize_single_line(&e))
|
||||
}
|
||||
|
||||
fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut qm_financials: Option<PathBuf> = None;
|
||||
let mut qm_filings: Option<PathBuf> = None;
|
||||
let mut provider_mapping: Option<PathBuf> = None;
|
||||
let mut listing_venues: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
let mut currency_field: Option<String> = None;
|
||||
let mut filings_form_type_field: Option<String> = None;
|
||||
let mut k: Option<usize> = None;
|
||||
let mut fiscal_period_fixed: Option<FiscalPeriod> = None;
|
||||
let mut quarterly_tokens: Option<Vec<String>> = None;
|
||||
let mut annual_tokens: Option<Vec<String>> = None;
|
||||
let mut financials_key_field: Option<String> = None;
|
||||
let mut period_end_field: Option<String> = None;
|
||||
let mut report_date_field: Option<String> = None;
|
||||
let mut report_period_field: Option<String> = None;
|
||||
let mut filings_key_field: Option<String> = None;
|
||||
let mut filings_timefiled_field: Option<String> = None;
|
||||
let mut mapping_source: Option<String> = None;
|
||||
let mut revenue_field: Option<String> = None;
|
||||
let mut net_income_field: Option<String> = None;
|
||||
let mut operating_cash_flow_field: Option<String> = None;
|
||||
let mut total_assets_field: Option<String> = None;
|
||||
let mut total_equity_field: Option<String> = None;
|
||||
let mut shares_outstanding_field: Option<String> = None;
|
||||
let mut filings_filing_id_field: Option<String> = None;
|
||||
let mut filings_url_field: Option<String> = None;
|
||||
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let token = args[i];
|
||||
if !token.starts_with("--") {
|
||||
return Err(format!(
|
||||
"unexpected positional argument '{token}' for curate-fundamentals"
|
||||
));
|
||||
}
|
||||
|
||||
let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag);
|
||||
if !matches!(
|
||||
flag_name,
|
||||
"--qm-financials"
|
||||
| "--qm-filings"
|
||||
| "--provider-mapping"
|
||||
| "--listing-venues"
|
||||
| "--out"
|
||||
| "--currency-field"
|
||||
| "--filings-form-type-field"
|
||||
| "--k"
|
||||
| "--fiscal-period"
|
||||
| "--quarterly-tokens"
|
||||
| "--annual-tokens"
|
||||
| "--financials-key-field"
|
||||
| "--period-end-field"
|
||||
| "--report-date-field"
|
||||
| "--report-period-field"
|
||||
| "--filings-key-field"
|
||||
| "--filings-timefiled-field"
|
||||
| "--mapping-source"
|
||||
| "--revenue-field"
|
||||
| "--net-income-field"
|
||||
| "--operating-cash-flow-field"
|
||||
| "--total-assets-field"
|
||||
| "--total-equity-field"
|
||||
| "--shares-outstanding-field"
|
||||
| "--filings-filing-id-field"
|
||||
| "--filings-url-field"
|
||||
) {
|
||||
return Err(format!(
|
||||
"unknown flag '{flag_name}' for curate-fundamentals"
|
||||
));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((flag, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(flag, v)
|
||||
} else {
|
||||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
||||
match flag {
|
||||
"--qm-financials" => set_path(&mut qm_financials, "--qm-financials", value)?,
|
||||
"--qm-filings" => set_path(&mut qm_filings, "--qm-filings", value)?,
|
||||
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
|
||||
"--listing-venues" => set_path(&mut listing_venues, "--listing-venues", value)?,
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
"--currency-field" => set_name(&mut currency_field, "--currency-field", value)?,
|
||||
"--filings-form-type-field" => {
|
||||
set_name(&mut filings_form_type_field, "--filings-form-type-field", value)?;
|
||||
}
|
||||
"--k" => {
|
||||
if k.is_some() {
|
||||
return Err("duplicate flag '--k'".to_string());
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty value for flag '--k'".to_string());
|
||||
}
|
||||
if !value.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(format!(
|
||||
"invalid --k '{value}' (expected a positive integer >= 1)"
|
||||
));
|
||||
}
|
||||
let parsed = value.parse::<usize>().map_err(|_| {
|
||||
format!("invalid --k '{value}' (expected a positive integer >= 1)")
|
||||
})?;
|
||||
if parsed == 0 {
|
||||
return Err(format!(
|
||||
"invalid --k '{value}' (expected a positive integer >= 1)"
|
||||
));
|
||||
}
|
||||
k = Some(parsed);
|
||||
}
|
||||
"--fiscal-period" => {
|
||||
if fiscal_period_fixed.is_some() {
|
||||
return Err("duplicate flag '--fiscal-period'".to_string());
|
||||
}
|
||||
fiscal_period_fixed = Some(match value {
|
||||
"quarterly" => FiscalPeriod::Quarterly,
|
||||
"annual" => FiscalPeriod::Annual,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"invalid --fiscal-period '{value}' (expected 'quarterly' or 'annual')"
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
"--quarterly-tokens" => {
|
||||
set_token_list(&mut quarterly_tokens, "--quarterly-tokens", value)?;
|
||||
}
|
||||
"--annual-tokens" => set_token_list(&mut annual_tokens, "--annual-tokens", value)?,
|
||||
"--financials-key-field" => {
|
||||
set_name(&mut financials_key_field, "--financials-key-field", value)?;
|
||||
}
|
||||
"--period-end-field" => set_name(&mut period_end_field, "--period-end-field", value)?,
|
||||
"--report-date-field" => {
|
||||
set_name(&mut report_date_field, "--report-date-field", value)?;
|
||||
}
|
||||
"--report-period-field" => {
|
||||
set_name(&mut report_period_field, "--report-period-field", value)?;
|
||||
}
|
||||
"--filings-key-field" => {
|
||||
set_name(&mut filings_key_field, "--filings-key-field", value)?;
|
||||
}
|
||||
"--filings-timefiled-field" => {
|
||||
set_name(
|
||||
&mut filings_timefiled_field,
|
||||
"--filings-timefiled-field",
|
||||
value,
|
||||
)?;
|
||||
}
|
||||
"--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?,
|
||||
"--revenue-field" => set_name(&mut revenue_field, "--revenue-field", value)?,
|
||||
"--net-income-field" => set_name(&mut net_income_field, "--net-income-field", value)?,
|
||||
"--operating-cash-flow-field" => {
|
||||
set_name(
|
||||
&mut operating_cash_flow_field,
|
||||
"--operating-cash-flow-field",
|
||||
value,
|
||||
)?;
|
||||
}
|
||||
"--total-assets-field" => {
|
||||
set_name(&mut total_assets_field, "--total-assets-field", value)?;
|
||||
}
|
||||
"--total-equity-field" => {
|
||||
set_name(&mut total_equity_field, "--total-equity-field", value)?;
|
||||
}
|
||||
"--shares-outstanding-field" => {
|
||||
set_name(
|
||||
&mut shares_outstanding_field,
|
||||
"--shares-outstanding-field",
|
||||
value,
|
||||
)?;
|
||||
}
|
||||
"--filings-filing-id-field" => {
|
||||
set_name(
|
||||
&mut filings_filing_id_field,
|
||||
"--filings-filing-id-field",
|
||||
value,
|
||||
)?;
|
||||
}
|
||||
"--filings-url-field" => {
|
||||
set_name(&mut filings_url_field, "--filings-url-field", value)?;
|
||||
}
|
||||
other => return Err(format!("unknown flag '{other}' for curate-fundamentals")),
|
||||
}
|
||||
}
|
||||
|
||||
let qm_financials =
|
||||
qm_financials.ok_or_else(|| "missing required flag '--qm-financials'".to_string())?;
|
||||
let qm_filings =
|
||||
qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?;
|
||||
let provider_mapping =
|
||||
provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let listing_venues =
|
||||
listing_venues.ok_or_else(|| "missing required flag '--listing-venues'".to_string())?;
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
let currency_field =
|
||||
currency_field.ok_or_else(|| "missing required flag '--currency-field'".to_string())?;
|
||||
let filings_form_type_field = filings_form_type_field
|
||||
.ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?;
|
||||
let k = k.ok_or_else(|| "missing required flag '--k'".to_string())?;
|
||||
|
||||
let fiscal_period = match (fiscal_period_fixed, quarterly_tokens, annual_tokens) {
|
||||
(Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
|
||||
return Err(
|
||||
"cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
(Some(fixed), None, None) => CurateFundamentalsFiscalPeriod::Fixed(fixed),
|
||||
(None, Some(quarterly), Some(annual)) => {
|
||||
CurateFundamentalsFiscalPeriod::ByTokens { quarterly, annual }
|
||||
}
|
||||
(None, Some(quarterly), None) => CurateFundamentalsFiscalPeriod::ByTokens {
|
||||
quarterly,
|
||||
annual: Vec::new(),
|
||||
},
|
||||
(None, None, Some(annual)) => CurateFundamentalsFiscalPeriod::ByTokens {
|
||||
quarterly: Vec::new(),
|
||||
annual,
|
||||
},
|
||||
(None, None, None) => {
|
||||
return Err(
|
||||
"missing required fiscal-period mode: pass either '--fiscal-period <quarterly|annual>' or '--quarterly-tokens' / '--annual-tokens'"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut parsed = CurateFundamentalsArgs::with_verified_defaults(
|
||||
qm_financials,
|
||||
qm_filings,
|
||||
provider_mapping,
|
||||
listing_venues,
|
||||
out_dir,
|
||||
currency_field,
|
||||
revenue_field,
|
||||
net_income_field,
|
||||
operating_cash_flow_field,
|
||||
total_assets_field,
|
||||
total_equity_field,
|
||||
shares_outstanding_field,
|
||||
fiscal_period,
|
||||
filings_form_type_field,
|
||||
k,
|
||||
);
|
||||
if let Some(v) = financials_key_field {
|
||||
parsed.financials_key_field = v;
|
||||
}
|
||||
if let Some(v) = period_end_field {
|
||||
parsed.financials_period_end_field = v;
|
||||
}
|
||||
if let Some(v) = report_date_field {
|
||||
parsed.financials_report_date_field = v;
|
||||
}
|
||||
if let Some(v) = report_period_field {
|
||||
parsed.financials_report_period_field = v;
|
||||
}
|
||||
if let Some(v) = filings_key_field {
|
||||
parsed.filings_key_field = v;
|
||||
}
|
||||
if let Some(v) = filings_timefiled_field {
|
||||
parsed.filings_timefiled_field = v;
|
||||
}
|
||||
if let Some(v) = filings_filing_id_field {
|
||||
parsed.filings_filing_id_field = Some(v);
|
||||
}
|
||||
if let Some(v) = filings_url_field {
|
||||
parsed.filings_url_field = Some(v);
|
||||
}
|
||||
if let Some(v) = mapping_source {
|
||||
parsed.mapping_source = v;
|
||||
}
|
||||
|
||||
parsed
|
||||
.financials_field_names()
|
||||
.validate()
|
||||
.map_err(|e| e.to_string())?;
|
||||
parsed
|
||||
.filings_field_names()
|
||||
.validate()
|
||||
.map_err(|e| e.to_string())?;
|
||||
parsed
|
||||
.fiscal_period
|
||||
.with_borrowed(|period| period.validate())
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(CliAction::CurateFundamentals(parsed))
|
||||
}
|
||||
|
||||
fn parse_curate_events_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut mongo = MongoFlagState::default();
|
||||
let mut qm_filings: Option<PathBuf> = None;
|
||||
|
|
@ -1915,6 +2246,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest),
|
||||
["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest),
|
||||
["curate-posts", rest @ ..] => parse_curate_posts_args(rest),
|
||||
["curate-fundamentals", rest @ ..] => parse_curate_fundamentals_args(rest),
|
||||
["send-ilp", rest @ ..] => parse_send_ilp_args(rest),
|
||||
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||
["bench-split", raw] => match raw.parse::<usize>() {
|
||||
|
|
@ -4895,6 +5227,466 @@ mod tests {
|
|||
assert!(err.contains("cannot share BSON field 'shared'"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_fundamentals_parsing_validation_and_usage() {
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
let stderr_usage = format_usage_stderr("curate-etl");
|
||||
for text in [&usage, &stderr_usage] {
|
||||
assert!(text.contains("curate-fundamentals --qm-financials"), "{text}");
|
||||
assert!(text.contains("--fiscal-period <quarterly|annual>"), "{text}");
|
||||
assert!(text.contains("--quarterly-tokens"), "{text}");
|
||||
assert!(text.contains("--annual-tokens"), "{text}");
|
||||
}
|
||||
|
||||
// Minimal valid invocation with --fiscal-period quarterly fills all verified defaults and None metrics
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&[
|
||||
"curate-fundamentals",
|
||||
"--qm-financials",
|
||||
"fin.bson",
|
||||
"--qm-filings",
|
||||
"fil.bson",
|
||||
"--provider-mapping",
|
||||
"map.tsv",
|
||||
"--listing-venues",
|
||||
"venues.tsv",
|
||||
"--out",
|
||||
"fund_out",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--k",
|
||||
"4",
|
||||
"--fiscal-period",
|
||||
"quarterly",
|
||||
])),
|
||||
Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs {
|
||||
qm_financials: PathBuf::from("fin.bson"),
|
||||
qm_filings: PathBuf::from("fil.bson"),
|
||||
provider_mapping: PathBuf::from("map.tsv"),
|
||||
listing_venues: PathBuf::from("venues.tsv"),
|
||||
out_dir: PathBuf::from("fund_out"),
|
||||
financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(),
|
||||
financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(),
|
||||
financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(),
|
||||
financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD
|
||||
.to_string(),
|
||||
financials_currency_field: "currency".to_string(),
|
||||
financials_revenue_field: None,
|
||||
financials_net_income_field: None,
|
||||
financials_operating_cash_flow_field: None,
|
||||
financials_total_assets_field: None,
|
||||
financials_total_equity_field: None,
|
||||
financials_shares_outstanding_field: None,
|
||||
fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly),
|
||||
filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(),
|
||||
filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(),
|
||||
filings_form_type_field: "formType".to_string(),
|
||||
filings_filing_id_field: None,
|
||||
filings_url_field: None,
|
||||
mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(),
|
||||
k: 4,
|
||||
}))
|
||||
);
|
||||
|
||||
// Fixed annual mode
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&[
|
||||
"curate-fundamentals",
|
||||
"--qm-financials=fin.bson",
|
||||
"--qm-filings=fil.bson",
|
||||
"--provider-mapping=map.tsv",
|
||||
"--listing-venues=venues.tsv",
|
||||
"--out=fund_out",
|
||||
"--currency-field=currency",
|
||||
"--filings-form-type-field=formType",
|
||||
"--k=2",
|
||||
"--fiscal-period=annual",
|
||||
])),
|
||||
Ok(CliAction::CurateFundamentals(
|
||||
CurateFundamentalsArgs::with_verified_defaults(
|
||||
PathBuf::from("fin.bson"),
|
||||
PathBuf::from("fil.bson"),
|
||||
PathBuf::from("map.tsv"),
|
||||
PathBuf::from("venues.tsv"),
|
||||
PathBuf::from("fund_out"),
|
||||
"currency",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Annual),
|
||||
"formType",
|
||||
2,
|
||||
)
|
||||
))
|
||||
);
|
||||
|
||||
// All optional flags overridden with --flag=value and paired token lists (preserving token whitespace)
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&[
|
||||
"curate-fundamentals",
|
||||
"--qm-financials=fin2.bson",
|
||||
"--qm-filings=fil2.bson",
|
||||
"--provider-mapping=map2.tsv",
|
||||
"--listing-venues=venues2.tsv",
|
||||
"--out=out2",
|
||||
"--currency-field=meta.ccy",
|
||||
"--filings-form-type-field=filingForm",
|
||||
"--k=8",
|
||||
"--quarterly-tokens=Q1,Q2, Q3 ,Q4",
|
||||
"--annual-tokens=FY,Annual",
|
||||
"--financials-key-field=secId",
|
||||
"--period-end-field=periodEnd",
|
||||
"--report-date-field=reportedAt",
|
||||
"--report-period-field=periodCode",
|
||||
"--revenue-field=IncomeStatement.revenue",
|
||||
"--net-income-field=IncomeStatement.netIncome",
|
||||
"--operating-cash-flow-field=CashFlow.operatingCashFlow",
|
||||
"--total-assets-field=BalanceSheet.totalAssets",
|
||||
"--total-equity-field=BalanceSheet.totalEquity",
|
||||
"--shares-outstanding-field=BalanceSheet.sharesOutstanding",
|
||||
"--filings-key-field=qmId",
|
||||
"--filings-timefiled-field=filedAt",
|
||||
"--filings-filing-id-field=filingId",
|
||||
"--filings-url-field=filingUrl",
|
||||
"--mapping-source=qm_alt",
|
||||
])),
|
||||
Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs {
|
||||
qm_financials: PathBuf::from("fin2.bson"),
|
||||
qm_filings: PathBuf::from("fil2.bson"),
|
||||
provider_mapping: PathBuf::from("map2.tsv"),
|
||||
listing_venues: PathBuf::from("venues2.tsv"),
|
||||
out_dir: PathBuf::from("out2"),
|
||||
financials_key_field: "secId".to_string(),
|
||||
financials_period_end_field: "periodEnd".to_string(),
|
||||
financials_report_date_field: "reportedAt".to_string(),
|
||||
financials_report_period_field: "periodCode".to_string(),
|
||||
financials_currency_field: "meta.ccy".to_string(),
|
||||
financials_revenue_field: Some("IncomeStatement.revenue".to_string()),
|
||||
financials_net_income_field: Some("IncomeStatement.netIncome".to_string()),
|
||||
financials_operating_cash_flow_field: Some(
|
||||
"CashFlow.operatingCashFlow".to_string()
|
||||
),
|
||||
financials_total_assets_field: Some("BalanceSheet.totalAssets".to_string()),
|
||||
financials_total_equity_field: Some("BalanceSheet.totalEquity".to_string()),
|
||||
financials_shares_outstanding_field: Some(
|
||||
"BalanceSheet.sharesOutstanding".to_string()
|
||||
),
|
||||
fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens {
|
||||
quarterly: vec![
|
||||
"Q1".to_string(),
|
||||
"Q2".to_string(),
|
||||
" Q3 ".to_string(),
|
||||
"Q4".to_string(),
|
||||
],
|
||||
annual: vec!["FY".to_string(), "Annual".to_string()],
|
||||
},
|
||||
filings_key_field: "qmId".to_string(),
|
||||
filings_timefiled_field: "filedAt".to_string(),
|
||||
filings_form_type_field: "filingForm".to_string(),
|
||||
filings_filing_id_field: Some("filingId".to_string()),
|
||||
filings_url_field: Some("filingUrl".to_string()),
|
||||
mapping_source: "qm_alt".to_string(),
|
||||
k: 8,
|
||||
}))
|
||||
);
|
||||
|
||||
// Single token-list modes (quarterly-only and annual-only)
|
||||
let q_only = parse_args(&to_args(&[
|
||||
"curate-fundamentals",
|
||||
"--qm-financials",
|
||||
"fin.bson",
|
||||
"--qm-filings",
|
||||
"fil.bson",
|
||||
"--provider-mapping",
|
||||
"map.tsv",
|
||||
"--listing-venues",
|
||||
"venues.tsv",
|
||||
"--out",
|
||||
"out",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--k",
|
||||
"1",
|
||||
"--quarterly-tokens",
|
||||
"Q1,Q2",
|
||||
]))
|
||||
.expect("quarterly-only token list");
|
||||
assert!(matches!(
|
||||
q_only,
|
||||
CliAction::CurateFundamentals(CurateFundamentalsArgs {
|
||||
fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens {
|
||||
ref quarterly,
|
||||
ref annual,
|
||||
},
|
||||
..
|
||||
}) if quarterly == &["Q1", "Q2"] && annual.is_empty()
|
||||
));
|
||||
|
||||
let a_only = parse_args(&to_args(&[
|
||||
"curate-fundamentals",
|
||||
"--qm-financials",
|
||||
"fin.bson",
|
||||
"--qm-filings",
|
||||
"fil.bson",
|
||||
"--provider-mapping",
|
||||
"map.tsv",
|
||||
"--listing-venues",
|
||||
"venues.tsv",
|
||||
"--out",
|
||||
"out",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--k",
|
||||
"1",
|
||||
"--annual-tokens",
|
||||
"FY",
|
||||
]))
|
||||
.expect("annual-only token list");
|
||||
assert!(matches!(
|
||||
a_only,
|
||||
CliAction::CurateFundamentals(CurateFundamentalsArgs {
|
||||
fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens {
|
||||
ref quarterly,
|
||||
ref annual,
|
||||
},
|
||||
..
|
||||
}) if quarterly.is_empty() && annual == &["FY"]
|
||||
));
|
||||
|
||||
// Each omitted required flag errors
|
||||
let required: [(&str, &str); 8] = [
|
||||
("--qm-financials", "fin.bson"),
|
||||
("--qm-filings", "fil.bson"),
|
||||
("--provider-mapping", "map.tsv"),
|
||||
("--listing-venues", "venues.tsv"),
|
||||
("--out", "out"),
|
||||
("--currency-field", "currency"),
|
||||
("--filings-form-type-field", "formType"),
|
||||
("--k", "4"),
|
||||
];
|
||||
for omit in 0..required.len() {
|
||||
let mut argv = vec!["curate-fundamentals", "--fiscal-period", "quarterly"];
|
||||
for (idx, &(flag, val)) in required.iter().enumerate() {
|
||||
if idx != omit {
|
||||
argv.push(flag);
|
||||
argv.push(val);
|
||||
}
|
||||
}
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
let missing_flag = required[omit].0;
|
||||
assert!(
|
||||
err.contains(&format!("missing required flag '{missing_flag}'")),
|
||||
"expected missing {missing_flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Neither fiscal mode supplied
|
||||
let mut base_no_fiscal = vec!["curate-fundamentals"];
|
||||
for &(flag, val) in &required {
|
||||
base_no_fiscal.push(flag);
|
||||
base_no_fiscal.push(val);
|
||||
}
|
||||
let err = parse_args(&to_args(&base_no_fiscal)).unwrap_err();
|
||||
assert!(err.contains("missing required fiscal-period mode"), "{err}");
|
||||
|
||||
// Both fiscal modes supplied
|
||||
for extra in [
|
||||
&["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"][..],
|
||||
&["--fiscal-period", "annual", "--annual-tokens", "FY"][..],
|
||||
&[
|
||||
"--fiscal-period",
|
||||
"quarterly",
|
||||
"--quarterly-tokens",
|
||||
"Q1",
|
||||
"--annual-tokens",
|
||||
"FY",
|
||||
][..],
|
||||
] {
|
||||
let mut argv = base_no_fiscal.clone();
|
||||
argv.extend_from_slice(extra);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(err.contains("cannot combine '--fiscal-period'"), "{err}");
|
||||
}
|
||||
|
||||
// Invalid fixed --fiscal-period
|
||||
for bad in ["", " ", "q", "QUARTERLY", "ANNUAL", "semi-annual"] {
|
||||
let mut argv = base_no_fiscal.clone();
|
||||
argv.extend_from_slice(&["--fiscal-period", bad]);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(err.contains("invalid --fiscal-period"), "{bad}: {err}");
|
||||
}
|
||||
|
||||
// Empty / blank tokens and token in both lists
|
||||
for (flag, bad_tokens) in [
|
||||
("--quarterly-tokens", ""),
|
||||
("--annual-tokens", ""),
|
||||
("--quarterly-tokens", " "),
|
||||
("--quarterly-tokens", "Q1,,Q2"),
|
||||
("--quarterly-tokens", ",Q1"),
|
||||
("--quarterly-tokens", "Q1,"),
|
||||
("--annual-tokens", "FY, ,Annual"),
|
||||
] {
|
||||
let mut argv = base_no_fiscal.clone();
|
||||
let tok = format!("{flag}={bad_tokens}");
|
||||
argv.push(&tok);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("empty value for flag") || err.contains("must not be empty or blank"),
|
||||
"{flag}={bad_tokens:?}: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut overlap = base_no_fiscal.clone();
|
||||
overlap.extend_from_slice(&["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"]);
|
||||
let err = parse_args(&to_args(&overlap)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("cannot appear in both quarterly and annual lists"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
// Malformed financials dotted path and overlapping filings fields
|
||||
for bad_path in ["Income..revenue", ".revenue", "revenue.", "Income. .rev"] {
|
||||
let mut argv = base_no_fiscal.clone();
|
||||
argv.extend_from_slice(&["--fiscal-period", "quarterly", "--revenue-field", bad_path]);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("empty or blank segment"),
|
||||
"{bad_path}: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut filings_collision = base_no_fiscal.clone();
|
||||
filings_collision.extend_from_slice(&[
|
||||
"--fiscal-period",
|
||||
"quarterly",
|
||||
"--filings-filing-id-field",
|
||||
"timefiled",
|
||||
]);
|
||||
let err = parse_args(&to_args(&filings_collision)).unwrap_err();
|
||||
assert!(err.contains("cannot share BSON field 'timefiled'"), "{err}");
|
||||
|
||||
// Invalid --k values: 0, -1, +1, abc, overflow, empty
|
||||
for bad_k in [
|
||||
"0",
|
||||
"-1",
|
||||
"+1",
|
||||
"abc",
|
||||
"999999999999999999999999999999",
|
||||
"",
|
||||
] {
|
||||
let mut argv = vec![
|
||||
"curate-fundamentals",
|
||||
"--qm-financials",
|
||||
"fin.bson",
|
||||
"--qm-filings",
|
||||
"fil.bson",
|
||||
"--provider-mapping",
|
||||
"map.tsv",
|
||||
"--listing-venues",
|
||||
"venues.tsv",
|
||||
"--out",
|
||||
"out",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--fiscal-period",
|
||||
"quarterly",
|
||||
];
|
||||
let k_tok = format!("--k={bad_k}");
|
||||
argv.push(&k_tok);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("invalid --k") || err.contains("empty value for flag '--k'"),
|
||||
"k={bad_k:?}: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Duplicate flags
|
||||
for (dup_flag, extra) in [
|
||||
("--qm-financials", &["--qm-financials=other.bson"][..]),
|
||||
("--k", &["--k=2"][..]),
|
||||
("--fiscal-period", &["--fiscal-period=annual"][..]),
|
||||
("--revenue-field", &["--revenue-field=a", "--revenue-field=b"][..]),
|
||||
] {
|
||||
let mut argv = base_no_fiscal.clone();
|
||||
argv.extend_from_slice(&["--fiscal-period", "quarterly"]);
|
||||
argv.extend_from_slice(extra);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("duplicate flag '{dup_flag}'")),
|
||||
"{dup_flag}: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut dup_tok = base_no_fiscal.clone();
|
||||
dup_tok.extend_from_slice(&["--quarterly-tokens=Q1", "--quarterly-tokens=Q2"]);
|
||||
let err = parse_args(&to_args(&dup_tok)).unwrap_err();
|
||||
assert!(err.contains("duplicate flag '--quarterly-tokens'"), "{err}");
|
||||
|
||||
// Unknown flags including --from-mongo and --mongo-uri (rejected before consuming a value)
|
||||
for (args, expected_flag) in [
|
||||
(&["curate-fundamentals", "--bogus", "1"][..], "--bogus"),
|
||||
(&["curate-fundamentals", "--from-mongo"][..], "--from-mongo"),
|
||||
(
|
||||
&["curate-fundamentals", "--from-mongo", "--out", "o"][..],
|
||||
"--from-mongo",
|
||||
),
|
||||
(
|
||||
&["curate-fundamentals", "--from-mongo=true"][..],
|
||||
"--from-mongo",
|
||||
),
|
||||
(
|
||||
&["curate-fundamentals", "--mongo-uri", "mongodb://host"][..],
|
||||
"--mongo-uri",
|
||||
),
|
||||
(
|
||||
&["curate-fundamentals", "--mongo-uri-env=MONGODB_READ_URI"][..],
|
||||
"--mongo-uri-env",
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(args)).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
format!("unknown flag '{expected_flag}' for curate-fundamentals")
|
||||
);
|
||||
}
|
||||
|
||||
// Positional argument rejected
|
||||
let err = parse_args(&to_args(&["curate-fundamentals", "extra"])).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
"unexpected positional argument 'extra' for curate-fundamentals"
|
||||
);
|
||||
|
||||
// Missing value at end or before another flag
|
||||
let err = parse_args(&to_args(&["curate-fundamentals", "--qm-financials"])).unwrap_err();
|
||||
assert_eq!(err, "missing value for flag '--qm-financials'");
|
||||
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-fundamentals",
|
||||
"--k",
|
||||
"--out",
|
||||
"o",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert_eq!(err, "missing value for flag '--k'");
|
||||
|
||||
// Multiline arguments are sanitized to a single diagnostic line
|
||||
let err = parse_args(&to_args(&["curate-fundamentals", "bad\nline\rarg"])).unwrap_err();
|
||||
assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}");
|
||||
assert!(err.contains("bad\\nline\\rarg"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_send_ilp_valid_space_and_equals_forms_and_all_allowed_prefixes() {
|
||||
for prefix in ["bars_1m", "bars_1m_qm", "fx_1m"] {
|
||||
|
|
|
|||
|
|
@ -388,6 +388,13 @@ pub use run_curate_fundamentals::{
|
|||
CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_macro;
|
||||
pub use run_curate_macro::{
|
||||
format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro,
|
||||
run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap,
|
||||
RunCurateMacroError, MACRO_SERIES_MAP_HEADER,
|
||||
};
|
||||
|
||||
pub mod run_curate_shorts;
|
||||
pub use run_curate_shorts::{
|
||||
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,
|
||||
|
|
|
|||
|
|
@ -29,6 +29,9 @@ use curate_etl::run_curate_corporate_actions::{
|
|||
format_curate_corporate_actions_report, run_curate_corporate_actions,
|
||||
};
|
||||
use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events};
|
||||
use curate_etl::run_curate_fundamentals::{
|
||||
format_curate_fundamentals_report, run_curate_fundamentals,
|
||||
};
|
||||
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
|
||||
use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m};
|
||||
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts};
|
||||
|
|
@ -231,6 +234,18 @@ fn main() -> ExitCode {
|
|||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateFundamentals(curate_args)) => {
|
||||
match run_curate_fundamentals(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_fundamentals_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_ilp_send_report(&report));
|
||||
|
|
|
|||
657
tools/curate-etl/src/run_curate_macro.rs
Normal file
657
tools/curate-etl/src/run_curate_macro.rs
Normal file
|
|
@ -0,0 +1,657 @@
|
|||
//! File-to-file `curate-macro` runner (`M2.2s`).
|
||||
//!
|
||||
//! Reads a concatenated length-prefixed raw BSON `teData` dump and a caller-supplied
|
||||
//! series-map TSV into an atomically published `<out_dir>/macro/part.parquet` dataset via
|
||||
//! [`curate_and_write_macro`].
|
||||
//!
|
||||
//! # Governance & Series-Map Contract
|
||||
//! - **Caller-owned mapping (no defaults):** Every row in the series-map TSV maps a verbatim
|
||||
//! `(te_symbol, country, category)` triple (no trimming, no case folding) to a
|
||||
//! [`MacroSeriesTarget`] (`country_iso`, `indicator`, `lag_class`). No country-to-ISO,
|
||||
//! indicator-name, or lag-class mapping is hardcoded here because live `teData` labels are
|
||||
//! unverified and Quant Research owns the coarse regime-use policy.
|
||||
//! - **Strict TSV format (`load_macro_series_map_tsv`):**
|
||||
//! - Required exact line-1 header:
|
||||
//! `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class`
|
||||
//! - LF (`\n`) and CRLF (`\r\n`) line endings are accepted; bare/embedded `\r` and invalid UTF-8
|
||||
//! fail closed with the 1-based physical line number.
|
||||
//! - Every data row must have exactly 6 nonempty tab-separated fields, verbatim keys, an exact
|
||||
//! `lag_class` token in `{policy_rate, monthly_release, gdp65, gdp90}`, and unique
|
||||
//! `(te_symbol, country, category)` triples (duplicates fail closed even when targets match).
|
||||
//!
|
||||
//! # Decode, Buffering & Fail-Closed Policy
|
||||
//! - **Series-map validation first:** The entire series map is parsed and validated before any
|
||||
//! `teData` bytes are decoded or `out_dir` is touched.
|
||||
//! - **In-memory file-mode buffering:** `run_curate_macro_with_readers` buffers the concatenated
|
||||
//! `teData` BSON input and collects borrowed [`TeDataPoint`] views from
|
||||
//! [`decode_te_data_buffer`] before calling [`curate_and_write_macro`], so memory usage grows
|
||||
//! with input size.
|
||||
//! - **Decode error policy (matching `run_curate_fx.rs`):** Per-document and per-point semantic
|
||||
//! rejects (missing/empty/wrong-type `teSymbol`, `country`, `category`, `data`, non-document
|
||||
//! points, invalid point dates/values) are counted in [`BsonTeDataDecodeStats`] and skipped so
|
||||
//! valid points continue. Structural BSON framing or element corruption
|
||||
//! ([`BsonTeDataError::TruncatedDocument`], [`BsonTeDataError::CorruptDocumentLength`],
|
||||
//! [`BsonTeDataError::CorruptBson`], [`BsonTeDataError::CorruptPointBson`]) is captured on the
|
||||
//! first occurrence and returned as [`RunCurateMacroError::CorruptTeDataBson`] before publishing,
|
||||
//! preventing partial datasets from a truncated or corrupt tail.
|
||||
//! - **Atomic publish & zero-row preservation:** Any series-map, I/O, structural BSON, or curation
|
||||
//! error (such as [`crate::curate_macro::CurateMacroError::ConflictingLagClass`]) returns before
|
||||
//! writing, leaving `out_dir` and any pre-existing `<out_dir>/macro/part.parquet` byte-identical.
|
||||
//! Empty or all-unmapped inputs preserve [`curate_and_write_macro`]'s zero-row success no-op.
|
||||
//!
|
||||
//! # Counter Conservation Invariants
|
||||
//! Every successful [`CurateMacroRunReport`] satisfies:
|
||||
//! - `decode_stats.docs_in == decode_stats.docs_accepted + decode_stats.docs_rejected_total()`
|
||||
//! - `decode_stats.points_in == decode_stats.points_decoded + decode_stats.rejected_total()`
|
||||
//! - `decode_stats.points_decoded == curate_stats.points_in`
|
||||
//! - `curate_stats.points_in == curate_stats.dropped_unmapped_series + curate_stats.builder.input`
|
||||
//! - `curate_stats.rows_out == curate_stats.builder.emitted == write_stats.rows_written`
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::error::Error;
|
||||
use std::fmt::{self, Write as _};
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::bson_te_data::{
|
||||
decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint,
|
||||
};
|
||||
use crate::curate_macro::{
|
||||
curate_and_write_macro, CurateMacroError, CurateMacroStats, CurateMacroWriteError,
|
||||
MacroSeriesTarget,
|
||||
};
|
||||
use crate::macro_series::MacroLagClass;
|
||||
use crate::parquet_macro::{MacroWriteOptions, MacroWriteStats, ParquetMacroError};
|
||||
|
||||
/// Required exact header line (line 1) for the macro series-map TSV.
|
||||
pub const MACRO_SERIES_MAP_HEADER: &str =
|
||||
"te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class";
|
||||
|
||||
const ROLE_TE_DATA: &str = "te-data";
|
||||
const ROLE_SERIES_MAP: &str = "series-map";
|
||||
const SERIES_MAP_COLUMN_COUNT: usize = 6;
|
||||
const SERIES_MAP_COLUMNS: [&str; SERIES_MAP_COLUMN_COUNT] = [
|
||||
"te_symbol",
|
||||
"country",
|
||||
"category",
|
||||
"country_iso",
|
||||
"indicator",
|
||||
"lag_class",
|
||||
];
|
||||
|
||||
/// File-mode arguments for [`run_curate_macro`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateMacroArgs {
|
||||
pub te_data: PathBuf,
|
||||
pub series_map: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
}
|
||||
|
||||
/// Validated caller-owned lookup from verbatim `(te_symbol, country, category)` triples to
|
||||
/// [`MacroSeriesTarget`], loaded by [`load_macro_series_map_tsv`].
|
||||
///
|
||||
/// Backed by nested [`BTreeMap`]s so lookups accept borrowed `&str` slices with zero allocation.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct MacroSeriesMap {
|
||||
entries: BTreeMap<String, BTreeMap<String, BTreeMap<String, MacroSeriesTarget>>>,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl MacroSeriesMap {
|
||||
/// Returns the number of mapped series entries.
|
||||
#[inline]
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
/// Returns `true` if the series map contains no entries.
|
||||
#[inline]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
/// Looks up a verbatim `(te_symbol, country, category)` triple without trimming or case folding.
|
||||
#[inline]
|
||||
pub fn get(
|
||||
&self,
|
||||
te_symbol: &str,
|
||||
country: &str,
|
||||
category: &str,
|
||||
) -> Option<&MacroSeriesTarget> {
|
||||
self.entries
|
||||
.get(te_symbol)
|
||||
.and_then(|by_country| by_country.get(country))
|
||||
.and_then(|by_category| by_category.get(category))
|
||||
}
|
||||
|
||||
fn insert(
|
||||
&mut self,
|
||||
te_symbol: String,
|
||||
country: String,
|
||||
category: String,
|
||||
target: MacroSeriesTarget,
|
||||
) -> bool {
|
||||
let by_category = self
|
||||
.entries
|
||||
.entry(te_symbol)
|
||||
.or_default()
|
||||
.entry(country)
|
||||
.or_default();
|
||||
if by_category.contains_key(&category) {
|
||||
return false;
|
||||
}
|
||||
by_category.insert(category, target);
|
||||
self.len += 1;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_macro`] and [`run_curate_macro_with_readers`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CurateMacroRunReport {
|
||||
pub series_map_entries: usize,
|
||||
pub decode_stats: BsonTeDataDecodeStats,
|
||||
pub curate_stats: CurateMacroStats,
|
||||
pub write_stats: MacroWriteStats,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`load_macro_series_map_tsv`], [`run_curate_macro`], and
|
||||
/// [`run_curate_macro_with_readers`].
|
||||
///
|
||||
/// Every variant's `Display` output is guaranteed to be a single line (CR and LF in dynamic
|
||||
/// strings, paths, and wrapped error messages are escaped as `\r` and `\n`).
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateMacroError {
|
||||
/// Failed to open a file-mode input (`te-data` or `series-map`).
|
||||
OpenInput {
|
||||
role: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Failed to read bytes from an input stream (`te-data` or `series-map`).
|
||||
ReadInput {
|
||||
role: &'static str,
|
||||
path: Option<PathBuf>,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Series-map TSV line contained invalid UTF-8 or a bare/embedded carriage return.
|
||||
SeriesMapMalformedLine { line: usize, detail: &'static str },
|
||||
/// Series-map TSV was empty or line 1 did not match [`MACRO_SERIES_MAP_HEADER`] verbatim.
|
||||
SeriesMapBadHeader { line: usize, found: Option<String> },
|
||||
/// Series-map TSV data row did not contain exactly 6 tab-separated columns.
|
||||
SeriesMapWrongColumnCount {
|
||||
line: usize,
|
||||
expected: usize,
|
||||
actual: usize,
|
||||
},
|
||||
/// Series-map TSV data row contained an empty (or blank) required field.
|
||||
SeriesMapEmptyField { line: usize, column: &'static str },
|
||||
/// Series-map TSV data row contained an unknown `lag_class` token.
|
||||
SeriesMapUnknownLagClass { line: usize, value: String },
|
||||
/// Series-map TSV contained a duplicate `(te_symbol, country, category)` triple.
|
||||
SeriesMapDuplicateKey {
|
||||
line: usize,
|
||||
te_symbol: String,
|
||||
country: String,
|
||||
category: String,
|
||||
},
|
||||
/// Structural BSON framing or element corruption in `teData` input.
|
||||
CorruptTeDataBson {
|
||||
path: Option<PathBuf>,
|
||||
offset: usize,
|
||||
source: BsonTeDataError,
|
||||
},
|
||||
/// Error returned by [`curate_and_write_macro`] (curation or Parquet write).
|
||||
CurateWrite(CurateMacroWriteError),
|
||||
}
|
||||
|
||||
impl RunCurateMacroError {
|
||||
fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self {
|
||||
match self {
|
||||
Self::ReadInput {
|
||||
role,
|
||||
path: None,
|
||||
source,
|
||||
} => {
|
||||
let path = match role {
|
||||
ROLE_TE_DATA => Some(te_data.to_path_buf()),
|
||||
ROLE_SERIES_MAP => Some(series_map.to_path_buf()),
|
||||
_ => None,
|
||||
};
|
||||
Self::ReadInput { role, path, source }
|
||||
}
|
||||
Self::CorruptTeDataBson {
|
||||
path: None,
|
||||
offset,
|
||||
source,
|
||||
} => Self::CorruptTeDataBson {
|
||||
path: Some(te_data.to_path_buf()),
|
||||
offset,
|
||||
source,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SingleLineWriter<'a, 'b> {
|
||||
f: &'a mut fmt::Formatter<'b>,
|
||||
}
|
||||
|
||||
impl fmt::Write for SingleLineWriter<'_, '_> {
|
||||
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||
let mut rest = s;
|
||||
while let Some(idx) = rest.find(['\n', '\r']) {
|
||||
let (head, tail) = rest.split_at(idx);
|
||||
if !head.is_empty() {
|
||||
self.f.write_str(head)?;
|
||||
}
|
||||
let mut chars = tail.chars();
|
||||
match chars.next() {
|
||||
Some('\n') => self.f.write_str("\\n")?,
|
||||
Some('\r') => self.f.write_str("\\r")?,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
rest = chars.as_str();
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
self.f.write_str(rest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateMacroError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let mut w = SingleLineWriter { f };
|
||||
match self {
|
||||
Self::OpenInput { role, path, source } => {
|
||||
write!(w, "failed to open {role} '{}': {source}", path.display())
|
||||
}
|
||||
Self::ReadInput { role, path, source } => match path {
|
||||
Some(path) => write!(w, "failed to read {role} '{}': {source}", path.display()),
|
||||
None => write!(w, "failed to read {role}: {source}"),
|
||||
},
|
||||
Self::SeriesMapMalformedLine { line, detail } => {
|
||||
write!(w, "series-map TSV line {line}: {detail}")
|
||||
}
|
||||
Self::SeriesMapBadHeader { line, found } => match found {
|
||||
Some(found) => write!(
|
||||
w,
|
||||
"series-map TSV line {line}: invalid header {found:?}; expected exact {MACRO_SERIES_MAP_HEADER:?}"
|
||||
),
|
||||
None => write!(
|
||||
w,
|
||||
"series-map TSV line {line}: missing required header {MACRO_SERIES_MAP_HEADER:?}"
|
||||
),
|
||||
},
|
||||
Self::SeriesMapWrongColumnCount {
|
||||
line,
|
||||
expected,
|
||||
actual,
|
||||
} => write!(
|
||||
w,
|
||||
"series-map TSV line {line}: expected {expected} tab-separated columns, got {actual}"
|
||||
),
|
||||
Self::SeriesMapEmptyField { line, column } => {
|
||||
write!(
|
||||
w,
|
||||
"series-map TSV line {line}: field '{column}' must not be empty"
|
||||
)
|
||||
}
|
||||
Self::SeriesMapUnknownLagClass { line, value } => write!(
|
||||
w,
|
||||
"series-map TSV line {line}: unknown lag_class {value:?}; expected one of 'policy_rate', 'monthly_release', 'gdp65', 'gdp90'"
|
||||
),
|
||||
Self::SeriesMapDuplicateKey {
|
||||
line,
|
||||
te_symbol,
|
||||
country,
|
||||
category,
|
||||
} => write!(
|
||||
w,
|
||||
"series-map TSV line {line}: duplicate series key ({te_symbol:?}, {country:?}, {category:?})"
|
||||
),
|
||||
Self::CorruptTeDataBson {
|
||||
path,
|
||||
offset,
|
||||
source,
|
||||
} => match path {
|
||||
Some(path) => write!(
|
||||
w,
|
||||
"corrupt {ROLE_TE_DATA} BSON '{}' at byte offset {offset}: {source}",
|
||||
path.display()
|
||||
),
|
||||
None => write!(
|
||||
w,
|
||||
"corrupt {ROLE_TE_DATA} BSON at byte offset {offset}: {source}"
|
||||
),
|
||||
},
|
||||
Self::CurateWrite(source) => write!(w, "{source}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateMacroError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
|
||||
Self::CorruptTeDataBson { source, .. } => Some(source),
|
||||
Self::CurateWrite(source) => Some(source),
|
||||
Self::SeriesMapMalformedLine { .. }
|
||||
| Self::SeriesMapBadHeader { .. }
|
||||
| Self::SeriesMapWrongColumnCount { .. }
|
||||
| Self::SeriesMapEmptyField { .. }
|
||||
| Self::SeriesMapUnknownLagClass { .. }
|
||||
| Self::SeriesMapDuplicateKey { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurateMacroWriteError> for RunCurateMacroError {
|
||||
fn from(err: CurateMacroWriteError) -> Self {
|
||||
Self::CurateWrite(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurateMacroError> for RunCurateMacroError {
|
||||
fn from(err: CurateMacroError) -> Self {
|
||||
Self::CurateWrite(CurateMacroWriteError::Curate(err))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParquetMacroError> for RunCurateMacroError {
|
||||
fn from(err: ParquetMacroError) -> Self {
|
||||
Self::CurateWrite(CurateMacroWriteError::Parquet(err))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_lag_class_token(token: &str) -> Option<MacroLagClass> {
|
||||
match token {
|
||||
"policy_rate" => Some(MacroLagClass::PolicyRate),
|
||||
"monthly_release" => Some(MacroLagClass::MonthlyRelease),
|
||||
"gdp65" => Some(MacroLagClass::Gdp65),
|
||||
"gdp90" => Some(MacroLagClass::Gdp90),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_structural_te_data_bson_error(err: &BsonTeDataError) -> bool {
|
||||
matches!(
|
||||
err,
|
||||
BsonTeDataError::TruncatedDocument { .. }
|
||||
| BsonTeDataError::CorruptDocumentLength { .. }
|
||||
| BsonTeDataError::CorruptBson { .. }
|
||||
| BsonTeDataError::CorruptPointBson { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Parses and validates a caller-supplied macro series-map TSV into a [`MacroSeriesMap`].
|
||||
///
|
||||
/// Format:
|
||||
/// - Line 1 must be the exact header
|
||||
/// `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class`.
|
||||
/// - Each subsequent line must have 6 nonempty tab-separated fields, preserved verbatim (no
|
||||
/// trimming or case folding), with `lag_class` in
|
||||
/// `{"policy_rate", "monthly_release", "gdp65", "gdp90"}` and unique
|
||||
/// `(te_symbol, country, category)` keys.
|
||||
pub fn load_macro_series_map_tsv<R: io::Read>(
|
||||
reader: R,
|
||||
) -> Result<MacroSeriesMap, RunCurateMacroError> {
|
||||
let mut buf_reader = BufReader::new(reader);
|
||||
let mut raw_buf: Vec<u8> = Vec::with_capacity(256);
|
||||
let mut line_no: usize = 0;
|
||||
let mut map = MacroSeriesMap::default();
|
||||
let mut saw_header = false;
|
||||
|
||||
loop {
|
||||
raw_buf.clear();
|
||||
let bytes_read = buf_reader.read_until(b'\n', &mut raw_buf).map_err(|source| {
|
||||
RunCurateMacroError::ReadInput {
|
||||
role: ROLE_SERIES_MAP,
|
||||
path: None,
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
if bytes_read == 0 {
|
||||
break;
|
||||
}
|
||||
line_no += 1;
|
||||
|
||||
let mut slice = raw_buf.as_slice();
|
||||
if slice.ends_with(b"\n") {
|
||||
slice = &slice[..slice.len() - 1];
|
||||
if slice.ends_with(b"\r") {
|
||||
slice = &slice[..slice.len() - 1];
|
||||
}
|
||||
}
|
||||
if slice.contains(&b'\r') {
|
||||
return Err(RunCurateMacroError::SeriesMapMalformedLine {
|
||||
line: line_no,
|
||||
detail: "unexpected carriage return inside TSV line",
|
||||
});
|
||||
}
|
||||
|
||||
let line = std::str::from_utf8(slice).map_err(|_| {
|
||||
RunCurateMacroError::SeriesMapMalformedLine {
|
||||
line: line_no,
|
||||
detail: "invalid UTF-8 in TSV line",
|
||||
}
|
||||
})?;
|
||||
|
||||
if !saw_header {
|
||||
if line != MACRO_SERIES_MAP_HEADER {
|
||||
return Err(RunCurateMacroError::SeriesMapBadHeader {
|
||||
line: 1,
|
||||
found: Some(line.to_owned()),
|
||||
});
|
||||
}
|
||||
saw_header = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let cols: Vec<&str> = line.split('\t').collect();
|
||||
if cols.len() != SERIES_MAP_COLUMN_COUNT {
|
||||
return Err(RunCurateMacroError::SeriesMapWrongColumnCount {
|
||||
line: line_no,
|
||||
expected: SERIES_MAP_COLUMN_COUNT,
|
||||
actual: cols.len(),
|
||||
});
|
||||
}
|
||||
|
||||
for (idx, (&col, &col_name)) in cols.iter().zip(SERIES_MAP_COLUMNS.iter()).enumerate() {
|
||||
let is_empty = if idx == 5 {
|
||||
col.is_empty()
|
||||
} else {
|
||||
col.trim().is_empty()
|
||||
};
|
||||
if is_empty {
|
||||
return Err(RunCurateMacroError::SeriesMapEmptyField {
|
||||
line: line_no,
|
||||
column: col_name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let te_symbol = cols[0];
|
||||
let country = cols[1];
|
||||
let category = cols[2];
|
||||
let country_iso = cols[3];
|
||||
let indicator = cols[4];
|
||||
let lag_token = cols[5];
|
||||
|
||||
let lag_class = parse_lag_class_token(lag_token).ok_or_else(|| {
|
||||
RunCurateMacroError::SeriesMapUnknownLagClass {
|
||||
line: line_no,
|
||||
value: lag_token.to_owned(),
|
||||
}
|
||||
})?;
|
||||
|
||||
let target = MacroSeriesTarget {
|
||||
country_iso: country_iso.to_owned(),
|
||||
indicator: indicator.to_owned(),
|
||||
lag_class,
|
||||
};
|
||||
|
||||
if !map.insert(
|
||||
te_symbol.to_owned(),
|
||||
country.to_owned(),
|
||||
category.to_owned(),
|
||||
target,
|
||||
) {
|
||||
return Err(RunCurateMacroError::SeriesMapDuplicateKey {
|
||||
line: line_no,
|
||||
te_symbol: te_symbol.to_owned(),
|
||||
country: country.to_owned(),
|
||||
category: category.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if !saw_header {
|
||||
return Err(RunCurateMacroError::SeriesMapBadHeader {
|
||||
line: 1,
|
||||
found: None,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and
|
||||
/// the series-map TSV, publishing `<out_dir>/macro/part.parquet` via [`curate_and_write_macro`].
|
||||
///
|
||||
/// The series map is validated in full before `te_data` is decoded or `out_dir` is touched. Any
|
||||
/// map, I/O, structural BSON, or curation error returns before publishing and leaves `out_dir` and
|
||||
/// any pre-existing `<out_dir>/macro/part.parquet` untouched.
|
||||
pub fn run_curate_macro_with_readers<RT: io::Read, RM: io::Read>(
|
||||
mut te_data: RT,
|
||||
series_map: RM,
|
||||
out_dir: &Path,
|
||||
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
||||
let map = load_macro_series_map_tsv(series_map)?;
|
||||
|
||||
let mut te_data_buf = Vec::new();
|
||||
te_data
|
||||
.read_to_end(&mut te_data_buf)
|
||||
.map_err(|source| RunCurateMacroError::ReadInput {
|
||||
role: ROLE_TE_DATA,
|
||||
path: None,
|
||||
source,
|
||||
})?;
|
||||
|
||||
let mut points: Vec<TeDataPoint<'_>> = Vec::new();
|
||||
let mut structural_err: Option<(usize, BsonTeDataError)> = None;
|
||||
let decode_stats = decode_te_data_buffer(
|
||||
&te_data_buf,
|
||||
|point| points.push(point),
|
||||
|offset, err| {
|
||||
if structural_err.is_none() && is_structural_te_data_bson_error(&err) {
|
||||
structural_err = Some((offset, err));
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Some((offset, source)) = structural_err {
|
||||
return Err(RunCurateMacroError::CorruptTeDataBson {
|
||||
path: None,
|
||||
offset,
|
||||
source,
|
||||
});
|
||||
}
|
||||
|
||||
let write_report = curate_and_write_macro(
|
||||
out_dir,
|
||||
points,
|
||||
|te_symbol, country, category| map.get(te_symbol, country, category).cloned(),
|
||||
MacroWriteOptions::default(),
|
||||
)?;
|
||||
|
||||
Ok(CurateMacroRunReport {
|
||||
series_map_entries: map.len(),
|
||||
decode_stats,
|
||||
curate_stats: write_report.curate_stats,
|
||||
write_stats: write_report.write_stats,
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating
|
||||
/// to [`run_curate_macro_with_readers`].
|
||||
///
|
||||
/// File open, read, and structural BSON errors attach the offending role (`te-data` or
|
||||
/// `series-map`) and path. Any error returns before writing to `args.out_dir`.
|
||||
pub fn run_curate_macro(args: &CurateMacroArgs) -> Result<CurateMacroRunReport, RunCurateMacroError> {
|
||||
let series_map_file =
|
||||
File::open(&args.series_map).map_err(|source| RunCurateMacroError::OpenInput {
|
||||
role: ROLE_SERIES_MAP,
|
||||
path: args.series_map.clone(),
|
||||
source,
|
||||
})?;
|
||||
let te_data_file =
|
||||
File::open(&args.te_data).map_err(|source| RunCurateMacroError::OpenInput {
|
||||
role: ROLE_TE_DATA,
|
||||
path: args.te_data.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
run_curate_macro_with_readers(te_data_file, series_map_file, &args.out_dir)
|
||||
.map_err(|err| err.with_input_paths(&args.te_data, &args.series_map))
|
||||
}
|
||||
|
||||
/// Formats [`CurateMacroRunReport`] into deterministic multi-line `key=value` text.
|
||||
pub fn format_curate_macro_report(report: &CurateMacroRunReport) -> String {
|
||||
let d = &report.decode_stats;
|
||||
let c = &report.curate_stats;
|
||||
let b = &c.builder;
|
||||
let w = &report.write_stats;
|
||||
format!(
|
||||
"curate-etl curate-macro\n\
|
||||
\x20 map: entries={}\n\
|
||||
\x20 decode: docs_in={} docs_accepted={} docs_rejected={} (missing_symbol={} empty_symbol={} wrong_symbol_type={} missing_country={} empty_country={} wrong_country_type={} missing_category={} empty_category={} wrong_category_type={} data_missing={} data_not_array={} corrupt_doc={}) points_in={} points_decoded={} points_rejected={} (not_doc={} invalid_date={} invalid_value={} corrupt_point={})\n\
|
||||
\x20 builder: input={} emitted={} skipped_unmapped_indicator={} skipped_non_finite_value={} skipped_duplicate={}\n\
|
||||
\x20 curate: points_in={} rows_out={} dropped_unmapped_series={} series_out={}\n\
|
||||
\x20 write: files={} row_groups={} rows_written={} bytes_written={}",
|
||||
report.series_map_entries,
|
||||
d.docs_in,
|
||||
d.docs_accepted,
|
||||
d.docs_rejected_total(),
|
||||
d.rejected_missing_symbol,
|
||||
d.rejected_empty_symbol,
|
||||
d.rejected_wrong_symbol_type,
|
||||
d.rejected_missing_country,
|
||||
d.rejected_empty_country,
|
||||
d.rejected_wrong_country_type,
|
||||
d.rejected_missing_category,
|
||||
d.rejected_empty_category,
|
||||
d.rejected_wrong_category_type,
|
||||
d.rejected_data_missing,
|
||||
d.rejected_data_not_array,
|
||||
d.rejected_corrupt_document,
|
||||
d.points_in,
|
||||
d.points_decoded,
|
||||
d.rejected_total(),
|
||||
d.rejected_point_not_document,
|
||||
d.rejected_invalid_date,
|
||||
d.rejected_invalid_value,
|
||||
d.rejected_corrupt_point,
|
||||
b.input,
|
||||
b.emitted,
|
||||
b.skipped_unmapped_indicator,
|
||||
b.skipped_non_finite_value,
|
||||
b.skipped_duplicate,
|
||||
c.points_in,
|
||||
c.rows_out,
|
||||
c.dropped_unmapped_series,
|
||||
c.series_out,
|
||||
w.files_written,
|
||||
w.row_groups_written,
|
||||
w.rows_written,
|
||||
w.bytes_written,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "run_curate_macro_tests.rs"]
|
||||
mod tests;
|
||||
1328
tools/curate-etl/src/run_curate_macro_tests.rs
Normal file
1328
tools/curate-etl/src/run_curate_macro_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
718
tools/curate-etl/tests/curate_fundamentals.rs
Normal file
718
tools/curate-etl/tests/curate_fundamentals.rs
Normal file
|
|
@ -0,0 +1,718 @@
|
|||
//! End-to-end tests for the file-mode `curate-fundamentals` CLI.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use curate_etl::fundamentals::FundamentalsFields;
|
||||
use curate_etl::run_curate_fundamentals::{
|
||||
format_curate_fundamentals_report, run_curate_fundamentals, CurateFundamentalsArgs,
|
||||
CurateFundamentalsFiscalPeriod,
|
||||
};
|
||||
use curate_etl::shorts::et_to_utc_micros;
|
||||
use curate_etl::split::ymd_to_epoch_days;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
use parquet::record::{Field, Row};
|
||||
|
||||
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-fundamentals-cli-{label}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create isolated test directory");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli() -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl"));
|
||||
command.arg("curate-fundamentals");
|
||||
command
|
||||
}
|
||||
|
||||
fn make_financials_doc(
|
||||
key: &str,
|
||||
period_end: &str,
|
||||
report_date: &str,
|
||||
report_period: &str,
|
||||
currency: &str,
|
||||
fields: FundamentalsFields,
|
||||
) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), key);
|
||||
doc.append(cstr!("periodEndDate"), period_end);
|
||||
doc.append(cstr!("reportDate"), report_date);
|
||||
doc.append(cstr!("reportPeriod"), report_period);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
|
||||
let mut income = RawDocumentBuf::new();
|
||||
if let Some(v) = fields.revenue {
|
||||
income.append(cstr!("revenue"), v);
|
||||
}
|
||||
if let Some(v) = fields.net_income {
|
||||
income.append(cstr!("netIncome"), v);
|
||||
}
|
||||
doc.append(cstr!("IncomeStatement"), income);
|
||||
|
||||
let mut cashflow = RawDocumentBuf::new();
|
||||
if let Some(v) = fields.operating_cash_flow {
|
||||
cashflow.append(cstr!("operatingCashFlow"), v);
|
||||
}
|
||||
doc.append(cstr!("CashFlow"), cashflow);
|
||||
|
||||
let mut balance = RawDocumentBuf::new();
|
||||
if let Some(v) = fields.total_assets {
|
||||
balance.append(cstr!("totalAssets"), v);
|
||||
}
|
||||
if let Some(v) = fields.total_equity {
|
||||
balance.append(cstr!("totalEquity"), v);
|
||||
}
|
||||
if let Some(v) = fields.shares_outstanding {
|
||||
balance.append(cstr!("sharesOutstanding"), v);
|
||||
}
|
||||
doc.append(cstr!("BalanceSheet"), balance);
|
||||
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn make_filing_doc(key: &str, timefiled: &str, form_type: &str, filing_id: &str) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), key);
|
||||
doc.append(cstr!("timefiled"), timefiled);
|
||||
doc.append(cstr!("formType"), form_type);
|
||||
doc.append(cstr!("filingId"), filing_id);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn read_parquet_partitions(out_dir: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
|
||||
let dataset_root = out_dir.join("fundamentals_pit");
|
||||
let mut files = BTreeMap::new();
|
||||
for entry in fs::read_dir(&dataset_root).expect("read fundamentals_pit dir") {
|
||||
let entry = entry.expect("dir entry");
|
||||
let name = entry.file_name();
|
||||
let part_path = entry.path().join("part.parquet");
|
||||
assert!(
|
||||
part_path.is_file(),
|
||||
"expected part.parquet in {}",
|
||||
entry.path().display()
|
||||
);
|
||||
let rel = PathBuf::from(&name).join("part.parquet");
|
||||
files.insert(rel, fs::read(&part_path).expect("read parquet bytes"));
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
fn write_restatement_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
|
||||
let fin_path = dir.join("qmFinancials.bson");
|
||||
let fil_path = dir.join("qmFilings.bson");
|
||||
let map_path = dir.join("provider_mapping.tsv");
|
||||
let venues_path = dir.join("listing_venues.tsv");
|
||||
|
||||
fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap();
|
||||
fs::write(&venues_path, "301\tus_tsx\n").unwrap();
|
||||
|
||||
// Specimen dates and field shapes from `run_curate_fundamentals_tests`:
|
||||
// four contiguous quarters (Q3 2023 .. Q2 2024) plus a late Q1 2024 restatement (10-Q/A on
|
||||
// 2024-09-15) and an unmapped observation.
|
||||
let mut fin_bytes = Vec::new();
|
||||
for (key, pe, rd, rp, rev, ni, ocf, ta, te, sh) in [
|
||||
(
|
||||
"ACME",
|
||||
"2023-09-30",
|
||||
"2023-11-05",
|
||||
"Q3",
|
||||
90.0,
|
||||
8.0,
|
||||
10.0,
|
||||
460.0,
|
||||
275.0,
|
||||
20.0,
|
||||
),
|
||||
(
|
||||
"ACME",
|
||||
"2023-12-31",
|
||||
"2024-02-20",
|
||||
"Q4",
|
||||
110.0,
|
||||
11.0,
|
||||
14.0,
|
||||
480.0,
|
||||
288.0,
|
||||
20.0,
|
||||
),
|
||||
(
|
||||
"ACME",
|
||||
"2024-03-31",
|
||||
"2024-05-05",
|
||||
"Q1",
|
||||
100.0,
|
||||
10.0,
|
||||
12.0,
|
||||
500.0,
|
||||
300.0,
|
||||
20.0,
|
||||
),
|
||||
(
|
||||
"ACME",
|
||||
"2024-06-30",
|
||||
"2024-08-05",
|
||||
"Q2",
|
||||
250.0,
|
||||
30.0,
|
||||
35.0,
|
||||
550.0,
|
||||
330.0,
|
||||
20.0,
|
||||
),
|
||||
(
|
||||
"ACME",
|
||||
"2024-03-31",
|
||||
"2024-09-15",
|
||||
"Q1",
|
||||
88.0,
|
||||
4.0,
|
||||
9.0,
|
||||
490.0,
|
||||
294.0,
|
||||
20.0,
|
||||
),
|
||||
(
|
||||
"UNMAPPED",
|
||||
"2024-06-30",
|
||||
"2024-08-05",
|
||||
"Q2",
|
||||
50.0,
|
||||
5.0,
|
||||
6.0,
|
||||
100.0,
|
||||
60.0,
|
||||
10.0,
|
||||
),
|
||||
] {
|
||||
fin_bytes.extend_from_slice(&make_financials_doc(
|
||||
key,
|
||||
pe,
|
||||
rd,
|
||||
rp,
|
||||
"USD",
|
||||
FundamentalsFields {
|
||||
revenue: Some(rev),
|
||||
net_income: Some(ni),
|
||||
operating_cash_flow: Some(ocf),
|
||||
total_assets: Some(ta),
|
||||
total_equity: Some(te),
|
||||
shares_outstanding: Some(sh),
|
||||
},
|
||||
));
|
||||
}
|
||||
fs::write(&fin_path, fin_bytes).unwrap();
|
||||
|
||||
let mut fil_bytes = Vec::new();
|
||||
for (key, ts, form, id) in [
|
||||
("ACME", "2023-11-05T16:10:00 EST", "10-Q", "q3-2023-1"),
|
||||
("ACME", "2024-02-20T16:10:00 EST", "10-Q", "q4-2023-1"),
|
||||
("ACME", "2024-05-05T16:10:00 EDT", "10-Q", "q1-2024-1"),
|
||||
("ACME", "2024-08-05T16:15:00 EDT", "10-Q", "q2-2024-1"),
|
||||
("ACME", "2024-09-15T16:20:00 EDT", "10-Q/A", "q1-2024-a"),
|
||||
] {
|
||||
fil_bytes.extend_from_slice(&make_filing_doc(key, ts, form, id));
|
||||
}
|
||||
fs::write(&fil_path, fil_bytes).unwrap();
|
||||
|
||||
(fin_path, fil_path, map_path, venues_path)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_publishes_runner_equivalent_fundamentals_and_preserves_pit_restatement() {
|
||||
let dir = TempDir::new("e2e");
|
||||
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
|
||||
|
||||
let baseline_dir = dir.0.join("baseline");
|
||||
let mut baseline_args = CurateFundamentalsArgs::with_verified_defaults(
|
||||
fin_path.clone(),
|
||||
fil_path.clone(),
|
||||
map_path.clone(),
|
||||
venues_path.clone(),
|
||||
baseline_dir.clone(),
|
||||
"currency",
|
||||
Some("IncomeStatement.revenue".to_string()),
|
||||
Some("IncomeStatement.netIncome".to_string()),
|
||||
Some("CashFlow.operatingCashFlow".to_string()),
|
||||
Some("BalanceSheet.totalAssets".to_string()),
|
||||
Some("BalanceSheet.totalEquity".to_string()),
|
||||
Some("BalanceSheet.sharesOutstanding".to_string()),
|
||||
CurateFundamentalsFiscalPeriod::ByTokens {
|
||||
quarterly: vec![
|
||||
"Q1".to_string(),
|
||||
"Q2".to_string(),
|
||||
"Q3".to_string(),
|
||||
"Q4".to_string(),
|
||||
],
|
||||
annual: vec!["FY".to_string()],
|
||||
},
|
||||
"formType",
|
||||
4,
|
||||
);
|
||||
baseline_args.filings_filing_id_field = Some("filingId".to_string());
|
||||
|
||||
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
|
||||
let expected_report = format_curate_fundamentals_report(&baseline_report);
|
||||
let baseline_partitions = read_parquet_partitions(&baseline_dir);
|
||||
assert!(
|
||||
baseline_partitions.contains_key(Path::new("year=2024/part.parquet")),
|
||||
"expected nonempty 2024 partition"
|
||||
);
|
||||
|
||||
let cli_out = dir.0.join("cli_out");
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--qm-financials",
|
||||
"qmFinancials.bson",
|
||||
"--qm-filings=qmFilings.bson",
|
||||
"--provider-mapping",
|
||||
"provider_mapping.tsv",
|
||||
"--listing-venues=listing_venues.tsv",
|
||||
"--out",
|
||||
"cli_out",
|
||||
"--currency-field=currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--filings-filing-id-field=filingId",
|
||||
"--k",
|
||||
"4",
|
||||
"--quarterly-tokens=Q1,Q2,Q3,Q4",
|
||||
"--annual-tokens",
|
||||
"FY",
|
||||
"--revenue-field",
|
||||
"IncomeStatement.revenue",
|
||||
"--net-income-field=IncomeStatement.netIncome",
|
||||
"--operating-cash-flow-field",
|
||||
"CashFlow.operatingCashFlow",
|
||||
"--total-assets-field=BalanceSheet.totalAssets",
|
||||
"--total-equity-field",
|
||||
"BalanceSheet.totalEquity",
|
||||
"--shares-outstanding-field=BalanceSheet.sharesOutstanding",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-fundamentals");
|
||||
|
||||
assert!(result.status.success(), "{result:?}");
|
||||
assert!(
|
||||
result.stderr.is_empty(),
|
||||
"unexpected stderr: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
|
||||
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
|
||||
let actual_lines: Vec<&str> = stdout.lines().collect();
|
||||
let expected_lines: Vec<&str> = expected_report.lines().collect();
|
||||
assert_eq!(actual_lines.len(), expected_lines.len(), "{stdout}");
|
||||
assert_eq!(
|
||||
&actual_lines[..actual_lines.len() - 1],
|
||||
&expected_lines[..expected_lines.len() - 1],
|
||||
"deterministic report lines must match library baseline"
|
||||
);
|
||||
let timing_line = *actual_lines.last().unwrap();
|
||||
let elapsed_str = timing_line
|
||||
.strip_prefix(" timing: elapsed_secs=")
|
||||
.unwrap_or_else(|| panic!("unexpected timing line: {timing_line:?}"));
|
||||
let elapsed: f64 = elapsed_str.parse().expect("valid elapsed_secs float");
|
||||
assert!(elapsed.is_finite() && elapsed >= 0.0, "{timing_line}");
|
||||
|
||||
let cli_partitions = read_parquet_partitions(&cli_out);
|
||||
assert_eq!(
|
||||
cli_partitions.keys().collect::<Vec<_>>(),
|
||||
baseline_partitions.keys().collect::<Vec<_>>(),
|
||||
"partition paths must match baseline"
|
||||
);
|
||||
for (rel, expected_bytes) in &baseline_partitions {
|
||||
assert_eq!(
|
||||
cli_partitions.get(rel).unwrap(),
|
||||
expected_bytes,
|
||||
"Parquet bytes differ for {}",
|
||||
rel.display()
|
||||
);
|
||||
}
|
||||
|
||||
// Read the 2024 partition and verify listing, currency, metric value, filing-derived known_at,
|
||||
// and PIT restatement isolation (Q1 restatement only visible at 2024-09-15).
|
||||
let part_2024 = cli_out.join("fundamentals_pit/year=2024/part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
|
||||
let rows: Vec<_> = reader
|
||||
.get_row_iter(None)
|
||||
.unwrap()
|
||||
.map(Result::unwrap)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows.len(),
|
||||
4,
|
||||
"expected Q4-23, Q1-24, Q2-24, and Q1-24/A snapshots in 2024"
|
||||
);
|
||||
|
||||
let q2_filed_micros =
|
||||
et_to_utc_micros(ymd_to_epoch_days(2024, 8, 5).unwrap(), 16, 15, 0).unwrap();
|
||||
let restate_filed_micros =
|
||||
et_to_utc_micros(ymd_to_epoch_days(2024, 9, 15).unwrap(), 16, 20, 0).unwrap();
|
||||
|
||||
fn col<'a>(row: &'a Row, name: &str) -> &'a Field {
|
||||
row.get_column_iter()
|
||||
.find(|(col_name, _)| col_name.as_str() == name)
|
||||
.unwrap_or_else(|| panic!("missing Parquet column '{name}'"))
|
||||
.1
|
||||
}
|
||||
|
||||
let q2_row = &rows[2];
|
||||
assert_eq!(col(q2_row, "listing_id"), &Field::Int(301));
|
||||
assert_eq!(
|
||||
col(q2_row, "effective_known_at"),
|
||||
&Field::TimestampMicros(q2_filed_micros)
|
||||
);
|
||||
assert_eq!(
|
||||
col(q2_row, "known_at_source"),
|
||||
&Field::Str("filing_timestamp".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
col(q2_row, "period_end"),
|
||||
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
|
||||
);
|
||||
assert_eq!(col(q2_row, "currency"), &Field::Str("USD".to_string()));
|
||||
assert_eq!(col(q2_row, "revenue"), &Field::Double(250.0));
|
||||
assert_eq!(col(q2_row, "ttm_revenue"), &Field::Double(550.0));
|
||||
|
||||
let restated_row = &rows[3];
|
||||
assert_eq!(col(restated_row, "listing_id"), &Field::Int(301));
|
||||
assert_eq!(
|
||||
col(restated_row, "effective_known_at"),
|
||||
&Field::TimestampMicros(restate_filed_micros)
|
||||
);
|
||||
assert_eq!(
|
||||
col(restated_row, "known_at_source"),
|
||||
&Field::Str("filing_timestamp".to_string())
|
||||
);
|
||||
// Latest period remains Q2 2024 (250.0 revenue) while TTM revenue reflects the -12.0 Q1 restatement.
|
||||
assert_eq!(
|
||||
col(restated_row, "period_end"),
|
||||
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
col(restated_row, "currency"),
|
||||
&Field::Str("USD".to_string())
|
||||
);
|
||||
assert_eq!(col(restated_row, "revenue"), &Field::Double(250.0));
|
||||
assert_eq!(col(restated_row, "ttm_revenue"), &Field::Double(538.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() {
|
||||
let dir = TempDir::new("fail-closed");
|
||||
let (_fin_path, _fil_path, _map_path, _venues_path) = write_restatement_fixture(&dir.0);
|
||||
|
||||
let out_missing_k = dir.0.join("out_missing_k");
|
||||
let res_missing_k = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--qm-financials",
|
||||
"qmFinancials.bson",
|
||||
"--qm-filings",
|
||||
"qmFilings.bson",
|
||||
"--provider-mapping",
|
||||
"provider_mapping.tsv",
|
||||
"--listing-venues",
|
||||
"listing_venues.tsv",
|
||||
"--out",
|
||||
"out_missing_k",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--fiscal-period",
|
||||
"quarterly",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-fundamentals missing --k");
|
||||
|
||||
assert_eq!(res_missing_k.status.code(), Some(1));
|
||||
assert!(res_missing_k.stdout.is_empty());
|
||||
let stderr_k = String::from_utf8(res_missing_k.stderr).unwrap();
|
||||
let mut lines_k = stderr_k.lines();
|
||||
assert_eq!(lines_k.next(), Some("error: missing required flag '--k'"));
|
||||
assert_eq!(lines_k.next(), Some("Usage:"));
|
||||
assert!(
|
||||
stderr_k.contains("curate-fundamentals --qm-financials"),
|
||||
"{stderr_k}"
|
||||
);
|
||||
assert!(!out_missing_k.exists(), "out_missing_k must not be created");
|
||||
|
||||
let out_from_mongo = dir.0.join("out_from_mongo");
|
||||
let res_mongo = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--from-mongo",
|
||||
"--qm-financials",
|
||||
"qmFinancials.bson",
|
||||
"--qm-filings",
|
||||
"qmFilings.bson",
|
||||
"--provider-mapping",
|
||||
"provider_mapping.tsv",
|
||||
"--listing-venues",
|
||||
"listing_venues.tsv",
|
||||
"--out",
|
||||
"out_from_mongo",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--k",
|
||||
"4",
|
||||
"--fiscal-period",
|
||||
"quarterly",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-fundamentals with --from-mongo");
|
||||
|
||||
assert_eq!(res_mongo.status.code(), Some(1));
|
||||
assert!(res_mongo.stdout.is_empty());
|
||||
let stderr_mongo = String::from_utf8(res_mongo.stderr).unwrap();
|
||||
let mut lines_mongo = stderr_mongo.lines();
|
||||
assert_eq!(
|
||||
lines_mongo.next(),
|
||||
Some("error: unknown flag '--from-mongo' for curate-fundamentals")
|
||||
);
|
||||
assert_eq!(lines_mongo.next(), Some("Usage:"));
|
||||
assert!(
|
||||
stderr_mongo.contains("curate-fundamentals --qm-financials"),
|
||||
"{stderr_mongo}"
|
||||
);
|
||||
assert!(
|
||||
!out_from_mongo.exists(),
|
||||
"out_from_mongo must not be created"
|
||||
);
|
||||
}
|
||||
|
||||
const FIXTURE_REQUIRED_ARGS: [&str; 14] = [
|
||||
"--qm-financials",
|
||||
"qmFinancials.bson",
|
||||
"--qm-filings",
|
||||
"qmFilings.bson",
|
||||
"--provider-mapping",
|
||||
"provider_mapping.tsv",
|
||||
"--listing-venues",
|
||||
"listing_venues.tsv",
|
||||
"--currency-field",
|
||||
"currency",
|
||||
"--filings-form-type-field",
|
||||
"formType",
|
||||
"--k",
|
||||
"4",
|
||||
];
|
||||
|
||||
fn assert_single_line_error_then_usage(stderr: &[u8], expected_error: &str) {
|
||||
let text = String::from_utf8(stderr.to_vec()).expect("utf-8 stderr");
|
||||
let mut lines = text.lines();
|
||||
assert_eq!(lines.next(), Some(expected_error), "{text}");
|
||||
assert_eq!(lines.next(), Some("Usage:"), "{text}");
|
||||
assert!(
|
||||
text.contains("curate-fundamentals --qm-financials"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_fixed_fiscal_period_without_metric_fields_matches_runner_and_writes_null_metrics() {
|
||||
let dir = TempDir::new("fixed-null-metrics");
|
||||
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
|
||||
|
||||
let baseline_dir = dir.0.join("baseline");
|
||||
let baseline_args = CurateFundamentalsArgs::with_verified_defaults(
|
||||
fin_path,
|
||||
fil_path,
|
||||
map_path,
|
||||
venues_path,
|
||||
baseline_dir.clone(),
|
||||
"currency",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
CurateFundamentalsFiscalPeriod::Fixed(curate_etl::fundamentals::FiscalPeriod::Quarterly),
|
||||
"formType",
|
||||
4,
|
||||
);
|
||||
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
|
||||
let expected_report = format_curate_fundamentals_report(&baseline_report);
|
||||
let baseline_partitions = read_parquet_partitions(&baseline_dir);
|
||||
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args(FIXTURE_REQUIRED_ARGS)
|
||||
.args(["--out=cli_out", "--fiscal-period=quarterly"])
|
||||
.output()
|
||||
.expect("run curate-fundamentals");
|
||||
assert!(result.status.success(), "{result:?}");
|
||||
assert!(result.stderr.is_empty(), "{result:?}");
|
||||
|
||||
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
|
||||
let actual: Vec<&str> = stdout.lines().collect();
|
||||
let expected: Vec<&str> = expected_report.lines().collect();
|
||||
assert_eq!(actual.len(), expected.len(), "{stdout}");
|
||||
assert_eq!(actual[..actual.len() - 1], expected[..expected.len() - 1]);
|
||||
|
||||
let cli_partitions = read_parquet_partitions(&dir.0.join("cli_out"));
|
||||
assert_eq!(cli_partitions, baseline_partitions);
|
||||
|
||||
let part_2024 = dir
|
||||
.0
|
||||
.join("cli_out/fundamentals_pit/year=2024/part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
|
||||
let rows: Vec<Row> = reader
|
||||
.get_row_iter(None)
|
||||
.unwrap()
|
||||
.map(Result::unwrap)
|
||||
.collect();
|
||||
assert!(!rows.is_empty(), "expected nonempty 2024 partition");
|
||||
for row in &rows {
|
||||
let revenue = row
|
||||
.get_column_iter()
|
||||
.find(|(name, _)| name.as_str() == "revenue")
|
||||
.expect("revenue column")
|
||||
.1;
|
||||
assert_eq!(revenue, &Field::Null, "unconfigured metric must be NULL");
|
||||
let currency = row
|
||||
.get_column_iter()
|
||||
.find(|(name, _)| name.as_str() == "currency")
|
||||
.expect("currency column")
|
||||
.1;
|
||||
assert_eq!(currency, &Field::Str("USD".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_rerun_into_fresh_out_dir_is_byte_deterministic() {
|
||||
let dir = TempDir::new("rerun");
|
||||
write_restatement_fixture(&dir.0);
|
||||
|
||||
for out in ["run_a", "run_b"] {
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args(FIXTURE_REQUIRED_ARGS)
|
||||
.args(["--out", out, "--quarterly-tokens", "Q1,Q2,Q3,Q4"])
|
||||
.args(["--revenue-field", "IncomeStatement.revenue"])
|
||||
.output()
|
||||
.expect("run curate-fundamentals");
|
||||
assert!(result.status.success(), "{result:?}");
|
||||
}
|
||||
|
||||
let a = read_parquet_partitions(&dir.0.join("run_a"));
|
||||
let b = read_parquet_partitions(&dir.0.join("run_b"));
|
||||
assert!(!a.is_empty());
|
||||
assert_eq!(
|
||||
a, b,
|
||||
"identical inputs must publish identical Parquet bytes"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_runner_failure_on_missing_input_exits_nonzero_single_line_without_usage_or_output() {
|
||||
let dir = TempDir::new("missing-input");
|
||||
write_restatement_fixture(&dir.0);
|
||||
fs::remove_file(dir.0.join("qmFilings.bson")).unwrap();
|
||||
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args(FIXTURE_REQUIRED_ARGS)
|
||||
.args(["--out", "out", "--fiscal-period", "quarterly"])
|
||||
.output()
|
||||
.expect("run curate-fundamentals");
|
||||
|
||||
assert_eq!(result.status.code(), Some(1));
|
||||
assert!(result.stdout.is_empty());
|
||||
let stderr = String::from_utf8(result.stderr).unwrap();
|
||||
assert_eq!(stderr.lines().count(), 1, "{stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{stderr}");
|
||||
assert!(stderr.contains("qmFilings.bson"), "{stderr}");
|
||||
assert!(!stderr.contains("Usage:"), "{stderr}");
|
||||
assert!(!dir.0.join("out").exists(), "out must not be created");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_truncated_financials_dump_fails_closed_without_publishing() {
|
||||
let dir = TempDir::new("truncated");
|
||||
write_restatement_fixture(&dir.0);
|
||||
fs::write(dir.0.join("qmFinancials.bson"), [0x10u8, 0x00, 0x00]).unwrap();
|
||||
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args(FIXTURE_REQUIRED_ARGS)
|
||||
.args(["--out", "out", "--fiscal-period", "quarterly"])
|
||||
.output()
|
||||
.expect("run curate-fundamentals");
|
||||
|
||||
assert_eq!(result.status.code(), Some(1));
|
||||
assert!(result.stdout.is_empty());
|
||||
let stderr = String::from_utf8(result.stderr).unwrap();
|
||||
assert_eq!(stderr.lines().count(), 1, "{stderr}");
|
||||
assert!(stderr.starts_with("error: "), "{stderr}");
|
||||
assert!(!dir.0.join("out/fundamentals_pit").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_parse_time_config_errors_fail_closed_before_touching_out() {
|
||||
let dir = TempDir::new("config-errors");
|
||||
write_restatement_fixture(&dir.0);
|
||||
|
||||
let cases: [(&[&str], &str); 4] = [
|
||||
(
|
||||
&["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"],
|
||||
"error: invalid qmFinancials fiscal period configuration: report_period token 'FY' cannot appear in both quarterly and annual lists",
|
||||
),
|
||||
(
|
||||
&["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"],
|
||||
"error: cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'",
|
||||
),
|
||||
(
|
||||
&["--fiscal-period", "quarterly", "--mongo-uri", "mongodb://localhost:27017/stock"],
|
||||
"error: unknown flag '--mongo-uri' for curate-fundamentals",
|
||||
),
|
||||
(
|
||||
&["--fiscal-period", "quarterly", "--k", "0"],
|
||||
"error: duplicate flag '--k'",
|
||||
),
|
||||
];
|
||||
|
||||
for (idx, (extra, expected_error)) in cases.iter().enumerate() {
|
||||
let out = format!("out_{idx}");
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args(FIXTURE_REQUIRED_ARGS)
|
||||
.args(["--out", out.as_str()])
|
||||
.args(*extra)
|
||||
.output()
|
||||
.expect("run curate-fundamentals");
|
||||
assert_eq!(result.status.code(), Some(1), "case {idx}");
|
||||
assert!(result.stdout.is_empty(), "case {idx}");
|
||||
assert_single_line_error_then_usage(&result.stderr, expected_error);
|
||||
assert!(
|
||||
!dir.0.join(&out).exists(),
|
||||
"case {idx}: out must not be created"
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue