Synchronous Connection

Import Connection from rmote.sync. Create a connection with from_local, from_command or from_ssh. Direct construction with Connection() raises TypeError.

See Transports for SSH, Docker/Kubernetes exec, local Python and relay adapters. The same connection API and tool calls apply to each transport.

class rmote.sync.Connection[source]

Own a subprocess, a protocol, and a private background event loop. Use a factory and close the connection after its callers finish.

classmethod from_local(*, python='/home/runner/work/rmote/rmote/.venv/bin/python', cwd=None, env=None, stderr=-1, connect_timeout=30.0, rpc_timeout=None, close_timeout=5.0, tls=None, decode_threshold=32768, accept_code=False, accept_calls=False, pickle_allowlist=None)[source]

Start a local Python interpreter and complete its protocol handshake.

Arguments go directly to subprocess exec, without a shell. The default stderr is a pipe that the connection reads: its last lines explain a failed start, and the rest is dropped.

Return type:

Self

classmethod from_command(*argv, python='python3', cwd=None, env=None, stderr=-1, start_new_session=False, connect_timeout=30.0, rpc_timeout=None, close_timeout=5.0, tls=None, decode_threshold=32768, accept_code=False, accept_calls=False, pickle_allowlist=None)[source]

Connect through a command that passes stdin and stdout unchanged.

Append python -qui to argv, without a shell. For example, from_command("docker", "exec", "-i", "app") starts docker exec -i app python3 -qui. Do not request a transport TTY. Empty argv starts the specified interpreter locally.

cwd and env configure the local transport process. Stderr and deadlines behave as in from_local() and from_ssh(). start_new_session isolates the transport from terminal signals, useful when the caller handles Ctrl-C itself.

tls establishes TLS before the protocol handshake. Its certificate paths are local. Bootstrap still requires a trusted transport.

decode_threshold sets the receive worker threshold in decoded bytes on both endpoints (default 32 KiB). Pass -1 to decode inline throughout. accept_code and accept_calls apply to the local endpoint only. Both default to False. Code-disabled endpoints use strict pickle decoding. A pickle_allowlist mapping adds local permitted globals; None uses the default permissions. Code-enabled endpoints use ordinary pickle decoding and do not consult the allowlist.

Return type:

Self

classmethod from_ssh(host, *, user=None, port=None, identity=None, python='python3', ssh_options=None, stderr=-1, connect_timeout=30.0, rpc_timeout=None, close_timeout=5.0, tls=None, decode_threshold=32768, accept_code=False, accept_calls=False, pickle_allowlist=None)[source]

Start SSH and complete the remote Python protocol handshake.

Return type:

Self

__call__(tool, /, *args, **kwargs)[source]
Overloads:
  • self, tool (Callable[P, AsyncIterator[Any]]), args (P.args), kwargs (P.kwargs) → Never

  • self, tool (Callable[P, Coroutine[Any, Any, R]]), args (P.args), kwargs (P.kwargs) → R

  • self, tool (Callable[P, R | Coroutine[Any, Any, R]]), args (P.args), kwargs (P.kwargs) → R

Call a Tool method using the connection’s default RPC deadline.

Both synchronous and asynchronous Tool methods return their result. Every keyword argument belongs to the remote method. Async generator methods require the asynchronous Protocol client and raise TypeError here before any remote call.

call_with_timeout(timeout, tool, /, *args, **kwargs)[source]
Overloads:
  • self, timeout (float | None), tool (Callable[P, AsyncIterator[Any]]), args (P.args), kwargs (P.kwargs) → Never

  • self, timeout (float | None), tool (Callable[P, Coroutine[Any, Any, R]]), args (P.args), kwargs (P.kwargs) → R

  • self, timeout (float | None), tool (Callable[P, R | Coroutine[Any, Any, R]]), args (P.args), kwargs (P.kwargs) → R

Call a Tool with a deadline covering upload, send, and response.

None disables this call’s deadline. Timeout and KeyboardInterrupt stop local waiting. They do not stop the remote operation. A cancellation during packet transmission can make the connection unusable. After a detected transport failure, new calls raise ConnectionError with the original error as their cause. Calls already waiting for a response propagate the original transport error. Async generator methods raise TypeError; use Protocol for streaming.

uncompressed(tool, /, *args, **kwargs)[source]
Overloads:
  • self, tool (Callable[P, AsyncIterator[Any]]), args (P.args), kwargs (P.kwargs) → Never

  • self, tool (Callable[P, Coroutine[Any, Any, R]]), args (P.args), kwargs (P.kwargs) → R

  • self, tool (Callable[P, R | Coroutine[Any, Any, R]]), args (P.args), kwargs (P.kwargs) → R

Call without compressing the request or the response.

Use it for data that cannot shrink, such as an archive or an image: the bytes then skip the dictionary of the connection instead of paying a deflate pass that gains nothing.

The deadline is the connection’s default. All arguments belong to the tool, including a keyword named compressed, and a neighbouring call keeps its own policy. Async generator methods raise TypeError, as they do for an ordinary call.

close()[source]

Close the protocol, reap the process, and join the runtime thread.

Concurrent calls wait for the same cleanup. Repeated calls are safe. Process shutdown uses close_timeout, then terminate and kill. Cancellation and executor shutdown require cooperative local code.

Return type:

None

__enter__()[source]
Return type:

Self

__exit__(exc_type, exc_value, traceback)[source]
Return type:

None

Endpoint permissions and strict decoding

Factories accept accept_code=False, accept_calls=False and an optional pickle_allowlist for the local endpoint. Code-disabled endpoints always use strict decoding. Built-in Tool models are registered; application types use local register or a connection allowlist. None does not disable strict decoding. With accept_code=True, the endpoint accepts Python code and uses ordinary pickle, ignoring the allowlist. The bootstrapped executor enables code and calls. See Protocol and Tool Support for the contract and compatibility. The Tool call syntax stays the same.

Deadlines

All factories accept these keyword-only arguments:

  • connect_timeout=30.0 limits process creation, bootstrap, and handshake.

  • rpc_timeout=None sets the default deadline for each Tool call.

  • close_timeout=5.0 limits graceful protocol and process shutdown.

None disables a connect or RPC deadline. Numeric deadlines must be finite and positive. close_timeout must be finite and positive; it cannot be None. Invalid values raise ValueError before resource creation.

connection.call_with_timeout(timeout, tool, /, *args, **kwargs) overrides the default RPC deadline for one call. It includes the first Tool upload, packet transmission, and response. All keyword arguments go to the Tool method, including arguments named timeout or tool.

connection.uncompressed(tool, /, *args, **kwargs) calls without compressing the request or the response. Use it for data that cannot shrink, such as an archive or an image: those bytes then skip the dictionary of the connection instead of paying a deflate pass that gains nothing. The call keeps the default deadline, every argument belongs to the Tool method, and a neighbouring call keeps its own policy. See the frame codec.

Timeout raises TimeoutError. KeyboardInterrupt propagates unchanged. Both stop local waiting; the remote operation can continue. Cancellation during packet transmission can make the connection unusable. Close it and create a new connection after a transport failure.

Ownership and concurrency

Each connection owns one subprocess, one protocol, and one private event loop in a background thread. Factories return after the handshake completes. Factory failure or interruption cleans up partially created resources.

Use with or call close() in finally. Closing rejects new calls, closes the channel, reaps the process, and joins the background thread. After close_timeout, process cleanup uses terminate, a one-second grace period, then kill and wait. This is not a fixed total limit for close(): local cancellation and executor shutdown require cooperative code.

Repeated close() calls are safe. Concurrent closes wait for the same cleanup. Nested context entry and calls after closing raise RuntimeError. Context exit preserves an exception raised by the body; cleanup errors are logged when a body exception already exists.

Multiple caller threads can share an open connection. Remote log records run local logging handlers in a delivery thread, so the time a handler takes does not limit the throughput of calls. Handlers must be thread safe and must not call this connection’s synchronous methods, because close() waits for the records that are still queued. Calls from the loop thread of the connection raise RuntimeError.

The throughput of one connection flattens as caller threads are added, because the interpreter lock serializes the Python work of every call. On a local transport with a tool that returns at once, one connection served 4 500 calls per second from one thread, 15 900 from eight, 19 000 from sixteen, 21 500 from thirty-two and 23 400 from sixty-four; the next doubling added 4 percent. The CPU the loop thread spends per call falls the whole way, from 62 to 30 microseconds, so nothing collapses past the knee: a wider pool simply stops paying off. Open a second connection when one is not enough.

In async applications, use Protocol or move the complete synchronous lifecycle into asyncio.to_thread. A direct synchronous call blocks the calling event loop. Shared runtimes, automatic reconnect, and remote cancellation are not supported.

See Quickstart, Work with Multiple Hosts, and Writing Tools for executable examples and Tool definitions.