4545
4646logger = logging .getLogger ("google_adk." + __name__ )
4747
48+ # Name of the Job container that runs the user's code, and so the one whose
49+ # termination status is the status of the execution.
50+ _CODE_CONTAINER_NAME = "code-runner"
51+
4852
4953class GkeCodeExecutor (BaseCodeExecutor ):
5054 """Executes Python code in a secure gVisor-sandboxed Pod on GKE.
@@ -187,7 +191,11 @@ def _execute_in_sandbox(self, code: str) -> CodeExecutionResult:
187191 sandbox .write ("script.py" , code )
188192 result = sandbox .run ("python3 script.py" )
189193
190- return CodeExecutionResult (stdout = result .stdout , stderr = result .stderr )
194+ return CodeExecutionResult (
195+ stdout = result .stdout ,
196+ stderr = result .stderr ,
197+ exit_code = result .exit_code ,
198+ )
191199 except RuntimeError as e :
192200 logger .error (
193201 "SandboxClient failed to initialize or find gateway" , exc_info = True
@@ -272,7 +280,7 @@ def _create_job_manifest(
272280 """Creates the complete V1Job object with security best practices."""
273281 # Define the container that will run the code.
274282 container = k8s .client .V1Container (
275- name = "code-runner" ,
283+ name = _CODE_CONTAINER_NAME ,
276284 image = self .image ,
277285 command = ["python3" , "/app/code.py" ],
278286 volume_mounts = [
@@ -350,16 +358,25 @@ def _watch_job_completion(self, job_name: str) -> CodeExecutionResult:
350358 timeout_seconds = self .timeout_seconds ,
351359 ):
352360 job = event ["object" ]
361+ # The Job reports only whether the pod succeeded, so the status the
362+ # container terminated with is read from the pod itself. It is absent
363+ # when the pod never reached a terminated state, and only then is the
364+ # code narrowed to the one the Job's outcome implies.
353365 if job .status .succeeded :
354366 watch .stop ()
355367 logger .info (f"Job '{ job_name } ' succeeded." )
356- logs = self ._get_pod_logs (job_name )
357- return CodeExecutionResult (stdout = logs )
368+ logs , exit_code = self ._get_pod_logs_and_exit_code (job_name )
369+ return CodeExecutionResult (
370+ stdout = logs , exit_code = 0 if exit_code is None else exit_code
371+ )
358372 if job .status .failed :
359373 watch .stop ()
360374 logger .error (f"Job '{ job_name } ' failed." )
361- logs = self ._get_pod_logs (job_name )
362- return CodeExecutionResult (stderr = f"Job failed. Logs:\n { logs } " )
375+ logs , exit_code = self ._get_pod_logs_and_exit_code (job_name )
376+ return CodeExecutionResult (
377+ stderr = f"Job failed. Logs:\n { logs } " ,
378+ exit_code = 1 if exit_code is None else exit_code ,
379+ )
363380
364381 # If the loop finishes without returning, the watch timed out.
365382 raise TimeoutError (
@@ -371,6 +388,25 @@ def _watch_job_completion(self, job_name: str) -> CodeExecutionResult:
371388 def _get_pod_logs (self , job_name : str ) -> str :
372389 """Retrieves logs from the pod created by the specified job.
373390
391+ Raises:
392+ RuntimeError: If the pod cannot be found or logs cannot be fetched.
393+ """
394+ logs , _ = self ._get_pod_logs_and_exit_code (job_name )
395+ return logs
396+
397+ def _get_pod_logs_and_exit_code (
398+ self , job_name : str
399+ ) -> tuple [str , int | None ]:
400+ """Retrieves the logs and exit code of the pod created by the given job.
401+
402+ Both are read from a single pod lookup, since the status a container
403+ terminated with is only available for as long as the pod its logs come
404+ from.
405+
406+ Returns:
407+ The pod's logs, and the status the code container exited with, or None
408+ when the pod reports no terminated container to read it from.
409+
374410 Raises:
375411 RuntimeError: If the pod cannot be found or logs cannot be fetched.
376412 """
@@ -385,18 +421,34 @@ def _get_pod_logs(self, job_name: str) -> str:
385421 f"Could not find Pod for Job '{ job_name } ' to retrieve logs."
386422 )
387423
388- pod_name = pods .items [0 ]. metadata . name
389- return cast (
424+ pod = pods .items [0 ]
425+ logs = cast (
390426 str ,
391427 self ._core_v1 .read_namespaced_pod_log (
392- name = pod_name , namespace = self .namespace
428+ name = pod . metadata . name , namespace = self .namespace
393429 ),
394430 )
431+ return logs , self ._get_container_exit_code (pod )
395432 except ApiException as e :
396433 raise RuntimeError (
397434 f"API error retrieving logs for job '{ job_name } ': { e .reason } "
398435 ) from e
399436
437+ def _get_container_exit_code (self , pod : k8s .client .V1Pod ) -> int | None :
438+ """Reads the status the code container of the given pod exited with.
439+
440+ Returns:
441+ The exit code, or None when the container is absent from the pod's
442+ status or has not reached a terminated state.
443+ """
444+ for container_status in pod .status .container_statuses or []:
445+ if container_status .name != _CODE_CONTAINER_NAME :
446+ continue
447+ state = container_status .state
448+ terminated = state .terminated if state else None
449+ return terminated .exit_code if terminated else None
450+ return None
451+
400452 def _create_code_configmap (self , name : str , code : str ) -> None :
401453 """Creates a ConfigMap to hold the Python code."""
402454 body = k8s .client .V1ConfigMap (
0 commit comments