diff --git a/native/ocx-child/src/link_ws.rs b/native/ocx-child/src/link_ws.rs index 51a5c5574b0..e949b325875 100644 --- a/native/ocx-child/src/link_ws.rs +++ b/native/ocx-child/src/link_ws.rs @@ -754,9 +754,30 @@ fn pump(shared: &Arc, from: Leg, mut source: R) { } Ok(n) => n, }; - let mut events = Vec::new(); - let fault = reader.push(&buf[..n], &mut events).err(); - for event in events { + let mut remaining = &buf[..n]; + loop { + // Finish each event's write and release its allocation before parsing the next one. + // Fragmented text retains the reassembly capacity even when its payload is empty. + let event = match reader.next_event(&mut remaining) { + Ok(Some(event)) => event, + Ok(None) => break, + Err(fault) => { + let code = fault.close_code(); + match from { + Leg::Codex => terminate( + shared, + CloseAction::Frame(code, String::new()), + CloseAction::Frame(1011, String::new()), + ), + Leg::Home => terminate( + shared, + CloseAction::Frame(1011, "home message refused".into()), + CloseAction::Frame(code, String::new()), + ), + } + return; + } + }; match event { FrameEvent::Text(text) => { #[cfg(test)] @@ -813,22 +834,6 @@ fn pump(shared: &Arc, from: Leg, mut source: R) { } } } - if let Some(fault) = fault { - let code = fault.close_code(); - match from { - Leg::Codex => terminate( - shared, - CloseAction::Frame(code, String::new()), - CloseAction::Frame(1011, String::new()), - ), - Leg::Home => terminate( - shared, - CloseAction::Frame(1011, "home message refused".into()), - CloseAction::Frame(code, String::new()), - ), - } - return; - } } } diff --git a/native/ocx-child/src/link_ws_frame.rs b/native/ocx-child/src/link_ws_frame.rs index 9eda1053627..6e2b649c2e7 100644 --- a/native/ocx-child/src/link_ws_frame.rs +++ b/native/ocx-child/src/link_ws_frame.rs @@ -12,12 +12,14 @@ //! - UTF-8 validation of complete text messages and close reasons (a leading U+FEFF is kept); //! - close codes 1000-1003, 1007-1014 and 3000-4999 only; //! - a message limit checked before a payload is held, and at most a bounded number of fragments; -//! - at most the limit plus a 14-byte header held: an unfragmented message gets a buffer of its exact -//! size, a fragmented one is written into one buffer reserved once at the limit (no growth), and a +//! - at most the limit plus a 125-byte control payload and a 14-byte header held: an unfragmented +//! message gets a buffer of its exact size, a fragmented one is written into one buffer reserved +//! once at the limit (no growth), and a //! control frame between fragments uses its own buffer of at most 125 bytes. //! -//! A violation returns the fault whose close code to send; events completed earlier in the same input -//! are already in the caller's vector. The reader never interprets a message. +//! `next_event` stops at one completed event so the relay can release it before another message is +//! allocated. A violation returns the fault whose close code to send. The reader never interprets a +//! message. /// Largest control-frame payload. pub const MAX_CONTROL_PAYLOAD: usize = 125; @@ -119,10 +121,20 @@ impl FrameReader { self.assembly.as_ref().map_or(0, |a| a.capacity()) + own + self.header_len } - /// Feed bytes off the socket. Completed events are appended to `events` in wire order, also when a - /// later frame in the same input is refused. + /// Collect completed events in wire order, also when a later frame in the same input is refused. + /// Callers own the collected capacity; the relay uses `next_event` instead of buffering a batch. pub fn push(&mut self, data: &[u8], events: &mut Vec) -> Result<(), ProtocolFault> { - let result = self.push_inner(data, events); + let mut remaining = data; + while let Some(event) = self.next_event(&mut remaining)? { + events.push(event); + } + Ok(()) + } + + /// Consume through one event, leaving later frames in `data` untouched. Handle and drop the + /// returned event before calling again, so completed messages share the reader's payload bound. + pub fn next_event(&mut self, data: &mut &[u8]) -> Result, ProtocolFault> { + let result = self.next_event_inner(data); if result.is_err() { self.done = true; self.frame = None; @@ -131,19 +143,13 @@ impl FrameReader { result } - fn push_inner( - &mut self, - data: &[u8], - events: &mut Vec, - ) -> Result<(), ProtocolFault> { - let mut offset = 0; - while offset < data.len() && !self.done { + fn next_event_inner(&mut self, data: &mut &[u8]) -> Result, ProtocolFault> { + while !data.is_empty() && !self.done { if self.frame.is_none() { - let take = (self.header_needed - self.header_len).min(data.len() - offset); - self.header[self.header_len..self.header_len + take] - .copy_from_slice(&data[offset..offset + take]); + let take = (self.header_needed - self.header_len).min(data.len()); + self.header[self.header_len..self.header_len + take].copy_from_slice(&data[..take]); self.header_len += take; - offset += take; + *data = &data[take..]; if self.header_len < self.header_needed { continue; } @@ -153,12 +159,14 @@ impl FrameReader { continue; } } - self.start_frame(events)?; + if let Some(event) = self.start_frame()? { + return Ok(Some(event)); + } continue; } let frame = self.frame.as_mut().expect("frame in progress"); - let take = (frame.len - frame.filled).min(data.len() - offset); - let chunk = &data[offset..offset + take]; + let take = (frame.len - frame.filled).min(data.len()); + let chunk = &data[..take]; let target: &mut Vec = if frame.fragment { self.assembly.as_mut().expect("reassembly buffer") } else { @@ -177,13 +185,15 @@ impl FrameReader { None => target.extend_from_slice(chunk), } frame.filled += take; - offset += take; + *data = &data[take..]; if frame.filled == frame.len { let done = self.frame.take().expect("frame in progress"); - self.end_frame(done, events)?; + if let Some(event) = self.end_frame(done)? { + return Ok(Some(event)); + } } } - Ok(()) + Ok(None) } /// Validate the first two header bytes; returns the full header length. @@ -216,7 +226,7 @@ impl FrameReader { Ok(2 + extended + if masked { 4 } else { 0 }) } - fn start_frame(&mut self, events: &mut Vec) -> Result<(), ProtocolFault> { + fn start_frame(&mut self) -> Result, ProtocolFault> { let (b0, b1) = (self.header[0], self.header[1]); let fin = b0 & 0x80 != 0; let opcode = b0 & 0x0f; @@ -263,7 +273,7 @@ impl FrameReader { } let len = len as usize; if fragment && self.assembly.is_none() { - self.assembly = Some(Vec::with_capacity(self.max_message)); + self.assembly = Some(payload_buffer(self.max_message)?); } self.header_len = 0; self.header_needed = 2; @@ -277,37 +287,26 @@ impl FrameReader { own: if fragment { Vec::new() } else { - Vec::with_capacity(len) + payload_buffer(len)? }, }; if len == 0 { - self.end_frame(frame, events) + self.end_frame(frame) } else { self.frame = Some(frame); - Ok(()) + Ok(None) } } - fn end_frame( - &mut self, - frame: Frame, - events: &mut Vec, - ) -> Result<(), ProtocolFault> { + fn end_frame(&mut self, frame: Frame) -> Result, ProtocolFault> { match frame.opcode { - 9 => { - events.push(FrameEvent::Ping(frame.own)); - return Ok(()); - } - 10 => { - events.push(FrameEvent::Pong(frame.own)); - return Ok(()); - } + 9 => return Ok(Some(FrameEvent::Ping(frame.own))), + 10 => return Ok(Some(FrameEvent::Pong(frame.own))), 8 => { self.done = true; let payload = frame.own; if payload.is_empty() { - events.push(FrameEvent::Close(None, String::new())); - return Ok(()); + return Ok(Some(FrameEvent::Close(None, String::new()))); } if payload.len() == 1 { return Err(ProtocolFault::Protocol); @@ -318,8 +317,7 @@ impl FrameReader { } let reason = String::from_utf8(payload[2..].to_vec()).map_err(|_| ProtocolFault::Utf8)?; - events.push(FrameEvent::Close(Some(code), reason)); - return Ok(()); + return Ok(Some(FrameEvent::Close(Some(code), reason))); } _ => {} } @@ -328,7 +326,7 @@ impl FrameReader { } self.fragment_count += 1; if !frame.fin { - return Ok(()); + return Ok(None); } let message = if frame.fragment { self.assembly.take().unwrap_or_default() @@ -340,14 +338,22 @@ impl FrameReader { self.message_opcode = 0; if opcode == 1 { let text = String::from_utf8(message).map_err(|_| ProtocolFault::Utf8)?; - events.push(FrameEvent::Text(text)); + Ok(Some(FrameEvent::Text(text))) } else { - events.push(FrameEvent::Binary(message.len())); + Ok(Some(FrameEvent::Binary(message.len()))) } - Ok(()) } } +/// A refused payload allocation closes this connection instead of aborting the daemon. +fn payload_buffer(capacity: usize) -> Result, ProtocolFault> { + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(capacity) + .map_err(|_| ProtocolFault::TooLarge)?; + Ok(buffer) +} + /// The header of one final frame of `len` payload bytes; with a mask, the caller masks the payload /// (mask_in_place) before writing it after this header. pub fn frame_header(opcode: u8, len: usize, mask: Option<[u8; 4]>) -> Vec { @@ -699,6 +705,86 @@ mod tests { assert_eq!(reader.held_bytes(), 1024); } + #[test] + fn a_coalesced_fragment_burst_retains_only_one_completed_message() { + // Scale the message limit down: a batched reader would retain tens of MiB from this + // one socket read, but the relay's one-event path must keep only one payload allocation. + const LIMIT: usize = 64 * 1024; + for (role, masked) in [(Role::FromClient, true), (Role::FromServer, false)] { + for payload in [b"".as_slice(), b"x".as_slice()] { + let message = [ + frame(1, payload, false, masked), + frame(0, b"", true, masked), + ] + .concat(); + let tail = frame(1, b"unfinished", false, masked); + let count = (8 * 1024 - tail.len()) / message.len(); + let mut wire = message.repeat(count); + wire.extend_from_slice(&tail); + let mut remaining = wire.as_slice(); + let mut reader = FrameReader::new(role, LIMIT, 4); + let mut seen = 0; + while let Some(event) = reader.next_event(&mut remaining).unwrap() { + let FrameEvent::Text(text) = event else { + panic!("expected text"); + }; + assert_eq!(text.as_bytes(), payload); + assert!(reader.held_bytes() + text.capacity() <= LIMIT); + seen += 1; + // The next message is still unparsed, even though it is already in the read. + assert_eq!(remaining.len(), (count - seen) * message.len() + tail.len()); + drop(text); + } + assert_eq!(seen, count); + assert!(seen >= 500); + assert!(remaining.is_empty()); + assert_eq!(reader.held_bytes(), LIMIT); + } + } + } + + #[test] + fn next_event_preserves_later_fault_and_close_boundaries() { + let mut reader = FrameReader::new(Role::FromServer, 1024, 4); + let invalid = [0xc1, 1, b'x']; + let wire = [server(1, b"first"), invalid.to_vec()].concat(); + let mut remaining = wire.as_slice(); + assert_eq!( + reader.next_event(&mut remaining), + Ok(Some(FrameEvent::Text("first".into()))) + ); + assert_eq!(remaining, invalid); + assert_eq!( + reader.next_event(&mut remaining), + Err(ProtocolFault::Protocol) + ); + assert!(reader.closed()); + + let mut reader = FrameReader::new(Role::FromServer, 1024, 4); + let later = frame(1, b"unread", false, false); + let wire = [server(8, &[]), later.clone()].concat(); + let mut remaining = wire.as_slice(); + assert_eq!( + reader.next_event(&mut remaining), + Ok(Some(FrameEvent::Close(None, String::new()))) + ); + assert_eq!(reader.next_event(&mut remaining), Ok(None)); + assert_eq!(remaining, later); + assert_eq!(reader.held_bytes(), 0); + } + + #[test] + fn an_unrepresentable_payload_reservation_is_a_connection_fault() { + // usize::MAX fails the capacity check without asking the allocator for real memory. + let mut reader = FrameReader::new(Role::FromServer, usize::MAX, 4); + let wire = frame(1, b"", false, false); + let mut remaining = wire.as_slice(); + let fault = reader.next_event(&mut remaining).unwrap_err(); + assert_eq!(fault.close_code(), 1009); + assert!(reader.closed()); + assert!(reader.held_bytes() <= 14); + } + #[test] fn binary_by_size() { assert_eq!( diff --git a/native/ocx-child/tests/link_websocket.rs b/native/ocx-child/tests/link_websocket.rs index a7baffa71d6..89cae206d82 100644 --- a/native/ocx-child/tests/link_websocket.rs +++ b/native/ocx-child/tests/link_websocket.rs @@ -410,6 +410,41 @@ fn with_the_gate_an_advertising_home_carries_frames_both_ways() { ); } +#[test] +fn a_coalesced_fragment_burst_keeps_the_relay_and_other_clients_usable() { + let scratch = Scratch::new("link-ws-fragment-burst"); + let home = home(true, false); + let relay = relay(&scratch, home.port, &home.parity, true); + relayed_http(relay.port); + let (status, _, _, mut codex, leftover) = upgrade(relay.port, ""); + assert_eq!(status, 101); + + // A small real-relay burst complements the scaled-capacity frame-reader regression without + // relying on allocator exhaustion or OS-specific memory limits. + let mask = Some([0, 0, 0, 0]); + let mut first = frame_header(1, 0, mask); + first[0] &= 0x7f; + let message = [first, frame_header(0, 0, mask)].concat(); + codex.write_all(&message.repeat(16)).unwrap(); + assert_eq!( + read_codex(&mut codex, &leftover, 16), + (0..16) + .map(|_| FrameEvent::Text("echo:".into())) + .collect::>() + ); + assert_eq!( + echo_round_trip(&mut codex, &[], "after-burst"), + vec![FrameEvent::Text("echo:after-burst".into())] + ); + + let (status, _, _, mut other, leftover) = upgrade(relay.port, ""); + assert_eq!(status, 101); + assert_eq!( + echo_round_trip(&mut other, &leftover, "other-client"), + vec![FrameEvent::Text("echo:other-client".into())] + ); +} + /// Discovery: only a verified preflight of the serving process turns the state on, a failed /// one teaches nothing, the parity loop is not needed, and a Home that switches off ends on HTTP. #[test] diff --git a/structure/remote-link.md b/structure/remote-link.md index c3a022fc478..920b9ffc750 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -375,4 +375,4 @@ Authenticated shutdown is bounded by `stop_owned_daemon`'s 3-second wait; open l Foreground startup requires an attached state, matching recovery journal, verified link key and matching listener port. Sync, restart and detach refuse a journal bound to different canonical homes; detach checks this before changing state or stopping the relay. Shutdown authenticates both ends on one socket without sending the private secret and never signals a process based only on a reported PID. Attach keeps a private rollback snapshot until success or completed recovery; detach can retry an incomplete rollback. Failed restore or cleanup keeps recovery records for retry. On Windows, temporary replacements are created with a protected owner-only DACL before bytes are written. -Link WebSocket in `ocx-child`. `native/ocx-child/src/link_ws.rs`, `link_ws_advert.rs` and `link_ws_frame.rs` carry Codex's Responses WebSocket over the link the way the TypeScript Child does, behind ocx-child's own release gate: `link_ws_advert::gate_open` is false in every build without the `link-ws-test-gate` Cargo feature, whatever its profile, and only a build with it reads `OCX_CHILD_TEST_LINK_WS_READY`; `build:ocx-child` (`cargo build --release --locked`) passes no features, and `test:ocx-child` runs the crate once without the feature (a unit test proves the gate stays closed with the variable set) and once with it (the `link_websocket` integration target, `required-features`), checked by `tests/clients/link-ocx-child-ws-gate.test.ts`, which also makes the run without the feature in CI, and `tests/clients/link-ocx-child-ws-feature.test.ts`, which makes the run with it; each runs alone (`SERIAL_FULL_SUITE_FILES`), and both Cargo runs are skipped on Windows (`ocxChildLinkWsCargoSkipped` in `tests/helpers/ocx-child-cargo.ts`), where the `link_websocket` target did not finish inside its bound on the hosted runner; the gate is a compile-time cfg, closed in every build without the feature, and the conformance Cargo run still builds and runs ocx-child on Windows. While the gate is closed, or the Home's verified on has not been applied for the current link, the `/v1/responses` upgrade keeps its 426 body byte for byte and nothing reaches the tunnel. Every relay-auth preflight of the serving process (relayed HTTP requests, the parity report, the `/readyz` probe) takes a number before it is written, and its answer's `x-opencodex-link-ws-state`/`-proof` (exactly one of each, the proof an HMAC under the 32 fingerprint bytes, equal to the Home's `linkWebsocketStateProof`, pinned for both by the vectors in `tests/fixtures/link/link-ws-state-proof.json`) applies only to its own link id's entry and only above the last number applied for it; at most 8 links with per-link watermarks; lifecycle commands run in their own process and teach nothing. A tried upgrade needs no `Origin`, a valid Codex handshake (GET `/v1/responses` without a query, Upgrade, Connection, version 13, a 16-byte key, no body framing), a slot (8 open or setting up, 4 setting up, 32 MiB of 256 MiB), then one preflight and the upgrade on one connection inside one 8 s deadline, cancellable by stop, proceeding only on that answer's own verified on; the Home leg's headers are Codex's minus its handshake, the hop-by-hop and Connection-nominated set, `Origin`, `Host`, framing, caller credentials and the relay's internal headers, with the link key added through the wiped request-head pattern; a 101 counts only with Upgrade, Connection, the right accept value (SHA-1 written in the module for this one use) and no extension or subprotocol. Every failure is the same 426; ocx-child has no tunnel supervisor, so it has no 503 of its own (the existing `child_busy` and `child_starting` 503s apply to upgrades as to HTTP). ocx-child writes the local 101 itself, with `x-codex-websocket-max-message-bytes: 8388608`, under Codex's write lock inside a control operation deadline; no frame is ever written to Codex before it, and a stop that claimed the socket first leaves the 101 unwritten; the worker then answers today's 426 as best effort, since the stop also shuts Codex's connection down and Codex may see it close with nothing written instead. Every setup write (preflight and upgrade head) gives each write call only the time left before the 8 s deadline (`relay::write_all_before`), so a Home that drains slowly cannot stretch setup. One frame reader serves both roles with the TypeScript Child's bounds (masked frames from Codex, unmasked from the Home, 8 MiB and 4 MiB + 64 KiB, at most the limit plus a 14-byte header held). Each socket has two threads, the worker reading Codex and one spawned thread (256 KiB stack) reading the Home, each writing whole messages to the other leg under that leg's write lock; every frame write is one operation with an absolute deadline (data 600 s, control 30 s) registered before the lock, plus a 300 s no-progress write timeout, and a single reaper thread enforces every deadline by shutting both sockets down, never taking a write lock. One idempotent terminal transition closes both legs with a 5 s bound (close frames best effort); Codex's close without a status reaches the Home as an empty close frame, Codex's drop ends the Home connection without one, a Home close is relayed (1005, 1006 and 1015 as 1011), a binary message closes both legs with 1003. A stop (serve shutdown) aborts setups, closes every socket with 1001 (best effort, at most 1 s per socket, all at once) and waits until every slot is free; registration is refused once stop began, and the worker's start step checks stopping under the registry lock and the socket's state lock. A socket's slot and reservation are a lease released only when nothing can use its descriptors. A panic in either of a socket's threads still ends both connections, unregisters the socket and frees its slot, and a relay worker or control thread that panics still returns its admission (drop guards; the crate builds with unwinding). ocx-child has no Child-local opt-out, counters, diagnostics or byte book for the link WebSocket, as it has none for HTTP. Two limits hold today: a frame write registers its absolute deadline before it takes the leg's write lock, so a pong (30 s) that waits behind a long data write on the same leg can reach its deadline and have the socket cut while the data write is healthy (the Home's link socket sends no pings, `idleTimeout: 0`; a ping from Codex is answered on Codex's leg and meets the same limit); and every frame write registers and clears a reaper deadline, which wakes the reaper twice per frame. Coverage: unit tests in `link_ws_frame.rs`, `link_ws_advert.rs` and `link_ws.rs` (an in-process mock Home and Codex on loopback sockets), and `native/ocx-child/tests/link_websocket.rs` (the real binary: today's 426 without the gate and no connection to the Home; frames both ways with it; a failed preflight teaching nothing and a later one teaching on with the parity loop stopped; a Home that switches off answered by the upgrade's own preflight with 426, the turn then completing on HTTP; the `/readyz` probe teaching on; the authenticated shutdown closing both legs with 1001). +Link WebSocket in `ocx-child`. `native/ocx-child/src/link_ws.rs`, `link_ws_advert.rs` and `link_ws_frame.rs` carry Codex's Responses WebSocket over the link the way the TypeScript Child does, behind ocx-child's own release gate: `link_ws_advert::gate_open` is false in every build without the `link-ws-test-gate` Cargo feature, whatever its profile, and only a build with it reads `OCX_CHILD_TEST_LINK_WS_READY`; `build:ocx-child` (`cargo build --release --locked`) passes no features, and `test:ocx-child` runs the crate once without the feature (a unit test proves the gate stays closed with the variable set) and once with it (the `link_websocket` integration target, `required-features`), checked by `tests/clients/link-ocx-child-ws-gate.test.ts`, which also makes the run without the feature in CI, and `tests/clients/link-ocx-child-ws-feature.test.ts`, which makes the run with it; each runs alone (`SERIAL_FULL_SUITE_FILES`), and both Cargo runs are skipped on Windows (`ocxChildLinkWsCargoSkipped` in `tests/helpers/ocx-child-cargo.ts`), where the `link_websocket` target did not finish inside its bound on the hosted runner; the gate is a compile-time cfg, closed in every build without the feature, and the conformance Cargo run still builds and runs ocx-child on Windows. While the gate is closed, or the Home's verified on has not been applied for the current link, the `/v1/responses` upgrade keeps its 426 body byte for byte and nothing reaches the tunnel. Every relay-auth preflight of the serving process (relayed HTTP requests, the parity report, the `/readyz` probe) takes a number before it is written, and its answer's `x-opencodex-link-ws-state`/`-proof` (exactly one of each, the proof an HMAC under the 32 fingerprint bytes, equal to the Home's `linkWebsocketStateProof`, pinned for both by the vectors in `tests/fixtures/link/link-ws-state-proof.json`) applies only to its own link id's entry and only above the last number applied for it; at most 8 links with per-link watermarks; lifecycle commands run in their own process and teach nothing. A tried upgrade needs no `Origin`, a valid Codex handshake (GET `/v1/responses` without a query, Upgrade, Connection, version 13, a 16-byte key, no body framing), a slot (8 open or setting up, 4 setting up, 32 MiB of 256 MiB), then one preflight and the upgrade on one connection inside one 8 s deadline, cancellable by stop, proceeding only on that answer's own verified on; the Home leg's headers are Codex's minus its handshake, the hop-by-hop and Connection-nominated set, `Origin`, `Host`, framing, caller credentials and the relay's internal headers, with the link key added through the wiped request-head pattern; a 101 counts only with Upgrade, Connection, the right accept value (SHA-1 written in the module for this one use) and no extension or subprotocol. Every failure is the same 426; ocx-child has no tunnel supervisor, so it has no 503 of its own (the existing `child_busy` and `child_starting` 503s apply to upgrades as to HTTP). ocx-child writes the local 101 itself, with `x-codex-websocket-max-message-bytes: 8388608`, under Codex's write lock inside a control operation deadline; no frame is ever written to Codex before it, and a stop that claimed the socket first leaves the 101 unwritten; the worker then answers today's 426 as best effort, since the stop also shuts Codex's connection down and Codex may see it close with nothing written instead. Every setup write (preflight and upgrade head) gives each write call only the time left before the 8 s deadline (`relay::write_all_before`), so a Home that drains slowly cannot stretch setup. One frame reader serves both roles with the TypeScript Child's bounds (masked frames from Codex, unmasked from the Home, 8 MiB and 4 MiB + 64 KiB, plus bounded header and control-frame storage). The pump consumes one completed event at a time and releases its payload after handling or writing it, before it parses the next event; a coalesced read never queues completed message allocations beyond the socket reservation. Payload reservation is fallible and a refused allocation closes that connection with 1009. Each socket has two threads, the worker reading Codex and one spawned thread (256 KiB stack) reading the Home, each writing whole messages to the other leg under that leg's write lock; every frame write is one operation with an absolute deadline (data 600 s, control 30 s) registered before the lock, plus a 300 s no-progress write timeout, and a single reaper thread enforces every deadline by shutting both sockets down, never taking a write lock. One idempotent terminal transition closes both legs with a 5 s bound (close frames best effort); Codex's close without a status reaches the Home as an empty close frame, Codex's drop ends the Home connection without one, a Home close is relayed (1005, 1006 and 1015 as 1011), a binary message closes both legs with 1003. A stop (serve shutdown) aborts setups, closes every socket with 1001 (best effort, at most 1 s per socket, all at once) and waits until every slot is free; registration is refused once stop began, and the worker's start step checks stopping under the registry lock and the socket's state lock. A socket's slot and reservation are a lease released only when nothing can use its descriptors. A panic in either of a socket's threads still ends both connections, unregisters the socket and frees its slot, and a relay worker or control thread that panics still returns its admission (drop guards; the crate builds with unwinding). ocx-child has no Child-local opt-out, counters, diagnostics or byte book for the link WebSocket, as it has none for HTTP. Two limits hold today: a frame write registers its absolute deadline before it takes the leg's write lock, so a pong (30 s) that waits behind a long data write on the same leg can reach its deadline and have the socket cut while the data write is healthy (the Home's link socket sends no pings, `idleTimeout: 0`; a ping from Codex is answered on Codex's leg and meets the same limit); and every frame write registers and clears a reaper deadline, which wakes the reaper twice per frame. Coverage: unit tests in `link_ws_frame.rs`, `link_ws_advert.rs` and `link_ws.rs` (an in-process mock Home and Codex on loopback sockets), and `native/ocx-child/tests/link_websocket.rs` (the real binary: today's 426 without the gate and no connection to the Home; frames both ways with it; a failed preflight teaching nothing and a later one teaching on with the parity loop stopped; a Home that switches off answered by the upgrade's own preflight with 426, the turn then completing on HTTP; the `/readyz` probe teaching on; the authenticated shutdown closing both legs with 1001).