You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "DanielLeens (via GitHub)" <gi...@apache.org> on 2026/04/20 06:55:47 UTC
Re: [PR] [Fix][Connector-V2] Improve connection validation and retry logic on connection errors [seatunnel]
DanielLeens commented on PR #10400:
URL: https://github.com/apache/seatunnel/pull/10400#issuecomment-4278478843
Hi @corgy-w, thanks for the work here. The goal is valuable: JDBC flush failures are painful to diagnose, and connection-loss handling definitely deserves clearer retry/reconnect behavior. I reviewed the latest PR locally from branch `seatunnel-review-10400` against current `upstream/dev`.
# What This PR Fixes
- User pain point: when `JdbcOutputFormat.flush()` calls `executeBatch()` and the database connection has already gone bad, the old code had limited context around retry/reconnect decisions.
- Fix approach: this PR adds root-cause inspection, SQLState `08` detection, explicit connection-validity checks, reconnect logging, bounded backoff, and more tolerant statement closing during reconnect.
- One-line summary: it improves JDBC flush diagnostics and connection-error handling, but the current implementation still cannot safely replay the original batch after reconnect.
# 1. Code Change Review
## 1.1 Core Logic Analysis
- Exact change description:
- `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:122-240` rewrites the flush retry loop.
- `JdbcOutputFormat.java:276-301` changes `updateExecutor(true)` so close failures during reconnect are logged and suppressed while new statements are prepared.
Before:
```java
for (int i = 0; i <= jdbcConnectionConfig.getMaxRetries(); i++) {
try {
attemptFlush();
batchCount = 0;
break;
} catch (SQLException e) {
if (i >= jdbcConnectionConfig.getMaxRetries()) {
throw new JdbcConnectorException(CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, e);
}
if (!connectionProvider.isConnectionValid()) {
updateExecutor(true);
}
Thread.sleep(sleepMs * i);
}
}
```
After:
```java
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
attemptFlush();
batchCount = 0;
return;
} catch (Exception e) {
Throwable root = Throwables.getRootCause(e);
if (!(root instanceof SQLException)) {
throw new JdbcConnectorException(CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, e);
}
SQLException sqlEx = (SQLException) root;
boolean sqlStateConnError = sqlEx.getSQLState() != null && sqlEx.getSQLState().startsWith("08");
boolean connValid = connectionProvider.isConnectionValid();
boolean needReconnect = sqlStateConnError || !connValid;
if (needReconnect) {
updateExecutor(true);
}
Thread.sleep(backoffMs);
}
}
```
- Key findings:
1. The normal JDBC Sink path does hit this PR: both regular and exactly-once writers call `JdbcOutputFormat.writeRecord()` and then `flush()` on batch-size, flush-event, checkpoint, or close paths.
2. The PR covers the exception branch after `JdbcBatchStatementExecutor.executeBatch()`.
3. This is a defensive fix, not a complete reliable retry design, because reconnecting the connection does not automatically replay rows that were already added to the old JDBC `PreparedStatement`.
4. The PR currently conflicts with latest `dev` in the same `flush()` method, so the final merged behavior is not reviewable yet.
- Full execution chain:
```text
Regular JDBC Sink
-> JdbcSinkWriter.write(row)
-> tryOpen()
-> JdbcOutputFormat.writeRecord(row)
-> addToBatch(row)
-> SimpleBatchStatementExecutor.addToBatch(row)
-> converter.toExternal(...)
-> PreparedStatement.addBatch()
-> batchCount++
-> batchCount >= batchSize -> flush()
Exactly-once JDBC Sink
-> JdbcExactlyOnceSinkWriter.write(row)
-> outputFormat.writeRecord(copy)
-> checkpoint / flush event
-> flushData()
-> outputFormat.flush()
Flush exception branch
-> JdbcOutputFormat.flush()
-> attemptFlush()
-> jdbcStatementExecutor.executeBatch()
-> connection lost / SQLState 08 / invalid connection
-> needReconnect = true
-> updateExecutor(true)
-> close old statements
-> connectionProvider.reestablishConnection()
-> jdbcStatementExecutor.prepareStatements(newConnection)
-> next attemptFlush()
-> for non-replayable executors, the new PreparedStatement has no original rows
-> empty batch may succeed
-> batchCount = 0
-> writer/checkpoint treats the batch as successfully flushed
```
## 1.2 Compatibility
Compatibility: partially incompatible until the retry semantics are fixed.
- API/config/defaults: no public API or config change.
- Protocol/serialization: unchanged.
- Historical behavior: the exception path changes. If reconnect turns a failed batch into an empty successful batch, the sink can report success where it should fail and recover from checkpoint.
## 1.3 Performance and Side Effects
Normal successful flush has little overhead. Failure paths now do more root-cause inspection, connection validation, logging, reconnect attempts, and backoff sleeps. The important side effect is semantic, not performance-related: retry happens without a uniform record replay mechanism.
## 1.4 Error Handling and Logging
The logging context is better than before, and I did not see sensitive data leakage. The main issue is false success after reconnect.
Issue 1: reconnect can lose the original batch and then clear `batchCount` after an empty successful retry
- Location: `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:213`
- Description: `updateExecutor(true)` only rebuilds the connection and prepares new statements. It does not re-add rows that were already stored inside the old JDBC `PreparedStatement` batch. For executors like `SimpleBatchStatementExecutor` and `InsertOrUpdateBatchStatementExecutor`, the original rows are not retained in a Java replay buffer. The next retry can execute an empty new statement successfully, and `flush()` then sets `batchCount = 0`.
- Risk: regular JDBC sink can silently drop the current batch. Exactly-once JDBC sink can advance checkpoint/prepare-commit after a flush that did not actually write the records.
- Suggested fix: either fail fast on connection loss during `executeBatch()` and let checkpoint recovery replay, or introduce an explicit replay contract/buffer so only replayable executors can retry after reconnect.
- Severity: high.
Issue 2: the PR conflicts with current `dev` in `JdbcOutputFormat.flush()`
- Location: `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:137`
- Description: GitHub reports `mergeable=false` / `mergeable_state=dirty`, and local `git merge-tree $(git merge-base upstream/dev HEAD) upstream/dev HEAD` shows conflict markers in `JdbcOutputFormat.java`. Current `dev` has `lastFlushTimeMs`, batch-interval helper logic, and close helpers in the same area that this PR rewrites.
- Risk: the current snapshot cannot be merged. A careless conflict resolution could either drop current `dev`'s batch-interval behavior or drop this PR's retry changes.
- Suggested fix: rebase onto latest `dev`, preserve the current batch interval behavior, then re-review the final `flush()` implementation.
- Severity: high.
Issue 3: missing regression tests for connection-loss replay semantics
- Location: `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:122`
- Description: the PR changes a critical sink reliability path but adds no tests for SQLState `08`, invalid connection checks, reconnect success/failure, or replayable vs non-replayable executors.
- Risk: CI can stay green while the sink drops or duplicates data during real database/network failures.
- Suggested fix: add focused fake `JdbcConnectionProvider`/`JdbcBatchStatementExecutor` tests proving that non-replayable executors fail instead of succeeding with an empty batch, and that replayable executors actually replay the original records.
- Severity: medium.
# 2. Code Quality
## 2.1 Style
`git diff --check` is clean. The final style still needs to be rechecked after resolving the current conflict.
## 2.2 Tests
No new unit, integration, or regression tests were added. This is not enough for a data-reliability change in JDBC sink flush/retry logic.
## 2.3 Documentation
No user-facing config changed, so docs are not required unless the final fix intentionally documents retry semantics.
# 3. Architecture
## 3.1 Elegance
This is a defensive patch. The direction is useful, but reliable retry needs an explicit replay/fail-fast model instead of just rebuilding statements.
## 3.2 Maintainability
The logs are better, but `flush()` now owns too many concerns: root-cause parsing, connection validation, reconnect, backoff, and exception wrapping. A replayability contract would make this safer.
## 3.3 Extensibility
The safer extension point is at `JdbcBatchStatementExecutor`: declare whether an executor can replay its batch after reconnect, or keep retry behavior fail-fast by default.
## 3.4 Historical Compatibility
No config migration is required, but the failure semantics are not safely compatible until false-success-after-reconnect is removed.
# 4. Issue Summary
| No. | Issue | Location | Severity |
|---|---|---|---|
| Issue 1 | Reconnect can lose the original batch and then clear `batchCount` after an empty successful retry | `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:213` | High |
| Issue 2 | The PR conflicts with current `dev` in `JdbcOutputFormat.flush()` | `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:137` | High |
| Issue 3 | Missing regression tests for connection-loss replay semantics | `seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java:122` | Medium |
# 5. Merge Conclusion
### Conclusion: not recommended to merge
1. Blocking items:
- Issue 1: retry/reconnect can report flush success without replaying the original batch.
- Issue 2: the PR is currently merge-conflicting with latest `dev`.
2. Suggested non-blocking fixes:
- Issue 3: add focused regression tests while fixing Issue 1.
Overall, the target is worth solving, but this needs a safer retry model. My preferred approach is fail-fast on connection loss during `executeBatch()` unless the executor explicitly supports replaying its buffered records after reconnect.
Local review details:
- Branch: `seatunnel-review-10400`
- Head: `b338f98cecc7dca0becc805477e0a5519fa9973c`
- Merge base: `ed021460f76b570538685af908f358f09a4be9e9`
- Diff scope: 1 file, 109 insertions, 26 deletions
- CI: historical Build / Notify / labeler checks are green, but they do not validate the current conflicting merge result
- I did not run local UT/E2E or database fault injection; the conclusion is based on local source review, the full diff, executor behavior, and call-chain analysis.
--
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@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org