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
Comprehensive error messages with stack traces for debugging failed executions.
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.
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.
Local Python execution treats
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 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.
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).
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):
The filesystem sandbox confines all reads and writes to these three roots and
refuses anything outside them. 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. - 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 response’scontinuation.next_start_byte. 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. - 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: Exception type, error message, and full stack trace for debugging.
- 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. - 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. - 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. Host paths outside those 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 - 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.
