diff --git a/application/state/sftp/transferDirectoryOps.discovery.test.tsx b/application/state/sftp/transferDirectoryOps.discovery.test.tsx index 6fc69a7b1..b34477a7e 100644 --- a/application/state/sftp/transferDirectoryOps.discovery.test.tsx +++ b/application/state/sftp/transferDirectoryOps.discovery.test.tsx @@ -146,7 +146,7 @@ test("directory transfer discovers each directory once with bounded listing conc assert.equal(listCalls.size, directoryCount + 1); assert.ok(Array.from(listCalls.values()).every((count) => count === 1)); assert.equal(listCalls.has("/source/loop"), false, "canonical symlink cycles must not be listed"); - // Bounded parallel discovery (default 4) — never unbounded fan-out. + // Bounded parallel discovery (default 4) - never unbounded fan-out. assert.ok(maxActiveListings >= 2, `expected parallel listings, got ${maxActiveListings}`); assert.ok(maxActiveListings <= 4, `listing concurrency exceeded budget: ${maxActiveListings}`); assert.equal(tasks.find((task) => task.id === root.id)?.totalBytes, directoryCount); diff --git a/electron/bridges/transferBridge.cjs b/electron/bridges/transferBridge.cjs index 7c078e64c..bfd2829e0 100644 --- a/electron/bridges/transferBridge.cjs +++ b/electron/bridges/transferBridge.cjs @@ -1498,7 +1498,10 @@ async function prepareStreamFallbackAfterRangeFailure(transfer, client) { /** * Wait for a prior truncating WRITE OPEN's published gate before fastPut. * Cancelable and time-bounded so a dead isolated OPEN that never callbacks - * cannot hang strategy fallback forever (#2755). + * cannot hang strategy fallback forever (#2755). On timeout/cancel the waiter + * fails closed without resolving the published gate: clearing that poison early + * lets fastPut complete an in-place destination that a late truncating OPEN can + * still wipe after sendComplete (Codex P1 on e2cc8241). */ async function waitForPendingWriteOpenPathGate(transfer, options = {}) { const gate = transfer?.pendingWriteOpenPathGate; @@ -1520,8 +1523,6 @@ async function waitForPendingWriteOpenPathGate(transfer, options = {}) { if (settled) return; settled = true; cleanup(); - // Unblock other waiters even if the underlying OPEN never finishes. - try { transfer._resolvePendingWriteOpenPathGate?.(); } catch { /* ignore */ } fn(value); }; const onAbort = () => { @@ -1538,7 +1539,11 @@ async function waitForPendingWriteOpenPathGate(transfer, options = {}) { onAbort(); return; } - timer = setTimeout(() => finish(resolve), timeoutMs); + timer = setTimeout(() => { + finish(reject, new Error("Timed out waiting for prior write OPEN to settle")); + }, timeoutMs); + // Only the real gate release unblocks safely. Do not resolve the published + // poison from this waiter on timeout/cancel. Promise.resolve(gate).then( () => finish(resolve), () => finish(resolve), @@ -2485,6 +2490,15 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {} try { transfer._resolvePendingWriteOpenPathGate?.(); } catch { /* ignore */ } }; + // In-place truncating OPEN must stay poisoned until the OPEN callback + // settles. Force-releasing lets fastPut/shared fallback finish, then a late + // OPEN truncates the already-reported destination and invalidation cannot + // restore it after sendComplete (Codex P1 on e2cc8241). Generated stages + // still force-release: promotion checks staleOpenTruncatedStage. + const mayForceReleasePathGate = () => !( + isTruncatingOpenNow() && !generatedStagePath + ); + const invalidateSameTransferAfterForcedGateRelease = () => { if (!pathGateForceReleased || !isTruncatingOpenNow() || !transfer) return; const transferId = transfer.transferId; @@ -2665,13 +2679,17 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {} settle(reject, new Error("Transfer cancelled")); if (trackSharedWriteDrain) { armSharedWriteDrainForceComplete(); - } else { - // Isolated write cancel: force-release path gate so fastPut / - // shared fallback (or a same-id retry) is not stuck forever when - // OPEN never callbacks after sftp.end() (#2755). Mark forced so - // a late OPEN invalidates that same-transfer fallback. + } else if (mayForceReleasePathGate()) { + // Isolated generated-stage write cancel: force-release path gate so + // fastPut / shared fallback (or a same-id retry) is not stuck + // forever when OPEN never callbacks after sftp.end() (#2755). + // Mark forced so a late OPEN invalidates that same-transfer fallback. completeSharedWriteDrain(); releasePathGate({ forced: true }); + } else { + // In-place truncating OPEN: settle the transfer UX, but keep the + // path gate until the late OPEN callback (finishLateSharedWriteOpen). + completeSharedWriteDrain(); } // Late OPEN after this still closes/unlinks via finishLateSharedWriteOpen. }, 2000); @@ -2693,11 +2711,11 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {} if (trackSharedWriteDrain) { armSharedWriteDrainForceComplete(); } else if (isWriteOpen) { - // Isolated write: hold until OPEN callback, but force-release after a - // short grace so strategy fallback / cancel cannot hang forever when - // the OPEN never arrives on a dead channel (#2755). Mark forced so a - // late truncating OPEN aborts the same-transfer fallback it wiped. - if (!openDrainTimer) { + // Isolated write: hold until OPEN callback. Generated stages may + // force-release after a short grace so strategy fallback / cancel cannot + // hang forever when the OPEN never arrives on a dead channel (#2755). + // In-place truncating OPEN never force-releases (Codex P1 on e2cc8241). + if (mayForceReleasePathGate() && !openDrainTimer) { openDrainTimer = setTimeout(() => { completeSharedWriteDrain(); releasePathGate({ forced: true }); @@ -6645,6 +6663,7 @@ module.exports = { listTransferSftpIds, _promoteLocalTransferForTests: promoteLocalTransfer, _preserveTransferredDestinationMtimeForTests: preserveTransferredDestinationMtime, + _waitForPendingWriteOpenPathGateForTests: waitForPendingWriteOpenPathGate, _stableLocalFileIdentityForTests: stableLocalFileIdentity, _getWorkerTransferLifecycleEpochCountForTests: () => workerTransferLifecycleEpochs.size, _setWorkerTransferLifecycleEpochForTests: (transferId, epoch) => { diff --git a/electron/bridges/transferBridge.test.cjs b/electron/bridges/transferBridge.test.cjs index 5b5efeef7..92df5ebaa 100644 --- a/electron/bridges/transferBridge.test.cjs +++ b/electron/bridges/transferBridge.test.cjs @@ -10055,3 +10055,166 @@ test("local-to-local transfer preserves source mtime on the destination", async assert.equal(Math.floor(targetStat.mtimeMs / 1000), Math.floor(sourceMtimeMs / 1000)); assert.deepEqual(await fs.promises.readFile(targetPath), Buffer.from("hello-mtime")); }); + +test("waitForPendingWriteOpenPathGate timeout fails closed without clearing poison", async () => { + let resolveGate; + const gate = new Promise((resolve) => { resolveGate = resolve; }); + const transfer = { + pendingWriteOpenPathGate: gate, + _resolvePendingWriteOpenPathGate() { + resolveGate(); + transfer.pendingWriteOpenPathGate = null; + transfer._resolvePendingWriteOpenPathGate = null; + }, + }; + + await assert.rejects( + () => transferBridge._waitForPendingWriteOpenPathGateForTests(transfer, { timeoutMs: 30 }), + /Timed out waiting for prior write OPEN to settle/i, + ); + assert.equal(transfer.pendingWriteOpenPathGate, gate, "timeout must not clear the published gate poison"); + resolveGate(); +}); + +test("in-place isolated OPEN keeps path gate until late callback after channel error", async (t) => { + // Codex P1 on e2cc8241: force-releasing an in-place truncating OPEN lets + // fastPut complete, then a late OPEN truncates the reported-success file. + const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-inplace-open-no-force-release-")); + t.after(async () => fs.promises.rm(tempDir, { recursive: true, force: true })); + + const payload = Buffer.alloc(TRANSFER_CHUNK_SIZE, 71); + const localPath = path.join(tempDir, "upload.bin"); + await fs.promises.writeFile(localPath, payload); + const targetPath = "/tmp/inplace-no-force.bin"; + const existingPayload = Buffer.from("keep-original"); + + const remoteFiles = new Map([[targetPath, Buffer.from(existingPayload)]]); + const eventLog = []; + let releaseOpen = null; + let openCalls = 0; + let fastPutCalls = 0; + + const isolatedSftp = createFastSftp({ + open(remotePath, flags, callback) { + assert.equal(flags, "w"); + openCalls += 1; + const key = String(remotePath); + releaseOpen = () => { + remoteFiles.set(key, Buffer.alloc(0)); + eventLog.push(`late-open-truncate:${key}`); + callback(null, Buffer.from(`handle:${key}`)); + }; + }, + write() { + throw new Error("WRITE must not run while OPEN is pending"); + }, + close(_handle, callback) { + eventLog.push("close"); + callback(null); + }, + end() { + eventLog.push("isolated-end"); + }, + fastPut() { + fastPutCalls += 1; + throw new Error("fastPut must not run while in-place OPEN poison is held"); + }, + }); + + const sharedSftp = createFastSftp({ + open() { + throw new Error("shared OPEN must not run while isolated in-place gate is held"); + }, + createWriteStream() { + throw new Error("serial WriteStream must not run"); + }, + lstat(remotePath, callback) { + const key = String(remotePath); + if (!remoteFiles.has(key)) { + const error = new Error("ENOENT"); + error.code = 2; + callback(error); + return; + } + callback(null, { + size: remoteFiles.get(key).length, + mode: 0o120777, + isDirectory: () => false, + isSymbolicLink: () => true, + }); + }, + }); + + const client = { + sftp: sharedSftp, + async lstat(remotePath) { + const key = String(remotePath); + if (!remoteFiles.has(key)) { + const error = new Error("ENOENT"); + error.code = 2; + throw error; + } + return { + size: remoteFiles.get(key).length, + mode: 0o120777, + isDirectory: () => false, + isSymbolicLink: () => true, + }; + }, + async stat(remotePath) { + const key = String(remotePath); + if (!remoteFiles.has(key)) { + const error = new Error("ENOENT"); + error.code = 2; + throw error; + } + return { size: remoteFiles.get(key).length }; + }, + rename() { + return Promise.resolve(); + }, + async delete() {}, + client: { + sftp(callback) { + callback(null, isolatedSftp); + }, + }, + }; + transferBridge.init({ sftpClients: new Map([["target", client]]) }); + + const sender = createSender(); + const transferId = "inplace-open-no-force-release"; + const running = transferBridge.startTransfer({ sender }, { + transferId, + sourcePath: localPath, + targetPath, + sourceType: "local", + targetType: "sftp", + targetSftpId: "target", + totalBytes: payload.length, + resumable: false, + skipAdmission: true, + }); + + const opened = await waitUntil(() => openCalls >= 1, 2000); + assert.ok(opened, "expected isolated in-place OPEN to stall"); + + isolatedSftp.emit("error", new Error("isolated channel died during in-place OPEN")); + + // Former force-release window (2s). Path gate must still block fallbacks. + await new Promise((resolve) => setTimeout(resolve, 2500)); + assert.equal(fastPutCalls, 0, "fastPut must not run while in-place OPEN is unsettled"); + assert.deepEqual(remoteFiles.get(targetPath), existingPayload, "destination must stay intact before late OPEN"); + + assert.equal(typeof releaseOpen, "function"); + releaseOpen(); + + const result = await Promise.race([ + running, + new Promise((_, reject) => setTimeout(() => reject(new Error("transfer hung after late in-place OPEN")), 8000)), + ]); + + assert.ok(result.error, "expected transfer to fail closed rather than report success after late truncate"); + assert.equal(sender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false); + assert.ok(eventLog.includes(`late-open-truncate:${targetPath}`) || eventLog.includes("close")); +}); diff --git a/electron/bridges/transferLimits.cjs b/electron/bridges/transferLimits.cjs index 006b6ea2a..f90187f5c 100644 --- a/electron/bridges/transferLimits.cjs +++ b/electron/bridges/transferLimits.cjs @@ -21,7 +21,7 @@ const DOWNLOAD_TRANSFER_CONCURRENCY = 64; // fail-closed). Folder fan-out is capped in the renderer by // runSftpTransferWorkers (settings transfer concurrency). Multi-select // top-level downloads enqueue in parallel and share the same host scheduler / -// channel pool caps — they must never fall back to serial body streams. +// channel pool caps - they must never fall back to serial body streams. const FAST_DOWNLOAD_CHANNELS_PER_SESSION = 1; module.exports = {