Files
alktunnels/docs/architecture/decisions/005-consumer-session-owns-teardown.md
T
glm-5.3-flash bd7d1ad8ec docs: Phase 1 architecture spec — ADRs 001..006, spec docs, OQ promotion
The Phase 0 OQ ledger (OQ-TN-01..10) promoted into
docs/architecture/open-questions.md (now OQ-TN-01..14, with four
new Phase 1 residues). Six ADRs and four spec docs, all Draft, all
decision-shaped per the SDD process (ADRs carry the WHY; specs carry
the WHAT and reference by number):

ADRs:
- 001 open-params-layout: params = {resource, substrate} — the
  producer's stable name, not an address; wire-stable from the first
  consumer; unknown substrates fail loudly at schema time
- 002 alpn-strategy: single alk/tunnel ALPN (option A); substrate in
  params selects the framing; prior art (SSH/SOCKS5/udpgw) gives no
  reason for the split
- 003 codec-and-udp-framing: raw pass-through (stream) / mandatory
  [len: u16 BE] (UDP) — F-2 mandate recorded (the codec is mandatory
  for correctness, not cosmetics); len=0 = legal empty datagram;
  OQ-TN-13 resolved fail-loud (truncation)
- 004 no-backend-trait: halves functions at the assembly layer;
  listen is an establisher shape; hub re-produce deferred(OQ-TN-12);
  trait re-evaluated at the alknet ADR-078 convergence threshold
- 005 consumer-session-owns-teardown: TunnelSession with
  open/adopt/stream_halves/take_halves/pump_against/close/join/Drop —
  the W3 adopter gap closes structurally; Drop is the best-effort
  fallback
- 006 access-control-posture: the open gate is the boundary;
  TUNNEL_OPEN_SCOPE = tunnel:open (stable once published); op-level
  ACL; ownership seam; no allowlists in v1; identity = 0.7.0's
  precedence chain

Spec docs:
- overview.md: purpose, resource model, deps (alkcall 0.7.0,
  wasm-clean default, local feature), module map
- wire.md: the open op (params/reply/typed errors), the data plane
  by substrate, sentinels + half-close, byte diagrams
- producer.md: spec, establisher (dial + listen shapes), pump
  handler (pump_bidi inline, R-02), registration API, ACL posture
- consumer.md: TunnelSession (forward open + reverse adopt
  construction), data plane, teardown API (close/join/Drop incl.
  pump-less join semantics)
- bast.md: the BAST doc for the UDP codec (convention 12's trigger
  fired — the framing IS binary beyond pass-through)
- open-questions.md: OQ-TN-01..14; 01..10 promoted (faithful to the
  phase-0 ledger's final states), 11 partially resolved (collision
  domain = per-producer registry per ADR-001; lifecycle open),
  12 deferred(scope), 13 resolved fail-loud (ADR-003), 14 open

Verified by an architecture-reviewer pass (2 criticals, 6 majors,
10 minors — all fixed: ADR-001/003-vs-OQ decision-state contradictions
resolved; the Layer-2 mislabel corrected to the ADR-047 §4 per-session
fork; alktty/alknet ADR misattributions fixed; codec placement pinned
to the establisher (pump stays substrate-agnostic); reverse-path
construction named (TunnelSession::adopt + pump_against); security
posture promoted to ADR-006; BAST doc written; F-2 rationale deduped;
README tables completed; channel_id > 0; MTU wording fixed; ADR-047 §5
attributions corrected; impacts lines added to unresolved OQs; review/
ledger pointer paths added to README references).

Verification: doc set internal cross-refs all resolve; cargo test,
fmt --check, doc --no-deps clean
2026-09-07 18:36:44 +00:00

5.6 KiB

ADR-005: The Consumer Session Type Owns Teardown

Status

Accepted (2026-09-07; resolves the reverse POC W3 finding)

Context

A tunnel channel's two ends have asymmetric lifecycle machinery:

  • The serving side (the side the open op ran on) is wrapper-managed: the open wrapper awaits the pump handler's JoinHandle, and its completion triggers channel teardown (drop of the demux sender = EOF to the handler's read half — alkcall ADR-049
    • review 007 R-02). Out-of-band channel/close also tears it down. Nothing leaks.
  • The adopting side (the side that called the open op and adopted the channel ID — the consumer) has NO such machinery: ChannelManager::adopt_channel installs routing state nothing awaits. The consumer-side pump (pump_bidi spawned locally) is somebody's JoinHandle; the adopted channel state is nobody's to reap. If the assembly layer drops both, the channel entry leaks in the manager until transport EOF (clear_all) — and worse, a consumer that drops the pump handle mid-flight aborts the pump without reaping, leaving half-open state on the peer.

The reverse POC found this by construction (W3, 2026-09-07): the hub must hold its pump handle and reap (teardown_channel) itself — ReverseTunnel::join_and_reap/close in the POC. The lifecycle is assembly-layer by design (OQ-TN-04 — no forced binding means no protocol-owned listener lifecycle either), but the POC demonstrated that leaving teardown discipline to each assembly layer's memory is exactly the kind of gap the spec must close with a type, not a doc note.

Related constraint from the same POC pass: one session = one channel = one tunnel (the channel ID is the flow key, OQ-TN-02's resolution); the session is also the natural owner of the substrate-shaped data plane (raw halves vs datagram codec, ADR-003).

Decision

The consumer half is a typed session, TunnelSession, and it owns its teardown:

  • Construction: TunnelSession::open(client, params) — calls the open op (ChannelClient::open_channel on the forward path; the reverse path's open_reverse_channel + adopt_channel equivalent), adopts the returned channel ID, splits the channel BiStream, and presents the substrate-shaped data plane:
    • Stream variant: raw halves (AsyncRead/AsyncWrite) — the halves ARE the tunnel.
    • Datagram variant: send_datagram/recv_datagram over the mandatory codec (ADR-003) — boundary-preserving, len=0 is an empty datagram, recv_datagram returns None only on stream EOF.
  • Pump ownership: the session's pump_against(accepted_halves) (the reverse-flow use) spawns pump_bidi and holds the returned JoinHandle. For the pure consumer (no local pump — the session halves ARE handed to the caller), the session does not spawn; the caller drives the halves and the session still owns the channel entry.
  • Teardown API (the point of the ADR):
    • close(self) — abort the pump (if session-owned), tear down the adopted channel (teardown_channel), consume the session. The abort path (ungraceful).
    • join(self) — await pump completion (both directions finished), THEN reap the adopted channel, return the (u64, u64) copy counts from pump_bidi for observability. The graceful path.
    • Dropping the session without either: the Drop impl tears the channel down (the panic-free fallback — never leak the entry). Drop cannot await, so it aborts the pump and calls the sync teardown_channel; this is semantically close.
  • Half-open semantics fall out of pump_bidi (ADR-050): one direction EOFs → the opposite sink shuts down (the EOF sentinel crosses the mux) → the other pump keeps running until its own EOF. The session's join completes when BOTH pumps finish. Half-close semantics validated end-to-end (reverse POC W4).
  • Error surface: a failed open resolves a typed error — ChannelOpenError::CallFailed carrying the wire CallError; branch on establishment_reason() for channel:open_failed's reason (ADR-049 §4). A failed open never yields a session (no phantom session, mirroring the no-phantom-channel property).
  • TunnelSession does not implement Clone. One session = one channel; aliasing a session would alias its teardown. Multi-channel consumers hold a Vec<TunnelSession> (or the assembly layer does).

Consequences

  • Assembly layers cannot leak adopted channels by forgetting to reap — the type is the discipline (the W3 gap closes structurally).
  • The reverse-flow initiator gets the same session shape as the forward consumer: the reverse POC's hub-side ReverseTunnel is the seed; the spec generalizes it so -L and -R consumers share one API (role-follows-resource, OQ-TN-03).
  • Observability for free: join's copy counts surface the data-plane volumes without extra plumbing.
  • Serving-side parity is upstream's: the worker's pump handler is already wrapper-managed (R-02); the session only fixes the adopter asymmetry.
  • Drop-based teardown is best-effort (abort + sync reap, no await) — the documented contract; graceful flows call join or close explicitly.

References

  • Reverse POC: docs/research/reverse-poc-summary.md §W3 (the finding), §W4 (half-close validation)
  • OQ-TN-03, OQ-TN-04, OQ-TN-09 (promoted)
  • alkcall ADR-049 + review 007 R-02 (wrapper-managed serving side), ADR-050 (pump_bidi + copy counts), ADR-047 §5 (allocation — the initiator adopts)
  • AGENTS.md convention 10 (limits inherited — the session adds no second bookkeeping layer; it owns exactly one channel's lifecycle)