Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ All notable milestones for the nera project are documented in this file.
- Timeout cleanup waits for child termination and removes only that child's
startup monitor and exit signals, preserving unrelated mailbox messages.

## Active TCP line sockets discard incomplete lines at close

- On the TCP reactor path, peer close on an active `{packet, line}` socket
sends `{tcp_closed, Socket}` without delivering an unterminated last line,
as BEAM does. Complete lines delivered before close keep their terminators.

## TCP receive deadlines

- `gen_tcp:recv/3` now returns `{error, timeout}` when its finite timeout
Expand Down
31 changes: 31 additions & 0 deletions COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,37 @@ a dependency, or using the editor tools does not establish runtime compatibility
Dated Thoas sections below preserve historical evidence; the table above and
the integration README summary define the current verdict.

## Active TCP line close regression

`tests/tcp_line_close.erl` compares the Erlang mailbox messages when a peer
closes an active `{packet, line}` socket with an unterminated tail. It checks
that a preceding complete line still arrives with its terminator before
`tcp_closed`, and that a tail on its own produces only `tcp_closed`, including
when `{active, once}` is armed after the peer closes.

On Linux x86_64, the native Nera reactor delivered the tail as an extra
`tcp` message in all four cases before the fix. After the fix, the reactor
matched Erlang/OTP 27.3.4.6 with both the `inet` and `socket` backends:
`STATUS\r\n` followed by `tcp_closed` in the complete-line case, and only
`tcp_closed` in the three tail-only cases. Reproduce with a freshly built
Nera runtime and compiler (Rust 1.100.0) and the same fixture on BEAM:

```sh
./target/release/nera test tcp_line_close -j 1 --timeout 30
beam_dir=$(mktemp -d)
erlc -o "$beam_dir" tests/tcp_line_close.erl
for backend in inet socket; do
erl -kernel inet_backend "$backend" -noshell -pa "$beam_dir" \
-eval 'ok = tcp_line_close:test(), halt().'
done
rm -rf "$beam_dir"
```

Every successful run prints `tcp_line_close_ok` after checking all four
mailbox sequences. This does not establish non-reactor mailbox behavior,
passive line framing, or behavior when re-arming a still-open line socket
with an already-buffered prefix.

## proc_lib startup failure regression

On macOS arm64 with Rust 1.99.0 and Erlang/OTP 29.1.2, the same
Expand Down
4 changes: 3 additions & 1 deletion FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,9 @@ Socket handles are plain integers (GC-safe). Blocking I/O operations are
dispatched to an async I/O thread pool so scheduler threads stay free for
CPU-bound process reductions. Active-mode sockets (`{active, once}`) deliver
`{tcp, Socket, Data}` messages to the controlling process. In `{packet, line}`
mode each message is one line with its `"\r\n"` or `"\n"`, as on BEAM.
mode each complete line keeps its `"\r\n"` or `"\n"`, as on BEAM. On the
reactor path, an active line socket sends `{tcp_closed, Socket}` at peer close
without delivering an unterminated tail.
On the mio reactor path, queued and in-flight registration commands keep the
scheduler alive until registration completes or fails. This includes active
TCP registration before any readiness event exists.
Expand Down
18 changes: 3 additions & 15 deletions crates/nera-runtime/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -745,24 +745,12 @@ fn handle_active_read_on_worker(
}
}
if got_eof {
// Deliver any remaining partial line before tcp_closed,
// matching BEAM behavior for incomplete lines at EOF.
if !line_buf.is_empty() {
let end = if line_buf.last() == Some(&b'\r') {
line_buf.len() - 1
} else {
line_buf.len()
};
if end > 0 {
build_tcp_data(proc, stream_handle, &line_buf[..end]);
}
line_buf.clear();
}
// BEAM discards any bytes that never reached a newline at EOF.
build_tcp_closed(proc, stream_handle);
crate::socket::set_active_local(stream_handle, ActiveMode::Passive);
} else {
crate::socket::set_line_buffer(stream_handle, line_buf);
}
// Save any remaining partial-line data for the next event.
crate::socket::set_line_buffer(stream_handle, line_buf);
} else {
// ── Raw mode: consume whatever is available ──
let mut buf = [0u8; 4096];
Expand Down
25 changes: 10 additions & 15 deletions crates/nera-runtime/src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,9 +763,9 @@ pub fn send(stream_handle: SocketHandle, data: &[u8]) -> io::Result<()> {
}

/// Read from a stream socket up to and including the next newline (`\n`).
/// The line keeps its `"\n"` or `"\r\n"` terminator, as BEAM delivers a
/// `{packet, line}` line. Safety limit: stops after 300,000 bytes to
/// prevent unbounded reads.
/// Keep the line terminator and discard an unterminated tail at EOF, as
/// BEAM does. Safety limit: stops after 300,000 bytes to prevent unbounded
/// reads.
pub fn recv_line(stream_handle: SocketHandle) -> io::Result<Vec<u8>> {
let mut line = Vec::new();
let mut byte = [0u8; 1];
Expand All @@ -774,13 +774,7 @@ pub fn recv_line(stream_handle: SocketHandle) -> io::Result<Vec<u8>> {
loop {
let n = recv_into(stream_handle, &mut byte)?;
if n == 0 {
if line.is_empty() {
return Err(io::Error::new(
io::ErrorKind::ConnectionAborted,
"closed",
));
}
return Ok(line);
return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "closed"));
}
line.push(byte[0]);
if byte[0] == b'\n' || line.len() >= MAX_LINE {
Expand Down Expand Up @@ -1127,10 +1121,10 @@ mod tests {
assert!(remove(h_new));
}

/// The `{packet, line}` reader that delivers active-mode lines where the
/// reactor is unavailable: each line keeps its terminator, as on BEAM.
/// The non-reactor active line reader must keep terminators and discard
/// an unterminated tail at peer EOF, as BEAM does.
#[test]
fn recv_line_keeps_each_line_terminator() {
fn recv_line_delivers_only_complete_lines_at_eof() {
use std::io::Write;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let mut client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap();
Expand All @@ -1139,14 +1133,15 @@ mod tests {
#[cfg(mio_supported)]
let server = mio::net::TcpStream::from_std(server);
let handle = register(Socket::Stream(Arc::new(server))).unwrap();
client.write_all(b"P\r\nQ\n\n\r\n").unwrap();
client.write_all(b"P\r\nQ\n\n\r\nQUIT\r").unwrap();
client.shutdown(std::net::Shutdown::Write).unwrap();
assert_eq!(recv_line(handle).unwrap(), b"P\r\n");
assert_eq!(recv_line(handle).unwrap(), b"Q\n");
assert_eq!(recv_line(handle).unwrap(), b"\n");
assert_eq!(recv_line(handle).unwrap(), b"\r\n");
assert_eq!(recv_line(handle).unwrap_err().kind(), io::ErrorKind::ConnectionAborted);
let eof = recv_line(handle);
assert!(remove(handle));
assert_eq!(eof.unwrap_err().kind(), io::ErrorKind::ConnectionAborted);
}

// ---------------------------------------------------------------
Expand Down
12 changes: 7 additions & 5 deletions docs/KNOWN_LIMITS.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,13 @@ platform and scope.
- **Sockets:** `gen_tcp:listen/2` ignores the `{port, P}` option when given in
the options list. `{active, 1}` returns `ok` but delivers no data and no
`tcp_passive` message. `{active, once}` and `{packet, line}` work: an active
socket delivers each line with its `"\r\n"` or `"\n"`, as BEAM does. In
`{packet, line}` mode, a passive `gen_tcp:recv/2,3` returns every byte
waiting, not one line. An incomplete last line is delivered when the peer
closes, where BEAM drops it. The start of a line read in active mode is lost
if the socket is then re-armed or read passively before the line ends.
socket keeps each complete line's `"\r\n"` or `"\n"`. The reactor drops an
incomplete last line at peer close, as BEAM does. Without the reactor, the
active reader handles only one packet per activation and cannot report a
close after a complete line without another activation. In `{packet, line}`
mode, a passive `gen_tcp:recv/2,3` returns every byte waiting, not one line.
The start of a line read in active mode is lost if the socket is then
re-armed or read passively before the line ends.
- **Late replies:** after a `gen_server:call` times out, the late reply still
arrives in the caller's mailbox. OTP's process aliases prevent that, and
Nera does not use them.
Expand Down
1 change: 1 addition & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,7 @@ These are automatically skipped by the runner and show up as SKIP in output.

| Test File | Feature Category | Assertions |
|---------------------------|-------------------------------------------|------------|
| `tcp_line_close.erl` | On the reactor path, peer close discards an incomplete last line on an active `{packet, line}` socket. A complete preceding line arrives before `tcp_closed`; no further socket message is already queued. Covers `{active, true}` and `{active, once}` armed before sending or after peer close; also runnable on BEAM | 4 cases |
| `tcp_line_terminator.erl` | An active `{packet, line}` socket delivers each line with its `"\r\n"` or `"\n"`: `{active, once}` armed before the data arrives and while it is waiting, then a passive recv of the rest; `{active, true}` with several lines and empty lines in one write, and lines split across writes, one between `"\r"` and `"\n"`; a partial line completed by a later write; also run on BEAM | 5 cases |

### OTP Behaviours
Expand Down
49 changes: 49 additions & 0 deletions tests/tcp_line_close.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
%% EXPECT: tcp_line_close_ok
%% BEAM drops an unterminated final packet on an active line socket. A
%% complete packet preceding that tail still arrives before tcp_closed.
-module(tcp_line_close).
-export([test/0]).

test() ->
AfterLine = close_messages(true_after_line, true, <<"STATUS\r\nQUIT">>, before_send),
TrailingCR = close_messages(true_trailing_cr, true, <<"QUIT\r">>, before_send),
OnceBeforeSend = close_messages(once_before_send, once, <<"NOOP">>, before_send),
OnceAfterClose = close_messages(once_after_close, once, <<"PING">>, after_close),
[{tcp, <<"STATUS\r\n">>}, tcp_closed] = AfterLine,
[tcp_closed] = TrailingCR,
[tcp_closed] = OnceBeforeSend,
[tcp_closed] = OnceAfterClose,
io:format("tcp_line_close_ok~n").

close_messages(Name, Mode, Bytes, Arm) ->
{ok, Listener} = gen_tcp:listen(0, [{active, false}, binary, {packet, line}]),
{ok, Port} = inet:port(Listener),
{ok, Peer} = gen_tcp:connect({127,0,0,1}, Port, [{active, false}, binary]),
{ok, Socket} = gen_tcp:accept(Listener),
ok = gen_tcp:close(Listener),
ok = maybe_arm(Socket, Mode, Arm, before_send),
ok = gen_tcp:send(Peer, Bytes),
ok = gen_tcp:close(Peer),
ok = maybe_arm(Socket, Mode, Arm, after_close),
Messages = until_close(Socket, []),
io:format("~s: ~w~n", [Name, Messages]),
ok = gen_tcp:close(Socket),
Messages.

maybe_arm(Socket, Mode, When, When) -> inet:setopts(Socket, [{active, Mode}]);
maybe_arm(_Socket, _Mode, _Arm, _When) -> ok.

until_close(Socket, Acc) ->
receive
{tcp, Socket, Data} -> until_close(Socket, [{tcp, Data} | Acc]);
{tcp_closed, Socket} ->
receive
Extra when element(2, Extra) =:= Socket ->
erlang:error({message_after_close, Extra})
after 0 -> ok
end,
lists:reverse([tcp_closed | Acc]);
{tcp_error, Socket, Reason} -> lists:reverse([{tcp_error, Reason} | Acc])
after 2000 ->
lists:reverse([timeout | Acc])
end.
Loading