Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix: dont return 500 from cancellation endpoint (#8004)

Sarah Wooders6eccd2025d6f
diff --git a/letta/errors.py b/letta/errors.py
index 1328f069a..7f07bf884 100644
--- a/letta/errors.py
+++ b/letta/errors.py
@@ -53,6 +53,17 @@ class PendingApprovalError(LettaError):
super().__init__(message=message, code=code, details=details)
+class NoActiveRunsToCancelError(LettaError):
+ """Error raised when attempting to cancel but there are no active runs to cancel."""
+
+ def __init__(self, agent_id: Optional[str] = None):
+ message = "No active runs to cancel"
+ if agent_id:
+ message = f"No active runs to cancel for agent {agent_id}"
+ details = {"error_code": "NO_ACTIVE_RUNS_TO_CANCEL", "agent_id": agent_id}
+ super().__init__(message=message, code=ErrorCode.CONFLICT, details=details)
+
+
class LettaToolCreateError(LettaError):
"""Error raised when a tool cannot be created."""
diff --git a/letta/server/rest_api/app.py b/letta/server/rest_api/app.py
index f1441ea54..3de5dcf79 100644
--- a/letta/server/rest_api/app.py
+++ b/letta/server/rest_api/app.py
@@ -50,6 +50,7 @@ from letta.errors import (
LLMProviderOverloaded,
LLMRateLimitError,
LLMTimeoutError,
+ NoActiveRunsToCancelError,
PendingApprovalError,
)
from letta.helpers.pinecone_utils import get_pinecone_indices, should_use_pinecone, upsert_pinecone_indices
@@ -493,6 +494,7 @@ def create_application() -> "FastAPI":
app.add_exception_handler(UniqueConstraintViolationError, _error_handler_409)
app.add_exception_handler(IntegrityError, _error_handler_409)
app.add_exception_handler(PendingApprovalError, _error_handler_409)
+ app.add_exception_handler(NoActiveRunsToCancelError, _error_handler_409)
# 415 Unsupported Media Type errors
app.add_exception_handler(LettaUnsupportedFileUploadError, _error_handler_415)
diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.py
index 8e2b43a34..752369446 100644
--- a/letta/server/rest_api/routers/v1/agents.py
+++ b/letta/server/rest_api/routers/v1/agents.py
@@ -24,8 +24,8 @@ from letta.errors import (
AgentExportProcessingError,
AgentFileImportError,
AgentNotFoundForExportError,
+ NoActiveRunsToCancelError,
PendingApprovalError,
- RunCancelError,
)
from letta.groups.sleeptime_multi_agent_v4 import SleeptimeMultiAgentV4
from letta.helpers.datetime_helpers import get_utc_time, get_utc_timestamp_ns
@@ -1670,40 +1670,50 @@ async def cancel_message(
raise HTTPException(status_code=400, detail="Agent run tracking is disabled")
run_ids = request.run_ids if request else None
if not run_ids:
- redis_client = await get_redis_client()
- run_id = await redis_client.get(f"{REDIS_RUN_ID_PREFIX}:{agent_id}")
+ run_id = None
+ try:
+ redis_client = await get_redis_client()
+ run_id = await redis_client.get(f"{REDIS_RUN_ID_PREFIX}:{agent_id}")
+ except Exception as e:
+ # Redis is optional; fall back to DB to avoid surfacing 5XXs for cancellation.
+ logger.warning(f"Failed to look up run to cancel in redis for agent {agent_id}, falling back to DB: {e}")
+
if run_id is None:
logger.warning("Cannot find run associated with agent to cancel in redis, fetching from db.")
- run_ids = await server.run_manager.list_runs(
+ runs = await server.run_manager.list_runs(
actor=actor,
statuses=[RunStatus.created, RunStatus.running],
ascending=False,
agent_id=agent_id, # NOTE: this will override agent_ids if provided
- limit=100, # Limit to 10 most recent active runs for cancellation
+ limit=100, # Limit to 100 most recent active runs for cancellation
)
- run_ids = [run.id for run in run_ids]
+ run_ids = [run.id for run in runs]
else:
run_ids = [run_id]
+ if not run_ids:
+ raise NoActiveRunsToCancelError(agent_id=agent_id)
+
results = {}
- failed_to_cancel = []
for run_id in run_ids:
- run = await server.run_manager.get_run_by_id(run_id=run_id, actor=actor)
- if run.metadata.get("lettuce"):
- lettuce_client = await LettuceClient.create()
- await lettuce_client.cancel(run_id)
try:
- run = await server.run_manager.cancel_run(actor=actor, agent_id=agent_id, run_id=run_id)
+ run = await server.run_manager.get_run_by_id(run_id=run_id, actor=actor)
+ if run.metadata and run.metadata.get("lettuce"):
+ try:
+ lettuce_client = await LettuceClient.create()
+ await lettuce_client.cancel(run_id)
+ except Exception as e:
+ # Do not surface cancellation failures as 5XXs.
+ logger.error(f"Failed to cancel Lettuce run {run_id}: {e}")
+
+ await server.run_manager.cancel_run(actor=actor, agent_id=agent_id, run_id=run_id)
except Exception as e:
results[run_id] = "failed"
+ # Cancellation failures should not raise errors back to the client.
logger.error(f"Failed to cancel run {run_id}: {str(e)}")
- failed_to_cancel.append(run_id)
continue
results[run_id] = "cancelled"
logger.info(f"Cancelled run {run_id}")
-
- if failed_to_cancel:
- raise RunCancelError(f"Failed to cancel runs: {failed_to_cancel}")
return results
diff --git a/letta/services/run_manager.py b/letta/services/run_manager.py
index c05b8da35..754cfebe0 100644
--- a/letta/services/run_manager.py
+++ b/letta/services/run_manager.py
@@ -613,12 +613,13 @@ class RunManager:
logger.debug(f"Cancelling run {run_id} for agent {agent_id}")
- # check if run can be cancelled (cannot cancel a completed, failed, or cancelled run)
+ # Cancellation should be idempotent: if a run is already terminated, treat this as a no-op.
+ # This commonly happens when a run finishes between client request and server handling.
if run.stop_reason and run.stop_reason not in [StopReasonType.requires_approval]:
- logger.error(f"Run {run_id} cannot be cancelled because it is already terminated with stop reason: {run.stop_reason.value}")
- raise LettaInvalidArgumentError(
+ logger.debug(
f"Run {run_id} cannot be cancelled because it is already terminated with stop reason: {run.stop_reason.value}"
)
+ return
# Check if agent is waiting for approval by examining the last message
agent_state = await self.agent_manager.get_agent_by_id_async(agent_id=agent_id, actor=actor)