Expand description
§monty-types
Shared boundary types for Monty, the Python sandbox — the owned, heap-free data types that cross between the sandbox and the hosts that embed it, with no interpreter implementation.
§What’s here
MontyObject/MontyType— Python values and their types at the host boundary, including thedatetimefamily (MontyDate,MontyDateTime,MontyTimeDelta,MontyTimeZone) andMontyFileHandle.ObjectRef— a borrowed value, with typed accessors (as_int,as_str,items,pairs).MontyObject::as_ref()borrows a value for inspection.CallArgs/NamedValues— the arguments or inputs of one message. Their builders acceptMontyObjectvalues; their iterators return borrowed values. Both carriers and theMontyObject/ObjectReftypes keep their fields private.unstable— graph representation APIs for bindings and transport adapters, with no API compatibility guarantee. They may change or disappear in any release; prefer value constructors and typed accessors when possible.MontyException/ExcType— exceptions with tracebacks (StackFrame,CodeLoc) and structured payloads (ExcData).OsFunctionCall— the typed OS-call payloads sandboxed code suspends with (file reads/writes,open(),os.getenv, …), plus thestat_resultbuilders hosts use to answer them.MontyPathpreserves OS-call paths for validation;normalize_virtual_pathprovides the lexical POSIX normalization shared by the interpreter, mounts, andOsFunctionCall::to_args()callbacks. It borrows canonical paths and resolves relative inputs from/. Validate NUL bytes and path limits before calling it; it does not confine filesystem access.ResourceTracker/ResourceLimits— the resource tracker the interpreter uses to enforce time/memory/recursion limits, plus themax_suspensionsbudget hosts enforce themselves.PrintStream/PrintWriter/CollectedStreams—print()output capture, and the labelled buffer behindPrintWriter::CollectStreams.CompileOptions,ExtFunctionResult,NameLookupResult,FileMode, and the CPython-compatible formatting helpers behind theirrepr()s.
§Who should depend on it
Host-side crates that need these types without linking the interpreter —
monty-fs (which services OsFunctionCalls locally via
MountTable::handle_os_call), monty-pool (which talks to Monty workers
over the wire), the pydantic-monty-client Python bindings and the
@pydantic/monty JS bindings — depend on this crate instead of monty,
so their binaries never link the interpreter itself. Only worker-side crates
(monty-runtime, monty-wasm-runtime, and monty-proto with its worker
feature) link monty.
use monty_types::MontyObject;
let value = MontyObject::list([MontyObject::int(1), MontyObject::string("x".to_owned())]);
assert_eq!(value.py_repr(), "[1, 'x']");§Monty crates
monty— the core interpreter: Python parser, bytecode VM, and sandbox.monty-types— the shared boundary data types (values, exceptions, OS calls, resource limits) hosts use without linking the interpreter. this cratemonty-fs— host-side filesystem mounts: maps virtual sandbox paths to real host directories.monty-runtime— themontybinary: REPL, file runner, and subprocess worker mode.monty-pool— an elastic pool of crash-isolatedmontyworker subprocesses.monty-proto— the protobuf wire protocol spoken between pool parents and workers.monty-type-checking— type checking of sandboxed code, powered by ty.monty-typeshed— the trimmed typeshed stubs describing the stdlib subset Monty implements.monty-macros— the proc macros behindmonty’s argument parsing.
§License
MIT
Re-exports§
pub use crate::builtins::BuiltinsFunctions;pub use crate::exceptions::CodeLoc;pub use crate::exceptions::ExcData;pub use crate::exceptions::ExcType;pub use crate::exceptions::JsonErrorData;pub use crate::exceptions::MontyException;pub use crate::exceptions::SourceRange;pub use crate::exceptions::StackFrame;pub use crate::exceptions::UnicodeErrorData;pub use crate::exceptions::UnicodeErrorObject;pub use crate::exceptions::unicode_decode_error_msg;pub use crate::file_mode::FileMode;pub use crate::format::FormatComplex;pub use crate::format::FormatFloat;pub use crate::format::StringRepr;pub use crate::format::bytes_repr;pub use crate::format::bytes_repr_fmt;pub use crate::format::string_repr_fmt;pub use crate::format::utf8_error_reason;pub use crate::io::COLLECT_STREAMS_ENTRY_OVERHEAD;pub use crate::io::CollectedStreams;pub use crate::io::DEFAULT_MAX_PRINT_COLLECT_BYTES;pub use crate::io::PrintStream;pub use crate::io::PrintWriter;pub use crate::io::PrintWriterCallback;pub use crate::io::check_print_collect_limit;pub use crate::object::CallArgs;pub use crate::object::ConversionError;pub use crate::object::InvalidInputError;pub use crate::object::MAX_TIMEZONE_OFFSET_SECONDS;pub use crate::object::MIN_TIMEZONE_OFFSET_SECONDS;pub use crate::object::MontyComplex;pub use crate::object::MontyDate;pub use crate::object::MontyDateTime;pub use crate::object::MontyFileHandle;pub use crate::object::MontyObject;pub use crate::object::MontyTime;pub use crate::object::MontyTimeDelta;pub use crate::object::MontyTimeZone;pub use crate::object::MontyType;pub use crate::object::NamedValues;pub use crate::object::ObjectRef;pub use crate::object::unstable;pub use crate::os::GetenvArgs;pub use crate::os::IMPORT_CALL;pub use crate::os::IMPORT_STUBS_CALL;pub use crate::os::IMPORT_STUBS_CALL_ID;pub use crate::os::MAX_SLEEP_SECONDS;pub use crate::os::MkdirCallArgs;pub use crate::os::MontyPath;pub use crate::os::OpenCallArgs;pub use crate::os::OsFunctionCall;pub use crate::os::PathBytesDataArgs;pub use crate::os::PathStringDataArgs;pub use crate::os::RenameCallArgs;pub use crate::os::SleepError;pub use crate::os::TimeCaller;pub use crate::os::UrandomArgs;pub use crate::os::dir_stat;pub use crate::os::file_stat;pub use crate::os::sleep_duration;pub use crate::os::sleep_duration_saturating;pub use crate::os::stat_result;pub use crate::os::symlink_stat;pub use crate::os_policy::DateTimeSource;pub use crate::os_policy::NamedZone;pub use crate::os_policy::OsPolicy;pub use crate::os_policy::ProcessTime;pub use crate::os_policy::RandomSeed;pub use crate::os_policy::RandomStart;pub use crate::os_policy::SandboxTimeZone;pub use crate::os_policy::SleepMode;pub use crate::os_policy::UnknownTimeZone;pub use crate::os_policy::ZoneConstants;pub use crate::os_policy::local_wall_clock;pub use crate::os_policy::unix_seconds;pub use crate::resource::BASELINE_MEMORY;pub use crate::resource::DEFAULT_GC_INTERVAL;pub use crate::resource::DEFAULT_MAX_RECURSION_DEPTH;pub use crate::resource::DEFAULT_MAX_SUSPENSIONS;pub use crate::resource::LARGE_RESULT_THRESHOLD;pub use crate::resource::LIVE_MEMORY;pub use crate::resource::OOM_EXIT_CODE;pub use crate::resource::ResourceError;pub use crate::resource::ResourceLimits;pub use crate::resource::ResourceTracker;pub use crate::resource::TimeLimitScope;pub use crate::resource::allocate_into_baseline;pub use crate::resource::memory_limit_with_headroom;pub use crate::results::ExtFunctionResult;pub use crate::results::NameLookupResult;pub use crate::run_options::AssertMessageAnnotations;pub use crate::run_options::CompileOptions;pub use crate::run_options::SOURCE_SCAN_THRESHOLD;pub use crate::scan::ScanArgs;pub use crate::type_checking::CHECKER_MODULE_NAMES;pub use crate::type_checking::ModuleStub;pub use crate::type_checking::ModuleStubError;pub use crate::type_checking::SANDBOX_MODULE_NAMES;pub use crate::type_checking::TypeCheckState;pub use crate::type_checking::TypeCheckingConfig;pub use crate::type_checking::TypeCheckingFormat;pub use crate::type_checking::validate_module_name;pub use crate::uuid::MontyUuid;pub use crate::virtual_path::normalize_virtual_path;pub use crate::virtual_path::validate_cwd;
Modules§
- args
- Projection of typed argument structs into the
CallArgshost callbacks consume. The#[derive(ToArgs)]macro inmonty-macrosemits implementations viacrate::args::ToArgs, which resolves in this crate. - format
- Pure CPython-compatible formatting helpers shared by the boundary types:
string/bytes
repr()escaping, shortest-round-trip float rendering, and timezone-offsettimedeltareprs. - scan
- Directory-tree scans: the one OS call behind
os.scandir,os.walk,Path.walk,Path.globandPath.rglob. - unstable
- Representation access for bindings and transport adapters.
Structs§
- Call
Args - The positional and keyword arguments of one function or OS call. A sub-object shared within an exported call stays shared at the host boundary.
- CodeLoc
- A line and column position in source code.
- Collected
Streams - The buffer behind
PrintWriter::CollectStreams:(stream, text)entries plus the running charge their cap is checked against. - Compile
Options - Options controlling how Monty behavior diverges from plain CPython.
- Conversion
Error - Error returned when a
MontyObjectcannot be converted to the requested Rust type. - Getenv
Args os.getenv(key, default=None)shape. The host decides whether to substitutedefaultwhen the variable is unset.- Json
Error Data - Structured fields of a
json.JSONDecodeError, mirroring CPython’smsg/doc/pos/lineno/colnoexception attributes.tomllib.TOMLDecodeErrordefines the same five attributes, so it carries this payload too. - Mkdir
Call Args mkdir(path, parents=False, exist_ok=False)shape.parents/exist_okare kw-only soToArgsemits them as kwargs (matching CPython).- Module
Stub - A host module’s
.pyi, written as a module or package tree for the type checker. Construction validates each path component and rejects top-level names reserved by the sandbox or checker, preventing stubs from shadowing their modules. - Monty
Complex - A Python
complexvalue as its twofloatparts. - Monty
Date - A Python
datetime.datevalue with year, month, and day components. - Monty
Date Time - A Python
datetime.datetimevalue with date, time, and optional timezone components. - Monty
Exception - Public representation of a Monty exception.
- Monty
File Handle - An open file object (the result of
open()). - Monty
Object - One owned Python value at the host boundary.
- Monty
Path - Owned virtual (sandbox) path carried by OS-call args.
- Monty
Time - A Python
datetime.timevalue: a wall clock with no date attached. - Monty
Time Delta - A Python
datetime.timedeltavalue representing a duration. - Monty
Time Zone - A Python
datetime.timezonefixed-offset timezone. - Monty
Uuid - A 16-byte UUID identifying a host or sandbox class/instance across the sandbox boundary.
- Named
Values - The named inputs of one feed, preserving sharing between exported values.
- Named
Zone - A zone resolved from the tz database by
SandboxTimeZone::named, which is the only way to build one: every value carries the database’s name for it. - Object
Ref - A borrowed Python value, for inspecting results, arguments and inputs without copying.
- Open
Call Args - Arguments to
open(): a virtual path and a parsed file mode. - OsPolicy
- Policies for clocks, sleeps and initial random state on every execution path.
CallHostsuspends to the host, or raisesNotImplementedErrorwithout one; the zone is always resolved in the sandbox. Defaults use the system clock, the UTC zone, OS entropy, a zero process clock, and sleeps capped at ten seconds. Hosts perform those sleeps without theiroshandler; standard execution waits inline. - Path
Bytes Data Args path + bytes datashape used byWriteBytesandAppendBytes.- Path
String Data Args path + str datashape used byWriteTextandAppendText.- Rename
Call Args rename(src, dst)shape.- Resource
Limits - Configuration for resource limits.
- Resource
Tracker - A resource tracker that enforces configurable limits.
- Source
Range - The source range of the expression that suspended execution, carried by every suspension.
- Stack
Frame - A single frame in a Python traceback.
- Type
Check State - Per-session type-check state: successfully committed snippets accumulate as stubs so later snippets can reference names defined by earlier ones.
- Type
Checking Config - How a type check renders whatever diagnostics it finds.
- Unicode
Error Data - Structured fields of a
UnicodeDecodeError/UnicodeEncodeError, mirroring CPython’sencoding/object/start/end/reasonexception attributes. - Unknown
Time Zone - A zone name
SandboxTimeZone::namedcould not resolve: malformed, or absent from the tz database available to this build. - Urandom
Args os.urandom(size)shape. The interpreter rejects a negativesizebefore suspending, so the count is unsigned; the host answers with exactlysizebytes.sizeis sandbox-controlled, so a handler should cap it before allocating.- Zone
Constants - The zone’s standard and daylight halves as the
timemodule reports them.
Enums§
- Assert
Message Annotations - Controls the pytest-style introspected
assertfailure messages ofCompileOptions::assert_message_annotations. - Builtins
Functions - Enumerates every interpreter-native Python builtin function.
- Date
Time Source - Where the clock calls read the instant.
- ExcData
- Structured payload attached to exception types whose CPython counterparts
carry more than a message. Currently unicode and json decode errors have
one; the enum leaves room for future variants (e.g.
OSError’serrno/filename) without another field on every exception. - ExcType
- Python exception types supported by the interpreter.
- ExtFunction
Result - Return value or exception from an external function.
- File
Mode - A parsed Python
open()mode. - Invalid
Input Error - Error returned when a value cannot be used as an input to code execution.
- Module
Stub Error - An invalid or reserved host module name; see
validate_module_name. - Monty
Type - The Python type of a builtin at the host boundary: the public mirror of
the runtime
Typeenum, minus class types, which cross as their ownclass_typevalue. Serializable and displayable without heap access. - Name
Lookup Result - Result of a name lookup from the host.
- OsFunction
Call - Tagged dispatch value for OS-level operations.
- Print
Stream - Identifies the output stream for a single print fragment.
- Print
Writer - Output handler for the
print()builtin function. - Process
Time - What
time.process_time()andtime.thread_time()report. - Random
Seed - Explicit seeds for
RandomStart::Seed, using CPython’srandom.seed()semantics. - Random
Start - Where an unseeded
randomgenerator gets its first state. - Resource
Error - Error returned when a resource limit is exceeded during execution.
- Sandbox
Time Zone - The sandbox’s local zone, UTC unless configured.
- Sleep
Error - Why a requested sleep length cannot be carried by an OS call.
- Sleep
Mode - What the sleep calls do.
- Time
Caller - Which
timefunction is reading the clock in anOsFunctionCall::Time. - Time
Limit Scope - Which of the two nested execution-time budgets a
ResourceError::Timerefers to. - Type
Checking Format - How type-check diagnostics are rendered into text.
- Unicode
Error Object - The
objectattribute of a unicode error: the input being converted.
Constants§
- CHECKER_
MODULE_ NAMES - Vendored typeshed modules outside
SANDBOX_MODULE_NAMES, including private dependencies, plus ty’sty_extensions. Hosts may provide these modules at runtime, butModuleStub::newrejects their stubs to prevent shadowing the checker’s definitions. - COLLECT_
STREAMS_ ENTRY_ OVERHEAD - Host bytes charged for each retained
(stream, text)entry beyond its text. - DEFAULT_
GC_ INTERVAL - GC-tracked allocations between cycle collections when
gc_intervalisNone. Builds with monty’smemory-model-checksfeature collect on every allocation instead. - DEFAULT_
MAX_ PRINT_ COLLECT_ BYTES - Default cap for
PrintWriter::CollectString/PrintWriter::CollectStreamsand the matching Python collectors. - DEFAULT_
MAX_ RECURSION_ DEPTH - Recommended maximum recursion depth if not otherwise specified.
- DEFAULT_
MAX_ SUSPENSIONS - Maximum suspensions a host services per session if not otherwise specified: a backstop against a sandbox looping on host calls while the execution clock is paused.
- IMPORT_
CALL OsFunctionCall::Import’s dispatch name. Hosts resolve it from their modules before other OS handlers.- IMPORT_
STUBS_ CALL OsFunctionCall::ImportStubs’s dispatch name, handled likeIMPORT_CALL.- IMPORT_
STUBS_ CALL_ ID - Reserved pre-feed
OsFunctionCall::ImportStubsID, outside the interpreter’s IDs counted from zero. - LARGE_
RESULT_ THRESHOLD - Threshold in bytes above which
check_large_resultis called. - MAX_
SLEEP_ SECONDS - Longest sleep the sleep calls accept, matching the point where CPython’s
PyTime_t(nanoseconds in ani64) overflows. - MAX_
TIMEZONE_ OFFSET_ SECONDS - Largest UTC offset
datetime.timezoneaccepts, +23:59:59. - MIN_
TIMEZONE_ OFFSET_ SECONDS - Smallest UTC offset
datetime.timezoneaccepts, -23:59:59. - MONTY_
VERSION - The monty version this build was compiled as.
- OOM_
EXIT_ CODE - Exit code a worker uses when it exceeded its memory limit or the allocator
refused an allocation, so the parent can report
MemoryErrorinstead of an unclassifiableSIGABRT. - SANDBOX_
MODULE_ NAMES - Sandbox module names, excluding the dotted name
os.path. Imports of these modules never reach the host, so host modules cannot use these names. Keep in sync with the runtime’sStandardLib. - SOURCE_
SCAN_ THRESHOLD - Byte length up to which a source is compiled without the pre-parse nesting
scan; the default for
CompileOptions::source_scan_threshold.
Statics§
- BASELINE_
MEMORY - What the worker costs to exist: the leanest the process has ever been at an
arming point, plus structures it keeps for life (see
allocate_into_baseline). - LIVE_
MEMORY - Allocator-backed live bytes requested through the global allocator
Traits§
- Print
Writer Callback - Trait for custom output handling from the
print()builtin function.
Functions§
- allocate_
into_ baseline - Runs
buildand adds what it leaves allocated toBASELINE_MEMORY, so a structure the worker keeps for life (such as typeshed) is not charged to the session that happened to build it first. - check_
print_ collect_ limit - Rejects a collect-buffer growth that would exceed
max_bytes. - dir_
stat - Creates a
stat_resultfor a directory. - file_
stat - Creates a
stat_resultfor a regular file. - is_
identifier - Returns
trueif a string is a valid Python identifier (e.g., variable name). - local_
wall_ clock - The wall clock
offset_secondsfrom UTC atutc, orNoneoutside the 1..=9999 years Python’sdatetimecan hold. - memory_
limit_ with_ headroom - Converts an interpreter soft memory limit into a worker allocator budget.
- normalize_
virtual_ path - Returns an absolute POSIX path with
.removed and..resolved, stopping at/. Relative inputs are rooted at/; this never reads the host cwd or follows symlinks. Already normalized paths are borrowed. Validate NUL bytes and length limits first: normalization can remove invalid components and does not provide filesystem confinement. - sleep_
duration - Converts a Python sleep argument into the
Durationan OS call carries. - sleep_
duration_ saturating - Like
sleep_duration, but forasyncio.sleep, which clamps rather than raising: a negative delay becomes no wait at all (CPython returns immediately) and an over-long one saturates atMAX_SLEEP_SECONDS. Only NaN is refused, the one delay CPython rejects there. - stat_
result - Creates a full
stat_resultwith all 10 fields specified. - symlink_
stat - Creates a
stat_resultfor a symbolic link. - unicode_
decode_ error_ msg - Formats the message for a
UnicodeDecodeErrorcovering the byte rangestart..end: CPython’s single-byte form (byte 0x{first_byte:02x} in position {start}) when the range is one byte, otherwise the range form (bytes in position {start}-{end - 1}). - unix_
seconds - The instant as
time.time()reports it: seconds since the Unix epoch. - validate_
cwd - Checks a host-supplied working directory: absolute, POSIX, no NUL bytes.
- validate_
module_ name - Rejects non-identifiers and
SANDBOX_MODULE_NAMES, whose imports never reach the host.CHECKER_MODULE_NAMESare valid runtime module names; onlyModuleStub::newrejects them.