Skip to content

feat(link): the uplink carries byte channels beside its messages, and small messages go first #556

Closed

Description

@V3RON

Part of #552.

Scope

After this PR, simlock has a link module (ADR 0028 §1–3): it wraps an
uplink transport connection, passes text messages through unchanged and
ahead of bulk bytes, and offers byte channels with credit. The uplink
transport port carries binary messages. Nothing in the daemons uses the
link yet: #558 wraps the uplink with it and moves relay bodies onto
channels, where the wiring is first tested. Tests drive the link directly.

The task stays whole: the transport half (port, WebSocket adapter,
in-memory pair) has three test lines of its own, and the link's tests need
it.

Every value this task builds is in #552's Shared values table.

In short

New term:

flowchart LR
  U["tests now; #558 later"] -->|text messages, openChannel / acceptChannel| L["link module (new)"]
  L -->|text + binary messages| P["uplink transport port *"]
  P --> WS["WebSocket adapter *"]
  P --> MP["in-memory pair *"]
Loading

(* = changed.) If this goes wrong, nothing changes for users yet; #558
would find a link that loses, reorders or stalls bytes or messages.

Technical spec

Facts

# Fact Source
F1 IpcConnection carries strings only: onData(chunk: string), write(contents: string) src/ports/ipc.ts:20-27
F2 The WebSocket adapter drops every binary message it receives, and buffers text that arrives before the first onData because the gateway's hello can arrive before the worker subscribes src/ports/uplink-websocket.ts:69, :49-61
F3 The WebSocket adapter's write sends one text message and resolves on ws's send callback; a write to a closed socket resolves without sending src/ports/uplink-websocket.ts:115-125
F4 The uplink connector returns an IpcConnection; an accepted uplink carries an IpcConnection src/ports/uplink.ts:157, :64
F5 The port's implementers: the WebSocket listener and connector, MemoryUplinkTransport, and the test's ScriptedConnector; createConnectionPair hands out PairedConnections src/ports/uplink-websocket.ts:146, :251; src/ports/uplink.ts:187, :233, :241; src/daemon/gateway-uplink.test.ts:16, :263-267 (an inline connector)
F6 DaemonServer and SimlockWire subscribe to onData, onClose and onError src/daemon/server.ts:680-682; src/simlock-client/wire.ts:127, :128, :133
F7 ws negotiates no compression here: the server's perMessageDeflate defaults to false node_modules/ws/lib/websocket-server.js:67 (ws 8.18.3, package.json)
F8 ws reports no event when its buffered amount drops; a send's callback fires once that message is written node_modules/ws/lib/websocket.js:119 (bufferedAmount), :448 (send(data, options, cb)); its only drain (:229) is the receiver's
F9 Clock and FakeClock are ports for timers in tests src/ports/clock.ts:5, :31
F10 Every wait that crosses a process boundary must be bounded docs/internal/agent-rules/architecture.md:80
F11 Every directory under src/ with an index.ts is a component that lint makes others enter through its index docs/internal/agent-rules/architecture.md:104-111

Modules touched

flowchart LR
  LK["link/ (new): index, channel, scheduler, envelope"] --> UP["ports/uplink.ts *"]
  UP --> WSA["ports/uplink-websocket.ts *"]
  LK --> CK["ports: Clock, Logger"]
  GT["daemon/gateway-uplink.test.ts * (ScriptedConnector)"] --> UP
Loading

(* = changed.)

Transport port (src/ports/uplink.ts). New interface
UplinkTransportConnection extends IpcConnection:
writeBinary(bytes: Uint8Array): Promise<void>,
onBinary(listener: (bytes: Uint8Array) => void): () => void,
readonly unsentBytes: number, and onSent(listener: () => void): () => void,
called whenever written bytes leave and unsentBytes drops. The
connector, the accepted uplink and createConnectionPair hand it out
(F4, F5); ScriptedConnector and the inline connector at
src/daemon/gateway-uplink.test.ts:263-267 return one. DaemonServer#acceptUplink,
GatewayUplinkOptions.accept and WorkerLink are unchanged: a transport
connection is an IpcConnection.

  • In-memory pair. Carries binary messages; a binary message that
    arrives with no onBinary listener is dropped, as the WebSocket adapter
    drops them today. hold() and release(): while held, written messages
    stay unsent, count in unsentBytes (text by its UTF-8 bytes), and their
    write and writeBinary promises stay pending; release delivers them
    in order, resolves the promises and fires onSent; closing a held pair
    resolves them unsent. fail(error) raises a transport error on that end
    and closes it, for tests. Otherwise unsentBytes is 0.
  • WebSocket adapter. Sends a Uint8Array as one binary message,
    resolving on the send callback like write (F3). Delivers received
    binary messages to onBinary instead of dropping them (F2); one that
    arrives with no onBinary listener is still dropped, so nothing piles up
    before a link subscribes. unsentBytes is the socket's
    bufferedAmount; each send callback fires onSent (F8).

Link module (new src/link/, a component through its index.ts,
F11). Exports createLink(transport, { end: "worker" | "gateway", clock, logger }), returning a LinkConnection, and the types LinkConnection,
LinkChannel and LinkChannelError.

  • LinkConnection is an IpcConnection (F1, F6). Text that arrives
    before the first onData is buffered and delivered to it. onClose
    attached after the close fires at once. Transport errors reach
    onError. write resolves when the transport's write resolves; a
    text message queued when the connection closes resolves without being
    sent, as a write to a closed socket does today (F3). Closing the link
    closes the transport; the transport closing closes the link.
  • openChannel({ signal }): the signal is required. Resolves with a
    LinkChannel once its OPEN is queued ahead of any later message. With
    64 channels already open from this side it waits until one ends; it
    rejects with the signal's reason when the signal aborts, and with
    closed when the connection closes. Waiters get a free slot first in,
    first out. Numbers are 32-bit; if this side's run out, openChannel
    rejects and the link logs it.
  • acceptChannel(id) throws for an id the peer never opened, one already
    accepted, and one already ended.
  • LinkChannel: id (1–32 characters of [A-Za-z0-9-]), readable,
    writable (standard Web streams of bytes), abort(reason?), credit
    and whenCredit(). credit is the peer's remaining window less what
    the link already holds unsent for this channel. The link takes as much
    of a written chunk as credit allows at once and the rest as credit
    arrives, so a chunk of any size goes through; the write resolves once
    all of it is taken, and the writable queues at most 64 KiB more
    behind it before its writer waits. whenCredit() resolves when credit
    arrives, and rejects when the channel fails or its sending direction
    ends. The 60 s stall runs only while a write or a whenCredit() waits
    and the peer already holds every byte this channel sent: the reader has
    everything and grants nothing. Waiting behind the bulk lane or a held
    transport never counts.
  • Ending: closing the writable sends END; cancelling the readable
    sends STOP. On STOP the peer's writable errors with stopped, the
    peer sends END for that direction to acknowledge it, and the other
    direction goes on. DATA that arrives after this side sent STOP and
    before that END is dropped quietly. A STOP for a direction whose
    END this side already sent is ignored, since that END already
    answers it, and cancelling a readable whose END has already
    arrived sends nothing; so a STOP and an END crossing on the wire is
    never a rule break. On each side, a direction is done
    once this side's END or RESET for it has been written to the
    transport and the peer's END or RESET for it has arrived (after a
    STOP, the peer's acknowledging END). A channel ends, and stops
    counting toward the 64, once both directions are done on that side;
    numbers are never reused on a connection.
  • LinkChannelError.reason: aborted (either side aborted; the side that
    called abort(reason) gets its reason string as the error's message,
    the peer gets none), invalid (the
    peer broke a rule), not-accepted (the peer did not accept within
    30 s), stalled (a write waited 60 s with no credit arriving), closed
    (the connection closed); a writer stopped by its peer errors with
    stopped. RESET carries the first four as a code so both sides report
    the same reason; a user's own abort reason string stays on its side.
  • Inside, private, as ADR 0028 §2: envelopes OPEN, DATA (at most
    64 KiB), END, STOP, CREDIT (at least 1), RESET; numbers (worker
    odd, gateway even); the first 4 MiB each way need no credit, and the
    receiver holds at most 4 MiB unread per channel; credit granted as the
    user reads, one CREDIT per 64 KiB read or when the reader has read
    everything it holds; one scheduler per connection with a priority lane (text,
    OPEN, STOP, CREDIT, RESET) and a bulk lane (DATA, END) that
    hands a message to the transport only while unsentBytes is under
    256 KiB and wakes on onSent; channels take turns; the bulk lane sends
    at least one message per 64 KiB (UTF-8 bytes) of priority messages while it has one it
    may send. A text message never waits for a bulk turn the 256 KiB mark
    blocks.
  • Rule breaks (ADR 0028 §2's list) are dropped, never buffered; the named
    channel, when held, is reset with invalid; the link logs which rule.
    Numbers are never reused, so a message naming a number of the right
    parity at or below the highest the peer has opened, but no longer held
    here, is late traffic for an ended channel: it is dropped quietly and
    never answered. Only a number the peer never opened is a rule break.

Contract and event changes

None. No message changes, no protocol bump, no events.

Other code on the same state

The state is the uplink transport connection.

  • GatewayUplink, GatewayService, WorkerLink, DaemonServer: still
    receive the transport connection as an IpcConnection; nothing wraps it
    with the link until feat(gateway): relayed bodies travel on byte channels #558. Their behaviour does not change.
  • Tests that hand createConnectionPair ends to DaemonServer
    (src/daemon/server.test.ts:2861, :2891, :2915;
    src/daemon/test-relay-support.ts:187;
    src/daemon/relay-gateway.e2e.test.ts:158) and ScriptedConnector
    (src/daemon/gateway-uplink.test.ts:16, :29, :272): typecheck
    against the new return type; behaviour unchanged.

Rules in play

  • architecture.md: rule 11 (every wait bounded: open, accept, credit,
    whenCredit), rule 14 (the module's surface is its index), rule 9 (the
    transport is a port with an in-memory fake).
  • safety.md: rule 10, every binary message from the peer is a claim:
    length, type, number, size and credit checked before use.
  • testing.md: lane order and credit tests fail on a named assertion,
    not a timeout.

Tests

Seam: createLink from src/link/index.ts over createConnectionPair
ends (with hold/release and FakeClock), and over the real WebSocket
adapter on 127.0.0.1. Model: src/ports/uplink.test.ts and
src/ports/uplink-websocket.test.ts. Rule-break tests write raw binary
messages into one transport end.

  • text messages written on one link arrive on the other unchanged and in order, over the in-memory pair and over the real WebSocket
  • text that arrives before the first onData is delivered to it; an onClose attached after the close fires; a pair's fail(error) reaches onError; closing the transport fails every open channel with closed; closing the link closes the transport
  • write resolves when the transport's write resolves; a text message queued at close resolves unsent, also when the pair was held
  • 20 MiB written to a channel arrives byte for byte at the accepted channel, each way at once, over the real WebSocket
  • over the real WebSocket, a 20 MiB channel transfer puts at most 20.2 MiB on the socket, in binary messages
  • a text message written right after openChannel resolves never reaches the peer before the channel's OPEN, even with the transport held
  • bytes written right after openChannel, before the peer accepts, arrive once it accepts
  • with credit left but the bulk lane held, the writable takes the chunks that fit in credit and then at most 64 KiB more before its writer waits
  • a writer whose peer never accepts stops after 4 MiB; 30 s after the open its streams error with not-accepted, and the peer's acceptChannel for that id then throws
  • a reader that stops reading holds its writer after 4 MiB unread, and reading again lets it go on
  • a write that waits 60 s with no credit arriving errors both sides' streams with stalled; a reader that reads 64 KiB every 50 s keeps a 10 MiB transfer going without a reset
  • credit counts down as the writer writes and up as the peer reads; whenCredit() resolves when credit arrives, rejects when the channel fails, when the peer stops that direction and when this side closes its own writable, and a whenCredit() pending 60 s, with the peer holding every byte and granting nothing, errors the channel stalled
  • a single 20 MiB write goes through in parts as credit arrives, and resolves once all of it is taken
  • with the transport held for 90 s and a write waiting behind it, the channel is not reset
  • a writer that writes no more than credit, against a reader that reads nothing for 10 minutes, is never reset
  • a channel whose peer sends nothing for 10 minutes, with no write waiting, stays open
  • one channel's stalled reader does not slow another channel on the same link
  • with the transport held and 1 MiB of channel bytes queued, a text message written next is sent before all but at most 256 KiB plus one 64 KiB message of them
  • with text messages written without pause and channel bytes queued, at least one channel message goes out per 64 KiB of text
  • two channels with bytes queued take turns, one message each
  • closing a writable ends the peer's readable; cancelling a readable errors the peer's writable with stopped, DATA still in flight is dropped without a reset, and the peer's acknowledging END arrives; either way the other direction still carries bytes to its end
  • a STOP and an END for the same direction crossing on the wire (the reader cancels while the writer closes, with the transport held) end that direction on both sides with no reset and no second END; cancelling a readable after its END arrived sends nothing
  • abort("why") on one side errors both streams on both sides with aborted; the aborting side's error message is why, and the peer's carries no reason string
  • acceptChannel throws for an id never opened, an id already accepted and an id already ended
  • channel ids match [A-Za-z0-9-]{1,32}, checked over 200 channels from each end
  • with 64 channels open from one side, the 65th openChannel waits, resolves once one ends, rejects with the signal's reason when its signal aborts first, and rejects with closed when the connection closes; three waiters get slots in the order they asked
  • with this side's numbers exhausted (a test hook sets the next number to the last one), the next openChannel rejects and the link logs it
  • with 64 channels open, ending one and opening another at once never makes the peer see 65, even with the transport held
  • 50 channels opened at once from each end never collide, and 200 opened and ended one after another each get a new number
  • each of these is dropped, resets the channel it names (when held) with invalid, is logged, and leaves text flowing: DATA past the allowed bytes, DATA over 64 KiB, DATA or END after that direction ended, a CREDIT of 0, credit beyond 4 MiB outstanding
  • each of these is dropped and logged and leaves text flowing: a channel number the peer never opened, an OPEN reusing a live number, an OPEN with the wrong parity, a 65th OPEN from the peer, an unknown envelope type, a message too short to read
  • a RESET for a channel this side does not hold is dropped and not answered
  • a STOP that arrives after its channel ended on this side (this side's END written and the peer's END arrived, then the peer cancels its reader) is dropped quietly: no log, no reset, no answer
  • the WebSocket adapter sends writeBinary bytes as one binary message and resolves on its send callback (and at once on a closed socket); it delivers a received binary message to onBinary, drops one that arrives with no listener, and unsentBytes follows the socket's buffered amount with onSent firing when a send completes
  • the in-memory pair carries binary messages and drops one with no onBinary listener; while held, unsentBytes counts what is written (text in UTF-8 bytes), nothing arrives and the write promises stay pending, until release delivers them in order and fires onSent

Done when

  • Every Tests line passes.

Out of scope

Depends on

Written by an agent.

Activity

  1. added
    task:draft
    on Oct 14, 2026
  2. added
    task:ready
    and removed
    task:draft
    on Oct 14, 2026
  3. self-assigned this
    on Oct 14, 2026
  4. added a commit that references this issue on Oct 14, 2026
    6d35d3e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

task:ready

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions