T-156: merge master

This commit is contained in:
Studio 2026-12-02 08:49:42 -05:00
commit 498b560c85
24 changed files with 7041 additions and 1375 deletions

View file

@ -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();

View file

@ -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, <standardized statement columns...>)`.
- **`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)`.

View file

@ -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 {

View file

@ -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<Bar1mRow, 'vwap' | 'session' | 'source'> & {
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<void>;
}
/** 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<void>;
writeFx1m(row: Fx1mIlpV2Row): Promise<void>;
flush(): Promise<void>;
finish(): Promise<IlpV2BatchWriterStats>;
}
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=<epoch_micros>t` (signed 64-bit integer preserved as supplied)
* - Designated timestamp ` <epoch_micros>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 ` <epoch_micros>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<void> = Promise.resolve();
function enqueue<T>(operation: () => Promise<T>): Promise<T> {
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<void> {
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<void> {
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<void> {
const snapshot = snapshotBar1mRow(row);
return enqueue(async () => {
assertHealthyForMutation('writeBar1m');
const encoded = encodeBar1mIlpV2(snapshot);
await enqueueEncodedRow(encoded);
});
},
writeFx1m(row: Fx1mIlpV2Row): Promise<void> {
const snapshot = snapshotFx1mRow(row);
return enqueue(async () => {
assertHealthyForMutation('writeFx1m');
const encoded = encodeFx1mIlpV2(snapshot);
await enqueueEncodedRow(encoded);
});
},
flush(): Promise<void> {
return enqueue(async () => {
assertHealthyForMutation('flush');
await flushPending();
});
},
finish(): Promise<IlpV2BatchWriterStats> {
return enqueue(async () => {
assertHealthyForMutation('finish');
await flushPending();
finished = true;
return {
rows: writtenRows,
batches: writtenBatches,
bytes: writtenBytes,
};
});
},
};
}

View file

@ -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,

View file

@ -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<typeof getLogger>;

View file

@ -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> = {}): 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> = {}): 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<void> {
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<void> {
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<void> {
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<void> {
order.push(`write:${b.byteLength}`);
if (release === null) {
return new Promise<void>(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}`]);
});
});

View file

@ -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> = {}): 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> = {}): 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<void> {
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<void> {
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
batches.push(batch.slice());
return new Promise<void>(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<void> {
sinkCalls += 1;
if (sinkCalls === 1) {
acceptedBatches.push(batch.slice());
return Promise.resolve();
}
return new Promise<void>((_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);
});
});

View file

@ -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<MarketDataStore, 'bars'>`, 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).

View file

@ -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",

View file

@ -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';

View file

@ -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<MarketDataStore, 'bars'>;
}
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<string, unknown> {
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<string, unknown> {
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<BarBatch>`
* 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);
},
};
}

File diff suppressed because it is too large Load diff

View file

@ -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> | 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([]);

View file

@ -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<void>)[] = [];
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([]);
});

View file

@ -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<string[]> {
const postgres = {
transaction: async <T>(callback: (client: { query: (sql: string) => unknown }) => Promise<T>) =>
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');
});
});

View file

@ -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> | 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<unknown>,
expectedCode: string,
messagePattern?: RegExp
): Promise<void> {
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<ProtectionTriggerRow[]> {
const result = await pool.query<ProtectionTriggerRow>(
`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<string, string | null> = {
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);
});
});

View file

@ -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',

View file

@ -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<Fx1mRow<'static>>,
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<BsonStreamError> for CurateFx1mBsonError {
fn from(err: BsonStreamError) -> Self {
Self::Stream(err)
}
}
impl From<IlpWriterError> 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<Fx1mRow<'static>>,
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<W: Write + Send>(
curated: CurateFx1mOutput,
writer: &mut IlpShardedWriter<W>,
) -> Result<CurateFx1mWriteReport, IlpWriterError> {
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<Item = RawEodIntradayBar<'a>>,
{
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<W>,
) -> Result<CurateFx1mWriteReport, IlpWriterError>
where
W: Write + Send,
B: IntoIterator<Item = RawEodIntradayBar<'a>>,
{
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<R, W>(
reader: R,
options: BsonStreamOptions,
writer: &mut IlpShardedWriter<W>,
) -> Result<CurateFx1mBsonReport, CurateFx1mBsonError>
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;

View file

@ -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<usize> {
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"));
}

View file

@ -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,

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -363,6 +363,25 @@ fn next_column<'a>(
}
}
pub(crate) fn write_bool_col(
rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter<File>>,
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<File>>,
values: &[i32],