T-184: M2.1s — Real DuckDB store factory for the MCP copilot stdio host: openResearchCopilotStore(config) in libs/data/duckdb/src/research-copilot-store.ts (ResearchCopilotHostConfig → openDuckDbMarketDataStore → ManagedMarketDataStore, single Vault cutoff, real-DuckDB host test; no new deps, no pg, no bin)
This commit is contained in:
commit
e50a08ff65
37 changed files with 20693 additions and 119 deletions
|
|
@ -121,7 +121,13 @@ export async function createNodeDuckDbExecutor(
|
|||
): Promise<ClosableDuckDbExecutor> {
|
||||
const databasePath = options.databasePath ?? ':memory:';
|
||||
const instance = await DuckDBInstance.create(databasePath);
|
||||
const connection: DuckDBConnection = await instance.connect();
|
||||
let connection: DuckDBConnection;
|
||||
try {
|
||||
connection = await instance.connect();
|
||||
} catch (err) {
|
||||
instance.closeSync();
|
||||
throw err;
|
||||
}
|
||||
let closed = false;
|
||||
|
||||
const assertOpen = (): void => {
|
||||
|
|
@ -264,3 +270,7 @@ export {
|
|||
type DuckDbParam,
|
||||
type PinnedAdjFactorsArtifact,
|
||||
};
|
||||
export {
|
||||
openResearchCopilotStore,
|
||||
type OpenResearchCopilotStoreOptions,
|
||||
} from './research-copilot-store';
|
||||
|
|
|
|||
49
libs/data/duckdb/src/research-copilot-store.ts
Normal file
49
libs/data/duckdb/src/research-copilot-store.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
/**
|
||||
* Real DuckDB `MarketDataStore` factory for the MCP research copilot stdio host
|
||||
* (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`).
|
||||
*
|
||||
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff shared
|
||||
* between the host and the underlying DuckDB store, and hardcodes
|
||||
* `vaultOperatorAuthorized: false` so every query remains strictly
|
||||
* `'vault_fenced'`.
|
||||
* - Returns a {@link ManagedMarketDataStore} (`{ store, close }`) whose
|
||||
* `close()` releases the underlying DuckDB connection and instance.
|
||||
* - Any failure during open (native connection creation or store validation)
|
||||
* releases already-acquired DuckDB resources before rejecting.
|
||||
*/
|
||||
|
||||
import type {
|
||||
ManagedMarketDataStore,
|
||||
ResearchCopilotHostConfig,
|
||||
ResearchCopilotStdioHostDeps,
|
||||
} from '@stock-bot/research/mcp';
|
||||
import { openDuckDbMarketDataStore } from './index';
|
||||
|
||||
export interface OpenResearchCopilotStoreOptions {
|
||||
/** Optional DuckDB database path; defaults to `':memory:'`. */
|
||||
readonly databasePath?: string;
|
||||
/** Optional environment overrides for DuckDB connection budget (`STOCKBOT_DUCKDB_*`). */
|
||||
readonly env?: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a Vault-fenced DuckDB-backed {@link ManagedMarketDataStore} from a
|
||||
* validated {@link ResearchCopilotHostConfig} for `ResearchCopilotStdioHostDeps.openStore`.
|
||||
*/
|
||||
export const openResearchCopilotStore = (async (
|
||||
config: ResearchCopilotHostConfig,
|
||||
options?: OpenResearchCopilotStoreOptions
|
||||
): Promise<ManagedMarketDataStore> => {
|
||||
const opened = await openDuckDbMarketDataStore({
|
||||
curatedRoot: config.curatedRoot,
|
||||
vaultCutoffTs: config.vaultCutoffTs,
|
||||
vaultOperatorAuthorized: false,
|
||||
...(options?.databasePath !== undefined ? { databasePath: options.databasePath } : {}),
|
||||
...(options?.env !== undefined ? { env: options.env } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
store: opened.store,
|
||||
close: opened.close,
|
||||
};
|
||||
}) satisfies ResearchCopilotStdioHostDeps['openStore'];
|
||||
394
libs/data/duckdb/test/research-copilot-store-qa.test.ts
Normal file
394
libs/data/duckdb/test/research-copilot-store-qa.test.ts
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api';
|
||||
import { createNodeDuckDbExecutor, openResearchCopilotStore } from '@stock-bot/duckdb';
|
||||
import {
|
||||
MarketDataStoreValidationError,
|
||||
VaultHoldoutFenceError,
|
||||
type BarRecord,
|
||||
} from '@stock-bot/research/market-data-store';
|
||||
import {
|
||||
runResearchCopilotStdioHost,
|
||||
type PostgresResearchCopilotExecutor,
|
||||
type QueryDataResultPayload,
|
||||
type ResearchCopilotHostConfig,
|
||||
type StdioInput,
|
||||
type StdioOutput,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
// QA coverage for T-184 beyond the implementation tests:
|
||||
// - budget env (`STOCKBOT_DUCKDB_*`) is forwarded and reaches DuckDB;
|
||||
// - invalid budget env fails closed without leaking native handles or the Postgres URL;
|
||||
// - `openStore: openResearchCopilotStore` works unwrapped (default env resolution);
|
||||
// - the Vault cutoff comes from `config.vaultCutoffTs` (not a constant);
|
||||
// - `databasePath` is forwarded.
|
||||
// Fixture: listing 202, rows at 2025-03-10/11/12 20:00Z (known_at == ts).
|
||||
|
||||
const LISTING_ID = 202;
|
||||
const DAY1_MS = Date.UTC(2025, 2, 10, 20, 0, 0, 0);
|
||||
const DAY2_MS = Date.UTC(2025, 2, 11, 20, 0, 0, 0);
|
||||
const DAY3_MS = Date.UTC(2025, 2, 12, 20, 0, 0, 0);
|
||||
const FIXED_NOW_MS = Date.UTC(2025, 2, 11, 12, 0, 0, 0);
|
||||
const PG_SECRET = 'qa_only_fake_pw_7c1e';
|
||||
const FAKE_POSTGRES_URL = `postgresql://research_ro:${PG_SECRET}@127.0.0.1:5433/trading_bot_dev`;
|
||||
const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
const spies: Array<{ mockRestore(): void }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (spies.length > 0) {
|
||||
spies.pop()?.mockRestore();
|
||||
}
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop();
|
||||
if (dir !== undefined) {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function track<T extends { mockRestore(): void }>(spy: T): T {
|
||||
spies.push(spy);
|
||||
return spy;
|
||||
}
|
||||
|
||||
function bar(ts: number, base: number): BarRecord {
|
||||
return {
|
||||
listingId: LISTING_ID,
|
||||
ts,
|
||||
open: base,
|
||||
high: base + 1,
|
||||
low: base - 1,
|
||||
close: base + 0.5,
|
||||
volume: 1000 * base,
|
||||
vwap: base + 0.25,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
const BAR1 = bar(DAY1_MS, 10);
|
||||
const BAR2 = bar(DAY2_MS, 20);
|
||||
const BAR3 = bar(DAY3_MS, 30);
|
||||
|
||||
function config(curatedRoot: string, vaultCutoffTs: number): ResearchCopilotHostConfig {
|
||||
return {
|
||||
postgresUrl: FAKE_POSTGRES_URL,
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
principalId: AGENT_PRINCIPAL,
|
||||
libraryRoot: '/tmp/unused-library-root',
|
||||
referenceListingIds: { XNYS: [LISTING_ID] },
|
||||
};
|
||||
}
|
||||
|
||||
async function makeRoot(): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-t184-qa-'));
|
||||
tempDirs.push(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
function utcTs(ms: number): string {
|
||||
return `${new Date(ms).toISOString().slice(0, 19).replace('T', ' ')}+00`;
|
||||
}
|
||||
|
||||
function utcDate(ms: number): string {
|
||||
return new Date(ms).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
async function writeFixture(root: string): Promise<string> {
|
||||
const curatedRoot = join(root, 'curated');
|
||||
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
|
||||
const rows = [BAR1, BAR2, BAR3]
|
||||
.map(
|
||||
b =>
|
||||
// Explicit UTC literals: casting naive timestamps to TIMESTAMPTZ would use the host TimeZone.
|
||||
`(${LISTING_ID}::INTEGER, DATE '${utcDate(b.ts)}', TIMESTAMPTZ '${utcTs(b.ts)}', ${b.open}::DOUBLE, ${b.high}::DOUBLE, ${b.low}::DOUBLE, ${b.close}::DOUBLE, ${b.volume}::DOUBLE, ${b.vwap}::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '${utcTs(b.knownAt)}')`
|
||||
)
|
||||
.join(',\n');
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES ${rows})
|
||||
AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
|
||||
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
return curatedRoot;
|
||||
}
|
||||
|
||||
async function collect(
|
||||
iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }>
|
||||
): Promise<BarRecord[]> {
|
||||
const out: BarRecord[] = [];
|
||||
for await (const batch of iterable) {
|
||||
out.push(...batch.rows);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function captureError(fn: () => Promise<unknown>): Promise<unknown> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function fullRangeQuery() {
|
||||
return {
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d' as const,
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-31',
|
||||
asOf: '2025-03-31',
|
||||
adjustment: 'raw' as const,
|
||||
};
|
||||
}
|
||||
|
||||
function memoryStdio(messages: readonly unknown[]): {
|
||||
readonly input: StdioInput;
|
||||
readonly output: StdioOutput;
|
||||
raw(): string;
|
||||
} {
|
||||
const chunks: string[] = [];
|
||||
return {
|
||||
input: {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const m of messages) {
|
||||
yield `${JSON.stringify(m)}\n`;
|
||||
}
|
||||
},
|
||||
},
|
||||
output: {
|
||||
write(chunk: string): boolean {
|
||||
chunks.push(chunk);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
raw: () => chunks.join(''),
|
||||
};
|
||||
}
|
||||
|
||||
function fakePg(): { executor: PostgresResearchCopilotExecutor; calls: number } {
|
||||
const state = {
|
||||
calls: 0,
|
||||
executor: {
|
||||
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
|
||||
state.calls += 1;
|
||||
return { rows: [] };
|
||||
},
|
||||
} as PostgresResearchCopilotExecutor,
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
function hostMessages(): unknown[] {
|
||||
return [
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: '2024-11-05',
|
||||
capabilities: {},
|
||||
clientInfo: { name: 't184-qa', version: '1.0.0' },
|
||||
},
|
||||
},
|
||||
{ jsonrpc: '2.0', method: 'notifications/initialized' },
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
id: 2,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'query_data',
|
||||
arguments: {
|
||||
listingIds: [LISTING_ID],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-31',
|
||||
asOf: '2025-03-31',
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
describe('openResearchCopilotStore QA (T-184)', () => {
|
||||
test('uses config.vaultCutoffTs as the only cutoff: moving the cutoff moves the visible rows', async () => {
|
||||
const curatedRoot = await writeFixture(await makeRoot());
|
||||
|
||||
// Cutoff exactly at DAY2 ts: DAY2 (ts == cutoff) is excluded, only DAY1 visible.
|
||||
const atDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS));
|
||||
try {
|
||||
expect(await collect(atDay2.store.bars(fullRangeQuery()))).toEqual([BAR1]);
|
||||
} finally {
|
||||
await atDay2.close();
|
||||
}
|
||||
|
||||
// Cutoff 1ms after DAY2: DAY1 + DAY2 visible, DAY3 still fenced.
|
||||
const afterDay2 = await openResearchCopilotStore(config(curatedRoot, DAY2_MS + 1));
|
||||
try {
|
||||
expect(await collect(afterDay2.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2]);
|
||||
const err = await captureError(() =>
|
||||
collect(afterDay2.store.bars({ ...fullRangeQuery(), from: '2025-03-12' }))
|
||||
);
|
||||
expect(err).toBeInstanceOf(VaultHoldoutFenceError);
|
||||
} finally {
|
||||
await afterDay2.close();
|
||||
}
|
||||
|
||||
// Cutoff after all rows: everything visible (proves no hidden constant cutoff).
|
||||
const late = await openResearchCopilotStore(config(curatedRoot, Date.UTC(2025, 5, 1)));
|
||||
try {
|
||||
expect(await collect(late.store.bars(fullRangeQuery()))).toEqual([BAR1, BAR2, BAR3]);
|
||||
} finally {
|
||||
await late.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('forwards STOCKBOT_DUCKDB_* budget env so DuckDB receives the configured spill directory, threads and memory limit', async () => {
|
||||
const root = await makeRoot();
|
||||
const curatedRoot = await writeFixture(root);
|
||||
const spillDir = join(root, 'spill');
|
||||
await mkdir(spillDir, { recursive: true });
|
||||
|
||||
const runSpy = track(spyOn(DuckDBConnection.prototype, 'run'));
|
||||
const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), {
|
||||
env: {
|
||||
STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MB',
|
||||
STOCKBOT_DUCKDB_THREADS: '1',
|
||||
STOCKBOT_DUCKDB_TEMP_DIRECTORY: spillDir,
|
||||
},
|
||||
});
|
||||
try {
|
||||
expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
|
||||
const statements = runSpy.mock.calls.map(call => String(call[0]));
|
||||
expect(statements).toContain(`SET temp_directory = '${spillDir}';`);
|
||||
expect(statements).toContain('SET threads = 1;');
|
||||
expect(statements).toContain("SET memory_limit = '512MB';");
|
||||
});
|
||||
|
||||
test('invalid budget env fails closed: open rejects, native connection and instance closed once, no Postgres URL in the error', async () => {
|
||||
const curatedRoot = await writeFixture(await makeRoot());
|
||||
const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
const err = await captureError(() =>
|
||||
openResearchCopilotStore(config(curatedRoot, DAY2_MS), {
|
||||
env: { STOCKBOT_DUCKDB_THREADS: 'not-a-number' },
|
||||
})
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(connClose).toHaveBeenCalledTimes(1);
|
||||
expect(instClose).toHaveBeenCalledTimes(1);
|
||||
const text = `${(err as Error).message} ${(err as Error).stack ?? ''}`;
|
||||
expect(text).not.toContain(PG_SECRET);
|
||||
expect(text).not.toContain('postgresql://');
|
||||
});
|
||||
|
||||
test('forwards databasePath: a file-backed DuckDB database is created at the given path', async () => {
|
||||
const root = await makeRoot();
|
||||
const curatedRoot = await writeFixture(root);
|
||||
const dbPath = join(root, 'copilot.duckdb');
|
||||
expect(existsSync(dbPath)).toBe(false);
|
||||
|
||||
const handle = await openResearchCopilotStore(config(curatedRoot, DAY2_MS), {
|
||||
databasePath: dbPath,
|
||||
});
|
||||
try {
|
||||
expect(existsSync(dbPath)).toBe(true);
|
||||
expect(await collect(handle.store.bars(fullRangeQuery()))).toEqual([BAR1]);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('host wired with openStore: openResearchCopilotStore (unwrapped, default env) serves query_data fenced at config cutoff and closes DuckDB once', async () => {
|
||||
const curatedRoot = await writeFixture(await makeRoot());
|
||||
const pg = fakePg();
|
||||
const io = memoryStdio(hostMessages());
|
||||
const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
await runResearchCopilotStdioHost({
|
||||
config: config(curatedRoot, DAY2_MS + 1),
|
||||
openExecutor: async () => ({ executor: pg.executor, close: async () => {} }),
|
||||
openStore: openResearchCopilotStore,
|
||||
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'qa-id',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: io.input, output: io.output },
|
||||
});
|
||||
|
||||
const lines = io
|
||||
.raw()
|
||||
.trimEnd()
|
||||
.split('\n')
|
||||
.map(l => JSON.parse(l) as { id: number; result: Record<string, unknown> });
|
||||
expect(lines.map(l => l.id)).toEqual([1, 2]);
|
||||
const envelope = lines[1]!.result as {
|
||||
isError?: boolean;
|
||||
content: Array<{ text: string }>;
|
||||
};
|
||||
expect(envelope.isError).toBeUndefined();
|
||||
const payload = JSON.parse(envelope.content[0]!.text) as QueryDataResultPayload;
|
||||
expect(payload.vaultCutoffTs).toBe(DAY2_MS + 1);
|
||||
expect(payload.toMs).toBe(DAY2_MS);
|
||||
expect(payload.rows).toEqual([BAR1, BAR2]);
|
||||
expect(io.raw()).not.toContain(PG_SECRET);
|
||||
expect(pg.calls).toBe(0);
|
||||
expect(connClose).toHaveBeenCalledTimes(1);
|
||||
expect(instClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('host with empty curatedRoot: query_data fails without hanging, leaks no Postgres URL, and DuckDB still closes once at EOF', async () => {
|
||||
const root = await makeRoot();
|
||||
const emptyRoot = join(root, 'curated');
|
||||
await mkdir(emptyRoot, { recursive: true });
|
||||
const io = memoryStdio(hostMessages());
|
||||
const connClose = track(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instClose = track(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
await runResearchCopilotStdioHost({
|
||||
config: config(emptyRoot, DAY2_MS),
|
||||
openExecutor: async () => ({ executor: fakePg().executor, close: async () => {} }),
|
||||
openStore: openResearchCopilotStore,
|
||||
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'qa-id',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: io.input, output: io.output },
|
||||
});
|
||||
|
||||
const lines = io
|
||||
.raw()
|
||||
.trimEnd()
|
||||
.split('\n')
|
||||
.map(
|
||||
l =>
|
||||
JSON.parse(l) as {
|
||||
id: number;
|
||||
result?: { isError?: boolean; content?: Array<{ text: string }> };
|
||||
error?: unknown;
|
||||
}
|
||||
);
|
||||
const toolResponse = lines.find(l => l.id === 2);
|
||||
expect(toolResponse).toBeDefined();
|
||||
const failed = toolResponse!.error !== undefined || toolResponse!.result?.isError === true;
|
||||
expect(failed).toBe(true);
|
||||
expect(io.raw()).not.toContain(PG_SECRET);
|
||||
expect(connClose).toHaveBeenCalledTimes(1);
|
||||
expect(instClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
530
libs/data/duckdb/test/research-copilot-store.test.ts
Normal file
530
libs/data/duckdb/test/research-copilot-store.test.ts
Normal file
|
|
@ -0,0 +1,530 @@
|
|||
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DuckDBConnection, DuckDBInstance } from '@duckdb/node-api';
|
||||
import {
|
||||
createNodeDuckDbExecutor,
|
||||
openResearchCopilotStore,
|
||||
} from '@stock-bot/duckdb';
|
||||
import {
|
||||
MarketDataStoreValidationError,
|
||||
VaultHoldoutFenceError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
type BarRecord,
|
||||
} from '@stock-bot/research/market-data-store';
|
||||
import {
|
||||
RESEARCH_COPILOT_HOST_NAME,
|
||||
RESEARCH_COPILOT_HOST_VERSION,
|
||||
runResearchCopilotStdioHost,
|
||||
type PostgresResearchCopilotExecutor,
|
||||
type QueryDataResultPayload,
|
||||
type ResearchCopilotHostConfig,
|
||||
type ResearchCopilotStdioHostDeps,
|
||||
type StdioInput,
|
||||
type StdioOutput,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
// Pinned synthetic fixture for T-184 (real-DuckDB store factory & stdio host wiring):
|
||||
// - Listing 101 (USD), Vault cutoff 2025-06-01T00:00:00.000Z
|
||||
// - Baseline visible row: 2025-05-30 20:00:00Z (known_at 2025-05-30 20:00:00Z)
|
||||
// - Excluded rows:
|
||||
// * at-cutoff ts: 2025-06-01 00:00:00Z (known_at 2025-05-30 20:00:00Z)
|
||||
// * post-cutoff ts: 2025-06-02 20:00:00Z (known_at 2025-06-02 20:00:00Z)
|
||||
// * late-known pre-cutoff ts: 2025-05-29 20:00:00Z (known_at 2025-06-01 00:00:00Z)
|
||||
|
||||
const LISTING_ID = 101;
|
||||
const VAULT_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0);
|
||||
const FIXED_NOW_MS = Date.UTC(2025, 4, 31, 12, 0, 0, 0);
|
||||
const FAKE_POSTGRES_URL =
|
||||
'postgresql://research_ro:test_only_not_a_real_secret@127.0.0.1:5433/trading_bot_dev?sslmode=disable';
|
||||
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
||||
|
||||
const EXPECTED_VISIBLE_BAR: BarRecord = {
|
||||
listingId: LISTING_ID,
|
||||
ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
|
||||
open: 100.5,
|
||||
high: 102.25,
|
||||
low: 99.75,
|
||||
close: 101.5,
|
||||
volume: 123_456,
|
||||
vwap: 101.1,
|
||||
knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
|
||||
};
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
const activeSpies: Array<{ mockRestore(): void }> = [];
|
||||
|
||||
function trackSpy<T extends { mockRestore(): void }>(spy: T): T {
|
||||
activeSpies.push(spy);
|
||||
return spy;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (activeSpies.length > 0) {
|
||||
activeSpies.pop()?.mockRestore();
|
||||
}
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop();
|
||||
if (dir !== undefined) {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function buildHostConfig(
|
||||
curatedRoot: string,
|
||||
overrides: Partial<ResearchCopilotHostConfig> = {}
|
||||
): ResearchCopilotHostConfig {
|
||||
return {
|
||||
postgresUrl: FAKE_POSTGRES_URL,
|
||||
curatedRoot,
|
||||
vaultCutoffTs: VAULT_CUTOFF_MS,
|
||||
principalId: VALID_AGENT_PRINCIPAL,
|
||||
libraryRoot: '/tmp/unused-library-root',
|
||||
referenceListingIds: { XNYS: [LISTING_ID] },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildDuckDbBudgetEnv(duckTempDir: string): Readonly<Record<string, string>> {
|
||||
return {
|
||||
STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCKBOT_DUCKDB_THREADS: '2',
|
||||
STOCKBOT_DUCKDB_TEMP_DIRECTORY: duckTempDir,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildBarsFixture(): Promise<{
|
||||
readonly curatedRoot: string;
|
||||
readonly duckTempDir: string;
|
||||
}> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-duckdb-'));
|
||||
tempDirs.push(root);
|
||||
const curatedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
|
||||
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(${LISTING_ID}::INTEGER, DATE '2025-05-29', TIMESTAMPTZ '2025-05-29 20:00:00+00', 94.0::DOUBLE, 96.0::DOUBLE, 93.5::DOUBLE, 95.0::DOUBLE, 80000.0::DOUBLE, 94.8::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-01 00:00:00+00'),
|
||||
(${LISTING_ID}::INTEGER, DATE '2025-05-30', TIMESTAMPTZ '2025-05-30 20:00:00+00', 100.5::DOUBLE, 102.25::DOUBLE, 99.75::DOUBLE, 101.5::DOUBLE, 123456.0::DOUBLE, 101.1::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'),
|
||||
(${LISTING_ID}::INTEGER, DATE '2025-06-01', TIMESTAMPTZ '2025-06-01 00:00:00+00', 199.0::DOUBLE, 201.0::DOUBLE, 198.0::DOUBLE, 200.0::DOUBLE, 200000.0::DOUBLE, 199.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-05-30 20:00:00+00'),
|
||||
(${LISTING_ID}::INTEGER, DATE '2025-06-02', TIMESTAMPTZ '2025-06-02 20:00:00+00', 299.0::DOUBLE, 301.0::DOUBLE, 298.0::DOUBLE, 300.0::DOUBLE, 300000.0::DOUBLE, 299.5::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-06-02 20:00:00+00')
|
||||
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
|
||||
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
|
||||
return { curatedRoot, duckTempDir };
|
||||
}
|
||||
|
||||
function createMemoryOutput(): {
|
||||
readonly output: StdioOutput;
|
||||
jsonLines(): unknown[];
|
||||
} {
|
||||
const chunks: string[] = [];
|
||||
const output: StdioOutput = {
|
||||
write(chunk: string): boolean {
|
||||
chunks.push(chunk);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
return {
|
||||
output,
|
||||
jsonLines: () => {
|
||||
const raw = chunks.join('');
|
||||
if (raw.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return raw
|
||||
.trimEnd()
|
||||
.split('\n')
|
||||
.map(line => JSON.parse(line) as unknown);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createMemoryInput(messages: readonly unknown[]): StdioInput {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const msg of messages) {
|
||||
yield `${JSON.stringify(msg)}\n`;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakePostgresExecutor(): {
|
||||
readonly executor: PostgresResearchCopilotExecutor;
|
||||
readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>;
|
||||
} {
|
||||
const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = [];
|
||||
const executor: PostgresResearchCopilotExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
calls.push({ text, params });
|
||||
return { rows: [] };
|
||||
},
|
||||
};
|
||||
return { executor, calls };
|
||||
}
|
||||
|
||||
async function collectBars(
|
||||
iterable: AsyncIterable<{ readonly rows: readonly BarRecord[] }>
|
||||
): Promise<BarRecord[]> {
|
||||
const rows: BarRecord[] = [];
|
||||
for await (const batch of iterable) {
|
||||
rows.push(...batch.rows);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
describe('openResearchCopilotStore (@duckdb/node-api)', () => {
|
||||
test('source invariants: no pg import, no process.env read, no console logging, always vault-fenced', () => {
|
||||
const sourcePath = join(import.meta.dir, '..', 'src', 'research-copilot-store.ts');
|
||||
const source = readFileSync(sourcePath, 'utf8');
|
||||
|
||||
expect(source).not.toMatch(/from\s+['"]pg['"]/);
|
||||
expect(source).not.toMatch(/require\(\s*['"]pg['"]\s*\)/);
|
||||
expect(source).not.toContain('process.env');
|
||||
expect(source).not.toMatch(/\bprocess\b/);
|
||||
expect(source).not.toContain('console.');
|
||||
expect(source).toContain('vaultOperatorAuthorized: false');
|
||||
|
||||
// Verify typed assignability to ResearchCopilotStdioHostDeps['openStore'] without casts.
|
||||
const directFactory: ResearchCopilotStdioHostDeps['openStore'] = openResearchCopilotStore;
|
||||
const wrappedFactory: ResearchCopilotStdioHostDeps['openStore'] = cfg =>
|
||||
openResearchCopilotStore(cfg);
|
||||
expect(typeof directFactory).toBe('function');
|
||||
expect(typeof wrappedFactory).toBe('function');
|
||||
});
|
||||
|
||||
test('enforces single Vault cutoff directly on store.bars(), replays identically, and blocks vault_evaluation_only even for operator principal', async () => {
|
||||
const { curatedRoot, duckTempDir } = await buildBarsFixture();
|
||||
const config = buildHostConfig(curatedRoot, { principalId: 'operator' });
|
||||
|
||||
const handle = await openResearchCopilotStore(config, {
|
||||
env: buildDuckDbBudgetEnv(duckTempDir),
|
||||
});
|
||||
|
||||
try {
|
||||
expect(Object.keys(handle).sort()).toEqual(['close', 'store']);
|
||||
|
||||
// Straddling query: to and asOf exceed cutoff -> only visible pre-cutoff row returned.
|
||||
const firstRun = await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-05-28',
|
||||
to: '2025-06-05',
|
||||
asOf: '2025-06-05',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
expect(firstRun).toEqual([EXPECTED_VISIBLE_BAR]);
|
||||
|
||||
// Replay produces identical results.
|
||||
const replayRun = await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-05-28',
|
||||
to: '2025-06-05',
|
||||
asOf: '2025-06-05',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
expect(replayRun).toEqual(firstRun);
|
||||
|
||||
// Query starting at cutoff throws VaultHoldoutFenceError.
|
||||
let atCutoffErr: unknown;
|
||||
try {
|
||||
await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-06-01',
|
||||
to: '2025-06-05',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
atCutoffErr = err;
|
||||
}
|
||||
expect(atCutoffErr).toBeInstanceOf(VaultHoldoutFenceError);
|
||||
|
||||
// Query starting after cutoff throws VaultHoldoutFenceError.
|
||||
let afterCutoffErr: unknown;
|
||||
try {
|
||||
await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-06-02',
|
||||
to: '2025-06-05',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
afterCutoffErr = err;
|
||||
}
|
||||
expect(afterCutoffErr).toBeInstanceOf(VaultHoldoutFenceError);
|
||||
|
||||
// vault_evaluation_only is always rejected even when config.principalId is 'operator'.
|
||||
let scopeErr: unknown;
|
||||
try {
|
||||
await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-05-28',
|
||||
to: '2025-06-05',
|
||||
adjustment: 'raw',
|
||||
scope: 'vault_evaluation_only',
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
scopeErr = err;
|
||||
}
|
||||
expect(scopeErr).toBeInstanceOf(VaultScopeNotAuthorizedError);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('wires into runResearchCopilotStdioHost end-to-end, serves initialize + query_data, and closes DuckDB exactly once at EOF', async () => {
|
||||
const { curatedRoot, duckTempDir } = await buildBarsFixture();
|
||||
const config = buildHostConfig(curatedRoot);
|
||||
const fakePg = createFakePostgresExecutor();
|
||||
const sink = createMemoryOutput();
|
||||
const input = createMemoryInput([
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: '2024-11-05',
|
||||
capabilities: {},
|
||||
clientInfo: { name: 'duckdb-host-test', version: '1.0.0' },
|
||||
},
|
||||
},
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
method: 'notifications/initialized',
|
||||
},
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
id: 2,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'query_data',
|
||||
arguments: {
|
||||
listingIds: [LISTING_ID],
|
||||
from: '2025-05-28',
|
||||
to: '2025-06-05',
|
||||
asOf: '2025-06-05',
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
// Install call-through spies after fixture writer is closed so counts reflect only the host store.
|
||||
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
let capturedStore: Awaited<ReturnType<typeof openResearchCopilotStore>>['store'] | undefined;
|
||||
|
||||
await runResearchCopilotStdioHost({
|
||||
config,
|
||||
openExecutor: async () => ({
|
||||
executor: fakePg.executor,
|
||||
close: async () => {},
|
||||
}),
|
||||
openStore: async cfg => {
|
||||
const opened = await openResearchCopilotStore(cfg, {
|
||||
env: buildDuckDbBudgetEnv(duckTempDir),
|
||||
});
|
||||
capturedStore = opened.store;
|
||||
return opened;
|
||||
},
|
||||
createLibraryCardReader: async () => ({
|
||||
listLibraryCards: async () => [],
|
||||
}),
|
||||
newId: () => 'id-1',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input, output: sink.output },
|
||||
});
|
||||
|
||||
const responses = sink.jsonLines() as Array<{
|
||||
readonly id: number;
|
||||
readonly result: Record<string, unknown>;
|
||||
}>;
|
||||
expect(responses).toHaveLength(2);
|
||||
|
||||
expect(responses[0]!.id).toBe(1);
|
||||
expect(responses[0]!.result.serverInfo).toEqual({
|
||||
name: RESEARCH_COPILOT_HOST_NAME,
|
||||
version: RESEARCH_COPILOT_HOST_VERSION,
|
||||
});
|
||||
|
||||
expect(responses[1]!.id).toBe(2);
|
||||
const toolEnvelope = responses[1]!.result as {
|
||||
readonly isError?: boolean;
|
||||
readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>;
|
||||
};
|
||||
expect(toolEnvelope.isError).toBeUndefined();
|
||||
|
||||
const payload = JSON.parse(toolEnvelope.content[0]!.text) as QueryDataResultPayload;
|
||||
expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_MS);
|
||||
expect(payload.clampedTo).toBe(true);
|
||||
expect(payload.clampedAsOf).toBe(true);
|
||||
expect(payload.toMs).toBe(VAULT_CUTOFF_MS - 1);
|
||||
expect(payload.asOfMs).toBe(VAULT_CUTOFF_MS - 1);
|
||||
expect(payload.rows).toEqual([EXPECTED_VISIBLE_BAR]);
|
||||
|
||||
expect(fakePg.calls).toHaveLength(0);
|
||||
expect(connCloseSpy).toHaveBeenCalledTimes(1);
|
||||
expect(instCloseSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Confirm the host-opened store rejects subsequent queries after EOF cleanup.
|
||||
expect(capturedStore).toBeDefined();
|
||||
let postCloseErr: unknown;
|
||||
try {
|
||||
await collectBars(
|
||||
capturedStore!.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-05-28',
|
||||
to: '2025-05-31',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
postCloseErr = err;
|
||||
}
|
||||
expect(postCloseErr).toBeInstanceOf(Error);
|
||||
expect((postCloseErr as Error).message).toContain('closed');
|
||||
});
|
||||
|
||||
test('directly opened handle resolves close() and rejects subsequent valid bars() queries', async () => {
|
||||
const { curatedRoot, duckTempDir } = await buildBarsFixture();
|
||||
const config = buildHostConfig(curatedRoot);
|
||||
|
||||
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
const handle = await openResearchCopilotStore(config, {
|
||||
env: buildDuckDbBudgetEnv(duckTempDir),
|
||||
});
|
||||
|
||||
await handle.close();
|
||||
await handle.close();
|
||||
|
||||
expect(connCloseSpy).toHaveBeenCalledTimes(1);
|
||||
expect(instCloseSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
let postCloseErr: unknown;
|
||||
try {
|
||||
await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-05-28',
|
||||
to: '2025-05-31',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
postCloseErr = err;
|
||||
}
|
||||
expect(postCloseErr).toBeInstanceOf(Error);
|
||||
expect((postCloseErr as Error).message).toContain('closed');
|
||||
});
|
||||
|
||||
test('fail-closed: empty curatedRoot rejects on first bars() read and closes cleanly in finally', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-mcp-empty-'));
|
||||
tempDirs.push(root);
|
||||
const emptyCuratedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
await mkdir(emptyCuratedRoot, { recursive: true });
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
const handle = await openResearchCopilotStore(buildHostConfig(emptyCuratedRoot), {
|
||||
env: buildDuckDbBudgetEnv(duckTempDir),
|
||||
});
|
||||
|
||||
let readErr: unknown;
|
||||
try {
|
||||
await collectBars(
|
||||
handle.store.bars({
|
||||
listingIds: [LISTING_ID],
|
||||
timeframe: '1d',
|
||||
from: '2025-05-28',
|
||||
to: '2025-05-31',
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
readErr = err;
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
|
||||
expect(readErr).toBeInstanceOf(Error);
|
||||
expect(connCloseSpy).toHaveBeenCalledTimes(1);
|
||||
expect(instCloseSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('fail-closed: invalid relative curatedRoot closes acquired connection and instance before rejecting', async () => {
|
||||
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
|
||||
let openErr: unknown;
|
||||
try {
|
||||
await openResearchCopilotStore(buildHostConfig('relative/curated/root'));
|
||||
} catch (err) {
|
||||
openErr = err;
|
||||
}
|
||||
|
||||
expect(openErr).toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(connCloseSpy).toHaveBeenCalledTimes(1);
|
||||
expect(instCloseSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('fail-closed: rejected native instance.connect() closes allocated DuckDBInstance before propagating error', async () => {
|
||||
const connectFailure = new Error('simulated native connect failure');
|
||||
const connCloseSpy = trackSpy(spyOn(DuckDBConnection.prototype, 'closeSync'));
|
||||
const instCloseSpy = trackSpy(spyOn(DuckDBInstance.prototype, 'closeSync'));
|
||||
const connectSpy = trackSpy(
|
||||
spyOn(DuckDBInstance.prototype, 'connect').mockImplementationOnce(async () => {
|
||||
throw connectFailure;
|
||||
})
|
||||
);
|
||||
|
||||
let openErr: unknown;
|
||||
try {
|
||||
await openResearchCopilotStore(buildHostConfig('/tmp/unused-curated-root'));
|
||||
} catch (err) {
|
||||
openErr = err;
|
||||
}
|
||||
|
||||
expect(openErr).toBe(connectFailure);
|
||||
expect(connectSpy).toHaveBeenCalledTimes(1);
|
||||
expect(connCloseSpy).toHaveBeenCalledTimes(0);
|
||||
expect(instCloseSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -276,6 +276,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
- **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency.
|
||||
- **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls.
|
||||
- **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days.
|
||||
- **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars.
|
||||
|
||||
### Filesystem Library Cards Adapter
|
||||
|
||||
|
|
@ -286,6 +287,25 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
### Copilot Server
|
||||
|
||||
- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions.
|
||||
- **`createPostgresResearchCopilotServer(options)`** (exported from `@stock-bot/research/mcp` alongside `PostgresResearchCopilotServerOptions` and `PostgresResearchCopilotExecutor`) wires one shared PostgreSQL executor into `createPostgresSymbolSearchPort`, `createPostgresTrialRefPort`, `createPostgresFindingWritePort`, `createPostgresKnowledgeReaders`, `createPostgresListingCalendarPort` + `createExchangeCalendarResolver`, and `trial_ledger`, while keeping `store`, `listLibraryCards`, `sessionDates` (with optional `earlyCloses`), `newId`, and `now` caller-supplied. `vaultContext.vaultCutoffTs` is the single authoritative Vault cutoff for all Vault-fenced tools and `trial_ledger` visibility lookups. When `schema` is supplied, the schema-aware adapters qualify their tables with `"<schema>".`, while `trial_ledger` writes and cluster DSR reads resolve through the executor's `search_path`.
|
||||
|
||||
### Stdio Host Composition
|
||||
|
||||
- **`parseResearchCopilotHostConfig(env)`** and **`runResearchCopilotStdioHost(deps)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotHostConfig`, `ResearchCopilotHostConfigError`, `ResearchCopilotStdioHostDeps`, `RESEARCH_COPILOT_HOST_NAME`, and `RESEARCH_COPILOT_HOST_VERSION`) provide a pure, dependency-free stdio host layer (`libs/research/src/mcp/host/stdio-host.ts`) with no `pg`, DuckDB, `node:*`, or bare `process` references.
|
||||
- **Environment variables (`RESEARCH_MCP_*`):** Unrelated keys are ignored; unknown `RESEARCH_MCP_*` keys, missing required variables, blank values, and malformed fields throw `ResearchCopilotHostConfigError` naming the variable without exposing raw values or credentials.
|
||||
|
||||
| Variable | Required | Format |
|
||||
| --- | --- | --- |
|
||||
| `RESEARCH_MCP_POSTGRES_URL` | Yes | `postgres://` or `postgresql://` URL with non-empty host (never echoed in errors) |
|
||||
| `RESEARCH_MCP_POSTGRES_SCHEMA` | No | PostgreSQL identifier `^[a-z_][a-z0-9_]*$` |
|
||||
| `RESEARCH_MCP_CURATED_ROOT` | Yes | Non-blank path string for curated Parquet datasets (validated by the store factory) |
|
||||
| `RESEARCH_MCP_VAULT_CUTOFF_TS` | Yes | Strict ISO-8601 UTC instant with seconds and `Z` suffix, optional ms (e.g. `2025-06-01T00:00:00Z`) |
|
||||
| `RESEARCH_MCP_PRINCIPAL_ID` | Yes | `operator` or `agent:<lowercase-uuid>` (UUID v1–8, RFC variant) |
|
||||
| `RESEARCH_MCP_LIBRARY_ROOT` | Yes | Non-blank directory path containing `library.yml` (validated by the reader factory) |
|
||||
| `RESEARCH_MCP_SESSION_REFERENCE_LISTINGS` | Yes | JSON object `{ "<calendarCode>": [<positive INT32>, ...] }` (non-empty, distinct IDs), e.g. `{"XNYS":[101,102],"XTSE":[201]}` |
|
||||
| `RESEARCH_MCP_EARLY_CLOSES` | No | JSON object `{ "<calendarCode>": { "<YYYY-MM-DD>": <1..960 ET min> } }` within `1976-01-01..=2030-12-31`, e.g. `{"XNYS":{"2024-11-29":780}}` |
|
||||
|
||||
- **Usage, single Vault cutoff & cleanup ownership:** Pass the parsed `config` to `runResearchCopilotStdioHost({ config, openExecutor, openStore, createLibraryCardReader, newId, now, stdio? })`. The host acquires `openExecutor` → `openStore` → `createLibraryCardReader`, builds `createBarSessionDatesPort` and `createPostgresResearchCopilotServer` (`stock-bot-research-copilot` / `0.1.0`) with `vaultContext: { vaultCutoffTs: config.vaultCutoffTs }`, and starts `runStdioServer` only after all setup succeeds. Callers' `openStore(config)` factory must configure its `MarketDataStore` with the same `config.vaultCutoffTs` so store queries and session-date derivation share one cutoff. Each factory owns internal cleanup on its own failed startup; once a handle is returned, the host awaits `close()` on every acquired handle exactly once in reverse acquisition order on EOF or error, preserving safe primary errors and replacing credential-bearing or uninspectable failures with fixed stage-specific errors. Keep all startup and runtime diagnostics off `stdout` (use `stderr` or structured logs outside stdio) so `stdout` carries only newline-delimited JSON-RPC frames.
|
||||
|
||||
### Remaining M2 MCP Items (Later Tasks)
|
||||
|
||||
|
|
@ -311,3 +331,24 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/feature-librar
|
|||
- **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`<curatedRoot>/features/<name>/v<version>/year=YYYY/`) exist before executing `COPY`.
|
||||
- **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`.
|
||||
- **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions.
|
||||
|
||||
## `marimo check`-Gated Notebook Snapshot Exporter
|
||||
|
||||
Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`). Subprocess execution and filesystem access are injected via `NotebookCommandRunner` and `NotebookSnapshotFs`, and `node:crypto` is loaded lazily at call time so the shared package barrel remains browser-bundleable. Command flags and JSON report validation are confirmed against **marimo `0.26.0`** (pinned in `python/uv.lock`).
|
||||
|
||||
### API & Ports
|
||||
|
||||
- **`exportNotebookSnapshot(options)`** — Validates options and paths, confirms `notebookPath` is an existing regular `.py` file, gates on `marimo check --format=json <notebookPath>`, and only on a clean check reserves a unique sibling `.html` temp file via `fs.createExclusive` and runs `marimo export html <notebookPath> -o <tempPath> --force` before computing byte length and lowercase SHA-256 and atomically publishing via `fs.rename(tempPath, outputPath)`.
|
||||
- **Frozen receipt (`NotebookSnapshotReceipt`)** — Returns `Object.freeze({ notebookPath, outputPath, bytes, sha256, checkDiagnostics })`, where `checkDiagnostics` is the deep-frozen marimo JSON report (or `null` when `marimo check` exits `0` with empty stdout).
|
||||
- **`NotebookCommandRunner`** — Must execute `command` directly with `args` as an argv array (never a shell string). On timeout (default `120_000` ms per command), implementations must terminate the subprocess and reject with `code: 'ETIMEDOUT'` **only after the process has exited and stopped writing** so cleanup cannot race with late writes.
|
||||
- **`NotebookSnapshotFs`** — Minimal port requiring `stat`, `createExclusive` (must throw `code: 'EEXIST'` on collision), `readBytes`, `rename`, and idempotent `remove`. On any export, read, or publish failure, only the owned temp file is removed and any pre-existing `outputPath` keeps its original bytes.
|
||||
- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check.
|
||||
- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**.
|
||||
|
||||
### Manual Host Smoke Check (Director / Host Only)
|
||||
|
||||
Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`):
|
||||
|
||||
1. Ensure `STOCK_BOT_TRIAL_LEDGER_DSN` is **unset** so the smoke check does not append trial rows to `trial_ledger`.
|
||||
2. Target `research/notebooks/ca_shorts_filings_study.py` against a fixed Vault-fenced dataset and run `exportNotebookSnapshot` (or the two commands it issues: `uv run --project python marimo check --format=json research/notebooks/ca_shorts_filings_study.py` followed by `uv run --project python marimo export html research/notebooks/ca_shorts_filings_study.py -o <out.html> --force`).
|
||||
3. Record the pinned inputs, whether `marimo check` reported 0 errors, and whether the exported HTML opens cleanly. Quant owns any research claims (including notebook revision, dataset ID, sample window, Vault cutoff, baseline, and cost assumptions); any paper or live write access requires a separate scope decision.
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ 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 './notebook-snapshot';
|
||||
export * from './signal-panel';
|
||||
export * from './signal-study';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
278
libs/research/src/mcp/adapters/bar-session-dates.ts
Normal file
278
libs/research/src/mcp/adapters/bar-session-dates.ts
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
/**
|
||||
* Bar-derived {@link SessionDatesPort} adapter for the MCP copilot `event_study`
|
||||
* exchange-calendar resolver (`createExchangeCalendarResolver`).
|
||||
*
|
||||
* Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare
|
||||
* `process` access, no `pg` dependency, and no DuckDB driver import.
|
||||
*
|
||||
* Daily bar timestamp convention:
|
||||
* - In `libs/research/src/market-data-store-duckdb.ts`, `planBars1dQuery`
|
||||
* projects `epoch_ms(b.ts) AS ts` and `mapBarRows` validates it as an integer
|
||||
* UTC epoch millisecond value on `BarRecord.ts`.
|
||||
* - In `tools/curate-etl/src/curate_bars.rs`, curated daily bars are stamped at
|
||||
* `16:00:00 America/New_York` (`16:00 ET`), which converts to `20:00:00Z`
|
||||
* (EDT) or `21:00:00Z` (EST) on the same UTC calendar date.
|
||||
* - Therefore, `Math.floor(bar.ts / MS_PER_DAY)` yields the session's integer
|
||||
* UTC day key (`formatDayKeyUtc`). Close timestamps and optional early-close
|
||||
* overrides remain owned by `createExchangeCalendarResolver`.
|
||||
*
|
||||
* Vault fence behavior:
|
||||
* - Queries `store.bars` with `timeframe: '1d'` and `adjustment: 'raw'`,
|
||||
* omitting `scope` and `asOf` so the injected store applies its default
|
||||
* `'vault_fenced'` scope. Never passes `'vault_evaluation_only'`.
|
||||
* - Errors thrown by the store (including `VaultHoldoutFenceError`) propagate
|
||||
* unchanged.
|
||||
*/
|
||||
|
||||
import type { MarketDataStore } from '../../market-data-store';
|
||||
import {
|
||||
MS_PER_DAY,
|
||||
formatDayKeyUtc,
|
||||
isPlainRecord,
|
||||
isValidEpochMs,
|
||||
isValidInt32,
|
||||
parseCalendarDayKey,
|
||||
} from '../../panel-shared';
|
||||
import type { SessionDatesPort, SessionDatesQuery } from './exchange-calendars';
|
||||
|
||||
/** Error codes thrown by {@link BarSessionDatesError}. */
|
||||
export type BarSessionDatesErrorCode =
|
||||
| 'invalid_options'
|
||||
| 'unknown_calendar'
|
||||
| 'invalid_query'
|
||||
| 'invalid_bar';
|
||||
|
||||
/** Optional error constructor metadata for {@link BarSessionDatesError}. */
|
||||
export interface BarSessionDatesErrorOptions {
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
/** Typed fail-closed error thrown by {@link createBarSessionDatesPort}. */
|
||||
export class BarSessionDatesError extends RangeError {
|
||||
readonly code: BarSessionDatesErrorCode;
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(
|
||||
code: BarSessionDatesErrorCode,
|
||||
message: string,
|
||||
options?: BarSessionDatesErrorOptions
|
||||
) {
|
||||
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
|
||||
this.name = 'BarSessionDatesError';
|
||||
this.code = code;
|
||||
if (options?.cause !== undefined) {
|
||||
this.cause = options.cause;
|
||||
}
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/** Factory options for {@link createBarSessionDatesPort}. */
|
||||
export interface BarSessionDatesPortOptions {
|
||||
readonly store: Pick<MarketDataStore, 'bars'>;
|
||||
/**
|
||||
* Caller-configured reference listing IDs per `exchange.calendar_code`
|
||||
* (e.g. `XNYS`, `XTSE`). The union of their daily bars defines the exchange's
|
||||
* session dates.
|
||||
*/
|
||||
readonly referenceListingIds: Readonly<Record<string, readonly number[]>>;
|
||||
}
|
||||
|
||||
interface CalendarReferenceConfig {
|
||||
readonly listingIds: readonly number[];
|
||||
readonly listingIdSet: ReadonlySet<number>;
|
||||
}
|
||||
|
||||
function isPlainObjectRecord(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 parseQueryDayKey(value: unknown, field: string): number {
|
||||
return parseCalendarDayKey(value, field, (message, cause) =>
|
||||
new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
message,
|
||||
cause !== undefined ? { cause } : undefined
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function validateOptions(options: BarSessionDatesPortOptions): {
|
||||
readonly store: Pick<MarketDataStore, 'bars'>;
|
||||
readonly calendars: ReadonlyMap<string, CalendarReferenceConfig>;
|
||||
} {
|
||||
if (!isPlainRecord(options)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
'Invalid options: expected an object with store and referenceListingIds.'
|
||||
);
|
||||
}
|
||||
|
||||
const { store, referenceListingIds } = options;
|
||||
if (typeof store !== 'object' || store === null || typeof store.bars !== 'function') {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
'Invalid "store": expected an object with a callable bars(query) method.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainObjectRecord(referenceListingIds)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
'Invalid "referenceListingIds": expected a plain object mapping calendar codes to positive INT32 listing ID arrays.'
|
||||
);
|
||||
}
|
||||
|
||||
const calendars = new Map<string, CalendarReferenceConfig>();
|
||||
const entries = Object.entries(referenceListingIds);
|
||||
|
||||
for (let i = 0; i < entries.length; i += 1) {
|
||||
const [calendarCode, rawIds] = entries[i] as [string, unknown];
|
||||
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Invalid "referenceListingIds" calendar code "${calendarCode}": expected a non-empty trimmed string.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(rawIds) || rawIds.length === 0) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Invalid "referenceListingIds.${calendarCode}": expected a non-empty array of positive 32-bit integer listing IDs.`
|
||||
);
|
||||
}
|
||||
|
||||
const copiedIds: number[] = [];
|
||||
const idSet = new Set<number>();
|
||||
|
||||
for (let j = 0; j < rawIds.length; j += 1) {
|
||||
const id: unknown = rawIds[j];
|
||||
if (!isValidInt32(id) || id <= 0) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Invalid "referenceListingIds.${calendarCode}[${j}]": expected a positive 32-bit integer, got ${String(id)}.`
|
||||
);
|
||||
}
|
||||
if (idSet.has(id)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Duplicate listing ID ${id} in "referenceListingIds.${calendarCode}".`
|
||||
);
|
||||
}
|
||||
idSet.add(id);
|
||||
copiedIds.push(id);
|
||||
}
|
||||
|
||||
calendars.set(calendarCode, {
|
||||
listingIds: copiedIds,
|
||||
listingIdSet: idSet,
|
||||
});
|
||||
}
|
||||
|
||||
return { store, calendars };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link SessionDatesPort} backed by Vault-fenced daily bars
|
||||
* (`timeframe: '1d'`, `adjustment: 'raw'`) for caller-configured reference
|
||||
* listings per `exchange.calendar_code`.
|
||||
*/
|
||||
export function createBarSessionDatesPort(
|
||||
options: BarSessionDatesPortOptions
|
||||
): SessionDatesPort {
|
||||
const { store, calendars } = validateOptions(options);
|
||||
|
||||
return {
|
||||
async listSessionDates(query: SessionDatesQuery): Promise<readonly string[]> {
|
||||
if (!isPlainRecord(query)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
'Invalid query: expected an object with calendarCode, fromDate, and toDate.'
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof query.calendarCode !== 'string') {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
'Invalid "calendarCode": expected a string.'
|
||||
);
|
||||
}
|
||||
|
||||
const config = calendars.get(query.calendarCode);
|
||||
if (config === undefined) {
|
||||
throw new BarSessionDatesError(
|
||||
'unknown_calendar',
|
||||
`No reference listings configured for calendarCode "${query.calendarCode}".`
|
||||
);
|
||||
}
|
||||
|
||||
const fromDayKey = parseQueryDayKey(query.fromDate, 'fromDate');
|
||||
const toDayKey = parseQueryDayKey(query.toDate, 'toDate');
|
||||
if (fromDayKey > toDayKey) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
`Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".`
|
||||
);
|
||||
}
|
||||
|
||||
const dayKeys = new Set<number>();
|
||||
const stream = store.bars({
|
||||
listingIds: config.listingIds.slice(),
|
||||
timeframe: '1d',
|
||||
from: query.fromDate,
|
||||
to: query.toDate,
|
||||
adjustment: 'raw',
|
||||
});
|
||||
|
||||
for await (const batch of stream) {
|
||||
if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
'Invalid bar batch: expected an object with a rows array.'
|
||||
);
|
||||
}
|
||||
|
||||
const rows = batch.rows;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const bar: unknown = rows[i];
|
||||
if (!isPlainRecord(bar)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
`Invalid bar row at index ${i}: expected a plain object.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isValidEpochMs(bar.ts)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
`Invalid bar timestamp at index ${i}: expected a finite integer epoch ms, got ${String(bar.ts)}.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isValidInt32(bar.listingId) || !config.listingIdSet.has(bar.listingId)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
`Unexpected bar listingId ${String(bar.listingId)} for calendarCode "${query.calendarCode}".`
|
||||
);
|
||||
}
|
||||
|
||||
const dayKey = Math.floor(bar.ts / MS_PER_DAY);
|
||||
if (dayKey >= fromDayKey && dayKey <= toDayKey) {
|
||||
dayKeys.add(dayKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (dayKeys.size === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sortedDayKeys = Array.from(dayKeys).sort((a, b) => a - b);
|
||||
return sortedDayKeys.map(formatDayKeyUtc);
|
||||
},
|
||||
};
|
||||
}
|
||||
173
libs/research/src/mcp/adapters/postgres-copilot.ts
Normal file
173
libs/research/src/mcp/adapters/postgres-copilot.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
/**
|
||||
* PostgreSQL composition root for the MCP research copilot server.
|
||||
*
|
||||
* Wires a single injected {@link PostgresResearchCopilotExecutor} into all
|
||||
* PostgreSQL-backed MCP adapters (`search_symbols`, `file_finding`,
|
||||
* `read_knowledge`, `event_study` listing calendars, and `trial_ledger`) with
|
||||
* one authoritative Vault cutoff (`vaultContext.vaultCutoffTs`).
|
||||
*
|
||||
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution,
|
||||
* market data store, library-card reader, session-date port, ID generator, and
|
||||
* clock are all injected by the caller.
|
||||
*/
|
||||
|
||||
import {
|
||||
type ResearchCopilotMcpServerOptions,
|
||||
createResearchCopilotMcpServer,
|
||||
} from '../copilot-server';
|
||||
import type { McpServer } from '../server';
|
||||
import type { KnowledgePort } from '../tools/read-knowledge';
|
||||
import {
|
||||
type EarlyCloseOverrides,
|
||||
type SessionDatesPort,
|
||||
createExchangeCalendarResolver,
|
||||
createPostgresListingCalendarPort,
|
||||
} from './exchange-calendars';
|
||||
import {
|
||||
createPostgresFindingWritePort,
|
||||
createPostgresKnowledgeReaders,
|
||||
} from './postgres-findings';
|
||||
import { createPostgresSymbolSearchPort } from './postgres-symbol-search';
|
||||
import { createPostgresTrialRefPort } from './postgres-trial-ref';
|
||||
|
||||
/**
|
||||
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface shared by
|
||||
* all PostgreSQL-backed MCP copilot adapters and `trial_ledger`.
|
||||
*
|
||||
* Assignable without casts to `SymbolSearchExecutor`, `TrialRefExecutor`,
|
||||
* `PostgresFindingsExecutor`, `ListingCalendarExecutor`, and
|
||||
* `TrialLedgerExecutor`.
|
||||
*/
|
||||
export interface PostgresResearchCopilotExecutor {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Composition options for {@link createPostgresResearchCopilotServer}.
|
||||
*
|
||||
* Uses `vaultContext.vaultCutoffTs` as the single authoritative Vault cutoff
|
||||
* across all Vault-fenced tools and `trial_ledger` visibility lookups.
|
||||
*/
|
||||
export interface PostgresResearchCopilotServerOptions
|
||||
extends Pick<
|
||||
ResearchCopilotMcpServerOptions,
|
||||
'name' | 'version' | 'store' | 'vaultContext' | 'principalId'
|
||||
> {
|
||||
readonly executor: PostgresResearchCopilotExecutor;
|
||||
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
|
||||
readonly schema?: string;
|
||||
readonly listLibraryCards: KnowledgePort['listLibraryCards'];
|
||||
readonly sessionDates: SessionDatesPort;
|
||||
readonly earlyCloses?: EarlyCloseOverrides;
|
||||
readonly newId: () => string;
|
||||
readonly now: () => Date | number;
|
||||
}
|
||||
|
||||
function validateOptions(options: PostgresResearchCopilotServerOptions): void {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new Error(
|
||||
'Invalid `options`: expected a PostgresResearchCopilotServerOptions object.'
|
||||
);
|
||||
}
|
||||
if (
|
||||
typeof options.executor !== 'object' ||
|
||||
options.executor === null ||
|
||||
typeof options.executor.query !== 'function'
|
||||
) {
|
||||
throw new Error(
|
||||
'Invalid `executor`: expected an object with a callable query(text, params?) method.'
|
||||
);
|
||||
}
|
||||
if (typeof options.vaultContext !== 'object' || options.vaultContext === null) {
|
||||
throw new Error('Invalid `vaultContext`: expected a VaultFenceContext object.');
|
||||
}
|
||||
if (typeof options.listLibraryCards !== 'function') {
|
||||
throw new Error('Invalid `listLibraryCards`: expected a callable function.');
|
||||
}
|
||||
if (
|
||||
typeof options.sessionDates !== 'object' ||
|
||||
options.sessionDates === null ||
|
||||
typeof options.sessionDates.listSessionDates !== 'function'
|
||||
) {
|
||||
throw new Error(
|
||||
'Invalid `sessionDates`: expected an object with a callable listSessionDates(query) method.'
|
||||
);
|
||||
}
|
||||
if (typeof options.newId !== 'function') {
|
||||
throw new Error('Invalid `newId`: expected a callable function.');
|
||||
}
|
||||
if (typeof options.now !== 'function') {
|
||||
throw new Error('Invalid `now`: expected a callable function.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes all six research copilot MCP tools into a single {@link McpServer}
|
||||
* backed by one shared PostgreSQL executor and one authoritative Vault cutoff.
|
||||
*
|
||||
* Schema-aware adapters (`search_symbols`, `trial_ledger` visibility lookup,
|
||||
* `findings`, `provider_caveats`, and listing-to-exchange calendars) qualify
|
||||
* their tables with `options.schema` when supplied; `trial_ledger` writes and
|
||||
* cluster DSR reads resolve through the executor's `search_path`.
|
||||
*/
|
||||
export function createPostgresResearchCopilotServer(
|
||||
options: PostgresResearchCopilotServerOptions
|
||||
): McpServer {
|
||||
validateOptions(options);
|
||||
|
||||
const pgAdapterOptions =
|
||||
options.schema === undefined
|
||||
? { executor: options.executor }
|
||||
: { executor: options.executor, schema: options.schema };
|
||||
|
||||
const symbolSearchPort = createPostgresSymbolSearchPort(pgAdapterOptions);
|
||||
const trialRefPort = createPostgresTrialRefPort({
|
||||
...pgAdapterOptions,
|
||||
vaultCutoffTs: options.vaultContext.vaultCutoffTs,
|
||||
});
|
||||
const findingWritePort = createPostgresFindingWritePort(pgAdapterOptions);
|
||||
const knowledgeReaders = createPostgresKnowledgeReaders(pgAdapterOptions);
|
||||
const listingCalendars = createPostgresListingCalendarPort(pgAdapterOptions);
|
||||
|
||||
const resolveExchangeCalendars = createExchangeCalendarResolver(
|
||||
options.earlyCloses === undefined
|
||||
? { listingCalendars, sessionDates: options.sessionDates }
|
||||
: {
|
||||
listingCalendars,
|
||||
sessionDates: options.sessionDates,
|
||||
earlyCloses: options.earlyCloses,
|
||||
}
|
||||
);
|
||||
|
||||
const knowledgePort: KnowledgePort = {
|
||||
listLibraryCards: options.listLibraryCards,
|
||||
...knowledgeReaders,
|
||||
};
|
||||
|
||||
return createResearchCopilotMcpServer({
|
||||
name: options.name,
|
||||
version: options.version,
|
||||
store: options.store,
|
||||
vaultContext: options.vaultContext,
|
||||
ledger: options.executor,
|
||||
principalId: options.principalId,
|
||||
searchSymbols: {
|
||||
port: symbolSearchPort,
|
||||
},
|
||||
eventStudy: {
|
||||
resolveExchangeCalendars,
|
||||
},
|
||||
fileFinding: {
|
||||
port: findingWritePort,
|
||||
trialLookup: trialRefPort,
|
||||
newId: options.newId,
|
||||
now: options.now,
|
||||
},
|
||||
readKnowledge: {
|
||||
port: knowledgePort,
|
||||
},
|
||||
});
|
||||
}
|
||||
835
libs/research/src/mcp/host/stdio-host.ts
Normal file
835
libs/research/src/mcp/host/stdio-host.ts
Normal file
|
|
@ -0,0 +1,835 @@
|
|||
/**
|
||||
* Dependency-free stdio host composition for the MCP research copilot.
|
||||
*
|
||||
* Parses `RESEARCH_MCP_*` environment variables into a strict typed
|
||||
* {@link ResearchCopilotHostConfig} and composes injected PostgreSQL executor,
|
||||
* market data store, and library-card reader factories with
|
||||
* {@link createBarSessionDatesPort}, {@link createPostgresResearchCopilotServer},
|
||||
* and {@link runStdioServer}.
|
||||
*
|
||||
* Pure and dependency-free: zero `node:*` imports, zero bare `process` access,
|
||||
* no `pg` dependency, and no DuckDB driver import.
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import type { MarketDataStore } from '../../market-data-store';
|
||||
import {
|
||||
MAX_ECMASCRIPT_EPOCH_MS,
|
||||
isValidInt32,
|
||||
parseCalendarDayKey,
|
||||
} from '../../panel-shared';
|
||||
import {
|
||||
type BarSessionDatesPortOptions,
|
||||
createBarSessionDatesPort,
|
||||
} from '../adapters/bar-session-dates';
|
||||
import {
|
||||
EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET,
|
||||
EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE,
|
||||
EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET,
|
||||
EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE,
|
||||
type EarlyCloseOverrides,
|
||||
} from '../adapters/exchange-calendars';
|
||||
import {
|
||||
type PostgresResearchCopilotExecutor,
|
||||
createPostgresResearchCopilotServer,
|
||||
} from '../adapters/postgres-copilot';
|
||||
import type { McpServer } from '../server';
|
||||
import { type StdioServerOptions, runStdioServer } from '../stdio';
|
||||
import type { KnowledgePort } from '../tools/read-knowledge';
|
||||
|
||||
/** Environment variable prefix owned by {@link parseResearchCopilotHostConfig}. */
|
||||
export const RESEARCH_MCP_ENV_PREFIX = 'RESEARCH_MCP_';
|
||||
|
||||
/** Headless MCP server name announced during `initialize`. */
|
||||
export const RESEARCH_COPILOT_HOST_NAME = 'stock-bot-research-copilot';
|
||||
|
||||
/** Headless MCP server version announced during `initialize`. */
|
||||
export const RESEARCH_COPILOT_HOST_VERSION = '0.1.0';
|
||||
|
||||
const ENV_POSTGRES_URL = 'RESEARCH_MCP_POSTGRES_URL';
|
||||
const ENV_POSTGRES_SCHEMA = 'RESEARCH_MCP_POSTGRES_SCHEMA';
|
||||
const ENV_CURATED_ROOT = 'RESEARCH_MCP_CURATED_ROOT';
|
||||
const ENV_VAULT_CUTOFF_TS = 'RESEARCH_MCP_VAULT_CUTOFF_TS';
|
||||
const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID';
|
||||
const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT';
|
||||
const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS';
|
||||
const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES';
|
||||
|
||||
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||
const AGENT_PRINCIPAL_RE =
|
||||
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
||||
const STRICT_UTC_INSTANT_RE =
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
|
||||
|
||||
const nonBlankEnvString = z.string().refine(value => value.trim().length > 0, {
|
||||
message: 'blank',
|
||||
});
|
||||
|
||||
const rawHostEnvSchema = z
|
||||
.object({
|
||||
[ENV_POSTGRES_URL]: nonBlankEnvString,
|
||||
[ENV_POSTGRES_SCHEMA]: nonBlankEnvString.optional(),
|
||||
[ENV_CURATED_ROOT]: nonBlankEnvString,
|
||||
[ENV_VAULT_CUTOFF_TS]: nonBlankEnvString,
|
||||
[ENV_PRINCIPAL_ID]: nonBlankEnvString,
|
||||
[ENV_LIBRARY_ROOT]: nonBlankEnvString,
|
||||
[ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString,
|
||||
[ENV_EARLY_CLOSES]: nonBlankEnvString.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */
|
||||
export interface ResearchCopilotHostConfig {
|
||||
readonly postgresUrl: string;
|
||||
readonly postgresSchema?: string;
|
||||
readonly curatedRoot: string;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly principalId: string;
|
||||
readonly libraryRoot: string;
|
||||
readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds'];
|
||||
readonly earlyCloses?: EarlyCloseOverrides;
|
||||
}
|
||||
|
||||
/**
|
||||
* Typed configuration error thrown by {@link parseResearchCopilotHostConfig}.
|
||||
*
|
||||
* Always names the offending `RESEARCH_MCP_*` variable with a fixed reason and
|
||||
* never embeds raw environment values, DSNs, JSON parser output, or Zod dumps.
|
||||
*/
|
||||
export class ResearchCopilotHostConfigError extends RangeError {
|
||||
readonly variable: string;
|
||||
|
||||
constructor(variable: string, message: string) {
|
||||
super(message);
|
||||
this.name = 'ResearchCopilotHostConfigError';
|
||||
this.variable = variable;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/** Managed PostgreSQL executor handle returned by `deps.openExecutor`. */
|
||||
export interface ManagedPostgresExecutor {
|
||||
readonly executor: PostgresResearchCopilotExecutor;
|
||||
close(): Promise<void> | void;
|
||||
}
|
||||
|
||||
/** Managed market data store handle returned by `deps.openStore`. */
|
||||
export interface ManagedMarketDataStore {
|
||||
readonly store: MarketDataStore;
|
||||
close(): Promise<void> | void;
|
||||
}
|
||||
|
||||
/** Library-card reader handle returned by `deps.createLibraryCardReader`. */
|
||||
export interface LibraryCardReaderHandle {
|
||||
readonly listLibraryCards: KnowledgePort['listLibraryCards'];
|
||||
}
|
||||
|
||||
/** Injected dependencies for {@link runResearchCopilotStdioHost}. */
|
||||
export interface ResearchCopilotStdioHostDeps {
|
||||
readonly config: ResearchCopilotHostConfig;
|
||||
readonly openExecutor: (
|
||||
config: ResearchCopilotHostConfig
|
||||
) => Promise<ManagedPostgresExecutor> | ManagedPostgresExecutor;
|
||||
readonly openStore: (
|
||||
config: ResearchCopilotHostConfig
|
||||
) => Promise<ManagedMarketDataStore> | ManagedMarketDataStore;
|
||||
readonly createLibraryCardReader: (
|
||||
config: ResearchCopilotHostConfig
|
||||
) => Promise<LibraryCardReaderHandle> | LibraryCardReaderHandle;
|
||||
readonly newId: () => string;
|
||||
readonly now: () => Date | number;
|
||||
readonly stdio?: StdioServerOptions;
|
||||
}
|
||||
|
||||
type HostStage =
|
||||
| 'executor_open'
|
||||
| 'store_open'
|
||||
| 'library_reader'
|
||||
| 'server_init'
|
||||
| 'stdio_serve'
|
||||
| 'cleanup';
|
||||
|
||||
const STAGE_ERROR_MESSAGES: Readonly<Record<HostStage, string>> = {
|
||||
executor_open: 'Research copilot stdio host failed while opening the PostgreSQL executor.',
|
||||
store_open: 'Research copilot stdio host failed while opening the market data store.',
|
||||
library_reader: 'Research copilot stdio host failed while creating the library card reader.',
|
||||
server_init: 'Research copilot stdio host failed while initializing the MCP server.',
|
||||
stdio_serve: 'Research copilot stdio host failed while serving MCP stdio.',
|
||||
cleanup: 'Research copilot stdio host failed while closing host resources.',
|
||||
};
|
||||
|
||||
function isPlainObjectRecord(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 defineDataProperty<T>(target: Record<string, T>, key: string, value: T): void {
|
||||
Object.defineProperty(target, key, {
|
||||
value,
|
||||
enumerable: true,
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
|
||||
function parsePostgresUrl(raw: string): string {
|
||||
if (raw !== raw.trim()) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
|
||||
);
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.`
|
||||
);
|
||||
}
|
||||
if (
|
||||
(parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') ||
|
||||
parsed.hostname.length === 0
|
||||
) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.`
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (parsed.username.length > 0) {
|
||||
decodeURIComponent(parsed.username);
|
||||
}
|
||||
if (parsed.password.length > 0) {
|
||||
decodeURIComponent(parsed.password);
|
||||
}
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.`
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function parsePostgresSchema(raw: string): string {
|
||||
if (!SCHEMA_IDENT_RE.test(raw)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_SCHEMA,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_SCHEMA}": expected a PostgreSQL identifier matching ^[a-z_][a-z0-9_]*$.`
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function parsePrincipalId(raw: string): string {
|
||||
if (raw !== 'operator' && !AGENT_PRINCIPAL_RE.test(raw)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_PRINCIPAL_ID,
|
||||
`Invalid configuration variable "${ENV_PRINCIPAL_ID}": expected "operator" or "agent:<lowercase-uuid>".`
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function parseVaultCutoffTs(raw: string): number {
|
||||
const match = STRICT_UTC_INSTANT_RE.exec(raw);
|
||||
if (match === null) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_VAULT_CUTOFF_TS,
|
||||
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": expected a strict ISO-8601 UTC instant ending in Z.`
|
||||
);
|
||||
}
|
||||
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
const hour = Number(match[4]);
|
||||
const minute = Number(match[5]);
|
||||
const second = Number(match[6]);
|
||||
const fracRaw = match[7];
|
||||
const millis = fracRaw === undefined ? 0 : Number(fracRaw.padEnd(3, '0'));
|
||||
|
||||
if (
|
||||
month < 1 ||
|
||||
month > 12 ||
|
||||
day < 1 ||
|
||||
day > 31 ||
|
||||
hour > 23 ||
|
||||
minute > 59 ||
|
||||
second > 59
|
||||
) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_VAULT_CUTOFF_TS,
|
||||
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.`
|
||||
);
|
||||
}
|
||||
|
||||
const epochMs = Date.UTC(year, month - 1, day, hour, minute, second, millis);
|
||||
if (!Number.isSafeInteger(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_VAULT_CUTOFF_TS,
|
||||
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is out of supported epoch range.`
|
||||
);
|
||||
}
|
||||
|
||||
const check = new Date(epochMs);
|
||||
if (
|
||||
check.getUTCFullYear() !== year ||
|
||||
check.getUTCMonth() !== month - 1 ||
|
||||
check.getUTCDate() !== day ||
|
||||
check.getUTCHours() !== hour ||
|
||||
check.getUTCMinutes() !== minute ||
|
||||
check.getUTCSeconds() !== second ||
|
||||
check.getUTCMilliseconds() !== millis
|
||||
) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_VAULT_CUTOFF_TS,
|
||||
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.`
|
||||
);
|
||||
}
|
||||
|
||||
return epochMs;
|
||||
}
|
||||
|
||||
function parseReferenceListingIds(
|
||||
raw: string
|
||||
): BarSessionDatesPortOptions['referenceListingIds'] {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_SESSION_REFERENCE_LISTINGS,
|
||||
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected valid JSON.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainObjectRecord(parsed)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_SESSION_REFERENCE_LISTINGS,
|
||||
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected a JSON object mapping calendar codes to listing ID arrays.`
|
||||
);
|
||||
}
|
||||
|
||||
const result: Record<string, readonly number[]> = {};
|
||||
const entries = Object.entries(parsed);
|
||||
|
||||
for (let i = 0; i < entries.length; i += 1) {
|
||||
const [calendarCode, rawIds] = entries[i] as [string, unknown];
|
||||
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_SESSION_REFERENCE_LISTINGS,
|
||||
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": calendar codes must be non-empty trimmed strings.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(rawIds) || rawIds.length === 0) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_SESSION_REFERENCE_LISTINGS,
|
||||
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": each calendar must map to a non-empty array of positive INT32 listing IDs.`
|
||||
);
|
||||
}
|
||||
|
||||
const copiedIds: number[] = [];
|
||||
const seen = new Set<number>();
|
||||
|
||||
for (let j = 0; j < rawIds.length; j += 1) {
|
||||
const id: unknown = rawIds[j];
|
||||
if (!isValidInt32(id) || id <= 0) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_SESSION_REFERENCE_LISTINGS,
|
||||
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs must be positive 32-bit integers.`
|
||||
);
|
||||
}
|
||||
if (seen.has(id)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_SESSION_REFERENCE_LISTINGS,
|
||||
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs within a calendar must be distinct.`
|
||||
);
|
||||
}
|
||||
seen.add(id);
|
||||
copiedIds.push(id);
|
||||
}
|
||||
|
||||
defineDataProperty(result, calendarCode, copiedIds);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseEarlyClosesEnv(raw: string): EarlyCloseOverrides {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": expected valid JSON.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainObjectRecord(parsed)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": expected a JSON object mapping calendar codes to date/minute overrides.`
|
||||
);
|
||||
}
|
||||
|
||||
const result: Record<string, Readonly<Record<string, number>>> = {};
|
||||
const calendarEntries = Object.entries(parsed);
|
||||
|
||||
for (let i = 0; i < calendarEntries.length; i += 1) {
|
||||
const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown];
|
||||
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": calendar codes must be non-empty trimmed strings.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainObjectRecord(rawDates)) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": each calendar must map to an object of YYYY-MM-DD dates and Eastern close minutes.`
|
||||
);
|
||||
}
|
||||
|
||||
const dates: Record<string, number> = {};
|
||||
const dateEntries = Object.entries(rawDates);
|
||||
|
||||
for (let j = 0; j < dateEntries.length; j += 1) {
|
||||
const [dateStr, minute] = dateEntries[j] as [string, unknown];
|
||||
parseCalendarDayKey(dateStr, ENV_EARLY_CLOSES, () =>
|
||||
new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must be valid YYYY-MM-DD calendar dates.`
|
||||
)
|
||||
);
|
||||
|
||||
if (
|
||||
dateStr < EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE ||
|
||||
dateStr > EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE
|
||||
) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.`
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof minute !== 'number' ||
|
||||
!Number.isSafeInteger(minute) ||
|
||||
minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET ||
|
||||
minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET
|
||||
) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_EARLY_CLOSES,
|
||||
`Invalid configuration variable "${ENV_EARLY_CLOSES}": close minutes must be integers from ${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET} through ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}.`
|
||||
);
|
||||
}
|
||||
|
||||
defineDataProperty(dates, dateStr, minute);
|
||||
}
|
||||
|
||||
defineDataProperty(result, calendarCode, dates);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Purely parses and validates `RESEARCH_MCP_*` environment variables into a
|
||||
* typed {@link ResearchCopilotHostConfig}.
|
||||
*
|
||||
* Unrelated environment keys are ignored. Unknown `RESEARCH_MCP_*` keys,
|
||||
* missing required variables, blank values, and malformed fields fail closed
|
||||
* with {@link ResearchCopilotHostConfigError} naming the variable without
|
||||
* exposing raw values or credentials.
|
||||
*/
|
||||
export function parseResearchCopilotHostConfig(
|
||||
env: Readonly<Record<string, string | undefined>>
|
||||
): ResearchCopilotHostConfig {
|
||||
if (typeof env !== 'object' || env === null) {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
RESEARCH_MCP_ENV_PREFIX,
|
||||
'Invalid environment object: expected a key-value record.'
|
||||
);
|
||||
}
|
||||
|
||||
const scopedEnv: Record<string, unknown> = {};
|
||||
const entries = Object.entries(env);
|
||||
for (let i = 0; i < entries.length; i += 1) {
|
||||
const [key, value] = entries[i] as [string, unknown];
|
||||
if (key.startsWith(RESEARCH_MCP_ENV_PREFIX) && value !== undefined) {
|
||||
defineDataProperty(scopedEnv, key, value);
|
||||
}
|
||||
}
|
||||
|
||||
const parsedEnv = rawHostEnvSchema.safeParse(scopedEnv);
|
||||
if (!parsedEnv.success) {
|
||||
const firstIssue = parsedEnv.error.issues[0];
|
||||
if (firstIssue !== undefined) {
|
||||
if (firstIssue.code === 'unrecognized_keys') {
|
||||
const unknownKey = firstIssue.keys[0] ?? RESEARCH_MCP_ENV_PREFIX;
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
unknownKey,
|
||||
`Unknown configuration variable "${unknownKey}".`
|
||||
);
|
||||
}
|
||||
|
||||
const variable =
|
||||
typeof firstIssue.path[0] === 'string' ? firstIssue.path[0] : RESEARCH_MCP_ENV_PREFIX;
|
||||
|
||||
if (firstIssue.code === 'invalid_type' && firstIssue.received === 'undefined') {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
variable,
|
||||
`Missing required configuration variable "${variable}".`
|
||||
);
|
||||
}
|
||||
|
||||
if (firstIssue.code === 'custom') {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
variable,
|
||||
`Invalid configuration variable "${variable}": value must not be empty or whitespace.`
|
||||
);
|
||||
}
|
||||
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
variable,
|
||||
`Invalid configuration variable "${variable}": expected a non-empty string.`
|
||||
);
|
||||
}
|
||||
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
RESEARCH_MCP_ENV_PREFIX,
|
||||
'Invalid research copilot host configuration.'
|
||||
);
|
||||
}
|
||||
|
||||
const data = parsedEnv.data;
|
||||
const postgresUrl = parsePostgresUrl(data[ENV_POSTGRES_URL]);
|
||||
const postgresSchema =
|
||||
data[ENV_POSTGRES_SCHEMA] !== undefined
|
||||
? parsePostgresSchema(data[ENV_POSTGRES_SCHEMA])
|
||||
: undefined;
|
||||
const curatedRoot = data[ENV_CURATED_ROOT].trim();
|
||||
const vaultCutoffTs = parseVaultCutoffTs(data[ENV_VAULT_CUTOFF_TS]);
|
||||
const principalId = parsePrincipalId(data[ENV_PRINCIPAL_ID]);
|
||||
const libraryRoot = data[ENV_LIBRARY_ROOT].trim();
|
||||
const referenceListingIds = parseReferenceListingIds(data[ENV_SESSION_REFERENCE_LISTINGS]);
|
||||
const earlyCloses =
|
||||
data[ENV_EARLY_CLOSES] !== undefined
|
||||
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
postgresUrl,
|
||||
...(postgresSchema !== undefined ? { postgresSchema } : {}),
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
principalId,
|
||||
libraryRoot,
|
||||
referenceListingIds,
|
||||
...(earlyCloses !== undefined ? { earlyCloses } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
||||
if (raw.length === 0) {
|
||||
return;
|
||||
}
|
||||
needles.add(raw);
|
||||
try {
|
||||
const decoded = decodeURIComponent(raw);
|
||||
if (decoded.length > 0) {
|
||||
needles.add(decoded);
|
||||
}
|
||||
} catch {
|
||||
// Malformed percent-encoding: raw needle is already registered.
|
||||
}
|
||||
}
|
||||
|
||||
function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
if (postgresUrl.length > 0) {
|
||||
needles.add(postgresUrl);
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(postgresUrl);
|
||||
if (parsed.href.length > 0) {
|
||||
needles.add(parsed.href);
|
||||
}
|
||||
addRawAndDecodedNeedle(needles, parsed.password);
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
if (key.toLowerCase() === 'password' && value.length > 0) {
|
||||
needles.add(value);
|
||||
}
|
||||
}
|
||||
if (parsed.search.length > 1) {
|
||||
const pairs = parsed.search.slice(1).split('&');
|
||||
for (let i = 0; i < pairs.length; i += 1) {
|
||||
const pair = pairs[i] as string;
|
||||
const eqIdx = pair.indexOf('=');
|
||||
if (eqIdx <= 0) {
|
||||
continue;
|
||||
}
|
||||
const rawKey = pair.slice(0, eqIdx);
|
||||
let decodedKey = rawKey;
|
||||
try {
|
||||
decodedKey = decodeURIComponent(rawKey);
|
||||
} catch {
|
||||
// Keep rawKey if percent-decoding fails.
|
||||
}
|
||||
if (decodedKey.toLowerCase() === 'password') {
|
||||
addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered.
|
||||
}
|
||||
return Array.from(needles);
|
||||
}
|
||||
|
||||
function containsAnyNeedle(text: string, needles: readonly string[]): boolean {
|
||||
for (let i = 0; i < needles.length; i += 1) {
|
||||
if (text.includes(needles[i] as string)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isErrorSafeToSurface(
|
||||
error: unknown,
|
||||
needles: readonly string[],
|
||||
visited: Set<unknown> = new Set(),
|
||||
depth = 0
|
||||
): error is Error {
|
||||
if (!(error instanceof Error) || depth > 8) {
|
||||
return false;
|
||||
}
|
||||
if (visited.has(error)) {
|
||||
return true;
|
||||
}
|
||||
visited.add(error);
|
||||
|
||||
try {
|
||||
const message = error.message;
|
||||
if (typeof message !== 'string' || containsAnyNeedle(message, needles)) {
|
||||
return false;
|
||||
}
|
||||
const stack = error.stack;
|
||||
if (typeof stack === 'string' && containsAnyNeedle(stack, needles)) {
|
||||
return false;
|
||||
}
|
||||
const cause = (error as { readonly cause?: unknown }).cause;
|
||||
if (cause !== undefined && !isErrorSafeToSurface(cause, needles, visited, depth + 1)) {
|
||||
return false;
|
||||
}
|
||||
if (error instanceof AggregateError || 'errors' in error) {
|
||||
const nested = (error as { readonly errors?: unknown }).errors;
|
||||
if (nested !== undefined) {
|
||||
if (!Array.isArray(nested)) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < nested.length; i += 1) {
|
||||
if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeHostError(
|
||||
error: unknown,
|
||||
stage: HostStage,
|
||||
needles: readonly string[]
|
||||
): Error {
|
||||
if (isErrorSafeToSurface(error, needles)) {
|
||||
return error;
|
||||
}
|
||||
return new Error(STAGE_ERROR_MESSAGES[stage]);
|
||||
}
|
||||
|
||||
function validateHostDeps(deps: ResearchCopilotStdioHostDeps): void {
|
||||
if (typeof deps !== 'object' || deps === null) {
|
||||
throw new Error('Invalid `deps`: expected a ResearchCopilotStdioHostDeps object.');
|
||||
}
|
||||
if (typeof deps.config !== 'object' || deps.config === null) {
|
||||
throw new Error('Invalid `deps.config`: expected a ResearchCopilotHostConfig object.');
|
||||
}
|
||||
if (typeof deps.openExecutor !== 'function') {
|
||||
throw new Error('Invalid `deps.openExecutor`: expected a callable factory function.');
|
||||
}
|
||||
if (typeof deps.openStore !== 'function') {
|
||||
throw new Error('Invalid `deps.openStore`: expected a callable factory function.');
|
||||
}
|
||||
if (typeof deps.createLibraryCardReader !== 'function') {
|
||||
throw new Error(
|
||||
'Invalid `deps.createLibraryCardReader`: expected a callable factory function.'
|
||||
);
|
||||
}
|
||||
if (typeof deps.newId !== 'function') {
|
||||
throw new Error('Invalid `deps.newId`: expected a callable ID generator function.');
|
||||
}
|
||||
if (typeof deps.now !== 'function') {
|
||||
throw new Error('Invalid `deps.now`: expected a callable clock function.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes and runs the headless MCP research copilot over stdio using
|
||||
* caller-injected resource factories.
|
||||
*
|
||||
* - Acquires resources sequentially (`openExecutor` -> `openStore` ->
|
||||
* `createLibraryCardReader`) before serving any stdio input.
|
||||
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff; the
|
||||
* caller's `openStore` factory must configure the store with that same cutoff.
|
||||
* - Always closes every acquired resource exactly once in reverse acquisition
|
||||
* order on EOF or error, preserving the primary failure when safe and
|
||||
* replacing credential-bearing or uninspectable errors with a fixed
|
||||
* stage-specific error without a raw `cause`.
|
||||
*/
|
||||
export async function runResearchCopilotStdioHost(
|
||||
deps: ResearchCopilotStdioHostDeps
|
||||
): Promise<void> {
|
||||
validateHostDeps(deps);
|
||||
|
||||
const { config } = deps;
|
||||
const secretNeedles = collectSecretNeedles(
|
||||
typeof config.postgresUrl === 'string' ? config.postgresUrl : ''
|
||||
);
|
||||
|
||||
const closers: Array<() => Promise<void> | void> = [];
|
||||
let primaryError: { readonly error: unknown; readonly stage: HostStage } | null = null;
|
||||
|
||||
try {
|
||||
let executorHandle: ManagedPostgresExecutor;
|
||||
try {
|
||||
executorHandle = await deps.openExecutor(config);
|
||||
} catch (error) {
|
||||
primaryError = { error, stage: 'executor_open' };
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof executorHandle !== 'object' ||
|
||||
executorHandle === null ||
|
||||
typeof executorHandle.close !== 'function'
|
||||
) {
|
||||
const error = new Error(
|
||||
'Invalid executor handle: expected an object with executor and close().'
|
||||
);
|
||||
primaryError = { error, stage: 'executor_open' };
|
||||
throw error;
|
||||
}
|
||||
closers.push(() => executorHandle.close());
|
||||
|
||||
let storeHandle: ManagedMarketDataStore;
|
||||
try {
|
||||
storeHandle = await deps.openStore(config);
|
||||
} catch (error) {
|
||||
primaryError = { error, stage: 'store_open' };
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof storeHandle !== 'object' ||
|
||||
storeHandle === null ||
|
||||
typeof storeHandle.close !== 'function'
|
||||
) {
|
||||
const error = new Error(
|
||||
'Invalid store handle: expected an object with store and close().'
|
||||
);
|
||||
primaryError = { error, stage: 'store_open' };
|
||||
throw error;
|
||||
}
|
||||
closers.push(() => storeHandle.close());
|
||||
|
||||
let libraryReader: LibraryCardReaderHandle;
|
||||
try {
|
||||
libraryReader = await deps.createLibraryCardReader(config);
|
||||
} catch (error) {
|
||||
primaryError = { error, stage: 'library_reader' };
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof libraryReader !== 'object' ||
|
||||
libraryReader === null ||
|
||||
typeof libraryReader.listLibraryCards !== 'function'
|
||||
) {
|
||||
const error = new Error(
|
||||
'Invalid library card reader: expected an object with listLibraryCards().'
|
||||
);
|
||||
primaryError = { error, stage: 'library_reader' };
|
||||
throw error;
|
||||
}
|
||||
|
||||
let server: McpServer;
|
||||
try {
|
||||
const sessionDates = createBarSessionDatesPort({
|
||||
store: storeHandle.store,
|
||||
referenceListingIds: config.referenceListingIds,
|
||||
});
|
||||
|
||||
server = createPostgresResearchCopilotServer({
|
||||
name: RESEARCH_COPILOT_HOST_NAME,
|
||||
version: RESEARCH_COPILOT_HOST_VERSION,
|
||||
executor: executorHandle.executor,
|
||||
...(config.postgresSchema !== undefined ? { schema: config.postgresSchema } : {}),
|
||||
store: storeHandle.store,
|
||||
vaultContext: { vaultCutoffTs: config.vaultCutoffTs },
|
||||
principalId: config.principalId,
|
||||
listLibraryCards: query => libraryReader.listLibraryCards(query),
|
||||
sessionDates,
|
||||
...(config.earlyCloses !== undefined ? { earlyCloses: config.earlyCloses } : {}),
|
||||
newId: deps.newId,
|
||||
now: deps.now,
|
||||
});
|
||||
} catch (error) {
|
||||
primaryError = { error, stage: 'server_init' };
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
await runStdioServer(server, deps.stdio);
|
||||
} catch (error) {
|
||||
primaryError = { error, stage: 'stdio_serve' };
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
if (primaryError === null) {
|
||||
primaryError = { error, stage: 'server_init' };
|
||||
}
|
||||
}
|
||||
|
||||
let firstCloseError: { readonly error: unknown } | null = null;
|
||||
for (let i = closers.length - 1; i >= 0; i -= 1) {
|
||||
try {
|
||||
await closers[i]?.();
|
||||
} catch (closeErr) {
|
||||
if (firstCloseError === null) {
|
||||
firstCloseError = { error: closeErr };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryError !== null) {
|
||||
throw sanitizeHostError(primaryError.error, primaryError.stage, secretNeedles);
|
||||
}
|
||||
if (firstCloseError !== null) {
|
||||
throw sanitizeHostError(firstCloseError.error, 'cleanup', secretNeedles);
|
||||
}
|
||||
}
|
||||
|
|
@ -13,3 +13,6 @@ export * from './tools/file-finding';
|
|||
export * from './tools/query-data';
|
||||
export * from './tools/read-knowledge';
|
||||
export * from './tools/search-symbols';
|
||||
export * from './adapters/postgres-copilot';
|
||||
export * from './adapters/bar-session-dates';
|
||||
export * from './host/stdio-host';
|
||||
|
|
|
|||
804
libs/research/src/notebook-snapshot.ts
Normal file
804
libs/research/src/notebook-snapshot.ts
Normal file
|
|
@ -0,0 +1,804 @@
|
|||
/**
|
||||
* `marimo check`-gated static HTML snapshot exporter for research notebooks.
|
||||
*
|
||||
* Enforces the D9 rule (`design/PLATFORM-PLAN.md`): a notebook must pass
|
||||
* `marimo check --format=json` with zero errors before `marimo export html`
|
||||
* runs, and exported HTML is published atomically via a sibling temp file.
|
||||
*
|
||||
* All subprocess execution and filesystem access are injected via ports
|
||||
* (`NotebookCommandRunner`, `NotebookSnapshotFs`). `node:crypto` is loaded
|
||||
* lazily at call time so `@stock-bot/research` remains browser-bundleable.
|
||||
*
|
||||
* Command flags and JSON diagnostic shape are confirmed against marimo 0.26.0
|
||||
* (pinned in `python/uv.lock`).
|
||||
*/
|
||||
|
||||
export const DEFAULT_MARIMO_COMMAND = 'marimo';
|
||||
export const DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS = 120_000;
|
||||
|
||||
const MAX_TEMP_RESERVATION_ATTEMPTS = 16;
|
||||
let tempSequence = 0;
|
||||
|
||||
/** Stable machine-readable error codes thrown by {@link NotebookSnapshotError}. */
|
||||
export type NotebookSnapshotErrorCode =
|
||||
| 'INVALID_OPTION'
|
||||
| 'INVALID_PATH'
|
||||
| 'NOTEBOOK_NOT_FOUND'
|
||||
| 'CHECK_FAILED'
|
||||
| 'CHECK_OUTPUT_INVALID'
|
||||
| 'EXPORT_FAILED'
|
||||
| 'EXPORT_EMPTY'
|
||||
| 'TIMEOUT';
|
||||
|
||||
export interface NotebookSnapshotErrorOptions {
|
||||
readonly details?: unknown;
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
/** Typed fail-closed error thrown by {@link exportNotebookSnapshot}. */
|
||||
export class NotebookSnapshotError extends Error {
|
||||
readonly code: NotebookSnapshotErrorCode;
|
||||
readonly details?: unknown;
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(
|
||||
code: NotebookSnapshotErrorCode,
|
||||
message: string,
|
||||
options?: NotebookSnapshotErrorOptions
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'NotebookSnapshotError';
|
||||
this.code = code;
|
||||
if (options && 'details' in options) {
|
||||
this.details = options.details;
|
||||
}
|
||||
if (options && 'cause' in options) {
|
||||
this.cause = options.cause;
|
||||
}
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export interface NotebookCommandRunOptions {
|
||||
readonly cwd?: string;
|
||||
readonly timeoutMs: number;
|
||||
}
|
||||
|
||||
export interface NotebookCommandResult {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injected command-runner port.
|
||||
*
|
||||
* Implementations MUST execute `command` directly with `args` as an argv array
|
||||
* (never via a shell string or shell interpolation).
|
||||
*
|
||||
* Timeout contract: on timeout, implementations MUST terminate the subprocess
|
||||
* and settle (rejecting with an error carrying `code: 'ETIMEDOUT'`) only after
|
||||
* the process has exited and stopped writing to disk.
|
||||
*/
|
||||
export interface NotebookCommandRunner {
|
||||
run(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: NotebookCommandRunOptions
|
||||
): Promise<NotebookCommandResult>;
|
||||
}
|
||||
|
||||
export interface NotebookSnapshotFileStat {
|
||||
readonly isFile: boolean;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal injected filesystem port for {@link exportNotebookSnapshot}.
|
||||
*/
|
||||
export interface NotebookSnapshotFs {
|
||||
/** Returns file metadata for `path`, or `null` when `path` does not exist. */
|
||||
stat(path: string): Promise<NotebookSnapshotFileStat | null>;
|
||||
/**
|
||||
* Exclusively creates an empty file at `path` (`O_CREAT | O_EXCL`).
|
||||
* MUST throw an error carrying `code: 'EEXIST'` if `path` already exists.
|
||||
*/
|
||||
createExclusive(path: string): Promise<void>;
|
||||
/** Reads the complete byte contents of `path`. */
|
||||
readBytes(path: string): Promise<Uint8Array>;
|
||||
/** Atomically replaces `destinationPath` with `sourcePath`. */
|
||||
rename(sourcePath: string, destinationPath: string): Promise<void>;
|
||||
/** Idempotently removes `path` (succeeds as a no-op if already absent). */
|
||||
remove(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Parsed marimo 0.26.0 `marimo check --format=json` summary object. */
|
||||
export interface MarimoCheckSummary {
|
||||
readonly errored: boolean;
|
||||
readonly total_files: number;
|
||||
readonly [key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Parsed marimo 0.26.0 `marimo check --format=json` report object. */
|
||||
export interface MarimoCheckReport {
|
||||
readonly issues: readonly Readonly<Record<string, unknown>>[];
|
||||
readonly summary: MarimoCheckSummary;
|
||||
readonly [key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ExportNotebookSnapshotOptions {
|
||||
readonly notebookPath: string;
|
||||
readonly outputPath: string;
|
||||
readonly runner: NotebookCommandRunner;
|
||||
readonly fs: NotebookSnapshotFs;
|
||||
/** Executable name or path for marimo (default `'marimo'`). */
|
||||
readonly marimoCommand?: string;
|
||||
/** Per-command timeout in milliseconds (default `120_000`). */
|
||||
readonly timeoutMs?: number;
|
||||
/** Optional working directory passed to `runner.run`. */
|
||||
readonly cwd?: string;
|
||||
/** Optional absolute root directory that `notebookPath` must lexically reside within. */
|
||||
readonly allowedNotebookRoot?: string;
|
||||
/** Optional absolute root directory that `outputPath` must lexically reside within. */
|
||||
readonly allowedOutputRoot?: string;
|
||||
}
|
||||
|
||||
/** Frozen receipt returned when a notebook snapshot is cleanly checked and published. */
|
||||
export interface NotebookSnapshotReceipt {
|
||||
readonly notebookPath: string;
|
||||
readonly outputPath: string;
|
||||
readonly bytes: number;
|
||||
readonly sha256: string;
|
||||
readonly checkDiagnostics: MarimoCheckReport | null;
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function getErrorCode(err: unknown): string | undefined {
|
||||
if (typeof err === 'object' && err !== null && 'code' in err) {
|
||||
const code = (err as { code?: unknown }).code;
|
||||
if (typeof code === 'string') {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizePosixAbsolutePath(rawPath: string): string {
|
||||
const segments = rawPath.split('/');
|
||||
const stack: string[] = [];
|
||||
for (let i = 0; i < segments.length; i += 1) {
|
||||
const seg = segments[i];
|
||||
if (seg === undefined || seg === '' || seg === '.') {
|
||||
continue;
|
||||
}
|
||||
if (seg === '..') {
|
||||
if (stack.length > 0) {
|
||||
stack.pop();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
stack.push(seg);
|
||||
}
|
||||
return `/${stack.join('/')}`;
|
||||
}
|
||||
|
||||
function validateAbsolutePath(
|
||||
rawPath: unknown,
|
||||
label: string,
|
||||
options?: { readonly requiredExtension?: string }
|
||||
): string {
|
||||
if (typeof rawPath !== 'string' || rawPath.length === 0) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_PATH',
|
||||
`Invalid ${label}: expected a non-empty string.`
|
||||
);
|
||||
}
|
||||
if (rawPath.includes('\0')) {
|
||||
throw new NotebookSnapshotError('INVALID_PATH', `Invalid ${label}: NUL bytes are not allowed.`);
|
||||
}
|
||||
if (rawPath.startsWith('-')) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_PATH',
|
||||
`Invalid ${label}: path must not start with '-'.`
|
||||
);
|
||||
}
|
||||
if (!rawPath.startsWith('/')) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_PATH',
|
||||
`Invalid ${label}: path must be an absolute POSIX path.`
|
||||
);
|
||||
}
|
||||
|
||||
if (options?.requiredExtension !== undefined) {
|
||||
if (rawPath.endsWith('/')) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_PATH',
|
||||
`Invalid ${label}: path must reference a ${options.requiredExtension} file, not a directory.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const normalized = normalizePosixAbsolutePath(rawPath);
|
||||
|
||||
if (options?.requiredExtension !== undefined) {
|
||||
const ext = options.requiredExtension;
|
||||
if (!normalized.endsWith(ext) || normalized === `/${ext}` || normalized.endsWith(`/${ext}`)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_PATH',
|
||||
`Invalid ${label}: path must end with '${ext}'.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function assertWithinRoot(
|
||||
normalizedPath: string,
|
||||
rawRoot: unknown,
|
||||
pathLabel: string,
|
||||
rootLabel: string
|
||||
): void {
|
||||
const normalizedRoot = validateAbsolutePath(rawRoot, rootLabel);
|
||||
if (normalizedRoot === '/') {
|
||||
return;
|
||||
}
|
||||
const requiredPrefix = `${normalizedRoot}/`;
|
||||
if (!normalizedPath.startsWith(requiredPrefix)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_PATH',
|
||||
`Invalid ${pathLabel}: resolved path '${normalizedPath}' escapes ${rootLabel} '${normalizedRoot}'.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function dirnamePosix(normalizedFilePath: string): string {
|
||||
const lastSlash = normalizedFilePath.lastIndexOf('/');
|
||||
return lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash);
|
||||
}
|
||||
|
||||
function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): {
|
||||
readonly notebookPath: string;
|
||||
readonly outputPath: string;
|
||||
readonly runner: NotebookCommandRunner;
|
||||
readonly fs: NotebookSnapshotFs;
|
||||
readonly marimoCommand: string;
|
||||
readonly timeoutMs: number;
|
||||
readonly cwd?: string;
|
||||
} {
|
||||
if (!isPlainObject(options)) {
|
||||
throw new NotebookSnapshotError('INVALID_OPTION', 'Invalid options: expected an object.');
|
||||
}
|
||||
|
||||
const { runner, fs } = options;
|
||||
if (!isPlainObject(runner) || typeof runner.run !== 'function') {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_OPTION',
|
||||
'Invalid runner: expected an object with a callable run(command, args, options) method.'
|
||||
);
|
||||
}
|
||||
if (
|
||||
!isPlainObject(fs) ||
|
||||
typeof fs.stat !== 'function' ||
|
||||
typeof fs.createExclusive !== 'function' ||
|
||||
typeof fs.readBytes !== 'function' ||
|
||||
typeof fs.rename !== 'function' ||
|
||||
typeof fs.remove !== 'function'
|
||||
) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_OPTION',
|
||||
'Invalid fs: expected an object implementing stat, createExclusive, readBytes, rename, and remove.'
|
||||
);
|
||||
}
|
||||
|
||||
const marimoCommand =
|
||||
options.marimoCommand === undefined ? DEFAULT_MARIMO_COMMAND : options.marimoCommand;
|
||||
if (
|
||||
typeof marimoCommand !== 'string' ||
|
||||
marimoCommand.trim().length === 0 ||
|
||||
marimoCommand.includes('\0') ||
|
||||
marimoCommand.startsWith('-')
|
||||
) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_OPTION',
|
||||
'Invalid marimoCommand: expected a non-empty command name or path without NUL bytes or leading "-".'
|
||||
);
|
||||
}
|
||||
|
||||
const timeoutMs =
|
||||
options.timeoutMs === undefined ? DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS : options.timeoutMs;
|
||||
if (typeof timeoutMs !== 'number' || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
|
||||
throw new NotebookSnapshotError(
|
||||
'INVALID_OPTION',
|
||||
'Invalid timeoutMs: expected a positive safe integer.'
|
||||
);
|
||||
}
|
||||
|
||||
const notebookPath = validateAbsolutePath(options.notebookPath, 'notebookPath', {
|
||||
requiredExtension: '.py',
|
||||
});
|
||||
const outputPath = validateAbsolutePath(options.outputPath, 'outputPath', {
|
||||
requiredExtension: '.html',
|
||||
});
|
||||
|
||||
if (options.allowedNotebookRoot !== undefined) {
|
||||
assertWithinRoot(
|
||||
notebookPath,
|
||||
options.allowedNotebookRoot,
|
||||
'notebookPath',
|
||||
'allowedNotebookRoot'
|
||||
);
|
||||
}
|
||||
if (options.allowedOutputRoot !== undefined) {
|
||||
assertWithinRoot(outputPath, options.allowedOutputRoot, 'outputPath', 'allowedOutputRoot');
|
||||
}
|
||||
|
||||
let cwd: string | undefined;
|
||||
if (options.cwd !== undefined) {
|
||||
cwd = validateAbsolutePath(options.cwd, 'cwd');
|
||||
}
|
||||
|
||||
return {
|
||||
notebookPath,
|
||||
outputPath,
|
||||
runner,
|
||||
fs,
|
||||
marimoCommand,
|
||||
timeoutMs,
|
||||
...(cwd !== undefined ? { cwd } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function validateCommandResult(result: unknown, phase: 'check' | 'export'): NotebookCommandResult {
|
||||
if (
|
||||
!isPlainObject(result) ||
|
||||
typeof result.exitCode !== 'number' ||
|
||||
!Number.isSafeInteger(result.exitCode) ||
|
||||
typeof result.stdout !== 'string' ||
|
||||
typeof result.stderr !== 'string'
|
||||
) {
|
||||
throw new NotebookSnapshotError(
|
||||
phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED',
|
||||
`Invalid runner result for marimo ${phase}: expected { exitCode, stdout, stderr }.`
|
||||
);
|
||||
}
|
||||
return {
|
||||
exitCode: result.exitCode,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
};
|
||||
}
|
||||
|
||||
function issueHasBlockingError(issue: Record<string, unknown>): boolean {
|
||||
if (issue.type === 'error' || issue.severity === 'breaking') {
|
||||
return true;
|
||||
}
|
||||
const nested = issue.diagnostics;
|
||||
if (Array.isArray(nested)) {
|
||||
for (let i = 0; i < nested.length; i += 1) {
|
||||
const diag = nested[i];
|
||||
if (isPlainObject(diag) && (diag.type === 'error' || diag.severity === 'breaking')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function parseAndValidateCheckReport(parsed: unknown): {
|
||||
readonly report: MarimoCheckReport;
|
||||
readonly hasBlockingError: boolean;
|
||||
} {
|
||||
if (!isPlainObject(parsed)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
'marimo check JSON output must be an object with { issues, summary }.'
|
||||
);
|
||||
}
|
||||
|
||||
const { issues, summary } = parsed;
|
||||
if (!Array.isArray(issues) || !isPlainObject(summary)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
'marimo check JSON output must contain an issues array and a summary object.'
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof summary.errored !== 'boolean' ||
|
||||
typeof summary.total_files !== 'number' ||
|
||||
!Number.isSafeInteger(summary.total_files)
|
||||
) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
'marimo check summary must include boolean errored and integer total_files.'
|
||||
);
|
||||
}
|
||||
|
||||
if (summary.total_files !== 1) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check reported summary.total_files=${summary.total_files}; expected exactly 1 checked file.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
|
||||
let hasBlockingError = summary.errored;
|
||||
|
||||
for (let i = 0; i < issues.length; i += 1) {
|
||||
const issue = issues[i];
|
||||
if (!isPlainObject(issue)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}] must be an object.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
if (issue.type !== undefined && typeof issue.type !== 'string') {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}].type must be a string when present.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
if (issue.severity !== undefined && typeof issue.severity !== 'string') {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}].severity must be a string when present.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
if (issue.diagnostics !== undefined) {
|
||||
if (!Array.isArray(issue.diagnostics)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}].diagnostics must be an array when present.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
for (let j = 0; j < issue.diagnostics.length; j += 1) {
|
||||
const diag = issue.diagnostics[j];
|
||||
if (!isPlainObject(diag)) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}].diagnostics[${j}] must be an object.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
if (diag.type !== undefined && typeof diag.type !== 'string') {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}].diagnostics[${j}].type must be a string when present.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
if (diag.severity !== undefined && typeof diag.severity !== 'string') {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
`marimo check issues[${i}].diagnostics[${j}].severity must be a string when present.`,
|
||||
{ details: { diagnostics: parsed } }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (issueHasBlockingError(issue)) {
|
||||
hasBlockingError = true;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
report: parsed as MarimoCheckReport,
|
||||
hasBlockingError,
|
||||
};
|
||||
}
|
||||
|
||||
function deepFreeze<T>(value: T): T {
|
||||
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {
|
||||
return value;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
deepFreeze(value[i]);
|
||||
}
|
||||
return Object.freeze(value);
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
const keys = Object.keys(record);
|
||||
for (let i = 0; i < keys.length; i += 1) {
|
||||
const key = keys[i] as string;
|
||||
deepFreeze(record[key]);
|
||||
}
|
||||
return Object.freeze(value);
|
||||
}
|
||||
|
||||
function generateTempToken(): string {
|
||||
tempSequence += 1;
|
||||
const randomPart =
|
||||
typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function'
|
||||
? globalThis.crypto.randomUUID().replace(/-/g, '')
|
||||
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return `${tempSequence}-${randomPart}`;
|
||||
}
|
||||
|
||||
async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise<string> {
|
||||
const dir = dirnamePosix(outputPath);
|
||||
const dirPrefix = dir === '/' ? '' : dir;
|
||||
|
||||
for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) {
|
||||
const candidate = `${dirPrefix}/.marimo-snapshot-${generateTempToken()}.tmp.html`;
|
||||
try {
|
||||
await fs.createExclusive(candidate);
|
||||
return candidate;
|
||||
} catch (err) {
|
||||
if (getErrorCode(err) === 'EEXIST') {
|
||||
continue;
|
||||
}
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
`Failed to reserve temporary HTML sibling for '${outputPath}'.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
`Failed to reserve a unique temporary HTML sibling for '${outputPath}' after ${MAX_TEMP_RESERVATION_ATTEMPTS} attempts.`
|
||||
);
|
||||
}
|
||||
|
||||
async function sha256HexNodeCrypto(bytes: Uint8Array): Promise<string> {
|
||||
// Keep the Node built-in specifier non-literal so browser bundlers do not try
|
||||
// to statically resolve `node:crypto` when bundling `@stock-bot/research`.
|
||||
const cryptoSpecifier = 'node:crypto';
|
||||
const nodeCrypto = (await import(cryptoSpecifier)) as typeof import('node:crypto');
|
||||
return nodeCrypto.createHash('sha256').update(bytes).digest('hex');
|
||||
}
|
||||
|
||||
async function runPhaseCommand(
|
||||
runner: NotebookCommandRunner,
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
runOptions: NotebookCommandRunOptions,
|
||||
phase: 'check' | 'export'
|
||||
): Promise<NotebookCommandResult> {
|
||||
let rawResult: unknown;
|
||||
try {
|
||||
rawResult = await runner.run(command, args, runOptions);
|
||||
} catch (err) {
|
||||
if (getErrorCode(err) === 'ETIMEDOUT') {
|
||||
throw new NotebookSnapshotError(
|
||||
'TIMEOUT',
|
||||
`marimo ${phase} timed out after ${runOptions.timeoutMs}ms.`,
|
||||
{ cause: err, details: { phase, timeoutMs: runOptions.timeoutMs } }
|
||||
);
|
||||
}
|
||||
throw new NotebookSnapshotError(
|
||||
phase === 'check' ? 'CHECK_FAILED' : 'EXPORT_FAILED',
|
||||
`marimo ${phase} command failed to execute.`,
|
||||
{ cause: err, details: { phase } }
|
||||
);
|
||||
}
|
||||
return validateCommandResult(rawResult, phase);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a marimo notebook with `marimo check --format=json` and, only when
|
||||
* the check is clean, exports a static HTML snapshot via `marimo export html`
|
||||
* and publishes it atomically via sibling temp-file rename.
|
||||
*/
|
||||
export async function exportNotebookSnapshot(
|
||||
options: ExportNotebookSnapshotOptions
|
||||
): Promise<NotebookSnapshotReceipt> {
|
||||
const { notebookPath, outputPath, runner, fs, marimoCommand, timeoutMs, cwd } =
|
||||
validatePortsAndOptions(options);
|
||||
|
||||
let notebookStat: NotebookSnapshotFileStat | null;
|
||||
try {
|
||||
notebookStat = await fs.stat(notebookPath);
|
||||
} catch (err) {
|
||||
if (getErrorCode(err) === 'ENOENT') {
|
||||
notebookStat = null;
|
||||
} else {
|
||||
throw new NotebookSnapshotError(
|
||||
'NOTEBOOK_NOT_FOUND',
|
||||
`Unable to stat notebook '${notebookPath}'.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (notebookStat === null || !notebookStat.isFile) {
|
||||
throw new NotebookSnapshotError(
|
||||
'NOTEBOOK_NOT_FOUND',
|
||||
`Notebook file not found or is not a regular file: '${notebookPath}'.`
|
||||
);
|
||||
}
|
||||
|
||||
const runOptions: NotebookCommandRunOptions =
|
||||
cwd !== undefined ? { cwd, timeoutMs } : { timeoutMs };
|
||||
|
||||
// Step 1: Gate on `marimo check --format=json <notebookPath>`.
|
||||
const checkResult = await runPhaseCommand(
|
||||
runner,
|
||||
marimoCommand,
|
||||
['check', '--format=json', notebookPath],
|
||||
runOptions,
|
||||
'check'
|
||||
);
|
||||
|
||||
const hasCheckStdout = checkResult.stdout.length > 0;
|
||||
let parsedCheckJson: unknown = undefined;
|
||||
let checkJsonParseError: unknown = undefined;
|
||||
if (hasCheckStdout) {
|
||||
try {
|
||||
parsedCheckJson = JSON.parse(checkResult.stdout);
|
||||
} catch (err) {
|
||||
checkJsonParseError = err;
|
||||
}
|
||||
}
|
||||
|
||||
if (checkResult.exitCode !== 0) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_FAILED',
|
||||
`marimo check exited with code ${checkResult.exitCode}.`,
|
||||
{
|
||||
details: {
|
||||
exitCode: checkResult.exitCode,
|
||||
stderr: checkResult.stderr,
|
||||
stdout: checkResult.stdout,
|
||||
...(checkJsonParseError === undefined && parsedCheckJson !== undefined
|
||||
? { diagnostics: parsedCheckJson }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let checkDiagnostics: MarimoCheckReport | null = null;
|
||||
if (hasCheckStdout) {
|
||||
if (checkJsonParseError !== undefined) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_OUTPUT_INVALID',
|
||||
'marimo check exited 0 but emitted non-JSON stdout.',
|
||||
{
|
||||
cause: checkJsonParseError,
|
||||
details: { stdout: checkResult.stdout, stderr: checkResult.stderr },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const { report, hasBlockingError } = parseAndValidateCheckReport(parsedCheckJson);
|
||||
if (hasBlockingError) {
|
||||
throw new NotebookSnapshotError(
|
||||
'CHECK_FAILED',
|
||||
'marimo check reported blocking errors in diagnostics.',
|
||||
{
|
||||
details: {
|
||||
exitCode: checkResult.exitCode,
|
||||
stderr: checkResult.stderr,
|
||||
diagnostics: report,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
checkDiagnostics = deepFreeze(report);
|
||||
}
|
||||
|
||||
// Step 2: Reserve an exclusive sibling `.html` temp file and run `marimo export html`.
|
||||
const tempPath = await reserveSiblingTempHtml(fs, outputPath);
|
||||
let tempOwned = true;
|
||||
|
||||
try {
|
||||
const exportResult = await runPhaseCommand(
|
||||
runner,
|
||||
marimoCommand,
|
||||
['export', 'html', notebookPath, '-o', tempPath, '--force'],
|
||||
runOptions,
|
||||
'export'
|
||||
);
|
||||
|
||||
if (exportResult.exitCode !== 0) {
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
`marimo export html exited with code ${exportResult.exitCode}.`,
|
||||
{
|
||||
details: {
|
||||
exitCode: exportResult.exitCode,
|
||||
stderr: exportResult.stderr,
|
||||
stdout: exportResult.stdout,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let tempStat: NotebookSnapshotFileStat | null;
|
||||
try {
|
||||
tempStat = await fs.stat(tempPath);
|
||||
} catch (err) {
|
||||
if (getErrorCode(err) === 'ENOENT') {
|
||||
tempStat = null;
|
||||
} else {
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
`Failed to stat exported snapshot temp file '${tempPath}'.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (tempStat === null || !tempStat.isFile || tempStat.size <= 0) {
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_EMPTY',
|
||||
`marimo export html produced missing or empty output at '${tempPath}'.`
|
||||
);
|
||||
}
|
||||
|
||||
let exportedBytes: Uint8Array;
|
||||
try {
|
||||
exportedBytes = await fs.readBytes(tempPath);
|
||||
} catch (err) {
|
||||
if (getErrorCode(err) === 'ENOENT') {
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_EMPTY',
|
||||
`Exported snapshot temp file '${tempPath}' disappeared before read.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
`Failed to read exported snapshot temp file '${tempPath}'.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
|
||||
if (!(exportedBytes instanceof Uint8Array) || exportedBytes.byteLength === 0) {
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_EMPTY',
|
||||
`marimo export html produced zero bytes at '${tempPath}'.`
|
||||
);
|
||||
}
|
||||
|
||||
const sha256 = await sha256HexNodeCrypto(exportedBytes);
|
||||
const receipt: NotebookSnapshotReceipt = Object.freeze({
|
||||
notebookPath,
|
||||
outputPath,
|
||||
bytes: exportedBytes.byteLength,
|
||||
sha256,
|
||||
checkDiagnostics,
|
||||
});
|
||||
|
||||
try {
|
||||
await fs.rename(tempPath, outputPath);
|
||||
tempOwned = false;
|
||||
} catch (err) {
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
`Failed to atomically publish snapshot from '${tempPath}' to '${outputPath}'.`,
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
|
||||
return receipt;
|
||||
} catch (err) {
|
||||
if (tempOwned) {
|
||||
try {
|
||||
await fs.remove(tempPath);
|
||||
} catch {
|
||||
// Preserve the primary error if temp cleanup also fails.
|
||||
}
|
||||
}
|
||||
if (err instanceof NotebookSnapshotError) {
|
||||
throw err;
|
||||
}
|
||||
throw new NotebookSnapshotError(
|
||||
'EXPORT_FAILED',
|
||||
'Unexpected failure during notebook snapshot export.',
|
||||
{ cause: err }
|
||||
);
|
||||
}
|
||||
}
|
||||
249
libs/research/test/mcp-bar-session-dates-qa.test.ts
Normal file
249
libs/research/test/mcp-bar-session-dates-qa.test.ts
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { VaultHoldoutFenceError } from '../src/market-data-store';
|
||||
import {
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
createDuckDbMarketDataStore,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import {
|
||||
type ListingCalendarPort,
|
||||
createBarSessionDatesPort,
|
||||
createExchangeCalendarResolver,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
/**
|
||||
* QA: the bar-derived SessionDatesPort composed with the real DuckDB store
|
||||
* planner (`planBars1dQuery` + `mapBarRows`) over a recording fake executor that
|
||||
* emulates the raw 1d SQL predicate (`listing_id IN (...) AND ts >= ? AND ts <= ?
|
||||
* AND known_at <= ?` ordered by `listing_id, ts`) on a pinned in-memory dataset.
|
||||
*/
|
||||
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const CUTOFF_MS = Date.UTC(2026, 4, 28, 0, 0, 0, 0); // 2026-05-28T00:00:00.000Z
|
||||
const MAX_ALLOWED_ISO_MICROS = '2026-05-27T23:59:59.999999Z';
|
||||
|
||||
interface FixtureBar {
|
||||
readonly listingId: number;
|
||||
readonly ts: number;
|
||||
readonly knownAt: number;
|
||||
}
|
||||
|
||||
function utcMs(dateStr: string, hour: number, minute = 0): number {
|
||||
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
|
||||
return Date.UTC(y, m - 1, d, hour, minute, 0, 0);
|
||||
}
|
||||
|
||||
/** 16:00 ET daily stamp (curate_bars.rs convention): 20:00Z in EDT. Known shortly after close. */
|
||||
function edtBar(listingId: number, date: string, knownAt?: number): FixtureBar {
|
||||
const ts = utcMs(date, 20);
|
||||
return { listingId, ts, knownAt: knownAt ?? ts + 60_000 };
|
||||
}
|
||||
|
||||
/** Parses `YYYY-MM-DDTHH:MM:SS(.ffffff)?Z` to fractional epoch ms (µs precision kept). */
|
||||
function isoToMs(iso: string): number {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?Z$/.exec(iso);
|
||||
if (m === null) {
|
||||
throw new Error(`Unexpected ISO bound: ${iso}`);
|
||||
}
|
||||
const frac = Number(`0.${(m[7] ?? '0').padEnd(6, '0').slice(0, 6)}`);
|
||||
return (
|
||||
Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])) +
|
||||
frac * 1000
|
||||
);
|
||||
}
|
||||
|
||||
function createFixtureExecutor(dataset: readonly FixtureBar[]): {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly queries: Array<{ sql: string; params: readonly DuckDbParam[] }>;
|
||||
} {
|
||||
const queries: Array<{ sql: string; params: readonly DuckDbParam[] }> = [];
|
||||
const executor: DuckDbExecutor = {
|
||||
async run(): Promise<void> {},
|
||||
async query(sql: string, params: readonly DuckDbParam[]) {
|
||||
queries.push({ sql, params: [...params] });
|
||||
const listingIds = new Set(params.slice(0, -3) as number[]);
|
||||
const [fromIso, toIso, asOfIso] = params.slice(-3) as [string, string, string];
|
||||
const fromMs = isoToMs(fromIso);
|
||||
const toMs = isoToMs(toIso);
|
||||
const asOfMs = isoToMs(asOfIso);
|
||||
return dataset
|
||||
.filter(
|
||||
(b) =>
|
||||
listingIds.has(b.listingId) && b.ts >= fromMs && b.ts <= toMs && b.knownAt <= asOfMs
|
||||
)
|
||||
.sort((a, b) => a.listingId - b.listingId || a.ts - b.ts)
|
||||
.map((b) => ({
|
||||
listing_id: b.listingId,
|
||||
ts: b.ts,
|
||||
open: 10,
|
||||
high: 11,
|
||||
low: 9,
|
||||
close: 10.5,
|
||||
volume: 1000,
|
||||
vwap: null,
|
||||
known_at: b.knownAt,
|
||||
}));
|
||||
},
|
||||
};
|
||||
return { executor, queries };
|
||||
}
|
||||
|
||||
const DATASET: readonly FixtureBar[] = [
|
||||
// XNYS reference listings 11 and 12 (overlapping + one-sided dates).
|
||||
edtBar(11, '2026-05-21'),
|
||||
edtBar(12, '2026-05-22'),
|
||||
edtBar(11, '2026-05-26'),
|
||||
edtBar(12, '2026-05-26'),
|
||||
edtBar(12, '2026-05-27'),
|
||||
// Held-out Vault sessions at and after the cutoff date.
|
||||
edtBar(11, '2026-05-28'),
|
||||
edtBar(12, '2026-05-29'),
|
||||
edtBar(11, '2026-06-01'),
|
||||
// XTSE reference listing 21.
|
||||
edtBar(21, '2026-05-25'), // Victoria Day: XTSE closed in reality, but present here to prove per-calendar isolation.
|
||||
edtBar(21, '2026-05-26'),
|
||||
// Pre-cutoff session whose bar only became known after the cutoff: must stay hidden.
|
||||
edtBar(21, '2026-05-27', CUTOFF_MS + 3_600_000),
|
||||
edtBar(21, '2026-05-28'),
|
||||
];
|
||||
|
||||
function makeStore(barBatchSize?: number) {
|
||||
const fake = createFixtureExecutor(DATASET);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fake.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: {},
|
||||
...(barBatchSize !== undefined ? { barBatchSize } : {}),
|
||||
});
|
||||
return { store, queries: fake.queries };
|
||||
}
|
||||
|
||||
describe('bar-session-dates QA — DuckDB store planner at the Vault cutoff', () => {
|
||||
test('window straddling the cutoff returns only pre-cutoff sessions with a raw bars_1d plan clamped to cutoff - 1µs', async () => {
|
||||
const { store, queries } = makeStore();
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [12, 11], XTSE: [21] },
|
||||
});
|
||||
|
||||
const dates = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2026-05-22',
|
||||
toDate: '2026-06-02',
|
||||
});
|
||||
|
||||
expect(dates).toEqual(['2026-05-22', '2026-05-26', '2026-05-27']);
|
||||
expect(queries).toHaveLength(1);
|
||||
const q = queries[0]!;
|
||||
expect(q.sql).toContain(`read_parquet('${CURATED_ROOT}/bars_1d/year=*/part.parquet'`);
|
||||
expect(q.sql).not.toContain('adj_factors');
|
||||
expect(q.params).toEqual([
|
||||
12,
|
||||
11,
|
||||
'2026-05-22T00:00:00.000Z',
|
||||
MAX_ALLOWED_ISO_MICROS,
|
||||
MAX_ALLOWED_ISO_MICROS,
|
||||
]);
|
||||
});
|
||||
|
||||
test('pre-cutoff bar first known after the cutoff is excluded via the default known_at fence', async () => {
|
||||
const { store } = makeStore();
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12], XTSE: [21] },
|
||||
});
|
||||
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XTSE',
|
||||
fromDate: '2026-05-25',
|
||||
toDate: '2026-05-31',
|
||||
})
|
||||
).toEqual(['2026-05-25', '2026-05-26']);
|
||||
});
|
||||
|
||||
test('fromDate on or after the cutoff date rejects with VaultHoldoutFenceError before any executor query', async () => {
|
||||
const { store, queries } = makeStore();
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12] },
|
||||
});
|
||||
|
||||
for (const fromDate of ['2026-05-28', '2026-06-01']) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({ calendarCode: 'XNYS', fromDate, toDate: '2026-06-02' });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(VaultHoldoutFenceError);
|
||||
}
|
||||
expect(queries).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('last pre-cutoff day as a single-day window is included, and output is identical across barBatchSize settings', async () => {
|
||||
const results: string[][] = [];
|
||||
for (const batchSize of [undefined, 1, 2]) {
|
||||
const { store } = makeStore(batchSize);
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12] },
|
||||
});
|
||||
results.push([
|
||||
...(await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2026-05-21',
|
||||
toDate: '2026-05-27',
|
||||
})),
|
||||
]);
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2026-05-27',
|
||||
toDate: '2026-05-27',
|
||||
})
|
||||
).toEqual(['2026-05-27']);
|
||||
}
|
||||
const expected = ['2026-05-21', '2026-05-22', '2026-05-26', '2026-05-27'];
|
||||
expect(results).toEqual([expected, expected, expected]);
|
||||
});
|
||||
|
||||
test('resolver composed over the DuckDB-backed port yields no post-cutoff session closes', async () => {
|
||||
const { store, queries } = makeStore();
|
||||
const sessionDates = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [11, 12], XTSE: [21] },
|
||||
});
|
||||
const listingCalendars: ListingCalendarPort = {
|
||||
getListingCalendars(listingIds) {
|
||||
return listingIds.map((listingId) => ({
|
||||
listingId,
|
||||
calendarCode: listingId === 901 ? 'XNYS' : 'XTSE',
|
||||
}));
|
||||
},
|
||||
};
|
||||
const resolve = createExchangeCalendarResolver({ listingCalendars, sessionDates });
|
||||
|
||||
const resolved = await resolve({
|
||||
listingIds: [901, 902],
|
||||
fromDate: '2026-05-26',
|
||||
toDate: '2026-06-02',
|
||||
});
|
||||
|
||||
expect(resolved.listingCalendarId).toEqual({ 901: 'XNYS', 902: 'XTSE' });
|
||||
expect(resolved.calendars).toEqual({
|
||||
XNYS: [
|
||||
{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) },
|
||||
{ date: '2026-05-27', closeTs: utcMs('2026-05-27', 20) },
|
||||
],
|
||||
XTSE: [{ date: '2026-05-26', closeTs: utcMs('2026-05-26', 20) }],
|
||||
});
|
||||
for (const closes of Object.values(resolved.calendars)) {
|
||||
for (const c of closes) {
|
||||
expect(c.closeTs).toBeLessThan(CUTOFF_MS);
|
||||
}
|
||||
}
|
||||
expect(queries).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
527
libs/research/test/mcp-bar-session-dates.test.ts
Normal file
527
libs/research/test/mcp-bar-session-dates.test.ts
Normal file
|
|
@ -0,0 +1,527 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
VaultHoldoutFenceError,
|
||||
} from '../src/market-data-store';
|
||||
import {
|
||||
BarSessionDatesError,
|
||||
type BarSessionDatesPortOptions,
|
||||
type ListingCalendarPort,
|
||||
type PostgresResearchCopilotServerOptions,
|
||||
type SessionDatesPort,
|
||||
createBarSessionDatesPort,
|
||||
createExchangeCalendarResolver,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
type BarsQueryArg = Parameters<MarketDataStore['bars']>[0];
|
||||
|
||||
function utcMs(
|
||||
year: number,
|
||||
month: number,
|
||||
day: number,
|
||||
hour = 0,
|
||||
minute = 0,
|
||||
second = 0
|
||||
): number {
|
||||
return Date.UTC(year, month - 1, day, hour, minute, second, 0);
|
||||
}
|
||||
|
||||
function makeBar(listingId: number, dateStr: string, closeHourUtc = 21): BarRecord {
|
||||
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
|
||||
const ts = utcMs(y, m, d, closeHourUtc, 0, 0);
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: 100,
|
||||
high: 101,
|
||||
low: 99,
|
||||
close: 100.5,
|
||||
volume: 100_000,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRecordingStore(
|
||||
handler: (q: BarsQueryArg) => AsyncIterable<BarBatch>
|
||||
): {
|
||||
readonly store: Pick<MarketDataStore, 'bars'>;
|
||||
readonly calls: BarsQueryArg[];
|
||||
} {
|
||||
const calls: BarsQueryArg[] = [];
|
||||
const store: Pick<MarketDataStore, 'bars'> = {
|
||||
bars(q: BarsQueryArg): AsyncIterable<BarBatch> {
|
||||
calls.push(q);
|
||||
return handler(q);
|
||||
},
|
||||
};
|
||||
return { store, calls };
|
||||
}
|
||||
|
||||
async function* yieldBatches(batches: readonly BarBatch[]): AsyncGenerator<BarBatch> {
|
||||
for (const batch of batches) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
|
||||
describe('createBarSessionDatesPort — exports, types, and query contract', () => {
|
||||
test('returned port is assignable to SessionDatesPort and PostgresResearchCopilotServerOptions["sessionDates"] without casts', async () => {
|
||||
const { store } = makeRecordingStore(() => yieldBatches([]));
|
||||
const options: BarSessionDatesPortOptions = {
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101],
|
||||
},
|
||||
};
|
||||
|
||||
const port = createBarSessionDatesPort(options);
|
||||
const asSessionDatesPort: SessionDatesPort = port;
|
||||
const asCopilotSessionDates: PostgresResearchCopilotServerOptions['sessionDates'] = port;
|
||||
|
||||
expect(asSessionDatesPort).toBe(port);
|
||||
expect(asCopilotSessionDates).toBe(port);
|
||||
expect(
|
||||
await asCopilotSessionDates.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
})
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test('calls store.bars once per query with exact Vault-default keys and configured ID order', async () => {
|
||||
const { store, calls } = makeRecordingStore(() =>
|
||||
yieldBatches([{ rows: [makeBar(202, '2024-11-26', 21)] }])
|
||||
);
|
||||
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [202, 101],
|
||||
XTSE: [303],
|
||||
},
|
||||
});
|
||||
|
||||
const dates = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
|
||||
expect(dates).toEqual(['2024-11-26']);
|
||||
expect(calls).toHaveLength(1);
|
||||
|
||||
const req = calls[0] as BarsQueryArg;
|
||||
expect(req.listingIds).toEqual([202, 101]);
|
||||
expect(req.timeframe).toBe('1d');
|
||||
expect(req.adjustment).toBe('raw');
|
||||
expect(req.from).toBe('2024-11-25');
|
||||
expect(req.to).toBe('2024-11-29');
|
||||
expect(Object.keys(req).sort()).toEqual(['adjustment', 'from', 'listingIds', 'timeframe', 'to']);
|
||||
expect('scope' in req).toBe(false);
|
||||
expect('asOf' in req).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — union, bounds, determinism, and empty streams', () => {
|
||||
test('returns strictly ascending de-duplicated union across multiple out-of-order batches inside [fromDate, toDate]', async () => {
|
||||
const batches: readonly BarBatch[] = [
|
||||
{
|
||||
rows: [
|
||||
// Valid bars outside the requested window must be excluded.
|
||||
makeBar(101, '2024-11-22', 21),
|
||||
makeBar(102, '2024-12-02', 21),
|
||||
// Out-of-order bars inside window, including upper inclusive bound.
|
||||
makeBar(102, '2024-11-29', 21),
|
||||
makeBar(101, '2024-11-27', 21),
|
||||
],
|
||||
},
|
||||
{
|
||||
rows: [
|
||||
// Overlapping date (2024-11-27), single-listing date (2024-11-26), lower inclusive bound (2024-11-25).
|
||||
makeBar(102, '2024-11-27', 21),
|
||||
makeBar(101, '2024-11-25', 21),
|
||||
makeBar(102, '2024-11-26', 21),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { store, calls } = makeRecordingStore(() => yieldBatches(batches));
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101, 102],
|
||||
},
|
||||
});
|
||||
|
||||
const first = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
const second = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
|
||||
const expected = ['2024-11-25', '2024-11-26', '2024-11-27', '2024-11-29'];
|
||||
expect(first).toEqual(expected);
|
||||
expect(second).toEqual(expected);
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('supports single-day inclusive window and returns [] for empty streams or empty batches', async () => {
|
||||
const { store: singleDayStore } = makeRecordingStore(() =>
|
||||
yieldBatches([
|
||||
{
|
||||
rows: [
|
||||
makeBar(101, '2024-07-01', 20),
|
||||
makeBar(101, '2024-07-02', 20),
|
||||
makeBar(101, '2024-07-03', 20),
|
||||
],
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const singleDayPort = createBarSessionDatesPort({
|
||||
store: singleDayStore,
|
||||
referenceListingIds: { XNYS: [101] },
|
||||
});
|
||||
|
||||
expect(
|
||||
await singleDayPort.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-07-02',
|
||||
toDate: '2024-07-02',
|
||||
})
|
||||
).toEqual(['2024-07-02']);
|
||||
|
||||
const { store: emptyBatchStore } = makeRecordingStore(() =>
|
||||
yieldBatches([{ rows: [] }, { rows: [] }])
|
||||
);
|
||||
const emptyPort = createBarSessionDatesPort({
|
||||
store: emptyBatchStore,
|
||||
referenceListingIds: { XNYS: [101] },
|
||||
});
|
||||
|
||||
expect(
|
||||
await emptyPort.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-07-02',
|
||||
toDate: '2024-07-02',
|
||||
})
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — fail-closed query, store error, and bar validation', () => {
|
||||
test('throws unknown_calendar and invalid_query with zero store calls', async () => {
|
||||
const { store, calls } = makeRecordingStore(() => yieldBatches([]));
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101],
|
||||
},
|
||||
});
|
||||
|
||||
const expectError = async (
|
||||
query: unknown,
|
||||
expectedCode: BarSessionDatesError['code']
|
||||
): Promise<void> => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates(query as never);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe(expectedCode);
|
||||
};
|
||||
|
||||
await expectError(
|
||||
{ calendarCode: 'XTSE', fromDate: '2024-11-25', toDate: '2024-11-29' },
|
||||
'unknown_calendar'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: '', fromDate: '2024-11-25', toDate: '2024-11-29' },
|
||||
'unknown_calendar'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024/11/25', toDate: '2024-11-29' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-11-25T00:00:00Z', toDate: '2024-11-29' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-02-30', toDate: '2024-03-01' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-11-25', toDate: '2023-02-29' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-11-29', toDate: '2024-11-25' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(null, 'invalid_query');
|
||||
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('propagates VaultHoldoutFenceError from the async iterator unchanged with no partial result', async () => {
|
||||
const vaultError = new VaultHoldoutFenceError(
|
||||
'2025-01-02',
|
||||
utcMs(2025, 1, 2, 0, 0, 0),
|
||||
utcMs(2025, 1, 1, 0, 0, 0)
|
||||
);
|
||||
|
||||
const { store } = makeRecordingStore(() =>
|
||||
(async function* (): AsyncGenerator<BarBatch> {
|
||||
yield { rows: [makeBar(101, '2024-12-31', 21)] };
|
||||
throw vaultError;
|
||||
})()
|
||||
);
|
||||
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [101] },
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-12-30',
|
||||
toDate: '2025-01-02',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(caught).toBe(vaultError);
|
||||
});
|
||||
|
||||
test('throws invalid_bar for NaN, Infinity, fractional ts, or unconfigured listingId', async () => {
|
||||
const badBars: readonly BarRecord[] = [
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: Number.NaN },
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: Number.POSITIVE_INFINITY },
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: Number.NEGATIVE_INFINITY },
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: utcMs(2024, 11, 25, 21, 0, 0) + 0.5 },
|
||||
// Listing ID configured only on XTSE, not XNYS.
|
||||
makeBar(202, '2024-11-25', 21),
|
||||
// Listing ID not configured on any calendar, even when outside the date window.
|
||||
makeBar(999, '2024-01-02', 21),
|
||||
];
|
||||
|
||||
for (const badBar of badBars) {
|
||||
const { store } = makeRecordingStore(() => yieldBatches([{ rows: [badBar] }]));
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101],
|
||||
XTSE: [202],
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe('invalid_bar');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — options validation and defensive copy', () => {
|
||||
test('rejects malformed options, empty keys, non-positive/non-INT32 IDs, and duplicates with invalid_options', () => {
|
||||
const { store } = makeRecordingStore(() => yieldBatches([]));
|
||||
|
||||
const invalidInputs: readonly unknown[] = [
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
{ store: null, referenceListingIds: { XNYS: [1] } },
|
||||
{ store: {}, referenceListingIds: { XNYS: [1] } },
|
||||
{ store: { bars: 'nope' }, referenceListingIds: { XNYS: [1] } },
|
||||
{ store, referenceListingIds: null },
|
||||
{ store, referenceListingIds: [] },
|
||||
{ store, referenceListingIds: { '': [1] } },
|
||||
{ store, referenceListingIds: { ' ': [1] } },
|
||||
{ store, referenceListingIds: { ' XNYS': [1] } },
|
||||
{ store, referenceListingIds: { XNYS: null } },
|
||||
{ store, referenceListingIds: { XNYS: [] } },
|
||||
{ store, referenceListingIds: { XNYS: [0] } },
|
||||
{ store, referenceListingIds: { XNYS: [-5] } },
|
||||
{ store, referenceListingIds: { XNYS: [1.5] } },
|
||||
{ store, referenceListingIds: { XNYS: [2_147_483_648] } },
|
||||
{ store, referenceListingIds: { XNYS: [Number.NaN] } },
|
||||
{ store, referenceListingIds: { XNYS: [101, 202, 101] } },
|
||||
];
|
||||
|
||||
for (const input of invalidInputs) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createBarSessionDatesPort(input as never);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe('invalid_options');
|
||||
}
|
||||
});
|
||||
|
||||
test('defensively copies caller config and isolates per-call listingIds arrays', async () => {
|
||||
const xnysIds = [101, 102];
|
||||
const referenceListingIds: Record<string, number[]> = {
|
||||
XNYS: xnysIds,
|
||||
};
|
||||
|
||||
const observedIds: number[][] = [];
|
||||
const store: Pick<MarketDataStore, 'bars'> = {
|
||||
bars(q: BarsQueryArg): AsyncIterable<BarBatch> {
|
||||
observedIds.push([...q.listingIds]);
|
||||
// Mutate caller-passed query array to confirm port passes a fresh copy each time.
|
||||
q.listingIds.push(999);
|
||||
return yieldBatches([{ rows: [makeBar(101, '2024-11-25', 21)] }]);
|
||||
},
|
||||
};
|
||||
|
||||
const port = createBarSessionDatesPort({ store, referenceListingIds });
|
||||
|
||||
// Mutate caller config after construction.
|
||||
xnysIds.push(303);
|
||||
xnysIds[0] = 404;
|
||||
referenceListingIds.XNYS = [505];
|
||||
referenceListingIds.XTSE = [606];
|
||||
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-25',
|
||||
})
|
||||
).toEqual(['2024-11-25']);
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-25',
|
||||
})
|
||||
).toEqual(['2024-11-25']);
|
||||
|
||||
expect(observedIds).toEqual([
|
||||
[101, 102],
|
||||
[101, 102],
|
||||
]);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XTSE',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-25',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe('unknown_calendar');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — composition with createExchangeCalendarResolver', () => {
|
||||
test('resolves XNYS and XTSE session closes including summer EDT, Thanksgiving divergence, and early-close override', async () => {
|
||||
const xnysBars: readonly BarRecord[] = [
|
||||
// Summer EDT session (16:00 ET = 20:00Z)
|
||||
makeBar(1001, '2024-07-02', 20),
|
||||
// Winter EST sessions (US closed 2024-11-28 Thanksgiving; open 2024-11-29)
|
||||
makeBar(1001, '2024-11-27', 21),
|
||||
makeBar(1002, '2024-11-29', 21),
|
||||
];
|
||||
|
||||
const xtseBars: readonly BarRecord[] = [
|
||||
// Summer EDT session (16:00 ET = 20:00Z)
|
||||
makeBar(2001, '2024-07-02', 20),
|
||||
// Winter EST sessions (TSX open on US Thanksgiving 2024-11-28 and regular close on 2024-11-29)
|
||||
makeBar(2001, '2024-11-27', 21),
|
||||
makeBar(2001, '2024-11-28', 21),
|
||||
makeBar(2002, '2024-11-29', 21),
|
||||
];
|
||||
|
||||
const { store, calls } = makeRecordingStore((q) => {
|
||||
const requested = new Set(q.listingIds);
|
||||
const rows = [...xnysBars, ...xtseBars].filter((bar) => requested.has(bar.listingId));
|
||||
return yieldBatches([{ rows }]);
|
||||
});
|
||||
|
||||
const sessionDates = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [1001, 1002],
|
||||
XTSE: [2001, 2002],
|
||||
},
|
||||
});
|
||||
|
||||
const listingCalendars: ListingCalendarPort = {
|
||||
getListingCalendars(listingIds) {
|
||||
return listingIds.map((listingId) => ({
|
||||
listingId,
|
||||
calendarCode: listingId === 501 ? 'XNYS' : 'XTSE',
|
||||
}));
|
||||
},
|
||||
};
|
||||
|
||||
const resolveExchangeCalendars = createExchangeCalendarResolver({
|
||||
listingCalendars,
|
||||
sessionDates,
|
||||
earlyCloses: {
|
||||
XNYS: {
|
||||
'2024-11-29': 13 * 60, // 13:00 ET -> 18:00Z (EST)
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resolved = await resolveExchangeCalendars({
|
||||
listingIds: [501, 602],
|
||||
fromDate: '2024-07-02',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
|
||||
expect(resolved.listingCalendarId).toEqual({
|
||||
501: 'XNYS',
|
||||
602: 'XTSE',
|
||||
});
|
||||
|
||||
expect(resolved.calendars).toEqual({
|
||||
XNYS: [
|
||||
{ date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) },
|
||||
{ date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) },
|
||||
{ date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) },
|
||||
],
|
||||
XTSE: [
|
||||
{ date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) },
|
||||
{ date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) },
|
||||
{ date: '2024-11-28', closeTs: utcMs(2024, 11, 28, 21, 0, 0) },
|
||||
{ date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 21, 0, 0) },
|
||||
],
|
||||
});
|
||||
|
||||
// One store.bars call per distinct calendar code (XNYS, XTSE).
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]?.listingIds).toEqual([1001, 1002]);
|
||||
expect(calls[1]?.listingIds).toEqual([2001, 2002]);
|
||||
});
|
||||
});
|
||||
1139
libs/research/test/mcp-postgres-copilot.test.ts
Normal file
1139
libs/research/test/mcp-postgres-copilot.test.ts
Normal file
File diff suppressed because it is too large
Load diff
496
libs/research/test/mcp-stdio-host-qa.test.ts
Normal file
496
libs/research/test/mcp-stdio-host-qa.test.ts
Normal file
|
|
@ -0,0 +1,496 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import type { BarBatch, BarQuery, MarketDataStore, Table } from '../src/market-data-store';
|
||||
import {
|
||||
EVENTS_COLUMNS,
|
||||
MarketDataStoreNotImplementedError,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import {
|
||||
type PostgresResearchCopilotExecutor,
|
||||
type ResearchCopilotStdioHostDeps,
|
||||
ResearchCopilotHostConfigError,
|
||||
type StdioInput,
|
||||
type StdioOutput,
|
||||
parseResearchCopilotHostConfig,
|
||||
runResearchCopilotStdioHost,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
// QA fixtures: synthetic in-memory factories and stdio only. No Postgres,
|
||||
// DuckDB, filesystem, or network. Protocol/wiring checks; no strategy claims.
|
||||
const FAKE_DECODED_PASSWORD = 'qa+p@ss w0rd/=?';
|
||||
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD);
|
||||
const FAKE_POSTGRES_URL = `postgresql://qa_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`;
|
||||
const CUTOFF_ISO = '2025-06-01T00:00:00Z';
|
||||
const CUTOFF_MS = Date.UTC(2025, 5, 1);
|
||||
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12);
|
||||
|
||||
function buildEnv(
|
||||
overrides: Readonly<Record<string, string | undefined>> = {}
|
||||
): Record<string, string | undefined> {
|
||||
return {
|
||||
RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL,
|
||||
RESEARCH_MCP_CURATED_ROOT: '/qa/curated',
|
||||
RESEARCH_MCP_VAULT_CUTOFF_TS: CUTOFF_ISO,
|
||||
RESEARCH_MCP_PRINCIPAL_ID: 'operator',
|
||||
RESEARCH_MCP_LIBRARY_ROOT: '/qa/library',
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101, 102] }),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function memoryOutput(): { readonly output: StdioOutput; readonly chunks: string[] } {
|
||||
const chunks: string[] = [];
|
||||
return {
|
||||
chunks,
|
||||
output: {
|
||||
write(chunk: string): boolean {
|
||||
chunks.push(chunk);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function trackingInput(messages: readonly unknown[]): {
|
||||
readonly input: StdioInput;
|
||||
readonly pulled: () => number;
|
||||
} {
|
||||
let count = 0;
|
||||
return {
|
||||
pulled: () => count,
|
||||
input: {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const msg of messages) {
|
||||
count += 1;
|
||||
yield `${JSON.stringify(msg)}\n`;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function recordingStore(): { readonly store: MarketDataStore; readonly barQueries: BarQuery[] } {
|
||||
const barQueries: BarQuery[] = [];
|
||||
const emptyEvents: Table = { columns: [...EVENTS_COLUMNS], rows: [] };
|
||||
const store: MarketDataStore = {
|
||||
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
|
||||
barQueries.push(q);
|
||||
yield { listingId: q.listingIds[0] ?? 0, timeframe: q.timeframe, rows: [] };
|
||||
},
|
||||
async events() {
|
||||
return emptyEvents;
|
||||
},
|
||||
async universe() {
|
||||
return [];
|
||||
},
|
||||
async crossSection() {
|
||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||
},
|
||||
async fundamentalsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
||||
},
|
||||
async shortsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
||||
},
|
||||
async macroAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
||||
},
|
||||
async fx() {
|
||||
throw new MarketDataStoreNotImplementedError('fx');
|
||||
},
|
||||
};
|
||||
return { store, barQueries };
|
||||
}
|
||||
|
||||
function calendarExecutor(): {
|
||||
readonly executor: PostgresResearchCopilotExecutor;
|
||||
readonly sql: string[];
|
||||
} {
|
||||
const sql: string[] = [];
|
||||
const executor: PostgresResearchCopilotExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
sql.push(text);
|
||||
if (text.includes('calendar_code AS calendar_code')) {
|
||||
const ids = (params?.[0] as readonly number[] | undefined) ?? [];
|
||||
return {
|
||||
rows: ids.map(id => ({ listing_id: id, calendar_code: 'XNYS' }) as unknown as Row),
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
},
|
||||
};
|
||||
return { executor, sql };
|
||||
}
|
||||
|
||||
function baseDeps(
|
||||
overrides: Partial<ResearchCopilotStdioHostDeps> = {}
|
||||
): ResearchCopilotStdioHostDeps {
|
||||
return {
|
||||
config: parseResearchCopilotHostConfig(buildEnv()),
|
||||
openExecutor: () => ({ executor: calendarExecutor().executor, close: () => {} }),
|
||||
openStore: () => ({ store: recordingStore().store, close: () => {} }),
|
||||
createLibraryCardReader: () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'qa-id',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: trackingInput([]).input, output: memoryOutput().output },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function captureRejection(run: () => Promise<unknown>): Promise<unknown> {
|
||||
try {
|
||||
await run();
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
throw new Error('expected rejection');
|
||||
}
|
||||
|
||||
function expectNoSecret(error: unknown): void {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const err = error as Error & { cause?: unknown };
|
||||
for (const text of [err.message, err.stack ?? '']) {
|
||||
expect(text).not.toContain(FAKE_POSTGRES_URL);
|
||||
expect(text).not.toContain(FAKE_ENCODED_PASSWORD);
|
||||
expect(text).not.toContain(FAKE_DECODED_PASSWORD);
|
||||
}
|
||||
expect(err.cause).toBeUndefined();
|
||||
}
|
||||
|
||||
describe('runResearchCopilotStdioHost QA: session-date wiring', () => {
|
||||
test('event_study derives session dates from the configured reference listings on the opened store, clamped below the env cutoff', async () => {
|
||||
const { store, barQueries } = recordingStore();
|
||||
const { executor } = calendarExecutor();
|
||||
const sink = memoryOutput();
|
||||
const { input } = trackingInput([
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'event_study',
|
||||
arguments: {
|
||||
listingIds: [555],
|
||||
from: '2025-05-01',
|
||||
to: '2025-06-20',
|
||||
event: { kinds: ['filing'] },
|
||||
preDays: 2,
|
||||
postDays: 3,
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
benchmark: 'none',
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
await runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({ executor, close: () => {} }),
|
||||
openStore: () => ({ store, close: () => {} }),
|
||||
stdio: { input, output: sink.output },
|
||||
})
|
||||
);
|
||||
|
||||
expect(sink.chunks).toHaveLength(1);
|
||||
const studyQuery = barQueries.find(q => q.listingIds.includes(555));
|
||||
expect(studyQuery?.scope).toBe('vault_fenced');
|
||||
|
||||
const sessionQueries = barQueries.filter(q => !q.listingIds.includes(555));
|
||||
expect(sessionQueries).toHaveLength(1);
|
||||
const sessionQuery = sessionQueries[0]!;
|
||||
expect([...sessionQuery.listingIds]).toEqual([101, 102]);
|
||||
expect(sessionQuery.timeframe).toBe('1d');
|
||||
expect(sessionQuery.scope).not.toBe('vault_evaluation_only');
|
||||
expect(sessionQuery.to < '2025-06-01').toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runResearchCopilotStdioHost QA: lifecycle edge cases', () => {
|
||||
test('supports synchronous factories and synchronously throwing close(), closing in reverse order once each', async () => {
|
||||
const events: string[] = [];
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => {
|
||||
events.push('open:executor');
|
||||
return {
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
events.push('close:executor');
|
||||
},
|
||||
};
|
||||
},
|
||||
openStore: () => {
|
||||
events.push('open:store');
|
||||
return {
|
||||
store: recordingStore().store,
|
||||
close: () => {
|
||||
events.push('close:store');
|
||||
throw new Error('sync store close failure');
|
||||
},
|
||||
};
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect((err as Error).message).toBe('sync store close failure');
|
||||
expect(events).toEqual(['open:executor', 'open:store', 'close:store', 'close:executor']);
|
||||
});
|
||||
|
||||
test('synchronous throw from openStore is the rethrown original and the executor is still closed', async () => {
|
||||
const storeError = new Error('sync store open failure');
|
||||
let execCloses = 0;
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
execCloses += 1;
|
||||
},
|
||||
}),
|
||||
openStore: () => {
|
||||
throw storeError;
|
||||
},
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBe(storeError);
|
||||
expect(execCloses).toBe(1);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['null', null],
|
||||
['missing close()', { executor: {} }],
|
||||
] as const)('invalid executor handle (%s) fails closed with no store open and no stdio', async (_label, handle) => {
|
||||
let storeOpened = false;
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => handle as never,
|
||||
openStore: () => {
|
||||
storeOpened = true;
|
||||
return { store: recordingStore().store, close: () => {} };
|
||||
},
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(storeOpened).toBe(false);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
|
||||
test('invalid store handle closes the executor and serves nothing', async () => {
|
||||
let execCloses = 0;
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
execCloses += 1;
|
||||
},
|
||||
}),
|
||||
openStore: () => ({ store: recordingStore().store }) as never,
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(execCloses).toBe(1);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
|
||||
test('library reader without listLibraryCards closes store then executor and serves nothing', async () => {
|
||||
const closes: string[] = [];
|
||||
const sink = memoryOutput();
|
||||
const tracker = trackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
||||
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => ({
|
||||
executor: calendarExecutor().executor,
|
||||
close: () => {
|
||||
closes.push('executor');
|
||||
},
|
||||
}),
|
||||
openStore: () => ({
|
||||
store: recordingStore().store,
|
||||
close: () => {
|
||||
closes.push('store');
|
||||
},
|
||||
}),
|
||||
createLibraryCardReader: () => ({}) as never,
|
||||
stdio: { input: tracker.input, output: sink.output },
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(closes).toEqual(['store', 'executor']);
|
||||
expect(sink.chunks).toEqual([]);
|
||||
expect(tracker.pulled()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runResearchCopilotStdioHost QA: credential redaction', () => {
|
||||
test('replaces a safe-message error whose cause chain carries the DSN', async () => {
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openExecutor: () => {
|
||||
throw new Error('connect failed', {
|
||||
cause: new Error('inner', { cause: new Error(`dsn=${FAKE_POSTGRES_URL}`) }),
|
||||
});
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expectNoSecret(err);
|
||||
expect((err as Error).message).toContain('PostgreSQL executor');
|
||||
});
|
||||
|
||||
test('replaces an error carrying only the URL-encoded password', async () => {
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
createLibraryCardReader: () => {
|
||||
throw new Error(`bad token ${FAKE_ENCODED_PASSWORD}`);
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expectNoSecret(err);
|
||||
expect((err as Error).message).toContain('library card reader');
|
||||
});
|
||||
|
||||
test('replaces an error whose message getter throws (uninspectable)', async () => {
|
||||
const hostile = new Error('placeholder');
|
||||
Object.defineProperty(hostile, 'message', {
|
||||
get() {
|
||||
throw new Error(FAKE_DECODED_PASSWORD);
|
||||
},
|
||||
});
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
openStore: () => {
|
||||
throw hostile;
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(err).not.toBe(hostile);
|
||||
expectNoSecret(err);
|
||||
expect((err as Error).message).toContain('market data store');
|
||||
});
|
||||
|
||||
test('redacts a query-parameter password containing "+" in both decoded forms', async () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_POSTGRES_URL: 'postgresql://qa_ro@127.0.0.1:5433/db?password=a+b%2Bc',
|
||||
})
|
||||
);
|
||||
for (const leaked of ['a b+c', 'a+b+c', 'a+b%2Bc']) {
|
||||
const err = await captureRejection(() =>
|
||||
runResearchCopilotStdioHost(
|
||||
baseDeps({
|
||||
config,
|
||||
openExecutor: () => {
|
||||
throw new Error(`auth failed: ${leaked}`);
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
expect((err as Error).message).not.toContain(leaked);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseResearchCopilotHostConfig QA: edge cases', () => {
|
||||
test('keeps a "__proto__" calendar code as an own data property without prototype pollution', () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"__proto__":[7],"XNYS":[101]}',
|
||||
})
|
||||
);
|
||||
|
||||
expect(Object.keys(config.referenceListingIds).sort()).toEqual(['XNYS', '__proto__']);
|
||||
expect(Object.getOwnPropertyDescriptor(config.referenceListingIds, '__proto__')?.value).toEqual([7]);
|
||||
expect(Object.getPrototypeOf(config.referenceListingIds)).toBe(Object.prototype);
|
||||
});
|
||||
|
||||
test('ignores undefined prefixed keys and differently cased look-alike keys', () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_NOT_SET: undefined,
|
||||
research_mcp_extra: 'x',
|
||||
Research_Mcp_Extra: 'y',
|
||||
})
|
||||
);
|
||||
expect(config.principalId).toBe('operator');
|
||||
});
|
||||
|
||||
test('accepts boundary early-close values (minute 1/960, dates 1976-01-01 and 2030-12-31)', () => {
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildEnv({
|
||||
RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({
|
||||
XNYS: { '1976-01-01': 1, '2030-12-31': 960 },
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(config.earlyCloses).toEqual({ XNYS: { '1976-01-01': 1, '2030-12-31': 960 } });
|
||||
});
|
||||
|
||||
test('accepts INT32 max listing id and rejects a two-digit-year cutoff that Date.UTC would remap', () => {
|
||||
expect(
|
||||
parseResearchCopilotHostConfig(
|
||||
buildEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: '{"XNYS":[2147483647]}' })
|
||||
).referenceListingIds
|
||||
).toEqual({ XNYS: [2147483647] });
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
parseResearchCopilotHostConfig(
|
||||
buildEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: '0050-01-01T00:00:00Z' })
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
// Must never silently become 1950-01-01 (a different, earlier cutoff).
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
||||
expect((caught as ResearchCopilotHostConfigError).variable).toBe(
|
||||
'RESEARCH_MCP_VAULT_CUTOFF_TS'
|
||||
);
|
||||
});
|
||||
|
||||
test('parses the cutoff once and repeated parses of the same env are deterministic', () => {
|
||||
const a = parseResearchCopilotHostConfig(buildEnv());
|
||||
const b = parseResearchCopilotHostConfig(buildEnv());
|
||||
expect(a).toEqual(b);
|
||||
expect(a.vaultCutoffTs).toBe(CUTOFF_MS);
|
||||
});
|
||||
});
|
||||
1206
libs/research/test/mcp-stdio-host.test.ts
Normal file
1206
libs/research/test/mcp-stdio-host.test.ts
Normal file
File diff suppressed because it is too large
Load diff
615
libs/research/test/notebook-snapshot-qa.test.ts
Normal file
615
libs/research/test/notebook-snapshot-qa.test.ts
Normal file
|
|
@ -0,0 +1,615 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
exportNotebookSnapshot,
|
||||
NotebookSnapshotError,
|
||||
type ExportNotebookSnapshotOptions,
|
||||
type NotebookCommandResult,
|
||||
type NotebookCommandRunner,
|
||||
type NotebookSnapshotFileStat,
|
||||
type NotebookSnapshotFs,
|
||||
} from '../src/notebook-snapshot';
|
||||
|
||||
// QA coverage for T-177 beyond the programmer's unit tests: fail-at-call-N fault
|
||||
// injection across every port call, realistic marimo 0.26.0 report payloads
|
||||
// (shapes taken from marimo/_lint/formatters/json.py, _lint/linter.py and
|
||||
// _cli/cli.py `check`, which echoes JSON with a trailing newline), temp-name
|
||||
// collisions, path normalization, and option validation. Fakes only; no real
|
||||
// marimo process is ever spawned.
|
||||
|
||||
const NOTEBOOK = '/work/notebooks/study.py';
|
||||
const OUTPUT = '/work/out/study.html';
|
||||
const ORIGINAL_SNAPSHOT = '<html>original-snapshot</html>';
|
||||
const NEW_SNAPSHOT = '<html>new-snapshot — €</html>';
|
||||
const TEMP_MARKER = '.marimo-snapshot-';
|
||||
|
||||
type PortOp =
|
||||
| 'fs.stat'
|
||||
| 'fs.createExclusive'
|
||||
| 'fs.readBytes'
|
||||
| 'fs.rename'
|
||||
| 'fs.remove'
|
||||
| 'runner.check'
|
||||
| 'runner.export';
|
||||
|
||||
function errWithCode(code: string, message = code): Error & { code: string } {
|
||||
const err = new Error(message) as Error & { code: string };
|
||||
err.code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory fs + runner pair sharing one ordered port-call log. `failAt` makes
|
||||
* the Nth port call throw EIO; `failPersistently` makes every later call throw too.
|
||||
*/
|
||||
class FaultyPorts {
|
||||
readonly files = new Map<string, { isFile: boolean; bytes: Uint8Array }>();
|
||||
readonly ops: PortOp[] = [];
|
||||
readonly runnerArgs: string[][] = [];
|
||||
failAt = 0;
|
||||
failPersistently = false;
|
||||
checkStdout = '';
|
||||
exportBytes: Uint8Array = new TextEncoder().encode(NEW_SNAPSHOT);
|
||||
createExclusiveHook: ((path: string, attempt: number) => void) | null = null;
|
||||
private createAttempts = 0;
|
||||
|
||||
constructor() {
|
||||
this.files.set(NOTEBOOK, { isFile: true, bytes: new TextEncoder().encode('import marimo\n') });
|
||||
this.files.set(OUTPUT, { isFile: true, bytes: new TextEncoder().encode(ORIGINAL_SNAPSHOT) });
|
||||
}
|
||||
|
||||
private tick(op: PortOp): void {
|
||||
this.ops.push(op);
|
||||
const n = this.ops.length;
|
||||
if (this.failAt > 0 && (n === this.failAt || (this.failPersistently && n > this.failAt))) {
|
||||
throw errWithCode('EIO', `injected EIO at port call ${n} (${op})`);
|
||||
}
|
||||
}
|
||||
|
||||
text(path: string): string | undefined {
|
||||
const entry = this.files.get(path);
|
||||
return entry ? new TextDecoder().decode(entry.bytes) : undefined;
|
||||
}
|
||||
|
||||
tempPaths(): string[] {
|
||||
return [...this.files.keys()].filter(p => p.includes(TEMP_MARKER));
|
||||
}
|
||||
|
||||
readonly fs: NotebookSnapshotFs = {
|
||||
stat: async (path): Promise<NotebookSnapshotFileStat | null> => {
|
||||
this.tick('fs.stat');
|
||||
const entry = this.files.get(path);
|
||||
return entry ? { isFile: entry.isFile, size: entry.bytes.byteLength } : null;
|
||||
},
|
||||
createExclusive: async path => {
|
||||
this.tick('fs.createExclusive');
|
||||
this.createAttempts += 1;
|
||||
this.createExclusiveHook?.(path, this.createAttempts);
|
||||
if (this.files.has(path)) {
|
||||
throw errWithCode('EEXIST');
|
||||
}
|
||||
this.files.set(path, { isFile: true, bytes: new Uint8Array(0) });
|
||||
},
|
||||
readBytes: async path => {
|
||||
this.tick('fs.readBytes');
|
||||
const entry = this.files.get(path);
|
||||
if (!entry) {
|
||||
throw errWithCode('ENOENT');
|
||||
}
|
||||
return new Uint8Array(entry.bytes);
|
||||
},
|
||||
rename: async (from, to) => {
|
||||
this.tick('fs.rename');
|
||||
const entry = this.files.get(from);
|
||||
if (!entry) {
|
||||
throw errWithCode('ENOENT');
|
||||
}
|
||||
this.files.delete(from);
|
||||
this.files.set(to, entry);
|
||||
},
|
||||
remove: async path => {
|
||||
this.tick('fs.remove');
|
||||
this.files.delete(path);
|
||||
},
|
||||
};
|
||||
|
||||
readonly runner: NotebookCommandRunner = {
|
||||
run: async (_command, args): Promise<NotebookCommandResult> => {
|
||||
this.runnerArgs.push([...args]);
|
||||
if (args[0] === 'check') {
|
||||
this.tick('runner.check');
|
||||
return { exitCode: 0, stdout: this.checkStdout, stderr: '' };
|
||||
}
|
||||
this.tick('runner.export');
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
this.files.set(tempPath, { isFile: true, bytes: this.exportBytes });
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
},
|
||||
};
|
||||
|
||||
options(extra: Partial<ExportNotebookSnapshotOptions> = {}): ExportNotebookSnapshotOptions {
|
||||
return { notebookPath: NOTEBOOK, outputPath: OUTPUT, runner: this.runner, fs: this.fs, ...extra };
|
||||
}
|
||||
}
|
||||
|
||||
async function captureSnapshotError(promise: Promise<unknown>): Promise<NotebookSnapshotError> {
|
||||
try {
|
||||
await promise;
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(NotebookSnapshotError);
|
||||
return err as NotebookSnapshotError;
|
||||
}
|
||||
throw new Error('Expected NotebookSnapshotError, but the export resolved.');
|
||||
}
|
||||
|
||||
function stubRunner(result: unknown): { runner: NotebookCommandRunner; calls: string[][] } {
|
||||
const calls: string[][] = [];
|
||||
return {
|
||||
calls,
|
||||
runner: {
|
||||
run: async (_c, args) => {
|
||||
calls.push([...args]);
|
||||
return result as NotebookCommandResult;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Realistic marimo 0.26.0 `check --format=json` stdout (click.echo appends '\n').
|
||||
function marimoCheckStdout(
|
||||
issues: readonly Record<string, unknown>[],
|
||||
errored: boolean,
|
||||
totalFiles = 1
|
||||
): string {
|
||||
return `${JSON.stringify({
|
||||
issues,
|
||||
summary: {
|
||||
total_files: totalFiles,
|
||||
files_with_issues: issues.length > 0 ? 1 : 0,
|
||||
total_issues: issues.length,
|
||||
fixed_issues: 0,
|
||||
errored,
|
||||
},
|
||||
})}\n`;
|
||||
}
|
||||
|
||||
describe('exportNotebookSnapshot QA: fail-at-call-N fault injection', () => {
|
||||
const expectedByStep: ReadonlyArray<{ op: PortOp; code: NotebookSnapshotError['code'] }> = [
|
||||
{ op: 'fs.stat', code: 'NOTEBOOK_NOT_FOUND' },
|
||||
{ op: 'runner.check', code: 'CHECK_FAILED' },
|
||||
{ op: 'fs.createExclusive', code: 'EXPORT_FAILED' },
|
||||
{ op: 'runner.export', code: 'EXPORT_FAILED' },
|
||||
{ op: 'fs.stat', code: 'EXPORT_FAILED' },
|
||||
{ op: 'fs.readBytes', code: 'EXPORT_FAILED' },
|
||||
{ op: 'fs.rename', code: 'EXPORT_FAILED' },
|
||||
];
|
||||
|
||||
test('happy path issues exactly the expected ordered port calls', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
await exportNotebookSnapshot(ports.options());
|
||||
expect(ports.ops).toEqual(expectedByStep.map(s => s.op));
|
||||
});
|
||||
|
||||
for (const persistent of [false, true]) {
|
||||
test(`failing port call N (${persistent ? 'and every later call' : 'only'}) fails closed with the mapped code, keeps the old snapshot, and a retry succeeds`, async () => {
|
||||
for (let n = 1; n <= expectedByStep.length; n += 1) {
|
||||
const ports = new FaultyPorts();
|
||||
ports.failAt = n;
|
||||
ports.failPersistently = persistent;
|
||||
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
const step = expectedByStep[n - 1]!;
|
||||
|
||||
expect({ n, op: ports.ops[n - 1], code: err.code }).toEqual({ n, op: step.op, code: step.code });
|
||||
expect(err.cause).toBeDefined();
|
||||
expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT);
|
||||
// Export must never run once the check phase (or anything before it) failed.
|
||||
if (n <= 2) {
|
||||
expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0);
|
||||
expect(ports.ops).not.toContain('fs.createExclusive');
|
||||
}
|
||||
if (!persistent) {
|
||||
// Cleanup succeeded: no owned temp file survives any injected fault.
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
if (n >= 4) {
|
||||
expect(ports.ops.at(-1)).toBe('fs.remove');
|
||||
}
|
||||
}
|
||||
|
||||
// Retry once the fault clears publishes the new snapshot.
|
||||
ports.failAt = 0;
|
||||
const receipt = await exportNotebookSnapshot(ports.options());
|
||||
expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT);
|
||||
expect(receipt.bytes).toBe(ports.exportBytes.byteLength);
|
||||
if (!persistent) {
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('an extra fault index past the last port call means the export succeeds (no hidden fault points)', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.failAt = expectedByStep.length + 1;
|
||||
const receipt = await exportNotebookSnapshot(ports.options());
|
||||
expect(receipt.sha256).toBe(createHash('sha256').update(ports.exportBytes).digest('hex'));
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportNotebookSnapshot QA: realistic marimo 0.26.0 check reports', () => {
|
||||
test('accepts the real report shape with trailing newline and formatting/runtime diagnostics', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const issues = [
|
||||
{
|
||||
type: 'diagnostic',
|
||||
message: 'Cell is not formatted',
|
||||
filename: NOTEBOOK,
|
||||
line: 3,
|
||||
column: 1,
|
||||
severity: 'formatting',
|
||||
name: 'general-formatting',
|
||||
code: 'MF001',
|
||||
fixable: true,
|
||||
cell_id: ['Hbol'],
|
||||
},
|
||||
{
|
||||
type: 'diagnostic',
|
||||
message: 'Self import',
|
||||
filename: NOTEBOOK,
|
||||
line: 7,
|
||||
column: 1,
|
||||
severity: 'runtime',
|
||||
name: 'self-import',
|
||||
code: 'MR001',
|
||||
fixable: false,
|
||||
},
|
||||
];
|
||||
ports.checkStdout = marimoCheckStdout(issues, false);
|
||||
|
||||
const receipt = await exportNotebookSnapshot(ports.options());
|
||||
|
||||
expect(receipt.checkDiagnostics).toEqual(JSON.parse(ports.checkStdout));
|
||||
expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('blocks export for a file-level error issue even when exit is 0 and summary.errored is false', async () => {
|
||||
// marimo marks `status == "invalid"` notebooks failed without necessarily
|
||||
// setting errored first; the gate must not rely on summary.errored alone.
|
||||
const ports = new FaultyPorts();
|
||||
ports.checkStdout = marimoCheckStdout(
|
||||
[{ type: 'error', filename: NOTEBOOK, error: `Failed to parse: ${NOTEBOOK} (not a valid notebook)` }],
|
||||
false
|
||||
);
|
||||
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
|
||||
expect(err.code).toBe('CHECK_FAILED');
|
||||
expect(ports.runnerArgs).toHaveLength(1);
|
||||
expect(ports.ops).not.toContain('fs.createExclusive');
|
||||
expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('blocks export for a breaking diagnostic (MB rule) on exit 0', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.checkStdout = marimoCheckStdout(
|
||||
[
|
||||
{
|
||||
type: 'diagnostic',
|
||||
message: "Variable 'x' is defined in multiple cells",
|
||||
filename: NOTEBOOK,
|
||||
line: 4,
|
||||
column: 1,
|
||||
severity: 'breaking',
|
||||
name: 'multiple-definitions',
|
||||
code: 'MB002',
|
||||
fixable: false,
|
||||
},
|
||||
],
|
||||
false
|
||||
);
|
||||
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
expect(err.code).toBe('CHECK_FAILED');
|
||||
expect(ports.runnerArgs).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('rejects a report that checked zero files (e.g. notebook vanished before check) as CHECK_OUTPUT_INVALID', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.checkStdout = marimoCheckStdout([], false, 0);
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
expect(err.code).toBe('CHECK_OUTPUT_INVALID');
|
||||
expect(ports.runnerArgs).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('blocks a nested diagnostics entry with type "error"', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.checkStdout = marimoCheckStdout(
|
||||
[{ filename: NOTEBOOK, diagnostics: [{ type: 'error', message: 'boom' }] }],
|
||||
false
|
||||
);
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
expect(err.code).toBe('CHECK_FAILED');
|
||||
expect(ports.runnerArgs).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('rejects non-string severity in an issue as CHECK_OUTPUT_INVALID', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.checkStdout = marimoCheckStdout([{ type: 'diagnostic', severity: 3 }], false);
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
expect(err.code).toBe('CHECK_OUTPUT_INVALID');
|
||||
expect(ports.runnerArgs).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('receipt diagnostics are deeply frozen and detached from later mutation attempts', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.checkStdout = marimoCheckStdout(
|
||||
[{ type: 'diagnostic', severity: 'formatting', code: 'MF001', cell_id: ['a'] }],
|
||||
false
|
||||
);
|
||||
const receipt = await exportNotebookSnapshot(ports.options());
|
||||
const diagnostics = receipt.checkDiagnostics!;
|
||||
|
||||
expect(() => {
|
||||
(diagnostics.summary as { errored: boolean }).errored = true;
|
||||
}).toThrow(TypeError);
|
||||
expect(() => {
|
||||
(diagnostics.issues as unknown[]).push({});
|
||||
}).toThrow(TypeError);
|
||||
expect(() => {
|
||||
(receipt as { sha256: string }).sha256 = 'x';
|
||||
}).toThrow(TypeError);
|
||||
expect(diagnostics.summary.errored).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportNotebookSnapshot QA: runner contract violations', () => {
|
||||
test('non-timeout runner rejection in check maps to CHECK_FAILED with cause and never exports', async () => {
|
||||
const spawnError = errWithCode('ENOENT', 'spawn marimo ENOENT');
|
||||
const calls: string[][] = [];
|
||||
const ports = new FaultyPorts();
|
||||
const runner: NotebookCommandRunner = {
|
||||
run: async (_c, args) => {
|
||||
calls.push([...args]);
|
||||
throw spawnError;
|
||||
},
|
||||
};
|
||||
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner })));
|
||||
|
||||
expect(err.code).toBe('CHECK_FAILED');
|
||||
expect(err.cause).toBe(spawnError);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
});
|
||||
|
||||
test('malformed runner results in check map to CHECK_FAILED and never export', async () => {
|
||||
const malformed: unknown[] = [
|
||||
null,
|
||||
'exit 0',
|
||||
{ exitCode: '0', stdout: '', stderr: '' },
|
||||
{ exitCode: Number.NaN, stdout: '', stderr: '' },
|
||||
{ exitCode: 0.5, stdout: '', stderr: '' },
|
||||
{ exitCode: 0, stderr: '' },
|
||||
{ exitCode: 0, stdout: '', stderr: null },
|
||||
];
|
||||
for (const result of malformed) {
|
||||
const ports = new FaultyPorts();
|
||||
const { runner, calls } = stubRunner(result);
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner })));
|
||||
expect(err.code).toBe('CHECK_FAILED');
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed runner result in export maps to EXPORT_FAILED, removes temp, and keeps destination', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const runner: NotebookCommandRunner = {
|
||||
run: async (_c, args) =>
|
||||
(args[0] === 'check'
|
||||
? { exitCode: 0, stdout: '', stderr: '' }
|
||||
: { exitCode: 0, stdout: undefined, stderr: '' }) as unknown as NotebookCommandResult,
|
||||
};
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner })));
|
||||
expect(err.code).toBe('EXPORT_FAILED');
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('readBytes returning zero bytes despite a nonzero stat size is EXPORT_EMPTY and cleans up', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const fs: NotebookSnapshotFs = { ...ports.fs, readBytes: async () => new Uint8Array(0) };
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs })));
|
||||
expect(err.code).toBe('EXPORT_EMPTY');
|
||||
expect(ports.tempPaths()).toEqual([]);
|
||||
expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('temp file vanishing between stat and read (ENOENT) is EXPORT_EMPTY', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const fs: NotebookSnapshotFs = {
|
||||
...ports.fs,
|
||||
readBytes: async () => {
|
||||
throw errWithCode('ENOENT');
|
||||
},
|
||||
};
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs })));
|
||||
expect(err.code).toBe('EXPORT_EMPTY');
|
||||
expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('notebook stat throwing ENOENT is NOTEBOOK_NOT_FOUND with zero runner calls', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const fs: NotebookSnapshotFs = {
|
||||
...ports.fs,
|
||||
stat: async () => {
|
||||
throw errWithCode('ENOENT');
|
||||
},
|
||||
};
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs })));
|
||||
expect(err.code).toBe('NOTEBOOK_NOT_FOUND');
|
||||
expect(ports.runnerArgs).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportNotebookSnapshot QA: temp reservation', () => {
|
||||
test('retries on EEXIST collisions and exports to the first free sibling', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.createExclusiveHook = (path, attempt) => {
|
||||
if (attempt <= 3) {
|
||||
ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') });
|
||||
}
|
||||
};
|
||||
|
||||
await exportNotebookSnapshot(ports.options());
|
||||
|
||||
const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!;
|
||||
const usedTemp = exportArgs[exportArgs.indexOf('-o') + 1]!;
|
||||
expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(4);
|
||||
expect(usedTemp.startsWith('/work/out/')).toBe(true);
|
||||
// The three foreign colliding files are not owned and must be left alone.
|
||||
expect(ports.tempPaths()).toHaveLength(3);
|
||||
expect(ports.tempPaths()).not.toContain(usedTemp);
|
||||
expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('gives up with EXPORT_FAILED after bounded EEXIST collisions, never exports, and never removes foreign files', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.createExclusiveHook = path => {
|
||||
ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') });
|
||||
};
|
||||
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options()));
|
||||
|
||||
expect(err.code).toBe('EXPORT_FAILED');
|
||||
expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(16);
|
||||
expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0);
|
||||
expect(ports.ops).not.toContain('fs.remove');
|
||||
expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('a destination directly under / reserves its temp under / without a double slash', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.files.set('/nb.py', { isFile: true, bytes: new TextEncoder().encode('x') });
|
||||
await exportNotebookSnapshot(ports.options({ notebookPath: '/nb.py', outputPath: '/snap.html' }));
|
||||
const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!;
|
||||
const temp = exportArgs[exportArgs.indexOf('-o') + 1]!;
|
||||
expect(temp).toMatch(/^\/\.marimo-snapshot-[^/]+\.tmp\.html$/);
|
||||
expect(ports.text('/snap.html')).toBe(NEW_SNAPSHOT);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportNotebookSnapshot QA: path normalization and roots', () => {
|
||||
test('passes and reports normalized paths (dot segments, duplicate slashes) to runner, fs, and receipt', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const receipt = await exportNotebookSnapshot(
|
||||
ports.options({
|
||||
notebookPath: '/work//notebooks/./sub/../study.py',
|
||||
outputPath: '/work/out/./x/../study.html',
|
||||
allowedNotebookRoot: '/work/notebooks/',
|
||||
allowedOutputRoot: '/work/out',
|
||||
})
|
||||
);
|
||||
expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', NOTEBOOK]);
|
||||
expect(ports.runnerArgs[1]?.[2]).toBe(NOTEBOOK);
|
||||
expect(receipt.notebookPath).toBe(NOTEBOOK);
|
||||
expect(receipt.outputPath).toBe(OUTPUT);
|
||||
expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT);
|
||||
});
|
||||
|
||||
test('a basename starting with "-" inside an absolute path is passed as one argv element', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
ports.files.set('/work/notebooks/-rf.py', { isFile: true, bytes: new TextEncoder().encode('x') });
|
||||
await exportNotebookSnapshot(ports.options({ notebookPath: '/work/notebooks/-rf.py' }));
|
||||
expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', '/work/notebooks/-rf.py']);
|
||||
});
|
||||
|
||||
test('root "/" accepts any absolute path; relative or NUL roots and relative cwd are rejected before any port call', async () => {
|
||||
const ok = new FaultyPorts();
|
||||
await exportNotebookSnapshot(ok.options({ allowedNotebookRoot: '/', allowedOutputRoot: '/' }));
|
||||
expect(ok.text(OUTPUT)).toBe(NEW_SNAPSHOT);
|
||||
|
||||
const badExtras: Array<Partial<ExportNotebookSnapshotOptions>> = [
|
||||
{ allowedNotebookRoot: 'work/notebooks' },
|
||||
{ allowedOutputRoot: './out' },
|
||||
{ allowedOutputRoot: '/work/out\0' },
|
||||
{ allowedNotebookRoot: '' },
|
||||
{ cwd: 'work' },
|
||||
// Path equal to the root itself is not "inside" it.
|
||||
{ allowedNotebookRoot: NOTEBOOK },
|
||||
// `..` that climbs above the root after normalization.
|
||||
{ notebookPath: '/work/notebooks/../../work/notebooks/../x.py', allowedNotebookRoot: '/work/notebooks' },
|
||||
];
|
||||
for (const extra of badExtras) {
|
||||
const ports = new FaultyPorts();
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra)));
|
||||
expect(err.code).toBe('INVALID_PATH');
|
||||
expect(ports.ops).toEqual([]);
|
||||
expect(ports.runnerArgs).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test('".." above filesystem root clamps to "/" and is still contained by roots', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const err = await captureSnapshotError(
|
||||
exportNotebookSnapshot(
|
||||
ports.options({ notebookPath: '/../../etc/x.py', allowedNotebookRoot: '/work/notebooks' })
|
||||
)
|
||||
);
|
||||
expect(err.code).toBe('INVALID_PATH');
|
||||
expect(ports.runnerArgs).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportNotebookSnapshot QA: option validation', () => {
|
||||
test('rejects malformed ports and options with INVALID_OPTION before any port call', async () => {
|
||||
const ports = new FaultyPorts();
|
||||
const bad: Array<Partial<ExportNotebookSnapshotOptions> | null> = [
|
||||
null,
|
||||
{ runner: undefined as unknown as NotebookCommandRunner },
|
||||
{ runner: {} as NotebookCommandRunner },
|
||||
{ fs: { ...ports.fs, rename: undefined } as unknown as NotebookSnapshotFs },
|
||||
{ fs: { ...ports.fs, createExclusive: 'x' } as unknown as NotebookSnapshotFs },
|
||||
{ timeoutMs: -1 },
|
||||
{ timeoutMs: 1.5 },
|
||||
{ timeoutMs: Number.NaN },
|
||||
{ timeoutMs: Number.POSITIVE_INFINITY },
|
||||
{ timeoutMs: '1000' as unknown as number },
|
||||
{ marimoCommand: '' },
|
||||
{ marimoCommand: ' ' },
|
||||
{ marimoCommand: 'mar\0imo' },
|
||||
{ marimoCommand: 42 as unknown as string },
|
||||
];
|
||||
for (const extra of bad) {
|
||||
const options =
|
||||
extra === null ? (null as unknown as ExportNotebookSnapshotOptions) : ports.options(extra);
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(options));
|
||||
expect(err.code).toBe('INVALID_OPTION');
|
||||
}
|
||||
expect(ports.ops).toEqual([]);
|
||||
expect(ports.runnerArgs).toEqual([]);
|
||||
});
|
||||
|
||||
test('non-string notebookPath/outputPath are INVALID_PATH', async () => {
|
||||
for (const extra of [
|
||||
{ notebookPath: undefined as unknown as string },
|
||||
{ outputPath: 7 as unknown as string },
|
||||
{ notebookPath: '' },
|
||||
]) {
|
||||
const ports = new FaultyPorts();
|
||||
const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra)));
|
||||
expect(err.code).toBe('INVALID_PATH');
|
||||
expect(ports.ops).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test('NotebookSnapshotError is a real Error subclass with stable name and code', () => {
|
||||
const err = new NotebookSnapshotError('TIMEOUT', 'm', { details: { a: 1 } });
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.name).toBe('NotebookSnapshotError');
|
||||
expect(err.code).toBe('TIMEOUT');
|
||||
expect(err.details).toEqual({ a: 1 });
|
||||
expect('cause' in err && err.cause !== undefined).toBe(false);
|
||||
});
|
||||
});
|
||||
851
libs/research/test/notebook-snapshot.test.ts
Normal file
851
libs/research/test/notebook-snapshot.test.ts
Normal file
|
|
@ -0,0 +1,851 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { exportNotebookSnapshot as barrelExportNotebookSnapshot } from '../src/index';
|
||||
import {
|
||||
DEFAULT_MARIMO_COMMAND,
|
||||
DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS,
|
||||
exportNotebookSnapshot,
|
||||
NotebookSnapshotError,
|
||||
type NotebookCommandResult,
|
||||
type NotebookCommandRunner,
|
||||
type NotebookCommandRunOptions,
|
||||
type NotebookSnapshotFileStat,
|
||||
type NotebookSnapshotFs,
|
||||
} from '../src/notebook-snapshot';
|
||||
|
||||
interface RecordedCall {
|
||||
readonly command: string;
|
||||
readonly args: readonly string[];
|
||||
readonly options: NotebookCommandRunOptions;
|
||||
}
|
||||
|
||||
interface FakeFsEntry {
|
||||
readonly isFile: boolean;
|
||||
bytes: Uint8Array;
|
||||
}
|
||||
|
||||
class InMemoryNotebookFs implements NotebookSnapshotFs {
|
||||
readonly entries = new Map<string, FakeFsEntry>();
|
||||
readonly createdTempPaths: string[] = [];
|
||||
readonly removedPaths: string[] = [];
|
||||
readonly renames: Array<{ readonly from: string; readonly to: string }> = [];
|
||||
failRenameError: Error | null = null;
|
||||
failRemoveError: Error | null = null;
|
||||
|
||||
putFile(path: string, content: string | Uint8Array): void {
|
||||
const bytes =
|
||||
typeof content === 'string' ? new TextEncoder().encode(content) : new Uint8Array(content);
|
||||
this.entries.set(path, { isFile: true, bytes });
|
||||
}
|
||||
|
||||
putDirectory(path: string): void {
|
||||
this.entries.set(path, { isFile: false, bytes: new Uint8Array(0) });
|
||||
}
|
||||
|
||||
getBytes(path: string): Uint8Array | undefined {
|
||||
const entry = this.entries.get(path);
|
||||
return entry?.isFile ? entry.bytes : undefined;
|
||||
}
|
||||
|
||||
getText(path: string): string | undefined {
|
||||
const bytes = this.getBytes(path);
|
||||
return bytes ? new TextDecoder().decode(bytes) : undefined;
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<NotebookSnapshotFileStat | null> {
|
||||
const entry = this.entries.get(path);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
return { isFile: entry.isFile, size: entry.bytes.byteLength };
|
||||
}
|
||||
|
||||
async createExclusive(path: string): Promise<void> {
|
||||
if (this.entries.has(path)) {
|
||||
const err = new Error(`EEXIST: file already exists '${path}'`) as Error & { code: string };
|
||||
err.code = 'EEXIST';
|
||||
throw err;
|
||||
}
|
||||
this.entries.set(path, { isFile: true, bytes: new Uint8Array(0) });
|
||||
this.createdTempPaths.push(path);
|
||||
}
|
||||
|
||||
async readBytes(path: string): Promise<Uint8Array> {
|
||||
const entry = this.entries.get(path);
|
||||
if (!entry || !entry.isFile) {
|
||||
const err = new Error(`ENOENT: no such file '${path}'`) as Error & { code: string };
|
||||
err.code = 'ENOENT';
|
||||
throw err;
|
||||
}
|
||||
return new Uint8Array(entry.bytes);
|
||||
}
|
||||
|
||||
async rename(sourcePath: string, destinationPath: string): Promise<void> {
|
||||
if (this.failRenameError) {
|
||||
throw this.failRenameError;
|
||||
}
|
||||
const entry = this.entries.get(sourcePath);
|
||||
if (!entry) {
|
||||
const err = new Error(`ENOENT: no such file '${sourcePath}'`) as Error & { code: string };
|
||||
err.code = 'ENOENT';
|
||||
throw err;
|
||||
}
|
||||
this.entries.delete(sourcePath);
|
||||
this.entries.set(destinationPath, entry);
|
||||
this.renames.push({ from: sourcePath, to: destinationPath });
|
||||
}
|
||||
|
||||
async remove(path: string): Promise<void> {
|
||||
this.removedPaths.push(path);
|
||||
if (this.failRemoveError) {
|
||||
throw this.failRemoveError;
|
||||
}
|
||||
this.entries.delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
type RunnerHandler = (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: NotebookCommandRunOptions,
|
||||
callIndex: number
|
||||
) => Promise<NotebookCommandResult>;
|
||||
|
||||
function createRecordingRunner(handler: RunnerHandler): {
|
||||
readonly runner: NotebookCommandRunner;
|
||||
readonly calls: RecordedCall[];
|
||||
} {
|
||||
const calls: RecordedCall[] = [];
|
||||
const runner: NotebookCommandRunner = {
|
||||
async run(command, args, options) {
|
||||
const callIndex = calls.length;
|
||||
calls.push({ command, args: [...args], options: { ...options } });
|
||||
return handler(command, args, options, callIndex);
|
||||
},
|
||||
};
|
||||
return { runner, calls };
|
||||
}
|
||||
|
||||
function makeTimeoutError(message = 'Command timed out'): Error & { code: string } {
|
||||
const err = new Error(message) as Error & { code: string };
|
||||
err.code = 'ETIMEDOUT';
|
||||
return err;
|
||||
}
|
||||
|
||||
async function expectSnapshotError(
|
||||
promise: Promise<unknown>,
|
||||
expectedCode: NotebookSnapshotError['code']
|
||||
): Promise<NotebookSnapshotError> {
|
||||
try {
|
||||
await promise;
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(NotebookSnapshotError);
|
||||
const snapshotErr = err as NotebookSnapshotError;
|
||||
expect(snapshotErr.code).toBe(expectedCode);
|
||||
return snapshotErr;
|
||||
}
|
||||
throw new Error(`Expected NotebookSnapshotError(${expectedCode}), but promise resolved.`);
|
||||
}
|
||||
|
||||
describe('exportNotebookSnapshot', () => {
|
||||
test('is re-exported from the @stock-bot/research barrel', () => {
|
||||
expect(barrelExportNotebookSnapshot).toBe(exportNotebookSnapshot);
|
||||
});
|
||||
|
||||
test('happy path: runs check then export html with exact argv, publishes via sibling temp rename, and returns frozen receipt with exact non-ASCII bytes and sha256', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
const notebookPath = '/workspace/research/notebooks/study.py';
|
||||
const outputPath = '/workspace/artifacts/study.html';
|
||||
fs.putFile(notebookPath, 'import marimo\n');
|
||||
|
||||
const nonAsciiHtml =
|
||||
'<!doctype html><html><body><h1>CA Shorts — €100 / 日本語</h1></body></html>';
|
||||
const expectedBytes = new TextEncoder().encode(nonAsciiHtml);
|
||||
const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex');
|
||||
|
||||
const cleanReport = {
|
||||
issues: [],
|
||||
summary: { errored: false, total_files: 1 },
|
||||
};
|
||||
|
||||
const { runner, calls } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: JSON.stringify(cleanReport), stderr: '' };
|
||||
}
|
||||
const outFlagIdx = args.indexOf('-o');
|
||||
const tempPath = args[outFlagIdx + 1] as string;
|
||||
fs.putFile(tempPath, expectedBytes);
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
const receipt = await exportNotebookSnapshot({
|
||||
notebookPath,
|
||||
outputPath,
|
||||
runner,
|
||||
fs,
|
||||
allowedNotebookRoot: '/workspace/research/notebooks',
|
||||
allowedOutputRoot: '/workspace/artifacts',
|
||||
});
|
||||
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]).toEqual({
|
||||
command: DEFAULT_MARIMO_COMMAND,
|
||||
args: ['check', '--format=json', notebookPath],
|
||||
options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS },
|
||||
});
|
||||
|
||||
expect(fs.createdTempPaths).toHaveLength(1);
|
||||
const tempPath = fs.createdTempPaths[0] as string;
|
||||
expect(tempPath.startsWith('/workspace/artifacts/')).toBe(true);
|
||||
expect(tempPath.endsWith('.html')).toBe(true);
|
||||
expect(tempPath).not.toBe(outputPath);
|
||||
|
||||
expect(calls[1]).toEqual({
|
||||
command: DEFAULT_MARIMO_COMMAND,
|
||||
args: ['export', 'html', notebookPath, '-o', tempPath, '--force'],
|
||||
options: { timeoutMs: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS },
|
||||
});
|
||||
|
||||
expect(fs.renames).toEqual([{ from: tempPath, to: outputPath }]);
|
||||
expect(fs.getBytes(tempPath)).toBeUndefined();
|
||||
expect(fs.getBytes(outputPath)).toEqual(expectedBytes);
|
||||
|
||||
expect(Object.isFrozen(receipt)).toBe(true);
|
||||
expect(Object.isFrozen(receipt.checkDiagnostics)).toBe(true);
|
||||
expect(receipt).toEqual({
|
||||
notebookPath,
|
||||
outputPath,
|
||||
bytes: expectedBytes.byteLength,
|
||||
sha256: expectedSha256,
|
||||
checkDiagnostics: cleanReport,
|
||||
});
|
||||
});
|
||||
|
||||
test('passes custom marimoCommand, timeoutMs, cwd, and notebook paths with spaces and shell metacharacters as single unmodified argv elements', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
const trickyNotebook = "/work/my notebooks/study $(rm -rf) & 'quote'; echo hi | cat.py";
|
||||
const outputPath = '/work/out/report snapshot.html';
|
||||
fs.putFile(trickyNotebook, 'import marimo\n');
|
||||
|
||||
const { runner, calls } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>ok</html>');
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
const receipt = await exportNotebookSnapshot({
|
||||
notebookPath: trickyNotebook,
|
||||
outputPath,
|
||||
runner,
|
||||
fs,
|
||||
marimoCommand: '/opt/uv/bin/marimo',
|
||||
timeoutMs: 45_000,
|
||||
cwd: '/work',
|
||||
});
|
||||
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]?.command).toBe('/opt/uv/bin/marimo');
|
||||
expect(calls[0]?.args).toEqual(['check', '--format=json', trickyNotebook]);
|
||||
expect(calls[0]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 });
|
||||
expect(calls[1]?.command).toBe('/opt/uv/bin/marimo');
|
||||
expect(calls[1]?.args[2]).toBe(trickyNotebook);
|
||||
expect(calls[1]?.options).toEqual({ cwd: '/work', timeoutMs: 45_000 });
|
||||
expect(receipt.checkDiagnostics).toBeNull();
|
||||
});
|
||||
|
||||
test('accepts formatting and runtime advisories on clean exit 0', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
const notebookPath = '/work/nb.py';
|
||||
const outputPath = '/work/out.html';
|
||||
fs.putFile(notebookPath, 'import marimo\n');
|
||||
|
||||
const advisoryReport = {
|
||||
issues: [
|
||||
{ code: 'MF001', severity: 'formatting', message: 'Formatting suggestion' },
|
||||
{ code: 'MR001', severity: 'runtime', message: 'Runtime advisory' },
|
||||
],
|
||||
summary: { errored: false, total_files: 1 },
|
||||
};
|
||||
|
||||
const { runner, calls } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: JSON.stringify(advisoryReport), stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>advisory ok</html>');
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
const receipt = await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs });
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(receipt.checkDiagnostics).toEqual(advisoryReport);
|
||||
expect(Object.isFrozen(receipt.checkDiagnostics?.issues)).toBe(true);
|
||||
});
|
||||
|
||||
test('never invokes export when marimo check exits non-zero and preserves parsed diagnostics', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
const notebookPath = '/work/bad.py';
|
||||
const outputPath = '/work/out.html';
|
||||
fs.putFile(notebookPath, 'def broken(:\n');
|
||||
|
||||
const failureReport = {
|
||||
issues: [{ code: 'MB001', severity: 'breaking', message: 'Syntax error' }],
|
||||
summary: { errored: true, total_files: 1 },
|
||||
};
|
||||
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 1,
|
||||
stdout: JSON.stringify(failureReport),
|
||||
stderr: 'check failed',
|
||||
}));
|
||||
|
||||
const err = await expectSnapshotError(
|
||||
exportNotebookSnapshot({ notebookPath, outputPath, runner, fs }),
|
||||
'CHECK_FAILED'
|
||||
);
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]?.args[0]).toBe('check');
|
||||
expect(fs.createdTempPaths).toHaveLength(0);
|
||||
expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(failureReport);
|
||||
});
|
||||
|
||||
test('nonzero check exit takes precedence as CHECK_FAILED even when stdout is non-JSON', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/bad.py', 'import marimo\n');
|
||||
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 2,
|
||||
stdout: 'not json at all',
|
||||
stderr: 'fatal error',
|
||||
}));
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/bad.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'CHECK_FAILED'
|
||||
);
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('never invokes export when check exits 0 with whitespace-only stdout', async () => {
|
||||
for (const stdout of ['\n', ' \t\r\n']) {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>existing-snapshot</html>');
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 0,
|
||||
stdout,
|
||||
stderr: '',
|
||||
}));
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'CHECK_OUTPUT_INVALID'
|
||||
);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]?.args[0]).toBe('check');
|
||||
expect(fs.createdTempPaths).toHaveLength(0);
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>existing-snapshot</html>');
|
||||
}
|
||||
});
|
||||
|
||||
test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => {
|
||||
const badOutputs = [
|
||||
'{not-valid-json',
|
||||
'[]',
|
||||
'{}',
|
||||
JSON.stringify({ issues: 'not-an-array', summary: { errored: false, total_files: 1 } }),
|
||||
JSON.stringify({ issues: [], summary: { errored: 'false', total_files: 1 } }),
|
||||
JSON.stringify({ issues: [], summary: { errored: false, total_files: 0 } }),
|
||||
JSON.stringify({ issues: [], summary: { errored: false, total_files: 2 } }),
|
||||
JSON.stringify({ issues: [123], summary: { errored: false, total_files: 1 } }),
|
||||
];
|
||||
|
||||
for (const stdout of badOutputs) {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 0,
|
||||
stdout,
|
||||
stderr: '',
|
||||
}));
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'CHECK_OUTPUT_INVALID'
|
||||
);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(fs.createdTempPaths).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('never invokes export when check exits 0 with summary.errored, file error, or breaking diagnostic', async () => {
|
||||
const blockingReports = [
|
||||
{ issues: [], summary: { errored: true, total_files: 1 } },
|
||||
{
|
||||
issues: [{ type: 'error', message: 'Failed to parse notebook' }],
|
||||
summary: { errored: false, total_files: 1 },
|
||||
},
|
||||
{
|
||||
issues: [{ code: 'MB002', severity: 'breaking', message: 'Cycle detected' }],
|
||||
summary: { errored: false, total_files: 1 },
|
||||
},
|
||||
{
|
||||
issues: [
|
||||
{
|
||||
file: '/work/nb.py',
|
||||
diagnostics: [{ code: 'MB003', severity: 'breaking', message: 'Multiple definitions' }],
|
||||
},
|
||||
],
|
||||
summary: { errored: false, total_files: 1 },
|
||||
},
|
||||
];
|
||||
|
||||
for (const report of blockingReports) {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 0,
|
||||
stdout: JSON.stringify(report),
|
||||
stderr: '',
|
||||
}));
|
||||
|
||||
const err = await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'CHECK_FAILED'
|
||||
);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(fs.createdTempPaths).toHaveLength(0);
|
||||
expect((err.details as { diagnostics?: unknown }).diagnostics).toEqual(report);
|
||||
}
|
||||
});
|
||||
|
||||
test('maps check timeout to TIMEOUT and never invokes export', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>original</html>');
|
||||
|
||||
const { runner, calls } = createRecordingRunner(async () => {
|
||||
throw makeTimeoutError('check timed out');
|
||||
});
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
timeoutMs: 5_000,
|
||||
}),
|
||||
'TIMEOUT'
|
||||
);
|
||||
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(fs.createdTempPaths).toHaveLength(0);
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>original</html>');
|
||||
});
|
||||
|
||||
test('fail-closed export: nonzero exit after partial HTML write removes temp and preserves existing destination', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>original-good-snapshot</html>');
|
||||
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>partial-broken-cell-output</html>');
|
||||
return { exitCode: 1, stdout: '', stderr: 'ZeroDivisionError in cell 3' };
|
||||
});
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'EXPORT_FAILED'
|
||||
);
|
||||
|
||||
expect(fs.createdTempPaths).toHaveLength(1);
|
||||
const tempPath = fs.createdTempPaths[0] as string;
|
||||
expect(fs.removedPaths).toContain(tempPath);
|
||||
expect(fs.getBytes(tempPath)).toBeUndefined();
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>original-good-snapshot</html>');
|
||||
});
|
||||
|
||||
test('fail-closed export: missing or zero-byte temp output throws EXPORT_EMPTY, cleans temp, and preserves destination', async () => {
|
||||
for (const mode of ['zero-byte', 'missing'] as const) {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>keep-me</html>');
|
||||
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
if (mode === 'missing') {
|
||||
fs.entries.delete(tempPath);
|
||||
}
|
||||
// In 'zero-byte' mode, tempPath stays at 0 bytes from createExclusive.
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'EXPORT_EMPTY'
|
||||
);
|
||||
|
||||
const tempPath = fs.createdTempPaths[0] as string;
|
||||
expect(fs.removedPaths).toContain(tempPath);
|
||||
expect(fs.getBytes(tempPath)).toBeUndefined();
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>keep-me</html>');
|
||||
}
|
||||
});
|
||||
|
||||
test('fail-closed export: export timeout after partial write throws TIMEOUT, removes temp, and preserves destination', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>keep-original</html>');
|
||||
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>partial-before-timeout</html>');
|
||||
throw makeTimeoutError('export timed out');
|
||||
});
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
timeoutMs: 1_000,
|
||||
}),
|
||||
'TIMEOUT'
|
||||
);
|
||||
|
||||
const tempPath = fs.createdTempPaths[0] as string;
|
||||
expect(fs.removedPaths).toContain(tempPath);
|
||||
expect(fs.getBytes(tempPath)).toBeUndefined();
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>keep-original</html>');
|
||||
});
|
||||
|
||||
test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, and preserves destination', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>prior-snapshot</html>');
|
||||
fs.failRenameError = new Error('EXDEV: cross-device link not permitted');
|
||||
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>new-snapshot</html>');
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
const err = await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'EXPORT_FAILED'
|
||||
);
|
||||
|
||||
const tempPath = fs.createdTempPaths[0] as string;
|
||||
expect(err.cause).toBe(fs.failRenameError);
|
||||
expect(fs.removedPaths).toContain(tempPath);
|
||||
expect(fs.getBytes(tempPath)).toBeUndefined();
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>');
|
||||
});
|
||||
|
||||
test('fail-closed export: rename failure preserves primary error if temp cleanup also fails', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>prior-snapshot</html>');
|
||||
fs.failRenameError = new Error('EXDEV: cross-device link not permitted');
|
||||
fs.failRemoveError = new Error('EIO: cleanup failed');
|
||||
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>new-snapshot</html>');
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
const err = await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'EXPORT_FAILED'
|
||||
);
|
||||
|
||||
expect(err.cause).toBe(fs.failRenameError);
|
||||
expect(fs.removedPaths).toContain(fs.createdTempPaths[0] as string);
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>');
|
||||
});
|
||||
|
||||
test('uses a short sibling temp filename even when output basename is near POSIX NAME_MAX', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
const notebookPath = '/work/nb.py';
|
||||
const longBasename = `${'a'.repeat(250)}.html`;
|
||||
const outputPath = `/work/${longBasename}`;
|
||||
fs.putFile(notebookPath, 'import marimo\n');
|
||||
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
fs.putFile(tempPath, '<html>long-name-ok</html>');
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs });
|
||||
|
||||
expect(fs.createdTempPaths).toHaveLength(1);
|
||||
const tempPath = fs.createdTempPaths[0] as string;
|
||||
const tempBasename = tempPath.slice(tempPath.lastIndexOf('/') + 1);
|
||||
expect(tempPath.startsWith('/work/')).toBe(true);
|
||||
expect(tempBasename.endsWith('.html')).toBe(true);
|
||||
expect(tempBasename.length).toBeLessThan(128);
|
||||
expect(fs.getText(outputPath)).toBe('<html>long-name-ok</html>');
|
||||
});
|
||||
|
||||
test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
fs.putFile('/work/out.html', '<html>initial</html>');
|
||||
|
||||
let releaseFirstExport: (() => void) | null = null;
|
||||
const firstExportStarted = new Promise<void>(resolve => {
|
||||
releaseFirstExport = resolve;
|
||||
});
|
||||
let unblockFirstExport: (() => void) | null = null;
|
||||
const gateFirstExport = new Promise<void>(resolve => {
|
||||
unblockFirstExport = resolve;
|
||||
});
|
||||
|
||||
let exportCount = 0;
|
||||
const { runner } = createRecordingRunner(async (_cmd, args) => {
|
||||
if (args[0] === 'check') {
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
exportCount += 1;
|
||||
const myExport = exportCount;
|
||||
const tempPath = args[args.indexOf('-o') + 1] as string;
|
||||
if (myExport === 1) {
|
||||
fs.putFile(tempPath, '<html>snapshot-A</html>');
|
||||
releaseFirstExport?.();
|
||||
await gateFirstExport;
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
}
|
||||
fs.putFile(tempPath, '<html>snapshot-B</html>');
|
||||
return { exitCode: 0, stdout: '', stderr: '' };
|
||||
});
|
||||
|
||||
const firstPromise = exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
});
|
||||
await firstExportStarted;
|
||||
|
||||
const secondReceipt = await exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
});
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>snapshot-B</html>');
|
||||
|
||||
unblockFirstExport?.();
|
||||
const firstReceipt = await firstPromise;
|
||||
|
||||
expect(fs.createdTempPaths).toHaveLength(2);
|
||||
expect(fs.createdTempPaths[0]).not.toBe(fs.createdTempPaths[1]);
|
||||
expect(firstReceipt.bytes).toBe(new TextEncoder().encode('<html>snapshot-A</html>').byteLength);
|
||||
expect(secondReceipt.bytes).toBe(
|
||||
new TextEncoder().encode('<html>snapshot-B</html>').byteLength
|
||||
);
|
||||
expect(fs.getText('/work/out.html')).toBe('<html>snapshot-A</html>');
|
||||
});
|
||||
|
||||
test('rejects invalid paths before any runner call', async () => {
|
||||
const cases: Array<{
|
||||
readonly name: string;
|
||||
readonly notebookPath: string;
|
||||
readonly outputPath: string;
|
||||
readonly allowedNotebookRoot?: string;
|
||||
readonly allowedOutputRoot?: string;
|
||||
}> = [
|
||||
{ name: 'non-.py notebook', notebookPath: '/work/nb.txt', outputPath: '/work/out.html' },
|
||||
{ name: 'bare .py filename', notebookPath: '/work/.py', outputPath: '/work/out.html' },
|
||||
{
|
||||
name: 'trailing slash notebook',
|
||||
notebookPath: '/work/nb.py/',
|
||||
outputPath: '/work/out.html',
|
||||
},
|
||||
{ name: 'non-.html output', notebookPath: '/work/nb.py', outputPath: '/work/out.htm' },
|
||||
{ name: 'bare .html filename', notebookPath: '/work/nb.py', outputPath: '/work/.html' },
|
||||
{ name: 'relative notebook', notebookPath: 'research/nb.py', outputPath: '/work/out.html' },
|
||||
{ name: 'relative output', notebookPath: '/work/nb.py', outputPath: './out.html' },
|
||||
{ name: 'leading dash notebook', notebookPath: '-nb.py', outputPath: '/work/out.html' },
|
||||
{ name: 'leading dash output', notebookPath: '/work/nb.py', outputPath: '--out.html' },
|
||||
{ name: 'NUL in notebook', notebookPath: '/work/nb\0.py', outputPath: '/work/out.html' },
|
||||
{ name: 'NUL in output', notebookPath: '/work/nb.py', outputPath: '/work/out\0.html' },
|
||||
{
|
||||
name: '.. escape outside allowedNotebookRoot',
|
||||
notebookPath: '/work/notebooks/../secret.py',
|
||||
outputPath: '/work/out/report.html',
|
||||
allowedNotebookRoot: '/work/notebooks',
|
||||
},
|
||||
{
|
||||
name: '.. escape outside allowedOutputRoot',
|
||||
notebookPath: '/work/notebooks/nb.py',
|
||||
outputPath: '/work/out/../evil.html',
|
||||
allowedOutputRoot: '/work/out',
|
||||
},
|
||||
{
|
||||
name: 'same-prefix sibling notebook root',
|
||||
notebookPath: '/work/notebooks-other/nb.py',
|
||||
outputPath: '/work/out/report.html',
|
||||
allowedNotebookRoot: '/work/notebooks',
|
||||
},
|
||||
{
|
||||
name: 'same-prefix sibling output root',
|
||||
notebookPath: '/work/notebooks/nb.py',
|
||||
outputPath: '/work/out-other/report.html',
|
||||
allowedOutputRoot: '/work/out',
|
||||
},
|
||||
];
|
||||
|
||||
for (const tc of cases) {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 0,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
}));
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: tc.notebookPath,
|
||||
outputPath: tc.outputPath,
|
||||
runner,
|
||||
fs,
|
||||
...(tc.allowedNotebookRoot !== undefined
|
||||
? { allowedNotebookRoot: tc.allowedNotebookRoot }
|
||||
: {}),
|
||||
...(tc.allowedOutputRoot !== undefined
|
||||
? { allowedOutputRoot: tc.allowedOutputRoot }
|
||||
: {}),
|
||||
}),
|
||||
'INVALID_PATH'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects missing notebook or directory in place of notebook with NOTEBOOK_NOT_FOUND and zero runner calls', async () => {
|
||||
for (const setup of ['missing', 'directory'] as const) {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
if (setup === 'directory') {
|
||||
fs.putDirectory('/work/nb.py');
|
||||
}
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 0,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
}));
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
}),
|
||||
'NOTEBOOK_NOT_FOUND'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects invalid timeoutMs or marimoCommand with INVALID_OPTION and zero runner calls', async () => {
|
||||
const fs = new InMemoryNotebookFs();
|
||||
fs.putFile('/work/nb.py', 'import marimo\n');
|
||||
const { runner, calls } = createRecordingRunner(async () => ({
|
||||
exitCode: 0,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
}));
|
||||
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
timeoutMs: 0,
|
||||
}),
|
||||
'INVALID_OPTION'
|
||||
);
|
||||
await expectSnapshotError(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath: '/work/nb.py',
|
||||
outputPath: '/work/out.html',
|
||||
runner,
|
||||
fs,
|
||||
marimoCommand: '-evil',
|
||||
}),
|
||||
'INVALID_OPTION'
|
||||
);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -748,6 +748,7 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59
|
|||
- `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result<BsonEodDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- `decode_te_data_stream` / `decode_te_data_chunks` → `Result<BsonTeDataDecodeStats, BsonStreamError>` (borrowed historical `TeDataPoint<'a>` points only — `forecast` unread — with absolute `u64` error offsets)
|
||||
- Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream.
|
||||
|
||||
### `bench-bson-stream`
|
||||
|
|
@ -1697,6 +1698,65 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m
|
|||
- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number.
|
||||
- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up.
|
||||
|
||||
## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`)
|
||||
|
||||
`run_curate_bars_1m` / `run_curate_bars_1m_with_readers` (`src/run_curate_bars_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a headerless 5-column `provider_mapping.tsv` (reusing `load_provider_mapping_tsv` and the shared `qmSplits` loader from `src/run_curate_bars.rs`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`):
|
||||
|
||||
- **Bounded-memory chunking & listing-keyed splits:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_eod_intraday_buffer` directly (the same reader and decoder wrapped by `decode_eod_intraday_chunks`, which hides chunk boundaries), resolving each bar's `listing_id` on its Eastern Time `session_date` before applying `listing_id`-keyed `qmSplits` un-adjustment (preventing split leakage across reused tickers) into one shared `IlpShardedWriter` and calling `finish()` once after EOF. Peak memory is bounded by the reference tables, `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`), per-chunk curation buffers, and one ILP batch buffer per shard.
|
||||
- **Cross-chunk semantics & reporting:** `mapping_source` must be `"eod"`. Collision collapse/drop and `(listing_id, ts)` ordering apply per chunk; the same `(listing_id, ts)` appearing in two chunks is emitted twice and relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`. Aggregated `curate_stats.listings_out` and `curate_stats.builder.keys_out` are sums of per-chunk counts (not global distinct counts). `known_at_micros` is caller-supplied and supplies no evidence of earlier market availability.
|
||||
- **Fail-closed publication:** Preflight scans `out_dir` for any pre-existing `bars_1m.shard-<digits>.ilp` file (regardless of `shard_count`) and rejects before staging, writes to exclusively created temp files in `out_dir`, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any publication error. File-mode CLI wiring is available via `curate-bars-1m` below; `--from-mongo` and live QuestDB ingestion remain follow-ups.
|
||||
|
||||
### `curate-bars-1m` Command (`M2.3n`)
|
||||
|
||||
File-mode CLI command wiring `run_curate_bars_1m` into the `curate-etl` binary:
|
||||
|
||||
```bash
|
||||
curate-etl curate-bars-1m \
|
||||
--eod-intraday eodIntraday1M.bson \
|
||||
--qm-splits qmSplits.bson \
|
||||
--provider-mapping provider_mapping.tsv \
|
||||
--out ./out \
|
||||
--shards 4 \
|
||||
--known-at-micros 1750000000000000
|
||||
```
|
||||
|
||||
- **Required flags:** `--eod-intraday <path>`, `--qm-splits <path>`, `--provider-mapping <path>`, `--out <dir>`, `--shards <N>` (positive base-10 integer, no default), and `--known-at-micros <i64>` (positive base-10 UTC microsecond timestamp, no default).
|
||||
- **Optional flag:** `--mapping-source <name>` (defaults to `eod`; only `eod` is accepted by the runner).
|
||||
- **Timestamp semantics:** `--known-at-micros` records the caller-supplied curation run timestamp verbatim in each ILP row's `known_at` column; it does not establish historical market availability.
|
||||
- **Outputs & fail-closed publication:** writes `<out>/bars_1m.shard-<NN>.ilp` (`00`..`<shards-1>`) and prints the `format_curate_bars_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `bars_1m.shard-*.ilp` files and leaves no partial shard or staging files on error).
|
||||
- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups.
|
||||
|
||||
## `run_curate_fx_1m` File-to-File Runner (`M2.3l`)
|
||||
|
||||
`run_curate_fx_1m` / `run_curate_fx_1m_with_readers` (`src/run_curate_fx_1m.rs`) streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`) via `curate_and_write_fx_1m_from_bson` (`src/curate_fx_1m.rs`):
|
||||
|
||||
- **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers.
|
||||
- **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files.
|
||||
- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-<digits>.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any error. File-mode CLI wiring is available via `curate-fx-1m` below; `--from-mongo` and live QuestDB load remain follow-ups.
|
||||
|
||||
### `curate-fx-1m` Command (`M2.3o`)
|
||||
|
||||
File-mode CLI command wiring `run_curate_fx_1m` into the `curate-etl` binary:
|
||||
|
||||
```bash
|
||||
curate-etl curate-fx-1m \
|
||||
--eod-intraday eodIntraday1M.bson \
|
||||
--out ./out \
|
||||
--shards 4
|
||||
```
|
||||
|
||||
- **Required flags:** `--eod-intraday <path>` (local concatenated raw BSON `eodIntraday1M` dump), `--out <dir>`, and `--shards <N>` (positive base-10 integer, no default).
|
||||
- **Outputs & fail-closed publication:** writes `<out>/fx_1m.shard-<NN>.ilp` (`00`..`<shards-1>`) and prints the `format_curate_fx_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `fx_1m.shard-*.ilp` files and leaves no partial shard or staging files on error).
|
||||
- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups.
|
||||
|
||||
## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`)
|
||||
|
||||
`run_curate_qm_bars_1m` / `run_curate_qm_bars_1m_with_readers` (`src/run_curate_qm_bars_1m.rs`) streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column `provider_mapping.tsv` (`load_provider_mapping_tsv`) into per-shard QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`) via `curate_and_write_qm_bars_1m` (`src/curate_qm_bars_1m.rs`):
|
||||
|
||||
- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`).
|
||||
- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-<NN>.ilp` prefix so QM and EOD (`bars_1m.shard-<NN>.ilp`) exports can share `out_dir` safely.
|
||||
- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-<digits>.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups.
|
||||
|
||||
## Lagged Macro Regime Series Builder (`M2.2n`)
|
||||
|
||||
`build_macro_rows` (`src/macro_series.rs`, tested in `src/macro_series_tests.rs`) is a pure, in-memory builder turning `MacroObservation<K>` inputs and a caller-supplied `(country_iso, indicator) -> Option<MacroLagClass>` lookup into sorted, unique `MacroRow<K>` records matching `macro/part.parquet` in `design/DATA-CONTRACTS.md` (§1 and §3A).
|
||||
|
|
|
|||
|
|
@ -54,6 +54,9 @@ use crate::bson_qm_intraday::{
|
|||
use crate::bson_qm_prices::{
|
||||
decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice,
|
||||
};
|
||||
use crate::bson_te_data::{
|
||||
decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint,
|
||||
};
|
||||
use crate::bson_te_market_data::{
|
||||
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
|
||||
};
|
||||
|
|
@ -983,6 +986,92 @@ where
|
|||
decode_te_market_data_chunks(&mut chunk_reader, target_symbol, on_bar, on_error)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_te_data_error(base: u64, err: BsonTeDataError) -> BsonTeDataError {
|
||||
match err {
|
||||
BsonTeDataError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonTeDataError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonTeDataError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonTeDataError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonTeDataError::CorruptBson { offset, detail } => BsonTeDataError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
},
|
||||
BsonTeDataError::CorruptPointBson {
|
||||
offset,
|
||||
point_index,
|
||||
detail,
|
||||
} => BsonTeDataError::CorruptPointBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
point_index,
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_te_data_buffer`],
|
||||
/// accumulating [`BsonTeDataDecodeStats`] and rebasing per-document and per-point error offsets
|
||||
/// to absolute stream byte offsets.
|
||||
///
|
||||
/// Emits historical `data` observations as borrowed [`TeDataPoint<'a>`] values; `forecast` is
|
||||
/// never read. Per-document and per-point data-quality errors are reported to `on_error` and do
|
||||
/// not abort the stream; only stream-level framing or I/O errors return `Err(BsonStreamError)`.
|
||||
pub fn decode_te_data_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_point: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonTeDataDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(TeDataPoint<'a>),
|
||||
E: FnMut(u64, BsonTeDataError),
|
||||
{
|
||||
let mut total = BsonTeDataDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_te_data_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_point,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_te_data_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `teData` [`std::io::Read`] source through
|
||||
/// [`decode_te_data_buffer`] with bounded memory.
|
||||
pub fn decode_te_data_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_point: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonTeDataDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(TeDataPoint<'a>),
|
||||
E: FnMut(u64, BsonTeDataError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_te_data_chunks(&mut chunk_reader, on_point, on_error)
|
||||
}
|
||||
|
||||
/// Terminal error returned by [`decode_ceo_posts_chunks`] and [`decode_ceo_posts_stream`].
|
||||
#[derive(Debug)]
|
||||
pub enum BsonCeoPostsStreamError {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
use std::error::Error as _;
|
||||
use std::io::{self, Cursor, Read};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
|
||||
use crate::bson_eod_intraday::{
|
||||
|
|
@ -25,9 +25,13 @@ use crate::bson_stream::{
|
|||
decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream,
|
||||
decode_qm_dividend_stream, decode_qm_financials_chunks, decode_qm_financials_stream,
|
||||
decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_stream,
|
||||
decode_qm_split_stream, BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions,
|
||||
decode_qm_split_stream, decode_te_data_chunks, decode_te_data_stream,
|
||||
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions,
|
||||
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
use crate::bson_te_data::{
|
||||
decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint,
|
||||
};
|
||||
use crate::fundamentals::FinancialObservation;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
|
|
@ -3092,3 +3096,739 @@ fn qm_financials_stream_rejects_invalid_config_before_read() {
|
|||
BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct OwnedTeDataPoint {
|
||||
te_symbol: String,
|
||||
country: String,
|
||||
category: String,
|
||||
period_date: i32,
|
||||
value_bits: u64,
|
||||
}
|
||||
|
||||
fn owned_te_data_point(p: TeDataPoint<'_>) -> OwnedTeDataPoint {
|
||||
OwnedTeDataPoint {
|
||||
te_symbol: p.te_symbol.to_owned(),
|
||||
country: p.country.to_owned(),
|
||||
category: p.category.to_owned(),
|
||||
period_date: p.period_date,
|
||||
value_bits: p.value.to_bits(),
|
||||
}
|
||||
}
|
||||
|
||||
fn make_te_data_doc(
|
||||
te_symbol: Option<&str>,
|
||||
country: &str,
|
||||
category: &str,
|
||||
data_points: &[(&str, f64)],
|
||||
forecast_points: &[(&str, f64)],
|
||||
) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
if let Some(sym) = te_symbol {
|
||||
doc.append(cstr!("teSymbol"), sym);
|
||||
}
|
||||
doc.append(cstr!("country"), country);
|
||||
doc.append(cstr!("category"), category);
|
||||
|
||||
let mut data_arr = RawArrayBuf::new();
|
||||
for &(d, v) in data_points {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("d"), d);
|
||||
pt.append(cstr!("v"), v);
|
||||
data_arr.push(pt);
|
||||
}
|
||||
doc.append(cstr!("data"), data_arr);
|
||||
|
||||
if !forecast_points.is_empty() {
|
||||
let mut fc_arr = RawArrayBuf::new();
|
||||
for &(d, v) in forecast_points {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("d"), d);
|
||||
pt.append(cstr!("v"), v);
|
||||
fc_arr.push(pt);
|
||||
}
|
||||
doc.append(cstr!("forecast"), fc_arr);
|
||||
}
|
||||
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_stream_and_chunks_match_buffer_across_tiny_chunks_and_short_reads() {
|
||||
let mut fixture = Vec::new();
|
||||
fixture.extend_from_slice(&make_te_data_doc(
|
||||
Some("USACPI"),
|
||||
"United States",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 3.1), ("2024-02-29", 3.2)],
|
||||
&[("2025-06-30", 2.4)],
|
||||
));
|
||||
fixture.extend_from_slice(&make_te_data_doc(
|
||||
Some("CACPI"),
|
||||
"Canada",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 2.9), ("2024-02-29", 2.8), ("2024-03-31", 2.9)],
|
||||
&[],
|
||||
));
|
||||
// Include a rejected doc (missing teSymbol) and a doc with a bad point date + valid trailing point.
|
||||
fixture.extend_from_slice(&make_te_data_doc(
|
||||
None,
|
||||
"United States",
|
||||
"GDP",
|
||||
&[("2024-03-31", 2.1)],
|
||||
&[],
|
||||
));
|
||||
fixture.extend_from_slice(&make_te_data_doc(
|
||||
Some("USAGDP"),
|
||||
"United States",
|
||||
"GDP Growth Rate",
|
||||
&[("2024-01-31", 1.6), ("2023-02-29", 9.9), ("2024-06-30", 3.0)],
|
||||
&[("2025-12-31", 2.0)],
|
||||
));
|
||||
fixture.extend_from_slice(&make_te_data_doc(
|
||||
Some("CAPOLICY"),
|
||||
"Canada",
|
||||
"Interest Rate",
|
||||
&[("2024-06-05", 4.75)],
|
||||
&[],
|
||||
));
|
||||
|
||||
let mut expected_points = Vec::new();
|
||||
let mut expected_errs = Vec::new();
|
||||
let expected_stats = decode_te_data_buffer(
|
||||
&fixture,
|
||||
|p| expected_points.push(owned_te_data_point(p)),
|
||||
|off, err| expected_errs.push((off as u64, err)),
|
||||
);
|
||||
assert_eq!(expected_stats.docs_in, 5);
|
||||
assert_eq!(expected_stats.docs_accepted, 4);
|
||||
assert_eq!(expected_stats.docs_rejected_total(), 1);
|
||||
assert_eq!(expected_stats.points_in, 9);
|
||||
assert_eq!(expected_stats.points_decoded, 8);
|
||||
assert_eq!(expected_stats.rejected_total(), 1);
|
||||
assert_eq!(
|
||||
expected_stats.docs_in,
|
||||
expected_stats.docs_accepted + expected_stats.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
expected_stats.points_in,
|
||||
expected_stats.points_decoded + expected_stats.rejected_total()
|
||||
);
|
||||
|
||||
// Tiny chunk capacities force multiple whole-document chunks; short FixedStepReader splits
|
||||
// both 4-byte length prefixes and document bodies across reads.
|
||||
let max_doc_bytes = 4096;
|
||||
for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (128, 17)] {
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: cap,
|
||||
max_doc_bytes,
|
||||
};
|
||||
let mut got_points = Vec::new();
|
||||
let mut got_errs = Vec::new();
|
||||
let got_stats = decode_te_data_stream(
|
||||
FixedStepReader::new(&fixture, step),
|
||||
opts,
|
||||
|p| got_points.push(owned_te_data_point(p)),
|
||||
|off, err| got_errs.push((off, err)),
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("teData stream cap={cap} step={step} failed: {e}"));
|
||||
|
||||
assert_eq!(got_stats, expected_stats, "stats mismatch cap={cap} step={step}");
|
||||
assert_eq!(got_points, expected_points, "points mismatch cap={cap} step={step}");
|
||||
assert_eq!(got_errs, expected_errs, "errors mismatch cap={cap} step={step}");
|
||||
}
|
||||
|
||||
// Exercise decode_te_data_chunks directly with tiny buffer + FixedStepReader and verify
|
||||
// buffer_capacity stays within max_doc_bytes.
|
||||
let chunk_opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes,
|
||||
};
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(
|
||||
RandomInterruptReader::new(&fixture, 0x7E_DA7A, true),
|
||||
chunk_opts,
|
||||
)
|
||||
.unwrap();
|
||||
let mut chunk_points = Vec::new();
|
||||
let mut chunk_errs = Vec::new();
|
||||
let chunk_stats = decode_te_data_chunks(
|
||||
&mut chunk_reader,
|
||||
|p| chunk_points.push(owned_te_data_point(p)),
|
||||
|off, err| chunk_errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(chunk_stats, expected_stats);
|
||||
assert_eq!(chunk_points, expected_points);
|
||||
assert_eq!(chunk_errs, expected_errs);
|
||||
assert!(chunk_reader.buffer_capacity() <= max_doc_bytes);
|
||||
assert_eq!(chunk_reader.docs_framed(), 5);
|
||||
assert_eq!(chunk_reader.bytes_read(), fixture.len() as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_stream_later_chunk_rejects_continue_with_absolute_offsets() {
|
||||
let doc1 = make_te_data_doc(
|
||||
Some("USACPI"),
|
||||
"United States",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 3.1)],
|
||||
&[],
|
||||
);
|
||||
let doc2_missing_sym = make_te_data_doc(
|
||||
None,
|
||||
"United States",
|
||||
"Unemployment Rate",
|
||||
&[("2024-01-31", 3.7)],
|
||||
&[],
|
||||
);
|
||||
let doc3_bad_point = make_te_data_doc(
|
||||
Some("CACPI"),
|
||||
"Canada",
|
||||
"Inflation Rate",
|
||||
&[
|
||||
("2024-01-31", 2.9),
|
||||
("not-a-date", 99.0),
|
||||
("2024-03-31", 2.8),
|
||||
],
|
||||
&[],
|
||||
);
|
||||
let doc4_trailing_valid = make_te_data_doc(
|
||||
Some("USAGDP"),
|
||||
"United States",
|
||||
"GDP Growth Rate",
|
||||
&[("2024-06-30", 3.0)],
|
||||
&[],
|
||||
);
|
||||
|
||||
let mut fixture = Vec::new();
|
||||
fixture.extend_from_slice(&doc1);
|
||||
let missing_sym_offset = fixture.len() as u64;
|
||||
assert!(missing_sym_offset > 0);
|
||||
fixture.extend_from_slice(&doc2_missing_sym);
|
||||
let bad_point_doc_offset = fixture.len() as u64;
|
||||
assert!(bad_point_doc_offset > missing_sym_offset);
|
||||
fixture.extend_from_slice(&doc3_bad_point);
|
||||
fixture.extend_from_slice(&doc4_trailing_valid);
|
||||
|
||||
// chunk_capacity_bytes == doc1.len() guarantees doc2 and doc3 start in non-first chunks.
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: doc1.len(),
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_stream(
|
||||
FixedStepReader::new(&fixture, 9),
|
||||
opts,
|
||||
|p| points.push(owned_te_data_point(p)),
|
||||
|off, err| errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Valid prefix, valid point before and after bad point, and trailing valid doc all emit.
|
||||
assert_eq!(points.len(), 4);
|
||||
assert_eq!(points[0].te_symbol, "USACPI");
|
||||
assert_eq!(points[1].te_symbol, "CACPI");
|
||||
assert_eq!(points[1].value_bits, 2.9_f64.to_bits());
|
||||
assert_eq!(points[2].te_symbol, "CACPI");
|
||||
assert_eq!(points[2].value_bits, 2.8_f64.to_bits());
|
||||
assert_eq!(points[3].te_symbol, "USAGDP");
|
||||
|
||||
assert_eq!(
|
||||
errs,
|
||||
vec![
|
||||
(missing_sym_offset, BsonTeDataError::MissingSymbol),
|
||||
(
|
||||
bad_point_doc_offset,
|
||||
BsonTeDataError::InvalidPointDate { point_index: 1 },
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.docs_accepted, 3);
|
||||
assert_eq!(stats.rejected_missing_symbol, 1);
|
||||
assert_eq!(stats.docs_rejected_total(), 1);
|
||||
assert_eq!(stats.points_in, 5);
|
||||
assert_eq!(stats.points_decoded, 4);
|
||||
assert_eq!(stats.rejected_invalid_date, 1);
|
||||
assert_eq!(stats.rejected_total(), 1);
|
||||
assert_eq!(
|
||||
stats.docs_in,
|
||||
stats.docs_accepted + stats.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(stats.points_in, stats.points_decoded + stats.rejected_total());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_stream_rebases_corrupt_bson_and_corrupt_point_bson_in_later_chunks() {
|
||||
let doc1 = make_te_data_doc(
|
||||
Some("USACPI"),
|
||||
"United States",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 3.1)],
|
||||
&[],
|
||||
);
|
||||
// Length-framed corrupt top-level BSON doc.
|
||||
let doc2_corrupt_top = make_corrupt_bson_doc(37);
|
||||
// Length-framed teData doc whose second point (point_index = 1) has a corrupt element type tag.
|
||||
let mut doc3_corrupt_point = make_te_data_doc(
|
||||
Some("CACPI"),
|
||||
"Canada",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 2.9), ("2024-02-29", 2.8)],
|
||||
&[],
|
||||
);
|
||||
let second_d_pos = doc3_corrupt_point
|
||||
.windows(3)
|
||||
.enumerate()
|
||||
.filter(|(_, w)| *w == b"\x02d\0")
|
||||
.nth(1)
|
||||
.map(|(idx, _)| idx)
|
||||
.expect("locate second point's 'd' element");
|
||||
doc3_corrupt_point[second_d_pos] = 0x7E;
|
||||
|
||||
let doc4_after = make_te_data_doc(
|
||||
Some("USAGDP"),
|
||||
"United States",
|
||||
"GDP Growth Rate",
|
||||
&[("2024-06-30", 3.0)],
|
||||
&[],
|
||||
);
|
||||
|
||||
let mut fixture = Vec::new();
|
||||
fixture.extend_from_slice(&doc1);
|
||||
let corrupt_top_offset = fixture.len() as u64;
|
||||
fixture.extend_from_slice(&doc2_corrupt_top);
|
||||
let corrupt_point_offset = fixture.len() as u64;
|
||||
fixture.extend_from_slice(&doc3_corrupt_point);
|
||||
fixture.extend_from_slice(&doc4_after);
|
||||
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: doc1.len(),
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut points = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_data_stream(
|
||||
FixedStepReader::new(&fixture, 11),
|
||||
opts,
|
||||
|p| points.push(owned_te_data_point(p)),
|
||||
|off, err| errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// doc1 point + doc3's valid first point + doc4 point all emit.
|
||||
assert_eq!(points.len(), 3);
|
||||
assert_eq!(points[0].te_symbol, "USACPI");
|
||||
assert_eq!(points[1].te_symbol, "CACPI");
|
||||
assert_eq!(points[2].te_symbol, "USAGDP");
|
||||
|
||||
assert_eq!(errs.len(), 2);
|
||||
assert!(
|
||||
matches!(
|
||||
&errs[0],
|
||||
(abs_off, BsonTeDataError::CorruptBson { offset, .. })
|
||||
if *abs_off == corrupt_top_offset && *offset as u64 == corrupt_top_offset
|
||||
),
|
||||
"expected rebased CorruptBson at {corrupt_top_offset}, got {:?}",
|
||||
errs[0]
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
&errs[1],
|
||||
(
|
||||
abs_off,
|
||||
BsonTeDataError::CorruptPointBson {
|
||||
offset,
|
||||
point_index: 1,
|
||||
..
|
||||
}
|
||||
) if *abs_off == corrupt_point_offset && *offset as u64 == corrupt_point_offset
|
||||
),
|
||||
"expected rebased CorruptPointBson at {corrupt_point_offset}, got {:?}",
|
||||
errs[1]
|
||||
);
|
||||
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.docs_accepted, 3);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.points_in, 4);
|
||||
assert_eq!(stats.points_decoded, 3);
|
||||
assert_eq!(stats.rejected_corrupt_point, 1);
|
||||
assert_eq!(
|
||||
stats.docs_in,
|
||||
stats.docs_accepted + stats.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(stats.points_in, stats.points_decoded + stats.rejected_total());
|
||||
|
||||
// Directly exercise rebase_te_data_error for the two framing-offset variants intercepted by
|
||||
// RawBsonChunkReader, plus non-offset variants.
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(
|
||||
1_000,
|
||||
BsonTeDataError::TruncatedDocument {
|
||||
offset: 42,
|
||||
remaining: 3,
|
||||
declared_len: Some(64),
|
||||
},
|
||||
),
|
||||
BsonTeDataError::TruncatedDocument {
|
||||
offset: 1_042,
|
||||
remaining: 3,
|
||||
declared_len: Some(64),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(
|
||||
2_000,
|
||||
BsonTeDataError::CorruptDocumentLength {
|
||||
offset: 17,
|
||||
declared_len: 3,
|
||||
},
|
||||
),
|
||||
BsonTeDataError::CorruptDocumentLength {
|
||||
offset: 2_017,
|
||||
declared_len: 3,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(500, BsonTeDataError::InvalidPointDate { point_index: 4 }),
|
||||
BsonTeDataError::InvalidPointDate { point_index: 4 }
|
||||
);
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(500, BsonTeDataError::MissingSymbol),
|
||||
BsonTeDataError::MissingSymbol
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_stream_ignores_forecast_and_handles_empty_input() {
|
||||
// Empty input via both decode_te_data_stream and decode_te_data_chunks.
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 64,
|
||||
max_doc_bytes: 1024,
|
||||
};
|
||||
let empty_stats = decode_te_data_stream(
|
||||
Cursor::new(&[][..]),
|
||||
opts,
|
||||
|_| panic!("unexpected point on empty input"),
|
||||
|_, _| panic!("unexpected error on empty input"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(empty_stats, BsonTeDataDecodeStats::default());
|
||||
|
||||
let mut empty_reader = RawBsonChunkReader::with_options(Cursor::new(&[][..]), opts).unwrap();
|
||||
let empty_chunk_stats = decode_te_data_chunks(
|
||||
&mut empty_reader,
|
||||
|_| panic!("unexpected point on empty chunks"),
|
||||
|_, _| panic!("unexpected error on empty chunks"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(empty_chunk_stats, BsonTeDataDecodeStats::default());
|
||||
|
||||
// Document with distinct historical `data` and forward-looking `forecast` arrays.
|
||||
let doc = make_te_data_doc(
|
||||
Some("USACPI"),
|
||||
"United States",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 3.1), ("2024-02-29", 3.2)],
|
||||
&[("2026-01-31", 99.1), ("2026-06-30", 99.2), ("2027-01-31", 99.3)],
|
||||
);
|
||||
let mut points = Vec::new();
|
||||
let stats = decode_te_data_stream(
|
||||
FixedStepReader::new(&doc, 7),
|
||||
BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 4096,
|
||||
},
|
||||
|p| points.push(owned_te_data_point(p)),
|
||||
|off, err| panic!("unexpected error at {off}: {err}"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.docs_accepted, 1);
|
||||
assert_eq!(stats.points_in, 2);
|
||||
assert_eq!(stats.points_decoded, 2);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert_eq!(points.len(), 2);
|
||||
assert_eq!(points[0].value_bits, 3.1_f64.to_bits());
|
||||
assert_eq!(points[1].value_bits, 3.2_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_stream_returns_terminal_errors_for_truncated_and_oversized_docs() {
|
||||
let prefix_doc = make_te_data_doc(
|
||||
Some("USACPI"),
|
||||
"United States",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", 3.1)],
|
||||
&[],
|
||||
);
|
||||
|
||||
// 1. Truncated trailing document after valid prefix.
|
||||
let mut truncated = prefix_doc.clone();
|
||||
let trunc_offset = truncated.len() as u64;
|
||||
truncated.extend_from_slice(&120_i32.to_le_bytes());
|
||||
truncated.extend_from_slice(&[0x02, b'a', 0x00]);
|
||||
|
||||
let mut trunc_points = Vec::new();
|
||||
let trunc_err = decode_te_data_stream(
|
||||
FixedStepReader::new(&truncated, 5),
|
||||
BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 4096,
|
||||
},
|
||||
|p| trunc_points.push(owned_te_data_point(p)),
|
||||
|off, err| panic!("terminal stream error must not reach on_error ({off}: {err})"),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(trunc_points.len(), 1);
|
||||
assert_eq!(trunc_points[0].te_symbol, "USACPI");
|
||||
assert!(matches!(
|
||||
trunc_err,
|
||||
BsonStreamError::TruncatedDocument {
|
||||
offset,
|
||||
remaining: 7,
|
||||
declared_len: Some(120),
|
||||
} if offset == trunc_offset
|
||||
));
|
||||
|
||||
// 2. Oversized trailing document (declared length > max_doc_bytes) after valid prefix.
|
||||
let mut oversized = prefix_doc;
|
||||
let oversize_offset = oversized.len() as u64;
|
||||
oversized.extend_from_slice(&1024_i32.to_le_bytes());
|
||||
oversized.extend_from_slice(&[0x00; 16]);
|
||||
|
||||
let mut oversize_points = Vec::new();
|
||||
let oversize_err = decode_te_data_stream(
|
||||
FixedStepReader::new(&oversized, 5),
|
||||
BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 512,
|
||||
},
|
||||
|p| oversize_points.push(owned_te_data_point(p)),
|
||||
|off, err| panic!("terminal stream error must not reach on_error ({off}: {err})"),
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
assert_eq!(oversize_points.len(), 1);
|
||||
assert_eq!(oversize_points[0].te_symbol, "USACPI");
|
||||
assert!(matches!(
|
||||
oversize_err,
|
||||
BsonStreamError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len: 1024,
|
||||
max_doc_bytes: 512,
|
||||
} if offset == oversize_offset
|
||||
));
|
||||
}
|
||||
|
||||
/// Builds a two-point teData doc whose byte length depends only on the string lengths, so
|
||||
/// fixtures can be made of equal-length documents and chunk layouts are exact.
|
||||
fn make_fixed_len_te_data_doc(te_symbol: &str, v0: f64, v1: f64) -> Vec<u8> {
|
||||
make_te_data_doc(
|
||||
Some(te_symbol),
|
||||
"Canada",
|
||||
"Inflation Rate",
|
||||
&[("2024-01-31", v0), ("2024-02-29", v1)],
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_stream_rebases_errors_at_nonzero_local_offsets_inside_later_multi_doc_chunks() {
|
||||
// Arrange: six equal-length docs, chunk capacity = 2 docs, so every chunk holds exactly two
|
||||
// documents and each offending document sits at local offset L inside a chunk with base 2L/4L.
|
||||
// This separates `chunk.start_offset` from the in-chunk local offset, which single-doc chunks
|
||||
// (local offset 0) cannot do.
|
||||
let doc_a = make_fixed_len_te_data_doc("TEDOCA", 1.0, 1.5);
|
||||
let len = doc_a.len();
|
||||
let doc_b = make_fixed_len_te_data_doc("TEDOCB", 2.0, 2.5);
|
||||
let doc_c = make_fixed_len_te_data_doc("TEDOCC", 3.0, 3.5);
|
||||
let doc_d_corrupt_top = make_corrupt_bson_doc(len);
|
||||
let doc_e = make_fixed_len_te_data_doc("TEDOCE", 5.0, 5.5);
|
||||
let mut doc_f_corrupt_point = make_fixed_len_te_data_doc("TEDOCF", 6.0, 6.5);
|
||||
let second_d_pos = doc_f_corrupt_point
|
||||
.windows(3)
|
||||
.enumerate()
|
||||
.filter(|(_, w)| *w == b"\x02d\0")
|
||||
.nth(1)
|
||||
.map(|(idx, _)| idx)
|
||||
.expect("locate second point's 'd' element");
|
||||
doc_f_corrupt_point[second_d_pos] = 0x7E;
|
||||
|
||||
let docs = [
|
||||
&doc_a,
|
||||
&doc_b,
|
||||
&doc_c,
|
||||
&doc_d_corrupt_top,
|
||||
&doc_e,
|
||||
&doc_f_corrupt_point,
|
||||
];
|
||||
for d in docs {
|
||||
assert_eq!(d.len(), len, "fixture docs must be equal length");
|
||||
}
|
||||
let fixture: Vec<u8> = docs.iter().flat_map(|d| d.iter().copied()).collect();
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 2 * len,
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
|
||||
// Pin the chunk layout the assertions below rely on.
|
||||
let mut layout_reader =
|
||||
RawBsonChunkReader::with_options(Cursor::new(fixture.as_slice()), opts).unwrap();
|
||||
let mut layout = Vec::new();
|
||||
while let Some(chunk) = layout_reader.next_chunk().unwrap() {
|
||||
layout.push((chunk.start_offset, chunk.bytes.len()));
|
||||
}
|
||||
let l = len as u64;
|
||||
assert_eq!(
|
||||
layout,
|
||||
vec![(0, 2 * len), (2 * l, 2 * len), (4 * l, 2 * len)]
|
||||
);
|
||||
|
||||
// Act: both entry points.
|
||||
let mut stream_points = Vec::new();
|
||||
let mut stream_errs = Vec::new();
|
||||
let stream_stats = decode_te_data_stream(
|
||||
Cursor::new(fixture.as_slice()),
|
||||
opts,
|
||||
|p| stream_points.push(owned_te_data_point(p)),
|
||||
|off, err| stream_errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut chunk_reader =
|
||||
RawBsonChunkReader::with_options(Cursor::new(fixture.as_slice()), opts).unwrap();
|
||||
let mut chunk_points = Vec::new();
|
||||
let mut chunk_errs = Vec::new();
|
||||
let chunk_stats = decode_te_data_chunks(
|
||||
&mut chunk_reader,
|
||||
|p| chunk_points.push(owned_te_data_point(p)),
|
||||
|off, err| chunk_errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Assert: absolute offsets 3L and 5L both in the callback argument and the embedded error.
|
||||
assert_eq!(stream_errs.len(), 2, "{stream_errs:?}");
|
||||
match &stream_errs[0] {
|
||||
(abs, BsonTeDataError::CorruptBson { offset, .. }) => {
|
||||
assert_eq!(*abs, 3 * l);
|
||||
assert_eq!(*offset as u64, 3 * l);
|
||||
}
|
||||
other => panic!("expected CorruptBson at {}, got {other:?}", 3 * l),
|
||||
}
|
||||
match &stream_errs[1] {
|
||||
(
|
||||
abs,
|
||||
BsonTeDataError::CorruptPointBson {
|
||||
offset,
|
||||
point_index,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
assert_eq!(*abs, 5 * l);
|
||||
assert_eq!(*offset as u64, 5 * l);
|
||||
assert_eq!(*point_index, 1);
|
||||
}
|
||||
other => panic!("expected CorruptPointBson at {}, got {other:?}", 5 * l),
|
||||
}
|
||||
assert_eq!(chunk_errs, stream_errs);
|
||||
|
||||
let symbols: Vec<(&str, u64)> = stream_points
|
||||
.iter()
|
||||
.map(|p| (p.te_symbol.as_str(), p.value_bits))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
symbols,
|
||||
vec![
|
||||
("TEDOCA", 1.0_f64.to_bits()),
|
||||
("TEDOCA", 1.5_f64.to_bits()),
|
||||
("TEDOCB", 2.0_f64.to_bits()),
|
||||
("TEDOCB", 2.5_f64.to_bits()),
|
||||
("TEDOCC", 3.0_f64.to_bits()),
|
||||
("TEDOCC", 3.5_f64.to_bits()),
|
||||
("TEDOCE", 5.0_f64.to_bits()),
|
||||
("TEDOCE", 5.5_f64.to_bits()),
|
||||
("TEDOCF", 6.0_f64.to_bits()),
|
||||
]
|
||||
);
|
||||
assert_eq!(chunk_points, stream_points);
|
||||
|
||||
assert_eq!(stream_stats, chunk_stats);
|
||||
assert_eq!(stream_stats.docs_in, 6);
|
||||
assert_eq!(stream_stats.docs_accepted, 5);
|
||||
assert_eq!(stream_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stream_stats.points_in, 10);
|
||||
assert_eq!(stream_stats.points_decoded, 9);
|
||||
assert_eq!(stream_stats.rejected_corrupt_point, 1);
|
||||
assert_eq!(
|
||||
stream_stats.docs_in,
|
||||
stream_stats.docs_accepted + stream_stats.docs_rejected_total()
|
||||
);
|
||||
assert_eq!(
|
||||
stream_stats.points_in,
|
||||
stream_stats.points_decoded + stream_stats.rejected_total()
|
||||
);
|
||||
assert_eq!(chunk_reader.docs_framed(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn te_data_rebase_preserves_payload_fields_and_saturates_offsets() {
|
||||
// CorruptBson keeps its detail; CorruptPointBson keeps point_index and detail.
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(
|
||||
4_096,
|
||||
BsonTeDataError::CorruptBson {
|
||||
offset: 10,
|
||||
detail: "bad top".to_owned(),
|
||||
},
|
||||
),
|
||||
BsonTeDataError::CorruptBson {
|
||||
offset: 4_106,
|
||||
detail: "bad top".to_owned(),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(
|
||||
4_096,
|
||||
BsonTeDataError::CorruptPointBson {
|
||||
offset: 0,
|
||||
point_index: 7,
|
||||
detail: "bad point".to_owned(),
|
||||
},
|
||||
),
|
||||
BsonTeDataError::CorruptPointBson {
|
||||
offset: 4_096,
|
||||
point_index: 7,
|
||||
detail: "bad point".to_owned(),
|
||||
}
|
||||
);
|
||||
// Overflowing absolute offsets saturate instead of wrapping (shared `rebase_offset` policy).
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(
|
||||
u64::MAX,
|
||||
BsonTeDataError::CorruptBson {
|
||||
offset: 1,
|
||||
detail: String::new(),
|
||||
},
|
||||
),
|
||||
BsonTeDataError::CorruptBson {
|
||||
offset: usize::MAX,
|
||||
detail: String::new(),
|
||||
}
|
||||
);
|
||||
// Point-level variants without an offset pass through unchanged.
|
||||
let passthrough = BsonTeDataError::WrongPointFieldType {
|
||||
point_index: 2,
|
||||
field: "v",
|
||||
actual: bson::spec::ElementType::String,
|
||||
};
|
||||
assert_eq!(
|
||||
super::rebase_te_data_error(9_999, passthrough.clone()),
|
||||
passthrough
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,9 @@ use crate::bson_qm_events::{
|
|||
DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD,
|
||||
DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD,
|
||||
};
|
||||
use crate::bson_stream::BsonStreamOptions;
|
||||
use crate::curate_adj::AdjPointInTimeFence;
|
||||
use crate::ilp::IlpWriterOptions;
|
||||
use crate::mongo_stream::{
|
||||
MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV,
|
||||
MAX_MONGO_BATCH_SIZE,
|
||||
|
|
@ -50,9 +52,11 @@ use crate::run_curate_adj::CurateAdjFactorsArgs;
|
|||
use crate::run_curate_bars::{
|
||||
default_curate_bars_threads, CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE};
|
||||
use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
|
||||
use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE};
|
||||
use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL};
|
||||
use crate::run_curate_fx_1m::CurateFx1mArgs;
|
||||
use crate::run_curate_posts::{
|
||||
CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE,
|
||||
};
|
||||
|
|
@ -80,6 +84,8 @@ pub enum CliAction {
|
|||
CurateShortsMongo(CurateShortsMongoArgs),
|
||||
CurateEvents(CurateEventsArgs),
|
||||
CurateEventsMongo(CurateEventsMongoArgs),
|
||||
CurateBars1m(CurateBars1mArgs),
|
||||
CurateFx1m(CurateFx1mArgs),
|
||||
CuratePosts(CuratePostsArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
|
|
@ -140,9 +146,12 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} curate-shorts --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
|
||||
Curate shorts from ceoShorts BSON or read-only MongoDB + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\
|
||||
{name} curate-events --qm-filings <path> --qm-earnings <path> --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-events --from-mongo [--mongo-uri-env <VAR> | --mongo-uri <uri>] [--batch-size <N>] [--limit <N>] [--date-gte <YYYY-MM-DD>] [--date-lt <YYYY-MM-DD>] --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
|
||||
Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\
|
||||
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
|
||||
Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-<NN>.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\
|
||||
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
|
||||
Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-<NN>.ilp\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
Curate ceoPosts from BSON + provider_mapping TSV into <out>/events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\
|
||||
{name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
|
||||
|
|
@ -193,6 +202,8 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
|
||||
{name} curate-shorts --ceo-shorts <path> --provider-mapping <path> --out <dir> --shares-short-field <name> [--key-field <name>] [--report-date-field <name>] [--net-change-field <name>] [--pct-float-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-events --qm-filings <path> --qm-earnings <path> --provider-mapping <path> --out <dir> --filings-form-type-field <name> [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--earnings-key-field <name>] [--earnings-report-date-field <name>] [--earnings-announce-time-field <name>] [--earnings-fiscal-period-end-field <name>] [--earnings-actual-eps-field <name>] [--earnings-revenue-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
|
||||
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
|
|
@ -1552,6 +1563,261 @@ fn parse_curate_events_args(args: &[&str]) -> Result<CliAction, String> {
|
|||
Ok(CliAction::CurateEvents(parsed))
|
||||
}
|
||||
|
||||
fn parse_curate_bars_1m_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut intraday_path: Option<PathBuf> = None;
|
||||
let mut splits_path: Option<PathBuf> = None;
|
||||
let mut provider_mapping_path: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
let mut shard_count: Option<usize> = None;
|
||||
let mut known_at_micros: Option<i64> = None;
|
||||
let mut mapping_source: Option<String> = None;
|
||||
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let token = args[i];
|
||||
if !token.starts_with("--") {
|
||||
return Err(format!(
|
||||
"unexpected positional argument '{token}' for curate-bars-1m"
|
||||
));
|
||||
}
|
||||
|
||||
let flag_name = token.split_once('=').map_or(token, |(k, _)| k);
|
||||
if matches!(
|
||||
flag_name,
|
||||
"--from-mongo"
|
||||
| "--mongo-uri"
|
||||
| "--mongo-uri-env"
|
||||
| "--batch-size"
|
||||
| "--limit"
|
||||
| "--date-gte"
|
||||
| "--date-lt"
|
||||
| "--with-qm-prices"
|
||||
) {
|
||||
return Err(format!(
|
||||
"MongoDB streaming flag '{flag_name}' is not supported by curate-bars-1m (file mode only)"
|
||||
));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(k, v)
|
||||
} else {
|
||||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
||||
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate flag '{flag_name}'"));
|
||||
}
|
||||
if raw.is_empty() {
|
||||
return Err(format!("empty value for flag '{flag_name}'"));
|
||||
}
|
||||
*slot = Some(PathBuf::from(raw));
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let set_name = |slot: &mut Option<String>, flag_name: &str, raw: &str| -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate flag '{flag_name}'"));
|
||||
}
|
||||
if raw.trim().is_empty() {
|
||||
return Err(format!("empty value for flag '{flag_name}'"));
|
||||
}
|
||||
*slot = Some(raw.to_string());
|
||||
Ok(())
|
||||
};
|
||||
|
||||
match flag {
|
||||
"--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?,
|
||||
"--qm-splits" => set_path(&mut splits_path, "--qm-splits", value)?,
|
||||
"--provider-mapping" => {
|
||||
set_path(&mut provider_mapping_path, "--provider-mapping", value)?;
|
||||
}
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
"--shards" => {
|
||||
if shard_count.is_some() {
|
||||
return Err("duplicate flag '--shards'".to_string());
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty value for flag '--shards'".to_string());
|
||||
}
|
||||
if !value.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(format!(
|
||||
"invalid --shards '{value}' (expected a positive integer >= 1)"
|
||||
));
|
||||
}
|
||||
let parsed = value.parse::<usize>().map_err(|_| {
|
||||
format!("invalid --shards '{value}' (expected a positive integer >= 1)")
|
||||
})?;
|
||||
if parsed == 0 {
|
||||
return Err(format!(
|
||||
"invalid --shards '{value}' (expected a positive integer >= 1)"
|
||||
));
|
||||
}
|
||||
shard_count = Some(parsed);
|
||||
}
|
||||
"--known-at-micros" => {
|
||||
if known_at_micros.is_some() {
|
||||
return Err("duplicate flag '--known-at-micros'".to_string());
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty value for flag '--known-at-micros'".to_string());
|
||||
}
|
||||
if !value.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(format!(
|
||||
"invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)"
|
||||
));
|
||||
}
|
||||
let parsed = value.parse::<i64>().map_err(|_| {
|
||||
format!(
|
||||
"invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)"
|
||||
)
|
||||
})?;
|
||||
if parsed <= 0 {
|
||||
return Err(format!(
|
||||
"invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)"
|
||||
));
|
||||
}
|
||||
known_at_micros = Some(parsed);
|
||||
}
|
||||
"--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?,
|
||||
other => return Err(format!("unknown flag '{other}' for curate-bars-1m")),
|
||||
}
|
||||
}
|
||||
|
||||
let intraday_path =
|
||||
intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?;
|
||||
let splits_path =
|
||||
splits_path.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
|
||||
let provider_mapping_path = provider_mapping_path
|
||||
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
let shard_count =
|
||||
shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?;
|
||||
let known_at_micros =
|
||||
known_at_micros.ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?;
|
||||
|
||||
Ok(CliAction::CurateBars1m(CurateBars1mArgs {
|
||||
intraday_path,
|
||||
splits_path,
|
||||
provider_mapping_path,
|
||||
out_dir,
|
||||
mapping_source: mapping_source
|
||||
.unwrap_or_else(|| DEFAULT_BARS_1M_MAPPING_SOURCE.to_string()),
|
||||
shard_count,
|
||||
known_at_micros,
|
||||
stream_options: BsonStreamOptions::default(),
|
||||
ilp_options: IlpWriterOptions::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_curate_fx_1m_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut intraday_path: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
let mut shard_count: Option<usize> = None;
|
||||
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let token = args[i];
|
||||
if !token.starts_with("--") {
|
||||
return Err(format!(
|
||||
"unexpected positional argument '{token}' for curate-fx-1m"
|
||||
));
|
||||
}
|
||||
|
||||
let flag_name = token.split_once('=').map_or(token, |(k, _)| k);
|
||||
if matches!(
|
||||
flag_name,
|
||||
"--from-mongo"
|
||||
| "--mongo-uri"
|
||||
| "--mongo-uri-env"
|
||||
| "--batch-size"
|
||||
| "--limit"
|
||||
| "--date-gte"
|
||||
| "--date-lt"
|
||||
| "--with-qm-prices"
|
||||
) {
|
||||
return Err(format!(
|
||||
"MongoDB streaming flag '{flag_name}' is not supported by curate-fx-1m (file mode only)"
|
||||
));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((k, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(k, v)
|
||||
} else {
|
||||
let Some(&v) = args.get(i + 1) else {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
};
|
||||
if v.starts_with("--") {
|
||||
return Err(format!("missing value for flag '{token}'"));
|
||||
}
|
||||
i += 2;
|
||||
(token, v)
|
||||
};
|
||||
|
||||
let set_path = |slot: &mut Option<PathBuf>, flag_name: &str, raw: &str| -> Result<(), String> {
|
||||
if slot.is_some() {
|
||||
return Err(format!("duplicate flag '{flag_name}'"));
|
||||
}
|
||||
if raw.is_empty() {
|
||||
return Err(format!("empty value for flag '{flag_name}'"));
|
||||
}
|
||||
*slot = Some(PathBuf::from(raw));
|
||||
Ok(())
|
||||
};
|
||||
|
||||
match flag {
|
||||
"--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?,
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
"--shards" => {
|
||||
if shard_count.is_some() {
|
||||
return Err("duplicate flag '--shards'".to_string());
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty value for flag '--shards'".to_string());
|
||||
}
|
||||
if !value.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(format!(
|
||||
"invalid --shards '{value}' (expected a positive integer >= 1)"
|
||||
));
|
||||
}
|
||||
let parsed = value.parse::<usize>().map_err(|_| {
|
||||
format!("invalid --shards '{value}' (expected a positive integer >= 1)")
|
||||
})?;
|
||||
if parsed == 0 {
|
||||
return Err(format!(
|
||||
"invalid --shards '{value}' (expected a positive integer >= 1)"
|
||||
));
|
||||
}
|
||||
shard_count = Some(parsed);
|
||||
}
|
||||
other => return Err(format!("unknown flag '{other}' for curate-fx-1m")),
|
||||
}
|
||||
}
|
||||
|
||||
let intraday_path =
|
||||
intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?;
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
let shard_count =
|
||||
shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?;
|
||||
|
||||
Ok(CliAction::CurateFx1m(CurateFx1mArgs {
|
||||
intraday_path,
|
||||
out_dir,
|
||||
shard_count,
|
||||
stream_options: BsonStreamOptions::default(),
|
||||
ilp_options: IlpWriterOptions::default(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`].
|
||||
pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
let slices: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
|
|
@ -1567,6 +1833,8 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest),
|
||||
["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest),
|
||||
["curate-events", rest @ ..] => parse_curate_events_args(rest),
|
||||
["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest),
|
||||
["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest),
|
||||
["curate-posts", rest @ ..] => parse_curate_posts_args(rest),
|
||||
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
|
||||
["bench-split", raw] => match raw.parse::<usize>() {
|
||||
|
|
@ -3591,6 +3859,576 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_bars_1m_valid_default_and_explicit_mapping_source() {
|
||||
let parsed = parse_args(&to_args(&[
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
"intraday.bson",
|
||||
"--qm-splits",
|
||||
"splits.bson",
|
||||
"--provider-mapping",
|
||||
"mapping.tsv",
|
||||
"--out",
|
||||
"out_dir",
|
||||
"--shards",
|
||||
"4",
|
||||
"--known-at-micros",
|
||||
"1735689600000000",
|
||||
]))
|
||||
.expect("valid curate-bars-1m args with default mapping source");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
CliAction::CurateBars1m(CurateBars1mArgs {
|
||||
intraday_path: PathBuf::from("intraday.bson"),
|
||||
splits_path: PathBuf::from("splits.bson"),
|
||||
provider_mapping_path: PathBuf::from("mapping.tsv"),
|
||||
out_dir: PathBuf::from("out_dir"),
|
||||
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
|
||||
shard_count: 4,
|
||||
known_at_micros: 1_735_689_600_000_000,
|
||||
stream_options: BsonStreamOptions::default(),
|
||||
ilp_options: IlpWriterOptions::default(),
|
||||
})
|
||||
);
|
||||
|
||||
let parsed_eq = parse_args(&to_args(&[
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday=i2.bson",
|
||||
"--qm-splits=s2.bson",
|
||||
"--provider-mapping=m2.tsv",
|
||||
"--out=o2",
|
||||
"--shards=2",
|
||||
"--known-at-micros=9223372036854775807",
|
||||
"--mapping-source=eod_alt",
|
||||
]))
|
||||
.expect("valid curate-bars-1m args with equals form and explicit mapping source");
|
||||
|
||||
assert_eq!(
|
||||
parsed_eq,
|
||||
CliAction::CurateBars1m(CurateBars1mArgs {
|
||||
intraday_path: PathBuf::from("i2.bson"),
|
||||
splits_path: PathBuf::from("s2.bson"),
|
||||
provider_mapping_path: PathBuf::from("m2.tsv"),
|
||||
out_dir: PathBuf::from("o2"),
|
||||
mapping_source: "eod_alt".to_string(),
|
||||
shard_count: 2,
|
||||
known_at_micros: i64::MAX,
|
||||
stream_options: BsonStreamOptions::default(),
|
||||
ilp_options: IlpWriterOptions::default(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_usage_mentions_command_and_all_flags() {
|
||||
let expected_flags = [
|
||||
"--eod-intraday",
|
||||
"--qm-splits",
|
||||
"--provider-mapping",
|
||||
"--out",
|
||||
"--shards",
|
||||
"--known-at-micros",
|
||||
"--mapping-source",
|
||||
];
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
let usage_stderr = format_usage_stderr("curate-etl");
|
||||
let usage_line = usage
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("curate-etl curate-bars-1m "))
|
||||
.expect("format_usage missing curate-bars-1m command line");
|
||||
let stderr_line = usage_stderr
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("curate-etl curate-bars-1m "))
|
||||
.expect("format_usage_stderr missing curate-bars-1m command line");
|
||||
for flag in expected_flags {
|
||||
assert!(
|
||||
usage_line.contains(flag),
|
||||
"format_usage curate-bars-1m line missing {flag}: {usage_line}"
|
||||
);
|
||||
assert!(
|
||||
stderr_line.contains(flag),
|
||||
"format_usage_stderr curate-bars-1m line missing {flag}: {stderr_line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_bars_1m_rejects_missing_required_flags() {
|
||||
let required: [(&str, &str); 6] = [
|
||||
("--eod-intraday", "intraday.bson"),
|
||||
("--qm-splits", "splits.bson"),
|
||||
("--provider-mapping", "mapping.tsv"),
|
||||
("--out", "out_dir"),
|
||||
("--shards", "2"),
|
||||
("--known-at-micros", "1735689600000000"),
|
||||
];
|
||||
|
||||
for omit in 0..required.len() {
|
||||
let mut argv: Vec<&str> = vec!["curate-bars-1m"];
|
||||
for (idx, &(flag, val)) in required.iter().enumerate() {
|
||||
if idx != omit {
|
||||
argv.push(flag);
|
||||
argv.push(val);
|
||||
}
|
||||
}
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
let missing_flag = required[omit].0;
|
||||
assert!(
|
||||
err.contains(&format!("missing required flag '{missing_flag}'")),
|
||||
"expected missing required flag '{missing_flag}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_bars_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() {
|
||||
let base = [
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
"i.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--out",
|
||||
"o",
|
||||
"--shards",
|
||||
"2",
|
||||
"--known-at-micros",
|
||||
"1000",
|
||||
"--mapping-source",
|
||||
"eod",
|
||||
];
|
||||
|
||||
// Duplicate flags (path, numeric, and name).
|
||||
for (flag, extra_val) in [
|
||||
("--eod-intraday", "i2.bson"),
|
||||
("--qm-splits", "s2.bson"),
|
||||
("--provider-mapping", "m2.tsv"),
|
||||
("--out", "o2"),
|
||||
("--shards", "3"),
|
||||
("--known-at-micros", "2000"),
|
||||
("--mapping-source", "eod"),
|
||||
] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(flag);
|
||||
argv.push(extra_val);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("duplicate flag '{flag}'")),
|
||||
"expected duplicate error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Empty values via --flag= and whitespace-only --mapping-source.
|
||||
for flag in [
|
||||
"--eod-intraday",
|
||||
"--qm-splits",
|
||||
"--provider-mapping",
|
||||
"--out",
|
||||
"--shards",
|
||||
"--known-at-micros",
|
||||
"--mapping-source",
|
||||
] {
|
||||
let empty_token = format!("{flag}=");
|
||||
let err = parse_args(&to_args(&["curate-bars-1m", &empty_token])).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("empty value for flag '{flag}'")),
|
||||
"expected empty value error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
let err = parse_args(&to_args(&["curate-bars-1m", "--mapping-source", " "])).unwrap_err();
|
||||
assert!(
|
||||
err.contains("empty value for flag '--mapping-source'"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
// Flag at end of input or followed by another flag.
|
||||
let err = parse_args(&to_args(&["curate-bars-1m", "--eod-intraday"])).unwrap_err();
|
||||
assert!(
|
||||
err.contains("missing value for flag '--eod-intraday'"),
|
||||
"{err}"
|
||||
);
|
||||
let err = parse_args(&to_args(&[
|
||||
"curate-bars-1m",
|
||||
"--shards",
|
||||
"--out",
|
||||
"o",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--shards'"), "{err}");
|
||||
|
||||
// Unknown flag.
|
||||
let mut unknown = base.to_vec();
|
||||
unknown.push("--nope");
|
||||
unknown.push("1");
|
||||
let err = parse_args(&to_args(&unknown)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("unknown flag '--nope' for curate-bars-1m"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
// Positional argument.
|
||||
let err = parse_args(&to_args(&["curate-bars-1m", "positional"])).unwrap_err();
|
||||
assert!(
|
||||
err.contains("unexpected positional argument 'positional' for curate-bars-1m"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_bars_1m_rejects_invalid_numeric_flags() {
|
||||
let base_without_shards = [
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
"i.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--out",
|
||||
"o",
|
||||
"--known-at-micros",
|
||||
"1000",
|
||||
];
|
||||
|
||||
for bad_shards in [
|
||||
"0",
|
||||
"-1",
|
||||
"+1",
|
||||
"abc",
|
||||
"1.5",
|
||||
"999999999999999999999999999999999999999",
|
||||
] {
|
||||
let mut argv = base_without_shards.to_vec();
|
||||
argv.push("--shards");
|
||||
argv.push(bad_shards);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("invalid --shards"),
|
||||
"expected invalid --shards for '{bad_shards}', got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
let base_without_known_at = [
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
"i.bson",
|
||||
"--qm-splits",
|
||||
"s.bson",
|
||||
"--provider-mapping",
|
||||
"m.tsv",
|
||||
"--out",
|
||||
"o",
|
||||
"--shards",
|
||||
"2",
|
||||
];
|
||||
|
||||
for bad_known_at in [
|
||||
"0",
|
||||
"-1",
|
||||
"-9223372036854775808",
|
||||
"+1000",
|
||||
"abc",
|
||||
"1.5",
|
||||
"9223372036854775808",
|
||||
"999999999999999999999999999999",
|
||||
] {
|
||||
let mut argv = base_without_known_at.to_vec();
|
||||
argv.push("--known-at-micros");
|
||||
argv.push(bad_known_at);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("invalid --known-at-micros"),
|
||||
"expected invalid --known-at-micros for '{bad_known_at}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() {
|
||||
let mongo_flags = [
|
||||
"--from-mongo",
|
||||
"--mongo-uri",
|
||||
"--mongo-uri-env",
|
||||
"--batch-size",
|
||||
"--limit",
|
||||
"--date-gte",
|
||||
"--date-lt",
|
||||
"--with-qm-prices",
|
||||
];
|
||||
|
||||
let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock";
|
||||
for flag in mongo_flags {
|
||||
// Bare form (at end of argv).
|
||||
let err_bare = parse_args(&to_args(&["curate-bars-1m", flag])).unwrap_err();
|
||||
assert!(
|
||||
err_bare.contains(flag) && err_bare.contains("file mode only"),
|
||||
"bare {flag} should fail with file-mode error, got: {err_bare}"
|
||||
);
|
||||
|
||||
// Separated value form.
|
||||
let err_sep = parse_args(&to_args(&["curate-bars-1m", flag, secret])).unwrap_err();
|
||||
assert!(
|
||||
err_sep.contains(flag) && err_sep.contains("file mode only"),
|
||||
"separated {flag} should fail with file-mode error, got: {err_sep}"
|
||||
);
|
||||
assert!(
|
||||
!err_sep.contains("s3cr3t_pw"),
|
||||
"separated {flag} error leaked value: {err_sep}"
|
||||
);
|
||||
|
||||
// Equals form.
|
||||
let eq_token = format!("{flag}={secret}");
|
||||
let err_eq = parse_args(&to_args(&["curate-bars-1m", &eq_token])).unwrap_err();
|
||||
assert!(
|
||||
err_eq.contains(flag) && err_eq.contains("file mode only"),
|
||||
"equals {flag} should fail with file-mode error, got: {err_eq}"
|
||||
);
|
||||
assert!(
|
||||
!err_eq.contains("s3cr3t_pw"),
|
||||
"equals {flag} error leaked value: {err_eq}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_fx_1m_valid_space_and_equals_forms() {
|
||||
let expected = CliAction::CurateFx1m(CurateFx1mArgs {
|
||||
intraday_path: PathBuf::from("A"),
|
||||
out_dir: PathBuf::from("B"),
|
||||
shard_count: 4,
|
||||
stream_options: BsonStreamOptions::default(),
|
||||
ilp_options: IlpWriterOptions::default(),
|
||||
});
|
||||
|
||||
let parsed_space = parse_args(&to_args(&[
|
||||
"curate-fx-1m",
|
||||
"--eod-intraday",
|
||||
"A",
|
||||
"--out",
|
||||
"B",
|
||||
"--shards",
|
||||
"4",
|
||||
]))
|
||||
.expect("valid curate-fx-1m args in space form");
|
||||
assert_eq!(parsed_space, expected);
|
||||
|
||||
let parsed_eq = parse_args(&to_args(&[
|
||||
"curate-fx-1m",
|
||||
"--eod-intraday=A",
|
||||
"--out=B",
|
||||
"--shards=4",
|
||||
]))
|
||||
.expect("valid curate-fx-1m args in equals form");
|
||||
assert_eq!(parsed_eq, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_fx_1m_usage_mentions_command_and_all_flags() {
|
||||
let expected_flags = ["--eod-intraday", "--out", "--shards"];
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
let usage_stderr = format_usage_stderr("curate-etl");
|
||||
let usage_line = usage
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m "))
|
||||
.expect("format_usage missing curate-fx-1m command line");
|
||||
let stderr_line = usage_stderr
|
||||
.lines()
|
||||
.find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m "))
|
||||
.expect("format_usage_stderr missing curate-fx-1m command line");
|
||||
for flag in expected_flags {
|
||||
assert!(
|
||||
usage_line.contains(flag),
|
||||
"format_usage curate-fx-1m line missing {flag}: {usage_line}"
|
||||
);
|
||||
assert!(
|
||||
stderr_line.contains(flag),
|
||||
"format_usage_stderr curate-fx-1m line missing {flag}: {stderr_line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_fx_1m_rejects_missing_required_flags() {
|
||||
let required: [(&str, &str); 3] = [
|
||||
("--eod-intraday", "intraday.bson"),
|
||||
("--out", "out_dir"),
|
||||
("--shards", "4"),
|
||||
];
|
||||
|
||||
for omit in 0..required.len() {
|
||||
let mut argv: Vec<&str> = vec!["curate-fx-1m"];
|
||||
for (idx, &(flag, val)) in required.iter().enumerate() {
|
||||
if idx != omit {
|
||||
argv.push(flag);
|
||||
argv.push(val);
|
||||
}
|
||||
}
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
let missing_flag = required[omit].0;
|
||||
assert!(
|
||||
err.contains(&format!("missing required flag '{missing_flag}'")),
|
||||
"expected missing required flag '{missing_flag}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_fx_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() {
|
||||
let base = [
|
||||
"curate-fx-1m",
|
||||
"--eod-intraday",
|
||||
"i.bson",
|
||||
"--out",
|
||||
"o",
|
||||
"--shards",
|
||||
"4",
|
||||
];
|
||||
|
||||
// Duplicate flags (path and numeric).
|
||||
for (flag, extra_val) in [
|
||||
("--eod-intraday", "i2.bson"),
|
||||
("--out", "o2"),
|
||||
("--shards", "2"),
|
||||
] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(flag);
|
||||
argv.push(extra_val);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("duplicate flag '{flag}'")),
|
||||
"expected duplicate error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Empty values via --flag=.
|
||||
for flag in ["--eod-intraday", "--out", "--shards"] {
|
||||
let empty_token = format!("{flag}=");
|
||||
let err = parse_args(&to_args(&["curate-fx-1m", &empty_token])).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("empty value for flag '{flag}'")),
|
||||
"expected empty value error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Flag at end of input or followed by another flag.
|
||||
let err = parse_args(&to_args(&["curate-fx-1m", "--eod-intraday"])).unwrap_err();
|
||||
assert!(
|
||||
err.contains("missing value for flag '--eod-intraday'"),
|
||||
"{err}"
|
||||
);
|
||||
let err = parse_args(&to_args(&["curate-fx-1m", "--shards", "--out", "o"])).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--shards'"), "{err}");
|
||||
|
||||
// Unknown flag.
|
||||
let mut unknown = base.to_vec();
|
||||
unknown.push("--nope");
|
||||
unknown.push("1");
|
||||
let err = parse_args(&to_args(&unknown)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("unknown flag '--nope' for curate-fx-1m"),
|
||||
"{err}"
|
||||
);
|
||||
|
||||
// Bars-only flags must be rejected as unknown flags.
|
||||
for (flag, val) in [
|
||||
("--qm-splits", "splits.bson"),
|
||||
("--provider-mapping", "mapping.tsv"),
|
||||
("--known-at-micros", "1735689600000000"),
|
||||
("--mapping-source", "eod"),
|
||||
] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(flag);
|
||||
argv.push(val);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains(&format!("unknown flag '{flag}' for curate-fx-1m")),
|
||||
"expected unknown flag error for {flag}, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
// Positional argument.
|
||||
let err = parse_args(&to_args(&["curate-fx-1m", "positional"])).unwrap_err();
|
||||
assert!(
|
||||
err.contains("unexpected positional argument 'positional' for curate-fx-1m"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_fx_1m_rejects_invalid_shards() {
|
||||
let base_without_shards = [
|
||||
"curate-fx-1m",
|
||||
"--eod-intraday",
|
||||
"i.bson",
|
||||
"--out",
|
||||
"o",
|
||||
];
|
||||
|
||||
for bad_shards in [
|
||||
"0",
|
||||
"-1",
|
||||
"+1",
|
||||
"1.5",
|
||||
"abc",
|
||||
"999999999999999999999999999999999999999",
|
||||
] {
|
||||
let mut argv = base_without_shards.to_vec();
|
||||
argv.push("--shards");
|
||||
argv.push(bad_shards);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert!(
|
||||
err.contains("invalid --shards"),
|
||||
"expected invalid --shards for '{bad_shards}', got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_curate_fx_1m_rejects_all_mongo_streaming_flags_without_echoing_values() {
|
||||
let mongo_flags = [
|
||||
"--from-mongo",
|
||||
"--mongo-uri",
|
||||
"--mongo-uri-env",
|
||||
"--batch-size",
|
||||
"--limit",
|
||||
"--date-gte",
|
||||
"--date-lt",
|
||||
"--with-qm-prices",
|
||||
];
|
||||
|
||||
let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock";
|
||||
for flag in mongo_flags {
|
||||
let expected = format!(
|
||||
"MongoDB streaming flag '{flag}' is not supported by curate-fx-1m (file mode only)"
|
||||
);
|
||||
|
||||
// Bare form (at end of argv).
|
||||
let err_bare = parse_args(&to_args(&["curate-fx-1m", flag])).unwrap_err();
|
||||
assert_eq!(err_bare, expected, "bare {flag} error mismatch");
|
||||
|
||||
// Separated value form.
|
||||
let err_sep = parse_args(&to_args(&["curate-fx-1m", flag, secret])).unwrap_err();
|
||||
assert_eq!(err_sep, expected, "separated {flag} error mismatch");
|
||||
assert!(
|
||||
!err_sep.contains("s3cr3t_pw"),
|
||||
"separated {flag} error leaked value: {err_sep}"
|
||||
);
|
||||
|
||||
// Equals form.
|
||||
let eq_token = format!("{flag}={secret}");
|
||||
let err_eq = parse_args(&to_args(&["curate-fx-1m", &eq_token])).unwrap_err();
|
||||
assert_eq!(err_eq, expected, "equals {flag} error mismatch");
|
||||
assert!(
|
||||
!err_eq.contains("s3cr3t_pw"),
|
||||
"equals {flag} error leaked value: {err_eq}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_posts_parsing_validation_and_usage() {
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ use crate::bson_eod_intraday::BsonEodIntradayDecodeStats;
|
|||
use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions};
|
||||
use crate::ilp::{IlpShardedWriter, IlpWriterError};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::split::SplitTable;
|
||||
use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable};
|
||||
|
||||
/// Accounting summary produced alongside [`CurateBars1mOutput::rows`].
|
||||
///
|
||||
|
|
@ -185,14 +185,36 @@ fn bar_1m_values_bit_eq(a: &Bar1mRow<i32>, b: &Bar1mRow<i32>) -> bool {
|
|||
&& a.session == b.session
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_valid_price(price: f64) -> bool {
|
||||
price.is_finite() && price > 0.0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool {
|
||||
high >= low && open >= low && open <= high && close >= low && close <= high
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decrement_builder_session_count(stats: &mut Bars1mStats, session: IntradaySession) {
|
||||
match session {
|
||||
IntradaySession::Pre => stats.pre_rows_out -= 1,
|
||||
IntradaySession::Rth => stats.rth_rows_out -= 1,
|
||||
IntradaySession::Post => stats.post_rows_out -= 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps source-keyed [`Bars1mBuild<K>`] rows to permanent `listing_id: i32` keys via
|
||||
/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in
|
||||
/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions.
|
||||
pub(crate) fn map_bars_1m<K>(
|
||||
/// `provider_mapping` on each bar's Eastern Time `session_date`, optionally un-adjusts OHLCV via
|
||||
/// `listing_splits` (keyed by permanent `listing_id`, preventing split leakage across reused
|
||||
/// tickers), stamps `source`, re-sorts in place by `(listing_id, ts)`, and compacts
|
||||
/// cross-`source_id` collisions.
|
||||
fn map_bars_1m_impl<K>(
|
||||
built: Bars1mBuild<K>,
|
||||
provider_mapping: &ProviderMappingTable,
|
||||
mapping_source: &str,
|
||||
source: &'static str,
|
||||
listing_splits: Option<&SplitTable<i32>>,
|
||||
) -> CurateBars1mOutput
|
||||
where
|
||||
K: Eq + AsRef<str>,
|
||||
|
|
@ -222,25 +244,84 @@ where
|
|||
continue;
|
||||
}
|
||||
|
||||
let mut key_kept_or_unmapped = false;
|
||||
for bar in &built.rows[run_start..run_end] {
|
||||
let Some(listing_id) = cursor.resolve(bar.session_date) else {
|
||||
stats.dropped_unmapped += 1;
|
||||
key_kept_or_unmapped = true;
|
||||
continue;
|
||||
};
|
||||
|
||||
let (open, high, low, close, volume) = if let Some(splits) = listing_splits {
|
||||
let factor = splits.cum_factor_after(&listing_id, bar.session_date);
|
||||
if factor != 1.0 {
|
||||
let mut unadj = unadjust_ohlcv(
|
||||
OhlcvBar {
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
},
|
||||
factor,
|
||||
);
|
||||
if !is_valid_price(unadj.open)
|
||||
|| !is_valid_price(unadj.high)
|
||||
|| !is_valid_price(unadj.low)
|
||||
|| !is_valid_price(unadj.close)
|
||||
{
|
||||
stats.builder.dropped_invalid_ohlc += 1;
|
||||
stats.builder.rows_out -= 1;
|
||||
decrement_builder_session_count(&mut stats.builder, bar.session);
|
||||
stats.rows_in -= 1;
|
||||
continue;
|
||||
}
|
||||
if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) {
|
||||
stats.builder.dropped_inconsistent_ohlc += 1;
|
||||
stats.builder.rows_out -= 1;
|
||||
decrement_builder_session_count(&mut stats.builder, bar.session);
|
||||
stats.rows_in -= 1;
|
||||
continue;
|
||||
}
|
||||
if !unadj.volume.is_finite()
|
||||
|| unadj.volume < 0.0
|
||||
|| (bar.volume > 0.0 && unadj.volume == 0.0)
|
||||
{
|
||||
stats.builder.dropped_invalid_volume += 1;
|
||||
stats.builder.rows_out -= 1;
|
||||
decrement_builder_session_count(&mut stats.builder, bar.session);
|
||||
stats.rows_in -= 1;
|
||||
continue;
|
||||
}
|
||||
if unadj.volume == 0.0 {
|
||||
unadj.volume = 0.0;
|
||||
}
|
||||
(unadj.open, unadj.high, unadj.low, unadj.close, unadj.volume)
|
||||
} else {
|
||||
(bar.open, bar.high, bar.low, bar.close, bar.volume)
|
||||
}
|
||||
} else {
|
||||
(bar.open, bar.high, bar.low, bar.close, bar.volume)
|
||||
};
|
||||
|
||||
key_kept_or_unmapped = true;
|
||||
rows.push(Bar1mRow {
|
||||
key: listing_id,
|
||||
ts: bar.ts,
|
||||
session_date: bar.session_date,
|
||||
open: bar.open,
|
||||
high: bar.high,
|
||||
low: bar.low,
|
||||
close: bar.close,
|
||||
volume: bar.volume,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
session: bar.session,
|
||||
source,
|
||||
});
|
||||
}
|
||||
|
||||
if !key_kept_or_unmapped {
|
||||
stats.builder.keys_out -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Free builder rows before sorting/compacting mapped rows to cut peak RAM.
|
||||
|
|
@ -306,6 +387,21 @@ where
|
|||
CurateBars1mOutput { rows, stats }
|
||||
}
|
||||
|
||||
/// Maps source-keyed [`Bars1mBuild<K>`] rows to permanent `listing_id: i32` keys via
|
||||
/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in
|
||||
/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions.
|
||||
pub(crate) fn map_bars_1m<K>(
|
||||
built: Bars1mBuild<K>,
|
||||
provider_mapping: &ProviderMappingTable,
|
||||
mapping_source: &str,
|
||||
source: &'static str,
|
||||
) -> CurateBars1mOutput
|
||||
where
|
||||
K: Eq + AsRef<str>,
|
||||
{
|
||||
map_bars_1m_impl(built, provider_mapping, mapping_source, source, None)
|
||||
}
|
||||
|
||||
/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via
|
||||
/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through
|
||||
/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow<i32>`]
|
||||
|
|
@ -389,6 +485,51 @@ where
|
|||
})
|
||||
}
|
||||
|
||||
/// Variant of [`curate_and_write_bars_1m`] that takes a [`SplitTable<i32>`] keyed by permanent
|
||||
/// `listing_id` and resolves `(mapping_source, source_id, session_date) -> listing_id` on each
|
||||
/// bar's Eastern Time `session_date` **before** applying split un-adjustment.
|
||||
///
|
||||
/// This prevents split leakage across reused tickers (e.g., `FB.US` listing 10 through June 2022
|
||||
/// vs. listing 20 starting in 2025) while preserving all [`CurateBars1mStats`] conservation
|
||||
/// invariants and cross-`source_id` collision handling.
|
||||
pub(crate) fn curate_and_write_bars_1m_by_listing<W, K, B>(
|
||||
bars: B,
|
||||
listing_splits: &SplitTable<i32>,
|
||||
provider_mapping: &ProviderMappingTable,
|
||||
mapping_source: &str,
|
||||
writer: &mut IlpShardedWriter<W>,
|
||||
known_at_micros: i64,
|
||||
) -> Result<CurateBars1mWriteReport, CurateBars1mWriteError>
|
||||
where
|
||||
W: Write + Send,
|
||||
K: Ord + Eq + Hash + Clone + AsRef<str>,
|
||||
B: IntoIterator<Item = EodIntradayBar<K>>,
|
||||
{
|
||||
if mapping_source.trim().is_empty() {
|
||||
return Err(CurateBars1mError::EmptyMappingSource.into());
|
||||
}
|
||||
|
||||
let empty_splits: SplitTable<K> = SplitTable::default();
|
||||
let built = build_bars_1m(bars, &empty_splits);
|
||||
let curated = map_bars_1m_impl(
|
||||
built,
|
||||
provider_mapping,
|
||||
mapping_source,
|
||||
BARS_1M_SOURCE_EOD,
|
||||
Some(listing_splits),
|
||||
);
|
||||
let mut rows_written = 0usize;
|
||||
for row in &curated.rows {
|
||||
writer.write_bar_1m(row, known_at_micros)?;
|
||||
rows_written += 1;
|
||||
}
|
||||
|
||||
Ok(CurateBars1mWriteReport {
|
||||
curate_stats: curated.stats,
|
||||
rows_written,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`],
|
||||
/// converts each valid document via [`crate::bson_eod_intraday::RawEodIntradayBar::into_eod_intraday_bar`],
|
||||
/// and runs [`curate_and_write_bars_1m`] against the caller-owned [`IlpShardedWriter`].
|
||||
|
|
|
|||
|
|
@ -458,6 +458,13 @@ impl<W: Write + Send> IlpShardedWriter<W> {
|
|||
self.shards.len()
|
||||
}
|
||||
|
||||
/// Returns `(flushed_rows, pending_rows)` across all shards.
|
||||
#[inline]
|
||||
pub(crate) fn row_counts(&self) -> (usize, usize) {
|
||||
let pending = self.shards.iter().map(|s| s.pending_rows).sum();
|
||||
(self.rows_written, pending)
|
||||
}
|
||||
|
||||
/// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`.
|
||||
pub fn write_bar_1m(
|
||||
&mut self,
|
||||
|
|
|
|||
851
tools/curate-etl/src/ilp_send.rs
Normal file
851
tools/curate-etl/src/ilp_send.rs
Normal file
|
|
@ -0,0 +1,851 @@
|
|||
//! Multi-socket QuestDB ILP v2 shard-file sender (`M2.3p`).
|
||||
//!
|
||||
//! Streams published `<prefix>.shard-<NN>.ilp` files (produced by [`crate::run_curate_bars_1m`],
|
||||
//! [`crate::run_curate_qm_bars_1m`], or [`crate::run_curate_fx_1m`]) verbatim over one dedicated
|
||||
//! sink/socket per shard using `std::thread::scope`.
|
||||
//!
|
||||
//! # Transport & Acknowledgement Semantics
|
||||
//!
|
||||
//! - **No server acknowledgement over TCP:** QuestDB's TCP ILP listener sends no per-row or
|
||||
//! per-batch acknowledgement. A server-side parse error or schema rejection surfaces only as a
|
||||
//! dropped connection or missing rows. A successful [`send_ilp_shard_files`] return therefore
|
||||
//! means **"all bytes were accepted by the local socket and write-half shutdown succeeded"**,
|
||||
//! not **"all rows were committed in QuestDB"**. Verify row counts and representative values
|
||||
//! separately via PGWire after loading.
|
||||
//! - **Protocol Version 2 binary doubles over TCP (unverified for QuestDB `10.2.0`):** QuestDB's
|
||||
//! ILP transport documentation (<https://questdb.com/docs/connect/compatibility/ilp/overview/>)
|
||||
//! documents explicit client-side protocol-version-2 selection for TCP without autodetection.
|
||||
//! Exact QuestDB `10.2.0` acceptance of this crate's ILP v2 binary `DOUBLE` payloads (`0x10` +
|
||||
//! 8-byte LE IEEE-754) on the TCP ILP port (default `9009`) without a handshake is
|
||||
//! **unverified** — confirm it in the manual `quant` load check using PGWire row counts and
|
||||
//! spot-checked OHLCV/FX values before bulk ingestion.
|
||||
//!
|
||||
//! # Data Ownership, Discovery & Replay Semantics
|
||||
//!
|
||||
//! - **Completed publisher output required:** [`discover_ilp_shard_files`] consumes a completed,
|
||||
//! immutable publisher output directory. Filenames alone cannot detect an in-progress
|
||||
//! publication or a missing trailing shard.
|
||||
//! - **Byte-for-byte streaming:** Bytes are streamed verbatim in fixed-size chunks
|
||||
//! (`IlpSendOptions::buffer_bytes`) without loading whole files into RAM and without splitting,
|
||||
//! re-framing, or re-encoding lines (binary `f64` fields may legitimately contain `0x0A`).
|
||||
//! - **Per-key ordering & idempotent resend:** Quant data curation owns the curated shard files
|
||||
//! as the durable replay baseline for OHLCV, FX values, timestamps, `known_at`, and per-key
|
||||
//! ordering (`design/DATA-CONTRACTS.md` §3.B, `design/MILESTONES.md` M2). Because each shard
|
||||
//! streams over a single dedicated sink in file order, per-key ordering is preserved. On any
|
||||
//! shard failure, [`IlpSendError::ShardIo`] includes a partial [`IlpSendReport`] with per-shard
|
||||
//! `bytes_sent` so operators can re-send the full, identical shard set against QuestDB's
|
||||
//! configured `DEDUP UPSERT KEYS(ts, listing_id)` (`bars_1m`) or `DEDUP UPSERT KEYS(ts, pair)`
|
||||
//! (`fx_1m`). Avoid replaying stale shard files after newer data sharing the same upsert keys
|
||||
//! has been ingested.
|
||||
//! - **Resource scaling:** Threads, open sockets, and read-buffer memory scale linearly with
|
||||
//! shard count (`shard_count * buffer_bytes`).
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::run_curate_bars_1m::is_final_shard_file_name_for_table;
|
||||
|
||||
/// Default per-shard streaming read buffer size (64 KiB).
|
||||
pub const DEFAULT_ILP_SEND_BUFFER_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Default TCP connect timeout per shard socket (10 seconds).
|
||||
pub const DEFAULT_ILP_TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Default TCP write timeout per shard socket (30 seconds).
|
||||
pub const DEFAULT_ILP_TCP_WRITE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// A discovered, validated published ILP shard file (`<prefix>.shard-<digits>.ilp`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct IlpShardFile {
|
||||
pub shard: usize,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
/// Streaming options for [`send_ilp_shard_files`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct IlpSendOptions {
|
||||
/// Fixed-size read buffer allocated per shard worker (must be `> 0`).
|
||||
pub buffer_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for IlpSendOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
buffer_bytes: DEFAULT_ILP_SEND_BUFFER_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Socket options for [`tcp_ilp_connector`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct IlpTcpOptions {
|
||||
/// Connect timeout applied to each shard socket (must be `> Duration::ZERO`).
|
||||
pub connect_timeout: Duration,
|
||||
/// Write timeout applied to each shard socket (must be `> Duration::ZERO`).
|
||||
pub write_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for IlpTcpOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
connect_timeout: DEFAULT_ILP_TCP_CONNECT_TIMEOUT,
|
||||
write_timeout: DEFAULT_ILP_TCP_WRITE_TIMEOUT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-shard delivery summary recorded in [`IlpSendReport`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct IlpShardSendReport {
|
||||
pub shard: usize,
|
||||
pub path: PathBuf,
|
||||
pub bytes_sent: u64,
|
||||
}
|
||||
|
||||
/// Delivery summary returned by [`send_ilp_shard_files`] (and attached as a partial report on
|
||||
/// [`IlpSendError::ShardIo`]).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct IlpSendReport {
|
||||
pub shards: Vec<IlpShardSendReport>,
|
||||
pub total_shards: usize,
|
||||
pub total_bytes_sent: u64,
|
||||
}
|
||||
|
||||
/// Operation stage in which a per-shard I/O failure occurred.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum IlpSendOp {
|
||||
SpawnWorker,
|
||||
OpenFile,
|
||||
Connect,
|
||||
Read,
|
||||
Write,
|
||||
Flush,
|
||||
}
|
||||
|
||||
impl fmt::Display for IlpSendOp {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
Self::SpawnWorker => f.write_str("spawn_worker"),
|
||||
Self::OpenFile => f.write_str("open_file"),
|
||||
Self::Connect => f.write_str("connect"),
|
||||
Self::Read => f.write_str("read"),
|
||||
Self::Write => f.write_str("write"),
|
||||
Self::Flush => f.write_str("flush"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`discover_ilp_shard_files`], [`send_ilp_shard_files`], and
|
||||
/// [`tcp_ilp_connector`].
|
||||
#[derive(Debug)]
|
||||
pub enum IlpSendError {
|
||||
/// Shard prefix was empty or contained characters outside `[A-Za-z0-9_-]`.
|
||||
InvalidPrefix { prefix: String },
|
||||
/// Target directory exists but is not a directory.
|
||||
InvalidDirectory { path: PathBuf, detail: String },
|
||||
/// Failed to stat or read the shard directory.
|
||||
ReadDir { path: PathBuf, source: io::Error },
|
||||
/// No `<prefix>.shard-<digits>.ilp` files matched in `dir`.
|
||||
NoShardFiles { dir: PathBuf, prefix: String },
|
||||
/// A matching shard file's numeric suffix overflowed `usize`.
|
||||
ShardIndexOverflow { path: PathBuf, digits: String },
|
||||
/// A matching entry was not a regular file (for example, a directory or symlink).
|
||||
NotRegularFile { path: PathBuf, detail: String },
|
||||
/// Two matching files resolved to the same numeric shard index (e.g. `shard-0` and `shard-00`).
|
||||
DuplicateShardIndex {
|
||||
shard: usize,
|
||||
first: PathBuf,
|
||||
second: PathBuf,
|
||||
},
|
||||
/// Discovered shard indices did not form a contiguous `0..n` sequence.
|
||||
MissingShardIndex {
|
||||
expected: usize,
|
||||
found: usize,
|
||||
path: PathBuf,
|
||||
},
|
||||
/// `IlpSendOptions::buffer_bytes` was zero.
|
||||
ZeroBufferBytes,
|
||||
/// TCP target address was empty, malformed, or could not be resolved.
|
||||
InvalidAddress { addr: String, detail: String },
|
||||
/// A TCP timeout option was zero.
|
||||
InvalidTimeout { field: &'static str },
|
||||
/// One or more shards failed during open, connect, read, write, or flush.
|
||||
///
|
||||
/// `op`, `shard`, `path`, and `source` identify the lowest-index failing shard;
|
||||
/// `partial_report` records `bytes_sent` for every shard after all workers finish.
|
||||
ShardIo {
|
||||
op: IlpSendOp,
|
||||
shard: usize,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
partial_report: IlpSendReport,
|
||||
},
|
||||
}
|
||||
|
||||
impl IlpSendError {
|
||||
/// Returns the partial delivery report when this error is [`IlpSendError::ShardIo`].
|
||||
pub fn partial_report(&self) -> Option<&IlpSendReport> {
|
||||
match self {
|
||||
Self::ShardIo { partial_report, .. } => Some(partial_report),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for IlpSendError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidPrefix { prefix } => write!(
|
||||
f,
|
||||
"invalid ILP shard prefix {prefix:?}: must be non-empty ASCII [A-Za-z0-9_-]"
|
||||
),
|
||||
Self::InvalidDirectory { path, detail } => {
|
||||
write!(f, "invalid ILP shard directory '{}': {detail}", path.display())
|
||||
}
|
||||
Self::ReadDir { path, source } => {
|
||||
write!(f, "failed to read ILP shard directory '{}': {source}", path.display())
|
||||
}
|
||||
Self::NoShardFiles { dir, prefix } => write!(
|
||||
f,
|
||||
"no ILP shard files matching '{prefix}.shard-<digits>.ilp' in '{}'",
|
||||
dir.display()
|
||||
),
|
||||
Self::ShardIndexOverflow { path, digits } => write!(
|
||||
f,
|
||||
"ILP shard index '{digits}' overflows usize in '{}'",
|
||||
path.display()
|
||||
),
|
||||
Self::NotRegularFile { path, detail } => write!(
|
||||
f,
|
||||
"ILP shard path '{}' is not a regular file: {detail}",
|
||||
path.display()
|
||||
),
|
||||
Self::DuplicateShardIndex {
|
||||
shard,
|
||||
first,
|
||||
second,
|
||||
} => write!(
|
||||
f,
|
||||
"duplicate ILP shard index {shard}: '{}' and '{}'",
|
||||
first.display(),
|
||||
second.display()
|
||||
),
|
||||
Self::MissingShardIndex {
|
||||
expected,
|
||||
found,
|
||||
path,
|
||||
} => write!(
|
||||
f,
|
||||
"missing ILP shard index {expected}: next shard is {found} ('{}')",
|
||||
path.display()
|
||||
),
|
||||
Self::ZeroBufferBytes => write!(f, "ILP send buffer_bytes must be > 0"),
|
||||
Self::InvalidAddress { addr, detail } => {
|
||||
write!(f, "invalid ILP TCP address {addr:?}: {detail}")
|
||||
}
|
||||
Self::InvalidTimeout { field } => {
|
||||
write!(f, "ILP TCP {field} must be > 0")
|
||||
}
|
||||
Self::ShardIo {
|
||||
op,
|
||||
shard,
|
||||
path,
|
||||
source,
|
||||
partial_report,
|
||||
} => write!(
|
||||
f,
|
||||
"ILP shard {shard} ('{}') failed during {op} ({source}; total_bytes_sent={})",
|
||||
path.display(),
|
||||
partial_report.total_bytes_sent
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for IlpSendError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::ReadDir { source, .. } | Self::ShardIo { source, .. } => Some(source),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates that `prefix` is non-empty and consists solely of ASCII letters, digits, `_`, or `-`.
|
||||
fn validate_prefix(prefix: &str) -> Result<(), IlpSendError> {
|
||||
if prefix.is_empty()
|
||||
|| !prefix
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|
||||
{
|
||||
return Err(IlpSendError::InvalidPrefix {
|
||||
prefix: prefix.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Discovers published `<prefix>.shard-<digits>.ilp` files in a completed output directory `dir`.
|
||||
///
|
||||
/// Files are returned sorted by ascending numeric shard index `0..n`. Fails closed on:
|
||||
/// - blank or invalid `prefix` (must match `[A-Za-z0-9_-]+`),
|
||||
/// - missing or non-directory `dir`,
|
||||
/// - zero matching files,
|
||||
/// - any matching entry that is not a regular file (including symlinks and directories),
|
||||
/// - numeric shard suffix overflowing `usize`,
|
||||
/// - duplicate numeric shard indices (e.g. `shard-0` and `shard-00`), or
|
||||
/// - any gap in `0..n`.
|
||||
pub fn discover_ilp_shard_files(
|
||||
dir: &Path,
|
||||
prefix: &str,
|
||||
) -> Result<Vec<IlpShardFile>, IlpSendError> {
|
||||
validate_prefix(prefix)?;
|
||||
|
||||
let dir_meta = fs::metadata(dir).map_err(|source| IlpSendError::ReadDir {
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
if !dir_meta.is_dir() {
|
||||
return Err(IlpSendError::InvalidDirectory {
|
||||
path: dir.to_path_buf(),
|
||||
detail: "path exists and is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let entries = fs::read_dir(dir).map_err(|source| IlpSendError::ReadDir {
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let mut discovered: Vec<IlpShardFile> = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|source| IlpSendError::ReadDir {
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let file_name = entry.file_name();
|
||||
if !is_final_shard_file_name_for_table(prefix, &file_name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = entry.path();
|
||||
let meta = fs::symlink_metadata(&path).map_err(|source| IlpSendError::ReadDir {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let file_type = meta.file_type();
|
||||
if file_type.is_symlink() {
|
||||
return Err(IlpSendError::NotRegularFile {
|
||||
path,
|
||||
detail: "entry is a symlink".to_string(),
|
||||
});
|
||||
}
|
||||
if !file_type.is_file() {
|
||||
let detail = if file_type.is_dir() {
|
||||
"entry is a directory"
|
||||
} else {
|
||||
"entry is not a regular file"
|
||||
};
|
||||
return Err(IlpSendError::NotRegularFile {
|
||||
path,
|
||||
detail: detail.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let name_str = file_name
|
||||
.to_str()
|
||||
.expect("is_final_shard_file_name_for_table guarantees valid UTF-8");
|
||||
let digits = name_str
|
||||
.strip_prefix(prefix)
|
||||
.and_then(|s| s.strip_prefix(".shard-"))
|
||||
.and_then(|s| s.strip_suffix(".ilp"))
|
||||
.expect("is_final_shard_file_name_for_table guarantees shard filename shape");
|
||||
|
||||
let shard = digits
|
||||
.parse::<usize>()
|
||||
.map_err(|_| IlpSendError::ShardIndexOverflow {
|
||||
path: path.clone(),
|
||||
digits: digits.to_string(),
|
||||
})?;
|
||||
|
||||
discovered.push(IlpShardFile { shard, path });
|
||||
}
|
||||
|
||||
if discovered.is_empty() {
|
||||
return Err(IlpSendError::NoShardFiles {
|
||||
dir: dir.to_path_buf(),
|
||||
prefix: prefix.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
discovered.sort_by(|a, b| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path)));
|
||||
|
||||
for pair in discovered.windows(2) {
|
||||
if pair[0].shard == pair[1].shard {
|
||||
return Err(IlpSendError::DuplicateShardIndex {
|
||||
shard: pair[0].shard,
|
||||
first: pair[0].path.clone(),
|
||||
second: pair[1].path.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (expected, item) in discovered.iter().enumerate() {
|
||||
if item.shard != expected {
|
||||
return Err(IlpSendError::MissingShardIndex {
|
||||
expected,
|
||||
found: item.shard,
|
||||
path: item.path.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(discovered)
|
||||
}
|
||||
|
||||
/// Streams each shard file in `files` verbatim to its own sink opened via `connector`, running one
|
||||
/// scoped worker thread per shard.
|
||||
///
|
||||
/// Guarantees:
|
||||
/// - Rejects `options.buffer_bytes == 0` before any file open or `connector` call.
|
||||
/// - Opens each shard file before calling `connector(file.shard)`.
|
||||
/// - Uses one reusable fixed-size read buffer per worker; never loads a whole file into memory and
|
||||
/// never splits or re-encodes bytes.
|
||||
/// - Calls `flush()` exactly once at EOF on every opened sink, including zero-length shard files.
|
||||
/// - Joins every worker before returning; fails closed with [`IlpSendError::ShardIo`] carrying
|
||||
/// the failing shard index, path, operation, `io::Error`, and full per-shard partial report if
|
||||
/// any shard errors.
|
||||
pub fn send_ilp_shard_files<W, C>(
|
||||
files: &[IlpShardFile],
|
||||
connector: C,
|
||||
options: IlpSendOptions,
|
||||
) -> Result<IlpSendReport, IlpSendError>
|
||||
where
|
||||
W: Write + Send,
|
||||
C: Fn(usize) -> io::Result<W> + Sync,
|
||||
{
|
||||
if options.buffer_bytes == 0 {
|
||||
return Err(IlpSendError::ZeroBufferBytes);
|
||||
}
|
||||
|
||||
if files.is_empty() {
|
||||
return Ok(IlpSendReport {
|
||||
shards: Vec::new(),
|
||||
total_shards: 0,
|
||||
total_bytes_sent: 0,
|
||||
});
|
||||
}
|
||||
|
||||
let connector_ref = &connector;
|
||||
let buffer_bytes = options.buffer_bytes;
|
||||
|
||||
let outcomes: Vec<ShardWorkerOutcome> = thread::scope(|scope| {
|
||||
enum WorkerSlot<'scope> {
|
||||
Running(thread::ScopedJoinHandle<'scope, ShardWorkerOutcome>),
|
||||
SpawnFailed(io::Error),
|
||||
}
|
||||
|
||||
let mut slots = Vec::with_capacity(files.len());
|
||||
for shard_file in files {
|
||||
let spawned = thread::Builder::new()
|
||||
.name(format!("ilp-send-shard-{}", shard_file.shard))
|
||||
.spawn_scoped(scope, move || {
|
||||
send_single_shard(shard_file, connector_ref, buffer_bytes)
|
||||
});
|
||||
match spawned {
|
||||
Ok(handle) => slots.push(WorkerSlot::Running(handle)),
|
||||
Err(err) => slots.push(WorkerSlot::SpawnFailed(err)),
|
||||
}
|
||||
}
|
||||
|
||||
let mut results = Vec::with_capacity(slots.len());
|
||||
let mut first_panic = None;
|
||||
for slot in slots {
|
||||
match slot {
|
||||
WorkerSlot::Running(handle) => match handle.join() {
|
||||
Ok(outcome) => results.push(outcome),
|
||||
Err(payload) => {
|
||||
if first_panic.is_none() {
|
||||
first_panic = Some(payload);
|
||||
}
|
||||
}
|
||||
},
|
||||
WorkerSlot::SpawnFailed(err) => results.push(ShardWorkerOutcome {
|
||||
bytes_sent: 0,
|
||||
failure: Some((IlpSendOp::SpawnWorker, err)),
|
||||
}),
|
||||
}
|
||||
}
|
||||
if let Some(payload) = first_panic {
|
||||
std::panic::resume_unwind(payload);
|
||||
}
|
||||
results
|
||||
});
|
||||
|
||||
let mut ordered: Vec<(&IlpShardFile, ShardWorkerOutcome)> =
|
||||
files.iter().zip(outcomes).collect();
|
||||
ordered.sort_by(|(a, _), (b, _)| a.shard.cmp(&b.shard).then_with(|| a.path.cmp(&b.path)));
|
||||
|
||||
let mut shard_reports = Vec::with_capacity(ordered.len());
|
||||
let mut total_bytes_sent: u64 = 0;
|
||||
let mut first_failure: Option<(IlpSendOp, usize, PathBuf, io::Error)> = None;
|
||||
|
||||
for (shard_file, outcome) in ordered {
|
||||
total_bytes_sent = total_bytes_sent.saturating_add(outcome.bytes_sent);
|
||||
shard_reports.push(IlpShardSendReport {
|
||||
shard: shard_file.shard,
|
||||
path: shard_file.path.clone(),
|
||||
bytes_sent: outcome.bytes_sent,
|
||||
});
|
||||
if first_failure.is_none() {
|
||||
if let Some((op, source)) = outcome.failure {
|
||||
first_failure = Some((op, shard_file.shard, shard_file.path.clone(), source));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let report = IlpSendReport {
|
||||
total_shards: shard_reports.len(),
|
||||
total_bytes_sent,
|
||||
shards: shard_reports,
|
||||
};
|
||||
|
||||
if let Some((op, shard, path, source)) = first_failure {
|
||||
return Err(IlpSendError::ShardIo {
|
||||
op,
|
||||
shard,
|
||||
path,
|
||||
source,
|
||||
partial_report: report,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
struct ShardWorkerOutcome {
|
||||
bytes_sent: u64,
|
||||
failure: Option<(IlpSendOp, io::Error)>,
|
||||
}
|
||||
|
||||
fn send_single_shard<W, C>(
|
||||
shard_file: &IlpShardFile,
|
||||
connector: &C,
|
||||
buffer_bytes: usize,
|
||||
) -> ShardWorkerOutcome
|
||||
where
|
||||
W: Write,
|
||||
C: Fn(usize) -> io::Result<W>,
|
||||
{
|
||||
let mut file = match File::open(&shard_file.path) {
|
||||
Ok(file) => file,
|
||||
Err(err) => {
|
||||
return ShardWorkerOutcome {
|
||||
bytes_sent: 0,
|
||||
failure: Some((IlpSendOp::OpenFile, err)),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let mut sink = match connector(shard_file.shard) {
|
||||
Ok(sink) => sink,
|
||||
Err(err) => {
|
||||
return ShardWorkerOutcome {
|
||||
bytes_sent: 0,
|
||||
failure: Some((IlpSendOp::Connect, err)),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let mut buf = vec![0u8; buffer_bytes];
|
||||
let mut bytes_sent: u64 = 0;
|
||||
|
||||
loop {
|
||||
let read_len = match file.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => n,
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => {
|
||||
return ShardWorkerOutcome {
|
||||
bytes_sent,
|
||||
failure: Some((IlpSendOp::Read, err)),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
let mut offset = 0usize;
|
||||
while offset < read_len {
|
||||
match sink.write(&buf[offset..read_len]) {
|
||||
Ok(0) => {
|
||||
return ShardWorkerOutcome {
|
||||
bytes_sent,
|
||||
failure: Some((
|
||||
IlpSendOp::Write,
|
||||
io::Error::new(
|
||||
io::ErrorKind::WriteZero,
|
||||
"sink returned Ok(0) on non-empty write",
|
||||
),
|
||||
)),
|
||||
};
|
||||
}
|
||||
Ok(written) => {
|
||||
offset += written;
|
||||
bytes_sent += written as u64;
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => {
|
||||
return ShardWorkerOutcome {
|
||||
bytes_sent,
|
||||
failure: Some((IlpSendOp::Write, err)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
match sink.flush() {
|
||||
Ok(()) => break,
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => {
|
||||
return ShardWorkerOutcome {
|
||||
bytes_sent,
|
||||
failure: Some((IlpSendOp::Flush, err)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ShardWorkerOutcome {
|
||||
bytes_sent,
|
||||
failure: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`TcpStream`] wrapper whose [`Write::flush`] flushes the stream and performs a write-side
|
||||
/// half-close (`shutdown(Shutdown::Write)`) so the peer observes clean EOF.
|
||||
#[derive(Debug)]
|
||||
pub struct IlpTcpSink {
|
||||
stream: TcpStream,
|
||||
}
|
||||
|
||||
impl IlpTcpSink {
|
||||
/// Wraps a connected [`TcpStream`].
|
||||
pub fn new(stream: TcpStream) -> Self {
|
||||
Self { stream }
|
||||
}
|
||||
|
||||
/// Borrows the underlying [`TcpStream`].
|
||||
pub fn inner(&self) -> &TcpStream {
|
||||
&self.stream
|
||||
}
|
||||
|
||||
/// Unwraps and returns the underlying [`TcpStream`].
|
||||
pub fn into_inner(self) -> TcpStream {
|
||||
self.stream
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for IlpTcpSink {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.stream.write(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.stream.flush()?;
|
||||
self.stream.shutdown(Shutdown::Write)
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates and resolves `addr` into one or more [`SocketAddr`]s without performing DNS lookups
|
||||
/// on syntactically malformed inputs.
|
||||
fn resolve_tcp_addr(addr: &str) -> Result<Vec<SocketAddr>, IlpSendError> {
|
||||
if addr.is_empty() || addr.trim() != addr {
|
||||
return Err(IlpSendError::InvalidAddress {
|
||||
addr: addr.to_string(),
|
||||
detail: "address must be non-empty without surrounding whitespace".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Ok(sock_addr) = addr.parse::<SocketAddr>() {
|
||||
return Ok(vec![sock_addr]);
|
||||
}
|
||||
|
||||
let Some((host, port_str)) = addr.rsplit_once(':') else {
|
||||
return Err(IlpSendError::InvalidAddress {
|
||||
addr: addr.to_string(),
|
||||
detail: "expected 'host:port'".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
if host.is_empty()
|
||||
|| host
|
||||
.bytes()
|
||||
.any(|b| b.is_ascii_whitespace() || b.is_ascii_control())
|
||||
{
|
||||
return Err(IlpSendError::InvalidAddress {
|
||||
addr: addr.to_string(),
|
||||
detail: "host component is empty or contains invalid characters".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
if port_str.is_empty() || port_str.parse::<u16>().is_err() {
|
||||
return Err(IlpSendError::InvalidAddress {
|
||||
addr: addr.to_string(),
|
||||
detail: "port must be a valid u16".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let resolved: Vec<SocketAddr> = addr
|
||||
.to_socket_addrs()
|
||||
.map_err(|err| IlpSendError::InvalidAddress {
|
||||
addr: addr.to_string(),
|
||||
detail: format!("failed to resolve address: {err}"),
|
||||
})?
|
||||
.collect();
|
||||
|
||||
if resolved.is_empty() {
|
||||
return Err(IlpSendError::InvalidAddress {
|
||||
addr: addr.to_string(),
|
||||
detail: "address resolved to zero socket addresses".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn connect_tcp_sink(
|
||||
sock_addr: &SocketAddr,
|
||||
connect_timeout: Duration,
|
||||
write_timeout: Duration,
|
||||
) -> io::Result<IlpTcpSink> {
|
||||
let stream = TcpStream::connect_timeout(sock_addr, connect_timeout)?;
|
||||
stream.set_nodelay(true)?;
|
||||
stream.set_write_timeout(Some(write_timeout))?;
|
||||
Ok(IlpTcpSink::new(stream))
|
||||
}
|
||||
|
||||
fn tcp_ilp_connector_for_addrs(
|
||||
resolved: Vec<SocketAddr>,
|
||||
options: IlpTcpOptions,
|
||||
) -> Result<impl Fn(usize) -> io::Result<IlpTcpSink>, IlpSendError> {
|
||||
if options.connect_timeout.is_zero() {
|
||||
return Err(IlpSendError::InvalidTimeout {
|
||||
field: "connect_timeout",
|
||||
});
|
||||
}
|
||||
if options.write_timeout.is_zero() {
|
||||
return Err(IlpSendError::InvalidTimeout {
|
||||
field: "write_timeout",
|
||||
});
|
||||
}
|
||||
|
||||
let connect_timeout = options.connect_timeout;
|
||||
let write_timeout = options.write_timeout;
|
||||
// Pin one resolved endpoint for the lifetime of this connector so shards can never silently
|
||||
// split a single load across two different QuestDB instances if a hostname resolves to
|
||||
// multiple addresses.
|
||||
let pinned_addr: Mutex<Option<SocketAddr>> = Mutex::new(None);
|
||||
|
||||
Ok(move |_shard: usize| -> io::Result<IlpTcpSink> {
|
||||
let already_pinned = {
|
||||
let guard = pinned_addr
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
*guard
|
||||
};
|
||||
|
||||
if let Some(sock_addr) = already_pinned {
|
||||
return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout);
|
||||
}
|
||||
|
||||
let mut guard = pinned_addr
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(sock_addr) = *guard {
|
||||
drop(guard);
|
||||
return connect_tcp_sink(&sock_addr, connect_timeout, write_timeout);
|
||||
}
|
||||
|
||||
let mut last_err: Option<io::Error> = None;
|
||||
for sock_addr in &resolved {
|
||||
match TcpStream::connect_timeout(sock_addr, connect_timeout) {
|
||||
Ok(stream) => {
|
||||
*guard = Some(*sock_addr);
|
||||
drop(guard);
|
||||
stream.set_nodelay(true)?;
|
||||
stream.set_write_timeout(Some(write_timeout))?;
|
||||
return Ok(IlpTcpSink::new(stream));
|
||||
}
|
||||
Err(err) => {
|
||||
last_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_err.unwrap_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::AddrNotAvailable,
|
||||
"no resolved socket addresses available",
|
||||
)
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds a thread-safe TCP connector for [`send_ilp_shard_files`].
|
||||
///
|
||||
/// Validates `options` and resolves `addr` once before returning the connector closure so invalid
|
||||
/// addresses fail closed before any connection attempt. Pins a single resolved [`SocketAddr`] for
|
||||
/// all shards so a load can never split across multiple backend instances. Each shard invocation
|
||||
/// opens a fresh [`TcpStream`] with `connect_timeout`, `set_nodelay(true)`, and `write_timeout`,
|
||||
/// wrapped in [`IlpTcpSink`] so the sender's final `flush()` half-closes the write side
|
||||
/// (`Shutdown::Write`).
|
||||
pub fn tcp_ilp_connector(
|
||||
addr: &str,
|
||||
options: IlpTcpOptions,
|
||||
) -> Result<impl Fn(usize) -> io::Result<IlpTcpSink>, IlpSendError> {
|
||||
if options.connect_timeout.is_zero() {
|
||||
return Err(IlpSendError::InvalidTimeout {
|
||||
field: "connect_timeout",
|
||||
});
|
||||
}
|
||||
if options.write_timeout.is_zero() {
|
||||
return Err(IlpSendError::InvalidTimeout {
|
||||
field: "write_timeout",
|
||||
});
|
||||
}
|
||||
|
||||
let resolved = resolve_tcp_addr(addr)?;
|
||||
tcp_ilp_connector_for_addrs(resolved, options)
|
||||
}
|
||||
|
||||
/// Formats [`IlpSendReport`] into a deterministic machine-readable `key=value` summary in the
|
||||
/// style of the crate's `format_curate_*_report` helpers.
|
||||
pub fn format_ilp_send_report(report: &IlpSendReport) -> String {
|
||||
let per_shard = if report.shards.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
report
|
||||
.shards
|
||||
.iter()
|
||||
.map(|entry| format!("{:02}={}", entry.shard, entry.bytes_sent))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
};
|
||||
|
||||
format!(
|
||||
"curate-etl ilp-send\n\
|
||||
\x20 ilp_send: shards={} total_bytes_sent={} per_shard_bytes={per_shard}",
|
||||
report.total_shards, report.total_bytes_sent,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ilp_send_tests.rs"]
|
||||
mod tests;
|
||||
1302
tools/curate-etl/src/ilp_send_tests.rs
Normal file
1302
tools/curate-etl/src/ilp_send_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -22,6 +22,7 @@ pub mod events;
|
|||
pub mod fundamentals;
|
||||
pub mod fx;
|
||||
pub mod ilp;
|
||||
pub mod ilp_send;
|
||||
pub mod macro_series;
|
||||
pub mod mongo_safety;
|
||||
pub mod mongo_stream;
|
||||
|
|
@ -105,7 +106,8 @@ pub use bson_stream::{
|
|||
decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_financials_chunks,
|
||||
decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream,
|
||||
decode_qm_price_chunks, decode_qm_price_stream, decode_qm_split_chunks,
|
||||
decode_qm_split_stream, decode_te_market_data_chunks, decode_te_market_data_stream,
|
||||
decode_qm_split_stream, decode_te_data_chunks, decode_te_data_stream,
|
||||
decode_te_market_data_chunks, decode_te_market_data_stream,
|
||||
BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError,
|
||||
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk,
|
||||
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
|
|
@ -155,6 +157,12 @@ pub use ilp::{
|
|||
DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS,
|
||||
FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M,
|
||||
};
|
||||
pub use ilp_send::{
|
||||
discover_ilp_shard_files, format_ilp_send_report, send_ilp_shard_files, tcp_ilp_connector,
|
||||
IlpSendError, IlpSendOp, IlpSendOptions, IlpSendReport, IlpShardFile, IlpShardSendReport,
|
||||
IlpTcpOptions, IlpTcpSink, DEFAULT_ILP_SEND_BUFFER_BYTES, DEFAULT_ILP_TCP_CONNECT_TIMEOUT,
|
||||
DEFAULT_ILP_TCP_WRITE_TIMEOUT,
|
||||
};
|
||||
pub use macro_series::{
|
||||
build_macro_rows, MacroBuild, MacroBuildStats, MacroError, MacroLagClass, MacroObservation,
|
||||
MacroRow, GDP65_LAG_DAYS, GDP90_LAG_DAYS, MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS,
|
||||
|
|
@ -326,6 +334,26 @@ pub use run_curate_bars::{
|
|||
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_bars_1m;
|
||||
pub use run_curate_bars_1m::{
|
||||
format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_with_readers,
|
||||
CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError,
|
||||
DEFAULT_BARS_1M_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_fx_1m;
|
||||
pub use run_curate_fx_1m::{
|
||||
format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs,
|
||||
CurateFx1mRunReport, RunCurateFx1mError,
|
||||
};
|
||||
|
||||
pub mod run_curate_qm_bars_1m;
|
||||
pub use run_curate_qm_bars_1m::{
|
||||
format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers,
|
||||
CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError,
|
||||
DEFAULT_QM_BARS_1M_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_adj;
|
||||
pub use run_curate_adj::{
|
||||
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
|
||||
|
|
|
|||
|
|
@ -23,11 +23,13 @@ use curate_etl::run_curate_adj::{
|
|||
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
|
||||
};
|
||||
use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d};
|
||||
use curate_etl::run_curate_bars_1m::{format_curate_bars_1m_report, run_curate_bars_1m};
|
||||
use curate_etl::run_curate_corporate_actions::{
|
||||
format_curate_corporate_actions_report, run_curate_corporate_actions,
|
||||
};
|
||||
use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events};
|
||||
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
|
||||
use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m};
|
||||
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts};
|
||||
use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
|
||||
use curate_etl::run_mongo::{
|
||||
|
|
@ -198,6 +200,26 @@ fn main() -> ExitCode {
|
|||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateBars1m(curate_args)) => match run_curate_bars_1m(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_bars_1m_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_fx_1m_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_posts_report(&report));
|
||||
|
|
|
|||
|
|
@ -310,6 +310,10 @@ impl StagingFileGuard {
|
|||
pub(crate) fn disarm(&mut self) {
|
||||
self.path = None;
|
||||
}
|
||||
|
||||
pub(crate) fn is_armed(&self) -> bool {
|
||||
self.path.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StagingFileGuard {
|
||||
|
|
|
|||
|
|
@ -516,12 +516,34 @@ struct LoadedCurateBarsInputs {
|
|||
buffered_bar_bytes: usize,
|
||||
}
|
||||
|
||||
struct EodListingRange {
|
||||
pub(crate) struct EodListingRange {
|
||||
valid_from: i32,
|
||||
valid_to: Option<i32>,
|
||||
key: Arc<str>,
|
||||
}
|
||||
|
||||
pub(crate) struct EodMappingIndex {
|
||||
pub(crate) eod_keys: HashSet<Arc<str>>,
|
||||
pub(crate) eod_by_listing: HashMap<i32, Vec<Arc<str>>>,
|
||||
pub(crate) eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>>,
|
||||
}
|
||||
|
||||
pub(crate) struct DecodedQmSplits {
|
||||
pub(crate) compacted_splits: Vec<(i32, SplitEvent)>,
|
||||
pub(crate) splits_docs_framed: u64,
|
||||
pub(crate) splits_bytes_read: u64,
|
||||
pub(crate) splits_decode: BsonQmActionDecodeStats,
|
||||
pub(crate) split_rekey: SplitRekeyStats,
|
||||
}
|
||||
|
||||
pub(crate) struct LoadedQmSplits {
|
||||
pub(crate) splits: SplitTable<Arc<str>>,
|
||||
pub(crate) splits_docs_framed: u64,
|
||||
pub(crate) splits_bytes_read: u64,
|
||||
pub(crate) splits_decode: BsonQmActionDecodeStats,
|
||||
pub(crate) split_rekey: SplitRekeyStats,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn valid_to_sort_key(valid_to: Option<i32>) -> (u8, i32) {
|
||||
match valid_to {
|
||||
|
|
@ -530,6 +552,170 @@ fn valid_to_sort_key(valid_to: Option<i32>) -> (u8, i32) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Builds the interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
||||
/// When `track_eod_ranges` is true, also builds a date-aware reverse index
|
||||
/// `listing_id -> [(valid_from, valid_to, Arc<str>)]` so reused EOD tickers never receive
|
||||
/// cross-check observations outside their mapping range.
|
||||
pub(crate) fn build_eod_mapping_index(
|
||||
mapping_rows: &[ProviderMappingRow],
|
||||
track_eod_ranges: bool,
|
||||
) -> EodMappingIndex {
|
||||
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
||||
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
|
||||
for row in mapping_rows {
|
||||
if row.source == "eod" {
|
||||
let key = match eod_keys.get(row.source_id.as_str()) {
|
||||
Some(existing) => Arc::clone(existing),
|
||||
None => {
|
||||
let arc: Arc<str> = Arc::from(row.source_id.as_str());
|
||||
eod_keys.insert(Arc::clone(&arc));
|
||||
arc
|
||||
}
|
||||
};
|
||||
if track_eod_ranges {
|
||||
eod_ranges_by_listing
|
||||
.entry(row.listing_id)
|
||||
.or_default()
|
||||
.push(EodListingRange {
|
||||
valid_from: row.valid_from,
|
||||
valid_to: row.valid_to,
|
||||
key: Arc::clone(&key),
|
||||
});
|
||||
}
|
||||
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
||||
}
|
||||
}
|
||||
for partners in eod_by_listing.values_mut() {
|
||||
partners.sort_unstable();
|
||||
partners.dedup();
|
||||
}
|
||||
for ranges in eod_ranges_by_listing.values_mut() {
|
||||
ranges.sort_unstable_by(|a, b| {
|
||||
a.valid_from
|
||||
.cmp(&b.valid_from)
|
||||
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
}
|
||||
EodMappingIndex {
|
||||
eod_keys,
|
||||
eod_by_listing,
|
||||
eod_ranges_by_listing,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, filters out
|
||||
/// listings without an `"eod"` partner, and compacts cross-key QM aliases per `(listing_id, ex_date)`
|
||||
/// while retaining permanent `listing_id` identity.
|
||||
pub(crate) fn decode_and_compact_qm_splits_from_reader<R: io::Read>(
|
||||
splits_stream: R,
|
||||
qm_splits_path: &Path,
|
||||
mapping: &ProviderMappingTable,
|
||||
eod_by_listing: &HashMap<i32, Vec<Arc<str>>>,
|
||||
) -> Result<DecodedQmSplits, RunCurateBarsError> {
|
||||
let mut splits_reader = RawBsonChunkReader::new(splits_stream);
|
||||
let mut split_rekey = SplitRekeyStats::default();
|
||||
let mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
if split.ratio == 1.0 {
|
||||
split_rekey.splits_noop_dropped += 1;
|
||||
return;
|
||||
}
|
||||
let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date)
|
||||
else {
|
||||
split_rekey.splits_unmapped_qm += 1;
|
||||
return;
|
||||
};
|
||||
let has_eod_partner = eod_by_listing
|
||||
.get(&listing_id)
|
||||
.is_some_and(|partners| !partners.is_empty());
|
||||
if !has_eod_partner {
|
||||
split_rekey.splits_no_eod_partner += 1;
|
||||
return;
|
||||
}
|
||||
mapped_splits.push(MappedQmSplit {
|
||||
listing_id,
|
||||
ex_date: split.ex_date,
|
||||
qm_key: split.qm_search_code.to_owned(),
|
||||
ratio: split.ratio,
|
||||
});
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::BsonStream {
|
||||
label: "qm-splits",
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let splits_docs_framed = splits_reader.docs_framed();
|
||||
let splits_bytes_read = splits_reader.bytes_read();
|
||||
split_rekey.splits_in = splits_decode.docs_in;
|
||||
|
||||
// Compact cross-key QM aliases per `(listing_id, ex_date)`.
|
||||
let (compacted_splits, splits_collision_collapsed) =
|
||||
compact_mapped_qm_splits(qm_splits_path, mapped_splits)?;
|
||||
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
|
||||
|
||||
Ok(DecodedQmSplits {
|
||||
compacted_splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
})
|
||||
}
|
||||
|
||||
/// Streams `qmSplits` BSON, resolves `("qm", qmSearchCode, ex_date) -> listing_id`, compacts
|
||||
/// cross-key QM aliases per `(listing_id, ex_date)`, fans out to `"eod"` partners, and builds
|
||||
/// [`SplitTable<Arc<str>>`].
|
||||
pub(crate) fn load_qm_splits_from_reader<R: io::Read>(
|
||||
splits_stream: R,
|
||||
qm_splits_path: &Path,
|
||||
mapping: &ProviderMappingTable,
|
||||
eod_by_listing: &HashMap<i32, Vec<Arc<str>>>,
|
||||
) -> Result<LoadedQmSplits, RunCurateBarsError> {
|
||||
let DecodedQmSplits {
|
||||
compacted_splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
mut split_rekey,
|
||||
} = decode_and_compact_qm_splits_from_reader(
|
||||
splits_stream,
|
||||
qm_splits_path,
|
||||
mapping,
|
||||
eod_by_listing,
|
||||
)?;
|
||||
|
||||
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
|
||||
for (listing_id, event) in compacted_splits {
|
||||
let partners = &eod_by_listing[&listing_id];
|
||||
split_rekey.splits_applied += 1;
|
||||
for eod_key in partners {
|
||||
split_events.push((Arc::clone(eod_key), event));
|
||||
}
|
||||
split_rekey.split_events_attached += partners.len();
|
||||
}
|
||||
|
||||
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
||||
RunCurateBarsError::SplitTable {
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(LoadedQmSplits {
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> {
|
||||
if out_dir.exists() && !out_dir.is_dir() {
|
||||
return Err(RunCurateBarsError::InvalidOutDir {
|
||||
|
|
@ -718,49 +904,11 @@ where
|
|||
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)?;
|
||||
let currencies = load_listing_currencies_tsv(listing_currencies_path)?;
|
||||
|
||||
// Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
||||
// When `--qm-prices` is provided, also build a date-aware reverse index
|
||||
// `listing_id -> [(valid_from, valid_to, Arc<str>)]` so reused EOD tickers never receive
|
||||
// cross-check observations outside their mapping range.
|
||||
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
||||
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
|
||||
let track_eod_ranges = qm_prices_path.is_some();
|
||||
for row in &mapping_rows {
|
||||
if row.source == "eod" {
|
||||
let key = match eod_keys.get(row.source_id.as_str()) {
|
||||
Some(existing) => Arc::clone(existing),
|
||||
None => {
|
||||
let arc: Arc<str> = Arc::from(row.source_id.as_str());
|
||||
eod_keys.insert(Arc::clone(&arc));
|
||||
arc
|
||||
}
|
||||
};
|
||||
if track_eod_ranges {
|
||||
eod_ranges_by_listing
|
||||
.entry(row.listing_id)
|
||||
.or_default()
|
||||
.push(EodListingRange {
|
||||
valid_from: row.valid_from,
|
||||
valid_to: row.valid_to,
|
||||
key: Arc::clone(&key),
|
||||
});
|
||||
}
|
||||
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
||||
}
|
||||
}
|
||||
for partners in eod_by_listing.values_mut() {
|
||||
partners.sort_unstable();
|
||||
partners.dedup();
|
||||
}
|
||||
for ranges in eod_ranges_by_listing.values_mut() {
|
||||
ranges.sort_unstable_by(|a, b| {
|
||||
a.valid_from
|
||||
.cmp(&b.valid_from)
|
||||
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
}
|
||||
let EodMappingIndex {
|
||||
eod_keys,
|
||||
eod_by_listing,
|
||||
eod_ranges_by_listing,
|
||||
} = build_eod_mapping_index(&mapping_rows, qm_prices_path.is_some());
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateBarsError::ProviderMapping {
|
||||
|
|
@ -771,67 +919,13 @@ where
|
|||
|
||||
// Stream `qmSplits` and resolve `("qm", qmSearchCode, ex_date) -> listing_id`.
|
||||
let splits_stream = open_splits()?;
|
||||
let mut splits_reader = RawBsonChunkReader::new(splits_stream);
|
||||
let mut split_rekey = SplitRekeyStats::default();
|
||||
let mut mapped_splits: Vec<MappedQmSplit> = Vec::new();
|
||||
let splits_decode = decode_qm_split_chunks(
|
||||
&mut splits_reader,
|
||||
|split| {
|
||||
if split.ratio == 1.0 {
|
||||
split_rekey.splits_noop_dropped += 1;
|
||||
return;
|
||||
}
|
||||
let Some(listing_id) = mapping.resolve("qm", split.qm_search_code, split.ex_date)
|
||||
else {
|
||||
split_rekey.splits_unmapped_qm += 1;
|
||||
return;
|
||||
};
|
||||
let has_eod_partner = eod_by_listing
|
||||
.get(&listing_id)
|
||||
.is_some_and(|partners| !partners.is_empty());
|
||||
if !has_eod_partner {
|
||||
split_rekey.splits_no_eod_partner += 1;
|
||||
return;
|
||||
}
|
||||
mapped_splits.push(MappedQmSplit {
|
||||
listing_id,
|
||||
ex_date: split.ex_date,
|
||||
qm_key: split.qm_search_code.to_owned(),
|
||||
ratio: split.ratio,
|
||||
});
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::BsonStream {
|
||||
label: "qm-splits",
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let splits_docs_framed = splits_reader.docs_framed();
|
||||
let splits_bytes_read = splits_reader.bytes_read();
|
||||
split_rekey.splits_in = splits_decode.docs_in;
|
||||
|
||||
// Compact cross-key QM aliases per `(listing_id, ex_date)` before fanning out to `"eod"` keys.
|
||||
let (compacted_splits, splits_collision_collapsed) =
|
||||
compact_mapped_qm_splits(qm_splits_path, mapped_splits)?;
|
||||
split_rekey.splits_collision_collapsed = splits_collision_collapsed;
|
||||
|
||||
let mut split_events: Vec<(Arc<str>, SplitEvent)> = Vec::with_capacity(compacted_splits.len());
|
||||
for (listing_id, event) in compacted_splits {
|
||||
let partners = &eod_by_listing[&listing_id];
|
||||
split_rekey.splits_applied += 1;
|
||||
for eod_key in partners {
|
||||
split_events.push((Arc::clone(eod_key), event));
|
||||
}
|
||||
split_rekey.split_events_attached += partners.len();
|
||||
}
|
||||
|
||||
let splits = SplitTable::<Arc<str>>::from_events(split_events).map_err(|source| {
|
||||
RunCurateBarsError::SplitTable {
|
||||
path: qm_splits_path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let LoadedQmSplits {
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
} = load_qm_splits_from_reader(splits_stream, qm_splits_path, &mapping, &eod_by_listing)?;
|
||||
|
||||
// Stream `eodPrices`, dropping unmapped `"eod"` keys before buffering and interning keys.
|
||||
let eod_stream = open_eod()?;
|
||||
|
|
|
|||
892
tools/curate-etl/src/run_curate_bars_1m.rs
Normal file
892
tools/curate-etl/src/run_curate_bars_1m.rs
Normal file
|
|
@ -0,0 +1,892 @@
|
|||
//! Bounded-memory file-to-file `bars_1m` runner (`M2.3k`).
|
||||
//!
|
||||
//! Streams a concatenated raw BSON `eodIntraday1M` dump alongside a `qmSplits` BSON dump and a
|
||||
//! headerless 5-column `provider_mapping.tsv` into per-shard QuestDB ILP v2 files
|
||||
//! (`<out_dir>/bars_1m.shard-<NN>.ilp`) via listing-keyed [`crate::curate_bars_1m`] curation.
|
||||
//!
|
||||
//! # Bounded-Memory Chunking
|
||||
//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and
|
||||
//! [`decode_eod_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by
|
||||
//! `crate::bson_stream::decode_eod_intraday_chunks`, whose callback API hides chunk boundaries.
|
||||
//! - Each framed chunk is decoded into a chunk-local `Vec<EodIntradayBar<Arc<str>>>` (reusing
|
||||
//! interned `"eod"` keys from `provider_mapping.tsv` and retaining unknown codes so
|
||||
//! `curate_bars_1m` counts them in `dropped_unmapped`) and curated per chunk against one shared
|
||||
//! [`IlpShardedWriter`] (resolving `listing_id` on each bar's Eastern Time `session_date` before
|
||||
//! applying listing-keyed splits).
|
||||
//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF.
|
||||
//! - Peak memory is bounded by the reference tables (`provider_mapping` + `SplitTable`), the
|
||||
//! current BSON chunk (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single
|
||||
//! document up to `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per
|
||||
//! shard—independent of the total `eodIntraday1M` input size.
|
||||
//!
|
||||
//! # Cross-Chunk Semantics & Reporting
|
||||
//! - Collision collapse/drop in `curate_bars_1m` and row ordering apply **per chunk**: output is
|
||||
//! sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing in
|
||||
//! two different chunks is emitted twice (with zero within-chunk collapse between them) and
|
||||
//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`.
|
||||
//! - `CurateBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its
|
||||
//! nested [`Bars1mStats`] across chunks. In particular, `curate_stats.listings_out` and
|
||||
//! `curate_stats.builder.keys_out` are **sums of per-chunk counts**, not global distinct counts.
|
||||
//! - `mapping_source` must be `"eod"` because the shared `qmSplits` loader
|
||||
//! (`run_curate_bars::decode_and_compact_qm_splits_from_reader`) filters to listings with `"eod"`
|
||||
//! partners. Split events retain permanent `listing_id: i32` identity (`SplitTable<i32>`), and
|
||||
//! each bar's listing is resolved via `provider_mapping` on its Eastern Time `session_date`
|
||||
//! **before** choosing the split factor so reused tickers cannot leak splits across listings.
|
||||
//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's
|
||||
//! `known_at` column; it supplies no evidence of earlier market availability.
|
||||
//!
|
||||
//! # File Publication & Fail-Closed Guarantees
|
||||
//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m.shard-<digits>.ilp` file
|
||||
//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards
|
||||
//! from a prior larger-shard-count run cannot survive alongside a new export.
|
||||
//! - Each shard writes into an exclusively created staging file in `out_dir`
|
||||
//! (`.bars_1m.shard-<NN>.<run_id>.tmp`), flushes and `sync_all`s on `finish`, and publishes to
|
||||
//! `bars_1m.shard-<NN>.ilp` via same-directory `hard_link` followed by removing the staged name
|
||||
//! (preserving no-overwrite semantics even if a final file appears after preflight).
|
||||
//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or
|
||||
//! publication collision) rolls back only final files created by this run, removes this run's
|
||||
//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors
|
||||
//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`].
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::ffi::OsStr;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bars_1m::{Bars1mStats, EodIntradayBar};
|
||||
use crate::bson_eod_intraday::{decode_eod_intraday_buffer, BsonEodIntradayDecodeStats};
|
||||
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
||||
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
|
||||
use crate::curate_bars_1m::{
|
||||
curate_and_write_bars_1m_by_listing, CurateBars1mStats, CurateBars1mWriteError,
|
||||
};
|
||||
use crate::ilp::{
|
||||
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_BARS_1M,
|
||||
};
|
||||
use crate::parquet_bars::RollbackFailure;
|
||||
use crate::parquet_publish::{
|
||||
next_run_id, rollback_published, PublishedPartition, StagingFileGuard, FILE_BUF_CAPACITY_BYTES,
|
||||
};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::run_curate_bars::{
|
||||
build_eod_mapping_index, decode_and_compact_qm_splits_from_reader, load_provider_mapping_tsv,
|
||||
DecodedQmSplits, EodMappingIndex, RunCurateBarsError, SplitRekeyStats,
|
||||
};
|
||||
use crate::split::SplitTable;
|
||||
|
||||
/// Required `provider_mapping` source namespace for `eodIntraday1M` bars.
|
||||
pub const DEFAULT_BARS_1M_MAPPING_SOURCE: &str = "eod";
|
||||
|
||||
/// Arguments for [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateBars1mArgs {
|
||||
pub intraday_path: PathBuf,
|
||||
pub splits_path: PathBuf,
|
||||
pub provider_mapping_path: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
pub mapping_source: String,
|
||||
pub shard_count: usize,
|
||||
pub known_at_micros: i64,
|
||||
pub stream_options: BsonStreamOptions,
|
||||
pub ilp_options: IlpWriterOptions,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `intraday_docs_framed as usize == intraday_decode.docs_seen`
|
||||
/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()`
|
||||
/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in`
|
||||
/// - `curate_stats.rows_in == curate_stats.builder.rows_out`
|
||||
/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped`
|
||||
/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out`
|
||||
/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::<usize>()`
|
||||
///
|
||||
/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks
|
||||
/// (not global distinct counts).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateBars1mRunReport {
|
||||
pub intraday_docs_framed: u64,
|
||||
pub intraday_bytes_read: u64,
|
||||
pub intraday_decode: BsonEodIntradayDecodeStats,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub split_rekey: SplitRekeyStats,
|
||||
pub chunks: usize,
|
||||
pub max_rows_per_chunk: usize,
|
||||
pub curate_stats: CurateBars1mStats,
|
||||
pub rows_written: usize,
|
||||
pub ilp_stats: IlpWriteStats,
|
||||
pub shard_count: usize,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`run_curate_bars_1m`] and [`run_curate_bars_1m_with_readers`].
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateBars1mError {
|
||||
/// `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
/// `mapping_source` was non-blank but not `"eod"`.
|
||||
UnsupportedMappingSource { mapping_source: String },
|
||||
/// `shard_count` was `0`.
|
||||
ZeroShardCount,
|
||||
/// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`.
|
||||
ShardCountMismatch { expected: usize, actual: usize },
|
||||
/// `out_dir` exists and is not a directory.
|
||||
InvalidOutDir { path: PathBuf, detail: String },
|
||||
/// A final shard output file (`bars_1m.shard-<NN>.ilp`) already existed.
|
||||
OutputFileExists { path: PathBuf },
|
||||
/// Failed to open an input dump file.
|
||||
OpenInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Failed to load `provider_mapping.tsv` or `qmSplits` via the shared reference loader.
|
||||
LoadReference(RunCurateBarsError),
|
||||
/// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`.
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
/// Curation or per-row ILP write error inside the per-chunk `bars_1m` curation stage.
|
||||
CurateWrite(CurateBars1mWriteError),
|
||||
/// ILP writer initialization or final flush error.
|
||||
Ilp(IlpWriterError),
|
||||
/// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files.
|
||||
Io { path: PathBuf, source: io::Error },
|
||||
/// Publication failed and rolling back one or more already-published shards also failed.
|
||||
RollbackFailed {
|
||||
cause: Box<RunCurateBars1mError>,
|
||||
failures: Vec<RollbackFailure>,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateBars1mError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"),
|
||||
Self::UnsupportedMappingSource { mapping_source } => write!(
|
||||
f,
|
||||
"unsupported mapping_source '{mapping_source}': only '{DEFAULT_BARS_1M_MAPPING_SOURCE}' is supported"
|
||||
),
|
||||
Self::ZeroShardCount => write!(f, "shard_count must be >= 1"),
|
||||
Self::ShardCountMismatch { expected, actual } => write!(
|
||||
f,
|
||||
"ILP writer shard count mismatch: expected {expected}, got {actual}"
|
||||
),
|
||||
Self::InvalidOutDir { path, detail } => {
|
||||
write!(f, "invalid out_dir '{}': {detail}", path.display())
|
||||
}
|
||||
Self::OutputFileExists { path } => write!(
|
||||
f,
|
||||
"refusing to overwrite existing output file '{}'",
|
||||
path.display()
|
||||
),
|
||||
Self::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
|
||||
Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"),
|
||||
Self::BsonStream {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
||||
Self::CurateWrite(err) => write!(f, "{err}"),
|
||||
Self::Ilp(err) => write!(f, "bars_1m ILP writer failed: {err}"),
|
||||
Self::Io { path, source } => {
|
||||
write!(f, "I/O error on '{}': {source}", path.display())
|
||||
}
|
||||
Self::RollbackFailed { cause, failures } => {
|
||||
write!(f, "{cause}; rollback also failed for: ")?;
|
||||
for (i, failure) in failures.iter().enumerate() {
|
||||
if i > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{failure}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateBars1mError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source),
|
||||
Self::LoadReference(err) => Some(err),
|
||||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::CurateWrite(err) => Some(err),
|
||||
Self::Ilp(err) => Some(err),
|
||||
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
|
||||
Self::EmptyMappingSource
|
||||
| Self::UnsupportedMappingSource { .. }
|
||||
| Self::ZeroShardCount
|
||||
| Self::ShardCountMismatch { .. }
|
||||
| Self::InvalidOutDir { .. }
|
||||
| Self::OutputFileExists { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadedReferenceInputs {
|
||||
mapping: ProviderMappingTable,
|
||||
eod_keys: HashSet<Arc<str>>,
|
||||
splits: SplitTable<i32>,
|
||||
splits_docs_framed: u64,
|
||||
splits_bytes_read: u64,
|
||||
splits_decode: BsonQmActionDecodeStats,
|
||||
split_rekey: SplitRekeyStats,
|
||||
}
|
||||
|
||||
fn validate_common_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> {
|
||||
if args.mapping_source.trim().is_empty() {
|
||||
return Err(RunCurateBars1mError::EmptyMappingSource);
|
||||
}
|
||||
if args.mapping_source != DEFAULT_BARS_1M_MAPPING_SOURCE {
|
||||
return Err(RunCurateBars1mError::UnsupportedMappingSource {
|
||||
mapping_source: args.mapping_source.clone(),
|
||||
});
|
||||
}
|
||||
if args.shard_count == 0 {
|
||||
return Err(RunCurateBars1mError::ZeroShardCount);
|
||||
}
|
||||
args.stream_options
|
||||
.validate()
|
||||
.map_err(|source| RunCurateBars1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) enum ShardPublishError {
|
||||
InvalidOutDir { path: PathBuf, detail: String },
|
||||
OutputFileExists { path: PathBuf },
|
||||
Io { path: PathBuf, source: io::Error },
|
||||
RollbackFailed {
|
||||
cause: Box<ShardPublishError>,
|
||||
failures: Vec<RollbackFailure>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<ShardPublishError> for RunCurateBars1mError {
|
||||
fn from(err: ShardPublishError) -> Self {
|
||||
match err {
|
||||
ShardPublishError::InvalidOutDir { path, detail } => {
|
||||
Self::InvalidOutDir { path, detail }
|
||||
}
|
||||
ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path },
|
||||
ShardPublishError::Io { path, source } => Self::Io { path, source },
|
||||
ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed {
|
||||
cause: Box::new((*cause).into()),
|
||||
failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_file_mode_args(args: &CurateBars1mArgs) -> Result<(), RunCurateBars1mError> {
|
||||
validate_common_args(args)?;
|
||||
if args.ilp_options.max_batch_bytes == 0 {
|
||||
return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes));
|
||||
}
|
||||
if args.ilp_options.max_batch_rows == 0 {
|
||||
return Err(RunCurateBars1mError::Ilp(IlpWriterError::ZeroMaxBatchRows));
|
||||
}
|
||||
preflight_shard_out_dir(&args.out_dir, TABLE_BARS_1M)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn preflight_shard_out_dir(
|
||||
out_dir: &Path,
|
||||
table: &str,
|
||||
) -> Result<(), ShardPublishError> {
|
||||
if out_dir.exists() {
|
||||
if !out_dir.is_dir() {
|
||||
return Err(ShardPublishError::InvalidOutDir {
|
||||
path: out_dir.to_path_buf(),
|
||||
detail: "path exists and is not a directory".to_string(),
|
||||
});
|
||||
}
|
||||
let entries = fs::read_dir(out_dir).map_err(|source| ShardPublishError::Io {
|
||||
path: out_dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let mut existing_shards: Vec<PathBuf> = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|source| ShardPublishError::Io {
|
||||
path: out_dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
if is_final_shard_file_name_for_table(table, &entry.file_name()) {
|
||||
existing_shards.push(entry.path());
|
||||
}
|
||||
}
|
||||
if !existing_shards.is_empty() {
|
||||
existing_shards.sort();
|
||||
return Err(ShardPublishError::OutputFileExists {
|
||||
path: existing_shards.remove(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn is_final_shard_file_name_for_table(table: &str, name: &OsStr) -> bool {
|
||||
let Some(s) = name.to_str() else {
|
||||
return false;
|
||||
};
|
||||
let Some(after_table) = s.strip_prefix(table) else {
|
||||
return false;
|
||||
};
|
||||
let Some(rest) = after_table.strip_prefix(".shard-") else {
|
||||
return false;
|
||||
};
|
||||
let Some(digits) = rest.strip_suffix(".ilp") else {
|
||||
return false;
|
||||
};
|
||||
!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn final_shard_path_for_table(
|
||||
out_dir: &Path,
|
||||
table: &str,
|
||||
shard_idx: usize,
|
||||
) -> PathBuf {
|
||||
out_dir.join(format!("{table}.shard-{shard_idx:02}.ilp"))
|
||||
}
|
||||
|
||||
fn load_reference_inputs<RS: io::Read>(
|
||||
provider_mapping_path: &Path,
|
||||
splits_path: &Path,
|
||||
splits_reader: RS,
|
||||
) -> Result<LoadedReferenceInputs, RunCurateBars1mError> {
|
||||
let mapping_rows =
|
||||
load_provider_mapping_tsv(provider_mapping_path).map_err(RunCurateBars1mError::LoadReference)?;
|
||||
let EodMappingIndex {
|
||||
eod_keys,
|
||||
eod_by_listing,
|
||||
..
|
||||
} = build_eod_mapping_index(&mapping_rows, false);
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateBars1mError::LoadReference(RunCurateBarsError::ProviderMapping {
|
||||
path: provider_mapping_path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
|
||||
let DecodedQmSplits {
|
||||
compacted_splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
mut split_rekey,
|
||||
} = decode_and_compact_qm_splits_from_reader(
|
||||
splits_reader,
|
||||
splits_path,
|
||||
&mapping,
|
||||
&eod_by_listing,
|
||||
)
|
||||
.map_err(RunCurateBars1mError::LoadReference)?;
|
||||
|
||||
split_rekey.splits_applied = compacted_splits.len();
|
||||
split_rekey.split_events_attached = compacted_splits.len();
|
||||
|
||||
let splits = SplitTable::<i32>::from_events(compacted_splits).map_err(|source| {
|
||||
RunCurateBars1mError::LoadReference(RunCurateBarsError::SplitTable {
|
||||
path: splits_path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
|
||||
Ok(LoadedReferenceInputs {
|
||||
mapping,
|
||||
eod_keys,
|
||||
splits,
|
||||
splits_docs_framed,
|
||||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn add_bars_1m_stats(total: &mut Bars1mStats, chunk: &Bars1mStats) {
|
||||
total.bars_in += chunk.bars_in;
|
||||
total.rows_out += chunk.rows_out;
|
||||
total.keys_out += chunk.keys_out;
|
||||
total.pre_rows_out += chunk.pre_rows_out;
|
||||
total.rth_rows_out += chunk.rth_rows_out;
|
||||
total.post_rows_out += chunk.post_rows_out;
|
||||
total.dropped_invalid_ohlc += chunk.dropped_invalid_ohlc;
|
||||
total.dropped_inconsistent_ohlc += chunk.dropped_inconsistent_ohlc;
|
||||
total.dropped_invalid_volume += chunk.dropped_invalid_volume;
|
||||
total.dropped_ts_out_of_range += chunk.dropped_ts_out_of_range;
|
||||
total.duplicate_collapsed += chunk.duplicate_collapsed;
|
||||
total.duplicate_conflict_dropped += chunk.duplicate_conflict_dropped;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn add_curate_bars_1m_stats(total: &mut CurateBars1mStats, chunk: &CurateBars1mStats) {
|
||||
add_bars_1m_stats(&mut total.builder, &chunk.builder);
|
||||
total.rows_in += chunk.rows_in;
|
||||
total.rows_out += chunk.rows_out;
|
||||
total.listings_out += chunk.listings_out;
|
||||
total.pre_rows_out += chunk.pre_rows_out;
|
||||
total.rth_rows_out += chunk.rth_rows_out;
|
||||
total.post_rows_out += chunk.post_rows_out;
|
||||
total.dropped_unmapped += chunk.dropped_unmapped;
|
||||
total.listing_collision_collapsed += chunk.listing_collision_collapsed;
|
||||
total.listing_collision_dropped += chunk.listing_collision_dropped;
|
||||
}
|
||||
|
||||
fn stream_intraday_chunks_to_writer<RI, W>(
|
||||
args: &CurateBars1mArgs,
|
||||
reference: LoadedReferenceInputs,
|
||||
intraday: RI,
|
||||
mut writer: IlpShardedWriter<W>,
|
||||
start: Instant,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||
where
|
||||
RI: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|
||||
|source| RunCurateBars1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
|
||||
let mut intraday_decode = BsonEodIntradayDecodeStats::default();
|
||||
let mut curate_stats = CurateBars1mStats::default();
|
||||
let mut chunks: usize = 0;
|
||||
let mut max_rows_per_chunk: usize = 0;
|
||||
let mut rows_written: usize = 0;
|
||||
|
||||
// Reusable per-chunk buffers; cleared before each chunk so peak RAM stays bounded by chunk size.
|
||||
let mut chunk_bars: Vec<EodIntradayBar<Arc<str>>> = Vec::new();
|
||||
let mut unknown_keys: HashMap<String, Arc<str>> = HashMap::new();
|
||||
|
||||
while let Some(chunk) =
|
||||
reader
|
||||
.next_chunk()
|
||||
.map_err(|source| RunCurateBars1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?
|
||||
{
|
||||
chunk_bars.clear();
|
||||
unknown_keys.clear();
|
||||
|
||||
let chunk_decode = decode_eod_intraday_buffer(
|
||||
chunk.bytes,
|
||||
|raw| {
|
||||
let key = if let Some(existing) = reference.eod_keys.get(raw.eod_search_code) {
|
||||
Arc::clone(existing)
|
||||
} else if let Some(existing) = unknown_keys.get(raw.eod_search_code) {
|
||||
Arc::clone(existing)
|
||||
} else {
|
||||
let arc: Arc<str> = Arc::from(raw.eod_search_code);
|
||||
unknown_keys.insert(raw.eod_search_code.to_owned(), Arc::clone(&arc));
|
||||
arc
|
||||
};
|
||||
chunk_bars.push(raw.into_eod_intraday_bar(|_, _| key));
|
||||
},
|
||||
|_local_offset, _err| {},
|
||||
);
|
||||
intraday_decode += chunk_decode;
|
||||
|
||||
chunks += 1;
|
||||
let chunk_len = chunk_bars.len();
|
||||
if chunk_len > max_rows_per_chunk {
|
||||
max_rows_per_chunk = chunk_len;
|
||||
}
|
||||
|
||||
let write_report = curate_and_write_bars_1m_by_listing(
|
||||
chunk_bars.drain(..),
|
||||
&reference.splits,
|
||||
&reference.mapping,
|
||||
&args.mapping_source,
|
||||
&mut writer,
|
||||
args.known_at_micros,
|
||||
)
|
||||
.map_err(RunCurateBars1mError::CurateWrite)?;
|
||||
|
||||
add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats);
|
||||
rows_written += write_report.rows_written;
|
||||
}
|
||||
|
||||
let intraday_docs_framed = reader.docs_framed();
|
||||
let intraday_bytes_read = reader.bytes_read();
|
||||
let ilp_stats = writer.finish().map_err(RunCurateBars1mError::Ilp)?;
|
||||
|
||||
Ok(CurateBars1mRunReport {
|
||||
intraday_docs_framed,
|
||||
intraday_bytes_read,
|
||||
intraday_decode,
|
||||
splits_docs_framed: reference.splits_docs_framed,
|
||||
splits_bytes_read: reference.splits_bytes_read,
|
||||
splits_decode: reference.splits_decode,
|
||||
split_rekey: reference.split_rekey,
|
||||
chunks,
|
||||
max_rows_per_chunk,
|
||||
curate_stats,
|
||||
rows_written,
|
||||
ilp_stats,
|
||||
shard_count: args.shard_count,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary [`io::Read`] streams into a
|
||||
/// caller-owned [`IlpShardedWriter`].
|
||||
///
|
||||
/// Validates `args`, loads `provider_mapping.tsv` from `args.provider_mapping_path` and `qmSplits`
|
||||
/// from `splits`, streams `intraday` through [`RawBsonChunkReader::with_options`] +
|
||||
/// [`decode_eod_intraday_buffer`] curating and writing once per chunk with listing-keyed splits,
|
||||
/// and calls [`IlpShardedWriter::finish`] exactly once after EOF.
|
||||
pub fn run_curate_bars_1m_with_readers<RI, RS, W>(
|
||||
args: &CurateBars1mArgs,
|
||||
intraday: RI,
|
||||
splits: RS,
|
||||
writer: IlpShardedWriter<W>,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||
where
|
||||
RI: io::Read,
|
||||
RS: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_common_args(args)?;
|
||||
if writer.shard_count() != args.shard_count {
|
||||
return Err(RunCurateBars1mError::ShardCountMismatch {
|
||||
expected: args.shard_count,
|
||||
actual: writer.shard_count(),
|
||||
});
|
||||
}
|
||||
|
||||
let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?;
|
||||
stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)
|
||||
}
|
||||
|
||||
/// Buffered file sink that flushes and calls `File::sync_all()` on [`Write::flush`] (invoked once
|
||||
/// per shard by [`IlpShardedWriter::finish`]).
|
||||
pub(crate) struct SyncedBufFile {
|
||||
inner: BufWriter<File>,
|
||||
}
|
||||
|
||||
impl SyncedBufFile {
|
||||
pub(crate) fn new(file: File) -> Self {
|
||||
Self {
|
||||
inner: BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for SyncedBufFile {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.inner.write(buf)
|
||||
}
|
||||
|
||||
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
|
||||
self.inner.write_all(buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()?;
|
||||
self.inner.get_ref().sync_all()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_exclusive_shard_tmp_file_for_table(
|
||||
out_dir: &Path,
|
||||
table: &str,
|
||||
shard_idx: usize,
|
||||
run_id: &str,
|
||||
) -> Result<(PathBuf, File), ShardPublishError> {
|
||||
for attempt in 0..1024u32 {
|
||||
let file_name = if attempt == 0 {
|
||||
format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")
|
||||
} else {
|
||||
format!(".{table}.shard-{shard_idx:02}.{run_id}.{attempt}.tmp")
|
||||
};
|
||||
let tmp_path = out_dir.join(file_name);
|
||||
match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp_path)
|
||||
{
|
||||
Ok(file) => return Ok((tmp_path, file)),
|
||||
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(source) => {
|
||||
return Err(ShardPublishError::Io {
|
||||
path: tmp_path,
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(ShardPublishError::Io {
|
||||
path: out_dir.join(format!(".{table}.shard-{shard_idx:02}.{run_id}.tmp")),
|
||||
source: io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"exhausted unique staging file names",
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn publish_staged_shards_for_table<F>(
|
||||
out_dir: &Path,
|
||||
table: &str,
|
||||
staged: &mut [(PathBuf, StagingFileGuard)],
|
||||
mut before_link: F,
|
||||
) -> Result<(), ShardPublishError>
|
||||
where
|
||||
F: FnMut(usize, &Path),
|
||||
{
|
||||
let mut published: Vec<PublishedPartition> = Vec::with_capacity(staged.len());
|
||||
|
||||
for (shard_idx, (tmp_path, guard)) in staged.iter_mut().enumerate() {
|
||||
let final_path = final_shard_path_for_table(out_dir, table, shard_idx);
|
||||
before_link(shard_idx, &final_path);
|
||||
|
||||
if let Err(source) = fs::hard_link(&tmp_path, &final_path) {
|
||||
let cause = if source.kind() == io::ErrorKind::AlreadyExists {
|
||||
ShardPublishError::OutputFileExists { path: final_path }
|
||||
} else {
|
||||
ShardPublishError::Io {
|
||||
path: final_path,
|
||||
source,
|
||||
}
|
||||
};
|
||||
let rollback_failures = rollback_published(&published);
|
||||
if !rollback_failures.is_empty() {
|
||||
return Err(ShardPublishError::RollbackFailed {
|
||||
cause: Box::new(cause),
|
||||
failures: rollback_failures,
|
||||
});
|
||||
}
|
||||
return Err(cause);
|
||||
}
|
||||
|
||||
published.push(PublishedPartition {
|
||||
final_path,
|
||||
backup_path: None,
|
||||
});
|
||||
|
||||
if let Err(source) = fs::remove_file(&tmp_path) {
|
||||
let cause = ShardPublishError::Io {
|
||||
path: tmp_path.clone(),
|
||||
source,
|
||||
};
|
||||
let rollback_failures = rollback_published(&published);
|
||||
if !rollback_failures.is_empty() {
|
||||
return Err(ShardPublishError::RollbackFailed {
|
||||
cause: Box::new(cause),
|
||||
failures: rollback_failures,
|
||||
});
|
||||
}
|
||||
return Err(cause);
|
||||
}
|
||||
guard.disarm();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting injected readers, sink factory, and pre-link hook so tests can
|
||||
/// exercise staging, writer failure, and post-preflight publication rollback through the exact
|
||||
/// file publication path.
|
||||
fn run_curate_bars_1m_to_dir_with_hooks<RI, RS, W, SF, BL>(
|
||||
args: &CurateBars1mArgs,
|
||||
intraday: RI,
|
||||
splits: RS,
|
||||
mut make_sink: SF,
|
||||
before_link: BL,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError>
|
||||
where
|
||||
RI: io::Read,
|
||||
RS: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let reference = load_reference_inputs(&args.provider_mapping_path, &args.splits_path, splits)?;
|
||||
|
||||
fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateBars1mError::Io {
|
||||
path: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let run_id = next_run_id();
|
||||
let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count);
|
||||
let mut sinks: Vec<W> = Vec::with_capacity(args.shard_count);
|
||||
for shard_idx in 0..args.shard_count {
|
||||
let (tmp_path, file) = create_exclusive_shard_tmp_file_for_table(
|
||||
&args.out_dir,
|
||||
TABLE_BARS_1M,
|
||||
shard_idx,
|
||||
&run_id,
|
||||
)?;
|
||||
let guard = StagingFileGuard::new(tmp_path.clone());
|
||||
staged.push((tmp_path, guard));
|
||||
sinks.push(make_sink(shard_idx, file));
|
||||
}
|
||||
|
||||
let writer = IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateBars1mError::Ilp)?;
|
||||
let report = stream_intraday_chunks_to_writer(args, reference, intraday, writer, start)?;
|
||||
|
||||
publish_staged_shards_for_table(&args.out_dir, TABLE_BARS_1M, &mut staged, before_link)?;
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly
|
||||
/// `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m.shard-<NN>.ilp`).
|
||||
pub fn run_curate_bars_1m(
|
||||
args: &CurateBars1mArgs,
|
||||
) -> Result<CurateBars1mRunReport, RunCurateBars1mError> {
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let splits_file = File::open(&args.splits_path).map_err(|source| {
|
||||
RunCurateBars1mError::OpenInput {
|
||||
label: "qm-splits",
|
||||
path: args.splits_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
let intraday_file = File::open(&args.intraday_path).map_err(|source| {
|
||||
RunCurateBars1mError::OpenInput {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
run_curate_bars_1m_to_dir_with_hooks(
|
||||
args,
|
||||
intraday_file,
|
||||
splits_file,
|
||||
|_shard_idx, file| SyncedBufFile::new(file),
|
||||
|_shard_idx, _final_path| {},
|
||||
)
|
||||
}
|
||||
|
||||
/// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_bars_1m_report(report: &CurateBars1mRunReport) -> String {
|
||||
let per_shard = if report.ilp_stats.per_shard_rows.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
report
|
||||
.ilp_stats
|
||||
.per_shard_rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, count)| format!("{idx:02}={count}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
};
|
||||
|
||||
let b = &report.curate_stats.builder;
|
||||
let c = &report.curate_stats;
|
||||
let d = &report.intraday_decode;
|
||||
let sd = &report.splits_decode;
|
||||
let sr = &report.split_rekey;
|
||||
|
||||
format!(
|
||||
"curate-etl curate-bars-1m\n\
|
||||
\x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\
|
||||
\x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
\x20 splits: splits_in={} splits_applied={} splits_collision_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop_dropped={} split_events_attached={}\n\
|
||||
\x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\
|
||||
\x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\
|
||||
\x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\
|
||||
\x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\
|
||||
\x20 timing: elapsed_secs={:.6}",
|
||||
report.intraday_docs_framed,
|
||||
report.intraday_bytes_read,
|
||||
d.docs_seen,
|
||||
d.rows_decoded,
|
||||
d.rejected_total(),
|
||||
d.rejected_missing_field,
|
||||
d.rejected_empty_field,
|
||||
d.rejected_wrong_type,
|
||||
d.rejected_invalid_timestamp,
|
||||
d.rejected_invalid_number,
|
||||
d.rejected_corrupt_document,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
sd.docs_in,
|
||||
sd.decoded,
|
||||
sd.split_noop_ratio_one,
|
||||
sd.rejected_total(),
|
||||
sd.rejected_missing_field,
|
||||
sd.rejected_empty_field,
|
||||
sd.rejected_wrong_type,
|
||||
sd.rejected_malformed_date,
|
||||
sd.rejected_invalid_number,
|
||||
sd.rejected_corrupt_document,
|
||||
sr.splits_in,
|
||||
sr.splits_applied,
|
||||
sr.splits_collision_collapsed,
|
||||
sr.splits_unmapped_qm,
|
||||
sr.splits_no_eod_partner,
|
||||
sr.splits_noop_dropped,
|
||||
sr.split_events_attached,
|
||||
report.chunks,
|
||||
report.max_rows_per_chunk,
|
||||
b.bars_in,
|
||||
b.rows_out,
|
||||
b.keys_out,
|
||||
b.pre_rows_out,
|
||||
b.rth_rows_out,
|
||||
b.post_rows_out,
|
||||
b.dropped_invalid_ohlc,
|
||||
b.dropped_inconsistent_ohlc,
|
||||
b.dropped_invalid_volume,
|
||||
b.dropped_ts_out_of_range,
|
||||
b.duplicate_collapsed,
|
||||
b.duplicate_conflict_dropped,
|
||||
c.rows_in,
|
||||
c.rows_out,
|
||||
c.listings_out,
|
||||
c.pre_rows_out,
|
||||
c.rth_rows_out,
|
||||
c.post_rows_out,
|
||||
c.dropped_unmapped,
|
||||
c.listing_collision_collapsed,
|
||||
c.listing_collision_dropped,
|
||||
report.shard_count,
|
||||
report.rows_written,
|
||||
report.ilp_stats.rows,
|
||||
report.ilp_stats.bytes,
|
||||
report.ilp_stats.flushes,
|
||||
report.elapsed_secs,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "run_curate_bars_1m_tests.rs"]
|
||||
pub(crate) mod tests;
|
||||
1998
tools/curate-etl/src/run_curate_bars_1m_tests.rs
Normal file
1998
tools/curate-etl/src/run_curate_bars_1m_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
555
tools/curate-etl/src/run_curate_fx_1m.rs
Normal file
555
tools/curate-etl/src/run_curate_fx_1m.rs
Normal file
|
|
@ -0,0 +1,555 @@
|
|||
//! File-to-file `fx_1m` runner (`M2.3l`).
|
||||
//!
|
||||
//! Streams a concatenated raw BSON `eodIntraday1M` dump into per-shard QuestDB ILP v2 files
|
||||
//! (`<out_dir>/fx_1m.shard-<NN>.ilp`) via [`crate::curate_fx_1m::curate_and_write_fx_1m_from_bson`].
|
||||
//!
|
||||
//! # Global Sort, Deduplication & Memory Bound
|
||||
//! - Calls [`curate_and_write_fx_1m_from_bson`] **once** over the entire input stream so timestamp
|
||||
//! sorting and `ts` deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop)
|
||||
//! are global across all BSON stream chunks, then calls [`IlpShardedWriter::finish`] exactly
|
||||
//! once after clean EOF.
|
||||
//! - **Memory bound:** `Fx1mAccumulator::push` in `src/curate_fx_1m.rs` counts non-`CAD.FOREX`
|
||||
//! rows in `dropped_wrong_code` and returns immediately without appending or allocating. Peak
|
||||
//! memory is therefore bounded by:
|
||||
//! - accepted `CAD.FOREX` rows (`Vec<Fx1mRow<'static>>`),
|
||||
//! - the configured BSON stream chunk buffer (`BsonStreamOptions::chunk_capacity_bytes`,
|
||||
//! growing only for a single document up to `max_doc_bytes`), and
|
||||
//! - bounded ILP output batch buffers per shard (`IlpWriterOptions`) plus per-shard file
|
||||
//! buffering in file mode.
|
||||
//!
|
||||
//! Non-`CAD.FOREX` rows from the full `eodIntraday1M` dump are never buffered.
|
||||
//! - **Single-pair sharding:** every curated row carries `pair = "USDCAD"` and `source = "eod"`,
|
||||
//! so [`IlpShardedWriter`] routes all rows deterministically to
|
||||
//! `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files.
|
||||
//! - **Timestamp provenance:** preserves EODHD's UTC microsecond bar-start `ts` and CAD-per-USD
|
||||
//! OHLC bits verbatim; bar-start `ts` alone does not establish when the bar's close was
|
||||
//! observable.
|
||||
//! - **Omitted framing counters:** [`CurateFx1mRunReport`] omits `intraday_docs_framed` and
|
||||
//! `intraday_bytes_read` because [`curate_and_write_fx_1m_from_bson`] owns the underlying
|
||||
//! `RawBsonChunkReader` internally and returns [`BsonEodIntradayDecodeStats`] only.
|
||||
//!
|
||||
//! # File Publication & Fail-Closed Guarantees
|
||||
//! - Preflight scans `out_dir` for **any** pre-existing `fx_1m.shard-<digits>.ilp` file
|
||||
//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards
|
||||
//! from a prior run cannot survive alongside a new export.
|
||||
//! - Each shard writes into an exclusively created staging file in `out_dir`
|
||||
//! (`.fx_1m.shard-<NN>.<run_id>.tmp`), flushes and `sync_all`s on `finish`, and publishes to
|
||||
//! `fx_1m.shard-<NN>.ilp` via same-directory `hard_link` followed by removing the staged name
|
||||
//! (preserving no-overwrite semantics even if a final file appears after preflight).
|
||||
//! - Any error (validation, missing input, fatal BSON framing/I/O, ILP write/flush, or
|
||||
//! publication collision) rolls back only final files created by this run, removes this run's
|
||||
//! staging files, and leaves pre-existing files untouched. Per-document semantic decode errors
|
||||
//! stay counted-and-skipped in [`BsonEodIntradayDecodeStats`].
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bson_eod_intraday::BsonEodIntradayDecodeStats;
|
||||
use crate::bson_stream::{BsonStreamError, BsonStreamOptions};
|
||||
use crate::curate_fx_1m::{
|
||||
curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, CurateFx1mStats,
|
||||
};
|
||||
use crate::ilp::{
|
||||
IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, TABLE_FX_1M,
|
||||
};
|
||||
use crate::parquet_bars::RollbackFailure;
|
||||
use crate::parquet_publish::{next_run_id, StagingFileGuard};
|
||||
use crate::run_curate_bars_1m::{
|
||||
create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir,
|
||||
publish_staged_shards_for_table, ShardPublishError, SyncedBufFile,
|
||||
};
|
||||
|
||||
/// Arguments for [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateFx1mArgs {
|
||||
pub intraday_path: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
pub shard_count: usize,
|
||||
pub stream_options: BsonStreamOptions,
|
||||
pub ilp_options: IlpWriterOptions,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`].
|
||||
///
|
||||
/// `intraday_docs_framed` and `intraday_bytes_read` are intentionally omitted because
|
||||
/// [`curate_and_write_fx_1m_from_bson`] owns the underlying `RawBsonChunkReader` and returns
|
||||
/// [`BsonEodIntradayDecodeStats`] only.
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `decode.docs_seen == decode.rows_decoded + decode.rejected_total()`
|
||||
/// - `decode.rows_decoded == curate_stats.bars_in`
|
||||
/// - `curate_stats.bars_in == curate_stats.rows_out + curate_stats.dropped_wrong_code + curate_stats.dropped_negative_ts + curate_stats.dropped_invalid_ohlc + curate_stats.dropped_high_below_bound + curate_stats.dropped_low_above_bound + curate_stats.duplicate_collapsed + curate_stats.duplicate_conflict_dropped`
|
||||
/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::<usize>()`
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateFx1mRunReport {
|
||||
pub decode: BsonEodIntradayDecodeStats,
|
||||
pub curate_stats: CurateFx1mStats,
|
||||
pub rows_written: usize,
|
||||
pub ilp_stats: IlpWriteStats,
|
||||
pub shard_count: usize,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`run_curate_fx_1m`] and [`run_curate_fx_1m_with_readers`].
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateFx1mError {
|
||||
/// `shard_count` was `0`.
|
||||
ZeroShardCount,
|
||||
/// Caller-supplied `IlpShardedWriter` shard count did not match `args.shard_count`.
|
||||
ShardCountMismatch { expected: usize, actual: usize },
|
||||
/// Caller-supplied `IlpShardedWriter` already had queued or flushed rows before the run.
|
||||
NonEmptyWriter {
|
||||
flushed_rows: usize,
|
||||
pending_rows: usize,
|
||||
},
|
||||
/// `out_dir` exists and is not a directory.
|
||||
InvalidOutDir { path: PathBuf, detail: String },
|
||||
/// A final shard output file (`fx_1m.shard-<digits>.ilp`) already existed.
|
||||
OutputFileExists { path: PathBuf },
|
||||
/// Failed to open the input `eodIntraday1M` dump file.
|
||||
OpenInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Fatal BSON framing, option validation, or I/O error while reading `eodIntraday1M`.
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
/// ILP writer initialization, per-row write, or final flush error.
|
||||
Ilp(IlpWriterError),
|
||||
/// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files.
|
||||
Io { path: PathBuf, source: io::Error },
|
||||
/// Publication or failure cleanup failed and removing one or more final or staging files also failed.
|
||||
RollbackFailed {
|
||||
cause: Box<RunCurateFx1mError>,
|
||||
failures: Vec<RollbackFailure>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<ShardPublishError> for RunCurateFx1mError {
|
||||
fn from(err: ShardPublishError) -> Self {
|
||||
match err {
|
||||
ShardPublishError::InvalidOutDir { path, detail } => {
|
||||
Self::InvalidOutDir { path, detail }
|
||||
}
|
||||
ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path },
|
||||
ShardPublishError::Io { path, source } => Self::Io { path, source },
|
||||
ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed {
|
||||
cause: Box::new((*cause).into()),
|
||||
failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateFx1mError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::ZeroShardCount => write!(f, "shard_count must be >= 1"),
|
||||
Self::ShardCountMismatch { expected, actual } => write!(
|
||||
f,
|
||||
"ILP writer shard count mismatch: expected {expected}, got {actual}"
|
||||
),
|
||||
Self::NonEmptyWriter {
|
||||
flushed_rows,
|
||||
pending_rows,
|
||||
} => write!(
|
||||
f,
|
||||
"ILP writer must be fresh before running fx_1m (found {flushed_rows} flushed and {pending_rows} pending rows)"
|
||||
),
|
||||
Self::InvalidOutDir { path, detail } => {
|
||||
write!(f, "invalid out_dir '{}': {detail}", path.display())
|
||||
}
|
||||
Self::OutputFileExists { path } => write!(
|
||||
f,
|
||||
"refusing to overwrite existing output file '{}'",
|
||||
path.display()
|
||||
),
|
||||
Self::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
|
||||
Self::BsonStream {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
||||
Self::Ilp(err) => write!(f, "fx_1m ILP writer failed: {err}"),
|
||||
Self::Io { path, source } => {
|
||||
write!(f, "I/O error on '{}': {source}", path.display())
|
||||
}
|
||||
Self::RollbackFailed { cause, failures } => {
|
||||
write!(f, "{cause}; rollback also failed for: ")?;
|
||||
for (i, failure) in failures.iter().enumerate() {
|
||||
if i > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{failure}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateFx1mError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source),
|
||||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::Ilp(err) => Some(err),
|
||||
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
|
||||
Self::ZeroShardCount
|
||||
| Self::ShardCountMismatch { .. }
|
||||
| Self::NonEmptyWriter { .. }
|
||||
| Self::InvalidOutDir { .. }
|
||||
| Self::OutputFileExists { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_common_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> {
|
||||
if args.shard_count == 0 {
|
||||
return Err(RunCurateFx1mError::ZeroShardCount);
|
||||
}
|
||||
args.stream_options
|
||||
.validate()
|
||||
.map_err(|source| RunCurateFx1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_file_mode_args(args: &CurateFx1mArgs) -> Result<(), RunCurateFx1mError> {
|
||||
validate_common_args(args)?;
|
||||
if args.ilp_options.max_batch_bytes == 0 {
|
||||
return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchBytes));
|
||||
}
|
||||
if args.ilp_options.max_batch_rows == 0 {
|
||||
return Err(RunCurateFx1mError::Ilp(IlpWriterError::ZeroMaxBatchRows));
|
||||
}
|
||||
preflight_shard_out_dir(&args.out_dir, TABLE_FX_1M)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_curate_fx_1m_with_readers_inner<R, W>(
|
||||
args: &CurateFx1mArgs,
|
||||
intraday: R,
|
||||
mut writer: IlpShardedWriter<W>,
|
||||
start: Instant,
|
||||
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let bson_report =
|
||||
curate_and_write_fx_1m_from_bson(intraday, args.stream_options, &mut writer).map_err(
|
||||
|err| match err {
|
||||
CurateFx1mBsonError::Stream(source) => RunCurateFx1mError::BsonStream {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
},
|
||||
CurateFx1mBsonError::Write(err) => RunCurateFx1mError::Ilp(err),
|
||||
},
|
||||
)?;
|
||||
|
||||
let ilp_stats = writer.finish().map_err(RunCurateFx1mError::Ilp)?;
|
||||
|
||||
Ok(CurateFx1mRunReport {
|
||||
decode: bson_report.decode_stats,
|
||||
curate_stats: bson_report.write_report.curate_stats,
|
||||
rows_written: bson_report.write_report.rows_written,
|
||||
ilp_stats,
|
||||
shard_count: args.shard_count,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the `fx_1m` curation pipeline from an arbitrary [`io::Read`] stream into a caller-owned
|
||||
/// [`IlpShardedWriter`].
|
||||
///
|
||||
/// Validates `args`, writer shard-count agreement, and that `writer` is fresh (zero queued or
|
||||
/// flushed rows) before reading `intraday`. Calls [`curate_and_write_fx_1m_from_bson`] once over
|
||||
/// the entire stream for global sort and `ts` deduplication, and calls [`IlpShardedWriter::finish`]
|
||||
/// exactly once after clean EOF.
|
||||
pub fn run_curate_fx_1m_with_readers<R, W>(
|
||||
args: &CurateFx1mArgs,
|
||||
intraday: R,
|
||||
writer: IlpShardedWriter<W>,
|
||||
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_common_args(args)?;
|
||||
if writer.shard_count() != args.shard_count {
|
||||
return Err(RunCurateFx1mError::ShardCountMismatch {
|
||||
expected: args.shard_count,
|
||||
actual: writer.shard_count(),
|
||||
});
|
||||
}
|
||||
let (flushed_rows, pending_rows) = writer.row_counts();
|
||||
if flushed_rows > 0 || pending_rows > 0 {
|
||||
return Err(RunCurateFx1mError::NonEmptyWriter {
|
||||
flushed_rows,
|
||||
pending_rows,
|
||||
});
|
||||
}
|
||||
|
||||
run_curate_fx_1m_with_readers_inner(args, intraday, writer, start)
|
||||
}
|
||||
|
||||
pub(crate) fn cleanup_armed_staged_shards<RF>(
|
||||
staged: &mut [(PathBuf, StagingFileGuard)],
|
||||
remove_file: &mut RF,
|
||||
) -> Vec<RollbackFailure>
|
||||
where
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
let mut failures = Vec::new();
|
||||
for (tmp_path, guard) in staged.iter_mut() {
|
||||
if !guard.is_armed() {
|
||||
continue;
|
||||
}
|
||||
match remove_file(tmp_path) {
|
||||
Ok(()) => guard.disarm(),
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => guard.disarm(),
|
||||
Err(source) => {
|
||||
guard.disarm();
|
||||
failures.push(RollbackFailure {
|
||||
final_path: tmp_path.clone(),
|
||||
backup_path: None,
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
fn fail_with_staging_cleanup<RF>(
|
||||
cause: RunCurateFx1mError,
|
||||
staged: &mut [(PathBuf, StagingFileGuard)],
|
||||
remove_file: &mut RF,
|
||||
) -> RunCurateFx1mError
|
||||
where
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
let staging_failures = cleanup_armed_staged_shards(staged, remove_file);
|
||||
if staging_failures.is_empty() {
|
||||
return cause;
|
||||
}
|
||||
match cause {
|
||||
RunCurateFx1mError::RollbackFailed {
|
||||
cause: inner_cause,
|
||||
mut failures,
|
||||
} => {
|
||||
failures.extend(staging_failures);
|
||||
RunCurateFx1mError::RollbackFailed {
|
||||
cause: inner_cause,
|
||||
failures,
|
||||
}
|
||||
}
|
||||
other => RunCurateFx1mError::RollbackFailed {
|
||||
cause: Box::new(other),
|
||||
failures: staging_failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging
|
||||
/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging
|
||||
/// unlink failure reporting deterministically.
|
||||
fn run_curate_fx_1m_to_dir_with_cleanup_hook<R, W, SF, BL, RF>(
|
||||
args: &CurateFx1mArgs,
|
||||
intraday: R,
|
||||
mut make_sink: SF,
|
||||
before_link: BL,
|
||||
mut remove_staged_file: RF,
|
||||
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateFx1mError::Io {
|
||||
path: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let run_id = next_run_id();
|
||||
let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count);
|
||||
let mut sinks: Vec<W> = Vec::with_capacity(args.shard_count);
|
||||
for shard_idx in 0..args.shard_count {
|
||||
let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table(
|
||||
&args.out_dir,
|
||||
TABLE_FX_1M,
|
||||
shard_idx,
|
||||
&run_id,
|
||||
) {
|
||||
Ok(pair) => pair,
|
||||
Err(err) => {
|
||||
drop(sinks);
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err.into(),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
let guard = StagingFileGuard::new(tmp_path.clone());
|
||||
staged.push((tmp_path, guard));
|
||||
sinks.push(make_sink(shard_idx, file));
|
||||
}
|
||||
|
||||
let writer = match IlpShardedWriter::new(sinks, args.ilp_options) {
|
||||
Ok(writer) => writer,
|
||||
Err(err) => {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
RunCurateFx1mError::Ilp(err),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
let report = match run_curate_fx_1m_with_readers_inner(args, intraday, writer, start) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err,
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) =
|
||||
publish_staged_shards_for_table(&args.out_dir, TABLE_FX_1M, &mut staged, before_link)
|
||||
{
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err.into(),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests
|
||||
/// can exercise staging, writer failure, and post-preflight publication rollback through the exact
|
||||
/// file publication path.
|
||||
fn run_curate_fx_1m_to_dir_with_hooks<R, W, SF, BL>(
|
||||
args: &CurateFx1mArgs,
|
||||
intraday: R,
|
||||
make_sink: SF,
|
||||
before_link: BL,
|
||||
) -> Result<CurateFx1mRunReport, RunCurateFx1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
{
|
||||
run_curate_fx_1m_to_dir_with_cleanup_hook(
|
||||
args,
|
||||
intraday,
|
||||
make_sink,
|
||||
before_link,
|
||||
|path| fs::remove_file(path),
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB
|
||||
/// ILP v2 files (`<out_dir>/fx_1m.shard-<NN>.ilp`).
|
||||
pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result<CurateFx1mRunReport, RunCurateFx1mError> {
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let intraday_file = File::open(&args.intraday_path).map_err(|source| {
|
||||
RunCurateFx1mError::OpenInput {
|
||||
label: "eod-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
|
||||
run_curate_fx_1m_to_dir_with_hooks(
|
||||
args,
|
||||
intraday_file,
|
||||
|_shard_idx, file| SyncedBufFile::new(file),
|
||||
|_shard_idx, _final_path| {},
|
||||
)
|
||||
}
|
||||
|
||||
/// Formats [`CurateFx1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_fx_1m_report(report: &CurateFx1mRunReport) -> String {
|
||||
let per_shard = if report.ilp_stats.per_shard_rows.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
report
|
||||
.ilp_stats
|
||||
.per_shard_rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, count)| format!("{idx:02}={count}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
};
|
||||
|
||||
let d = &report.decode;
|
||||
let c = &report.curate_stats;
|
||||
|
||||
format!(
|
||||
"curate-etl curate-fx-1m\n\
|
||||
\x20 intraday_bson: docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\
|
||||
\x20 curate: bars_in={} rows_out={} wrong_code={} negative_ts={} invalid_ohlc={} high_below_bound={} low_above_bound={} dup_collapsed={} dup_conflict_dropped={}\n\
|
||||
\x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\
|
||||
\x20 timing: elapsed_secs={:.6}",
|
||||
d.docs_seen,
|
||||
d.rows_decoded,
|
||||
d.rejected_total(),
|
||||
d.rejected_missing_field,
|
||||
d.rejected_empty_field,
|
||||
d.rejected_wrong_type,
|
||||
d.rejected_invalid_timestamp,
|
||||
d.rejected_invalid_number,
|
||||
d.rejected_corrupt_document,
|
||||
c.bars_in,
|
||||
c.rows_out,
|
||||
c.dropped_wrong_code,
|
||||
c.dropped_negative_ts,
|
||||
c.dropped_invalid_ohlc,
|
||||
c.dropped_high_below_bound,
|
||||
c.dropped_low_above_bound,
|
||||
c.duplicate_collapsed,
|
||||
c.duplicate_conflict_dropped,
|
||||
report.shard_count,
|
||||
report.rows_written,
|
||||
report.ilp_stats.rows,
|
||||
report.ilp_stats.bytes,
|
||||
report.ilp_stats.flushes,
|
||||
report.elapsed_secs,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "run_curate_fx_1m_tests.rs"]
|
||||
mod tests;
|
||||
1728
tools/curate-etl/src/run_curate_fx_1m_tests.rs
Normal file
1728
tools/curate-etl/src/run_curate_fx_1m_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
643
tools/curate-etl/src/run_curate_qm_bars_1m.rs
Normal file
643
tools/curate-etl/src/run_curate_qm_bars_1m.rs
Normal file
|
|
@ -0,0 +1,643 @@
|
|||
//! Bounded-memory file-to-file `qmIntraday` -> `bars_1m` runner (`M2.3m`).
|
||||
//!
|
||||
//! Streams a concatenated raw BSON `qmIntraday` dump alongside a headerless 5-column
|
||||
//! `provider_mapping.tsv` into per-shard QuestDB ILP v2 files
|
||||
//! (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`) via [`crate::curate_qm_bars_1m`].
|
||||
//!
|
||||
//! # Bounded-Memory Chunking & Zero Split Un-Adjustment
|
||||
//! - Drives [`RawBsonChunkReader::with_options`], [`RawBsonChunkReader::next_chunk`], and
|
||||
//! [`decode_qm_intraday_buffer`] directly—the exact reader and buffer decoder wrapped by
|
||||
//! `crate::bson_stream::decode_qm_intraday_chunks`, whose callback API hides chunk boundaries.
|
||||
//! - Each framed chunk is decoded into a chunk-local `Vec<EodIntradayBar<&str>>` borrowing
|
||||
//! `qmSearchCode` directly from the chunk slice, then curated per chunk via
|
||||
//! [`curate_and_write_qm_bars_1m`] against one shared [`IlpShardedWriter`]. Borrows are
|
||||
//! consumed before advancing the chunk reader.
|
||||
//! - Takes no splits input: `qmIntraday` raw fields (`open..close`, `sharevolume`) are already
|
||||
//! un-adjusted (`design/DATA-CONTRACTS.md` §1) and pass through bit-identical (aside from
|
||||
//! `-0.0 -> +0.0` volume normalization).
|
||||
//! - [`IlpShardedWriter::finish`] is called exactly once after clean EOF.
|
||||
//! - Peak memory is bounded by the `provider_mapping` table, the current BSON chunk
|
||||
//! (`BsonStreamOptions::chunk_capacity_bytes`, growing only for a single document up to
|
||||
//! `max_doc_bytes`), that chunk's curation buffers, and one ILP batch buffer per shard—
|
||||
//! independent of the total `qmIntraday` input size.
|
||||
//!
|
||||
//! # Cross-Chunk Semantics, Output Naming & Reporting
|
||||
//! - Collision collapse/drop in `curate_qm_bars_1m` and row ordering apply **per chunk**: output
|
||||
//! is sorted by `(listing_id, ts)` within each chunk, and the same `(listing_id, ts)` appearing
|
||||
//! in two different chunks is emitted twice (with zero within-chunk collapse between them) and
|
||||
//! relies on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`.
|
||||
//! - `CurateQmBars1mRunReport::curate_stats` sums every field of [`CurateBars1mStats`] and its
|
||||
//! nested [`crate::bars_1m::Bars1mStats`] across chunks. In particular,
|
||||
//! `curate_stats.listings_out` and `curate_stats.builder.keys_out` are **sums of per-chunk
|
||||
//! counts**, not global distinct counts.
|
||||
//! - Output files use the distinct shard prefix `bars_1m_qm` (`bars_1m_qm.shard-<NN>.ilp`) so a
|
||||
//! QM run can share `out_dir` with `run_curate_bars_1m` (`bars_1m.shard-<NN>.ilp`) without
|
||||
//! tripping either preflight, while every emitted ILP v2 row still targets QuestDB table
|
||||
//! `bars_1m` (`TABLE_BARS_1M`) with `source=qm_raw` (`BARS_1M_SOURCE_QM`).
|
||||
//! - `mapping_source` is caller-supplied and forwarded verbatim to `curate_and_write_qm_bars_1m`
|
||||
//! after rejecting empty or whitespace-only values (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`).
|
||||
//! - `known_at_micros` is a caller-supplied run timestamp written verbatim to every ILP row's
|
||||
//! `known_at` column; it supplies no evidence of earlier market availability.
|
||||
//!
|
||||
//! # File Publication & Fail-Closed Guarantees
|
||||
//! - Preflight scans `out_dir` for **any** pre-existing `bars_1m_qm.shard-<digits>.ilp` file
|
||||
//! (regardless of the requested `shard_count`) and fails closed before staging so stale shards
|
||||
//! from a prior larger-shard-count run cannot survive alongside a new export.
|
||||
//! - Each shard writes into an exclusively created staging file in `out_dir`
|
||||
//! (`.bars_1m_qm.shard-<NN>.<run_id>.tmp`), flushes and `sync_all`s on `finish`, and publishes
|
||||
//! to `bars_1m_qm.shard-<NN>.ilp` via same-directory `hard_link` followed by removing the staged
|
||||
//! name (preserving no-overwrite semantics even if a final file appears after preflight).
|
||||
//! - Any error (validation, missing/malformed inputs, fatal BSON framing/I/O, ILP write/flush, or
|
||||
//! publication collision) drops open sinks, rolls back only final files created by this run,
|
||||
//! removes this run's staging files, and leaves pre-existing files untouched. Per-document
|
||||
//! semantic decode errors stay counted-and-skipped in [`BsonQmIntradayDecodeStats`].
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bars_1m::EodIntradayBar;
|
||||
use crate::bson_qm_intraday::{decode_qm_intraday_buffer, BsonQmIntradayDecodeStats};
|
||||
use crate::bson_stream::{BsonStreamError, BsonStreamOptions, RawBsonChunkReader};
|
||||
use crate::curate_bars_1m::{CurateBars1mStats, CurateBars1mWriteError};
|
||||
use crate::curate_qm_bars_1m::curate_and_write_qm_bars_1m;
|
||||
use crate::ilp::{IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions};
|
||||
use crate::parquet_bars::RollbackFailure;
|
||||
use crate::parquet_publish::{next_run_id, StagingFileGuard};
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError};
|
||||
use crate::run_curate_bars_1m::{
|
||||
add_curate_bars_1m_stats, create_exclusive_shard_tmp_file_for_table, preflight_shard_out_dir,
|
||||
publish_staged_shards_for_table, ShardPublishError, SyncedBufFile,
|
||||
};
|
||||
use crate::run_curate_fx_1m::cleanup_armed_staged_shards;
|
||||
|
||||
/// Default `provider_mapping` source namespace for `qmSearchCode` rows in `qmIntraday`.
|
||||
pub const DEFAULT_QM_BARS_1M_MAPPING_SOURCE: &str = "qm";
|
||||
|
||||
/// Output filename prefix for QM intraday shard files (`bars_1m_qm.shard-<NN>.ilp`).
|
||||
///
|
||||
/// Distinct from `TABLE_BARS_1M` (`bars_1m`) so QM and EOD intraday exports can share `out_dir`
|
||||
/// without colliding in preflight or publication while both emit ILP v2 rows into `bars_1m`.
|
||||
const QM_BARS_1M_SHARD_PREFIX: &str = "bars_1m_qm";
|
||||
|
||||
/// Arguments for [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CurateQmBars1mArgs {
|
||||
pub intraday_path: PathBuf,
|
||||
pub provider_mapping_path: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
pub mapping_source: String,
|
||||
pub shard_count: usize,
|
||||
pub known_at_micros: i64,
|
||||
pub stream_options: BsonStreamOptions,
|
||||
pub ilp_options: IlpWriterOptions,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_qm_bars_1m`] and
|
||||
/// [`run_curate_qm_bars_1m_with_readers`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `intraday_docs_framed as usize == intraday_decode.docs_seen`
|
||||
/// - `intraday_decode.docs_seen == intraday_decode.rows_decoded + intraday_decode.rejected_total()`
|
||||
/// - `intraday_decode.rows_decoded == curate_stats.builder.bars_in`
|
||||
/// - `curate_stats.rows_in == curate_stats.builder.rows_out`
|
||||
/// - `curate_stats.rows_in == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_collision_collapsed + curate_stats.listing_collision_dropped`
|
||||
/// - `curate_stats.pre_rows_out + curate_stats.rth_rows_out + curate_stats.post_rows_out == curate_stats.rows_out`
|
||||
/// - `rows_written == curate_stats.rows_out == ilp_stats.rows == ilp_stats.per_shard_rows.iter().sum::<usize>()`
|
||||
///
|
||||
/// Note: `curate_stats.listings_out` and `curate_stats.builder.keys_out` are summed across chunks
|
||||
/// (not global distinct counts).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateQmBars1mRunReport {
|
||||
pub intraday_docs_framed: u64,
|
||||
pub intraday_bytes_read: u64,
|
||||
pub intraday_decode: BsonQmIntradayDecodeStats,
|
||||
pub chunks: usize,
|
||||
pub max_rows_per_chunk: usize,
|
||||
pub curate_stats: CurateBars1mStats,
|
||||
pub rows_written: usize,
|
||||
pub ilp_stats: IlpWriteStats,
|
||||
pub shard_count: usize,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
/// Typed errors returned by [`run_curate_qm_bars_1m`] and [`run_curate_qm_bars_1m_with_readers`].
|
||||
#[derive(Debug)]
|
||||
pub enum RunCurateQmBars1mError {
|
||||
/// `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
/// `shard_count` was `0`.
|
||||
ZeroShardCount,
|
||||
/// `out_dir` exists and is not a directory.
|
||||
InvalidOutDir { path: PathBuf, detail: String },
|
||||
/// A final shard output file (`bars_1m_qm.shard-<digits>.ilp`) already existed.
|
||||
OutputFileExists { path: PathBuf },
|
||||
/// Failed to open the input `qmIntraday` dump file.
|
||||
OpenInput {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: io::Error,
|
||||
},
|
||||
/// Failed to load `provider_mapping.tsv` via the shared reference loader.
|
||||
LoadReference(RunCurateBarsError),
|
||||
/// Fatal BSON framing, option validation, or I/O error while reading `qmIntraday`.
|
||||
BsonStream {
|
||||
label: &'static str,
|
||||
path: PathBuf,
|
||||
source: BsonStreamError,
|
||||
},
|
||||
/// Curation or per-row ILP write error inside the per-chunk `qmIntraday` curation stage.
|
||||
CurateWrite(CurateBars1mWriteError),
|
||||
/// ILP writer initialization or final flush error.
|
||||
Ilp(IlpWriterError),
|
||||
/// Filesystem I/O error while creating, syncing, linking, or cleaning up shard files.
|
||||
Io { path: PathBuf, source: io::Error },
|
||||
/// Publication or failure cleanup failed and removing one or more final or staging files also
|
||||
/// failed.
|
||||
RollbackFailed {
|
||||
cause: Box<RunCurateQmBars1mError>,
|
||||
failures: Vec<RollbackFailure>,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<ShardPublishError> for RunCurateQmBars1mError {
|
||||
fn from(err: ShardPublishError) -> Self {
|
||||
match err {
|
||||
ShardPublishError::InvalidOutDir { path, detail } => {
|
||||
Self::InvalidOutDir { path, detail }
|
||||
}
|
||||
ShardPublishError::OutputFileExists { path } => Self::OutputFileExists { path },
|
||||
ShardPublishError::Io { path, source } => Self::Io { path, source },
|
||||
ShardPublishError::RollbackFailed { cause, failures } => Self::RollbackFailed {
|
||||
cause: Box::new((*cause).into()),
|
||||
failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RunCurateQmBars1mError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::EmptyMappingSource => write!(f, "mapping_source must not be empty or blank"),
|
||||
Self::ZeroShardCount => write!(f, "shard_count must be >= 1"),
|
||||
Self::InvalidOutDir { path, detail } => {
|
||||
write!(f, "invalid out_dir '{}': {detail}", path.display())
|
||||
}
|
||||
Self::OutputFileExists { path } => write!(
|
||||
f,
|
||||
"refusing to overwrite existing output file '{}'",
|
||||
path.display()
|
||||
),
|
||||
Self::OpenInput {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed to open {label} '{}': {source}", path.display()),
|
||||
Self::LoadReference(err) => write!(f, "failed loading reference inputs: {err}"),
|
||||
Self::BsonStream {
|
||||
label,
|
||||
path,
|
||||
source,
|
||||
} => write!(f, "failed reading {label} '{}': {source}", path.display()),
|
||||
Self::CurateWrite(err) => write!(f, "{err}"),
|
||||
Self::Ilp(err) => write!(f, "qm bars_1m ILP writer failed: {err}"),
|
||||
Self::Io { path, source } => {
|
||||
write!(f, "I/O error on '{}': {source}", path.display())
|
||||
}
|
||||
Self::RollbackFailed { cause, failures } => {
|
||||
write!(f, "{cause}; rollback also failed for: ")?;
|
||||
for (i, failure) in failures.iter().enumerate() {
|
||||
if i > 0 {
|
||||
write!(f, ", ")?;
|
||||
}
|
||||
write!(f, "{failure}")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for RunCurateQmBars1mError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::OpenInput { source, .. } | Self::Io { source, .. } => Some(source),
|
||||
Self::LoadReference(err) => Some(err),
|
||||
Self::BsonStream { source, .. } => Some(source),
|
||||
Self::CurateWrite(err) => Some(err),
|
||||
Self::Ilp(err) => Some(err),
|
||||
Self::RollbackFailed { cause, .. } => Some(cause.as_ref()),
|
||||
Self::EmptyMappingSource
|
||||
| Self::ZeroShardCount
|
||||
| Self::InvalidOutDir { .. }
|
||||
| Self::OutputFileExists { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_common_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> {
|
||||
if args.mapping_source.trim().is_empty() {
|
||||
return Err(RunCurateQmBars1mError::EmptyMappingSource);
|
||||
}
|
||||
if args.shard_count == 0 {
|
||||
return Err(RunCurateQmBars1mError::ZeroShardCount);
|
||||
}
|
||||
args.stream_options
|
||||
.validate()
|
||||
.map_err(|source| RunCurateQmBars1mError::BsonStream {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
if args.ilp_options.max_batch_bytes == 0 {
|
||||
return Err(RunCurateQmBars1mError::Ilp(
|
||||
IlpWriterError::ZeroMaxBatchBytes,
|
||||
));
|
||||
}
|
||||
if args.ilp_options.max_batch_rows == 0 {
|
||||
return Err(RunCurateQmBars1mError::Ilp(
|
||||
IlpWriterError::ZeroMaxBatchRows,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_file_mode_args(args: &CurateQmBars1mArgs) -> Result<(), RunCurateQmBars1mError> {
|
||||
validate_common_args(args)?;
|
||||
preflight_shard_out_dir(&args.out_dir, QM_BARS_1M_SHARD_PREFIX)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_provider_mapping_table(
|
||||
provider_mapping_path: &Path,
|
||||
) -> Result<ProviderMappingTable, RunCurateQmBars1mError> {
|
||||
let mapping_rows = load_provider_mapping_tsv(provider_mapping_path)
|
||||
.map_err(RunCurateQmBars1mError::LoadReference)?;
|
||||
ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateQmBars1mError::LoadReference(RunCurateBarsError::ProviderMapping {
|
||||
path: provider_mapping_path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn stream_qm_intraday_chunks_to_writer<R, W>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
mapping: &ProviderMappingTable,
|
||||
intraday: R,
|
||||
mut writer: IlpShardedWriter<W>,
|
||||
start: Instant,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
{
|
||||
let mut reader = RawBsonChunkReader::with_options(intraday, args.stream_options).map_err(
|
||||
|source| RunCurateQmBars1mError::BsonStream {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
},
|
||||
)?;
|
||||
|
||||
let mut intraday_decode = BsonQmIntradayDecodeStats::default();
|
||||
let mut curate_stats = CurateBars1mStats::default();
|
||||
let mut chunks: usize = 0;
|
||||
let mut max_rows_per_chunk: usize = 0;
|
||||
let mut rows_written: usize = 0;
|
||||
|
||||
while let Some(chunk) =
|
||||
reader
|
||||
.next_chunk()
|
||||
.map_err(|source| RunCurateQmBars1mError::BsonStream {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?
|
||||
{
|
||||
let mut chunk_bars: Vec<EodIntradayBar<&str>> = Vec::new();
|
||||
let chunk_decode = decode_qm_intraday_buffer(
|
||||
chunk.bytes,
|
||||
|raw| {
|
||||
chunk_bars.push(raw.into_eod_intraday_bar(|key, _| key));
|
||||
},
|
||||
|_local_offset, _err| {},
|
||||
);
|
||||
intraday_decode.merge(&chunk_decode);
|
||||
|
||||
chunks += 1;
|
||||
let chunk_len = chunk_bars.len();
|
||||
if chunk_len > max_rows_per_chunk {
|
||||
max_rows_per_chunk = chunk_len;
|
||||
}
|
||||
|
||||
let write_report = curate_and_write_qm_bars_1m(
|
||||
chunk_bars,
|
||||
mapping,
|
||||
&args.mapping_source,
|
||||
&mut writer,
|
||||
args.known_at_micros,
|
||||
)
|
||||
.map_err(RunCurateQmBars1mError::CurateWrite)?;
|
||||
|
||||
add_curate_bars_1m_stats(&mut curate_stats, &write_report.curate_stats);
|
||||
rows_written += write_report.rows_written;
|
||||
}
|
||||
|
||||
let intraday_docs_framed = reader.docs_framed();
|
||||
let intraday_bytes_read = reader.bytes_read();
|
||||
let ilp_stats = writer.finish().map_err(RunCurateQmBars1mError::Ilp)?;
|
||||
|
||||
Ok(CurateQmBars1mRunReport {
|
||||
intraday_docs_framed,
|
||||
intraday_bytes_read,
|
||||
intraday_decode,
|
||||
chunks,
|
||||
max_rows_per_chunk,
|
||||
curate_stats,
|
||||
rows_written,
|
||||
ilp_stats,
|
||||
shard_count: args.shard_count,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary
|
||||
/// [`io::Read`] stream into per-shard sinks created by `make_sink`.
|
||||
///
|
||||
/// Validates `args` (rejecting blank `mapping_source` first, then `shard_count`, stream options,
|
||||
/// and ILP options) and loads `provider_mapping.tsv` from `args.provider_mapping_path` before
|
||||
/// calling `make_sink` once per shard (`0..args.shard_count`). Streams `intraday` through
|
||||
/// [`RawBsonChunkReader::with_options`] + [`decode_qm_intraday_buffer`], curating and writing once
|
||||
/// per chunk without split un-adjustment, and calls [`IlpShardedWriter::finish`] exactly once
|
||||
/// after clean EOF.
|
||||
pub fn run_curate_qm_bars_1m_with_readers<R, W, F>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
intraday: R,
|
||||
mut make_sink: F,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
F: FnMut(usize) -> W,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_common_args(args)?;
|
||||
|
||||
let mapping = load_provider_mapping_table(&args.provider_mapping_path)?;
|
||||
|
||||
let mut sinks = Vec::with_capacity(args.shard_count);
|
||||
for shard_idx in 0..args.shard_count {
|
||||
sinks.push(make_sink(shard_idx));
|
||||
}
|
||||
let writer =
|
||||
IlpShardedWriter::new(sinks, args.ilp_options).map_err(RunCurateQmBars1mError::Ilp)?;
|
||||
|
||||
stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
|
||||
}
|
||||
|
||||
fn fail_with_staging_cleanup<RF>(
|
||||
cause: RunCurateQmBars1mError,
|
||||
staged: &mut [(PathBuf, StagingFileGuard)],
|
||||
remove_file: &mut RF,
|
||||
) -> RunCurateQmBars1mError
|
||||
where
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
let staging_failures = cleanup_armed_staged_shards(staged, remove_file);
|
||||
if staging_failures.is_empty() {
|
||||
return cause;
|
||||
}
|
||||
match cause {
|
||||
RunCurateQmBars1mError::RollbackFailed {
|
||||
cause: inner_cause,
|
||||
mut failures,
|
||||
} => {
|
||||
failures.extend(staging_failures);
|
||||
RunCurateQmBars1mError::RollbackFailed {
|
||||
cause: inner_cause,
|
||||
failures,
|
||||
}
|
||||
}
|
||||
other => RunCurateQmBars1mError::RollbackFailed {
|
||||
cause: Box::new(other),
|
||||
failures: staging_failures,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting an injected reader, sink factory, pre-link hook, and staging
|
||||
/// unlink hook so tests can exercise staging, writer failure, publication rollback, and staging
|
||||
/// unlink failure reporting deterministically.
|
||||
fn run_curate_qm_bars_1m_to_dir_with_cleanup_hook<R, W, SF, BL, RF>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
intraday: R,
|
||||
mut make_sink: SF,
|
||||
before_link: BL,
|
||||
mut remove_staged_file: RF,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
RF: FnMut(&Path) -> io::Result<()>,
|
||||
{
|
||||
let start = Instant::now();
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let mapping = load_provider_mapping_table(&args.provider_mapping_path)?;
|
||||
|
||||
fs::create_dir_all(&args.out_dir).map_err(|source| RunCurateQmBars1mError::Io {
|
||||
path: args.out_dir.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
let run_id = next_run_id();
|
||||
let mut staged: Vec<(PathBuf, StagingFileGuard)> = Vec::with_capacity(args.shard_count);
|
||||
let mut sinks: Vec<W> = Vec::with_capacity(args.shard_count);
|
||||
for shard_idx in 0..args.shard_count {
|
||||
let (tmp_path, file) = match create_exclusive_shard_tmp_file_for_table(
|
||||
&args.out_dir,
|
||||
QM_BARS_1M_SHARD_PREFIX,
|
||||
shard_idx,
|
||||
&run_id,
|
||||
) {
|
||||
Ok(pair) => pair,
|
||||
Err(err) => {
|
||||
drop(sinks);
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err.into(),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
let guard = StagingFileGuard::new(tmp_path.clone());
|
||||
staged.push((tmp_path, guard));
|
||||
sinks.push(make_sink(shard_idx, file));
|
||||
}
|
||||
|
||||
let writer = match IlpShardedWriter::new(sinks, args.ilp_options) {
|
||||
Ok(writer) => writer,
|
||||
Err(err) => {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
RunCurateQmBars1mError::Ilp(err),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
let report = match stream_qm_intraday_chunks_to_writer(args, &mapping, intraday, writer, start)
|
||||
{
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err,
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = publish_staged_shards_for_table(
|
||||
&args.out_dir,
|
||||
QM_BARS_1M_SHARD_PREFIX,
|
||||
&mut staged,
|
||||
before_link,
|
||||
) {
|
||||
return Err(fail_with_staging_cleanup(
|
||||
err.into(),
|
||||
&mut staged,
|
||||
&mut remove_staged_file,
|
||||
));
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// Private file-mode seam accepting an injected reader, sink factory, and pre-link hook so tests
|
||||
/// can exercise staging, writer failure, and post-preflight publication rollback through the exact
|
||||
/// file publication path.
|
||||
fn run_curate_qm_bars_1m_to_dir_with_hooks<R, W, SF, BL>(
|
||||
args: &CurateQmBars1mArgs,
|
||||
intraday: R,
|
||||
make_sink: SF,
|
||||
before_link: BL,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError>
|
||||
where
|
||||
R: io::Read,
|
||||
W: Write + Send,
|
||||
SF: FnMut(usize, File) -> W,
|
||||
BL: FnMut(usize, &Path),
|
||||
{
|
||||
run_curate_qm_bars_1m_to_dir_with_cleanup_hook(
|
||||
args,
|
||||
intraday,
|
||||
make_sink,
|
||||
before_link,
|
||||
|path| fs::remove_file(path),
|
||||
)
|
||||
}
|
||||
|
||||
/// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing
|
||||
/// exactly `args.shard_count` QuestDB ILP v2 files (`<out_dir>/bars_1m_qm.shard-<NN>.ilp`).
|
||||
pub fn run_curate_qm_bars_1m(
|
||||
args: &CurateQmBars1mArgs,
|
||||
) -> Result<CurateQmBars1mRunReport, RunCurateQmBars1mError> {
|
||||
validate_file_mode_args(args)?;
|
||||
|
||||
let intraday_file =
|
||||
File::open(&args.intraday_path).map_err(|source| RunCurateQmBars1mError::OpenInput {
|
||||
label: "qm-intraday",
|
||||
path: args.intraday_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
run_curate_qm_bars_1m_to_dir_with_hooks(
|
||||
args,
|
||||
intraday_file,
|
||||
|_shard_idx, file| SyncedBufFile::new(file),
|
||||
|_shard_idx, _final_path| {},
|
||||
)
|
||||
}
|
||||
|
||||
/// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary.
|
||||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_qm_bars_1m_report(report: &CurateQmBars1mRunReport) -> String {
|
||||
let per_shard = if report.ilp_stats.per_shard_rows.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
report
|
||||
.ilp_stats
|
||||
.per_shard_rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, count)| format!("{idx:02}={count}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
};
|
||||
|
||||
let b = &report.curate_stats.builder;
|
||||
let c = &report.curate_stats;
|
||||
let d = &report.intraday_decode;
|
||||
|
||||
format!(
|
||||
"curate-etl curate-qm-bars-1m\n\
|
||||
\x20 intraday_bson: docs_framed={} bytes_read={} docs_seen={} rows_decoded={} rejected={} (missing={} empty={} wrong_type={} invalid_ts={} invalid_num={} corrupt={})\n\
|
||||
\x20 chunking: chunks={} max_rows_per_chunk={} cross_chunk_dedup=questdb_dedup_upsert_keys(ts,listing_id)\n\
|
||||
\x20 builder: bars_in={} rows_out={} keys_out_per_chunk_sum={} pre={} rth={} post={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_out_of_range={} dup_collapsed={} dup_conflict_dropped={}\n\
|
||||
\x20 curate: rows_in={} rows_out={} listings_out_per_chunk_sum={} pre={} rth={} post={} dropped_unmapped={} listing_collision_collapsed={} listing_collision_dropped={}\n\
|
||||
\x20 ilp: shards={} rows_written={} ilp_rows={} bytes={} flushes={} per_shard_rows={per_shard}\n\
|
||||
\x20 timing: elapsed_secs={:.6}",
|
||||
report.intraday_docs_framed,
|
||||
report.intraday_bytes_read,
|
||||
d.docs_seen,
|
||||
d.rows_decoded,
|
||||
d.rejected_total(),
|
||||
d.rejected_missing_field,
|
||||
d.rejected_empty_field,
|
||||
d.rejected_wrong_type,
|
||||
d.rejected_invalid_timestamp,
|
||||
d.rejected_invalid_number,
|
||||
d.rejected_corrupt_document,
|
||||
report.chunks,
|
||||
report.max_rows_per_chunk,
|
||||
b.bars_in,
|
||||
b.rows_out,
|
||||
b.keys_out,
|
||||
b.pre_rows_out,
|
||||
b.rth_rows_out,
|
||||
b.post_rows_out,
|
||||
b.dropped_invalid_ohlc,
|
||||
b.dropped_inconsistent_ohlc,
|
||||
b.dropped_invalid_volume,
|
||||
b.dropped_ts_out_of_range,
|
||||
b.duplicate_collapsed,
|
||||
b.duplicate_conflict_dropped,
|
||||
c.rows_in,
|
||||
c.rows_out,
|
||||
c.listings_out,
|
||||
c.pre_rows_out,
|
||||
c.rth_rows_out,
|
||||
c.post_rows_out,
|
||||
c.dropped_unmapped,
|
||||
c.listing_collision_collapsed,
|
||||
c.listing_collision_dropped,
|
||||
report.shard_count,
|
||||
report.rows_written,
|
||||
report.ilp_stats.rows,
|
||||
report.ilp_stats.bytes,
|
||||
report.ilp_stats.flushes,
|
||||
report.elapsed_secs,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "run_curate_qm_bars_1m_tests.rs"]
|
||||
mod tests;
|
||||
1746
tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs
Normal file
1746
tools/curate-etl/src/run_curate_qm_bars_1m_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
635
tools/curate-etl/tests/curate_bars_1m.rs
Normal file
635
tools/curate-etl/tests/curate_bars_1m.rs
Normal file
|
|
@ -0,0 +1,635 @@
|
|||
//! End-to-end binary integration tests for `curate-etl curate-bars-1m` (`M2.3n`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use curate_etl::{
|
||||
et_to_utc_micros, format_curate_bars_1m_report, run_curate_bars_1m, ymd_to_epoch_days,
|
||||
BsonStreamOptions, CurateBars1mArgs, IlpWriterOptions, DEFAULT_BARS_1M_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let pid = std::process::id();
|
||||
let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("curate-etl-it-bars-1m-{tag}-{pid}-{seq}"));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create integration test temp dir");
|
||||
Self { path }
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn run_bin(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("spawn curate-etl binary")
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn et_ts_sec(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 {
|
||||
let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp");
|
||||
assert_eq!(micros % 1_000_000, 0);
|
||||
micros / 1_000_000
|
||||
}
|
||||
|
||||
fn make_intraday_doc(
|
||||
code: &str,
|
||||
timestamp_sec: 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"), timestamp_sec);
|
||||
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 make_split_doc(
|
||||
qm_search_code: &str,
|
||||
ex_date: &str,
|
||||
for_factor: f64,
|
||||
to_factor: f64,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), qm_search_code);
|
||||
doc.append(cstr!("date"), ex_date);
|
||||
doc.append(cstr!("forfactor"), for_factor);
|
||||
doc.append(cstr!("tofactor"), to_factor);
|
||||
doc.append(cstr!("splitratio"), for_factor / to_factor);
|
||||
doc
|
||||
}
|
||||
|
||||
fn concat_docs(docs: &[RawDocumentBuf]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for doc in docs {
|
||||
out.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn read_dir_files(dir: &Path) -> BTreeMap<String, Vec<u8>> {
|
||||
let mut out = BTreeMap::new();
|
||||
for entry in fs::read_dir(dir).expect("read output dir") {
|
||||
let entry = entry.expect("dir entry");
|
||||
let name = entry
|
||||
.file_name()
|
||||
.into_string()
|
||||
.expect("UTF-8 file name in output dir");
|
||||
let bytes = fs::read(entry.path()).expect("read output file");
|
||||
out.insert(name, bytes);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn strip_timing_line(report: &str) -> Vec<&str> {
|
||||
report
|
||||
.lines()
|
||||
.filter(|line| !line.trim_start().starts_with("timing:"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_matches_direct_runner_bytes_and_report() {
|
||||
let tmp = TempDir::new("parity");
|
||||
|
||||
// Pin NVDA 10:1 forward split (2024-06-10) and NEXM 1:20 reverse split (2025-06-20)
|
||||
// fixtures in the style of src/run_curate_bars_1m_tests.rs.
|
||||
let intraday_path = tmp.path().join("eodIntraday1M.bson");
|
||||
let intraday_bytes = concat_docs(&[
|
||||
// NVDA pre-split (2024-06-07): 10:1 split un-adjusts prices x10 and volume /10.
|
||||
make_intraday_doc(
|
||||
"NVDA.US",
|
||||
et_ts_sec(2024, 6, 7, 15, 59),
|
||||
120.50,
|
||||
121.00,
|
||||
120.40,
|
||||
120.888,
|
||||
412_390.0,
|
||||
),
|
||||
// NVDA ex-date (2024-06-10): already post-split (factor = 1.0).
|
||||
make_intraday_doc(
|
||||
"NVDA.US",
|
||||
et_ts_sec(2024, 6, 10, 15, 59),
|
||||
121.50,
|
||||
122.00,
|
||||
121.20,
|
||||
121.79,
|
||||
350_000.0,
|
||||
),
|
||||
// NEXM pre-split (2025-06-18): 1:20 reverse split un-adjusts prices x0.05 and volume x20.
|
||||
make_intraday_doc(
|
||||
"NEXM.V",
|
||||
et_ts_sec(2025, 6, 18, 15, 59),
|
||||
24.20,
|
||||
24.40,
|
||||
24.10,
|
||||
24.29,
|
||||
5_000.0,
|
||||
),
|
||||
// NEXM ex-date (2025-06-20): already post-split (factor = 1.0).
|
||||
make_intraday_doc(
|
||||
"NEXM.V",
|
||||
et_ts_sec(2025, 6, 20, 15, 59),
|
||||
24.10,
|
||||
24.35,
|
||||
24.00,
|
||||
24.28,
|
||||
12_500.0,
|
||||
),
|
||||
]);
|
||||
fs::write(&intraday_path, &intraday_bytes).expect("write intraday bson");
|
||||
|
||||
let splits_path = tmp.path().join("qmSplits.bson");
|
||||
let splits_bytes = concat_docs(&[
|
||||
make_split_doc("NVDA", "2024-06-10", 1.0, 10.0),
|
||||
make_split_doc("NEXM:CA", "2025-06-20", 20.0, 1.0),
|
||||
]);
|
||||
fs::write(&splits_path, &splits_bytes).expect("write splits bson");
|
||||
|
||||
let mapping_path = tmp.path().join("provider_mapping.tsv");
|
||||
fs::write(
|
||||
&mapping_path,
|
||||
"eod\tNVDA.US\t2000-01-01\t\t1001\n\
|
||||
qm\tNVDA\t2000-01-01\t\t1001\n\
|
||||
eod\tNEXM.V\t2000-01-01\t\t2002\n\
|
||||
qm\tNEXM:CA\t2000-01-01\t\t2002\n",
|
||||
)
|
||||
.expect("write provider_mapping.tsv");
|
||||
|
||||
let known_at_micros: i64 = 1_750_000_000_000_000;
|
||||
let shard_count: usize = 2;
|
||||
|
||||
let bin_out = tmp.path().join("out-bin");
|
||||
let direct_out = tmp.path().join("out-direct");
|
||||
|
||||
let output = run_bin(&[
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
intraday_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
mapping_path.to_str().unwrap(),
|
||||
"--out",
|
||||
bin_out.to_str().unwrap(),
|
||||
"--shards",
|
||||
"2",
|
||||
"--known-at-micros",
|
||||
"1750000000000000",
|
||||
]);
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"expected exit 0, got {:?}; stderr:\n{stderr}\nstdout:\n{stdout}",
|
||||
output.status.code()
|
||||
);
|
||||
assert!(
|
||||
stderr.is_empty(),
|
||||
"expected empty stderr on success, got:\n{stderr}"
|
||||
);
|
||||
|
||||
let direct_args = CurateBars1mArgs {
|
||||
intraday_path,
|
||||
splits_path,
|
||||
provider_mapping_path: mapping_path,
|
||||
out_dir: direct_out.clone(),
|
||||
mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(),
|
||||
shard_count,
|
||||
known_at_micros,
|
||||
stream_options: BsonStreamOptions::default(),
|
||||
ilp_options: IlpWriterOptions::default(),
|
||||
};
|
||||
let direct_report = run_curate_bars_1m(&direct_args).expect("direct run_curate_bars_1m");
|
||||
assert_eq!(
|
||||
direct_report.rows_written, 4,
|
||||
"expected 4 emitted bars_1m rows"
|
||||
);
|
||||
|
||||
let direct_formatted = format_curate_bars_1m_report(&direct_report);
|
||||
assert_eq!(
|
||||
strip_timing_line(&stdout),
|
||||
strip_timing_line(&direct_formatted),
|
||||
"binary stdout report should match direct runner report excluding timing line"
|
||||
);
|
||||
assert!(
|
||||
stdout
|
||||
.lines()
|
||||
.any(|line| line.trim_start().starts_with("timing: elapsed_secs=")),
|
||||
"expected timing line in stdout:\n{stdout}"
|
||||
);
|
||||
|
||||
let bin_files = read_dir_files(&bin_out);
|
||||
let direct_files = read_dir_files(&direct_out);
|
||||
|
||||
let expected_names: Vec<String> = vec![
|
||||
"bars_1m.shard-00.ilp".to_string(),
|
||||
"bars_1m.shard-01.ilp".to_string(),
|
||||
];
|
||||
assert_eq!(
|
||||
bin_files.keys().cloned().collect::<Vec<_>>(),
|
||||
expected_names,
|
||||
"unexpected files in binary output dir"
|
||||
);
|
||||
assert_eq!(
|
||||
bin_files, direct_files,
|
||||
"binary shard files must be byte-identical to direct runner output"
|
||||
);
|
||||
assert!(
|
||||
bin_files.values().map(Vec::len).sum::<usize>() > 0,
|
||||
"expected non-empty ILP output across shards"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_missing_input_exits_nonzero_and_leaves_out_clean() {
|
||||
let tmp = TempDir::new("missing-input");
|
||||
|
||||
let missing_intraday = tmp.path().join("does-not-exist.bson");
|
||||
let splits_path = tmp.path().join("qmSplits.bson");
|
||||
fs::write(&splits_path, concat_docs(&[])).expect("write empty splits bson");
|
||||
|
||||
let mapping_path = tmp.path().join("provider_mapping.tsv");
|
||||
fs::write(&mapping_path, "eod\tNVDA.US\t2000-01-01\t\t1001\n")
|
||||
.expect("write provider_mapping.tsv");
|
||||
|
||||
let out_dir = tmp.path().join("out-empty");
|
||||
fs::create_dir_all(&out_dir).expect("create empty out dir");
|
||||
|
||||
let output = run_bin(&[
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
missing_intraday.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
mapping_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_dir.to_str().unwrap(),
|
||||
"--shards",
|
||||
"2",
|
||||
"--known-at-micros",
|
||||
"1750000000000000",
|
||||
]);
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"expected non-zero exit when intraday file is missing"
|
||||
);
|
||||
assert!(
|
||||
stdout.is_empty(),
|
||||
"expected no success report on stdout, got:\n{stdout}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains("error:") && stderr.contains("failed to open eod-intraday"),
|
||||
"expected input-open error on stderr, got:\n{stderr}"
|
||||
);
|
||||
|
||||
let remaining = read_dir_files(&out_dir);
|
||||
assert!(
|
||||
remaining.is_empty(),
|
||||
"expected no shard or staging files in output dir, found: {:?}",
|
||||
remaining.keys().collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// QA edge cases (T-186): binary-level behaviour not covered by the parity tests.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct Fixture {
|
||||
intraday: PathBuf,
|
||||
splits: PathBuf,
|
||||
mapping: PathBuf,
|
||||
}
|
||||
|
||||
/// NVDA 10:1 split fixture: one pre-split bar (2024-06-07) and one ex-date bar (2024-06-10).
|
||||
fn write_nvda_fixture(dir: &Path) -> Fixture {
|
||||
let intraday = dir.join("eodIntraday1M.bson");
|
||||
fs::write(
|
||||
&intraday,
|
||||
concat_docs(&[
|
||||
make_intraday_doc(
|
||||
"NVDA.US",
|
||||
et_ts_sec(2024, 6, 7, 15, 59),
|
||||
120.50,
|
||||
121.00,
|
||||
120.40,
|
||||
120.75,
|
||||
412_390.0,
|
||||
),
|
||||
make_intraday_doc(
|
||||
"NVDA.US",
|
||||
et_ts_sec(2024, 6, 10, 15, 59),
|
||||
121.50,
|
||||
122.00,
|
||||
121.20,
|
||||
121.75,
|
||||
350_000.0,
|
||||
),
|
||||
]),
|
||||
)
|
||||
.expect("write intraday bson");
|
||||
let splits = dir.join("qmSplits.bson");
|
||||
fs::write(&splits, concat_docs(&[make_split_doc("NVDA", "2024-06-10", 1.0, 10.0)]))
|
||||
.expect("write splits bson");
|
||||
let mapping = dir.join("provider_mapping.tsv");
|
||||
fs::write(
|
||||
&mapping,
|
||||
"eod\tNVDA.US\t2000-01-01\t\t1001\nqm\tNVDA\t2000-01-01\t\t1001\n",
|
||||
)
|
||||
.expect("write provider_mapping.tsv");
|
||||
Fixture {
|
||||
intraday,
|
||||
splits,
|
||||
mapping,
|
||||
}
|
||||
}
|
||||
|
||||
fn bin_args<'a>(
|
||||
fx: &'a Fixture,
|
||||
out: &'a Path,
|
||||
known_at: &'a str,
|
||||
extra: &[&'a str],
|
||||
) -> Vec<&'a str> {
|
||||
let mut argv = vec![
|
||||
"curate-bars-1m",
|
||||
"--eod-intraday",
|
||||
fx.intraday.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
fx.splits.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
fx.mapping.to_str().unwrap(),
|
||||
"--out",
|
||||
out.to_str().unwrap(),
|
||||
"--shards",
|
||||
"2",
|
||||
"--known-at-micros",
|
||||
known_at,
|
||||
];
|
||||
argv.extend_from_slice(extra);
|
||||
argv
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IlpRow {
|
||||
listing_id: i32,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
known_at: i64,
|
||||
ts: i64,
|
||||
}
|
||||
|
||||
/// Minimal ILP v2 `bars_1m` decoder (binary DOUBLE fields, `known_at=<i64>t`, `<ts>t\n`).
|
||||
fn decode_rows(data: &[u8]) -> Vec<IlpRow> {
|
||||
let mut rows = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < data.len() {
|
||||
let tag_start = i;
|
||||
while data[i] != b' ' {
|
||||
i += 1;
|
||||
}
|
||||
let tags = std::str::from_utf8(&data[tag_start..i]).unwrap();
|
||||
i += 1;
|
||||
let listing_id: i32 = tags
|
||||
.split(',')
|
||||
.find_map(|t| t.strip_prefix("listing_id="))
|
||||
.expect("listing_id tag")
|
||||
.parse()
|
||||
.unwrap();
|
||||
let mut read_f64 = |name: &str| -> f64 {
|
||||
let prefix = format!("{name}==");
|
||||
assert!(data[i..].starts_with(prefix.as_bytes()), "expected {prefix}");
|
||||
i += prefix.len() + 1; // skip binary DOUBLE type tag
|
||||
let v = f64::from_le_bytes(data[i..i + 8].try_into().unwrap());
|
||||
i += 8;
|
||||
if data[i] == b',' {
|
||||
i += 1;
|
||||
}
|
||||
v
|
||||
};
|
||||
let open = read_f64("open");
|
||||
let high = read_f64("high");
|
||||
let low = read_f64("low");
|
||||
let close = read_f64("close");
|
||||
let volume = read_f64("volume");
|
||||
assert!(data[i..].starts_with(b"known_at="), "expected known_at=");
|
||||
i += b"known_at=".len();
|
||||
let ks = i;
|
||||
while data[i] != b' ' {
|
||||
i += 1;
|
||||
}
|
||||
let known_at: i64 = std::str::from_utf8(&data[ks..i])
|
||||
.unwrap()
|
||||
.strip_suffix('t')
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap();
|
||||
i += 1;
|
||||
let ts_start = i;
|
||||
while data[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
let ts: i64 = std::str::from_utf8(&data[ts_start..i])
|
||||
.unwrap()
|
||||
.strip_suffix('t')
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap();
|
||||
i += 1;
|
||||
rows.push(IlpRow {
|
||||
listing_id,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
known_at,
|
||||
ts,
|
||||
});
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn assert_close(actual: f64, expected: f64, what: &str) {
|
||||
assert!(
|
||||
(actual - expected).abs() <= 1e-9 * expected.abs().max(1.0),
|
||||
"{what}: expected {expected}, got {actual}"
|
||||
);
|
||||
}
|
||||
|
||||
fn shard_and_staging_files(dir: &Path) -> Vec<String> {
|
||||
if !dir.exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
read_dir_files(dir).into_keys().collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_writes_known_at_verbatim_and_unadjusts_nvda_split() {
|
||||
let tmp = TempDir::new("values");
|
||||
let fx = write_nvda_fixture(tmp.path());
|
||||
let out = tmp.path().join("out");
|
||||
|
||||
let output = run_bin(&bin_args(&fx, &out, "1700000000123456", &[]));
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
let mut rows: Vec<IlpRow> = read_dir_files(&out)
|
||||
.values()
|
||||
.flat_map(|bytes| decode_rows(bytes))
|
||||
.collect();
|
||||
rows.sort_by_key(|r| r.ts);
|
||||
assert_eq!(rows.len(), 2, "rows: {rows:?}");
|
||||
|
||||
for row in &rows {
|
||||
assert_eq!(row.listing_id, 1001);
|
||||
assert_eq!(row.known_at, 1_700_000_000_123_456, "known_at must be verbatim");
|
||||
}
|
||||
|
||||
let pre = &rows[0];
|
||||
assert_eq!(pre.ts, et_ts_sec(2024, 6, 7, 15, 59) * 1_000_000);
|
||||
assert_close(pre.open, 1205.0, "pre-split open x10");
|
||||
assert_close(pre.high, 1210.0, "pre-split high x10");
|
||||
assert_close(pre.low, 1204.0, "pre-split low x10");
|
||||
assert_close(pre.close, 1207.5, "pre-split close x10");
|
||||
assert_close(pre.volume, 41_239.0, "pre-split volume /10");
|
||||
|
||||
let ex = &rows[1];
|
||||
assert_eq!(ex.ts, et_ts_sec(2024, 6, 10, 15, 59) * 1_000_000);
|
||||
assert_close(ex.close, 121.75, "ex-date close unchanged");
|
||||
assert_close(ex.volume, 350_000.0, "ex-date volume unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_is_deterministic_across_runs() {
|
||||
let tmp = TempDir::new("determinism");
|
||||
let fx = write_nvda_fixture(tmp.path());
|
||||
let out_a = tmp.path().join("out-a");
|
||||
let out_b = tmp.path().join("out-b");
|
||||
|
||||
let a = run_bin(&bin_args(&fx, &out_a, "1750000000000000", &[]));
|
||||
let b = run_bin(&bin_args(&fx, &out_b, "1750000000000000", &[]));
|
||||
assert!(a.status.success() && b.status.success());
|
||||
|
||||
let files_a = read_dir_files(&out_a);
|
||||
assert!(!files_a.is_empty());
|
||||
assert_eq!(files_a, read_dir_files(&out_b), "repeat runs must be byte-identical");
|
||||
assert_eq!(
|
||||
strip_timing_line(&String::from_utf8_lossy(&a.stdout)),
|
||||
strip_timing_line(&String::from_utf8_lossy(&b.stdout)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_refuses_to_overwrite_existing_shards() {
|
||||
let tmp = TempDir::new("overwrite");
|
||||
let fx = write_nvda_fixture(tmp.path());
|
||||
let out = tmp.path().join("out");
|
||||
|
||||
let first = run_bin(&bin_args(&fx, &out, "1750000000000000", &[]));
|
||||
assert!(first.status.success());
|
||||
let before = read_dir_files(&out);
|
||||
|
||||
// Different known_at so any overwrite would change bytes.
|
||||
let second = run_bin(&bin_args(&fx, &out, "1760000000000000", &[]));
|
||||
assert!(!second.status.success(), "second run into populated --out must fail");
|
||||
assert!(second.stdout.is_empty(), "no success report expected");
|
||||
assert!(String::from_utf8_lossy(&second.stderr).starts_with("error:"));
|
||||
assert_eq!(
|
||||
read_dir_files(&out),
|
||||
before,
|
||||
"existing shards must be untouched and no staging files left"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_rejects_non_eod_mapping_source_without_output() {
|
||||
let tmp = TempDir::new("mapping-source");
|
||||
let fx = write_nvda_fixture(tmp.path());
|
||||
let out = tmp.path().join("out");
|
||||
|
||||
let output = run_bin(&bin_args(
|
||||
&fx,
|
||||
&out,
|
||||
"1750000000000000",
|
||||
&["--mapping-source", "qm"],
|
||||
));
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(stderr.contains("error:") && stderr.contains("qm"), "stderr: {stderr}");
|
||||
assert!(
|
||||
shard_and_staging_files(&out).is_empty(),
|
||||
"no files expected in --out: {:?}",
|
||||
shard_and_staging_files(&out)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothing() {
|
||||
let tmp = TempDir::new("parse-error");
|
||||
let fx = write_nvda_fixture(tmp.path());
|
||||
let out = tmp.path().join("out");
|
||||
|
||||
let secret = "--mongo-uri=mongodb://user:s3cr3t_pw@localhost:27017/stock";
|
||||
let output = run_bin(&bin_args(&fx, &out, "1750000000000000", &[secret]));
|
||||
assert!(!output.status.success());
|
||||
assert!(output.stdout.is_empty());
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(stderr.contains("file mode only"), "stderr: {stderr}");
|
||||
assert!(stderr.contains("curate-bars-1m --eod-intraday"), "usage expected: {stderr}");
|
||||
assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}");
|
||||
assert!(!out.exists(), "parse failure must not create --out");
|
||||
|
||||
// Missing --known-at-micros: no clock fallback, nothing written.
|
||||
let mut argv = bin_args(&fx, &out, "1", &[]);
|
||||
argv.truncate(argv.len() - 2);
|
||||
let output = run_bin(&argv);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr)
|
||||
.contains("missing required flag '--known-at-micros'"));
|
||||
assert!(!out.exists());
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue