diff --git a/autobot-backend/api/conversation_file_cleanup_admin.py b/autobot-backend/api/conversation_file_cleanup_admin.py new file mode 100644 index 0000000000..b40d259eae --- /dev/null +++ b/autobot-backend/api/conversation_file_cleanup_admin.py @@ -0,0 +1,62 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Admin view of deleted conversation files waiting on a human, and the reset for a stuck one (#20234, #17038). + +A deleted file's bytes stay on disk until an approved proposal removes them. A file whose removal was +refused ``AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS`` times is no longer proposed (a "stuck" file); +without this module nothing showed it to anyone. Mounted at ``/api/conversation-files/cleanup`` and +shown by ``components/llc/StuckFileCleanupPanel.vue``. + +* ``GET /cleanup/status`` -- pending and stuck counts, bytes, and the stuck list. Read only. +* ``POST /cleanup/{file_id}/reset`` -- a person lets a stuck file be proposed again. It zeroes the + refusal counter and audits who did it. It removes no bytes: the new proposal still needs an approval. +""" + +from __future__ import annotations + +from typing import Any, Dict + +from fastapi import APIRouter, Depends, HTTPException, Request + +from auth_middleware import check_admin_permission, resolve_human_user +from autobot_shared.logging_manager import get_logger +from conversation_file_cleanup import cleanup_status, reset_cleanup_attempts +from services.audit_logger import audit_log + +logger = get_logger(__name__) + +router = APIRouter(prefix="/cleanup", dependencies=[Depends(check_admin_permission)]) + + +def _manager(request: Request): + manager = getattr(request.app.state, "conversation_file_manager", None) + if manager is None: + raise HTTPException(status_code=503, detail="File management service temporarily unavailable") + return manager + + +@router.get("/status") +async def get_cleanup_status(request: Request) -> Dict[str, Any]: + """Deleted files whose bytes still await removal, and those stuck after repeated refusals.""" + return await cleanup_status(_manager(request)) + + +@router.post("/{file_id}/reset") +async def reset_stuck_cleanup(request: Request, file_id: str) -> Dict[str, Any]: + """Let a stuck file be proposed again; a person's action, audited, and it removes nothing.""" + manager = _manager(request) + if not await reset_cleanup_attempts(manager, file_id): + raise HTTPException(status_code=404, detail="No refused cleanup is recorded for this file") + user = await resolve_human_user(request) or {} + await audit_log( + "conversation_file.cleanup_reset", + user_id=user.get("username") or user.get("user_id") or "internal-service", + resource=f"conversation_file:{file_id}", + details={"effect": "file may be proposed for removal again; no bytes removed"}, + ) + from services.conversation_file_cleanup_proposals import propose_due_cleanups_logged + + await propose_due_cleanups_logged(manager) # raises a proposal only; the bytes wait for an approval + return {"file_id": file_id, "reset": True} diff --git a/autobot-backend/api/conversation_file_upload.py b/autobot-backend/api/conversation_file_upload.py index 8c85747de9..799d2e1e47 100644 --- a/autobot-backend/api/conversation_file_upload.py +++ b/autobot-backend/api/conversation_file_upload.py @@ -8,48 +8,50 @@ here so ``conversation_files.py`` stays under its size ceiling while it gains the owner gate. """ +from typing import Awaitable, Callable + from fastapi import HTTPException, UploadFile +from conversation_file_quota import file_too_large from security.upload_filename_policy import is_safe_file from utils.catalog_http_exceptions import raise_invalid_input # Maximum file size (50MB) - consistent with general file API MAX_FILE_SIZE = 50 * 1024 * 1024 +_CHUNK_BYTES = 1024 * 1024 -async def validate_and_read_upload_file( - file: UploadFile, -) -> bytes: - """ - Validate and read uploaded file content. - Issue #281: Extracted from upload_conversation_file to reduce function - length and improve reusability of validation logic. +async def _read_within(file: UploadFile, limit: int, refuse: Callable[[], Awaitable[HTTPException]]) -> bytes: + """Read *file* in chunks; raise ``await refuse()`` the moment it passes *limit*, so no oversize body is buffered.""" + chunks: list[bytes] = [] + total = 0 + while chunk := await file.read(_CHUNK_BYTES): + total += len(chunk) + if total > limit: + raise await refuse() + chunks.append(chunk) + return b"".join(chunks) + + +async def _too_large() -> HTTPException: + return file_too_large(MAX_FILE_SIZE) + - Args: - file: Uploaded file object +async def validate_and_read_upload_file(file: UploadFile, quota_manager=None, user_id: str | None = None) -> bytes: + """Validate the name, then read the body under the size cap and *user_id*'s remaining quota (#20217). - Returns: - File content as bytes + ``quota_manager`` (the conversation file manager) says what the user may still store; ``None`` = no + quota. The stricter limit ends the read early, each refusal with its own stable code. Raises: - HTTPException: If validation fails (400, 413) + HTTPException: 400 for a bad name; 413 (``UploadRefused``) for an oversize file or an exhausted quota """ - # Validate filename if not file.filename: raise_invalid_input("filename", "required") - if not is_safe_file(file.filename): raise_invalid_input("filename", f"file type not allowed: {file.filename}") - - # Read file content - content = await file.read() - - # Check file size - if len(content) > MAX_FILE_SIZE: - raise HTTPException( - status_code=413, - detail=f"File too large. Maximum size: {MAX_FILE_SIZE // (1024*1024)}MB", - ) - - return content + remaining = None if quota_manager is None else await quota_manager.remaining_upload_quota(user_id) + if remaining is not None and remaining < MAX_FILE_SIZE: + return await _read_within(file, max(remaining, 0), lambda: quota_manager.upload_quota_refusal(user_id)) + return await _read_within(file, MAX_FILE_SIZE, _too_large) diff --git a/autobot-backend/api/conversation_files.py b/autobot-backend/api/conversation_files.py index cc5adc3efc..1748d205fc 100644 --- a/autobot-backend/api/conversation_files.py +++ b/autobot-backend/api/conversation_files.py @@ -141,8 +141,8 @@ async def upload_conversation_file( """Upload a file to a conversation session (Issue #398: refactored).""" try: user_data = await _authorize_file_operation(request, session_id, "upload", existing_only=True) - content = await validate_and_read_upload_file(file) file_manager = _get_required_file_manager(request) + content = await validate_and_read_upload_file(file, file_manager, user_data.get("username")) file_info_dict = await file_manager.upload_file( session_id=session_id, @@ -158,11 +158,7 @@ async def upload_conversation_file( "conversation_file_upload", user_data, session_id, - { - "filename": file.filename, - "file_id": file_info.file_id, - "size": len(content), - }, + {"filename": file.filename, "file_id": file_info.file_id, "size": len(content)}, ) upload_id = f"upload_{datetime.now(tz=timezone.utc).strftime('%Y%m%d_%H%M%S')}_{secrets.token_hex(4)}" diff --git a/autobot-backend/api/conversation_files_owner_upload_20133_test.py b/autobot-backend/api/conversation_files_owner_upload_20133_test.py index 8e28ab1335..b18a46817f 100644 --- a/autobot-backend/api/conversation_files_owner_upload_20133_test.py +++ b/autobot-backend/api/conversation_files_owner_upload_20133_test.py @@ -96,6 +96,7 @@ async def _owner(_session_id): manager = create_autospec(ConversationFileManager, instance=True) # a method it lacks would fail here (#20225) manager.upload_file.side_effect = lambda **kw: _file_info(kw["session_id"], kw["user_id"]) + manager.remaining_upload_quota.return_value = 1 << 30 # the real manager reads the user's stored bytes (#20217) manager.list_files.return_value = {"files": [], "total_files": 0, "total_size": 0} app = FastAPI() app.include_router(module.router, prefix="/api") diff --git a/autobot-backend/api/conversation_files_upload_limits_20217_test.py b/autobot-backend/api/conversation_files_upload_limits_20217_test.py new file mode 100644 index 0000000000..7996c86afe --- /dev/null +++ b/autobot-backend/api/conversation_files_upload_limits_20217_test.py @@ -0,0 +1,75 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""Conversation-file uploads stop reading at the size cap and refuse a user past their quota (#20217).""" + +from __future__ import annotations + +import asyncio +import io + +import pytest +from fastapi import HTTPException, UploadFile + +import conversation_file_quota as quota +from api import conversation_file_upload as upload +from api.conversation_files_owner_upload_20133_test import world # noqa: F401 -- fixture +from api.conversation_files_real_manager_20225_test import _SESSION, _upload, real # noqa: F401 -- fixture + + +class _CountingStream(io.BytesIO): + """A body that records how many bytes the reader actually pulled.""" + + pulled = 0 + + def read(self, size=-1): + data = super().read(size) + self.pulled += len(data) + return data + + +def _file(body: io.BytesIO, name="big.txt") -> UploadFile: + return UploadFile(file=body, filename=name) + + +def test_an_oversize_body_stops_the_read_early(monkeypatch): + monkeypatch.setattr(upload, "MAX_FILE_SIZE", 2 * upload._CHUNK_BYTES) + body = _CountingStream(b"x" * (50 * upload._CHUNK_BYTES)) + with pytest.raises(HTTPException) as caught: + asyncio.run(upload.validate_and_read_upload_file(_file(body))) + assert caught.value.status_code == 413 and caught.value.detail["code"] == quota.FILE_TOO_LARGE + assert body.pulled == 3 * upload._CHUNK_BYTES # cap + the one chunk that crossed it, not the whole body + + +def test_a_body_exactly_at_the_cap_is_read_whole(monkeypatch): + monkeypatch.setattr(upload, "MAX_FILE_SIZE", 10) + assert asyncio.run(upload.validate_and_read_upload_file(_file(io.BytesIO(b"x" * 10)))) == b"x" * 10 + + +def test_the_remaining_quota_ends_the_read_with_its_own_code(real, monkeypatch): # noqa: F811 + monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 5) + body = _CountingStream(b"x" * (10 * upload._CHUNK_BYTES)) + with pytest.raises(HTTPException) as caught: + asyncio.run(upload.validate_and_read_upload_file(_file(body), real.real, "alice")) + assert caught.value.status_code == 413 and caught.value.detail["code"] == quota.QUOTA_EXCEEDED + assert body.pulled == upload._CHUNK_BYTES + + +def test_a_user_past_their_quota_is_refused_by_the_route_and_nothing_is_stored(real, monkeypatch): # noqa: F811 + monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 20) + assert _upload(real, body=b"x" * 15).status_code == 200 + response = _upload(real, name="two.txt", body=b"y" * 10) + assert response.status_code == 413 and response.json()["detail"]["code"] == quota.QUOTA_EXCEEDED + assert asyncio.run(real.real.remaining_upload_quota("alice")) == 5 + + +def test_the_quota_is_per_user_not_shared(real, monkeypatch): # noqa: F811 + monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 20) + assert _upload(real, body=b"x" * 20).status_code == 200 + assert asyncio.run(real.real.remaining_upload_quota("alice")) == 0 + assert asyncio.run(real.real.remaining_upload_quota("bob")) == 20 + + +def test_the_quota_limit_is_the_registered_env_default(): + from autobot_shared.env_registry import REGISTRY + + assert REGISTRY["AUTOBOT_CONVERSATION_FILE_USER_QUOTA_BYTES"].default == quota.USER_QUOTA_BYTES == 1 << 30 diff --git a/autobot-backend/conversation_file_cleanup.py b/autobot-backend/conversation_file_cleanup.py new file mode 100644 index 0000000000..cc330c53cb --- /dev/null +++ b/autobot-backend/conversation_file_cleanup.py @@ -0,0 +1,250 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""What a deleted conversation file's bytes may do: wait for a human (#20234, #17038). + +Deleting a conversation file only marks it (``is_deleted``), and a trigger schedules a +``file_cleanup_queue`` row for every file. Nothing here removes bytes on its own: + +* :func:`list_cleanup_candidates` reads the queue -- entries that are due, not yet processed, whose + file is soft-deleted, and which have not been refused ``AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS`` + times or refused within the cooldown (``file_cleanup_attempts``; a capped file is "stuck" in the stats); +* ``services/conversation_file_cleanup_proposals.py`` turns each into an approval-gate proposal; +* only an APPROVED proposal reaches :func:`remove_approved_file`, which re-validates everything + at removal time and marks the queue row processed -- the row, the soft-deleted file record, + the approval and its audit entry are the durable record that outlives the bytes. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Any, Dict, List + +from autobot_shared.env_registry import env +from autobot_shared.logging_manager import get_logger + +logger = get_logger(__name__) + +# Refusals per file, durable beside the queue (#20234). CREATE IF NOT EXISTS: an existing install gains +# an empty table and no row of any other table is rewritten. +_ATTEMPTS_DDL = """ + CREATE TABLE IF NOT EXISTS file_cleanup_attempts ( + file_id TEXT PRIMARY KEY, + failed_attempts INTEGER NOT NULL DEFAULT 0, + last_failed_at TIMESTAMP, + last_reason TEXT + ) +""" + +_CANDIDATES_SQL = """ + SELECT cf.file_id, MIN(fcq.session_id) AS session_id, cf.original_filename, cf.file_size + FROM file_cleanup_queue fcq + JOIN conversation_files cf ON cf.file_id = fcq.file_id + LEFT JOIN file_cleanup_attempts fca ON fca.file_id = cf.file_id + WHERE fcq.is_processed = 0 AND cf.is_deleted = 1 AND fcq.scheduled_deletion_time <= datetime('now') + AND COALESCE(fca.failed_attempts, 0) < ? + AND (fca.last_failed_at IS NULL OR fca.last_failed_at <= datetime('now', ?)) + GROUP BY cf.file_id + ORDER BY MIN(fcq.cleanup_id) +""" + +_PENDING_STATS_SQL = """ + SELECT COUNT(DISTINCT cf.file_id) AS files, COALESCE(SUM(cf.file_size), 0) AS bytes + FROM conversation_files cf + WHERE cf.is_deleted = 1 + AND cf.file_id IN (SELECT file_id FROM file_cleanup_queue WHERE is_processed = 0) +""" + +_STUCK_SQL = """ + SELECT cf.file_id, cf.file_size, fca.failed_attempts, fca.last_reason + FROM file_cleanup_attempts fca + JOIN conversation_files cf ON cf.file_id = fca.file_id + WHERE fca.failed_attempts >= ? AND cf.is_deleted = 1 + AND cf.file_id IN (SELECT file_id FROM file_cleanup_queue WHERE is_processed = 0) + ORDER BY fca.last_failed_at DESC +""" + +_RECORD_FAILURE_SQL = """ + INSERT INTO file_cleanup_attempts (file_id, failed_attempts, last_failed_at, last_reason) + VALUES (?, 1, CURRENT_TIMESTAMP, ?) + ON CONFLICT(file_id) DO UPDATE SET failed_attempts = failed_attempts + 1, + last_failed_at = CURRENT_TIMESTAMP, last_reason = excluded.last_reason + RETURNING failed_attempts +""" + +#: Most stuck files itemised in the stats; the count is always complete. +_STUCK_LISTED = 50 + + +def cleanup_max_attempts() -> int: + """Refusals after which a file is no longer proposed (``AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS``).""" + return max(1, int(env("AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS"))) + + +def cooldown_seconds() -> int: + """Seconds a refused file waits before it may be proposed again.""" + return max(0, int(env("AUTOBOT_CONVERSATION_FILE_CLEANUP_COOLDOWN_SECONDS"))) + + +async def list_cleanup_candidates(manager) -> List[Dict[str, Any]]: + """Soft-deleted files whose cleanup is due, unprocessed, and not stuck or cooling down after refusals.""" + connection = await manager._get_async_db_connection() + try: + await connection.execute(_ATTEMPTS_DDL) + params = (cleanup_max_attempts(), f"-{cooldown_seconds()} seconds") + async with connection.execute(_CANDIDATES_SQL, params) as cursor: + return [dict(row) for row in await cursor.fetchall()] + finally: + await connection.close() + + +async def pending_cleanup_stats(connection) -> Dict[str, Any]: + """Deleted files still waiting on the queue (bytes on disk), proposed or not, and those stuck.""" + await connection.execute(_ATTEMPTS_DDL) + async with connection.execute(_PENDING_STATS_SQL) as cursor: + row = await cursor.fetchone() + async with connection.execute(_STUCK_SQL, (cleanup_max_attempts(),)) as cursor: + stuck = [dict(r) for r in await cursor.fetchall()] + return { + "pending_cleanup_files": row["files"] or 0, + "pending_cleanup_bytes": row["bytes"] or 0, + "stuck_cleanup_files": len(stuck), + "stuck_cleanup_bytes": sum(r["file_size"] or 0 for r in stuck), + "stuck_cleanup": stuck[:_STUCK_LISTED], + } + + +async def reset_cleanup_attempts(manager, file_id: str) -> bool: + """Forget a file's refusals so it can be proposed again; ``True`` when there was a count to forget. + + A person's action (``api/conversation_file_cleanup_admin.py``). It touches only the counter: no bytes, + queue row or file record, and the next proposal still waits for an approval. + """ + async with manager._lock: + connection = await manager._get_async_db_connection() + try: + await connection.execute(_ATTEMPTS_DDL) + cursor = await connection.execute("DELETE FROM file_cleanup_attempts WHERE file_id = ?", (file_id,)) + await connection.commit() + return cursor.rowcount > 0 + finally: + await connection.close() + + +async def cleanup_status(manager) -> Dict[str, Any]: + """:func:`pending_cleanup_stats` on its own connection, for the admin read route.""" + connection = await manager._get_async_db_connection() + try: + return await pending_cleanup_stats(connection) + finally: + await connection.close() + + +async def _record_failure(connection, file_id: str, reason: str) -> None: + """Count one refused removal; log once when the file reaches the cap and stops being proposed.""" + await connection.execute(_ATTEMPTS_DDL) + async with connection.execute(_RECORD_FAILURE_SQL, (file_id, reason)) as cursor: + attempts = (await cursor.fetchone())[0] + await connection.commit() + if attempts >= cleanup_max_attempts(): + logger.warning( + "Conversation file %s is stuck: removal refused %d time(s), last reason: %s; no longer proposed", + file_id, + attempts, + reason, + ) + + +async def deleted_file_stats(connection) -> tuple: + """Deleted file count and size.""" + query = ( + "SELECT COUNT(*) as deleted_files, SUM(file_size) as deleted_size " + "FROM conversation_files WHERE is_deleted = 1" + ) + async with connection.execute(query) as cursor: + row = await cursor.fetchone() + return row["deleted_files"] or 0, row["deleted_size"] or 0 + + +def _contained_file(storage_dir: Path, stored_path: str) -> Path | None: + """The resolved path when it is strictly inside the store, else ``None``.""" + resolved = Path(stored_path).resolve() + root = storage_dir.resolve() + if resolved == root or not resolved.is_relative_to(root): + return None + return resolved + + +async def _refusal(connection, file_id: str, row) -> str | None: + """Why this file must NOT be removed, or ``None`` when it may be.""" + if row is None: + return "no such file record" + if not row["is_deleted"]: + return "file is live (restored or never deleted)" + async with connection.execute( + "SELECT 1 FROM conversation_files WHERE file_path = ? AND file_id != ? AND is_deleted = 0 LIMIT 1", + (row["file_path"], file_id), + ) as cursor: + if await cursor.fetchone(): + return "file is still referenced by a live record" + return None + + +def _unlink_contained(storage_dir: Path, stored_path: str) -> str: + """Remove the file if (and only if) it resolves inside the store NOW. Returns the outcome.""" + target = _contained_file(storage_dir, stored_path) + if target is None: + return "outside" + if not target.exists(): + return "absent" + if not target.is_file(): + return "outside" + target.unlink() + return "removed" + + +async def _remove_validated(connection, manager, file_id: str, row) -> Dict[str, Any]: + """Unlink one validated file and mark its queue rows processed, or return the refusal.""" + reason = await _refusal(connection, file_id, row) + if reason: + return {"removed": False, "reason": reason, "size": 0} + outcome = await asyncio.to_thread(_unlink_contained, manager.storage_dir, row["file_path"]) + if outcome == "outside": + logger.error("Refused to remove %s: its stored path is outside the conversation file store", file_id) + return {"removed": False, "reason": "path is outside the conversation file store", "size": 0} + await connection.execute( + "UPDATE file_cleanup_queue SET is_processed = 1, processed_at = CURRENT_TIMESTAMP " + "WHERE file_id = ? AND is_processed = 0", + (file_id,), + ) + await connection.commit() + removed = outcome == "removed" + return {"removed": removed, "reason": None if removed else "bytes were already absent", "size": row["file_size"]} + + +async def remove_approved_file(manager, file_id: str) -> Dict[str, Any]: + """Remove the bytes of one approved file, re-validated now; a refusal is a result, not a raise. + + Returns ``{"removed": bool, "reason": str | None, "size": int}``. A refused file keeps its + queue row unprocessed, so it stays visible in the storage stats, and the refusal is counted + (an unlink error too, which still raises) so a permanent one stops being proposed (#20234). + """ + async with manager._lock: + connection = await manager._get_async_db_connection() + try: + async with connection.execute( + "SELECT file_path, file_size, is_deleted FROM conversation_files WHERE file_id = ?", (file_id,) + ) as cursor: + row = await cursor.fetchone() + try: + result = await _remove_validated(connection, manager, file_id, row) + except OSError as exc: + await _record_failure(connection, file_id, f"unlink failed: {exc}") + raise + if not result["removed"] and result["reason"] != "bytes were already absent": + await _record_failure(connection, file_id, result["reason"]) + return result + finally: + await connection.close() diff --git a/autobot-backend/conversation_file_cleanup_20234_test.py b/autobot-backend/conversation_file_cleanup_20234_test.py new file mode 100644 index 0000000000..2ee0b80ea9 --- /dev/null +++ b/autobot-backend/conversation_file_cleanup_20234_test.py @@ -0,0 +1,176 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""Deleted conversation files: queue -> proposal -> human approval -> removal (#20234, #17038). + +Real SQLite, real schema and a real directory; the real proposer, approval gate and dispatcher. +Only the approval DB session (a fake) and the audit sink are stubbed. +""" + +import asyncio +import uuid +from unittest.mock import AsyncMock + +import pytest + +from conversation_file_manager import ConversationFileManager +from services import approval_execution, conversation_file_cleanup_action, conversation_file_cleanup_proposals +from services.approval_gate_service import ApprovalGateService +from testkit.fake_approval_session import ApprovalClaimSession + +pytestmark = pytest.mark.asyncio + + +@pytest.fixture +async def manager(tmp_path): + mgr = ConversationFileManager(storage_dir=tmp_path / "storage", db_path=tmp_path / "files.db") + mgr._initialize_schema() + mgr._invalidate_session_cache = AsyncMock() + return mgr + + +async def _sql(mgr, sql, args=()): + conn = await mgr._get_async_db_connection() + try: + async with conn.execute(sql, args) as cur: + rows = await cur.fetchall() + await conn.commit() + return rows + finally: + await conn.close() + + +async def _deleted_file(mgr, session="s1", name="a.txt", content=b"bytes"): + stored = await mgr.add_file(session, content, name, uploaded_by="u") + await mgr.delete_file(session, stored["file_id"]) + await _sql(mgr, "UPDATE file_cleanup_queue SET scheduled_deletion_time = datetime('now', '-1 day')") + return stored + + +@pytest.fixture +def gate(monkeypatch, manager): + monkeypatch.setattr(approval_execution, "_REGISTRY", {}) + monkeypatch.setattr(approval_execution, "_PROPOSERS", {}) + monkeypatch.setattr(ApprovalGateService, "_notify", lambda self, event, approval: _noop()) + audited = [] + + async def _audit(operation, **kwargs): + audited.append({"operation": operation, **kwargs}) + return True + + monkeypatch.setattr(conversation_file_cleanup_action, "audit_log", _audit) + monkeypatch.setattr(approval_execution, "audit_log", _audit) + monkeypatch.setattr(conversation_file_cleanup_proposals, "_already_proposed", AsyncMock(return_value=set())) + monkeypatch.setattr("conversation_file_manager.get_conversation_file_manager", AsyncMock(return_value=manager)) + conversation_file_cleanup_action.register_conversation_file_cleanup_action() + return audited + + +async def _noop(): + return None + + +async def _propose(manager, session): + from conversation_file_cleanup import list_cleanup_candidates + + candidates = await list_cleanup_candidates(manager) + return await conversation_file_cleanup_proposals.propose_cleanups_for(session, candidates) + + +async def test_due_queue_entries_become_pending_proposals_and_remove_nothing(manager, gate): + stored = await _deleted_file(manager) + session = ApprovalClaimSession() + + ids = await _propose(manager, session) + + assert len(ids) == 1 + assert session.approval.status == "pending" + assert session.approval.context["file_id"] == stored["file_id"] + assert "file_path" not in session.approval.context + assert (manager.storage_dir / "sessions" / "s1" / stored["stored_filename"]).exists(), "unapproved removes nothing" + + +async def test_a_live_file_is_never_a_candidate(manager, gate): + await manager.add_file("s1", b"keep", "keep.txt", uploaded_by="u") + await _sql(manager, "UPDATE file_cleanup_queue SET scheduled_deletion_time = datetime('now', '-1 day')") + assert await _propose(manager, ApprovalClaimSession()) == [] + + +async def test_approving_removes_the_bytes_and_records_it(manager, gate): + stored = await _deleted_file(manager) + path = manager.storage_dir / "sessions" / "s1" / stored["stored_filename"] + session = ApprovalClaimSession() + ids = await _propose(manager, session) + + await ApprovalGateService(session).approve(uuid.UUID(ids[0]), decided_by="alice", author_type="human", comment=None) + + assert not path.exists() + assert [a["operation"] for a in gate] == ["conversation_file.cleanup"] + assert gate[0]["result"] == "success" + assert gate[0]["user_id"] == "alice" + processed = await _sql( + manager, "SELECT is_processed FROM file_cleanup_queue WHERE file_id = ?", (stored["file_id"],) + ) + assert [r[0] for r in processed] == [1] + assert await _sql( + manager, "SELECT 1 FROM conversation_files WHERE file_id = ?", (stored["file_id"],) + ), "record outlives bytes" + stats = await manager.get_storage_stats() + assert stats["pending_cleanup_files"] == 0 + + +async def test_a_denied_entry_stays_on_disk_and_pending_in_the_stats(manager, gate): + stored = await _deleted_file(manager) + path = manager.storage_dir / "sessions" / "s1" / stored["stored_filename"] + session = ApprovalClaimSession() + ids = await _propose(manager, session) + + await ApprovalGateService(session).reject(uuid.UUID(ids[0]), decided_by="alice", author_type="human", comment=None) + + assert path.exists() and gate == [] + stats = await manager.get_storage_stats() + assert stats["pending_cleanup_files"] == 1 + assert stats["pending_cleanup_bytes"] == len(b"bytes") + + +async def test_a_path_outside_the_store_is_refused(manager, gate, tmp_path): + from conversation_file_cleanup import remove_approved_file + + stored = await _deleted_file(manager) + outside = tmp_path / "outside.txt" + await asyncio.to_thread(outside.write_bytes, b"not ours") + await _sql( + manager, "UPDATE conversation_files SET file_path = ? WHERE file_id = ?", (str(outside), stored["file_id"]) + ) + + result = await remove_approved_file(manager, stored["file_id"]) + + assert result["removed"] is False and "outside" in result["reason"] + assert outside.exists() + assert (await _sql(manager, "SELECT is_processed FROM file_cleanup_queue"))[0][0] == 0 + + +async def test_a_restored_file_is_not_removed(manager, gate): + from conversation_file_cleanup import remove_approved_file + + stored = await _deleted_file(manager) + path = manager.storage_dir / "sessions" / "s1" / stored["stored_filename"] + await _sql(manager, "UPDATE conversation_files SET is_deleted = 0 WHERE file_id = ?", (stored["file_id"],)) + + result = await remove_approved_file(manager, stored["file_id"]) + + assert result["removed"] is False and "live" in result["reason"] + assert path.exists() + + +async def test_a_file_still_referenced_by_a_live_record_is_not_removed(manager, gate): + from conversation_file_cleanup import remove_approved_file + + stored = await _deleted_file(manager) + path = manager.storage_dir / "sessions" / "s1" / stored["stored_filename"] + live = await manager.add_file("s2", b"other", "b.txt", uploaded_by="u") + await _sql(manager, "UPDATE conversation_files SET file_path = ? WHERE file_id = ?", (str(path), live["file_id"])) + + result = await remove_approved_file(manager, stored["file_id"]) + + assert result["removed"] is False and "referenced" in result["reason"] + assert path.exists() diff --git a/autobot-backend/conversation_file_cleanup_admin_20234_test.py b/autobot-backend/conversation_file_cleanup_admin_20234_test.py new file mode 100644 index 0000000000..d1213872bb --- /dev/null +++ b/autobot-backend/conversation_file_cleanup_admin_20234_test.py @@ -0,0 +1,151 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""Admin view and reset of stuck cleanups, and the duplicate-refusing migration (#20234, #17038). + +The routes run against the real SQLite file store; only auth, the audit sink and the proposer are +stubbed. The migration runs its real ``upgrade()`` on SQLite, which understands ``->>``; PostgreSQL's +index DDL is not executed here. +""" + +import importlib.util +import re +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +import sqlalchemy as sa +from fastapi import HTTPException + +from api import conversation_file_cleanup_admin as admin +from conversation_file_manager import ConversationFileManager + +pytestmark = pytest.mark.asyncio + + +@pytest.fixture +async def manager(tmp_path, monkeypatch): + mgr = ConversationFileManager(storage_dir=tmp_path / "storage", db_path=tmp_path / "files.db") + mgr._initialize_schema() + mgr._invalidate_session_cache = AsyncMock() + monkeypatch.setattr( + "services.conversation_file_cleanup_proposals.propose_due_cleanups_logged", AsyncMock(return_value=None) + ) + return mgr + + +@pytest.fixture +def request_for(manager, monkeypatch): + audit = AsyncMock(return_value=True) + monkeypatch.setattr(admin, "audit_log", audit) + monkeypatch.setattr(admin, "resolve_human_user", AsyncMock(return_value={"username": "alice"})) + monkeypatch.setenv("AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS", "2") + req = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(conversation_file_manager=manager))) + return req, audit + + +async def _stuck_file(mgr): + stored = await mgr.add_file("s1", b"bytes", "a.txt", uploaded_by="u") + await mgr.delete_file("s1", stored["file_id"]) + conn = await mgr._get_async_db_connection() + try: + await conn.execute( + "CREATE TABLE IF NOT EXISTS file_cleanup_attempts (file_id TEXT PRIMARY KEY, failed_attempts INTEGER " + "NOT NULL DEFAULT 0, last_failed_at TIMESTAMP, last_reason TEXT)" + ) + await conn.execute( + "INSERT INTO file_cleanup_attempts VALUES (?, 2, CURRENT_TIMESTAMP, 'path is outside')", + (stored["file_id"],), + ) + await conn.commit() + finally: + await conn.close() + return stored["file_id"] + + +async def test_status_lists_the_stuck_file(manager, request_for): + req, _ = request_for + file_id = await _stuck_file(manager) + status = await admin.get_cleanup_status(req) + assert status["stuck_cleanup_files"] == 1 and status["pending_cleanup_files"] == 1 + assert status["stuck_cleanup"][0]["file_id"] == file_id + + +async def test_reset_clears_the_count_audits_and_removes_no_bytes(manager, request_for): + req, audit = request_for + file_id = await _stuck_file(manager) + path = Path((await manager.get_storage_stats())["storage_directory"]) + before = sorted(p.name for p in path.rglob("*") if p.is_file()) + + assert await admin.reset_stuck_cleanup(req, file_id) == {"file_id": file_id, "reset": True} + + assert (await admin.get_cleanup_status(req))["stuck_cleanup_files"] == 0 + assert sorted(p.name for p in path.rglob("*") if p.is_file()) == before, "reset removes no bytes" + audit.assert_awaited_once() + assert audit.await_args.args[0] == "conversation_file.cleanup_reset" + assert audit.await_args.kwargs["user_id"] == "alice" + assert audit.await_args.kwargs["resource"] == f"conversation_file:{file_id}" + + +async def test_reset_of_a_file_with_no_refusals_is_404_and_audits_nothing(manager, request_for): + req, audit = request_for + with pytest.raises(HTTPException) as err: + await admin.reset_stuck_cleanup(req, "no-such-file") + assert err.value.status_code == 404 + audit.assert_not_awaited() + + +async def test_routes_are_admin_only_and_declared(): + deps = [d.dependency.__name__ for d in admin.router.dependencies] + assert len(deps) == 1 and "admin_permission" in deps[0] # the suite may stub the dependency by name + assert {r.path for r in admin.router.routes} == {"/cleanup/status", "/cleanup/{file_id}/reset"} + + +def _migration(): + path = Path(__file__).parent / "migrations/versions/20261101_110_approvals_pending_file_cleanup_unique.py" + spec = importlib.util.spec_from_file_location("mig109_admin_test", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _run_upgrade(mod, monkeypatch, rows): + engine = sa.create_engine("sqlite://") # canonical: ignore py-adhoc-db-engine + with engine.begin() as conn: + conn.execute(sa.text("CREATE TABLE approvals (status TEXT, requested_by_agent TEXT, context JSON)")) + for file_id in rows: + conn.execute( + sa.text( + "INSERT INTO approvals VALUES ('pending', 'conversation-file-cleanup', " + "json_object('action', 'conversation_file_cleanup', 'file_id', :f))" + ), + {"f": file_id}, + ) + + def execute(statement): # this SQLite predates ``->>``: the same path read with json_extract + sql = re.sub(r"context ->> '(\w+)'", r"json_extract(context, '$.\1')", str(statement)) + return conn.execute(sa.text(sql)) + + bind = SimpleNamespace(dialect=SimpleNamespace(name="postgresql"), execute=execute) + create = MagicMock() + monkeypatch.setattr(mod.op, "get_bind", lambda: bind) + monkeypatch.setattr(mod.op, "create_index", create) + monkeypatch.setattr(mod, "has_table", lambda _t: True) + monkeypatch.setattr(mod, "has_index", lambda _t, _i: False) + mod.upgrade() + return create + + +async def test_migration_fails_naming_duplicates_and_changes_nothing(monkeypatch): + mod = _migration() + with pytest.raises(RuntimeError) as err: + _run_upgrade(mod, monkeypatch, ["f-dup", "f-dup", "f-ok"]) + message = str(err.value) + assert "f-dup (2 pending)" in message and "f-ok" not in message + assert "Approvals inbox" in message and "Nothing was changed" in message + + +async def test_migration_creates_the_index_when_there_are_no_duplicates(monkeypatch): + create = _run_upgrade(_migration(), monkeypatch, ["f-1", "f-2"]) + create.assert_called_once() + assert create.call_args.args[0] == "uq_approvals_pending_file_cleanup" diff --git a/autobot-backend/conversation_file_cleanup_bounds_20234_test.py b/autobot-backend/conversation_file_cleanup_bounds_20234_test.py new file mode 100644 index 0000000000..e6b93bc64d --- /dev/null +++ b/autobot-backend/conversation_file_cleanup_bounds_20234_test.py @@ -0,0 +1,192 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""Two bounds on cleanup proposals (#20234): one pending per file under concurrency, and a cap on refusals. + +Real SQLite for the file store and for ``approvals``; the real proposer, gate and dispatcher run. +The database-level uniqueness is exercised with an equivalent partial unique index created on SQLite +(the model's own index is PostgreSQL-only; its definition is pinned against the migration below). +""" + +import asyncio +import uuid +from unittest.mock import AsyncMock + +import pytest +from sqlalchemy import func, select, text +from sqlalchemy.dialects import postgresql +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine +from sqlalchemy.ext.compiler import compiles +from sqlalchemy.schema import CreateIndex + +from conversation_file_manager import ConversationFileManager +from models.approval import ( + PENDING_FILE_CLEANUP_INDEX, + PENDING_FILE_CLEANUP_WHERE, + Approval, + ApprovalComment, + TaskApprovalLink, +) +from services import approval_execution, conversation_file_cleanup_action, conversation_file_cleanup_proposals +from services.approval_gate_service import ApprovalGateService + +pytestmark = pytest.mark.asyncio + +_SQLITE_UNIQUE_PENDING = ( + "CREATE UNIQUE INDEX uq_pending ON approvals (json_extract(context, '$.file_id')) " + "WHERE status = 'pending' AND requested_by_agent = 'conversation-file-cleanup'" +) + + +@compiles(JSONB, "sqlite") +def _jsonb_as_json(element, compiler, **kw): + return "JSON" + + +@pytest.fixture +async def manager(tmp_path): + mgr = ConversationFileManager(storage_dir=tmp_path / "storage", db_path=tmp_path / "files.db") + mgr._initialize_schema() + mgr._invalidate_session_cache = AsyncMock() + return mgr + + +@pytest.fixture +async def engine(tmp_path): + url = f"sqlite+aiosqlite:///{tmp_path / 'approvals.db'}" + eng = create_async_engine(url) # canonical: ignore py-adhoc-db-engine + async with eng.begin() as conn: + for model in (Approval, ApprovalComment, TaskApprovalLink): + await conn.run_sync(model.__table__.create) + yield eng + await eng.dispose() + + +@pytest.fixture +def gate(monkeypatch, manager): + monkeypatch.setattr(approval_execution, "_REGISTRY", {}) + monkeypatch.setattr(approval_execution, "_PROPOSERS", {}) + monkeypatch.setattr(ApprovalGateService, "_notify", AsyncMock()) + monkeypatch.setattr(conversation_file_cleanup_action, "audit_log", AsyncMock(return_value=True)) + monkeypatch.setattr(approval_execution, "audit_log", AsyncMock(return_value=True)) + monkeypatch.setattr("conversation_file_manager.get_conversation_file_manager", AsyncMock(return_value=manager)) + conversation_file_cleanup_action.register_conversation_file_cleanup_action() + + +async def _sql(mgr, sql, args=()): + conn = await mgr._get_async_db_connection() + try: + async with conn.execute(sql, args) as cur: + rows = await cur.fetchall() + await conn.commit() + return rows + finally: + await conn.close() + + +async def _deleted_file(mgr): + stored = await mgr.add_file("s1", b"bytes", "a.txt", uploaded_by="u") + await mgr.delete_file("s1", stored["file_id"]) + await _sql(mgr, "UPDATE file_cleanup_queue SET scheduled_deletion_time = datetime('now', '-1 day')") + return stored + + +async def _sweep(manager, db): + from conversation_file_cleanup import list_cleanup_candidates + + return await conversation_file_cleanup_proposals.propose_cleanups_for(db, await list_cleanup_candidates(manager)) + + +async def _refuse_once(manager, db): + """Propose, point the file outside the store, approve: the removal is refused and counted.""" + (approval_id,) = await _sweep(manager, db) + await ApprovalGateService(db).approve(uuid.UUID(approval_id), decided_by="alice", author_type="human") + + +async def test_two_concurrent_proposers_create_one_pending_proposal(manager, engine, gate, monkeypatch): + stored = await _deleted_file(manager) + async with engine.begin() as conn: + await conn.execute(text(_SQLITE_UNIQUE_PENDING)) + # Both workers read "nothing proposed yet" before either inserts: only the database can stop the second. + monkeypatch.setattr(conversation_file_cleanup_proposals, "_already_proposed", AsyncMock(return_value=set())) + factory = async_sessionmaker(engine, expire_on_commit=False) # canonical: ignore py-adhoc-db-engine + + async def worker(): + async with factory() as session: + return await _sweep(manager, session) + + results = await asyncio.gather(worker(), worker()) + + assert sorted(len(r) for r in results) == [0, 1] + async with factory() as session: + count = await session.scalar(select(func.count()).select_from(Approval).where(Approval.status == "pending")) + assert count == 1, stored["file_id"] + + +async def test_model_index_is_postgres_only_and_matches_the_migration(): + import importlib.util + from pathlib import Path + + index = next(i for i in Approval.__table__.indexes if i.name == PENDING_FILE_CLEANUP_INDEX) + ddl = str(CreateIndex(index).compile(dialect=postgresql.dialect())) + assert "UNIQUE" in ddl and "(context ->> 'file_id')" in ddl and PENDING_FILE_CLEANUP_WHERE in ddl + assert f"requested_by_agent = '{conversation_file_cleanup_proposals.REQUESTED_BY}'" in PENDING_FILE_CLEANUP_WHERE + assert f"= '{conversation_file_cleanup_proposals.ACTION}'" in PENDING_FILE_CLEANUP_WHERE + path = Path(__file__).parent / "migrations/versions/20261101_110_approvals_pending_file_cleanup_unique.py" + spec = importlib.util.spec_from_file_location("mig109", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + assert mod._WHERE == PENDING_FILE_CLEANUP_WHERE and mod._INDEX == PENDING_FILE_CLEANUP_INDEX + + +async def test_a_refused_removal_stops_being_proposed_after_the_cap(manager, engine, gate, tmp_path, monkeypatch): + monkeypatch.setenv("AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS", "2") + monkeypatch.setenv("AUTOBOT_CONVERSATION_FILE_CLEANUP_COOLDOWN_SECONDS", "0") + stored = await _deleted_file(manager) + outside = tmp_path / "outside.txt" + await asyncio.to_thread(outside.write_bytes, b"not ours") + await _sql( + manager, "UPDATE conversation_files SET file_path = ? WHERE file_id = ?", (str(outside), stored["file_id"]) + ) + + async with AsyncSession(engine, expire_on_commit=False) as db: + await _refuse_once(manager, db) + assert (await manager.get_storage_stats())["stuck_cleanup_files"] == 0 + await _refuse_once(manager, db) + assert await _sweep(manager, db) == [], "capped: no third proposal" + total = await db.scalar(select(func.count()).select_from(Approval)) + + assert total == 2 + stats = await manager.get_storage_stats() + assert stats["stuck_cleanup_files"] == 1 and stats["stuck_cleanup_bytes"] == len(b"bytes") + assert stats["stuck_cleanup"][0]["file_id"] == stored["file_id"] + assert stats["stuck_cleanup"][0]["failed_attempts"] == 2 + assert "outside" in stats["stuck_cleanup"][0]["last_reason"] + assert stats["pending_cleanup_files"] == 1, "the bytes are still on disk and still counted as pending" + assert outside.exists() + + +async def test_a_refusal_inside_the_cooldown_is_not_proposed_again(manager, engine, gate, tmp_path, monkeypatch): + monkeypatch.setenv("AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS", "5") + monkeypatch.setenv("AUTOBOT_CONVERSATION_FILE_CLEANUP_COOLDOWN_SECONDS", "3600") + stored = await _deleted_file(manager) + outside = tmp_path / "outside.txt" + await asyncio.to_thread(outside.write_bytes, b"not ours") + await _sql( + manager, "UPDATE conversation_files SET file_path = ? WHERE file_id = ?", (str(outside), stored["file_id"]) + ) + + async with AsyncSession(engine, expire_on_commit=False) as db: + await _refuse_once(manager, db) + assert await _sweep(manager, db) == [], "cooling down" + await _sql(manager, "UPDATE file_cleanup_attempts SET last_failed_at = datetime('now', '-2 hours')") + assert len(await _sweep(manager, db)) == 1, "cooldown over, under the cap: proposed again" + assert (await manager.get_storage_stats())["stuck_cleanup_files"] == 0 + + +async def test_a_successful_removal_is_never_counted(manager, engine, gate): + await _deleted_file(manager) + async with AsyncSession(engine, expire_on_commit=False) as db: + (approval_id,) = await _sweep(manager, db) + await ApprovalGateService(db).approve(uuid.UUID(approval_id), decided_by="alice", author_type="human") + assert await _sql(manager, "SELECT 1 FROM file_cleanup_attempts") == [] diff --git a/autobot-backend/conversation_file_cleanup_reproposal_20234_test.py b/autobot-backend/conversation_file_cleanup_reproposal_20234_test.py new file mode 100644 index 0000000000..fbe831b5ce --- /dev/null +++ b/autobot-backend/conversation_file_cleanup_reproposal_20234_test.py @@ -0,0 +1,159 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""Re-proposal of conversation file cleanups, and the hard-delete gate (#20234, #20488, #17038). + +The real proposer, approval gate service and dispatcher run on a real SQLite ``approvals`` table +(JSONB rendered as JSON), so the lookup that decides "already proposed" executes as SQL rather +than being stubbed. A denial must stay denied; a failed or expired proposal must come back. +""" + +import uuid +from unittest.mock import AsyncMock + +import pytest +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine +from sqlalchemy.ext.compiler import compiles + +from conversation_file_manager import ConversationFileManager +from models.approval import Approval, ApprovalComment, TaskApprovalLink +from services import approval_execution, conversation_file_cleanup_action, conversation_file_cleanup_proposals +from services.approval_gate_service import ApprovalGateService + +pytestmark = pytest.mark.asyncio + +_URL = "sqlite+aiosqlite:///:memory:" + + +@compiles(JSONB, "sqlite") +def _jsonb_as_json(element, compiler, **kw): + return "JSON" + + +@pytest.fixture +async def manager(tmp_path): + mgr = ConversationFileManager(storage_dir=tmp_path / "storage", db_path=tmp_path / "files.db") + mgr._initialize_schema() + mgr._invalidate_session_cache = AsyncMock() + return mgr + + +@pytest.fixture +async def db(): + engine = create_async_engine(_URL) # canonical: ignore py-adhoc-db-engine (in-memory test store) + async with engine.begin() as conn: + for model in (Approval, ApprovalComment, TaskApprovalLink): + await conn.run_sync(model.__table__.create) + async with AsyncSession(engine, expire_on_commit=False) as session: + yield session + await engine.dispose() + + +@pytest.fixture +def gate(monkeypatch, manager): + monkeypatch.setattr(approval_execution, "_REGISTRY", {}) + monkeypatch.setattr(approval_execution, "_PROPOSERS", {}) + monkeypatch.setattr(ApprovalGateService, "_notify", AsyncMock()) + monkeypatch.setattr(conversation_file_cleanup_action, "audit_log", AsyncMock(return_value=True)) + monkeypatch.setattr(approval_execution, "audit_log", AsyncMock(return_value=True)) + monkeypatch.setattr("conversation_file_manager.get_conversation_file_manager", AsyncMock(return_value=manager)) + conversation_file_cleanup_action.register_conversation_file_cleanup_action() + + +async def _sql(mgr, sql, args=()): + conn = await mgr._get_async_db_connection() + try: + async with conn.execute(sql, args) as cur: + rows = await cur.fetchall() + await conn.commit() + return rows + finally: + await conn.close() + + +async def _make_due(mgr): + await _sql(mgr, "UPDATE file_cleanup_queue SET scheduled_deletion_time = datetime('now', '-1 day')") + + +async def _deleted_file(mgr, session="s1", name="a.txt"): + stored = await mgr.add_file(session, b"bytes", name, uploaded_by="u") + await mgr.delete_file(session, stored["file_id"]) + await _make_due(mgr) + return stored + + +async def _sweep(manager, db): + from conversation_file_cleanup import list_cleanup_candidates + + return await conversation_file_cleanup_proposals.propose_cleanups_for(db, await list_cleanup_candidates(manager)) + + +async def test_a_pending_proposal_is_not_repeated(manager, db, gate): + await _deleted_file(manager) + assert len(await _sweep(manager, db)) == 1 + assert await _sweep(manager, db) == [] + + +async def test_a_denied_proposal_stays_denied(manager, db, gate): + await _deleted_file(manager) + (approval_id,) = await _sweep(manager, db) + await ApprovalGateService(db).reject(uuid.UUID(approval_id), decided_by="alice", author_type="human") + + assert await _sweep(manager, db) == [] + assert await _sweep(manager, db) == [] + + +async def test_a_failed_execution_is_proposed_again(manager, db, gate, monkeypatch): + """Approved, but the removal was refused (the file is live): the bytes remain, so retry.""" + monkeypatch.setenv("AUTOBOT_CONVERSATION_FILE_CLEANUP_COOLDOWN_SECONDS", "0") # bounds: ..._bounds_20234_test.py + stored = await _deleted_file(manager) + (first,) = await _sweep(manager, db) + await _sql(manager, "UPDATE conversation_files SET is_deleted = 0 WHERE file_id = ?", (stored["file_id"],)) + await ApprovalGateService(db).approve(uuid.UUID(first), decided_by="alice", author_type="human") + await _sql(manager, "UPDATE conversation_files SET is_deleted = 1 WHERE file_id = ?", (stored["file_id"],)) + assert (manager.storage_dir / "sessions" / "s1" / stored["stored_filename"]).exists() + + (second,) = await _sweep(manager, db) + + assert second != first + + +async def test_an_expired_proposal_is_proposed_again(manager, db, gate): + await _deleted_file(manager) + (first,) = await _sweep(manager, db) + approval = await db.get(Approval, uuid.UUID(first)) + approval.status = "expired" + await db.commit() + + (second,) = await _sweep(manager, db) + + assert second != first + + +async def test_a_removed_file_is_not_proposed_again(manager, db, gate): + await _deleted_file(manager) + (approval_id,) = await _sweep(manager, db) + await ApprovalGateService(db).approve(uuid.UUID(approval_id), decided_by="alice", author_type="human") + + assert await _sweep(manager, db) == [] + + +async def test_hard_delete_removes_no_bytes_and_leaves_them_to_the_gate(manager, db, gate): + stored = await manager.add_file("s1", b"bytes", "a.txt", uploaded_by="u") + path = manager.storage_dir / "sessions" / "s1" / stored["stored_filename"] + + assert await manager.delete_session_files("s1", hard_delete=True) == 1 + + assert path.exists() + assert (await _sql(manager, "SELECT is_deleted FROM conversation_files"))[0][0] == 1 + await _make_due(manager) + assert len(await _sweep(manager, db)) == 1, "the bytes now wait on a proposal" + + +async def test_cleanup_session_defaults_to_the_gate_too(manager, gate): + stored = await manager.add_file("s1", b"bytes", "a.txt", uploaded_by="u") + path = manager.storage_dir / "sessions" / "s1" / stored["stored_filename"] + + result = await manager.cleanup_session("s1") + + assert result["files_deleted"] == 1 and path.exists() diff --git a/autobot-backend/conversation_file_manager.py b/autobot-backend/conversation_file_manager.py index 7e2ad933da..f7f21c6aec 100644 --- a/autobot-backend/conversation_file_manager.py +++ b/autobot-backend/conversation_file_manager.py @@ -36,6 +36,8 @@ from config import unified_config_manager from constants.threshold_constants import TimingConstants from constants.ttl_constants import TTL_1_HOUR +from conversation_file_cleanup import deleted_file_stats, pending_cleanup_stats +from conversation_file_quota import UploadRefused, abandon, file_too_large, insert_within_quota, resize_within_quota from conversation_file_route_api import FILE_INFO_COLUMNS, ConversationFileRouteApi from conversation_file_upload_info import UploadInfo from utils.chat_utils import validate_chat_session_id @@ -155,7 +157,8 @@ async def cleanup_session(self, session_id: str, hard_delete: bool = True) -> Di Args: session_id: Chat session identifier - hard_delete: If True, remove files from disk and database + hard_delete: Kept for callers; the files are soft-deleted and their bytes leave only + through an approved cleanup proposal (#20488) Returns: Dict with cleanup statistics @@ -217,7 +220,7 @@ async def _lookup_session_file(self, connection, session_id: str, file_id: str): """ async with connection.execute( """ - SELECT cf.file_id, cf.original_filename, cf.file_path, cf.mime_type + SELECT cf.file_id, cf.original_filename, cf.file_path, cf.mime_type, cf.uploaded_by FROM conversation_files cf JOIN session_file_associations sfa ON cf.file_id = sfa.file_id WHERE cf.file_id = ? AND sfa.session_id = ? AND cf.is_deleted = 0 @@ -307,13 +310,9 @@ async def _write_and_update_file(self, connection, row, content: str, session_id encoded = content.encode("utf-8") new_hash = self._compute_file_hash(encoded) + await resize_within_quota(connection, row, len(encoded), new_hash) # before the write: a refusal writes nothing async with aiofiles.open(file_path, "wb") as f: await f.write(encoded) - - await connection.execute( - "UPDATE conversation_files SET file_size = ?, file_hash = ? WHERE file_id = ?", - (len(encoded), new_hash, row["file_id"]), - ) await connection.commit() await self._invalidate_session_cache(session_id) return { @@ -329,7 +328,8 @@ async def update_file_content(self, session_id: str, file_id: str, content: str) try: row = await self._lookup_session_file(connection, session_id, file_id) return await self._write_and_update_file(connection, row, content, session_id) - except RuntimeError: + except (RuntimeError, UploadRefused): + await connection.rollback() raise except Exception as e: await connection.rollback() @@ -366,7 +366,7 @@ async def copy_file(self, session_id: str, file_id: str, new_filename: str | Non original_filename=copy_name, mime_type=row["mime_type"], ) - except RuntimeError: + except (RuntimeError, UploadRefused): raise except Exception as e: logger.error("Error copying file: %s", e) @@ -624,10 +624,10 @@ async def _invalidate_session_cache(self, session_id: str) -> None: logger.error("Unexpected error invalidating cache: %s", e) def _validate_file_size(self, file_content: bytes) -> int: - """Validate file size and return size in bytes.""" + """Validate file size and return size in bytes; past the cap is the 413 ``file_too_large`` (#20217).""" file_size = len(file_content) if file_size > self.MAX_FILE_SIZE: - raise ValueError(f"File size ({file_size} bytes) exceeds maximum " f"({self.MAX_FILE_SIZE} bytes)") + raise file_too_large(self.MAX_FILE_SIZE) return file_size async def _check_existing_file(self, connection, session_id: str, file_hash: str): @@ -713,16 +713,8 @@ async def _write_file_to_disk(self, file_path: Path, file_content: bytes) -> Non raise RuntimeError(f"Failed to write file to disk: {e}") async def _insert_file_record(self, connection, file_info: UploadInfo) -> None: - """Insert file record into database (Issue #375: uses UploadInfo dataclass).""" - await connection.execute( - """ - INSERT INTO conversation_files - (file_id, session_id, original_filename, stored_filename, - file_path, file_size, file_hash, mime_type, uploaded_by) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - file_info.to_db_tuple(), - ) + """Insert the file record unless its owner would pass the quota (#20217, #375).""" + await insert_within_quota(connection, file_info.to_db_tuple(), file_info.uploaded_by, file_info.file_size) async def _insert_file_metadata(self, connection, file_id: str, metadata: Dict[str, Any]) -> None: """Insert file metadata records into database.""" @@ -817,15 +809,17 @@ async def add_file( ) connection = await self._get_async_db_connection() + deduplicated = False try: existing_file = await self._check_existing_file(connection, file_info.session_id, file_info.file_hash) if existing_file: + deduplicated = True return await self._handle_deduplicated_file(connection, existing_file, file_info) return await self._store_new_file(connection, file_info, file_content) except Exception as e: - await connection.rollback() - if await asyncio.to_thread(file_info.file_path.exists): - await asyncio.to_thread(file_info.file_path.unlink) + await abandon(connection, file_info.file_path, remove_bytes=not deduplicated) + if isinstance(e, UploadRefused): + raise # a refusal (quota, #20217) keeps its 413 and stable code logger.error("Error adding file: %s", e) raise RuntimeError(f"Failed to add file: {e}") finally: @@ -960,7 +954,11 @@ async def get_session_files(self, session_id: str, include_deleted: bool = False await connection.close() async def _hard_delete_file(self, connection, file_id: str, file_path: Path) -> None: - """Permanently delete a file (Issue #315 - extracted helper).""" + """Permanently delete a file (Issue #315 - extracted helper). + + Not wired: nothing calls it. Removing stored bytes goes through the approval gate + (#17038), so ``hard_delete=True`` soft-deletes instead; see #20488. + """ await connection.execute("DELETE FROM conversation_files WHERE file_id = ?", (file_id,)) # Issue #358 - avoid blocking if await asyncio.to_thread(file_path.exists): @@ -1003,32 +1001,19 @@ async def _delete_files_batch(self, connection, files: List, hard_delete: bool) file_ids = [file_row["file_id"] for file_row in files] if hard_delete: - # For hard delete, we need to delete files from disk (can't batch filesystem ops) - # but we can batch the SQL delete - for file_row in files: - file_path = Path(file_row["file_path"]) - if await asyncio.to_thread(file_path.exists): - await asyncio.to_thread(file_path.unlink) - logger.info("Hard deleted file: %s", file_path) - - # Issue #397: Batch SQL delete using IN clause - placeholders = ",".join("?" * len(file_ids)) - await connection.execute( - f"DELETE FROM conversation_files WHERE file_id IN ({placeholders})", # nosec B608 # parameterized ? - file_ids, - ) - else: - # Issue #397: Batch soft delete using IN clause instead of N+1 pattern - placeholders = ",".join("?" * len(file_ids)) - await connection.execute( - f""" - UPDATE conversation_files - SET is_deleted = 1, deleted_at = CURRENT_TIMESTAMP - WHERE file_id IN ({placeholders}) - """, # nosec B608 # parameterized placeholders, not string interpolation - file_ids, - ) - logger.info("Soft deleted %d files in batch", len(file_ids)) + # Removing stored bytes needs a person's approval (#17038, #20488): a hard delete + # is a soft delete here, and the bytes leave only through the cleanup proposal gate. + logger.info("hard_delete requested for %d file(s): bytes await approval (#20488)", len(file_ids)) + placeholders = ",".join("?" * len(file_ids)) + await connection.execute( + f""" + UPDATE conversation_files + SET is_deleted = 1, deleted_at = CURRENT_TIMESTAMP + WHERE file_id IN ({placeholders}) + """, # nosec B608 # parameterized placeholders, not string interpolation + file_ids, + ) + logger.info("Soft deleted %d files in batch", len(file_ids)) return len(file_ids) @@ -1134,6 +1119,9 @@ async def initialize(self) -> None: # Verify schema version version = await self.get_schema_version() logger.info("Conversation files database initialized (schema version: %s)", version) + from services.conversation_file_cleanup_proposals import propose_due_cleanups_logged + + await propose_due_cleanups_logged(self) # proposes only; removal waits for a human (#20234) except Exception as e: logger.error("Failed to initialize conversation files database: %s", e) @@ -1182,25 +1170,16 @@ async def _get_session_count(self, connection) -> int: row = await cursor.fetchone() return row["total_sessions"] or 0 - async def _get_deleted_file_stats(self, connection) -> tuple: - """Get deleted file count and size.""" - query = ( - "SELECT COUNT(*) as deleted_files, SUM(file_size) as deleted_size " - "FROM conversation_files WHERE is_deleted = 1" - ) - async with connection.execute(query) as cursor: - row = await cursor.fetchone() - return row["deleted_files"] or 0, row["deleted_size"] or 0 - async def get_storage_stats(self) -> Dict[str, Any]: """Get storage statistics.""" connection = await self._get_async_db_connection() try: total_files, total_size = await self._get_active_file_stats(connection) total_sessions = await self._get_session_count(connection) - deleted_files, deleted_size = await self._get_deleted_file_stats(connection) + deleted_files, deleted_size = await deleted_file_stats(connection) return { + **await pending_cleanup_stats(connection), # bytes awaiting a human's approval (#20234) "total_files": total_files, "total_size_bytes": total_size, "total_size_mb": round(total_size / (1024 * 1024), 2), diff --git a/autobot-backend/conversation_file_manager_init_test.py b/autobot-backend/conversation_file_manager_init_test.py index 57aa55fb1e..63ba09bd12 100644 --- a/autobot-backend/conversation_file_manager_init_test.py +++ b/autobot-backend/conversation_file_manager_init_test.py @@ -303,8 +303,8 @@ async def test_idempotent_initialization(self, conversation_file_manager, temp_d ) table_count = rows[0][0] - # Expected: 6 schema tables (5 + chat_attachment_marks, #20195) + 1 schema_migrations table - assert table_count == 7, f"Should have exactly 7 tables, found {table_count}" + # Expected: 6 schema tables (5 + chat_attachment_marks, #20195), file_cleanup_attempts (#20234) and schema_migrations + assert table_count == 8, f"Should have exactly 8 tables, found {table_count}" logger.info(f"✓ Table count correct: {table_count}") logger.info("=== Test 1.2: PASSED ===\n") @@ -629,7 +629,7 @@ async def test_concurrent_initialization_safe(self, temp_db_path): "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'", ) table_count = rows[0][0] - assert table_count == 7, f"Should have 7 tables, found {table_count}" + assert table_count == 8, f"Should have 8 tables, found {table_count}" logger.info("✓ All tables exist after concurrent initialization") # Verify all manager instances can query schema version diff --git a/autobot-backend/conversation_file_quota.py b/autobot-backend/conversation_file_quota.py new file mode 100644 index 0000000000..79f6f44580 --- /dev/null +++ b/autobot-backend/conversation_file_quota.py @@ -0,0 +1,136 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""The size cap and per-user byte quota on stored conversation files (#20217). + +Every way a file enters the store (upload, create, agent-create, copy, content update) ends in +``ConversationFileManager.add_file`` or ``_write_and_update_file``; both call the conditional statements +here, so the quota is enforced where the bytes are recorded, not per route. + +What counts against an owner: live files, plus soft-deleted files whose bytes still await removal +(an unprocessed ``file_cleanup_queue`` row, the representation #20234 uses). A deleted file's bytes +leave only through a human-approved proposal (#17038), so nothing here frees or purges anything; +once that removal marks the queue row processed the file stops counting. + +``uploaded_by`` NULL is its own owner: one shared bucket for files stored with no named owner, held to +the same quota. Agent-created files are charged to the agent's name for the same reason (#20217). +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from typing import Dict + +from fastapi import HTTPException + +from autobot_shared.env_registry import env + +#: Bytes one owner may keep (``AUTOBOT_CONVERSATION_FILE_USER_QUOTA_BYTES``). +USER_QUOTA_BYTES: int = int(env("AUTOBOT_CONVERSATION_FILE_USER_QUOTA_BYTES")) + +#: Stable error codes the frontend maps to translation keys (``utils/conversationFileUpload.ts``). +FILE_TOO_LARGE = "conversation_file_too_large" +QUOTA_EXCEEDED = "conversation_file_quota_exceeded" + +# Bytes still on disk for an owner: live files, and deleted files whose removal has not happened. +# The three statements below embed only this module constant; the owner and sizes are bound parameters (B608). +_HELD = ( + "uploaded_by IS ? AND (is_deleted = 0 OR file_id IN " + "(SELECT file_id FROM file_cleanup_queue WHERE is_processed = 0))" +) +_USAGE_SQL = ( + "SELECT COALESCE(SUM(CASE WHEN is_deleted = 0 THEN file_size END), 0), " # nosec B608 + "COALESCE(SUM(CASE WHEN is_deleted = 1 THEN file_size END), 0) " + f"FROM conversation_files WHERE {_HELD}" +) +_INSERT_SQL = ( + "INSERT INTO conversation_files (file_id, session_id, original_filename, stored_filename, " # nosec B608 + "file_path, file_size, file_hash, mime_type, uploaded_by) " + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ? " + f"WHERE (SELECT COALESCE(SUM(file_size), 0) FROM conversation_files WHERE {_HELD}) + ? <= ?" +) +_RESIZE_SQL = ( + "UPDATE conversation_files SET file_size = ?, file_hash = ? WHERE file_id = ? AND " # nosec B608 + f"(SELECT COALESCE(SUM(file_size), 0) FROM conversation_files WHERE {_HELD} AND file_id != ?) + ? <= ?" +) + + +class UploadRefused(HTTPException): + """HTTP 413 whose ``detail`` is ``{"code", "message", ...figures}``; the code is stable, the message is not.""" + + def __init__(self, code: str, message: str, **figures: int) -> None: + super().__init__(status_code=413, detail={"code": code, "message": message, **figures}) + + +def file_too_large(max_bytes: int) -> UploadRefused: + """The refusal for a file past the per-file size cap.""" + return UploadRefused( + FILE_TOO_LARGE, f"File too large. Maximum size: {max_bytes // (1024 * 1024)}MB", max_bytes=max_bytes + ) + + +def quota_refusal(live: int, pending_removal: int) -> UploadRefused: + """The refusal for an owner without room, naming live bytes and bytes awaiting human-approved removal apart.""" + message = ( + f"Upload quota exceeded: {live} bytes in use and {pending_removal} bytes of deleted files awaiting " + f"human review before removal (of {USER_QUOTA_BYTES} allowed)" + ) + return UploadRefused( + QUOTA_EXCEEDED, + message, + limit_bytes=USER_QUOTA_BYTES, + live_bytes=live, + pending_removal_bytes=pending_removal, + remaining_bytes=max(USER_QUOTA_BYTES - live - pending_removal, 0), + ) + + +async def usage(connection, owner: str | None) -> Dict[str, int]: + """Live bytes and pending-removal bytes held for *owner*, kept apart so the message can be true.""" + async with connection.execute(_USAGE_SQL, (owner,)) as cursor: + live, pending = await cursor.fetchone() + return {"live": live, "pending_removal": pending} + + +async def remaining_bytes(connection, owner: str | None) -> int: + """Bytes *owner* may still store (both kinds counted).""" + held = await usage(connection, owner) + return USER_QUOTA_BYTES - held["live"] - held["pending_removal"] + + +async def _refuse(connection, owner: str | None) -> UploadRefused: + """The quota refusal carrying *owner*'s current figures.""" + held = await usage(connection, owner) + return quota_refusal(held["live"], held["pending_removal"]) + + +async def insert_within_quota(connection, record: tuple, owner: str | None, size: int) -> None: + """Insert the ``conversation_files`` row only if *owner* stays within quota, in ONE statement. + + The sum and the insert are a single SQLite statement, so concurrent writers (other workers, other + manager instances) cannot each pass a read-then-write check and overshoot; the loser is refused. + """ + cursor = await connection.execute(_INSERT_SQL, (*record, owner, size, USER_QUOTA_BYTES)) + if cursor.rowcount == 0: + raise await _refuse(connection, owner) + + +async def resize_within_quota(connection, row, size: int, file_hash: str) -> None: + """Set an existing file's size only if its owner stays within quota (a content update can grow it).""" + owner, file_id = row["uploaded_by"], row["file_id"] + cursor = await connection.execute(_RESIZE_SQL, (size, file_hash, file_id, owner, file_id, size, USER_QUOTA_BYTES)) + if cursor.rowcount == 0: + raise await _refuse(connection, owner) + + +async def abandon(connection, stored_path: Path, remove_bytes: bool = True) -> None: + """Roll back a store that failed or was refused, and remove the bytes this call wrote. + + ``remove_bytes`` is False for a deduplicated add: its path is derived from the hash and may be the + existing file's, which this call did not store. + """ + await connection.rollback() + if remove_bytes and await asyncio.to_thread(stored_path.exists): + await asyncio.to_thread(stored_path.unlink) diff --git a/autobot-backend/conversation_file_quota_store_20217_test.py b/autobot-backend/conversation_file_quota_store_20217_test.py new file mode 100644 index 0000000000..ec850ed26b --- /dev/null +++ b/autobot-backend/conversation_file_quota_store_20217_test.py @@ -0,0 +1,156 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""The quota is enforced where bytes are recorded, so every way into the store is covered (#20217). + +Real ``ConversationFileManager`` on real SQLite. Covers: each entry path (upload, create, agent-create, +copy, content update, the manager itself), the live / pending-removal split in the refusal, a removal that +frees space only once its queue row is processed, a conditional insert under concurrent writers, the +NULL-owner bucket, and the ``uploaded_by`` index. +""" + +from __future__ import annotations + +import asyncio +import sqlite3 +from unittest.mock import AsyncMock + +import pytest +from redis.exceptions import ConnectionError as RedisConnectionError + +import conversation_file_quota as quota +from api.conversation_files_owner_upload_20133_test import world # noqa: F401 -- fixture +from api.conversation_files_real_manager_20225_test import ( # noqa: F401 + _SESSION, + _as_admin, + _rows, + _seed, + _upload, + real, +) +from conversation_file_manager import ConversationFileManager + +_API = "/api/conversation/" + _SESSION + + +@pytest.fixture +def small(real, monkeypatch): # noqa: F811 + """A 20-byte quota; ``root`` (the admin the routes run as) and ``alice`` each start empty.""" + monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 20) + return real + + +def _code(response) -> str: + assert response.status_code == 413, response.text + return response.json()["detail"]["code"] + + +def test_create_is_refused_past_the_quota_and_stores_nothing(small): + admin = _as_admin(small) + body = {"filename": "a.txt", "content": "x" * 21} + assert _code(admin.client.post(f"{_API}/files/create", json=body)) == quota.QUOTA_EXCEEDED + assert _rows(small, "SELECT COUNT(*) FROM conversation_files") == [(0,)] + assert [p for p in (small.tmp / "storage").rglob("*") if p.is_file()] == [] + assert admin.client.post(f"{_API}/files/create", json={"filename": "a.txt", "content": "x" * 20}).status_code == 200 + + +def test_agent_create_is_refused_past_the_quota_for_the_agent_that_owns_it(small): + admin = _as_admin(small) + body = {"filename": "g.txt", "content": "y" * 15, "agent_name": "scribe"} + assert admin.client.post(f"{_API}/generate", json=body).status_code == 200 + body["filename"] = "g2.txt" + body["content"] = "z" * 6 + assert _code(admin.client.post(f"{_API}/generate", json=body)) == quota.QUOTA_EXCEEDED + assert _rows(small, "SELECT uploaded_by, SUM(file_size) FROM conversation_files") == [("scribe", 15)] + + +def test_a_copy_is_a_reference_that_stores_no_bytes_so_it_cannot_pass_the_quota(small): + file_id = _seed(small, body=b"c" * 20) # alice is exactly at the quota + copied = _as_admin(small).client.post(f"{_API}/files/{file_id}/copy", json={"new_filename": "c2.txt"}) + assert copied.status_code == 200, copied.text + assert _rows(small, "SELECT COUNT(*), SUM(file_size) FROM conversation_files") == [(1, 20)] + + +def test_a_content_update_cannot_grow_a_file_past_the_quota(small): + file_id = _seed(small, body=b"u" * 10) + admin = _as_admin(small) + assert ( + _code(admin.client.put(f"{_API}/files/{file_id}/content", json={"content": "v" * 21})) == quota.QUOTA_EXCEEDED + ) + assert _rows(small, "SELECT file_size FROM conversation_files") == [(10,)] + assert [p.read_bytes() for p in (small.tmp / "storage").rglob("*") if p.is_file()] == [b"u" * 10] + assert admin.client.put(f"{_API}/files/{file_id}/content", json={"content": "v" * 20}).status_code == 200 + assert _rows(small, "SELECT file_size FROM conversation_files") == [(20,)] + + +def test_the_manager_itself_refuses_so_no_caller_can_skip_the_quota(small): + asyncio.run(small.real.add_file(_SESSION, b"m" * 20, "m.txt", uploaded_by="dora")) + with pytest.raises(quota.UploadRefused) as caught: + asyncio.run(small.real.add_file(_SESSION, b"n" * 1, "n.txt", uploaded_by="dora")) + assert caught.value.detail["code"] == quota.QUOTA_EXCEEDED and caught.value.detail["live_bytes"] == 20 + + +def test_a_deduplicated_reference_stores_no_bytes_and_needs_no_room(small): + asyncio.run(small.real.add_file(_SESSION, b"d" * 20, "d.txt", uploaded_by="dora")) + again = asyncio.run(small.real.add_file(_SESSION, b"d" * 20, "d-again.txt", uploaded_by="dora")) + assert again["deduplicated"] is True + + +def test_the_refusal_says_how_much_is_live_and_how_much_awaits_human_review(small): + assert _upload(small, body=b"l" * 8).status_code == 200 + gone = _upload(small, name="p.txt", body=b"p" * 12).json()["file_info"] + asyncio.run(small.real.delete_file(_SESSION, gone["file_id"])) + response = _upload(small, name="q.txt", body=b"q" * 5) + assert _code(response) == quota.QUOTA_EXCEEDED + detail = response.json()["detail"] + assert (detail["live_bytes"], detail["pending_removal_bytes"], detail["remaining_bytes"]) == (8, 12, 0) + assert "awaiting human review" in detail["message"] + + +def test_space_returns_only_once_a_removal_marks_the_queue_row_processed(small): + info = _upload(small, body=b"x" * 20).json()["file_info"] + asyncio.run(small.real.delete_file(_SESSION, info["file_id"])) + assert _code(_upload(small, name="two.txt", body=b"y" * 5)) == quota.QUOTA_EXCEEDED + assert asyncio.run(small.real.remaining_upload_quota("alice")) == 0 # nothing freed by the delete alone + conn = sqlite3.connect(small.db) + conn.execute("UPDATE file_cleanup_queue SET is_processed = 1 WHERE file_id = ?", (info["file_id"],)) + conn.commit() + conn.close() # what an approved removal does (#20234); the test purges nothing itself + assert asyncio.run(small.real.remaining_upload_quota("alice")) == 20 + assert _upload(small, name="two.txt", body=b"y" * 5).status_code == 200 + + +def test_the_ownerless_bucket_is_one_shared_owner_held_to_the_same_quota(small): + asyncio.run(small.real.add_file(_SESSION, b"a" * 15, "a.txt", uploaded_by=None)) + with pytest.raises(quota.UploadRefused): + asyncio.run(small.real.add_file(_SESSION, b"b" * 6, "b.txt", uploaded_by=None)) + assert asyncio.run(small.real.remaining_upload_quota(None)) == 5 + assert asyncio.run(small.real.remaining_upload_quota("alice")) == 20 # a named owner is unaffected + + +def test_concurrent_writers_cannot_overshoot_the_quota(real, monkeypatch, tmp_path): # noqa: F811 + """Eight independent managers (their own locks) race on one database file: only two 10-byte files fit in 25.""" + monkeypatch.setattr(quota, "USER_QUOTA_BYTES", 25) + managers = [ + ConversationFileManager(storage_dir=tmp_path / "storage", db_path=tmp_path / "files.db") for _ in range(8) + ] + for manager in managers: + monkeypatch.setattr(manager, "_get_redis_sessions", AsyncMock(side_effect=RedisConnectionError("down"))) + + async def race(): + jobs = [ + m.add_file(_SESSION, bytes([65 + i]) * 10, f"f{i}.txt", uploaded_by="erin") for i, m in enumerate(managers) + ] + return await asyncio.gather(*jobs, return_exceptions=True) + + results = asyncio.run(race()) + assert sum(isinstance(r, dict) for r in results) == 2, results + assert all(isinstance(r, quota.UploadRefused) for r in results if not isinstance(r, dict)), results + assert _rows(real, "SELECT COUNT(*), SUM(file_size) FROM conversation_files") == [(2, 20)] + assert len([p for p in (tmp_path / "storage").rglob("*") if p.is_file()]) == 2 # refused bytes are not left behind + + +def test_uploaded_by_is_indexed(real): # noqa: F811 + names = {r[0] for r in _rows(real, "SELECT name FROM sqlite_master WHERE type = 'index'")} + assert "idx_conversation_files_uploaded_by" in names + plan = _rows(real, "EXPLAIN QUERY PLAN SELECT SUM(file_size) FROM conversation_files WHERE uploaded_by IS 'x'") + assert any("idx_conversation_files_uploaded_by" in str(row) for row in plan), plan diff --git a/autobot-backend/conversation_file_route_api.py b/autobot-backend/conversation_file_route_api.py index 7c42a4d482..e766b4fbe3 100644 --- a/autobot-backend/conversation_file_route_api.py +++ b/autobot-backend/conversation_file_route_api.py @@ -14,6 +14,7 @@ from typing import Any, Dict, List from autobot_shared.logging_manager import get_logger +from conversation_file_quota import UploadRefused, quota_refusal, remaining_bytes, usage logger = get_logger(__name__) @@ -47,6 +48,23 @@ async def upload_file( extension = filename.rsplit(".", 1)[-1].lower() if "." in filename else None return {**stored, "filename": filename, "size": stored["file_size"], "extension": extension} + async def remaining_upload_quota(self, user_id: str | None) -> int: + """Bytes *user_id* may still store; deleted files awaiting human-approved removal count (#20217).""" + connection = await self._get_async_db_connection() + try: + return await remaining_bytes(connection, user_id) + finally: + await connection.close() + + async def upload_quota_refusal(self, user_id: str | None) -> UploadRefused: + """The 413 for *user_id* out of room: live bytes and bytes awaiting human-approved removal, apart.""" + connection = await self._get_async_db_connection() + try: + held = await usage(connection, user_id) + finally: + await connection.close() + return quota_refusal(held["live"], held["pending_removal"]) + async def get_file_info(self, session_id: str, file_id: str) -> Dict[str, Any] | None: """The live file ``file_id`` of ``session_id`` as a ``ConversationFileInfo`` dict, else ``None``.""" connection = await self._get_async_db_connection() @@ -96,6 +114,9 @@ async def delete_file(self, session_id: str, file_id: str, user_id: str | None = await connection.close() await self._invalidate_session_cache(session_id) await self._log_access(file_id, "delete", user_id, {"session_id": session_id}) + from services.conversation_file_cleanup_proposals import propose_due_cleanups_logged + + await propose_due_cleanups_logged(self) # proposes only; removal waits for a human (#20234) return True async def transfer_files( diff --git a/autobot-backend/conversation_file_size_cap_20217_test.py b/autobot-backend/conversation_file_size_cap_20217_test.py new file mode 100644 index 0000000000..cae2510100 --- /dev/null +++ b/autobot-backend/conversation_file_size_cap_20217_test.py @@ -0,0 +1,57 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +"""The per-file size cap answers with the same coded 413 on every route, and a failed dedupe keeps its bytes (#20217). + +Real ``ConversationFileManager`` on real SQLite, reusing the fixtures of the quota store tests. +""" + +from __future__ import annotations + +import asyncio +from unittest.mock import AsyncMock + +import pytest + +import conversation_file_quota as quota +from api.conversation_files_owner_upload_20133_test import world # noqa: F401 -- fixture +from api.conversation_files_real_manager_20225_test import ( # noqa: F401 + _SESSION, + _as_admin, + _rows, + real, +) +from conversation_file_manager import ConversationFileManager + +_API = "/api/conversation/" + _SESSION + + +def _code(response) -> str: + assert response.status_code == 413, response.text + return response.json()["detail"]["code"] + + +def test_create_and_generate_past_the_size_cap_answer_413_with_the_stable_code(real, monkeypatch): # noqa: F811 + monkeypatch.setattr(ConversationFileManager, "MAX_FILE_SIZE", 10) + admin = _as_admin(real) + created = admin.client.post(f"{_API}/files/create", json={"filename": "big.txt", "content": "x" * 11}) + generated = admin.client.post(f"{_API}/generate", json={"filename": "big2.txt", "content": "y" * 11}) + assert _code(created) == quota.FILE_TOO_LARGE + assert _code(generated) == quota.FILE_TOO_LARGE + assert created.json()["detail"]["max_bytes"] == 10 + assert _rows(real, "SELECT COUNT(*) FROM conversation_files") == [(0,)] + + +def test_the_manager_raises_the_coded_refusal_not_a_plain_value_error(real, monkeypatch): # noqa: F811 + monkeypatch.setattr(ConversationFileManager, "MAX_FILE_SIZE", 4) + with pytest.raises(quota.UploadRefused) as caught: + asyncio.run(real.real.add_file(_SESSION, b"12345", "f.txt", uploaded_by="dora")) + assert caught.value.status_code == 413 and caught.value.detail["code"] == quota.FILE_TOO_LARGE + + +def test_a_failed_deduplicated_add_leaves_the_existing_files_bytes_in_place(real, monkeypatch): # noqa: F811 + asyncio.run(real.real.add_file(_SESSION, b"k" * 5, "k.txt", uploaded_by="dora")) + stored = [p for p in (real.tmp / "storage").rglob("*") if p.is_file()] + monkeypatch.setattr(real.real, "_handle_deduplicated_file", AsyncMock(side_effect=RuntimeError("db down"))) + with pytest.raises(RuntimeError): + asyncio.run(real.real.add_file(_SESSION, b"k" * 5, "k.txt", uploaded_by="dora")) + assert stored and all(p.exists() for p in stored) diff --git a/autobot-backend/database/migrations/001_create_conversation_files.py b/autobot-backend/database/migrations/001_create_conversation_files.py index d72c72ab5f..bd246fec5d 100644 --- a/autobot-backend/database/migrations/001_create_conversation_files.py +++ b/autobot-backend/database/migrations/001_create_conversation_files.py @@ -267,6 +267,7 @@ def _get_expected_schema_objects(self): "idx_conversation_files_session", "idx_conversation_files_hash", "idx_conversation_files_uploaded_at", + "idx_conversation_files_uploaded_by", "idx_file_metadata_file_id", "idx_session_associations_session", "idx_session_associations_file", diff --git a/autobot-backend/database/schemas/conversation_files_schema.sql b/autobot-backend/database/schemas/conversation_files_schema.sql index 37403058a3..f34fa59b54 100644 --- a/autobot-backend/database/schemas/conversation_files_schema.sql +++ b/autobot-backend/database/schemas/conversation_files_schema.sql @@ -112,6 +112,11 @@ CREATE INDEX IF NOT EXISTS idx_conversation_files_hash CREATE INDEX IF NOT EXISTS idx_conversation_files_uploaded_at ON conversation_files(uploaded_at DESC); +-- Per-owner quota sum (conversation_file_quota.py, #20217): every upload sums one owner's bytes. +-- IF NOT EXISTS: an existing install gains the index the next time the schema is applied; no row changes. +CREATE INDEX IF NOT EXISTS idx_conversation_files_uploaded_by + ON conversation_files(uploaded_by, is_deleted); + CREATE INDEX IF NOT EXISTS idx_file_metadata_file_id ON file_metadata(file_id); diff --git a/autobot-backend/initialization/router_registry/core_routers.py b/autobot-backend/initialization/router_registry/core_routers.py index d175252fd4..40f1164c56 100644 --- a/autobot-backend/initialization/router_registry/core_routers.py +++ b/autobot-backend/initialization/router_registry/core_routers.py @@ -42,6 +42,7 @@ from api.collaboration import router as collaboration_router from api.collaboration_events import router as collaboration_events_router # #16460 from api.config_revisions import router as config_revisions_router # #1404 +from api.conversation_file_cleanup_admin import router as conversation_file_cleanup_router # #20234 from api.coordination import router as coordination_router # #15949 from api.coordination_issue_claims import router as coordination_issue_claims_router # #18811 from api.coordination_issue_claims_credential import router as issue_claims_credential_router # #18811 @@ -169,6 +170,7 @@ def _get_system_routers() -> list: (users_router, "", ["users"], "users"), (mobile_devices_router, "/devices", ["devices", "integrations"], "mobile_devices"), # GH#4463 (data_storage_router, "", ["data-storage"], "data_storage"), + (conversation_file_cleanup_router, "/conversation-files", ["conversation-files"], "conversation_file_cleanup"), (prompts_router, "/prompts", ["prompts"], "prompts"), (frontend_config_router, "", ["frontend-config"], "frontend_config"), ] diff --git a/autobot-backend/migrations/versions/20261101_110_approvals_pending_file_cleanup_unique.py b/autobot-backend/migrations/versions/20261101_110_approvals_pending_file_cleanup_unique.py new file mode 100644 index 0000000000..3bec9d8309 --- /dev/null +++ b/autobot-backend/migrations/versions/20261101_110_approvals_pending_file_cleanup_unique.py @@ -0,0 +1,65 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""One PENDING conversation-file-cleanup proposal per file, enforced by the database (#20234). + +A delete and a startup sweep on different workers can both read "no pending proposal" and both +insert one. A partial unique index is the only thing that makes the second insert fail; the +proposer maps that failure to "already proposed". + +``NO DATA REWRITE``: this adds an index only. No row or column is touched, and the index is partial, +so it constrains nothing except pending rows of this one requester and action (the rows the cleanup +proposer creates; none exist before #20234). If a dev install already holds duplicate pending rows +the index cannot be built over them, and the migration FAILS with a message naming the files. It does +not skip (the index is the only thing that closes the race, and a skipped one is an invariant nobody +sees missing) and it does not delete (no agent cleans data on its own, #17038). The fix is a person's: +reject the extra pending proposals in the Approvals inbox, then run the upgrade again. Only dev installs +can hold duplicates, since the proposer that creates these rows ships in the same change. +""" + +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +from migrations.guards import has_index, has_table + +revision: str = "20261101_110" +down_revision: Union[str, None] = "20261101_109" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + +_TABLE = "approvals" +_INDEX = "uq_approvals_pending_file_cleanup" +_WHERE = ( + "status = 'pending' AND requested_by_agent = 'conversation-file-cleanup' " + "AND context ->> 'action' = 'conversation_file_cleanup'" +) +_DUPLICATES = ( + "SELECT context ->> 'file_id' AS file_id, count(*) AS pending FROM approvals " + "WHERE status = 'pending' AND requested_by_agent = 'conversation-file-cleanup' " + "AND context ->> 'action' = 'conversation_file_cleanup' " + "GROUP BY context ->> 'file_id' HAVING count(*) > 1 ORDER BY file_id LIMIT 20" +) + + +def upgrade() -> None: + bind = op.get_bind() + if bind.dialect.name != "postgresql" or not has_table(_TABLE) or has_index(_TABLE, _INDEX): + return + duplicates = bind.execute(sa.text(_DUPLICATES)).all() + if duplicates: + listed = ", ".join(f"{row.file_id} ({row.pending} pending)" for row in duplicates) + raise RuntimeError( + f"#20234: cannot create {_INDEX}: these conversation files hold several pending cleanup proposals " + f"(first 20): {listed}. Nothing was changed. Reject the extra pending proposals in the Approvals " + "inbox so each file keeps one, then run the upgrade again." + ) + op.create_index(_INDEX, _TABLE, [sa.text("(context ->> 'file_id')")], unique=True, postgresql_where=sa.text(_WHERE)) + + +def downgrade() -> None: + bind = op.get_bind() + if bind.dialect.name == "postgresql" and has_index(_TABLE, _INDEX): + op.drop_index(_INDEX, table_name=_TABLE) diff --git a/autobot-backend/models/approval.py b/autobot-backend/models/approval.py index 4529c78f92..6516d96d49 100644 --- a/autobot-backend/models/approval.py +++ b/autobot-backend/models/approval.py @@ -11,7 +11,7 @@ import uuid from enum import Enum -from sqlalchemy import Column, DateTime, ForeignKey, Index, String, Text +from sqlalchemy import Column, DateTime, ForeignKey, Index, String, Text, text from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import relationship from sqlalchemy.types import Uuid @@ -223,3 +223,21 @@ class TaskApprovalLink(Base): def __repr__(self) -> str: return f"" + + +#: One PENDING conversation-file-cleanup proposal per file, enforced by the database (#20234). +#: Two workers (a delete and a startup sweep) can both pass an application-level "already proposed" +#: read; only a unique index makes the second insert fail. Partial, so it constrains nothing else in +#: this table and never an approved, rejected or expired row. PostgreSQL only -- ``ddl_if`` keeps +#: SQLite test stores, which lack the partial-index predicate on a JSON expression, unaffected. +PENDING_FILE_CLEANUP_INDEX = "uq_approvals_pending_file_cleanup" +PENDING_FILE_CLEANUP_WHERE = ( + "status = 'pending' AND requested_by_agent = 'conversation-file-cleanup' " + "AND context ->> 'action' = 'conversation_file_cleanup'" +) +Index( + PENDING_FILE_CLEANUP_INDEX, + Approval.context["file_id"].astext, + unique=True, + postgresql_where=text(PENDING_FILE_CLEANUP_WHERE), +).ddl_if(dialect="postgresql") diff --git a/autobot-backend/services/conversation_file_cleanup_action.py b/autobot-backend/services/conversation_file_cleanup_action.py new file mode 100644 index 0000000000..0e53d50454 --- /dev/null +++ b/autobot-backend/services/conversation_file_cleanup_action.py @@ -0,0 +1,69 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Executes an APPROVED proposal to remove one deleted conversation file's bytes (#20234, #17038). + +The proposal (``services/conversation_file_cleanup_proposals.py``) is an ordinary approval +gate whose context names this action and the file id -- never a path:: + + {"action": "conversation_file_cleanup", "file_id": "...", "session_id": "..."} + +Approving it runs :func:`execute_conversation_file_cleanup` through the generic +``services.approval_execution`` registry. The path is read from the file record and +re-validated against the store at removal time. The outcome lands as a comment on the +approval and as a durable audit entry (#17038 rule 3). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from models.approval import ApprovalComment +from services.approval_execution import register_post_approval_action +from services.audit_logger import audit_log + +if TYPE_CHECKING: + from sqlalchemy.ext.asyncio import AsyncSession + + from models.approval import Approval + +#: The ``context["action"]`` value a proposal names to route here. +ACTION = "conversation_file_cleanup" + +#: The production module that PROPOSES this action (#17315). +PROPOSED_BY = "services.conversation_file_cleanup_proposals" + + +async def execute_conversation_file_cleanup(approval: "Approval", session: "AsyncSession") -> None: + """Remove the bytes an approved gate named, and record what happened.""" + from conversation_file_cleanup import remove_approved_file + from conversation_file_manager import get_conversation_file_manager + + file_id = (approval.context or {}).get("file_id") + if not file_id: + # #17141: raise, so the dispatcher records the failure durably. + raise ValueError(f"approval {approval.id} is missing file_id in its action context") + + result = await remove_approved_file(await get_conversation_file_manager(), file_id) + outcome = "removed" if result["removed"] else "did NOT remove" + body = f"Conversation file cleanup {outcome} the bytes of file {file_id} ({result['size']} bytes)" + if result["reason"]: + body += f": {result['reason']}" + session.add(ApprovalComment(approval_id=approval.id, author="system", author_type="system", body=body)) + await session.commit() + await audit_log( + "conversation_file.cleanup", + result="success" if result["removed"] else "failed", + user_id=approval.decided_by_user, + resource=f"conversation_file:{file_id}", + details={"approval_id": str(approval.id), "size": result["size"], "reason": result["reason"]}, + ) + + +def register_conversation_file_cleanup_action() -> None: + """Idempotent. Server-only: the file id is the proposer's to name, never a caller's.""" + register_post_approval_action(ACTION, execute_conversation_file_cleanup, proposed_by=PROPOSED_BY, server_only=True) + + +__all__ = ["ACTION", "PROPOSED_BY", "execute_conversation_file_cleanup", "register_conversation_file_cleanup_action"] diff --git a/autobot-backend/services/conversation_file_cleanup_proposals.py b/autobot-backend/services/conversation_file_cleanup_proposals.py new file mode 100644 index 0000000000..d9350f8ea3 --- /dev/null +++ b/autobot-backend/services/conversation_file_cleanup_proposals.py @@ -0,0 +1,108 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Turns due ``file_cleanup_queue`` entries into approval-gate proposals (#20234, #17038). + +A proposal only asks. It deletes nothing, cannot approve itself, and never expires into +approval; a proposal nobody reviews stays pending in the Approvals inbox. A file with a +pending, rejected or revision-requested proposal is not proposed again: a denial is a person's +decision and stays one. An approved proposal whose removal failed, an expired one and a +withdrawn one leave the queue row unprocessed (the queue, not the proposal, records that the +bytes are gone), so the next sweep proposes that file again, until the removal has been refused +``AUTOBOT_CONVERSATION_FILE_CLEANUP_MAX_ATTEMPTS`` times (``conversation_file_cleanup.py``). + +Two workers can both read "not proposed yet"; the partial unique index +``uq_approvals_pending_file_cleanup`` (migration 20261101_110) lets exactly one insert win, and the +loser's ``IntegrityError`` is read as "already proposed". +""" + +from __future__ import annotations + +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError + +from autobot_shared.logging_manager import get_logger +from models.approval import ApprovalStatus +from services.conversation_file_cleanup_action import ACTION, register_conversation_file_cleanup_action + +logger = get_logger(__name__) + +REQUESTED_BY = "conversation-file-cleanup" + +# Registered at import, like api/legacy_transcript_disposal.py: the handler must be in +# place before any approve() can reach a proposal this module raised. +register_conversation_file_cleanup_action() + + +#: Proposal states that keep a file from being proposed again. +_BLOCKING = (ApprovalStatus.PENDING.value, ApprovalStatus.REJECTED.value, ApprovalStatus.REVISION_REQUESTED.value) + + +async def _already_proposed(db) -> set[str]: + """File ids with a proposal that must not be repeated. Plain columns only, any SQL dialect.""" + from models.approval import Approval, ApprovalType + + query = select(Approval.context).where( + Approval.approval_type == ApprovalType.DESTRUCTIVE_ACTION.value, + Approval.requested_by_agent == REQUESTED_BY, + Approval.status.in_(_BLOCKING), + ) + contexts = (await db.execute(query)).scalars().all() + return {str(c["file_id"]) for c in contexts if c and c.get("action") == ACTION and c.get("file_id")} + + +async def _propose_one(db, service, item: dict): + """Create the proposal, or ``None`` when another worker's pending one won the unique index.""" + from models.approval import ApprovalType + + try: + return await service.create_approval( + title=f"Remove deleted conversation file: {item['original_filename']}", + approval_type=ApprovalType.DESTRUCTIVE_ACTION.value, + description=f"The file was deleted from its conversation; its {item['file_size']} bytes are still on disk.", + requested_by_agent=REQUESTED_BY, + context={"action": ACTION, "file_id": item["file_id"], "session_id": item["session_id"]}, + ) + except IntegrityError: + await db.rollback() + logger.info("Cleanup proposal for file %s already pending (raised concurrently)", item["file_id"]) + return None + + +async def propose_cleanups_for(db, candidates: list[dict]) -> list[str]: + """Create one PENDING proposal per candidate with no pending or denied proposal; returns the new ids.""" + from services.approval_gate_service import ApprovalGateService + + seen = await _already_proposed(db) + service = ApprovalGateService(db) + created = [] + for item in candidates: + if item["file_id"] in seen: + continue + approval = await _propose_one(db, service, item) + if approval is not None: + created.append(str(approval.id)) + return created + + +async def propose_due_cleanups(manager) -> list[str]: + """Sweep the queue and raise proposals. Never removes anything.""" + from conversation_file_cleanup import list_cleanup_candidates + from user_management.database import get_async_session_factory + + candidates = await list_cleanup_candidates(manager) + if not candidates: + return [] + async with get_async_session_factory()() as db: + return await propose_cleanups_for(db, candidates) + + +async def propose_due_cleanups_logged(manager) -> None: + """Trigger for callers that must not fail on it: a failure is logged at error, the files stay.""" + try: + created = await propose_due_cleanups(manager) + if created: + logger.info("Raised %d conversation file cleanup proposal(s) for review", len(created)) + except Exception as exc: + logger.error("Could not raise conversation file cleanup proposals (files kept): %s", exc) diff --git a/autobot-frontend/src/components/llc/StuckFileCleanupPanel.vue b/autobot-frontend/src/components/llc/StuckFileCleanupPanel.vue new file mode 100644 index 0000000000..49b2c47c9b --- /dev/null +++ b/autobot-frontend/src/components/llc/StuckFileCleanupPanel.vue @@ -0,0 +1,142 @@ + + + + + + diff --git a/autobot-frontend/src/components/llc/__tests__/StuckFileCleanupPanel.test.ts b/autobot-frontend/src/components/llc/__tests__/StuckFileCleanupPanel.test.ts new file mode 100644 index 0000000000..9405c50c10 --- /dev/null +++ b/autobot-frontend/src/components/llc/__tests__/StuckFileCleanupPanel.test.ts @@ -0,0 +1,94 @@ +// Copyright 2025-2026 mrveiss +// SPDX-License-Identifier: Apache-2.0 +// #20234: a person can see, approve and reject a pending removal proposal, and reset a stuck file. + +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { mount, flushPromises } from '@vue/test-utils' +import { createI18n } from 'vue-i18n' +import { HttpError } from '@autobot/ui' +import en from '@/i18n/locales/en.json' + +const get = vi.fn() +const post = vi.fn() + +vi.mock('@/plugins/api', () => ({ useApiClient: () => ({ get, post }) })) +vi.mock('@/composables/useNotificationBus', () => ({ useNotificationBus: () => ({ showToast: vi.fn() }) })) +vi.mock('@/utils/debugUtils', () => ({ + createLogger: () => ({ warn: vi.fn(), error: vi.fn(), info: vi.fn(), debug: vi.fn() }), +})) + +import Panel from '../StuckFileCleanupPanel.vue' + +const i18n = createI18n({ legacy: false, locale: 'en', fallbackLocale: 'en', messages: { en } }) +const STATUS = { + stuck_cleanup_files: 1, + stuck_cleanup_bytes: 5, + stuck_cleanup: [{ file_id: 'f1', file_size: 5, failed_attempts: 3, last_reason: 'outside' }], +} +const PROPOSALS = [ + { id: 'a1', title: 'Remove deleted conversation file: a.txt', description: 'd', approval_type: 'destructive_action' }, + { id: 'a2', title: 'Something else', description: 'd', approval_type: 'tool_use' }, +] + +async function mountPanel() { + const wrapper = mount(Panel, { global: { plugins: [i18n] } }) + await flushPromises() + return wrapper +} + +beforeEach(() => { + get.mockReset() + post.mockReset() + post.mockResolvedValue({}) + get.mockImplementation((url: string) => + Promise.resolve(url.includes('/approval-gates/pending') ? PROPOSALS : STATUS) + ) +}) + +describe('StuckFileCleanupPanel (#20234)', () => { + it('lists only destructive-action proposals and approves one through the existing route', async () => { + const wrapper = await mountPanel() + const rows = wrapper.findAll('[data-testid="removal-proposals"] li') + expect(rows).toHaveLength(1) + await rows[0].findAll('button')[0].trigger('click') + expect(post).toHaveBeenCalledWith('/api/approval-gates/a1/approve', {}) + }) + + it('rejects through the existing route', async () => { + const wrapper = await mountPanel() + await wrapper.findAll('[data-testid="removal-proposals"] li')[0].findAll('button')[1].trigger('click') + expect(post).toHaveBeenCalledWith('/api/approval-gates/a1/reject', {}) + }) + + it('resets a stuck file', async () => { + const wrapper = await mountPanel() + await wrapper.find('[data-testid="stuck-files"] button').trigger('click') + expect(post).toHaveBeenCalledWith('/api/conversation-files/cleanup/f1/reset', {}) + }) + + it.each([401, 403])('hides the panel and never asks for proposals on HTTP %i', async (status) => { + get.mockRejectedValue(new HttpError(status, 'refused')) + const wrapper = await mountPanel() + expect(wrapper.html()).not.toContain('removal-proposals') + expect(wrapper.find('[data-testid="load-error"]').exists()).toBe(false) + expect(get).toHaveBeenCalledTimes(1) + }) + + it('shows an error alert, not an empty panel, when the status call fails with a server error', async () => { + get.mockRejectedValueOnce(new HttpError(500, 'boom')) + const wrapper = await mountPanel() + const alert = wrapper.find('[data-testid="load-error"]') + expect(alert.exists()).toBe(true) + expect(alert.text()).toContain(en.llc.approvals.stuckCleanup.loadError) + expect(wrapper.find('[data-testid="stuck-files"]').exists()).toBe(false) + }) + + it('retries a failed load and shows the data once it succeeds', async () => { + get.mockRejectedValueOnce(new HttpError(500, 'boom')) + const wrapper = await mountPanel() + await wrapper.find('[data-testid="load-error"] button').trigger('click') + await flushPromises() + expect(wrapper.find('[data-testid="load-error"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="stuck-files"]').exists()).toBe(true) + }) +}) diff --git a/autobot-frontend/src/composables/__tests__/useConversationFiles.createRefusal.spec.ts b/autobot-frontend/src/composables/__tests__/useConversationFiles.createRefusal.spec.ts new file mode 100644 index 0000000000..d4dad22bc5 --- /dev/null +++ b/autobot-frontend/src/composables/__tests__/useConversationFiles.createRefusal.spec.ts @@ -0,0 +1,55 @@ +// Copyright 2025-2026 mrveiss +// SPDX-License-Identifier: Apache-2.0 +// #20217: a 413 on /files/create carries a structured `detail`; error.value must be translated text, never an object. +import { describe, it, expect, vi } from 'vitest' + +const { post } = vi.hoisted(() => ({ post: vi.fn() })) + +vi.mock('@/plugins/api', () => ({ useApiClient: () => ({ post, get: vi.fn() }) })) +vi.mock('@/i18n', () => ({ + default: { + global: { t: (key: string, params: Record = {}) => `${key}|${JSON.stringify(params)}` }, + }, +})) + +import { useConversationFiles } from '@/composables/useConversationFiles' +import { extractApiErrorMessage } from '@/utils/errorExtract' + +const tooLarge = { code: 'conversation_file_too_large', message: 'File too large. Maximum size: 50MB', max_bytes: 52428800 } + +describe('createFile refusal', () => { + it('maps a client HttpError 413 code to the translated key with its figures', async () => { + post.mockRejectedValueOnce(Object.assign(new Error('HTTP 413'), { status: 413, details: { detail: tooLarge } })) + const files = useConversationFiles('s1') + expect(await files.createFile('a.txt', 'x')).toBe(false) + expect(files.error.value).toBe('chat.input.uploadError.fileTooLarge|{"maxMb":50,"limitMb":0,"liveMb":0,"pendingMb":0,"remainingMb":0}') + }) + + it('maps an axios-shaped 413 quota code too, and never stores an object', async () => { + const detail = { code: 'conversation_file_quota_exceeded', message: 'm', limit_bytes: 1048576, live_bytes: 1048576 } + post.mockRejectedValueOnce({ response: { status: 413, data: { detail } } }) + const files = useConversationFiles('s1') + await files.createFile('a.txt', 'x') + expect(typeof files.error.value).toBe('string') + expect(files.error.value).toContain('chat.input.uploadError.quotaExceeded') + }) + + it('falls back to the structured detail message for an unrecognised code', async () => { + post.mockRejectedValueOnce({ response: { status: 400, data: { detail: { code: 'other', message: 'Nope' } } } }) + const files = useConversationFiles('s1') + await files.createFile('a.txt', 'x') + expect(files.error.value).toBe('Nope') + }) +}) + +describe('extractApiErrorMessage', () => { + it('returns detail.message when detail is an object, and a string detail unchanged', () => { + expect(extractApiErrorMessage({ response: { data: { detail: tooLarge } } }, 'fb')).toBe(tooLarge.message) + expect(extractApiErrorMessage({ response: { data: { detail: 'plain' } } }, 'fb')).toBe('plain') + }) + + it('skips an object detail with no message and uses data.message, then the fallback', () => { + expect(extractApiErrorMessage({ response: { data: { detail: { code: 'x' }, message: 'top' } } }, 'fb')).toBe('top') + expect(extractApiErrorMessage({ response: { data: { detail: { code: 'x' } } } }, 'fb')).toBe('fb') + }) +}) diff --git a/autobot-frontend/src/composables/useConversationFiles.ts b/autobot-frontend/src/composables/useConversationFiles.ts index d1e5b67a41..cd0e9c49f4 100644 --- a/autobot-frontend/src/composables/useConversationFiles.ts +++ b/autobot-frontend/src/composables/useConversationFiles.ts @@ -15,6 +15,8 @@ import { useApiClient } from '@/plugins/api' import { useBatchSelection } from './useBatchSelection' import { createLogger } from '@/utils/debugUtils' import { extractApiErrorMessage } from '@/utils/errorExtract' +import { describeApiRefusal } from '@/utils/conversationFileUpload' +import i18n from '@/i18n' import { getApiBase } from '@/config/ssot-config' import { mapFileList, type BackendFileList } from '@/utils/conversationFileList' import { useLoadingState } from '@/composables/useLoadingState' @@ -355,7 +357,9 @@ export function useConversationFiles(sessionId: string) { error.value = 'Failed to create file' return false } catch (err: unknown) { - error.value = extractApiErrorMessage(err, 'Failed to create file') + error.value = + describeApiRefusal(err, (key, params) => i18n.global.t(key, params ?? {})) ?? + extractApiErrorMessage(err, 'Failed to create file') logger.error('Create file error:', err) return false } diff --git a/autobot-frontend/src/i18n/locales/en.json b/autobot-frontend/src/i18n/locales/en.json index e85e2590e3..78b4132def 100644 --- a/autobot-frontend/src/i18n/locales/en.json +++ b/autobot-frontend/src/i18n/locales/en.json @@ -320,6 +320,9 @@ "invalidResponse": "The server sent an unreadable response", "network": "Network error during upload", "cancelled": "Upload cancelled", + "fileTooLarge": "This file is too large. The maximum size is {maxMb} MB.", + "quotaExceeded": "Your storage limit of {limitMb} MB is reached. {liveMb} MB is in use and {remainingMb} MB is left.", + "quotaExceededPendingRemoval": "Your storage limit of {limitMb} MB is reached. {liveMb} MB is in use, and {pendingMb} MB of deleted files still count until their removal is approved after human review.", "unknown": "Upload failed" }, "filesAttached": "{count} files attached", @@ -8573,6 +8576,21 @@ }, "approvals": { "title": "Approvals Inbox", + "removals": { + "title": "{count} removal proposal(s) await your decision.", + "hint": "Approving permanently removes the named data; rejecting keeps it and the proposal is not repeated.", + "approve": "Approve", + "reject": "Reject", + "decideError": "Could not record the decision." + }, + "stuckCleanup": { + "title": "{count} deleted file(s), {size}, are stuck: removal was refused repeatedly and they are no longer proposed.", + "hint": "The bytes are still on disk. Reset lets a file be proposed again; removal still needs an approval.", + "reset": "Propose again", + "resetDone": "The file will be proposed for removal again.", + "resetError": "Could not reset this file.", + "loadError": "Could not load the file cleanup status. Try again." + }, "tabPending": "Pending", "tabHistory": "History", "selectCompany": "Select a company to view approvals.", diff --git a/autobot-frontend/src/utils/__tests__/conversationFileUpload.spec.ts b/autobot-frontend/src/utils/__tests__/conversationFileUpload.spec.ts index f8c2a77e24..fe8ba23320 100644 --- a/autobot-frontend/src/utils/__tests__/conversationFileUpload.spec.ts +++ b/autobot-frontend/src/utils/__tests__/conversationFileUpload.spec.ts @@ -104,6 +104,91 @@ describe('postConversationUpload (#20133)', () => { }) }) +describe('a 413 refusal keeps its stable reason (#20217)', () => { + const refuse = async (status: number, body: string) => { + const p = postConversationUpload('s1', file(), () => {}) + FakeXhr.last.status = status + FakeXhr.last.responseText = body + FakeXhr.last.listeners.load() + return p.catch((e) => e) + } + beforeEach(() => vi.stubGlobal('XMLHttpRequest', FakeXhr)) + afterEach(() => vi.unstubAllGlobals()) + + it('maps the quota code and carries the server figures', async () => { + const detail = { + code: 'conversation_file_quota_exceeded', + message: 'x', + limit_bytes: 20, + live_bytes: 8, + pending_removal_bytes: 12, + remaining_bytes: 0, + } + const error = await refuse(413, JSON.stringify({ detail })) + expect(error).toMatchObject({ + code: 'quota_exceeded', + status: 413, + refusal: { live_bytes: 8, pending_removal_bytes: 12 }, + }) + }) + + it('maps the file-too-large code', async () => { + const detail = { code: 'conversation_file_too_large', max_bytes: 52428800 } + expect(await refuse(413, JSON.stringify({ detail }))).toMatchObject({ code: 'file_too_large', status: 413 }) + }) + + it('stays a plain http error for an unknown code, a non-413, a string detail or an unreadable body', async () => { + const unknown = JSON.stringify({ detail: { code: 'something_else' } }) + const quotaOn401 = JSON.stringify({ detail: { code: 'conversation_file_quota_exceeded' } }) + expect(await refuse(413, unknown)).toMatchObject({ code: 'http', status: 413 }) + expect(await refuse(401, quotaOn401)).toMatchObject({ code: 'http', status: 401 }) + expect(await refuse(413, JSON.stringify({ detail: 'File too large' }))).toMatchObject({ code: 'http', status: 413 }) + expect(await refuse(413, '')).toMatchObject({ code: 'http', status: 413 }) + }) +}) + +describe('describeUploadError for server refusals (#20217)', () => { + const t = (key: string, params?: Record) => `${key}|${JSON.stringify(params ?? {})}` + const MB = 1024 * 1024 + + it('names the maximum for an oversize file', () => { + const error = new ConversationUploadError('file_too_large', 413, { max_bytes: 50 * MB }) + expect(describeUploadError(error, t)).toBe( + 'chat.input.uploadError.fileTooLarge|{"maxMb":50,"limitMb":0,"liveMb":0,"pendingMb":0,"remainingMb":0}' + ) + }) + + it('reports live bytes and the room left when nothing awaits removal', () => { + const error = new ConversationUploadError('quota_exceeded', 413, { + limit_bytes: 1024 * MB, + live_bytes: 1000 * MB, + pending_removal_bytes: 0, + remaining_bytes: 24 * MB, + }) + expect(describeUploadError(error, t)).toBe( + 'chat.input.uploadError.quotaExceeded|{"maxMb":0,"limitMb":1024,"liveMb":1000,"pendingMb":0,"remainingMb":24}' + ) + }) + + it('uses the human-review wording when deleted bytes still count', () => { + const error = new ConversationUploadError('quota_exceeded', 413, { + limit_bytes: 1024 * MB, + live_bytes: 100 * MB, + pending_removal_bytes: 924 * MB, + remaining_bytes: 0, + }) + expect(describeUploadError(error, t)).toContain('chat.input.uploadError.quotaExceededPendingRemoval|') + expect(describeUploadError(error, t)).toContain('"pendingMb":924') + }) + + it('every key it can ask for exists in en.json', async () => { + const en = (await import('@/i18n/locales/en.json')).default as any + for (const key of ['fileTooLarge', 'quotaExceeded', 'quotaExceededPendingRemoval']) { + expect(en.chat.input.uploadError[key]).toEqual(expect.any(String)) + } + }) +}) + describe('describeUploadError (#20133)', () => { const t = (key: string, params?: Record) => `${key}|${JSON.stringify(params ?? {})}` diff --git a/autobot-frontend/src/utils/conversationFileUpload.ts b/autobot-frontend/src/utils/conversationFileUpload.ts index 5676c8fbc3..89e245851e 100644 --- a/autobot-frontend/src/utils/conversationFileUpload.ts +++ b/autobot-frontend/src/utils/conversationFileUpload.ts @@ -19,7 +19,30 @@ import { readStoredAuthToken } from '@/utils/authToken' export type ConversationUploadResponse = components['schemas']['FileUploadResponse'] -export type UploadErrorCode = 'http' | 'invalid_response' | 'network' | 'cancelled' +export type UploadErrorCode = + | 'http' + | 'invalid_response' + | 'network' + | 'cancelled' + | 'file_too_large' + | 'quota_exceeded' + +/** + * The figures the server attaches to a 413 (`detail`, `conversation_file_quota.py`, #20217). `detail.code` + * is stable; the server's English `message` is never shown. Bytes are what the server measured. + */ +export interface UploadRefusal { + max_bytes?: number + limit_bytes?: number + live_bytes?: number + pending_removal_bytes?: number + remaining_bytes?: number +} + +const SERVER_REFUSALS: Record = { + conversation_file_too_large: 'file_too_large', + conversation_file_quota_exceeded: 'quota_exceeded', +} /** * Why a chat attachment upload failed. `message` is a diagnostic for logs, never UI text: @@ -28,7 +51,8 @@ export type UploadErrorCode = 'http' | 'invalid_response' | 'network' | 'cancell export class ConversationUploadError extends Error { constructor( readonly code: UploadErrorCode, - readonly status?: number + readonly status?: number, + readonly refusal?: UploadRefusal ) { super(`conversation upload failed: ${code}${status === undefined ? '' : ` (${status})`}`) this.name = 'ConversationUploadError' @@ -42,14 +66,72 @@ const UPLOAD_ERROR_KEYS: Record = { invalid_response: 'chat.input.uploadError.invalidResponse', network: 'chat.input.uploadError.network', cancelled: 'chat.input.uploadError.cancelled', + file_too_large: 'chat.input.uploadError.fileTooLarge', + quota_exceeded: 'chat.input.uploadError.quotaExceeded', +} + +const BYTES_PER_MB = 1024 * 1024 +const toMb = (bytes = 0) => Math.ceil(bytes / BYTES_PER_MB) + +/** Translation parameters for a server refusal; used space rounds up and space left rounds down, so neither is overstated. */ +function refusalParams(refusal: UploadRefusal = {}): Record { + return { + maxMb: toMb(refusal.max_bytes), + limitMb: toMb(refusal.limit_bytes), + liveMb: toMb(refusal.live_bytes), + pendingMb: toMb(refusal.pending_removal_bytes), + remainingMb: Math.floor((refusal.remaining_bytes ?? 0) / BYTES_PER_MB), + } } /** The translated text the chat shows for a rejected upload; any other rejection gets the generic key. */ export function describeUploadError(error: unknown, t: Translate): string { if (!(error instanceof ConversationUploadError)) return t('chat.input.uploadError.unknown') - return error.code === 'http' - ? t(UPLOAD_ERROR_KEYS.http, { status: error.status }) - : t(UPLOAD_ERROR_KEYS[error.code]) + if (error.code === 'http') return t(UPLOAD_ERROR_KEYS.http, { status: error.status }) + if (error.code === 'quota_exceeded' && (error.refusal?.pending_removal_bytes ?? 0) > 0) { + return t('chat.input.uploadError.quotaExceededPendingRemoval', refusalParams(error.refusal)) + } + if (error.code === 'file_too_large' || error.code === 'quota_exceeded') { + return t(UPLOAD_ERROR_KEYS[error.code], refusalParams(error.refusal)) + } + return t(UPLOAD_ERROR_KEYS[error.code]) +} + +/** The typed rejection for a recognised server reason (`detail.code` on a 413); undefined for anything else. */ +function refusalFor(status: number | undefined, detail: unknown): ConversationUploadError | undefined { + if (status !== 413 || !detail || typeof detail !== 'object') return undefined + const code = SERVER_REFUSALS[(detail as { code?: string }).code ?? ''] + return code ? new ConversationUploadError(code, status, detail as UploadRefusal) : undefined +} + +/** The typed rejection for a non-200: a recognised server reason, else a plain http one. */ +function rejectionFor(status: number, responseText: string): ConversationUploadError { + try { + const refusal = refusalFor(status, JSON.parse(responseText)?.detail) + if (refusal) return refusal + } catch { + // an unreadable error body is still an http failure + } + return new ConversationUploadError('http', status) +} + +interface CaughtApiError { + status?: number + details?: { detail?: unknown } | null + response?: { status?: number; data?: { detail?: unknown } } +} + +/** + * The translated text for a caught API error that carries a recognised 413 refusal (`/files/create`, + * `/generate`), whether it is the client's `HttpError` (`status`, `details.detail`) or axios-shaped + * (`response.status`, `response.data.detail`); null when it is any other error. + */ +export function describeApiRefusal(err: unknown, t: Translate): string | null { + if (!err || typeof err !== 'object') return null + const caught = err as CaughtApiError + const status = caught.status ?? caught.response?.status + const refusal = refusalFor(status, caught.details?.detail ?? caught.response?.data?.detail) + return refusal ? describeUploadError(refusal, t) : null } /** POST `file` to the conversation's upload route; rejects on a non-200, a bad body, a network error or an abort. */ @@ -66,7 +148,7 @@ export function postConversationUpload( if (event.lengthComputable) onProgress(event.loaded, event.total) }) xhr.addEventListener('load', () => { - if (xhr.status !== 200) return reject(new ConversationUploadError('http', xhr.status)) + if (xhr.status !== 200) return reject(rejectionFor(xhr.status, xhr.responseText)) try { resolve(JSON.parse(xhr.responseText) as ConversationUploadResponse) } catch { diff --git a/autobot-frontend/src/utils/errorExtract.ts b/autobot-frontend/src/utils/errorExtract.ts index 9e98bacf2d..a5c998b801 100644 --- a/autobot-frontend/src/utils/errorExtract.ts +++ b/autobot-frontend/src/utils/errorExtract.ts @@ -9,7 +9,7 @@ interface AxiosLikeError { response?: { data?: { - detail?: string + detail?: string | { message?: string } message?: string } } @@ -27,7 +27,9 @@ function isAxiosLikeError(err: unknown): err is AxiosLikeError { export function extractApiErrorMessage(err: unknown, fallback: string): string { if (isAxiosLikeError(err)) { const detail = err.response?.data?.detail - if (detail) return detail + if (typeof detail === 'string' && detail) return detail + // A structured detail ({code, message, ...}) is read as its message, never returned as the object. + if (detail && typeof detail === 'object' && detail.message) return detail.message const message = err.response?.data?.message if (message) return message } diff --git a/autobot-frontend/src/views/llc/ApprovalsInbox.vue b/autobot-frontend/src/views/llc/ApprovalsInbox.vue index 4cdd274bd7..dde1d9ffe8 100644 --- a/autobot-frontend/src/views/llc/ApprovalsInbox.vue +++ b/autobot-frontend/src/views/llc/ApprovalsInbox.vue @@ -26,6 +26,8 @@ + +
{{ $t('llc.approvals.selectCompany') }}