T-116: M1.2af — data-pipeline: read-only security-master → curate-etl input exporter (provider_mapping.tsv, listing_currencies.tsv, Pass 6 delistings.tsv from PostgreSQL) with tests and local benchmark

This commit is contained in:
Studio 2026-11-29 05:25:54 -05:00
parent 40a48e90ee
commit 88b7f1f020
7 changed files with 718 additions and 137 deletions

View file

@ -1,8 +1,12 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtemp, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { mkdtemp, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import type { StockAppConfig } from '@stock-bot/stock-config';
import {
initializeStockConfig,
resetStockConfig,
type StockAppConfig,
} from '@stock-bot/stock-config';
import {
assertExportCurateInputsSafety,
buildDelistingExportRows,
@ -17,7 +21,9 @@ import {
formatPlainDecimal,
formatProviderMappingTsv,
parseExportCurateInputsArgs,
pinCurateInputSnapshot,
runExportCurateInputs,
runExportCurateInputsCli,
type ContinuityExportSourceRow,
type DelistingExportRow,
type ListingCurrencyExportRow,
@ -128,6 +134,8 @@ function createInMemoryQueryable(
);
let queryCount = 0;
let pmCursorOpen = false;
let pmCursorOffset = 0;
return {
async query<Row = Record<string, unknown>>(
@ -146,6 +154,33 @@ function createInMemoryQueryable(
normalized === 'COMMIT' ||
normalized === 'ROLLBACK'
) {
if (normalized === 'COMMIT' || normalized === 'ROLLBACK') {
pmCursorOpen = false;
pmCursorOffset = 0;
}
return { rows: [] };
}
if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) {
pmCursorOpen = true;
pmCursorOffset = 0;
return { rows: [] };
}
const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized);
if (fetchMatch) {
if (!pmCursorOpen) {
throw new Error('Cursor not open for FETCH');
}
const limit = Number(fetchMatch[1]);
const slice = sortedMappings.slice(pmCursorOffset, pmCursorOffset + limit);
pmCursorOffset += slice.length;
return { rows: slice as unknown as Row[] };
}
if (/^CLOSE \S+$/i.test(normalized)) {
pmCursorOpen = false;
pmCursorOffset = 0;
return { rows: [] };
}
@ -777,7 +812,7 @@ describe('exportCurateInputs atomic publish and streaming', () => {
);
await assertIntact();
// 3. Mid-rename failure on the 2nd published file (after 3 backups + 1st publish rename)
// 3. Mid-rename failure on the 2nd top-level target symlink replacement (after staging->gen + 1st backup/link + 2nd backup)
let renameCalls = 0;
const goodClient = createInMemoryQueryable(baseData);
await expect(
@ -795,6 +830,242 @@ describe('exportCurateInputs atomic publish and streaming', () => {
})
).rejects.toThrow('Simulated EIO on 2nd target publish rename');
await assertIntact();
// 4. Failure at the atomic `current` commit rename restores all 3 pre-existing files cleanly
const commitFailClient = createInMemoryQueryable(baseData);
await expect(
exportCurateInputs(commitFailClient, {
outDir,
fs: {
rename: async (oldPath, newPath) => {
if (String(newPath) === join(outDir, 'current')) {
throw new Error('Simulated EIO on current commit rename');
}
return rename(oldPath, newPath);
},
},
})
).rejects.toThrow('Simulated EIO on current commit rename');
await assertIntact();
});
test('post-commit backup deletion failure does not roll back committed publication and reports warning', async () => {
const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-');
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies);
const dlPath = join(outDir, CURATE_INPUT_FILES.delistings);
await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8');
await writeFile(lcPath, '1\tUSD\n', 'utf8');
await writeFile(dlPath, 'OLD\t2023-01-01\t1\t\t-0.3\n', 'utf8');
const newData: InMemorySecurityMasterData = {
listings: [
{ listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null },
],
continuities: [],
providerMappings: [
{ source: 'eod', source_id: 'NEW.TO', valid_from: '2022-01-01', valid_to: null, listing_id: 2 },
],
};
let backupUnlinkCalls = 0;
const result = await exportCurateInputs(createInMemoryQueryable(newData), {
outDir,
fs: {
unlink: async filePath => {
if (String(filePath).endsWith('.bak')) {
backupUnlinkCalls += 1;
if (backupUnlinkCalls === 2) {
throw new Error('Simulated EIO deleting 2nd backup');
}
}
return unlink(filePath);
},
},
});
// All three live paths reflect the new committed snapshot (no partial rollback).
expect(await readFile(pmPath, 'utf8')).toBe('eod\tNEW.TO\t2022-01-01\t\t2\n');
expect(await readFile(lcPath, 'utf8')).toBe('2\tCAD\n');
expect(await readFile(dlPath, 'utf8')).toBe('');
// Backup #1 and #3 were deleted; #2 failed and is reported in cleanupWarnings.
expect(backupUnlinkCalls).toBe(3);
expect(result.cleanupWarnings).toHaveLength(1);
expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup');
expect(result.cleanupWarnings[0]).toContain('.bak');
expect(formatExportCurateInputsSummary(result)).toContain('warning:');
});
test('failure during rollback restoration retains unrestored backup on disk and reports it', async () => {
const outDir = await makeTempDir('curate-inputs-restore-fail-');
const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping);
const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies);
const dlPath = join(outDir, CURATE_INPUT_FILES.delistings);
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
const origLc = '1\tUSD\n';
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
await writeFile(pmPath, origPm, 'utf8');
await writeFile(lcPath, origLc, 'utf8');
await writeFile(dlPath, origDl, 'utf8');
const newData: InMemorySecurityMasterData = {
listings: [
{ listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null },
],
continuities: [],
providerMappings: [
{ source: 'eod', source_id: 'NEW.TO', valid_from: '2022-01-01', valid_to: null, listing_id: 2 },
],
};
const err = await expectExportErrorAsync(
() =>
exportCurateInputs(createInMemoryQueryable(newData), {
outDir,
fs: {
rename: async (oldPath, newPath) => {
// Fail at the atomic commit point to trigger rollback of all 3 backups.
if (String(newPath) === join(outDir, 'current')) {
throw new Error('Simulated commit EIO');
}
// Fail restoring the provider_mapping backup specifically.
if (
String(oldPath).includes(`${CURATE_INPUT_FILES.providerMapping}.`) &&
String(oldPath).endsWith('.bak') &&
String(newPath) === pmPath
) {
throw new Error('Simulated restore EIO');
}
return rename(oldPath, newPath);
},
},
}),
'PUBLISH_ROLLBACK_FAILED',
'publish',
'providerMapping'
);
expect(err.message).toContain('Simulated commit EIO');
expect(err.message).toContain('Simulated restore EIO');
expect(err.message).toContain('.bak');
// The other two targets were restored intact.
expect(await readFile(lcPath, 'utf8')).toBe(origLc);
expect(await readFile(dlPath, 'utf8')).toBe(origDl);
// The unrestored provider_mapping backup MUST still exist on disk with original bytes!
const entries = await readdir(outDir);
const retainedBackups = entries.filter(
e => e.startsWith(`${CURATE_INPUT_FILES.providerMapping}.`) && e.endsWith('.bak')
);
expect(retainedBackups).toHaveLength(1);
expect(await readFile(join(outDir, retainedBackups[0]!), 'utf8')).toBe(origPm);
});
test('consumer pinning snapshot during publication reads consistent pre-refresh generation while new consumers see new generation', async () => {
const outDir = await makeTempDir('curate-inputs-pin-during-publish-');
// Generation 1: only SIVB active (no SIVBQ successor yet).
const gen1Data: InMemorySecurityMasterData = {
listings: [
{ listing_id: 4, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
],
continuities: [],
providerMappings: [
{ source: 'qm', source_id: 'SIVB', valid_from: '1988-01-04', valid_to: null, listing_id: 4 },
],
};
// Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings.
const gen2Data: InMemorySecurityMasterData = {
listings: [
{ listing_id: 4, currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null },
{ listing_id: 6, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
],
continuities: [
{ from_listing_id: 4, to_listing_id: 6, effective_date: '2023-03-28', kind: 'otc_delist_transfer' },
],
providerMappings: [
{ source: 'qm', source_id: 'SIVB', valid_from: '1988-01-04', valid_to: '2023-03-10', listing_id: 4 },
{ source: 'qm', source_id: 'SIVBQ', valid_from: '2023-03-28', valid_to: null, listing_id: 6 },
],
};
const res1 = await exportCurateInputs(createInMemoryQueryable(gen1Data), { outDir });
// Consumer 1 pins generation 1 before opening any TSV, then reads provider_mapping.tsv.
const pinned1 = await pinCurateInputSnapshot(outDir);
expect(pinned1.generationId).toBe(res1.generationId);
const consumer1Pm = await readFile(pinned1.providerMapping, 'utf8');
expect(consumer1Pm).toBe('qm\tSIVB\t1988-01-04\t\t4\n');
// While Consumer 1 is mid-read, Generation 2 publishes atomically.
const res2 = await exportCurateInputs(createInMemoryQueryable(gen2Data), { outDir });
expect(res2.generationId).not.toBe(res1.generationId);
// Consumer 1 finishes reading listing_currencies.tsv and delistings.tsv from its pinned generation 1.
const consumer1Lc = await readFile(pinned1.listingCurrencies, 'utf8');
const consumer1Dl = await readFile(pinned1.delistings, 'utf8');
expect(consumer1Lc).toBe('4\tUSD\n');
expect(consumer1Dl).toBe(''); // Consistent with gen1 (no SIVBQ transfer referencing missing SIVBQ!)
// Consumer 2 pins after Generation 2 committed and sees the full Generation 2 snapshot.
const pinned2 = await pinCurateInputSnapshot(outDir);
expect(pinned2.generationId).toBe(res2.generationId);
expect(await readFile(pinned2.providerMapping, 'utf8')).toBe(
'qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n'
);
expect(await readFile(pinned2.listingCurrencies, 'utf8')).toBe('4\tUSD\n6\tUSD\n');
expect(await readFile(pinned2.delistings, 'utf8')).toBe('SIVB\t2023-03-28\t4\tSIVBQ\t\n');
});
test('concurrent exports to the same outDir never interleave into a mixed snapshot', async () => {
const outDir = await makeTempDir('curate-inputs-concurrent-');
const snapA: InMemorySecurityMasterData = {
listings: [
{ listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' },
],
continuities: [],
providerMappings: [
{ source: 'qm', source_id: 'SNAP_A', valid_from: '2020-01-01', valid_to: '2023-06-15', listing_id: 10 },
],
};
const snapB: InMemorySecurityMasterData = {
listings: [
{ listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' },
],
continuities: [],
providerMappings: [
{ source: 'qm', source_id: 'SNAP_B', valid_from: '2021-01-01', valid_to: '2024-01-15', listing_id: 20 },
],
};
const [resA, resB] = await Promise.all([
exportCurateInputs(createInMemoryQueryable(snapA), { outDir }),
exportCurateInputs(createInMemoryQueryable(snapB), { outDir }),
]);
const pinned = await pinCurateInputSnapshot(outDir);
const pm = await readFile(pinned.providerMapping, 'utf8');
const lc = await readFile(pinned.listingCurrencies, 'utf8');
const dl = await readFile(pinned.delistings, 'utf8');
const isAllA =
pinned.generationId === resA.generationId &&
pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' &&
lc === '10\tUSD\n' &&
dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n';
const isAllB =
pinned.generationId === resB.generationId &&
pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' &&
lc === '20\tCAD\n' &&
dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n';
expect(isAllA || isAllB).toBe(true);
});
test('rejects pool-like objects and invalid chunkSize', async () => {
@ -996,4 +1267,104 @@ describe('CLI args, safety guard, and runner', () => {
expect(stdoutText).toContain('listing_currencies.tsv: rows_in=1 rows_out=1');
expect(stdoutText).toContain('delistings.tsv: rows_in=1 rows_out=0');
});
test('runExportCurateInputsCli initializes postgresOnly config so unrelated QA MONGODB_URI does not block dev PostgreSQL export', async () => {
const outDir = await makeTempDir('curate-inputs-cli-pg-only-');
const envKeys = [
'NODE_ENV',
'POSTGRES_ENABLED',
'POSTGRES_HOST',
'POSTGRES_PORT',
'POSTGRES_DATABASE',
'DATABASE_POSTGRES_HOST',
'DATABASE_POSTGRES_PORT',
'DATABASE_POSTGRES_DATABASE',
'MONGODB_URI',
'MONGODB_READ_URI',
'DATABASE_MONGODB_URI',
'DATABASE_MONGODB_READURI',
'STOCK_BOT_ALLOW_DEV_ON_QA_DB',
] as const;
const savedEnv: Record<string, string | undefined> = {};
for (const key of envKeys) {
savedEnv[key] = process.env[key];
}
try {
resetStockConfig();
process.env.NODE_ENV = 'development';
process.env.POSTGRES_ENABLED = 'true';
process.env.POSTGRES_HOST = 'localhost';
process.env.POSTGRES_PORT = '5433';
process.env.POSTGRES_DATABASE = 'trading_bot_dev';
process.env.DATABASE_POSTGRES_HOST = 'localhost';
process.env.DATABASE_POSTGRES_PORT = '5433';
process.env.DATABASE_POSTGRES_DATABASE = 'trading_bot_dev';
process.env.MONGODB_URI = 'mongodb://trading_admin:secret@localhost:27017/stock';
delete process.env.MONGODB_READ_URI;
delete process.env.DATABASE_MONGODB_URI;
delete process.env.DATABASE_MONGODB_READURI;
delete process.env.STOCK_BOT_ALLOW_DEV_ON_QA_DB;
// Prove the exact same env fails under the old mongoReadOnly config init.
expect(() => initializeStockConfig('dataPipeline', { mongoReadOnly: true })).toThrow(
'Safety guard'
);
resetStockConfig();
const queryable = createInMemoryQueryable({
listings: [
{ listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null },
],
continuities: [],
providerMappings: [
{ source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1 },
],
});
let stdoutText = '';
await runExportCurateInputsCli(['--out-dir', outDir], {
createPostgresClient: () => ({
queryable,
close: () => {},
}),
writeStdout: text => {
stdoutText += text;
},
});
expect(stdoutText).toContain('Curate-ETL TSV export complete');
expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(
'qm\tAAPL\t2020-01-01\t\t1\n'
);
// Still rejects dev -> QA PostgreSQL even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true!
resetStockConfig();
process.env.POSTGRES_PORT = '5432';
process.env.POSTGRES_DATABASE = 'trading_bot';
process.env.DATABASE_POSTGRES_PORT = '5432';
process.env.DATABASE_POSTGRES_DATABASE = 'trading_bot';
process.env.STOCK_BOT_ALLOW_DEV_ON_QA_DB = 'true';
await expect(
runExportCurateInputsCli(['--out-dir', outDir], {
createPostgresClient: () => ({
queryable,
close: () => {},
}),
writeStdout: () => {},
})
).rejects.toThrow('Safety guard');
} finally {
for (const key of envKeys) {
const value = savedEnv[key];
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
resetStockConfig();
}
});
});