Skip to content

Return rows of unbounded Beam SQL queries while the pipeline runs - #41315

Merged
ahmedabu98 merged 2 commits into
apache:masterfrom
ahmedabu98:sql-live-results
Nov 16, 2026
Merged

ahmedabu98 merged 2 commits into
apache:masterfrom
ahmedabu98:sql-live-results

Conversation

@ahmedabu98

Copy link
Copy Markdown
Contributor

Addresses #41313

A SELECT on a streaming (unbounded) source never shows any rows in the Beam SQL shell. The shell collects the rows in memory and only hands them over once the pipeline finishes. A streaming pipeline never finishes.

This PR hands the rows over while the pipeline runs. For an unbounded SELECT, ResultSet.next() returns each row as soon as the pipeline produces it. The shell already prints JDBC rows one at a time, so a query like this now prints rows as messages arrive on the topic:

CREATE EXTERNAL TABLE orders (id BIGINT, item VARCHAR, amount DOUBLE)
TYPE kafka
LOCATION 'localhost:9092/orders'
TBLPROPERTIES '{"format": "json"}';

SELECT * FROM orders WHERE amount > 100;

Canceling the statement (Ctrl+C in the shell) or closing the result set cancels the pipeline. If the pipeline fails, the query fails with the pipeline's error.

Each row also keeps its change kind (ValueKind). A follow-up PR adds a full-screen live view to the shell that shows it as +I, -U, +U or -D. The view plugs in through LiveResult.setViewer(...).

Bounded queries, LIMIT queries and INSERTs work as before. Like any SELECT in the shell, this needs the DirectRunner.

@github-actions github-actions Bot added java extensions sql iceberg Iceberg IO connector size/l L: 250-999 lines changed labels Nov 13, 2026

@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 introduces LiveResult and LiveRows to stream rows from unbounded Beam SQL queries running on DirectRunner without blocking until pipeline completion. The implementation is well-structured and cleanly integrated with BeamEnumerableConverter, though there are a few notable issues around Calcite's Enumerable.enumerator() delegation, failure handling on the watcher thread, and statement cancellation propagation.

🔍 General Feedback

  • LiveRows.enumerator() currently delegates to Linq4j.iterableEnumerator(this), which checks if (iterable instanceof Enumerable) and calls enumerator() again, leading to a StackOverflowError whenever enumerator() is invoked.
  • Pipeline failure handling in LiveResult.watch() should guard against Error throws (which DirectRunner rethrows directly) and non-throwing State.FAILED results so failed pipelines are not silently treated as normal stream completion.
  • LiveResult.viewer is stored in a process-wide static volatile field; if concurrent sessions/tests run in the same JVM, they could interfere with each other.

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

this.result = result;
}

@Override

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.

🟠 High: LiveRows extends AbstractEnumerable<Object> (which implements Enumerable<Object>). In Calcite's Linq4j.iterableEnumerator(Iterable), the first check is if (iterable instanceof Enumerable) { return ((Enumerable<T>) iterable).enumerator(); }. Passing this causes infinite recursion (StackOverflowError) whenever enumerator() is called on LiveRows. Pass this::iterator (or extend AbstractEnumerable2<Object>) so Linq4j wraps the Iterator instead of recursing back into enumerator().

Suggested change
@Override
return Linq4j.iterableEnumerator(this::iterator);

@Nullable State end = null;
try {
end = pipelineResult.waitUntilFinish();
} catch (RuntimeException e) {

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: DirectRunner's ExecutorServiceParallelExecutor.waitUntilFinish() rethrows Error subclasses (e.g., AssertionError, NoClassDefFoundError) directly without wrapping them in a RuntimeException. Because watch() only catches RuntimeException, an Error escapes the try block, sets state = State.UNKNOWN and counts down finished in finally while leaving failure = null. The consumer then sees isFinished() == true and getFailure() == null, silently treating a crashed pipeline as a normal end-of-stream. Additionally, if waitUntilFinish() returns State.FAILED without throwing, failure remains null. Catch Throwable (wrapping non-RuntimeException in a RuntimeException) and ensure failure is populated if end == State.FAILED.

void add(ValueKind kind, Row row) {
Change change = new Change(kind, row);
try {
while (!closed) {

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 Statement.cancel() is called while the caller is not blocked inside LiveIterator.hasNext() (for example, between ResultSet.next() calls), AvaticaResultSet.next() checks statement.cancelFlag.get() before calling cursor.next() and throws SQLException("Statement canceled") without ever entering LiveIterator.hasNext(). In that case LiveResult.close() is not triggered by hasNext(), and worker threads blocked in add() when the queue is full will stay blocked until the ResultSet is explicitly closed. Checking !cancelFlag.get() here (and/or monitoring cancelFlag in watch) avoids blocking pipeline workers after cancellation is requested.

Suggested change
while (!closed) {
while (!closed && !cancelFlag.get()) {

// A cancelled statement ends the rows.
while (next == null && !result.isCancelRequested()) {
// No rows come after the pipeline ends, so then an empty poll means there are no more.
boolean finished = result.isFinished();

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: When finished is already true and the buffer is empty, result.poll(100, TimeUnit.MILLISECONDS) still blocks for 100ms even though no further rows can be produced. Using a timeout of 0 when finished is true avoids adding a 100ms delay at the end of every bounded-completion or cancelled query.

Suggested change
boolean finished = result.isFinished();
next = result.poll(finished ? 0 : 100, TimeUnit.MILLISECONDS);

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.94737% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.81%. Comparing base (3b8d886) to head (075e2a9).
⚠️ Report is 48 commits behind head on master.

Files with missing lines Patch % Lines
...e/beam/sdk/extensions/sql/impl/rel/LiveResult.java 72.97% 14 Missing and 6 partials ⚠️
...tensions/sql/impl/rel/BeamEnumerableConverter.java 86.44% 6 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41315      +/-   ##
============================================
- Coverage     58.54%   57.81%   -0.74%     
- Complexity     2291     2730     +439     
============================================
  Files          1132     1205      +73     
  Lines        169864   172293    +2429     
  Branches       1487     2259     +772     
============================================
+ Hits          99454    99617     +163     
- Misses        67866    69986    +2120     
- Partials       2544     2690     +146     
Flag Coverage Δ
java 65.98% <78.94%> (-9.99%) ⬇️

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.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @chamikaramj for label iceberg.
Backup reviewer: Abacn (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).

@claudevdm claudevdm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is static viewer safe?

@ahmedabu98

Copy link
Copy Markdown
Contributor Author

Yeah should be safe. We're only going to set it through the SQL shell at startup (will come up in a follow-up PR). The shell runs one query at time.

@ahmedabu98
ahmedabu98 merged commit 6bcdbe0 into apache:master Nov 16, 2026
21 checks passed
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.

2 participants