Skip to content

Commit 319b145

Browse files
authored
fix(kernel): evict invalid sessions and reject reuse (#595)
SEA reports unusable sessions as either `404 Session does not exist` or `400 Invalid SessionHandle`. Recognize both while preserving unrelated `NotFound` and `InvalidArgument` errors. Return the original error for the request that discovers the dead session to prevent automatic replay. Reject later execution on an invalid session with `ErrBadConn` before calling the kernel, so pinned `*sql.Conn` instances are retired too. Validation: full pure-Go and kernel-tagged test suites pass. Regression tests use a local SEA endpoint to verify both response shapes, no replay of the failed statement, and no additional statement requests from pinned connections. Standard lint and tagged lint for changed code pass; two pre-existing unchecked `r.Close()` calls remain in `rows.go`.
2 parents 63f1603 + 1ad0563 commit 319b145

6 files changed

Lines changed: 229 additions & 40 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
- **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475).
88
- **Behavior change:** Without direct results, `ArrowIPCStreamIterator.SchemaBytes()` and `ArrowBatchIterator.Schema()` now retrieve result metadata without fetching data and return the result schema, including for empty results, and can return request or schema-conversion errors. Schemas inferred from Thrift metadata may differ from CloudFetch file schemas when server ArrowSchema is absent (databricks/databricks-sql-go#312).
9+
- Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement.
910

1011
## v2.0.0 (2026-11-23)
1112

‎internal/backend/kernel/backend.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ import (
7474

7575
dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors"
7676
"github.com/databricks/databricks-sql-go/v2/internal/backend"
77+
dbsqlerrint "github.com/databricks/databricks-sql-go/v2/internal/errors"
7778
)
7879

7980
// kernelSessionSeq is a process-wide monotonic counter for kernel session ids.
@@ -894,7 +895,7 @@ func (k *KernelBackend) markSessionDead() { k.valid = false }
894895
// the KernelError before passing it here.
895896
func (k *KernelBackend) evictIfSessionFatal(err error) {
896897
var ke *KernelError
897-
if errors.As(err, &ke) && isSessionFatal(ke.Code) {
898+
if errors.As(err, &ke) && isSessionFatal(ke) {
898899
k.markSessionDead()
899900
}
900901
}
@@ -908,6 +909,11 @@ func (k *KernelBackend) SessionID() string { return k.sessionID }
908909
// parameters (req.Params) are bound onto the statement in execute (see
909910
// bindParams).
910911
func (k *KernelBackend) Execute(ctx context.Context, req backend.ExecRequest) (backend.Operation, error) {
912+
if !k.valid {
913+
// Pinned sql.Conn instances bypass pool validation. Nothing has been sent,
914+
// so ErrBadConn can safely retire the connection before this request.
915+
return &kernelOp{}, dbsqlerrint.NewBadConnectionError(errors.New("kernel: session is no longer valid"))
916+
}
911917
// Staging (Unity Catalog volume PUT/GET/REMOVE) needs a local file transfer the
912918
// kernel path can't perform, and the kernel C ABI surfaces no IsStagingOperation
913919
// signal to drive conn.execStagingOperation. Reject it here rather than let

‎internal/backend/kernel/errors_classify.go‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package kernel
33
import (
44
"errors"
55
"fmt"
6+
"strings"
67

78
dbsqlerrint "github.com/databricks/databricks-sql-go/v2/internal/errors"
89
)
@@ -129,17 +130,17 @@ func isBadConnection(code int) bool {
129130
}
130131
}
131132

132-
// isSessionFatal reports whether a status code means the server-side session is no
133-
// longer usable, so the conn must be evicted from the pool rather than reused for
134-
// the next query. Broader than isBadConnection: it also covers Unauthenticated (an
135-
// expired/revoked token kills the session) — but unlike isBadConnection it is NOT
136-
// used to produce driver.ErrBadConn on the statement path, so eviction happens
137-
// without database/sql replaying the statement (see toStatementError + the
138-
// KernelBackend.markSessionDead call sites).
139-
func isSessionFatal(code int) bool {
140-
switch code {
133+
// isSessionFatal reports whether the connection must be evicted. Missing or
134+
// invalid session handles are fatal; other missing resources or invalid
135+
// arguments leave the session usable.
136+
func isSessionFatal(ke *KernelError) bool {
137+
switch ke.Code {
141138
case statusUnauthenticated, statusUnavailable, statusNetworkError:
142139
return true
140+
case statusNotFound:
141+
return strings.Contains(strings.ToLower(ke.Message), "session does not exist")
142+
case statusInvalidArgument:
143+
return strings.Contains(strings.ToLower(ke.Message), "invalid sessionhandle")
143144
default:
144145
return false
145146
}

‎internal/backend/kernel/errors_classify_test.go‎

Lines changed: 83 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,18 +39,98 @@ func TestIsBadConnection(t *testing.T) {
3939
func TestIsSessionFatal(t *testing.T) {
4040
fatal := []int{statusUnauthenticated, statusUnavailable, statusNetworkError}
4141
for _, code := range fatal {
42-
if !isSessionFatal(code) {
42+
if !isSessionFatal(&KernelError{Code: code}) {
4343
t.Errorf("code %d should be session-fatal", code)
4444
}
4545
}
46-
notFatal := []int{statusInvalidArgument, statusSqlError, statusTimeout}
46+
notFatal := []int{statusInvalidArgument, statusSqlError, statusTimeout, statusNotFound}
4747
for _, code := range notFatal {
48-
if isSessionFatal(code) {
48+
if isSessionFatal(&KernelError{Code: code}) {
4949
t.Errorf("code %d should not be session-fatal", code)
5050
}
5151
}
5252
}
5353

54+
func expiredSessionError() *KernelError {
55+
return &KernelError{
56+
Code: statusNotFound,
57+
Message: "HTTP 404: Session does not exist: test-session; error_code=NOT_FOUND",
58+
HTTPStatus: 404,
59+
}
60+
}
61+
62+
func invalidSessionHandleError() *KernelError {
63+
return &KernelError{
64+
Code: statusInvalidArgument,
65+
Message: "HTTP 400: Invalid SessionHandle: test-session; error_code=BAD_REQUEST",
66+
HTTPStatus: 400,
67+
}
68+
}
69+
70+
func TestIsSessionFatalInvalidSessionHandle(t *testing.T) {
71+
cases := []struct {
72+
name string
73+
err *KernelError
74+
want bool
75+
}{
76+
{"invalid session handle", invalidSessionHandleError(), true},
77+
{"case insensitive", &KernelError{Code: statusInvalidArgument, Message: "HTTP 400: invalid sessionhandle: test-session"}, true},
78+
{"invalid argument", &KernelError{Code: statusInvalidArgument, Message: "invalid parameter value"}, false},
79+
{"no detail", &KernelError{Code: statusInvalidArgument}, false},
80+
{"SQL error echoes message", &KernelError{Code: statusSqlError, Message: "Invalid SessionHandle"}, false},
81+
}
82+
for _, tc := range cases {
83+
t.Run(tc.name, func(t *testing.T) {
84+
if got := isSessionFatal(tc.err); got != tc.want {
85+
t.Errorf("isSessionFatal(%v) = %v, want %v", tc.err, got, tc.want)
86+
}
87+
})
88+
}
89+
}
90+
91+
func TestIsSessionFatalNotFound(t *testing.T) {
92+
cases := []struct {
93+
name string
94+
err *KernelError
95+
want bool
96+
}{
97+
{"expired session", expiredSessionError(), true},
98+
{"case insensitive", &KernelError{Code: statusNotFound, Message: "HTTP 404: session does not exist: test-session"}, true},
99+
{"missing statement", &KernelError{Code: statusNotFound, Message: "HTTP 404: Statement does not exist: test-statement; error_code=NOT_FOUND"}, false},
100+
{"missing table", &KernelError{Code: statusNotFound, Message: "[TABLE_OR_VIEW_NOT_FOUND] The table or view cannot be found.", SQLState: "42P01"}, false},
101+
{"missing volume path", &KernelError{Code: statusNotFound, Message: "volume path does not exist"}, false},
102+
{"no detail", &KernelError{Code: statusNotFound}, false},
103+
{"SQL error echoes message", &KernelError{Code: statusSqlError, Message: "Session does not exist"}, false},
104+
}
105+
for _, tc := range cases {
106+
t.Run(tc.name, func(t *testing.T) {
107+
if got := isSessionFatal(tc.err); got != tc.want {
108+
t.Errorf("isSessionFatal(%v) = %v, want %v", tc.err, got, tc.want)
109+
}
110+
})
111+
}
112+
}
113+
114+
func TestExpiredSessionDoesNotTriggerReplay(t *testing.T) {
115+
for _, ke := range []*KernelError{expiredSessionError(), invalidSessionHandleError()} {
116+
t.Run(fmt.Sprintf("status=%d", ke.HTTPStatus), func(t *testing.T) {
117+
for name, err := range map[string]error{
118+
"statement": toStatementError(ke),
119+
"connection": toConnError(ke),
120+
} {
121+
t.Run(name, func(t *testing.T) {
122+
if err != ke {
123+
t.Errorf("got %v, want the original kernel error", err)
124+
}
125+
if errors.Is(err, driver.ErrBadConn) {
126+
t.Error("an expired-session error must not trigger automatic replay")
127+
}
128+
})
129+
}
130+
})
131+
}
132+
}
133+
54134
// isUserFault picks the log level for a kernel-call failure: user/query faults
55135
// (bad SQL, bad argument) log at Debug so they don't inflate the WARN rate;
56136
// infra codes stay at Warn.

‎internal/backend/kernel/kernel_test.go‎

Lines changed: 48 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"database/sql/driver"
99
"encoding/json"
1010
"errors"
11+
"fmt"
1112
"os"
1213
"strings"
1314
"sync"
@@ -476,39 +477,59 @@ func TestEvictIfSessionFatal(t *testing.T) {
476477
// valid tracks the session-dead flag SessionValid() gates on; the opaque
477478
// session pointer is orthogonal here (can't construct the incomplete C type),
478479
// so assert on k.valid directly.
479-
k := &KernelBackend{valid: true}
480-
481-
// Non-fatal (e.g. a SQL error) leaves the session valid.
482-
k.evictIfSessionFatal(&KernelError{Code: statusSqlError})
483-
if !k.valid {
484-
t.Error("a SQL error must not evict the session")
480+
cases := []struct {
481+
name string
482+
err error
483+
wantValid bool
484+
}{
485+
{"nil", nil, true},
486+
{"plain error", errors.New("Session does not exist"), true},
487+
{"SQL error", &KernelError{Code: statusSqlError}, true},
488+
{"unavailable", &KernelError{Code: statusUnavailable}, false},
489+
{"expired session", expiredSessionError(), false},
490+
{"wrapped expired session", fmt.Errorf("execute: %w", expiredSessionError()), false},
491+
{"invalid session handle", invalidSessionHandleError(), false},
492+
{"wrapped invalid session handle", fmt.Errorf("execute: %w", invalidSessionHandleError()), false},
493+
{"invalid argument", &KernelError{Code: statusInvalidArgument, Message: "invalid parameter value"}, true},
494+
{"missing statement", &KernelError{Code: statusNotFound, Message: "Statement does not exist"}, true},
495+
{"missing table", &KernelError{Code: statusNotFound, Message: "Table does not exist"}, true},
496+
}
497+
for _, tc := range cases {
498+
t.Run(tc.name, func(t *testing.T) {
499+
k := &KernelBackend{valid: true}
500+
k.evictIfSessionFatal(tc.err)
501+
if k.valid != tc.wantValid {
502+
t.Errorf("valid = %v, want %v", k.valid, tc.wantValid)
503+
}
504+
if err := toStatementError(tc.err); err != tc.err || errors.Is(err, driver.ErrBadConn) {
505+
t.Errorf("statement error = %v, want the original error without ErrBadConn", err)
506+
}
507+
})
485508
}
509+
}
486510

487-
// A session-fatal error marks the session dead, and the surfaced statement-path
488-
// error is NOT driver.ErrBadConn (so database/sql won't re-run the statement).
489-
fatal := &KernelError{Code: statusUnavailable, Message: "session gone"}
490-
k.evictIfSessionFatal(fatal)
491-
if k.valid {
492-
t.Error("a session-fatal error must evict the session (valid=false)")
511+
func TestExecuteRejectsDeadSession(t *testing.T) {
512+
k := &KernelBackend{valid: true}
513+
k.markSessionDead()
514+
op, err := k.Execute(context.Background(), backend.ExecRequest{Query: "SELECT 1"})
515+
if !errors.Is(err, driver.ErrBadConn) {
516+
t.Fatalf("Execute error = %v, want ErrBadConn before submission", err)
493517
}
494-
if errors.Is(toStatementError(fatal), driver.ErrBadConn) {
495-
t.Error("the statement-path error must not be driver.ErrBadConn (no replay)")
518+
if op == nil {
519+
t.Fatal("Execute must return a non-nil Operation per the Backend contract")
520+
}
521+
if op.StatementID() != "" {
522+
t.Error("a rejected request must not have a statement ID")
523+
}
524+
if closed, closeErr := op.Close(context.Background()); closed || closeErr != nil {
525+
t.Errorf("Close = (%v, %v), want (false, nil) for an unsubmitted operation", closed, closeErr)
496526
}
497527
}
498528

499-
// Bound parameters are rejected up front by Execute with a clear error, before
500-
// any session/C work — so this runs on a zero-value backend. The returned
501-
// Operation must be non-nil (Backend contract) and its Close must report
502-
// closed=false, since no server statement was ever created (a phantom
503-
// CLOSE_STATEMENT would otherwise be recorded for it).
504-
// When Execute fails before it acquires a statement handle (here: a nil session
505-
// makes new_statement fail), it must still honor the Backend contract — a non-nil,
506-
// handle-less Operation that Closes as a no-op (closed=false, no CLOSE_STATEMENT)
507-
// and reports zero AffectedRows. (A nil-session unit test can't reach the bind
508-
// path: the param mapping is unit-tested hermetically in TestParamBindArg, and
509-
// exercised live end-to-end in TestKernelParamsVsThrift.)
529+
// Failure before allocating a statement handle must still return an operation
530+
// whose Close is a no-op, so callers cannot record a phantom close RPC.
510531
func TestExecuteHandleLessOpContract(t *testing.T) {
511-
k := &KernelBackend{} // nil session → new_statement fails
532+
k := &KernelBackend{valid: true} // nil session → new_statement fails
512533
op, err := k.Execute(context.Background(), backend.ExecRequest{
513534
Query: "SELECT ?",
514535
Params: []backend.Param{{Name: "x", Type: "STRING", Value: strPtr("v")}},
@@ -536,7 +557,7 @@ func TestExecuteHandleLessOpContract(t *testing.T) {
536557
// refactor that dropped or reordered the check would silently reopen the
537558
// silent-no-op data-loss path. Mirrors TestExecuteRejectsParams.
538559
func TestExecuteRejectsStaging(t *testing.T) {
539-
k := &KernelBackend{}
560+
k := &KernelBackend{valid: true}
540561
op, err := k.Execute(context.Background(), backend.ExecRequest{
541562
Query: "PUT '/tmp/f' INTO '/Volumes/main/s/e/f.csv'",
542563
})

‎kernel_closed_conn_test.go‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package dbsql
55
import (
66
"context"
77
"crypto/tls"
8+
"database/sql"
89
"database/sql/driver"
910
"io"
1011
"net"
@@ -91,3 +92,82 @@ func TestKernelClosedConnRejectsStatementsWithoutRequests(t *testing.T) {
9192
require.NoError(t, b.Close())
9293
assert.Equal(t, int32(0), statements.Load())
9394
}
95+
96+
func TestKernelDeadSessionRejectsPinnedConnWithoutRequests(t *testing.T) {
97+
cases := []struct {
98+
name string
99+
status int
100+
body string
101+
message string
102+
}{
103+
{"timed out session", http.StatusBadRequest, `{"error_code":"BAD_REQUEST","message":"Invalid SessionHandle: test-session"}`, "Invalid SessionHandle"},
104+
{"missing session", http.StatusNotFound, `{"error_code":"NOT_FOUND","message":"Session does not exist: test-session"}`, "Session does not exist"},
105+
}
106+
for _, tc := range cases {
107+
for _, nextCall := range []string{"exec", "query"} {
108+
t.Run(tc.name+"/"+nextCall, func(t *testing.T) {
109+
ca, caKey, caPEM := makeMTLSTestCA(t)
110+
serverCert := makeMTLSTestLeaf(t, ca, caKey, "127.0.0.1", net.ParseIP("127.0.0.1"))
111+
var statements atomic.Int32
112+
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113+
path := strings.TrimSuffix(r.URL.Path, "/")
114+
w.Header().Set("Content-Type", "application/json")
115+
switch {
116+
case r.Method == http.MethodPost && strings.HasSuffix(path, "/sessions"):
117+
_, _ = io.WriteString(w, `{"session_id":"test-session"}`)
118+
case r.Method == http.MethodDelete && strings.HasSuffix(path, "/sessions/test-session"):
119+
_, _ = io.WriteString(w, `{}`)
120+
case strings.Contains(path, "/statements"):
121+
statements.Add(1)
122+
w.WriteHeader(tc.status)
123+
_, _ = io.WriteString(w, tc.body)
124+
default:
125+
http.NotFound(w, r)
126+
}
127+
}))
128+
srv.TLS = &tls.Config{Certificates: []tls.Certificate{serverCert.tlsCert}, MinVersion: tls.VersionTLS12}
129+
srv.StartTLS()
130+
t.Cleanup(srv.Close)
131+
132+
connector, err := NewConnector(
133+
WithServerHostname(srv.Listener.Addr().String()),
134+
WithHTTPPath("/sql/1.0/warehouses/hermetic"),
135+
WithAccessToken("dapi-hermetic-placeholder"),
136+
WithUseKernel(true),
137+
WithRetries(-1, 0, 0),
138+
WithKernelTrustedCerts(caPEM),
139+
)
140+
require.NoError(t, err)
141+
db := sql.OpenDB(connector)
142+
t.Cleanup(func() { _ = db.Close() })
143+
ctx := context.Background()
144+
pinned, err := db.Conn(ctx)
145+
require.NoError(t, err)
146+
t.Cleanup(func() { _ = pinned.Close() })
147+
148+
_, err = pinned.ExecContext(ctx, "UPDATE test SET value = value + 1")
149+
require.ErrorContains(t, err, tc.message)
150+
require.NotErrorIs(t, err, driver.ErrBadConn)
151+
require.Equal(t, int32(1), statements.Load(), "the failed statement must not be replayed")
152+
require.NoError(t, pinned.Raw(func(dc any) error {
153+
require.False(t, dc.(driver.Validator).IsValid())
154+
return nil
155+
}))
156+
157+
if nextCall == "exec" {
158+
_, err = pinned.ExecContext(ctx, "SELECT 1")
159+
} else {
160+
var rows *sql.Rows
161+
rows, err = pinned.QueryContext(ctx, "SELECT 1")
162+
if rows != nil {
163+
_ = rows.Close()
164+
}
165+
}
166+
require.ErrorIs(t, err, driver.ErrBadConn)
167+
require.Equal(t, int32(1), statements.Load(), "the invalid connection must reject requests locally")
168+
_, err = pinned.ExecContext(ctx, "SELECT 1")
169+
require.ErrorIs(t, err, sql.ErrConnDone)
170+
})
171+
}
172+
}
173+
}

0 commit comments

Comments
 (0)