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
4 changes: 2 additions & 2 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ updates:
- dependency-name: "monty-types"
- dependency-name: "monty-macros"

# Crates only the two forks declare. The forks track Monty 1.4.0's own
# Crates only the two forks declare. The forks track Monty 1.5.0's own
# dependency versions and move only when upstream source is re-copied;
# a Dependabot bump edits the fork manifests directly (#2848 bumped
# ruff_python_* 0.0.14 -> 0.0.20 and unicode_names2 1 -> 4, and failed
Expand All @@ -56,7 +56,7 @@ updates:
# there as well as in the workspace), which check_monty_fork.py rejects
# unless the fork's line carries a `bashkit fork:` marker. So taking one
# of those bumps means moving the fork line and marking it, not just the
# workspace line; fancy-regex and getrandom are marked that way today.
# workspace line; getrandom and jiter are marked that way today.
# scripts/tests/test_dependabot_coverage.py keeps this list complete.
- dependency-name: "ahash"
- dependency-name: "hashbrown"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ jobs:
- name: Test repo scripts
run: python3 -m unittest discover -s scripts/tests -p 'test_*.py'

# The Monty forks must match the pinned upstream 1.4.0 crates except
# The Monty forks must match the pinned upstream 1.5.0 crates except
# where a `bashkit fork:` comment marks a local edit.
- name: Check Monty fork drift
run: python3 scripts/check_monty_fork.py
Expand Down
22 changes: 12 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ See [knowledge/integrations/git-support.md](knowledge/integrations/git-support.m
## Experimental: Python Support

Enable the `python` feature to embed the [Monty](https://github.com/pydantic/monty) Python interpreter (pure Rust, Python 3.12).
Bashkit uses a slightly patched Monty 1.4, published as `bashkit-monty` and `bashkit-monty-types`: the patch adds a per-run memory probe and a VM checkpoint hook, so concurrent runs in one process get separate memory limits and honour cancellation. The upstream proposal is [pydantic/monty#740](https://github.com/pydantic/monty/pull/740); the forks go away once upstream has the hooks.
Bashkit uses a slightly patched Monty 1.5, published as `bashkit-monty` and `bashkit-monty-types`: the patch adds a per-run memory probe and a VM checkpoint hook, so concurrent runs in one process get separate memory limits and honour cancellation. The upstream proposal is [pydantic/monty#740](https://github.com/pydantic/monty/pull/740); the forks go away once upstream has the hooks.
Python code runs in-memory with configurable resource limits and VFS bridging, files created
by bash are readable from Python and vice versa.

Expand Down
12 changes: 8 additions & 4 deletions crates/bashkit-monty-types/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Fork of pydantic/monty monty-types-1.4.0 (MIT) for bashkit's in-process Python.
# Fork of pydantic/monty monty-types-1.5.0 (MIT) for bashkit's in-process Python.
#
# Important decision (security): bashkit runs many tenants' Python in one
# process. Upstream Monty enforces `max_memory` through a process-wide
# allocator counter and has no in-VM host checkpoint, so bashkit carries a
# small patch in `bashkit-monty-types` (`set_memory_probe`, pydantic/monty#740,
# and `set_checkpoint_hook`) and republishes `monty` against it. Source is
# upstream monty-types-1.4.0 unchanged except marked edits; the library names stay `monty` /
# upstream monty-types-1.5.0 unchanged except marked edits; the library names stay `monty` /
# `monty_types` so code reads as upstream. Drop both crates once upstream ships
# the hooks. See knowledge/runtimes/python-builtin.md.
#
Expand All @@ -22,7 +22,7 @@ rust-version = "1.96"
authors = ["Samuel Colvin <samuel@pydantic.dev>", "Everruns"]
license = "MIT"
repository.workspace = true
description = "Fork of pydantic/monty's monty-types 1.4.0 with an embedder memory probe and checkpoint hook, for bashkit's python3"
description = "Fork of pydantic/monty's monty-types 1.5.0 with an embedder memory probe and checkpoint hook, for bashkit's python3"
keywords = ["python", "interpreter", "sandbox", "bashkit"]
categories = ["compilers", "emulators"]
readme = "README.md"
Expand All @@ -38,7 +38,7 @@ doctest = false
[dependencies]
chrono = { version = "0.4", features = ["serde"] }
jiff = { version = "0.2", features = ["std", "serde"], default-features = false }
monty-macros = { version = "1.4.0" }
monty-macros = { version = "=1.5.0" }
num-bigint = { version = "0.4", features = ["serde"] }
num-traits = { version = "0.2" }
ruff_python_stdlib = { version = "0.0.14" }
Expand All @@ -50,7 +50,11 @@ unicode-general-category = { version = "1" }
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
web-time = { version = "1.1" }

[target.'cfg(target_os = "linux")'.dependencies]
nix = { version = "0.31", features = ["fs", "time"], optional = true }

[features]
cpu-clock = ["dep:nix"]
test-hooks = []
tzdb = ["jiff/tzdb-zoneinfo", "tzdb-bundled"]
tzdb-bundled = ["jiff/tzdb-bundle-always"]
Expand Down
17 changes: 17 additions & 0 deletions crates/bashkit-monty-types/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ implementation**.

## Who should depend on it

The `monty` interpreter enables the `cpu-clock` feature for native CPU accounting, which is Linux-only.
Host-only users do not need this feature or its platform CPU dependencies.
`ExecutionClock::is_available()` reports whether the current thread can read the selected clock.

Host-side crates that need these types without linking the interpreter —
`monty-fs` (which services `OsFunctionCall`s locally via
`MountTable::handle_os_call`), `monty-pool` (which talks to Monty workers
Expand Down Expand Up @@ -64,6 +68,19 @@ assert_eq!(value.py_repr(), "[1, 'x']");
- [`monty-typeshed`](https://crates.io/crates/monty-typeshed) — the trimmed typeshed stubs describing the stdlib subset Monty implements.
- [`monty-macros`](https://crates.io/crates/monty-macros) — the proc macros behind `monty`'s argument parsing.

## Execution time

Execution budgets charge bytecode and native builtins, excluding host suspension.
They use `ExecutionClock::Wall` by default. Native callers can select
`ExecutionClock::Cpu` with `ResourceTracker::with_execution_clock`.
Subprocess hosts set `PoolConfig::execution_clock` once for the pool; CPU enforcement needs a local Linux subprocess
worker, so remote (gRPC) setups enable it in the server's local pool. CPU mode samples the executing
thread with a cache of up to 1 ms and reads exact execution boundaries.
Unavailable or unusable counters use conservative elapsed time for that window; off Linux the counter is always
unavailable, so check `ExecutionClock::is_available()` before selecting CPU mode directly.
The OS controls counter accuracy and resolution. Snapshots preserve clock selection
and recorded consumption. WebAssembly workers accept wall mode only.

## License

MIT
186 changes: 186 additions & 0 deletions crates/bashkit-monty-types/src/import.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
//! Imports the host resolves: the [`ImportArgs`] an
//! [`OsFunctionCall::Import`](crate::OsFunctionCall::Import) carries, and the
//! `.py` file search a host runs when it has no host module of that name.
//!
//! The sandbox never reads module files itself. It sends one `import` call per
//! module, and the host answers with a host module, a [`ModuleFile`] it found
//! on the search path, or not-found. [`find_module_file`] is the search, in
//! CPython's order; hosts supply how one candidate is read.

use crate::{
exceptions::{ExcType, MontyException},
object::CallArgs,
results::ExtFunctionResult,
type_checking::is_identifier,
};

/// The most search-path directories an import searches; later ones are ignored.
///
/// The sandbox sets `__path__`, and each directory costs the host two reads in
/// one suspension, so without a cap a long `__path__` amplifies host work.
pub const MAX_SEARCH_DIRS: usize = 32;

/// The arguments of an `import` call: the module and where its file may be.
///
/// Deserializes from a bare module name too, the form dumps written before
/// file imports store; such a call has an empty search path.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(from = "DumpedImportArgs")]
pub struct ImportArgs {
/// The fully-qualified dotted module name, e.g. `pkg.sub`.
pub module: String,
/// Absolute virtual directories to search for the module's file, in order:
/// the working directory for a top-level name, the package's `__path__`
/// for a submodule. Empty means the host offers host modules only.
pub search_path: Vec<String>,
}

impl ImportArgs {
/// An import of `module` that only host modules can answer.
#[must_use]
pub fn new(module: impl Into<String>) -> Self {
Self {
module: module.into(),
search_path: Vec::new(),
}
}

/// Reads the arguments back from the [`CallArgs`] a host sees for an
/// `import` call: the module name, then its search path, which a call from
/// a sandbox predating file imports leaves out. `None` when malformed.
#[must_use]
pub fn from_call_args(args: &CallArgs) -> Option<Self> {
let mut args = args.args();
let module = args.next()?.as_str()?.to_owned();
let search_path = match args.next() {
Some(dirs) => dirs
.items()?
.iter()
.map(|dir| dir.as_str().map(str::to_owned))
.collect::<Option<_>>()?,
None => Vec::new(),
};
args.next().is_none().then_some(Self { module, search_path })
}

/// The files that may hold the module, in the order a search reads them:
/// per directory, the package `name/__init__.py` before the module `name.py`.
///
/// The call comes from an untrusted sandbox, so a name with a component
/// that is not an identifier has no candidates, and a directory that is not
/// absolute or holds a NUL byte is skipped, and only the first
/// [`MAX_SEARCH_DIRS`] remaining directories are searched. Paths are built one directory at
/// a time: a long name times many directories never sits in memory at once.
/// They are not normalized: mounts check them as sent, as for `open()`, and
/// an `os` handler receives them normalized through [`OsFunctionCall::to_args`](crate::OsFunctionCall::to_args).
pub fn candidates(&self) -> impl Iterator<Item = String> + '_ {
let valid = self.module.split('.').all(is_identifier);
let leaf = self.module.rsplit('.').next().unwrap_or(&self.module);
self.search_path
.iter()
.filter(move |dir| valid && dir.starts_with('/') && !dir.contains('\0'))
.take(MAX_SEARCH_DIRS)
.flat_map(move |dir| {
let dir = dir.strip_suffix('/').unwrap_or(dir);
[format!("{dir}/{leaf}/__init__.py"), format!("{dir}/{leaf}.py")]
})
}
}

/// The two forms an `import` call's arguments take in a dump.
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum DumpedImportArgs {
/// A dump written before file imports: the module name alone.
Name(String),
Args {
module: String,
search_path: Vec<String>,
},
}

impl From<DumpedImportArgs> for ImportArgs {
fn from(dumped: DumpedImportArgs) -> Self {
match dumped {
DumpedImportArgs::Name(module) => Self::new(module),
DumpedImportArgs::Args { module, search_path } => Self { module, search_path },
}
}
}

/// A module's `.py` file found by the host, which the sandbox runs as the module.
///
/// A `path` ending in `/__init__.py` makes the module a package.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ModuleFile {
/// The virtual path the file was read from: the module's `__file__`.
pub path: String,
/// The file's text.
pub source: String,
}

/// The outcome of reading one candidate file during a [`find_module_file`] search.
#[derive(Debug)]
pub enum ModuleRead {
/// The file's text: the search ends here.
Text(String),
/// No such file: the search moves on.
Missing,
/// No handler serves this path: the search moves on, as for a missing file.
NotHandled,
/// Reading failed for another reason: the import raises it.
Error(MontyException),
}

impl ModuleRead {
/// Classifies a `Path.read_text` failure: missing, a directory in the way,
/// or a path outside anything the host serves moves on; anything else raises.
#[must_use]
pub fn from_exception(exc: MontyException) -> Self {
match exc.exc_type() {
ExcType::FileNotFoundError
| ExcType::NotADirectoryError
| ExcType::IsADirectoryError
| ExcType::PermissionError => Self::Missing,
_ => Self::Error(exc),
}
}

/// Classifies a host handler's answer to `Path.read_text` for a candidate.
#[must_use]
pub fn from_result(result: ExtFunctionResult) -> Self {
match result {
ExtFunctionResult::Return(value) => match value.as_ref().as_str() {
Some(text) => Self::Text(text.to_owned()),
None => Self::Error(MontyException::new(
ExcType::RuntimeError,
Some(format!(
"invalid return type: Path.read_text for an import must return a str, not {}",
value.as_ref().type_name()
)),
)),
},
ExtFunctionResult::Error(exc) => Self::from_exception(exc),
ExtFunctionResult::NotFound(_) => Self::NotHandled,
ExtFunctionResult::Future(_) | ExtFunctionResult::ModuleFile(_) => Self::Error(MontyException::new(
ExcType::RuntimeError,
Some("Path.read_text for an import must be answered with a str".to_owned()),
)),
}
}
}

/// Searches `args`' candidates with `read`, returning the first file found as
/// a [`ExtFunctionResult::ModuleFile`], or the error a read raised.
///
/// `None` when no candidate exists: the host answers the import with not-found.
pub fn find_module_file(args: &ImportArgs, mut read: impl FnMut(&str) -> ModuleRead) -> Option<ExtFunctionResult> {
for path in args.candidates() {
match read(&path) {
ModuleRead::Text(source) => return Some(ExtFunctionResult::ModuleFile(ModuleFile { path, source })),
ModuleRead::Missing | ModuleRead::NotHandled => {}
ModuleRead::Error(exc) => return Some(ExtFunctionResult::Error(exc)),
}
}
None
}
Loading
Loading