fix(sftp): keep path-gate poison across successor waiters

Reinstall the poisoned truncatingSharedWriteOpenGates entry on fail() so a
same-path waiter that replaced the map slot cannot release the barrier for a
third OPEN. Propagate fail (not resolve) when abandonGateWait sees a poisoned
prior, and poison on cancel during the fastPut gate wait as well as timeout.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
This commit is contained in:
Cursor Agentand陈大猫 committed 2026-08-06 07:56:31 +00:00
1 parent 0292802cbb
commit 64450bfd58
2 files changed
+396 -10

No files matched your search

+42 -10
View File
@@ -454,22 +454,38 @@ function beginTruncatingSharedWriteOpen(filePath, sessionKey = "unknown") {
if (truncatingSharedWriteOpenGates.get(key) === entry) {
truncatingSharedWriteOpenGates.delete(key);
}
// Already failed: promise rejected; just drop the barrier once OPEN settled.
// Already failed: promise rejected; drop the barrier once OPEN settled.
if (entry.failed) return;
entry.resolve();
};
const fail = (error) => {
if (entry.released || entry.failed) return;
const err = error instanceof Error
? error
: createPoisonedWriteOpenPathGateError(String(error?.message || error || ""));
if (!err.noTransferFallback) err.noTransferFallback = true;
entry.failed = true;
entry.failError = err;
// Keep entry in the map so later beginTruncatingSharedWriteOpen sees failed
// and rejects promptly without clearing the fail-closed barrier.
entry.reject(err);
if (!entry.released && !entry.failed) {
entry.failed = true;
entry.failError = err;
entry.reject(err);
}
// A successor waiter may already own the map slot. Poison that head too so
// its promise cannot resolve and clear the barrier for a third upload while
// the original truncating OPEN may still land (Codex P1 on 0292802c).
const current = truncatingSharedWriteOpenGates.get(key);
if (current && current !== entry && !current.released && !current.failed) {
current.failed = true;
current.failError = err;
current.reject(err);
}
// Reinstall this poisoned entry as the durable fail-closed barrier even if
// a successor replaced us. Successor release must not delete the poison.
if (!entry.released) {
truncatingSharedWriteOpenGates.set(key, entry);
}
};
return { waitForPrior, release, fail };
@@ -2043,6 +2059,16 @@ async function uploadFile(
const onAbort = () => {
try { previousAbort?.(); } catch { /* ignore */ }
transfer.cancelled = true;
// Same fail-closed poison as the timeout path: a dead prior OPEN
// leaves the shared gate unresolved, and cancel must not leave
// later same-path uploads hanging on waitForPrior (Codex P2).
try {
transfer._failPendingWriteOpenPathGate?.(
createPoisonedWriteOpenPathGateError(
"Prior write OPEN never settled; path gate is fail-closed",
),
);
} catch { /* ignore */ }
finish(reject, new Error("Transfer cancelled"));
};
if (transfer.cancelled || signal?.aborted) {
@@ -2683,14 +2709,20 @@ function openSftpHandleForTransfer(sftp, filePath, flags, transfer, options = {}
// Do not release this waiter immediately: beginTruncatingSharedWriteOpen
// already replaced the map entry with us. Releasing now would leave later
// same-path attempts with no barrier while the prior OPEN is still in
// flight (stale truncating OPEN race). Chain our release to the prior.
// flight (stale truncating OPEN race). Chain our release to the prior
// settle; on prior *failure* (poison), propagate fail instead of resolve
// so a successor waiting on our promise cannot start OPEN (Codex P1).
pathGate.waitForPrior.then(
() => {
pathGate.release();
try { transfer._resolvePendingWriteOpenPathGate?.(); } catch { /* ignore */ }
},
() => {
pathGate.release();
(priorErr) => {
const failErr = priorErr instanceof Error
? priorErr
: createPoisonedWriteOpenPathGateError(String(priorErr?.message || priorErr || ""));
if (!failErr.noTransferFallback) failErr.noTransferFallback = true;
try { pathGate.fail?.(failErr); } catch { /* ignore */ }
try { transfer._resolvePendingWriteOpenPathGate?.(); } catch { /* ignore */ }
},
);
+354
View File
@@ -5341,6 +5341,360 @@ test("later same-path upload fails promptly after prior write OPEN gate is poiso
assert.equal(laterSender.sent.some((entry) => entry.channel === "netcatty:transfer:complete"), false);
});
test("path gate poison survives a same-path waiter queued during fastPut timeout", async (t) => {
// Codex P1 on 0292802c: if another upload replaces the map entry during the
// 2s fastPut gate wait, fail() must still leave a fail-closed barrier so a
// third upload cannot OPEN while the original truncating OPEN may land.
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-transfer-gate-poison-successor-"));
t.after(async () => {
await fs.promises.rm(tempDir, { recursive: true, force: true });
});
const payload = Buffer.alloc(TRANSFER_CHUNK_SIZE, 64);
const localPath = path.join(tempDir, "upload.bin");
const targetPath = "/tmp/upload-inplace-gate-poison-successor.bin";
const remoteFiles = new Map([[targetPath, Buffer.from("old")]]);
await fs.promises.writeFile(localPath, payload);
let isolatedChannelCount = 0;
let firstOpenStarted = false;
let firstIsolated = null;
let thirdWriteOpens = 0;
const symlinkLstat = (remotePath, callback) => {
const key = String(remotePath);
if (key.includes(".netcatty-backup-") || key.includes(".netcatty-upload-") || key.includes(".netcatty-")) {
const error = new Error("ENOENT");
error.code = 2;
callback(error);
return;
}
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: createFastSftp({
lstat: symlinkLstat,
open() {
throw new Error("shared OPEN must not run while path gate is fail-closed");
},
createWriteStream() {
throw new Error("stream fallback must not run after fail-closed path gate");
},
}),
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(remotePath) {
remoteFiles.delete(String(remotePath));
},
client: {
sftp(callback) {
isolatedChannelCount += 1;
if (isolatedChannelCount === 1) {
firstIsolated = createFastSftp({
lstat: symlinkLstat,
open(remotePath, flags) {
assert.equal(flags, "w");
assert.equal(String(remotePath), targetPath);
firstOpenStarted = true;
},
end() {},
});
callback(null, firstIsolated);
return;
}
callback(null, createFastSftp({
lstat: symlinkLstat,
open(remotePath, flags, cb) {
thirdWriteOpens += 1;
cb(null, Buffer.from(`isolated-handle:${flags}:${remotePath}`));
},
write(_handle, _buffer, _offset, length, _position, cb) {
cb(null);
},
close(_handle, cb) {
cb(null);
},
fastPut(_local, _remote, _opts, cb) {
cb(null);
},
end() {},
}));
},
},
};
transferBridge.init({ sftpClients: new Map([["target", client]]) });
const firstRunning = transferBridge.startTransfer(
{ sender: createSender() },
{
transferId: "upload-inplace-gate-poison-successor-first",
sourcePath: localPath,
targetPath,
sourceType: "local",
targetType: "sftp",
targetSftpId: "target",
totalBytes: payload.length,
resumable: false,
skipAdmission: true,
},
);
const openReady = await waitUntil(() => firstOpenStarted, 2000);
assert.ok(openReady, "expected first in-place write OPEN to stall");
firstIsolated.emit("error", new Error("isolated SFTP channel died during OPEN"));
// Wait until first transfer has reopened for fastPut (second isolated channel)
// and is inside the 2s pendingWriteOpenPathGate wait.
const fastPutWaiting = await waitUntil(() => isolatedChannelCount >= 2, 2000);
assert.ok(fastPutWaiting, "expected fastPut reopen while prior OPEN gate pending");
// Queue a second same-path upload during the timeout window so it replaces the
// map entry before fail() runs.
const secondRunning = transferBridge.startTransfer(
{ sender: createSender() },
{
transferId: "upload-inplace-gate-poison-successor-second",
sourcePath: localPath,
targetPath,
sourceType: "local",
targetType: "sftp",
targetSftpId: "target",
totalBytes: payload.length,
resumable: false,
skipAdmission: true,
},
);
const firstResult = await Promise.race([
firstRunning,
new Promise((_, reject) => {
setTimeout(() => reject(new Error("first transfer hung on gate timeout")), 5000);
}),
]);
assert.match(firstResult.error || "", /Timed out waiting for prior write OPEN to settle before fastPut/i);
const secondResult = await Promise.race([
secondRunning,
new Promise((_, reject) => {
setTimeout(() => reject(new Error("second transfer hung after prior gate poison")), 1500);
}),
]);
assert.ok(secondResult.error, "expected second waiter to fail closed after poison");
assert.match(secondResult.error, /prior write OPEN never settled|path gate is fail-closed/i);
const thirdStartedAt = Date.now();
const thirdRunning = transferBridge.startTransfer(
{ sender: createSender() },
{
transferId: "upload-inplace-gate-poison-successor-third",
sourcePath: localPath,
targetPath,
sourceType: "local",
targetType: "sftp",
targetSftpId: "target",
totalBytes: payload.length,
resumable: false,
skipAdmission: true,
},
);
const thirdResult = await Promise.race([
thirdRunning,
new Promise((_, reject) => {
setTimeout(() => reject(new Error("third upload hung or raced after successor release")), 1500);
}),
]);
assert.ok(Date.now() - thirdStartedAt < 1500, "third upload must settle promptly");
assert.ok(thirdResult.error, "expected third upload to fail closed");
assert.match(thirdResult.error, /prior write OPEN never settled|path gate is fail-closed/i);
assert.equal(thirdWriteOpens, 0, "poisoned barrier must survive successor waiter release");
});
test("later same-path upload fails promptly after cancel during unresolved OPEN gate wait", async (t) => {
// Codex P2 on 0292802c: cancel during the fastPut pending-gate wait must
// poison the shared path gate, same as the idle timeout path.
const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "netcatty-transfer-gate-cancel-poison-"));
t.after(async () => {
await fs.promises.rm(tempDir, { recursive: true, force: true });
});
const payload = Buffer.alloc(TRANSFER_CHUNK_SIZE, 65);
const localPath = path.join(tempDir, "upload.bin");
const targetPath = "/tmp/upload-inplace-gate-cancel-poison.bin";
const remoteFiles = new Map([[targetPath, Buffer.from("old")]]);
await fs.promises.writeFile(localPath, payload);
let isolatedChannelCount = 0;
let firstOpenStarted = false;
let firstIsolated = null;
let laterWriteOpens = 0;
const symlinkLstat = (remotePath, callback) => {
const key = String(remotePath);
if (key.includes(".netcatty-backup-") || key.includes(".netcatty-upload-") || key.includes(".netcatty-")) {
const error = new Error("ENOENT");
error.code = 2;
callback(error);
return;
}
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: createFastSftp({
lstat: symlinkLstat,
open() {
laterWriteOpens += 1;
throw new Error("shared OPEN must not run while path gate is fail-closed");
},
createWriteStream() {
throw new Error("stream fallback must not run after fail-closed path gate");
},
}),
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(remotePath) {
remoteFiles.delete(String(remotePath));
},
client: {
sftp(callback) {
isolatedChannelCount += 1;
if (isolatedChannelCount === 1) {
firstIsolated = createFastSftp({
lstat: symlinkLstat,
open(remotePath, flags) {
assert.equal(flags, "w");
assert.equal(String(remotePath), targetPath);
firstOpenStarted = true;
},
end() {},
});
callback(null, firstIsolated);
return;
}
callback(null, createFastSftp({
lstat: symlinkLstat,
open(remotePath, flags, cb) {
laterWriteOpens += 1;
cb(null, Buffer.from(`isolated-handle:${flags}:${remotePath}`));
},
write(_handle, _buffer, _offset, length, _position, cb) {
cb(null);
},
close(_handle, cb) {
cb(null);
},
fastPut(_local, _remote, _opts, cb) {
cb(null);
},
end() {},
}));
},
},
};
transferBridge.init({ sftpClients: new Map([["target", client]]) });
const firstTransferId = "upload-inplace-gate-cancel-poison-first";
const firstRunning = transferBridge.startTransfer(
{ sender: createSender() },
{
transferId: firstTransferId,
sourcePath: localPath,
targetPath,
sourceType: "local",
targetType: "sftp",
targetSftpId: "target",
totalBytes: payload.length,
resumable: false,
skipAdmission: true,
},
);
const openReady = await waitUntil(() => firstOpenStarted, 2000);
assert.ok(openReady, "expected first in-place write OPEN to stall");
firstIsolated.emit("error", new Error("isolated SFTP channel died during OPEN"));
const reopened = await waitUntil(() => isolatedChannelCount >= 2, 2000);
assert.ok(reopened, "expected fastPut reopen while prior OPEN gate pending");
await transferBridge.cancelTransfer(null, { transferId: firstTransferId });
const firstResult = await Promise.race([
firstRunning,
new Promise((_, reject) => {
setTimeout(() => reject(new Error("first transfer hung on cancel during gate wait")), 1500);
}),
]);
assert.match(firstResult.error || "", /cancel/i);
const laterStartedAt = Date.now();
const laterRunning = transferBridge.startTransfer(
{ sender: createSender() },
{
transferId: "upload-inplace-gate-cancel-poison-later",
sourcePath: localPath,
targetPath,
sourceType: "local",
targetType: "sftp",
targetSftpId: "target",
totalBytes: payload.length,
resumable: false,
skipAdmission: true,
},
);
const laterResult = await Promise.race([
laterRunning,
new Promise((_, reject) => {
setTimeout(() => reject(new Error("later upload hung after cancel left path gate unresolved")), 1500);
}),
]);
assert.ok(Date.now() - laterStartedAt < 1500, "later upload must settle promptly after cancel poison");
assert.ok(laterResult.error, "expected later upload to fail closed");
assert.match(laterResult.error, /prior write OPEN never settled|path gate is fail-closed/i);
assert.equal(laterWriteOpens, 0, "cancel poison must not allow a later truncating write OPEN");
});
test("shared upload OPEN drain unlinks late staged OPEN after channel-error force-complete", async (t) => {
// Codex P2 on bd42c51c: late truncating OPEN after channel-error drain
// force-complete is not a cancel (`transfer.cancelled` false). Non-resumable