Skip to content

[Feature][Client] Add Java detection utility to Python SDK - #12740

Merged
davidzollo merged 2 commits into
apache:devfrom
karthik-0306:feature/python-sdk-java-detection
Oct 16, 2026
Merged

davidzollo merged 2 commits into
apache:devfrom
karthik-0306:feature/python-sdk-java-detection

Conversation

@karthik-0306

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Related to #12707 (pip-installable SeaTunnel launcher).

This PR adds the first small building block for that work: a helper that finds Java on the user's machine and checks that it is new enough. Today seatunnel.sh has no Java version check, so someone running Java 8 gets a confusing UnsupportedClassVersionError from the JVM. This helper lets the future launcher fail early with a clear message instead.

What detect_java(min_version=11) does:

  1. Looks for Java in $JAVA_HOME/bin/java first, then falls back to java on PATH.
  2. Runs java -version and reads the major version. It handles the old format (1.8.0_292 is Java 8) and the new formats (11.0.2, 17, 21.0.1, 17-ea).
  3. Returns a small JavaInfo(executable, major_version) object, so the launcher can reuse both the path and the version without parsing anything again.
  4. Raises JavaDetectionError if Java is missing, older than min_version, its output can't be read, or running it fails or times out. Every message states what was found (or that nothing was found) and guides the user to set JAVA_HOME or install JDK {min_version}+ (default 11+).

Design note: If JAVA_HOME is set but has no Java binary in it, the helper raises an error instead of quietly falling back to PATH. A typo in JAVA_HOME would otherwise be ignored, and the user could end up on a different Java than intended. PATH is only consulted when JAVA_HOME is unset or empty. Happy to adapt this if reviewers prefer a fallback.

Scope: This adds two new files under tools/seatunnel-python-sdk. It is not exported from seatunnel/__init__.py, and seatunnel.sh and the engine are untouched. Adding the same check to seatunnel.sh could be handled in a separate change.

Does this PR introduce any user-facing change?

No. It is an internal helper that nothing calls yet, and it is not part of the SDK's public API.

How was this patch tested?

Added 20 new unit tests in tools/seatunnel-python-sdk/tests/test_java_detector.py. They mock the java -version output, so no real JDK is needed. They cover:

  • Old and new version formats: 1.7.0_80, 1.8.0_292, 11, 11.0.2, 17.0.1, 17-ea, 21.0.1
  • JAVA_HOME used before PATH, and a bad JAVA_HOME failing without falling back to PATH
  • Java missing, Java too old, unreadable output, a non-zero exit code, a timeout, and an OSError
  • Extra JVM noise lines such as Picked up JAVA_TOOL_OPTIONS or NOTE: Picked up JDK_JAVA_OPTIONS, and a version printed on stdout instead of stderr
  • A custom min_version, with all error messages using that value instead of a hardcoded 11

To run them (from tools/seatunnel-python-sdk/):

python -m pytest tests/ -v

@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 contribution, and for the clear PR description and design note! I went through the full diff and traced the logic path by path. I did not find any blocking issue in the code. Details below.

What Problem Does This PR Solve?

  • User pain point: Today there is no Java version check before launching SeaTunnel, so a user on an older JDK gets an opaque UnsupportedClassVersionError. The Java 11 baseline matches java.version=11 in the root pom.xml and the "Java 11 or Java 17" requirement in docs/en/getting-started/locally/deployment.md.
  • Fix approach: Add detect_java(min_version=11) and JavaInfo / JavaDetectionError in tools/seatunnel-python-sdk/seatunnel/java_detector.py, as a first building block for #12707.
  • One-sentence summary: A small, self-contained, currently-unused helper that resolves Java (JAVA_HOME first, then PATH), parses its major version, and fails early with an actionable message.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path: detect_java -> _find_java_executable (JAVA_HOME/bin/java[.exe], or shutil.which("java") only when JAVA_HOME is unset/blank) -> subprocess.run([exe, "-version"], timeout=10) -> _parse_major_version on stderr, then stdout -> compare with min_version -> JavaInfo.

What I verified:

  • Version parsing handles 1.7.0_80 / 1.8.0_292 (-> 7 / 8), 11.0.2, 17, 17-ea, 21.0.1 correctly. The first == "1" and second is not None branch is correct, and a bare "17" correctly falls to the new-style path.
  • Picked up JAVA_TOOL_OPTIONS ... noise lines are skipped, and or between the two parses is safe because a real major version is never 0.
  • Failure modes are all mapped to JavaDetectionError with from exc chaining: timeout, OSError, non-zero exit, unparseable output, too old.
  • The "bad JAVA_HOME does not silently fall back to PATH" decision is reasonable for a launcher, and I agree with it.
  • Python 3.9 compatible (Optional, dataclass(frozen=True), f-strings), matching python_requires='>=3.9'.
  • New files carry the ASF license header.

1.2 Compatibility Impact

Fully compatible. Two new files only; not exported from seatunnel/__init__.py, nothing calls the helper, seatunnel.sh and the engine are untouched. No API, config, default, protocol or serialization impact.

1.3 Performance / Side-Effect Analysis

One short-lived subprocess with a 10s timeout; no shared state, no retries, no resources left open. No concerns.

1.4 Error Handling and Logging

Messages include what was found and a next step, which is exactly what the launcher needs. Nothing is swallowed and no sensitive data is printed (only paths and java -version output).

No blocking issues found. Non-blocking suggestions:

Issue 1: JAVA_HOME candidate is only checked with isfile

  • Location: tools/seatunnel-python-sdk/seatunnel/java_detector.py (_find_java_executable, the os.path.isfile(candidate) check)
  • Problem description: A non-executable file at JAVA_HOME/bin/java passes the check and then fails in subprocess.run with PermissionError. That is already converted to JavaDetectionError via the OSError branch, so the user still gets a message, just a slightly less direct one.
  • Potential risk: Cosmetic only.
  • Best improvement: Optionally use os.path.isfile(candidate) and os.access(candidate, os.X_OK).
  • Severity: Low
  • Raised by another reviewer: No

Issue 2: The min_version default is duplicated

  • Location: java_detector.py (_find_java_executable and detect_java both default to 11)
  • Problem description: The baseline lives in two signatures; they can drift when the baseline moves (for example to 17).
  • Best improvement: A module constant such as DEFAULT_MIN_JAVA_VERSION = 11, or make the private helper's parameter required.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Clean, well-named, and the docstrings explain resolution order and constraints. Nothing missing on the documentation front.

2.2 Test Coverage and Test Stability

The 20 tests mock subprocess.run, shutil.which and the environment, and cover old/new version formats, JAVA_HOME precedence, bad JAVA_HOME, missing/too-old/unreadable/non-zero/timeout/OSError, JVM noise lines, stdout fallback, and a custom min_version. Platform differences are handled with sys.platform in the expected path.

  • Stability rating: Stable. No real JDK, network, sleeps, or ordering dependence; the environment is isolated via mock.patch.dict(..., clear=True).
  • Small note (no action required): I could not find a CI job that runs the Python SDK tests, so these tests are currently only exercised when run locally with python -m pytest tests/ -v. Worth keeping in mind for the follow-up launcher PRs.

2.3 Documentation Updates

Not needed: the helper is internal and not user-facing yet. docs/en / docs/zh need no change in this PR.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise, minimal first step toward #12707.

3.2 Maintainability

Small and readable; error text is centralized in the one function.

3.3 Extensibility

Returning JavaInfo(executable, major_version) lets the launcher reuse both values, which is a good shape.

3.4 Historical-Version Compatibility

Fully compatible; no upgrade action.

4. Issue Summary

# Issue Location Severity
1 JAVA_HOME candidate checked only with isfile java_detector.py _find_java_executable Low
2 Default min_version duplicated java_detector.py Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed: none on the code side.
  2. Recommended fixes - non-blocking: Issue 1 and Issue 2 (both Low, purely optional).

CI status (current head 8e75f8c): the apache-side Build check is only a pointer; the real run is in your fork. The failures there are the Java integration jobs (all-connectors-it-2 on Java 11 and 17, and engine-v2-it (11)), while all unit-test, code-style, license-header and docs jobs are green. This PR only adds two Python files that no Java code path touches, so those failures do not look related to this change. The branch is also 3 commits behind dev (diverged), so the lowest-cost next step is to sync with the latest dev and re-run the failed jobs. If the same jobs fail again after that, please paste the new failing link here and I am happy to help narrow it down.

Overall: a nice, well-tested starting point. Thanks again, and happy to take another look after the sync!

@karthik-0306
karthik-0306 force-pushed the feature/python-sdk-java-detection branch from 8e75f8c to 6acc237 Compare October 14, 2026 08:09
@karthik-0306

Copy link
Copy Markdown
Contributor Author

Pushed an update, rebased on the latest dev. Thanks @DanielLeens for the review.

  • Added a single DEFAULT_MIN_JAVA_VERSION constant (Issue 2).
  • If JAVA_HOME points to a Java older than the minimum, the error now includes the JAVA_HOME value and says to fix or unset it, as @SEZ9 asked. Added a test for it.
  • I left the isfile check as it is (Issue 1): a non-executable file already gives a clear JavaDetectionError through the OSError branch. Happy to add os.access if you prefer.

Tests: 28 passed on Python 3.9 and 3.13.

@CryoThrust

Copy link
Copy Markdown
Contributor

Rechecked 6acc237f against the two JAVA_HOME requests. The new missing-binary and too-old-JDK paths both include the attempted JAVA_HOME and fix/unset guidance. The shared minimum-version constant also keeps custom-minimum diagnostics consistent.

All 21 detector tests pass locally on Python 3.13. I also exercised this head with real Java 8/11/17 on macOS: 11 and 17 resolve correctly; 8 is rejected with its JAVA_HOME value, found version and unset guidance. A missing JAVA_HOME is rejected with the attempted value and recovery hint. This covers the detection helper; I have not tested Windows execution or the complete pip launcher.

@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 @karthik-0306 for the update and for the clear explanation of what you took and what you left alone! I re-read the full diff of the new head 6acc237f (2 commits on top of current dev, ahead_by=2, behind_by=0, so the sync is done), re-traced detect_java end to end, and read the issue #12707 thread plus @SEZ9's two asks and @CryoThrust's real-JDK check. Short version: my earlier Issue 2 is fixed, I accept your reasoning on Issue 1, and I found no blocker.

What Problem Does This PR Solve?

  • User pain point: There is no Java version check before launching SeaTunnel, so a user on an older JDK gets an opaque UnsupportedClassVersionError. The Java 11 baseline matches the root pom.xml (java.version=11).
  • Fix approach: Add detect_java(min_version=DEFAULT_MIN_JAVA_VERSION), JavaInfo and JavaDetectionError in tools/seatunnel-python-sdk/seatunnel/java_detector.py, as the first building block for #12707.
  • One-sentence summary: A small, self-contained, currently unused helper that resolves Java (JAVA_HOME first, then PATH), parses its major version, and fails early with an actionable message.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path:

detect_java(min_version)
  -> _find_java_executable: JAVA_HOME set  -> JAVA_HOME/bin/java[.exe] or JavaDetectionError (no fallback to PATH)
                            JAVA_HOME unset/blank -> shutil.which("java")
  -> subprocess.run([exe, "-version"], timeout=10)   (TimeoutExpired / OSError -> JavaDetectionError, chained)
  -> non-zero exit -> JavaDetectionError
  -> _parse_major_version(stderr) or (stdout)         ("1.8.0_292" -> 8, "11.0.2" -> 11, "17-ea" -> 17)
  -> major < min_version -> JavaDetectionError (mentions JAVA_HOME value when the binary came from it)
  -> JavaInfo(executable, major)

Status of my previous round and the new asks:

  • Earlier Issue 2 (duplicated default): fixed with DEFAULT_MIN_JAVA_VERSION (java_detector.py:45), used by both signatures.
  • Earlier Issue 1 (isfile only): I accept your reasoning. A non-executable JAVA_HOME/bin/java fails in subprocess.run with PermissionError, which the OSError branch already converts into JavaDetectionError with the path, so the user still gets a clear message. No change needed.
  • @SEZ9's two asks (error shows the tried JAVA_HOME value and why it was rejected, and a test): both covered. "Nothing found there" is in _find_java_executable (:61-64) and "version below minimum" is in detect_java (:144-155, includes the JAVA_HOME value, the resolved executable, the found version and "Fix or unset JAVA_HOME"). The tests are test_java_home_set_but_binary_missing_raises and test_java_home_too_old_error_mentions_java_home_value.
  • Version parsing re-checked: 1.8.0_292/1.7.0_80 -> 8/7, bare 17, 17-ea, 21.0.1 all land on the right branch (java_detector.py:75-86). Python 3.9 compatible (Optional, dataclass(frozen=True)), matching python_requires='>=3.9' in setup.py.

1.2 Compatibility Impact

Fully compatible. Two new files only; nothing imports the helper, seatunnel/__init__.py, seatunnel.sh and the engine are untouched. No API, config, default, protocol or serialization impact, and no incompatible-changes.md entry needed.

1.3 Performance / Side-Effect Analysis

One short-lived subprocess with a 10s timeout, no shared state, no retries, nothing left open.

1.4 Error Handling and Logging

Every failure mode maps to JavaDetectionError with from exc chaining where relevant; nothing is swallowed and no sensitive data is printed.

Issue 1 (Low, non-blocking): errors after the JAVA_HOME binary is resolved do not follow the same "fix or unset JAVA_HOME" guidance

  • Location: java_detector.py:108-139 (timeout, OSError, non-zero exit, unparseable output branches)
  • Problem description: When JAVA_HOME is set and its binary exists but cannot be run, exits non-zero or prints something unparseable, the message ends with "Set JAVA_HOME or install JDK N+." Since JAVA_HOME is already set, that hint is slightly misleading, and the message does not say the executable came from JAVA_HOME. The executable path is shown, so the user can still figure it out. @SEZ9's ask covered "nothing found" and "version below minimum", which are handled, so this is only a consistency polish.
  • Potential risk: Cosmetic; a less direct message for a rare broken-JDK case.
  • Best improvement: Reuse the "from JAVA_HOME='...' ... Fix or unset JAVA_HOME" wording through a small helper used by all branches, or leave as is for this first PR and handle it in the launcher PR.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Clean and well-named, docstrings explain resolution order and constraints, ASF headers are present on both new files.

2.2 Test Coverage and Test Stability

test_java_detector.py has 21 mocked tests covering old and new version formats, JAVA_HOME precedence, bad JAVA_HOME (no fallback to PATH, enforced with a shutil.which mock that raises), too-old JAVA_HOME, missing java, timeout, OSError, non-zero exit, unparseable output, stdout fallback, JVM option noise lines, and custom min_version in all error messages. Thanks also to @CryoThrust for running it against real Java 8/11/17 on macOS (11 and 17 resolve; 8 is rejected with the JAVA_HOME value and unset hint); I did not run it myself.

Stability rating: Stable. No real JDK, network, sleeps or ordering dependence; the environment is isolated with mock.patch.dict("os.environ", ..., clear=True) (test_java_detector.py:51-56), and the platform difference is handled with sys.platform.

Issue 2 (Low, non-blocking): the Picked up guard does not match the NOTE: Picked up ... form, and its test passes for a different reason

  • Location: java_detector.py:76 (line.strip().startswith("Picked up")) and test_java_detector.py:230 (test_note_picked_up_jdk_java_options_line_is_ignored)
  • Problem description: The JDK prints NOTE: Picked up JDK_JAVA_OPTIONS: ... (with the NOTE: prefix), which does not start with Picked up, so the guard does not skip it. The test still passes only because the regex needs version " with a space before the quote and the sample option -Dfoo="1" does not contain that. So the test docstring ("is skipped") overstates what protects it, and an option such as -Dx="a version "9"" is an unrealistic but possible way to fool the parser.
  • Potential risk: Very low; the regex already ignores realistic option strings.
  • Best improvement: Use "Picked up" in line for the skip, or reword the docstring to say the line simply does not match the version regex.
  • Severity: Low
  • Raised by another reviewer: No

Note, no action required: I could not find a CI job that runs tools/seatunnel-python-sdk tests (.github/workflows/cli.yml covers seatunnel-cli/ only), so these tests run only locally with python -m pytest tests -v. Worth keeping in mind for the launcher PRs.

2.3 Documentation Updates

Not needed: the helper is internal and not user-facing yet, so docs/en and docs/zh need no change.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise, minimal first step toward #12707.

3.2 Maintainability

Small and readable; the baseline now lives in one constant.

3.3 Extensibility

Returning JavaInfo(executable, major_version) lets the launcher reuse both values.

3.4 Historical-Version Compatibility

Fully compatible; no upgrade action.

4. Issue Summary

# Issue Location Severity
1 Post-resolution errors do not use the "fix or unset JAVA_HOME" wording java_detector.py:108-139 Low
2 Picked up guard misses the NOTE: form; test passes for another reason java_detector.py:76, test_java_detector.py:230 Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed: none on the code, test, docs or compatibility side.
  2. Recommended fixes - non-blocking: Issues 1 and 2 (both Low, optional, fine for a follow-up).

Merge state and CI: the branch is up to date with dev (ahead 2, behind 0) with no conflicts. At the time of this review the apache-side checks for this head show only Notify test workflow and labeler as queued, and there is no Build check yet, so there is no CI result to evaluate. The previous head's red jobs were Java integration lanes unrelated to these two Python files. I would hold the merge itself until Build has run and is green, and a committer approval is still needed on top of this technical review. @SEZ9 has also said this PR is on their review list.

Overall: a nice, well-tested starting point. Thanks again!

@karthik-0306

Copy link
Copy Markdown
Contributor Author

@SEZ9 the JAVA_HOME error changes and the new test are pushed to this PR, so the latest head already includes them. I ran the full suite locally on Windows with Python 3.9 and 3.13: 28 passed (21 detector tests including the new JAVA_HOME too-old test, plus the 7 existing SDK tests). I haven't run it on macOS or Linux myself beyond CryoThrust's run. Thanks for the review.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @karthik-0306 for the clear follow-up, and thanks @SEZ9 and @CryoThrust for the extra verification. Nothing further is needed from the code side for my review.

One CI correction on my side: in my last review I wrote that the apache-side Build check had not started yet. It has now completed on head 6acc237f with one failed job, Run / engine-v2-it (11, ubuntu-latest) (step "run seatunnel zeta integration test"; 82 jobs succeeded and 11 were skipped). This PR only adds two Python files under tools/seatunnel-python-sdk, which that Java engine lane does not exercise, so I read this as unrelated to the diff (this is an inference from the diff scope, I did not see the failing test log). The minimal next step is to re-run only that failed job from the fork's Actions run, and no code change is required. My technical approval still stands; the merge itself should wait for a green Build and a committer approval.

@SEZ9

SEZ9 commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

@karthik-0306 thanks for the follow-up — confirmed, 6acc237f includes the JAVA_HOME error changes (attempted value plus fix/unset guidance for both the missing-binary and too-old-JDK paths) and the new too-old test, so my two asks are addressed. Your Windows run on Python 3.9 and 3.13 (28 passed: 21 detector + 7 existing SDK) plus CryoThrust's macOS check with real Java 8/11/17 gives me enough confidence in the detection helper across platforms; I don't need you to run macOS or Linux manually.

Also agree with leaving the isfile check as is — the OSError branch already turns a non-executable JAVA_HOME/bin/java into a clear JavaDetectionError, so no need to add os.access.

Two small things left before merge:

  1. The Build check on 6acc237f reportedly has one failed job, Run / engine-v2-it (11, ubuntu-latest). Since this PR only touches Python files under tools/seatunnel-python-sdk, that looks unrelated to the diff, but please re-run just that job from your fork's Actions run so we get a green Build. No code change expected.
  2. Could you confirm whether the new detector tests actually execute in CI (i.e. on a Linux runner), or only locally? If they are not wired into CI yet, let me know and we can decide whether that belongs in this PR or the follow-up for the launcher.

Once Build is green I'll do the final pass for merge.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEZ9 for the question, and thanks @karthik-0306 for the quick turnaround. I checked the CI wiring on current dev so you do not have to guess.

On the second point (do the new detector tests run in CI): as far as I can tell from the workflow files, no. The only Python workflow is .github/workflows/cli.yml, which is triggered by seatunnel-cli/** and runs ruff and pytest inside seatunnel-cli only. There is no workflow that references tools/seatunnel-python-sdk, so neither tests/test_java_detector.py from this PR nor the existing tests/test_sdk.py is executed by GitHub CI today. The Build check on this PR therefore says nothing about the Python tests (this is from reading the workflows on dev; I did not run anything).

My suggestion is to keep that out of this PR: wiring a path-filtered pytest job for the SDK is a separate CI change that also affects the existing SDK tests, and the detector has already been verified locally on Windows and macOS (thanks @CryoThrust). It would fit well together with the launcher follow-up for #12707, or as a small dedicated PR.

On the first point (Build red): the only failed job is still Run / engine-v2-it (11, ubuntu-latest), in the first attempt of your fork's run (run attempt 1, so it has not been re-run yet). Since this PR only touches two Python files, that Java engine lane is not exercised by it, so please re-run just that failed job from your fork's Actions page (Re-run failed jobs). No code change is needed. My technical approval still stands.

@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.

CI update for head 6acc237f0, with no code change since my last review.

In my last review there was no Build check on this head yet, and I said I would hold the merge until it ran and was green. That fact has changed. The apache-side Build check (see https://github.com/apache/seatunnel/runs/116944660568) is now SUCCESS on this exact head.

CI was previously the only remaining blocker, and it is now passing, so I am changing my conclusion to approve. I did not find any code-side blocker in my last review and nothing has changed in the diff since.

This approval is based on a static review of the code plus the passing CI above; I did not execute the PR myself. A committer approval is still required for merge.

Thanks for the contribution!

@davidzollo davidzollo 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.

Approving: Build is green on this exact head and the code-side review found no blockers.

@davidzollo
davidzollo added this pull request to the merge queue Oct 16, 2026
Merged via the queue into apache:dev with commit be8a310 Oct 16, 2026
3 checks passed
Asthenia0412 added a commit to Asthenia0412/seatunnel that referenced this pull request Oct 18, 2026
)

Signed-off-by: Asthenia0412 <Asthenia0412@users.noreply.github.com>
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.

5 participants