Skip to content

[Fix][Connector-V2] Fix Oracle CDC split generation error when analyze table fails - #12024

Closed
zhang-arvin wants to merge 2 commits into
apache:devfrom
zhang-arvin:fix/oracle-cdc-split-generation-12019
Closed

zhang-arvin wants to merge 2 commits into
apache:devfrom
zhang-arvin:fix/oracle-cdc-split-generation-12019

Conversation

@zhang-arvin

Copy link
Copy Markdown
Contributor

Purpose

Fix Oracle CDC connector fails with 'Generate Splits' error when the analyze table statement times out on Oracle.

Problem

When the Oracle CDC connector runs analyze table ... compute statistics for table to estimate row count for chunk splitting, the analyze statement can fail due to Oracle session timeouts (e.g., No more data to read from socket). This causes the entire split generation to fail with Generate Splits for table XXX error.

Root Cause

In OracleUtils.queryApproximateRowCnt(), the jdbc.execute(analyzeTable) call is not wrapped in a try-catch. When it fails, the SQLException propagates up and causes the split generation to fail.

Fix

Wrap the analyze table execution in a try-catch. When the analyze fails:

  1. Log a warning with the error message
  2. Fall back to using select count(*) to get the row count

This makes the Oracle CDC split generation resilient to Oracle session timeout issues.

Related Issue

Closes #12019

Checklist

  • Code compiles correctly
  • Formatting applied (spotless:apply)
  • Tests added (no logic change to test — this is a defensive error-handling fix)
  • Documentation updated (no user-facing config changes)

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

Thanks for taking this on, @zhang-arvin! This PR targets a real and well-documented problem: in OracleUtils.queryApproximateRowCnt(), the analyze table ... compute statistics for table statement used to refresh Oracle's row-count statistics before chunk splitting is executed without a try-catch. When that statement fails (for example due to an Oracle session/socket timeout), the SQLException propagates all the way up through AbstractJdbcSourceChunkSplitter.splitTableIntoChunks() and generateSplits(), and the whole snapshot phase for that table dies with Generate Splits for table XXX error.

I traced the exact call chain and cross-checked it against the stack trace attached to the linked issue (#12019):

OracleUtils.queryApproximateRowCnt (executes "analyze table ... compute statistics for table")
  -> OracleChunkSplitter.queryApproximateRowCnt
  -> AbstractJdbcSourceChunkSplitter.splitTableIntoChunks (line 167, wraps SQLException as RuntimeException)
  -> AbstractJdbcSourceChunkSplitter.generateSplits (wraps as "Generate Splits for table %s error")

The issue's stack trace shows java.sql.SQLRecoverableException: No more data to read from socket thrown from exactly OracleUtils.queryApproximateRowCnt(OracleUtils.java:105) (the pre-fix jdbc.execute(analyzeTable) line), which matches the PR's root-cause description precisely. So the diagnosis is correct and the fix targets the right call site. USE_SELECT_COUNT/SKIP_ANALYZE both default to false, so this analyze step runs on the normal snapshot path for every Oracle CDC job unless a user has opted out — this is not a rarely-hit edge case, it is the default execution path.

1. Code Change Review

1.1 Core Logic Analysis

The intent (wrap jdbc.execute(analyzeTable) in try-catch, fall back to select count(*) on failure) is sound and is a genuine improvement over letting any analyze table failure kill the whole split-generation step — this also transparently helps a very common real-world case that is arguably more likely than a socket timeout: DB accounts that lack ANALYZE ANY / stats-gathering privileges, where analyze table fails with ORA-01031 today and would now fall back gracefully to a privilege-free select count(*).

However, the change as written does not compile, and this is confirmed by the fork's own CI run, not just by static reading:

OracleUtils.java:[125,40] error: local variables referenced from a lambda expression must be final or effectively final

Root cause: rowCountQuery (seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtils.java) is declared once, then assigned in the else branch (line ~93-96), and now also reassigned again inside the new catch block (line ~112-113):

} catch (SQLException e) {
    ...
    useSelectCount = true;
    rowCountQuery =
            String.format("select count(*) from %s", quoteSchemaAndTable(tableId)); // 2nd assignment
}

Because rowCountQuery is written to twice along this code path, it is no longer effectively final, and the later jdbc.queryAndMap(rowCountQuery, rs -> { ... rowCountQuery ... }) lambda (line 118-128) that captures it fails to compile under javac. This is a hard compile break in connector-cdc-oracle, not a style nit — every CI job that builds this module fails as a direct result (see section 4/5).

Suggested minimal fix: introduce a fresh effectively-final local right before the lambda, e.g.

log.info("row count query: {}", rowCountQuery);
final String finalRowCountQuery = rowCountQuery;
return jdbc.queryAndMap(
        finalRowCountQuery,
        rs -> {
            if (!rs.next()) {
                throw new SQLException(
                        String.format(
                                "No result returned after running query [%s]",
                                finalRowCountQuery));
            }
            return rs.getLong(1);
        });

Also, once that's fixed: the useSelectCount = true; reassignment inside the catch block has no observable effect — useSelectCount is never read again after line 90's if (useSelectCount) check, so this line is dead code. It doesn't hurt correctness, but it's worth removing (or, if it was meant to make behavior/logging clearer, consider logging it instead) to avoid confusing future readers into thinking it changes control flow.

1.2 Compatibility Impact

Fully backward compatible in design: no config option added/removed/renamed, no default value changed, no public API/SPI signature changed, no change to SnapshotSplit serialization or checkpoint/savepoint state. queryApproximateRowCnt's result only feeds an in-memory, generation-time heuristic (chunk count / distribution factor), so this doesn't affect restore compatibility for jobs upgrading across versions. Once the compile error above is fixed, I see no compatibility concerns.

1.3 Performance / Side-Effect Analysis

No cost added to the success path (the try-catch only wraps the existing analyze call). On the failure path, an extra select count(*) full-table scan is issued, which is the correct trade-off for correctness over relying on a stale/possibly-NULL all_tables.NUM_ROWS value (a table that was never analyzed before would have NUM_ROWS IS NULL, and reading a NULL via rs.getLong(1) silently returns 0, which would have been a worse, silent bug than what this PR is fixing — good catch falling back to count(*) here rather than reusing the stale NUM_ROWS query).

One thing worth verifying in a real Oracle environment before merge: the fallback reuses the same jdbc connection that just failed with SQLRecoverableException: No more data to read from socket. If that error genuinely indicates the underlying socket/session is dead (which "no more data to read from socket" at the T4C protocol layer commonly does indicate), the follow-up select count(*) on the same connection may also fail — in which case the net effect for the specific scenario in #12019 would be an unhandled exception one query later (no regression vs. today, since the ultimate outcome is still "Generate Splits" failing, just with an extra WARN logged first), rather than a full fix. This fix unambiguously helps the "analyze without stats privilege" case; whether it fully resolves the "genuinely dead socket" case from #12019 would be good to confirm against a real reproduction, or ask the reporter to confirm.

1.4 Error Handling and Logging

The new log.warn includes the table id and e.getMessage(), which is adequate for diagnosis. Minor suggestion: pass the exception itself (log.warn("... {}", tableId, e)) rather than just e.getMessage(), so the stack trace is preserved for anyone debugging a recurring failure — this doesn't need to block the PR, just a nice-to-have for future troubleshooting.

2. Code Quality Assessment

2.1 Coding Standards

Style (indentation, line wrapping, brace placement) is consistent with the rest of the file and looks Spotless-compliant. The dead useSelectCount = true; write noted in 1.1 is the only real quality nit. Minor DRY observation: String.format("select count(*) from %s", quoteSchemaAndTable(tableId)) is now duplicated (once in the if (useSelectCount) branch, once in the new catch block) — not a big deal for two lines, but a tiny local helper would avoid future drift if the count-query format ever changes.

2.2 Test Coverage and Test Stability

No new test was added (the PR description explicitly says so). This is a genuine gap: this module already has OracleUtilsTest under seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtilsTest.java, and the root pom.xml already provides mockito-junit-jupiter/mockito-inline as project-wide test dependencies, so a unit test mocking JdbcConnection.execute(...) to throw SQLException and asserting the fallback to select count(*) (and the correct final row count) is both feasible and low-cost here. Given this PR is adding a new branch of behavior (not just a comment/doc change), I'd like to see at least one such test before merge — this would also have caught the compile error immediately.

No test files were changed, so the flaky-test-anti-pattern check does not apply here.

2.3 Documentation Updates

No user-facing config/behavior contract changes (no new options, no changed defaults/descriptions), so no docs update is required here — agreed with the PR checklist on this point.

3. Architectural Soundness

3.1 Elegance of the Solution

The overall shape of the fix (catch, warn, fall back to a safe alternative query) is a good, idiomatic pattern for this kind of defensive resiliency improvement, and it stays entirely local to OracleUtils without leaking Oracle-specific concerns into AbstractJdbcSourceChunkSplitter or other connectors — nice and contained. It just needs the compile-correctness fix in 1.1 to actually realize that intent.

3.2 Maintainability

Once the lambda-capture issue is fixed and the dead useSelectCount = true; write is cleaned up, this is easy to read and maintain; the log lines clearly explain why the fallback happened.

3.3 Extensibility

No concerns; this doesn't add new config surface or change any interface, so it doesn't constrain future extension of OracleUtils or the chunk-splitter abstraction.

3.4 Historical-Version Compatibility

No checkpoint/savepoint state, serialization format, or protocol touched by this change, so upgrading an existing Oracle CDC job across this fix carries no restore-compatibility risk. No concerns here beyond the general "must actually compile" requirement below.

4. Issue Summary

# Issue Location (path:line) Severity
1 Compile error: rowCountQuery is reassigned inside the new catch block, so it is no longer effectively final and the jdbc.queryAndMap(...) lambda that captures it fails to compile (javac error confirmed in the fork's own CI run at every affected job) seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtils.java:112-125 Critical
2 useSelectCount = true; inside the catch block is dead code — the variable is never read again after line 90 seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtils.java:111 Low
3 No unit test added for the new fallback branch, even though OracleUtilsTest already exists in this module and Mockito is available project-wide seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtilsTest.java Medium
4 Unverified whether the select count(*) fallback on the same JDBC connection actually succeeds when the original failure is a genuinely dead socket (as opposed to a stats-privilege error) OracleUtils.java:104-114 Low (informational, worth confirming)

5. Merge Recommendation

Conclusion: Not recommended for merge

  1. Blockers — must be fixed

    • Fix the compile error (issue #1): make the value captured by the jdbc.queryAndMap lambda effectively final (e.g. a separate final String finalRowCountQuery = rowCountQuery; right before the call), and verify the module actually builds. All of this PR's own CI failures (unit-test on JDK 8/11 for Windows/Ubuntu, oracle-cdc-connector-it, updated-modules-integration-test-part-1/part-8, doris-connector-it) trace back to this single compile error in connector-cdc-oracle, since a Maven reactor build fails the whole run once one module fails to compile — these are not unrelated/environmental flakes, they are all caused directly by this diff.
    • Add a unit test covering the new fallback path (issue #3).
  2. Recommended fixes — non-blocking

    • Remove the dead useSelectCount = true; write (issue #2), or make it meaningful.
    • Consider logging the exception object (not just e.getMessage()) for better diagnosability.
    • Please confirm (ideally against the reporter's environment, or your own repro) whether the select count(*) fallback actually succeeds after the specific "No more data to read from socket" failure in #12019, since that determines whether this PR fully closes #12019 or mainly helps the (also valid) stats-privilege-failure case.

This is a good, well-targeted fix for a real production issue and I'd love to see it merged once the compile error is resolved — thank you for digging into this and for the very clear root-cause writeup in the PR description, it made this review much faster to verify end-to-end!

…e table fails

When the Oracle CDC connector runs analyze table to compute statistics
for estimating row count, the analyze statement can fail due to Oracle
session timeouts (e.g., 'No more data to read from socket'). This causes
the entire split generation to fail with 'Generate Splits for table XXX'
error.

This fix wraps the analyze table execution in a try-catch and falls back
to using select count(*) when the analyze fails, making the split
generation resilient to Oracle session timeout issues.
@zhang-arvin
zhang-arvin force-pushed the fix/oracle-cdc-split-generation-12019 branch from 2f413e9 to 62623a9 Compare September 16, 2026 08:19

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What Problem Does This PR Solve?

This PR targets a real problem in OracleUtils.queryApproximateRowCnt(): the analyze table ... compute statistics for table statement, used to refresh Oracle's row-count statistics before chunk-splitting, is executed without a try-catch. When it fails (Oracle session timeout, missing ANALYZE ANY privilege, stats-gathering disabled, etc.) the SQLException propagates up through AbstractJdbcSourceChunkSplitter.splitTableIntoChunks()/generateSplits() and kills the whole snapshot phase for that table with Generate Splits for table XXX error (linked issue #12019). The fix wraps the analyze call in try-catch and falls back to select count(*) on failure.

This is a re-review of the current head, 62623a9c (pushed 2026-09-16T08:19:20Z). I reviewed this PR once before at commit 2f413e9b (2026-09-01, state COMMENTED) and flagged one Critical blocker plus three lower-severity items. Comparing the true diff of the current head against a freshly-fetched apache/dev (b37af3a9bf6) — not the diff between the two head SHAs directly, which picks up unrelated intervening dev history — shows the PR is still exactly one file, 11 insertions / 2 deletions, byte-for-byte identical to what I reviewed on 2026-09-01. The only event between rounds was a head_ref_force_pushed (rebase) by the author on 2026-09-16T08:19:23Z with no content change to the flagged method. None of the four issues from round 1 have been addressed, including the Critical compile-blocking one.

1. Code Change Review

1.1 Core Logic Analysis

Current head, OracleUtils.java (seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtils.java), queryApproximateRowCnt():

// before (dev)
log.info("analyze table sql: {}", analyzeTable);
jdbc.execute(analyzeTable);

// after (PR head, lines 100-116)
log.info("analyze table sql: {}", analyzeTable);
try {
    jdbc.execute(analyzeTable);
} catch (SQLException e) {
    log.warn(
            "Failed to analyze table {}, falling back to select count(*). Error: {}",
            tableId,
            e.getMessage());
    useSelectCount = true;
    rowCountQuery =
            String.format("select count(*) from %s", quoteSchemaAndTable(tableId));
}

Directly below, unchanged, the result is consumed by:

log.info("row count query: {}", rowCountQuery);
return jdbc.queryAndMap(
        rowCountQuery,
        rs -> {
            if (!rs.next()) {
                throw new SQLException(
                        String.format(
                                "No result returned after running query [%s]",
                                rowCountQuery));   // <-- captures rowCountQuery
            }
            return rs.getLong(1);
        });

Issue #1 — Critical, unchanged from round 1 — this still does not compile. rowCountQuery (declared String rowCountQuery; with no initializer) is assigned once in the else branch (line ~93-96) and, along that same execution path, assigned again inside the new catch block (line ~112-114). A local variable that receives more than one assignment along a reachable path is not effectively final, so the lambda above — which captures rowCountQuery directly in the error-message format call — fails javac's effectively-final check for lambda captures.

I did not rely on stale CI evidence for this round — the fork's CI (zhang-arvin/seatunnel) for this exact commit was still queued/pending at review time (pushed ~08:19 UTC, checked ~09:2x UTC, 0/75 relevant jobs had executed). Instead I isolated the identical control-flow shape (declare-then-branch-assign-then-catch-reassign into a lambda capture) in a throwaway, unrelated Java file and compiled it with this project's own toolchain, javac 1.8.0_171 (/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk):

Repro.java:28: error: local variables referenced from a lambda expression must be final or effectively final
            return "result for [" + rowCountQuery + "]";
                                    ^
1 error

This is the exact same error class I reported from the fork's CI run in round 1 (OracleUtils.java:[125,40] error: local variables referenced from a lambda expression must be final or effectively final), reproduced from first principles against the current code shape. Since the flagged method is byte-for-byte unchanged between the two rounds, I'm confident this diagnosis still holds and the module will fail to compile the moment the fork's CI actually runs the unit-test / oracle-cdc-connector-it / updated-modules-integration-test-* jobs against this commit.

Minimal fix (unchanged suggestion from round 1): introduce a second, freshly-declared effectively-final local right before the lambda, e.g. final String finalRowCountQuery = rowCountQuery;, and capture that instead.

Aside from the compile break, the intent of the fallback is sound: falling back to select count(*) instead of relying on a possibly-stale/NULL all_tables.NUM_ROWS (which rs.getLong(1) would silently read as 0 for a never-analyzed table) is the right trade-off, and this transparently helps the very common "account lacks ANALYZE ANY / stats-gathering privilege" case in addition to the session-timeout case named in the PR description.

Fallback-boundary check (per this round's specific mandate): the fallback does not risk producing a degenerate 0/negative chunk count or an infinite loop. If the fallback select count(*) itself throws, that SQLException propagates out of jdbc.queryAndMap(...) uncaught (the new catch block only wraps the analyze statement, not the subsequent count query), matching pre-fix behavior exactly — no new silent-zero-row or empty-snapshot path is introduced by this diff, once the compile issue above is fixed.

Over-broad-catch check: the new catch (SQLException e) is narrowly scoped to just the jdbc.execute(analyzeTable) call, not to any of the surrounding split-boundary or checkpoint logic, and it does not swallow the exception — it logs it and degrades to a safe alternative query rather than suppressing failure outright. queryApproximateRowCnt()'s result only feeds an in-memory, generation-time row-count heuristic used to decide chunk count/distribution; it is not part of SnapshotSplit boundary computation itself (that's driven by min/max/sampling queries elsewhere in this file) and not part of checkpoint/savepoint state, so this doesn't risk masking a genuine data-correctness error into a silently-wrong split.

Issue #2 — Low, unchanged from round 1 — dead code. useSelectCount = true; inside the new catch block (line ~111) has no observable effect: useSelectCount is only read once, at the earlier if (useSelectCount) check (line ~90), which has already executed by the time the catch block runs. This line does not change control flow and should be removed (or converted to a log statement) to avoid misleading future readers.

1.2 Compatibility Impact

Unchanged from round 1: no config option added/removed/renamed, no default value changed, no public API/SPI signature changed, no SnapshotSplit serialization or checkpoint/savepoint state touched. queryApproximateRowCnt()'s result only feeds an in-memory, generation-time heuristic, so upgrade/restore compatibility for jobs crossing this version boundary is unaffected. No new concerns this round — contingent, as before, on the code actually compiling.

1.3 Performance / Side-Effect Analysis

Unchanged from round 1: no cost added on the success path. On the failure path, an extra select count(*) full-table scan is issued — the correct trade-off for correctness. Still open from round 1 and still unverified this round: the fallback reuses the same jdbc connection that just failed the analyze call. If the underlying socket/session is genuinely dead (as SQLRecoverableException: No more data to read from socket in the linked issue's stack trace suggests), the follow-up select count(*) on that same connection may also fail — net effect for that specific scenario would be an unhandled exception one query later (no regression vs. today), rather than a full fix. This doesn't block the "stats-privilege-failure" case this PR clearly does fix, but it would be good for the author to confirm against a real reproduction or ask the reporter to confirm before claiming this closes #12019 outright.

1.4 Error Handling and Logging

Issues (numbered, continuing from 1.1):

  1. [Critical] [Carryover — Raised by another reviewer: No] Compile error: rowCountQuery is reassigned inside the new catch block, so it is no longer effectively final and the jdbc.queryAndMap(...) lambda that captures it fails to compile. — OracleUtils.java:100-127 (current head 62623a9c). Identical in substance to the issue reported in round 1 at OracleUtils.java:112-125 (commit 2f413e9b); only line numbers shifted trivially due to unrelated context. Confirmed via an isolated reproduction of the same control-flow shape against this project's own JDK 8 toolchain (javac 1.8.0_171), since the fork's actual CI run for this commit had not executed any relevant job yet at review time.
  2. [Low] [Carryover — Raised by another reviewer: No] Dead code: useSelectCount = true; inside the catch block has no observable effect. — OracleUtils.java:111.
  3. [Medium] [Carryover — Raised by another reviewer: No] No unit test added for the new fallback branch. — seatunnel-connectors-v2/connector-cdc/connector-cdc-oracle/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/oracle/utils/OracleUtilsTest.java already exists in this module and Mockito is available project-wide (mockito-junit-jupiter/mockito-inline in the root pom.xml), so a test mocking JdbcConnection.execute(...) to throw SQLException and asserting the fallback to select count(*) is feasible and low-cost. Confirmed via git diff apache/dev..<PR head> --stat: the PR still touches exactly one file, OracleUtils.java (11 insertions / 2 deletions) — no test file is part of this PR.
  4. [Low, informational] [Carryover — Raised by another reviewer: No] Unverified whether the select count(*) fallback on the same JDBC connection actually succeeds when the original failure is a genuinely dead socket (as opposed to a stats-privilege error). — OracleUtils.java:100-116.

Minor style note carried over: log.warn(..., e.getMessage()) drops the stack trace; passing the exception object (log.warn("...", tableId, e)) would preserve it for future troubleshooting. Non-blocking.

2. Code Quality Assessment

Style is Spotless-consistent with the rest of the file. Issue #2 (dead write) and the minor DRY duplication of the select count(*) format string (now appears in both the if (useSelectCount) branch and the new catch block) are the only quality nits, both unchanged from round 1 and both non-blocking on their own — but see the Critical compile issue above, which is blocking.

3. Architectural Soundness

The overall shape of the fix (catch, warn, fall back to a safe alternative query) is a good, contained pattern that stays entirely local to OracleUtils without leaking Oracle-specific fallback concerns into AbstractJdbcSourceChunkSplitter or other connectors. No checkpoint/savepoint state, serialization format, or protocol is touched, so there is no historical-version restore-compatibility risk. Once it actually compiles and gains a regression test, this is a clean, minimal, well-targeted change.

4. Issue Summary

# Issue Location (path:line) Severity Raised by another reviewer
1 Compile error: rowCountQuery reassigned inside the new catch block breaks effectively-final capture in jdbc.queryAndMap(...) lambda — confirmed via isolated JDK 8 repro since fork CI for this commit had not yet run OracleUtils.java:100-127 Critical No (carryover from my round 1, unresolved)
2 Dead code: useSelectCount = true; in the catch block is never read afterward OracleUtils.java:111 Low No (carryover, unresolved)
3 No unit test added for the new analyze-failure fallback path, despite OracleUtilsTest already existing and Mockito being available OracleUtilsTest.java (module) Medium No (carryover, unresolved)
4 Unverified whether select count(*) on the same connection actually succeeds after a genuinely dead-socket analyze failure OracleUtils.java:100-116 Low (informational) No (carryover, unresolved)

5. Merge Recommendation

Conclusion: Not recommended for merge

This is round 2 of review, triggered by a new commit on the PR. That "new commit" is a rebase (head_ref_force_pushed on 2026-09-16T08:19:23Z) with no functional change to the flagged code — the diff against a freshly-fetched apache/dev is byte-identical in substance to what I reviewed on 2026-09-01, and all four issues from round 1 remain open, including the Critical one.

  1. Blockers — must be fixed

    • Fix the compile error (issue #1): capture a freshly-declared, genuinely effectively-final local (e.g. final String finalRowCountQuery = rowCountQuery;) in the jdbc.queryAndMap(...) lambda instead of the reassigned rowCountQuery. Please push this and let the fork's CI actually run to completion this time — as of this review, 0 of the 75 relevant CI jobs for this commit had executed yet (all queued), so there's no fresh CI evidence one way or the other; my own reproduction is a stand-in for that missing evidence, not a replacement for actually watching the build go green.
    • Add a unit test covering the new fallback branch (issue #3), which — as in round 1 — would also have caught the compile error immediately.
  2. Recommended fixes — non-blocking

    • Remove the dead useSelectCount = true; write (issue #2).
    • Consider logging the exception object, not just e.getMessage(), for better diagnosability.
    • Please confirm (ideally against the reporter's environment) whether the select count(*) fallback actually succeeds after the specific "No more data to read from socket" failure in #12019, since that determines whether this PR fully closes #12019 or mainly helps the (also valid) stats-privilege-failure case.

Overall assessment: the intent and shape of this fix remain sound and worth merging once it compiles and has test coverage — I don't have anything new to add beyond my round-1 review, since the code itself hasn't changed. Happy to re-review again as soon as the compile fix and test land; thanks for continuing to work on this, @zhang-arvin.

Make rowCountQuery effectively final so the lambda in
queryApproximateRowCnt() compiles, and drop the dead useSelectCount
write flagged in review.
@zhang-arvin

Copy link
Copy Markdown
Contributor Author

@DanielLeens Thanks for the precise diagnosis. Fixed both items and pushed:

  1. Issue Add a Gitter chat badge to README.md #1 (compile blocker): rowCountQuery is now declared final and assigned exactly once on each path (the analyze-fallback branch builds an intermediate String query and only assigns rowCountQuery once at the end). The lambda capture of rowCountQuery now compiles.
  2. Issue fixed ConfigBuilder.scala #2 (dead write): removed the useSelectCount = true; statement; the fallback now just reassigns the local query.

Also de-duplicated the select count(*) format string into a single selectCountQuery. Verified locally with the project toolchain (JDK 8): ./mvnw -o compile -pl connector-cdc-oracle passes, and spotless:apply is clean. New head: 692c6bda5.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround, @zhang-arvin, and for the clear write-up of what changed. I re-reviewed the full diff of the latest head 692c6bda50 against current dev. Both the compile blocker (round-1 Issue 1) and the dead-write nit (Issue 2) are genuinely fixed, and the DRY cleanup of the select count(*) string is a nice touch. One item from my earlier rounds is still open (the unit test), listed below.

What Problem Does This PR Solve?

  • User pain point: In Oracle CDC snapshot split generation, OracleUtils.queryApproximateRowCnt() runs analyze table ... compute statistics for table before reading NUM_ROWS. If that statement fails (missing privilege, session or socket problem, statistics gathering restricted), the SQLException escapes through AbstractJdbcSourceChunkSplitter.splitTableIntoChunks() (the RuntimeException("Failed to split chunks ...") wrap at AbstractJdbcSourceChunkSplitter.java:~108) and the whole snapshot for that table fails with Generate Splits for table XXX (issue #12019).
  • Fix approach: Wrap the analyze call in a try/catch (SQLException), log a warning, and fall back to select count(*) from <table> for the approximate row count.
  • One-sentence summary: A failed optimizer-statistics refresh no longer kills the snapshot phase; the splitter just gets a (slower but exact) row count instead.

1. Code Change Review

1.1 Core Logic Analysis

Only one file changes: connector-cdc-oracle/.../utils/OracleUtils.java (+16/-7), method queryApproximateRowCnt() at lines 85-127.

Before (dev):

Boolean useSelectCount = oracleSourceConfig.getUseSelectCount();
String rowCountQuery;
if (useSelectCount) { rowCountQuery = "select count(*) from ..."; }
else {
    rowCountQuery = "select NUM_ROWS from all_tables where TABLE_NAME = '...'";
    if (!skipAnalyze) { jdbc.execute(analyzeTable); }   // SQLException propagates
}

After (head), lines 88-116:

final String selectCountQuery = String.format("select count(*) from %s", quoteSchemaAndTable(tableId));
final String rowCountQuery;
if (oracleSourceConfig.getUseSelectCount()) { rowCountQuery = selectCountQuery; }
else {
    String query = "select NUM_ROWS from all_tables ...";
    if (!skipAnalyze) {
        try { jdbc.execute(analyzeTable); }
        catch (SQLException e) { log.warn(...); query = selectCountQuery; }
    }
    rowCountQuery = query;      // single assignment, so the lambda capture below is legal
}

Runtime path:

OracleIncrementalSource split enumeration (snapshot phase)
  -> OracleChunkSplitter.queryApproximateRowCnt(jdbc, tableId)        [OracleChunkSplitter.java:86-87]
      -> OracleUtils.queryApproximateRowCnt(config, jdbc, tableId)    [OracleUtils.java:85]
          -> use_select_count=false, skip_analyze=false (both defaults, OracleIncrementalSourceOptions.java:68-78)
              -> jdbc.execute("analyze table ...")                    [OracleUtils.java:106]
                  -- ok     -> query stays "select NUM_ROWS ..."   (unchanged behavior)
                  -- fails  -> warn + query = "select count(*) ..."  (NEW)
          -> jdbc.queryAndMap(rowCountQuery, rs -> rs.getLong(1))      [OracleUtils.java:118-128]
  -> AbstractJdbcSourceChunkSplitter.splitTableIntoChunks()            [only when the split column is "evenly splittable", i.e. numeric]
      -> calculateDistributionFactor(min, max, approximateRowCnt) -> evenly-sized vs. sampled/unevenly-sized chunks

Key findings:

  1. The default configuration reaches the changed code for every table whose split column is numeric, so this is a main-path fix and not just a boundary case.
  2. The success path is byte-for-byte unchanged (same SQL, same single query, same result mapping), so the behavior change is limited to the case that used to throw.
  3. The compile problem is resolved: rowCountQuery is final and definitely assigned once on every path, so the capture at OracleUtils.java:125 is valid.
  4. This is a precise, contained fix and it does not leak Oracle-specific fallback logic into AbstractJdbcSourceChunkSplitter or other connectors.

1.2 Compatibility Impact

Fully compatible. No option, default, protocol, serialization format, or checkpoint/savepoint state is touched. The only behavior change is that a previously fatal analyze failure now degrades to an exact count. Existing jobs that never hit the failure behave identically.

1.3 Performance / Side-Effect Analysis

  • Only the failure path adds work: a full select count(*) on the table. For a very large table this can be slower than reading NUM_ROWS, but it runs once per table per split-generation, is the same query the user could already opt into with use_select_count=true, and is strictly better than failing the job. No new threads, locks, retries, or buffers; no resource-release changes.
  • Note that if the original analyze failure was caused by a dead connection rather than a privilege/statistics problem, the fallback query on the same JdbcConnection will fail with a similar SQLException, which is the same end result as before (not a regression).

1.4 Error Handling and Logging

  • The exception is handled narrowly (SQLException only) and not silently swallowed: a WARN with the table id is emitted and the fallback is explicit in the log line, so the degradation is visible to operators.

Issue 1: No unit test for the new analyze-failure fallback

  • Location: OracleUtilsTest.java (the module's existing test class; the PR still changes only OracleUtils.java)
  • Problem description: The new branch (jdbc.execute(analyzeTable) throws, then the row-count query becomes select count(*)) is never exercised by any test in the PR. The Oracle CDC IT only covers the case where analyze succeeds, so a future refactor could silently drop the fallback again. OracleUtilsTest already exists, and JdbcConnection is a regular (non-final) Debezium class, so a Mockito-based test is cheap.
  • Potential risk: The regression this PR fixes (whole snapshot fails on a failed analyze) can come back unnoticed.
  • Best improvement: Extend OracleUtilsTest with one or two cases: (a) a mocked JdbcConnection.execute(...) that throws SQLException while useSelectCount=false and skipAnalyze=false, asserting that the SQL passed to queryAndMap(...) is select count(*) from "SCHEMA"."TABLE" (an ArgumentCaptor on the first argument works well); and (b) the happy path asserting the select NUM_ROWS ... query is still used when execute succeeds. Please keep to the existing test class instead of adding a new one.
  • Severity: Medium (carryover from my earlier rounds, still open)
  • Raised by another reviewer: No

Issue 2: Stack trace is dropped from the warning

  • Location: OracleUtils.java:109-113
  • Problem description: log.warn("... Error: {}", tableId, e.getMessage()) keeps only the message. For ORA errors the vendor code and cause chain are what operators need to tell "missing ANALYZE ANY privilege" apart from "socket closed".
  • Best improvement: log.warn("Failed to analyze table {}, falling back to select count(*)", tableId, e); (the trailing throwable is printed with its stack trace by SLF4J).
  • Severity: Low (non-blocking)
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Spotless-consistent and readable. selectCountQuery de-duplication is good. The fallback branch has a clear log message; a one-line comment explaining why the failure is deliberately tolerated (statistics refresh is an optimization, not a correctness requirement) would help future maintainers, but it is optional.

2.2 Test Coverage and Test Stability

No test was added or changed in this PR, so there is no test-stability concern to rate. Coverage is the gap described in Issue 1.

2.3 Documentation Updates

No user-visible option or default changed, so docs/en and docs/zh do not need updates. If you want to be helpful to users, one sentence in the Oracle-CDC docs next to skip_analyze / use_select_count noting that a failing analyze now falls back to select count(*) would be nice, but it is not required.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix.

3.2 Maintainability

Clear and local; behavior is easy to reason about from the single method.

3.3 Extensibility

Fine as is. Other CDC connectors' queryApproximateRowCnt (Db2, SQL Server, Postgres, MySQL) have different statistics mechanics, so there is no need to generalize here.

3.4 Historical-Version Compatibility

Fully compatible; no state, option, or serialization changes, so no upgrade action is needed.

4. Issue Summary

# Issue Location Severity
1 No unit test for the analyze-failure fallback OracleUtilsTest.java Medium
2 Warning drops the exception stack trace OracleUtils.java:109-113 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed

    • Issue 1: add the unit test for the fallback branch (it would also have caught the original compile break, and it is the same ask as in my earlier rounds).
  2. Recommended fixes - non-blocking

    • Issue 2: log the exception object, not only its message.

CI status on this head (fork run, zhang-arvin/seatunnel, run 37721978366): Build is red, but I could not find a failure attributable to this diff. The failing jobs are: Dead links (deepwiki.com returning HTTP 429), unit-test (11, windows-latest) (PayPalClientTest.closeWakesRetryWait, a known timing flake in an unrelated connector), oracle-cdc-connector-it (11) (failed at the Maven wrapper download with HTTP 429 from Maven Central, so the tests never started), paimon-connector-it (PaimonWithS3IT cannot pull its Docker image), updated-modules-integration-test-part-2 (Hudi S3 ITs cannot pull their Docker image), and updated-modules-integration-test-part-3 (OpengaussCDCIT.testAddFieldWithRestore condition timeout). Importantly, oracle-cdc-connector-it (8) passed on this head, which exercises the Oracle CDC module on the new code. Once the unit test is pushed, the next CI run should be the cleaner signal; if any of those infrastructure-style failures recur, a rerun of just the failed jobs is the right move rather than changing code. The branch is also 163 commits behind dev (compare status: diverged, no conflicts reported), so syncing with the latest dev when you push the test is a good idea.

Overall assessment: the approach is sound, minimal, and now compiles; with the regression test added it is a clean, well-targeted fix. There is no better alternative placement than OracleUtils for this change. Thank you for sticking with it, and happy to re-review as soon as the test lands!

@zhang-arvin

Copy link
Copy Markdown
Contributor Author

Closing: #12019 was closed after triage — the analyze table ... compute statistics timeout it reported is addressed by the existing skip_analyze / use_select_count options rather than a code change. No remaining target for this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] [Oracle CDC] Generate Splits for table XXX

2 participants