You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "ziqiangliang (via GitHub)" <gi...@apache.org> on 2025/06/12 01:33:11 UTC
[I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
ziqiangliang opened a new issue, #7378:
URL: https://github.com/apache/gravitino/issues/7378
### Version
main branch
### Describe what's wrong
### Summary
In `org.apache.gravitino.storage.relational.utils.SessionUtils`, the methods:
* `doWithoutCommitAndFetchResult`
* `doWithoutCommit`
**do not properly close** the underlying `SqlSession`, resulting in JDBC **connection leaks** when used repeatedly in production environments.
### Affected Methods
```java
public static <T, R> R doWithoutCommitAndFetchResult(Class<T> mapperClazz, Function<T, R> func) {
T mapper = SqlSessions.getMapper(mapperClazz); // opens session
return func.apply(mapper); // does NOT close session
}
public static <T> void doWithoutCommit(Class<T> mapperClazz, Consumer<T> consumer) {
T mapper = SqlSessions.getMapper(mapperClazz); // opens session
consumer.accept(mapper); // does NOT close session
}
```
These methods obtain a `SqlSession` via `SqlSessions.getMapper()`, which internally opens a session and stores it in a `ThreadLocal`, but **they never call `commitAndCloseSqlSession()` or `rollbackAndCloseSqlSession()`**, nor do they use try-with-resources.
As a result, **connections are never released back to the pool** if the caller forgets to manually close them—which violates the encapsulation these helper methods are meant to provide.
### Why This Is a Problem
In long-running applications:
* Connections accumulate in the pool in an active but idle state.
* Eventually, all connections are used up.
* DBCP cannot reclaim them since they’re not marked abandoned.
* Leads to errors like:
```
CommunicationsException: The last packet successfully received from the server was ...
```
### Comparison with `doWithCommit()`
The `doWithCommit` method is correctly implemented:
```java
public static <T> void doWithCommit(Class<T> mapperClazz, Consumer<T> consumer) {
try (SqlSession session = SqlSessions.getSqlSession()) {
try {
T mapper = SqlSessions.getMapper(mapperClazz);
consumer.accept(mapper);
SqlSessions.commitAndCloseSqlSession();
} catch (Throwable t) {
SqlSessions.rollbackAndCloseSqlSession();
throw t;
}
}
}
```
It guarantees session cleanup and avoids leaks.
### Suggested Fix
Update both `doWithoutCommit` and `doWithoutCommitAndFetchResult` to ensure proper resource handling. For example:
```java
public static <T, R> R doWithoutCommitAndFetchResult(Class<T> mapperClazz, Function<T, R> func) {
try (SqlSession session = SqlSessions.getSqlSession()) {
try {
T mapper = SqlSessions.getMapper(mapperClazz);
return func.apply(mapper);
} finally {
SqlSessions.closeSqlSession(); // or use commit/rollback if necessary
}
}
}
```
Or possibly use the same pattern as in `doWithCommit`, depending on your desired transactional guarantees.
### Impact
* Prevents JDBC connection leaks
* Ensures proper lifecycle management of SqlSession
* Restores pool stability under load
### Error message and/or stacktrace
```
### Error querying database. Cause: com.mysql.cj.jdbc.exceptions.CommunicationsException: The last packet successfully received from the server was 37,288,357 milliseconds ago. The last packet sent successfully to the server was 37,288,357 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem
```
### How to reproduce
version: **0.8.1-incubating-r1**
### reproduce way
1. Start the Gravitino service with a JDBC backend and a limited connection pool (e.g., DBCP2).
2. Call the REST API GET `/metalakes/{metalake}/objects/{type}/{fullName}/tags` repeatedly. This triggers `SessionUtils.doWithoutCommitAndFetchResult(...)`.
3. Observe:
Even after stopping all traffic, the connection pool’s **active count remains > 0 indefinitely, indicating leaked sessions**.
4. This can be confirmed by inspecting metrics via DBCP2 or through Arthas/JMX.
### Additional context
_No response_
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "ziqiangliang (via GitHub)" <gi...@apache.org>.
ziqiangliang commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2972160854
> Good catch!!!! Could you raise a PR to resolve the issue?
yes, i will fix it
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades closed issue #7378: [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks
URL: https://github.com/apache/gravitino/issues/7378
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2965321029
Good catch!!!! Could you raise a PR to resolve the issue?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "ziqiangliang (via GitHub)" <gi...@apache.org>.
ziqiangliang commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2975017394
> [@ziqiangliang](https://github.com/ziqiangliang) Hi, thanks for your work, I'm very confused about the format.
>
> public static <T, R> Operation<T, R> callWithoutCommit(
> Class<T> mapperClass, Function<T, R> function) {
> return new Operation<>(mapperClass, function);
> }
> Why is it able to solve the connection leakage problem? When will the connection be closed? Did I miss something?
Hi, great question!
You're right — just looking at `callWithoutCommit(...)` itself, it seems like nothing changes regarding connection management. But the key is: **this method doesn't actually open a connection** or do any DB operation **immediately**.
Instead, it just **wraps the logic into an `Operation` object**, which gets passed later into:
```java
SessionUtils.doMultipleWithCommit(Operation... ops)
```
This `doMultipleWithCommit(...)` method is where:
* The DB connection is opened (inside a try-with-resources block),
* All the `Operation#execute()` calls are run using the same connection,
* And finally, the connection is committed or rolled back and closed properly.
Because the `execute()` method of `Operation` is **package-private**, you can't accidentally run the operation outside of this method. So, compared to the old `doWithoutCommit(...)` style (which would **immediately** get a connection and potentially leave it open if misused), this new design **prevents misuse** and **avoids connection leaks**.
Hope that helps! Let me know if you'd like me to walk through a code example.
---
> So essentially, this API design guides the developer toward the safe usage pattern and makes the wrong usage harder or impossible.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2975730950
I have reviewed your design and have the following points to share.
How do you handle the case if users call `callWithoutCommit` without wrapping it in `doWithCommit`? Currently, it seems that all `callWithoutCommit` are wrapped in `doWithCommit`, though some users may mistakenly use it separately. When will the session be closed if it is used alone?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2975020756
I understand your point. Let me review the design thoroughly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "ziqiangliang (via GitHub)" <gi...@apache.org>.
ziqiangliang commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2973810871
To eliminate connection leak issues, I redesigned the transactional API for composing multiple operations.
The current utility methods like:
```java
/**
* This method is used to perform a database operation without a commit and fetch the result. If
* the operation fails, will throw the RuntimeException.
*/
public static <T, R> R doWithoutCommitAndFetchResult(Class<T> mapperClazz, Function<T, R> func) {
T mapper = SqlSessions.getMapper(mapperClazz);
return func.apply(mapper);
}
/**
* This method is used to perform a database operation without a commit. If the operation fails,
* will throw the RuntimeException.
*/
public static <T> void doWithoutCommit(Class<T> mapperClazz, Consumer<T> consumer) {
T mapper = SqlSessions.getMapper(mapperClazz);
consumer.accept(mapper);
}
/**
* This method is used to perform multiple database operations with a commit. If any of the
* operations fail, the transaction will totally roll back.
*/
public static void doMultipleWithCommit(Runnable... operations) {
try (SqlSession session = SqlSessions.getSqlSession()) {
try {
Arrays.stream(operations).forEach(Runnable::run);
SqlSessions.commitAndCloseSqlSession();
} catch (Exception e) {
SqlSessions.rollbackAndCloseSqlSession();
throw e;
}
}
}
```
allow users to perform operations without committing, relying on external transactional control (e.g., via `doMultipleWithCommit`). However, they can be **misused independently** like this:
```java
// Dangerous usage - no commit or session close guaranteed
SessionUtils.doWithoutCommit(SomeMapper.class, mapper -> mapper.insert(...));
```
which risks leaking database connections and leaving transactions uncommitted.
### ✅ Proposed New API Design
Introduce a structured transactional operation wrapper:
```java
/**
* Creates a database operation with the given mapper and function, to be executed without committing.
*/
public static <T, R> Operation<T, R> callWithoutCommit(
Class<T> mapperClass, Function<T, R> function) {
return new Operation<>(mapperClass, function);
}
/**
* Creates a database operation that performs an action using the given mapper, without returning
* a result or committing the transaction.
*/
public static <T> Operation<T, Void> opWithoutCommit(Class<T> mapperClass, Consumer<T> consumer) {
return new Operation<>(
mapperClass,
mapper -> {
consumer.accept(mapper);
return null;
});
}
/**
* Executes multiple database operations within a single transaction. If all succeed, commits.
* If any fail, rolls back.
*/
public static List<Object> doMultipleWithCommit(Operation<?, ?>... operations) {
try (SqlSession session = SqlSessions.getSqlSession()) {
try {
List<Object> results = new ArrayList<>();
for (Operation<?, ?> op : operations) {
results.add(op.execute());
}
SqlSessions.commitAndCloseSqlSession();
return results;
} catch (Throwable t) {
SqlSessions.rollbackAndCloseSqlSession();
throw t;
}
}
}
/**
* Represents a database operation that can be executed with a given mapper.
*/
public static class Operation<T, R> {
private final Class<T> mapperClass;
private final Function<T, R> function;
private Operation(Class<T> mapperClass, Function<T, R> function) {
this.mapperClass = mapperClass;
this.function = function;
}
R execute() {
T mapper = SqlSessions.getMapper(mapperClass);
return function.apply(mapper);
}
}
```
Example usage:
```java
int[] deleteCount1 = new int[1];
int[] deleteCount2 = new int[1];
List<Object> results = SessionUtils.doMultipleWithCommit(
SessionUtils.opWithoutCommit(ModelVersionMetaMapper.class, mapper ->
deleteCount1[0] = mapper.deleteModelVersionMetasByLegacyTimeline(legacyTimeline, limit)),
SessionUtils.callWithoutCommit(ModelVersionAliasRelMapper.class, mapper ->
deleteCount2[0] = mapper.deleteModelVersionAliasRelsByLegacyTimeline(legacyTimeline, limit))
);
System.out.println("Deleted ModelVersionMeta count: " + deleteCount1[0]);
System.out.println("Deleted ModelVersionAliasRel count: " + deleteCount2[0]);
```
The access modifier of Operation#execute is package-private, so it cannot be called outside of doMultipleWithCommit. This prevents issues like connection leaks and transaction hangs.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "mchades (via GitHub)" <gi...@apache.org>.
mchades commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-3235928050
I'm closing this issue since the fix was already included in PR #8242. Thanks to everyone for the discussion.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2974979190
@ziqiangliang
Hi, thanks for your work, I'm very confused about the format.
```java
public static <T, R> Operation<T, R> callWithoutCommit(
Class<T> mapperClass, Function<T, R> function) {
return new Operation<>(mapperClass, function);
}
```
Why is it able to solve the connection leakage problem? When will the connection be closed? Did I miss something?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Bug report] Missing SqlSession Cleanup in doWithoutCommit* Methods Causes Connection Leaks [gravitino]
Posted by "ziqiangliang (via GitHub)" <gi...@apache.org>.
ziqiangliang commented on issue #7378:
URL: https://github.com/apache/gravitino/issues/7378#issuecomment-2976586901
> I have reviewed your design and have the following points to share.
>
> How do you handle the case if users call `callWithoutCommit` without wrapping it in `doWithCommit`? Currently, it seems that all `callWithoutCommit` are wrapped in `doWithCommit`, though some users may mistakenly use it separately. When will the session be closed if it is used alone?
`callWithoutCommit()` just creates an operation descriptor — it doesn’t actually run anything by itself. The real execution (and connection usage) only happens when the operation is passed into `doMultipleWithCommit()`.
Also, we intentionally made `Operation#execute()` package-private to prevent users from calling it directly outside the transaction framework. This way, we avoid connection leaks and hanging transactions right from the API level.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org