Skip to content

Commit e421ac9

Browse files
browstudio
andauthored
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>
1 parent 3c71556 commit e421ac9

7 files changed

Lines changed: 281 additions & 16 deletions

File tree

‎mobile/lib/shared/relay/relay_call_error.dart‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,47 @@
11
import 'dart:async';
22

3+
/// The most lines of a call site's stack that an error carries, counting
4+
/// `<asynchronous suspension>` gaps and any symbolication header. Sentry parses
5+
/// a whole stack synchronously and has no cap of its own.
6+
const maxCallSiteFrames = 64;
7+
8+
/// The line the Dart VM writes for an async gap in a stack.
9+
const _asyncGap = '<asynchronous suspension>';
10+
11+
/// [callSite] cut to its [maxCallSiteFrames] innermost lines. The cut is made
12+
/// only when the stack is first formatted, so an error its caller discards
13+
/// costs no formatting.
14+
StackTrace trimCallSite(StackTrace callSite) => _TrimmedCallSite(callSite);
15+
16+
final class _TrimmedCallSite implements StackTrace {
17+
_TrimmedCallSite(this._callSite);
18+
19+
final StackTrace _callSite;
20+
21+
late final String _text = () {
22+
final text = _callSite.toString();
23+
final lines = text.trimRight().split('\n');
24+
if (lines.length <= maxCallSiteFrames) return text;
25+
final kept = lines.take(maxCallSiteFrames).toList();
26+
// stack_trace's `Chain.parse`, which Sentry uses, reads a VM stack
27+
// directly only when it holds a gap line; without one it first tries
28+
// other formats with whole-text regex scans. When the kept lines hold no
29+
// gap, one after them keeps that fast path; a trailing gap adds no frame.
30+
if (!kept.contains(_asyncGap)) kept.add(_asyncGap);
31+
return '${kept.join('\n')}\n';
32+
}();
33+
34+
@override
35+
String toString() => _text;
36+
}
37+
38+
extension RelayCallSiteCompleter<T> on Completer<T> {
39+
/// Completes with [error] and the trimmed stack of the call that made this
40+
/// completer, for errors that a timer or a socket callback completes later.
41+
void completeErrorAt(Object error, StackTrace callSite) =>
42+
completeError(error, trimCallSite(callSite));
43+
}
44+
345
/// The relay call an error came from.
446
enum RelayCall {
547
/// An EVENT sent over the socket and acknowledged with OK.

‎mobile/lib/shared/relay/relay_http_query_client.dart‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,10 @@ class RelayHttpQueryClient {
8787
_currentGeneration = null;
8888
}
8989
generation?.retire();
90-
Error.throwWithStackTrace(_timedOut(timeout, RelayCall.query), callSite);
90+
Error.throwWithStackTrace(
91+
_timedOut(timeout, RelayCall.query),
92+
trimCallSite(callSite),
93+
);
9194
} finally {
9295
active = false;
9396
generation?.release();
@@ -162,7 +165,10 @@ class RelayHttpQueryClient {
162165
_currentGeneration = null;
163166
}
164167
generation?.retire();
165-
Error.throwWithStackTrace(_timedOut(timeout, call), callSite);
168+
Error.throwWithStackTrace(
169+
_timedOut(timeout, call),
170+
trimCallSite(callSite),
171+
);
166172
} finally {
167173
finished = true;
168174
// Cancelling an iterator that never listened leaves the body

‎mobile/lib/shared/relay/relay_session.dart‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -328,14 +328,14 @@ class RelaySessionNotifier extends Notifier<SessionState> {
328328
NostrFilter filter, {
329329
Duration timeout = const Duration(seconds: 8),
330330
}) async {
331+
final callSite = StackTrace.current;
331332
final generation = _contextGeneration;
332333
if (_rateLimitGate.isActive) await _rateLimitGate.wait();
333334
if (_disposed || generation != _contextGeneration) {
334335
throw StateError('Relay history request belongs to a retired session');
335336
}
336337
final subId = _nextSubId('h');
337338
final completer = Completer<List<NostrEvent>>();
338-
339339
final timer = Timer(timeout, () {
340340
final sub = _historySubscriptions.remove(subId);
341341
if (sub != null && !sub.completer.isCompleted) {
@@ -353,6 +353,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
353353
completer: completer,
354354
timeout: timer,
355355
startedAt: _now(),
356+
callSite: callSite,
356357
);
357358
_historySubscriptions[subId] = subscription;
358359

@@ -458,14 +459,14 @@ class RelaySessionNotifier extends Notifier<SessionState> {
458459
Duration timeout = const Duration(seconds: 8),
459460
Future<bool> Function()? mayPublish,
460461
}) async {
462+
final callSite = StackTrace.current;
461463
final generation = _connectionGeneration;
462464
if (_rateLimitGate.isActive) await _rateLimitGate.wait();
463465
bool connected() => _isActiveConnection(generation) && _socketConnected;
464466
if (!connected()) throw RelayNotConnectedError();
465467
if ((mayPublish != null && !await mayPublish()) || !connected()) {
466468
throw StateError('Event no longer wanted');
467469
}
468-
469470
final completer = Completer<NostrEvent>();
470471
final timer = Timer(timeout, () {
471472
final pending = _pendingEvents.remove(event.id);
@@ -483,6 +484,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
483484
completer: completer,
484485
timeout: timer,
485486
startedAt: _now(),
487+
callSite: callSite,
486488
);
487489

488490
_socket?.send(['EVENT', event.toJson()]);
@@ -938,7 +940,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
938940
if (closedClass == RelayClosedClass.terminal &&
939941
!isRelayDeadlineError(message)) {
940942
if (readyCompleter != null && !readyCompleter.isCompleted) {
941-
readyCompleter.completeError(
943+
readyCompleter.completeErrorAt(
942944
RelayClosedException(RelayCall.subscribe, message),
943945
liveSub.callSite,
944946
);

‎mobile/lib/shared/relay/relay_session_subscriptions.dart‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ class _HistorySubscription {
66
final Timer timeout;
77
final DateTime startedAt;
88

9-
/// Where the call was made. Errors completed later, from a timer or a
10-
/// socket callback, carry it, so an escaped error's stack reaches the caller.
11-
final StackTrace callSite = StackTrace.current;
9+
/// Where the call was made, before any wait. Errors completed later, from a
10+
/// timer or a socket callback, carry it, so an escaped error's stack reaches
11+
/// the caller.
12+
final StackTrace callSite;
1213

13-
void fail(Object error) => completer.completeError(error, callSite);
14+
void fail(Object error) => completer.completeErrorAt(error, callSite);
1415

1516
void timedOut(Duration timeout) => fail(
1617
RelayTimeoutException(
@@ -27,6 +28,7 @@ class _HistorySubscription {
2728
required this.completer,
2829
required this.timeout,
2930
required this.startedAt,
31+
required this.callSite,
3032
});
3133
}
3234

@@ -97,11 +99,12 @@ class _PendingEvent {
9799
final Timer timeout;
98100
final DateTime startedAt;
99101

100-
/// Where the call was made. Errors completed later, from a timer or a
101-
/// socket callback, carry it, so an escaped error's stack reaches the caller.
102-
final StackTrace callSite = StackTrace.current;
102+
/// Where the call was made, before any wait. Errors completed later, from a
103+
/// timer or a socket callback, carry it, so an escaped error's stack reaches
104+
/// the caller.
105+
final StackTrace callSite;
103106

104-
void fail(Object error) => completer.completeError(error, callSite);
107+
void fail(Object error) => completer.completeErrorAt(error, callSite);
105108

106109
void timedOut(String eventId, Duration timeout) => fail(
107110
RelayAckTimeoutError(
@@ -114,6 +117,7 @@ class _PendingEvent {
114117
required this.completer,
115118
required this.timeout,
116119
required this.startedAt,
120+
required this.callSite,
117121
});
118122
}
119123

‎mobile/lib/shared/relay/signed_event_relay.dart‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ class SignedEventRelay {
4242
FutureOr<void> Function(NostrEvent event)? onSigned,
4343
Future<bool> Function()? mayPublish,
4444
}) async {
45+
// Taken before the first await, while the caller is still on the stack: a
46+
// caller that doesn't await this call is gone from it afterwards.
47+
final callSite = StackTrace.current;
4548
final nsec = _nsec;
4649
if (nsec == null || nsec.isEmpty) {
4750
throw Exception('Cannot submit event: no signing key available');
@@ -64,7 +67,12 @@ class SignedEventRelay {
6467
// Durable callers must finish journaling the exact signed bytes before
6568
// the relay can accept an event whose acknowledgement might be lost.
6669
await onSigned?.call(nostrEvent);
67-
return _session.publish(nostrEvent, mayPublish: mayPublish);
70+
try {
71+
return await _session.publish(nostrEvent, mayPublish: mayPublish);
72+
} on RelayCallError catch (error) {
73+
// The session's own call site starts after the wait for `onSigned`.
74+
Error.throwWithStackTrace(error, trimCallSite(callSite));
75+
}
6876
}
6977
}
7078

@@ -122,7 +130,7 @@ Future<NostrEvent> submitSignedEventOnce({
122130
var expired = false;
123131
void fail(Object error) {
124132
if (result.isCompleted) return;
125-
result.completeError(
133+
result.completeErrorAt(
126134
sent ? SignedEventUnacknowledged(error) : error,
127135
callSite,
128136
);
@@ -160,7 +168,7 @@ Future<NostrEvent> submitSignedEventOnce({
160168
operation: DiagnosticOperation.relayRejection,
161169
);
162170
}
163-
result.completeError(_SignedEventRejection(detail), callSite);
171+
result.completeErrorAt(_SignedEventRejection(detail), callSite);
164172
}
165173
}
166174
},

‎mobile/test/shared/relay/relay_call_error_test.dart‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,103 @@ void main() {
130130
expect(error.duration, const Duration(seconds: 8));
131131
});
132132
});
133+
134+
group('the stack an escaped error carries', () {
135+
List<String> lines(StackTrace trace) =>
136+
trace.toString().trimRight().split('\n');
137+
const gap = '<asynchronous suspension>';
138+
139+
Future<StackTrace> completedWith(StackTrace callSite) async {
140+
final completer = Completer<void>();
141+
completer.completeErrorAt(Exception('late'), callSite);
142+
try {
143+
await completer.future;
144+
} catch (_, trace) {
145+
return trace;
146+
}
147+
throw StateError('the completer did not fail');
148+
}
149+
150+
test('is cut to the innermost $maxCallSiteFrames lines', () async {
151+
final deep = _stackFromDepth(maxCallSiteFrames * 3);
152+
final deepLines = lines(deep);
153+
expect(deepLines.indexOf(gap), greaterThan(maxCallSiteFrames));
154+
155+
final trace = await completedWith(deep);
156+
157+
expect(lines(trace), [...deepLines.take(maxCallSiteFrames), gap]);
158+
});
159+
160+
// A stack whose kept lines hold no async gap gets one after them, so
161+
// Sentry's parser reads it as a VM stack without first trying other
162+
// formats. A gap it already keeps needs none: a second one would parse as
163+
// an extra frame.
164+
for (final (gapLine, appended) in [
165+
(null, true),
166+
(30, false),
167+
(maxCallSiteFrames, false),
168+
(maxCallSiteFrames + 1, true),
169+
(maxCallSiteFrames + 40, true),
170+
]) {
171+
test('with its first gap on line $gapLine '
172+
'${appended ? 'gets one after the cut' : 'gets no other'}', () async {
173+
final callSite = _TextStackTrace(
174+
List.generate(
175+
maxCallSiteFrames + 60,
176+
(i) => i + 1 == gapLine ? gap : '#$i frame$i (file.dart:$i)',
177+
),
178+
);
179+
180+
expect(lines(await completedWith(callSite)), [
181+
...callSite.lines.take(maxCallSiteFrames),
182+
if (appended) gap,
183+
]);
184+
});
185+
}
186+
187+
test('is formatted only when read, and only once', () async {
188+
final callSite = _CountingStackTrace(maxCallSiteFrames + 36);
189+
190+
final trace = await completedWith(callSite);
191+
expect(callSite.formats, 0);
192+
193+
trace.toString();
194+
expect(lines(trace), hasLength(maxCallSiteFrames + 1));
195+
expect(callSite.formats, 1);
196+
});
197+
198+
test('is kept whole when it is short', () async {
199+
final shallow = _stackFromDepth(3);
200+
201+
expect((await completedWith(shallow)).toString(), shallow.toString());
202+
});
203+
});
204+
}
205+
206+
StackTrace _stackFromDepth(int depth) =>
207+
depth == 0 ? StackTrace.current : _stackFromDepth(depth - 1);
208+
209+
final class _CountingStackTrace implements StackTrace {
210+
_CountingStackTrace(this._lines);
211+
212+
final int _lines;
213+
int formats = 0;
214+
215+
@override
216+
String toString() {
217+
formats++;
218+
return List.generate(
219+
_lines,
220+
(i) => '#$i frame$i (file.dart:$i)',
221+
).join('\n');
222+
}
223+
}
224+
225+
final class _TextStackTrace implements StackTrace {
226+
_TextStackTrace(this.lines);
227+
228+
final List<String> lines;
229+
230+
@override
231+
String toString() => '${lines.join('\n')}\n';
133232
}

0 commit comments

Comments
 (0)