Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(api): remove unpublished uploads when cancelled (#1945)

Rudy Mizrahi Celekli362e0721d7d9
diff --git a/agent/src/api/uploads_routes.py b/agent/src/api/uploads_routes.py
index 9dab1a038..ce75bed14 100644
--- a/agent/src/api/uploads_routes.py
+++ b/agent/src/api/uploads_routes.py
@@ -5,6 +5,7 @@ Mounted by ``agent/api_server.py`` via ``register_uploads_routes(app, ...)``.
from __future__ import annotations
+import asyncio
import re
import uuid
from pathlib import Path
@@ -25,13 +26,40 @@ _UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1 MB
_BLOCKED_UPLOAD_EXT = {
# binaries / executables we should never accept
- ".exe", ".msi", ".bat", ".cmd", ".com", ".scr", ".app", ".dmg",
- ".so", ".dll", ".dylib",
+ ".exe",
+ ".msi",
+ ".bat",
+ ".cmd",
+ ".com",
+ ".scr",
+ ".app",
+ ".dmg",
+ ".so",
+ ".dll",
+ ".dylib",
# executable-adjacent source, shell, config, and template files
- ".py", ".pyw", ".sh", ".bash", ".zsh", ".fish", ".ps1",
- ".yaml", ".yml", ".j2", ".jinja", ".jinja2", ".template",
+ ".py",
+ ".pyw",
+ ".sh",
+ ".bash",
+ ".zsh",
+ ".fish",
+ ".ps1",
+ ".yaml",
+ ".yml",
+ ".j2",
+ ".jinja",
+ ".jinja2",
+ ".template",
# archives — don't auto-extract; user can unpack locally
- ".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".bz2", ".xz",
+ ".zip",
+ ".rar",
+ ".7z",
+ ".tar",
+ ".gz",
+ ".tgz",
+ ".bz2",
+ ".xz",
}
_BLOCKED_UPLOAD_NAMES = {
@@ -97,6 +125,7 @@ def register_uploads_routes(
async def get_generated_report(report_id: str):
"""Download only a staged generated PDF via an opaque ID."""
from src.tools.report_artifacts import report_path
+
path = report_path(report_id)
if path is None:
raise HTTPException(status_code=404, detail="Report not found")
@@ -118,9 +147,13 @@ def register_uploads_routes(
reports_dir = get_runtime_root() / "shadow_reports"
path = reports_dir / f"{shadow_id}.{format}"
if not path.exists():
- raise HTTPException(status_code=404, detail=f"Shadow report not found: {shadow_id}.{format}")
+ raise HTTPException(
+ status_code=404, detail=f"Shadow report not found: {shadow_id}.{format}"
+ )
- media_type = "text/html; charset=utf-8" if format == "html" else "application/pdf"
+ media_type = (
+ "text/html; charset=utf-8" if format == "html" else "application/pdf"
+ )
return FileResponse(
path,
media_type=media_type,
@@ -170,6 +203,11 @@ def register_uploads_routes(
detail=f"File too large (limit {max_size // (1024 * 1024)} MB)",
)
handle.write(chunk)
+ except asyncio.CancelledError:
+ # The destination is not published until the route returns. A
+ # cancelled read must not leave that partial upload orphaned.
+ dest.unlink(missing_ok=True)
+ raise
except HTTPException:
raise
except OSError as exc:
diff --git a/agent/tests/test_upload_cancellation.py b/agent/tests/test_upload_cancellation.py
new file mode 100644
index 000000000..395b1b41c
--- /dev/null
+++ b/agent/tests/test_upload_cancellation.py
@@ -0,0 +1,58 @@
+"""Cancellation cleanup for the registered upload route, without server I/O."""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+from io import BytesIO
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import FastAPI, UploadFile
+
+from src.api import uploads_routes
+
+
+def test_cancelled_upload_removes_unpublished_partial_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Cancel a real route task after a chunk was written and a read suspended."""
+
+ async def exercise() -> None:
+ app = FastAPI()
+ # The module's compatibility host lookup stays isolated from api_server
+ # and any operator runtime state.
+ host = SimpleNamespace(
+ UPLOADS_DIR=tmp_path, MAX_UPLOAD_SIZE=1024, _UPLOAD_CHUNK_SIZE=4
+ )
+ monkeypatch.setitem(sys.modules, "api_server", host)
+ uploads_routes.register_uploads_routes(app, require_auth=lambda: None)
+ endpoint = next(
+ route.endpoint for route in app.routes if route.path == "/upload"
+ )
+ upload = UploadFile(file=BytesIO(b"part"), filename="note.txt")
+ read_started = asyncio.Event()
+ original_read = upload.read
+
+ async def interrupted_read(size: int = -1) -> bytes:
+ if upload.file.tell() == 0:
+ return await original_read(size)
+ read_started.set()
+ await asyncio.Future()
+ raise AssertionError("cancelled read resumed")
+
+ upload.read = interrupted_read
+ upload.close = AsyncMock(wraps=upload.close)
+ task = asyncio.create_task(endpoint(upload))
+ await asyncio.wait_for(read_started.wait(), timeout=2)
+ assert len(list(tmp_path.iterdir())) == 1
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ upload.close.assert_awaited_once()
+ assert upload.file.closed
+ assert list(tmp_path.iterdir()) == []
+
+ asyncio.run(exercise())