← Blog

Gemini Code Execution Output Needs Field-Level Validation

Parminder Singh
Parminder Singh··7 min read
Summarize with AI

Gemini code execution responses can contain executableCode and codeExecutionResult parts alongside model text. A gateway should validate part types, correlate optional IDs, enforce language and outcome policies, cap output, and keep provider execution evidence separate from application approval or downstream action.

Problem-Awareai-securityllm-securitypolicy-enforcementzero-trustarchitectureaudit
Gemini Code Execution Output Needs Field-Level Validation

Gemini can return generated code and its execution result as content parts. Google's REST schema names those fields executableCode and codeExecutionResult. The result carries a required outcome plus optional output, while newer schema versions can also use IDs to associate a result with generated code. A production parser has more work than reading the final text summary.

I want every part validated before an authenticated caller or downstream workflow receives it. Execution success is provider evidence. Application acceptance still depends on shape and correlation. Output limits and the route's contract also apply.

TL;DR

  • Validate every Gemini content part and reject malformed executableCode or codeExecutionResult objects.
  • Allowlist the documented language and outcome enums while preserving unknown raw values for review.
  • Correlate code and result IDs when present, then cap output bytes before logging or display and before downstream parsing.
  • Separate HTTP success from provider execution outcome. Keep application acceptance separate from any later business action.

Code execution returns several part types

Google's official code execution guide says the tool lets Gemini generate and run Python code. The response can combine model text with generated code and execution results. The guide's current output explanation names inline text and generated code meant for execution. It describes the result of that execution as a separate part.

The broader GenerateContent API reference defines the candidate and content envelope. The machine-readable Gemini API Discovery document gives the field contract for REST parsers. ExecutableCode requires code and language. The documented language enum includes PYTHON, plus LANGUAGE_UNSPECIFIED, which the schema says should not be used.

CodeExecutionResult requires outcome, with four documented values:

  • OUTCOME_OK reports that code execution completed successfully.
  • OUTCOME_FAILED reports an execution failure and can carry stderr with stdout.
  • OUTCOME_DEADLINE_EXCEEDED can include partial output from the expired run.
  • OUTCOME_UNSPECIFIED supplies no usable execution classification.

The optional output field carries the corresponding execution text.

The Google Gemini enterprise security guide covers the wider authenticated route. This control focuses on the fields crossing back over that route.

Parse parts under a closed schema

Walk every candidate and every content part by index. Require each part to match one supported variant. For executableCode, validate an object, a known language string, a bounded code string, and an optional ID with route-approved length and character rules. Preserve unknown fields in protected evidence if policy requires them, but keep the part out of delivery until the parser contract is updated.

For codeExecutionResult, require an object and a known outcome. Validate output as a string when present and apply a byte limit before copying it into general logs. Validate the optional ID under the same identifier rules used for executable code. Duplicate JSON members and mixed part variants should produce named validation failures. Wrong scalar types and excessive nesting should do the same.

My opinion is that a permissive Map<String, Any> parser has no place on a tool-enabled production route. It turns a documented protocol into a bag of values and hides provider changes until a workflow breaks.

The AI audit log schema supplies the common response ID, model version, identity, route, and policy fields around this part-level evidence.

Correlation prevents code and results from drifting apart

The current Discovery schema says an ExecutableCode.id is optional and that the server returns a matching ID on the corresponding CodeExecutionResult when the code part has one. Use that relationship when IDs appear. Require one result to point to one known code part under the candidate's ordered content, unless a current API contract explicitly permits another shape.

Record candidate index, part index, code ID, and result ID. Record language, outcome, and output length in the same evidence. Reject duplicate IDs and results that reference an unknown code ID. Reject a code ID with conflicting results. When IDs are absent, preserve the exact part order and apply the API version's documented association rule instead of inventing identifiers.

A review screen can make drift visible. Put generated code in a numbered gray card and place the associated result immediately beneath it with the same ID label. A result that lands under the wrong card should fail the fixture before release.

Correlation is evidence about which returned result belongs to which returned code. It does not prove that the code was sensible or deterministic. It also does not establish suitability for a business decision.

Outcome controls delivery and downstream action

OUTCOME_OK means code execution completed successfully and output contains stdout when available. It makes the pair eligible for route-specific validation. It does not establish that the output answers the user's question or matches the final model text. The application's schema still applies.

OUTCOME_FAILED should retain bounded output because the schema says it can contain stderr and stdout. Avoid placing that output in public error text or alert titles. Stack traces and printed values can carry prompt-derived content. OUTCOME_DEADLINE_EXCEEDED needs an incomplete classification because partial output may be present. OUTCOME_UNSPECIFIED and unknown values belong in a hold path under a strict route.

Keep HTTP exchange status and provider execution outcome in separate fields. Application validation disposition and downstream effect status also remain separate. An HTTP 200 can carry failed execution. An OUTCOME_OK result can fail the application's numeric or JSON contract. A valid answer can still be withheld by policy.

The per-route AI policies guide gives the named owner for output limits, accepted outcomes, and downstream permissions.

Output is untrusted data after provider execution

Treat the output string as untrusted model-tool data. It can contain terminal control characters, markup, or large repeated text. It can also contain CSV formulas, JSON-looking fragments, file paths, or prompt-derived secrets. Normalize line endings only if the evidence policy records that transformation. Strip or escape control characters for display while preserving a protected digest of the provider bytes.

Render output as text by default. A route that interprets JSON, CSV, Markdown, HTML, or an image reference needs a second parser with its own schema and size limits. Never route stdout into a shell, template engine, database query, or browser HTML sink because an outcome says OUTCOME_OK.

Google's guide says code execution output and generated code count toward token billing. It also documents a 30-second maximum runtime for code execution I/O and notes that execution errors can lead the model to regenerate code several times. Cap each part before logging, and keep regeneration attempts in order because each can return different code and output.

The safe idempotent LLM retries guide covers repeated HTTP operations. A retry can generate different code and output, so retain each attempt instead of overwriting the failed pair.

Response validation differs from sandbox security

This article addresses the HTTP response after Gemini has performed provider-side code execution. The gateway can validate generated-code fields, result fields, enum values, IDs, sizes, and delivery policy. It can also block an unacceptable response before that response reaches the authenticated caller.

Provider sandbox design is a separate security domain. The response fields do not reveal the full isolation model, host hardening, tenant separation, outbound network policy, patch state, or internal execution controls. A valid CodeExecutionResult offers no proof about those properties. Review Google's service documentation and contractual materials for provider execution assurance.

Local execution creates another boundary. If an application copies executableCode.code into its own Python process, notebook, container, CI runner, or agent tool, that new execution happens outside Gemini's returned result and outside a response-only validation control. It needs a separate authorization and sandbox policy.

Release fixtures should break each field

Build a controllable Gemini-compatible stub behind the deployed route. Return a valid PYTHON code part with a matching OUTCOME_OK result and bounded stdout. Then mutate one property at a time: missing code, unknown language, non-string output, missing outcome, unknown outcome, duplicate IDs, orphaned result ID, excessive output, and a deeply nested extra field.

Add OUTCOME_FAILED with mixed stderr and stdout, plus OUTCOME_DEADLINE_EXCEEDED with partial text. Confirm that neither enters a normal-success branch. Return OUTCOME_OK with output that fails the application's declared JSON schema and verify that provider success remains separate from application rejection.

Finally, include terminal escape sequences, HTML tags, a spreadsheet formula prefix, and a string that looks like a shell command. The UI should show escaped text inside the gray result card. No fixture should execute or render active markup. It should not trigger a downstream write.

DeepInspect

DeepInspect can inspect Gemini code-execution responses on authenticated user or agent HTTP traffic deliberately routed through its proxy. It can validate part shapes, language and outcome values, ID correlation, output limits, and route policy before delivery, then write a per-decision audit record tied to caller identity.

The application owns domain validation, local rendering, downstream effects, and any decision to execute returned code again. Google's provider sandbox, direct Gemini calls, local Python or notebook execution, STDIO tools, and traffic that bypasses the proxy remain outside DeepInspect's enforcement and evidence.

Book a technical deep dive at deepinspect.ai.

Frequently asked questions

Does OUTCOME_OK mean the final Gemini answer is correct?

OUTCOME_OK reports successful code execution. The application still validates the output shape and its relationship to the generated code and final answer. Any domain-specific acceptance rule also applies.

What should happen to OUTCOME_FAILED output?

Retain a bounded, access-controlled copy or digest under the route's evidence policy. Display a stable error state to the caller. Keep raw stderr or stdout out of metrics labels and ticket titles. Keep it out of public error bodies.

Can deadline-exceeded output be used?

Google's schema says partial output may be present. Treat it as incomplete. A route can expose it as diagnostic text, while structured workflows should withhold it unless their contract explicitly accepts partial results.

Must executableCode and codeExecutionResult always have IDs?

The current schema marks both IDs optional. When an executable code ID is present, the corresponding result ID should match it. Without IDs, retain ordered part positions and follow the documented contract for the API version in use.

Should generated Python be executed again inside the application?

The returned code is evidence of what Gemini generated. Running it locally creates a new execution event with a different trust boundary. Require explicit authorization, isolation, resource limits, and audit evidence for that separate action.

Does gateway validation secure Gemini's code sandbox?

Gateway validation controls the enterprise HTTP response boundary. Google's internal execution isolation and sandbox controls remain provider responsibilities and require their own assurance review.