-
Notifications
You must be signed in to change notification settings - Fork 13
fix(csharp): surface closed/expired sessions as a clear, typed error #510
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jadewang-db
wants to merge
1
commit into
main
Choose a base branch
from
fix/csharp-session-expired-typed-error
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| /* | ||
| * Copyright (c) 2025 ADBC Drivers Contributors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| using System; | ||
| using Apache.Arrow.Adbc; | ||
|
|
||
| namespace AdbcDrivers.Databricks | ||
| { | ||
| /// <summary> | ||
| /// Raised when the server-side session backing a connection has been closed or has | ||
| /// expired (e.g. due to an inactivity timeout) and the connection can no longer be used. | ||
| /// | ||
| /// The server reports this as HTTP 400 with a Thrift error message containing | ||
| /// "Invalid SessionHandle". Without this typed exception the condition surfaces as a | ||
| /// generic, misleading "An unexpected error occurred while fetching results / Couldn't | ||
| /// connect to server" error, which makes it impossible for callers to distinguish a | ||
| /// recoverable "reconnect" situation from a genuine network/transport failure. | ||
| /// | ||
| /// Callers that catch this exception should dispose the connection and open a new one. | ||
| /// </summary> | ||
| public class DatabricksSessionExpiredException : DatabricksException | ||
| { | ||
| /// <summary> | ||
| /// Substring present in the server's error message for a closed/expired session. | ||
| /// Both the inactivity-timeout variant ("Invalid SessionHandle: Session [..] is closed") | ||
| /// and the explicitly-closed variant ("Invalid SessionHandle: SessionHandle [..]") | ||
| /// contain this phrase. | ||
| /// </summary> | ||
| internal const string ServerErrorSignature = "Invalid SessionHandle"; | ||
|
|
||
| /// <summary> | ||
| /// Message used when failing fast on a connection already known to have an invalid session. | ||
| /// </summary> | ||
| internal const string FastFailMessage = | ||
| "The Databricks session has expired or was closed by the server and is no longer usable. " + | ||
| "Open a new connection to continue."; | ||
|
|
||
| public DatabricksSessionExpiredException(string message) | ||
| : base(message, AdbcStatusCode.InvalidState) | ||
| { | ||
| } | ||
|
|
||
| public DatabricksSessionExpiredException(string message, Exception innerException) | ||
| : base(message, AdbcStatusCode.InvalidState, innerException) | ||
| { | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Determines whether the given exception (or any exception in its inner / aggregate | ||
| /// chain) represents a closed or expired server-side session. | ||
| /// </summary> | ||
| internal static bool IsSessionExpired(Exception? exception) | ||
| { | ||
| switch (exception) | ||
| { | ||
| case null: | ||
| return false; | ||
| case DatabricksSessionExpiredException: | ||
| return true; | ||
| case AggregateException aggregate: | ||
| foreach (Exception inner in aggregate.InnerExceptions) | ||
| { | ||
| if (IsSessionExpired(inner)) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| if (exception.Message != null && | ||
| exception.Message.IndexOf(ServerErrorSignature, StringComparison.OrdinalIgnoreCase) >= 0) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| return IsSessionExpired(exception.InnerException); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -211,60 +211,118 @@ private void RecordError(StatementTelemetryContext ctx, Exception ex) | |
| CaptureRetryCount(ctx); | ||
| } | ||
|
|
||
| public override QueryResult ExecuteQuery() | ||
| /// <summary> | ||
| /// Tier 2 fast-fail: if the connection's server-side session is already known to be | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tier 2 fast-fails emit no telemetry |
||
| /// closed/expired, throw immediately instead of issuing an RPC that would reuse the | ||
| /// stale handle and return the same opaque error. | ||
| /// </summary> | ||
| private void ThrowIfSessionInvalid() | ||
| { | ||
| if (((DatabricksConnection)Connection).IsSessionInvalid) | ||
| { | ||
| throw new DatabricksSessionExpiredException(DatabricksSessionExpiredException.FastFailMessage); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Tier 1: when an execution failure indicates a closed/expired server-side session, | ||
| /// mark the connection invalid and rethrow as a clear <see cref="DatabricksSessionExpiredException"/>. | ||
| /// Otherwise returns so the caller can rethrow the original exception (preserving its stack). | ||
| /// </summary> | ||
| private void ThrowIfSessionExpired(Exception ex) | ||
| { | ||
| var ctx = IsMetadataCommand | ||
| ? CreateMetadataTelemetryContext() | ||
| : CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Query); | ||
| if (ctx == null) return MaybeWrapComplexTypes(base.ExecuteQuery()); | ||
| if (!DatabricksSessionExpiredException.IsSessionExpired(ex)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| ((DatabricksConnection)Connection).MarkSessionInvalid(); | ||
|
|
||
| // Expose ctx to NewReader so the operation status poller can update PollCount/PollLatencyMs (PECO-2992). | ||
| PendingTelemetryContext = ctx; | ||
| // Already the clean typed exception (e.g. surfaced by a nested statement) — preserve it. | ||
| if (ex is DatabricksSessionExpiredException sessionEx) | ||
| { | ||
| throw sessionEx; | ||
| } | ||
|
|
||
| throw new DatabricksSessionExpiredException( | ||
| "The Databricks session has expired or was closed by the server " + | ||
| "(e.g. due to an inactivity timeout). The connection can no longer be used; " + | ||
| "open a new connection to continue. Server error: " + ex.Message, | ||
| ex); | ||
| } | ||
|
|
||
| public override QueryResult ExecuteQuery() | ||
| { | ||
| ThrowIfSessionInvalid(); | ||
| try | ||
| { | ||
| QueryResult result = base.ExecuteQuery(); | ||
| // Store the UNWRAPPED result for telemetry: EmitTelemetry inspects | ||
| // _lastQueryResult.Stream via `is CloudFetchReader/DatabricksCompositeReader` | ||
| // to read chunk metrics and IsCompressed/ResultFormat. ComplexTypeSerializingStream | ||
| // would mask those types, so keep the real reader here and wrap only on return. | ||
| _lastQueryResult = result; | ||
| RecordSuccess(ctx); | ||
| return MaybeWrapComplexTypes(result); | ||
| var ctx = IsMetadataCommand | ||
| ? CreateMetadataTelemetryContext() | ||
| : CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Query); | ||
| if (ctx == null) return MaybeWrapComplexTypes(base.ExecuteQuery()); | ||
|
|
||
| // Expose ctx to NewReader so the operation status poller can update PollCount/PollLatencyMs (PECO-2992). | ||
| PendingTelemetryContext = ctx; | ||
| try | ||
| { | ||
| QueryResult result = base.ExecuteQuery(); | ||
| // Store the UNWRAPPED result for telemetry: EmitTelemetry inspects | ||
| // _lastQueryResult.Stream via `is CloudFetchReader/DatabricksCompositeReader` | ||
| // to read chunk metrics and IsCompressed/ResultFormat. ComplexTypeSerializingStream | ||
| // would mask those types, so keep the real reader here and wrap only on return. | ||
| _lastQueryResult = result; | ||
| RecordSuccess(ctx); | ||
| return MaybeWrapComplexTypes(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| throw; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| ThrowIfSessionExpired(ex); // Tier 1: reclassify a closed/expired session; else rethrow as-is. | ||
| throw; | ||
| } | ||
| } | ||
|
|
||
| public override async ValueTask<QueryResult> ExecuteQueryAsync() | ||
| { | ||
| var ctx = IsMetadataCommand | ||
| ? CreateMetadataTelemetryContext() | ||
| : CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Query); | ||
| if (ctx == null) return MaybeWrapComplexTypes(await base.ExecuteQueryAsync()); | ||
|
|
||
| // Expose ctx to NewReader so the operation status poller can update PollCount/PollLatencyMs (PECO-2992). | ||
| PendingTelemetryContext = ctx; | ||
| ThrowIfSessionInvalid(); | ||
| try | ||
| { | ||
| QueryResult result = await base.ExecuteQueryAsync(); | ||
| // Store the UNWRAPPED result for telemetry (see ExecuteQuery for rationale): | ||
| // the wrapper would mask CloudFetchReader/DatabricksCompositeReader from EmitTelemetry. | ||
| _lastQueryResult = result; | ||
| RecordSuccess(ctx); | ||
| return MaybeWrapComplexTypes(result); | ||
| var ctx = IsMetadataCommand | ||
| ? CreateMetadataTelemetryContext() | ||
| : CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Query); | ||
| if (ctx == null) return MaybeWrapComplexTypes(await base.ExecuteQueryAsync()); | ||
|
|
||
| // Expose ctx to NewReader so the operation status poller can update PollCount/PollLatencyMs (PECO-2992). | ||
| PendingTelemetryContext = ctx; | ||
| try | ||
| { | ||
| QueryResult result = await base.ExecuteQueryAsync(); | ||
| // Store the UNWRAPPED result for telemetry (see ExecuteQuery for rationale): | ||
| // the wrapper would mask CloudFetchReader/DatabricksCompositeReader from EmitTelemetry. | ||
| _lastQueryResult = result; | ||
| RecordSuccess(ctx); | ||
| return MaybeWrapComplexTypes(result); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| throw; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| ThrowIfSessionExpired(ex); // Tier 1: reclassify a closed/expired session; else rethrow as-is. | ||
| throw; | ||
| } | ||
| } | ||
|
|
@@ -286,44 +344,62 @@ private QueryResult MaybeWrapComplexTypes(QueryResult result) | |
|
|
||
| public override UpdateResult ExecuteUpdate() | ||
| { | ||
| var ctx = CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Update); | ||
| if (ctx == null) return base.ExecuteUpdate(); | ||
|
|
||
| PendingTelemetryContext = ctx; | ||
| ThrowIfSessionInvalid(); | ||
| try | ||
| { | ||
| UpdateResult result = base.ExecuteUpdate(); | ||
| RecordSuccess(ctx); | ||
| return result; | ||
| var ctx = CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Update); | ||
| if (ctx == null) return base.ExecuteUpdate(); | ||
|
|
||
| PendingTelemetryContext = ctx; | ||
| try | ||
| { | ||
| UpdateResult result = base.ExecuteUpdate(); | ||
| RecordSuccess(ctx); | ||
| return result; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| throw; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| ThrowIfSessionExpired(ex); // Tier 1: reclassify a closed/expired session; else rethrow as-is. | ||
| throw; | ||
| } | ||
| } | ||
|
|
||
| public override async Task<UpdateResult> ExecuteUpdateAsync() | ||
| { | ||
| var ctx = CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Update); | ||
| if (ctx == null) return await base.ExecuteUpdateAsync(); | ||
|
|
||
| PendingTelemetryContext = ctx; | ||
| ThrowIfSessionInvalid(); | ||
| try | ||
| { | ||
| UpdateResult result = await base.ExecuteUpdateAsync(); | ||
| RecordSuccess(ctx); | ||
| return result; | ||
| var ctx = CreateTelemetryContext(Telemetry.Proto.Statement.Types.Type.Update); | ||
| if (ctx == null) return await base.ExecuteUpdateAsync(); | ||
|
|
||
| PendingTelemetryContext = ctx; | ||
| try | ||
| { | ||
| UpdateResult result = await base.ExecuteUpdateAsync(); | ||
| RecordSuccess(ctx); | ||
| return result; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| throw; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| RecordError(ctx, ex); | ||
| // Emit telemetry immediately on error (won't reach Dispose) | ||
| EmitTelemetry(ctx); | ||
| PendingTelemetryContext = null; // Clear to avoid double emission | ||
| ThrowIfSessionExpired(ex); // Tier 1: reclassify a closed/expired session; else rethrow as-is. | ||
| throw; | ||
| } | ||
| } | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is there no better way to identify this?