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

@ -232,7 +232,7 @@ bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
- After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta).
## Read-Only Curate-ETL TSV Exporter (`export-curate-inputs.ts`)
`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts` and its CLI `run-export-curate-inputs.ts` read the PostgreSQL security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` transaction (keyset-paginated in chunks `<= 5,000`) and atomically publish the three headerless `\t`-separated TSV inputs consumed by `tools/curate-etl`:
`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts` and its CLI `run-export-curate-inputs.ts` read the PostgreSQL security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` transaction (bounded chunks `<= 5,000`, using a server-side `NO SCROLL` cursor for `provider_mapping`) and atomically publish each complete three-file set as an immutable generation under `<out-dir>/generations/<generationId>` through a single atomic `<out-dir>/current` symlink commit point (`--chunk-size` is optional; default `5000`, max `5000`):
```bash
NODE_ENV=development \
@ -241,10 +241,13 @@ POSTGRES_PORT=5433 \
POSTGRES_DATABASE=trading_bot_dev \
bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \
--out-dir ./tmp/curate-inputs \
[--chunk-size 5000]
--chunk-size 5000
```
- **Output files (`--out-dir`, atomic publish via temp files + rollback on error):**
- **Immutable snapshot layout & consumer pinning:**
- Each export writes all three TSVs into `<out-dir>/generations/<generationId>/` and atomically commits `<out-dir>/current -> generations/<generationId>`. Top-level symlinks (`<out-dir>/provider_mapping.tsv`, `<out-dir>/listing_currencies.tsv`, `<out-dir>/delistings.tsv`) point through `current/<file>`.
- Consumers opening multiple TSVs (such as `curate-corporate-actions`) should pin the active generation once before opening any file — via `pinCurateInputSnapshot(outDir)` in TypeScript or `SNAP=$(readlink -f ./tmp/curate-inputs/current)` in shell — so concurrent refreshes never expose files from different snapshots.
- **Output files:**
- `provider_mapping.tsv` — `source \t source_id \t valid_from \t valid_to(or empty) \t listing_id`, sorted in `COLLATE "C"` ASCII order, preserving non-blank values verbatim and failing closed on `\t`/`\n`/`\r`, duplicates, or overlapping inclusive ranges.
- `listing_currencies.tsv` — `listing_id \t currency`, sorted by ascending `listing_id`.
- `delistings.tsv` — Pass 6 delistings (`source_id \t delist_date \t from_listing_id \t successor_source_id(or empty) \t terminal_return(or empty)`), resolved against `qm` mappings (`valid_from <= effective_date` for outgoing OTC transfers, valid on `effective_date` for OTC successors, valid on `listed_to` for terminal delistings) and indexed by `from_listing_id` so OTC successors (e.g. `SIVBQ`) still emit their own terminal delisting.
@ -261,6 +264,6 @@ POSTGRES_DATABASE=trading_bot_dev \
bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts
```
- **Recorded baseline (`2026-11-29`, local sandbox, in-memory keyset-paginated queryable, `chunkSize = 5000`):**
- **Recorded baseline (`2026-11-29`, local sandbox, in-memory cursor/keyset queryable, `chunkSize = 5000`):**
- Workload: `500,000` `provider_mapping` rows, `100,000` `listing` rows, `2,000` OTC continuities, terminal delistings, and skipped rows (`606,680` exported rows, `17,203,861` bytes written across all three TSVs).
- Observed throughput: `1,525,062 rows/s` (`397.8 ms` elapsed, `262.88 MiB` peak RSS).
- Observed throughput: `1,506,181 rows/s` (`402.8 ms` elapsed, `277.01 MiB` peak RSS).

View file

@ -199,6 +199,20 @@ function createFastPaginatedQueryable(tables: {
if (normalized === 'COMMIT' || normalized === 'ROLLBACK') {
return { rows: [] };
}
if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) {
mappingOffset = 0;
return { rows: [] };
}
const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized);
if (fetchMatch) {
const fetchLimit = Number(fetchMatch[1]);
const slice = tables.mappings.slice(mappingOffset, mappingOffset + fetchLimit);
mappingOffset += slice.length;
return { rows: slice as unknown as Row[] };
}
if (/^CLOSE \S+$/i.test(normalized)) {
return { rows: [] };
}
const limit = values ? (values[values.length - 1] as number) : DEFAULT_EXPORT_CHUNK_SIZE;

View file

@ -1,6 +1,19 @@
import { randomUUID } from 'node:crypto';
import { access, mkdir, open, rename, unlink, type FileHandle } from 'node:fs/promises';
import { join } from 'node:path';
import {
access,
lstat,
mkdir,
open,
readlink,
realpath,
rename,
rm,
rmdir,
symlink,
unlink,
type FileHandle,
} from 'node:fs/promises';
import { basename, join } from 'node:path';
import { compareAscii } from './exchange-pass1';
import type { SecurityMasterQueryable } from './persist';
@ -10,9 +23,12 @@ export const CURATE_INPUT_FILES = Object.freeze({
delistings: 'delistings.tsv',
} as const);
export const CURATE_INPUT_GENERATIONS_DIR = 'generations';
export const CURATE_INPUT_CURRENT_LINK = 'current';
export const DEFAULT_EXPORT_CHUNK_SIZE = 5000;
export const MAX_EXPORT_CHUNK_SIZE = 5000;
export const DEFAULT_DELISTING_MAPPING_SOURCE = 'qm';
const PROVIDER_MAPPING_CURSOR_NAME = 'curate_export_pm_cursor';
const MAX_PG_INT4 = 2_147_483_647;
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
@ -38,7 +54,8 @@ export type CurateInputExportErrorCode =
| 'ACTIVE_LISTING_WITH_OUTCOME'
| 'SELF_SUCCESSOR_CONTINUITY'
| 'DUPLICATE_OTC_CONTINUITY'
| 'OUT_OF_ORDER_CONTINUITY_STREAM';
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
| 'PUBLISH_ROLLBACK_FAILED';
export interface CurateInputExportErrorOptions {
readonly code: CurateInputExportErrorCode;
@ -46,6 +63,7 @@ export interface CurateInputExportErrorOptions {
readonly key: string;
readonly field?: string;
readonly detail: string;
readonly cause?: unknown;
}
export class CurateInputExportError extends Error {
@ -56,7 +74,10 @@ export class CurateInputExportError extends Error {
constructor(options: CurateInputExportErrorOptions) {
const fieldPart = options.field !== undefined ? ` field=${options.field}` : '';
super(`[${options.code}] ${options.table} (${options.key})${fieldPart}: ${options.detail}`);
super(
`[${options.code}] ${options.table} (${options.key})${fieldPart}: ${options.detail}`,
options.cause !== undefined ? { cause: options.cause } : undefined
);
this.name = 'CurateInputExportError';
this.code = options.code;
this.table = options.table;
@ -135,6 +156,12 @@ export interface ExportCurateInputsFsHooks {
readonly rename?: typeof rename;
readonly unlink?: typeof unlink;
readonly access?: typeof access;
readonly lstat?: typeof lstat;
readonly readlink?: typeof readlink;
readonly symlink?: typeof symlink;
readonly realpath?: typeof realpath;
readonly rm?: typeof rm;
readonly rmdir?: typeof rmdir;
}
export interface ExportCurateInputsOptions {
@ -151,8 +178,20 @@ export interface ExportCurateInputsFileStats {
readonly bytesWritten: number;
}
export interface PinnedCurateInputSnapshot {
readonly outDir: string;
readonly generationId: string;
readonly generationDir: string;
readonly providerMapping: string;
readonly listingCurrencies: string;
readonly delistings: string;
}
export interface ExportCurateInputsResult {
readonly outDir: string;
readonly generationId: string;
readonly generationDir: string;
readonly currentLink: string;
readonly chunkSize: number;
readonly delistingMappingSource: string;
readonly providerMapping: ExportCurateInputsFileStats;
@ -161,6 +200,7 @@ export interface ExportCurateInputsResult {
readonly stats: DelistingExportStats;
};
readonly totalBytesWritten: number;
readonly cleanupWarnings: readonly string[];
}
interface QmListingMappingRange {
@ -1060,21 +1100,6 @@ function validateChunkSize(chunkSize: number | undefined): number {
return resolved;
}
async function fileExists(
accessFn: typeof access,
filePath: string
): Promise<boolean> {
try {
await accessFn(filePath);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException | undefined)?.code === 'ENOENT') {
return false;
}
throw error;
}
}
async function safeUnlink(unlinkFn: typeof unlink, filePath: string): Promise<void> {
try {
await unlinkFn(filePath);
@ -1085,6 +1110,17 @@ async function safeUnlink(unlinkFn: typeof unlink, filePath: string): Promise<vo
}
}
async function safeRmdirIfEmpty(rmdirFn: typeof rmdir, dirPath: string): Promise<void> {
try {
await rmdirFn(dirPath);
} catch (error) {
const code = (error as NodeJS.ErrnoException | undefined)?.code;
if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') {
throw error;
}
}
}
async function writeAll(handle: FileHandle, buf: Buffer): Promise<void> {
let offset = 0;
while (offset < buf.byteLength) {
@ -1096,11 +1132,45 @@ async function writeAll(handle: FileHandle, buf: Buffer): Promise<void> {
}
}
/**
* Resolves and pins the currently active immutable generation directory via `<outDir>/current`
* before a consumer opens any TSV file. All three returned paths belong to the same atomic
* PostgreSQL snapshot and remain immutable even if a concurrent export refreshes `<outDir>/current`.
*/
export async function pinCurateInputSnapshot(
outDir: string,
fsHooks?: Pick<ExportCurateInputsFsHooks, 'realpath'>
): Promise<PinnedCurateInputSnapshot> {
if (typeof outDir !== 'string' || outDir.trim().length === 0) {
throw new CurateInputExportError({
code: 'INVALID_OPTION',
table: 'options',
key: 'outDir',
field: 'outDir',
detail: 'outDir must be a non-empty string',
});
}
const normalizedOutDir = outDir.trim();
const fsRealpath = fsHooks?.realpath ?? realpath;
const currentLink = join(normalizedOutDir, CURATE_INPUT_CURRENT_LINK);
const generationDir = await fsRealpath(currentLink);
const generationId = basename(generationDir);
return {
outDir: normalizedOutDir,
generationId,
generationDir,
providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping),
listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies),
delistings: join(generationDir, CURATE_INPUT_FILES.delistings),
};
}
/**
* Reads security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY`
* transaction using keyset pagination (`chunkSize <= 5000`), streams formatted chunks to per-run
* temp files, and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and
* Pass 6 `delistings.tsv` into `options.outDir`.
* transaction in bounded chunks (`chunkSize <= 5000`), streams formatted chunks to an immutable
* generation directory under `<outDir>/generations/<generationId>`, and atomically commits
* `<outDir>/current` (plus top-level symlinks `provider_mapping.tsv`, `listing_currencies.tsv`,
* and `delistings.tsv` pointing through `current/`).
*/
export async function exportCurateInputs(
queryable: SecurityMasterQueryable,
@ -1137,26 +1207,50 @@ export async function exportCurateInputs(
const fsOpen = options.fs?.open ?? open;
const fsRename = options.fs?.rename ?? rename;
const fsUnlink = options.fs?.unlink ?? unlink;
const fsAccess = options.fs?.access ?? access;
const fsLstat = options.fs?.lstat ?? lstat;
const fsReadlink = options.fs?.readlink ?? readlink;
const fsSymlink = options.fs?.symlink ?? symlink;
const fsRm = options.fs?.rm ?? rm;
const fsRmdir = options.fs?.rmdir ?? rmdir;
await fsMkdir(outDir, { recursive: true });
const runTag = `${process.pid}-${Date.now()}-${randomUUID().slice(0, 8)}`;
const uniqueSuffix = randomUUID().slice(0, 8);
const timestamp = Date.now();
const runTag = `${process.pid}-${timestamp}-${uniqueSuffix}`;
const generationId = `gen-${timestamp}-${process.pid}-${uniqueSuffix}`;
const generationsRoot = join(outDir, CURATE_INPUT_GENERATIONS_DIR);
const stagingDir = join(outDir, `.staging-${runTag}`);
const generationDir = join(generationsRoot, generationId);
const relativeGenerationTarget = join(CURATE_INPUT_GENERATIONS_DIR, generationId);
const currentLink = join(outDir, CURATE_INPUT_CURRENT_LINK);
const currentTempLink = join(outDir, `.${CURATE_INPUT_CURRENT_LINK}.${runTag}.tmp`);
const targets = {
providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping),
listingCurrencies: join(outDir, CURATE_INPUT_FILES.listingCurrencies),
delistings: join(outDir, CURATE_INPUT_FILES.delistings),
};
const temps = {
providerMapping: `${targets.providerMapping}.${runTag}.tmp`,
listingCurrencies: `${targets.listingCurrencies}.${runTag}.tmp`,
delistings: `${targets.delistings}.${runTag}.tmp`,
const stagedFiles = {
providerMapping: join(stagingDir, CURATE_INPUT_FILES.providerMapping),
listingCurrencies: join(stagingDir, CURATE_INPUT_FILES.listingCurrencies),
delistings: join(stagingDir, CURATE_INPUT_FILES.delistings),
};
const generationFiles = {
providerMapping: join(generationDir, CURATE_INPUT_FILES.providerMapping),
listingCurrencies: join(generationDir, CURATE_INPUT_FILES.listingCurrencies),
delistings: join(generationDir, CURATE_INPUT_FILES.delistings),
};
const backups = {
providerMapping: `${targets.providerMapping}.${runTag}.bak`,
listingCurrencies: `${targets.listingCurrencies}.${runTag}.bak`,
delistings: `${targets.delistings}.${runTag}.bak`,
};
const linkTemps = {
providerMapping: `${targets.providerMapping}.${runTag}.link.tmp`,
listingCurrencies: `${targets.listingCurrencies}.${runTag}.link.tmp`,
delistings: `${targets.delistings}.${runTag}.link.tmp`,
};
let providerMappingHandle: FileHandle | null = null;
let listingCurrenciesHandle: FileHandle | null = null;
@ -1171,21 +1265,24 @@ export async function exportCurateInputs(
let listingCurrenciesBytes = 0;
let delistingsBytes = 0;
let delistingsStats: DelistingExportStats;
let delistingsStats!: DelistingExportStats;
const publishOrder: Array<'providerMapping' | 'listingCurrencies' | 'delistings'> = [
'providerMapping',
'listingCurrencies',
'delistings',
];
type PublishKey = 'providerMapping' | 'listingCurrencies' | 'delistings';
const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings'];
const backedUp = new Set<'providerMapping' | 'listingCurrencies' | 'delistings'>();
const published = new Set<'providerMapping' | 'listingCurrencies' | 'delistings'>();
let stagingCreated = false;
let generationMoved = false;
let currentTempCreated = false;
const backedUp = new Set<PublishKey>();
const createdLinks = new Set<PublishKey>();
try {
providerMappingHandle = await fsOpen(temps.providerMapping, 'wx');
listingCurrenciesHandle = await fsOpen(temps.listingCurrencies, 'wx');
delistingsHandle = await fsOpen(temps.delistings, 'wx');
await fsMkdir(stagingDir, { recursive: false });
stagingCreated = true;
providerMappingHandle = await fsOpen(stagedFiles.providerMapping, 'wx');
listingCurrenciesHandle = await fsOpen(stagedFiles.listingCurrencies, 'wx');
delistingsHandle = await fsOpen(stagedFiles.delistings, 'wx');
const otcByFromListingId = new Map<number, ContinuityExportSourceRow>();
const relevantDelistingListingIds = new Set<number>();
@ -1444,44 +1541,29 @@ export async function exportCurateInputs(
}
}
// 3. Keyset-paginated read of provider_mapping -> stream provider_mapping.tsv directly.
// 3. Server-side NO SCROLL cursor read of provider_mapping -> stream provider_mapping.tsv
// directly in bounded chunks without repeated per-page sorts on non-C DB collations.
let lastSource: string | null = null;
let lastSourceId: string | null = null;
let lastValidFrom: string | null = null;
let lastValidTo: string | null = null;
await queryable.query(
`DECLARE ${PROVIDER_MAPPING_CURSOR_NAME} NO SCROLL CURSOR FOR
SELECT
source,
source_id,
to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
to_char(valid_to, 'YYYY-MM-DD') AS valid_to,
listing_id
FROM provider_mapping
ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC`
);
for (;;) {
const res =
lastSource === null
? await queryable.query<DbProviderMappingRow>(
`SELECT
source,
source_id,
to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
to_char(valid_to, 'YYYY-MM-DD') AS valid_to,
listing_id
FROM provider_mapping
ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC
LIMIT $1`,
[chunkSize]
)
: await queryable.query<DbProviderMappingRow>(
`SELECT
source,
source_id,
to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
to_char(valid_to, 'YYYY-MM-DD') AS valid_to,
listing_id
FROM provider_mapping
WHERE (
source COLLATE "C" > $1 COLLATE "C"
OR (source COLLATE "C" = $1 COLLATE "C" AND source_id COLLATE "C" > $2 COLLATE "C")
OR (source COLLATE "C" = $1 COLLATE "C" AND source_id COLLATE "C" = $2 COLLATE "C" AND valid_from > $3::date)
)
ORDER BY source COLLATE "C" ASC, source_id COLLATE "C" ASC, valid_from ASC
LIMIT $4`,
[lastSource, lastSourceId, lastValidFrom, chunkSize]
);
const res = await queryable.query<DbProviderMappingRow>(
`FETCH FORWARD ${chunkSize} FROM ${PROVIDER_MAPPING_CURSOR_NAME}`
);
if (res.rows.length === 0) {
break;
@ -1590,6 +1672,7 @@ export async function exportCurateInputs(
}
}
await queryable.query(`CLOSE ${PROVIDER_MAPPING_CURSOR_NAME}`);
await queryable.query('COMMIT');
} catch (error) {
try {
@ -1688,7 +1771,7 @@ export async function exportCurateInputs(
},
};
// 5. Sync and close all three temp files before atomic publish.
// 5. Sync and close all three staged files before atomic generation publish.
await providerMappingHandle.sync();
await providerMappingHandle.close();
providerMappingHandle = null;
@ -1701,75 +1784,156 @@ export async function exportCurateInputs(
await delistingsHandle.close();
delistingsHandle = null;
// 6. Atomic publish: back up pre-existing targets, rename all temps, then drop backups.
// 6. Promote staging directory to an immutable generation and prepare top-level links.
// Keep every backup until the single atomic commit point (`rename(currentTempLink, currentLink)`).
await fsMkdir(generationsRoot, { recursive: true });
await fsRename(stagingDir, generationDir);
generationMoved = true;
stagingCreated = false;
await fsSymlink(relativeGenerationTarget, currentTempLink);
currentTempCreated = true;
for (const key of publishOrder) {
if (await fileExists(fsAccess, targets[key])) {
await fsRename(targets[key], backups[key]);
backedUp.add(key);
const expectedLinkTarget = join(CURATE_INPUT_CURRENT_LINK, CURATE_INPUT_FILES[key]);
let existingStat: Awaited<ReturnType<typeof lstat>> | null = null;
try {
existingStat = await fsLstat(targets[key]);
} catch (statErr) {
if ((statErr as NodeJS.ErrnoException | undefined)?.code !== 'ENOENT') {
throw statErr;
}
}
if (existingStat === null) {
await fsSymlink(expectedLinkTarget, linkTemps[key]);
await fsRename(linkTemps[key], targets[key]);
createdLinks.add(key);
continue;
}
if (existingStat.isSymbolicLink()) {
const currentTarget = await fsReadlink(targets[key]);
if (currentTarget === expectedLinkTarget) {
continue;
}
}
// Pre-existing regular file or non-standard symlink: back it up and keep backup until commit.
await fsRename(targets[key], backups[key]);
backedUp.add(key);
await fsSymlink(expectedLinkTarget, linkTemps[key]);
await fsRename(linkTemps[key], targets[key]);
}
for (const key of publishOrder) {
await fsRename(temps[key], targets[key]);
published.add(key);
}
for (const key of backedUp) {
await safeUnlink(fsUnlink, backups[key]);
}
return {
outDir,
chunkSize,
delistingMappingSource,
providerMapping: {
path: targets.providerMapping,
rowsIn: providerMappingRowsIn,
rowsOut: providerMappingRowsOut,
bytesWritten: providerMappingBytes,
},
listingCurrencies: {
path: targets.listingCurrencies,
rowsIn: listingCurrenciesRowsIn,
rowsOut: listingCurrenciesRowsOut,
bytesWritten: listingCurrenciesBytes,
},
delistings: {
path: targets.delistings,
rowsIn: delistingsStats.rowsIn,
rowsOut: delistingsStats.rowsOut,
bytesWritten: delistingsBytes,
stats: delistingsStats,
},
totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes,
};
// 7. Single atomic commit point: atomically swap `<outDir>/current` -> `generations/<generationId>`.
await fsRename(currentTempLink, currentLink);
currentTempCreated = false;
} catch (error) {
// Close any still-open temp file handles.
// Close any still-open staged file handles.
for (const handle of [providerMappingHandle, listingCurrenciesHandle, delistingsHandle]) {
if (handle !== null) {
await handle.close().catch(() => {});
}
}
// Roll back any already-published targets or moved backups.
// Roll back any backed-up targets or newly created top-level links.
// Never unlink backups here: if a restore fails, retain the backup on disk and report it.
const restoreFailures: Array<{
key: PublishKey;
target: string;
backup: string;
message: string;
}> = [];
for (const key of [...publishOrder].reverse()) {
if (published.has(key)) {
if (backedUp.has(key)) {
await fsRename(backups[key], targets[key]).catch(() => {});
} else {
await safeUnlink(fsUnlink, targets[key]).catch(() => {});
if (backedUp.has(key)) {
try {
await fsRename(backups[key], targets[key]);
} catch (restoreErr) {
restoreFailures.push({
key,
target: targets[key],
backup: backups[key],
message: restoreErr instanceof Error ? restoreErr.message : String(restoreErr),
});
}
} else if (backedUp.has(key)) {
await fsRename(backups[key], targets[key]).catch(() => {});
} else if (createdLinks.has(key)) {
await safeUnlink(fsUnlink, targets[key]).catch(() => {});
}
}
// Clean up any leftover temp or backup files.
// Clean up uncommitted temporary artifacts (never backups).
for (const key of publishOrder) {
await safeUnlink(fsUnlink, temps[key]).catch(() => {});
await safeUnlink(fsUnlink, backups[key]).catch(() => {});
await safeUnlink(fsUnlink, linkTemps[key]).catch(() => {});
}
if (currentTempCreated) {
await safeUnlink(fsUnlink, currentTempLink).catch(() => {});
}
if (stagingCreated) {
await fsRm(stagingDir, { recursive: true, force: true }).catch(() => {});
}
if (generationMoved) {
await fsRm(generationDir, { recursive: true, force: true }).catch(() => {});
}
await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {});
if (restoreFailures.length > 0) {
const originalMessage = error instanceof Error ? error.message : String(error);
const failureSummary = restoreFailures
.map(f => `${f.key} (retained backup: ${f.backup}, target: ${f.target}): ${f.message}`)
.join('; ');
throw new CurateInputExportError({
code: 'PUBLISH_ROLLBACK_FAILED',
table: 'publish',
key: restoreFailures.map(f => f.key).join(','),
detail: `export failed (${originalMessage}) and backup restoration failed; retained backups: ${failureSummary}`,
cause: error,
});
}
throw error;
}
// 8. Post-commit backup cleanup (outside rollback scope: publication is already committed).
const cleanupWarnings: string[] = [];
for (const key of backedUp) {
try {
await safeUnlink(fsUnlink, backups[key]);
} catch (cleanupErr) {
const msg = cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr);
cleanupWarnings.push(
`Failed to remove post-commit backup ${backups[key]} (publication committed): ${msg}`
);
}
}
return {
outDir,
generationId,
generationDir,
currentLink,
chunkSize,
delistingMappingSource,
providerMapping: {
path: generationFiles.providerMapping,
rowsIn: providerMappingRowsIn,
rowsOut: providerMappingRowsOut,
bytesWritten: providerMappingBytes,
},
listingCurrencies: {
path: generationFiles.listingCurrencies,
rowsIn: listingCurrenciesRowsIn,
rowsOut: listingCurrenciesRowsOut,
bytesWritten: listingCurrenciesBytes,
},
delistings: {
path: generationFiles.delistings,
rowsIn: delistingsStats.rowsIn,
rowsOut: delistingsStats.rowsOut,
bytesWritten: delistingsBytes,
stats: delistingsStats,
},
totalBytesWritten: providerMappingBytes + listingCurrenciesBytes + delistingsBytes,
cleanupWarnings,
};
}

View file

@ -49,7 +49,9 @@ export {
export {
buildDelistingExportRows,
CURATE_INPUT_CURRENT_LINK,
CURATE_INPUT_FILES,
CURATE_INPUT_GENERATIONS_DIR,
CurateInputExportError,
DEFAULT_DELISTING_MAPPING_SOURCE,
DEFAULT_EXPORT_CHUNK_SIZE,
@ -60,6 +62,7 @@ export {
formatProviderMappingTsv,
isValidStrictYmd,
MAX_EXPORT_CHUNK_SIZE,
pinCurateInputSnapshot,
type BuildDelistingExportRowsOptions,
type BuildDelistingExportRowsResult,
type ContinuityExportSourceRow,
@ -74,6 +77,7 @@ export {
type ExportCurateInputsResult,
type ListingCurrencyExportRow,
type ListingDelistingSourceRow,
type PinnedCurateInputSnapshot,
type ProviderMappingExportRow,
} from './export-curate-inputs';

View file

@ -168,12 +168,15 @@ export function formatExportCurateInputsSummary(result: ExportCurateInputsResult
const d = result.delistings.stats;
const s = d.skipped;
const lines = [
`Curate-ETL TSV export complete (${result.outDir})`,
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId})`,
` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`,
` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`,
` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`,
` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`,
];
for (const warning of result.cleanupWarnings) {
lines.push(` warning: ${warning}`);
}
return `${lines.join('\n')}\n`;
}
@ -219,15 +222,23 @@ export async function runExportCurateInputs(
return { result, summary };
}
export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise<void> {
export async function runCli(
argv: readonly string[] = process.argv.slice(2),
overrides?: Partial<RunExportCurateInputsDeps>
): Promise<void> {
const parsed = parseExportCurateInputsArgs(argv);
if (parsed.help) {
process.stdout.write(`${EXPORT_CURATE_INPUTS_USAGE}\n`);
const writeStdout =
overrides?.writeStdout ??
((text: string) => {
process.stdout.write(text);
});
writeStdout(`${EXPORT_CURATE_INPUTS_USAGE}\n`);
return;
}
const logger = getLogger('security-master-export-curate-inputs-cli');
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
const config = initializeStockConfig('dataPipeline', { postgresOnly: true });
const assertSafety = (): void => {
assertExportCurateInputsSafety(config, process.env);
@ -313,8 +324,10 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
await runExportCurateInputs(
{
assertSafety,
createPostgresClient,
assertSafety: overrides?.assertSafety ?? assertSafety,
createPostgresClient: overrides?.createPostgresClient ?? createPostgresClient,
exportFn: overrides?.exportFn,
writeStdout: overrides?.writeStdout,
},
{
outDir: parsed.outDir,

View file

@ -8,6 +8,7 @@ import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
exportCurateInputs,
pinCurateInputSnapshot,
type SecurityMasterQueryable,
type SecurityMasterQueryResult,
} from '../../apps/stock/data-pipeline/src/security-master';
@ -383,15 +384,26 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
})
);
// Read-only SQL verification: REPEATABLE READ READ ONLY transaction + zero writes/DDL.
// Read-only SQL verification: REPEATABLE READ READ ONLY transaction + server-side cursor + zero writes/DDL.
for (const sqlLog of [sql5000, sql1]) {
expect(sqlLog[0]).toBe('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
expect(sqlLog[sqlLog.length - 1]).toBe('COMMIT');
expect(sqlLog.some(s => s.startsWith('DECLARE curate_export_pm_cursor NO SCROLL CURSOR FOR'))).toBe(
true
);
expect(sqlLog.some(s => s === 'CLOSE curate_export_pm_cursor')).toBe(true);
for (const stmt of sqlLog) {
expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE)\b/i);
}
}
// Verify snapshot pinning resolves to the published immutable generation.
const pinned5000 = await pinCurateInputSnapshot(outDir5000);
expect(pinned5000.generationId).toBe(res5000.generationId);
expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path);
expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path);
expect(pinned5000.delistings).toBe(res5000.delistings.path);
// Verify chunkSize=1 actually paginated across multiple queries.
expect(sql1.length).toBeGreaterThan(sql5000.length);

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