Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions crates/bashkit-python/bashkit/_bashkit.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,9 @@ class Bash:
max_commands: Limit total commands executed.
max_loop_iterations: Limit iterations per loop.
max_memory: Memory limit in bytes for the VFS.
timeout_seconds: Abort execution after this duration.
timeout_seconds: Abort execution after this duration. Also the time
limit of each embedded ``python3`` run (profile default: 30 s,
Hardened 10 s).
python: Enable embedded Python (``python3`` builtin).
sqlite: Enable embedded SQLite (``sqlite``/``sqlite3`` builtin).
Defaults to ``False``. When ``True``, the Turso-backed engine
Expand Down Expand Up @@ -1204,7 +1206,9 @@ class BashTool:
max_commands: Limit total commands executed.
max_loop_iterations: Limit iterations per loop.
max_memory: Memory limit in bytes for the VFS.
timeout_seconds: Abort execution after this duration.
timeout_seconds: Abort execution after this duration. Also the time
limit of each embedded ``python3``/``ts`` run (profile default:
30 s, Hardened 10 s).
files: Dict mapping VFS paths to file contents or lazy callables.
mounts: List of real host directory mount configs.
allowed_mount_paths: Host path prefixes allowed for real filesystem
Expand Down
74 changes: 56 additions & 18 deletions crates/bashkit-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4748,6 +4748,30 @@ fn prepare_runtime_external_handler(
.map(Some)
}

/// Embedded Python limits from the profile, with `timeout` as each run's cap.
///
/// Decision: `timeout_seconds` also sets the runtimes' own time limit, see
/// knowledge/runtimes/python-package.md#embedded-tool-runtimes.
fn python_limits(profile: &bashkit::ExecutionProfile, timeout: Option<Duration>) -> PythonLimits {
let limits = profile.python_limits().clone();
match timeout {
Some(timeout) => limits.max_duration(timeout),
None => limits,
}
}

/// Embedded TypeScript limits; see [`python_limits`].
fn typescript_limits(
profile: &bashkit::ExecutionProfile,
timeout: Option<Duration>,
) -> bashkit::TypeScriptLimits {
let limits = profile.typescript_limits().clone();
match timeout {
Some(timeout) => limits.max_duration(timeout),
None => limits,
}
}

/// Apply python/external_handler configuration to a `BashBuilder`.
///
/// Centralises the logic shared between `new()` and `reset()`.
Expand Down Expand Up @@ -4956,6 +4980,10 @@ impl PyBash {
}
}

let timeout = self
.timeout_seconds
.map(parse_timeout_seconds)
.transpose()?;
let mut limits = profile.execution_limits().clone();
if let Some(max_commands) = self.max_commands {
limits = limits.max_commands(usize::try_from(max_commands).unwrap_or(usize::MAX));
Expand All @@ -4964,8 +4992,8 @@ impl PyBash {
limits = limits
.max_loop_iterations(usize::try_from(max_loop_iterations).unwrap_or(usize::MAX));
}
if let Some(timeout_seconds) = self.timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(timeout_seconds)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand All @@ -4977,7 +5005,7 @@ impl PyBash {
builder = apply_python_config(
builder,
self.python,
profile.python_limits().clone(),
python_limits(&profile, timeout),
self.external_functions.clone(),
handler_clone,
);
Expand Down Expand Up @@ -5073,15 +5101,16 @@ impl PyBash {
}
}

let timeout = timeout_seconds.map(parse_timeout_seconds).transpose()?;
let mut limits = core_profile.execution_limits().clone();
if let Some(mc) = max_commands {
limits = limits.max_commands(usize::try_from(mc).unwrap_or(usize::MAX));
}
if let Some(mli) = max_loop_iterations {
limits = limits.max_loop_iterations(usize::try_from(mli).unwrap_or(usize::MAX));
}
if let Some(ts) = timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(ts)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand All @@ -5108,7 +5137,7 @@ impl PyBash {
builder = apply_python_config(
builder,
python,
core_profile.python_limits().clone(),
python_limits(&core_profile, timeout),
fn_names,
handler_for_build,
);
Expand Down Expand Up @@ -6112,26 +6141,32 @@ impl BashTool {
fn build_live_builder(&self, py: Python<'_>) -> PyResult<bashkit::BashBuilder> {
let profile = self.profile.core();
let mut builder = Bash::builder().profile(profile.clone());
let timeout = self
.timeout_seconds
.map(parse_timeout_seconds)
.transpose()?;
if self.python {
let limits = python_limits(&profile, timeout);
if let Some(handler) = &self.external_handler {
builder = builder.python_with_external_handler(
profile.python_limits().clone(),
limits,
self.external_functions.clone(),
make_external_handler_native(py, handler),
);
} else {
builder = builder.python();
builder = builder.python_with_limits(limits);
}
}
if self.typescript {
let limits = typescript_limits(&profile, timeout);
if let Some(handler) = &self.typescript_external_handler {
builder = builder.typescript_with_external_handler(
profile.typescript_limits().clone(),
limits,
self.typescript_external_functions.clone(),
make_typescript_external_handler_native(py, handler),
);
} else {
builder = builder.typescript();
builder = builder.typescript_with_limits(limits);
}
}

Expand All @@ -6158,8 +6193,8 @@ impl BashTool {
limits = limits
.max_loop_iterations(usize::try_from(max_loop_iterations).unwrap_or(usize::MAX));
}
if let Some(timeout_seconds) = self.timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(timeout_seconds)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand Down Expand Up @@ -6294,6 +6329,7 @@ impl BashTool {
) -> PyResult<Self> {
let core_profile = profile.core();
let mut builder = Bash::builder().profile(core_profile.clone());
let timeout = timeout_seconds.map(parse_timeout_seconds).transpose()?;
let fn_names = external_functions.unwrap_or_default();
let external_handler_reentry_guard = ExternalHandlerReentryGuard::new(
py,
Expand All @@ -6307,14 +6343,15 @@ impl BashTool {
&external_handler_reentry_guard,
)?;
if python {
let limits = python_limits(&core_profile, timeout);
if let Some(handler) = &external_handler {
builder = builder.python_with_external_handler(
core_profile.python_limits().clone(),
limits,
fn_names.clone(),
make_external_handler_native(py, handler),
);
} else {
builder = builder.python();
builder = builder.python_with_limits(limits);
}
}
let ts_fn_names = typescript_external_functions.unwrap_or_default();
Expand All @@ -6328,14 +6365,15 @@ impl BashTool {
"typescript_external",
)?;
if typescript {
let limits = typescript_limits(&core_profile, timeout);
if let Some(handler) = &typescript_external_handler {
builder = builder.typescript_with_external_handler(
core_profile.typescript_limits().clone(),
limits,
ts_fn_names.clone(),
make_typescript_external_handler_native(py, handler),
);
} else {
builder = builder.typescript();
builder = builder.typescript_with_limits(limits);
}
}

Expand All @@ -6361,8 +6399,8 @@ impl BashTool {
if let Some(mli) = max_loop_iterations {
limits = limits.max_loop_iterations(usize::try_from(mli).unwrap_or(usize::MAX));
}
if let Some(ts) = timeout_seconds {
limits = limits.timeout(parse_timeout_seconds(ts)?);
if let Some(timeout) = timeout {
limits = limits.timeout(timeout);
}
builder = builder.limits(limits);

Expand Down
21 changes: 19 additions & 2 deletions crates/bashkit-python/tests/test_tool_runtimes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Opt-in tool runtimes share the VFS and survive interpreter rebuilds."""
"""Opt-in tool runtimes share the VFS, survive interpreter rebuilds, and honor timeout_seconds."""

import importlib.util
import time

import pytest

from bashkit import BashTool
from bashkit import Bash, BashTool, ExecutionProfile

PYTHON_ENV = {"BASHKIT_ALLOW_INPROCESS_PYTHON": "1"}

Expand Down Expand Up @@ -124,3 +125,19 @@ def test_invalid_runtime_program_reports_failure(runtime, script):
assert result.exit_code != 0
assert result.stdout == ""
assert result.stderr


@pytest.mark.parametrize(
("cls", "runtime", "script"),
[
(Bash, "python", "python3 -c 'while True: pass'"),
(BashTool, "typescript", "ts -c 'for (;;) {}'"),
],
)
def test_timeout_seconds_raises_runtime_time_limit(cls, runtime, script):
# Hardened caps each runtime call at 10 s; timeout_seconds must lift it too.
tool = cls(profile=ExecutionProfile.Hardened, timeout_seconds=11, env=PYTHON_ENV, **{runtime: True})
start = time.monotonic()
result = tool.execute_sync(script)
assert result.exit_code != 0
assert time.monotonic() - start > 10.5
1 change: 1 addition & 0 deletions knowledge/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 2026-11-06

* **Python package runtime timeout**: `Bash(timeout_seconds=...)` and `BashTool(timeout_seconds=...)` raised the shell timeout but left embedded Python and TypeScript at the profile's `max_duration` per run (30 s, Hardened 10 s), so `timeout_seconds=120` still stopped `python3` at 30 s. `timeout_seconds` now also sets that limit, as `Bash` already did for SQLite. See [Python Package](runtimes/python-package.md#embedded-tool-runtimes).
* **Python wall-clock limit**: Monty 1.x pauses its clock while the VM waits on the host, so `PythonLimits::max_duration` bounded VM time only. A `while True: p.write_text('x')` loop under a 500 ms limit ran 6 s, never yielding its worker thread, so caller-side timeouts could not cancel it and co-tenants on that thread stalled. The host-call loop now enforces the wall-clock deadline (exit 124) and yields at every host call. Found by the multi-tenant stress suite. See [Python Builtin](runtimes/python-builtin.md), TM-PY-036.
* **Monty fork drift check**: `scripts/check_monty_fork.py` compares both forks with the SHA-256-pinned upstream 1.4.0 crates and fails on unmarked edits (it found one unmarked import, now marked); runs in CI lint and `just check`. Re-sync checklist for upstream security fixes added. See [Dependencies](operations/dependencies.md#monty-forks).
* **Monty multi-tenant stress**: `python_tenant_stress_tests` mixes hostile and well-behaved `python3` tenants on shared worker threads, abandons calls mid-run, and reuses one session's memory budget many times; each tenant must hit only its own limit. 20-round soak passed locally (80 s). See [Python Builtin](runtimes/python-builtin.md), TM-PY-032.
Expand Down
10 changes: 9 additions & 1 deletion knowledge/runtimes/python-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ captures this grant at construction, so an agent's `export` cannot enable it.
Do not infer permission from untrusted script contents. See
[Python Builtin](python-builtin.md) and [ZapCode Runtime](zapcode-runtime.md).

`timeout_seconds` on `Bash` and `BashTool` also sets the embedded runtimes'
`max_duration` (the limit of each `python3`/`ts` run, profile default 30 s,
Hardened 10 s), as `Bash` does for SQLite. Each run stays clamped to the
remaining execution deadline. `ts` VM time also draws on the execution work
budget at one unit per microsecond, so a `ts` run past about 100 s (Hardened
25 s) still fails on `max_work_units`.

LangChain's `BashkitTool` / `create_bash_tool`, deepagents' `BashkitMiddleware` /
`create_bash_middleware`, and `BashkitBackend` forward `python`, `typescript`,
and `env` to their native tool. Backend-created middleware shares the configured
Expand All @@ -192,7 +199,8 @@ reset retain the host's runtime selection.
Regression evidence: `crates/bashkit-python/tests/test_tool_runtimes.py` covers
defaults, independent runtime selection, metadata, sync/async execution, shared
VFS, reset, keyed/unkeyed snapshot factories, framework forwarding, invalid
programs, and rejection of script-only Python opt-in.
programs, rejection of script-only Python opt-in, and `timeout_seconds` raising
the runtime time limit.

### Embedded runtime host functions

Expand Down
4 changes: 2 additions & 2 deletions site/src/content/apidocs/python.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Create a new Bash interpreter.
- **`max_commands`** — Limit total commands executed.
- **`max_loop_iterations`** — Limit iterations per loop.
- **`max_memory`** — Memory limit in bytes for the VFS.
- **`timeout_seconds`** — Abort execution after this duration.
- **`timeout_seconds`** — Abort execution after this duration. Also the time limit of each embedded ``python3`` run (profile default: 30 s, Hardened 10 s).
- **`python`** — Enable embedded Python (``python3`` builtin).
- **`sqlite`** — Enable embedded SQLite (``sqlite``/``sqlite3`` builtin). Defaults to ``False``. When ``True``, the Turso-backed engine is registered and ``BASHKIT_ALLOW_INPROCESS_SQLITE=1`` is injected automatically. Default ``SqliteLimits`` apply: 4 MiB script cap, 256 MiB DB cap, 30 s wall-clock budget, resource-affecting PRAGMAs (`cache_size`, `mmap_size`, …) rejected, ``ATTACH``/``DETACH`` rejected.
- **`external_functions`** — Function names callable from Python code.
Expand Down Expand Up @@ -614,7 +614,7 @@ Create a new BashTool.
- **`max_commands`** — Limit total commands executed.
- **`max_loop_iterations`** — Limit iterations per loop.
- **`max_memory`** — Memory limit in bytes for the VFS.
- **`timeout_seconds`** — Abort execution after this duration.
- **`timeout_seconds`** — Abort execution after this duration. Also the time limit of each embedded ``python3``/``ts`` run (profile default: 30 s, Hardened 10 s).
- **`files`** — Dict mapping VFS paths to file contents or lazy callables.
- **`mounts`** — List of real host directory mount configs.
- **`allowed_mount_paths`** — Host path prefixes allowed for real filesystem mounts. Required when mounting sensitive host locations such as paths under a user home directory.
Expand Down
Loading