updated 2026-11-26·5 min read
Parallel Language Workers & Event Bus
Five language-specific Python workers feeding a bounded asyncio.Queue with 16.6 ms render coalescing and 4-byte binary IPC framing.
Printing diagnostics straight from five async tasks at once turns ANSI terminal output into flicker and torn lines. Inside Stokes, five language-specific Python workers run concurrently and push typed events into a single bounded asyncio.Queue(maxsize=1024) drained on a 16.6 ms (60 FPS) render loop, while external IPC uses 4-byte big-endian length-prefixed framing.

Worker Topology
- CLI Worker Coordinator
Detects active file extensions in the workspace and schedules matching language workers concurrently.
- Five Language Workers + Binary IPC Framing
Dispatches scanning across stokes-sql, stokes-proto, stokes-python, stokes-rust, and stokes-verify; external IPC frames payloads with a 4-byte big-endian uint32 length header.
- Bounded Event Queue (maxsize=1024)
BobMultiplexer buffers worker events and flushes them on a 60 FPS (16.6 ms) tick so terminal diffs never flicker.
The Five Language Workers
| Worker | Target Languages / Runtimes | What It Checks | Synthesized Fix |
|---|---|---|---|
stokes-sql | ClickHouse, PostgreSQL, SQLite, MySQL | Unscoped system.columns / information_schema, shard replicas (_r0, _r1), SELECT * | Injects database = currentDatabase(), strict table equality, projection limits |
stokes-proto | Protocol Buffers (proto2 / proto3) | Unbounded repeated fields, field number churn, enum tag collisions | Injects [(stokes.max_items) = N] annotations and bounds checks |
stokes-python | Python (CPython 3.10+) | Dynamic dict appends with priority = 0, unbounded ETL loops | Injects static slice ceilings ([:MAX_CANONICAL]) and typed dataclasses |
stokes-rust | Rust (Pingora, Tokio, Envoy FFI) | .try_into().unwrap() on fixed arrays, heap allocations on hot paths | Synthesizes Dual-Zone select_nth_unstable_by and 8-byte repr(C, align(8)) structs |
stokes-verify | Criterion, Proptest, sandbox harness | 10,000-case IEEE-754 float fuzzing, Criterion JSON checks, BGP flap simulation | Emits stokes.lock and CONFORMANCE.md |
4-Byte Length-Prefixed Binary Framing
For external IPC sockets, each frame carries a 4-byte big-endian length header capped at 16 MB (0x01000000) so malformed headers drop cleanly instead of exhausting memory:
| Wire Field | Length | Encoding | Semantics |
|---|---|---|---|
| Length Header | 4 Bytes | Big-Endian uint32 (>I) | Payload length in bytes; enforces 16 MB ceiling (0x01000000). |
| Payload Body | Bytes | UTF-8 JSON | JSON-RPC 2.0 request/response or typed progress event. |
Bounded Queue & 60 FPS Render Coalescing
Instead of locking stdout on every regex or AST hit, BobMultiplexer queues events in asyncio.Queue(maxsize=1024) and drains batches every 16.6 ms:
Binary Framing & BobMultiplexer Coalescer (Python)
# stokes/subagents/actor_base.py
import json
import struct
from typing import Any
MAX_FRAME_BUDGET = 0x01000000 # 16 MB
def encode_frame(payload: dict[str, Any]) -> bytes:
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
if len(body) > MAX_FRAME_BUDGET:
raise ValueError(f"Frame exceeds 16 MB budget ({len(body)} bytes)")
return struct.pack(">I", len(body)) + body
def decode_frame(data: bytes) -> dict[str, Any]:
if len(data) < 4:
raise ValueError("Frame too short: missing 4-byte length header")
(length,) = struct.unpack(">I", data[:4])
if length > MAX_FRAME_BUDGET:
raise ValueError(f"Frame length {length} exceeds 16 MB budget")
return json.loads(data[4 : 4 + length].decode("utf-8"))# stokes/subagents/bob_multiplexer.py
import asyncio
from typing import Any, Callable
class BobMultiplexer:
RENDER_TICK_SECONDS = 1.0 / 60.0 # 16.6ms monotonic cadence
MAX_QUEUE_SIZE = 1024
def __init__(self) -> None:
self._queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=self.MAX_QUEUE_SIZE)
self._coalesced_buffer: list[dict[str, Any]] = []
self._running = False
async def publish(self, event: dict[str, Any]) -> None:
await self._queue.put(event)
async def consume_all(self) -> list[dict[str, Any]]:
events = []
while not self._queue.empty():
try:
events.append(self._queue.get_nowait())
self._queue.task_done()
except asyncio.QueueEmpty:
break
return events
async def run_render_loop(self, on_tick: Callable[[list[dict[str, Any]]], None]) -> None:
self._running = True
while self._running:
await asyncio.sleep(self.RENDER_TICK_SECONDS)
events = await self.consume_all()
if events:
self._coalesced_buffer.extend(events)
on_tick(self._coalesced_buffer[:])
self._coalesced_buffer.clear()Worker Lifecycle & Fault Isolation
Each worker moves through a straightforward state machine:
| Phase | Trigger / Meaning |
|---|---|
INITIALIZING → BOUNDARY_DISCOVERY → AST_PARSING | Worker scans boundary files inside its own language domain. |
CROSS_BOUNDARY_LINKING → INVARIANT_EVALUATION | Coordinator connects extracted signatures in the reachability DAG and evaluates Risk <= 1.0. |
HALTED_ON_VIOLATION | Fired on syntax errors or strict contract violations without crashing sibling workers. |
PROPERTY_FUZZING → CERTIFICATE_GENERATION → COMPLETED | Validates Dual-Zone / float sanitization patches and emits stokes.lock + CONFORMANCE.md. |
Workers only push events upward to BobMultiplexer and never make synchronous calls to sibling workers. Each queue caps at maxsize=1024 with cooperative await queue.put(), so an error inside stokes-python halts only that worker while stokes-sql and stokes-rust finish cleanly:
| Constraint | Mechanism | Behavior |
|---|---|---|
| Max Frame Size | 4-byte big-endian uint32 prefix | Checked on every read; > 16 MB rejected |
| Terminal Frame Rate | 16.6 ms monotonic sleep loop | 60 FPS cap; zero UI flicker |
| Event Backpressure | asyncio.Queue(maxsize=1024) | Cooperative yield on saturation |
| Worker Concurrency | asyncio.gather(*workers) | Concurrent coroutine execution |
| Fault Isolation | Per-worker exception boundary | Worker fault emits event without killing peers |
See Parallel AST Analyzers Reference for the progress event schema and Verification, Fuzzing & Simulation Harness for runtime stress tests.