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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

All notable milestones for the nera project are documented in this file.

## Passive TCP receives return one line at a time

- On a passive `{packet, line}` socket, `gen_tcp:recv(Socket, 0)` and its
timeout form return one complete line, including `\n` or `\r\n`, even when
several lines are waiting. An unfinished line survives a timeout and is
discarded if the peer closes before completing it. Lines above 300,000
bytes, including the terminator, return `{error, emsgsize}`.

## Bare binary comprehension bodies match `erlc`

- Bare calls, signed expressions, map literals, record literals and record
Expand Down
34 changes: 34 additions & 0 deletions COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,40 @@ 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.

## Passive TCP line receive regression

`tests/tcp_recv_line.erl` checks `gen_tcp:recv/2,3` with length zero on a
passive `{packet, line}` socket. The unchanged native Linux x86_64 runtime
returned `STATUS\r\nQUIT\n\n` in one binary. On Erlang/OTP 27.3.4.6,
both `inet` and `socket` return three lines with their original terminators.
The fixture also checks that a partial line survives a poll and a finite
timeout, that a pending read completes when its line arrives, and that peer
and local close return `{error, closed}` rather than an unfinished line.

Reproduce with a freshly built runtime and compiler (Rust 1.100.0):

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

Compare the printed receive results and the final `tcp_recv_line_ok` marker.
This comparison does not cover bytes already read in active mode or positive
lengths. Both BEAM backends reject a positive length with `{error, einval}`
in line mode; Nera still requests an exact byte count.

`./target/release/nera test tcp_recv_line_limit -j 1 --timeout 30` checks
Nera's separate size policy: a 300,000-byte line succeeds and a 300,001-byte
unfinished line returns `{error, emsgsize}` without delivery. Switching to
raw mode can recover the original bytes. BEAM's `inet` and `socket`
backends already differ on large lines, so this is not a BEAM comparison.

## proc_lib startup failure regression

On macOS arm64 with Rust 1.99.0 and Erlang/OTP 29.1.2, the same
Expand Down
11 changes: 8 additions & 3 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,14 @@ 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 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.
mode each complete line keeps its `"\r\n"` or `"\n"`, as on BEAM. Passive
`gen_tcp:recv/2,3` with length zero returns one complete line at a time.
A timeout preserves any incomplete line for the next receive; a passive
line read discards an unfinished tail at peer close. Lines longer than
300,000 bytes including the terminator return `{error, emsgsize}` rather
than a truncated line. Switch to raw mode to recover the buffered bytes.
On the reactor path, an active line socket sends `{tcp_closed, Socket}` at
peer close without also 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
42 changes: 34 additions & 8 deletions crates/nera-runtime/src/ffi/gen_tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_accept(
}
}

/// gen_tcp:recv/2 uses the same validated length and exact-read path as recv/3.
/// gen_tcp:recv/2 is recv/3 with an infinite timeout.
///
/// # Safety
/// Requires the context and live-term invariants of nera_rt_gen_tcp_recv_3.
Expand Down Expand Up @@ -586,8 +586,8 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_close(

/// gen_tcp:recv/3 — receive data from a socket with timeout (ms).
/// Finite timeouts use a monotonic deadline shared by all partial reads.
/// If length > 0, reads exactly that many bytes. If length == 0, reads
/// any available data (same as recv/2).
/// A zero-length read returns one complete line in line mode, or whatever
/// data is available in raw mode. A positive length requests an exact read.
#[no_mangle]
pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3(
ctx: *mut ProcessContext,
Expand All @@ -610,14 +610,41 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3(
};
Some(std::time::Instant::now() + std::time::Duration::from_millis(u64::from(ms)))
};
let poll_only = timeout.as_small_int() == Some(0);
#[cfg(mio_supported)]
let self_pid = if !ctx.is_null() { unsafe { (*ctx).pid } } else { crate::process::ProcessId::new(0) };

if length == 0
&& crate::socket::with_entry_opts(handle, |opts| opts.packet) == Some(PacketMode::Line)
{
#[cfg(mio_supported)]
{
let mut buf = Vec::new();
if let Some(result) = crate::socket::try_recv_line(handle, &mut buf, deadline, poll_only) {
return with_ctx_heap(ctx, |heap| crate::io_pool::io_result_to_term(heap, result).0);
}
return submit_to_reactor_and_wait(
ctx,
crate::reactor::PendingOp::RecvLine {
pid: self_pid,
stream_handle: handle,
buf,
deadline,
},
);
}
#[cfg(not(mio_supported))]
return submit_io_and_wait(ctx, Box::new(move || {
crate::socket::recv_passive_line(handle, deadline, poll_only)
}));
}

#[cfg(not(mio_supported))]
if let Some(deadline) = deadline {
let poll_only = timeout.as_small_int() == Some(0);
return submit_io_and_wait(ctx, Box::new(move || {
crate::socket::recv_with_deadline(handle, length, deadline, poll_only)
}));
}
let self_pid = if !ctx.is_null() { unsafe { (*ctx).pid } } else { crate::process::ProcessId::new(0) };

if length > 0 {
let len = length;
Expand All @@ -639,13 +666,13 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3(
});
}
// A zero-timeout poll drains all currently available chunks, not just 4096 bytes.
if timeout.as_small_int() == Some(0) { continue; }
if poll_only { continue; }
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => return socket_error(ctx, io_error_to_atom_id(&e)),
}
if deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
crate::socket::restore_recv_buffer(handle, buf);
crate::socket::restore_recv_buffer(handle, &buf);
return socket_error(ctx, global_atom_table().intern("timeout"));
}
return submit_to_reactor_and_wait(ctx, crate::reactor::PendingOp::RecvExact {
Expand All @@ -665,7 +692,6 @@ pub unsafe extern "C" fn nera_rt_gen_tcp_recv_3(
}));
}
} else {
// length == 0: read any available data (same as recv/2)
#[cfg(mio_supported)]
{
match crate::socket::try_recv(handle) {
Expand Down
5 changes: 5 additions & 0 deletions crates/nera-runtime/src/io_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ pub(crate) fn wake_process_with_result(pid: ProcessId, result: IoResult) {
/// - `OkHandle(h)` → `{ok, H}` (small int)
/// - `Closed` → `{error, closed}`
/// - `Timeout` → `{error, timeout}`
/// - `MessageTooLarge` → `{error, emsgsize}`
/// - `Err(e)` → `{error, Reason}` where Reason is a POSIX atom
pub(crate) fn io_result_to_term(heap: &mut crate::heap::ProcessHeap, result: IoResult) -> ErlTerm {
match result {
Expand All @@ -284,6 +285,10 @@ pub(crate) fn io_result_to_term(heap: &mut crate::heap::ProcessHeap, result: IoR
ErlTerm::atom(ATOM_ERROR),
ErlTerm::atom(crate::atom_table::global_atom_table().intern("timeout")),
]),
IoResult::MessageTooLarge => heap.alloc_tuple(&[
ErlTerm::atom(ATOM_ERROR),
ErlTerm::atom(crate::atom_table::global_atom_table().intern("emsgsize")),
]),
IoResult::Err(e) => {
let error_atom = ErlTerm::atom(ATOM_ERROR);
let reason_atom = ErlTerm::atom(io_error_to_atom(e));
Expand Down
2 changes: 2 additions & 0 deletions crates/nera-runtime/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,8 @@ pub enum IoResult {
Closed,
/// A TCP receive deadline elapsed without completing the read.
Timeout,
/// A framed receive exceeded its packet limit.
MessageTooLarge,
/// I/O error.
Err(std::io::Error),
}
Expand Down
Loading
Loading