Skip to content
Merged
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
31 changes: 27 additions & 4 deletions crates/bashkit-monty-types/src/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,11 @@ pub struct ResourceTracker {
/// tighten the bound from Python code without escaping the
/// host-configured ceiling. `None` means the configured limit applies.
recursion_limit_override: Cell<Option<usize>>,
/// bashkit fork: one counter for every amortized `*_every` check, so many
/// short Rust loops still add up to a full check every
/// `LOOP_CHECK_INTERVAL` steps (see [`check_time_every`](Self::check_time_every)).
#[serde(skip)]
tick: Cell<usize>,
}

impl Default for ResourceTracker {
Expand Down Expand Up @@ -375,6 +380,7 @@ impl ResourceTracker {
turn_execution_time: Cell::new(Duration::ZERO),
running_since: Cell::new(None),
recursion_limit_override: Cell::new(None),
tick: Cell::new(0),
}
}

Expand Down Expand Up @@ -569,22 +575,39 @@ impl ResourceTracker {
/// increasing counter. Fires at the *end* of each block (`i % N == N-1`)
/// so loops shorter than the interval pay no clock read at all — the VM
/// dispatch checkpoint covers cadence between short calls.
///
/// bashkit fork: `i` is ignored; the cadence comes from one tracker-wide
/// counter (`tick`). Keyed on a loop index, a recursion made of short
/// loops never reached a check: `x == y` or `repr(x)` over a shared graph
/// of two-item lists (`x = [x, x]` thirty times) ran for minutes past the
/// limit, synchronously, so the host could not interrupt it either.
#[inline]
pub fn check_time_every(&self, i: usize) -> Result<(), ResourceError> {
if i % Self::LOOP_CHECK_INTERVAL == Self::LOOP_CHECK_INTERVAL - 1 {
pub fn check_time_every(&self, _i: usize) -> Result<(), ResourceError> {
if self.next_tick_is_check() {
self.check_time()
} else {
Ok(())
}
}

/// bashkit fork: advances the shared amortization counter and reports
/// whether this step is due a full check.
#[inline]
fn next_tick_is_check(&self) -> bool {
let i = self.tick.get().wrapping_add(1);
self.tick.set(i);
i % Self::LOOP_CHECK_INTERVAL == 0
}

/// Amortized per-item memory + time check; the memory-probing sibling of
/// [`check_time_every`](Self::check_time_every), for loops that allocate
/// per item. Between full checks the allocator's hard limit still bounds
/// runaway growth.
///
/// bashkit fork: `i` is ignored, as in [`check_time_every`](Self::check_time_every).
#[inline]
pub fn check_memory_time_every(&self, i: usize) -> Result<(), ResourceError> {
if i % Self::LOOP_CHECK_INTERVAL == Self::LOOP_CHECK_INTERVAL - 1 {
pub fn check_memory_time_every(&self, _i: usize) -> Result<(), ResourceError> {
if self.next_tick_is_check() {
self.check_memory_time()
} else {
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions crates/bashkit-monty/src/types/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,7 @@ impl<'h> HeapRead<'h, Dict> {
defer_drop!(pair, vm);
let (key, value) = pair;
if printed > 0 {
if repr_check_time(printed, vm) {
if repr_check_time(printed, vm)? {
f.write_str(", ...[timeout]")?;
break;
}
Expand Down Expand Up @@ -1207,7 +1207,7 @@ impl<'h> HeapRead<'h, Dict> {
f.write_char('{')?;
for (n, &i) in order.iter().enumerate() {
if n > 0 {
if repr_check_time(n, vm) {
if repr_check_time(n, vm)? {
f.write_str(", ...[timeout]")?;
break;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bashkit-monty/src/types/generic_alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, GenericAlias> {
}
for index in 0..count {
if index > 0 {
if repr_check_time(index, vm) {
if repr_check_time(index, vm)? {
f.write_str(", ...[timeout]")?;
break;
}
Expand Down
9 changes: 7 additions & 2 deletions crates/bashkit-monty/src/types/host_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,8 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, HostClass> {
///
/// Each caller supplies its own field list via `field`, mapping an index to that
/// field's name and a cloned value (dropped here). A cycle renders `...`, a
/// `None` value `<?>`, and exhausting a time limit truncates `...[timeout]`.
/// `None` value `<?>`, a memory limit truncates `...[timeout]`, and a time
/// limit raises (see `repr_check_time`).
///
/// `field` is resolved immediately before that field is written, never all up
/// front, so a `__repr__` that mutates a later field is observed — matching the
Expand All @@ -337,7 +338,11 @@ pub(crate) fn write_dataclass_repr<'h>(
if i > 0 {
// Same between-item checkpoint as sequence repr, so a wide instance
// cannot outrun its time limit.
if vm.heap.tracker.check_memory_time_every(i).is_err() {
// bashkit fork: through `repr_check_time`, so a time hit errors
// instead of truncating (a shared `D(d, d)` graph otherwise kept
// formatting: with the tracker-wide cadence only one call in 64
// sees the expired clock, so truncation never unwound the walk).
if super::list::repr_check_time(i, vm)? {
f.write_str(", ...[timeout]")?;
Comment thread
chaliy marked this conversation as resolved.
Resolved
break;
}
Expand Down
29 changes: 24 additions & 5 deletions crates/bashkit-monty/src/types/list.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{cmp::Ordering, fmt::Write, mem};

use monty_types::ResourceError;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;

Expand Down Expand Up @@ -1067,7 +1068,7 @@ pub(crate) fn repr_sequence_fmt<'h>(
let Some(item) = get_item(vm.heap, i) else { break };
defer_drop!(item, vm);
if i > 0 {
if repr_check_time(i, vm) {
if repr_check_time(i, vm)? {
f.write_str(", ...[timeout]")?;
break;
}
Expand Down Expand Up @@ -1095,7 +1096,7 @@ pub(crate) fn repr_items_fmt(
) -> RunResult<()> {
for (i, item) in items.iter().enumerate() {
if i > 0 {
if repr_check_time(i, vm) {
if repr_check_time(i, vm)? {
f.write_str(", ...[timeout]")?;
break;
}
Expand All @@ -1108,9 +1109,27 @@ pub(crate) fn repr_items_fmt(

/// Polls the time/memory soft limits every 64th item rather than every item,
/// keeping per-item overhead to one branch while still truncating huge reprs
/// promptly with `", ...[timeout]"` (tested in `resource_limits.rs`).
pub(crate) fn repr_check_time(i: usize, vm: &VM<'_>) -> bool {
vm.heap.tracker.check_memory_time_every(i).is_err()
/// promptly with `", ...[timeout]"`. Pinned by bashkit's
/// `python_security_tests::whitebox_resource_limits::shared_graph_walks_respect_time_limit`.
///
/// bashkit fork: two changes, both for reprs of shared graphs (`x = [x, x]`
/// thirty times is 2^30 nested two-item lists).
/// - The poll cadence is tracker-wide (see `check_time_every`), not the
/// index `i` within one container: a two-item list never reached index 63,
/// so the clock was never read and the repr ran for minutes past the limit
/// on a thread the host cannot interrupt.
/// - A time-limit hit is returned as an error instead of truncating. The
/// time budget never recovers within a run, and truncating only ends the
/// current container while every enclosing one keeps formatting its next
/// item, and with the tracker-wide cadence only one call in 64 sees the
/// expired clock, so the others would keep formatting. A memory hit still
/// truncates, as upstream does. Every repr checkpoint goes through here.
pub(crate) fn repr_check_time(_i: usize, vm: &VM<'_>) -> RunResult<bool> {
Comment thread
chaliy marked this conversation as resolved.
Resolved
match vm.heap.tracker.check_memory_time_every(0) {
Ok(()) => Ok(false),
Err(err @ ResourceError::Time { .. }) => Err(err.into()),
Err(_) => Ok(true),
}
}

/// Iterates over a list while observing changes to its current contents.
Expand Down
4 changes: 2 additions & 2 deletions crates/bashkit-monty/src/types/partial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Partial> {
let mut item = 0;
'items: {
for index in 0..self.get(vm.heap).args.len() {
if repr_check_time(item, vm) {
if repr_check_time(item, vm)? {
f.write_str(", ...[timeout]")?;
break 'items;
}
Expand All @@ -383,7 +383,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Partial> {
}

for index in 0..self.get(vm.heap).keywords.len() {
if repr_check_time(item, vm) {
if repr_check_time(item, vm)? {
f.write_str(", ...[timeout]")?;
break 'items;
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bashkit-monty/src/types/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ impl<'h> PyTrait<'h> for HeapObjectRead<'h, Union> {
let count = args.get(vm.heap).as_slice().len();
for index in 0..count {
if index > 0 {
if repr_check_time(index, vm) {
if repr_check_time(index, vm)? {
f.write_str(" | ...[timeout]")?;
break;
}
Expand Down
1 change: 1 addition & 0 deletions crates/bashkit/docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,7 @@ Python `pathlib.Path` and `open()` operations are bridged to Bashkit's virtual f
| Uninterruptible VM loop (TM-PY-034) | Tight loop ignores cancellation or shared budget | Forked checkpoint hook runs the request `ExecutionBudget` check inside the VM | MITIGATED |
| Shared-graph expansion in host conversion (TM-PY-035) | `x = [x, x]` repeated, then returned to the host | Every converter walks Monty values with a node cap | MITIGATED |
| Host-call loop outruns the time limit (TM-PY-036) | `while True:` around a cheap file write; Monty's clock pauses on host calls and the VM never yields the thread | Wall-clock deadline and an executor yield at every host call | MITIGATED |
| Shared-graph walk outlives time limit (TM-PY-037) | `x = [x, x]` repeated, then `repr` or `==` inside Python | Forked tracker counts every amortized check on one tick, so recursive walks still check time | MITIGATED |

**Architecture:**

Expand Down
55 changes: 55 additions & 0 deletions crates/bashkit/tests/integration/python_security_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,61 @@ mod blackbox_class_escape {
mod whitebox_resource_limits {
use super::*;

/// Regression: walking a shared graph (`x = [x, x]` thirty times is
/// 2^30 nested two-item lists, or two-field dataclasses) in repr, `==`, `<` or `in` never read the
/// clock, because the fork polled time by the index within one list. It ran for minutes past
/// a 2 s limit, synchronously, so the host's exec timeout could not stop
/// it either. Each path must now hit the time limit (exit 124) promptly.
#[tokio::test(flavor = "multi_thread")]
async fn shared_graph_walks_respect_time_limit() {
let graph = "x = [1]\nfor _ in range(30):\n x = [x, x]\n";
for (name, tail) in [
("repr", "s = repr(x)"),
("str", "s = str(x)"),
("print", "print(x)"),
("fstring", "s = f\"{x}\""),
("dict", "s = repr({1: x})"),
("tuple", "s = repr((x, x))"),
(
"eq",
"y = [1]\nfor _ in range(30):\n y = [y, y]\nb = x == y",
),
(
"lt",
"y = [1]\nfor _ in range(30):\n y = [y, y]\nb = x < y",
),
(
"in",
"y = [1]\nfor _ in range(30):\n y = [y, y]\nb = x in [y]",
),
("json", "import json\ns = json.dumps(x)"),
(
"dataclass",
"from dataclasses import dataclass\n@dataclass\nclass D:\n a: object\n b: object\nd = D(1, 1)\nfor _ in range(30):\n d = D(d, d)\ns = repr(d)",
),
] {
let mut bash = bash_python_limits(
PythonLimits::default().max_duration(std::time::Duration::from_millis(500)),
);
let script = format!("python3 -c '{graph}{tail}' >/dev/null; echo rc=$?");
let started = std::time::Instant::now();
// Spawned so the timer runs on another worker: a regression blocks
// the thread running the script, not the one awaiting it.
let task = tokio::spawn(async move { bash.exec(&script).await });
let r = tokio::time::timeout(std::time::Duration::from_secs(20), task).await;
let elapsed = started.elapsed();
let r = r
.unwrap_or_else(|_| panic!("{name}: still running after 20s"))
.unwrap()
.unwrap();
assert!(
elapsed < std::time::Duration::from_secs(10),
"{name}: took {elapsed:?}"
);
assert_eq!(r.stdout, "rc=124\n", "{name}: {}", r.stderr);
}
}

/// Regression: every invocation used to reserve `max_memory / 64` work
/// units up front (1M at the 64 MiB default) out of the 100M budget, so
/// the 96th `python3` call in one script failed even for `pass`.
Expand Down
1 change: 1 addition & 0 deletions knowledge/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* **Dependabot config parse fix**: #2852 set `versioning-strategy: increase` on a cargo entry, which cargo rejects, so Dependabot refused the whole `dependabot.yml` (red check on `main`). Replaced by committing the two random-fs fixture lockfiles, which also puts them in the advisory scan; a test pins cargo strategies to `auto`/`lockfile-only`. See [Dependencies](operations/dependencies.md).
* **Monty fuzz target**: `python_fuzz` fuzzes the forked Monty `python3` with the metered allocator installed (file, stdin, `-c`, CLI args; 32 MiB / 500 ms limits, per-exec wall-clock assertion, leak checks). Nightly in `fuzz.yml`, build-checked in `fuzz-check`. First local run: 282k execs in 8 min, 0 crashes. See [Python Builtin](runtimes/python-builtin.md), TM-PY-032.
* **rg searches as it reads**: `rg` searched every file only after reading all of them, holding ~160 B of text per file (~300 MB at 2M files) within the input budget. Searching moved into the walk (`RgSearch`): each file is searched and dropped as it is read, several roots stream one after another in path order, and `-q` stops the walk at its answer. Peak over 200k files: 34 MB to 1.3 MiB. See [Virtual Filesystem](foundations/vfs.md#remote-backends-round-trips), TM-DOS-140.
* **Python shared-graph hang**: in Monty 1.4.0, `x = [x, x]` thirty times then `repr(x)`, `print(x)`, `x == y`, `x < y` or `x in [y]` ran for minutes past a 2 s limit and blocked the thread, so the shell timeout could not stop it. Amortized time checks keyed on each loop's own index, and 2-item lists never reach 64. The fork now counts every amortized check on one tracker-wide tick, and `repr` exits 124 on a time hit instead of truncating. See [Python Builtin](runtimes/python-builtin.md), TM-PY-037.
* **Dependabot jobs green again**: the weekly cargo "/" job failed since 2026-10-19 because `turso_core = "0.8.0-pre.1"` (lock at 0.8.3) made Dependabot try 0.9.0-pre.2 as an in-range lockfile update, which cargo rejects; the requirement is now the stable `0.8.3`. The example/fixture job failed since 2026-10-13 because Dependabot follows the `crates/bashkit` path dep into the root workspace and tries to bump bashkit's own (root-owned, partly optional) deps; that entry now `allow`s only each manifest's own deps and uses `versioning-strategy: increase` for the lockfile-less fixtures. Crates only the Monty forks declare are ignored in the "/" entry so they move with upstream (#2848 had bumped them and broke the build). All three are pinned by `scripts/tests/test_dependabot_coverage.py`. See [Dependencies](operations/dependencies.md).

## 2026-11-05
Expand Down
17 changes: 14 additions & 3 deletions knowledge/runtimes/python-builtin.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,20 @@ limit, a greedy tenant beside small ones, many small objects, `str.join` bomb)
and the `whitebox_resource_limits` / `threat_python_pow_exhaustion` regression
tests that failed on every earlier bump attempt.

Known upstream gaps in 1.4.0: `repr` of nested 2-item lists only checks time
every 64 items, and `str.join` can overshoot `max_memory` before the next
check (bounded by the meter, not by Monty).
Amortized checks (fork edit, TM-PY-037): upstream `check_time_every(i)` and
`check_memory_time_every(i)` fire when the caller's loop index hits a multiple
of 64, so a recursive walk over many short loops never checked. `x = [x, x]`
thirty times (or a two-field dataclass `D(d, d)`), then
`repr`/`print`/f-string/`==`/`<`/`in`, ran for minutes past
a 2 s limit, synchronously, so the shell timeout could not stop it either. The
fork counts every `*_every` call on one tracker-wide tick instead, and the
`repr` walks (sequences, dicts, dataclasses, host classes) return a
time-limit error (exit 124) where upstream truncated to
`...[timeout]`; a memory hit still truncates. Pinned by
`whitebox_resource_limits::shared_graph_walks_respect_time_limit`.

Known upstream gap in 1.4.0: `str.join` can overshoot `max_memory` before the
next check (bounded by the meter, not by Monty).

### Python Feature Support

Expand Down
1 change: 1 addition & 0 deletions knowledge/security/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -2012,6 +2012,7 @@ yield `OsCall` events that Bashkit intercepts and dispatches to the VFS.
| TM-PY-034 | Uninterruptible VM loop ignores cancellation / shared budget | High | Forked `monty_types::set_checkpoint_hook` runs the request `ExecutionBudget` check at every VM time checkpoint; `Err` stops the run uncatchably | `python_security_tests::whitebox_resource_limits::*`, budget tests in `builtins::python`, `python_tenant_stress_tests::*` (spin, abandoned calls, budget reuse) |
| TM-PY-035 | Shared object graph expands exponentially in host conversion | High | Monty 1.x `MontyObject` graphs can share children; every host converter (runtime values, scripted-tool JSON, Python binding) walks with a node cap (100k / 1M) | `runtime_value` and `tool_registry` unit tests |
| TM-PY-036 | Host-call loop outruns the time limit / starves the worker thread | High | Monty 1.x pauses its clock while suspended on the host, so `max_duration` counted VM time only. The host-call loop checks the wall-clock deadline at every OS/external call and yields to the executor there | `python_tenant_stress_tests::host_call_loops_stop_at_the_wall_clock_limit`, `python_tenant_stress_tests::abandoned_calls_do_not_poison_the_worker_threads` |
| TM-PY-037 | Shared-graph walk outlives the time limit | Critical | Upstream amortized checks key on the per-loop index, so recursive `repr`/compare over `x = [x, x]` never checks time and blocks the thread past every limit. Fork counts all `*_every` calls on one tracker-wide tick; `repr` errors on a time hit | `python_security_tests::whitebox_resource_limits::shared_graph_walks_respect_time_limit` |
| TM-PY-013 | Unknown CLI options smuggle behavior | Low | Unknown `python` options rejected with exit 2 | `threat_python_unknown_options` |
| TM-PY-014 | Python escapes Bashkit resource limits | High | Bashkit `ExecutionLimits` apply to the `python` command like any builtin | `threat_python_respects_bash_limits` |
| TM-PY-015 | Real filesystem read via pathlib | Critical | VFS bridge reads only from Bashkit VFS, not host | `threat_python_vfs_no_real_fs` |
Expand Down
Loading