@@ -116,6 +116,13 @@ public function withTransaction(callable $callback): mixed
116116 // and we want to throw the original exception.
117117 } finally {
118118 // Ensure state is cleaned up even if rollback fails
119+ if ($ this ->session ) {
120+ try {
121+ $ this ->client ->endSessions ([$ this ->session ]);
122+ } catch (\Throwable $ endSessionError ) {
123+ // Ignore errors when ending session during error cleanup
124+ }
125+ }
119126 $ this ->inTransaction = 0 ;
120127 $ this ->session = null ;
121128 }
@@ -170,6 +177,9 @@ public function commitTransaction(): bool
170177 // This is not necessarily a failure, just return success since the transaction was already terminated.
171178 $ e = $ this ->processException ($ e );
172179 if ($ e instanceof TransactionException) {
180+ if ($ this ->session ) {
181+ $ this ->client ->endSessions ([$ this ->session ]);
182+ }
173183 $ this ->session = null ;
174184 $ this ->inTransaction = 0 ; // Reset counter when transaction is already terminated
175185 return true ;
@@ -178,6 +188,9 @@ public function commitTransaction(): bool
178188 } catch (\Throwable $ e ) {
179189 throw new DatabaseException ($ e ->getMessage (), $ e ->getCode (), $ e );
180190 } finally {
191+ if ($ this ->session ) {
192+ $ this ->client ->endSessions ([$ this ->session ]);
193+ }
181194 $ this ->session = null ;
182195 }
183196
@@ -186,6 +199,13 @@ public function commitTransaction(): bool
186199 return true ;
187200 } catch (\Throwable $ e ) {
188201 // Ensure cleanup on any failure
202+ if ($ this ->session ) {
203+ try {
204+ $ this ->client ->endSessions ([$ this ->session ]);
205+ } catch (\Throwable $ endSessionError ) {
206+ // Ignore errors when ending session during error cleanup
207+ }
208+ }
189209 $ this ->session = null ;
190210 $ this ->inTransaction = 0 ;
191211 throw new DatabaseException ('Failed to commit transaction: ' . $ e ->getMessage (), $ e ->getCode (), $ e );
@@ -214,13 +234,23 @@ public function rollbackTransaction(): bool
214234 } catch (\Throwable $ e ) {
215235 throw new DatabaseException ($ e ->getMessage (), $ e ->getCode (), $ e );
216236 } finally {
237+ if ($ this ->session ) {
238+ $ this ->client ->endSessions ([$ this ->session ]);
239+ }
217240 $ this ->session = null ;
218241 }
219242
220243 return true ;
221244 }
222245 return true ;
223246 } catch (\Throwable $ e ) {
247+ if ($ this ->session ) {
248+ try {
249+ $ this ->client ->endSessions ([$ this ->session ]);
250+ } catch (\Throwable $ endSessionError ) {
251+ // Ignore errors when ending session during error cleanup
252+ }
253+ }
224254 $ this ->session = null ;
225255 $ this ->inTransaction = 0 ;
226256 throw new DatabaseException ('Failed to rollback transaction: ' . $ e ->getMessage (), $ e ->getCode (), $ e );
0 commit comments