From f4f48419dd74dbc321bad342de2a44231e53b893 Mon Sep 17 00:00:00 2001 From: Torantulino <40276179@live.napier.ac.uk> Date: Mon, 26 Jan 2026 21:39:28 +0100 Subject: [PATCH] refactor(backend): Improve cleanup pattern per code review - Initialize synthetic_exec_id before try block instead of using locals() - Replace anti-pattern `if "var" in locals()` with proper `if var:` check - Add cleanup in credentials error path for consistency Co-Authored-By: Claude Opus 4.5 --- .../backend/backend/api/features/chat/tools/run_block.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/autogpt_platform/backend/backend/api/features/chat/tools/run_block.py b/autogpt_platform/backend/backend/api/features/chat/tools/run_block.py index 15da49262c..58792bb195 100644 --- a/autogpt_platform/backend/backend/api/features/chat/tools/run_block.py +++ b/autogpt_platform/backend/backend/api/features/chat/tools/run_block.py @@ -222,6 +222,7 @@ class RunBlockTool(BaseTool): graph_version=None, ) + synthetic_exec_id = None try: # Generate synthetic execution context for standalone block execution synthetic_exec_id = f"copilot-{session.session_id}-{uuid.uuid4().hex[:8]}" @@ -253,6 +254,8 @@ class RunBlockTool(BaseTool): if actual_credentials: exec_kwargs[field_name] = actual_credentials else: + if synthetic_exec_id: + clean_exec_files(synthetic_exec_id) return ErrorResponse( message=f"Failed to retrieve credentials for {field_name}", session_id=session_id, @@ -281,7 +284,7 @@ class RunBlockTool(BaseTool): except BlockError as e: logger.warning(f"Block execution failed: {e}") # Clean up temporary files even on failure - if "synthetic_exec_id" in locals(): + if synthetic_exec_id: clean_exec_files(synthetic_exec_id) return ErrorResponse( message=f"Block execution failed: {e}", @@ -291,7 +294,7 @@ class RunBlockTool(BaseTool): except Exception as e: logger.error(f"Unexpected error executing block: {e}", exc_info=True) # Clean up temporary files even on failure - if "synthetic_exec_id" in locals(): + if synthetic_exec_id: clean_exec_files(synthetic_exec_id) return ErrorResponse( message=f"Failed to execute block: {str(e)}",