Skip to content

[Python] Add beam sql to the experimental beam command - #41436

Open
jk-shah wants to merge 6 commits into
apache:masterfrom
jk-shah:beam-sql-pr3
Open

jk-shah wants to merge 6 commits into
apache:masterfrom
jk-shah:beam-sql-pr3

Conversation

@jk-shah

@jk-shah jk-shah commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Adds beam sql to the experimental beam command introduced in #40968 and #41040.

beam sql launches the Apache Beam SQL shell (BeamSqlLine) with the same flags, shaded uber-JAR build (including delta and iceberg connector parity from #40958 / #41090), and ~/.beam/cache/ + ~/.beam/maven-wrapper/ layout as scripts/beam-sql.sh, so cached JARs are shared between both entry points without rebuilding:

beam sql
beam sql --io csv --io parquet
beam sql -e "SELECT 1 + 1 AS two;"
beam sql --runner dataflow --io google-cloud-platform
beam sql --list-versions
beam sql --list-ios
beam sql --list-runners

Key details

  • Cross-platform & prerequisite checks: Verifies a working Java 11+ runtime (JAVA_HOME or PATH, including java.exe on Windows and catching macOS's /usr/bin/java stub and Java 8 with exit code 4), invokes MavenWrapperMain directly via java rather than sh/mvnw, and queries Maven Central via Python urllib (no curl, sed, or GNU sort -V required).
  • Cache & network safety: Uses cross-process file locks (.maven-wrapper.lock, <jar>.lock with O_NOFOLLOW), zipfile.is_zipfile validation (rebuilding truncated/corrupt cached JARs automatically), atomic tempfile.mkstemp + os.replace writes, HTTPS-only redirect enforcement, and SNAPSHOT-only snapshot repository gating.

beam sql launches the interactive Apache Beam SQL shell (BeamSqlLine) with
the same flags, shaded uber-JAR build, and ~/.beam/cache/ +
~/.beam/maven-wrapper/ layout as scripts/beam-sql.sh, so existing cached
JARs are reused without rebuilding.

Checks for a working Java 11+ runtime (catching missing Java, macOS's
/usr/bin/java stub, and older JDKs with exit code 4) and queries Maven
Central using the Python standard library rather than curl/grep/sed.

@github-actions github-actions Bot 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.

📋 Review Summary

This PR adds the beam sql subcommand to the experimental beam CLI, enabling users to launch the interactive Apache Beam SQL shell (BeamSqlLine) while sharing cached JARs (~/.beam/cache/) and Maven Wrapper files (~/.beam/maven-wrapper/) with scripts/beam-sql.sh. The implementation is well-structured, thorough with cross-platform file locking and security hardening, and well-tested.

🔍 General Feedback

  • Found two minor compatibility differences with scripts/beam-sql.sh regarding SNAPSHOT version normalization and filtering --list-runners results by the target Beam version.
  • Identified a potential file descriptor leak in _download_https if an exception occurs while reading from the HTTPS response.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

Comment thread sdks/python/apache_beam/cli/sql.py Outdated
if version:
if '..' in version or not _VALID_ARTIFACT_PART.match(version.lower()):
raise SqlError(f'invalid Beam version {version!r}', _EXIT_USAGE)
return version

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.

🟡 Medium: scripts/beam-sql.sh normalizes lowercase or mixed-case -snapshot suffixes to uppercase -SNAPSHOT (normalize_beam_version). In Maven, snapshot artifact versions are case-sensitive (2.79.0-SNAPSHOT), so passing --version 2.79.0-snapshot currently enables the snapshot repository (via 'snapshot' in str(version).lower()) but leaves ${beam.version} lowercase in the POM and cache filename, causing Maven resolution to fail and cache keys to diverge from beam-sql.sh.

Suggested change
return version
return re.sub(r'-snapshot$', '-SNAPSHOT', version, flags=re.IGNORECASE)

Comment thread sdks/python/apache_beam/cli/sql.py Outdated
with contextlib.suppress(OSError):
if os.path.exists(tmp_path):
os.remove(tmp_path)
raise

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.

🟡 Medium: If _https_urlopen or resp.read() raises an exception (such as urllib.error.URLError, TimeoutError, or OSError) before os.fdopen(fd, 'wb') takes ownership of fd, the file descriptor fd returned by tempfile.mkstemp is never closed (os.close(fd) is only called in the len(data) > max_bytes branch). On Windows, leaving fd open also causes os.remove(tmp_path) in the except block to fail with PermissionError.

Comment thread sdks/python/apache_beam/cli/sql.py Outdated

def _list_runners(version):
safe_ver = _sanitize_log_token(version)
runners = _query_maven_artifacts('beam-runners-', _EXCLUDED_RUNNER_RE)

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.

🟢 Low: _list_runners(version) accepts version and prints Available runners in Maven Central (Beam {safe_ver}):, but does not filter the Solr query by version (unlike scripts/beam-sql.sh, which includes +AND+v:${BEAM_VERSION} in the query). Passing version to _query_maven_artifacts so it appends +AND+v:{version} when provided will ensure the output accurately reflects the requested Beam version.

@github-actions github-actions Bot added python size/xl XL: >=1000 lines changed labels Nov 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @damccorm for label python.
Backup reviewer: claudevdm (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

- Normalize lowercase/mixed-case -snapshot suffixes to -SNAPSHOT (#discussion_r4604918226)
- Close mkstemp fd in finally if _https_urlopen/read raises before fdopen (#discussion_r4604918253)
- Filter --list-runners Maven Solr query by +AND+v:<version> (#discussion_r4604918260)
@jk-shah

jk-shah commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

1 similar comment
@derrickaw

Copy link
Copy Markdown
Collaborator

/gemini review

@github-actions github-actions Bot 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.

📋 Review Summary

This PR adds the beam sql subcommand to the experimental beam CLI, providing a cross-platform Python equivalent of scripts/beam-sql.sh that shares ~/.beam/cache/ and ~/.beam/maven-wrapper/, validates Java 11+ prerequisites, and includes thorough unit test coverage. The implementation is well-structured and already addresses the feedback from the initial review round.

🔍 General Feedback

  • Launching the interactive BeamSqlLine session via subprocess.run causes Ctrl-C (SIGINT) to SIGKILL the child JVM and raise an unhandled KeyboardInterrupt traceback in Python, rather than letting BeamSqlLine/JLine cancel the current input line and restore terminal settings.
  • When reporting Maven dependency resolution errors, selecting details.splitlines()[-1] surfaces Maven's generic [Help 1] footer URL rather than the line naming the missing artifact.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

Comment thread sdks/python/apache_beam/cli/sql.py Outdated
cmd = [java_bin, '-cp', jar_path, _MAIN_CLASS, *sqlline_args]
if debug:
print('+ ' + ' '.join(_sanitize_log_token(c) for c in cmd), file=sys.stderr)
return subprocess.run(cmd, check=False).returncode

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.

🟡 Medium: subprocess.run() catches KeyboardInterrupt on Ctrl-C and immediately calls process.kill() (SIGKILL) before re-raising KeyboardInterrupt. In an interactive BeamSqlLine session, pressing Ctrl-C sends SIGINT to the foreground process group; having Python SIGKILL the JVM prevents BeamSqlLine/JLine from cancelling the current SQL prompt line, skips JVM shutdown hooks that restore terminal settings, and prints an unhandled Python traceback.

Wait for the child process while ignoring KeyboardInterrupt in the parent (or return 130 if interrupted in non-interactive mode) so the JVM handles SIGINT directly:

  with subprocess.Popen(cmd) as proc:
    while True:
      try:
        return proc.wait()
      except KeyboardInterrupt:
        pass

if proc.returncode != 0 or not _is_valid_jar(built_jar):
if 'Could not find artifact org.apache.beam:' in details:
last_ln = _sanitize_log_token(details.splitlines()[-1])
raise SqlError(

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.

🟡 Medium: When Maven fails to resolve an artifact (even with -q --batch-mode), it appends [ERROR] To see the full stack trace... and [ERROR] [Help 1] http://cwiki.apache.org/... lines after the actual resolution error. Taking details.splitlines()[-1] reports the [Help 1] URL line rather than the line identifying which org.apache.beam artifact could not be found.

Select the matching line instead:

          match_ln = next(
              (ln for ln in reversed(details.splitlines())
               if 'Could not find artifact org.apache.beam:' in ln),
              details.splitlines()[-1])
          last_ln = _sanitize_log_token(match_ln)

Comment thread sdks/python/apache_beam/cli/main.py Outdated
_SQL_EPILOG = """\
examples:
beam sql
beam sql --io csv --io parquet

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.

This set of examples is not completely clear to me. What does beam sql do if you don't pass in a query? Similarly, what does beam sql --io csv --io parquet do? Are these valid on their own?

It would be good to have an example that shows reading from a CSV file, doing some filtering/aggregation, and writing to a parquet sink.

I also don't see that level of functionality tested (I was trying to use that to find an example) - could we add an E2E test that confirms you can run sql with a set of IOs?

Comment thread sdks/python/apache_beam/cli/main.py Outdated
beam sql
beam sql --io csv --io parquet
beam sql -e "SELECT 1 + 1 AS two;"
beam sql --runner dataflow --io google-cloud-platform

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 does --io google-cloud-platform do?

Comment thread sdks/python/apache_beam/cli/sql.py Outdated
file=sys.stderr)

java_home = env_home or os.path.dirname(
os.path.dirname(os.path.realpath(java_bin)))

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.

On macOS when JAVA_HOME isn't set, shutil.which('java') resolves to /usr/bin/java, which is an Apple launcher binary rather than a symlink. realpath stays /usr/bin/java, so java_home ends up as /usr—and when _build_shaded_jar exports JAVA_HOME=/usr into the subprocess env, /usr/bin/java tries to use /usr as the JDK root and fails to find a runtime (similar issue on Windows with javapath\java.exe shims).

Could we run java -XshowSettings:properties -version above and read java.home = ... from that output instead (falling back to realpath if it's missing)?

Comment thread sdks/python/apache_beam/cli/sql.py Outdated


# Same Maven Wrapper, Iceberg, GCS connector, and repository constants as
# `scripts/beam-sql.sh` on upstream master (#40958, #41090).

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.

Nit: since these versions and the POM dependency/shading rules (delta, iceberg, the Conscrypt exclusion, etc.) now live in both scripts/beam-sql.sh and sql.py, could we also add a quick comment in scripts/beam-sql.sh pointing here so future updates don't accidentally update one and miss the other?

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.14894% with 51 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.07%. Comparing base (d2e1eeb) to head (5316bba).
⚠️ Report is 65 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/cli/sql.py 88.61% 51 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41436      +/-   ##
============================================
+ Coverage     57.99%   58.07%   +0.08%     
  Complexity     2838     2838              
============================================
  Files          1210     1211       +1     
  Lines        173067   173569     +502     
  Branches       2329     2329              
============================================
+ Hits         100367   100805     +438     
- Misses        69987    70051      +64     
  Partials       2713     2713              
Flag Coverage Δ
python 80.67% <89.14%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants