A Python runtime interface for Chalk's RemoteCallService. This package provides a gRPC server backed by a Rust implementation (tonic + PyO3) that lets you define a handler(event, context) function to process incoming Arrow-serialized requests.
The server receives Arrow IPC record batches over a bidirectional gRPC stream, transforms them into a Python dict, invokes your handler, and streams the results back as Arrow IPC.
Requirements
Python >= 3.10
Rust 1.99.0 (for building the native extension)
pyarrow >= 14.0.0
Usage
1. Write a handler
Create a Python module with a handler function:
# my_handler.py
import pyarrow as pa
import pyarrow.compute as pc
def on_startup():
"""Optional -- runs once before the server starts accepting requests."""
print("Loading model weights...")
def handler(event: dict[str, pa.Array], context: dict) -> pa.Array:
"""Called for each incoming request.
Args:
event: dict mapping column names to pyarrow.Array values.
context: dict with request metadata
Returns:
A pyarrow.Array, pyarrow.RecordBatch, pyarrow.Table, list, dict, or scalar.
The framework auto-converts the result to Arrow IPC for the response.
"""
return pc.multiply(event["x"], event["y"])
def on_shutdown():
"""Optional -- runs once after the server stops accepting requests."""
print("Releasing resources...")
The CLI writes Python logs to stderr as one JSON object per line, with separate
timestamp, severity, logger, and message fields. Exceptions include an
exception.stacktrace field, which the log collector uses for the traceback.
CLI logging is configured before importing runtime dependencies. Import failures,
invalid environment configuration, and exceptions escaping startup or the server
emit a single ERROR record with the full traceback and exit with status 1.
Calls to serve() from Python retain the embedding application's logging configuration.
On Linux, server shutdown drains buffered function-call metrics before the runtime exits,
including when the server returns an error. Draining waits up to 10 seconds; a timeout or
publisher failure is logged as a warning.
Routine drain messages are logged at DEBUG; set RUST_LOG=info,_native::metrics=debug
to include them.
Missing optional StatsD endpoints or a metrics-bus topic do not emit warnings.
Failures initializing configured metrics sinks still warn. Routine customer
StatsD configuration messages are emitted at DEBUG by the shared metrics library;
set RUST_LOG=info,chalk_metrics::metrics::config=debug to include them.
Environment variables
Variable
Description
CHALK_INPUT_ARGS
Comma-separated list of column names (e.g. x,y,z). Renames incoming RecordBatch columns by index. If unset, the original column names are used. Reserved columns (below) are held out of this mapping and keep their own name.
CHALK_FNQ_CONSUMER_ENDPOINT
Opt into DP API FnqConsumerService consumption (HTTP or HTTPS gRPC endpoint). Unset preserves direct Redis consumption. API errors never fall back to Redis.
CHALK_FUNCTION_QUEUE_TOKEN_FILE
Controller-mounted working JWT, reopened per RPC to observe rotation. Defaults to /var/run/secrets/chalk-function-queue/identity-token. The shim does not exchange credentials.
CHALK_FNQ_QUEUE_PROTOCOL
Self-consumer work transport: list_v1 (default/backward compatible) or stream_v1. Deployment tooling sets this from immutable scaling-group revision metadata.
Reserved columns
A caller may attach framework side-channel data to a request as an extra column. Reserved
columns are matched by name, are optional on any given request, and are excluded from the
positional CHALK_INPUT_ARGS mapping — so CHALK_INPUT_ARGS always lists exactly the
handler's declared arguments, whether or not the caller sent one.
Column
Meaning
__chalk_row_metadata__
Per-row binary blob supplied by the caller (Chalk's engine sets it from catalog_call(..., row_metadata => ...)). Handlers read it via chalkcompute.get_row_metadata().
3. Docker image
FROM python:3.11-slim
WORKDIR /app
RUN pip install chalk-remote-call-python
# Copy your handler code
COPY my_handler.py /app
EXPOSE 6666
ENTRYPOINT ["chalk-remote-call"]
CMD ["--handler", "handler.handler"]
Model-serving integrations can pass a native ServingHandle to control gRPC
health and admission of new synchronous or async enqueue requests:
import time
import threading
from chalk_remote_call import ServingHandle, serve
serving = ServingHandle() # starts NOT_SERVING
def model_controller():
# After loading and verifying the selected model target:
serving.set_serving(True, lease_expires_at=time.time() + 30)
# Before applying another target, stop new admissions and drain requests:
serving.set_serving(False)
# After applying and verifying the new target, supply its later expiry.
serving.set_serving(True, lease_expires_at=time.time() + 30)
threading.Thread(target=model_controller, daemon=True).start()
serve(handler=handler, port=8080, serving_handle=serving)
The absolute Unix expiry is required when enabling serving and must be no more
than 300 seconds in the future. Repeating the same expiry cannot renew the
lease; the target provider must deliver a later expiry first. Rust converts the
absolute timestamp to a monotonic deadline, expires health and admission without
further Python calls, and rejects stale or expired timestamps. A new later
expiry can reopen serving after an update, provided it remains within the
five-minute bound.
This handle only controls gRPC health and admission of new calls. It does not
cancel or drain calls that passed admission before the state changed. An
integration must stop new calls and wait for its own admitted requests to drain
before modifying model state. Omitting serving_handle preserves the existing
always-serving health behavior. The handle is a local control surface; it does
not authenticate a target descriptor or provide trusted controller delivery.
Invocation context
Each Python bridge invocation runs in a fresh contextvars.Context. Handler
changes to context variables stay within that invocation, including across
awaits and generator iteration, and are discarded on return or error. Incoming
request metadata still supplies the tracing parent. A coalesced batch has one
invocation context for the whole batch.
Workers retain their Python thread state for compatibility with native
extensions. This context boundary does not reset process globals or
threading.local() storage, whose lifetime follows the worker thread.
Local Testing
Use grpcurl to verify the server is running:
# Check health
grpcurl -plaintext localhost:6666 grpc.health.v1.Health/Check
# List services via reflection
grpcurl -plaintext localhost:6666 list
Architecture
The server uses a Rust backend via PyO3:
tonic — gRPC server with health checking and reflection
prost — protobuf message handling
arrow-rs — Arrow IPC validation
PyO3 — FFI bridge to call Python handler functions
The Rust server runs on a tokio async runtime. When a request arrives, Arrow IPC bytes are passed to Python via PyO3 (spawn_blocking + GIL acquisition), where the handler is invoked. Results are passed back as IPC bytes.
Handler failures retain their original exception type, message, traceback,
exception chains, and exception groups. Runtime dispatch frames are excluded
from the user traceback, along with callers above the handler dispatch boundary.
Handler frames and their downstream calls remain visible (except for Chalk SDK
and marked generated dispatch frames); full diagnostics are retained in server
logs and internal_stacktrace.
All call modes carry a JSON payload with chalk_remote_error: 1 and an
exception object containing the ChalkException fields kind, message,
stacktrace, and internal_stacktrace. Direct calls carry the payload as the
unescaped gRPC status message; queued calls carry it in the error message. The
local async service additionally populates ChalkError.exception. This permits
existing queue transports to forward structured errors without a protobuf
migration. Clients must decode the versioned payload, not parse gRPC debug text
or classify user errors by their message. Unknown versions remain opaque.
Payloads are bounded for gRPC header limits. Truncation is marked explicitly,
with complete tracebacks kept in server logs. Exception objects and locals are
never pickled or sent. Chalk SDK-generated handlers identify their dispatch
frames, and notebook source maps identify the deployed snapshot's lines.
Fnq integration test
On Linux, build the native extension and the paired chalk-private test harness:
Use an isolated Redis instance. The tests create temporary signing keys and start
the production JWT layer and Fnq service, then exercise real native-shim execution,
lease renewal, result writes, token rotation, and environment isolation. These tests
skip unless FNQ_TEST_SERVER and REDIS_URL are set. Deploy the service before
setting CHALK_FNQ_CONSUMER_ENDPOINT on a workload.
Managed model target admission
The model deployment API records a typed serving configuration. Its launcher
passes one private --model-serving-bootstrap JSON argument containing the static
configuration and platform-generated deployment binding. The entire UTF-8
payload is bounded to 64 KiB. This creates a strict ServingHandle before
importing the user handler and starts the optional
chalkcompute.weights.serving.model_runtime.ManagedModelRuntime. Environment
feature switches alone cannot activate this path. Managed images
must install the compatible ChalkCompute serving extra and native runtime.
Ordinary remote-call handlers do not load this integration.
Managed calls carry x-chalk-model-weight-target, the exact immutable target
fingerprint selected by the backend. The native server checks this constraint
at ingress and again when actual Python execution starts. An expired lease,
missing target, stale target, or paused update rejects execution. The header is
an admission constraint and does not replace authentication.
Before changing weights the SDK closes admission and waits for native execution
to finish, including generators and blocking Python tasks after a client
disconnect. An uncertain managed execution permanently closes the native gate
until the replica restarts.
Managed durable async work requires the dataplane function queue. If its pinned
target becomes unavailable after delivery, the consumer persists an explicit
ModelWeightTargetUnavailable failed-call result before acknowledging delivery.
The caller can submit a fresh request against the new target. This avoids
executing old work against new weights or silently acknowledging it. The
legacy Redis-list consumer remains available to ordinary handlers.
Works well with
Use together with chalk-remote-call-python: extensions, drivers, servers and companion tools.