Skip to main content

Crate monty_types

Crate monty_types 

Source
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 the datetime family (MontyDate, MontyDateTime, MontyTimeDelta, MontyTimeZone) and MontyFileHandle.
  • 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 accept MontyObject values; their iterators return borrowed values. Both carriers and the MontyObject / ObjectRef types 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 the stat_result builders hosts use to answer them.
  • MontyPath preserves OS-call paths for validation; normalize_virtual_path provides the lexical POSIX normalization shared by the interpreter, mounts, and OsFunctionCall::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 the max_suspensions budget hosts enforce themselves.
  • PrintStream / PrintWriter / CollectedStreams — print() output capture, and the labelled buffer behind PrintWriter::CollectStreams.
  • CompileOptions, ExtFunctionResult, NameLookupResult, FileMode, and the CPython-compatible formatting helpers behind their repr()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 crate
  • monty-fs — host-side filesystem mounts: maps virtual sandbox paths to real host directories.
  • monty-runtime — the monty binary: REPL, file runner, and subprocess worker mode.
  • monty-pool — an elastic pool of crash-isolated monty worker 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 behind monty’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_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 CallArgs host callbacks consume. The #[derive(ToArgs)] macro in monty-macros emits implementations via crate::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-offset timedelta reprs.
scan
Directory-tree scans: the one OS call behind os.scandir, os.walk, Path.walk, Path.glob and Path.rglob.
unstable
Representation access for bindings and transport adapters.

Structs§

CallArgs
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.
CollectedStreams
The buffer behind PrintWriter::CollectStreams: (stream, text) entries plus the running charge their cap is checked against.
CompileOptions
Options controlling how Monty behavior diverges from plain CPython.
ConversionError
Error returned when a MontyObject cannot be converted to the requested Rust type.
GetenvArgs
os.getenv(key, default=None) shape. The host decides whether to substitute default when the variable is unset.
JsonErrorData
Structured fields of a json.JSONDecodeError, mirroring CPython’s msg / doc / pos / lineno / colno exception attributes. tomllib.TOMLDecodeError defines the same five attributes, so it carries this payload too.
MkdirCallArgs
mkdir(path, parents=False, exist_ok=False) shape. parents/exist_ok are kw-only so ToArgs emits them as kwargs (matching CPython).
ModuleStub
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.
MontyComplex
A Python complex value as its two float parts.
MontyDate
A Python datetime.date value with year, month, and day components.
MontyDateTime
A Python datetime.datetime value with date, time, and optional timezone components.
MontyException
Public representation of a Monty exception.
MontyFileHandle
An open file object (the result of open()).
MontyObject
One owned Python value at the host boundary.
MontyPath
Owned virtual (sandbox) path carried by OS-call args.
MontyTime
A Python datetime.time value: a wall clock with no date attached.
MontyTimeDelta
A Python datetime.timedelta value representing a duration.
MontyTimeZone
A Python datetime.timezone fixed-offset timezone.
MontyUuid
A 16-byte UUID identifying a host or sandbox class/instance across the sandbox boundary.
NamedValues
The named inputs of one feed, preserving sharing between exported values.
NamedZone
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.
ObjectRef
A borrowed Python value, for inspecting results, arguments and inputs without copying.
OpenCallArgs
Arguments to open(): a virtual path and a parsed file mode.
OsPolicy
Policies for clocks, sleeps and initial random state on every execution path. CallHost suspends to the host, or raises NotImplementedError without 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 their os handler; standard execution waits inline.
PathBytesDataArgs
path + bytes data shape used by WriteBytes and AppendBytes.
PathStringDataArgs
path + str data shape used by WriteText and AppendText.
RenameCallArgs
rename(src, dst) shape.
ResourceLimits
Configuration for resource limits.
ResourceTracker
A resource tracker that enforces configurable limits.
SourceRange
The source range of the expression that suspended execution, carried by every suspension.
StackFrame
A single frame in a Python traceback.
TypeCheckState
Per-session type-check state: successfully committed snippets accumulate as stubs so later snippets can reference names defined by earlier ones.
TypeCheckingConfig
How a type check renders whatever diagnostics it finds.
UnicodeErrorData
Structured fields of a UnicodeDecodeError / UnicodeEncodeError, mirroring CPython’s encoding / object / start / end / reason exception attributes.
UnknownTimeZone
A zone name SandboxTimeZone::named could not resolve: malformed, or absent from the tz database available to this build.
UrandomArgs
os.urandom(size) shape. The interpreter rejects a negative size before suspending, so the count is unsigned; the host answers with exactly size bytes. size is sandbox-controlled, so a handler should cap it before allocating.
ZoneConstants
The zone’s standard and daylight halves as the time module reports them.

Enums§

AssertMessageAnnotations
Controls the pytest-style introspected assert failure messages of CompileOptions::assert_message_annotations.
BuiltinsFunctions
Enumerates every interpreter-native Python builtin function.
DateTimeSource
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’s errno/filename) without another field on every exception.
ExcType
Python exception types supported by the interpreter.
ExtFunctionResult
Return value or exception from an external function.
FileMode
A parsed Python open() mode.
InvalidInputError
Error returned when a value cannot be used as an input to code execution.
ModuleStubError
An invalid or reserved host module name; see validate_module_name.
MontyType
The Python type of a builtin at the host boundary: the public mirror of the runtime Type enum, minus class types, which cross as their own class_type value. Serializable and displayable without heap access.
NameLookupResult
Result of a name lookup from the host.
OsFunctionCall
Tagged dispatch value for OS-level operations.
PrintStream
Identifies the output stream for a single print fragment.
PrintWriter
Output handler for the print() builtin function.
ProcessTime
What time.process_time() and time.thread_time() report.
RandomSeed
Explicit seeds for RandomStart::Seed, using CPython’s random.seed() semantics.
RandomStart
Where an unseeded random generator gets its first state.
ResourceError
Error returned when a resource limit is exceeded during execution.
SandboxTimeZone
The sandbox’s local zone, UTC unless configured.
SleepError
Why a requested sleep length cannot be carried by an OS call.
SleepMode
What the sleep calls do.
TimeCaller
Which time function is reading the clock in an OsFunctionCall::Time.
TimeLimitScope
Which of the two nested execution-time budgets a ResourceError::Time refers to.
TypeCheckingFormat
How type-check diagnostics are rendered into text.
UnicodeErrorObject
The object attribute of a unicode error: the input being converted.

Constants§

CHECKER_MODULE_NAMES
Vendored typeshed modules outside SANDBOX_MODULE_NAMES, including private dependencies, plus ty’s ty_extensions. Hosts may provide these modules at runtime, but ModuleStub::new rejects 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_interval is None. Builds with monty’s memory-model-checks feature collect on every allocation instead.
DEFAULT_MAX_PRINT_COLLECT_BYTES
Default cap for PrintWriter::CollectString / PrintWriter::CollectStreams and 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 like IMPORT_CALL.
IMPORT_STUBS_CALL_ID
Reserved pre-feed OsFunctionCall::ImportStubs ID, outside the interpreter’s IDs counted from zero.
LARGE_RESULT_THRESHOLD
Threshold in bytes above which check_large_result is called.
MAX_SLEEP_SECONDS
Longest sleep the sleep calls accept, matching the point where CPython’s PyTime_t (nanoseconds in an i64) overflows.
MAX_TIMEZONE_OFFSET_SECONDS
Largest UTC offset datetime.timezone accepts, +23:59:59.
MIN_TIMEZONE_OFFSET_SECONDS
Smallest UTC offset datetime.timezone accepts, -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 MemoryError instead of an unclassifiable SIGABRT.
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’s StandardLib.
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§

PrintWriterCallback
Trait for custom output handling from the print() builtin function.

Functions§

allocate_into_baseline
Runs build and adds what it leaves allocated to BASELINE_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_result for a directory.
file_stat
Creates a stat_result for a regular file.
is_identifier
Returns true if a string is a valid Python identifier (e.g., variable name).
local_wall_clock
The wall clock offset_seconds from UTC at utc, or None outside the 1..=9999 years Python’s datetime can 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 Duration an OS call carries.
sleep_duration_saturating
Like sleep_duration, but for asyncio.sleep, which clamps rather than raising: a negative delay becomes no wait at all (CPython returns immediately) and an over-long one saturates at MAX_SLEEP_SECONDS. Only NaN is refused, the one delay CPython rejects there.
stat_result
Creates a full stat_result with all 10 fields specified.
symlink_stat
Creates a stat_result for a symbolic link.
unicode_decode_error_msg
Formats the message for a UnicodeDecodeError covering the byte range start..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_NAMES are valid runtime module names; only ModuleStub::new rejects them.