@@ -126,11 +126,13 @@ public class SessionImpl implements Session, VRpcSessionApi {
126126
127127 private Instant nextHeartbeat ;
128128
129- // Handle for the in-flight heartbeat tick (one outstanding at a time). Set under lock when the
130- // session enters READY (handleOpenSessionResponse) and again from checkHeartbeat to chain the
131- // next tick. Cancelled under lock from updateState when the session transitions past READY.
132- @ Nullable
133- private BigtableTimer .Timeout heartbeatTimeout ;
129+ // Handle for the in-flight heartbeat tick (one outstanding at a time). Cancelled on terminal
130+ // transitions so the wheel doesn't carry a no-op entry until the next fire.
131+ @ Nullable private BigtableTimer .Timeout heartbeatTimeout ;
132+
133+ // Set by the global SyncContext handler when an uncaught exception triggers an abort. Read on
134+ // re-entry to break out instead of looping. Only accessed inside sessionSyncContext.
135+ private boolean isAborting = false ;
134136
135137 public SessionImpl (
136138 Metrics metrics ,
@@ -156,14 +158,77 @@ public SessionImpl(
156158 this .debugTagTracer = metrics .getDebugTagTracer ();
157159 this .nextHeartbeat = clock .instant ().plus (FUTURE_TIME );
158160 this .openParamsUpdated = false ;
161+ // On uncaught exception, drive the session through a clean terminal-close path so the pool
162+ // and the in-flight vRpc are always notified. notifyTerminalClose has local guards, and
163+ // isAborting prevents recursion if the abort path itself throws.
159164 this .sessionSyncContext =
160- new SynchronizationContext (
161- (thread , e ) ->
162- logger .log (
163- Level .WARNING ,
164- String .format (
165- "Uncaught exception in session SyncContext for %s" , info .getLogName ()),
166- e ));
165+ new SynchronizationContext ((thread , e ) -> abortFromUncaughtException (e ));
166+ }
167+
168+ private void abortFromUncaughtException (Throwable e ) {
169+ if (isAborting ) {
170+ logger .log (
171+ Level .WARNING ,
172+ String .format (
173+ "Session error: %s Secondary uncaught exception during abort, ignoring" ,
174+ info .getLogName ()),
175+ e );
176+ return ;
177+ }
178+ isAborting = true ;
179+
180+ logger .log (
181+ Level .SEVERE ,
182+ String .format (
183+ "Session error: %s Uncaught exception in session SyncContext in state %s, PeerInfo:"
184+ + " %s — aborting session" ,
185+ info .getLogName (), state , formatPeerInfo (safeGetPeerInfo ())),
186+ e );
187+
188+ if (state == SessionState .CLOSED ) {
189+ return ;
190+ }
191+
192+ // Always overwrite closeReason: the abort is what actually happened, not whatever clean close
193+ // we may have been attempting. Fold the prior reason into the description for forensics so
194+ // downstream metrics (which bucket by reason) attribute this to ERROR rather than the
195+ // interrupted close.
196+ String prevDesc =
197+ (closeReason != null )
198+ ? " (was closing for: "
199+ + closeReason .getReason ()
200+ + " — "
201+ + closeReason .getDescription ()
202+ + ")"
203+ : "" ;
204+ closeReason =
205+ CloseSessionRequest .newBuilder ()
206+ .setReason (CloseSessionReason .CLOSE_SESSION_REASON_ERROR )
207+ .setDescription ("Uncaught exception in session SyncContext: " + e + prevDesc )
208+ .build ();
209+
210+ VRpcImpl <?, ?, ?> localRpc = currentRpc ;
211+ currentRpc = null ;
212+ SessionState prevState = state ;
213+ updateState (SessionState .CLOSED );
214+
215+ // Defensively tell the transport we're done. Safe on un-started streams via the try/catch.
216+ try {
217+ stream .forceClose ("Session aborted due to uncaught exception" , e );
218+ } catch (Throwable t ) {
219+ logger .log (
220+ Level .WARNING ,
221+ String .format (
222+ "Session error: %s Exception while force-closing stream during abort" ,
223+ info .getLogName ()),
224+ t );
225+ }
226+
227+ notifyTerminalClose (
228+ Status .INTERNAL .withDescription ("Session aborted" ).withCause (e ),
229+ new Metadata (),
230+ localRpc ,
231+ prevState );
167232 }
168233
169234 @ Override
@@ -681,13 +746,45 @@ private void dispatchStreamClosed(Status status, Metadata trailers) {
681746 }
682747
683748 VRpcImpl <?, ?, ?> localVRpc = currentRpc ;
684- PeerInfo localPeerInfo = stream .getPeerInfo ();
685749 currentRpc = null ;
686750 updateState (SessionState .CLOSED );
687751
688- if (localVRpc != null ) {
752+ notifyTerminalClose (status , trailers , localVRpc , prevState );
753+ }
754+
755+ /**
756+ * Fan out terminal notifications to the in-flight vRpc, tracer, and session listener with local
757+ * guards so a throw in one notification does not suppress the others.
758+ *
759+ * <p>Caller contract: must have already transitioned to {@link SessionState#CLOSED} and captured
760+ * and cleared {@code currentRpc}. Callers should also set {@code closeReason}; if missing we
761+ * synthesize a fallback here rather than throw, since throwing from this fan-out aborts the
762+ * remaining notifications and (because the state is already CLOSED) defeats the
763+ * sessionSyncContext uncaught handler's cleanup.
764+ */
765+ private void notifyTerminalClose (
766+ Status status ,
767+ Metadata trailers ,
768+ @ Nullable VRpcImpl <?, ?, ?> localRpc ,
769+ SessionState prevState ) {
770+ // Should never happen — matches the synthesizer in startGracefulClose.
771+ if (closeReason == null ) {
772+ debugTagTracer .record (TelemetryConfiguration .Level .WARN , "session_close_no_reason" );
773+ logger .log (
774+ Level .WARNING ,
775+ String .format (
776+ "%s notifyTerminalClose reached without a closeReason; status=%s" ,
777+ info .getLogName (), status ),
778+ new IllegalStateException ("notifyTerminalClose without closeReason" ));
779+ closeReason =
780+ CloseSessionRequest .newBuilder ()
781+ .setReason (CloseSessionReason .CLOSE_SESSION_REASON_ERROR )
782+ .setDescription ("notifyTerminalClose reached without closeReason; status=" + status )
783+ .build ();
784+ }
785+ if (localRpc != null ) {
689786 try {
690- localVRpc .handleSessionClose (VRpcResult .createRemoteTransportError (status , trailers ));
787+ localRpc .handleSessionClose (VRpcResult .createRemoteTransportError (status , trailers ));
691788 } catch (Throwable t ) {
692789 logger .log (
693790 Level .WARNING ,
@@ -697,10 +794,44 @@ private void dispatchStreamClosed(Status status, Metadata trailers) {
697794 info .getLogName (), status ),
698795 t );
699796 }
700- tracer .onVRpcClose (Status .UNAVAILABLE .getCode ());
797+ try {
798+ tracer .onVRpcClose (Status .UNAVAILABLE .getCode ());
799+ } catch (Throwable t ) {
800+ logger .log (
801+ Level .WARNING ,
802+ String .format (
803+ "Session error: %s Unhandled exception in tracer.onVRpcClose" , info .getLogName ()),
804+ t );
805+ }
806+ }
807+ try {
808+ tracer .onClose (safeGetPeerInfo (), closeReason .getReason (), status );
809+ } catch (Throwable t ) {
810+ logger .log (
811+ Level .WARNING ,
812+ String .format ("Session error: %s Unhandled exception in tracer.onClose" , info .getLogName ()),
813+ t );
814+ }
815+ if (sessionListener != null ) {
816+ try {
817+ sessionListener .onClose (prevState , status , trailers );
818+ } catch (Throwable t ) {
819+ logger .log (
820+ Level .WARNING ,
821+ String .format (
822+ "Session error: %s Unhandled exception in sessionListener.onClose" ,
823+ info .getLogName ()),
824+ t );
825+ }
826+ }
827+ }
828+
829+ private PeerInfo safeGetPeerInfo () {
830+ try {
831+ return stream .getPeerInfo ();
832+ } catch (Throwable t ) {
833+ return SessionStream .DISCONNECTED_PEER_INFO ;
701834 }
702- tracer .onClose (localPeerInfo , closeReason .getReason (), status );
703- sessionListener .onClose (prevState , status , trailers );
704835 }
705836
706837 private void updateState (SessionState newState ) {
0 commit comments