From e421ac98704ed9d3efe93a0d9e67f51c12f86559 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 25 Nov 2026 15:05:52 -0800 Subject: [PATCH] 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 `` 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 Co-authored-by: studio --- mobile/lib/shared/relay/relay_call_error.dart | 42 +++++++ .../shared/relay/relay_http_query_client.dart | 10 +- mobile/lib/shared/relay/relay_session.dart | 8 +- .../relay/relay_session_subscriptions.dart | 20 ++-- .../lib/shared/relay/signed_event_relay.dart | 14 ++- .../shared/relay/relay_call_error_test.dart | 99 +++++++++++++++++ .../test/shared/relay/relay_session_test.dart | 104 ++++++++++++++++++ 7 files changed, 281 insertions(+), 16 deletions(-) diff --git a/mobile/lib/shared/relay/relay_call_error.dart b/mobile/lib/shared/relay/relay_call_error.dart index a8b48c35c3..f87fa409f2 100644 --- a/mobile/lib/shared/relay/relay_call_error.dart +++ b/mobile/lib/shared/relay/relay_call_error.dart @@ -1,5 +1,47 @@ import 'dart:async'; +/// The most lines of a call site's stack that an error carries, counting +/// `` 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 = ''; + +/// [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 on Completer { + /// 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. diff --git a/mobile/lib/shared/relay/relay_http_query_client.dart b/mobile/lib/shared/relay/relay_http_query_client.dart index 9a58f2f7c0..ee91c18292 100644 --- a/mobile/lib/shared/relay/relay_http_query_client.dart +++ b/mobile/lib/shared/relay/relay_http_query_client.dart @@ -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 diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index d5da7cf379..42db5a41d1 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -328,6 +328,7 @@ class RelaySessionNotifier extends Notifier { 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 { } final subId = _nextSubId('h'); final completer = Completer>(); - final timer = Timer(timeout, () { final sub = _historySubscriptions.remove(subId); if (sub != null && !sub.completer.isCompleted) { @@ -353,6 +353,7 @@ class RelaySessionNotifier extends Notifier { completer: completer, timeout: timer, startedAt: _now(), + callSite: callSite, ); _historySubscriptions[subId] = subscription; @@ -458,6 +459,7 @@ class RelaySessionNotifier extends Notifier { Duration timeout = const Duration(seconds: 8), Future 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 { if ((mayPublish != null && !await mayPublish()) || !connected()) { throw StateError('Event no longer wanted'); } - final completer = Completer(); final timer = Timer(timeout, () { final pending = _pendingEvents.remove(event.id); @@ -483,6 +484,7 @@ class RelaySessionNotifier extends Notifier { completer: completer, timeout: timer, startedAt: _now(), + callSite: callSite, ); _socket?.send(['EVENT', event.toJson()]); @@ -938,7 +940,7 @@ class RelaySessionNotifier extends Notifier { if (closedClass == RelayClosedClass.terminal && !isRelayDeadlineError(message)) { if (readyCompleter != null && !readyCompleter.isCompleted) { - readyCompleter.completeError( + readyCompleter.completeErrorAt( RelayClosedException(RelayCall.subscribe, message), liveSub.callSite, ); diff --git a/mobile/lib/shared/relay/relay_session_subscriptions.dart b/mobile/lib/shared/relay/relay_session_subscriptions.dart index 6d7b73bcd2..ee1613f44e 100644 --- a/mobile/lib/shared/relay/relay_session_subscriptions.dart +++ b/mobile/lib/shared/relay/relay_session_subscriptions.dart @@ -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, }); } diff --git a/mobile/lib/shared/relay/signed_event_relay.dart b/mobile/lib/shared/relay/signed_event_relay.dart index 2a1204dc0d..91f52d558e 100644 --- a/mobile/lib/shared/relay/signed_event_relay.dart +++ b/mobile/lib/shared/relay/signed_event_relay.dart @@ -42,6 +42,9 @@ class SignedEventRelay { FutureOr Function(NostrEvent event)? onSigned, Future 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 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 submitSignedEventOnce({ operation: DiagnosticOperation.relayRejection, ); } - result.completeError(_SignedEventRejection(detail), callSite); + result.completeErrorAt(_SignedEventRejection(detail), callSite); } } }, diff --git a/mobile/test/shared/relay/relay_call_error_test.dart b/mobile/test/shared/relay/relay_call_error_test.dart index 2f7663f818..7d3e171143 100644 --- a/mobile/test/shared/relay/relay_call_error_test.dart +++ b/mobile/test/shared/relay/relay_call_error_test.dart @@ -130,4 +130,103 @@ void main() { expect(error.duration, const Duration(seconds: 8)); }); }); + + group('the stack an escaped error carries', () { + List lines(StackTrace trace) => + trace.toString().trimRight().split('\n'); + const gap = ''; + + Future completedWith(StackTrace callSite) async { + final completer = Completer(); + 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 lines; + + @override + String toString() => '${lines.join('\n')}\n'; } diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index 5a2cfb165e..8427442870 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -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.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.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.delayed(Duration.zero); + final sent = socket.messages.single; + session.debugHandleMessage([ + 'OK', + (sent[1] as Map)['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 _publishFromTheCaller(RelaySessionNotifier session) => session.publish(_event()); +Future> _fetchHistoryFromTheCaller( + RelaySessionNotifier session, +) => session.fetchHistory(_channelFilter); + +Future _submitFromTheCaller(SignedEventRelay relay) => relay.submit( + kind: 1, + content: '', + tags: const [], + onSigned: (_) => Future.delayed(Duration.zero), +); + NostrEvent _event({int createdAt = 20, String id = 'event-1'}) { return NostrEvent( id: id,