@devries-cameron20 / composio-1 / commits / 4257b9903
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(sdk): remove a claimed download file when its write fails

jkomyno committed Sep 30, 2026 at 12:38 UTC 4257b9903d9b3e7cd4c0f1db2d6c561951c37901
5 files changed +81 -6
python/composio/core/models/tool_router_session_files.py
+8 -2
@@ -261,8 +261,14 @@ class RemoteFile:
261 save_path.write_bytes(content)
262 else:
263 save_path, fd = open_unique_file(save_path)
264 - with fd:
265 - fd.write(content)
264 + try:
265 + with fd:
266 + fd.write(content)
267 + except BaseException:
268 + # The path was claimed for this save, so a failed write must
269 + # not leave a partial file that a retry would number around.
270 + save_path.unlink(missing_ok=True)
271 + raise
272 return str(save_path.resolve())
273
274 @classmethod
python/tests/test_tool_router_session_files.py
+18
@@ -406,6 +406,24 @@ class TestRemoteFile:
406 assert all(len(path.name.encode()) <= 128 for path in paths)
407 assert all(path.suffix == Path(names[0]).suffix for path in paths)
408
409 + def test_failed_default_save_leaves_no_file_behind(self, tmp_path):
410 + file = RemoteFile(
411 + expires_at="2026-01-01",
412 + mount_relative_path="report.pdf",
413 + sandbox_mount_prefix="/mnt/files",
414 + download_url="https://example.com/file",
415 + )
416 + with patch("pathlib.Path.home", return_value=tmp_path):
417 + # Writing `str` to the binary file fails after the path is claimed.
418 + with patch.object(file, "buffer", return_value="not bytes"):
419 + with pytest.raises(TypeError):
420 + file.save()
421 + with patch.object(file, "buffer", return_value=b"content"):
422 + saved = Path(file.save())
423 +
424 + assert saved.name == "report.pdf"
425 + assert [path.name for path in saved.parent.iterdir()] == ["report.pdf"]
426 +
427
428 class TestResponseDerivedUrlsAreGuarded:
429 """`download_url` and `upload_url` are response fields, so they are guarded.
ts/packages/core/src/platform/node.ts
+11 -1
@@ -110,6 +110,16 @@ export const platform = {
110 },
111
112 writeFileExclusiveSync(filePath: string, content: Uint8Array): void {
113 - fs.writeFileSync(filePath, content, { flag: 'wx' });
113 + const fd = fs.openSync(filePath, 'wx');
114 + let written = false;
115 + try {
116 + fs.writeFileSync(fd, content);
117 + written = true;
118 + } finally {
119 + fs.closeSync(fd);
120 + // The path was created here, so a failed write must not leave a
121 + // partial file that a retry would treat as an existing download.
122 + if (!written) fs.rmSync(filePath, { force: true });
123 + }
124 },
125 } as Platform;
ts/packages/core/src/platform/types.ts
+1 -1
@@ -85,7 +85,7 @@ export interface Platform {
85 writeFileSync(filePath: string, content: Uint8Array, encoding?: never): void;
86 writeFileSync(filePath: string, content: string, encoding: Uint8ArrayEncoding): void;
87
88 - /** Writes a new file, failing if its path already exists. */
88 + /** Writes a new file, failing if its path already exists. A failed write removes the file. */
89 writeFileExclusiveSync(filePath: string, content: Uint8Array): void;
90
91 /**
ts/packages/core/test/platform/node.test.ts
+43 -2
@@ -1,9 +1,15 @@
1 -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
1 +import * as fs from 'node:fs';
2 +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3 import * as os from 'node:os';
4 import * as path from 'node:path';
4 -import { describe, expect, it } from 'vitest';
5 +import { describe, expect, it, vi } from 'vitest';
6 import { platform } from '../../src/platform/node';
7
8 +vi.mock('node:fs', async importOriginal => {
9 + const actual = await importOriginal<typeof import('node:fs')>();
10 + return { ...actual, writeFileSync: vi.fn(actual.writeFileSync) };
11 +});
12 +
13 const invertAsciiCase = (value: string): string =>
14 [...value]
15 .map(character => {
@@ -35,3 +41,38 @@ describe('node platform filesystem case detection', () => {
41 }
42 });
43 });
44 +
45 +describe('node platform exclusive writes', () => {
46 + it('removes the file it created when the write fails', () => {
47 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-exclusive-write-'));
48 + try {
49 + const filePath = path.join(root, 'report.pdf');
50 + const actual = vi.mocked(fs.writeFileSync).getMockImplementation()!;
51 + // A disk that fills up mid-write: some bytes land, then the write fails.
52 + vi.mocked(fs.writeFileSync).mockImplementationOnce((file, data, options) => {
53 + actual(file, (data as Uint8Array).subarray(0, 1), options);
54 + throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' });
55 + });
56 +
57 + expect(() => platform.writeFileExclusiveSync(filePath, new Uint8Array([1, 2]))).toThrow(
58 + 'no space left on device'
59 + );
60 + expect(existsSync(filePath)).toBe(false);
61 + } finally {
62 + rmSync(root, { recursive: true, force: true });
63 + }
64 + });
65 +
66 + it('leaves an existing file untouched', () => {
67 + const root = mkdtempSync(path.join(os.tmpdir(), 'composio-exclusive-write-'));
68 + try {
69 + const filePath = path.join(root, 'report.pdf');
70 + writeFileSync(filePath, 'original');
71 +
72 + expect(() => platform.writeFileExclusiveSync(filePath, new Uint8Array([1]))).toThrow();
73 + expect(readFileSync(filePath, 'utf8')).toBe('original');
74 + } finally {
75 + rmSync(root, { recursive: true, force: true });
76 + }
77 + });
78 +});