diff --git a/database/postgres/init/37-research-findings.sql b/database/postgres/init/37-research-findings.sql new file mode 100644 index 00000000..b4c800ac --- /dev/null +++ b/database/postgres/init/37-research-findings.sql @@ -0,0 +1,99 @@ +-- Research findings & provider caveats schema (M2.1i) +-- Research track migration: creates append-only findings and provider_caveats tables, +-- lookup/idempotency indexes, and immutability triggers reusing +-- reject_research_evidence_mutation() from 17-research-retention.sql. + +CREATE OR REPLACE FUNCTION research_trim_ecmascript(value TEXT) +RETURNS TEXT +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + -- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and + -- trimmed length caps match String.prototype.trim() regardless of DB collation. + SELECT btrim( + value, + U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF' + ); +$$; + +CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER) +RETURNS BOOLEAN +LANGUAGE SQL +IMMUTABLE +STRICT +AS $$ + SELECT COALESCE(array_ndims(refs), 1) = 1 + AND NOT EXISTS ( + SELECT 1 + FROM unnest(refs) AS r + WHERE r IS NULL + OR char_length(r) > max_len + ); +$$; + +CREATE TABLE IF NOT EXISTS findings ( + id TEXT PRIMARY KEY + CHECK (research_trim_ecmascript(id) <> ''), + kind TEXT NOT NULL + CHECK (kind IN ('finding', 'dead_end')), + title TEXT NOT NULL + CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), + summary TEXT NOT NULL + CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), + status TEXT NOT NULL DEFAULT 'pending_review' + CHECK (research_trim_ecmascript(status) <> ''), + created_at TIMESTAMPTZ NOT NULL, + trial_refs TEXT[] NOT NULL + CHECK (cardinality(trial_refs) <= 32) + CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) + CHECK (research_finding_refs_valid(trial_refs, 256)), + evidence_refs TEXT[] NOT NULL + CHECK (cardinality(evidence_refs) <= 32) + CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) + CHECK (research_finding_refs_valid(evidence_refs, 256)), + idempotency_key TEXT + CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key + ON findings (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_findings_created_at + ON findings (created_at); + +CREATE TABLE IF NOT EXISTS provider_caveats ( + id TEXT PRIMARY KEY + CHECK (research_trim_ecmascript(id) <> ''), + provider TEXT NOT NULL + CHECK (research_trim_ecmascript(provider) <> ''), + dataset TEXT NOT NULL + CHECK (research_trim_ecmascript(dataset) <> ''), + caveat TEXT NOT NULL + CHECK (research_trim_ecmascript(caveat) <> ''), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider + ON provider_caveats (lower(provider)); + +DROP TRIGGER IF EXISTS findings_retained ON findings; +CREATE TRIGGER findings_retained + BEFORE UPDATE OR DELETE ON findings + FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS findings_no_truncate ON findings; +CREATE TRIGGER findings_no_truncate + BEFORE TRUNCATE ON findings + FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS provider_caveats_retained ON provider_caveats; +CREATE TRIGGER provider_caveats_retained + BEFORE UPDATE OR DELETE ON provider_caveats + FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); + +DROP TRIGGER IF EXISTS provider_caveats_no_truncate ON provider_caveats; +CREATE TRIGGER provider_caveats_no_truncate + BEFORE TRUNCATE ON provider_caveats + FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 9f973afe..837da47a 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -194,6 +194,65 @@ The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD 2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings). 3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols). +### Research Knowledge & Findings Schema (PostgreSQL, Append-Only) + +Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables). + +- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`. +- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt. +- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. + +```sql +CREATE TABLE IF NOT EXISTS findings ( + id TEXT PRIMARY KEY + CHECK (research_trim_ecmascript(id) <> ''), + kind TEXT NOT NULL + CHECK (kind IN ('finding', 'dead_end')), + title TEXT NOT NULL + CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), + summary TEXT NOT NULL + CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), + status TEXT NOT NULL DEFAULT 'pending_review' + CHECK (research_trim_ecmascript(status) <> ''), + created_at TIMESTAMPTZ NOT NULL, + trial_refs TEXT[] NOT NULL + CHECK (cardinality(trial_refs) <= 32) + CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) + CHECK (research_finding_refs_valid(trial_refs, 256)), + evidence_refs TEXT[] NOT NULL + CHECK (cardinality(evidence_refs) <= 32) + CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) + CHECK (research_finding_refs_valid(evidence_refs, 256)), + idempotency_key TEXT + CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key + ON findings (idempotency_key) + WHERE idempotency_key IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_findings_created_at + ON findings (created_at); + +CREATE TABLE IF NOT EXISTS provider_caveats ( + id TEXT PRIMARY KEY + CHECK (research_trim_ecmascript(id) <> ''), + provider TEXT NOT NULL + CHECK (research_trim_ecmascript(provider) <> ''), + dataset TEXT NOT NULL + CHECK (research_trim_ecmascript(dataset) <> ''), + caveat TEXT NOT NULL + CHECK (research_trim_ecmascript(caveat) <> ''), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider + ON provider_caveats (lower(provider)); +``` + +- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer. +- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`. + --- ## 3. Curated Storage Schemas @@ -217,9 +276,9 @@ Schemas: - **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`. - **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`. - **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, )`. -- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes: +- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes: $$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$ - forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2. + forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted). - **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`. - **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`. - **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`. diff --git a/libs/data/postgres/src/migrations.ts b/libs/data/postgres/src/migrations.ts index 1f05331a..1fa68e3c 100644 --- a/libs/data/postgres/src/migrations.ts +++ b/libs/data/postgres/src/migrations.ts @@ -45,6 +45,7 @@ const RESEARCH_FILES = new Set([ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]); function locateMigrationsDir(): string { diff --git a/libs/data/questdb/src/ilp-v2-writer.ts b/libs/data/questdb/src/ilp-v2-writer.ts new file mode 100644 index 00000000..6917f5b7 --- /dev/null +++ b/libs/data/questdb/src/ilp-v2-writer.ts @@ -0,0 +1,550 @@ +import type { Bar1mRow } from './types'; + +/** QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). */ +export const ILP_V2_DOUBLE_TYPE = 0x10; + +/** Default maximum buffered bytes before flushing a batch (1 MiB). */ +export const DEFAULT_ILP_MAX_BATCH_BYTES = 1_048_576; + +/** Default maximum buffered rows before flushing a batch. */ +export const DEFAULT_ILP_MAX_BATCH_ROWS = 10_000; + +const TABLE_BARS_1M = 'bars_1m'; +const TABLE_FX_1M = 'fx_1m'; + +const INT32_MIN = -2_147_483_648; +const INT32_MAX = 2_147_483_647; +const INT64_MIN = -(2n ** 63n); +const INT64_MAX = 2n ** 63n - 1n; + +const BYTE_SPACE = 0x20; +const BYTE_COMMA = 0x2c; +const BYTE_EQUALS = 0x3d; +const BYTE_LF = 0x0a; +const BYTE_CR = 0x0d; +const BYTE_BACKSLASH = 0x5c; + +const textEncoder = new TextEncoder(); + +const BARS_1M_OPEN_PREFIX = textEncoder.encode(' open=='); +const HIGH_PREFIX = textEncoder.encode(',high=='); +const LOW_PREFIX = textEncoder.encode(',low=='); +const CLOSE_PREFIX = textEncoder.encode(',close=='); +const VOLUME_PREFIX = textEncoder.encode(',volume=='); +const FX_1M_PREFIX = textEncoder.encode(`${TABLE_FX_1M},pair=`); +const FX_1M_SOURCE_PREFIX = textEncoder.encode(',source='); + +/** Valid intraday trading session tags for `bars_1m`. */ +export type Bar1mSession = 'PRE' | 'RTH' | 'POST'; + +/** + * Curated `bars_1m` row input for QuestDB ILP v2 encoding. + * + * Derived from read-side `Bar1mRow` with `vwap` omitted (left NULL in QuestDB) and + * `session` / `source` narrowed to required non-null write values matching `M2_INTRADAY_SCHEMAS.bars_1m`. + */ +export type Bar1mIlpV2Row = Omit & { + session: Bar1mSession; + source: string; +}; + +/** + * Curated `fx_1m` row input for QuestDB ILP v2 encoding. + * + * Matches `M2_INTRADAY_SCHEMAS.fx_1m`: symbols `pair`, `source`; binary doubles + * `open`, `high`, `low`, `close`; designated timestamp `ts` (UTC epoch microseconds). + */ +export interface Fx1mIlpV2Row { + pair: string; + source: string; + open: number; + high: number; + low: number; + close: number; + ts: bigint; +} + +/** Discriminated error kinds for `IlpV2EncodeError`. */ +export type IlpV2EncodeErrorKind = + | 'empty-symbol' + | 'invalid-session' + | 'invalid-listing-id' + | 'non-finite-double' + | 'negative-timestamp' + | 'timestamp-out-of-range'; + +/** + * Typed validation error thrown by `encodeBar1mIlpV2` and `encodeFx1mIlpV2`. + * + * Validation runs atomically before any bytes are encoded or buffered. + */ +export class IlpV2EncodeError extends Error { + public readonly kind: IlpV2EncodeErrorKind; + public readonly field: string; + public readonly value?: number | bigint | string; + + constructor( + kind: IlpV2EncodeErrorKind, + field: string, + message: string, + value?: number | bigint | string + ) { + super(message); + this.name = 'IlpV2EncodeError'; + this.kind = kind; + this.field = field; + if (value !== undefined) { + this.value = value; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Injected output port for `createIlpV2BatchWriter`. */ +export interface IlpV2BatchSink { + write(batch: Uint8Array): Promise; +} + +/** Configuration options for `createIlpV2BatchWriter`. */ +export interface IlpV2BatchWriterOptions { + sink: IlpV2BatchSink; + maxBatchBytes?: number; + maxBatchRows?: number; +} + +/** Write summary returned by `IlpV2BatchWriter.finish()`. */ +export interface IlpV2BatchWriterStats { + rows: number; + batches: number; + bytes: number; +} + +/** Pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. */ +export interface IlpV2BatchWriter { + writeBar1m(row: Bar1mIlpV2Row): Promise; + writeFx1m(row: Fx1mIlpV2Row): Promise; + flush(): Promise; + finish(): Promise; +} + +function validateNonEmptySymbol(field: string, value: string): void { + if (typeof value !== 'string' || value.length === 0) { + throw new IlpV2EncodeError('empty-symbol', field, `empty ILP symbol field '${field}'`); + } +} + +function validateSession(value: Bar1mSession): void { + if (typeof value !== 'string' || value.length === 0) { + throw new IlpV2EncodeError('empty-symbol', 'session', "empty ILP symbol field 'session'"); + } + if (value !== 'PRE' && value !== 'RTH' && value !== 'POST') { + throw new IlpV2EncodeError( + 'invalid-session', + 'session', + `invalid ILP session '${String(value)}' (expected PRE, RTH, or POST)`, + String(value) + ); + } +} + +function validateListingId(value: number): void { + if ( + typeof value !== 'number' || + !Number.isInteger(value) || + value < INT32_MIN || + value > INT32_MAX + ) { + throw new IlpV2EncodeError( + 'invalid-listing-id', + 'listing_id', + `invalid ILP listing_id '${String(value)}' (expected signed 32-bit integer)`, + value + ); + } +} + +function validateFiniteDouble(field: string, value: number): void { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new IlpV2EncodeError( + 'non-finite-double', + field, + `non-finite ILP double field '${field}': ${String(value)}`, + value + ); + } +} + +function validateInt64Timestamp(field: string, value: bigint): void { + if (typeof value !== 'bigint' || value < INT64_MIN || value > INT64_MAX) { + throw new IlpV2EncodeError( + 'timestamp-out-of-range', + field, + `ILP timestamp '${field}' out of signed 64-bit range: ${String(value)}`, + typeof value === 'bigint' ? value : undefined + ); + } +} + +function validateDesignatedTimestamp(field: string, value: bigint): void { + validateInt64Timestamp(field, value); + if (value < 0n) { + throw new IlpV2EncodeError( + 'negative-timestamp', + field, + `negative ILP designated timestamp '${field}': ${value.toString(10)} (must be >= 0)`, + value + ); + } +} + +function needsSymbolEscape(byte: number): boolean { + return ( + byte === BYTE_SPACE || + byte === BYTE_COMMA || + byte === BYTE_EQUALS || + byte === BYTE_LF || + byte === BYTE_CR || + byte === BYTE_BACKSLASH + ); +} + +/** + * Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. + */ +function encodeEscapedSymbol(value: string): Uint8Array { + const raw = textEncoder.encode(value); + let extra = 0; + for (const b of raw) { + if (needsSymbolEscape(b)) { + extra += 1; + } + } + if (extra === 0) { + return raw; + } + + const escaped = new Uint8Array(raw.length + extra); + let out = 0; + for (const b of raw) { + if (needsSymbolEscape(b)) { + escaped[out++] = BYTE_BACKSLASH; + } + escaped[out++] = b; + } + return escaped; +} + +function writeBinaryDoubleField( + out: Uint8Array, + view: DataView, + offset: number, + prefix: Uint8Array, + value: number +): number { + out.set(prefix, offset); + const typeOffset = offset + prefix.byteLength; + out[typeOffset] = ILP_V2_DOUBLE_TYPE; + view.setFloat64(typeOffset + 1, value, true); + return typeOffset + 9; +} + +/** + * Encodes one curated `bars_1m` row in QuestDB ILP v2 format. + * + * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_bar_1m`): + * - Table `bars_1m` + * - Symbols `listing_id` (decimal), `session` (`PRE`/`RTH`/`POST`), `source` (escaped) + * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close`, `volume` (`vwap` omitted) + * - Timestamp column `known_at=t` (signed 64-bit integer preserved as supplied) + * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) + */ +export function encodeBar1mIlpV2(row: Bar1mIlpV2Row): Uint8Array { + validateListingId(row.listing_id); + validateSession(row.session); + validateNonEmptySymbol('source', row.source); + validateFiniteDouble('open', row.open); + validateFiniteDouble('high', row.high); + validateFiniteDouble('low', row.low); + validateFiniteDouble('close', row.close); + validateFiniteDouble('volume', row.volume); + validateInt64Timestamp('known_at', row.known_at); + validateDesignatedTimestamp('ts', row.ts); + + const listingIdDecimal = row.listing_id === 0 ? '0' : String(row.listing_id); + const prefixBytes = textEncoder.encode( + `${TABLE_BARS_1M},listing_id=${listingIdDecimal},session=${row.session},source=` + ); + const escapedSourceBytes = encodeEscapedSymbol(row.source); + const suffixBytes = textEncoder.encode( + `,known_at=${row.known_at.toString(10)}t ${row.ts.toString(10)}t\n` + ); + + // Binary doubles section: ' open==\x10<8>,high==\x10<8>,low==\x10<8>,close==\x10<8>,volume==\x10<8>' + const binaryFieldsLen = + BARS_1M_OPEN_PREFIX.byteLength + + 9 + + HIGH_PREFIX.byteLength + + 9 + + LOW_PREFIX.byteLength + + 9 + + CLOSE_PREFIX.byteLength + + 9 + + VOLUME_PREFIX.byteLength + + 9; + + const out = new Uint8Array( + prefixBytes.byteLength + escapedSourceBytes.byteLength + binaryFieldsLen + suffixBytes.byteLength + ); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + + let offset = 0; + out.set(prefixBytes, offset); + offset += prefixBytes.byteLength; + out.set(escapedSourceBytes, offset); + offset += escapedSourceBytes.byteLength; + + offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); + offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); + offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); + offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); + offset = writeBinaryDoubleField(out, view, offset, VOLUME_PREFIX, row.volume); + + out.set(suffixBytes, offset); + return out; +} + +/** + * Encodes one `fx_1m` row in QuestDB ILP v2 format. + * + * Wire contract (byte-for-byte parity with `tools/curate-etl/src/ilp.rs::encode_fx_1m`): + * - Table `fx_1m` + * - Symbols `pair` (escaped), `source` (escaped) + * - Binary IEEE-754 little-endian doubles `open`, `high`, `low`, `close` + * - Designated timestamp ` t\n` (non-negative signed 64-bit integer) + */ +export function encodeFx1mIlpV2(row: Fx1mIlpV2Row): Uint8Array { + validateNonEmptySymbol('pair', row.pair); + validateNonEmptySymbol('source', row.source); + validateFiniteDouble('open', row.open); + validateFiniteDouble('high', row.high); + validateFiniteDouble('low', row.low); + validateFiniteDouble('close', row.close); + validateDesignatedTimestamp('ts', row.ts); + + const escapedPairBytes = encodeEscapedSymbol(row.pair); + const escapedSourceBytes = encodeEscapedSymbol(row.source); + const suffixBytes = textEncoder.encode(` ${row.ts.toString(10)}t\n`); + + const binaryFieldsLen = + BARS_1M_OPEN_PREFIX.byteLength + + 9 + + HIGH_PREFIX.byteLength + + 9 + + LOW_PREFIX.byteLength + + 9 + + CLOSE_PREFIX.byteLength + + 9; + + const out = new Uint8Array( + FX_1M_PREFIX.byteLength + + escapedPairBytes.byteLength + + FX_1M_SOURCE_PREFIX.byteLength + + escapedSourceBytes.byteLength + + binaryFieldsLen + + suffixBytes.byteLength + ); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + + let offset = 0; + out.set(FX_1M_PREFIX, offset); + offset += FX_1M_PREFIX.byteLength; + out.set(escapedPairBytes, offset); + offset += escapedPairBytes.byteLength; + out.set(FX_1M_SOURCE_PREFIX, offset); + offset += FX_1M_SOURCE_PREFIX.byteLength; + out.set(escapedSourceBytes, offset); + offset += escapedSourceBytes.byteLength; + + offset = writeBinaryDoubleField(out, view, offset, BARS_1M_OPEN_PREFIX, row.open); + offset = writeBinaryDoubleField(out, view, offset, HIGH_PREFIX, row.high); + offset = writeBinaryDoubleField(out, view, offset, LOW_PREFIX, row.low); + offset = writeBinaryDoubleField(out, view, offset, CLOSE_PREFIX, row.close); + + out.set(suffixBytes, offset); + return out; +} + +function assertPositiveIntegerOption(name: string, value: number): void { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) { + throw new RangeError(`ILP v2 batch writer option '${name}' must be a positive integer`); + } +} + +/** + * Creates a pure, sink-injected QuestDB ILP v2 batch writer for `bars_1m` and `fx_1m`. + * + * Operations are serialized in call order so overlapping calls never reorder rows or overlap + * sink writes. Batches always end on whole-row boundaries, fail closed on sink errors, and + * reject writes after `finish()`. + */ +export function createIlpV2BatchWriter(options: IlpV2BatchWriterOptions): IlpV2BatchWriter { + if (!options || !options.sink || typeof options.sink.write !== 'function') { + throw new TypeError('ILP v2 batch writer requires a sink with a write(batch) method'); + } + + const maxBatchBytes = options.maxBatchBytes ?? DEFAULT_ILP_MAX_BATCH_BYTES; + const maxBatchRows = options.maxBatchRows ?? DEFAULT_ILP_MAX_BATCH_ROWS; + assertPositiveIntegerOption('maxBatchBytes', maxBatchBytes); + assertPositiveIntegerOption('maxBatchRows', maxBatchRows); + + const { sink } = options; + + const pendingChunks: Uint8Array[] = []; + let pendingBytes = 0; + let pendingRows = 0; + + let writtenRows = 0; + let writtenBatches = 0; + let writtenBytes = 0; + + let finished = false; + let hasSinkFailure = false; + let sinkFailure: unknown = null; + + let queueTail: Promise = Promise.resolve(); + + function enqueue(operation: () => Promise): Promise { + const result = queueTail.then(operation, operation); + queueTail = result.then( + () => undefined, + () => undefined + ); + return result; + } + + function assertHealthyForMutation(action: string): void { + if (hasSinkFailure) { + throw new Error(`ILP v2 batch writer is closed after a sink write failure (${action})`, { + cause: sinkFailure, + }); + } + if (finished) { + throw new Error(`ILP v2 batch writer is already finished (${action})`); + } + } + + async function flushPending(): Promise { + if (pendingChunks.length === 0) { + return; + } + + const batch = new Uint8Array(pendingBytes); + let offset = 0; + for (const chunk of pendingChunks) { + batch.set(chunk, offset); + offset += chunk.byteLength; + } + + const rowCount = pendingRows; + const byteCount = pendingBytes; + + try { + await sink.write(batch); + } catch (error) { + hasSinkFailure = true; + sinkFailure = error; + pendingChunks.length = 0; + pendingBytes = 0; + pendingRows = 0; + throw error; + } + + pendingChunks.length = 0; + pendingBytes = 0; + pendingRows = 0; + writtenRows += rowCount; + writtenBatches += 1; + writtenBytes += byteCount; + } + + async function enqueueEncodedRow(encoded: Uint8Array): Promise { + if (pendingChunks.length > 0 && pendingBytes + encoded.byteLength > maxBatchBytes) { + await flushPending(); + } + + pendingChunks.push(encoded); + pendingBytes += encoded.byteLength; + pendingRows += 1; + + if (pendingRows >= maxBatchRows || pendingBytes >= maxBatchBytes) { + await flushPending(); + } + } + + function snapshotBar1mRow(row: Bar1mIlpV2Row): Bar1mIlpV2Row { + return { + listing_id: row.listing_id, + ts: row.ts, + known_at: row.known_at, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + volume: row.volume, + session: row.session, + source: row.source, + }; + } + + function snapshotFx1mRow(row: Fx1mIlpV2Row): Fx1mIlpV2Row { + return { + pair: row.pair, + source: row.source, + open: row.open, + high: row.high, + low: row.low, + close: row.close, + ts: row.ts, + }; + } + + return { + writeBar1m(row: Bar1mIlpV2Row): Promise { + const snapshot = snapshotBar1mRow(row); + return enqueue(async () => { + assertHealthyForMutation('writeBar1m'); + const encoded = encodeBar1mIlpV2(snapshot); + await enqueueEncodedRow(encoded); + }); + }, + + writeFx1m(row: Fx1mIlpV2Row): Promise { + const snapshot = snapshotFx1mRow(row); + return enqueue(async () => { + assertHealthyForMutation('writeFx1m'); + const encoded = encodeFx1mIlpV2(snapshot); + await enqueueEncodedRow(encoded); + }); + }, + + flush(): Promise { + return enqueue(async () => { + assertHealthyForMutation('flush'); + await flushPending(); + }); + }, + + finish(): Promise { + return enqueue(async () => { + assertHealthyForMutation('finish'); + await flushPending(); + finished = true; + return { + rows: writtenRows, + batches: writtenBatches, + bytes: writtenBytes, + }; + }); + }, + }; +} diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 94841d60..6036ae94 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -9,6 +9,23 @@ export { QuestDBClient, readBars1m } from './client'; export { QuestDBHealthMonitor } from './health'; export { QuestDBQueryBuilder } from './query-builder'; export { QuestDBInfluxWriter } from './influx-writer'; +export { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + ILP_V2_DOUBLE_TYPE, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Bar1mSession, + type Fx1mIlpV2Row, + type IlpV2BatchSink, + type IlpV2BatchWriter, + type IlpV2BatchWriterOptions, + type IlpV2BatchWriterStats, + type IlpV2EncodeErrorKind, +} from './ilp-v2-writer'; export { formatCreateTableSQL, getM2IntradayDDL, diff --git a/libs/data/questdb/src/influx-writer.ts b/libs/data/questdb/src/influx-writer.ts index 90e6145b..6f48aae7 100644 --- a/libs/data/questdb/src/influx-writer.ts +++ b/libs/data/questdb/src/influx-writer.ts @@ -11,6 +11,9 @@ interface QuestDBClientInterface { * * Provides high-performance data ingestion using InfluxDB Line Protocol * which QuestDB supports natively for optimal time-series data insertion. + * + * @deprecated Legacy text-ILP writer. Use `createIlpV2BatchWriter` (from `./ilp-v2-writer`) + * for QuestDB ILP v2 binary-double ingestion into `bars_1m` and `fx_1m`. */ export class QuestDBInfluxWriter { private readonly logger: ReturnType; diff --git a/libs/data/questdb/test/ilp-v2-writer-edges.test.ts b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts new file mode 100644 index 00000000..d43bd8ae --- /dev/null +++ b/libs/data/questdb/test/ilp-v2-writer-edges.test.ts @@ -0,0 +1,426 @@ +import { describe, expect, it } from 'bun:test'; +import { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Bar1mSession, + type Fx1mIlpV2Row, + type IlpV2BatchSink, +} from '../src/index'; + +const encoder = new TextEncoder(); + +function asciiBytes(text: string): number[] { + return Array.from(encoder.encode(text)); +} + +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { + const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { + return { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_000_000n, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: 'RTH', + source: 'eod_unadj', + ...overrides, + }; +} + +function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { + return { + pair: 'USD.CAD', + source: 'eod', + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + ts: 1_736_951_400_000_000n, + ...overrides, + }; +} + +function expectEncodeError(fn: () => unknown, kind: IlpV2EncodeError['kind'], field: string) { + let caught: unknown; + try { + fn(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(IlpV2EncodeError); + expect((caught as IlpV2EncodeError).kind).toBe(kind); + expect((caught as IlpV2EncodeError).field).toBe(field); +} + +describe('ILP v2 encoder edge cases', () => { + it('matches golden_bytes_literal_ieee754_little_endian_without_to_le_bytes with hand-written bytes', () => { + // Mirrors `golden_bytes_literal_ieee754_little_endian_without_to_le_bytes` + // in `tools/curate-etl/src/ilp_tests.rs` (key 7, source eod_unadj). + const actual = encodeBar1mIlpV2({ + listing_id: 7, + ts: 1_700_000_000_000_000n, + known_at: 1_700_000_060_000_000n, + open: 1.0, + high: 2.0, + low: 0.5, + close: 1.5, + volume: 0.0, + session: 'RTH', + source: 'eod_unadj', + }); + + const expected = new Uint8Array([ + ...asciiBytes('bars_1m,listing_id=7,session=RTH,source=eod_unadj '), + ...asciiBytes('open=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf0, + 0x3f, + ...asciiBytes(',high=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x40, + ...asciiBytes(',low=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xe0, + 0x3f, + ...asciiBytes(',close=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf8, + 0x3f, + ...asciiBytes(',volume=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + ...asciiBytes(',known_at=1700000060000000t 1700000000000000t\n'), + ]); + + expect(actual).toEqual(expected); + }); + + it('preserves the negative-zero sign bit like Rust f64::to_le_bytes and emits -0 listing_id as 0', () => { + const bytes = encodeBar1mIlpV2(sampleBar({ listing_id: -0, volume: -0 })); + + expect(Array.from(bytes.slice(0, 22))).toEqual(asciiBytes('bars_1m,listing_id=0,s')); + const volumePrefix = encoder.encode(',volume=='); + const suffix = encoder.encode(',known_at=1736951460000000t 1736951400000000t\n'); + const volStart = bytes.byteLength - suffix.byteLength - 9 - volumePrefix.byteLength; + expect(bytes.slice(volStart, volStart + volumePrefix.byteLength)).toEqual(volumePrefix); + expect( + Array.from( + bytes.slice(volStart + volumePrefix.byteLength, volStart + volumePrefix.byteLength + 9) + ) + ).toEqual([0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]); + }); + + it('encodes extreme finite doubles (MAX_VALUE, MIN_VALUE subnormal, negative) without rejection', () => { + const bytes = encodeFx1mIlpV2( + sampleFx({ open: Number.MAX_VALUE, high: Number.MIN_VALUE, low: -1.5, close: 0 }) + ); + const head = encoder.encode('fx_1m,pair=USD.CAD,source=eod open=='); + expect(bytes.slice(0, head.byteLength)).toEqual(head); + let o = head.byteLength; + // MAX_VALUE = 0x7fefffffffffffff + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xef, 0x7f, + ]); + o += 9 + ',high=='.length; + // MIN_VALUE = 0x0000000000000001 + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]); + o += 9 + ',low=='.length; + // -1.5 = 0xbff8000000000000 + expect(Array.from(bytes.slice(o, o + 9))).toEqual([ + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xbf, + ]); + }); + + it('returns a fresh buffer per call so mutating one encoding cannot corrupt another', () => { + const row = sampleFx(); + const a = encodeFx1mIlpV2(row); + const b = encodeFx1mIlpV2(row); + a.fill(0); + expect(b).toEqual(encodeFx1mIlpV2(row)); + expect(b[0]).toBe(0x66); // 'f' + }); + + it('escapes a symbol consisting only of special characters', () => { + const bytes = encodeFx1mIlpV2(sampleFx({ pair: ' ,=\\\n\r' })); + const expected = encoder.encode('fx_1m,pair=\\ \\,\\=\\\\\\\n\\\r,source=eod open=='); + expect(bytes.slice(0, expected.byteLength)).toEqual(expected); + }); + + it('rejects invalid or empty session tags with a typed error', () => { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: 'rth' as Bar1mSession })), + 'invalid-session', + 'session' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: 'RTH ' as Bar1mSession })), + 'invalid-session', + 'session' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ session: '' as Bar1mSession })), + 'empty-symbol', + 'session' + ); + }); + + it('rejects non-bigint timestamps (JS number) instead of silently encoding them', () => { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: 1_700_000_000_000_000 as unknown as bigint })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: 5 as unknown as bigint })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ ts: 0 as unknown as bigint })), + 'timestamp-out-of-range', + 'ts' + ); + }); + + it('accepts the fx_1m designated timestamp at INT64_MAX', () => { + const max = 2n ** 63n - 1n; + const bytes = encodeFx1mIlpV2(sampleFx({ ts: max })); + const suffix = encoder.encode(` ${max.toString(10)}t\n`); + expect(bytes.slice(bytes.byteLength - suffix.byteLength)).toEqual(suffix); + }); +}); + +describe('createIlpV2BatchWriter edge cases', () => { + it('rejects construction without a usable sink and rejects unsafe-integer limits', () => { + expect(() => createIlpV2BatchWriter(undefined as never)).toThrow(TypeError); + expect(() => createIlpV2BatchWriter({} as never)).toThrow(TypeError); + expect(() => createIlpV2BatchWriter({ sink: {} as IlpV2BatchSink })).toThrow(TypeError); + const sink: IlpV2BatchSink = { write: async () => {} }; + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 2 ** 53 })).toThrow(RangeError); + expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: '5' as unknown as number })).toThrow( + RangeError + ); + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: 1, maxBatchRows: 1 })).not.toThrow(); + }); + + it('flushes at DEFAULT_ILP_MAX_BATCH_ROWS when no limits are supplied', async () => { + const batches: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ sink: { write: async b => void batches.push(b) } }); + const row = sampleFx({ ts: 0n }); + const rowLen = encodeFx1mIlpV2(row).byteLength; + // Row size keeps 10_000 rows well below the 1 MiB default, so only the row limit triggers. + expect(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS).toBeLessThan(DEFAULT_ILP_MAX_BATCH_BYTES); + + for (let i = 0; i < DEFAULT_ILP_MAX_BATCH_ROWS - 1; i++) { + await writer.writeFx1m(row); + } + expect(batches).toHaveLength(0); + await writer.writeFx1m(row); + expect(batches).toHaveLength(1); + expect(batches[0]!.byteLength).toBe(rowLen * DEFAULT_ILP_MAX_BATCH_ROWS); + + await writer.writeFx1m(row); + const stats = await writer.finish(); + expect(stats).toEqual({ + rows: DEFAULT_ILP_MAX_BATCH_ROWS + 1, + batches: 2, + bytes: rowLen * (DEFAULT_ILP_MAX_BATCH_ROWS + 1), + }); + }); + + it('hands the sink a fresh batch buffer per flush so retained batches are never overwritten', async () => { + const retained: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ + sink: { write: async b => void retained.push(b) }, + maxBatchRows: 1, + }); + const r1 = sampleBar({ listing_id: 1 }); + const r2 = sampleBar({ listing_id: 2 }); + await writer.writeBar1m(r1); + await writer.writeBar1m(r2); + await writer.finish(); + expect(retained[0]).not.toBe(retained[1]); + expect(retained[0]!.buffer).not.toBe(retained[1]!.buffer); + expect(retained).toEqual([encodeBar1mIlpV2(r1), encodeBar1mIlpV2(r2)]); + }); + + it('a rejected row in the middle of overlapping writes does not block or reorder later queued rows', async () => { + const batches: Uint8Array[] = []; + const writer = createIlpV2BatchWriter({ + sink: { write: async b => void batches.push(b.slice()) }, + maxBatchRows: 2, + maxBatchBytes: 100_000, + }); + const a = sampleBar({ listing_id: 1 }); + const c = sampleFx({ pair: 'EUR.USD' }); + const d = sampleBar({ listing_id: 4 }); + + const pa = writer.writeBar1m(a); + const pb = writer.writeBar1m(sampleBar({ high: Number.NaN })); + const pc = writer.writeFx1m(c); + const pd = writer.writeBar1m(d); + const pFinish = writer.finish(); + + await pa; + await expect(pb).rejects.toBeInstanceOf(IlpV2EncodeError); + await pc; + await pd; + const stats = await pFinish; + + const expected = [encodeBar1mIlpV2(a), encodeFx1mIlpV2(c), encodeBar1mIlpV2(d)]; + expect(batches).toEqual([concatBytes(expected.slice(0, 2)), expected[2]!]); + expect(stats).toEqual({ + rows: 3, + batches: 2, + bytes: expected.reduce((s, e) => s + e.byteLength, 0), + }); + }); + + it('treats a synchronously throwing sink like a rejected write and fails closed', async () => { + const boom = new Error('sync sink failure'); + let calls = 0; + const sink: IlpV2BatchSink = { + write(): Promise { + calls += 1; + throw boom; + }, + }; + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1 }); + + await expect(writer.writeBar1m(sampleBar())).rejects.toBe(boom); + await expect(writer.writeBar1m(sampleBar())).rejects.toThrow(/sink write failure/i); + await expect(writer.flush()).rejects.toThrow(/sink write failure/i); + expect(calls).toBe(1); + }); + + it('propagates a sink failure on the finish() tail flush, excludes it from stats, and stays closed', async () => { + const boom = new Error('tail failure'); + let calls = 0; + const sink: IlpV2BatchSink = { + async write(): Promise { + calls += 1; + if (calls === 2) { + throw boom; + } + }, + }; + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); + await writer.writeBar1m(sampleBar({ listing_id: 1 })); + await writer.writeBar1m(sampleBar({ listing_id: 2 })); // batch 1 OK + await writer.writeBar1m(sampleBar({ listing_id: 3 })); // pending tail + + await expect(writer.finish()).rejects.toBe(boom); + expect(calls).toBe(2); + + const err = await writer.finish().then( + () => null, + (e: unknown) => e as Error + ); + expect(err).toBeInstanceOf(Error); + expect(err!.message).toMatch(/sink write failure/i); + // The original sink error is preserved as the cause for diagnostics. + expect(err!.cause).toBe(boom); + expect(calls).toBe(2); + }); + + it('flush() on an explicit call propagates sink failure and blocks the tail on finish()', async () => { + const boom = new Error('flush failure'); + let calls = 0; + const writer = createIlpV2BatchWriter({ + sink: { + async write(): Promise { + calls += 1; + throw boom; + }, + }, + }); + await writer.writeFx1m(sampleFx()); + await expect(writer.flush()).rejects.toBe(boom); + await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); + await expect(writer.finish()).rejects.toThrow(/sink write failure/i); + expect(calls).toBe(1); + }); + + it('serializes an overlapping explicit flush() behind in-flight writes', async () => { + const order: string[] = []; + let release: (() => void) | null = null; + const writer = createIlpV2BatchWriter({ + sink: { + write(b: Uint8Array): Promise { + order.push(`write:${b.byteLength}`); + if (release === null) { + return new Promise(resolve => { + release = resolve; + }); + } + return Promise.resolve(); + }, + }, + maxBatchRows: 1, + }); + const row = sampleFx(); + const len = encodeFx1mIlpV2(row).byteLength; + + const p1 = writer.writeFx1m(row); + const pFlush = writer.flush().then(() => order.push('flushed')); + const p2 = writer.writeFx1m(row); + + await Promise.resolve(); + expect(order).toEqual([`write:${len}`]); + release!(); + await Promise.all([p1, pFlush, p2]); + expect(order).toEqual([`write:${len}`, 'flushed', `write:${len}`]); + }); +}); diff --git a/libs/data/questdb/test/ilp-v2-writer.test.ts b/libs/data/questdb/test/ilp-v2-writer.test.ts new file mode 100644 index 00000000..c7d4c6ca --- /dev/null +++ b/libs/data/questdb/test/ilp-v2-writer.test.ts @@ -0,0 +1,820 @@ +import { describe, expect, it } from 'bun:test'; +import { + createIlpV2BatchWriter, + DEFAULT_ILP_MAX_BATCH_BYTES, + DEFAULT_ILP_MAX_BATCH_ROWS, + encodeBar1mIlpV2, + encodeFx1mIlpV2, + ILP_V2_DOUBLE_TYPE, + IlpV2EncodeError, + type Bar1mIlpV2Row, + type Fx1mIlpV2Row, + type IlpV2BatchSink, +} from '../src/index'; + +const encoder = new TextEncoder(); + +function asciiBytes(text: string): number[] { + return Array.from(encoder.encode(text)); +} + +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { + const total = chunks.reduce((sum, c) => sum + c.byteLength, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} + +function indexOfSubarray(haystack: Uint8Array, needle: Uint8Array): number { + outer: for (let i = 0; i <= haystack.length - needle.length; i++) { + for (let j = 0; j < needle.length; j++) { + if (haystack[i + j] !== needle[j]) { + continue outer; + } + } + return i; + } + return -1; +} + +function sampleBar(overrides: Partial = {}): Bar1mIlpV2Row { + return { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_000_000n, + open: 123.45, + high: 125.75, + low: 122.125, + close: 124.5, + volume: 98_765.0, + session: 'RTH', + source: 'eod_unadj', + ...overrides, + }; +} + +function sampleFx(overrides: Partial = {}): Fx1mIlpV2Row { + return { + pair: 'USD.CAD', + source: 'eod', + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + ts: 1_736_951_400_000_000n, + ...overrides, + }; +} + +function createMemorySink(): { sink: IlpV2BatchSink; batches: Uint8Array[] } { + const batches: Uint8Array[] = []; + const sink: IlpV2BatchSink = { + async write(batch: Uint8Array): Promise { + batches.push(batch.slice()); + }, + }; + return { sink, batches }; +} + +describe('ILP v2 writer constants', () => { + it('matches Rust tools/curate-etl/src/ilp.rs constants', () => { + expect(ILP_V2_DOUBLE_TYPE).toBe(0x10); + expect(DEFAULT_ILP_MAX_BATCH_BYTES).toBe(1_048_576); + expect(DEFAULT_ILP_MAX_BATCH_ROWS).toBe(10_000); + }); +}); + +describe('ILP v2 byte-parity with tools/curate-etl/src/ilp_tests.rs', () => { + it('matches golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract byte-for-byte', () => { + // Mirrors `golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract` + // in `tools/curate-etl/src/ilp_tests.rs`. + const row: Bar1mIlpV2Row = { + listing_id: 42, + ts: 1_736_951_400_000_000n, + known_at: 1_736_951_460_123_456n, + open: 150.25, + high: 151.75, + low: 149.5, + close: 151.125, + volume: 12_345.0, + session: 'RTH', + source: 'eod_unadj', + }; + + const actual = encodeBar1mIlpV2(row); + + // Expected wire bytes written out literally (little-endian IEEE-754 doubles): + // 150.25 -> 0x4062c80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x62, 0x40] + // 151.75 -> 0x4062f80000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x62, 0x40] + // 149.5 -> 0x4062b00000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x62, 0x40] + // 151.125 -> 0x4062e40000000000 -> [0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x62, 0x40] + // 12345.0 -> 0x40c81c8000000000 -> [0x00, 0x00, 0x00, 0x00, 0x80, 0x1c, 0xc8, 0x40] + const expected = new Uint8Array([ + ...asciiBytes('bars_1m,listing_id=42,session=RTH,source=eod_unadj open=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xc8, + 0x62, + 0x40, + ...asciiBytes(',high=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xf8, + 0x62, + 0x40, + ...asciiBytes(',low=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xb0, + 0x62, + 0x40, + ...asciiBytes(',close=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xe4, + 0x62, + 0x40, + ...asciiBytes(',volume=='), + 0x10, + 0x00, + 0x00, + 0x00, + 0x00, + 0x80, + 0x1c, + 0xc8, + 0x40, + ...asciiBytes(',known_at=1736951460123456t 1736951400000000t\n'), + ]); + + expect(actual).toEqual(expected); + expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1); + + // Verify PRE and POST session tags as in the Rust golden test. + const preBytes = encodeBar1mIlpV2({ ...row, session: 'PRE' }); + expect( + indexOfSubarray(preBytes, encoder.encode('bars_1m,listing_id=42,session=PRE,source=eod_unadj ')) + ).toBe(0); + + const postBytes = encodeBar1mIlpV2({ ...row, session: 'POST' }); + expect( + indexOfSubarray( + postBytes, + encoder.encode('bars_1m,listing_id=42,session=POST,source=eod_unadj ') + ) + ).toBe(0); + }); + + it('matches golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract byte-for-byte', () => { + // Mirrors `golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract` + // in `tools/curate-etl/src/ilp_tests.rs`. + const row: Fx1mIlpV2Row = { + pair: 'USD.CAD', + ts: 1_736_951_400_000_000n, + open: 1.3625, + high: 1.365, + low: 1.36125, + close: 1.364375, + source: 'eod', + }; + + const actual = encodeFx1mIlpV2(row); + + // Expected wire bytes written out literally (little-endian IEEE-754 doubles): + // 1.3625 -> 0x3ff5cccccccccccc -> [0xcd, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xf5, 0x3f] + // 1.365 -> 0x3ff5d70a3d70a3d7 -> [0xd7, 0xa3, 0x70, 0x3d, 0x0a, 0xd7, 0xf5, 0x3f] + // 1.36125 -> 0x3ff5c7ae147ae148 -> [0x48, 0xe1, 0x7a, 0x14, 0xae, 0xc7, 0xf5, 0x3f] + // 1.364375 -> 0x3ff5d47ae147ae14 -> [0x14, 0xae, 0x47, 0xe1, 0x7a, 0xd4, 0xf5, 0x3f] + const expected = new Uint8Array([ + ...asciiBytes('fx_1m,pair=USD.CAD,source=eod open=='), + 0x10, + 0xcd, + 0xcc, + 0xcc, + 0xcc, + 0xcc, + 0xcc, + 0xf5, + 0x3f, + ...asciiBytes(',high=='), + 0x10, + 0xd7, + 0xa3, + 0x70, + 0x3d, + 0x0a, + 0xd7, + 0xf5, + 0x3f, + ...asciiBytes(',low=='), + 0x10, + 0x48, + 0xe1, + 0x7a, + 0x14, + 0xae, + 0xc7, + 0xf5, + 0x3f, + ...asciiBytes(',close=='), + 0x10, + 0x14, + 0xae, + 0x47, + 0xe1, + 0x7a, + 0xd4, + 0xf5, + 0x3f, + ...asciiBytes(' 1736951400000000t\n'), + ]); + + expect(actual).toEqual(expected); + expect(indexOfSubarray(actual, encoder.encode('known_at'))).toBe(-1); + expect(indexOfSubarray(actual, encoder.encode('volume'))).toBe(-1); + expect(indexOfSubarray(actual, encoder.encode('vwap'))).toBe(-1); + }); +}); + +describe('ILP v2 escaping, timestamps, and atomic rejection', () => { + it('escapes all six ILP symbol characters and preserves UTF-8 and signed known_at', () => { + // Mirrors `symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection` + // in `tools/curate-etl/src/ilp_tests.rs`. + const rawSym = 'a b,c=d\\e\nf\rg caf\u00e9'; + const expectedEscaped = new Uint8Array([ + ...asciiBytes('a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf'), + 0xc3, + 0xa9, + ]); + + // Rust `encode_bar_1m` writes signed `known_at` via `write_i64_decimal` without rejecting < 0. + const barBytes = encodeBar1mIlpV2( + sampleBar({ + listing_id: 7, + ts: 0n, + known_at: -1n, + source: rawSym, + }) + ); + const expectedBarPrefix = concatBytes([ + encoder.encode('bars_1m,listing_id=7,session=RTH,source='), + expectedEscaped, + encoder.encode(' '), + ]); + expect(barBytes.slice(0, expectedBarPrefix.byteLength)).toEqual(expectedBarPrefix); + const expectedBarSuffix = encoder.encode(',known_at=-1t 0t\n'); + expect(barBytes.slice(barBytes.byteLength - expectedBarSuffix.byteLength)).toEqual( + expectedBarSuffix + ); + + // Also check signed 64-bit timestamp endpoints and INT32 listing_id endpoints. + const int64Min = -(2n ** 63n); + const int64Max = 2n ** 63n - 1n; + const endpointBar = encodeBar1mIlpV2( + sampleBar({ + listing_id: -2_147_483_648, + known_at: int64Min, + ts: int64Max, + }) + ); + expect( + indexOfSubarray(endpointBar, encoder.encode('bars_1m,listing_id=-2147483648,session=RTH,')) + ).toBe(0); + const endpointSuffix = encoder.encode( + `,known_at=${int64Min.toString(10)}t ${int64Max.toString(10)}t\n` + ); + expect(endpointBar.slice(endpointBar.byteLength - endpointSuffix.byteLength)).toEqual( + endpointSuffix + ); + + const maxListingBar = encodeBar1mIlpV2( + sampleBar({ + listing_id: 2_147_483_647, + known_at: int64Max, + ts: 0n, + }) + ); + expect( + indexOfSubarray(maxListingBar, encoder.encode('bars_1m,listing_id=2147483647,session=RTH,')) + ).toBe(0); + + // FX pair and source escaping. + const fxBytes = encodeFx1mIlpV2( + sampleFx({ + pair: rawSym, + source: 'src=1,2 3\\4\n\r', + ts: 123n, + }) + ); + const expectedFxPrefix = concatBytes([ + encoder.encode('fx_1m,pair='), + expectedEscaped, + encoder.encode(',source=src\\=1\\,2\\ 3\\\\4\\\n\\\r '), + ]); + expect(fxBytes.slice(0, expectedFxPrefix.byteLength)).toEqual(expectedFxPrefix); + const expectedFxSuffix = encoder.encode(' 123t\n'); + expect(fxBytes.slice(fxBytes.byteLength - expectedFxSuffix.byteLength)).toEqual( + expectedFxSuffix + ); + }); + + it('throws typed IlpV2EncodeError for negative ts, int64 overflow, non-finite doubles, empty symbols, and non-int32 listing_id', () => { + const expectEncodeError = ( + fn: () => unknown, + kind: IlpV2EncodeError['kind'], + field: string + ) => { + try { + fn(); + throw new Error('Expected IlpV2EncodeError to be thrown'); + } catch (err) { + expect(err).toBeInstanceOf(IlpV2EncodeError); + const encodeErr = err as IlpV2EncodeError; + expect(encodeErr.kind).toBe(kind); + expect(encodeErr.field).toBe(field); + } + }; + + // Negative designated timestamps. + expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ ts: -1n })), 'negative-timestamp', 'ts'); + expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ ts: -42n })), 'negative-timestamp', 'ts'); + + // Signed 64-bit timestamp overflow / underflow. + const overInt64 = 2n ** 63n; + const underInt64 = -(2n ** 63n) - 1n; + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: overInt64 })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ ts: underInt64 })), + 'timestamp-out-of-range', + 'ts' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: overInt64 })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ known_at: underInt64 })), + 'timestamp-out-of-range', + 'known_at' + ); + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ ts: overInt64 })), + 'timestamp-out-of-range', + 'ts' + ); + + // Non-finite doubles across every double column. + for (const badVal of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { + for (const field of ['open', 'high', 'low', 'close', 'volume'] as const) { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ [field]: badVal })), + 'non-finite-double', + field + ); + } + for (const field of ['open', 'high', 'low', 'close'] as const) { + expectEncodeError( + () => encodeFx1mIlpV2(sampleFx({ [field]: badVal })), + 'non-finite-double', + field + ); + } + } + + // Empty symbols. + expectEncodeError(() => encodeBar1mIlpV2(sampleBar({ source: '' })), 'empty-symbol', 'source'); + expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ pair: '' })), 'empty-symbol', 'pair'); + expectEncodeError(() => encodeFx1mIlpV2(sampleFx({ source: '' })), 'empty-symbol', 'source'); + + // Non-INT32 listing_id. + for (const badId of [ + 1.5, + -0.25, + 2_147_483_648, + -2_147_483_649, + Number.NaN, + Number.POSITIVE_INFINITY, + ]) { + expectEncodeError( + () => encodeBar1mIlpV2(sampleBar({ listing_id: badId })), + 'invalid-listing-id', + 'listing_id' + ); + } + }); + + it('rejects invalid rows at a batch boundary without calling sink and preserves pending rows', async () => { + const validRow = sampleBar({ listing_id: 101 }); + const validBytes = encodeBar1mIlpV2(validRow); + const { sink, batches } = createMemorySink(); + + // Limit allows 1 row to sit pending right at the byte boundary so a second valid row would flush. + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: validBytes.byteLength + 1, + maxBatchRows: 2, + }); + + await writer.writeBar1m(validRow); + expect(batches).toHaveLength(0); + + // Rejected bar and FX rows must not flush the pending row or write anything to sink. + await expect(writer.writeBar1m(sampleBar({ ts: -1n }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeBar1m(sampleBar({ volume: Number.NaN }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeBar1m(sampleBar({ source: '' }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeBar1m(sampleBar({ listing_id: 3.14 }))).rejects.toBeInstanceOf( + IlpV2EncodeError + ); + await expect(writer.writeFx1m(sampleFx({ pair: '' }))).rejects.toBeInstanceOf(IlpV2EncodeError); + await expect(writer.writeFx1m(sampleFx({ ts: -5n }))).rejects.toBeInstanceOf(IlpV2EncodeError); + expect(batches).toHaveLength(0); + + // Pending valid row is still intact and flushes cleanly on finish(). + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 1, batches: 1, bytes: validBytes.byteLength }); + expect(batches).toEqual([validBytes]); + }); +}); + +describe('createIlpV2BatchWriter batching, boundaries, and option validation', () => { + it('validates maxBatchBytes and maxBatchRows at construction', () => { + const { sink } = createMemorySink(); + for (const invalid of [0, -1, -100, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => createIlpV2BatchWriter({ sink, maxBatchBytes: invalid })).toThrow(RangeError); + expect(() => createIlpV2BatchWriter({ sink, maxBatchRows: invalid })).toThrow(RangeError); + } + }); + + it('flushes on exact maxBatchRows, exact maxBatchBytes, pre-overflow, oversized singleton, and explicit/empty flush', async () => { + // Include a finite double whose IEEE-754 LE payload contains 0x0a (LF) and a symbol with LF. + const lfDoubleBuf = new Uint8Array([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); + const doubleWithLf = new DataView(lfDoubleBuf.buffer).getFloat64(0, true); + expect(Number.isFinite(doubleWithLf)).toBe(true); + + const row = sampleBar({ open: doubleWithLf, source: 'eod\nwith_lf' }); + const oneLine = encodeBar1mIlpV2(row); + const rowLen = oneLine.byteLength; + + // 1. Exact row limit (maxBatchRows = 3) + 1 remainder row. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 100_000, + maxBatchRows: 3, + }); + for (let i = 0; i < 7; i++) { + await writer.writeBar1m(row); + } + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 7, batches: 3, bytes: 7 * rowLen }); + expect(batches).toHaveLength(3); + expect(batches[0]).toEqual(concatBytes([oneLine, oneLine, oneLine])); + expect(batches[1]).toEqual(concatBytes([oneLine, oneLine, oneLine])); + expect(batches[2]).toEqual(oneLine); + expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); + } + + // 2. Exact byte limit (2 * rowLen): flushes immediately when the 2nd and 4th rows hit the limit. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 2 * rowLen, + maxBatchRows: 100, + }); + await writer.writeBar1m(row); + expect(batches).toHaveLength(0); + await writer.writeBar1m(row); + expect(batches).toHaveLength(1); + expect(batches[0]).toEqual(concatBytes([oneLine, oneLine])); + await writer.writeBar1m(row); + expect(batches).toHaveLength(1); + await writer.writeBar1m(row); + expect(batches).toHaveLength(2); + expect(batches[1]).toEqual(concatBytes([oneLine, oneLine])); + await writer.writeBar1m(row); + expect(batches).toHaveLength(2); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 5, batches: 3, bytes: 5 * rowLen }); + expect(batches).toHaveLength(3); + expect(batches[2]).toEqual(oneLine); + } + + // 3. Row would exceed remaining capacity (2 * rowLen - 1): pre-flushes before appending. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 2 * rowLen - 1, + maxBatchRows: 100, + }); + for (let i = 0; i < 3; i++) { + await writer.writeBar1m(row); + } + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 3, batches: 3, bytes: 3 * rowLen }); + expect(batches).toEqual([oneLine, oneLine, oneLine]); + } + + // 4. Individually oversized row (maxBatchBytes = 16 < rowLen): sent alone, never split. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ + sink, + maxBatchBytes: 16, + maxBatchRows: 100, + }); + await writer.writeBar1m(row); + await writer.writeBar1m(row); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 2, batches: 2, bytes: 2 * rowLen }); + expect(batches).toEqual([oneLine, oneLine]); + } + + // 5. Empty flush, explicit flush, and zero-row finish. + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink, maxBatchBytes: 100_000, maxBatchRows: 10 }); + await writer.flush(); + expect(batches).toHaveLength(0); + await writer.writeBar1m(row); + await writer.flush(); + expect(batches).toEqual([oneLine]); + await writer.flush(); + expect(batches).toHaveLength(1); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 1, batches: 1, bytes: rowLen }); + } + + { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink }); + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 0, batches: 0, bytes: 0 }); + expect(batches).toHaveLength(0); + } + }); + + it('preserves mixed bars_1m and fx_1m input order and rejects writes after finish()', async () => { + const bar1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n }); + const fx1 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n }); + const bar2 = sampleBar({ listing_id: 2, ts: 1_700_000_120_000_000n }); + const fx2 = sampleFx({ pair: 'EUR.USD', ts: 1_700_000_180_000_000n }); + + const expectedAll = concatBytes([ + encodeBar1mIlpV2(bar1), + encodeFx1mIlpV2(fx1), + encodeBar1mIlpV2(bar2), + encodeFx1mIlpV2(fx2), + ]); + + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 2, maxBatchBytes: 100_000 }); + + await writer.writeBar1m(bar1); + await writer.writeFx1m(fx1); + await writer.writeBar1m(bar2); + await writer.writeFx1m(fx2); + + const stats = await writer.finish(); + expect(stats).toEqual({ rows: 4, batches: 2, bytes: expectedAll.byteLength }); + expect(concatBytes(batches)).toEqual(expectedAll); + expect(batches.every(b => b[b.byteLength - 1] === 0x0a)).toBe(true); + + // Writes, flush, and finish after finish() throw without calling sink. + await expect(writer.writeBar1m(bar1)).rejects.toThrow(/already finished/i); + await expect(writer.writeFx1m(fx1)).rejects.toThrow(/already finished/i); + await expect(writer.flush()).rejects.toThrow(/already finished/i); + await expect(writer.finish()).rejects.toThrow(/already finished/i); + expect(batches).toHaveLength(2); + }); +}); + +describe('createIlpV2BatchWriter serialization and fail-closed sink errors', () => { + it('serializes overlapping writes and finish() without overlapping sink calls', async () => { + let inFlight = 0; + let maxInFlight = 0; + const batches: Uint8Array[] = []; + const resolvers: Array<() => void> = []; + + const sink: IlpV2BatchSink = { + write(batch: Uint8Array): Promise { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + batches.push(batch.slice()); + return new Promise(resolve => { + resolvers.push(() => { + inFlight -= 1; + resolve(); + }); + }); + }, + }; + + const row1 = sampleBar({ listing_id: 1, ts: 1_700_000_000_000_000n }); + const row2 = sampleFx({ pair: 'USD.CAD', ts: 1_700_000_060_000_000n }); + const row3 = sampleBar({ listing_id: 3, ts: 1_700_000_120_000_000n }); + + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); + + // Launch overlapping operations without awaiting between calls. + const p1 = writer.writeBar1m(row1); + const p2 = writer.writeFx1m(row2); + const p3 = writer.writeBar1m(row3); + const pFinish = writer.finish(); + + // Drain queued manual resolutions one by one as each sink.write starts. + await Promise.resolve(); + expect(resolvers).toHaveLength(1); + expect(inFlight).toBe(1); + resolvers[0]!(); + await p1; + + await Promise.resolve(); + expect(resolvers).toHaveLength(2); + expect(inFlight).toBe(1); + resolvers[1]!(); + await p2; + + await Promise.resolve(); + expect(resolvers).toHaveLength(3); + expect(inFlight).toBe(1); + resolvers[2]!(); + await p3; + + const stats = await pFinish; + expect(maxInFlight).toBe(1); + expect(stats).toEqual({ + rows: 3, + batches: 3, + bytes: + encodeBar1mIlpV2(row1).byteLength + + encodeFx1mIlpV2(row2).byteLength + + encodeBar1mIlpV2(row3).byteLength, + }); + expect(batches).toEqual([ + encodeBar1mIlpV2(row1), + encodeFx1mIlpV2(row2), + encodeBar1mIlpV2(row3), + ]); + }); + + it('snapshots row field values at submission when a caller reuses mutable row objects across overlapping writes', async () => { + const { sink, batches } = createMemorySink(); + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); + + const mutableBar = sampleBar({ + listing_id: 10, + ts: 1_700_000_000_000_000n, + known_at: 1_700_000_060_000_000n, + open: 100.0, + high: 101.0, + low: 99.5, + close: 100.5, + volume: 1_000, + session: 'PRE', + source: 'bar_one', + }); + const expectedBar1 = encodeBar1mIlpV2(mutableBar); + + const mutableFx = sampleFx({ + pair: 'USD.CAD', + source: 'fx_one', + open: 1.35, + high: 1.36, + low: 1.34, + close: 1.355, + ts: 1_700_000_000_000_000n, + }); + const expectedFx1 = encodeFx1mIlpV2(mutableFx); + + // Submit first bar and FX row without awaiting, then mutate both objects in place. + const pBar1 = writer.writeBar1m(mutableBar); + const pFx1 = writer.writeFx1m(mutableFx); + + mutableBar.listing_id = 11; + mutableBar.ts = 1_700_000_060_000_000n; + mutableBar.known_at = 1_700_000_120_000_000n; + mutableBar.open = 200.0; + mutableBar.high = 202.0; + mutableBar.low = 199.0; + mutableBar.close = 201.5; + mutableBar.volume = 2_000; + mutableBar.session = 'RTH'; + mutableBar.source = 'bar_two'; + const expectedBar2 = encodeBar1mIlpV2(mutableBar); + + mutableFx.pair = 'EUR.USD'; + mutableFx.source = 'fx_two'; + mutableFx.open = 1.08; + mutableFx.high = 1.09; + mutableFx.low = 1.07; + mutableFx.close = 1.085; + mutableFx.ts = 1_700_000_060_000_000n; + const expectedFx2 = encodeFx1mIlpV2(mutableFx); + + const pBar2 = writer.writeBar1m(mutableBar); + const pFx2 = writer.writeFx1m(mutableFx); + + await Promise.all([pBar1, pFx1, pBar2, pFx2]); + const stats = await writer.finish(); + + expect(stats).toEqual({ + rows: 4, + batches: 4, + bytes: + expectedBar1.byteLength + + expectedFx1.byteLength + + expectedBar2.byteLength + + expectedFx2.byteLength, + }); + expect(batches).toEqual([expectedBar1, expectedFx1, expectedBar2, expectedFx2]); + }); + + it('propagates sink rejection and fails closed for queued and subsequent calls with zero extra sink writes', async () => { + const boom = new Error('simulated sink EPIPE'); + let sinkCalls = 0; + const acceptedBatches: Uint8Array[] = []; + let rejectSecondWrite: ((err: Error) => void) | null = null; + + const sink: IlpV2BatchSink = { + write(batch: Uint8Array): Promise { + sinkCalls += 1; + if (sinkCalls === 1) { + acceptedBatches.push(batch.slice()); + return Promise.resolve(); + } + return new Promise((_resolve, reject) => { + rejectSecondWrite = reject; + }); + }, + }; + + const row1 = sampleBar({ listing_id: 1 }); + const row2 = sampleBar({ listing_id: 2 }); + const row3 = sampleBar({ listing_id: 3 }); + + const writer = createIlpV2BatchWriter({ sink, maxBatchRows: 1, maxBatchBytes: 100_000 }); + + // First batch succeeds. + await writer.writeBar1m(row1); + expect(sinkCalls).toBe(1); + expect(acceptedBatches).toEqual([encodeBar1mIlpV2(row1)]); + + // Trigger second batch (in-flight) and queue a third write + finish behind it. + const failingWrite = writer.writeBar1m(row2); + const queuedWrite = writer.writeBar1m(row3); + const queuedFinish = writer.finish(); + + await Promise.resolve(); + expect(sinkCalls).toBe(2); + expect(rejectSecondWrite).not.toBeNull(); + rejectSecondWrite!(boom); + + // Triggering call receives the exact original error. + await expect(failingWrite).rejects.toBe(boom); + // Queued operations fail closed without invoking sink.write again. + await expect(queuedWrite).rejects.toThrow(/sink write failure/i); + await expect(queuedFinish).rejects.toThrow(/sink write failure/i); + + // Later calls also fail closed without invoking sink.write. + await expect(writer.writeBar1m(row3)).rejects.toThrow(/sink write failure/i); + await expect(writer.writeFx1m(sampleFx())).rejects.toThrow(/sink write failure/i); + await expect(writer.flush()).rejects.toThrow(/sink write failure/i); + await expect(writer.finish()).rejects.toThrow(/sink write failure/i); + + expect(sinkCalls).toBe(2); + }); +}); diff --git a/libs/research/README.md b/libs/research/README.md index dd076551..93e29a1d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -124,6 +124,37 @@ Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across - **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`) - **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`) +## Routed `MarketDataStore` (DuckDB Daily + QuestDB `1m` Intraday) + +Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-routed` (`libs/research/src/market-data-store-routed.ts`). The QuestDB intraday reader is also exported from `@stock-bot/research/market-data-store-questdb`. Both modules are pure, dependency-free, and browser-safe. + +- **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick`, e.g. `createQuestDbIntradayBarsReader`). + - `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars. + - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`. + - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily` and `intraday` with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`, and pass that same `vaultCutoffTs` to `createQueryDataTool` (which is always Vault-fenced and accepts only `{ vaultCutoffTs }`): + +```ts +const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); +const vaultOperatorAuthorized = false; + +const daily = createDuckDbMarketDataStore({ + executor: duckDbExecutor, + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs, + vaultOperatorAuthorized, +}); +const intraday = createQuestDbIntradayBarsReader({ + executor: questDbExecutor, + vaultCutoffTs, + vaultOperatorAuthorized, +}); +const store = createRoutedMarketDataStore({ daily, intraday }); +const queryDataTool = createQueryDataTool({ + store, + vaultContext: { vaultCutoffTs }, +}); +``` + ## Signal Panel Builder Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). diff --git a/libs/research/package.json b/libs/research/package.json index e5cf853d..eb1522e3 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -14,6 +14,8 @@ "./feature-library": "./src/feature-library.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", + "./market-data-store-questdb": "./src/market-data-store-questdb.ts", + "./market-data-store-routed": "./src/market-data-store-routed.ts", "./mcp": "./src/mcp/index.ts", "./results": "./src/results.ts", "./signal-panel": "./src/signal-panel.ts", diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index dcc88deb..bb5e7062 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -5,6 +5,7 @@ export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; export * from './market-data-store-questdb'; +export * from './market-data-store-routed'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts new file mode 100644 index 00000000..a7b52608 --- /dev/null +++ b/libs/research/src/market-data-store-routed.ts @@ -0,0 +1,192 @@ +/** + * Pure, dependency-free `MarketDataStore` router that dispatches intraday + * `bars` queries (`timeframe: '1m'`) to an injected intraday reader (such as + * {@link createQuestDbIntradayBarsReader}) and routes every other `bars` + * timeframe and all other `MarketDataStore` methods to the injected daily + * store (such as {@link createDuckDbMarketDataStore}). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` + * access, and no database or filesystem I/O. + * + * Vault & point-in-time semantics: + * - This router adds no Vault logic of its own; each delegate continues to + * enforce its own Vault holdout fence and point-in-time predicates. + * - Callers MUST construct both `daily` and `intraday` with the exact same + * `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same + * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`, which is + * always Vault-fenced) so the holdout boundary is identical across + * timeframes. + * - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports + * split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests + * and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective + * delegate without modification. + */ + +import { type MarketDataStore, MarketDataStoreValidationError } from './market-data-store'; + +/** Configuration for {@link createRoutedMarketDataStore}. */ +export interface RoutedMarketDataStoreOptions { + /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ + readonly daily: MarketDataStore; + /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ + readonly intraday: Pick; +} + +const REQUIRED_DAILY_METHODS = [ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', +] as const satisfies readonly (keyof MarketDataStore)[]; + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null) { + return false; + } + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function isDelegateObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function isIntraday1mBarsQuery(q: unknown): boolean { + return ( + typeof q === 'object' && + q !== null && + !Array.isArray(q) && + (q as { readonly timeframe?: unknown }).timeframe === '1m' + ); +} + +/** + * Composes a daily `MarketDataStore` and an intraday `bars` reader into a + * single read-only `MarketDataStore`. + * + * Routing rules: + * - `bars(q)` with `q.timeframe === '1m'` delegates directly to + * `options.intraday.bars(q)` and returns its `AsyncIterable` + * unchanged (preserving receiver, query identity, lazy iteration, and error + * timing). + * - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed + * runtime inputs) delegates directly to `options.daily.bars(q)`. + * - All other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, + * `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly + * to `options.daily` and return its original promise. + * + * Vault fence note: + * Both `daily` and `intraday` MUST be constructed with the exact same + * `vaultCutoffTs` and `vaultOperatorAuthorized` settings. The QuestDB intraday + * reader serves raw (`adjustment: 'raw'`) `1m` bars. + * + * @example + * ```ts + * const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); + * const vaultOperatorAuthorized = false; + * + * const daily = createDuckDbMarketDataStore({ + * executor: duckDbExecutor, + * curatedRoot: '/mnt/data/stockbot/curated', + * vaultCutoffTs, + * vaultOperatorAuthorized, + * }); + * const intraday = createQuestDbIntradayBarsReader({ + * executor: questDbExecutor, + * vaultCutoffTs, + * vaultOperatorAuthorized, + * }); + * const store = createRoutedMarketDataStore({ daily, intraday }); + * // `createQueryDataTool` is always Vault-fenced and accepts only `vaultCutoffTs`. + * const queryDataTool = createQueryDataTool({ + * store, + * vaultContext: { vaultCutoffTs }, + * }); + * ``` + */ +export function createRoutedMarketDataStore( + options: RoutedMarketDataStoreOptions +): MarketDataStore { + if (!isPlainObject(options)) { + throw new MarketDataStoreValidationError( + 'Expected a plain RoutedMarketDataStoreOptions object.', + 'options' + ); + } + + const rawDaily: unknown = options.daily; + if (!isDelegateObject(rawDaily)) { + throw new MarketDataStoreValidationError( + 'Expected `daily` to be a MarketDataStore object.', + 'daily' + ); + } + + for (const method of REQUIRED_DAILY_METHODS) { + if (typeof rawDaily[method] !== 'function') { + throw new MarketDataStoreValidationError( + `Expected \`daily.${method}\` to be a function.`, + `daily.${method}` + ); + } + } + + const rawIntraday: unknown = options.intraday; + if (!isDelegateObject(rawIntraday)) { + throw new MarketDataStoreValidationError( + 'Expected `intraday` to be an object with a `bars` method.', + 'intraday' + ); + } + + if (typeof rawIntraday.bars !== 'function') { + throw new MarketDataStoreValidationError( + 'Expected `intraday.bars` to be a function.', + 'intraday.bars' + ); + } + + const daily = options.daily; + const intraday = options.intraday; + + return { + bars(q) { + if (isIntraday1mBarsQuery(q)) { + return intraday.bars(q); + } + return daily.bars(q); + }, + + crossSection(q) { + return daily.crossSection(q); + }, + + fundamentalsAsOf(q) { + return daily.fundamentalsAsOf(q); + }, + + events(q) { + return daily.events(q); + }, + + shortsAsOf(q) { + return daily.shortsAsOf(q); + }, + + macroAsOf(q) { + return daily.macroAsOf(q); + }, + + fx(q) { + return daily.fx(q); + }, + + universe(q) { + return daily.universe(q); + }, + }; +} diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts new file mode 100644 index 00000000..81b38fb6 --- /dev/null +++ b/libs/research/test/market-data-store-routed.test.ts @@ -0,0 +1,1098 @@ +import { describe, expect, it } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type DuckDbExecutor, + type DuckDbParam, + type MarketDataStore, + MarketDataStoreNotImplementedError, + MarketDataStoreValidationError, + type QuestDbQueryExecutor, + type RoutedMarketDataStoreOptions, + type Table, + type TableRow, + createDuckDbMarketDataStore, + createQuestDbIntradayBarsReader, + createRoutedMarketDataStore, +} from '@stock-bot/research'; +import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; +import { createRoutedMarketDataStore as subpathCreateRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; +import { + type QueryDataResultPayload, + createMcpServer, + createQueryDataTool, +} from '../src/mcp/index'; + +type BarsQuery = Parameters[0]; +type CrossSectionQuery = Parameters[0]; +type FundamentalsQuery = Parameters[0]; +type EventsQuery = Parameters[0]; +type ShortsQuery = Parameters[0]; +type MacroQuery = Parameters[0]; +type FxQuery = Parameters[0]; +type UniverseQuery = Parameters[0]; + +const LISTING_ID = 42; +const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z +const VAULT_CUTOFF_US = VAULT_CUTOFF_TS * 1000; +const CLAMPED_END_ISO = '2025-06-30T23:59:59.999Z'; +const CURATED_ROOT = '/mnt/data/stockbot/curated'; + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close - 0.5, + high: close + 0.5, + low: close - 1, + close, + volume: 1_000, + vwap: close, + knownAt, + }; +} + +async function collectBatches(iterable: AsyncIterable): Promise { + const batches: BarBatch[] = []; + for await (const batch of iterable) { + batches.push(batch); + } + return batches; +} + +class PrototypeDailyStore implements MarketDataStore { + readonly calls: { method: keyof MarketDataStore; arg: unknown }[] = []; + readonly returnedPromises = new Map>(); + readonly barsBatches: BarBatch[]; + + constructor(barsBatches: BarBatch[] = []) { + this.barsBatches = barsBatches; + } + + private assertReceiver(): void { + if (!(this instanceof PrototypeDailyStore)) { + throw new Error('Lost daily receiver (`this`).'); + } + } + + bars(q: BarsQuery): AsyncIterable { + this.assertReceiver(); + this.calls.push({ method: 'bars', arg: q }); + const batches = this.barsBatches; + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + } + + crossSection(q: CrossSectionQuery): Promise { + this.assertReceiver(); + this.calls.push({ method: 'crossSection', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id'], rows: [{ listing_id: 42 }] }); + this.returnedPromises.set('crossSection', p); + return p; + } + + fundamentalsAsOf(q: FundamentalsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'fundamentalsAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'revenue'], rows: [] }); + this.returnedPromises.set('fundamentalsAsOf', p); + return p; + } + + events(q: EventsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'events', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'kind'], rows: [] }); + this.returnedPromises.set('events', p); + return p; + } + + shortsAsOf(q: ShortsQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'shortsAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['listing_id', 'shares_short'], rows: [] }); + this.returnedPromises.set('shortsAsOf', p); + return p; + } + + macroAsOf(q: MacroQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'macroAsOf', arg: q }); + const p = Promise.resolve
({ columns: ['country', 'value'], rows: [] }); + this.returnedPromises.set('macroAsOf', p); + return p; + } + + fx(q: FxQuery): Promise
{ + this.assertReceiver(); + this.calls.push({ method: 'fx', arg: q }); + const p = Promise.resolve
({ columns: ['pair', 'close'], rows: [] }); + this.returnedPromises.set('fx', p); + return p; + } + + universe(q: UniverseQuery): Promise { + this.assertReceiver(); + this.calls.push({ method: 'universe', arg: q }); + const p = Promise.resolve([42, 101]); + this.returnedPromises.set('universe', p); + return p; + } +} + +class PrototypeIntradayReader implements Pick { + readonly calls: BarsQuery[] = []; + readonly barsBatches: BarBatch[]; + + constructor(barsBatches: BarBatch[] = []) { + this.barsBatches = barsBatches; + } + + bars(q: BarsQuery): AsyncIterable { + if (!(this instanceof PrototypeIntradayReader)) { + throw new Error('Lost intraday receiver (`this`).'); + } + this.calls.push(q); + const batches = this.barsBatches; + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + } +} + +interface QuestDbFixtureRow { + readonly listing_id: string; + readonly ts_us: number; + readonly open: number; + readonly high: number; + readonly low: number; + readonly close: number; + readonly volume: number; + readonly vwap: number | null; + readonly known_at_us: number; +} + +class PredicateAwareQuestDbExecutor implements QuestDbQueryExecutor { + readonly calls: { readonly sql: string; readonly params: readonly unknown[] }[] = []; + private readonly rows: readonly QuestDbFixtureRow[]; + private readonly leaky: boolean; + + constructor(rows: readonly QuestDbFixtureRow[], options?: { leaky?: boolean }) { + this.rows = rows; + this.leaky = options?.leaky === true; + } + + async query( + sql: string, + params: readonly unknown[] + ): Promise<{ readonly rows: readonly Record[] }> { + this.calls.push({ sql, params: [...params] }); + if (this.leaky) { + return { rows: this.rows as unknown as readonly Record[] }; + } + const fromUs = Date.parse(String(params[0])) * 1000; + const toUs = Date.parse(String(params[1])) * 1000; + const asOfUs = Date.parse(String(params[params.length - 1])) * 1000; + const listingIds = new Set(params.slice(2, params.length - 1).map(String)); + + const filtered = this.rows.filter( + row => + row.ts_us >= fromUs && + row.ts_us <= toUs && + row.known_at_us <= asOfUs && + listingIds.has(row.listing_id) + ); + return { rows: filtered as unknown as readonly Record[] }; + } +} + +class RecordingDuckDbExecutor implements DuckDbExecutor { + readonly runCalls: string[] = []; + readonly queryCalls: { readonly sql: string; readonly params: readonly DuckDbParam[] }[] = []; + private readonly rows: readonly TableRow[]; + + constructor(rows: readonly TableRow[] = []) { + this.rows = rows; + } + + async run(sql: string): Promise { + this.runCalls.push(sql); + } + + async query(sql: string, params: readonly DuckDbParam[]): Promise { + this.queryCalls.push({ sql, params: [...params] }); + return this.rows; + } +} + +describe('package exports', () => { + it('re-exports createRoutedMarketDataStore and createQuestDbIntradayBarsReader from root and subpaths', () => { + expect(createRoutedMarketDataStore).toBe(subpathCreateRoutedMarketDataStore); + expect(createQuestDbIntradayBarsReader).toBe(subpathCreateQuestDbIntradayBarsReader); + }); +}); + +describe('createRoutedMarketDataStore', () => { + describe('constructor validation', () => { + it('rejects null, primitives, arrays, and class instances for options', () => { + const invalidOptions: unknown[] = [ + null, + undefined, + 42, + 'options', + true, + [], + new Date(), + new (class OptionsClass { + daily = new PrototypeDailyStore(); + intraday = new PrototypeIntradayReader(); + })(), + ]; + + for (const bad of invalidOptions) { + let caught: unknown; + try { + createRoutedMarketDataStore(bad as RoutedMarketDataStoreOptions); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('options'); + } + }); + + it('accepts a null-prototype options object and prototype-backed delegates', () => { + const options = Object.create(null) as { + daily: MarketDataStore; + intraday: Pick; + }; + options.daily = new PrototypeDailyStore(); + options.intraday = new PrototypeIntradayReader(); + + const store = createRoutedMarketDataStore(options); + expect(typeof store.bars).toBe('function'); + }); + + it('rejects missing or malformed daily delegate and each missing daily method', () => { + const intraday = new PrototypeIntradayReader(); + + for (const badDaily of [null, undefined, 'daily', 123, []]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily: badDaily as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('daily'); + } + + const requiredMethods: (keyof MarketDataStore)[] = [ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', + ]; + + for (const missingMethod of requiredMethods) { + const base = new PrototypeDailyStore(); + const incomplete: Record = { + bars: base.bars.bind(base), + crossSection: base.crossSection.bind(base), + fundamentalsAsOf: base.fundamentalsAsOf.bind(base), + events: base.events.bind(base), + shortsAsOf: base.shortsAsOf.bind(base), + macroAsOf: base.macroAsOf.bind(base), + fx: base.fx.bind(base), + universe: base.universe.bind(base), + }; + delete incomplete[missingMethod]; + + let caughtMissing: unknown; + try { + createRoutedMarketDataStore({ + daily: incomplete as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caughtMissing = err; + } + expect(caughtMissing).toBeInstanceOf(MarketDataStoreValidationError); + expect((caughtMissing as MarketDataStoreValidationError).field).toBe( + `daily.${missingMethod}` + ); + + incomplete[missingMethod] = 'not-a-function'; + let caughtNonFn: unknown; + try { + createRoutedMarketDataStore({ + daily: incomplete as unknown as MarketDataStore, + intraday, + }); + } catch (err) { + caughtNonFn = err; + } + expect(caughtNonFn).toBeInstanceOf(MarketDataStoreValidationError); + expect((caughtNonFn as MarketDataStoreValidationError).field).toBe( + `daily.${missingMethod}` + ); + } + }); + + it('rejects missing or non-callable intraday delegate and intraday.bars', () => { + const daily = new PrototypeDailyStore(); + + for (const badIntraday of [null, undefined, 'intraday', 99, []]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily, + intraday: badIntraday as unknown as Pick, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('intraday'); + } + + for (const badBars of [undefined, null, 'bars', 42, {}]) { + let caught: unknown; + try { + createRoutedMarketDataStore({ + daily, + intraday: { bars: badBars } as unknown as Pick, + }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect((caught as MarketDataStoreValidationError).field).toBe('intraday.bars'); + } + }); + }); + + describe('routing and delegation', () => { + it('routes 1m bars exclusively to intraday and 1d bars exclusively to daily with exact query identity', async () => { + const intradayBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 101.25)], + }; + const dailyBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 20, 0, 0), 102.5)], + }; + const daily = new PrototypeDailyStore([dailyBatch]); + const intraday = new PrototypeIntradayReader([intradayBatch]); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const q1m: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }; + const q1d: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-01', + to: '2025-06-30', + adjustment: 'raw', + }; + + const intradayOut = await collectBatches(store.bars(q1m)); + expect(intraday.calls).toHaveLength(1); + expect(intraday.calls[0]).toBe(q1m); + expect(daily.calls).toHaveLength(0); + expect(intradayOut).toHaveLength(1); + expect(intradayOut[0]).toBe(intradayBatch); + + const dailyOut = await collectBatches(store.bars(q1d)); + expect(daily.calls).toHaveLength(1); + expect(daily.calls[0]?.method).toBe('bars'); + expect(daily.calls[0]?.arg).toBe(q1d); + expect(intraday.calls).toHaveLength(1); + expect(dailyOut).toHaveLength(1); + expect(dailyOut[0]).toBe(dailyBatch); + }); + + it('forwards invalid timeframe values and non-object inputs to daily unchanged', async () => { + const daily = new PrototypeDailyStore(); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const arrayWithTimeframe = Object.assign(['1m'], { timeframe: '1m' }); + const malformedInputs: unknown[] = [ + null, + undefined, + '1m', + 42, + ['1m'], + arrayWithTimeframe, + { listingIds: [42], timeframe: '2m', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, + { listingIds: [42], timeframe: '', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, + ]; + + for (const badInput of malformedInputs) { + await collectBatches(store.bars(badInput as BarsQuery)); + } + + expect(intraday.calls).toHaveLength(0); + expect(daily.calls).toHaveLength(malformedInputs.length); + for (let i = 0; i < malformedInputs.length; i += 1) { + expect(daily.calls[i]?.method).toBe('bars'); + expect(daily.calls[i]?.arg).toBe(malformedInputs[i]); + } + }); + + it('preserves DuckDB MarketDataStoreNotImplementedError for 5m and 1h with zero executor or intraday calls', async () => { + const duckExecutor = new RecordingDuckDbExecutor(); + const daily = createDuckDbMarketDataStore({ + executor: duckExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + for (const timeframe of ['5m', '1h'] as const) { + let caught: unknown; + try { + for await (const _batch of store.bars({ + listingIds: [LISTING_ID], + timeframe, + from: '2025-06-01', + to: '2025-06-30', + adjustment: 'raw', + })) { + // unreachable + } + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); + } + + expect(duckExecutor.runCalls).toHaveLength(0); + expect(duckExecutor.queryCalls).toHaveLength(0); + expect(intraday.calls).toHaveLength(0); + }); + + it('delegates all seven non-bars methods (including fx 1m) to daily with argument, receiver, and promise identity', async () => { + const daily = new PrototypeDailyStore(); + const intraday = new PrototypeIntradayReader(); + const store = createRoutedMarketDataStore({ daily, intraday }); + + const crossSectionArg: CrossSectionQuery = { + features: ['ret_1d@v1'], + date: '2025-06-30', + universe: 'US_EQ', + }; + const fundamentalsArg: FundamentalsQuery = { + listingIds: [LISTING_ID], + fields: ['revenue'], + asOf: '2025-06-30', + }; + const eventsArg: EventsQuery = { + kinds: ['filing'], + listingIds: [LISTING_ID], + from: '2025-06-01', + to: '2025-06-30', + }; + const shortsArg: ShortsQuery = { + listingIds: [LISTING_ID], + from: '2025-06-01', + to: '2025-06-30', + }; + const macroArg: MacroQuery = { + countries: ['US'], + indicators: ['CPI'], + from: '2025-06-01', + to: '2025-06-30', + }; + const fxArg: FxQuery = { + pair: 'USD.CAD', + timeframe: '1m', + from: '2025-06-01', + to: '2025-06-30', + }; + const universeArg: UniverseQuery = { + ref: 'US_EQ', + date: '2025-06-30', + }; + + const pCrossSection = store.crossSection(crossSectionArg); + const pFundamentals = store.fundamentalsAsOf(fundamentalsArg); + const pEvents = store.events(eventsArg); + const pShorts = store.shortsAsOf(shortsArg); + const pMacro = store.macroAsOf(macroArg); + const pFx = store.fx(fxArg); + const pUniverse = store.universe(universeArg); + + expect(pCrossSection).toBe(daily.returnedPromises.get('crossSection') as Promise
); + expect(pFundamentals).toBe(daily.returnedPromises.get('fundamentalsAsOf') as Promise
); + expect(pEvents).toBe(daily.returnedPromises.get('events') as Promise
); + expect(pShorts).toBe(daily.returnedPromises.get('shortsAsOf') as Promise
); + expect(pMacro).toBe(daily.returnedPromises.get('macroAsOf') as Promise
); + expect(pFx).toBe(daily.returnedPromises.get('fx') as Promise
); + expect(pUniverse).toBe(daily.returnedPromises.get('universe') as Promise); + + await Promise.all([ + pCrossSection, + pFundamentals, + pEvents, + pShorts, + pMacro, + pFx, + pUniverse, + ]); + + expect(intraday.calls).toHaveLength(0); + expect(daily.calls).toHaveLength(7); + expect(daily.calls[0]).toEqual({ method: 'crossSection', arg: crossSectionArg }); + expect(daily.calls[0]?.arg).toBe(crossSectionArg); + expect(daily.calls[1]).toEqual({ method: 'fundamentalsAsOf', arg: fundamentalsArg }); + expect(daily.calls[1]?.arg).toBe(fundamentalsArg); + expect(daily.calls[2]).toEqual({ method: 'events', arg: eventsArg }); + expect(daily.calls[2]?.arg).toBe(eventsArg); + expect(daily.calls[3]).toEqual({ method: 'shortsAsOf', arg: shortsArg }); + expect(daily.calls[3]?.arg).toBe(shortsArg); + expect(daily.calls[4]).toEqual({ method: 'macroAsOf', arg: macroArg }); + expect(daily.calls[4]?.arg).toBe(macroArg); + expect(daily.calls[5]).toEqual({ method: 'fx', arg: fxArg }); + expect(daily.calls[5]?.arg).toBe(fxArg); + expect(daily.calls[6]).toEqual({ method: 'universe', arg: universeArg }); + expect(daily.calls[6]?.arg).toBe(universeArg); + }); + }); + + describe('error propagation and lazy iteration', () => { + it('propagates exact error instances for sync throws, promise rejections, and mid-iteration failures', async () => { + const syncIntradayErr = new Error('sync intraday boom'); + const syncDailyErr = new Error('sync daily boom'); + const rejectedUniverseErr = new Error('async universe boom'); + const iterErr = new Error('mid-iteration boom'); + + const baseDaily = new PrototypeDailyStore(); + const firstBatch: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], + }; + + const dailySyncStore = createRoutedMarketDataStore({ + daily: { + bars: () => { + throw syncDailyErr; + }, + crossSection: baseDaily.crossSection.bind(baseDaily), + fundamentalsAsOf: baseDaily.fundamentalsAsOf.bind(baseDaily), + events: baseDaily.events.bind(baseDaily), + shortsAsOf: baseDaily.shortsAsOf.bind(baseDaily), + macroAsOf: baseDaily.macroAsOf.bind(baseDaily), + fx: baseDaily.fx.bind(baseDaily), + universe: () => Promise.reject(rejectedUniverseErr), + }, + intraday: { + bars: () => { + throw syncIntradayErr; + }, + }, + }); + + let caughtSyncIntraday: unknown; + try { + dailySyncStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }); + } catch (err) { + caughtSyncIntraday = err; + } + expect(caughtSyncIntraday).toBe(syncIntradayErr); + + let caughtSyncDaily: unknown; + try { + dailySyncStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + }); + } catch (err) { + caughtSyncDaily = err; + } + expect(caughtSyncDaily).toBe(syncDailyErr); + + let caughtRejected: unknown; + try { + await dailySyncStore.universe({ ref: 'US_EQ', date: '2025-06-30' }); + } catch (err) { + caughtRejected = err; + } + expect(caughtRejected).toBe(rejectedUniverseErr); + + const iterFailStore = createRoutedMarketDataStore({ + daily: baseDaily, + intraday: { + bars() { + return { + async *[Symbol.asyncIterator]() { + yield firstBatch; + throw iterErr; + }, + }; + }, + }, + }); + + const received: BarBatch[] = []; + let caughtIter: unknown; + try { + for await (const batch of iterFailStore.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + })) { + received.push(batch); + } + } catch (err) { + caughtIter = err; + } + expect(received).toHaveLength(1); + expect(received[0]).toBe(firstBatch); + expect(caughtIter).toBe(iterErr); + }); + + it('preserves lazy iteration and closes the delegate iterator on early exit', async () => { + const batch1: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], + }; + const batch2: BarBatch = { + rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 31, 0), 101)], + }; + let nextCalls = 0; + let returnCalls = 0; + + const store = createRoutedMarketDataStore({ + daily: new PrototypeDailyStore(), + intraday: { + bars() { + return { + [Symbol.asyncIterator]() { + const batches = [batch1, batch2]; + return { + async next() { + const idx = nextCalls; + nextCalls += 1; + const value = batches[idx]; + if (value === undefined) { + return { done: true as const, value: undefined }; + } + return { done: false as const, value }; + }, + async return() { + returnCalls += 1; + return { done: true as const, value: undefined }; + }, + }; + }, + }; + }, + }, + }); + + const consumed: BarBatch[] = []; + for await (const batch of store.bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-06-30', + adjustment: 'raw', + })) { + consumed.push(batch); + break; + } + + expect(consumed).toHaveLength(1); + expect(consumed[0]).toBe(batch1); + expect(nextCalls).toBe(1); + expect(returnCalls).toBe(1); + }); + }); + + describe('QuestDB intraday reader integration and Vault fence', () => { + const preCutoffTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; + const preCutoffTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; + const fixtureRows: readonly QuestDbFixtureRow[] = [ + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs1Us, + open: 100.0, + high: 101.0, + low: 99.5, + close: 100.5, + volume: 500, + vwap: 100.25, + known_at_us: preCutoffTs1Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs2Us, + open: 100.5, + high: 101.5, + low: 100.25, + close: 101.25, + volume: 750, + vwap: 101.0, + known_at_us: preCutoffTs2Us + 60_000_000, + }, + // Row with ts exactly at Vault cutoff (must be excluded by fence) + { + listing_id: String(LISTING_ID), + ts_us: VAULT_CUTOFF_US, + open: 102.0, + high: 103.0, + low: 101.5, + close: 102.5, + volume: 900, + vwap: 102.25, + known_at_us: preCutoffTs2Us + 60_000_000, + }, + // Row with known_at exactly at Vault cutoff (must be excluded by fence) + { + listing_id: String(LISTING_ID), + ts_us: preCutoffTs2Us + 60_000_000, + open: 101.25, + high: 102.0, + low: 101.0, + close: 101.75, + volume: 600, + vwap: 101.5, + known_at_us: VAULT_CUTOFF_US, + }, + ]; + + const straddlingQuery: BarsQuery = { + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30T13:30:00Z', + to: '2025-07-05T20:00:00Z', + adjustment: 'raw', + asOf: '2025-07-10T00:00:00Z', + }; + + it('streams batches unchanged from createQuestDbIntradayBarsReader and clamps to/asOf strictly below vaultCutoffTs', async () => { + const directExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); + const directReader = createQuestDbIntradayBarsReader({ + executor: directExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + + const routedExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); + const underlyingIntraday = createQuestDbIntradayBarsReader({ + executor: routedExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + + const yieldedByIntraday: BarBatch[] = []; + const recordingIntraday: Pick = { + bars(q) { + const inner = underlyingIntraday.bars(q); + return { + async *[Symbol.asyncIterator]() { + for await (const batch of inner) { + yieldedByIntraday.push(batch); + yield batch; + } + }, + }; + }, + }; + + const daily = new PrototypeDailyStore(); + const store = createRoutedMarketDataStore({ daily, intraday: recordingIntraday }); + + const directBatches = await collectBatches(directReader.bars(straddlingQuery)); + const routedBatches = await collectBatches(store.bars(straddlingQuery)); + + expect(daily.calls).toHaveLength(0); + expect(routedExecutor.calls).toHaveLength(1); + expect(routedExecutor.calls[0]?.params[1]).toBe(CLAMPED_END_ISO); + expect(routedExecutor.calls[0]?.params[3]).toBe(CLAMPED_END_ISO); + + expect(routedBatches).toEqual(directBatches); + expect(routedBatches).toHaveLength(2); + expect(routedBatches[0]).toBe(yieldedByIntraday[0]); + expect(routedBatches[1]).toBe(yieldedByIntraday[1]); + + for (const batch of routedBatches) { + for (const row of batch.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + } + }); + + it('rejects a leaky QuestDB executor returning a row with ts or known_at at vaultCutoffTs before yielding any batch', async () => { + const tsCutoffRow = fixtureRows[2] as QuestDbFixtureRow; + const knownAtCutoffRow = fixtureRows[3] as QuestDbFixtureRow; + const preCutoffRow = fixtureRows[0] as QuestDbFixtureRow; + + for (const leakyRows of [ + [preCutoffRow, tsCutoffRow], + [preCutoffRow, knownAtCutoffRow], + ]) { + const leakyExecutor = new PredicateAwareQuestDbExecutor(leakyRows, { leaky: true }); + const intraday = createQuestDbIntradayBarsReader({ + executor: leakyExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + batchSize: 1, + }); + const store = createRoutedMarketDataStore({ + daily: new PrototypeDailyStore(), + intraday, + }); + + const yielded: BarBatch[] = []; + let caught: unknown; + try { + for await (const batch of store.bars(straddlingQuery)) { + yielded.push(batch); + } + } catch (err) { + caught = err; + } + + expect(caught).toBeInstanceOf(MarketDataStoreValidationError); + expect(yielded).toHaveLength(0); + } + }); + }); + + describe('MCP query_data end-to-end over routed store', () => { + it('routes 1m calls to fake QuestDB and 1d calls to fake DuckDB, enforcing the Vault cutoff deterministically', async () => { + const intradayTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; + const intradayTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; + const questDbRows: readonly QuestDbFixtureRow[] = [ + { + listing_id: String(LISTING_ID), + ts_us: intradayTs1Us, + open: 100.0, + high: 100.75, + low: 99.5, + close: 100.5, + volume: 1_200, + vwap: 100.2, + known_at_us: intradayTs1Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: intradayTs2Us, + open: 100.5, + high: 101.25, + low: 100.25, + close: 101.0, + volume: 1_500, + vwap: 100.8, + known_at_us: intradayTs2Us + 60_000_000, + }, + // Out-of-fence rows at exact cutoff (filtered by predicate-aware executor) + { + listing_id: String(LISTING_ID), + ts_us: VAULT_CUTOFF_US, + open: 105.0, + high: 106.0, + low: 104.0, + close: 105.5, + volume: 2_000, + vwap: 105.2, + known_at_us: intradayTs2Us + 60_000_000, + }, + { + listing_id: String(LISTING_ID), + ts_us: intradayTs2Us + 60_000_000, + open: 101.0, + high: 101.5, + low: 100.75, + close: 101.25, + volume: 1_100, + vwap: 101.1, + known_at_us: VAULT_CUTOFF_US, + }, + ]; + + const dailyBarTs = Date.UTC(2025, 5, 30, 20, 0, 0, 0); + const duckDbRows: readonly TableRow[] = [ + { + listing_id: LISTING_ID, + ts: dailyBarTs, + open: 99.0, + high: 102.0, + low: 98.5, + close: 101.5, + volume: 250_000, + vwap: 100.75, + known_at: dailyBarTs, + }, + ]; + + const questExecutor = new PredicateAwareQuestDbExecutor(questDbRows); + const duckExecutor = new RecordingDuckDbExecutor(duckDbRows); + + const daily = createDuckDbMarketDataStore({ + executor: duckExecutor, + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }); + const intraday = createQuestDbIntradayBarsReader({ + executor: questExecutor, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }); + const routedStore = createRoutedMarketDataStore({ daily, intraday }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: routedStore, + vaultContext: { + vaultCutoffTs: VAULT_CUTOFF_TS, + }, + }), + ], + }); + + const direct1mBatches = await collectBatches( + createQuestDbIntradayBarsReader({ + executor: new PredicateAwareQuestDbExecutor(questDbRows), + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }).bars({ + listingIds: [LISTING_ID], + timeframe: '1m', + from: '2025-06-30', + to: '2025-07-05', + adjustment: 'raw', + }) + ); + const expected1mRows = direct1mBatches.flatMap(b => b.rows); + + const req1m = JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-1m', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-06-30', + to: '2025-07-05', + timeframe: '1m', + adjustment: 'raw', + }, + }, + }); + + const raw1mFirst = await server.handleMessage(req1m); + const raw1mSecond = await server.handleMessage(req1m); + expect(raw1mFirst).not.toBeNull(); + expect(raw1mSecond).toBe(raw1mFirst); + + expect(questExecutor.calls).toHaveLength(2); + expect(duckExecutor.queryCalls).toHaveLength(0); + expect(duckExecutor.runCalls).toHaveLength(0); + + const resp1m = JSON.parse(raw1mFirst as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(resp1m.result.isError).toBeUndefined(); + const payload1m = JSON.parse(resp1m.result.content[0]?.text ?? '') as QueryDataResultPayload; + expect(payload1m.rows).toEqual(expected1mRows); + expect(payload1m.rows).toHaveLength(2); + for (const row of payload1m.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + + const direct1dBatches = await collectBatches( + createDuckDbMarketDataStore({ + executor: new RecordingDuckDbExecutor(duckDbRows), + curatedRoot: CURATED_ROOT, + vaultCutoffTs: VAULT_CUTOFF_TS, + vaultOperatorAuthorized: false, + }).bars({ + listingIds: [LISTING_ID], + timeframe: '1d', + from: '2025-06-25', + to: '2025-07-05', + adjustment: 'raw', + }) + ); + const expected1dRows = direct1dBatches.flatMap(b => b.rows); + + const req1d = JSON.stringify({ + jsonrpc: '2.0', + id: 'mcp-1d', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [LISTING_ID], + from: '2025-06-25', + to: '2025-07-05', + timeframe: '1d', + adjustment: 'raw', + }, + }, + }); + + const raw1dFirst = await server.handleMessage(req1d); + const raw1dSecond = await server.handleMessage(req1d); + expect(raw1dFirst).not.toBeNull(); + expect(raw1dSecond).toBe(raw1dFirst); + + expect(questExecutor.calls).toHaveLength(2); + expect(duckExecutor.queryCalls).toHaveLength(2); + + const resp1d = JSON.parse(raw1dFirst as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(resp1d.result.isError).toBeUndefined(); + const payload1d = JSON.parse(resp1d.result.content[0]?.text ?? '') as QueryDataResultPayload; + expect(payload1d.rows).toEqual(expected1dRows); + expect(payload1d.rows).toHaveLength(1); + for (const row of payload1d.rows) { + expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); + expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); + } + }); + }); +}); diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts index df95c7b7..8bfb3325 100644 --- a/test/postgres/fresh-database-schema.test.ts +++ b/test/postgres/fresh-database-schema.test.ts @@ -78,6 +78,7 @@ const RESEARCH_FILES = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]; const cleanup: (() => Promise | void)[] = []; @@ -138,13 +139,13 @@ async function createIsolatedFixture() { } describe.skipIf(!url)('fresh PostgreSQL database schema', () => { - test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { + test('Case A: init SQL 01-37 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { const f = await createIsolatedFixture(); const sqlFiles = readdirSync(initDir) .filter(file => file.endsWith('.sql')) .sort(); - expect(sqlFiles.length).toBeGreaterThanOrEqual(36); + expect(sqlFiles.length).toBeGreaterThanOrEqual(37); for (const file of sqlFiles) { const sql = readFileSync(join(initDir, file), 'utf8'); @@ -159,7 +160,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { ...LEGACY_MASTER_TABLES, // Security master tables (34) ...SECURITY_MASTER_TABLES, - // Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36) + // Research tables (06-33, 36-37, including representatives from 12, 16, 20, 22, 28, 30, 36, 37) 'backtests', 'backtest_results', 'runs', @@ -171,6 +172,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { 'paper_deployments', 'trial_ledger', 'vault_evaluations', + 'findings', + 'provider_caveats', ]) { expect(createdTables.has(expectedTable)).toBe(true); } @@ -193,6 +196,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(false); expect(createdTables.has('vault_evaluations')).toBe(false); + expect(createdTables.has('findings')).toBe(false); + expect(createdTables.has('provider_caveats')).toBe(false); expect(await f.hasColumn('exchanges', 'visible')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'master' }); @@ -200,7 +205,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { expect(await f.recorded()).toEqual(MASTER_FILES); }); - test('Case C: all track with 06-08 pre-applied records master + research (including 36) and never records 06-08', async () => { + test('Case C: all track with 06-08 pre-applied records master + research (including 36-37) and never records 06-08', async () => { const f = await createIsolatedFixture(); for (const file of BOOTSTRAP_FILES) { @@ -223,6 +228,8 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(true); expect(createdTables.has('vault_evaluations')).toBe(true); + expect(createdTables.has('findings')).toBe(true); + expect(createdTables.has('provider_caveats')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'all' }); expect(second).toEqual([]); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 6b43c3d3..0e87eebb 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -37,6 +37,7 @@ const migrations = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', + '37-research-findings.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { @@ -384,17 +385,22 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { ]; // 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql, - // and MUST apply 36-trial-ledger.sql; master track applies 34-35 (not 36) and is idempotent on re-run. + // and MUST apply 36-trial-ledger.sql and 37-research-findings.sql; master track applies 34-35 (not 36-37) and is idempotent on re-run. const f1 = await fixture(); const runner1 = f1.startup(); const researchApplied = await runner1.runTrack('research'); expect(researchApplied).not.toContain('34-security-master.sql'); expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql'); expect(researchApplied).toContain('36-trial-ledger.sql'); + expect(researchApplied).toContain('37-research-findings.sql'); + expect(researchApplied.indexOf('37-research-findings.sql')).toBe( + researchApplied.indexOf('36-trial-ledger.sql') + 1 + ); const recordedAfterResearch = await f1.recorded(); expect(recordedAfterResearch).not.toContain('34-security-master.sql'); expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterResearch).toContain('36-trial-ledger.sql'); + expect(recordedAfterResearch).toContain('37-research-findings.sql'); const tablesAfterResearch = new Set(await f1.relations()); for (const table of securityMasterTables) { @@ -402,11 +408,14 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterResearch.has('trial_ledger')).toBe(true); expect(tablesAfterResearch.has('vault_evaluations')).toBe(true); + expect(tablesAfterResearch.has('findings')).toBe(true); + expect(tablesAfterResearch.has('provider_caveats')).toBe(true); const masterApplied = await runner1.runTrack('master'); expect(masterApplied).toContain('34-security-master.sql'); expect(masterApplied).toContain('35-security-master-exchange-seed.sql'); expect(masterApplied).not.toContain('36-trial-ledger.sql'); + expect(masterApplied).not.toContain('37-research-findings.sql'); expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe( masterApplied.indexOf('34-security-master.sql') + 1 ); @@ -421,7 +430,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(await runner1.runTrack('master')).toEqual([]); - // 2. all track applies 34, 35, and 36 alongside 01-05 and 09-33 and is idempotent. + // 2. all track applies 34, 35, 36, and 37 alongside 01-05 and 09-33 and is idempotent. const f2 = await fixture(); const runner2 = f2.startup(); const allApplied = await runner2.runTrack('all'); @@ -432,10 +441,12 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(allApplied).toContain('34-security-master.sql'); expect(allApplied).toContain('35-security-master-exchange-seed.sql'); expect(allApplied).toContain('36-trial-ledger.sql'); + expect(allApplied).toContain('37-research-findings.sql'); const recordedAfterAll = await f2.recorded(); expect(recordedAfterAll).toContain('34-security-master.sql'); expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterAll).toContain('36-trial-ledger.sql'); + expect(recordedAfterAll).toContain('37-research-findings.sql'); const tablesAfterAll = new Set(await f2.relations()); for (const table of securityMasterTables) { @@ -443,6 +454,8 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterAll.has('trial_ledger')).toBe(true); expect(tablesAfterAll.has('vault_evaluations')).toBe(true); + expect(tablesAfterAll.has('findings')).toBe(true); + expect(tablesAfterAll.has('provider_caveats')).toBe(true); expect(await runner2.runTrack('all')).toEqual([]); }); diff --git a/test/postgres/research-findings-contract.test.ts b/test/postgres/research-findings-contract.test.ts new file mode 100644 index 00000000..36c9d2e3 --- /dev/null +++ b/test/postgres/research-findings-contract.test.ts @@ -0,0 +1,180 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { setLoggerConfig } from '@stock-bot/logger'; +import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres'; +import { + FILE_FINDING_INITIAL_STATUS, + FILE_FINDING_KINDS, + FILE_FINDING_MAX_EVIDENCE_REFS, + FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + FILE_FINDING_MAX_REF_LENGTH, + FILE_FINDING_MAX_SUMMARY_LENGTH, + FILE_FINDING_MAX_TITLE_LENGTH, + FILE_FINDING_MAX_TRIAL_REFS, +} from '@stock-bot/research/mcp'; + +// Static contract checks for 37-research-findings.sql. No database needed, so these run in the +// sandbox as well as in Studio's unsandboxed run. They guard against drift between the SQL CHECKs, +// the MCP tool limits they mirror, and the design/DATA-CONTRACTS.md copy of the schema. + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); + +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const sqlPath = `${initDir}37-research-findings.sql`; +const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url)); + +const readSql = () => readFileSync(sqlPath, 'utf8'); +const readDoc = () => readFileSync(docPath, 'utf8'); + +function stripComments(sql: string): string { + return sql + .split('\n') + .map(line => line.replace(/--.*$/, '').trimEnd()) + .join('\n'); +} + +function normalize(sql: string): string { + return stripComments(sql).replace(/\s+/g, ' ').trim(); +} + +function tableBlock(sql: string, table: string): string { + const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec( + stripComments(sql) + ); + if (!match?.[1]) { + throw new Error(`CREATE TABLE ${table} not found`); + } + return match[1].replace(/\s+/g, ' ').trim(); +} + +function docSqlBlock(): string { + const doc = readDoc(); + const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS findings ('); + expect(tableStart).toBeGreaterThan(-1); + const fenceStart = doc.lastIndexOf('```sql', tableStart); + const fenceEnd = doc.indexOf('```', tableStart); + return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim(); +} + +function trimCodePointsFromSql(): number[] { + const match = /U&'([^']*)'/.exec(stripComments(readSql())); + if (!match?.[1]) { + throw new Error('research_trim_ecmascript U& character set not found'); + } + return match[1] + .split('\\') + .filter(part => part.length > 0) + .map(part => { + expect(part).toMatch(/^[0-9A-F]{4}$/i); + return Number.parseInt(part, 16); + }); +} + +async function filesForTrack(track: MigrationTrack): Promise { + const postgres = { + transaction: async (callback: (client: { query: (sql: string) => unknown }) => Promise) => + callback({ query: async () => ({ rows: [] }) }), + }; + return runPostgresMigrations(postgres as never, { track }); +} + +describe('37-research-findings.sql static contract', () => { + test('creates exactly findings and provider_caveats with IF NOT EXISTS and no schema qualifiers', () => { + const sql = stripComments(readSql()); + const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)]; + expect(created.map(m => m[2])).toEqual(['findings', 'provider_caveats']); + expect(created.every(m => m[1] !== undefined)).toBe(true); + expect(sql).not.toMatch(/CREATE\s+DATABASE/i); + expect(sql).not.toMatch(/^\s*\\c\b/m); + expect(sql).not.toMatch(/\bSET\s+search_path\b/i); + expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|ON|FROM)\s+"?\w+"?\."?\w+/i); + }); + + test('findings CHECKs mirror the file_finding tool limits exported from file-finding.ts', () => { + const findings = tableBlock(readSql(), 'findings'); + const kinds = FILE_FINDING_KINDS.map(kind => `'${kind}'`).join(', '); + + expect(findings).toContain(`CHECK (kind IN (${kinds}))`); + expect(findings).toContain(`DEFAULT '${FILE_FINDING_INITIAL_STATUS}'`); + expect(findings).toContain( + `CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND ${FILE_FINDING_MAX_TITLE_LENGTH})` + ); + expect(findings).toContain( + `CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND ${FILE_FINDING_MAX_SUMMARY_LENGTH})` + ); + expect(findings).toContain(`CHECK (cardinality(trial_refs) <= ${FILE_FINDING_MAX_TRIAL_REFS})`); + expect(findings).toContain( + `CHECK (cardinality(evidence_refs) <= ${FILE_FINDING_MAX_EVIDENCE_REFS})` + ); + expect(findings).toContain( + `CHECK (research_finding_refs_valid(trial_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` + ); + expect(findings).toContain( + `CHECK (research_finding_refs_valid(evidence_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` + ); + expect(findings).toContain( + `char_length(idempotency_key) BETWEEN 1 AND ${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH}` + ); + expect(findings).toContain('created_at TIMESTAMPTZ NOT NULL,'); + expect(findings).toMatch(/idempotency_key TEXT CHECK \(idempotency_key IS NULL OR/); + }); + + test('research_trim_ecmascript strips exactly the BMP code points String.prototype.trim() strips', () => { + const sqlSet = trimCodePointsFromSql(); + const jsSet: number[] = []; + for (let cp = 0; cp <= 0xffff; cp++) { + if (cp >= 0xd800 && cp <= 0xdfff) { + continue; + } + if (String.fromCharCode(cp).trim() === '') { + jsSet.push(cp); + } + } + + expect(new Set(sqlSet).size).toBe(sqlSet.length); + expect([...sqlSet].sort((a, b) => a - b)).toEqual(jsSet); + expect(sqlSet).toHaveLength(25); + }); + + test('both tables are append-only via reject_research_evidence_mutation row and TRUNCATE triggers', () => { + const sql = normalize(readSql()); + for (const table of ['findings', 'provider_caveats']) { + expect(sql).toContain( + `DROP TRIGGER IF EXISTS ${table}_retained ON ${table}; CREATE TRIGGER ${table}_retained BEFORE UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();` + ); + expect(sql).toContain( + `DROP TRIGGER IF EXISTS ${table}_no_truncate ON ${table}; CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();` + ); + } + // The migration must reuse the shared function, never redefine it. + expect(sql).not.toMatch(/FUNCTION reject_research_evidence_mutation\s*\(\s*\)\s*RETURNS/i); + }); + + test('design/DATA-CONTRACTS.md documents both tables and indexes exactly as the migration creates them', () => { + const doc = docSqlBlock(); + const sql = readSql(); + expect(tableBlock(doc, 'findings')).toBe(tableBlock(sql, 'findings')); + expect(tableBlock(doc, 'provider_caveats')).toBe(tableBlock(sql, 'provider_caveats')); + + const indexes = (text: string) => + [...normalize(text).matchAll(/CREATE (?:UNIQUE )?INDEX IF NOT EXISTS [^;]+;/g)].map( + m => m[0] + ); + expect(indexes(doc)).toEqual(indexes(sql)); + expect(indexes(sql)).toHaveLength(3); + }); + + test('37-research-findings.sql runs on research and all tracks right after 36 and never on master', async () => { + const research = await filesForTrack('research'); + const all = await filesForTrack('all'); + const master = await filesForTrack('master'); + + expect(research.indexOf('37-research-findings.sql')).toBe( + research.indexOf('36-trial-ledger.sql') + 1 + ); + expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(-1); + expect(all).toContain('37-research-findings.sql'); + expect(master).not.toContain('37-research-findings.sql'); + }); +}); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts new file mode 100644 index 00000000..60324763 --- /dev/null +++ b/test/postgres/research-findings-schema.test.ts @@ -0,0 +1,700 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('research-findings-schema-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const researchFindingsSqlPath = `${initDir}37-research-findings.sql`; + +const FIXED_TS = '2026-01-15T12:34:56.789Z'; +const EXPECTED_IMMUTABLE_MSG = /Retained research evidence cannot be rewritten or deleted/; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const poolUrl = new URL(url); + const existingOptions = poolUrl.searchParams.get('options')?.trim(); + const fixtureOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; + poolUrl.searchParams.set( + 'options', + existingOptions ? `${existingOptions} ${fixtureOptions}` : fixtureOptions + ); + const pool = new Pool({ connectionString: poolUrl.toString() }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const activeSchema = (await pool.query<{ schema: string }>('SELECT current_schema() AS schema')) + .rows[0]?.schema; + if (activeSchema !== schema) { + throw new Error(`Expected active fixture schema ${schema}, got ${activeSchema ?? 'null'}`); + } + + // Bootstrap pre-additive tables needed by the research migration track. + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { pool, schema, postgres }; +} + +async function expectPgErrorCode( + operation: Promise, + expectedCode: string, + messagePattern?: RegExp +): Promise { + try { + await operation; + } catch (error) { + const pgError = error as { code?: string; message?: string } | null; + expect(pgError?.code).toBe(expectedCode); + if (messagePattern) { + expect(pgError?.message ?? '').toMatch(messagePattern); + } + return; + } + throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); +} + +interface FindingInsertOverrides { + id?: string; + kind?: string; + title?: string; + summary?: string; + status?: string; + createdAt?: string; + trialRefs?: (string | null)[]; + evidenceRefs?: (string | null)[]; + idempotencyKey?: string | null; +} + +function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) { + const id = overrides.id ?? `finding-${randomUUID()}`; + const kind = overrides.kind ?? 'finding'; + const title = overrides.title ?? 'Momentum factor decays after 5 sessions'; + const summary = overrides.summary ?? 'Cross-sectional rank IC turns negative past day 5.'; + const createdAt = overrides.createdAt ?? FIXED_TS; + const trialRefs = overrides.trialRefs ?? ['101', '102']; + const evidenceRefs = overrides.evidenceRefs ?? ['snap:2026-01-15:ic']; + const idempotencyKey = overrides.idempotencyKey === undefined ? null : overrides.idempotencyKey; + + if (overrides.status !== undefined) { + return pool.query( + `INSERT INTO findings ( + id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key + ) VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9) + RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, + [ + id, + kind, + title, + summary, + overrides.status, + createdAt, + trialRefs, + evidenceRefs, + idempotencyKey, + ] + ); + } + + return pool.query( + `INSERT INTO findings ( + id, kind, title, summary, created_at, trial_refs, evidence_refs, idempotency_key + ) VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[], $8) + RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, + [id, kind, title, summary, createdAt, trialRefs, evidenceRefs, idempotencyKey] + ); +} + +interface ProviderCaveatInsertOverrides { + id?: string; + provider?: string; + dataset?: string; + caveat?: string; + createdAt?: string; +} + +function insertProviderCaveat(pool: Pool, overrides: ProviderCaveatInsertOverrides = {}) { + const id = overrides.id ?? `caveat-${randomUUID()}`; + const provider = overrides.provider ?? 'EODHD'; + const dataset = overrides.dataset ?? 'eodIntraday1M'; + const caveat = + overrides.caveat ?? 'Intraday 1m OHLCV is retroactively split-adjusted; un-adjust before use.'; + + if (overrides.createdAt !== undefined) { + return pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ($1, $2, $3, $4, $5::timestamptz) + RETURNING id, provider, dataset, caveat, created_at`, + [id, provider, dataset, caveat, overrides.createdAt] + ); + } + + return pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat) + VALUES ($1, $2, $3, $4) + RETURNING id, provider, dataset, caveat, created_at`, + [id, provider, dataset, caveat] + ); +} + +interface ProtectionTriggerRow { + relname: string; + tgname: string; + proname: string; + tgenabled: string; +} + +const EXPECTED_PROTECTION_TRIGGERS: ProtectionTriggerRow[] = [ + { + relname: 'findings', + tgname: 'findings_no_truncate', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, + { + relname: 'findings', + tgname: 'findings_retained', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, + { + relname: 'provider_caveats', + tgname: 'provider_caveats_no_truncate', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, + { + relname: 'provider_caveats', + tgname: 'provider_caveats_retained', + proname: 'reject_research_evidence_mutation', + tgenabled: 'O', + }, +]; + +async function listProtectionTriggers(pool: Pool, schema: string): Promise { + const result = await pool.query( + `SELECT c.relname, t.tgname, p.proname, t.tgenabled::text AS tgenabled + FROM pg_trigger t + JOIN pg_class c ON c.oid = t.tgrelid + JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_proc p ON p.oid = t.tgfoid + WHERE NOT t.tgisinternal + AND n.nspname = $1 + AND c.relname IN ('findings', 'provider_caveats') + ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`, + [schema] + ); + return result.rows; +} + +describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { + test('creates tables, indexes, and triggers and is idempotent on runner re-run and raw SQL re-execution', async () => { + const f = await createIsolatedFixture(); + + const tables = new Set( + ( + await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema]) + ).rows.map(row => row.tablename as string) + ); + expect(tables.has('findings')).toBe(true); + expect(tables.has('provider_caveats')).toBe(true); + + const indexDefs = new Map( + ( + await f.pool.query('SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = $1', [ + f.schema, + ]) + ).rows.map(row => [row.indexname as string, row.indexdef as string]) + ); + expect(indexDefs.get('idx_findings_idempotency_key')).toMatch( + /CREATE UNIQUE INDEX idx_findings_idempotency_key ON .*findings .* \(idempotency_key\) WHERE \(idempotency_key IS NOT NULL\)/ + ); + expect(indexDefs.get('idx_findings_created_at')).toMatch( + /CREATE INDEX idx_findings_created_at ON .*findings .* \(created_at\)/ + ); + expect(indexDefs.get('idx_provider_caveats_lower_provider')).toMatch( + /CREATE INDEX idx_provider_caveats_lower_provider ON .*provider_caveats .* \(lower\(provider\)\)/ + ); + + expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); + + const insertedFinding = ( + await insertFinding(f.pool, { id: 'f-idempotent', idempotencyKey: 'idem-keep' }) + ).rows[0]; + const insertedCaveat = ( + await insertProviderCaveat(f.pool, { id: 'c-idempotent', createdAt: FIXED_TS }) + ).rows[0]; + + expect(await runPostgresMigrations(f.postgres, { track: 'research' })).toEqual([]); + + const rawSql = readFileSync(researchFindingsSqlPath, 'utf8'); + await f.pool.query(rawSql); + + expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); + + const findingsAfter = (await f.pool.query('SELECT * FROM findings')).rows; + const caveatsAfter = (await f.pool.query('SELECT * FROM provider_caveats')).rows; + expect(findingsAfter).toEqual([insertedFinding]); + expect(caveatsAfter).toEqual([insertedCaveat]); + + await expectPgErrorCode( + f.pool.query("UPDATE findings SET title = 'mutated'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); + await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); + + await expectPgErrorCode( + f.pool.query("UPDATE provider_caveats SET caveat = 'mutated'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('DELETE FROM provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('TRUNCATE provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + + expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([insertedFinding]); + expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([insertedCaveat]); + }); + + test('findings round-trips every FiledFindingRecord field, defaults status, and accepts exact limit boundaries', async () => { + const f = await createIsolatedFixture(); + + const first = ( + await insertFinding(f.pool, { + id: 'finding-001', + kind: 'finding', + title: 'Earnings drift persists through day 3', + summary: 'Post-announcement drift remains positive across US large caps.', + createdAt: FIXED_TS, + trialRefs: ['42', '43'], + evidenceRefs: ['artifact:drift-v1'], + idempotencyKey: 'req-001', + }) + ).rows[0]; + + expect(first.id).toBe('finding-001'); + expect(first.kind).toBe('finding'); + expect(first.title).toBe('Earnings drift persists through day 3'); + expect(first.summary).toBe('Post-announcement drift remains positive across US large caps.'); + expect(first.status).toBe('pending_review'); + expect((first.created_at as Date).toISOString()).toBe(FIXED_TS); + expect(first.trial_refs).toEqual(['42', '43']); + expect(first.evidence_refs).toEqual(['artifact:drift-v1']); + expect(first.idempotency_key).toBe('req-001'); + + // Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities + // including Unicode NBSP / ideographic-space padding around max-length title and summary. + const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r')); + const boundary = ( + await insertFinding(f.pool, { + id: 'finding-002', + kind: 'dead_end', + title: `\u00A0${'t'.repeat(256)}\u00A0`, + summary: `\u00A0\u3000${'s'.repeat(4096)}\u00A0`, + createdAt: '2026-02-01T00:00:00.000Z', + trialRefs: maxRefs, + evidenceRefs: [], + idempotencyKey: 'k'.repeat(128), + }) + ).rows[0]; + + expect(boundary.kind).toBe('dead_end'); + expect(boundary.status).toBe('pending_review'); + expect((boundary.created_at as Date).toISOString()).toBe('2026-02-01T00:00:00.000Z'); + expect(boundary.trial_refs).toEqual(maxRefs); + expect(boundary.evidence_refs).toEqual([]); + expect(boundary.idempotency_key).toBe('k'.repeat(128)); + + // 32 evidence_refs at 256 chars and 1-char idempotency key also succeed. + const maxEvidence = ( + await insertFinding(f.pool, { + id: 'finding-003', + trialRefs: [], + evidenceRefs: maxRefs, + idempotencyKey: 'x', + }) + ).rows[0]; + expect(maxEvidence.trial_refs).toEqual([]); + expect(maxEvidence.evidence_refs).toEqual(maxRefs); + expect(maxEvidence.idempotency_key).toBe('x'); + }); + + test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => { + const f = await createIsolatedFixture(); + + // Blank / whitespace-only (ASCII and ECMAScript Unicode) id and status + const unicodeBlanks = ['\u00A0', '\u00A0\u2003\u3000\uFEFF', '\u2028\u2029']; + await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514'); + for (const blank of unicodeBlanks) { + await expectPgErrorCode(insertFinding(f.pool, { id: blank }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { status: blank }), '23514'); + } + + // Invalid kind + await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514'); + + // Blank, whitespace-only (ASCII and ECMAScript Unicode), or oversized title / summary + await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514'); + await expectPgErrorCode( + insertFinding(f.pool, { title: `\u00A0${'t'.repeat(257)}\u00A0` }), + '23514' + ); + await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514'); + for (const blank of unicodeBlanks) { + await expectPgErrorCode(insertFinding(f.pool, { title: blank }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { summary: blank }), '23514'); + } + + // Cardinality > 32 + const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`); + await expectPgErrorCode(insertFinding(f.pool, { trialRefs: refs33 }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: refs33 }), '23514'); + + // Ref length > 256 + const ref257 = 'r'.repeat(257); + await expectPgErrorCode(insertFinding(f.pool, { trialRefs: [ref257] }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: ['ok', ref257] }), '23514'); + + // NULL array elements + await expectPgErrorCode(insertFinding(f.pool, { trialRefs: ['101', null] }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: [null] }), '23514'); + + // Multidimensional arrays + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) + VALUES ('f-2d-trial', 'finding', 'Title', 'Summary', $1::timestamptz, '{{a,b},{c,d}}'::text[], '{}'::text[])`, + [FIXED_TS] + ), + '23514' + ); + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) + VALUES ('f-2d-ev', 'finding', 'Title', 'Summary', $1::timestamptz, '{101}'::text[], '{{a,b},{c,d}}'::text[])`, + [FIXED_TS] + ), + '23514' + ); + + // Invalid idempotency_key (empty, whitespace-only, > 128 chars) + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514'); + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514'); + for (const blank of unicodeBlanks) { + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: blank }), '23514'); + } + await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514'); + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); + }); + + test('findings enforces unique non-NULL idempotency_key while allowing multiple NULL keys', async () => { + const f = await createIsolatedFixture(); + + await insertFinding(f.pool, { id: 'f-key-1', idempotencyKey: 'shared-key' }); + await expectPgErrorCode( + insertFinding(f.pool, { id: 'f-key-2', idempotencyKey: 'shared-key' }), + '23505' + ); + + await insertFinding(f.pool, { id: 'f-null-1', idempotencyKey: null }); + await insertFinding(f.pool, { id: 'f-null-2', idempotencyKey: null }); + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); + }); + + test('provider_caveats round-trips every ProviderCaveatRecord field, defaults created_at, and rejects blank fields', async () => { + const f = await createIsolatedFixture(); + + const explicit = ( + await insertProviderCaveat(f.pool, { + id: 'caveat-001', + provider: 'QuoteMedia', + dataset: 'qmSplits', + caveat: 'splitratio stores old_shares / new_shares; invert to canonical new / old.', + createdAt: FIXED_TS, + }) + ).rows[0]; + + expect(explicit.id).toBe('caveat-001'); + expect(explicit.provider).toBe('QuoteMedia'); + expect(explicit.dataset).toBe('qmSplits'); + expect(explicit.caveat).toBe( + 'splitratio stores old_shares / new_shares; invert to canonical new / old.' + ); + expect((explicit.created_at as Date).toISOString()).toBe(FIXED_TS); + + const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0]; + expect(defaulted.created_at).toBeInstanceOf(Date); + + for (const blank of [ + '', + ' ', + '\t\n\r', + '\u00A0', + '\u00A0\u2003\u3000\uFEFF', + '\u2028\u2029', + ]) { + await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514'); + await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514'); + await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514'); + await expectPgErrorCode(insertProviderCaveat(f.pool, { caveat: blank }), '23514'); + } + + expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( + 2 + ); + }); + + test('UPDATE, DELETE, and TRUNCATE are blocked on both findings and provider_caveats', async () => { + const f = await createIsolatedFixture(); + + const findingBefore = (await insertFinding(f.pool, { id: 'f-immutable' })).rows[0]; + const caveatBefore = ( + await insertProviderCaveat(f.pool, { id: 'c-immutable', createdAt: FIXED_TS }) + ).rows[0]; + + await expectPgErrorCode( + f.pool.query("UPDATE findings SET status = 'approved'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); + await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); + + await expectPgErrorCode( + f.pool.query("UPDATE provider_caveats SET provider = 'Other'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('DELETE FROM provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query('TRUNCATE provider_caveats'), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + + expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([findingBefore]); + expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([caveatBefore]); + }); +}); + +describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema edge cases (QA)', () => { + test('research_trim_ecmascript matches String.prototype.trim() for every ECMAScript blank and for look-alike non-blanks', async () => { + const f = await createIsolatedFixture(); + // 25 ECMAScript WhiteSpace + LineTerminator code points, plus characters JS trim() keeps: + // ZERO WIDTH SPACE, NEXT LINE, MONGOLIAN VOWEL SEPARATOR, WORD JOINER. + const codePoints = [ + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, + 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, + 0xfeff, 0x200b, 0x0085, 0x180e, 0x2060, + ]; + for (const cp of codePoints) { + const c = String.fromCodePoint(cp); + for (const input of [c, `${c}${c}a b${c}`]) { + const sqlTrimmed = ( + await f.pool.query<{ v: string }>('SELECT research_trim_ecmascript($1) AS v', [input]) + ).rows[0]?.v; + expect({ cp, input, trimmed: sqlTrimmed }).toEqual({ cp, input, trimmed: input.trim() }); + } + } + }); + + test('non-ECMAScript blanks the MCP tool accepts (U+200B, U+0085) are accepted, and text is stored untrimmed', async () => { + const f = await createIsolatedFixture(); + const paddedTitle = `\u00A0 Interior spacing\tkept \u3000`; + + const zwsp = (await insertFinding(f.pool, { id: 'f-zwsp', title: '\u200B' })).rows[0]; + const nel = (await insertFinding(f.pool, { id: 'f-nel', summary: '\u0085' })).rows[0]; + const padded = (await insertFinding(f.pool, { id: 'f-padded', title: paddedTitle })).rows[0]; + + expect(zwsp.title).toBe('\u200B'); + expect(nel.summary).toBe('\u0085'); + expect(padded.title).toBe(paddedTitle); + }); + + test('title/summary caps count code points: 256 astral characters accepted, 257 rejected', async () => { + const f = await createIsolatedFixture(); + const emoji = '\u{1F4C8}'; + + const ok = (await insertFinding(f.pool, { id: 'f-astral-ok', title: emoji.repeat(256) })) + .rows[0]; + expect(ok.title).toBe(emoji.repeat(256)); + await expectPgErrorCode( + insertFinding(f.pool, { id: 'f-astral-bad', title: emoji.repeat(257) }), + '23514' + ); + await expectPgErrorCode( + insertFinding(f.pool, { id: 'f-astral-ref', trialRefs: [emoji.repeat(257)] }), + '23514' + ); + }); + + test('NOT NULL columns reject NULL with SQLSTATE 23502 and leave no rows', async () => { + const f = await createIsolatedFixture(); + const base = { + id: 'f-null', + kind: 'finding', + title: 'Title', + summary: 'Summary', + created_at: FIXED_TS, + trial_refs: ['1'], + evidence_refs: [] as string[], + }; + for (const column of Object.keys(base) as (keyof typeof base)[]) { + const row = { ...base, [column]: null }; + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) + VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[])`, + [ + row.id, + row.kind, + row.title, + row.summary, + row.created_at, + row.trial_refs, + row.evidence_refs, + ] + ), + '23502' + ); + } + // created_at has no default on findings: the tool's clock must supply it. + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, trial_refs, evidence_refs) + VALUES ('f-no-ts', 'finding', 'Title', 'Summary', '{1}', '{}')` + ), + '23502' + ); + await expectPgErrorCode( + f.pool.query( + `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs, status) + VALUES ('f-null-status', 'finding', 'Title', 'Summary', $1::timestamptz, '{1}', '{}', NULL)`, + [FIXED_TS] + ), + '23502' + ); + for (const column of ['id', 'provider', 'dataset', 'caveat', 'created_at']) { + const values: Record = { + id: 'c-null', + provider: 'EODHD', + dataset: 'eodPrices', + caveat: 'Caveat text', + created_at: FIXED_TS, + [column]: null, + }; + await expectPgErrorCode( + f.pool.query( + `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) + VALUES ($1, $2, $3, $4, $5::timestamptz)`, + [values.id, values.provider, values.dataset, values.caveat, values.created_at] + ), + '23502' + ); + } + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); + expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( + 0 + ); + }); + + test('duplicate ids are rejected (23505) on both tables and idempotency keys are case-sensitive', async () => { + const f = await createIsolatedFixture(); + + await insertFinding(f.pool, { id: 'dup-finding' }); + await expectPgErrorCode(insertFinding(f.pool, { id: 'dup-finding' }), '23505'); + await insertProviderCaveat(f.pool, { id: 'dup-caveat' }); + await expectPgErrorCode(insertProviderCaveat(f.pool, { id: 'dup-caveat' }), '23505'); + + // file_finding compares idempotency keys exactly; the unique index must not fold case. + await insertFinding(f.pool, { id: 'f-case-1', idempotencyKey: 'Retry-Key' }); + await insertFinding(f.pool, { id: 'f-case-2', idempotencyKey: 'retry-key' }); + + expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); + expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( + 1 + ); + }); + + test('a rejected UPDATE matching one row leaves every other row and column untouched', async () => { + const f = await createIsolatedFixture(); + await insertFinding(f.pool, { id: 'f-a', createdAt: '2026-01-01T00:00:00.000Z' }); + await insertFinding(f.pool, { id: 'f-b', createdAt: '2026-01-02T00:00:00.000Z' }); + const before = (await f.pool.query('SELECT * FROM findings ORDER BY id')).rows; + + await expectPgErrorCode( + f.pool.query("UPDATE findings SET status = 'approved' WHERE id = 'f-b'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + await expectPgErrorCode( + f.pool.query("DELETE FROM findings WHERE id = 'f-a'"), + '23514', + EXPECTED_IMMUTABLE_MSG + ); + + expect((await f.pool.query('SELECT * FROM findings ORDER BY id')).rows).toEqual(before); + }); +}); diff --git a/test/postgres/security-master-contract.test.ts b/test/postgres/security-master-contract.test.ts index eb140bb2..292bca21 100644 --- a/test/postgres/security-master-contract.test.ts +++ b/test/postgres/security-master-contract.test.ts @@ -274,12 +274,13 @@ describe('34-security-master.sql track registration', () => { expect(await runPostgresMigrations(postgres as never)).toEqual(research); }); - test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => { + test('all track runs 33, 34, 35, 36, 37 last in exact order and skips 06-08', async () => { const all = await filesForTrack('all'); - expect(all.at(-4)).toBe('33-candidate-decimal-normalization.sql'); - expect(all.at(-3)).toBe('34-security-master.sql'); - expect(all.at(-2)).toBe('35-security-master-exchange-seed.sql'); - expect(all.at(-1)).toBe('36-trial-ledger.sql'); + expect(all.at(-5)).toBe('33-candidate-decimal-normalization.sql'); + expect(all.at(-4)).toBe('34-security-master.sql'); + expect(all.at(-3)).toBe('35-security-master-exchange-seed.sql'); + expect(all.at(-2)).toBe('36-trial-ledger.sql'); + expect(all.at(-1)).toBe('37-research-findings.sql'); for (const bootstrap of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', diff --git a/tools/curate-etl/src/curate_fx_1m.rs b/tools/curate-etl/src/curate_fx_1m.rs new file mode 100644 index 00000000..0bdcc390 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_1m.rs @@ -0,0 +1,327 @@ +//! Pure, in-memory `fx_1m` curation stage for EODHD `CAD.FOREX` 1-minute FX bars (`M2.3k`), +//! joining [`crate::bson_eod_intraday::RawEodIntradayBar`], +//! [`crate::bson_stream::decode_eod_intraday_stream`], and [`crate::ilp::IlpShardedWriter`]. +//! +//! # Contract & Point-in-Time Rules +//! - **Source selection:** accepts only rows whose `eod_search_code` matches +//! [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`) verbatim. Any other code is dropped and counted in +//! [`CurateFx1mStats::dropped_wrong_code`] without erroring. +//! - **No split un-adjustment, listing mapping, or session tagging:** FX trades ~24h and is not +//! subject to equity splits or `provider_mapping` ranges. Every valid `CAD.FOREX` bar is kept +//! with its UTC microsecond bar-start `ts` unchanged (preserving the source clock without +//! implying the bar's close was observable at bar start). +//! - **Rate direction & bitwise preservation:** OHLC values pass through bit-identical in CAD per +//! 1 USD (matching `fx_1d`); `volume` is ignored at the curation layer. +//! - **Canonical labels:** emits `pair = FX_PAIR_USDCAD` (`"USDCAD"`, shared with `fx_1d` so +//! daily and intraday FX tables join on the same label) and `source = FX_1M_SOURCE_EOD` +//! (`"eod"`, fitting QuestDB `SYMBOL CAPACITY 8`). +//! - **Validation precedence:** bad single bars never panic or abort the stage; each bar is +//! classified once in strict priority order: +//! 1. `dropped_wrong_code` (`eod_search_code != "CAD.FOREX"`) +//! 2. `dropped_negative_ts` (`ts < 0`) +//! 3. `dropped_invalid_ohlc` (any of `open`, `high`, `low`, `close` non-finite or `<= 0.0`) +//! 4. `dropped_high_below_bound` (`high < max(open, close, low)`) +//! 5. `dropped_low_above_bound` (`low > min(open, close)`) +//! - **Ordering & deduplication:** surviving rows are sorted ascending by `ts` and compacted in +//! place per timestamp group using `f64::to_bits` equality across all four OHLC fields: +//! bitwise-identical groups of size `n` emit one row (`duplicate_collapsed += n - 1`), while +//! conflicting groups emit zero rows (`duplicate_conflict_dropped += n`). +//! - **Writer lifecycle:** [`curate_and_write_fx_1m`] and [`curate_and_write_fx_1m_from_bson`] +//! stream sorted [`Fx1mRow`]s into a caller-owned [`IlpShardedWriter`] via +//! [`IlpShardedWriter::write_fx_1m`] without calling [`IlpShardedWriter::finish`], allowing +//! multiple chunks to share one writer. +//! +//! # Memory, Chunking & BSON Validation Boundary +//! - **In-memory sort & per-call deduplication:** sorting buffers accepted `CAD.FOREX` rows for a +//! single call in memory, and deduplication applies within that call only. Callers splitting +//! large inputs across calls must keep all copies of a timestamp in the same call and submit +//! chunks in chronological order when global ordering is required. +//! - **BSON validation boundary:** [`curate_and_write_fx_1m_from_bson`] decodes via +//! [`decode_eod_intraday_stream`], which validates non-empty `eodSearchCode`, non-negative +//! integral `timestamp`, finite positive OHLC, and finite non-negative `volume` before invoking +//! the curation accumulator. Document-level decode rejects are accounted in +//! [`BsonEodIntradayDecodeStats`] (so `decode_stats.rows_decoded == write_report.curate_stats.bars_in`), +//! while direct in-memory calls to [`build_fx_1m`] / [`curate_and_write_fx_1m`] exercise the full +//! builder validation rules and ignore `volume`. + +use std::error::Error; +use std::fmt; +use std::io::{self, Write}; + +use crate::bson_eod_intraday::{BsonEodIntradayDecodeStats, RawEodIntradayBar}; +use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; +use crate::fx::FX_PAIR_USDCAD; +use crate::ilp::{Fx1mRow, IlpShardedWriter, IlpWriterError}; +use crate::run_curate_fx::EOD_CAD_FOREX_CODE; + +/// Canonical provenance label written to [`Fx1mRow::source`] for EODHD `eodIntraday1M` FX bars +/// (`SYMBOL CAPACITY 8`). +pub const FX_1M_SOURCE_EOD: &str = "eod"; + +/// Accounting summary produced alongside [`CurateFx1mOutput::rows`]. +/// +/// Conservation invariant: +/// `bars_in == rows_out + dropped_wrong_code + dropped_negative_ts + dropped_invalid_ohlc + dropped_high_below_bound + dropped_low_above_bound + duplicate_collapsed + duplicate_conflict_dropped` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mStats { + pub bars_in: usize, + pub rows_out: usize, + pub dropped_wrong_code: usize, + pub dropped_negative_ts: usize, + pub dropped_invalid_ohlc: usize, + pub dropped_high_below_bound: usize, + pub dropped_low_above_bound: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, +} + +/// Output of [`build_fx_1m`]: curated `fx_1m` rows sorted and unique by `ts`, plus exact +/// accounting statistics. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFx1mOutput { + pub rows: Vec>, + pub stats: CurateFx1mStats, +} + +/// Summary returned by [`curate_and_write_fx_1m`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mWriteReport { + pub curate_stats: CurateFx1mStats, + /// Number of curated rows accepted by [`IlpShardedWriter::write_fx_1m`] in this call. + pub rows_written: usize, +} + +/// Combined decode and write summary returned by [`curate_and_write_fx_1m_from_bson`]. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CurateFx1mBsonReport { + pub decode_stats: BsonEodIntradayDecodeStats, + pub write_report: CurateFx1mWriteReport, +} + +/// Typed error returned by [`curate_and_write_fx_1m_from_bson`]. +#[derive(Debug)] +pub enum CurateFx1mBsonError { + Stream(BsonStreamError), + Write(IlpWriterError), +} + +impl fmt::Display for CurateFx1mBsonError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "fx_1m BSON stream failed: {err}"), + Self::Write(err) => write!(f, "fx_1m ILP write failed: {err}"), + } + } +} + +impl Error for CurateFx1mBsonError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Write(err) => Some(err), + } + } +} + +impl From for CurateFx1mBsonError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for CurateFx1mBsonError { + fn from(err: IlpWriterError) -> Self { + Self::Write(err) + } +} + +#[inline] +fn is_valid_rate(rate: f64) -> bool { + rate.is_finite() && rate > 0.0 +} + +#[inline] +fn fx_1m_ohlc_bit_eq(a: &Fx1mRow<'_>, b: &Fx1mRow<'_>) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() +} + +#[derive(Default)] +struct Fx1mAccumulator { + rows: Vec>, + stats: CurateFx1mStats, +} + +impl Fx1mAccumulator { + #[inline] + fn push(&mut self, bar: RawEodIntradayBar<'_>) { + self.stats.bars_in += 1; + + if bar.eod_search_code != EOD_CAD_FOREX_CODE { + self.stats.dropped_wrong_code += 1; + return; + } + if bar.ts < 0 { + self.stats.dropped_negative_ts += 1; + return; + } + if !is_valid_rate(bar.open) + || !is_valid_rate(bar.high) + || !is_valid_rate(bar.low) + || !is_valid_rate(bar.close) + { + self.stats.dropped_invalid_ohlc += 1; + return; + } + if bar.high < bar.open || bar.high < bar.close || bar.high < bar.low { + self.stats.dropped_high_below_bound += 1; + return; + } + if bar.low > bar.open || bar.low > bar.close { + self.stats.dropped_low_above_bound += 1; + return; + } + + self.rows.push(Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: bar.ts, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + source: FX_1M_SOURCE_EOD, + }); + } + + fn finish(mut self) -> CurateFx1mOutput { + self.rows.sort_unstable_by_key(|row| row.ts); + + let len = self.rows.len(); + let mut write_idx = 0usize; + let mut read_idx = 0usize; + + while read_idx < len { + let ts = self.rows[read_idx].ts; + let mut group_end = read_idx + 1; + while group_end < len && self.rows[group_end].ts == ts { + group_end += 1; + } + let group_len = group_end - read_idx; + let first = self.rows[read_idx]; + let all_identical = self.rows[read_idx + 1..group_end] + .iter() + .all(|other| fx_1m_ohlc_bit_eq(&first, other)); + + if all_identical { + self.stats.duplicate_collapsed += group_len - 1; + if write_idx != read_idx { + self.rows[write_idx] = first; + } + write_idx += 1; + } else { + self.stats.duplicate_conflict_dropped += group_len; + } + + read_idx = group_end; + } + + self.rows.truncate(write_idx); + self.stats.rows_out = self.rows.len(); + + CurateFx1mOutput { + rows: self.rows, + stats: self.stats, + } + } +} + +fn write_curated_fx_1m( + curated: CurateFx1mOutput, + writer: &mut IlpShardedWriter, +) -> Result { + let mut rows_written = 0usize; + for row in &curated.rows { + writer.write_fx_1m(row)?; + rows_written += 1; + } + + Ok(CurateFx1mWriteReport { + curate_stats: curated.stats, + rows_written, + }) +} + +/// Pure `eodIntraday1M` (`CAD.FOREX`) -> `fx_1m` curation builder. +/// +/// Filters to exact [`EOD_CAD_FOREX_CODE`] rows, validates timestamps and OHLC in strict priority +/// order (ignoring `volume`), sorts ascending by `ts`, and deduplicates same-`ts` groups using +/// bitwise OHLC equality. Valid OHLC and UTC microsecond `ts` pass through unchanged, stamped +/// with `pair = FX_PAIR_USDCAD` and `source = FX_1M_SOURCE_EOD`. +pub fn build_fx_1m<'a, B>(bars: B) -> CurateFx1mOutput +where + B: IntoIterator>, +{ + let mut acc = Fx1mAccumulator::default(); + for bar in bars { + acc.push(bar); + } + acc.finish() +} + +/// Runs [`build_fx_1m`] and streams every curated row in ascending `ts` order into the +/// caller-owned [`IlpShardedWriter`] via [`IlpShardedWriter::write_fx_1m`]. +/// +/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple +/// chunks through a single writer before flushing and collecting aggregate +/// [`crate::ilp::IlpWriteStats`]. +pub fn curate_and_write_fx_1m<'a, W, B>( + bars: B, + writer: &mut IlpShardedWriter, +) -> Result +where + W: Write + Send, + B: IntoIterator>, +{ + let curated = build_fx_1m(bars); + write_curated_fx_1m(curated, writer) +} + +/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], +/// feeds every decoded [`RawEodIntradayBar`] directly into the `fx_1m` curation accumulator, and +/// streams sorted curated rows into the caller-owned [`IlpShardedWriter`]. +/// +/// - Per-document semantic decode errors are counted and skipped in +/// [`BsonEodIntradayDecodeStats`]; fatal stream framing or I/O errors abort before any row from +/// this call is written to `writer`. +/// - Intentionally does **not** call [`IlpShardedWriter::finish`]. +pub fn curate_and_write_fx_1m_from_bson( + reader: R, + options: BsonStreamOptions, + writer: &mut IlpShardedWriter, +) -> Result +where + R: io::Read, + W: Write + Send, +{ + let mut acc = Fx1mAccumulator::default(); + let decode_stats = decode_eod_intraday_stream( + reader, + options, + |raw| acc.push(raw), + |_offset, _err| {}, + )?; + + let curated = acc.finish(); + let write_report = write_curated_fx_1m(curated, writer)?; + + Ok(CurateFx1mBsonReport { + decode_stats, + write_report, + }) +} + +#[cfg(test)] +#[path = "curate_fx_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/curate_fx_1m_tests.rs b/tools/curate-etl/src/curate_fx_1m_tests.rs new file mode 100644 index 00000000..8a5622d3 --- /dev/null +++ b/tools/curate-etl/src/curate_fx_1m_tests.rs @@ -0,0 +1,560 @@ +use std::error::Error; +use std::io::{self, Cursor, Write}; + +use bson::raw::{cstr, RawDocumentBuf}; + +use super::*; +use crate::ilp::{encode_fx_1m, shard_for_fx_pair, IlpWriterOptions}; + +fn raw_bar<'a>( + code: &'a str, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawEodIntradayBar<'a> { + RawEodIntradayBar { + eod_search_code: code, + ts, + open, + high, + low, + close, + volume, + } +} + +fn make_eod_intraday_bson_doc( + code: &str, + ts_seconds: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("eodSearchCode"), code); + doc.append(cstr!("timestamp"), ts_seconds); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("volume"), volume); + doc +} + +fn assert_conservation_and_order(out: &CurateFx1mOutput) { + let s = &out.stats; + assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); + assert_eq!( + s.bars_in, + s.rows_out + + s.dropped_wrong_code + + s.dropped_negative_ts + + s.dropped_invalid_ohlc + + s.dropped_high_below_bound + + s.dropped_low_above_bound + + s.duplicate_collapsed + + s.duplicate_conflict_dropped, + "curate_fx_1m conservation invariant failed: {s:?}" + ); + + for pair in out.rows.windows(2) { + assert!( + pair[0].ts < pair[1].ts, + "rows not strictly ascending by ts: {} >= {}", + pair[0].ts, + pair[1].ts + ); + } + + for row in &out.rows { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + } +} + +struct FailingSink; + +impl Write for FailingSink { + fn write(&mut self, _buf: &[u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "sink failure")) + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "flush failure")) + } +} + +#[test] +fn empty_input_returns_empty_rows_and_zeroed_stats() { + let out = build_fx_1m(std::iter::empty()); + assert!(out.rows.is_empty()); + assert_eq!(out.stats, CurateFx1mStats::default()); + assert_conservation_and_order(&out); +} + +#[test] +fn valid_out_of_order_bars_sort_preserve_ohlc_bits_keep_off_session_and_ignore_volume() { + // 2024-06-09 22:15:00 UTC (Sunday evening FX open, off equity RTH). + let ts_sunday_utc = 1_717_971_300_000_000_i64; + // 2024-06-10 03:00:00 UTC (overnight). + let ts_overnight_utc = 1_717_988_400_000_000_i64; + // Exact epoch start ts = 0 must be accepted. + let ts_zero = 0_i64; + + let b_late = raw_bar( + EOD_CAD_FOREX_CODE, + ts_overnight_utc, + 1.37654321, + 1.37712345, + 1.37611111, + 1.37689012, + -99.0, // invalid volume ignored by builder + ); + let b_zero = raw_bar( + EOD_CAD_FOREX_CODE, + ts_zero, + 1.0725, + 1.0731, + 1.0720, + 1.0728, + f64::NAN, // NaN volume ignored by builder + ); + let b_mid = raw_bar( + EOD_CAD_FOREX_CODE, + ts_sunday_utc, + 1.3750, + 1.3755, + 1.3745, + 1.3752, + f64::INFINITY, // inf volume ignored by builder + ); + // Exact-match failures (case mismatch, trailing space, different ticker) -> dropped, not errored. + let b_lowercase = raw_bar("cad.forex", ts_sunday_utc + 60_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); + let b_padded = raw_bar("CAD.FOREX ", ts_sunday_utc + 120_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); + let b_other = raw_bar("AAPL.US", ts_sunday_utc + 180_000_000, 195.0, 196.0, 194.5, 195.5, 1000.0); + + let out = build_fx_1m([b_late, b_lowercase, b_zero, b_other, b_mid, b_padded]); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.bars_in, 6); + assert_eq!(out.stats.rows_out, 3); + assert_eq!(out.stats.dropped_wrong_code, 3); + assert_eq!(out.stats.dropped_negative_ts, 0); + assert_eq!(out.stats.dropped_invalid_ohlc, 0); + assert_eq!(out.stats.dropped_high_below_bound, 0); + assert_eq!(out.stats.dropped_low_above_bound, 0); + assert_eq!(out.stats.duplicate_collapsed, 0); + assert_eq!(out.stats.duplicate_conflict_dropped, 0); + + let expected_inputs = [b_zero, b_mid, b_late]; + for (row, src) in out.rows.iter().zip(expected_inputs) { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.source, FX_1M_SOURCE_EOD); + assert_eq!(row.ts, src.ts); + assert_eq!(row.open.to_bits(), src.open.to_bits()); + assert_eq!(row.high.to_bits(), src.high.to_bits()); + assert_eq!(row.low.to_bits(), src.low.to_bits()); + assert_eq!(row.close.to_bits(), src.close.to_bits()); + } +} + +#[test] +fn every_reject_reason_counted_separately_with_strict_precedence() { + let base_ts = 1_718_000_000_000_000_i64; + let bars = vec![ + // 1. Wrong code (also has negative ts and NaN OHLC to verify wrong_code precedence). + raw_bar("USD.FOREX", -1, f64::NAN, 1.0, 2.0, 0.0, 0.0), + // 2. Negative timestamps (second also has NaN OHLC to verify negative_ts precedence). + raw_bar(EOD_CAD_FOREX_CODE, -1, 1.35, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, i64::MIN, f64::NAN, 1.36, 1.34, 1.35, 0.0), + // 3. Invalid OHLC: NaN, +inf, -inf, +0.0, -0.0, negative price. + raw_bar(EOD_CAD_FOREX_CODE, base_ts, f64::NAN, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 1, 1.35, f64::INFINITY, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 2, 1.35, 1.36, f64::NEG_INFINITY, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 3, 1.35, 1.36, 1.34, 0.0, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 4, -0.0, 1.36, 1.34, 1.35, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 5, 1.35, 1.36, -1.34, 1.35, 0.0), + // 4. high < max(open, close, low): + // - high < open + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 6, 1.37, 1.36, 1.34, 1.35, 0.0), + // - high < close + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 7, 1.35, 1.36, 1.34, 1.37, 0.0), + // - high < low (while high >= open/close is impossible if low > open/close, test open=close=1.35, high=1.35, low=1.36) + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 8, 1.35, 1.35, 1.36, 1.35, 0.0), + // - overlapping high < open AND low > close -> pinned to dropped_high_below_bound + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 9, 1.38, 1.36, 1.37, 1.35, 0.0), + // 5. low > min(open, close) (with high >= max(open, close, low)): + // - low > open + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 10, 1.33, 1.36, 1.34, 1.35, 0.0), + // - low > close + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 11, 1.35, 1.36, 1.34, 1.33, 0.0), + // Valid bar. + raw_bar(EOD_CAD_FOREX_CODE, base_ts + 12, 1.35, 1.36, 1.34, 1.355, 0.0), + ]; + + let out = build_fx_1m(bars); + assert_conservation_and_order(&out); + + assert_eq!(out.stats.bars_in, 16); + assert_eq!(out.stats.dropped_wrong_code, 1); + assert_eq!(out.stats.dropped_negative_ts, 2); + assert_eq!(out.stats.dropped_invalid_ohlc, 6); + assert_eq!(out.stats.dropped_high_below_bound, 4); + assert_eq!(out.stats.dropped_low_above_bound, 2); + assert_eq!(out.stats.duplicate_collapsed, 0); + assert_eq!(out.stats.duplicate_conflict_dropped, 0); + assert_eq!(out.stats.rows_out, 1); + assert_eq!(out.rows[0].ts, base_ts + 12); +} + +#[test] +fn dedup_collapses_identical_ohlc_drops_conflicting_group_and_is_permutation_invariant() { + let ts_identical = 1_718_000_060_000_000_i64; + let ts_conflict = 1_718_000_120_000_000_i64; + let ts_valid_plus_bad = 1_718_000_180_000_000_i64; + + // Group 1: three bitwise-identical OHLC bars with differing volumes -> collapse to 1. + let id1 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 0.0); + let id2 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 42.0); + let id3 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, f64::NAN); + + // Group 2: two identical rows + one conflicting close -> drop all 3. + let cf1 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); + let cf2 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); + let cf3 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3626, 1.0); + + // Group 3: one valid row + one invalid row at same ts -> invalid rejected early, valid survives. + let ok = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, 1.3630, 1.3640, 1.3625, 1.3635, 0.0); + let bad = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, f64::NAN, 1.3640, 1.3625, 1.3635, 0.0); + + let perm_a = [id1, id2, id3, cf1, cf2, cf3, ok, bad]; + let perm_b = [cf3, bad, id3, cf1, ok, id1, cf2, id2]; + let perm_c = [ok, cf2, id2, cf3, id1, bad, cf1, id3]; + + let out_a = build_fx_1m(perm_a); + let out_b = build_fx_1m(perm_b); + let out_c = build_fx_1m(perm_c); + + assert_conservation_and_order(&out_a); + assert_conservation_and_order(&out_b); + assert_conservation_and_order(&out_c); + assert_eq!(out_a, out_b); + assert_eq!(out_a, out_c); + + assert_eq!(out_a.stats.bars_in, 8); + assert_eq!(out_a.stats.dropped_invalid_ohlc, 1); + assert_eq!(out_a.stats.duplicate_collapsed, 2); + assert_eq!(out_a.stats.duplicate_conflict_dropped, 3); + assert_eq!(out_a.stats.rows_out, 2); + + assert_eq!(out_a.rows[0].ts, ts_identical); + assert_eq!(out_a.rows[0].close.to_bits(), 1.3615_f64.to_bits()); + assert_eq!(out_a.rows[1].ts, ts_valid_plus_bad); + assert_eq!(out_a.rows[1].close.to_bits(), 1.3635_f64.to_bits()); +} + +#[test] +fn writer_streams_two_chunks_through_one_writer_matches_encode_fx_1m_and_routes_one_shard() { + let ts1 = 1_718_000_000_000_000_i64; + let ts2 = 1_718_000_060_000_000_i64; + let ts3 = 1_718_000_120_000_000_i64; + + // Chunk 1 given out of order plus an unrelated ticker. + let chunk1 = [ + raw_bar(EOD_CAD_FOREX_CODE, ts2, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), + raw_bar("EUR.FOREX", ts1, 1.0800, 1.0810, 1.0790, 1.0805, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), + ]; + // Chunk 2 chronologically after chunk 1. + let chunk2 = [raw_bar( + EOD_CAD_FOREX_CODE, + ts3, + 1.3715, + 1.3725, + 1.3710, + 1.3722, + 0.0, + )]; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let mut s2 = Vec::new(); + let mut s3 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1, &mut s2, &mut s3], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = curate_and_write_fx_1m(chunk1, &mut writer).unwrap(); + // Writer remains open (finish was NOT called) so chunk 2 streams into the same writer. + let rep2 = curate_and_write_fx_1m(chunk2, &mut writer).unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + assert_eq!(rep1.curate_stats.bars_in, 3); + assert_eq!(rep1.curate_stats.dropped_wrong_code, 1); + assert_eq!(rep1.curate_stats.rows_out, 2); + assert_eq!(rep1.rows_written, 2); + + assert_eq!(rep2.curate_stats.bars_in, 1); + assert_eq!(rep2.curate_stats.rows_out, 1); + assert_eq!(rep2.rows_written, 1); + + assert_eq!(ilp_stats.rows, rep1.rows_written + rep2.rows_written); + assert_eq!(ilp_stats.rows, 3); + + let expected_rows = [ + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts1, + open: 1.3700, + high: 1.3710, + low: 1.3695, + close: 1.3705, + source: FX_1M_SOURCE_EOD, + }, + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts2, + open: 1.3710, + high: 1.3720, + low: 1.3705, + close: 1.3715, + source: FX_1M_SOURCE_EOD, + }, + Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts3, + open: 1.3715, + high: 1.3725, + low: 1.3710, + close: 1.3722, + source: FX_1M_SOURCE_EOD, + }, + ]; + let mut expected_bytes = Vec::new(); + for row in &expected_rows { + encode_fx_1m(&mut expected_bytes, row).unwrap(); + } + + let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 4); + let actual_shards = [&s0, &s1, &s2, &s3]; + for (idx, shard_bytes) in actual_shards.iter().enumerate() { + if idx == target_shard { + assert_eq!(*shard_bytes, &expected_bytes, "target shard ILP mismatch"); + } else { + assert!( + shard_bytes.is_empty(), + "non-target shard {idx} should be empty" + ); + } + } + assert_eq!(ilp_stats.per_shard_rows[target_shard], 3); +} + +#[test] +fn bson_stream_handles_mixed_docs_matches_builder_and_supports_writer_reuse() { + let ts1_sec = 1_718_000_000_i64; + let ts2_sec = 1_718_000_060_i64; + let ts3_sec = 1_718_000_120_i64; + + // Out-of-order CAD.FOREX docs + an identical duplicate + a decodable other code + a malformed doc. + let doc_late = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts2_sec, 1.3720, 1.3730, 1.3715, 1.3725, 0.0); + let doc_other = + make_eod_intraday_bson_doc("AAPL.US", ts1_sec, 195.0, 196.0, 194.5, 195.5, 1200.0); + // Correctly framed BSON document missing required field `close`. + let mut doc_missing_close = RawDocumentBuf::new(); + doc_missing_close.append(cstr!("eodSearchCode"), EOD_CAD_FOREX_CODE); + doc_missing_close.append(cstr!("timestamp"), ts1_sec); + doc_missing_close.append(cstr!("open"), 1.3700_f64); + doc_missing_close.append(cstr!("high"), 1.3710_f64); + doc_missing_close.append(cstr!("low"), 1.3695_f64); + doc_missing_close.append(cstr!("volume"), 0.0_f64); + + let doc_early = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 0.0); + let doc_early_dup = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 5.0); + + let mut chunk1_bytes = Vec::new(); + chunk1_bytes.extend_from_slice(doc_late.as_bytes()); + chunk1_bytes.extend_from_slice(doc_other.as_bytes()); + chunk1_bytes.extend_from_slice(doc_missing_close.as_bytes()); + chunk1_bytes.extend_from_slice(doc_early.as_bytes()); + chunk1_bytes.extend_from_slice(doc_early_dup.as_bytes()); + + let doc_chunk2 = + make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts3_sec, 1.3725, 1.3735, 1.3720, 1.3731, 0.0); + let chunk2_bytes = doc_chunk2.as_bytes().to_vec(); + + // Small chunk capacity forces multi-chunk framing across documents. + let stream_opts = BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }; + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (rep1, rep2, ilp_stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions::default(), + ) + .unwrap(); + let rep1 = + curate_and_write_fx_1m_from_bson(Cursor::new(&chunk1_bytes), stream_opts, &mut writer) + .unwrap(); + let rep2 = + curate_and_write_fx_1m_from_bson(Cursor::new(&chunk2_bytes), stream_opts, &mut writer) + .unwrap(); + let stats = writer.finish().unwrap(); + (rep1, rep2, stats) + }; + + // Decode accounting: 5 docs seen = 4 decoded + 1 missing_field reject. + assert_eq!(rep1.decode_stats.docs_seen, 5); + assert_eq!(rep1.decode_stats.rows_decoded, 4); + assert_eq!(rep1.decode_stats.rejected_missing_field, 1); + assert_eq!( + rep1.decode_stats.docs_seen, + rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() + ); + + // Builder input equals rows_decoded. + assert_eq!( + rep1.write_report.curate_stats.bars_in, + rep1.decode_stats.rows_decoded + ); + assert_eq!(rep1.write_report.curate_stats.dropped_wrong_code, 1); + assert_eq!(rep1.write_report.curate_stats.duplicate_collapsed, 1); + assert_eq!(rep1.write_report.curate_stats.rows_out, 2); + assert_eq!(rep1.write_report.rows_written, 2); + + // Compare chunk 1 curation stats directly against `build_fx_1m` on the same decoded inputs. + let direct_expected = build_fx_1m([ + raw_bar(EOD_CAD_FOREX_CODE, ts2_sec * 1_000_000, 1.3720, 1.3730, 1.3715, 1.3725, 0.0), + raw_bar("AAPL.US", ts1_sec * 1_000_000, 195.0, 196.0, 194.5, 195.5, 1200.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), + raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 5.0), + ]); + assert_eq!(rep1.write_report.curate_stats, direct_expected.stats); + + // Chunk 2 stats & aggregate ILP stats. + assert_eq!(rep2.decode_stats.docs_seen, 1); + assert_eq!(rep2.decode_stats.rows_decoded, 1); + assert_eq!(rep2.write_report.rows_written, 1); + assert_eq!(ilp_stats.rows, 3); + + // Exact ILP bytes match `encode_fx_1m` of chunk 1 + chunk 2 expected rows in order. + let mut expected_bytes = Vec::new(); + for row in &direct_expected.rows { + encode_fx_1m(&mut expected_bytes, row).unwrap(); + } + encode_fx_1m( + &mut expected_bytes, + &Fx1mRow { + pair: FX_PAIR_USDCAD, + ts: ts3_sec * 1_000_000, + open: 1.3725, + high: 1.3735, + low: 1.3720, + close: 1.3731, + source: FX_1M_SOURCE_EOD, + }, + ) + .unwrap(); + + let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 2); + let other_shard = 1 - target_shard; + let shards = [&s0, &s1]; + assert_eq!(shards[target_shard], &expected_bytes); + assert!(shards[other_shard].is_empty()); +} + +#[test] +fn truncated_bson_stream_fails_closed_with_zero_rows_written_and_typed_errors_format() { + let doc1 = make_eod_intraday_bson_doc( + EOD_CAD_FOREX_CODE, + 1_718_000_000, + 1.3700, + 1.3710, + 1.3695, + 1.3705, + 0.0, + ); + let doc2 = make_eod_intraday_bson_doc( + EOD_CAD_FOREX_CODE, + 1_718_000_060, + 1.3710, + 1.3720, + 1.3705, + 1.3715, + 0.0, + ); + + let mut truncated_bytes = Vec::new(); + truncated_bytes.extend_from_slice(doc1.as_bytes()); + let doc2_bytes = doc2.as_bytes(); + truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); + + let mut s0 = Vec::new(); + let mut s1 = Vec::new(); + let (stream_err, stats) = { + let mut writer = IlpShardedWriter::new( + vec![&mut s0, &mut s1], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let err = curate_and_write_fx_1m_from_bson( + Cursor::new(&truncated_bytes), + BsonStreamOptions::default(), + &mut writer, + ) + .unwrap_err(); + let stats = writer.finish().unwrap(); + (err, stats) + }; + + assert!(matches!( + stream_err, + CurateFx1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) + )); + assert!(stream_err.source().is_some()); + assert!(stream_err.to_string().contains("fx_1m BSON stream failed")); + assert_eq!(stats.rows, 0); + assert!(s0.is_empty()); + assert!(s1.is_empty()); + + // Writer I/O failure surfaces as `CurateFx1mBsonError::Write(IlpWriterError::Io { .. })`. + let mut failing_writer = IlpShardedWriter::new( + vec![FailingSink], + IlpWriterOptions { + max_batch_bytes: 1024, + max_batch_rows: 1, + }, + ) + .unwrap(); + let write_err = curate_and_write_fx_1m_from_bson( + Cursor::new(doc1.as_bytes()), + BsonStreamOptions::default(), + &mut failing_writer, + ) + .unwrap_err(); + assert!(matches!( + write_err, + CurateFx1mBsonError::Write(IlpWriterError::Io { shard: 0, .. }) + )); + assert!(write_err.source().is_some()); + assert!(write_err.to_string().contains("fx_1m ILP write failed")); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index fb59f375..1a8ff478 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -164,8 +164,9 @@ pub use parquet_events::{ EventsWriteStats, ParquetEventsError, }; pub use parquet_fundamentals::{ - fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitParquetRow, - FundamentalsPitWriteOptions, FundamentalsPitWriteStats, ParquetFundamentalsError, + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, + FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, + ParquetFundamentalsError, }; pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, @@ -255,6 +256,13 @@ pub use curate_qm_bars_1m::{ CurateQmBars1mBsonError, CurateQmBars1mBsonReport, }; +pub mod curate_fx_1m; +pub use curate_fx_1m::{ + build_fx_1m, curate_and_write_fx_1m, curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, + CurateFx1mBsonReport, CurateFx1mOutput, CurateFx1mStats, CurateFx1mWriteReport, + FX_1M_SOURCE_EOD, +}; + pub mod run_curate_bars; pub use run_curate_bars::{ default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv, diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs index f833350d..38000652 100644 --- a/tools/curate-etl/src/parquet_fundamentals.rs +++ b/tools/curate-etl/src/parquet_fundamentals.rs @@ -1,8 +1,7 @@ //! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. //! //! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column -//! contract schema read by `planFundamentalsAsOfQuery` in -//! `libs/research/src/market-data-store-duckdb.ts`: +//! contract schema in `design/DATA-CONTRACTS.md` (§3A): //! //! 1. `listing_id` (`INT32`, `REQUIRED`) //! 2. `effective_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) @@ -24,6 +23,11 @@ //! 18. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) //! 19. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) //! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) +//! +//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the +//! builder-provided 4-quarter `ttm` summary from a [`FundamentalsSnapshot`]. Lagged period slots +//! (`periods[1..]`) are intentionally omitted from the flat Parquet representation; TTM values +//! computed by [`crate::fundamentals::build_fundamentals_snapshots`] are preserved as-is. use std::borrow::{Borrow, Cow}; use std::cmp::Ordering; @@ -39,159 +43,119 @@ use std::time::Duration; use parquet::basic::{ Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, }; -use parquet::column::writer::ColumnWriter; use parquet::data_type::ByteArray; use parquet::errors::ParquetError; use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; -use parquet::file::writer::{SerializedFileWriter, SerializedRowGroupWriter}; +use parquet::file::writer::SerializedFileWriter; use parquet::schema::types::{ColumnPath, Type, TypePtr}; -use crate::events::partition_year_utc; -use crate::fundamentals::FundamentalsSnapshot; +use crate::events::{ + partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm}; pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; use crate::parquet_publish::{ create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, - rollback_published, write_i32_col, write_i64_col, write_interned_str_col, + rollback_published, write_bool_col, write_i32_col, write_i64_col, write_interned_str_col, write_optional_f64_col, write_optional_i32_col, write_optional_interned_str_col, DatasetFileLock, PublishIoError, PublishedPartition, StagingFileGuard, StringInterner, DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, }; pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; -use crate::shorts::epoch_days_to_ymd; -/// Single flat `fundamentals_pit` row keyed by `(listing_id, effective_known_at_micros)`. +/// Latest visible period projection flattened into a [`FundamentalsPitParquetRow`]. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPitLatestPeriod { + pub period_end: i32, + pub fiscal_period: Cow<'static, str>, + pub currency: String, + pub period_known_at_micros: i64, + pub fields: FundamentalsFields, +} + +/// Single `fundamentals_pit` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. +/// +/// Only `periods[0]` (the latest visible period) and `ttm` are stored; lagged slots +/// (`periods[1..]`) are intentionally omitted. #[derive(Debug, Clone, PartialEq)] pub struct FundamentalsPitParquetRow { pub listing_id: i32, pub effective_known_at_micros: i64, pub known_at_source: Cow<'static, str>, pub has_estimated_lag: bool, - pub period_end: i32, - pub fiscal_period: Cow<'static, str>, - pub currency: Cow<'static, str>, - pub period_known_at_micros: i64, - pub revenue: Option, - pub net_income: Option, - pub operating_cash_flow: Option, - pub total_assets: Option, - pub total_equity: Option, - pub shares_outstanding: Option, - pub ttm_revenue: Option, - pub ttm_net_income: Option, - pub ttm_operating_cash_flow: Option, - pub ttm_period_end: Option, - pub ttm_currency: Option>, - pub ttm_has_estimated_lag: Option, + latest_period: Option, + pub ttm: Option, } -impl TryFrom<&FundamentalsSnapshot> for FundamentalsPitParquetRow { - type Error = ParquetFundamentalsError; +impl FundamentalsPitParquetRow { + /// Constructs a valid `fundamentals_pit` Parquet row with an explicit latest visible period. + pub fn new( + listing_id: i32, + effective_known_at_micros: i64, + known_at_source: Cow<'static, str>, + has_estimated_lag: bool, + latest_period: FundamentalsPitLatestPeriod, + ttm: Option, + ) -> Self { + Self { + listing_id, + effective_known_at_micros, + known_at_source, + has_estimated_lag, + latest_period: Some(latest_period), + ttm, + } + } - fn try_from(snapshot: &FundamentalsSnapshot) -> Result { - let latest = snapshot.periods.first().ok_or( - ParquetFundamentalsError::EmptySnapshotPeriods { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - }, - )?; - - let ( - ttm_revenue, - ttm_net_income, - ttm_operating_cash_flow, - ttm_period_end, - ttm_currency, - ttm_has_estimated_lag, - ) = match &snapshot.ttm { - Some(ttm) => ( - ttm.flows.revenue, - ttm.flows.net_income, - ttm.flows.operating_cash_flow, - Some(ttm.ending_period_end), - Some(Cow::Owned(ttm.currency.clone())), - Some(ttm.has_estimated_lag), - ), - None => (None, None, None, None, None, None), - }; - - Ok(Self { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - known_at_source: Cow::Borrowed(snapshot.known_at_source), - has_estimated_lag: snapshot.has_estimated_lag, - period_end: latest.period_end, - fiscal_period: Cow::Borrowed(latest.fiscal_period.as_str()), - currency: Cow::Owned(latest.currency.clone()), - period_known_at_micros: latest.known_at_utc_micros, - revenue: latest.fields.revenue, - net_income: latest.fields.net_income, - operating_cash_flow: latest.fields.operating_cash_flow, - total_assets: latest.fields.total_assets, - total_equity: latest.fields.total_equity, - shares_outstanding: latest.fields.shares_outstanding, - ttm_revenue, - ttm_net_income, - ttm_operating_cash_flow, - ttm_period_end, - ttm_currency, - ttm_has_estimated_lag, - }) + /// Returns the flattened latest visible period (`periods[0]`), or `None` if converted from a + /// malformed snapshot with an empty `periods` vector. + #[inline] + pub fn latest_period(&self) -> Option<&FundamentalsPitLatestPeriod> { + self.latest_period.as_ref() } } -impl TryFrom> for FundamentalsPitParquetRow { - type Error = ParquetFundamentalsError; - - fn try_from(snapshot: FundamentalsSnapshot) -> Result { - let mut periods = snapshot.periods.into_iter(); - let latest = periods.next().ok_or( - ParquetFundamentalsError::EmptySnapshotPeriods { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - }, - )?; - - let ( - ttm_revenue, - ttm_net_income, - ttm_operating_cash_flow, - ttm_period_end, - ttm_currency, - ttm_has_estimated_lag, - ) = match snapshot.ttm { - Some(ttm) => ( - ttm.flows.revenue, - ttm.flows.net_income, - ttm.flows.operating_cash_flow, - Some(ttm.ending_period_end), - Some(Cow::Owned(ttm.currency)), - Some(ttm.has_estimated_lag), - ), - None => (None, None, None, None, None, None), - }; - - Ok(Self { +impl From<&FundamentalsSnapshot> for FundamentalsPitParquetRow { + fn from(snapshot: &FundamentalsSnapshot) -> Self { + let latest_period = snapshot.periods.first().map(|slot| FundamentalsPitLatestPeriod { + period_end: slot.period_end, + fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), + currency: slot.currency.clone(), + period_known_at_micros: slot.known_at_utc_micros, + fields: slot.fields, + }); + Self { listing_id: snapshot.key, effective_known_at_micros: snapshot.effective_known_at_utc_micros, known_at_source: Cow::Borrowed(snapshot.known_at_source), has_estimated_lag: snapshot.has_estimated_lag, - period_end: latest.period_end, - fiscal_period: Cow::Borrowed(latest.fiscal_period.as_str()), - currency: Cow::Owned(latest.currency), - period_known_at_micros: latest.known_at_utc_micros, - revenue: latest.fields.revenue, - net_income: latest.fields.net_income, - operating_cash_flow: latest.fields.operating_cash_flow, - total_assets: latest.fields.total_assets, - total_equity: latest.fields.total_equity, - shares_outstanding: latest.fields.shares_outstanding, - ttm_revenue, - ttm_net_income, - ttm_operating_cash_flow, - ttm_period_end, - ttm_currency, - ttm_has_estimated_lag, - }) + latest_period, + ttm: snapshot.ttm.clone(), + } + } +} + +impl From> for FundamentalsPitParquetRow { + fn from(snapshot: FundamentalsSnapshot) -> Self { + let latest_period = snapshot + .periods + .into_iter() + .next() + .map(|slot| FundamentalsPitLatestPeriod { + period_end: slot.period_end, + fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), + currency: slot.currency, + period_known_at_micros: slot.known_at_utc_micros, + fields: slot.fields, + }); + Self { + listing_id: snapshot.key, + effective_known_at_micros: snapshot.effective_known_at_utc_micros, + known_at_source: Cow::Borrowed(snapshot.known_at_source), + has_estimated_lag: snapshot.has_estimated_lag, + latest_period, + ttm: snapshot.ttm, + } } } @@ -221,15 +185,15 @@ pub struct FundamentalsPitWriteStats { pub rows_by_year: BTreeMap, } -/// Typed error returned by [`FundamentalsPitParquetRow::try_from`] and -/// [`write_fundamentals_pit_dataset`]. +/// Typed error returned by [`write_fundamentals_pit_dataset`]. #[derive(Debug)] pub enum ParquetFundamentalsError { InvalidRowGroupRows, InvalidZstdLevel { level: i32, }, - EmptySnapshotPeriods { + EmptyPeriods { + row_index: usize, listing_id: i32, effective_known_at_micros: i64, }, @@ -253,35 +217,17 @@ pub enum ParquetFundamentalsError { min_year: i32, max_year: i32, }, - PeriodEndOutOfRange { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - period_end: i32, - year: i32, - min_year: i32, - max_year: i32, - }, - TtmPeriodEndOutOfRange { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - ttm_period_end: i32, - year: i32, - min_year: i32, - max_year: i32, - }, - PeriodKnownAtAfterEffectiveKnownAt { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - period_known_at_micros: i64, - }, EmptyKnownAtSource { row_index: usize, listing_id: i32, effective_known_at_micros: i64, }, + InvalidKnownAtSource { + row_index: usize, + listing_id: i32, + effective_known_at_micros: i64, + value: String, + }, EmptyFiscalPeriod { row_index: usize, listing_id: i32, @@ -297,11 +243,6 @@ pub enum ParquetFundamentalsError { listing_id: i32, effective_known_at_micros: i64, }, - InconsistentTtmMetadata { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, NonFiniteValue { row_index: usize, listing_id: i32, @@ -336,12 +277,13 @@ impl fmt::Display for ParquetFundamentalsError { Self::InvalidZstdLevel { level } => { write!(f, "invalid Zstd compression level: {level}") } - Self::EmptySnapshotPeriods { + Self::EmptyPeriods { + row_index, listing_id, effective_known_at_micros, } => write!( f, - "snapshot for (listing_id={listing_id}, effective_known_at={effective_known_at_micros}) has no visible periods" + "snapshot has empty periods at row {row_index} for (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" ), Self::UnsortedInput { row_index, @@ -372,39 +314,6 @@ impl fmt::Display for ParquetFundamentalsError { f, "partition year {year} (effective_known_at {effective_known_at_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" ), - Self::PeriodEndOutOfRange { - row_index, - listing_id, - effective_known_at_micros, - period_end, - year, - min_year, - max_year, - } => write!( - f, - "period_end {period_end} (year {year}) at row {row_index} for ({listing_id}, {effective_known_at_micros}) is outside allowed range {min_year}..={max_year}" - ), - Self::TtmPeriodEndOutOfRange { - row_index, - listing_id, - effective_known_at_micros, - ttm_period_end, - year, - min_year, - max_year, - } => write!( - f, - "ttm_period_end {ttm_period_end} (year {year}) at row {row_index} for ({listing_id}, {effective_known_at_micros}) is outside allowed range {min_year}..={max_year}" - ), - Self::PeriodKnownAtAfterEffectiveKnownAt { - row_index, - listing_id, - effective_known_at_micros, - period_known_at_micros, - } => write!( - f, - "period_known_at {period_known_at_micros} is after effective_known_at {effective_known_at_micros} at row {row_index} for listing_id {listing_id}" - ), Self::EmptyKnownAtSource { row_index, listing_id, @@ -413,6 +322,15 @@ impl fmt::Display for ParquetFundamentalsError { f, "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" ), + Self::InvalidKnownAtSource { + row_index, + listing_id, + effective_known_at_micros, + value, + } => write!( + f, + "invalid known_at_source {value:?} at row {row_index} for ({listing_id}, {effective_known_at_micros}): expected {KNOWN_AT_SOURCE_FILING_TIMESTAMP:?} or {KNOWN_AT_SOURCE_STATUTORY_LAG:?}" + ), Self::EmptyFiscalPeriod { row_index, listing_id, @@ -435,15 +353,7 @@ impl fmt::Display for ParquetFundamentalsError { effective_known_at_micros, } => write!( f, - "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty when present" - ), - Self::InconsistentTtmMetadata { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "inconsistent TTM columns at row {row_index} for ({listing_id}, {effective_known_at_micros}): ttm_period_end, ttm_currency, and ttm_has_estimated_lag must all be Some or all be None, and TTM flow values require TTM metadata" + "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" ), Self::NonFiniteValue { row_index, @@ -453,7 +363,7 @@ impl fmt::Display for ParquetFundamentalsError { value, } => write!( f, - "non-finite value {value} in field '{field}' at row {row_index} for ({listing_id}, {effective_known_at_micros})" + "non-finite {field} value {value} at row {row_index} for ({listing_id}, {effective_known_at_micros})" ), Self::LockTimeout { path, waited } => write!( f, @@ -502,57 +412,64 @@ impl From for ParquetFundamentalsError { } } -/// Builds the exact 20-column Parquet schema for `fundamentals_pit` matching -/// `FUNDAMENTALS_BASE_SCHEMA`, `FUNDAMENTALS_PIT_VALUE_FIELDS`, and -/// `FUNDAMENTALS_TTM_META_SCHEMA` in `libs/research/src/market-data-store-duckdb.ts`. +/// Builds the exact 20-column Parquet schema for `fundamentals_pit` per `design/DATA-CONTRACTS.md` (§3A). pub fn fundamentals_pit_parquet_schema() -> Result { let fields: Vec = vec![ + // 1. listing_id INT32 REQUIRED Arc::new( Type::primitive_type_builder("listing_id", PhysicalType::INT32) .with_repetition(Repetition::REQUIRED) .build()?, ), + // 2. effective_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) Arc::new( Type::primitive_type_builder("effective_known_at", PhysicalType::INT64) .with_repetition(Repetition::REQUIRED) .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) .build()?, ), + // 3. known_at_source STRING REQUIRED Arc::new( Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) .with_repetition(Repetition::REQUIRED) .with_logical_type(Some(LogicalType::String)) .build()?, ), + // 4. has_estimated_lag BOOLEAN REQUIRED Arc::new( Type::primitive_type_builder("has_estimated_lag", PhysicalType::BOOLEAN) .with_repetition(Repetition::REQUIRED) .build()?, ), + // 5. period_end INT32 DATE REQUIRED Arc::new( Type::primitive_type_builder("period_end", PhysicalType::INT32) .with_repetition(Repetition::REQUIRED) .with_logical_type(Some(LogicalType::Date)) .build()?, ), + // 6. fiscal_period STRING REQUIRED Arc::new( Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) .with_repetition(Repetition::REQUIRED) .with_logical_type(Some(LogicalType::String)) .build()?, ), + // 7. currency STRING REQUIRED Arc::new( Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) .with_repetition(Repetition::REQUIRED) .with_logical_type(Some(LogicalType::String)) .build()?, ), + // 8. period_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) Arc::new( Type::primitive_type_builder("period_known_at", PhysicalType::INT64) .with_repetition(Repetition::REQUIRED) .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) .build()?, ), + // 9-14. latest-period financial metrics DOUBLE OPTIONAL Arc::new( Type::primitive_type_builder("revenue", PhysicalType::DOUBLE) .with_repetition(Repetition::OPTIONAL) @@ -583,6 +500,7 @@ pub fn fundamentals_pit_parquet_schema() -> Result { .with_repetition(Repetition::OPTIONAL) .build()?, ), + // 15-17. TTM flow sums DOUBLE OPTIONAL Arc::new( Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) .with_repetition(Repetition::OPTIONAL) @@ -598,18 +516,21 @@ pub fn fundamentals_pit_parquet_schema() -> Result { .with_repetition(Repetition::OPTIONAL) .build()?, ), + // 18. ttm_period_end INT32 DATE OPTIONAL Arc::new( Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) .with_repetition(Repetition::OPTIONAL) .with_logical_type(Some(LogicalType::Date)) .build()?, ), + // 19. ttm_currency STRING OPTIONAL Arc::new( Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) .with_repetition(Repetition::OPTIONAL) .with_logical_type(Some(LogicalType::String)) .build()?, ), + // 20. ttm_has_estimated_lag BOOLEAN OPTIONAL Arc::new( Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) .with_repetition(Repetition::OPTIONAL) @@ -637,38 +558,40 @@ fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { ) } -#[inline] -fn compare_row_keys(a: &FundamentalsPitParquetRow, b: &FundamentalsPitParquetRow) -> Ordering { - a.listing_id - .cmp(&b.listing_id) - .then_with(|| a.effective_known_at_micros.cmp(&b.effective_known_at_micros)) -} - #[inline] fn check_opt_finite( row: &FundamentalsPitParquetRow, row_index: usize, field: &'static str, - value: Option, + val: Option, ) -> Result<(), ParquetFundamentalsError> { - if let Some(v) = value { - if !v.is_finite() { + if let Some(value) = val { + if !value.is_finite() { return Err(ParquetFundamentalsError::NonFiniteValue { row_index, listing_id: row.listing_id, effective_known_at_micros: row.effective_known_at_micros, field, - value: v, + value, }); } } Ok(()) } +#[inline] fn validate_row( row: &FundamentalsPitParquetRow, row_index: usize, -) -> Result { +) -> Result<(i32, &FundamentalsPitLatestPeriod), ParquetFundamentalsError> { + let Some(latest) = row.latest_period.as_ref() else { + return Err(ParquetFundamentalsError::EmptyPeriods { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + }); + }; + let year = partition_year_utc(row.effective_known_at_micros); if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { return Err(ParquetFundamentalsError::PartitionYearOutOfRange { @@ -681,30 +604,6 @@ fn validate_row( }); } - let (period_year, _, _) = epoch_days_to_ymd(row.period_end); - if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&period_year) { - return Err(ParquetFundamentalsError::PeriodEndOutOfRange { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - period_end: row.period_end, - year: period_year, - min_year: MIN_PARQUET_YEAR, - max_year: MAX_PARQUET_YEAR, - }); - } - - if row.period_known_at_micros > row.effective_known_at_micros { - return Err( - ParquetFundamentalsError::PeriodKnownAtAfterEffectiveKnownAt { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - period_known_at_micros: row.period_known_at_micros, - }, - ); - } - if row.known_at_source.trim().is_empty() { return Err(ParquetFundamentalsError::EmptyKnownAtSource { row_index, @@ -712,14 +611,24 @@ fn validate_row( effective_known_at_micros: row.effective_known_at_micros, }); } - if row.fiscal_period.trim().is_empty() { + if row.known_at_source.as_ref() != KNOWN_AT_SOURCE_FILING_TIMESTAMP + && row.known_at_source.as_ref() != KNOWN_AT_SOURCE_STATUTORY_LAG + { + return Err(ParquetFundamentalsError::InvalidKnownAtSource { + row_index, + listing_id: row.listing_id, + effective_known_at_micros: row.effective_known_at_micros, + value: row.known_at_source.to_string(), + }); + } + if latest.fiscal_period.trim().is_empty() { return Err(ParquetFundamentalsError::EmptyFiscalPeriod { row_index, listing_id: row.listing_id, effective_known_at_micros: row.effective_known_at_micros, }); } - if row.currency.trim().is_empty() { + if latest.currency.trim().is_empty() { return Err(ParquetFundamentalsError::EmptyCurrency { row_index, listing_id: row.listing_id, @@ -727,144 +636,54 @@ fn validate_row( }); } - check_opt_finite(row, row_index, "revenue", row.revenue)?; - check_opt_finite(row, row_index, "net_income", row.net_income)?; + check_opt_finite(row, row_index, "revenue", latest.fields.revenue)?; + check_opt_finite(row, row_index, "net_income", latest.fields.net_income)?; check_opt_finite( row, row_index, "operating_cash_flow", - row.operating_cash_flow, + latest.fields.operating_cash_flow, )?; - check_opt_finite(row, row_index, "total_assets", row.total_assets)?; - check_opt_finite(row, row_index, "total_equity", row.total_equity)?; - check_opt_finite(row, row_index, "shares_outstanding", row.shares_outstanding)?; - check_opt_finite(row, row_index, "ttm_revenue", row.ttm_revenue)?; - check_opt_finite(row, row_index, "ttm_net_income", row.ttm_net_income)?; + check_opt_finite(row, row_index, "total_assets", latest.fields.total_assets)?; + check_opt_finite(row, row_index, "total_equity", latest.fields.total_equity)?; check_opt_finite( row, row_index, - "ttm_operating_cash_flow", - row.ttm_operating_cash_flow, + "shares_outstanding", + latest.fields.shares_outstanding, )?; - let has_ttm_period_end = row.ttm_period_end.is_some(); - let has_ttm_currency = row.ttm_currency.is_some(); - let has_ttm_lag = row.ttm_has_estimated_lag.is_some(); - let all_ttm_meta = has_ttm_period_end && has_ttm_currency && has_ttm_lag; - let no_ttm_meta = !has_ttm_period_end && !has_ttm_currency && !has_ttm_lag; - let has_any_ttm_flow = row.ttm_revenue.is_some() - || row.ttm_net_income.is_some() - || row.ttm_operating_cash_flow.is_some(); - - if (!all_ttm_meta && !no_ttm_meta) || (no_ttm_meta && has_any_ttm_flow) { - return Err(ParquetFundamentalsError::InconsistentTtmMetadata { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - - if let Some(ttm_end) = row.ttm_period_end { - let (ttm_year, _, _) = epoch_days_to_ymd(ttm_end); - if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&ttm_year) { - return Err(ParquetFundamentalsError::TtmPeriodEndOutOfRange { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - ttm_period_end: ttm_end, - year: ttm_year, - min_year: MIN_PARQUET_YEAR, - max_year: MAX_PARQUET_YEAR, - }); - } - } - if let Some(ttm_ccy) = row.ttm_currency.as_deref() { - if ttm_ccy.trim().is_empty() { + if let Some(ttm) = row.ttm.as_ref() { + if ttm.currency.trim().is_empty() { return Err(ParquetFundamentalsError::EmptyTtmCurrency { row_index, listing_id: row.listing_id, effective_known_at_micros: row.effective_known_at_micros, }); } + check_opt_finite(row, row_index, "ttm_revenue", ttm.flows.revenue)?; + check_opt_finite(row, row_index, "ttm_net_income", ttm.flows.net_income)?; + check_opt_finite( + row, + row_index, + "ttm_operating_cash_flow", + ttm.flows.operating_cash_flow, + )?; } - Ok(year) + Ok((year, latest)) } -fn write_bool_col( - rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, - values: &[bool], -) -> Result<(), ParquetError> { - let mut col = match rg_writer.next_column()? { - Some(col) => col, +#[inline] +fn push_opt_f64(values: &mut Vec, defs: &mut Vec, val: Option) { + match val { + Some(v) => { + values.push(v); + defs.push(1); + } None => { - return Err(ParquetError::General( - "unexpected end of Parquet schema columns".to_string(), - )); + defs.push(0); } - }; - match col.untyped() { - ColumnWriter::BoolColumnWriter(typed) => { - typed.write_batch(values, None, None)?; - } - _ => { - return Err(ParquetError::General( - "expected BOOLEAN column writer".to_string(), - )); - } - } - col.close() -} - -fn write_optional_bool_col( - rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, - values: &[bool], - def_levels: &[i16], -) -> Result<(), ParquetError> { - let mut col = match rg_writer.next_column()? { - Some(col) => col, - None => { - return Err(ParquetError::General( - "unexpected end of Parquet schema columns".to_string(), - )); - } - }; - match col.untyped() { - ColumnWriter::BoolColumnWriter(typed) => { - typed.write_batch(values, Some(def_levels), None)?; - } - _ => { - return Err(ParquetError::General( - "expected BOOLEAN column writer".to_string(), - )); - } - } - col.close() -} - -#[derive(Default)] -struct OptionalF64Column { - values: Vec, - def_levels: Vec, -} - -impl OptionalF64Column { - #[inline] - fn push(&mut self, value: Option) { - match value { - Some(v) => { - self.values.push(v); - self.def_levels.push(1); - } - None => { - self.def_levels.push(0); - } - } - } - - fn clear(&mut self) { - self.values.clear(); - self.def_levels.clear(); } } @@ -881,22 +700,31 @@ struct RowGroupBuffer { currency_ids: Vec, currency_interner: StringInterner, period_known_at_micros: Vec, - revenue: OptionalF64Column, - net_income: OptionalF64Column, - operating_cash_flow: OptionalF64Column, - total_assets: OptionalF64Column, - total_equity: OptionalF64Column, - shares_outstanding: OptionalF64Column, - ttm_revenue: OptionalF64Column, - ttm_net_income: OptionalF64Column, - ttm_operating_cash_flow: OptionalF64Column, + revenue_values: Vec, + revenue_def: Vec, + net_income_values: Vec, + net_income_def: Vec, + operating_cash_flow_values: Vec, + operating_cash_flow_def: Vec, + total_assets_values: Vec, + total_assets_def: Vec, + total_equity_values: Vec, + total_equity_def: Vec, + shares_outstanding_values: Vec, + shares_outstanding_def: Vec, ttm_period_end_values: Vec, - ttm_period_end_defs: Vec, + ttm_period_end_def: Vec, ttm_currency_ids: Vec, - ttm_currency_defs: Vec, + ttm_currency_def: Vec, ttm_currency_interner: StringInterner, + ttm_revenue_values: Vec, + ttm_revenue_def: Vec, + ttm_net_income_values: Vec, + ttm_net_income_def: Vec, + ttm_operating_cash_flow_values: Vec, + ttm_operating_cash_flow_def: Vec, ttm_has_estimated_lag_values: Vec, - ttm_has_estimated_lag_defs: Vec, + ttm_has_estimated_lag_def: Vec, } impl RowGroupBuffer { @@ -905,7 +733,7 @@ impl RowGroupBuffer { self.listing_id.len() } - fn push(&mut self, row: &FundamentalsPitParquetRow) { + fn push(&mut self, row: &FundamentalsPitParquetRow, latest: &FundamentalsPitLatestPeriod) { self.listing_id.push(row.listing_id); self.effective_known_at_micros .push(row.effective_known_at_micros); @@ -914,53 +742,80 @@ impl RowGroupBuffer { .intern(row.known_at_source.as_ref()); self.known_at_source_ids.push(kas_id); self.has_estimated_lag.push(row.has_estimated_lag); - self.period_end.push(row.period_end); + self.period_end.push(latest.period_end); let fp_id = self .fiscal_period_interner - .intern(row.fiscal_period.as_ref()); + .intern(latest.fiscal_period.as_ref()); self.fiscal_period_ids.push(fp_id); - let ccy_id = self.currency_interner.intern(row.currency.as_ref()); - self.currency_ids.push(ccy_id); + let cur_id = self.currency_interner.intern(latest.currency.as_str()); + self.currency_ids.push(cur_id); self.period_known_at_micros - .push(row.period_known_at_micros); + .push(latest.period_known_at_micros); - self.revenue.push(row.revenue); - self.net_income.push(row.net_income); - self.operating_cash_flow.push(row.operating_cash_flow); - self.total_assets.push(row.total_assets); - self.total_equity.push(row.total_equity); - self.shares_outstanding.push(row.shares_outstanding); - self.ttm_revenue.push(row.ttm_revenue); - self.ttm_net_income.push(row.ttm_net_income); - self.ttm_operating_cash_flow - .push(row.ttm_operating_cash_flow); + push_opt_f64( + &mut self.revenue_values, + &mut self.revenue_def, + latest.fields.revenue, + ); + push_opt_f64( + &mut self.net_income_values, + &mut self.net_income_def, + latest.fields.net_income, + ); + push_opt_f64( + &mut self.operating_cash_flow_values, + &mut self.operating_cash_flow_def, + latest.fields.operating_cash_flow, + ); + push_opt_f64( + &mut self.total_assets_values, + &mut self.total_assets_def, + latest.fields.total_assets, + ); + push_opt_f64( + &mut self.total_equity_values, + &mut self.total_equity_def, + latest.fields.total_equity, + ); + push_opt_f64( + &mut self.shares_outstanding_values, + &mut self.shares_outstanding_def, + latest.fields.shares_outstanding, + ); - match row.ttm_period_end { - Some(day) => { - self.ttm_period_end_values.push(day); - self.ttm_period_end_defs.push(1); + match row.ttm.as_ref() { + Some(ttm) => { + self.ttm_period_end_values.push(ttm.ending_period_end); + self.ttm_period_end_def.push(1); + let ttm_cur_id = self.ttm_currency_interner.intern(ttm.currency.as_str()); + self.ttm_currency_ids.push(ttm_cur_id); + self.ttm_currency_def.push(1); + push_opt_f64( + &mut self.ttm_revenue_values, + &mut self.ttm_revenue_def, + ttm.flows.revenue, + ); + push_opt_f64( + &mut self.ttm_net_income_values, + &mut self.ttm_net_income_def, + ttm.flows.net_income, + ); + push_opt_f64( + &mut self.ttm_operating_cash_flow_values, + &mut self.ttm_operating_cash_flow_def, + ttm.flows.operating_cash_flow, + ); + self.ttm_has_estimated_lag_values + .push(ttm.has_estimated_lag); + self.ttm_has_estimated_lag_def.push(1); } None => { - self.ttm_period_end_defs.push(0); - } - } - match row.ttm_currency.as_deref() { - Some(ccy) => { - let id = self.ttm_currency_interner.intern(ccy); - self.ttm_currency_ids.push(id); - self.ttm_currency_defs.push(1); - } - None => { - self.ttm_currency_defs.push(0); - } - } - match row.ttm_has_estimated_lag { - Some(flag) => { - self.ttm_has_estimated_lag_values.push(flag); - self.ttm_has_estimated_lag_defs.push(1); - } - None => { - self.ttm_has_estimated_lag_defs.push(0); + self.ttm_period_end_def.push(0); + self.ttm_currency_def.push(0); + self.ttm_revenue_def.push(0); + self.ttm_net_income_def.push(0); + self.ttm_operating_cash_flow_def.push(0); + self.ttm_has_estimated_lag_def.push(0); } } } @@ -977,26 +832,35 @@ impl RowGroupBuffer { self.currency_ids.clear(); self.currency_interner.clear(); self.period_known_at_micros.clear(); - self.revenue.clear(); - self.net_income.clear(); - self.operating_cash_flow.clear(); - self.total_assets.clear(); - self.total_equity.clear(); - self.shares_outstanding.clear(); - self.ttm_revenue.clear(); - self.ttm_net_income.clear(); - self.ttm_operating_cash_flow.clear(); + self.revenue_values.clear(); + self.revenue_def.clear(); + self.net_income_values.clear(); + self.net_income_def.clear(); + self.operating_cash_flow_values.clear(); + self.operating_cash_flow_def.clear(); + self.total_assets_values.clear(); + self.total_assets_def.clear(); + self.total_equity_values.clear(); + self.total_equity_def.clear(); + self.shares_outstanding_values.clear(); + self.shares_outstanding_def.clear(); self.ttm_period_end_values.clear(); - self.ttm_period_end_defs.clear(); + self.ttm_period_end_def.clear(); self.ttm_currency_ids.clear(); - self.ttm_currency_defs.clear(); + self.ttm_currency_def.clear(); self.ttm_currency_interner.clear(); + self.ttm_revenue_values.clear(); + self.ttm_revenue_def.clear(); + self.ttm_net_income_values.clear(); + self.ttm_net_income_def.clear(); + self.ttm_operating_cash_flow_values.clear(); + self.ttm_operating_cash_flow_def.clear(); self.ttm_has_estimated_lag_values.clear(); - self.ttm_has_estimated_lag_defs.clear(); + self.ttm_has_estimated_lag_def.clear(); } } -struct PartitionWriter { +struct YearWriter { tmp_path: PathBuf, final_path: PathBuf, writer: SerializedFileWriter>, @@ -1005,7 +869,7 @@ struct PartitionWriter { row_groups_written: usize, } -impl PartitionWriter { +impl YearWriter { fn open( dataset_dir: &Path, year: i32, @@ -1071,7 +935,7 @@ impl PartitionWriter { ) .map_err(map_pq)?; // 4. has_estimated_lag (BOOLEAN, REQUIRED) - write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag).map_err(map_pq)?; + write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag, None).map_err(map_pq)?; // 5. period_end (INT32, REQUIRED, DATE) write_i32_col(&mut rg_writer, &self.buf.period_end).map_err(map_pq)?; // 6. fiscal_period (BYTE_ARRAY, REQUIRED, STRING) @@ -1095,87 +959,87 @@ impl PartitionWriter { // 9. revenue (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.revenue.values, - &self.buf.revenue.def_levels, + &self.buf.revenue_values, + &self.buf.revenue_def, ) .map_err(map_pq)?; // 10. net_income (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.net_income.values, - &self.buf.net_income.def_levels, + &self.buf.net_income_values, + &self.buf.net_income_def, ) .map_err(map_pq)?; // 11. operating_cash_flow (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.operating_cash_flow.values, - &self.buf.operating_cash_flow.def_levels, + &self.buf.operating_cash_flow_values, + &self.buf.operating_cash_flow_def, ) .map_err(map_pq)?; // 12. total_assets (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.total_assets.values, - &self.buf.total_assets.def_levels, + &self.buf.total_assets_values, + &self.buf.total_assets_def, ) .map_err(map_pq)?; // 13. total_equity (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.total_equity.values, - &self.buf.total_equity.def_levels, + &self.buf.total_equity_values, + &self.buf.total_equity_def, ) .map_err(map_pq)?; // 14. shares_outstanding (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.shares_outstanding.values, - &self.buf.shares_outstanding.def_levels, + &self.buf.shares_outstanding_values, + &self.buf.shares_outstanding_def, ) .map_err(map_pq)?; // 15. ttm_revenue (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.ttm_revenue.values, - &self.buf.ttm_revenue.def_levels, + &self.buf.ttm_revenue_values, + &self.buf.ttm_revenue_def, ) .map_err(map_pq)?; // 16. ttm_net_income (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.ttm_net_income.values, - &self.buf.ttm_net_income.def_levels, + &self.buf.ttm_net_income_values, + &self.buf.ttm_net_income_def, ) .map_err(map_pq)?; // 17. ttm_operating_cash_flow (DOUBLE, OPTIONAL) write_optional_f64_col( &mut rg_writer, - &self.buf.ttm_operating_cash_flow.values, - &self.buf.ttm_operating_cash_flow.def_levels, + &self.buf.ttm_operating_cash_flow_values, + &self.buf.ttm_operating_cash_flow_def, ) .map_err(map_pq)?; // 18. ttm_period_end (INT32, OPTIONAL, DATE) write_optional_i32_col( &mut rg_writer, &self.buf.ttm_period_end_values, - &self.buf.ttm_period_end_defs, + &self.buf.ttm_period_end_def, ) .map_err(map_pq)?; // 19. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) write_optional_interned_str_col( &mut rg_writer, &self.buf.ttm_currency_ids, - &self.buf.ttm_currency_defs, + &self.buf.ttm_currency_def, &self.buf.ttm_currency_interner, scratch, ) .map_err(map_pq)?; // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) - write_optional_bool_col( + write_bool_col( &mut rg_writer, &self.buf.ttm_has_estimated_lag_values, - &self.buf.ttm_has_estimated_lag_defs, + Some(&self.buf.ttm_has_estimated_lag_def), ) .map_err(map_pq)?; @@ -1190,7 +1054,7 @@ impl PartitionWriter { fn finish_and_sync( mut self, scratch: &mut Vec, - ) -> Result { + ) -> Result { self.flush_row_group(scratch)?; let mut buf_writer = @@ -1226,7 +1090,7 @@ impl PartitionWriter { .len(); drop(file); - Ok(SyncedPartitionFile { + Ok(SyncedYearFile { tmp_path: self.tmp_path, final_path: self.final_path, rows_written: self.rows_written, @@ -1236,7 +1100,7 @@ impl PartitionWriter { } } -struct SyncedPartitionFile { +struct SyncedYearFile { tmp_path: PathBuf, final_path: PathBuf, rows_written: usize, @@ -1264,17 +1128,28 @@ fn finish_with_rollback( } } -/// Streams strictly ascending `fundamentals_pit` rows into year-partitioned Zstd Parquet files at -/// `/fundamentals_pit/year=YYYY/part.parquet`, partitioned by the UTC year of -/// `effective_known_at`. +/// Streams strictly ascending `(listing_id, effective_known_at)` snapshot rows into +/// year-partitioned Zstd Parquet files at `/fundamentals_pit/year=YYYY/part.parquet`, +/// partitioned by the UTC year of `effective_known_at`. /// /// # Sort Order & Validation -/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at_micros)`. -/// Out-of-order rows, duplicates, non-finite numeric fields, out-of-range dates/years, -/// `period_known_at_micros > effective_known_at_micros`, empty required strings, or inconsistent -/// TTM metadata return typed [`ParquetFundamentalsError`] variants with nothing published. Empty -/// input returns `Ok(FundamentalsPitWriteStats::default())` without creating +/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at)`. +/// Out-of-order rows, duplicate keys, snapshots with empty `periods`, partition years outside +/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, empty string metadata fields, and non-finite numeric +/// values return typed [`ParquetFundamentalsError`] variants with nothing published. Empty input +/// returns `Ok(FundamentalsPitWriteStats::default())` without creating /// `/fundamentals_pit` or touching pre-existing partitions. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/fundamentals_pit` directory are serialized via +/// an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year +/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), +/// flushed, and `sync_all`'d before publication. Pre-existing `part.parquet` files are backed up +/// in place (hard link with exclusive copy fallback) so the live path remains readable until +/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before +/// owned staging files are unlinked, replaced partitions are restored from backup, and newly +/// published partitions are removed (reporting rollback errors via +/// [`ParquetFundamentalsError::RollbackFailed`]). pub fn write_fundamentals_pit_dataset( out_dir: P, rows: I, @@ -1299,37 +1174,12 @@ fn write_fundamentals_pit_dataset_with_hooks( rows: I, options: FundamentalsPitWriteOptions, lock_timeout: Duration, - on_after_backup: F, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, - F: FnMut(i32, &Path, Option<&Path>), -{ - write_fundamentals_pit_dataset_with_lock_and_backup_hooks( - out_dir, - rows, - options, - lock_timeout, - || {}, - on_after_backup, - ) -} - -fn write_fundamentals_pit_dataset_with_lock_and_backup_hooks( - out_dir: P, - rows: I, - options: FundamentalsPitWriteOptions, - lock_timeout: Duration, - mut on_lock_contended: G, mut on_after_backup: F, ) -> Result where P: AsRef, I: IntoIterator, R: Borrow, - G: FnMut(), F: FnMut(i32, &Path, Option<&Path>), { if options.row_group_rows == 0 { @@ -1362,30 +1212,24 @@ where })?; let dataset_mu = dataset_mutex(&dataset_dir); - let _in_process_guard = match dataset_mu.try_lock() { - Ok(guard) => guard, - Err(std::sync::TryLockError::Poisoned(err)) => err.into_inner(), - Err(std::sync::TryLockError::WouldBlock) => { - on_lock_contended(); - dataset_mu.lock().unwrap_or_else(|err| err.into_inner()) - } - }; + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; let run_id = next_run_id(); - // Declared before `writers` so reverse drop order closes file handles before unlinking `.tmp`. + // Declared before `writers` so Rust's reverse drop order closes all Parquet file handles + // before unlinking owned `.tmp` staging files on error or panic unwind. let mut staging_guards: BTreeMap = BTreeMap::new(); - let mut writers: BTreeMap = BTreeMap::new(); + let mut writers: BTreeMap = BTreeMap::new(); let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - let synced_files: Vec<(i32, SyncedPartitionFile)> = { - let mut prev_item: Option = None; + let synced_files: Vec<(i32, SyncedYearFile)> = { + let mut prev_key: Option<(i32, i64)> = None; for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { let row = item.borrow(); - if let Some(prev) = prev_item.as_ref() { - let prev_row = prev.borrow(); - match compare_row_keys(row, prev_row) { + let key = (row.listing_id, row.effective_known_at_micros); + if let Some((prev_listing_id, prev_effective_known_at_micros)) = prev_key { + match key.cmp(&(prev_listing_id, prev_effective_known_at_micros)) { Ordering::Equal => { return Err(ParquetFundamentalsError::DuplicateRow { row_index, @@ -1396,8 +1240,8 @@ where Ordering::Less => { return Err(ParquetFundamentalsError::UnsortedInput { row_index, - prev_listing_id: prev_row.listing_id, - prev_effective_known_at_micros: prev_row.effective_known_at_micros, + prev_listing_id, + prev_effective_known_at_micros, listing_id: row.listing_id, effective_known_at_micros: row.effective_known_at_micros, }); @@ -1405,12 +1249,13 @@ where Ordering::Greater => {} } } - let year = validate_row(row, row_index)?; - let pw = match writers.entry(year) { + let (year, latest) = validate_row(row, row_index)?; + + let yw = match writers.entry(year) { std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), std::collections::btree_map::Entry::Vacant(entry) => { - let opened = PartitionWriter::open( + let opened = YearWriter::open( &dataset_dir, year, &run_id, @@ -1422,18 +1267,17 @@ where } }; - pw.buf.push(row); - if pw.buf.len() == options.row_group_rows { - pw.flush_row_group(&mut scratch)?; + yw.buf.push(row, latest); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; } - prev_item = Some(item); + prev_key = Some(key); } let mut synced = Vec::with_capacity(writers.len()); - let drained: Vec<(i32, PartitionWriter)> = - std::mem::take(&mut writers).into_iter().collect(); - for (year, pw) in drained { - let file = pw.finish_and_sync(&mut scratch)?; + let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); + for (year, yw) in drained { + let file = yw.finish_and_sync(&mut scratch)?; synced.push((year, file)); } synced @@ -1451,6 +1295,8 @@ where } } } + // Directory occupying final_path: leave it in place so the rename below fails + // cleanly and triggers rollback of all earlier partitions. Ok(_) => None, Err(err) if err.kind() == io::ErrorKind::NotFound => None, Err(source) => { diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs index eedf655e..922f4435 100644 --- a/tools/curate-etl/src/parquet_fundamentals_tests.rs +++ b/tools/curate-etl/src/parquet_fundamentals_tests.rs @@ -1,5 +1,5 @@ -//! Schema, round-trip, PIT restatement replay, partitioning, validation, and atomic-rollback -//! tests for `parquet_fundamentals`. +//! Round-trip, schema, partitioning, validation, and atomic rollback tests for +//! `parquet_fundamentals`. use std::borrow::Cow; use std::collections::BTreeMap; @@ -14,19 +14,18 @@ use parquet::column::reader::ColumnReader; use parquet::file::reader::{FileReader, SerializedFileReader}; use super::{ - fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, - write_fundamentals_pit_dataset_with_hooks, FundamentalsPitParquetRow, - FundamentalsPitWriteOptions, FundamentalsPitWriteStats, ParquetFundamentalsError, - DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, + fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, + FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, + ParquetFundamentalsError, DEFAULT_ZSTD_LEVEL, }; use crate::events::{ partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; use crate::fundamentals::{ build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, - FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, StatutoryLagVenue, + FundamentalsFields, FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, + StatutoryLagVenue, TtmFlowFields, }; -use crate::parquet_publish::DEFAULT_LOCK_TIMEOUT; use crate::split::ymd_to_epoch_days; static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); @@ -58,20 +57,12 @@ impl Drop for TempDirGuard { } } -fn day(year: i32, month: u32, day: u32) -> i32 { - ymd_to_epoch_days(year, month, day).expect("valid test date") +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") } -fn utc_micros( - year: i32, - month: u32, - day_of_month: u32, - hour: u8, - minute: u8, - second: u8, - micro: i64, -) -> i64 { - let epoch_day = day(year, month, day_of_month); +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8, micro: i64) -> i64 { + let epoch_day = day(y, m, d); let secs = i64::from(epoch_day) * 86_400 + i64::from(hour) * 3_600 + i64::from(minute) * 60 @@ -79,32 +70,59 @@ fn utc_micros( secs * 1_000_000 + micro } -fn assert_no_transient_files(dir: &Path) { - if !dir.exists() { - return; +fn filing(key: i32, timefiled: &str, form_type: &str) -> QmFiling { + QmFiling { + key, + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: None, + url: None, } - fn walk(dir: &Path) { - for entry in fs::read_dir(dir).expect("read_dir") { - let path = entry.expect("dir entry").path(); - if path.is_dir() { - walk(&path); - } else { - let name = path - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or_default(); - assert!( - !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", - "unexpected transient file left behind: {}", - path.display() - ); - } - } - } - walk(dir); } -fn read_parquet_rows(path: &Path) -> Vec { +fn obs( + key: i32, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: &str, + report_date: Option, + fields: FundamentalsFields, +) -> FinancialObservation { + FinancialObservation { + key, + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + } +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedFundamentalsPitRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_has_estimated_lag: Option, +} + +fn read_parquet_rows(path: &Path) -> Vec { let file = File::open(path).expect("open parquet file"); let reader = SerializedFileReader::new(file).expect("open parquet reader"); let meta = reader.metadata(); @@ -114,7 +132,7 @@ fn read_parquet_rows(path: &Path) -> Vec { let rg_rows = meta.row_group(rg_idx).num_rows() as usize; let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - let read_i32_col = |col_idx: usize| -> Vec { + let read_req_i32 = |col_idx: usize| -> Vec { let mut vals = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::Int32ColumnReader(mut typed) => { @@ -122,18 +140,18 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i32 records"); - assert!(n > 0, "unexpected short read in INT32 column {col_idx}"); + .expect("read req i32"); + assert!(n > 0); read += n; } } - _ => panic!("expected INT32 column at index {col_idx}"), + _ => panic!("expected INT32 at col {col_idx}"), } vals }; - let read_opt_i32_col = |col_idx: usize| -> Vec> { - let mut vals = Vec::new(); + let read_opt_i32 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); let mut defs = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::Int32ColumnReader(mut typed) => { @@ -141,20 +159,29 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read optional i32 records"); - assert!(n > 0, "unexpected short read in opt INT32 column {col_idx}"); + .expect("read opt i32"); + assert!(n > 0); read += n; } } - _ => panic!("expected optional INT32 column at index {col_idx}"), + _ => panic!("expected INT32 at col {col_idx}"), } - let mut val_iter = vals.into_iter(); + let mut vi = 0usize; defs.into_iter() - .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) .collect() }; - let read_i64_col = |col_idx: usize| -> Vec { + let read_req_i64 = |col_idx: usize| -> Vec { let mut vals = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::Int64ColumnReader(mut typed) => { @@ -162,17 +189,17 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, None, None, &mut vals) - .expect("read i64 records"); - assert!(n > 0, "unexpected short read in INT64 column {col_idx}"); + .expect("read req i64"); + assert!(n > 0); read += n; } } - _ => panic!("expected INT64 column at index {col_idx}"), + _ => panic!("expected INT64 at col {col_idx}"), } vals }; - let read_bool_col = |col_idx: usize| -> Vec { + let read_req_bool = |col_idx: usize| -> Vec { let mut vals = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::BoolColumnReader(mut typed) => { @@ -180,18 +207,18 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, None, None, &mut vals) - .expect("read bool records"); - assert!(n > 0, "unexpected short read in BOOLEAN column {col_idx}"); + .expect("read req bool"); + assert!(n > 0); read += n; } } - _ => panic!("expected BOOLEAN column at index {col_idx}"), + _ => panic!("expected BOOLEAN at col {col_idx}"), } vals }; - let read_opt_bool_col = |col_idx: usize| -> Vec> { - let mut vals = Vec::new(); + let read_opt_bool = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); let mut defs = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::BoolColumnReader(mut typed) => { @@ -199,21 +226,30 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read optional bool records"); - assert!(n > 0, "unexpected short read in opt BOOLEAN column {col_idx}"); + .expect("read opt bool"); + assert!(n > 0); read += n; } } - _ => panic!("expected optional BOOLEAN column at index {col_idx}"), + _ => panic!("expected BOOLEAN at col {col_idx}"), } - let mut val_iter = vals.into_iter(); + let mut vi = 0usize; defs.into_iter() - .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) .collect() }; - let read_opt_f64_col = |col_idx: usize| -> Vec> { - let mut vals = Vec::new(); + let read_opt_f64 = |col_idx: usize| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); let mut defs = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::DoubleColumnReader(mut typed) => { @@ -221,20 +257,29 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read optional f64 records"); - assert!(n > 0, "unexpected short read in DOUBLE column {col_idx}"); + .expect("read opt f64"); + assert!(n > 0); read += n; } } - _ => panic!("expected DOUBLE column at index {col_idx}"), + _ => panic!("expected DOUBLE at col {col_idx}"), } - let mut val_iter = vals.into_iter(); + let mut vi = 0usize; defs.into_iter() - .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) .collect() }; - let read_str_col = |col_idx: usize| -> Vec { + let read_req_str = |col_idx: usize| -> Vec { let mut raw = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::ByteArrayColumnReader(mut typed) => { @@ -242,20 +287,20 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, None, None, &mut raw) - .expect("read byte_array records"); - assert!(n > 0, "unexpected short read in BYTE_ARRAY column {col_idx}"); + .expect("read req str"); + assert!(n > 0); read += n; } } - _ => panic!("expected BYTE_ARRAY column at index {col_idx}"), + _ => panic!("expected BYTE_ARRAY at col {col_idx}"), } raw.iter() .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) .collect() }; - let read_opt_str_col = |col_idx: usize| -> Vec> { - let mut raw = Vec::new(); + let read_opt_str = |col_idx: usize| -> Vec> { + let mut raw = Vec::with_capacity(rg_rows); let mut defs = Vec::with_capacity(rg_rows); match rg_reader.get_column_reader(col_idx).expect("col reader") { ColumnReader::ByteArrayColumnReader(mut typed) => { @@ -263,58 +308,61 @@ fn read_parquet_rows(path: &Path) -> Vec { while read < rg_rows { let (n, _, _) = typed .read_records(rg_rows - read, Some(&mut defs), None, &mut raw) - .expect("read optional byte_array records"); - assert!( - n > 0, - "unexpected short read in opt BYTE_ARRAY column {col_idx}" - ); + .expect("read opt str"); + assert!(n > 0); read += n; } } - _ => panic!("expected optional BYTE_ARRAY column at index {col_idx}"), + _ => panic!("expected BYTE_ARRAY at col {col_idx}"), } - let mut val_iter = raw.into_iter().map(|b| { - std::str::from_utf8(b.data()) - .expect("valid utf8") - .to_string() - }); + let mut vi = 0usize; defs.into_iter() - .map(|d| if d == 1 { Some(val_iter.next().unwrap()) } else { None }) + .map(|d| { + if d == 1 { + let s = std::str::from_utf8(raw[vi].data()) + .expect("valid utf8") + .to_string(); + vi += 1; + Some(s) + } else { + assert_eq!(d, 0); + None + } + }) .collect() }; - // Positional 20-column decode matching fundamentals_pit_parquet_schema(). - let listing_ids = read_i32_col(0); - let effective_known_at = read_i64_col(1); - let known_at_source = read_str_col(2); - let has_estimated_lag = read_bool_col(3); - let period_end = read_i32_col(4); - let fiscal_period = read_str_col(5); - let currency = read_str_col(6); - let period_known_at = read_i64_col(7); - let revenue = read_opt_f64_col(8); - let net_income = read_opt_f64_col(9); - let operating_cash_flow = read_opt_f64_col(10); - let total_assets = read_opt_f64_col(11); - let total_equity = read_opt_f64_col(12); - let shares_outstanding = read_opt_f64_col(13); - let ttm_revenue = read_opt_f64_col(14); - let ttm_net_income = read_opt_f64_col(15); - let ttm_operating_cash_flow = read_opt_f64_col(16); - let ttm_period_end = read_opt_i32_col(17); - let ttm_currency = read_opt_str_col(18); - let ttm_has_estimated_lag = read_opt_bool_col(19); + let listing_id = read_req_i32(0); + let effective_known_at = read_req_i64(1); + let known_at_source = read_req_str(2); + let has_estimated_lag = read_req_bool(3); + let period_end = read_req_i32(4); + let fiscal_period = read_req_str(5); + let currency = read_req_str(6); + let period_known_at = read_req_i64(7); + let revenue = read_opt_f64(8); + let net_income = read_opt_f64(9); + let operating_cash_flow = read_opt_f64(10); + let total_assets = read_opt_f64(11); + let total_equity = read_opt_f64(12); + let shares_outstanding = read_opt_f64(13); + let ttm_revenue = read_opt_f64(14); + let ttm_net_income = read_opt_f64(15); + let ttm_operating_cash_flow = read_opt_f64(16); + let ttm_period_end = read_opt_i32(17); + let ttm_currency = read_opt_str(18); + let ttm_has_estimated_lag = read_opt_bool(19); for i in 0..rg_rows { - out.push(FundamentalsPitParquetRow { - listing_id: listing_ids[i], - effective_known_at_micros: effective_known_at[i], - known_at_source: Cow::Owned(known_at_source[i].clone()), + out.push(DecodedFundamentalsPitRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), has_estimated_lag: has_estimated_lag[i], period_end: period_end[i], - fiscal_period: Cow::Owned(fiscal_period[i].clone()), - currency: Cow::Owned(currency[i].clone()), - period_known_at_micros: period_known_at[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: period_known_at[i], revenue: revenue[i], net_income: net_income[i], operating_cash_flow: operating_cash_flow[i], @@ -325,7 +373,7 @@ fn read_parquet_rows(path: &Path) -> Vec { ttm_net_income: ttm_net_income[i], ttm_operating_cash_flow: ttm_operating_cash_flow[i], ttm_period_end: ttm_period_end[i], - ttm_currency: ttm_currency[i].clone().map(Cow::Owned), + ttm_currency: ttm_currency[i].clone(), ttm_has_estimated_lag: ttm_has_estimated_lag[i], }); } @@ -334,8 +382,8 @@ fn read_parquet_rows(path: &Path) -> Vec { out } -fn assert_row_matches_snapshot_bit_for_bit( - actual: &FundamentalsPitParquetRow, +fn assert_decoded_matches_snapshot_bit_for_bit( + actual: &DecodedFundamentalsPitRow, snapshot: &FundamentalsSnapshot, ) { let latest = snapshot @@ -344,15 +392,15 @@ fn assert_row_matches_snapshot_bit_for_bit( .expect("snapshot must have at least one period"); assert_eq!(actual.listing_id, snapshot.key); assert_eq!( - actual.effective_known_at_micros, + actual.effective_known_at, snapshot.effective_known_at_utc_micros ); - assert_eq!(actual.known_at_source.as_ref(), snapshot.known_at_source); + assert_eq!(actual.known_at_source, snapshot.known_at_source); assert_eq!(actual.has_estimated_lag, snapshot.has_estimated_lag); assert_eq!(actual.period_end, latest.period_end); - assert_eq!(actual.fiscal_period.as_ref(), latest.fiscal_period.as_str()); - assert_eq!(actual.currency.as_ref(), latest.currency.as_str()); - assert_eq!(actual.period_known_at_micros, latest.known_at_utc_micros); + assert_eq!(actual.fiscal_period, latest.fiscal_period.as_str()); + assert_eq!(actual.currency, latest.currency); + assert_eq!(actual.period_known_at, latest.known_at_utc_micros); assert_eq!( actual.revenue.map(f64::to_bits), @@ -408,87 +456,175 @@ fn assert_row_matches_snapshot_bit_for_bit( } } -fn assert_row_bit_eq(a: &FundamentalsPitParquetRow, b: &FundamentalsPitParquetRow) { - assert_eq!(a.listing_id, b.listing_id); - assert_eq!(a.effective_known_at_micros, b.effective_known_at_micros); - assert_eq!(a.known_at_source, b.known_at_source); - assert_eq!(a.has_estimated_lag, b.has_estimated_lag); - assert_eq!(a.period_end, b.period_end); - assert_eq!(a.fiscal_period, b.fiscal_period); - assert_eq!(a.currency, b.currency); - assert_eq!(a.period_known_at_micros, b.period_known_at_micros); - assert_eq!(a.revenue.map(f64::to_bits), b.revenue.map(f64::to_bits)); - assert_eq!( - a.net_income.map(f64::to_bits), - b.net_income.map(f64::to_bits) - ); - assert_eq!( - a.operating_cash_flow.map(f64::to_bits), - b.operating_cash_flow.map(f64::to_bits) - ); - assert_eq!( - a.total_assets.map(f64::to_bits), - b.total_assets.map(f64::to_bits) - ); - assert_eq!( - a.total_equity.map(f64::to_bits), - b.total_equity.map(f64::to_bits) - ); - assert_eq!( - a.shares_outstanding.map(f64::to_bits), - b.shares_outstanding.map(f64::to_bits) - ); - assert_eq!( - a.ttm_revenue.map(f64::to_bits), - b.ttm_revenue.map(f64::to_bits) - ); - assert_eq!( - a.ttm_net_income.map(f64::to_bits), - b.ttm_net_income.map(f64::to_bits) - ); - assert_eq!( - a.ttm_operating_cash_flow.map(f64::to_bits), - b.ttm_operating_cash_flow.map(f64::to_bits) - ); - assert_eq!(a.ttm_period_end, b.ttm_period_end); - assert_eq!(a.ttm_currency, b.ttm_currency); - assert_eq!(a.ttm_has_estimated_lag, b.ttm_has_estimated_lag); +fn assert_no_transient_files(dir: &Path) { + if !dir.exists() { + return; + } + fn walk(dir: &Path) { + for entry in fs::read_dir(dir).expect("read_dir") { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(&path); + } else { + let name = path + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or_default(); + assert!( + !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", + "unexpected transient file left behind: {}", + path.display() + ); + } + } + } + walk(dir); } -fn sample_row(listing_id: i32, effective_known_at_micros: i64) -> FundamentalsPitParquetRow { - FundamentalsPitParquetRow { +fn make_row( + listing_id: i32, + effective_known_at_micros: i64, + period_end: i32, + revenue: Option, + ttm: Option, +) -> FundamentalsPitParquetRow { + FundamentalsPitParquetRow::new( listing_id, effective_known_at_micros, - known_at_source: Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - has_estimated_lag: false, - period_end: day(2024, 3, 31), - fiscal_period: Cow::Borrowed("Q"), - currency: Cow::Borrowed("USD"), - period_known_at_micros: effective_known_at_micros, - revenue: Some(100.0), - net_income: Some(15.0), - operating_cash_flow: Some(22.0), - total_assets: Some(500.0), - total_equity: Some(250.0), - shares_outstanding: Some(10_000_000.0), - ttm_revenue: Some(400.0), - ttm_net_income: Some(60.0), - ttm_operating_cash_flow: Some(88.0), - ttm_period_end: Some(day(2024, 3, 31)), - ttm_currency: Some(Cow::Borrowed("USD")), - ttm_has_estimated_lag: Some(false), - } + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end, + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: effective_known_at_micros, + fields: FundamentalsFields { + revenue, + net_income: revenue.map(|r| r * 0.1), + operating_cash_flow: revenue.map(|r| r * 0.15), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + }, + ttm, + ) } #[test] -fn schema_matches_contract_columns_types_nullability_and_order() { - let schema = fundamentals_pit_parquet_schema().expect("build schema"); - assert_eq!(schema.name(), "fundamentals_pit"); +fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { + let tmp = TempDirGuard::new("schema"); - let fields = schema.get_fields(); + // 1) Row with no TTM (all 6 ttm_* columns must be null) and some null latest-period fields. + let row_no_ttm = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 5, 1, 20, 15, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: utc_micros(2024, 5, 1, 20, 15, 0, 0), + fields: FundamentalsFields { + revenue: Some(100.0), + net_income: None, + operating_cash_flow: Some(15.0), + total_assets: None, + total_equity: Some(220.0), + shares_outstanding: None, + }, + }, + None, + ); + + // 2) Row with TTM where ttm_has_estimated_lag = Some(false) and all flows present. + let row_ttm_false = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 8, 1, 20, 15, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 6, 30), + fiscal_period: Cow::Borrowed("Q"), + currency: "USD".to_string(), + period_known_at_micros: utc_micros(2024, 8, 1, 20, 15, 0, 0), + fields: FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(18.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), + }, + }, + Some(FundamentalsTtm { + ending_period_end: day(2024, 6, 30), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(370.0), + net_income: Some(37.0), + operating_cash_flow: Some(55.0), + }, + has_estimated_lag: false, + }), + ); + + // 3) Row with TTM where ttm_has_estimated_lag = Some(true), FY latest period, and partial null TTM flow. + let row_ttm_true = FundamentalsPitParquetRow::new( + 10, + utc_micros(2024, 11, 15, 21, 5, 0, 0), + Cow::Borrowed(KNOWN_AT_SOURCE_STATUTORY_LAG), + true, + FundamentalsPitLatestPeriod { + period_end: day(2024, 9, 30), + fiscal_period: Cow::Borrowed("FY"), + currency: "CAD".to_string(), + period_known_at_micros: utc_micros(2024, 11, 15, 21, 5, 0, 0), + fields: FundamentalsFields { + revenue: Some(450.0), + net_income: Some(45.0), + operating_cash_flow: None, + total_assets: Some(600.0), + total_equity: Some(250.0), + shares_outstanding: Some(105.0), + }, + }, + Some(FundamentalsTtm { + ending_period_end: day(2024, 9, 30), + currency: "CAD".to_string(), + flows: TtmFlowFields { + revenue: Some(450.0), + net_income: None, + operating_cash_flow: Some(60.0), + }, + has_estimated_lag: true, + }), + ); + + let rows = vec![row_no_ttm, row_ttm_false, row_ttm_true]; + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write schema test dataset"); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 3)])); + + let path = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let reader = SerializedFileReader::new(File::open(&path).expect("open parquet")) + .expect("open parquet reader"); + let meta = reader.metadata(); + let expected_schema = fundamentals_pit_parquet_schema().expect("schema"); + assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); + assert_eq!(expected_schema.name(), "fundamentals_pit"); + + let fields = meta.file_metadata().schema().get_fields(); assert_eq!(fields.len(), 20); - let expected: [( + let expected_cols: [( &str, PhysicalType, Repetition, @@ -637,7 +773,7 @@ fn schema_matches_contract_columns_types_nullability_and_order() { ), ]; - for (idx, (name, phys, rep, logical, converted)) in expected.into_iter().enumerate() { + for (idx, (name, phys, rep, logical, converted)) in expected_cols.into_iter().enumerate() { let field = &fields[idx]; assert_eq!(field.name(), name, "column {idx} name"); assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); @@ -657,11 +793,62 @@ fn schema_matches_contract_columns_types_nullability_and_order() { "column {idx} converted type" ); } + + for rg in meta.row_groups() { + for col in rg.columns() { + assert!( + matches!(col.compression(), Compression::ZSTD(_)), + "column {} must use ZSTD compression", + col.column_path() + ); + } + } + + let decoded = read_parquet_rows(&path); + assert_eq!(decoded.len(), 3); + + // Row 0: no TTM -> all 6 ttm_* columns are None. + assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!decoded[0].has_estimated_lag); + assert_eq!(decoded[0].revenue, Some(100.0)); + assert_eq!(decoded[0].net_income, None); + assert_eq!(decoded[0].operating_cash_flow, Some(15.0)); + assert_eq!(decoded[0].total_assets, None); + assert_eq!(decoded[0].total_equity, Some(220.0)); + assert_eq!(decoded[0].shares_outstanding, None); + assert_eq!(decoded[0].ttm_revenue, None); + assert_eq!(decoded[0].ttm_net_income, None); + assert_eq!(decoded[0].ttm_operating_cash_flow, None); + assert_eq!(decoded[0].ttm_period_end, None); + assert_eq!(decoded[0].ttm_currency, None); + assert_eq!(decoded[0].ttm_has_estimated_lag, None); + + // Row 1: ttm_has_estimated_lag = Some(false) + assert_eq!(decoded[1].ttm_revenue, Some(370.0)); + assert_eq!(decoded[1].ttm_net_income, Some(37.0)); + assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0)); + assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); + assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); + assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false)); + + // Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source. + assert_eq!(decoded[2].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(decoded[2].has_estimated_lag); + assert_eq!(decoded[2].fiscal_period, "FY"); + assert_eq!(decoded[2].currency, "CAD"); + assert_eq!(decoded[2].ttm_revenue, Some(450.0)); + assert_eq!(decoded[2].ttm_net_income, None); + assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0)); + assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); + assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); + assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true)); + + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } #[test] fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero() { - let tmp = TempDirGuard::new("builder-roundtrip"); + let tmp = TempDirGuard::new("builder-roundtrip-bits"); let venues = BTreeMap::from([ (10_i32, StatutoryLagVenue::UsTsx), @@ -669,16 +856,33 @@ fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero( ]); let observations = vec![ - // Listing 10: 4 consecutive quarters (Q2 2023 .. Q1 2024), with distinct flow values - // and a missing operating_cash_flow in Q4 2023 so TTM operating_cash_flow is None while - // ttm_revenue and ttm_net_income are populated. - FinancialObservation { - key: 10_i32, - period_end: day(2023, 6, 30), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2023, 8, 2)), - fields: FundamentalsFields { + // Listing 10: 5 consecutive quarters (Q1 2023 .. Q1 2024). + // Q1..Q4 2023 all have distinct non-null flow values so Q4 2023's snapshot carries + // three distinct non-null TTM flows (catching any positional TTM column transposition). + // Q1 2024 omits operating_cash_flow so its snapshot has ttm_operating_cash_flow = None + // while ttm_revenue and ttm_net_income remain populated and distinct. + obs( + 10, + day(2023, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 5, 2)), + FundamentalsFields { + revenue: Some(95.5), + net_income: Some(9.25), + operating_cash_flow: Some(17.75), + total_assets: Some(960.0), + total_equity: Some(380.0), + shares_outstanding: Some(49_500_000.0), + }, + ), + obs( + 10, + day(2023, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 8, 2)), + FundamentalsFields { revenue: Some(101.25), net_income: Some(11.5), operating_cash_flow: Some(19.75), @@ -686,14 +890,14 @@ fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero( total_equity: Some(400.0), shares_outstanding: Some(50_000_000.0), }, - }, - FinancialObservation { - key: 10_i32, - period_end: day(2023, 9, 30), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2023, 11, 3)), - fields: FundamentalsFields { + ), + obs( + 10, + day(2023, 9, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 3)), + FundamentalsFields { revenue: Some(110.5), net_income: Some(12.25), operating_cash_flow: Some(21.0), @@ -701,92 +905,71 @@ fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero( total_equity: Some(415.0), shares_outstanding: Some(50_100_000.0), }, - }, - FinancialObservation { - key: 10_i32, - period_end: day(2023, 12, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2024, 2, 14)), - fields: FundamentalsFields { + ), + obs( + 10, + day(2023, 12, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 14)), + FundamentalsFields { revenue: Some(125.0), net_income: Some(14.0), - operating_cash_flow: None, + operating_cash_flow: Some(22.5), total_assets: Some(1_120.0), total_equity: None, shares_outstanding: Some(50_200_000.0), }, - }, - FinancialObservation { - key: 10_i32, - period_end: day(2024, 3, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2024, 5, 1)), - fields: FundamentalsFields { + ), + obs( + 10, + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { revenue: Some(130.75), net_income: Some(16.5), - operating_cash_flow: Some(24.25), + operating_cash_flow: None, total_assets: Some(1_150.0), total_equity: Some(440.0), shares_outstanding: None, }, - }, - // Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE), ttm == None. - FinancialObservation { - key: 20_i32, - period_end: day(2024, 3, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "CAD".to_string(), - report_date: None, - fields: FundamentalsFields { - revenue: Some(-0.0), + ), + // Listing 20: unlinked observation -> statutory_lag_estimate (+60d for TSXV/CSE), + // ttm == None. + obs( + 20, + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "CAD", + None, + FundamentalsFields { + revenue: Some(42.5), net_income: Some(-3.5), operating_cash_flow: None, total_assets: Some(25.0), total_equity: Some(12.5), shares_outstanding: Some(8_000_000.0), }, - }, + ), ]; let filings = vec![ - QmFiling { - key: 10_i32, - timefiled: "2023-08-02T16:10:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-10-2023Q2".to_string()), - url: None, - }, - QmFiling { - key: 10_i32, - timefiled: "2023-11-03T16:05:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-10-2023Q3".to_string()), - url: None, - }, - QmFiling { - key: 10_i32, - timefiled: "2024-02-14T16:15:00 EST".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-10-2023Q4".to_string()), - url: None, - }, - QmFiling { - key: 10_i32, - timefiled: "2024-05-01T16:20:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-10-2024Q1".to_string()), - url: None, - }, + filing(10, "2023-05-02T16:05:00 EDT", "10-Q"), + filing(10, "2023-08-02T16:10:00 EDT", "10-Q"), + filing(10, "2023-11-03T16:05:00 EDT", "10-Q"), + filing(10, "2024-02-14T16:15:00 EST", "10-Q"), + filing(10, "2024-05-01T16:20:00 EDT", "10-Q"), ]; let built = build_fundamentals_rows(observations, filings, &venues); let mut snapshots = build_fundamentals_snapshots(&built.rows, 4).expect("build snapshots"); - assert_eq!(snapshots.len(), 5); + assert_eq!(snapshots.len(), 6); - // Append a direct snapshot carrying signed negative zero (-0.0) in a statement field so we - // verify the Parquet writer preserves exact IEEE-754 bit patterns without altering them. + // Append a direct snapshot carrying signed negative zero (-0.0) vs positive zero (+0.0) in + // statement fields (builder normalizes -0.0; this verifies the Parquet writer preserves exact + // IEEE-754 bit patterns without altering them). snapshots.push(FundamentalsSnapshot { key: 30_i32, effective_known_at_utc_micros: utc_micros(2024, 6, 15, 20, 5, 0, 0), @@ -813,68 +996,90 @@ fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero( let rows_from_ref: Vec = snapshots .iter() - .map(FundamentalsPitParquetRow::try_from) - .collect::>() - .expect("convert snapshots by ref"); + .map(FundamentalsPitParquetRow::from) + .collect(); let rows_from_owned: Vec = snapshots .clone() .into_iter() - .map(FundamentalsPitParquetRow::try_from) - .collect::>() - .expect("convert snapshots owned"); - assert_eq!(rows_from_ref.len(), rows_from_owned.len()); - for (a, b) in rows_from_ref.iter().zip(rows_from_owned.iter()) { - assert_row_bit_eq(a, b); - } + .map(FundamentalsPitParquetRow::from) + .collect(); + assert_eq!(rows_from_ref, rows_from_owned); - let opts = FundamentalsPitWriteOptions { - row_group_rows: 2, - zstd_level: DEFAULT_ZSTD_LEVEL, - }; - let stats = write_fundamentals_pit_dataset(tmp.path(), &rows_from_ref, opts) - .expect("write fundamentals_pit"); + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows_from_ref, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write builder snapshots"); - let expected_by_year = BTreeMap::from([(2023, 2), (2024, 4)]); - assert_eq!(stats.rows_written, 6); + let expected_by_year = BTreeMap::from([(2023, 3), (2024, 4)]); + assert_eq!(stats.rows_written, 7); assert_eq!(stats.files_written, 2); - assert_eq!(stats.row_groups_written, 3); + assert_eq!(stats.row_groups_written, 4); assert_eq!(stats.rows_by_year, expected_by_year); - let expected_schema = fundamentals_pit_parquet_schema().unwrap(); let mut total_bytes = 0u64; for (&year, &expected_count) in &expected_by_year { let path = tmp .path() .join(format!("fundamentals_pit/year={year:04}/part.parquet")); assert!(path.is_file(), "missing {}", path.display()); - total_bytes += fs::metadata(&path).unwrap().len(); - - let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); - let meta = reader.metadata(); - assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); - assert_eq!(meta.file_metadata().num_rows() as usize, expected_count); - for rg in meta.row_groups() { - for col in rg.columns() { - assert!( - matches!(col.compression(), Compression::ZSTD(_)), - "year {year} column {} must be ZSTD", - col.column_path() - ); - } - } + total_bytes += fs::metadata(&path).expect("metadata").len(); let decoded = read_parquet_rows(&path); let expected_snapshots: Vec<&FundamentalsSnapshot> = snapshots .iter() .filter(|s| partition_year_utc(s.effective_known_at_utc_micros) == year) .collect(); + assert_eq!(decoded.len(), expected_count); assert_eq!(decoded.len(), expected_snapshots.len()); for (actual_row, snap) in decoded.iter().zip(expected_snapshots.iter()) { - assert_row_matches_snapshot_bit_for_bit(actual_row, snap); + assert_decoded_matches_snapshot_bit_for_bit(actual_row, snap); } if year == 2024 { - // Verify signed negative zero (-0.0) survived bit-for-bit on listing 30. + // Q4 2023 snapshot (filed 2024-02-14): all three TTM flows present and distinct. + let full_ttm = decoded + .iter() + .find(|r| r.listing_id == 10 && r.period_end == day(2023, 12, 31)) + .expect("listing 10 Q4 2023 row"); + assert_eq!(full_ttm.ttm_revenue, Some(432.25)); + assert_eq!(full_ttm.ttm_net_income, Some(47.0)); + assert_eq!(full_ttm.ttm_operating_cash_flow, Some(81.0)); + assert_eq!(full_ttm.ttm_period_end, Some(day(2023, 12, 31))); + assert_eq!(full_ttm.ttm_currency.as_deref(), Some("USD")); + assert_eq!(full_ttm.ttm_has_estimated_lag, Some(false)); + + // Q1 2024 snapshot (filed 2024-05-01): partial null TTM flow. + let partial_ttm = decoded + .iter() + .find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31)) + .expect("listing 10 Q1 2024 row"); + assert_eq!(partial_ttm.ttm_revenue, Some(467.5)); + assert_eq!(partial_ttm.ttm_net_income, Some(54.25)); + assert_eq!(partial_ttm.ttm_operating_cash_flow, None); + assert_eq!(partial_ttm.ttm_period_end, Some(day(2024, 3, 31))); + assert_eq!(partial_ttm.ttm_currency.as_deref(), Some("USD")); + assert_eq!(partial_ttm.ttm_has_estimated_lag, Some(false)); + + // Listing 20: statutory lag provenance and ttm == None. + let est_row = decoded + .iter() + .find(|r| r.listing_id == 20) + .expect("listing 20 row"); + assert_eq!(est_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(est_row.has_estimated_lag); + assert_eq!(est_row.ttm_revenue, None); + assert_eq!(est_row.ttm_net_income, None); + assert_eq!(est_row.ttm_operating_cash_flow, None); + assert_eq!(est_row.ttm_period_end, None); + assert_eq!(est_row.ttm_currency, None); + assert_eq!(est_row.ttm_has_estimated_lag, None); + + // Listing 30: exact IEEE-754 -0.0 vs +0.0 bit preservation across Parquet write/read. let signed_zero_row = decoded .iter() .find(|r| r.listing_id == 30) @@ -891,166 +1096,173 @@ fn builder_snapshots_round_trip_bit_for_bit_including_nulls_ttm_and_signed_zero( signed_zero_row.net_income.map(f64::to_bits), Some(0.0_f64.to_bits()) ); - - // Verify listing 10 Q1 2024 snapshot has TTM revenue & net_income populated, - // TTM operating_cash_flow None, and distinct flow values. - let ttm_row = decoded - .iter() - .find(|r| r.listing_id == 10 && r.period_end == day(2024, 3, 31)) - .expect("listing 10 Q1 2024 row"); - assert_eq!(ttm_row.ttm_revenue, Some(467.5)); - assert_eq!(ttm_row.ttm_net_income, Some(54.25)); - assert_eq!(ttm_row.ttm_operating_cash_flow, None); - assert_eq!(ttm_row.ttm_period_end, Some(day(2024, 3, 31))); - assert_eq!(ttm_row.ttm_currency.as_deref(), Some("USD")); - assert_eq!(ttm_row.ttm_has_estimated_lag, Some(false)); } } + assert_eq!(stats.bytes_written, total_bytes); assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } #[test] -fn restated_q1_after_q2_preserves_earlier_snapshots_and_keeps_q2_as_latest_period() { - let venues = BTreeMap::from([(42_i32, StatutoryLagVenue::UsTsx)]); +fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() { + let listing_id = 42_i32; + let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::UsTsx)]); - let base_observations = vec![ - FinancialObservation { - key: 42_i32, - period_end: day(2023, 6, 30), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2023, 8, 1)), - fields: FundamentalsFields { + let p_2023_q3 = day(2023, 9, 30); + let p_2023_q4 = day(2023, 12, 31); + let p_2024_q1 = day(2024, 3, 31); + let p_2024_q2 = day(2024, 6, 30); + + let initial_filings = vec![ + filing(listing_id, "2023-11-01T16:15:00 EDT", "10-Q"), + filing(listing_id, "2024-02-01T16:15:00 EST", "10-Q"), + filing(listing_id, "2024-05-01T16:15:00 EDT", "10-Q"), + filing(listing_id, "2024-08-01T16:15:00 EDT", "10-Q"), + ]; + let amendment_filing = filing(listing_id, "2024-09-15T17:00:00 EDT", "10-Q/A"); + + let initial_obs = vec![ + obs( + listing_id, + p_2023_q3, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 1)), + FundamentalsFields { + revenue: Some(70.0), + net_income: Some(7.0), + operating_cash_flow: Some(10.0), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2023_q4, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 1)), + FundamentalsFields { + revenue: Some(80.0), + net_income: Some(8.0), + operating_cash_flow: Some(12.0), + total_assets: Some(520.0), + total_equity: Some(210.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + listing_id, + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { revenue: Some(100.0), net_income: Some(10.0), operating_cash_flow: Some(15.0), - total_assets: Some(900.0), - total_equity: Some(400.0), - shares_outstanding: Some(10_000_000.0), + total_assets: Some(540.0), + total_equity: Some(220.0), + shares_outstanding: Some(100.0), }, - }, - FinancialObservation { - key: 42_i32, - period_end: day(2023, 9, 30), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2023, 11, 1)), - fields: FundamentalsFields { - revenue: Some(110.0), - net_income: Some(11.0), - operating_cash_flow: Some(16.0), - total_assets: Some(920.0), - total_equity: Some(410.0), - shares_outstanding: Some(10_000_000.0), - }, - }, - FinancialObservation { - key: 42_i32, - period_end: day(2023, 12, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2024, 2, 1)), - fields: FundamentalsFields { + ), + obs( + listing_id, + p_2024_q2, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 1)), + FundamentalsFields { revenue: Some(120.0), net_income: Some(12.0), - operating_cash_flow: Some(17.0), - total_assets: Some(950.0), - total_equity: Some(420.0), - shares_outstanding: Some(10_000_000.0), - }, - }, - // Q1 2024 original filing on 2024-05-01 - FinancialObservation { - key: 42_i32, - period_end: day(2024, 3, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2024, 5, 1)), - fields: FundamentalsFields { - revenue: Some(130.0), - net_income: Some(13.0), operating_cash_flow: Some(18.0), - total_assets: Some(980.0), - total_equity: Some(430.0), - shares_outstanding: Some(10_000_000.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), }, - }, - // Q2 2024 filing on 2024-08-01 - FinancialObservation { - key: 42_i32, - period_end: day(2024, 6, 30), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2024, 8, 1)), - fields: FundamentalsFields { - revenue: Some(140.0), - net_income: Some(14.0), - operating_cash_flow: Some(19.0), - total_assets: Some(1_010.0), - total_equity: Some(445.0), - shares_outstanding: Some(10_000_000.0), - }, - }, + ), ]; - let base_filings = vec![ - QmFiling { - key: 42_i32, - timefiled: "2023-08-01T16:10:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-Q2-2023".to_string()), - url: None, + // Late Q1 amendment filed on 2024-09-15 (after Q2's 2024-08-01 filing). + // Restates revenue 100 -> 110 and net_income 10 -> 11, while omitting operating_cash_flow. + let q1_amendment = obs( + listing_id, + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 15)), + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: None, + total_assets: None, + total_equity: Some(225.0), + shares_outstanding: None, }, - QmFiling { - key: 42_i32, - timefiled: "2023-11-01T16:10:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-Q3-2023".to_string()), - url: None, - }, - QmFiling { - key: 42_i32, - timefiled: "2024-02-01T16:10:00 EST".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-Q4-2023".to_string()), - url: None, - }, - QmFiling { - key: 42_i32, - timefiled: "2024-05-01T16:10:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-Q1-2024".to_string()), - url: None, - }, - QmFiling { - key: 42_i32, - timefiled: "2024-08-01T16:10:00 EDT".to_string(), - form_type: "10-Q".to_string(), - filing_id: Some("F-Q2-2024".to_string()), - url: None, - }, - ]; - - // Baseline run (pre-amendment) - let tmp_base = TempDirGuard::new("restatement-base"); - let base_built = build_fundamentals_rows( - base_observations.clone(), - base_filings.clone(), - &venues, ); - let base_snaps = build_fundamentals_snapshots(&base_built.rows, 4).expect("build base snaps"); - let base_rows: Vec = base_snaps + + let mut full_obs = initial_obs.clone(); + full_obs.push(q1_amendment); + let mut full_filings = initial_filings.clone(); + full_filings.push(amendment_filing); + + let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); + let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).expect("full snapshots"); + assert_eq!(full_snaps.len(), 5); + + let baseline_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); + let baseline_snaps = + build_fundamentals_snapshots(&baseline_build.rows, 4).expect("baseline snapshots"); + assert_eq!(baseline_snaps.len(), 4); + + let full_rows_from_ref: Vec = + full_snaps.iter().map(FundamentalsPitParquetRow::from).collect(); + let full_rows_from_owned: Vec = full_snaps + .into_iter() + .map(FundamentalsPitParquetRow::from) + .collect(); + assert_eq!(full_rows_from_ref, full_rows_from_owned); + + let baseline_rows: Vec = baseline_snaps .iter() - .map(FundamentalsPitParquetRow::try_from) - .collect::>() - .unwrap(); - write_fundamentals_pit_dataset( - tmp_base.path(), - &base_rows, + .map(FundamentalsPitParquetRow::from) + .collect(); + + let tmp_full = TempDirGuard::new("restatement-full"); + let tmp_base = TempDirGuard::new("restatement-baseline"); + + let full_stats = write_fundamentals_pit_dataset( + tmp_full.path(), + &full_rows_from_ref, FundamentalsPitWriteOptions::default(), ) - .expect("write baseline"); + .expect("write full dataset"); + assert_eq!(full_stats.rows_written, 5); + assert_eq!(full_stats.files_written, 2); + assert_eq!(full_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 4)])); + + let base_stats = write_fundamentals_pit_dataset( + tmp_base.path(), + &baseline_rows, + FundamentalsPitWriteOptions::default(), + ) + .expect("write baseline dataset"); + assert_eq!(base_stats.rows_written, 4); + assert_eq!(base_stats.files_written, 2); + assert_eq!(base_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 3)])); + + let mut full_decoded = read_parquet_rows( + &tmp_full + .path() + .join("fundamentals_pit/year=2023/part.parquet"), + ); + full_decoded.extend(read_parquet_rows( + &tmp_full + .path() + .join("fundamentals_pit/year=2024/part.parquet"), + )); + assert_eq!(full_decoded.len(), 5); let mut base_decoded = read_parquet_rows( &tmp_base @@ -1062,476 +1274,970 @@ fn restated_q1_after_q2_preserves_earlier_snapshots_and_keeps_q2_as_latest_perio .path() .join("fundamentals_pit/year=2024/part.parquet"), )); - assert_eq!(base_decoded.len(), 5); + assert_eq!(base_decoded.len(), 4); - // Amended run: append Q1 2024 restatement filed on 2024-09-15 (after Q2's 2024-08-01 filing) - let mut amended_observations = base_observations; - amended_observations.push(FinancialObservation { - key: 42_i32, - period_end: day(2024, 3, 31), - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - report_date: Some(day(2024, 9, 15)), - fields: FundamentalsFields { - revenue: Some(125.0), // restated -5.0 - net_income: Some(9.0), // restated -4.0 - operating_cash_flow: None, // carried forward from Q1 original (18.0) - total_assets: Some(975.0), - total_equity: Some(426.0), - shares_outstanding: Some(10_000_000.0), - }, - }); - let mut amended_filings = base_filings; - amended_filings.push(QmFiling { - key: 42_i32, - timefiled: "2024-09-15T16:30:00 EDT".to_string(), - form_type: "10-Q/A".to_string(), - filing_id: Some("F-Q1-2024-A".to_string()), - url: None, - }); + let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0, 0); + let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0, 0); - let tmp_amended = TempDirGuard::new("restatement-amended"); - let amended_built = build_fundamentals_rows(amended_observations, amended_filings, &venues); - let amended_snaps = - build_fundamentals_snapshots(&amended_built.rows, 4).expect("build amended snaps"); - let amended_rows: Vec = amended_snaps + // Every earlier row (before the amendment) must match the unamended baseline identically. + assert_eq!(&full_decoded[..4], &base_decoded[..]); + + // Every row at or after Q2 filing must keep Q2 as the latest visible period with unchanged fields. + let post_q2_rows: Vec<&DecodedFundamentalsPitRow> = full_decoded .iter() - .map(FundamentalsPitParquetRow::try_from) - .collect::>() - .unwrap(); - write_fundamentals_pit_dataset( - tmp_amended.path(), - &amended_rows, - FundamentalsPitWriteOptions::default(), - ) - .expect("write amended"); + .filter(|r| r.effective_known_at >= ts_q2) + .collect(); + assert_eq!(post_q2_rows.len(), 2); + assert_eq!(post_q2_rows[0].effective_known_at, ts_q2); + assert_eq!(post_q2_rows[1].effective_known_at, ts_amend); - let mut amended_decoded = read_parquet_rows( - &tmp_amended - .path() - .join("fundamentals_pit/year=2023/part.parquet"), - ); - amended_decoded.extend(read_parquet_rows( - &tmp_amended - .path() - .join("fundamentals_pit/year=2024/part.parquet"), - )); - assert_eq!(amended_decoded.len(), 6); - - // Every earlier snapshot (including Q2 on 2024-08-01) must remain bit-for-bit identical. - for i in 0..5 { - assert_row_bit_eq(&amended_decoded[i], &base_decoded[i]); + for row in &post_q2_rows { + assert_eq!(row.listing_id, listing_id); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!row.has_estimated_lag); + assert_eq!(row.period_end, p_2024_q2); + assert_eq!(row.period_known_at, ts_q2); + assert_eq!(row.fiscal_period, "Q"); + assert_eq!(row.currency, "USD"); + assert_eq!(row.revenue, Some(120.0)); + assert_eq!(row.net_income, Some(12.0)); + assert_eq!(row.operating_cash_flow, Some(18.0)); + assert_eq!(row.total_assets, Some(560.0)); + assert_eq!(row.total_equity, Some(230.0)); + assert_eq!(row.shares_outstanding, Some(100.0)); + assert_eq!(row.ttm_period_end, Some(p_2024_q2)); + assert_eq!(row.ttm_currency.as_deref(), Some("USD")); + assert_eq!(row.ttm_has_estimated_lag, Some(false)); } - let q2_row = &amended_decoded[4]; - let restatement_row = &amended_decoded[5]; - // Restatement appears as its own later effective_known_at row (2024-09-15 16:30 EDT = 20:30 UTC). - assert_eq!( - restatement_row.effective_known_at_micros, - utc_micros(2024, 9, 15, 20, 30, 0, 0) - ); - assert!(restatement_row.effective_known_at_micros > q2_row.effective_known_at_micros); + // At Q2 filing (before amendment): TTM uses original Q1 (revenue=100, net_income=10, ocf=15). + assert_eq!(post_q2_rows[0].ttm_revenue, Some(370.0)); + assert_eq!(post_q2_rows[0].ttm_net_income, Some(37.0)); + assert_eq!(post_q2_rows[0].ttm_operating_cash_flow, Some(55.0)); - // Q2 remains the latest period_end and period_known_at — restated Q1 never replaces Q2. - assert_eq!(restatement_row.period_end, day(2024, 6, 30)); - assert_eq!(restatement_row.period_known_at_micros, q2_row.period_known_at_micros); - assert_eq!(restatement_row.revenue, q2_row.revenue); - assert_eq!(restatement_row.net_income, q2_row.net_income); - assert_eq!( - restatement_row.operating_cash_flow, - q2_row.operating_cash_flow - ); + // At Q1 amendment: TTM revenue & net_income update (+10, +1); TTM OCF preserves prior Q1's 15.0. + assert_eq!(post_q2_rows[1].ttm_revenue, Some(380.0)); + assert_eq!(post_q2_rows[1].ttm_net_income, Some(38.0)); + assert_eq!(post_q2_rows[1].ttm_operating_cash_flow, Some(55.0)); - // TTM flows reflect the restated Q1 (Q3 2023 + Q4 2023 + Q1 2024 restated + Q2 2024): - // baseline Q2 TTM: rev = 110+120+130+140 = 500, ni = 11+12+13+14 = 50, ocf = 16+17+18+19 = 70 - assert_eq!(q2_row.ttm_revenue, Some(500.0)); - assert_eq!(q2_row.ttm_net_income, Some(50.0)); - assert_eq!(q2_row.ttm_operating_cash_flow, Some(70.0)); - // after Q1 restatement: rev = 495, ni = 46, ocf unchanged = 70 - assert_eq!(restatement_row.ttm_revenue, Some(495.0)); - assert_eq!(restatement_row.ttm_net_income, Some(46.0)); - assert_eq!(restatement_row.ttm_operating_cash_flow, Some(70.0)); - assert_eq!(restatement_row.ttm_period_end, Some(day(2024, 6, 30))); + assert_no_transient_files(&tmp_full.path().join("fundamentals_pit")); + assert_no_transient_files(&tmp_base.path().join("fundamentals_pit")); } #[test] -fn partitions_by_effective_known_at_utc_year_with_boundary_and_stats() { - let tmp_a = TempDirGuard::new("partition-boundary-a"); - let tmp_b = TempDirGuard::new("partition-boundary-b"); +fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() { + let tmp = TempDirGuard::new("partitioning"); + + // Globally ordered by (listing_id, effective_known_at), with interleaved UTC years across + // multiple listings and timestamps 1 microsecond apart across midnight UTC. + let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); + let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); + assert_eq!(partition_year_utc(ts_2023_end), 2023); + assert_eq!(partition_year_utc(ts_2024_start), 2024); let rows = vec![ - sample_row(1, utc_micros(2023, 5, 1, 12, 0, 0, 0)), - sample_row(1, utc_micros(2023, 12, 31, 23, 59, 59, 999_999)), - sample_row(1, utc_micros(2024, 1, 1, 0, 0, 0, 0)), - sample_row(2, utc_micros(2023, 11, 15, 21, 5, 0, 0)), - sample_row(2, utc_micros(2024, 2, 10, 14, 0, 0, 0)), + make_row(1, utc_micros(2023, 5, 1, 14, 0, 0, 0), day(2023, 3, 31), Some(10.0), None), + make_row(1, ts_2023_end, day(2023, 9, 30), Some(11.0), None), + make_row(1, ts_2024_start, day(2023, 12, 31), Some(12.0), None), + make_row(2, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(20.0), None), + make_row(2, utc_micros(2024, 2, 1, 14, 0, 0, 0), day(2023, 12, 31), Some(21.0), None), + make_row(3, utc_micros(2023, 11, 1, 14, 0, 0, 0), day(2023, 9, 30), Some(30.0), None), + make_row(3, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(31.0), None), ]; - let opts = FundamentalsPitWriteOptions::default(); - let stats_a = write_fundamentals_pit_dataset(tmp_a.path(), &rows, opts).unwrap(); - let stats_b = write_fundamentals_pit_dataset(tmp_b.path(), &rows, opts).unwrap(); - assert_eq!(stats_a, stats_b); + let stats = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write partitioned dataset"); - let expected_by_year = BTreeMap::from([(2023, 3), (2024, 2)]); - assert_eq!(stats_a.rows_written, 5); - assert_eq!(stats_a.files_written, 2); - assert_eq!(stats_a.row_groups_written, 2); - assert_eq!(stats_a.rows_by_year, expected_by_year); + assert_eq!(stats.rows_written, 7); + assert_eq!(stats.files_written, 2); + // 2023: 4 rows -> 2 row groups; 2024: 3 rows -> 2 row groups + assert_eq!(stats.row_groups_written, 4); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 4), (2024, 3)])); - let dataset_dir = tmp_a.path().join("fundamentals_pit"); - let mut year_dirs: Vec = fs::read_dir(&dataset_dir) - .unwrap() - .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) - .collect(); - year_dirs.sort(); - assert_eq!(year_dirs, vec!["year=2023", "year=2024"]); + let path_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + assert!(path_2023.is_file()); + assert!(path_2024.is_file()); + assert_eq!( + stats.bytes_written, + fs::metadata(&path_2023).expect("meta 2023").len() + + fs::metadata(&path_2024).expect("meta 2024").len() + ); - let mut total_bytes = 0u64; - for year in [2023, 2024] { - let pa = tmp_a - .path() - .join(format!("fundamentals_pit/year={year:04}/part.parquet")); - let pb = tmp_b - .path() - .join(format!("fundamentals_pit/year={year:04}/part.parquet")); - assert!(pa.is_file()); - let bytes_a = fs::read(&pa).unwrap(); - let bytes_b = fs::read(&pb).unwrap(); - assert_eq!( - bytes_a, bytes_b, - "year {year} output must be deterministic across runs" - ); - total_bytes += bytes_a.len() as u64; + let decoded_2023 = read_parquet_rows(&path_2023); + let decoded_2024 = read_parquet_rows(&path_2024); - let decoded = read_parquet_rows(&pa); - assert_eq!(decoded.len(), expected_by_year[&year]); - for pair in decoded.windows(2) { - let k0 = (pair[0].listing_id, pair[0].effective_known_at_micros); - let k1 = (pair[1].listing_id, pair[1].effective_known_at_micros); - assert!(k0 < k1, "keys must be strictly increasing: {k0:?} vs {k1:?}"); + assert_eq!(decoded_2023.len(), 4); + assert_eq!(decoded_2024.len(), 3); + + // Verify exact membership and strict sort order by (listing_id, effective_known_at). + for (year, decoded) in [(2023, &decoded_2023), (2024, &decoded_2024)] { + for r in decoded { + assert_eq!(partition_year_utc(r.effective_known_at), year); } - for row in &decoded { - assert_eq!(partition_year_utc(row.effective_known_at_micros), year); + for pair in decoded.windows(2) { + assert!( + (pair[0].listing_id, pair[0].effective_known_at) + < (pair[1].listing_id, pair[1].effective_known_at), + "year {year} rows must be strictly increasing by (listing_id, effective_known_at)" + ); } } - assert_eq!(stats_a.bytes_written, total_bytes); - assert_no_transient_files(&dataset_dir); + + assert_eq!(decoded_2023[1].effective_known_at, ts_2023_end); + assert_eq!(decoded_2024[0].effective_known_at, ts_2024_start); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } #[test] -fn empty_input_creates_no_directory_and_preserves_existing_dataset() { - let tmp_fresh = TempDirGuard::new("empty-fresh"); - let stats = write_fundamentals_pit_dataset( - tmp_fresh.path(), - std::iter::empty::(), - FundamentalsPitWriteOptions::default(), - ) - .unwrap(); - assert_eq!(stats, FundamentalsPitWriteStats::default()); - assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); +fn invalid_inputs_return_typed_errors_and_preserve_existing_partitions() { + let tmp = TempDirGuard::new("errors"); - let tmp_existing = TempDirGuard::new("empty-existing"); - let seed = vec![sample_row(1, utc_micros(2024, 5, 1, 20, 0, 0, 0))]; + // Seed an existing 2024 partition and snapshot its exact bytes. + let seed = vec![make_row( + 1, + utc_micros(2024, 3, 1, 15, 0, 0, 0), + day(2023, 12, 31), + Some(50.0), + None, + )]; write_fundamentals_pit_dataset( - tmp_existing.path(), + tmp.path(), &seed, FundamentalsPitWriteOptions::default(), ) - .unwrap(); - let part = tmp_existing - .path() - .join("fundamentals_pit/year=2024/part.parquet"); - let before = fs::read(&part).unwrap(); + .expect("seed existing partition"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let before_bytes = fs::read(&part_2024).expect("read seed bytes"); - let stats2 = write_fundamentals_pit_dataset( - tmp_existing.path(), - std::iter::empty::(), - FundamentalsPitWriteOptions::default(), - ) - .unwrap(); - assert_eq!(stats2, FundamentalsPitWriteStats::default()); - assert_eq!(fs::read(&part).unwrap(), before); -} + let rg1 = FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; -#[test] -fn rejects_empty_snapshot_periods() { - let empty_snapshot = FundamentalsSnapshot:: { - key: 7, - effective_known_at_utc_micros: utc_micros(2024, 5, 1, 20, 0, 0, 0), + // 1. Duplicate (listing_id, effective_known_at) with different payload after a valid row. + let ts_a = utc_micros(2024, 5, 1, 20, 0, 0, 0); + let dup_rows = vec![ + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + make_row(1, ts_a, day(2024, 3, 31), Some(999.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &dup_rows, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::DuplicateRow { + row_index: 1, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_a + ), + "expected DuplicateRow, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 2. Unsorted (descending effective_known_at for same listing) after a valid row. + let ts_b = utc_micros(2024, 8, 1, 20, 0, 0, 0); + let unsorted_ts = vec![ + make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_ts, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 1, + prev_effective_known_at_micros, + listing_id: 1, + effective_known_at_micros, + } if prev_effective_known_at_micros == ts_b && effective_known_at_micros == ts_a + ), + "expected UnsortedInput, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 3. Unsorted (descending listing_id) after a valid row. + let unsorted_lid = vec![ + make_row(2, ts_a, day(2024, 3, 31), Some(100.0), None), + make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), + ]; + let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_lid, rg1).unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::UnsortedInput { + row_index: 1, + prev_listing_id: 2, + listing_id: 1, + .. + } + ), + "expected UnsortedInput for descending listing_id, got {err:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 4. Empty periods snapshot (at row_index 0 and at row_index 1 after a flushed row group). + let empty_snap = FundamentalsSnapshot { + key: 1_i32, + effective_known_at_utc_micros: ts_b, known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, has_estimated_lag: false, periods: Vec::new(), ttm: None, }; + let empty_row = FundamentalsPitParquetRow::from(&empty_snap); + assert!(empty_row.latest_period().is_none()); - let err_ref = FundamentalsPitParquetRow::try_from(&empty_snapshot).unwrap_err(); - assert!(matches!( - err_ref, - ParquetFundamentalsError::EmptySnapshotPeriods { - listing_id: 7, - .. - } - )); + let tmp_fresh = TempDirGuard::new("empty-periods-first"); + let err_first = write_fundamentals_pit_dataset(tmp_fresh.path(), &[empty_row.clone()], rg1) + .unwrap_err(); + assert!( + matches!( + err_first, + ParquetFundamentalsError::EmptyPeriods { + row_index: 0, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_b + ), + "expected EmptyPeriods at row 0, got {err_first:?}" + ); + assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); - let err_owned = FundamentalsPitParquetRow::try_from(empty_snapshot).unwrap_err(); - assert!(matches!( - err_owned, - ParquetFundamentalsError::EmptySnapshotPeriods { - listing_id: 7, - .. - } - )); + let mixed = vec![ + make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), + empty_row, + ]; + let err_second = write_fundamentals_pit_dataset(tmp.path(), &mixed, rg1).unwrap_err(); + assert!( + matches!( + err_second, + ParquetFundamentalsError::EmptyPeriods { + row_index: 1, + listing_id: 1, + effective_known_at_micros, + } if effective_known_at_micros == ts_b + ), + "expected EmptyPeriods at row 1, got {err_second:?}" + ); + assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + + // 5. Empty input does not create directory or touch existing partitions. + let tmp_empty = TempDirGuard::new("empty-input"); + let empty_stats = write_fundamentals_pit_dataset( + tmp_empty.path(), + std::iter::empty::(), + FundamentalsPitWriteOptions::default(), + ) + .expect("empty input succeeds"); + assert_eq!(empty_stats, FundamentalsPitWriteStats::default()); + assert!(!tmp_empty.path().join("fundamentals_pit").exists()); } #[test] -fn rejects_duplicate_and_unsorted_keys_without_leaving_partial_output() { - let ts1 = utc_micros(2023, 8, 1, 20, 0, 0, 0); - let ts2 = utc_micros(2024, 5, 1, 20, 0, 0, 0); +fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { + let tmp = TempDirGuard::new("rollback"); - // Duplicate (listing_id, effective_known_at) - let tmp_dup = TempDirGuard::new("reject-dup"); - let dup_rows = vec![sample_row(1, ts1), sample_row(1, ts1)]; - let err = write_fundamentals_pit_dataset( - tmp_dup.path(), - &dup_rows, + // Seed an existing 2023 partition. + let seed = vec![make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(50.0), + None, + )]; + write_fundamentals_pit_dataset( + tmp.path(), + &seed, FundamentalsPitWriteOptions::default(), ) - .unwrap_err(); - assert!(matches!( - err, - ParquetFundamentalsError::DuplicateRow { - row_index: 1, - listing_id: 1, - .. - } - )); - assert!(!tmp_dup - .path() - .join("fundamentals_pit/year=2023/part.parquet") - .exists()); - assert_no_transient_files(&tmp_dup.path().join("fundamentals_pit")); + .expect("seed 2023"); - // Unsorted keys (later row has smaller effective_known_at for same listing) - let tmp_unsorted = TempDirGuard::new("reject-unsorted"); - let unsorted_rows = vec![sample_row(1, ts2), sample_row(1, ts1)]; - let err = write_fundamentals_pit_dataset( - tmp_unsorted.path(), - &unsorted_rows, - FundamentalsPitWriteOptions::default(), - ) - .unwrap_err(); - assert!(matches!( - err, - ParquetFundamentalsError::UnsortedInput { - row_index: 1, - prev_listing_id: 1, - listing_id: 1, - .. - } - )); - assert!(!tmp_unsorted - .path() - .join("fundamentals_pit/year=2024/part.parquet") - .exists()); - assert_no_transient_files(&tmp_unsorted.path().join("fundamentals_pit")); -} + let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); + let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); + let part_2025 = tmp.path().join("fundamentals_pit/year=2025/part.parquet"); + let before_2023 = fs::read(&part_2023).expect("read seed 2023"); -#[test] -fn rejects_non_finite_statement_and_ttm_values_without_leaving_partial_output() { - let ts_2023 = utc_micros(2023, 8, 1, 20, 0, 0, 0); - let ts_2024 = utc_micros(2024, 5, 1, 20, 0, 0, 0); + // Occupy year=2025/part.parquet with a directory so rename fails after 2023 (replaced) + // and 2024 (newly created) have been renamed into place. + fs::create_dir_all(&part_2025).expect("create blocking directory at year=2025/part.parquet"); - type RowMutator = fn(&mut FundamentalsPitParquetRow); - let cases: [(&str, RowMutator); 4] = [ - ("revenue", |r| r.revenue = Some(f64::NAN)), - ("total_assets", |r| r.total_assets = Some(f64::INFINITY)), - ("ttm_revenue", |r| r.ttm_revenue = Some(f64::NEG_INFINITY)), - ("ttm_operating_cash_flow", |r| { - r.ttm_operating_cash_flow = Some(f64::NAN) - }), + let rows = vec![ + make_row(1, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(75.0), None), + make_row(1, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(100.0), None), + make_row(1, utc_micros(2025, 5, 1, 14, 0, 0, 0), day(2025, 3, 31), Some(125.0), None), ]; - for (expected_field, mutate) in cases { - let tmp = TempDirGuard::new(&format!("reject-nonfinite-{expected_field}")); - let good = sample_row(1, ts_2023); - let mut bad = sample_row(1, ts_2024); - mutate(&mut bad); + let err = write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions::default(), + ) + .unwrap_err(); + assert!( + matches!(err, ParquetFundamentalsError::Io { ref path, .. } if path == &part_2025), + "expected Io error at year=2025/part.parquet, got {err:?}" + ); - let err = write_fundamentals_pit_dataset( - tmp.path(), - &[good, bad], - FundamentalsPitWriteOptions::default(), - ) - .unwrap_err(); - match err { - ParquetFundamentalsError::NonFiniteValue { - row_index: 1, - field, - .. - } => assert_eq!(field, expected_field), - other => panic!("expected NonFiniteValue({expected_field}), got {other:?}"), + // 2023 must be restored byte for byte; 2024 must be removed; no transient files remain. + assert_eq!(fs::read(&part_2023).expect("read restored 2023"), before_2023); + assert!( + !part_2024.exists(), + "newly published 2024 partition must be removed on rollback" + ); + assert!(part_2025.is_dir()); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +// --------------------------------------------------------------------------------------------- +// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance, +// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors. +// --------------------------------------------------------------------------------------------- + +/// Expected decoded form of a row: what the reader must see after a write/read round trip. +fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRow { + let latest = row + .latest_period() + .expect("expected row must have a latest period"); + let ttm = row.ttm.as_ref(); + DecodedFundamentalsPitRow { + listing_id: row.listing_id, + effective_known_at: row.effective_known_at_micros, + known_at_source: row.known_at_source.to_string(), + has_estimated_lag: row.has_estimated_lag, + period_end: latest.period_end, + fiscal_period: latest.fiscal_period.to_string(), + currency: latest.currency.clone(), + period_known_at: latest.period_known_at_micros, + revenue: latest.fields.revenue, + net_income: latest.fields.net_income, + operating_cash_flow: latest.fields.operating_cash_flow, + total_assets: latest.fields.total_assets, + total_equity: latest.fields.total_equity, + shares_outstanding: latest.fields.shares_outstanding, + ttm_revenue: ttm.and_then(|t| t.flows.revenue), + ttm_net_income: ttm.and_then(|t| t.flows.net_income), + ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow), + ttm_period_end: ttm.map(|t| t.ending_period_end), + ttm_currency: ttm.map(|t| t.currency.clone()), + ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag), + } +} + +fn read_year(out_dir: &Path, year: i32) -> Vec { + read_parquet_rows(&out_dir.join(format!("fundamentals_pit/year={year}/part.parquet"))) +} + +fn list_year_dirs(out_dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(out_dir.join("fundamentals_pit")) + .expect("read dataset dir") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with("year=")) + .collect(); + names.sort(); + names +} + +/// Deterministic LCG so fixtures are reproducible without an RNG crate. +struct Lcg(u64); + +impl Lcg { + fn next_u32(&mut self) -> u32 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as u32 + } + fn chance(&mut self, pct: u32) -> bool { + self.next_u32() % 100 < pct + } + fn opt(&mut self, pct_null: u32, v: f64) -> Option { + if self.chance(pct_null) { + None + } else { + Some(v) } - assert!(!tmp - .path() - .join("fundamentals_pit/year=2023/part.parquet") - .exists()); - assert!(!tmp - .path() - .join("fundamentals_pit/year=2024/part.parquet") - .exists()); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); } } #[test] -fn rejects_invalid_options_dates_strings_and_inconsistent_ttm_metadata() { - let tmp = TempDirGuard::new("reject-validation"); - let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); - - // row_group_rows == 0 - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[sample_row(1, ts)], - FundamentalsPitWriteOptions { - row_group_rows: 0, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, +fn partition_files_contain_exact_expected_row_sequence_per_year() { + let tmp = TempDirGuard::new("qa-partition-exact"); + let ttm = |end: i32, rev: f64| FundamentalsTtm { + ending_period_end: end, + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(rev), + net_income: None, + operating_cash_flow: Some(rev / 2.0), + }, + has_estimated_lag: false, + }; + let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); + let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); + let rows = vec![ + make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(10.0), + None, ), - Err(ParquetFundamentalsError::InvalidRowGroupRows) - )); - - // Invalid Zstd level - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[sample_row(1, ts)], - FundamentalsPitWriteOptions { - row_group_rows: 10, - zstd_level: 999, - }, + make_row( + 1, + ts_2023_end, + day(2023, 9, 30), + Some(11.0), + Some(ttm(day(2023, 9, 30), 40.0)), ), - Err(ParquetFundamentalsError::InvalidZstdLevel { level: 999 }) - )); - - // Partition year out of range - let mut bad_year = sample_row(1, utc_micros(MIN_PARQUET_YEAR - 1, 6, 1, 0, 0, 0, 0)); - bad_year.period_known_at_micros = bad_year.effective_known_at_micros; - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[bad_year], - FundamentalsPitWriteOptions::default(), + make_row( + 1, + ts_2024_start, + day(2023, 12, 31), + Some(12.0), + Some(ttm(day(2023, 12, 31), 44.0)), ), - Err(ParquetFundamentalsError::PartitionYearOutOfRange { .. }) - )); - - // period_end out of range - let mut bad_period = sample_row(1, ts); - bad_period.period_end = day(MAX_PARQUET_YEAR + 1, 1, 1); - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[bad_period], - FundamentalsPitWriteOptions::default(), + make_row( + 2, + utc_micros(2023, 8, 1, 14, 0, 0, 0), + day(2023, 6, 30), + None, + None, ), - Err(ParquetFundamentalsError::PeriodEndOutOfRange { .. }) - )); - - // period_known_at > effective_known_at - let mut future_period_known = sample_row(1, ts); - future_period_known.period_known_at_micros = ts + 1; - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[future_period_known], - FundamentalsPitWriteOptions::default(), + make_row( + 2, + utc_micros(2024, 2, 1, 14, 0, 0, 0), + day(2023, 12, 31), + Some(21.0), + None, ), - Err(ParquetFundamentalsError::PeriodKnownAtAfterEffectiveKnownAt { .. }) - )); - - // Empty required strings - let mut empty_source = sample_row(1, ts); - empty_source.known_at_source = Cow::Borrowed(" "); - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[empty_source], - FundamentalsPitWriteOptions::default(), + make_row( + 3, + utc_micros(2023, 11, 1, 14, 0, 0, 0), + day(2023, 9, 30), + Some(30.0), + None, ), - Err(ParquetFundamentalsError::EmptyKnownAtSource { .. }) - )); - - // Partial TTM metadata (ttm_currency missing while ttm_period_end present) - let mut partial_ttm = sample_row(1, ts); - partial_ttm.ttm_currency = None; - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[partial_ttm], - FundamentalsPitWriteOptions::default(), + make_row( + 3, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + day(2024, 3, 31), + Some(31.0), + Some(ttm(day(2024, 3, 31), 120.0)), ), - Err(ParquetFundamentalsError::InconsistentTtmMetadata { .. }) - )); + ]; - // TTM flow present while all TTM metadata is None - let mut orphan_ttm_flow = sample_row(1, ts); - orphan_ttm_flow.ttm_period_end = None; - orphan_ttm_flow.ttm_currency = None; - orphan_ttm_flow.ttm_has_estimated_lag = None; - assert!(matches!( - write_fundamentals_pit_dataset( - tmp.path(), - &[orphan_ttm_flow], - FundamentalsPitWriteOptions::default(), - ), - Err(ParquetFundamentalsError::InconsistentTtmMetadata { .. }) - )); + write_fundamentals_pit_dataset( + tmp.path(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .expect("write"); - assert!(!tmp.path().join("fundamentals_pit").exists()); + let expected_2023: Vec<_> = [0, 1, 3, 5] + .iter() + .map(|&i| expected_decoded(&rows[i])) + .collect(); + let expected_2024: Vec<_> = [2, 4, 6] + .iter() + .map(|&i| expected_decoded(&rows[i])) + .collect(); + assert_eq!(list_year_dirs(tmp.path()), vec!["year=2023", "year=2024"]); + assert_eq!(read_year(tmp.path(), 2023), expected_2023); + assert_eq!(read_year(tmp.path(), 2024), expected_2024); } #[test] -fn failed_later_year_publish_rolls_back_and_preserves_existing_partitions_byte_for_byte() { - let tmp = TempDirGuard::new("rollback-existing"); +fn seeded_mixed_null_patterns_round_trip_across_many_row_groups() { + let tmp = TempDirGuard::new("qa-seeded"); + let mut rng = Lcg(0x5EED_1430); + let mut rows = Vec::new(); + for listing_id in 1..=9_i32 { + for q in 0..12_i32 { + // One quarter apart; spans 2021..=2023 so multiple partitions get interleaved. + let ts = utc_micros( + 2021 + q / 4, + (q % 4) as u32 * 3 + 2, + 10, + 20, + 30, + 0, + i64::from(listing_id), + ); + let period_end = day(2021 + q / 4, (q % 4) as u32 * 3 + 1, 1); + let base = f64::from(listing_id * 1000 + q); + let estimated = rng.chance(30); + let currency = if rng.chance(20) { "CAD" } else { "USD" }; + let ttm = if rng.chance(40) { + None + } else { + Some(FundamentalsTtm { + ending_period_end: period_end, + currency: currency.to_string(), + flows: TtmFlowFields { + revenue: rng.opt(25, base * 4.0), + net_income: rng.opt(25, -base * 0.25), + operating_cash_flow: rng.opt(25, 0.0), + }, + has_estimated_lag: rng.chance(50), + }) + }; + rows.push(FundamentalsPitParquetRow::new( + listing_id, + ts, + Cow::Borrowed(if estimated { + KNOWN_AT_SOURCE_STATUTORY_LAG + } else { + KNOWN_AT_SOURCE_FILING_TIMESTAMP + }), + estimated, + FundamentalsPitLatestPeriod { + period_end, + fiscal_period: Cow::Borrowed(if q % 4 == 3 { "FY" } else { "Q" }), + currency: currency.to_string(), + period_known_at_micros: ts - 1, + fields: FundamentalsFields { + revenue: rng.opt(20, base), + net_income: rng.opt(20, -base / 10.0), + operating_cash_flow: rng.opt(20, base / 7.0), + total_assets: rng.opt(20, base * 5.0), + total_equity: rng.opt(20, base * 2.0), + shares_outstanding: rng.opt(20, 1.0e9), + }, + }, + ttm, + )); + } + } + // Sanity: the fixture really exercises all-null and all-present TTM in the same file. + assert!(rows.iter().any(|r| r.ttm.is_none())); + assert!(rows + .iter() + .any(|r| r.ttm.as_ref().is_some_and(|t| t.flows.revenue.is_none()))); - // Seed an existing 2023 partition. - let initial_rows = vec![sample_row(1, utc_micros(2023, 8, 1, 20, 0, 0, 0))]; - write_fundamentals_pit_dataset( + let stats = write_fundamentals_pit_dataset( tmp.path(), - &initial_rows, - FundamentalsPitWriteOptions::default(), + &rows, + FundamentalsPitWriteOptions { + row_group_rows: 5, + zstd_level: 1, + }, ) - .expect("seed initial 2023 partition"); + .expect("write seeded dataset"); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!( + stats.rows_by_year, + BTreeMap::from([(2021, 36), (2022, 36), (2023, 36)]) + ); + // 36 rows per year at 5 rows per group -> 8 groups per year. + assert_eq!(stats.row_groups_written, 24); + for year in 2021..=2023 { + let expected: Vec<_> = rows + .iter() + .filter(|r| partition_year_utc(r.effective_known_at_micros) == year) + .map(expected_decoded) + .collect(); + assert_eq!(read_year(tmp.path(), year), expected, "year {year}"); + } + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() { + // Listing 7 (TSXV/CSE venue) files Q1 via a 10-Q; Q2 has no filing and no report date, + // so its known_at falls back to period_end + 60d at 16:05 America/Toronto. + let listing_id = 7_i32; + let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::TsxvCse)]); + let p_q1 = day(2024, 3, 31); + let p_q2 = day(2024, 6, 30); + let fields = |rev: f64| FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev / 10.0), + operating_cash_flow: None, + total_assets: Some(900.0), + total_equity: Some(400.0), + shares_outstanding: Some(50.0), + }; + let observations = vec![ + obs( + listing_id, + p_q1, + FiscalPeriod::Quarterly, + "CAD", + None, + fields(100.0), + ), + obs( + listing_id, + p_q2, + FiscalPeriod::Quarterly, + "CAD", + None, + fields(130.0), + ), + ]; + let filings = vec![filing(listing_id, "2024-05-10T16:30:00 EDT", "10-Q")]; + + let build = build_fundamentals_rows(observations, filings, &venues); + let snaps = build_fundamentals_snapshots(&build.rows, 4).expect("snapshots"); + assert_eq!(snaps.len(), 2); + let rows: Vec = + snaps.iter().map(FundamentalsPitParquetRow::from).collect(); + + let tmp = TempDirGuard::new("qa-estimated"); + write_fundamentals_pit_dataset(tmp.path(), &rows, FundamentalsPitWriteOptions::default()) + .expect("write"); + let decoded = read_year(tmp.path(), 2024); + assert_eq!( + decoded, + rows.iter().map(expected_decoded).collect::>() + ); + + // Q1: filing-backed, at the 10-Q's UTC timestamp. + let ts_q1 = utc_micros(2024, 5, 10, 20, 30, 0, 0); + assert_eq!(decoded[0].effective_known_at, ts_q1); + assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!decoded[0].has_estimated_lag); + assert_eq!(decoded[0].period_end, p_q1); + assert_eq!(decoded[0].period_known_at, ts_q1); + assert_eq!(decoded[0].currency, "CAD"); + + // Q2: estimated, 2024-06-30 + 60d = 2024-08-29 16:05 EDT = 20:05 UTC. + let ts_q2_est = utc_micros(2024, 8, 29, 20, 5, 0, 0); + assert_eq!(decoded[1].effective_known_at, ts_q2_est); + assert_eq!(decoded[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(decoded[1].has_estimated_lag); + assert_eq!(decoded[1].period_end, p_q2); + assert_eq!(decoded[1].period_known_at, ts_q2_est); + assert_eq!(decoded[1].revenue, Some(130.0)); + assert_eq!(decoded[1].operating_cash_flow, None); + // Only two quarters exist, so TTM is unavailable and every ttm_* column is null. + for r in &decoded { + assert_eq!(r.ttm_revenue, None); + assert_eq!(r.ttm_net_income, None); + assert_eq!(r.ttm_operating_cash_flow, None); + assert_eq!(r.ttm_period_end, None); + assert_eq!(r.ttm_currency, None); + assert_eq!(r.ttm_has_estimated_lag, None); + } +} + +#[test] +fn rewrite_replaces_only_years_present_in_new_input() { + let tmp = TempDirGuard::new("qa-rewrite"); + let first = vec![ + make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(10.0), + None, + ), + make_row( + 1, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + day(2024, 3, 31), + Some(20.0), + None, + ), + ]; + write_fundamentals_pit_dataset(tmp.path(), &first, FundamentalsPitWriteOptions::default()) + .expect("first write"); let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let original_2023_bytes = fs::read(&part_2023).unwrap(); + let bytes_2023 = fs::read(&part_2023).expect("read 2023"); - // Attempt a 2-year write (2023 update + 2024 new) where publishing 2024 fails because a - // directory occupies `year=2024/part.parquet` right before rename. - let mut updated_2023 = sample_row(1, utc_micros(2023, 8, 1, 20, 0, 0, 0)); - updated_2023.revenue = Some(999.0); - let new_2024 = sample_row(1, utc_micros(2024, 5, 1, 20, 0, 0, 0)); + let second = vec![ + make_row( + 5, + utc_micros(2024, 2, 1, 14, 0, 0, 0), + day(2023, 12, 31), + Some(55.0), + None, + ), + make_row( + 5, + utc_micros(2024, 6, 1, 14, 0, 0, 0), + day(2024, 3, 31), + Some(56.0), + None, + ), + ]; + let stats = + write_fundamentals_pit_dataset(tmp.path(), &second, FundamentalsPitWriteOptions::default()) + .expect("second write"); + assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 2)])); - let err = write_fundamentals_pit_dataset_with_hooks( - tmp.path(), - &[updated_2023, new_2024], - FundamentalsPitWriteOptions::default(), - DEFAULT_LOCK_TIMEOUT, - |year, final_path, _bak| { - if year == 2024 { - fs::create_dir_all(final_path).expect("inject directory conflict at 2024 target"); + // 2024 is fully replaced (no merge with old rows); 2023 is untouched byte for byte. + assert_eq!( + read_year(tmp.path(), 2024), + second.iter().map(expected_decoded).collect::>() + ); + assert_eq!(fs::read(&part_2023).expect("reread 2023"), bytes_2023); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); +} + +#[test] +fn identical_input_produces_byte_identical_partitions() { + let rows = vec![ + make_row( + 1, + utc_micros(2023, 5, 1, 14, 0, 0, 0), + day(2023, 3, 31), + Some(10.0), + None, + ), + make_row( + 2, + utc_micros(2024, 5, 1, 14, 0, 0, 0), + day(2024, 3, 31), + None, + None, + ), + ]; + let a = TempDirGuard::new("qa-determinism-a"); + let b = TempDirGuard::new("qa-determinism-b"); + let opts = FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + write_fundamentals_pit_dataset(a.path(), &rows, opts).expect("write a"); + write_fundamentals_pit_dataset(b.path(), &rows, opts).expect("write b"); + for year in [2023, 2024] { + let rel = format!("fundamentals_pit/year={year}/part.parquet"); + assert_eq!( + fs::read(a.path().join(&rel)).expect("read a"), + fs::read(b.path().join(&rel)).expect("read b"), + "year {year} bytes differ between identical runs" + ); + } +} + +#[test] +fn remaining_validation_errors_are_typed_and_publish_nothing() { + let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); + let valid = make_row(1, ts - 1, day(2024, 3, 31), Some(1.0), None); + let defaults = FundamentalsPitWriteOptions::default(); + + let run = |label: &str, bad: FundamentalsPitParquetRow, opts: FundamentalsPitWriteOptions| { + let tmp = TempDirGuard::new(label); + let err = write_fundamentals_pit_dataset(tmp.path(), [valid.clone(), bad], opts) + .expect_err("invalid input must fail"); + let year_dir = tmp.path().join("fundamentals_pit/year=2024"); + assert!( + !year_dir.join("part.parquet").exists(), + "{label}: partial file published" + ); + assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + err + }; + + let mut nan_row = make_row(1, ts, day(2024, 3, 31), Some(f64::NAN), None); + nan_row.has_estimated_lag = true; + let err = run("qa-nan", nan_row, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::NonFiniteValue { + row_index: 1, + field: "revenue", + .. } + ), + "got {err:?}" + ); + + let inf_ttm = make_row( + 1, + ts, + day(2024, 3, 31), + Some(1.0), + Some(FundamentalsTtm { + ending_period_end: day(2024, 3, 31), + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(1.0), + net_income: None, + operating_cash_flow: Some(f64::INFINITY), + }, + has_estimated_lag: false, + }), + ); + let err = run("qa-inf-ttm", inf_ttm, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::NonFiniteValue { + field: "ttm_operating_cash_flow", + .. + } + ), + "got {err:?}" + ); + + let mut blank_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); + blank_source.known_at_source = Cow::Borrowed(" "); + let err = run("qa-blank-source", blank_source, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::EmptyKnownAtSource { row_index: 1, .. } + ), + "got {err:?}" + ); + + let mut invalid_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); + invalid_source.known_at_source = Cow::Borrowed("manual_override"); + let err = run("qa-invalid-source", invalid_source, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::InvalidKnownAtSource { + row_index: 1, + ref value, + .. + } if value == "manual_override" + ), + "got {err:?}" + ); + + let mut padded_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); + padded_source.known_at_source = Cow::Borrowed(" filing_timestamp "); + let err = run("qa-padded-source", padded_source, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::InvalidKnownAtSource { + row_index: 1, + ref value, + .. + } if value == " filing_timestamp " + ), + "got {err:?}" + ); + + let blank_ttm_currency = make_row( + 1, + ts, + day(2024, 3, 31), + Some(1.0), + Some(FundamentalsTtm { + ending_period_end: day(2024, 3, 31), + currency: String::new(), + flows: TtmFlowFields { + revenue: None, + net_income: None, + operating_cash_flow: None, + }, + has_estimated_lag: false, + }), + ); + let err = run("qa-blank-ttm-ccy", blank_ttm_currency, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::EmptyTtmCurrency { row_index: 1, .. } + ), + "got {err:?}" + ); + + let blank_currency = FundamentalsPitParquetRow::new( + 1, + ts, + Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), + false, + FundamentalsPitLatestPeriod { + period_end: day(2024, 3, 31), + fiscal_period: Cow::Borrowed("Q"), + currency: String::new(), + period_known_at_micros: ts, + fields: FundamentalsFields { + revenue: None, + net_income: None, + operating_cash_flow: None, + total_assets: None, + total_equity: None, + shares_outstanding: None, + }, + }, + None, + ); + let err = run("qa-blank-ccy", blank_currency, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::EmptyCurrency { row_index: 1, .. } + ), + "got {err:?}" + ); + + // Year 2201 is above MAX_PARQUET_YEAR (2200). + let far_future = make_row( + 1, + utc_micros(2201, 1, 1, 0, 0, 0, 0), + day(2024, 3, 31), + Some(1.0), + None, + ); + let err = run("qa-year-range", far_future, defaults); + assert!( + matches!( + err, + ParquetFundamentalsError::PartitionYearOutOfRange { + row_index: 1, + year: 2201, + .. + } + ), + "got {err:?}" + ); + + // Option validation happens before any filesystem side effects. + let tmp = TempDirGuard::new("qa-bad-options"); + let err = write_fundamentals_pit_dataset( + tmp.path(), + [valid.clone()], + FundamentalsPitWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, }, ) .unwrap_err(); - assert!(matches!(err, ParquetFundamentalsError::Io { .. })); - - // 2023 must be restored byte-for-byte; 2024 must not contain a published file. - assert_eq!(fs::read(&part_2023).unwrap(), original_2023_bytes); - assert!(part_2024.is_dir(), "injected blocker dir remains untouched"); - fs::remove_dir(&part_2024).unwrap(); - assert!(!part_2024.exists()); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); + assert!( + matches!(err, ParquetFundamentalsError::InvalidRowGroupRows), + "got {err:?}" + ); + let err = write_fundamentals_pit_dataset( + tmp.path(), + [valid], + FundamentalsPitWriteOptions { + row_group_rows: 1, + zstd_level: 99, + }, + ) + .unwrap_err(); + assert!( + matches!( + err, + ParquetFundamentalsError::InvalidZstdLevel { level: 99 } + ), + "got {err:?}" + ); + assert!(!tmp.path().join("fundamentals_pit").exists()); } diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index fd9b89c2..00d6f1a4 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -363,6 +363,25 @@ fn next_column<'a>( } } +pub(crate) fn write_bool_col( + rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, + values: &[bool], + def_levels: Option<&[i16]>, +) -> Result<(), ParquetError> { + let mut col = next_column(rg_writer)?; + match col.untyped() { + ColumnWriter::BoolColumnWriter(typed) => { + typed.write_batch(values, def_levels, None)?; + } + _ => { + return Err(ParquetError::General( + "expected BOOLEAN column writer".to_string(), + )); + } + } + col.close() +} + pub(crate) fn write_i32_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, values: &[i32],