Skip to content

perf(core-py): release the GIL while blocking on the tokio runtime - #2485

Merged
goldmedal merged 2 commits into
Canner:mainfrom
ttw225:perf/core-py-release-gil-during-block-on
Jul 14, 2026
Merged

perf(core-py): release the GIL while blocking on the tokio runtime#2485
goldmedal merged 2 commits into
Canner:mainfrom
ttw225:perf/core-py-release-gil-during-block-on

Conversation

@ttw225

@ttw225 ttw225 commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Summary

Release the Python GIL while PySessionContext waits on Tokio
Runtime::block_on, allowing calls on different SessionContext
instances to run concurrently.

This covers all 13 Python-reachable block_on sites, including
construction, SQL transformation, query execution, table registration,
dry runs, MDL loading, and function discovery.

Problem

Every blocking SessionContext call previously held the GIL for the
entire planning or execution operation. Python threads therefore
serialized even when they used independent contexts and independent
Tokio runtimes.

This also prevented an asyncio event loop from progressing while a
synchronous Wren call was offloaded to a worker thread: the worker still
held the GIL until the call completed.

Implementation

Each blocking operation now runs inside Python::detach.

Python-borrowed arguments such as SQL, function names, and paths are
converted to Rust-owned values before entering the detached closure.
Session properties are also converted eagerly during construction, and
the futures do not call back into Python.

Releasing the GIL exposed a pre-existing same-context catalog race.
transform_sql_with_ctx re-applies the MDL catalog to shared context
state, so concurrent calls could observe a partially registered catalog.

A per-context call_lock preserves the previous ordering for calls on
the same context. The lock is acquired only after releasing the GIL to
avoid a lock/GIL deadlock. Calls using different contexts can run in
parallel.

list_tables does not use block_on, but it reads the same catalog
state and therefore participates in the same locking protocol.

The unused Clone implementation is removed because cloned wrappers
could share catalog and lock state while later diverging in their
ctx, exec_ctx, and mdl fields.

Behavioral note

Methods taking &mut self, currently load_mdl, may now return a PyO3
borrow error when called concurrently with another in-flight operation
on the same object. Previously such calls implicitly waited for the GIL.

Same-context engine calls otherwise retain their previous serialized
ordering.

Benchmark

Release build on an Apple M5 Pro with 18 cores. Each thread used its own
SessionContext and performed 200 transform_sql calls. Measurements
were collected with Python 3.14 using the abi3-py311 wheel.

Threads Before calls/s Before scaling After calls/s After scaling
1 956 1.00x 953 1.00x
2 987 1.03x 1,070 1.12x
4 980 1.03x 1,721 1.80x
8 984 1.03x 3,142 3.30x
16 991 1.04x 5,142 5.39x

Single-thread throughput remained effectively unchanged (956 versus
953 calls/s). At 16 threads, throughput improved from 991 to 5,142
calls/s, a 5.19x improvement at the same concurrency level.

Scaling remains sublinear because every context currently owns a
multi-thread Tokio runtime, which oversubscribes the machine at higher
thread counts. Sharing one process-wide runtime is planned as a
follow-up. I plan to follow up with a PR for this.

Tests

  • Added a concurrent-calls smoke test using separate contexts.
  • Added a shared-context mode covering mixed methods and catalog access.
  • The test checks correctness, crashes, and deadlocks without timing
    assertions.

Validation:

  • cargo test: 37 passed
  • cargo clippy --all-targets --all-features -- -D warnings
  • pytest: 34 passed

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Improved thread-safety for Python session operations by serializing blocking runtime calls, reducing race conditions during SQL transformation, querying, table registration, and semantic-layer loading.
    • Improved Python responsiveness by releasing the interpreter lock while engine work runs.
  • Tests

    • Added concurrent coverage for transform_sql across threads (both separate and shared session contexts).
    • Updated an expected SQL rewrite output to match the latest escaping/quoting behavior.

@github-actions github-actions Bot added python Pull requests that update Python code core labels Jul 12, 2026
@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: be76cb41-4021-4fe7-a02b-3dadd2415ca1

📥 Commits

Reviewing files that changed from the base of the PR and between 8d605a0 and b7d0ac1.

📒 Files selected for processing (2)
  • core/wren-core-py/src/context.rs
  • core/wren-core-py/tests/test_modeling_core.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • core/wren-core-py/tests/test_modeling_core.py
  • core/wren-core-py/src/context.rs

Walkthrough

PySessionContext now serializes blocking runtime work with a per-context mutex while releasing the Python GIL. Python-exposed methods accept a Python token, detach runtime operations, and concurrency tests cover shared and separate contexts.

Changes

Concurrent engine calls

Layer / File(s) Summary
Context locking contract
core/wren-core-py/src/context.rs
Adds and initializes call_lock, removes Clone, and centralizes poisoned-mutex handling.
Detached runtime operations
core/wren-core-py/src/context.rs
Updates context creation, SQL operations, registration, lookups, MDL loading, and function registration to detach blocking work and acquire the call lock.
Concurrency regression coverage
core/wren-core-py/tests/test_modeling_core.py
Adds threaded shared-context and separate-context coverage and updates the RLAC SQL expectation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Python
  participant PySessionContext
  participant CallLock
  participant Runtime
  Python->>PySessionContext: invoke runtime method
  PySessionContext->>Python: detach blocking work
  PySessionContext->>CallLock: acquire per-context mutex
  PySessionContext->>Runtime: execute runtime operation
  Runtime-->>PySessionContext: return result
  PySessionContext-->>Python: return result
Loading

Poem

A rabbit hops where threads align,
Locks guard the calls in tidy time.
The GIL steps back, the runtimes run,
Shared contexts greet the rising sun.
SQL blooms safely, line by line.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: releasing the GIL around blocking Tokio runtime calls for performance and concurrency.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

🧹 Nitpick comments (1)
core/wren-core-py/src/context.rs (1)

371-400: 🚀 Performance & Scalability | 🔵 Trivial

Long-running queries serialize the whole context.

lock_calls() is held for the entire sql().await + collect().await, so any concurrent transform_sql, list_tables, or dry_run on the same SessionContext blocks until this query finishes. This is correct given the shared-catalog re-registration invariant, but for read-heavy or long-running query workloads consider routing heavy query calls through a dedicated context (or documenting this ordering guarantee) so a single slow query doesn't stall lightweight metadata calls on the same context.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@core/wren-core-py/src/context.rs` around lines 371 - 400, Document the
ordering guarantee in query and related SessionContext operations, or route
heavy query execution through a dedicated context so sql().await and
collect().await do not block lightweight transform_sql, list_tables, and dry_run
calls. Preserve the shared-catalog re-registration invariant when choosing the
implementation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@core/wren-core-py/src/context.rs`:
- Around line 371-400: Document the ordering guarantee in query and related
SessionContext operations, or route heavy query execution through a dedicated
context so sql().await and collect().await do not block lightweight
transform_sql, list_tables, and dry_run calls. Preserve the shared-catalog
re-registration invariant when choosing the implementation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ec67f681-9631-4181-ae10-0ac406a834d0

📥 Commits

Reviewing files that changed from the base of the PR and between bdaefa9 and abcf935.

📒 Files selected for processing (2)
  • core/wren-core-py/src/context.rs
  • core/wren-core-py/tests/test_modeling_core.py

@goldmedal

Copy link
Copy Markdown
Collaborator

The shared CI failure here (maturin failedcannot update the lock file core/wren-core-py/Cargo.lock because --locked was passed) came from the Rust core 0.2.0 bump in #2467 leaving core/wren-core-py/Cargo.lock out of sync. That's now fixed on main by #2478 — please rebase onto latest main to pick up the lockfile fix and turn CI green. 🙏

ttw225 added 2 commits July 13, 2026 21:00
Two modes: separate contexts per thread, and one shared context with
mixed methods. A barrier forces the threads to overlap. The
shared-context mode catches the same-context catalog race if the
per-context call lock is ever removed while the GIL is released.
Correctness-only by design - performance evidence lives in the PR
benchmark, not in CI.
Every blocking call in PySessionContext (transform_sql, query,
register_*, dry_run, load_mdl, and the constructor) held the GIL for
the whole planning/execution call, so concurrent calls from Python
threads serialized: 4-thread throughput scaled at 1.04x on a 16-core
machine, and any embedding asyncio application froze entirely while a
call was in flight.

Wrap each runtime.block_on in Python::detach. Python-borrowed
arguments are copied to owned values before entering the detached
closure, so no GIL-dependent data crosses the boundary. The futures
never call back into Python (session properties are converted eagerly
at construction; UDFs are ByPass* stubs), so releasing the GIL cannot
deadlock.

Releasing the GIL also removes the accidental serialization that hid a
real race: transform_sql re-applies the MDL catalog onto the context's
shared catalog list on every call, so two concurrent calls on the same
context could observe each other's half-registered catalogs (planning
failed with 'table not found'). Preserve the previous per-context
ordering with an internal call lock, taken only while detached; calls
on different contexts now run in parallel. list_tables has no block_on
but reads the same shared catalog list, so it takes the lock too. The
unused Clone derive is removed so a Rust clone can't silently share
the lock and catalog state while diverging on ctx/exec_ctx/mdl.

Behavior note: methods that take &mut self (load_mdl) can now observe
PyO3's borrow error if called concurrently with an in-flight call on
the same object, instead of silently waiting for the GIL - a loud
failure rather than an implicit queue.
@ttw225
ttw225 force-pushed the perf/core-py-release-gil-during-block-on branch from 8d605a0 to b7d0ac1 Compare July 13, 2026 13:00
@ttw225

ttw225 commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

Related core fix: #2495

While validating this PR's same-context concurrency path, I traced the
underlying catalog race to apply_wren_on_ctx sharing and mutating the
base context's top-level catalog list. #2495 gives each
apply call a private catalog-list snapshot.

This PR keeps the per-context call_lock for now. Removing it and adding
same-context throughput measurements will be a separate follow-up after
both PRs land.

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

Thanks @ttw225, nice improvement 👍. It makes Wren efficient in concurrent cases.

@goldmedal
goldmedal merged commit ac499d7 into Canner:main Jul 14, 2026
11 checks passed
@ttw225
ttw225 deleted the perf/core-py-release-gil-during-block-on branch July 14, 2026 05:40
@ttw225

ttw225 commented Jul 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for taking the time to review and merge this. Really appreciate it!

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

Labels

core python Pull requests that update Python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants