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:
parent
88b7f1f020
commit
7c55c97c44
8 changed files with 576 additions and 26 deletions
|
|
@ -245,8 +245,8 @@ POSTGRES_DATABASE=trading_bot_dev \
|
|||
```
|
||||
|
||||
- **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.
|
||||
- Each export writes all three TSVs into `<out-dir>/generations/<generationId>/` and serializes top-level link setup, commit (`<out-dir>/current -> generations/<generationId>`), and rollback behind `<out-dir>/.publish.lock`. Top-level symlinks (`<out-dir>/provider_mapping.tsv`, `<out-dir>/listing_currencies.tsv`, `<out-dir>/delistings.tsv`) point through `current/<file>`.
|
||||
- Multi-TSV Rust commands pin the active generation once before opening any TSV via `--curate-inputs <out-dir>` (e.g. `curate-etl curate-corporate-actions --qm-splits qmSplits.bson --qm-dividends qmDividends.bson --curate-inputs ./tmp/curate-inputs --out ./out` and `curate-etl curate-bars-1d --eod-prices eodPrices.bson --qm-splits qmSplits.bson --curate-inputs ./tmp/curate-inputs --out ./out`), and TypeScript consumers can pin via `pinCurateInputSnapshot(outDir)` so concurrent refreshes never mix files from different PostgreSQL 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`.
|
||||
|
|
|
|||
|
|
@ -25,9 +25,12 @@ export const CURATE_INPUT_FILES = Object.freeze({
|
|||
|
||||
export const CURATE_INPUT_GENERATIONS_DIR = 'generations';
|
||||
export const CURATE_INPUT_CURRENT_LINK = 'current';
|
||||
export const CURATE_INPUT_PUBLISH_LOCK = '.publish.lock';
|
||||
export const DEFAULT_EXPORT_CHUNK_SIZE = 5000;
|
||||
export const MAX_EXPORT_CHUNK_SIZE = 5000;
|
||||
export const DEFAULT_DELISTING_MAPPING_SOURCE = 'qm';
|
||||
export const DEFAULT_PUBLISH_LOCK_TIMEOUT_MS = 30_000;
|
||||
const PUBLISH_LOCK_RETRY_MS = 5;
|
||||
const PROVIDER_MAPPING_CURSOR_NAME = 'curate_export_pm_cursor';
|
||||
|
||||
const MAX_PG_INT4 = 2_147_483_647;
|
||||
|
|
@ -55,6 +58,7 @@ export type CurateInputExportErrorCode =
|
|||
| 'SELF_SUCCESSOR_CONTINUITY'
|
||||
| 'DUPLICATE_OTC_CONTINUITY'
|
||||
| 'OUT_OF_ORDER_CONTINUITY_STREAM'
|
||||
| 'PUBLISH_LOCK_TIMEOUT'
|
||||
| 'PUBLISH_ROLLBACK_FAILED';
|
||||
|
||||
export interface CurateInputExportErrorOptions {
|
||||
|
|
@ -168,6 +172,7 @@ export interface ExportCurateInputsOptions {
|
|||
readonly outDir: string;
|
||||
readonly chunkSize?: number;
|
||||
readonly delistingMappingSource?: string;
|
||||
readonly publishLockTimeoutMs?: number;
|
||||
readonly fs?: ExportCurateInputsFsHooks;
|
||||
}
|
||||
|
||||
|
|
@ -1132,6 +1137,47 @@ async function writeAll(handle: FileHandle, buf: Buffer): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
async function acquirePublishLock(
|
||||
lockPath: string,
|
||||
outDir: string,
|
||||
runTag: string,
|
||||
timeoutMs: number,
|
||||
fsOpen: typeof open
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const payload = Buffer.from(
|
||||
`${JSON.stringify({ pid: process.pid, runTag, acquiredAtMs: Date.now() })}\n`,
|
||||
'utf8'
|
||||
);
|
||||
for (;;) {
|
||||
let handle: FileHandle | null = null;
|
||||
try {
|
||||
handle = await fsOpen(lockPath, 'wx');
|
||||
await writeAll(handle, payload);
|
||||
await handle.close();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (handle !== null) {
|
||||
await handle.close().catch(() => {});
|
||||
}
|
||||
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
||||
if (code !== 'EEXIST') {
|
||||
throw error;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new CurateInputExportError({
|
||||
code: 'PUBLISH_LOCK_TIMEOUT',
|
||||
table: 'publish',
|
||||
key: outDir,
|
||||
detail: `timed out after ${timeoutMs}ms waiting for publish lock ${lockPath}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, PUBLISH_LOCK_RETRY_MS));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
|
@ -1196,6 +1242,20 @@ export async function exportCurateInputs(
|
|||
|
||||
const outDir = options.outDir.trim();
|
||||
const chunkSize = validateChunkSize(options.chunkSize);
|
||||
const publishLockTimeoutMs = options.publishLockTimeoutMs ?? DEFAULT_PUBLISH_LOCK_TIMEOUT_MS;
|
||||
if (
|
||||
typeof publishLockTimeoutMs !== 'number' ||
|
||||
!Number.isFinite(publishLockTimeoutMs) ||
|
||||
publishLockTimeoutMs < 0
|
||||
) {
|
||||
throw new CurateInputExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
table: 'options',
|
||||
key: 'publishLockTimeoutMs',
|
||||
field: 'publishLockTimeoutMs',
|
||||
detail: `publishLockTimeoutMs must be a non-negative finite number (got ${String(publishLockTimeoutMs)})`,
|
||||
});
|
||||
}
|
||||
const delistingMappingSource = assertNonBlankVerbatim(
|
||||
options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE,
|
||||
'options',
|
||||
|
|
@ -1225,6 +1285,7 @@ export async function exportCurateInputs(
|
|||
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 publishLockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK);
|
||||
|
||||
const targets = {
|
||||
providerMapping: join(outDir, CURATE_INPUT_FILES.providerMapping),
|
||||
|
|
@ -1271,6 +1332,7 @@ export async function exportCurateInputs(
|
|||
const publishOrder: PublishKey[] = ['providerMapping', 'listingCurrencies', 'delistings'];
|
||||
|
||||
let stagingCreated = false;
|
||||
let publishLockAcquired = false;
|
||||
let generationMoved = false;
|
||||
let currentTempCreated = false;
|
||||
const backedUp = new Set<PublishKey>();
|
||||
|
|
@ -1784,7 +1846,13 @@ export async function exportCurateInputs(
|
|||
await delistingsHandle.close();
|
||||
delistingsHandle = null;
|
||||
|
||||
// 6. Promote staging directory to an immutable generation and prepare top-level links.
|
||||
// 6. Acquire cross-process publish lock before touching shared top-level links or `current`.
|
||||
// The lock serializes link setup, backups, atomic `current` commit, and any rollback across
|
||||
// concurrent exporters targeting the same `outDir`.
|
||||
await acquirePublishLock(publishLockPath, outDir, runTag, publishLockTimeoutMs, fsOpen);
|
||||
publishLockAcquired = true;
|
||||
|
||||
// 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);
|
||||
|
|
@ -1837,7 +1905,7 @@ export async function exportCurateInputs(
|
|||
}
|
||||
}
|
||||
|
||||
// Roll back any backed-up targets or newly created top-level links.
|
||||
// Roll back any backed-up targets or newly created top-level links while still holding the publish lock.
|
||||
// Never unlink backups here: if a restore fails, retain the backup on disk and report it.
|
||||
const restoreFailures: Array<{
|
||||
key: PublishKey;
|
||||
|
|
@ -1877,6 +1945,11 @@ export async function exportCurateInputs(
|
|||
}
|
||||
await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {});
|
||||
|
||||
if (publishLockAcquired) {
|
||||
await safeUnlink(fsUnlink, publishLockPath).catch(() => {});
|
||||
publishLockAcquired = false;
|
||||
}
|
||||
|
||||
if (restoreFailures.length > 0) {
|
||||
const originalMessage = error instanceof Error ? error.message : String(error);
|
||||
const failureSummary = restoreFailures
|
||||
|
|
@ -1894,8 +1967,20 @@ export async function exportCurateInputs(
|
|||
throw error;
|
||||
}
|
||||
|
||||
// 8. Post-commit backup cleanup (outside rollback scope: publication is already committed).
|
||||
// 8. Post-commit lock release & backup cleanup (outside rollback scope: publication is already committed).
|
||||
const cleanupWarnings: string[] = [];
|
||||
if (publishLockAcquired) {
|
||||
try {
|
||||
await safeUnlink(fsUnlink, publishLockPath);
|
||||
publishLockAcquired = false;
|
||||
} catch (lockCleanupErr) {
|
||||
const msg =
|
||||
lockCleanupErr instanceof Error ? lockCleanupErr.message : String(lockCleanupErr);
|
||||
cleanupWarnings.push(
|
||||
`Failed to remove post-commit publish lock ${publishLockPath} (publication committed): ${msg}`
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const key of backedUp) {
|
||||
try {
|
||||
await safeUnlink(fsUnlink, backups[key]);
|
||||
|
|
|
|||
|
|
@ -52,9 +52,11 @@ export {
|
|||
CURATE_INPUT_CURRENT_LINK,
|
||||
CURATE_INPUT_FILES,
|
||||
CURATE_INPUT_GENERATIONS_DIR,
|
||||
CURATE_INPUT_PUBLISH_LOCK,
|
||||
CurateInputExportError,
|
||||
DEFAULT_DELISTING_MAPPING_SOURCE,
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
DEFAULT_PUBLISH_LOCK_TIMEOUT_MS,
|
||||
exportCurateInputs,
|
||||
formatDelistingsTsv,
|
||||
formatListingCurrenciesTsv,
|
||||
|
|
|
|||
|
|
@ -168,7 +168,7 @@ export function formatExportCurateInputsSummary(result: ExportCurateInputsResult
|
|||
const d = result.delistings.stats;
|
||||
const s = d.skipped;
|
||||
const lines = [
|
||||
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId})`,
|
||||
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`,
|
||||
` ${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}`,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { mkdtemp, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises';
|
||||
import { mkdtemp, open, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import {
|
||||
|
|
@ -11,6 +11,7 @@ import {
|
|||
assertExportCurateInputsSafety,
|
||||
buildDelistingExportRows,
|
||||
CURATE_INPUT_FILES,
|
||||
CURATE_INPUT_PUBLISH_LOCK,
|
||||
CurateInputExportError,
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
EXPORT_CURATE_INPUTS_USAGE,
|
||||
|
|
@ -1068,6 +1069,186 @@ describe('exportCurateInputs atomic publish and streaming', () => {
|
|||
expect(isAllA || isAllB).toBe(true);
|
||||
});
|
||||
|
||||
test('concurrent fresh-dir exports serialize publish/rollback so a failed export never deletes a committed export top-level links', async () => {
|
||||
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 },
|
||||
],
|
||||
};
|
||||
|
||||
// Case 1: Export A enters publish first on a fresh dir, creates top-level links, and fails at
|
||||
// commit rename while Export B is waiting for `.publish.lock`. A rolls back cleanly under the
|
||||
// lock; B then acquires the lock and commits with all top-level and pinned paths readable.
|
||||
{
|
||||
const outDir = await makeTempDir('curate-inputs-race-a-fails-');
|
||||
let aEnteredPublishResolve!: () => void;
|
||||
const aEnteredPublish = new Promise<void>(resolve => {
|
||||
aEnteredPublishResolve = resolve;
|
||||
});
|
||||
let bWaitingForLockResolve!: () => void;
|
||||
const bWaitingForLock = new Promise<void>(resolve => {
|
||||
bWaitingForLockResolve = resolve;
|
||||
});
|
||||
|
||||
const promiseA = exportCurateInputs(createInMemoryQueryable(snapA), {
|
||||
outDir,
|
||||
fs: {
|
||||
rename: async (oldPath, newPath) => {
|
||||
if (String(newPath) === join(outDir, 'current')) {
|
||||
aEnteredPublishResolve();
|
||||
await bWaitingForLock;
|
||||
throw new Error('Simulated commit EIO in Export A');
|
||||
}
|
||||
return rename(oldPath, newPath);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const promiseB = (async () => {
|
||||
await aEnteredPublish;
|
||||
let signaledWait = false;
|
||||
return exportCurateInputs(createInMemoryQueryable(snapB), {
|
||||
outDir,
|
||||
fs: {
|
||||
open: async (filePath, flags) => {
|
||||
if (String(filePath) === join(outDir, CURATE_INPUT_PUBLISH_LOCK) && !signaledWait) {
|
||||
signaledWait = true;
|
||||
bWaitingForLockResolve();
|
||||
}
|
||||
return open(filePath, flags);
|
||||
},
|
||||
},
|
||||
});
|
||||
})();
|
||||
|
||||
const [settledA, settledB] = await Promise.allSettled([promiseA, promiseB]);
|
||||
expect(settledA.status).toBe('rejected');
|
||||
expect(settledB.status).toBe('fulfilled');
|
||||
|
||||
// Top-level TSV paths AND pinned snapshot must both resolve to Export B cleanly.
|
||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(
|
||||
'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n'
|
||||
);
|
||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
||||
'20\tCAD\n'
|
||||
);
|
||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(
|
||||
'SNAP_B\t2024-01-15\t20\t\t-1\n'
|
||||
);
|
||||
const pinned = await pinCurateInputSnapshot(outDir);
|
||||
expect(await readFile(pinned.delistings, 'utf8')).toBe('SNAP_B\t2024-01-15\t20\t\t-1\n');
|
||||
const entries = await readdir(outDir);
|
||||
expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false);
|
||||
}
|
||||
|
||||
// Case 2: Export B enters publish first on a fresh dir and commits while Export A is waiting
|
||||
// on `.publish.lock`; Export A then acquires the lock, sees existing top-level links, and fails
|
||||
// at commit rename. A's rollback must leave B's top-level links and `current` intact.
|
||||
{
|
||||
const outDir = await makeTempDir('curate-inputs-race-b-commits-');
|
||||
let bEnteredPublishResolve!: () => void;
|
||||
const bEnteredPublish = new Promise<void>(resolve => {
|
||||
bEnteredPublishResolve = resolve;
|
||||
});
|
||||
let aWaitingForLockResolve!: () => void;
|
||||
const aWaitingForLock = new Promise<void>(resolve => {
|
||||
aWaitingForLockResolve = resolve;
|
||||
});
|
||||
|
||||
const promiseB = exportCurateInputs(createInMemoryQueryable(snapB), {
|
||||
outDir,
|
||||
fs: {
|
||||
rename: async (oldPath, newPath) => {
|
||||
if (String(newPath) === join(outDir, 'current')) {
|
||||
bEnteredPublishResolve();
|
||||
await aWaitingForLock;
|
||||
}
|
||||
return rename(oldPath, newPath);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const promiseA = (async () => {
|
||||
await bEnteredPublish;
|
||||
let signaledWait = false;
|
||||
return exportCurateInputs(createInMemoryQueryable(snapA), {
|
||||
outDir,
|
||||
fs: {
|
||||
open: async (filePath, flags) => {
|
||||
if (String(filePath) === join(outDir, CURATE_INPUT_PUBLISH_LOCK) && !signaledWait) {
|
||||
signaledWait = true;
|
||||
aWaitingForLockResolve();
|
||||
}
|
||||
return open(filePath, flags);
|
||||
},
|
||||
rename: async (oldPath, newPath) => {
|
||||
if (String(newPath) === join(outDir, 'current')) {
|
||||
throw new Error('Simulated commit EIO in Export A after B committed');
|
||||
}
|
||||
return rename(oldPath, newPath);
|
||||
},
|
||||
},
|
||||
});
|
||||
})();
|
||||
|
||||
const [settledB, settledA] = await Promise.allSettled([promiseB, promiseA]);
|
||||
expect(settledB.status).toBe('fulfilled');
|
||||
expect(settledA.status).toBe('rejected');
|
||||
|
||||
// Export B's top-level TSV paths AND pinned snapshot remain 100% readable.
|
||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(
|
||||
'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n'
|
||||
);
|
||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(
|
||||
'20\tCAD\n'
|
||||
);
|
||||
expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(
|
||||
'SNAP_B\t2024-01-15\t20\t\t-1\n'
|
||||
);
|
||||
const pinned = await pinCurateInputSnapshot(outDir);
|
||||
expect(await readFile(pinned.providerMapping, 'utf8')).toBe(
|
||||
'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n'
|
||||
);
|
||||
const entries = await readdir(outDir);
|
||||
expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('fails closed with PUBLISH_LOCK_TIMEOUT when publish lock is held past timeout without removing foreign lock', async () => {
|
||||
const outDir = await makeTempDir('curate-inputs-lock-timeout-');
|
||||
const lockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK);
|
||||
await writeFile(lockPath, '{"pid":999999,"runTag":"foreign"}\n', 'utf8');
|
||||
|
||||
const client = createInMemoryQueryable({
|
||||
listings: [],
|
||||
continuities: [],
|
||||
providerMappings: [],
|
||||
});
|
||||
|
||||
await expectExportErrorAsync(
|
||||
() => exportCurateInputs(client, { outDir, publishLockTimeoutMs: 15 }),
|
||||
'PUBLISH_LOCK_TIMEOUT',
|
||||
'publish',
|
||||
outDir
|
||||
);
|
||||
|
||||
// Foreign lock file must remain untouched.
|
||||
expect(await readFile(lockPath, 'utf8')).toBe('{"pid":999999,"runTag":"foreign"}\n');
|
||||
});
|
||||
|
||||
test('rejects pool-like objects and invalid chunkSize', async () => {
|
||||
const outDir = await makeTempDir('curate-inputs-pool-');
|
||||
const poolLike = {
|
||||
|
|
|
|||
|
|
@ -1022,12 +1022,13 @@ End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBso
|
|||
curate-etl curate-bars-1d \
|
||||
--eod-prices <path> # concatenated raw BSON (mongodump eodPrices.bson)
|
||||
--qm-splits <path> # concatenated raw BSON (mongodump qmSplits.bson)
|
||||
--provider-mapping <path> # headerless TSV (5 columns)
|
||||
--listing-currencies <path> # headerless TSV (2 columns)
|
||||
--curate-inputs <dir> # exporter output dir (pins <dir>/current once before opening TSVs)
|
||||
--out <dir> # dataset root -> bars_1d/year=YYYY/part.parquet
|
||||
[--rel-tolerance <f64>] # default: 0.01
|
||||
```
|
||||
|
||||
Instead of `--curate-inputs <dir>`, standalone TSV files may be passed directly with `--provider-mapping <path> --listing-currencies <path>` (mutually exclusive with `--curate-inputs`). When reading from a live exporter output directory, always prefer `--curate-inputs <dir>` so `curate-bars-1d` pins `<dir>/current` once before opening either TSV and cannot mix generations across a concurrent refresh.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`.
|
||||
|
||||
### TSV Formats (strict, headerless, `\t`-separated)
|
||||
|
|
@ -1161,16 +1162,15 @@ End-to-end file-to-Parquet CLI command (`src/run_curate_corporate_actions.rs`) w
|
|||
curate-etl curate-corporate-actions \
|
||||
--qm-splits qmSplits.bson \
|
||||
--qm-dividends qmDividends.bson \
|
||||
--provider-mapping provider_mapping.tsv \
|
||||
--delistings delistings.tsv \
|
||||
--curate-inputs ./tmp/curate-inputs \
|
||||
--out ./out
|
||||
```
|
||||
|
||||
Inputs and output:
|
||||
- `--qm-splits <path>`: concatenated raw BSON (`mongodump` `qmSplits.bson`).
|
||||
- `--qm-dividends <path>`: concatenated raw BSON (`mongodump` `qmDividends.bson`).
|
||||
- `--provider-mapping <path>`: headerless 5-column TSV (same format as `curate-bars-1d`).
|
||||
- `--delistings <path>` *(optional)*: headerless 5-column Pass 6 delisting-outcomes TSV; when omitted, zero delisting rows are loaded and only split/dividend actions are curated.
|
||||
- `--curate-inputs <dir>`: exporter output directory (or direct generation directory). Resolves `<dir>/current` once via `canonicalize` before opening `provider_mapping.tsv` and `delistings.tsv` so both files always come from the same atomic PostgreSQL snapshot even if an export refreshes `current` concurrently. Mutually exclusive with `--provider-mapping` and `--delistings`.
|
||||
- `--provider-mapping <path>` / `--delistings <path>` *(alternative to `--curate-inputs`)*: standalone headerless 5-column TSVs (`--delistings` is optional when using explicit TSV paths; when omitted, zero delisting rows are loaded).
|
||||
- `--out <dir>`: dataset root where `corporate_actions/part.parquet` is atomically published.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--delistings`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, malformed `provider_mapping.tsv` or `delistings.tsv` reporting path + 1-based line number, overlapping mapping ranges, truncated/corrupt/oversized BSON stream carrying byte offset, or unwritable `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/corporate_actions/part.parquet` byte-identical).
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@
|
|||
//! Kept inside the library crate so CLI argument parsing tests run under
|
||||
//! `cargo test --workspace --lib --offline`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
|
|
@ -83,11 +85,11 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Usage:\n\
|
||||
{name} [--help | -h]\n\
|
||||
{name} [--version | -V]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> --provider-mapping <path> --listing-currencies <path> --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>]\n\
|
||||
Curate daily bars from BSON + TSV files into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE})\n\
|
||||
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
Curate retrospective adj_factors from BSON + TSV + bars_1d Parquet into adj_factors/part.parquet\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> --provider-mapping <path> [--delistings <path>] --out <dir>\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> (--curate-inputs <dir> | --provider-mapping <path> [--delistings <path>]) --out <dir>\n\
|
||||
Curate corporate_actions from BSON + TSV files into corporate_actions/part.parquet\n\
|
||||
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
|
||||
Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\
|
||||
|
|
@ -133,9 +135,9 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
"Usage:\n\
|
||||
{name} [--help | -h]\n\
|
||||
{name} [--version | -V]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> --provider-mapping <path> --listing-currencies <path> --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> --provider-mapping <path> [--delistings <path>] --out <dir>\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> (--curate-inputs <dir> | --provider-mapping <path> [--delistings <path>]) --out <dir>\n\
|
||||
{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\
|
||||
|
|
@ -171,9 +173,43 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
)
|
||||
}
|
||||
|
||||
/// Pins a `curate-inputs` directory to one immutable generation directory before opening any TSV.
|
||||
///
|
||||
/// If `<dir>/current` exists (the atomic symlink published by `run-export-curate-inputs.ts`),
|
||||
/// resolves `<dir>/current` once via [`fs::canonicalize`] so every TSV in this invocation comes
|
||||
/// from that exact generation even if a concurrent export refreshes `current`. Otherwise resolves
|
||||
/// `<dir>` itself (supporting direct generation directories or flat fixture directories).
|
||||
pub fn pin_curate_inputs_dir(dir: &Path) -> Result<PathBuf, String> {
|
||||
let current = dir.join("current");
|
||||
let target = match fs::symlink_metadata(¤t) {
|
||||
Ok(_) => current,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => dir.to_path_buf(),
|
||||
Err(err) => {
|
||||
return Err(format!(
|
||||
"failed to inspect --curate-inputs '{}': {err}",
|
||||
current.display()
|
||||
));
|
||||
}
|
||||
};
|
||||
let canonical = fs::canonicalize(&target).map_err(|err| {
|
||||
format!(
|
||||
"failed to resolve --curate-inputs '{}': {err}",
|
||||
target.display()
|
||||
)
|
||||
})?;
|
||||
if !canonical.is_dir() {
|
||||
return Err(format!(
|
||||
"--curate-inputs '{}' does not resolve to a directory",
|
||||
dir.display()
|
||||
));
|
||||
}
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String> {
|
||||
let mut eod_prices: Option<PathBuf> = None;
|
||||
let mut qm_splits: Option<PathBuf> = None;
|
||||
let mut curate_inputs: Option<PathBuf> = None;
|
||||
let mut provider_mapping: Option<PathBuf> = None;
|
||||
let mut listing_currencies: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
|
|
@ -216,6 +252,7 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
|
|||
match flag {
|
||||
"--eod-prices" => set_path(&mut eod_prices, "--eod-prices", value)?,
|
||||
"--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?,
|
||||
"--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?,
|
||||
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
|
||||
"--listing-currencies" => {
|
||||
set_path(&mut listing_currencies, "--listing-currencies", value)?;
|
||||
|
|
@ -245,10 +282,27 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
|
|||
let eod_prices =
|
||||
eod_prices.ok_or_else(|| "missing required flag '--eod-prices'".to_string())?;
|
||||
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
|
||||
let provider_mapping =
|
||||
provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let listing_currencies = listing_currencies
|
||||
.ok_or_else(|| "missing required flag '--listing-currencies'".to_string())?;
|
||||
let (provider_mapping, listing_currencies) = if let Some(inputs_dir) = curate_inputs {
|
||||
if provider_mapping.is_some() {
|
||||
return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string());
|
||||
}
|
||||
if listing_currencies.is_some() {
|
||||
return Err(
|
||||
"cannot combine '--curate-inputs' with '--listing-currencies'".to_string(),
|
||||
);
|
||||
}
|
||||
let pinned = pin_curate_inputs_dir(&inputs_dir)?;
|
||||
(
|
||||
pinned.join("provider_mapping.tsv"),
|
||||
pinned.join("listing_currencies.tsv"),
|
||||
)
|
||||
} else {
|
||||
let provider_mapping = provider_mapping
|
||||
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let listing_currencies = listing_currencies
|
||||
.ok_or_else(|| "missing required flag '--listing-currencies'".to_string())?;
|
||||
(provider_mapping, listing_currencies)
|
||||
};
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
|
||||
Ok(CurateBars1dArgs {
|
||||
|
|
@ -334,6 +388,7 @@ fn parse_curate_corporate_actions_args(
|
|||
) -> Result<CurateCorporateActionsArgs, String> {
|
||||
let mut qm_splits: Option<PathBuf> = None;
|
||||
let mut qm_dividends: Option<PathBuf> = None;
|
||||
let mut curate_inputs: Option<PathBuf> = None;
|
||||
let mut provider_mapping: Option<PathBuf> = None;
|
||||
let mut delistings: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = None;
|
||||
|
|
@ -375,6 +430,7 @@ fn parse_curate_corporate_actions_args(
|
|||
match flag {
|
||||
"--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?,
|
||||
"--qm-dividends" => set_path(&mut qm_dividends, "--qm-dividends", value)?,
|
||||
"--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?,
|
||||
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
|
||||
"--delistings" => set_path(&mut delistings, "--delistings", value)?,
|
||||
"--out" => set_path(&mut out_dir, "--out", value)?,
|
||||
|
|
@ -389,8 +445,23 @@ fn parse_curate_corporate_actions_args(
|
|||
let qm_splits = qm_splits.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?;
|
||||
let qm_dividends =
|
||||
qm_dividends.ok_or_else(|| "missing required flag '--qm-dividends'".to_string())?;
|
||||
let provider_mapping =
|
||||
provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
let (provider_mapping, delistings) = if let Some(inputs_dir) = curate_inputs {
|
||||
if provider_mapping.is_some() {
|
||||
return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string());
|
||||
}
|
||||
if delistings.is_some() {
|
||||
return Err("cannot combine '--curate-inputs' with '--delistings'".to_string());
|
||||
}
|
||||
let pinned = pin_curate_inputs_dir(&inputs_dir)?;
|
||||
(
|
||||
pinned.join("provider_mapping.tsv"),
|
||||
Some(pinned.join("delistings.tsv")),
|
||||
)
|
||||
} else {
|
||||
let provider_mapping = provider_mapping
|
||||
.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?;
|
||||
(provider_mapping, delistings)
|
||||
};
|
||||
let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?;
|
||||
|
||||
Ok(CurateCorporateActionsArgs {
|
||||
|
|
|
|||
|
|
@ -2,14 +2,17 @@
|
|||
//! security-master exporter (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`)
|
||||
//! load cleanly through the real Rust TSV loaders and curate with zero drops.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::bson_eod_prices::parse_ymd_strict_days;
|
||||
use crate::cli::{parse_args, CliAction};
|
||||
use crate::corporate_actions::{CorporateActionKind, DividendActionEvent, SplitActionEvent};
|
||||
use crate::curate_corporate_actions::curate_corporate_actions;
|
||||
use crate::provider_mapping::ProviderMappingTable;
|
||||
use crate::run_curate_bars::{load_listing_currencies_tsv, load_provider_mapping_tsv};
|
||||
use crate::run_curate_corporate_actions::load_delistings_tsv;
|
||||
use crate::run_curate_corporate_actions::{load_delistings_tsv, run_curate_corporate_actions};
|
||||
|
||||
fn fixture_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
|
|
@ -93,3 +96,211 @@ fn loads_ts_golden_curate_inputs_and_curates_delistings_with_zero_drops() {
|
|||
assert_eq!(del30_term.successor_listing_id, None);
|
||||
assert_eq!(del30_term.terminal_return, Some(-0.3));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn make_temp_dir(prefix: &str) -> PathBuf {
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("system clock after epoch")
|
||||
.as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
|
||||
fs::create_dir_all(&dir).expect("create temp dir");
|
||||
dir
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn atomic_swap_current_link(inputs_dir: &Path, relative_gen: &str) {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = inputs_dir.join(format!(".current.swap.{}.tmp", std::process::id()));
|
||||
let _ = fs::remove_file(&tmp);
|
||||
symlink(relative_gen, &tmp).expect("create temp current symlink");
|
||||
fs::rename(&tmp, inputs_dir.join("current")).expect("atomically swap current symlink");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn curate_corporate_actions_with_curate_inputs_pins_generation_across_refresh() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let root = make_temp_dir("curate-inputs-pin-ca");
|
||||
let inputs_dir = root.join("curate-inputs");
|
||||
let gen1 = inputs_dir.join("generations").join("gen-1");
|
||||
let gen2 = inputs_dir.join("generations").join("gen-2");
|
||||
fs::create_dir_all(&gen1).unwrap();
|
||||
fs::create_dir_all(&gen2).unwrap();
|
||||
|
||||
// Generation 1: SIVB active only (no SIVBQ successor, empty delistings.tsv).
|
||||
fs::write(
|
||||
gen1.join("provider_mapping.tsv"),
|
||||
"qm\tSIVB\t1988-01-04\t\t4\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(gen1.join("listing_currencies.tsv"), "4\tUSD\n").unwrap();
|
||||
fs::write(gen1.join("delistings.tsv"), "").unwrap();
|
||||
|
||||
// Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping.tsv and delistings.tsv.
|
||||
fs::write(
|
||||
gen2.join("provider_mapping.tsv"),
|
||||
"qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(gen2.join("listing_currencies.tsv"), "4\tUSD\n6\tUSD\n").unwrap();
|
||||
fs::write(gen2.join("delistings.tsv"), "SIVB\t2023-03-28\t4\tSIVBQ\t\n").unwrap();
|
||||
|
||||
symlink("generations/gen-1", inputs_dir.join("current")).unwrap();
|
||||
symlink(
|
||||
"current/provider_mapping.tsv",
|
||||
inputs_dir.join("provider_mapping.tsv"),
|
||||
)
|
||||
.unwrap();
|
||||
symlink(
|
||||
"current/listing_currencies.tsv",
|
||||
inputs_dir.join("listing_currencies.tsv"),
|
||||
)
|
||||
.unwrap();
|
||||
symlink("current/delistings.tsv", inputs_dir.join("delistings.tsv")).unwrap();
|
||||
|
||||
let empty_splits = root.join("qmSplits.bson");
|
||||
let empty_divs = root.join("qmDividends.bson");
|
||||
fs::write(&empty_splits, b"").unwrap();
|
||||
fs::write(&empty_divs, b"").unwrap();
|
||||
let out1 = root.join("out-1");
|
||||
let out2 = root.join("out-2");
|
||||
|
||||
// 1. Parse invocation while `current` points to gen-1: pins gen-1 before opening any TSV.
|
||||
let argv1 = vec![
|
||||
"curate-corporate-actions".to_string(),
|
||||
"--qm-splits".to_string(),
|
||||
empty_splits.display().to_string(),
|
||||
"--qm-dividends".to_string(),
|
||||
empty_divs.display().to_string(),
|
||||
"--curate-inputs".to_string(),
|
||||
inputs_dir.display().to_string(),
|
||||
"--out".to_string(),
|
||||
out1.display().to_string(),
|
||||
];
|
||||
let action1 = parse_args(&argv1).expect("parse --curate-inputs on gen-1");
|
||||
let CliAction::CurateCorporateActions(args1) = action1 else {
|
||||
panic!("expected CurateCorporateActions action");
|
||||
};
|
||||
assert_eq!(args1.provider_mapping, fs::canonicalize(&gen1).unwrap().join("provider_mapping.tsv"));
|
||||
assert_eq!(
|
||||
args1.delistings,
|
||||
Some(fs::canonicalize(&gen1).unwrap().join("delistings.tsv"))
|
||||
);
|
||||
|
||||
// 2. Refresh `current` -> gen-2 BEFORE `run_curate_corporate_actions` opens either TSV!
|
||||
atomic_swap_current_link(&inputs_dir, "generations/gen-2");
|
||||
|
||||
// Invocation 1 still reads both TSVs from pinned gen-1 (zero mixed snapshot, zero drops).
|
||||
let report1 = run_curate_corporate_actions(&args1).expect("run pinned gen-1 after refresh");
|
||||
assert_eq!(report1.delistings_rows_loaded, 0);
|
||||
assert_eq!(report1.curate_stats.dropped_unmapped_successor, 0);
|
||||
assert_eq!(report1.curate_stats.rows_out, 0);
|
||||
|
||||
// 3. A new invocation after the refresh pins gen-2 and curates SIVB -> SIVBQ with 0 drops.
|
||||
let argv2 = vec![
|
||||
"curate-corporate-actions".to_string(),
|
||||
"--qm-splits".to_string(),
|
||||
empty_splits.display().to_string(),
|
||||
"--qm-dividends".to_string(),
|
||||
empty_divs.display().to_string(),
|
||||
"--curate-inputs".to_string(),
|
||||
inputs_dir.display().to_string(),
|
||||
"--out".to_string(),
|
||||
out2.display().to_string(),
|
||||
];
|
||||
let action2 = parse_args(&argv2).expect("parse --curate-inputs on gen-2");
|
||||
let CliAction::CurateCorporateActions(args2) = action2 else {
|
||||
panic!("expected CurateCorporateActions action");
|
||||
};
|
||||
let report2 = run_curate_corporate_actions(&args2).expect("run pinned gen-2");
|
||||
assert_eq!(report2.delistings_rows_loaded, 1);
|
||||
assert_eq!(report2.curate_stats.builder.otc_delist_transfers_out, 1);
|
||||
assert_eq!(report2.curate_stats.dropped_unmapped, 0);
|
||||
assert_eq!(report2.curate_stats.dropped_unmapped_successor, 0);
|
||||
assert_eq!(report2.curate_stats.rows_out, 1);
|
||||
|
||||
// 4. Combining --curate-inputs with individual TSV flags is rejected.
|
||||
let bad_argv = vec![
|
||||
"curate-corporate-actions".to_string(),
|
||||
"--qm-splits".to_string(),
|
||||
empty_splits.display().to_string(),
|
||||
"--qm-dividends".to_string(),
|
||||
empty_divs.display().to_string(),
|
||||
"--curate-inputs".to_string(),
|
||||
inputs_dir.display().to_string(),
|
||||
"--delistings".to_string(),
|
||||
gen2.join("delistings.tsv").display().to_string(),
|
||||
"--out".to_string(),
|
||||
out2.display().to_string(),
|
||||
];
|
||||
let err = parse_args(&bad_argv).unwrap_err();
|
||||
assert!(err.contains("cannot combine '--curate-inputs' with '--delistings'"));
|
||||
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn curate_bars_1d_with_curate_inputs_pins_generation_across_refresh() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let root = make_temp_dir("curate-inputs-pin-bars");
|
||||
let inputs_dir = root.join("curate-inputs");
|
||||
let gen1 = inputs_dir.join("generations").join("gen-1");
|
||||
let gen2 = inputs_dir.join("generations").join("gen-2");
|
||||
fs::create_dir_all(&gen1).unwrap();
|
||||
fs::create_dir_all(&gen2).unwrap();
|
||||
fs::write(gen1.join("provider_mapping.tsv"), "eod\tAAPL.US\t2020-01-01\t\t1\n").unwrap();
|
||||
fs::write(gen1.join("listing_currencies.tsv"), "1\tUSD\n").unwrap();
|
||||
fs::write(gen2.join("provider_mapping.tsv"), "eod\tSHOP.TO\t2020-01-01\t\t2\n").unwrap();
|
||||
fs::write(gen2.join("listing_currencies.tsv"), "2\tCAD\n").unwrap();
|
||||
symlink("generations/gen-1", inputs_dir.join("current")).unwrap();
|
||||
|
||||
let argv = vec![
|
||||
"curate-bars-1d".to_string(),
|
||||
"--eod-prices".to_string(),
|
||||
root.join("eodPrices.bson").display().to_string(),
|
||||
"--qm-splits".to_string(),
|
||||
root.join("qmSplits.bson").display().to_string(),
|
||||
"--curate-inputs".to_string(),
|
||||
inputs_dir.display().to_string(),
|
||||
"--out".to_string(),
|
||||
root.join("out").display().to_string(),
|
||||
];
|
||||
let action1 = parse_args(&argv).expect("parse curate-bars-1d --curate-inputs gen-1");
|
||||
let CliAction::CurateBars1d(args1) = action1 else {
|
||||
panic!("expected CurateBars1d action");
|
||||
};
|
||||
let canon_gen1 = fs::canonicalize(&gen1).unwrap();
|
||||
assert_eq!(args1.provider_mapping, canon_gen1.join("provider_mapping.tsv"));
|
||||
assert_eq!(args1.listing_currencies, canon_gen1.join("listing_currencies.tsv"));
|
||||
|
||||
// Swap `current` -> gen-2 and verify pinned paths from args1 still load gen-1 consistently.
|
||||
atomic_swap_current_link(&inputs_dir, "generations/gen-2");
|
||||
let pm1 = load_provider_mapping_tsv(&args1.provider_mapping).unwrap();
|
||||
let lc1 = load_listing_currencies_tsv(&args1.listing_currencies).unwrap();
|
||||
assert_eq!(pm1.len(), 1);
|
||||
assert_eq!(pm1[0].source_id, "AAPL.US");
|
||||
assert_eq!(lc1.get(&1).map(|c| c.as_ref()), Some("USD"));
|
||||
assert!(!lc1.contains_key(&2));
|
||||
|
||||
// A subsequent parse pins gen-2.
|
||||
let action2 = parse_args(&argv).expect("parse curate-bars-1d --curate-inputs gen-2");
|
||||
let CliAction::CurateBars1d(args2) = action2 else {
|
||||
panic!("expected CurateBars1d action");
|
||||
};
|
||||
let canon_gen2 = fs::canonicalize(&gen2).unwrap();
|
||||
assert_eq!(args2.provider_mapping, canon_gen2.join("provider_mapping.tsv"));
|
||||
assert_eq!(args2.listing_currencies, canon_gen2.join("listing_currencies.tsv"));
|
||||
|
||||
// Combining --curate-inputs with --listing-currencies is rejected.
|
||||
let mut bad_argv = argv.clone();
|
||||
bad_argv.push("--listing-currencies".to_string());
|
||||
bad_argv.push(gen2.join("listing_currencies.tsv").display().to_string());
|
||||
let err = parse_args(&bad_argv).unwrap_err();
|
||||
assert!(err.contains("cannot combine '--curate-inputs' with '--listing-currencies'"));
|
||||
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue