Skip to content

Commit cca49e6

Browse files
committed
fix(runtime): align stacktrace readers and guard crash report order
1 parent 018b389 commit cca49e6

10 files changed

Lines changed: 99 additions & 35 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,10 @@ jobs:
202202
# Keep timing-sensitive reactor checks isolated, as in the shell runner.
203203
run: ./target/release/nera test -j 1 --timeout 30 --shard ${{ matrix.part }}/3
204204

205+
- name: Uncaught stacktrace order
206+
if: matrix.part == 1
207+
run: python3 scripts/test-stacktrace-order.py
208+
205209
cowlib:
206210
name: Cowlib (Linux x86_64)
207211
needs: [changes, build]

‎CHANGELOG.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,12 @@ All notable milestones for the nera project are documented in this file.
1111
exit reasons, such as a failed `gen_server` start.
1212
- `erlang:raise/3` keeps the supplied stacktrace's order, including when it
1313
re-raises a captured exception.
14+
- Uncaught crash reports keep the raising function first, with a corrected
15+
"most recent call first" header. `process_info(self(), current_stacktrace)`
16+
now lists the innermost function first too.
1417
- The `stacktrace_order` fixture checks caught errors, throws, exits and
15-
failed matches, re-raises and stack-bearing exit reasons on native Nera
16-
and BEAM.
18+
failed matches, re-raises, the current stacktrace and stack-bearing exit
19+
reasons on native Nera and BEAM.
1720

1821
## Funs stored in ETS and persistent_term keep their captured values
1922

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,7 @@ cargo clippy --workspace --all-targets --locked -- -D warnings
227227
cargo test --workspace --locked --no-fail-fast
228228
python3 scripts/test-allocator-config.py
229229
./target/release/nera test -j 1 --timeout 30
230+
python3 scripts/test-stacktrace-order.py
230231
```
231232

232233
For runtime shutdown changes, build the runtime before the compiler (so native

‎crates/nera-runtime/src/ffi/helpers.rs‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -171,24 +171,29 @@ fn fill_exception_trace(trace: &mut Vec<crate::process::StackFrame>, frames: Tra
171171
trace.clear();
172172
match frames {
173173
TraceFrames::Full(frames) => trace.extend(frames.iter().rev().copied()),
174-
TraceFrames::Compact(frames) => {
175-
let info_table = crate::entry::global_func_info_table();
176-
trace.extend(frames.iter().rev().map(|cf| {
177-
let (module, function, arity) = info_table
178-
.get(cf.func_index as usize)
179-
.copied()
180-
.unwrap_or((0, 0, 0));
181-
crate::process::StackFrame {
182-
module,
183-
function,
184-
arity,
185-
line: cf.line,
186-
}
187-
}));
188-
}
174+
TraceFrames::Compact(frames) => trace.extend(compact_stacktrace(frames)),
189175
}
190176
}
191177

178+
/// Convert an active compact call stack to Erlang's innermost-first order.
179+
pub(super) fn compact_stacktrace(
180+
frames: &[crate::process::CompactFrame],
181+
) -> impl Iterator<Item = crate::process::StackFrame> + '_ {
182+
let info_table = crate::entry::global_func_info_table();
183+
frames.iter().rev().map(move |cf| {
184+
let (module, function, arity) = info_table
185+
.get(cf.func_index as usize)
186+
.copied()
187+
.unwrap_or((0, 0, 0));
188+
crate::process::StackFrame {
189+
module,
190+
function,
191+
arity,
192+
line: cf.line,
193+
}
194+
})
195+
}
196+
192197
/// Helper: raise an error exception and return nil.
193198
/// Used by FFI functions when they encounter bad arguments.
194199
/// # Safety

‎crates/nera-runtime/src/ffi/process.rs‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,15 +1101,7 @@ unsafe fn gather_process_info_snapshot(
11011101
if !base.is_null() && cursor > base {
11021102
let depth = (cursor as usize - base as usize) / std::mem::size_of::<crate::process::CompactFrame>();
11031103
let frames = unsafe { std::slice::from_raw_parts(base, depth) };
1104-
let info_table = crate::entry::global_func_info_table();
1105-
frames.iter().map(|cf| {
1106-
let (module, function, arity) = if (cf.func_index as usize) < info_table.len() {
1107-
info_table[cf.func_index as usize]
1108-
} else {
1109-
(0, 0, 0)
1110-
};
1111-
crate::process::StackFrame { module, function, arity, line: cf.line }
1112-
}).collect()
1104+
compact_stacktrace(frames).collect()
11131105
} else {
11141106
Vec::new()
11151107
}

‎crates/nera-runtime/src/scheduler.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1710,8 +1710,8 @@ fn worker_loop(
17101710
let trace = &proc.exception_trace;
17111711
if !trace.is_empty() {
17121712
let atoms = crate::atom_table::global_atom_table();
1713-
eprintln!("Stacktrace (most recent call last):");
1714-
for frame in trace.iter().rev() {
1713+
eprintln!("Stacktrace (most recent call first):");
1714+
for frame in trace.iter() {
17151715
let mod_name = atoms
17161716
.resolve(frame.module)
17171717
.unwrap_or_else(|| "?".to_string());

‎docs/ERROR_DESIGN.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ Runtime crash output (`crates/nera-runtime/src/scheduler.rs`, lines 784-803):
288288

289289
```
290290
Error in process <0.42.0>: {error, badarg}
291-
Stacktrace (most recent call last):
291+
Stacktrace (most recent call first):
292292
lists:member/2
293293
main:start/0
294294
```
@@ -396,7 +396,7 @@ stack frame — negligible.
396396
**Instead of:**
397397
```
398398
Error in process <0.5.0>: {error, {badmatch, {error, timeout}}}
399-
Stacktrace (most recent call last):
399+
Stacktrace (most recent call first):
400400
main:handle_request/1
401401
main:loop/1
402402
```
@@ -431,7 +431,7 @@ Stack:
431431
**Instead of:**
432432
```
433433
Error in process <0.5.0>: {error, function_clause}
434-
Stacktrace (most recent call last):
434+
Stacktrace (most recent call first):
435435
main:process/1
436436
main:start/0
437437
```
@@ -494,7 +494,7 @@ Stack:
494494
**Instead of:**
495495
```
496496
Error in process <0.5.0>: {error, badarg}
497-
Stacktrace (most recent call last):
497+
Stacktrace (most recent call first):
498498
erlang:list_to_integer/1
499499
main:parse_id/1
500500
```
@@ -811,7 +811,7 @@ Did you mean `lists:map/2`? (from the stdlib)
811811
**Before:**
812812
```
813813
Error in process <0.5.0>: {error, {badmatch, {error, timeout}}}
814-
Stacktrace (most recent call last):
814+
Stacktrace (most recent call first):
815815
main:handle_request/1
816816
main:loop/1
817817
```

‎scripts/test-stacktrace-order.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python3
2+
"""Keep native crash reports raising-first, as Erlang stacktrace lists are.
3+
4+
Run after rebuilding the runtime and compiler. The shared Erlang regression
5+
supplies the real nested calls; this checks the uncaught report on stderr.
6+
"""
7+
import argparse
8+
import os
9+
from pathlib import Path
10+
import re
11+
import subprocess
12+
import tempfile
13+
14+
15+
def main():
16+
parser = argparse.ArgumentParser(description=__doc__)
17+
parser.add_argument("--nera", type=Path, default=Path("target/release/nera"))
18+
parser.add_argument("--temp-parent", type=Path)
19+
args = parser.parse_args()
20+
compiler = args.nera.resolve()
21+
source = Path(__file__).resolve().parents[1] / "tests" / "stacktrace_order.erl"
22+
with tempfile.TemporaryDirectory(prefix="nera stacktrace order ", dir=args.temp_parent) as temporary:
23+
work = Path(temporary)
24+
binary = work / ("stacktrace-order.exe" if os.name == "nt" else "stacktrace-order")
25+
subprocess.run(
26+
[compiler, "build", source, "-e", "stacktrace_order:crash", "-o", binary],
27+
cwd=work, check=True, timeout=120,
28+
)
29+
result = subprocess.run(
30+
[binary], cwd=work, capture_output=True, text=True, timeout=30,
31+
)
32+
print(result.stderr, end="")
33+
assert result.returncode == 1, result
34+
assert "error:boom" in result.stderr, result.stderr
35+
assert "Stacktrace (most recent call first):" in result.stderr, result.stderr
36+
frames = re.findall(r"^ stacktrace_order:([^/]+)/\d+", result.stderr, re.MULTILINE)
37+
assert frames == ["inner", "middle", "outer", "crash"], frames
38+
print("uncaught stacktrace order ok")
39+
40+
41+
if __name__ == "__main__":
42+
main()

‎tests/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ nera test --list
2525

2626
# Control parallelism and timeout
2727
nera test -j 4 --timeout 30
28+
29+
# Check uncaught crash output using the same stacktrace_order fixture
30+
python3 scripts/test-stacktrace-order.py
2831
```
2932

3033
The legacy shell script `./tests/run_tests.sh` is still available but `nera test`
@@ -224,7 +227,7 @@ These are automatically skipped by the runner and show up as SKIP in output.
224227
| `branch_export_reads.erl` | Names bound in `begin...end` or every `case`/`if`/`receive` branch, read afterwards: bodies, nested and scrutinee exports, call arguments, `try ... of`, fun-head and generator keys and sizes, construction sizes, guards, captures, later patterns and binary tails; funs in record field defaults; fun heads and generators still shadow, and a comprehension's first generator source keeps its bindings local; a binary tail read in a comprehension source or `maybe` block stays readable after it; a name local to an earlier fun does not stop a later read; a generator source or `catch` operand reads its own exports; a sibling clause, fun clause or receive timeout may reuse the name; also run on BEAM | 71 |
225228
| `receive_timeout_bindings.erl` | Names bound in a `receive`'s `after` timeout expression, read after the `receive`: the timeout and message paths, a block timeout, binary tails, later patterns, guards, fun captures and fun-head map keys; also run on BEAM | 6 |
226229
| `exception_basic.erl` | try/catch/throw/error/exit | ~12 |
227-
| `stacktrace_order.erl` | Raising function before non-tail callers: caught error/throw/exit/badmatch, full and shortened real traces through raise/3, monitored {Reason, Stack} exits and failed gen_server starts; also run on BEAM | Table-driven |
230+
| `stacktrace_order.erl` | Innermost function before non-tail callers: current_stacktrace, caught error/throw/exit/badmatch, full and shortened real traces through raise/3, monitored {Reason, Stack} exits and failed gen_server starts; also run on BEAM | Table-driven |
228231
| `try_of.erl` | try...of clause | ~6 |
229232
| `try_clause.erl` | Unmatched try-of results raise error:{try_clause, Value}: exact unmatched terms, failed guards, local-catch bypass and after cleanup, with matching and body-exception controls; also run on BEAM | Table-driven |
230233
| `try_catch_bound_vars.erl` | Bound names in try-of and catch class/reason patterns: exact equality, guards, fresh names, binary tails and re-raise; also run on BEAM | Table-driven |

‎tests/stacktrace_order.erl‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22
%% Stacktraces identify the raising function before its non-tail callers,
33
%% including re-raises and {Reason, Stack} exit reasons. Run on Nera and BEAM.
44
-module(stacktrace_order).
5-
-export([test/0, init/1]).
5+
-export([test/0, init/1, crash/0]).
66

77
test() ->
88
{outer, {middle, ok}} = outer(ok),
9+
ok = check_current_stacktrace(),
910
lists:foreach(fun check_caught/1, [error, throw, exit, badmatch]),
1011
lists:foreach(fun check_reraised/1, [error, throw, exit, badmatch]),
1112
ok = check_exit_reason(),
@@ -31,6 +32,8 @@ inner(error) -> erlang:error(boom);
3132
inner(throw) -> throw(boom);
3233
inner(exit) -> exit(boom);
3334
inner(badmatch) -> 1 = id(2), ok;
35+
inner(current_stacktrace) ->
36+
{current_stacktrace, erlang:process_info(self(), current_stacktrace)};
3437
inner(ok) -> ok.
3538

3639
expected(error) -> {error, boom};
@@ -46,6 +49,14 @@ check_order(Stack) ->
4649
first_calls(Stack) ->
4750
[{M, F, A} || {M, F, A, _} <- lists:sublist(Stack, 3)].
4851

52+
check_current_stacktrace() ->
53+
{outer, {middle, {current_stacktrace, {current_stacktrace, Stack}}}} =
54+
outer(current_stacktrace),
55+
%% BEAM includes a process_info/2 BIF frame that Nera does not record.
56+
Calls = [Frame || {M, _, _, _} = Frame <- Stack, M =:= ?MODULE],
57+
ok = check_order(Calls),
58+
io:format("current stacktrace: ~p~n", [first_calls(Calls)]).
59+
4960
check_reraised(Mode) ->
5061
{Class, Reason, Original} = captured(Mode),
5162
%% Also supply a shortened, real trace: raise/3 must keep list order,
@@ -78,5 +89,8 @@ check_failed_start() ->
7889
ok = check_order(Stack),
7990
io:format("failed start: ~p~n", [first_calls(Stack)]).
8091

92+
%% Uncaught entry used by scripts/test-stacktrace-order.py to check stderr.
93+
crash() -> {crash, outer(error)}.
94+
8195
init([]) -> {ok, outer(error)}.
8296
id(X) -> X.

0 commit comments

Comments
 (0)