gisolate
Gevent has tormented me a thousand times, yet I keep coming back for more. This library is proof of that love.
Process isolation for gevent applications. Run any object in a clean subprocess, call its methods transparently via ZMQ IPC.
Why
gevent's monkey.patch_all() replaces stdlib modules globally. Some libraries (database drivers, native async frameworks, etc.) break under monkey-patching. gisolate spawns a clean child process — no monkey-patching — and proxies method calls over ZMQ, so incompatible code runs in isolation while your gevent app stays cooperative.
Install
pip install gisolate
Requires Python 3.13+.
Quick Start
ProcessProxy — persistent child process
Proxy method calls to an object living in an isolated subprocess:
import gevent.monkey
gevent.monkey.patch_all()
from gisolate import ProcessProxy
# Define a factory (must be importable / picklable)
def create_client():
from some_native_lib import Client
return Client(host="localhost")
# Option 1: inline
proxy = ProcessProxy.create(create_client, timeout=30)
result = proxy.query("SELECT 1") # runs in child process
proxy.shutdown()
# Option 2: subclass
class ClientProxy(ProcessProxy):
client_factory = staticmethod(create_client)
timeout = 30
with ClientProxy() as proxy:
result = proxy.query("SELECT 1")
serve / attach — one worker, many client processes
A ProcessProxy spawns a worker at a random address it never advertises, so N
client processes pay for N copies of the isolated library. Where that matters (several gunicorn workers in
one container, say), one process hosts the worker and the rest attach to it:
# Host process — becomes the worker; blocks.
import os
from gisolate import serve
os.makedirs("/run/myapp", exist_ok=True)
os.chmod("/run/myapp", 0o700) # mode= on makedirs only applies when it creates
serve(create_client, "ipc:///run/myapp/client.sock")
# Every client process — no spawn, no factory.
from gisolate import ProcessProxy
proxy = ProcessProxy.attach("ipc:///run/myapp/client.sock", timeout=10)
result = proxy.query("SELECT 1") # runs in the host
proxy.shutdown() # closes this client only; the host keeps serving
Put the socket in a directory you control. The wire is unauthenticated
pickle and an empty frame stops the worker, so anyone who can connect can run
code in the host or shut it down for every client. The socket file's own mode
follows the host's umask — a world-writable one in a shared directory like
/tmp is reachable by any local user — whereas a 0700 directory is not,
whatever the umask. ipc:// only, and same host only: a call carries the
caller's monotonic deadline, which means nothing on another machine's clock.
Attaching is asynchronous: it connects to an address nobody has bound yet just as
happily, a restarted host is picked up by the DEALER's own reconnect, and an
absent one surfaces as an RPC timeout. The proxy is process-local like any ZMQ
socket — a forking server attaches after the fork, once per worker. serve()'s
max_concurrency bounds the worker, so it is shared by every client.
run_in_subprocess — one-shot call
Run a single function in a subprocess and get the result:
from gisolate import run_in_subprocess
def heavy_compute(n):
return sum(range(n))
result = run_in_subprocess(heavy_compute, args=(10_000_000,), timeout=60)
ProcessBridge — cross-process RPC
ZMQ-based RPC bridge for server/client architectures. Server side uses gevent, client side uses asyncio:
from gisolate import ProcessBridge
# Server (gevent side)
server = ProcessBridge("ipc:///tmp/rpc.sock", mode=ProcessBridge.Mode.SERVER)
server.start()
# Client (asyncio side)
import asyncio
async def main():
client = ProcessBridge("ipc:///tmp/rpc.sock", mode=ProcessBridge.Mode.CLIENT)
result = await client.call(lambda x, y: x + y, 3, 4, timeout=5)
print(result) # 7
client.close()
asyncio.run(main())
server.close()
ProcessPublisher / ProcessSubscriber — one-way fan-out
ZMQ PUB/SUB for one-way data streaming (snapshots, signals, heartbeats). Use this when message loss is acceptable; use ProcessBridge when you need request/response with delivery guarantees.
Both ends take a runtime= kwarg (a PubSubRuntime enum, also accepts the strings "gevent" / "asyncio") selecting the concurrency backend:
| Class | Default runtime | publish / close |
|---|---|---|
ProcessPublisher |
PubSubRuntime.GEVENT |
sync in GEVENT, awaitable in ASYNC |
ProcessSubscriber |
PubSubRuntime.ASYNC |
close sync in GEVENT, awaitable in ASYNC; handlers must be sync in GEVENT and async def in ASYNC |
The wire format is identical across runtimes, so a gevent publisher pairs with an asyncio subscriber (and vice versa) without any adapter.
# Producer (gevent side — default runtime)
from gisolate import ProcessPublisher
pub = ProcessPublisher("ipc:///tmp/stream.sock").start()
pub.publish("v1.snapshot.AAPL", {"price": 150.0})
pub.publish("v1.heartbeat.gevent", {"ts_ns": 1234567890})
pub.close()
# Consumer (asyncio side — default runtime)
import asyncio
from gisolate import ProcessSubscriber
async def main():
sub = ProcessSubscriber("ipc:///tmp/stream.sock")
async def on_snapshot(topic, payload):
print(topic, payload)
async def on_heartbeat(topic, payload):
print("heartbeat", payload)
sub.subscribe("v1.snapshot.", on_snapshot)
sub.subscribe("v1.heartbeat.", on_heartbeat)
sub.start()
await asyncio.sleep(10)
await sub.close()
asyncio.run(main())
Asyncio publisher / gevent subscriber — same wire format, just flip the runtime=:
# Producer (asyncio side)
from gisolate import ProcessPublisher, PubSubRuntime
async def producer():
async with ProcessPublisher(addr, runtime=PubSubRuntime.ASYNC) as pub:
await pub.publish("v1.tick.AAPL", {"price": 150.0})
# Consumer (gevent side) — handlers are sync
from gisolate import ProcessSubscriber, PubSubRuntime
def on_tick(topic, payload): # sync, not async def
print(topic, payload)
with ProcessSubscriber(addr, runtime=PubSubRuntime.GEVENT) as sub:
sub.subscribe("v1.tick.", on_tick)
gevent.sleep(10)
Notes:
- Runtime must match the host loop —
start()requires a running asyncio loop in ASYNC mode and a greenlet context in GEVENT mode. Subsequentsubscribe/unsubscribe/publish/closecalls must stay on that same loop/hub; ZMQ sockets are not thread-safe. - Handler signature follows the subscriber's runtime, not the publisher's — a gevent subscriber consuming from an asyncio publisher still uses sync handlers.
- Context managers —
withfor GEVENT,async withfor ASYNC; using the wrong form raisesRuntimeError.start()andclose()are idempotent. - Topic prefix matching —
sub.subscribe("v1.snapshot.", h)receives every topic starting with that prefix. Multiple handlers may share a prefix; in ASYNC mode they run viaasyncio.gather, in GEVENT mode each is spawned in its own greenlet. An exception in one handler is logged and does not kill the reader. close()from inside a handler is safe — the reader is not joined in that case (would self-deadlock); sibling handlers in the current dispatch are allowed to finish.- Lossy by design —
publishis non-blocking; messages are dropped when the send queue is full (slow subscriber). Tune viasndhwm=on the publisher. - Late joiners miss history — PUB/SUB has no replay; a subscriber that connects after a message was published will not see it. Treat published state as a stream, not a store.
- IPC cleanup —
close()unlinks the socket file foripc://addresses on the publisher side. Relying on__del__is best-effort only; callclose()(or use a context manager) for deterministic teardown. - Pluggable serializer — defaults to
SmartPickle(pickle, falling back to dill). Pass any object implementing theSerializerprotocol (dumps/loads) to use msgpack, JSON, etc. Publisher and subscriber must agree.
ThreadLocalProxy — per-thread instances
Thread-local proxy using unpatched threading.local for true isolation in gevent.threadpool:
from gisolate import ThreadLocalProxy
proxy = ThreadLocalProxy(create_client)
proxy.query("SELECT 1") # each real OS thread gets its own instance
AsyncioThread — asyncio on a native thread
One asyncio loop on one real OS thread inside the gevent process — for a library that only speaks asyncio (an ASGI app, an async SDK's protocol engine) when a child process is too much. The loop is built on the unpatched poll() and socketpair(), so nothing in that thread ever waits on a gevent hub; application and network I/O stay on the gevent side. That is a boundary, not a convenience: an asyncio socket, or the getaddrinfo behind one, needs the loop's executor, which is refused (below) — hand the I/O to to_gevent.
from gisolate import AsyncioThread
aio = AsyncioThread().start() # once per process, after any fork
async def handle(payload):
# ... asyncio-only code ...
rows = await aio.to_gevent(query_db, payload) # hop back: runs in a greenlet on the gevent thread
return rows
result = aio.call(handle(payload), timeout=30) # from any greenlet: blocks only that greenlet
aio.stop()
Both crossings are cancellable from either side: a timeout, gevent.Timeout or killed greenlet cancels the coroutine, and call() returns only once the loop has unwound it (6s grace); a cancelled coroutine kills the greenlet it awaits. A dead loop fails every in-flight call() with LoopStopped. While threading is monkey-patched, run_in_executor / asyncio.to_thread are refused (their worker would be a greenlet on the loop's own blocked thread) — use to_gevent.
Child Process Modes
patch_kwargs |
Child process runtime |
|---|---|
None (default) |
asyncio event loop |
dict |
gevent with patch_all(**patch_kwargs) |
# Child uses asyncio (default)
proxy = ProcessProxy.create(factory)
# Child uses gevent with selective patching
proxy = ProcessProxy.create(factory, patch_kwargs={"thread": False, "os": False})
API Reference
ProcessProxy
ProcessProxy.create(factory, *, timeout=24, max_concurrency=None, mp_context=None, patch_kwargs=None)— create a proxy without subclassingproxy.<method>(*args, **kwargs)— transparently call any method on the remote objectProcessProxy.attach(address, *, timeout=24)— proxy a worker hosted byserve(); never spawns, andshutdown()leaves the worker runningproxy.restart_process()— kill and restart the child process; on an attached proxy there is no process to kill, so it rebuilds the local transport insteadproxy.shutdown()— gracefully stop child process- Supports context manager (
withstatement) - Thread-safe: usable from greenlets and native threads
serve(factory, address, *, patch_kwargs=None, max_concurrency=None)
Turn this process into the worker, bound to address, for clients that
ProcessProxy.attach(). Blocks until interrupted or terminated.
run_in_subprocess(target, args=(), kwargs=None, *, timeout=3600, mp_context=None, poll_interval=0.1, daemon=True)
Run a function in an isolated subprocess. Blocks with gevent-safe polling.
ProcessBridge(address, mode)
ipc:// only — the wire is unauthenticated pickle.
bridge.start()— start the bridge (idempotent, returns self)bridge.address— IPC addressawait bridge.call(func, *args, timeout=60, **kwargs)— async RPC call (client mode)bridge.close()— cleanup resources
ProcessPublisher(address, *, runtime=PubSubRuntime.GEVENT, serializer=SmartPickle, sndhwm=1000)
pub.start()— bind the PUB socket (idempotent, returns self). In ASYNC mode requires a running asyncio loop.pub.publish(topic, payload)— non-blocking publish; drops on slow consumers. ReturnsNonein GEVENT mode, a coroutine in ASYNC mode (mustawait).pub.close()— cleanup (idempotent). ReturnsNonein GEVENT mode, a coroutine in ASYNC mode.pub.address/pub.runtime— read-only properties.- Context manager:
withfor GEVENT,async withfor ASYNC. Using the wrong form raisesRuntimeError.
ProcessSubscriber(address, *, runtime=PubSubRuntime.ASYNC, serializer=SmartPickle)
sub.subscribe(topic_prefix, handler)— register a handler for a topic prefix. Handler must be sync (def) in GEVENT mode andasync def(or returning an awaitable) in ASYNC mode. Safe to call before or afterstart().sub.unsubscribe(topic_prefix, handler=None)— remove a specific handler or all handlers for a prefix. When the last handler is removed, the ZMQ-level subscription is dropped.sub.start()— connect and spawn the reader (idempotent, returns self). In ASYNC mode requires a running asyncio loop; in GEVENT mode must be called from a greenlet context.sub.close()— tear down the socket and join the reader (idempotent). ReturnsNonein GEVENT mode, a coroutine in ASYNC mode. Safe to call from inside a handler — the reader is not joined in that case to avoid self-deadlock.sub.address/sub.runtime— read-only properties.- Context manager:
withfor GEVENT,async withfor ASYNC.
PubSubRuntime (StrEnum)
PubSubRuntime.GEVENT("gevent") — bind to the gevent hub; sync APIs and sync handlers.PubSubRuntime.ASYNC("asyncio") — bind to the running asyncio loop; awaitable APIs and async handlers.
Serializer (Protocol)
Anything with dumps(obj) -> bytes and loads(bytes) -> obj static methods can be used as a serializer for ProcessPublisher / ProcessSubscriber. Default is SmartPickle (pickle, falling back to dill). Publisher and subscriber must agree on the serializer.
ThreadLocalProxy(factory)
Transparent proxy delegating attribute access to a per-thread instance.
AsyncioThread(*, start_timeout=10.0)
POSIX only (a native socketpair for the loop's wake-up pipe).
.start()/.stop(timeout=10.0)— start / stop the loop thread (also a context manager).stop()kills every greenlet ato_geventawaits and cancels every other task: a call whose coroutine honours the cancellation raisesLoopStopped, one that finishes anyway gets its answer. The teardown is bounded by a 6s grace, after which whatever has not yielded is abandoned and the loop closed; nothing more is promised for a coroutine that resists cancellation (full contract in the docstring).call(coro, timeout=None)— run a coroutine on the loop from a greenlet; raisesWaitTimeouton timeout and cancels the coroutine whenever the caller leaves earlyawait .to_gevent(fn, *args, **kwargs)— from the loop: runfnin a fresh greenlet on the thread that called in (the starting thread for tasks nobody called in); a killed greenlet raisesGreenletExithere, a cancelled await kills the greenlet
LoopStopped / WaitTimeout
LoopStopped: raised by call() when the loop is not running, or stopped before the call completed. WaitTimeout: call()'s timeout, exported here as well as from gisolate.hub.
ensure_hub_started()
Pre-start the internal gevent hub loop on demand. Idempotent and thread-safe. Called automatically by ProcessProxy, but can be invoked explicitly to control initialization timing.
spawn_on_main_hub(func, *args, **kwargs)
Schedule a function on the main gevent hub without waiting. Thread-safe, fire-and-forget.
ProcessError
Raised when a child process dies or communication fails.
RemoteError
Wrapper for exceptions from the child process that can't be pickled. Preserves the original exception type name and message.
shutdown_hub()
Stop accepting cross-thread marshaled tasks: afterwards spawn_on_main_hub drops
its task and a proxy call from another thread raises RuntimeError. Registered
via atexit automatically.
set_default_mp_context(ctx) / get_default_mp_context()
Configure the default multiprocessing context for all proxies (default: "spawn").
Note on multiprocessing and __main__
gisolate children never re-import the caller's __main__, so its top-level
side effects (a gevent.monkey.patch_all(), say) do not run twice. Only
gisolate's own starts are affected — the suppression is scoped to the starting
greenlet or thread, so other multiprocessing children keep their __main__.
The flip side: the factory travels by value, but any name it reaches for in
__main__ is a NameError in the child. Keep the factory and what it uses in
an importable module.
Known limits
Deliberate trade-offs, each documented at the code it concerns.
- Asyncio worker: what it cannot interrupt. Sync methods and a sync
factory()/connect()run on the default executor: an expired deadline abandons the wait, not the thread, so side effects can land after the caller saw a timeout, andmax_concurrencycounts handlers, not those threads (a client whose sync methods must not overlap needs its own lock). A client build that never finishes is never cancelled or retried — every call times out against it until the worker is restarted. On shutdown, a cancelled handler'sfinallymay run after the client is closed, andserve()has no hard bound: past the 6s drain, a coroutine that swallows its cancellation holds the host open. The gevent worker has no executor gap:kill()lands inside client code at its next switch. - A subscriber handler that never returns wedges its subscriber. Each batch
of handlers is awaited before the next receive, so a slow handler gets
backpressure from SUB's queue and PUB's high-water mark; one that never
returns stops the stream, and
close()does not kill it. - Construct a
ProcessProxyon the main thread. Its socket, reader and lifecycle belong to the constructing thread's hub, but other threads marshal to the MAIN hub; built on a native thread, the two disagree (undefined behaviour for a ZMQ socket). Calling and restarting from any thread is fine. ProcessBridgebelongs to one thread.start()/close()are unsynchronized; concurrentcall()from coroutines on the owning thread is supported. UseProcessProxywhen calls come from several threads.- A
ProcessProxydropped withoutshutdown()is never collected. The hub holds its reader and the reader holds it, so child, socket and socket file live until process exit;__del__is a best-effort backstop only. - A revival is not bounded by the call that triggers it. The deadline
bounds the marshal, not the respawn;
restart_cooldownbounds how often. - An interrupt inside
Process.start()can orphan the worker. One (e.g. Ctrl-C) landing after the child's bootstrap payload is written but before multiprocessing publishes the process handle leaves a live worker and its socket file — the same end state as SIGKILL of the parent. One landing during the payload write leaves a child that exits once the parent exits. - Under
patch_all, a child that dies before reading a bootstrap payload larger than the pipe buffer can leave the parent blocked inProcess.start(). gevent defersos.close, so the write gets no EPIPE. Reach:run_in_subprocesswith multi-MB arguments. ipc://socket files: a rebind inside microsecond windows around our claim or release can be taken for ours;ipc://@nameleaks its file off Linux, where@is an ordinary path character.serve()trusts whoever can connect. The wire is unauthenticated pickle and an empty frame stops the worker, so the socket's directory is the access control. A spawnedProcessProxygets a per-uid0700directory for free.
License
MIT
Metadata
Release files for gisolate 0.2.32
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gisolate-0.2.32.tar.gz | 125.9 kB | Without provenance | Details for gisolate-0.2.32.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gisolate-0.2.32-py3-none-any.whl | Python 3 | none | any | Details for gisolate-0.2.32-py3-none-any.whl |
Total release size: 182.6 kB
Release files / gisolate-0.2.32.tar.gz
| Download URL | gisolate-0.2.32.tar.gz |
|---|---|
| Size | 125.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
08a401cfec044a6dba9353386e2d086aa8c645095e98a6a525bb225b347fa570
|
|
BLAKE2b-256 checksum How to use checksums |
6dd9927ff1e13f3fbc62f1857088c6325a90c720eb70a5e5ebbd32f96cd103a8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.7
|
Release files / gisolate-0.2.32-py3-none-any.whl
| Download URL | gisolate-0.2.32-py3-none-any.whl |
|---|---|
| Size | 56.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ed930adb3c39d26459dcafb0eb85453e080ac6aebdebe9fb331e7450dfbb0960
|
|
BLAKE2b-256 checksum How to use checksums |
653c01c34bce87d5958e7f845c42ad5698f32f59cd262ff69372efcc68c84332
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.7
|
Security for gisolate 0.2.32
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.