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,