Overview
Tool Name
Purpose
The code_executor_tools enable secure execution of Python code within Genesis Data Agents. Run dynamic calculations, data transformations, API integrations, and custom logic without pre-defined functions. Perfect for ad-hoc analysis, prototyping, data science workflows, and extending agent capabilities with custom code on-the-fly.Functions Available
execute_python_code: Run Python locally or on Snowflake Snowpark. For local execution, assign the final value to theresultvariable.create_env: Create a named managed environment for local or Snowpark execution.list_envs: List available managed environments.list_env_deps: Inspect the packages installed in one managed environment.update_env: Add or remove packages from an existing managed environment.delete_env: Delete a managed environment after explicit confirmation.run_repo_script: Run a server-pinned Pythonrequired_checkfor the active Blueprint phase and record platform-owned evidence.
Key Features
Secure Execution
Run code in isolated sandbox with resource limits and security constraints to prevent system abuse.
Rich Library Access
Standard/runtime libraries are available immediately, but local execution should not assume third-party packages are already installed. Use managed environments when you need extra dependencies.
Data Source Integration
Direct access to configured databases, file systems, and APIs within executed code.
File System Access
Read and write files to Git repositories and storage locations from within executed code.
Vault Secret Injection
Collect credentials with
get_web_content(action="ask_user_for_secret") and pass the returned vault names in secrets so values are injected as SECRET_<NAME> environment variables.Dynamic Variables
Pass variables into code execution and retrieve results for further processing.
Error Handling
Local exception details are subject to the output safety guard; when allowed, responses include a sanitized traceback.
Genesis injects
bot_id, thread_id, and user_id automatically for
execute_python_code. The parameter tables on this page list only the
user-supplied fields.Managed local environments
Whenexecute_python_code runs with the local executor, do not assume
third-party packages are preinstalled. Use the managed environment tools to
install and reuse dependencies outside the running code.
On container deployments where Genesis runs as root with the cortex_sandbox
user, named local environments are stored under
<GIT_PATH>/.genesis_runtime/python_envs, rather than bot storage. Genesis
migrates existing environments to this folder at startup. The environments
remain readable and runnable by sandboxed code, but only the root-owned server
can write them. On these deployments, keep the mounted Git workspace persistent;
see Genesis on Docker — volume mounts.
For direct API calls,
create_env declares a call_seconds budget of 720
seconds and update_env declares 660 seconds. Read the declared budget from
POST /api/tool_call/schema
and use it for the HTTP client’s read timeout; it is separate from the
execute_python_code timeout parameter.
For the API restriction that applies during package builds, see Requests from local agent code.
Each local run leads its own process session. When code exits, times out, or is
cancelled, Genesis stops the processes it left running in that session so they
do not outlive the run.
On Linux, Genesis also stops descendants that detach from the session with
setsid or a double fork, when those operations are available to the run. On
macOS, a process that leaves the session with setsid can outlive the run.
The local executor is unavailable when the Genesis server runs on Windows. In
that case, execute_python_code(executor="local") returns
success: false, unsupported_platform: true, and an error explaining that
its sandboxed child process requires POSIX file-descriptor passing and process
controls. Use a Genesis server running on macOS or Linux, or select
executor="snowpark" with a configured Snowflake connection.
run_repo_script
Use run_repo_script when the active Blueprint phase declares a
required_check exit criterion. The platform resolves the check’s script path
and SHA-256 from the server-owned snapshot captured when the mission started,
refuses execution if the repository bytes do not match that hash, and records
the observed exit code as durable provenance for the phase gate.
Use the proposal path only after trying the check and confirming it cannot pass, not as a shortcut for fixing a failing check. Genesis records the proposal and returns
goal_question; copy it unchanged into questions_for_person and end the turn with AWAITING_INPUT. The card offers Waive this check and Keep it required. Only the person’s own answer can record the waiver. The proposal is refused if the check passed, was already waived, is satisfied by a person’s valid acceptance of an undecided Prover result, has not run, or any named Prover run finished after the check’s latest run.
sys.exit() and sys.exit(0) as clean
completion. For run_repo_script, Genesis reports success: true when the
observed exit code matches the phase’s expected code, including a matching
non-zero code. See required check exit criteria
for how to configure that code.
The script runs with a scratch working directory. Read mission files through
the GENESIS_MISSION_REPO_PATH environment variable, which contains the
mission repository’s absolute path. The script must be a valid UTF-8 Python
file from that repository and is limited to 256 KB. Genesis applies the same
safety judges used by local execute_python_code when required, runs the
verified bytes, and records the result consumed by EXIT_PHASE.
The script also receives GENESIS_CHECK_NAME, set to the check name from the
active phase snapshot. Imports of installed packages remain allowed. A check may
also import a blueprint-declared, hash-pinned utility library by its declared
name; Genesis verifies and safety-reviews its source on each run and serves the
verified source from memory. Changes to that library refuse the check. Other
imports that resolve to Python code in the mission repository or scratch area
remain refused because that code is not covered by a pin. See Shared libraries
for required checks
for how to declare libraries from the mission repository or a registered managed
source at a pinned commit.
For this pinned required-check path, the safety review permits reading files under
the mission repository as data, including source files such as .py, .ipynb, and
.sql; parsing their contents is allowed. It does not permit importing, compiling,
or executing those files. This exception does not apply to local
execute_python_code, whose source-file restrictions are described below; path
scope and sensitive-file restrictions still apply to required checks.
For local required-check execution, a phase that captured entry context also
provides REQUIRED_CHECK_CONTEXT from genesis. It is a read-only snapshot with
blueprint_inputs, mission_thread_id, and phase_entered_at; nested objects
are immutable too. It is None when the active check has no captured context.
The context is supplied by the server, not by code-execution arguments or
environment variables. Snowpark execution does not provide this local-check
context.
required_check.
When a safety preflight or postflight refuses a required-check execution, the response identifies its
check_name and script_sha256, sets required_check_blocked: true, and gives
recovery guidance in safety_guidance. A hash pin verifies integrity, not safety
approval; workspace execution controls do not override a safety-judge denial. Do
not retry identical judge-denied code to seek a different verdict. Have an
operator review the response and, if appropriate, record a reasoned waiver in
Required checks on the Mission page.
For
executor="local", keep the submitted entry point inline with code=....
script_path is rejected, and local code must not read source files or load,
import, compile, or execute code from local files. Native open() may read
task-owned documents and data in the task’s own repository or scratch area
under BOT_GIT_PATH, BOT_REPOS_PATH, or BOT_SCRATCH_PATH; source-code
files remain disallowed. Other threads’ uploads, environment, credential, or
secret files, and .git internals are also disallowed regardless of file
suffix. Local preflight still rejects obvious sandbox-escape, host-probing,
and native/FFI bridge patterns.
Local execution runs in a fixed subprocess child runner with
BOT_SCRATCH_PATH as the working directory and temp root. Import workspace
roots with from genesis import BOT_GIT_PATH, BOT_REPOS_PATH, BOT_SCRATCH_PATH, sanitize_path to read or write permitted task files under
those roots (including the repo working tree at BOT_REPOS_PATH). Genesis
also copies a managed child_runner.py into scratch before each run. Use
executor="snowpark" when you need file-backed code execution.Local preflight checks Python syntax and AST structure rather than matching
policy terms in raw text. This avoids rejecting comments, ordinary prose
strings, regular-expression patterns, or unrelated attribute calls for rules
aimed at executable constructs. The scan resolves module-scope aliases and
direct function rebindings before classification, so restricted calls remain
blocked when reached through imports or aliases; forbidden-module imports are
rejected in any scope. When a construct is rejected, safety_guidance
identifies its blocked_rule, the matched_code, and matched_line; code
that does not parse is rejected with block_reason_code: "syntax_error".
Safety-judge denials also include a fixed, actionable safety_guidance.reason
selected by denial category, rather than the judge’s free-form explanation.Snowpark requires a live Snowflake connection. On SQLite-metadata deployments
(SNOWFLAKE_METADATA=FALSE), Snowpark calls that resolve to the default
connection_id="Snowflake" fail fast with error_code: STAGE_REQUIRES_SNOWFLAKE_CONNECTION before opening a session — add a saved
Snowflake connection and pass its id, or use executor="local". When an
administrator has hidden the virtual System Snowflake connection, Snowpark
calls that target it return success: false with type: connection_disabled;
use a user-created Snowflake connection instead.When stage setup fails because the Snowflake session has no current database,
Snowpark returns error_code: CONNECTION_DATABASE_UNAVAILABLE with the
configured database and schema from the connection. Fix the connection’s
database/schema in Config → Connections, grant the role USAGE on that
database, or pass a different connection_id.See Snowflake attribution.When a request or returned error mentions
boto3, AWS SDK work,
EKS/Kubernetes, Helm, kubectl, AWS CLI, cloud deployment, or cloud
monitoring, execute_python_code can return agent_reminders,
sandbox_tools_recommended, and sandbox_tools_reference to steer the task
toward sandbox_action on a remote backend such as eks or k8s instead
of retrying inside the Genesis application container.Genesis SDK in local execution
When the local executor injects runtime credentials, inline Python can import the governedgenesis_sdk client instead of reaching into backend internals:
genesis_sdk ships inside the Genesis runtime image at /app/genesis_sdk
(it is not a PyPI package). Do not call
create_env(deps=['genesis-sdk']), create_env(deps=['genesis_sdk']),
update_env(add_packages=['genesis-sdk']), or
update_env(add_packages=['genesis_sdk']) — the similarly named public
PyPI package is unrelated and will not satisfy
from genesis_sdk import Genesis. If the import fails on a deployed
Genesis runtime, treat it as a deployment/packaging regression and file a
CLI ticket rather than attempting to install a workaround.Genesis.from_environment() reads GENESIS_API_BASE_URL plus either
GENESIS_RUNTIME_TOKEN (managed local execution) or GENESIS_API_TOKEN
(external PAT mode).
For managed local execution, the executor passes its reviewed runtime
environment and explicitly requested secrets to the subprocess; other server
environment variables, including provider credentials and the internal service
token, are not inherited. The runtime token’s API boundaries are described in
Local agent-run API access.
To give someone a file created in Python, request a link as you write it, or
create one later for a file already in the default scratch folder:
download_link exactly, including its brackets, so Genesis Chat
renders a download button. The link is limited to people who can open the
current thread. Files larger than 100 MB, and files outside the default
BOT_SCRATCH_PATH, return download_link_error instead. In Slack, pass the
same link to _slack_reply(files=[...]) to attach it.
Inline code executes as a plain module from top to bottom. Its returned value
is the top-level result variable. function_name and args are only valid
with script_path; passing either with inline code is rejected. To invoke a
function from inline code, call it in the module and assign the result yourself.
For a custom-scanner launcher, the active scan session id is available as
from genesis import scan_id; outside a scan launcher, scan_id is None.
Prefer these SDK surfaces before a generic tool bridge:
gx.capabilities()gx.query.rows(...)andgx.query.df(...)gx.tools.list(),gx.tools.schema(name), andgx.tools.call(name, args)gx.artifacts.write_text(...),write_json(...),write_csv(...),write_bytes(...),read_text(...),read_json(...),read_bytes(...),list(...),exists(...), anddelete(...)gx.progress.message(...),update(...),complete(...),fail(...), andartifact(...)
For binary artifacts (zip, image, parquet, sqlite, etc.), prefer
gx.artifacts.write_bytes and read_bytes, which handle bytes natively. If
you must move binary content through the file tool via
gx.tools.call("file", ...), read with return_base64=True, then write with
content=<base64> and is_base64=True so the tool decodes before
writing. Writing a base64 string without is_base64=True stores the literal
text and corrupts the file.gx.progress.* emits structured runtime events instead of relying on stdout.
Successful and failed execute_python_code responses can return those events
under progress_events, which makes multi-step Python workflows easier to
inspect.Workspace files (local execution)
To read and write files under the bot’s git repo or scratch area, import the workspace roots from thegenesis module (not os.environ):
In every mode, the runner’s in-process guard refuses writes outside
BOT_GIT_PATH, BOT_REPOS_PATH and BOT_SCRATCH_PATH, and the advisory pre-run review may refuse such code before it runs. On a non-root server, security.code_isolation defaults to off, which runs code as the server’s own user without the kernel layer. Set it to confine to use Landlock and seccomp on supported Linux hosts; code can write only to its scratch directory, while the rest of BOT_GIT_PATH and BOT_REPOS_PATH is read-only. In this mode, files in the bot repositories and scratch cannot be launched as executables, and agent code cannot start child processes (including shell commands); threads remain available. If the host cannot enforce confinement, execution is refused. The former auto value is read as off; any other unrecognized value resolves to confine. Set the GENESIS__SECURITY__CODE_ISOLATION deployment override so a stored value cannot switch confinement off. Root deployments drop privileges to the separate cortex_sandbox user. On a root server with Landlock support, execute_python_code is confined regardless of this setting and retains repository write access except in .git folders. When a .git link or gitfile redirects to metadata inside a granted workspace, confinement also withholds whole-directory write grants from directories leading to that metadata; file grants are evaluated separately, and directory operations such as renaming those paths may be denied. If Landlock is unavailable, confine refuses execution while off runs as cortex_sandbox without kernel confinement. At startup, supported hosts run a confined self-test that imports common packages, writes scratch, reads a granted file, and verifies a blocked file is denied. The resulting level is full (namespaces, Landlock and seccomp), landlock_only (Landlock and seccomp), or none when no kernel-isolation level passes. If the startup namespace probe times out or cannot start, Genesis treats the result as inconclusive rather than a refusal and clears it so a later run probes again. When the no-namespace Landlock/seccomp self-test passes in that case, startup reports landlock_only. If launcher refuses a run before its code starts while using namespaces, Genesis retries once without namespaces, regardless of code size; when the retry reaches the runner, Genesis records the namespace layer as unavailable and lowers the level when appropriate. Code that has started is never retried. For the install’s current status and degraded-surface threshold handling, see the admin Code Isolation card.
For root deployments with the cortex_sandbox user, dashboard renders and Databricks App execute_python_code workers are also confined when kernel support is available; the launcher drops to that user before confinement. If kernel confinement is unavailable, confine refuses these runs while off keeps their prior unconfined sandbox-user behavior.
Each local execute_python_code run checks what the current executor policy exposes beyond the caller’s grants. security.run_grants defaults to shadow, which logs paths those grants would refuse without changing execution; enforce locks those folders against access. Without a rebuilt namespace view, refused folders remain visible in directory listings. When namespace isolation is active and Genesis can build a grant-based view, it rebuilds the BOT_REPOS_PATH/repos folder from the run’s grants: granted folders are mounted into the view, while other entries are locked and their contents are unavailable. A grant path reached through a link is omitted from the view and remains denied by Landlock; this does not disable the namespace layer. The rebuilt folder is listable only when refused contents can be safely hidden; locked entry names may still appear in listings. If the run reaches a refused folder, its response includes access_denials and access_denial_messages, even when the code catches the access error. The messages identify the folder and explain who can share it or what to do if sharing cannot resolve the refusal. Under enforcement, the run does not start if its grants cannot be determined or its scratch folder is refused. See the Configuration Reference for modes and the deployment override.
Use native open() for repo working-tree
files; use gx.artifacts for artifact-store outputs.
sanitize_path(p) rewrites an absolute workspace path to its BOT_*_PATH
shorthand so results stay host-agnostic. It also rewrites absolute paths from
the interpreter installation in tracebacks and diagnostics to PYTHON_ROOT;
the active managed-environment name remains visible when applicable. When
reporting where a file went, prefer repo-relative form (repo_id plus path) or
sanitize_path(p) instead of absolute host paths. If you return absolute
workspace paths without sanitizing, the executor rewrites them for you and sets
paths_sanitized: true on the response with a short notice.
Input Parameters for Each Function
python_exec
Parameters
Use Cases
- Ad-Hoc Data Analysis Perform quick calculations, statistical analysis, or data exploration without creating permanent functions or scripts.
- Data Transformation Execute custom transformation logic on datasets that does not fit into standard SQL or built-in functions.
- API Integration Make HTTP requests, parse responses, and integrate with external APIs dynamically based on user requirements.
- Prototyping & Testing Test algorithms, validate assumptions, or prototype solutions before implementing them as permanent features.
- Custom Business Logic Implement organization-specific calculations, rules, or validations that vary by use case or customer.
Workflow/How It Works
-
Step 1: Simple Calculation
Execute basic Python for quick results:
-
Step 2: Data Analysis with Pandas
Analyze data using pre-loaded libraries:
-
Step 3: Pass Variables from Context
Use data from previous operations:
-
Step 4: API Integration
Make external API calls and process responses:
-
Step 5: File Operations
Read and write files within execution:
-
Step 6: Complex Data Processing
Implement multi-step algorithms:
Integration Relevance
- data_connector_tools to fetch data from databases, then process with custom Python code.
- file tools to read/write files before or after code execution.
- github_connector_tools / git_and_file_tools (
git_action, for GitLab) to version control generated scripts. - image_tools to process images or generate visualizations from code execution results.
- web_access_tools to fetch data via HTTP within executed code.
- project_manager_tools to execute custom code as part of automated mission tasks.
Configuration Details
- Execution Environment: Python 3.9+ with isolated namespace per execution.
- Pre-loaded Libraries: pandas, numpy, requests, json, datetime, os, sys, re, math, statistics.
- Resource Limits: Local execution time limit (default 10s, max 600s), address-space cap
1,073,741,824bytes, max file size52,428,800bytes, max128open files, and max8processes. - File System Access: Reads and writes are confined to
BOT_GIT_PATH,BOT_REPOS_PATH, andBOT_SCRATCH_PATH(import viafrom genesis import ...). Local execution may read task-owned documents and data in the task’s own repository or scratch area, but not source-code files or sensitive files such as other threads’ uploads, credentials, secrets, or.gitinternals. Local runs start inBOT_SCRATCH_PATH, which is also the temp root. You may write into the repo working tree underBOT_REPOS_PATHas well as scratch. Genesis stages a managedchild_runner.pyin scratch for each local run. Absolute workspace paths in responses are rewritten toBOT_*_PATHshorthands, and interpreter-installation paths toPYTHON_ROOT, before they reach the agent. - Network Access: HTTP/HTTPS requests allowed; other protocols restricted.
- Security Mode: Blocks process creation, native library / FFI loading, dangerous filesystem probes, and other common sandbox-escape patterns. This is defense in depth, not a kernel-enforced boundary.
- Return Value: Can return primitive types, dictionaries, lists, or serializable objects.
Limitations or Notes
- Execution Timeout: Local execution defaults to 10 seconds and can run for up to 600 seconds (10 minutes). Long-running operations may be terminated once the timeout is reached.
-
Memory Limits: Default address-space cap is
1,073,741,824bytes (~1 GB). Large dataset operations may exceed limits and fail. - No Subprocess: Cannot spawn subprocesses, fork, or execute shell commands from local execution.
-
No Native / FFI Loads: Native library loading and common FFI bridges such as
ctypesandcffiare blocked in local execution. -
Managed Dependencies: Do not install packages from inside the running code. For local execution, create or update a named environment first, then rerun with
env="<name>". -
Local Inline Entry Point: Local execution must use inline
code;script_pathis rejected, and local code cannot load or execute code from files. Use Snowpark for file-backed code execution. - Network Limitations: Only HTTP/HTTPS allowed; no raw socket access or other protocols.
-
File System Scope: Reads and writes are confined to
BOT_GIT_PATH,BOT_REPOS_PATH, andBOT_SCRATCH_PATH(fromfrom genesis import ...); task-owned documents and data may be read, but source-code and sensitive files are disallowed, and the sandbox refuses paths outside those roots. Low-level file descriptor access is blocked, and path-based operations such asos.rename,os.replace,os.link,os.symlink,os.readlink,os.access,os.chmod,os.truncate, andos.utimeare enforced against the same allowed-path rules. Callsanitize_path(p)when returning file locations so output stays host-agnostic. For runs associated with a person, Genesis also blocks Python from reading or listing Foundry connection crawl folders that person is not allowed to access. Only people who can see a connection, or who manage every connection, may read its crawl; Python cannot modify or remove a restricted crawl folder either. If Genesis cannot determine which crawls are outside the person’s access, it refuses to start the run. This per-person restriction does not apply to runs without an associated person. - Serialization: Return values must be JSON-serializable or primitive types.
- State Persistence: Each execution is isolated; no state persists between calls.
-
Large Responses: When the serialized
execute_python_coderesponse exceeds the inline Python budget (default98,304bytes / 96 KB, configurable withGENESIS_TOOL_OUTPUT_PYTHON_BUDGET), Genesis returns a capped envelope withtool_output_capped,preview,truncation_info,full_output_ref, andagent_guidanceinstead of the full inline payload.
next_steps with remediation guidance. Rule ids include
dynamic_code_execution, builtins_access, sandbox_introspection,
process_spawn, native_ffi, account_enum, escape_probe, fs_probe,
syntax_error, and workspace_source_unreadable. For an fs_probe refusal,
spell the allowed root directly using from genesis import BOT_SCRATCH_PATH
or genesis.BOT_SCRATCH_PATH, or use os.environ["BOT_SCRATCH_PATH"]; wrappers
such as Path(...), str(...), os.path.join, / "subdir", .joinpath(...),
and f-strings remain supported when the root is statically provable. A caller-
supplied path, rebound root, or untraceable variable remains refused even if it
happens to point inside an allowed workspace.
Supported Operations
✅ Basic Python operations - Variables, functions, loops, conditionals✅ Data manipulation - pandas DataFrames, numpy arrays, list/dict operations
✅ File I/O - Read/write text and binary files in workspace
✅ HTTP requests - GET, POST, PUT, DELETE with requests library
✅ JSON/CSV processing - Parse and generate structured data formats
✅ Date/time calculations - datetime, timedelta operations
✅ Regular expressions - Pattern matching and text processing
✅ Mathematical operations - Statistics, linear algebra, calculations
✅ String manipulation - Formatting, parsing, encoding
✅ Exception handling - Try/except blocks and error recovery
Not Supported
❌ Installing new packages withpip during execution. Use create_env / update_env outside the running code instead.❌ Subprocess execution, shell launches, or process forking (
subprocess, os.system, pty, etc.)❌ Native library / FFI loading (
ctypes, cffi, similar bridges)❌ Disk-backed local execution via
script_path or by loading additional local Python files❌ System file access outside the allowed repo/workspace and runtime import paths
❌ Database connections (use data_connector_tools instead)
❌ Multi-threading or multiprocessing
❌ Raw socket programming
❌ Modifying Python environment or interpreter
❌ Accessing arbitrary host environment variables (except values explicitly injected by Genesis, such as managed scratch paths or secrets passed through
secrets)❌ Infinite loops (terminated by timeout)
❌ Heavy machine learning model training (use dedicated tools)
Output
- Success: Execution result with returned variable(s), stdout output, and execution time.
- Variables: Dictionary of all variables in execution context (unless specific return_var specified).
- Standard Output: Captured print statements and logging output. For local execution,
stdoutandstderrare each capped at200,000characters; larger streams are truncated with... [truncated]before the normal inline response budget is applied. - Capped Oversized Output:
truncation_infoincludesbucket,bytes_in,bytes_out,budget_bytes, andspill_path. Whenfull_output_refis notnull, the full output is saved undertruncated_tool_outputs/<thread_id>/...in theappsBotGit repo and can be paged back withfile(action="read", file_path=full_output_ref, repo_id="apps", start_byte=0, max_bytes=N), continuing from each read response’scontinuation.next_start_byte. For an initial capped response,next_start_bytemarks where its preview ends in the saved copy; use it as the firststart_byteto continue after that preview. The byte range is the read shape that returns the saved copy exactly as written; the whole-file and line-window paths read in text mode and rewrite line endings. - The accompanying
agent_guidanceexplains that oversized output is routinely stored this way, is not a context limit or an error, and can be read back from the spill path without data loss. If saving the spill copy fails, it instead says that no spill file is available and recommends rerunning with narrower parameters. After a thread has received a full recovery notice with a saved copy, later truncation notices in that thread use a shorter form with the same recovery path.notice_formreportsfullorcompact. - Truncation record: Over-budget JSON objects are shrunk in place when possible:
every key at every depth is preserved, and trailing elements are removed from the
longest lists first. The returned object includes
tool_output_truncationwithtruncated,truncation_basis,truncated_keys,bytes_before,bytes_after,full_output_ref, andagent_guidance. For each shortened list,truncated_keysreports its JSON key path as an array plus thekeptandtotalelement counts. This means a missing key was not silently dropped by the cap; only reported list elements may be absent. The governor measures candidate payloads against the configured byte budget and keeps as many list elements as fit; the result is not decided by a fixed count of restoration attempts. Usebytes_afterand each entry’skept/totalcounts to see the actual delivered size and what was omitted. - Amended next step: When a shrunk object carries a
nextcall shape (averbplus a stringwhy— the directive the tool computed over the whole result), the shortening is stated at the front ofwhy: which lists were shortened with theirkept/totalcounts, and the way to the rest (thefull_output_refpath with thefile(action="read", ...)call that reads it, or advice to narrow the call when no spill copy was saved).verb,argsand the tool’s own sentence are preserved. Anextthat is not a call shape is left untouched. - Tail-cut fallback: Non-object payloads and objects that cannot be shrunk under
the budget keep the capped envelope (
tool_output_capped,preview,truncation_info,full_output_ref, andagent_guidance) and also include the sametool_output_truncationrecord. Itstruncation_basisidentifies why the fallback was used (not_an_object,object_irreducible,record_key_in_use,serialized_key_collision, orstructure_unwalkable), and a compact copy of the record’s measurements is appended on a trailer line inpreviewwhen that trailer fits within the budget. - Execution Time: Time taken to execute code in seconds.
- Errors: When the output safety guard allows a local Python exception response, it includes the exception type and message; when traceback frames are present, runner frames and source lines are omitted, and installed-library paths use
<python>,<site-packages>, or<library>placeholders. When the guard withholds output, the response gives a fixed failure headline without the exception message and keeps raw stdout and stderr empty. To diagnose a withheld failure, catch the exception and return its type and a short, non-sensitive description inresult. - Local Failure Metadata: Failed local runs can also include
status,error_type,policy_violations, andmetrics.error_typeis the reported exception class name.statusis one ofuser_error,policy_denied,resource_limit, orinternal_error.metricsincludeswall_ms,cpu_ms,peak_rss_bytes,applied_limits, andskipped_limits. - Kernel Confinement: When a run has denied folders, the response includes
kernel_confined:truewhen kernel confinement is active, orfalsewhen those folders are withheld only by the runner’s in-process guards. - Safety-Judge Denials: A request denied by the local safety judge includes a fixed, actionable
safety_guidance.reasoninstead of the judge’s free-form explanation.judge_reason_codeidentifies the category:OUTSIDE_ROOTS,SOURCE_READ,CODE_EXEC_FROM_FILE,PROCESS_OR_ESCAPE,NATIVE_BYPASS,HOST_PROBE,NETWORK,SENSITIVE_FILE, orOTHER.NETWORKindicates code tried to open a socket, HTTP, or database connection to a private, internal, or Outpost-routed host; use a Genesis connection to reach that system instead. - Safety-Judge Unavailable: If the local safety judge fails or returns no decision,
safety_guidanceidentifies this as an outage. For a request-side failure, the code does not run; for an output-side failure, the code has already run and its output is withheld, so do not retry it because its side effects may have happened. Operators can check the active provider’s model assignments and the server log’s sanitizedjudge_errordiagnostic. - Path Sanitization: When a response contains absolute workspace paths, the local executor rewrites them to
BOT_GIT_PATH/BOT_REPOS_PATH/BOT_SCRATCH_PATHshorthands and may setpaths_sanitized: truewith anoticesuggestingsanitize_path(p)for future runs. - Run-grant Denials: Local execution responses include
access_denialsandaccess_denial_messagesfor up to 20 refused folders the code reached. The messages state whether access was denied or would be denied under enforcement, name the folder, and give the sharing or next-step guidance; relay each message as written. - AWS/EKS Sandbox Guidance: When the request or response mentions
boto3, AWS SDK work, EKS/Kubernetes, Helm,kubectl, AWS CLI, cloud deployment, or cloud monitoring, Genesis can addagent_reminders,sandbox_tools_recommended, andsandbox_tools_referenceto recommendsandbox_actionplus theaws-eks-sandbox-operationsskill. - Warnings: Any resource warnings (approaching timeout, high memory usage).
Best Practices
Small & Focused
Keep code blocks focused on single tasks. Break complex operations into multiple executions.
Error Handling
Always use try/except blocks for operations that might fail (API calls, file I/O, parsing).
Resource Awareness
Monitor execution time and memory usage. Use sampling for large datasets.
Data Validation
Validate input data and function parameters before processing to avoid runtime errors.
Logging
Use print statements to track execution progress and debug issues.
Return Values
Always assign results to variables for retrieval. Do not rely solely on print output.
Example: Complete Data Analysis Workflow
Advanced Features
Statistical Analysis
Text Processing
Data Validation
API Pagination Handler
Troubleshooting
Execution Timeout
Execution Timeout
- Reduce dataset size or use sampling
- Optimize algorithms (vectorize operations with numpy/pandas)
- Increase timeout parameter (up to 600 seconds for local execution)
- Break into smaller execution steps
- Use generators or lazy evaluation for large data
Memory Error
Memory Error
- Process data in chunks instead of loading all at once
- Use pandas iterator options (chunksize parameter)
- Delete large intermediate variables with del variable
- Use more memory-efficient data types (int8 vs int64)
- Consider using data_connector_tools for heavy processing
Import Error - Module Not Found
Import Error - Module Not Found
- If you are using local execution, create a named environment with
create_env(name=..., deps=[...]). - If the environment already exists, inspect it with
list_env_deps(venv=...)and add missing packages withupdate_env(name=..., add_packages=[...]). - Reuse that same environment name with
execute_python_code(..., env=...). - If managed package installation is unavailable in the current runtime, continue with a stdlib-only approach or switch to Snowpark with approval.
- Exception —
genesis_sdk: the Genesis SDK is provided by the Genesis runtime image itself (/app/genesis_sdk), not by PyPI. Do not callcreate_env(deps=['genesis-sdk']),create_env(deps=['genesis_sdk']),update_env(add_packages=['genesis-sdk']), orupdate_env(add_packages=['genesis_sdk'])— the public PyPI packages of those names are unrelated and will not satisfyfrom genesis_sdk import Genesis. If the import fails on a deployed Genesis runtime, that is a deployment/packaging regression — report it (file a CLI ticket) rather than attempting to install a workaround.
File Not Found
File Not Found
- Build paths from
from genesis import BOT_GIT_PATH, BOT_REPOS_PATH, BOT_SCRATCH_PATH - Use
f"{BOT_REPOS_PATH}/<repo_id>/..."for repo working-tree files - Check file exists using
os.path.exists()on a path rooted at one of the workspace globals - Ensure file was created in a previous step under the same root
- Writes outside
BOT_GIT_PATH,BOT_REPOS_PATH, orBOT_SCRATCH_PATHare refused by the sandbox
Serialization Error on Return
Serialization Error on Return
- Convert numpy arrays to lists: array.tolist()
- Convert pandas DataFrames to dicts: df.to_dict()
- Use float() for numpy float types
- Use int() for numpy integer types
- Convert datetime to ISO strings: dt.isoformat()
API Request Failed
API Request Failed
- Check internet connectivity (if applicable)
- Verify API endpoint URL is correct
- Check authentication credentials
- Add error handling with try/except
- Check for rate limiting and add delays
- Verify API response format matches expectations
Syntax Error in Code
Syntax Error in Code
- Check for proper indentation (use 4 spaces)
- Verify quotes are properly closed
- Check for balanced parentheses/brackets
- Test code in local Python environment first
- Use syntax highlighter to identify issues
Snowpark Connection or Stage Errors
Snowpark Connection or Stage Errors
STAGE_REQUIRES_SNOWFLAKE_CONNECTION: the deployment metadata store is not Snowflake — pass a saved Snowflakeconnection_idor useexecutor="local"CONNECTION_DATABASE_UNAVAILABLE: the connection’s configured database is missing or the role lacksUSAGE— setdatabaseandschemaon the connection and grant access, or choose a differentconnection_idtype: connection_disabled: the SystemSnowflakeconnection is hidden — use a user-created Snowflake connection id instead of the default
Security Considerations
Sandbox Protections
The code executor implements multiple security layers:- Restricted Imports: Blocks process-launch and native/FFI escape paths in local execution, including common modules used for host probing
- File System Isolation: Reads and writes are confined to
BOT_GIT_PATH,BOT_REPOS_PATH, andBOT_SCRATCH_PATH; task-owned documents and data may be read, but source-code and sensitive-file reads are blocked even under those roots. Connection-scoped crawl folders the requesting person cannot see are hidden; a run with no person cannot read any connection crawl folder, except a live bundled Foundry scan reading its own crawl. Host paths outside allowed roots are refused. Responses sanitize absolute workspace paths toBOT_*_PATHshorthands - Process Blocking: Local execution blocks subprocesses, forks, shell launches, and related process-creation APIs
- Native Library Blocking: Local execution blocks
ctypes,cffi, and similar native loading paths. Native extension modules from run-writable repository or scratch locations are refused; installed package extensions remain available. Sub-interpreters and CPython test escape modules are also refused - Network Filtering: Only HTTP/HTTPS; no raw sockets or other protocols
- Resource Limits: CPU time and memory caps prevent denial-of-service
- Namespace Isolation: Each execution has isolated variable scope
- No Privilege Escalation: Sensitive shell/user environment variables are scrubbed before privilege-drop execution, and the local hardening is defense in depth rather than full kernel-enforced isolation
execute_python_code and package installs
use the confinement configured for that deployment; see Deploying Genesis on Databricks.
Safe Coding Practices
Input Validation
Validate and sanitize all user inputs before using them in code execution.
Error Containment
Use try/except blocks to prevent error propagation and information leakage.
Resource Monitoring
Monitor execution time and memory usage. Set appropriate timeouts.
Audit Logging
Genesis records code executions and local safety-guard decisions with
runtime context, including
bot_id, thread_id, and user_id, for
security auditing.
