Skip to content

Errors

Every exception pydantic_monty raises, plus the traceback Frame they carry and the ExcType names accepted when answering a snapshot with an exception.

MontyError

Bases: Exception

Base exception for all Monty interpreter errors.

Catching MontyError will catch syntax, runtime, and typing errors from Monty. This exception is raised internally by Monty and cannot be constructed directly.

Methods

exception
def exception() -> BaseException

Returns the inner exception as a Python exception object.

Returns

BaseException

__str__
def __str__() -> str

Returns the exception message.

Returns

str

MontySyntaxError

Bases: MontyError

Raised when Python code has syntax errors or cannot be parsed by Monty.

Inherits exception(), str() from MontyError.

Methods

traceback
def traceback() -> list[Frame]

Returns the Monty traceback as a list of Frame objects.

Returns

list[Frame]

display
def display(format: Literal['traceback', 'type-msg', 'msg'] = 'traceback') -> str

Returns formatted exception string.

Returns

str

Parameters

format : Literal[‘traceback’, ‘type-msg’, ‘msg’] Default: 'traceback'

‘traceback’ - full traceback with exception ‘type-msg’ - ‘ExceptionType: message’ format ‘msg’ - just the message

MontyTypingError

Bases: MontyError

Raised when type checking rejects a fed snippet.

Type checking runs inside the worker subprocess; the diagnostics arrive pre-rendered as text, in the type_check_format chosen at checkout.

Inherits exception(), str() from MontyError. Cannot be constructed directly from Python.

Methods

display
def display() -> str

Returns the rendered type-check diagnostics.

Returns

str

MontyRuntimeError

Bases: MontyError

Raised when Monty code fails during execution.

Inherits exception(), str() from MontyError. Additionally provides traceback() and display() methods.

Methods

traceback
def traceback() -> list[Frame]

Returns the Monty traceback as a list of Frame objects.

Returns

list[Frame]

display
def display(format: Literal['traceback', 'type-msg', 'msg'] = 'traceback') -> str

Returns formatted exception string.

Returns

str

Parameters

format : Literal[‘traceback’, ‘type-msg’, ‘msg’] Default: 'traceback'

‘traceback’ - full traceback with exception ‘type-msg’ - ‘ExceptionType: message’ format ‘msg’ - just the message

MontyConversionError

Bases: MontyError

Raised when a host value cannot be converted across the Monty/host boundary.

A value Monty cannot represent — an external_lookup entry or an inputs value of an unsupported type — rejects the feed with this error rather than crossing into the sandbox. Inherits exception() (a native TypeError) and __str__() (the conversion message) from MontyError.

MontyCrashedError

Bases: MontyError

Raised when the sandbox is gone and the session with it.

This is the failure mode subprocess pools exist to contain: the worker is gone — segfault, allocator abort, external kill, request_timeout watchdog, or a fatal error it announced before exiting — but the host process is unharmed and the pool replaces it. A remote server also reports its own failure to start a worker this way. Catch this error to retry or report; the message says which happened.

exit_status is None whenever the process could not be reaped, which includes every remote worker.

Cannot be constructed directly from Python.

Attributes

timed_out

True when a client-side elapsed-time or CPU watchdog killed the worker.

Type: bool

exit_status

Exit code of the dead worker when the OS reported one (signal deaths report None).

Type: int | None

MontyDisconnectError

Bases: MontyError

Raised when a remote worker’s stream ended mid-session (remote transport only).

The local analogue is MontyCrashedError. The sandbox may have died, the connection may have dropped, or the server may have ended the session by policy — an idle, session, or turn timeout, or being over capacity (a worker out of memory is reported as MemoryError instead). A server that did so says which in status_code, status_message and cause; otherwise this error claims no more than that the stream went away. The request may have run; do not replay it automatically.

Cannot be constructed directly from Python.

Attributes

status_code

The gRPC status code the server ended the stream with, by its canonical name (DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, …); OK when it simply finished the stream; None for a transport failure.

Type: str | None

status_message

The message on that status, or None without one.

Type: str | None

cause

The policy reason the server attached to the status, in snake_case (idle_timeout, session_timeout, turn_timeout, capacity, …), or None when it attached none this client knows.

Type: str | None

transport_error

The recorded transport or protocol error, or None when the server sent a status.

Type: str | None

MontyRefusedError

Bases: MontyError

Raised when the remote server refused to open a session’s stream (remote transport only).

The server was at capacity (capacity, or caller_cap for this caller’s share of it), could start no worker (worker_unavailable), or rejected the caller’s credentials (unauthenticated) or what a valid credential asked for (permission_denied); it says which in status_code, status_message and cause. No session existed, so nothing ran. retryable identifies temporary refusals. A server that could not be reached, that answered with any other status (such as UNIMPLEMENTED from a URL that is no Monty server), or that is no gRPC server at all (such as a web server’s page), raises MontyConnectError instead.

Cannot be constructed directly from Python.

Attributes

status_code

The gRPC status code the server refused with, by its canonical name (RESOURCE_EXHAUSTED, UNAUTHENTICATED, PERMISSION_DENIED, …).

Type: str | None

status_message

The message on that status, or None without one.

Type: str | None

cause

The policy reason the server attached to the status, in snake_case (capacity, caller_cap, unauthenticated, permission_denied, worker_unavailable, …), or None when it attached none this client knows.

Type: str | None

retryable

True for RESOURCE_EXHAUSTED or UNAVAILABLE, not for credential errors.

No automatic retry is performed. A disconnected request must not be replayed.

Type: bool

retry_after

Suggested delay in seconds from Retry-After, or None if absent or invalid.

Both delay-seconds and HTTP dates are accepted. Past dates give zero; delays are capped at one hour. A retry delay does not make a permanent refusal retryable.

Type: float | None

MontyConnectError

Bases: MontyError

Raised when a remote connection fails before a session opens.

This includes invalid URLs, DNS and TLS failures, timeouts, HTTP responses that are not gRPC, and unexpected gRPC statuses. Nothing ran. Cannot be constructed directly from Python.

Attributes

status_code

The canonical gRPC code, or None when the server sent no status.

Type: str | None

status_message

The server’s status message, or None.

Type: str | None

cause

The recognized policy reason in monty-cause, in snake_case, or None.

Type: str | None

transport_error

The underlying transport error, or None when the server sent a status.

Type: str | None

MontyConfigurationError

Bases: MontyError

Raised for invalid pool settings, malformed request metadata, or settings incompatible with the remote server.

CPU-mode pools and servers require a finite client request_timeout. A worker or server refusing the session’s configuration (deeply nested type_check_stubs, an unknown profile) raises it as session refused: … from the session’s first request, which did not run, or from get_session_id() when it opens the session alone; the session is lost. Options the binding checks itself, such as os_policy, raise TypeError or ValueError from checkout() instead. Cannot be constructed directly from Python.

MontyShutdown

Bases: MontyError

Raised when the remote server is shutting down (remote transport only).

Not an error in your code, which is why it is the one exception here without an Error suffix; it still subclasses MontyError. The request that raised it did not run, so re-running it on a fresh session is safe.

dump is what restores the session on a new one, with session.load_session (idle, between feeds) or session.load_snapshot (suspended mid-feed): the session’s ID from a server that stores sessions. It is None from a server that stores nothing, for an ephemeral session, or when the server could not store the session in time.

One caveat: if the interrupted request was answering a suspension (an external function or os callback), the host already ran that call and the restored session re-announces it, so it runs again. Make such callbacks idempotent if you intend to restore across a shutdown.

Cannot be constructed directly from Python.

Attributes

dump

What load_session / load_snapshot restores, or None when there is nothing to load.

Type: bytes | None

Frame

A single frame in a Monty traceback.

Attributes

filename

The filename where the code is located.

Type: str

line

Line number (1-based).

Type: int

column

Column number (1-based).

Type: int

end_line

End line number (1-based).

Type: int

end_column

End column number (1-based).

Type: int

function_name

The name of the function, or None for module-level code.

Type: str | None

source_line

The source code line for preview in the traceback.

Type: str | None

Methods

dict
def dict() -> dict[str, int | str | None]

dict of attributes.

Returns

dict[str, int | str | None]

ExcType

String names of Python exception types that Monty understands.

Used by ExternalExceptionData to identify an exception by name rather than passing a concrete Python exception instance. Names match Python’s built-in exception classes, except for json.JSONDecodeError, tomllib.TOMLDecodeError, re.PatternError, binascii.Error, binascii.Incomplete, statistics.StatisticsError, _csv.Error and the decimal signals (decimal.InvalidOperation, …), which are dotted to disambiguate from their ValueError / Exception / ArithmeticError parents.

Default: Literal['Exception', 'BaseException', 'SystemExit', 'KeyboardInterrupt', 'ArithmeticError', 'OverflowError', 'ZeroDivisionError', 'LookupError', 'IndexError', 'KeyError', 'RuntimeError', 'NotImplementedError', 'RecursionError', 'AttributeError', 'FrozenInstanceError', 'NameError', 'UnboundLocalError', 'ValueError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'json.JSONDecodeError', 'tomllib.TOMLDecodeError', '_csv.Error', 'ImportError', 'ModuleNotFoundError', 'OSError', 'FileNotFoundError', 'FileExistsError', 'IsADirectoryError', 'NotADirectoryError', 'PermissionError', 'io.UnsupportedOperation', 'AssertionError', 'MemoryError', 'StopIteration', 'SyntaxError', 'TimeoutError', 'TypeError', 're.PatternError', 'binascii.Error', 'binascii.Incomplete', 'statistics.StatisticsError', 'decimal.DecimalException', 'decimal.Clamped', 'decimal.InvalidOperation', 'decimal.ConversionSyntax', 'decimal.DivisionByZero', 'decimal.DivisionImpossible', 'decimal.DivisionUndefined', 'decimal.Inexact', 'decimal.InvalidContext', 'decimal.Rounded', 'decimal.Subnormal', 'decimal.Overflow', 'decimal.Underflow', 'decimal.FloatOperation']