lietzsche;stokes

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.

Stokes parallel analyzers dashboard showing stokes-sql, stokes-python, stokes-rust, stokes-proto, and stokes-verify running concurrently
parallel ast analyzer run: five domain-isolated workers streaming into the event bus.

Worker Topology

  1. CLI Worker Coordinator

    Detects active file extensions in the workspace and schedules matching language workers concurrently.

  2. 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.

  3. 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

WorkerTarget Languages / RuntimesWhat It ChecksSynthesized Fix
stokes-sqlClickHouse, PostgreSQL, SQLite, MySQLUnscoped system.columns / information_schema, shard replicas (_r0, _r1), SELECT *Injects database = currentDatabase(), strict table equality, projection limits
stokes-protoProtocol Buffers (proto2 / proto3)Unbounded repeated fields, field number churn, enum tag collisionsInjects [(stokes.max_items) = N] annotations and bounds checks
stokes-pythonPython (CPython 3.10+)Dynamic dict appends with priority = 0, unbounded ETL loopsInjects static slice ceilings ([:MAX_CANONICAL]) and typed dataclasses
stokes-rustRust (Pingora, Tokio, Envoy FFI).try_into().unwrap() on fixed arrays, heap allocations on hot pathsSynthesizes Dual-Zone select_nth_unstable_by and 8-byte repr(C, align(8)) structs
stokes-verifyCriterion, Proptest, sandbox harness10,000-case IEEE-754 float fuzzing, Criterion JSON checks, BGP flap simulationEmits 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 FieldLengthEncodingSemantics
Length Header4 BytesBig-Endian uint32 (>I)Payload length NN in bytes; enforces 16 MB ceiling (0x01000000).
Payload BodyNN BytesUTF-8 JSONJSON-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:

PhaseTrigger / Meaning
INITIALIZING → BOUNDARY_DISCOVERY → AST_PARSINGWorker scans boundary files inside its own language domain.
CROSS_BOUNDARY_LINKING → INVARIANT_EVALUATIONCoordinator connects extracted signatures in the reachability DAG and evaluates Risk <= 1.0.
HALTED_ON_VIOLATIONFired on syntax errors or strict contract violations without crashing sibling workers.
PROPERTY_FUZZING → CERTIFICATE_GENERATION → COMPLETEDValidates 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:

ConstraintMechanismBehavior
Max Frame Size4-byte big-endian uint32 prefixChecked on every read; > 16 MB rejected
Terminal Frame Rate16.6 ms monotonic sleep loop60 FPS cap; zero UI flicker
Event Backpressureasyncio.Queue(maxsize=1024)Cooperative yield on saturation
Worker Concurrencyasyncio.gather(*workers)Concurrent coroutine execution
Fault IsolationPer-worker exception boundaryWorker 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.

Search wiki and portfolio

type to search across all entries.