Python stable · Mojo preview
Learn CoAkka Runtime with Python + Mojo
Python is the complete package-manager journey: Embedded first, then peers and data lanes. Mojo shares this learning family but remains a separate source preview over its packaged C shim, without a stable high-level Mojo API.
Beginner · 01 / 04
Install the wheel and receive a reply
Use GIL-enabled CPython 3.11 or later. Version 3.3.2 installs the matching native dependency. Import coakka_v2_connector in the example.
python --versionmkdir coakka-python-demo
cd coakka-python-demo
python -m venv .venv
. .venv/bin/activate
python -m pip install --only-binary=:all: coakka-runtime-python==3.3.2On Windows use .venv\Scripts\python.exe -m pip install --only-binary=:all: coakka-runtime-python==3.3.2. Always invoke pip through the intended interpreter.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
target = "customers.accept"
start_spec = ConnectorStartSpec(
system_name="customer-app",
node_id="customer-app-1",
routes=[local_route(target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(target, lambda payload: b"accepted-" + payload)
reply = runtime.ask_payload(
source="customer-api",
target=target,
payload=b"hello",
timeout_ms=2_000,
)
print(reply.decode("utf-8"))
python first_run.pyExpected result
accepted-hello
ConnectorStartSpec- App-host startup intent; omitted queue, network and Monitor let Core resolve defaults.
local_route(target)- Creates a same-process route without invented host/port values.
with RuntimeHost.start(...)- The context manager owns one host and closes it when the scope exits.
ask_payload- Bytes-first request/reply; Core owns framing and terminal matching.
Beginner · 02 / 04
Name the work
orders.quote is a business address. The handler calculates a quote; the caller knows only the target.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="orders-python-1",
routes=[local_route(target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(
target,
lambda payload: str(int(payload) * 120_000).encode("utf-8"),
)
for quantity in (1, 2):
reply = runtime.ask_payload(
source="checkout",
target=target,
payload=str(quantity).encode("utf-8"),
timeout_ms=2_000,
)
print(f"quantity={quantity} quote={reply.decode('utf-8')} VND")
python quote.pyExpected result
quantity=1 quote=120000 VND quantity=2 quote=240000 VND
Beginner · 03 / 04
Read a structured deadletter
A route miss after admission is DeadletterError, not a business response or timeout. Branch on the reason code; do not parse detail text.
from coakka_v2_connector import (
ConnectorStartSpec,
DeadletterError,
RuntimeHost,
local_route,
)
live_target = "orders.quote"
missing_target = "orders.missing"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="orders-python-1",
routes=[local_route(live_target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
try:
runtime.ask_payload(
source="checkout",
target=missing_target,
payload=b"1",
timeout_ms=2_000,
)
except DeadletterError as error:
deadletter = error.deadletter
print(
f"deadletter reason={deadletter.reason} "
f"target={deadletter.original_envelope.target}"
)
python route_miss.pyExpected result
deadletter reason=2 target=orders.missing
Compare admission failure, Deadletter, response and timeout.
Beginner · 04 / 04
Let the application own lifecycle
Create the host at the composition root, pass it to services that call targets and never construct one per request.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
def run_checkout(runtime: RuntimeHost) -> None:
reply = runtime.ask_payload(
source="checkout",
target="orders.quote",
payload=b"2",
timeout_ms=2_000,
)
print(f"checkout total={reply.decode('utf-8')} VND")
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="orders-python-1",
routes=[local_route(target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(
target,
lambda payload: str(int(payload) * 120_000).encode("utf-8"),
)
run_checkout(runtime)
python integration.pyExpected result
checkout total=240000 VND
Advanced · 05 / 08
Move the handler to a peer, keep the target
Open two terminals. The service is a NETWORK_NODE; the caller is OUTBOUND_ONLY. Loopback demonstrates two processes on one machine; production uses private DNS/IP.
from coakka_v2_connector import (
ConnectorStartSpec,
RuntimeHost,
RuntimeNetworkConfig,
local_route,
)
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="quote-python-1",
routes=[local_route(target)],
network=RuntimeNetworkConfig.network_node(
bind_host="127.0.0.1",
bind_port=19_321,
advertise_host="127.0.0.1",
advertise_port=19_321,
),
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(
target,
lambda payload: str(int(payload) * 120_000).encode("utf-8"),
)
print("quote service ready on 127.0.0.1:19321")
input("Press Enter to stop...\n")
python quote_service.pyfrom coakka_v2_connector import (
ConnectorStartSpec,
EndpointSpec,
RouteSpec,
RouteStrategy,
RuntimeHost,
RuntimeNetworkConfig,
)
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="checkout-python-1",
routes=[
RouteSpec(
target=target,
endpoints=[EndpointSpec(host="127.0.0.1", port=19_321)],
strategy=RouteStrategy.SINGLE_OWNER,
)
],
network=RuntimeNetworkConfig.outbound_only(),
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
reply = runtime.ask_payload(
source="checkout",
target=target,
payload=b"3",
timeout_ms=2_000,
)
print(f"order quote: {reply.decode('utf-8')} VND")
python checkout.pyExpected result
order quote: 360000 VND
network_node- Bind is where the listener opens; advertise is what peers use.
outbound_only- The caller reaches peers without owning an inbound listener.
RouteStrategy.SINGLE_OWNER- One endpoint owns the target here; multi-endpoint failover belongs to product Advanced.
Advanced · 06 / 08
Transfer an immutable file with File Lane
File Lane is an independent owner. The receiver issues an exact-owner grant; both peers must succeed terminally before records are forgotten.
from pathlib import Path
from tempfile import TemporaryDirectory
from coakka_v2_connector import (
FileLane,
FileLaneConfig,
FileReceiveSpec,
FileTransferDirection,
LaneOwnerConfig,
)
def wait_terminal(lane: FileLane, transfer_id: str, direction: FileTransferDirection):
sequence = 0
while True:
snapshot = lane.wait_transfer(
transfer_id=transfer_id,
direction=direction,
after_update_sequence=sequence,
timeout_ms=5_000,
)
if snapshot.terminal:
return snapshot
sequence = snapshot.update_sequence
with TemporaryDirectory() as directory:
root = Path(directory)
source = root / "source.txt"
destination = root / "received.txt"
source.write_text("hello from File Lane", encoding="utf-8")
digest = FileLane.sha256(source)
with FileLane.open_owned(
config=FileLaneConfig(),
owner=LaneOwnerConfig(
owner_instance_id="receiver-python-1",
advertised_host="127.0.0.1",
),
) as receiver, FileLane.open() as sender:
transfer_id = "python-file-1"
grant = receiver.prepare_receive_grant(
FileReceiveSpec(
transfer_id=transfer_id,
authorization_token="file-token-1",
destination_path=destination,
expected_size=digest.size,
expected_sha256=digest.sha256,
)
)
sender.submit_send(grant.to_send_spec(source_path=source, timeout_ms=5_000))
sent = wait_terminal(sender, transfer_id, FileTransferDirection.SEND)
received = wait_terminal(receiver, transfer_id, FileTransferDirection.RECEIVE)
if not sent.completed or not received.completed:
raise RuntimeError("File Lane did not complete on both peers")
print(destination.read_text(encoding="utf-8"))
sender.forget(transfer_id, FileTransferDirection.SEND)
receiver.forget(transfer_id, FileTransferDirection.RECEIVE)
python file_lane.pyExpected result
hello from File Lane
Advanced · 07 / 08
Send live frames with Stream Lane
The source writes into a borrowed destination; the consumer copies before callback return when retaining data. The window bounds in-flight bytes.
from coakka_v2_connector import (
LaneOwnerConfig,
StreamConsumerDecision,
StreamDirection,
StreamLane,
StreamLaneConfig,
StreamPublishSpec,
StreamSourceFrame,
StreamSourceSignal,
)
frames = [b"frame-one", b"frame-two"]
received: list[str] = []
def next_frame(destination: memoryview):
if not frames:
return StreamSourceSignal.END
frame = frames.pop(0)
destination[: len(frame)] = frame
return StreamSourceFrame(size=len(frame))
def consume_frame(data: memoryview, _metadata):
received.append(bytes(data).decode("utf-8"))
return StreamConsumerDecision.CONTINUE
def wait_terminal(lane: StreamLane, session_id: str, direction: StreamDirection):
sequence = 0
while True:
snapshot = lane.wait_session(
session_id=session_id,
direction=direction,
after_update_sequence=sequence,
timeout_ms=5_000,
)
if snapshot.terminal:
return snapshot
sequence = snapshot.update_sequence
with StreamLane.open_owned(
config=StreamLaneConfig(),
owner=LaneOwnerConfig(
owner_instance_id="publisher-python-1",
advertised_host="127.0.0.1",
),
) as publisher, StreamLane.open() as subscriber:
session_id = "python-stream-1"
grant = publisher.prepare_publish_grant(
StreamPublishSpec(
session_id=session_id,
authorization_token="stream-token-1",
format_id=1,
max_frame_bytes=1_024,
source=next_frame,
)
)
subscriber.subscribe(
grant.to_subscribe_spec(
initial_window_bytes=4_096,
consumer=consume_frame,
timeout_ms=5_000,
)
)
published = wait_terminal(publisher, session_id, StreamDirection.PUBLISH)
subscribed = wait_terminal(subscriber, session_id, StreamDirection.SUBSCRIBE)
if not published.completed or not subscribed.completed:
raise RuntimeError("Stream Lane did not end successfully on both peers")
print(", ".join(received))
publisher.forget(session_id, StreamDirection.PUBLISH)
subscriber.forget(session_id, StreamDirection.SUBSCRIBE)
python stream_lane.pyExpected result
frame-one, frame-two
Advanced · 08 / 08
Enable Monitor before startup
Monitor defaults OFF. enable_monitor=True is intent; monitor_is_enabled() and snapshots are Core-issued facts.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="monitor-python-1",
routes=[local_route(target)],
enable_monitor=True,
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
snapshot = runtime.await_next_monitor(timeout_ms=1_000)
if snapshot is None:
raise RuntimeError("expected the startup Monitor signal")
runtime.register_payload_handler(target, lambda payload: payload)
runtime.ask_payload(
source="checkout",
target=target,
payload=b"signal",
timeout_ms=2_000,
)
print(f"monitor enabled={str(runtime.monitor_is_enabled()).lower()}")
print(f"state={snapshot.health['runtimeState']} signal={snapshot.signal_count}")
python monitoring.pyVerified result
monitor enabled=true state=1 signal=1
Preview · 09
Run the Mojo source preview without inventing a stable API
Mojo 3.3.1 preview pins toolchain 1.0.0b2.dev2026052115. A thin Mojo executable calls the packaged C shim; the shim owns the complete runtime lifecycle and checks request/reply, cancellation and route miss.
curl -fL -o coakka-runtime-mojo-3.3.1-source.tar.gz \
'https://raw.githubusercontent.com/phuong-tran/coakka-publish/22d885f240dd9c458249fe93854a8a7ec8ba0b4a/coakka-runtime/mojo/releases/3.3.1%2B16bdd692faf918d1a959c073ad20318392659f4b/coakka-runtime-mojo-3.3.1-source.tar.gz'
printf '%s %s\n' \
'a9b1a9cc78086d92d81294f7c1efa7e42c510f81df115d3830545bf5f143e5c1' \
'coakka-runtime-mojo-3.3.1-source.tar.gz' | shasum -a 256 -c -
tar -xzf coakka-runtime-mojo-3.3.1-source.tar.gzfrom std.ffi import OwnedDLHandle, c_int
from std.sys import argv
# Mojo's direct native-call surface is still evolving. The packaged C shim
# owns the complete CoAkka Runtime lifecycle; this file is not a stable
# high-level Mojo application API.
def main() raises:
var args = argv()
if len(args) != 2:
print("usage: mojo runtime_connector_smoke.mojo <connector-shim-library>")
raise Error("missing connector shim library path")
var lib = OwnedDLHandle(String(args[1]))
var status = lib.call["coakka_mojo_runtime_connector_smoke", c_int](0)
if status != 0:
raise Error("coakka_mojo_runtime_connector_smoke failed")
mkdir -p coakka-mojo-work
cd coakka-runtime-mojo-3.3.1-source
export COAKKA_CONNECTOR_WORK_ROOT="$(cd .. && pwd)/coakka-mojo-work"
if [ "$(uname -s)" = Darwin ]; then
export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"
export MACOSX_DEPLOYMENT_TARGET=13.0
fi
bash scripts/verify-native-payload.sh
bash scripts/smoke.shExecution evidence currently covers macOS ARM64 and Raspberry Pi 5 Linux ARM64. Five native images in the archive are payload inventory, not automatic proof of Mojo compiler support on every target.