perf(mobile): trim relay call-site stacks and capture them before async waits (#9949)

## Summary

Two follow-ups to the call-site stacks that escaped relay errors carry:

- **Trim:** Sentry parses a whole stack synchronously and has no cap, so
a call-site stack is now cut to its innermost 64 lines (async gap lines
included). When the kept lines hold no `<asynchronous suspension>` line,
one is added after them, so Sentry's stack parser still reads it as a VM
stack directly instead of first scanning it for other formats. The cut
is made when the stack is first formatted, so an error its caller
discards costs no formatting. One `completeErrorAt` helper next to the
error types applies it at every completion site, and query timeouts
throw with the cut stack too.
- **Capture at entry:** `publish`, `fetchHistory` and
`SignedEventRelay.submit` took their call site after the rate-limit
wait, `mayPublish` or `onSigned`. A caller that doesn't await the call
was already gone from the stack by then, so its frame was missing. The
call site is now taken before the first `await`. `submit` re-stacks
relay call errors from `publish` with its own entry stack, since
`publish` only starts after `onSigned`.

### Validation

Added tests: [stack
trimming](https://github.com/block/buzz/blob/tomb/mobile-relay-stack-trim/mobile/test/shared/relay/relay_call_error_test.dart)
(a deep stack is cut to the cap and keeps the frames nearest the call; a
short one is kept whole; a cut stack keeps exactly one async gap
wherever its first gap falls; the stack is formatted only when read, and
only once), and [capture before the
wait](https://github.com/block/buzz/blob/tomb/mobile-relay-stack-trim/mobile/test/shared/relay/relay_session_test.dart)
for a publish and a history request held by the rate limit and a submit
held by `onSigned`, each checking that the caller's frame is on the
completed error's stack.


Full-app check on an iOS simulator signed in to a Builderlab community:
the channel list loads, opening two channels fetches their history, and
a sent message publishes and shows as sent. No relay call errors logged.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Tom Brow
2026-11-25 15:05:52 -08:00
committed by GitHub
parent 3c71556ff3
commit e421ac9870
7 changed files with 281 additions and 16 deletions

View File

@@ -1,5 +1,47 @@
import 'dart:async';
/// The most lines of a call site's stack that an error carries, counting
/// `<asynchronous suspension>` gaps and any symbolication header. Sentry parses
/// a whole stack synchronously and has no cap of its own.
const maxCallSiteFrames = 64;
/// The line the Dart VM writes for an async gap in a stack.
const _asyncGap = '<asynchronous suspension>';
/// [callSite] cut to its [maxCallSiteFrames] innermost lines. The cut is made
/// only when the stack is first formatted, so an error its caller discards
/// costs no formatting.
StackTrace trimCallSite(StackTrace callSite) => _TrimmedCallSite(callSite);
final class _TrimmedCallSite implements StackTrace {
_TrimmedCallSite(this._callSite);
final StackTrace _callSite;
late final String _text = () {
final text = _callSite.toString();
final lines = text.trimRight().split('\n');
if (lines.length <= maxCallSiteFrames) return text;
final kept = lines.take(maxCallSiteFrames).toList();
// stack_trace's `Chain.parse`, which Sentry uses, reads a VM stack
// directly only when it holds a gap line; without one it first tries
// other formats with whole-text regex scans. When the kept lines hold no
// gap, one after them keeps that fast path; a trailing gap adds no frame.
if (!kept.contains(_asyncGap)) kept.add(_asyncGap);
return '${kept.join('\n')}\n';
}();
@override
String toString() => _text;
}
extension RelayCallSiteCompleter<T> on Completer<T> {
/// Completes with [error] and the trimmed stack of the call that made this
/// completer, for errors that a timer or a socket callback completes later.
void completeErrorAt(Object error, StackTrace callSite) =>
completeError(error, trimCallSite(callSite));
}
/// The relay call an error came from.
enum RelayCall {
/// An EVENT sent over the socket and acknowledged with OK.

View File

@@ -87,7 +87,10 @@ class RelayHttpQueryClient {
_currentGeneration = null;
}
generation?.retire();
Error.throwWithStackTrace(_timedOut(timeout, RelayCall.query), callSite);
Error.throwWithStackTrace(
_timedOut(timeout, RelayCall.query),
trimCallSite(callSite),
);
} finally {
active = false;
generation?.release();
@@ -162,7 +165,10 @@ class RelayHttpQueryClient {
_currentGeneration = null;
}
generation?.retire();
Error.throwWithStackTrace(_timedOut(timeout, call), callSite);
Error.throwWithStackTrace(
_timedOut(timeout, call),
trimCallSite(callSite),
);
} finally {
finished = true;
// Cancelling an iterator that never listened leaves the body

View File

@@ -328,6 +328,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
final callSite = StackTrace.current;
final generation = _contextGeneration;
if (_rateLimitGate.isActive) await _rateLimitGate.wait();
if (_disposed || generation != _contextGeneration) {
@@ -335,7 +336,6 @@ class RelaySessionNotifier extends Notifier<SessionState> {
}
final subId = _nextSubId('h');
final completer = Completer<List<NostrEvent>>();
final timer = Timer(timeout, () {
final sub = _historySubscriptions.remove(subId);
if (sub != null && !sub.completer.isCompleted) {
@@ -353,6 +353,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
completer: completer,
timeout: timer,
startedAt: _now(),
callSite: callSite,
);
_historySubscriptions[subId] = subscription;
@@ -458,6 +459,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
Duration timeout = const Duration(seconds: 8),
Future<bool> Function()? mayPublish,
}) async {
final callSite = StackTrace.current;
final generation = _connectionGeneration;
if (_rateLimitGate.isActive) await _rateLimitGate.wait();
bool connected() => _isActiveConnection(generation) && _socketConnected;
@@ -465,7 +467,6 @@ class RelaySessionNotifier extends Notifier<SessionState> {
if ((mayPublish != null && !await mayPublish()) || !connected()) {
throw StateError('Event no longer wanted');
}
final completer = Completer<NostrEvent>();
final timer = Timer(timeout, () {
final pending = _pendingEvents.remove(event.id);
@@ -483,6 +484,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
completer: completer,
timeout: timer,
startedAt: _now(),
callSite: callSite,
);
_socket?.send(['EVENT', event.toJson()]);
@@ -938,7 +940,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
if (closedClass == RelayClosedClass.terminal &&
!isRelayDeadlineError(message)) {
if (readyCompleter != null && !readyCompleter.isCompleted) {
readyCompleter.completeError(
readyCompleter.completeErrorAt(
RelayClosedException(RelayCall.subscribe, message),
liveSub.callSite,
);

View File

@@ -6,11 +6,12 @@ class _HistorySubscription {
final Timer timeout;
final DateTime startedAt;
/// Where the call was made. Errors completed later, from a timer or a
/// socket callback, carry it, so an escaped error's stack reaches the caller.
final StackTrace callSite = StackTrace.current;
/// Where the call was made, before any wait. Errors completed later, from a
/// timer or a socket callback, carry it, so an escaped error's stack reaches
/// the caller.
final StackTrace callSite;
void fail(Object error) => completer.completeError(error, callSite);
void fail(Object error) => completer.completeErrorAt(error, callSite);
void timedOut(Duration timeout) => fail(
RelayTimeoutException(
@@ -27,6 +28,7 @@ class _HistorySubscription {
required this.completer,
required this.timeout,
required this.startedAt,
required this.callSite,
});
}
@@ -97,11 +99,12 @@ class _PendingEvent {
final Timer timeout;
final DateTime startedAt;
/// Where the call was made. Errors completed later, from a timer or a
/// socket callback, carry it, so an escaped error's stack reaches the caller.
final StackTrace callSite = StackTrace.current;
/// Where the call was made, before any wait. Errors completed later, from a
/// timer or a socket callback, carry it, so an escaped error's stack reaches
/// the caller.
final StackTrace callSite;
void fail(Object error) => completer.completeError(error, callSite);
void fail(Object error) => completer.completeErrorAt(error, callSite);
void timedOut(String eventId, Duration timeout) => fail(
RelayAckTimeoutError(
@@ -114,6 +117,7 @@ class _PendingEvent {
required this.completer,
required this.timeout,
required this.startedAt,
required this.callSite,
});
}

View File

@@ -42,6 +42,9 @@ class SignedEventRelay {
FutureOr<void> Function(NostrEvent event)? onSigned,
Future<bool> Function()? mayPublish,
}) async {
// Taken before the first await, while the caller is still on the stack: a
// caller that doesn't await this call is gone from it afterwards.
final callSite = StackTrace.current;
final nsec = _nsec;
if (nsec == null || nsec.isEmpty) {
throw Exception('Cannot submit event: no signing key available');
@@ -64,7 +67,12 @@ class SignedEventRelay {
// Durable callers must finish journaling the exact signed bytes before
// the relay can accept an event whose acknowledgement might be lost.
await onSigned?.call(nostrEvent);
return _session.publish(nostrEvent, mayPublish: mayPublish);
try {
return await _session.publish(nostrEvent, mayPublish: mayPublish);
} on RelayCallError catch (error) {
// The session's own call site starts after the wait for `onSigned`.
Error.throwWithStackTrace(error, trimCallSite(callSite));
}
}
}
@@ -122,7 +130,7 @@ Future<NostrEvent> submitSignedEventOnce({
var expired = false;
void fail(Object error) {
if (result.isCompleted) return;
result.completeError(
result.completeErrorAt(
sent ? SignedEventUnacknowledged(error) : error,
callSite,
);
@@ -160,7 +168,7 @@ Future<NostrEvent> submitSignedEventOnce({
operation: DiagnosticOperation.relayRejection,
);
}
result.completeError(_SignedEventRejection(detail), callSite);
result.completeErrorAt(_SignedEventRejection(detail), callSite);
}
}
},

View File

@@ -130,4 +130,103 @@ void main() {
expect(error.duration, const Duration(seconds: 8));
});
});
group('the stack an escaped error carries', () {
List<String> lines(StackTrace trace) =>
trace.toString().trimRight().split('\n');
const gap = '<asynchronous suspension>';
Future<StackTrace> completedWith(StackTrace callSite) async {
final completer = Completer<void>();
completer.completeErrorAt(Exception('late'), callSite);
try {
await completer.future;
} catch (_, trace) {
return trace;
}
throw StateError('the completer did not fail');
}
test('is cut to the innermost $maxCallSiteFrames lines', () async {
final deep = _stackFromDepth(maxCallSiteFrames * 3);
final deepLines = lines(deep);
expect(deepLines.indexOf(gap), greaterThan(maxCallSiteFrames));
final trace = await completedWith(deep);
expect(lines(trace), [...deepLines.take(maxCallSiteFrames), gap]);
});
// A stack whose kept lines hold no async gap gets one after them, so
// Sentry's parser reads it as a VM stack without first trying other
// formats. A gap it already keeps needs none: a second one would parse as
// an extra frame.
for (final (gapLine, appended) in [
(null, true),
(30, false),
(maxCallSiteFrames, false),
(maxCallSiteFrames + 1, true),
(maxCallSiteFrames + 40, true),
]) {
test('with its first gap on line $gapLine '
'${appended ? 'gets one after the cut' : 'gets no other'}', () async {
final callSite = _TextStackTrace(
List.generate(
maxCallSiteFrames + 60,
(i) => i + 1 == gapLine ? gap : '#$i frame$i (file.dart:$i)',
),
);
expect(lines(await completedWith(callSite)), [
...callSite.lines.take(maxCallSiteFrames),
if (appended) gap,
]);
});
}
test('is formatted only when read, and only once', () async {
final callSite = _CountingStackTrace(maxCallSiteFrames + 36);
final trace = await completedWith(callSite);
expect(callSite.formats, 0);
trace.toString();
expect(lines(trace), hasLength(maxCallSiteFrames + 1));
expect(callSite.formats, 1);
});
test('is kept whole when it is short', () async {
final shallow = _stackFromDepth(3);
expect((await completedWith(shallow)).toString(), shallow.toString());
});
});
}
StackTrace _stackFromDepth(int depth) =>
depth == 0 ? StackTrace.current : _stackFromDepth(depth - 1);
final class _CountingStackTrace implements StackTrace {
_CountingStackTrace(this._lines);
final int _lines;
int formats = 0;
@override
String toString() {
formats++;
return List.generate(
_lines,
(i) => '#$i frame$i (file.dart:$i)',
).join('\n');
}
}
final class _TextStackTrace implements StackTrace {
_TextStackTrace(this.lines);
final List<String> lines;
@override
String toString() => '${lines.join('\n')}\n';
}

View File

@@ -2424,6 +2424,99 @@ void main() {
expect(stack.toString(), contains('_publishFromTheCaller'));
});
test(
'a publish held by the rate limit keeps the stack of its caller',
() async {
final gateTimers = <_ManualTimer>[];
final gate = RelayRateLimitGate(
timerFactory: (duration, callback) {
final timer = _ManualTimer(duration, callback);
gateTimers.add(timer);
return timer;
},
);
final session = RelaySessionNotifier(rateLimitGate: gate);
session.debugAttachSocketForTest(_RecordingRelaySocket());
gate.activate(4);
final publish = _publishFromTheCaller(session);
gateTimers.single.fire();
await Future<void>.delayed(Duration.zero);
session.debugHandleMessage(['OK', 'event-1', false, 'invalid: bad']);
StackTrace? stack;
try {
await publish;
} on RelayEventRejectedException catch (_, trace) {
stack = trace;
}
expect(stack.toString(), contains('_publishFromTheCaller'));
},
);
test(
'a history request held by the rate limit keeps the stack of its caller',
() async {
final gateTimers = <_ManualTimer>[];
final gate = RelayRateLimitGate(
timerFactory: (duration, callback) {
final timer = _ManualTimer(duration, callback);
gateTimers.add(timer);
return timer;
},
);
final session = RelaySessionNotifier(rateLimitGate: gate);
final socket = _RecordingRelaySocket();
session.debugAttachSocketForTest(socket);
gate.activate(4);
final history = _fetchHistoryFromTheCaller(session);
gateTimers.single.fire();
await Future<void>.delayed(Duration.zero);
session.debugHandleMessage([
'CLOSED',
_reqs(socket).last[1] as String,
'restricted: not a member',
]);
StackTrace? stack;
try {
await history;
} on RelayClosedException catch (_, trace) {
stack = trace;
}
expect(stack.toString(), contains('_fetchHistoryFromTheCaller'));
},
);
test('a submit held by signing keeps the stack of its caller', () async {
final session = RelaySessionNotifier();
final socket = _RecordingRelaySocket();
session.debugAttachSocketForTest(socket);
final relay = SignedEventRelay(
session: session,
nsec: nostr.Keys.generate().nsec,
);
final submit = _submitFromTheCaller(relay);
await Future<void>.delayed(Duration.zero);
final sent = socket.messages.single;
session.debugHandleMessage([
'OK',
(sent[1] as Map<String, dynamic>)['id'],
false,
'invalid: bad',
]);
StackTrace? stack;
try {
await submit;
} on RelayEventRejectedException catch (_, trace) {
stack = trace;
}
expect(stack.toString(), contains('_submitFromTheCaller'));
});
test('an unacknowledged publish is a timeout of the publish', () async {
final session = RelaySessionNotifier();
session.debugAttachSocketForTest(_RecordingRelaySocket());
@@ -2710,6 +2803,17 @@ class _FakeRelayConfigNotifier extends RelayConfigNotifier {
Future<NostrEvent> _publishFromTheCaller(RelaySessionNotifier session) =>
session.publish(_event());
Future<List<NostrEvent>> _fetchHistoryFromTheCaller(
RelaySessionNotifier session,
) => session.fetchHistory(_channelFilter);
Future<NostrEvent> _submitFromTheCaller(SignedEventRelay relay) => relay.submit(
kind: 1,
content: '',
tags: const [],
onSigned: (_) => Future<void>.delayed(Duration.zero),
);
NostrEvent _event({int createdAt = 20, String id = 'event-1'}) {
return NostrEvent(
id: id,