Repository navigation
feat(statement): add directResults execute_direct (additive); CLOSED as terminal success - #140
Conversation
…JDBC model
`Statement::execute_direct()` runs ExecuteStatement with a bounded server-side
inline wait (omits `wait_timeout` so the server applies its ~10s default AND
auto-closes on success) and returns WITHOUT the internal poll loop:
- `DirectStatement::Completed(ExecutedStatement)` when the statement finished
within the inline wait — result stream materialised inline, no extra
GetStatementResult round-trip (identical to `execute()`'s fast path);
- `DirectStatement::Running(ExecutedAsyncStatement)` when it did not — a
poll/cancel handle (identical to `submit()`'s return) the caller drives.
This is the directResults shape that Thrift / JDBC / Python `use_sea` use: fast
queries come back terminal+inline, slow ones come back as a running handle. It
gives consumers three properties the plain blocking `execute()` can't all have
at once:
- fire-and-forget DDL/DML commits (the server runs it inline during the POST,
so a CREATE/INSERT with no fetch still lands);
- `close()` is a clean release on a server-owned statement — no client-side
drive-to-terminal ("close-drives");
- a long query stays cancellable via the running handle's statement id, which
the POST response publishes (no mid-execute observer race).
Additive: `execute()` and `submit()` are unchanged, so existing consumers are
untouched. New transport method `execute_statement_direct` (call_execute_api +
conditional reader, no `wait_for_completion`); `DirectOutcome` transport enum;
`DirectStatement` re-exported from the crate root. Exposed on both bindings:
napi `Connection.executeStatementDirect` (Either<Statement, AsyncStatement>)
and pyo3 `Statement.execute_direct` (ExecutedStatement | ExecutedAsyncStatement).
Tests: cargo +stable fmt --all --check, cargo clippy --all-targets -D warnings
clean; cargo test --lib 620 passed. Validated e2e via the Node and Python
bindings against a live warehouse (CREATE commits, mid-run cancel, no
close-drive, error-at-execute).
Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
…rror
`terminal_outcome` rejected a `CLOSED` response with no result payload as
`invalid_state("Statement was closed")` — stricter than JDBC and inconsistent
with this crate's own `create_reader` (which already builds an `EmptyReader`
for an empty `CLOSED`). JDBC's `DatabricksSdkClient` treats `SUCCEEDED` and
`CLOSED` identically as success (only other states hit `handleFailedExecution`);
an empty `CLOSED` yields an empty result set, not an error. Make `CLOSED ->
Done` unconditional.
Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
|
|
||
| /// directResults execute — the Thrift/JDBC model. | ||
| /// | ||
| /// Sends ExecuteStatement with a bounded server-side inline wait |
There was a problem hiding this comment.
[HIGH CONFIDENCE — 7 reviewers; verified against head SHA]
This doc comment (and the inline comment at mutable.rs:427-428, plus napi/src/connection.rs:374 and src/client/transport.rs:265) states the direct path sends wait_timeout=10s, on_wait_timeout=CONTINUE. The implementation sends neither — execute_direct → prepare_for_dispatch(None) → resolve_wait_timeout(None, None) returns (None, None), so both fields are omitted and the server applies its ~10s default and auto-closes on success (state=CLOSED). Only sea.rs:793 ("OMIT wait_timeout") and pyo3/src/statement.rs:244-246 are correct.
This isn't cosmetic: the OMIT-vs-10s distinction is the close() contract of the Completed arm — omission is what makes close() a no-op and fire-and-forget DDL work. The inline comment at :427-428 ("execute_statement_direct forces wait_timeout=10s…") is doubly wrong — the transport forces nothing. A maintainer who "fixes" the transport to match these docs would silently break the fire-and-forget guarantee.
Recommend aligning all four wrong sites to the pyo3/sea wording.
| self.invalidate_prior().await; | ||
| // `prepare_for_dispatch(None)` here; `execute_statement_direct` | ||
| // forces `wait_timeout=10s` + `on_wait_timeout=CONTINUE` itself. | ||
| let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; |
There was a problem hiding this comment.
[HIGH CONFIDENCE — 3 reviewers; verified against head SHA]
prepare_for_dispatch(None) routes to resolve_wait_timeout(None, spec.query_timeout_secs). When query_timeout_secs = Some(secs) this returns (Some("{secs}s"), Some("CANCEL")) (verified at mutable.rs:118-120). So a caller who sets query_timeout_secs on executeStatementDirect gets: server holds for {secs}, then CANCELs the statement → eager error — not the documented DirectStatement::Running poll/cancel handle. For query_timeout_secs < ~10s the Running arm becomes unreachable.
This may be intended (a hard timeout is a hard timeout), but it directly contradicts the "slow queries come back as a cancellable Running handle" contract stated in every direct-path doc-comment, and it is undocumented. Please document the query_timeout_secs→CANCEL interaction and that it suppresses the Running arm.
| @@ -329,21 +330,17 @@ impl SeaRestTransport { | |||
| )) | |||
| } | |||
| StatementState::Closed => { | |||
There was a problem hiding this comment.
[verified against head SHA]
Making CLOSED-no-data return StatementOutcome::Done is reachable by all three terminal_outcome callers — including the pre-existing sync execute() and fetch_completed_result paths, not just the new direct path. Several public-API reachability contracts still assert the old behavior and are now false:
src/statement/executed.rs:181-183, 205-206, 222, 236— "the kernel returnsErr… onClosed-no-data".num_modified_rows/display_message/diagnostic_info/error_details_jsonare now reachable on a Closed-no-data handle.napi/src/statement.rs:250-254— same false claim.- The
terminal_outcomemethod doc atsea.rs:263-265still listsCLOSED-no-dataas producing an error (the enum-level doc at:40-46was updated; this one was missed).
Separately: this is a behavior change to shipped execute()/fetch_completed_result paths riding in on an "additive" PR (an empty CLOSED that previously errored now yields an empty result set everywhere). Worth an explicit callout in the PR/release notes. The change itself is a sound consistency fix (it makes the decoder agree with create_reader, which already treated Closed == Succeeded) — only the stale docs need correcting.
| &self, | ||
| sql: String, | ||
| mut options: Option<ExecuteOptions>, | ||
| ) -> napi::Result<napi::Either<Statement, AsyncStatement>> { |
There was a problem hiding this comment.
[MODERATE CONFIDENCE — 2 reviewers]
The kernel models the union correctly (DirectStatement::{Completed, Running}, exhaustively matchable). Both bindings throw the tag away: this napi method returns Either<Statement, AsyncStatement> (opaque #[napi] classes with no discriminant — TS cannot narrow the union), and pyo3 returns untyped Bound<PyAny>. The only discrimination mechanism is probing for awaitResult/await_result.
Verified sound today (those methods exist only on the async arm), but soundness rests on an unenforced invariant: the day someone adds an awaitResult-named method (or shim) to Statement, every consumer silently misroutes — and since the Running arm lacks fetchNextBatch, mis-discrimination yields a runtime TypeError, not a typed error. The consumer (databricks-sql-nodejs#426) already needs an as unknown as double-cast to defeat the type checker, which corroborates the gap.
Suggestion: add an explicit kind/boolean discriminant per arm so TS can narrow and Python can branch safely; at minimum document the feature-detect as a load-bearing contract and add a kernel test asserting Statement never gains an awaitResult/await_result member.
| // a concurrent `StatementCanceller::cancel()` (the Running arm) can | ||
| // target the still-running query immediately, no mid-execute observer | ||
| // race (the id is known from this POST response). | ||
| if let Some(observer) = params.inflight_id_observer.as_ref() { |
There was a problem hiding this comment.
[LOW — maintainability, conf 85]
This observer-publish block is character-for-character identical to sea.rs:498-502 in execute_and_read, and the Done-arm reader-materialisation below (create_reader → on-error close_orphaned_statement → build ExecuteResult) duplicates sea.rs:512-544. The orphan-close-on-create_reader-failure invariant now lives in two places and can drift.
Suggestion: extract a fn publish_inflight_id(params, id) and an async fn materialise_result(&self, r, statement_id, phase) helper, called by both execute_and_read and the Done arm here. (Also, minor: the bookkeeping triple last_statement_id/last_valid/last_closed is now repeated 4× in mutable.rs — a small track_executed helper would collapse it.)
| StatementOutcome::NotReady(r) => Ok(DirectOutcome::Running(r)), | ||
| // Inline terminal failure/cancel → surface it (close the orphan). | ||
| StatementOutcome::Err(e) => { | ||
| self.close_orphaned_statement(&statement_id, "execute_statement_direct") |
There was a problem hiding this comment.
[LOW — devils-advocate, conf 80]
On StatementOutcome::Err, the transport has already published the id to the shared slot (:813-817) and then calls close_orphaned_statement here. Back in Statement::execute_direct, the ? on execute_statement_direct().await? (mutable.rs:442) propagates the error without reaching guard.defuse() (defuse only runs inside the Completed/Running match arms). So MidExecuteCancelGuard::drop reads the now-populated slot and spawns a second RPC — cancel_statement — against a statement that is already terminal and just got closed.
It's idempotent and harmless, but it's an avoidable extra round-trip on every inline failure. Defusing the guard before returning on the transport-error path (or not publishing the observer slot on the Err arm) would remove it.
Code Review Squad — 9/9 reviewers, merge-safety score 82/100 (MODERATE RISK)Summary: 0 Critical/High findings; 8 Medium/Low findings covering doc/contract/test-coverage gaps. The mechanism is sound; all findings are actionable and cheap to fix. Out-of-line findingsF4 — Zero kernel-crate test coverage for the new paths and the flipped CLOSED behavior[Severity: Medium] [HIGH CONFIDENCE — 2 reviewers] 333 lines of new production logic ship with zero new assertions — the only test edits are two The wiremock harness already exists ( F6 — Eager-at-execute error surfacing is undocumented at both binding boundaries[Severity: Low] [LOW — agent-compat, conf 82] A query that reaches FAILED/CANCELLED within the inline wait is surfaced as a thrown/raised error from the execute call itself (correct: |
… correct docs
Behavioral fix (verified via debug-log trace against a live warehouse):
- `execute_direct`: on an inline terminal failure, the transport already closes
the orphaned statement, but the `?` propagated the error WITHOUT defusing the
`MidExecuteCancelGuard`, so its `Drop` fired a SECOND, redundant
`CancelStatement` against the just-closed statement. Now defuse on the error
path. Validated: inline error previously logged Closing/Closed + Canceling/
Canceled (2 RPCs); now logs only Closing/Closed (1 RPC).
Doc corrections (no behavior change):
- The direct path sends NO `wait_timeout` field (server default ~10s + auto-close
on success); the docs claiming `wait_timeout=10s, on_wait_timeout=CONTINUE`
were wrong. Fixed in `mutable.rs` (doc + inline), `napi/connection.rs`,
`transport.rs`. The OMIT (vs explicit 10s) is what makes the Completed arm's
`close()` a no-op.
- Documented the `query_timeout_secs` interaction: it sends `wait_timeout={N}s`
+ CANCEL, so a timeout shorter than the query yields an eager Cancelled error,
NOT a `Running` handle (and <5s is rejected by the SEA wire as HTTP 400).
Verified live: `queryTimeout=5` cancels at ~5.3s.
- CLOSED-as-terminal-success reaches ALL `terminal_outcome` callers (sync
`execute()` + `fetch_completed_result`), not just the direct path. Corrected
the stale "Closed-no-data returns Err" contracts in `executed.rs`,
`napi/statement.rs`, and the `terminal_outcome` method doc.
- Documented the load-bearing `awaitResult` feature-detect contract on
`executeStatementDirect` (`Statement` must never gain an `awaitResult` member).
Tests: clippy clean (lib+napi+pyo3); cargo test --lib 620; v0_execute_wiremock 17.
Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
|
Addressed all findings in
Tests: clippy clean (lib+napi+pyo3); |
…eal timeout
`query_timeout_secs` mapped the JDBC-style `setQueryTimeout` onto the SEA
`wait_timeout` field via `resolve_wait_timeout` (`{N}s` + on_wait_timeout=CANCEL).
That is incorrect: `wait_timeout` is the server's inline-HOLD window (how long the
ExecuteStatement POST blocks for results, capped 5–50s), NOT a statement-execution
timeout. Mapping there silently caps the timeout at 50s, rejects <5s with HTTP 400,
and conflates the inline wait with execution. A real per-statement timeout is the
`STATEMENT_TIMEOUT` SQL conf, not this field.
It was reachable only through the napi `ExecuteOptions.query_timeout_secs` (pyo3
never exposed it; Python `use_kernel` has no query-timeout wiring at all), and the
Node driver now treats `queryTimeout` as a no-op — so the field had no correct
consumer. Remove it end to end:
- `StatementSpec`: drop the `query_timeout_secs` field + setter + tests.
- `resolve_wait_timeout`: drop the `spec_query_timeout_secs` param and the CANCEL
branch; the sync path now always omits `wait_timeout` (server default + auto-close).
- napi `ExecuteOptions`: drop the `query_timeout_secs` field; `build_statement`
loses the param; all three call sites stop decoding/threading it.
- Doc cleanups across `mutable.rs` / `connection.rs` / `spec.rs`.
Tests: clippy clean (lib+napi+pyo3); cargo test --lib 619; v0_execute_wiremock 17.
e2e: `queryTimeout` is now ignored (a 5s timeout on a ~34s query no longer cancels).
Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
The root `cargo fmt --all` does not reach the napi sub-crate; run fmt there so the call sites left after dropping the query_timeout_secs arg are formatted. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
The directResults primitive was mirrored onto pyo3 for binding parity, but no consumer uses it: Python `use_kernel` runs the blocking `execute()` (the additive design means Python needs no change), and there is no pyo3 test for it. Only Node consumes directResults (via the napi `executeStatementDirect`), so the pyo3 surface is dead. Remove `Statement.execute_direct` and the now-unused `DirectStatement as KDirectStatement` import. Clean removal — pyo3 `ExecutedStatement` is still constructed by the unchanged blocking `execute()` and `ExecutedAsyncStatement` by `submit()`, so nothing is orphaned. pyo3 clippy clean; Python use_kernel e2e (CREATE / cheap-close / mid-run cancel) unaffected. The kernel `Statement::execute_direct` and napi `executeStatementDirect` are untouched. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
gopalldb
left a comment
There was a problem hiding this comment.
Lets add e2e tests on different usage of direct execute interface, okay to separate from this PR
…removal Add NEXT_CHANGELOG entries (Rust crate + napi binding) for this PR, per the changelog system merged from main (#138). pyo3 has no entry (untouched). Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
|
Thanks @gopalldb! Agreed — I'll add dedicated e2e coverage for the direct-execute interface as a follow-up PR (you OK'd separating it), landing in
Most of these are already validated ad-hoc against a live warehouse during this PR (Node + Python e2e); the follow-up will codify them as kernel (Also: rebased |
Per @gopalldb's review request, add live e2e coverage for `execute_direct` to the `#[ignore]` `v0_execute_e2e` suite — one test per distinct usage: - `execute_direct_completed_returns_inline_result` — Completed (fast) arm: result materialised inline, no extra fetch. - `execute_direct_empty_result_is_not_an_error` — empty/CLOSED-no-data → empty result set, not an error (JDBC parity). - `execute_direct_inline_failure_surfaces_eagerly` — analysis error surfaces as `Err(SqlError)` from execute_direct (eager), matching Python use_kernel. - `execute_direct_running_handle_is_cancellable` — Running arm: a 40B-row scan returns a live handle; cancel() → await_result surfaces `Cancelled`. - `execute_direct_running_await_result_completes` — Running arm driven to a successful terminal result via await_result. All 5 pass against a live warehouse (40s; the two Running tests run a 40B scan). clippy --all-targets clean. Co-authored-by: Isaac Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
|
Update: added the direct-execute e2e tests to this PR (
All 5 pass against a live warehouse (40s). Thanks for the nudge — good to have these codified. |
What
Additive directResults support, plus a JDBC-parity fix. Two commits:
feat(statement): add execute_direct— addsStatement::execute_direct()(the Thrift/JDBC directResults model) alongside the existingexecute(), which is left completely unchanged.execute_direct()POSTs with the server inline wait and returns without the internal poll loop:DirectStatement::Completed(ExecutedStatement)(finished within the wait, result attached) orDirectStatement::Running(ExecutedAsyncStatement)(a poll/cancel handle).execute_statement_direct(call_execute_api+ conditional reader, nowait_for_completion) +DirectOutcome. Exposed on both bindings: napiConnection.executeStatementDirect(Either<Statement, AsyncStatement>), pyo3Statement.execute_direct.fix(client): treat CLOSED as terminal success (JDBC parity)—terminal_outcomenow treatsCLOSEDas success unconditionally (an emptyCLOSED→ empty result set), matching JDBC'sDatabricksSdkClient(treatsSUCCEEDEDandCLOSEDidentically) and this crate's owncreate_reader.Why this exists — the single consumer that needs it is Node
Mid-run cancellation needs a handle to the running statement during the run. That requirement is Node-shaped:
op.cancel(), andopis the return value ofexecuteStatement. The blockingexecute()resolves only at completion, so the handle would arrive too late to cancel.execute_direct()returns the handle after the inline wait, while the statement is still running, so the event loop holds a cancel point mid-run. This is the reasonexecute_directexists.use_kerneldoes NOT need it. Its cancel lives on the cursor (cursor.cancel()), backed by aStatementCancellerregistered beforeexecute()and fired from another thread while the blockingexecute()runs. So Python keeps plain blockingexecute()— no change.Why additive (vs folding
execute())execute_direct() + await_result()is functionally "execute then poll to done", butexecute()(wait_for_completion) andawait_result()are distinct poll loops (different error envelopes, a drop-cancel guard, status caching) — equivalent, not identical. Foldingexecute()into directResults would change its return type and force migrating ~50 kernel tests + the Python driver, for no functional gain. Keepingexecute()untouched means:use_kernelneeds no change (verified e2e against this kernel);execute_direct.Consumers
executeStatementDirect).use_kernel: no change — keeps blockingexecute().Supersedes #136 (the in-place fold, which introduced
execute_to_completion+ ~50-test churn).Testing — CI green
cargo test), Clippy, Formatting, DCO, Security Scan, Integration tests: pass.This pull request and its description were written by Isaac.