LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-1824 [FIX] Return HTTP 409 when tool image not found in container registry (#1757)
Praveen Kumar4d4a5b46267e
diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.pyindex a7aeeb701..92468a2f9 100644--- a/backend/api_v2/api_deployment_views.py+++ b/backend/api_v2/api_deployment_views.py@@ -22,7 +22,11 @@ from api_v2.api_deployment_dto_registry import ApiDeploymentDTORegistryfrom api_v2.constants import ApiExecutionfrom api_v2.deployment_helper import DeploymentHelperfrom api_v2.dto import DeploymentExecutionDTO-from api_v2.exceptions import NoActiveAPIKeyError, RateLimitExceeded+from api_v2.exceptions import (+ NoActiveAPIKeyError,+ RateLimitExceeded,+ contains_tool_not_found_error,+)from api_v2.models import APIDeploymentfrom api_v2.rate_limiter import APIDeploymentRateLimiterfrom api_v2.serializers import (@@ -126,13 +130,29 @@ class DeploymentExecution(views.APIView):logger.exception(f"Workflow execution failed: {error}")raise- # Success - signal will handle slot release when workflow completes- if "error" in response and response["error"]:+ # Determine response status based on execution result+ execution_status = response.get("execution_status", "")+ has_error = response.get("error") or execution_status == "ERROR"++ if has_error:+ # Check for tool not found in registry error - return 500 Internal Server Error+ # This is a server-side deployment state issue, not a client-actionable error+ if contains_tool_not_found_error(response):+ logger.error(+ "API deployment failed: Tool not found in container registry"+ )+ return Response(+ {"message": response},+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )+ # Other errors - return 422 Unprocessable Entitylogger.error("API deployment execution failed")return Response({"message": response},status=status.HTTP_422_UNPROCESSABLE_ENTITY,)++ # Successreturn Response({"message": response}, status=status.HTTP_200_OK)@DeploymentHelper.validate_api_key@@ -152,9 +172,45 @@ class DeploymentExecution(views.APIView):# Fetch execution statusresponse: ExecutionResponse = DeploymentHelper.get_execution_status(execution_id)- # Determine response status++ # Handle result already acknowledged+ if response.result_acknowledged:+ return Response(+ data={+ "status": response.execution_status,+ "message": "Result already acknowledged",+ },+ status=status.HTTP_406_NOT_ACCEPTABLE,+ )++ # Determine response status based on execution state+ execution_status_value = response.execution_status++ # Check for tool not found in registry error - return 500 Internal Server Error+ # This is a server-side deployment state issue, not a client-actionable error+ if contains_tool_not_found_error(response):+ logger.error("Execution failed: Tool not found in container registry")+ return Response(+ data={+ "status": execution_status_value,+ "message": response.result,+ },+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )++ # Check for ERROR status - return 422 Unprocessable Entity+ if execution_status_value == "ERROR":+ return Response(+ data={+ "status": execution_status_value,+ "message": response.result,+ },+ status=status.HTTP_422_UNPROCESSABLE_ENTITY,+ )++ # Process completed executionresponse_status = status.HTTP_422_UNPROCESSABLE_ENTITY- if response.execution_status == CeleryTaskState.COMPLETED.value:+ if execution_status_value == CeleryTaskState.COMPLETED.value:response_status = status.HTTP_200_OK# Check if highlight data should be removed using configuration registryapi_deployment = deployment_execution_dto.api@@ -177,9 +233,6 @@ class DeploymentExecution(views.APIView):response.remove_result_metadata_keys()if not include_metrics:response.remove_result_metrics()- if response.result_acknowledged:- response_status = status.HTTP_406_NOT_ACCEPTABLE- response.result = "Result already acknowledged"return Response(data={"status": response.execution_status,diff --git a/backend/api_v2/exceptions.py b/backend/api_v2/exceptions.pyindex 246788bff..764021952 100644--- a/backend/api_v2/exceptions.py+++ b/backend/api_v2/exceptions.py@@ -1,5 +1,10 @@+from typing import TYPE_CHECKING+from rest_framework.exceptions import APIException+if TYPE_CHECKING:+ from workflow_manager.workflow_v2.dto import ExecutionResponse+class NotFoundException(APIException):status_code = 404@@ -87,6 +92,84 @@ class RateLimitExceeded(APIException):super().__init__(detail, code)+class ToolNotFoundInRegistry(APIException):+ """Raised when a tool image is not found in the container registry.++ This indicates a server-side platform deployment state issue - the+ requested tool image is not available in the container registry.+ HTTP 500 Internal Server Error is used because this is a server-side+ configuration/deployment problem, not a client-actionable error.+ """++ status_code = 500+ default_detail = "Tool not found in container registry"++ # Error code used to identify this error in execution results+ ERROR_CODE = "TOOL_IMAGE_NOT_FOUND"++ def __init__(+ self,+ detail: str | None = None,+ code: str | None = None,+ tool_name: str = "",+ ):+ if detail is None:+ if tool_name:+ detail = (+ f"Tool '{tool_name}' not found in container registry. "+ f"Please ensure the tool is properly deployed."+ )+ else:+ detail = self.default_detail+ super().__init__(detail, code)+++def _check_error_code(error_value: str | None) -> bool:+ """Check if error string contains the tool not found error code.++ Uses deterministic error code matching instead of fragile string patterns.+ """+ if not error_value:+ return False+ return ToolNotFoundInRegistry.ERROR_CODE in str(error_value)+++def contains_tool_not_found_error(+ response: "dict | ExecutionResponse",+) -> bool:+ """Check if response contains a tool not found in registry error.++ Uses deterministic error code matching (TOOL_IMAGE_NOT_FOUND) instead of+ fragile string pattern matching to identify this specific error condition.++ Args:+ response: Either a dict (from POST) or ExecutionResponse (from GET)++ Returns:+ bool: True if tool not found error is detected+ """+ # Get error and result from response+ if isinstance(response, dict):+ error = response.get("error")+ result = response.get("result", [])+ else:+ error = getattr(response, "error", None)+ result = getattr(response, "result", []) or []++ # Check top-level error for error code+ if _check_error_code(error):+ return True++ # Check file-level errors in result array+ if isinstance(result, list):+ for item in result:+ if isinstance(item, dict):+ if _check_error_code(item.get("error")):+ return True++ return False++class PresignedURLFetchError(APIException):default_detail = "Failed to fetch file from presigned URL"diff --git a/backend/workflow_manager/workflow_v2/file_execution_tasks.py b/backend/workflow_manager/workflow_v2/file_execution_tasks.pyindex a9b3ab871..5ea898637 100644--- a/backend/workflow_manager/workflow_v2/file_execution_tasks.py+++ b/backend/workflow_manager/workflow_v2/file_execution_tasks.py@@ -30,6 +30,7 @@ from unstract.core.file_execution_tracker import (FileExecutionStatusTracker,)from unstract.core.tool_execution_status import ToolExecutionData, ToolExecutionTracker+from unstract.tool_sandbox.exceptions import ToolNotFoundInRegistryErrorfrom unstract.workflow_execution.enums import LogComponent, LogStage, LogStatefrom unstract.workflow_execution.exceptions import StopExecutionfrom workflow_manager.endpoint_v2.destination import DestinationConnector@@ -947,6 +948,15 @@ class FileExecutionTasks:except StopExecution:workflow_file_execution.update_status(status=ExecutionStatus.STOPPED)raise+ except ToolNotFoundInRegistryError as error:+ # Preserve specific error pattern for API layer detection (HTTP 409)+ error_msg = f"Tool not found in container registry: {error.message}"+ tool_execution_result = ToolExecutionResult(+ error=error_msg,+ result=None,+ )+ logger.error(f"Tool not found in registry: {error.message}", exc_info=True)+ return tool_execution_resultexcept WorkflowExecutionError as error:tool_execution_result = ToolExecutionResult(error=str(error),@@ -1050,8 +1060,18 @@ class FileExecutionTasks:metadata=execution_metadata,)except Exception as e:- error_msg = f"Final output processing failed: {str(e)}"- logger.error(error_msg, exc_info=True)+ # Preserve original processing_error if it exists, as it may contain+ # important error info (e.g., "tool not found in container registry")+ if processing_error:+ error_msg = processing_error+ logger.error(+ f"Final output processing failed with original error: {processing_error}. "+ f"Additional error during finalization: {str(e)}",+ exc_info=True,+ )+ else:+ error_msg = f"Final output processing failed: {str(e)}"+ logger.error(error_msg, exc_info=True)return FinalOutputResult(output=None, metadata=None, error=error_msg)return FinalOutputResult(diff --git a/runner/src/unstract/runner/clients/docker_client.py b/runner/src/unstract/runner/clients/docker_client.pyindex 62dcaaa6d..735f0f341 100644--- a/runner/src/unstract/runner/clients/docker_client.py+++ b/runner/src/unstract/runner/clients/docker_client.py@@ -14,6 +14,7 @@ from unstract.runner.clients.interface import (ContainerInterface,)from unstract.runner.constants import Env+from unstract.runner.exception import ToolImageNotFoundErrorfrom unstract.runner.utils import Utils@@ -174,26 +175,42 @@ class Client(ContainerClientInterface):return image_name_with_tagself.logger.info("Pulling the container: %s", image_name_with_tag)- resp = self.client.api.pull(- repository=repository,- tag=image_tag,- stream=True,- decode=True,- )- counter = 0- for line in resp:- # The counter is used to print status on every 100th status- # Otherwise the output logs will be polluted.- if counter < 100:- counter += 1- continue- counter = 0- self.logger.info(- "CONTAINER PULL STATUS: %s - %s : %s",- line.get("status"),- line.get("id"),- line.get("progress"),+ try:+ resp = self.client.api.pull(+ repository=repository,+ tag=image_tag,+ stream=True,+ decode=True,)+ counter = 0+ for line in resp:+ # Check for error in pull response+ if "error" in line:+ error_msg = line.get("error", "Unknown error during image pull")+ self.logger.error(+ f"Error pulling image {image_name_with_tag}: {error_msg}"+ )+ raise ToolImageNotFoundError(repository, image_tag)+ # The counter is used to print status on every 100th status+ # Otherwise the output logs will be polluted.+ if counter < 100:+ counter += 1+ continue+ counter = 0+ self.logger.info(+ "CONTAINER PULL STATUS: %s - %s : %s",+ line.get("status"),+ line.get("id"),+ line.get("progress"),+ )+ except ImageNotFound:+ self.logger.error(f"Image {image_name_with_tag} not found in registry")+ raise ToolImageNotFoundError(repository, image_tag)+ except APIError as e:+ if e.status_code == 404 or "not found" in str(e).lower():+ self.logger.error(f"Image {image_name_with_tag} not found in registry")+ raise ToolImageNotFoundError(repository, image_tag)+ raiseself.logger.info("Finished pulling the container: %s", image_name_with_tag)return image_name_with_tag@@ -277,7 +294,7 @@ class Client(ContainerClientInterface):)except ImageNotFound:self.logger.error(f"Image {self.image_name}:{self.image_tag} not found")- raise+ raise ToolImageNotFoundError(self.image_name, self.image_tag)def run_container_with_sidecar(self, container_config: dict[str, Any], sidecar_config: dict[str, Any]@@ -310,7 +327,7 @@ class Client(ContainerClientInterface):)except ImageNotFound:self.logger.error(f"Image {self.image_name}:{self.image_tag} not found")- raise+ raise ToolImageNotFoundError(self.image_name, self.image_tag)def wait_for_container_stop(self,diff --git a/runner/src/unstract/runner/exception.py b/runner/src/unstract/runner/exception.pyindex c7c639877..0ca7c3426 100644--- a/runner/src/unstract/runner/exception.py+++ b/runner/src/unstract/runner/exception.py@@ -2,3 +2,19 @@ class ToolRunException(Exception):def __init__(self, message):self.message = messagesuper().__init__(self.message)+++class ToolImageNotFoundError(ToolRunException):+ """Raised when a tool image is not found in the container registry."""++ # Error code for deterministic error identification across services+ ERROR_CODE = "TOOL_IMAGE_NOT_FOUND"++ def __init__(self, image_name: str, image_tag: str):+ self.image_name = image_name+ self.image_tag = image_tag+ self.message = (+ f"Tool image '{image_name}:{image_tag}' not found in container registry. "+ f"Please ensure the tool is properly deployed and the image exists."+ )+ super().__init__(self.message)diff --git a/runner/src/unstract/runner/runner.py b/runner/src/unstract/runner/runner.pyindex f20a373b0..03ed6f341 100644--- a/runner/src/unstract/runner/runner.py+++ b/runner/src/unstract/runner/runner.py@@ -1,6 +1,7 @@import astimport jsonimport os+import shlexfrom datetime import UTC, datetimefrom typing import Any@@ -26,7 +27,7 @@ from unstract.runner.clients.interface import (ContainerInterface,)from unstract.runner.constants import Env, LogLevel, LogType, ToolKey-from unstract.runner.exception import ToolRunException+from unstract.runner.exception import ToolImageNotFoundError, ToolRunExceptionfrom unstract.runner.utils import Utilsload_dotenv()@@ -293,11 +294,11 @@ class UnstractRunner:self, shared_log_dir: str, shared_log_file: str, settings: dict[str, Any]):"""Returns the container command to run the tool."""- settings_json = json.dumps(settings).replace("'", "\\'")+ settings_json = json.dumps(settings)# Prepare the tool execution commandtool_cmd = (f"python main.py --command RUN "- f"--settings '{settings_json}' --log-level DEBUG"+ f"--settings {shlex.quote(settings_json)} --log-level DEBUG")if not self.sidecar_enabled:@@ -461,45 +462,46 @@ class UnstractRunner:tool_container_name=container_name,)- container_config = self.client.get_container_run_config(- command=["/bin/sh", "-c", container_command],- file_execution_id=file_execution_id,- shared_log_dir=shared_log_dir, # Pass directory for mounting- container_name=container_name,- envs={**envs, **additional_env},- organization_id=organization_id,- workflow_id=workflow_id,- execution_id=execution_id,- messaging_channel=messaging_channel,- tool_instance_id=tool_instance_id,- )-- sidecar_config: dict[str, Any] | None = None- if self.sidecar_enabled:- sidecar_config = self._get_sidecar_container_config(- container_name=container_name,- shared_log_dir=shared_log_dir,- shared_log_file=shared_log_file,+ # Run the Docker container+ container = None+ sidecar = None+ result = {"type": "RESULT", "result": None, "status": "RUNNING"}+ try:+ # Build container config inside try block to catch ToolImageNotFoundError+ # during image pull in get_container_run_config() -> get_image()+ container_config = self.client.get_container_run_config(+ command=["/bin/sh", "-c", container_command],file_execution_id=file_execution_id,- execution_id=execution_id,+ shared_log_dir=shared_log_dir, # Pass directory for mounting+ container_name=container_name,+ envs={**envs, **additional_env},organization_id=organization_id,+ workflow_id=workflow_id,+ execution_id=execution_id,messaging_channel=messaging_channel,tool_instance_id=tool_instance_id,)- # Add labels to container for logging with Loki.- # This only required for observability.- try:- labels = ast.literal_eval(os.getenv(Env.TOOL_CONTAINER_LABELS, "[]"))- container_config["labels"] = labels- except Exception as e:- self.logger.info(f"Invalid labels for logging: {e}")+ sidecar_config: dict[str, Any] | None = None+ if self.sidecar_enabled:+ sidecar_config = self._get_sidecar_container_config(+ container_name=container_name,+ shared_log_dir=shared_log_dir,+ shared_log_file=shared_log_file,+ file_execution_id=file_execution_id,+ execution_id=execution_id,+ organization_id=organization_id,+ messaging_channel=messaging_channel,+ tool_instance_id=tool_instance_id,+ )- # Run the Docker container- container = None- sidecar = None- result = {"type": "RESULT", "result": None, "status": "RUNNING"}- try:+ # Add labels to container for logging with Loki.+ # This only required for observability.+ try:+ labels = ast.literal_eval(os.getenv(Env.TOOL_CONTAINER_LABELS, "[]"))+ container_config["labels"] = labels+ except Exception as e:+ self.logger.info(f"Invalid labels for logging: {e}")self.logger.info(f"Execution ID: {execution_id}, running docker "f"container: {container_name}"@@ -529,9 +531,22 @@ class UnstractRunner:f"container: {container_name} ran successfully")result = {"type": "RESULT", "result": None, "status": "SUCCESS"}+ except ToolImageNotFoundError as e:+ self.logger.error(+ f"Tool image not found in container registry: {e.image_name}:{e.image_tag}",+ stack_info=True,+ exc_info=True,+ )+ result = {+ "type": "RESULT",+ "result": None,+ "error": str(e.message),+ "error_code": ToolImageNotFoundError.ERROR_CODE,+ "status": "ERROR",+ }except ToolRunException as te:self.logger.error(- f"Error while running docker container {container_config.get('name')}: {te}",+ f"Error while running docker container {container_name}: {te}",stack_info=True,exc_info=True,)diff --git a/unstract/tool-sandbox/src/unstract/tool_sandbox/dto.py b/unstract/tool-sandbox/src/unstract/tool_sandbox/dto.pyindex 88e81be4a..3fcd9a37a 100644--- a/unstract/tool-sandbox/src/unstract/tool_sandbox/dto.py+++ b/unstract/tool-sandbox/src/unstract/tool_sandbox/dto.py@@ -15,14 +15,18 @@ class RunnerContainerRunResponse:result: dict[str, Any] | Noneerror: str | Nonestatus: RunnerContainerRunStatus+ error_code: str | None = Nonedef to_dict(self) -> dict[str, Any]:- return {+ result = {"type": self.type,"result": self.result,"error": self.error,"status": self.status.value,}+ if self.error_code:+ result["error_code"] = self.error_code+ return result@classmethoddef from_dict(cls, data: dict[str, Any]) -> "RunnerContainerRunResponse":@@ -31,6 +35,7 @@ class RunnerContainerRunResponse:result=data.get("result"),error=data.get("error"),status=RunnerContainerRunStatus(data.get("status")),+ error_code=data.get("error_code"),)diff --git a/unstract/tool-sandbox/src/unstract/tool_sandbox/exceptions.py b/unstract/tool-sandbox/src/unstract/tool_sandbox/exceptions.pyindex a549c1348..92030ad43 100644--- a/unstract/tool-sandbox/src/unstract/tool_sandbox/exceptions.py+++ b/unstract/tool-sandbox/src/unstract/tool_sandbox/exceptions.py@@ -2,3 +2,17 @@ class ToolExecutionException(Exception):def __init__(self, message):self.message = messagesuper().__init__(self.message)+++class ToolNotFoundInRegistryError(Exception):+ """Raised when a tool image is not found in the container registry.++ This indicates a platform configuration issue - the requested tool+ is not available in the container registry.+ """++ ERROR_CODE = "TOOL_IMAGE_NOT_FOUND"++ def __init__(self, message: str):+ self.message = message+ super().__init__(self.message)diff --git a/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py b/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.pyindex 014fa4899..c5050fd80 100644--- a/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py+++ b/unstract/tool-sandbox/src/unstract/tool_sandbox/helper.py@@ -30,6 +30,7 @@ from unstract.tool_sandbox.dto import (RunnerContainerRunResponse,RunnerContainerRunStatus,)+from unstract.tool_sandbox.exceptions import ToolNotFoundInRegistryErrorlogger = logging.getLogger(__name__)@@ -609,16 +610,29 @@ class ToolSandboxHelper:raise ToolSanboxError(msg) from connect_errexcept RequestException as e:error_message = str(e)+ error_code = Nonecontent_type = response.headers.get("Content-Type", "").lower()if "application/json" in content_type:response_json = response.json()if "error" in response_json:error_message = response_json["error"]+ error_code = response_json.get("error_code")elif response.text:error_message = response.textlogger.error(f"Error from runner: {error_message}")+ # Check for tool image not found error+ if error_code == ToolNotFoundInRegistryError.ERROR_CODE:+ raise ToolNotFoundInRegistryError(error_message) from eraise ToolSanboxError(error_message) from e- return RunnerContainerRunResponse.from_dict(response.json())++ # Parse response and check for tool image not found error+ result = RunnerContainerRunResponse.from_dict(response.json())+ if (+ result.status == RunnerContainerRunStatus.ERROR+ and result.error_code == ToolNotFoundInRegistryError.ERROR_CODE+ ):+ raise ToolNotFoundInRegistryError(result.error or "Tool image not found")+ return resultdef create_tool_request_data(self,diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py b/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.pyindex ef05ffd77..3530994ea 100644--- a/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py+++ b/unstract/workflow-execution/src/unstract/workflow_execution/tools_utils.py@@ -8,6 +8,7 @@ from unstract.core.pubsub_helper import LogPublisherfrom unstract.tool_registry import ToolRegistryfrom unstract.tool_sandbox import ToolSandboxfrom unstract.tool_sandbox.dto import RunnerContainerRunResponse+from unstract.tool_sandbox.exceptions import ToolNotFoundInRegistryErrorfrom unstract.workflow_execution.constants import ToolExecutionfrom unstract.workflow_execution.constants import ToolRuntimeVariable as ToolRVfrom unstract.workflow_execution.dto import ToolInstance, WorkflowDto@@ -195,6 +196,10 @@ class ToolsUtils:logger.warning(f"ToolExecutionException - Retrying ({retry_count + 1}/{max_retries})")+ except ToolNotFoundInRegistryError:+ # Don't retry configuration errors - tool image is not available+ logger.error("Tool image not found in container registry - not retrying")+ raiseexcept Exception as e:if retry_count < max_retries - 1:logger.warning(