diff --git a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts index 5b5a4d58..299bac4d 100644 --- a/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts +++ b/apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts @@ -1142,7 +1142,8 @@ async function acquirePublishLock( outDir: string, runTag: string, timeoutMs: number, - fsOpen: typeof open + fsOpen: typeof open, + fsUnlink: typeof unlink ): Promise { const deadline = Date.now() + timeoutMs; const payload = Buffer.from( @@ -1151,15 +1152,23 @@ async function acquirePublishLock( ); for (;;) { let handle: FileHandle | null = null; + let created = false; try { handle = await fsOpen(lockPath, 'wx'); + created = true; await writeAll(handle, payload); - await handle.close(); + const toClose = handle; + handle = null; + await toClose.close(); return; } catch (error) { if (handle !== null) { await handle.close().catch(() => {}); } + if (created) { + await safeUnlink(fsUnlink, lockPath).catch(() => {}); + throw error; + } const code = (error as NodeJS.ErrnoException | undefined)?.code; if (code !== 'EEXIST') { throw error; @@ -1849,7 +1858,14 @@ export async function exportCurateInputs( // 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); + await acquirePublishLock( + publishLockPath, + outDir, + runTag, + publishLockTimeoutMs, + fsOpen, + fsUnlink + ); publishLockAcquired = true; // Promote staging directory to an immutable generation and prepare top-level links. @@ -1943,9 +1959,9 @@ export async function exportCurateInputs( if (generationMoved) { await fsRm(generationDir, { recursive: true, force: true }).catch(() => {}); } - await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {}); if (publishLockAcquired) { + await safeRmdirIfEmpty(fsRmdir, generationsRoot).catch(() => {}); await safeUnlink(fsUnlink, publishLockPath).catch(() => {}); publishLockAcquired = false; } diff --git a/test/unit/security-master-export-curate-inputs.test.ts b/test/unit/security-master-export-curate-inputs.test.ts index c2639431..9d3f728d 100644 --- a/test/unit/security-master-export-curate-inputs.test.ts +++ b/test/unit/security-master-export-curate-inputs.test.ts @@ -1249,6 +1249,74 @@ describe('exportCurateInputs atomic publish and streaming', () => { expect(await readFile(lockPath, 'utf8')).toBe('{"pid":999999,"runTag":"foreign"}\n'); }); + test('removes .publish.lock when writing metadata fails after exclusive creation so an immediate retry succeeds', async () => { + const outDir = await makeTempDir('curate-inputs-lock-write-fail-'); + const lockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); + + const makeClient = () => + 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 injected = false; + await expect( + exportCurateInputs(makeClient(), { + outDir, + fs: { + open: async (path, flags, mode) => { + const realHandle = await open(path, flags, mode); + if (!injected && String(path) === lockPath && flags === 'wx') { + injected = true; + const wrappedHandle = Object.create(realHandle) as typeof realHandle; + wrappedHandle.write = async () => { + const err = new Error('Simulated ENOSPC while writing lock metadata') as NodeJS.ErrnoException; + err.code = 'ENOSPC'; + throw err; + }; + wrappedHandle.close = () => realHandle.close(); + return wrappedHandle; + } + return realHandle; + }, + }, + }) + ).rejects.toThrow('Simulated ENOSPC while writing lock metadata'); + + expect(injected).toBe(true); + const entriesAfterFailure = await readdir(outDir); + expect(entriesAfterFailure).not.toContain(CURATE_INPUT_PUBLISH_LOCK); + + // Immediate retry to the same outDir must succeed without PUBLISH_LOCK_TIMEOUT. + const retryResult = await exportCurateInputs(makeClient(), { + outDir, + publishLockTimeoutMs: 50, + }); + expect(retryResult.providerMapping.rowsOut).toBe(1); + expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( + 'qm\tAAPL\t2020-01-01\t\t1\n' + ); + const entriesAfterRetry = await readdir(outDir); + expect(entriesAfterRetry).not.toContain(CURATE_INPUT_PUBLISH_LOCK); + }); + test('rejects pool-like objects and invalid chunkSize', async () => { const outDir = await makeTempDir('curate-inputs-pool-'); const poolLike = { diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 60e98ea0..acc90bcb 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1169,7 +1169,7 @@ curate-etl curate-corporate-actions \ Inputs and output: - `--qm-splits `: concatenated raw BSON (`mongodump` `qmSplits.bson`). - `--qm-dividends `: concatenated raw BSON (`mongodump` `qmDividends.bson`). -- `--curate-inputs `: exporter output directory (or direct generation directory). Resolves `/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`. +- `--curate-inputs `: exporter output directory containing a committed `current` link. Requires `/current` and resolves it 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. Fails closed if `current` is absent (use `--provider-mapping` / `--delistings` for standalone files or direct generation paths). Mutually exclusive with `--provider-mapping` and `--delistings`. - `--provider-mapping ` / `--delistings ` *(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 `: dataset root where `corporate_actions/part.parquet` is atomically published. diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index f99b867a..eca286fa 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -175,26 +175,33 @@ pub fn format_usage_stderr(name: &str) -> String { /// Pins a `curate-inputs` directory to one immutable generation directory before opening any TSV. /// -/// If `/current` exists (the atomic symlink published by `run-export-curate-inputs.ts`), -/// resolves `/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 -/// `` itself (supporting direct generation directories or flat fixture directories). +/// Requires `/current` (the atomic symlink published by `run-export-curate-inputs.ts`) to +/// exist and resolves it once via [`fs::canonicalize`] so every TSV in this invocation comes from +/// that exact generation even if a concurrent export refreshes `current`. Fails closed when +/// `/current` is absent; pass explicit `--provider-mapping`, `--listing-currencies`, or +/// `--delistings` flags for standalone files or direct generation directories. pub fn pin_curate_inputs_dir(dir: &Path) -> Result { 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(), + match fs::symlink_metadata(¤t) { + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => { + return Err(format!( + "--curate-inputs '{}' requires a committed 'current' link (missing '{}'); pass explicit --provider-mapping / --listing-currencies / --delistings flags for standalone or direct-generation TSV files", + dir.display(), + current.display() + )); + } Err(err) => { return Err(format!( "failed to inspect --curate-inputs '{}': {err}", current.display() )); } - }; - let canonical = fs::canonicalize(&target).map_err(|err| { + } + let canonical = fs::canonicalize(¤t).map_err(|err| { format!( "failed to resolve --curate-inputs '{}': {err}", - target.display() + current.display() ) })?; if !canonical.is_dir() { diff --git a/tools/curate-etl/src/tsv_fixture_tests.rs b/tools/curate-etl/src/tsv_fixture_tests.rs index 8c60029a..8512761d 100644 --- a/tools/curate-etl/src/tsv_fixture_tests.rs +++ b/tools/curate-etl/src/tsv_fixture_tests.rs @@ -304,3 +304,56 @@ fn curate_bars_1d_with_curate_inputs_pins_generation_across_refresh() { let _ = fs::remove_dir_all(&root); } + +#[cfg(unix)] +#[test] +fn curate_inputs_rejects_flat_directory_without_committed_current_link() { + let root = make_temp_dir("curate-inputs-flat-reject"); + let flat_dir = root.join("flat-inputs"); + fs::create_dir_all(&flat_dir).unwrap(); + fs::write( + flat_dir.join("provider_mapping.tsv"), + "qm\tSIVB\t1988-01-04\t\t4\n", + ) + .unwrap(); + fs::write(flat_dir.join("listing_currencies.tsv"), "4\tUSD\n").unwrap(); + fs::write(flat_dir.join("delistings.tsv"), "").unwrap(); + + let ca_argv = vec![ + "curate-corporate-actions".to_string(), + "--qm-splits".to_string(), + root.join("qmSplits.bson").display().to_string(), + "--qm-dividends".to_string(), + root.join("qmDividends.bson").display().to_string(), + "--curate-inputs".to_string(), + flat_dir.display().to_string(), + "--out".to_string(), + root.join("out-ca").display().to_string(), + ]; + let ca_err = parse_args(&ca_argv).unwrap_err(); + assert!( + ca_err.contains("requires a committed 'current' link"), + "unexpected error for curate-corporate-actions: {ca_err}" + ); + assert!(ca_err.contains("--provider-mapping")); + + let bars_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(), + flat_dir.display().to_string(), + "--out".to_string(), + root.join("out-bars").display().to_string(), + ]; + let bars_err = parse_args(&bars_argv).unwrap_err(); + assert!( + bars_err.contains("requires a committed 'current' link"), + "unexpected error for curate-bars-1d: {bars_err}" + ); + assert!(bars_err.contains("--listing-currencies")); + + let _ = fs::remove_dir_all(&root); +}