Skip to content

fix: make Python plugin teardown asyncio-safe - #605

Merged
rapids-bot[bot] merged 4 commits into
NVIDIA:release/0.7from
willkill07:fix/relay-599-async-plugin-clear
Jul 31, 2026
Merged

fix: make Python plugin teardown asyncio-safe#605
rapids-bot[bot] merged 4 commits into
NVIDIA:release/0.7from
willkill07:fix/relay-599-async-plugin-clear

Conversation

@willkill07

@willkill07 willkill07 commented Jul 31, 2026

Copy link
Copy Markdown
Member

Overview

Prevent plugin.clear() from deadlocking a running Python asyncio loop when queued subscriber delivery depends on an event sanitizer coroutine.

  • I confirm this contribution is my own work, or I have the right to submit it under this project's license.
  • I searched existing issues and open pull requests, and this does not duplicate existing work.

Details

  • Add plugin.clear_async() and run native teardown on the Rust blocking worker pool so the Python event loop remains available to pending sanitizer callbacks.
  • Make synchronous plugin.clear() raise an actionable RuntimeError when called from a running event loop.
  • Route async plugin context-manager cleanup through clear_async() and update Python type stubs and documentation examples.
  • Add timeout-isolated regression coverage for a plugin-owned mark sanitizer and subscriber with undrained delivery.

Validation:

  • uv run pre-commit run --all-files: passed.
  • cargo clippy --workspace --all-targets -- -D warnings: passed.
  • just docs: passed.
  • Focused sanitizer, observability, adaptive, dynamic-host, and native binding tests: passed.
  • just test-python: 599 passed; 12 tests were blocked by an ignored local .nemo-relay/plugins.toml using unsupported observability config version 2.
  • just test-rust: 996 passed; 88 tests were blocked by the same ignored local configuration.

Where should the reviewer start?

Start with python/nemo_relay/plugin.py for the public lifecycle contract, then crates/python/src/py_plugin.rs for the non-blocking native bridge and python/tests/test_event_sanitizers.py for the deadlock regression.

Related Issues: (use one of the action keywords Closes / Fixes / Resolves / Relates to)

Summary by CodeRabbit

  • New Features

    • Added asynchronous plugin cleanup with await plugin.clear_async(), allowing teardown without blocking Python event loops.
    • Added an awaitable API for clearing global plugin configuration.
    • Async cleanup now reports teardown and cleanup errors to callers.
    • Plugin context managers perform asynchronous cleanup on exit.
  • Bug Fixes

    • Synchronous clear() rejects calls from running event loops and directs callers to the async alternative.
  • Documentation

    • Updated plugin configuration and graceful-shutdown examples to use asynchronous cleanup where appropriate.

Signed-off-by: Will Killian <wkillian@nvidia.com>
@willkill07
willkill07 requested review from a team as code owners July 31, 2026 18:01
@github-actions github-actions Bot added size:M PR is medium Bug issue describes bug; PR fixes bug lang:python PR changes/introduces Python code lang:rust PR changes/introduces Rust code labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

The PR adds coordinated asynchronous Python plugin cleanup backed by native teardown workers. Synchronous clear() now rejects calls from a running event loop. Context managers, tests, examples, and shutdown guidance use clear_async().

Changes

Async plugin cleanup

Layer / File(s) Summary
Native asynchronous cleanup binding
crates/python/src/py_plugin.rs, crates/python/tests/coverage/py_plugin_coverage_tests.rs, python/nemo_relay/_native.pyi
The native binding coordinates teardown completion, runs global cleanup on a dedicated thread, maps panics and spawn failures to Python errors, and verifies completion.
Python asynchronous cleanup lifecycle
python/nemo_relay/plugin.py, python/nemo_relay/plugin.pyi, python/tests/test_event_sanitizers.py, python/tests/test_adaptive.py, python/tests/test_dynamic_plugin_host.py, python/tests/test_observability_plugin.py, crates/python/tests/coverage/nemo_guardrails_coverage_tests.rs
The API adds clear_async(). clear() raises RuntimeError inside a running event loop. Context-manager teardown and cleanup tests await asynchronous completion.
Examples and shutdown guidance
docs/build-plugins/language-binding/*.mdx, docs/configure-plugins/adaptive/*.mdx, docs/configure-plugins/observability/*.mdx
Python examples use clear_async(). Shutdown guidance distinguishes synchronous and asyncio teardown and documents timed-out workers.

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

Sequence Diagram(s)

sequenceDiagram
  participant PythonCaller
  participant clear_async
  participant NativeBinding
  participant TeardownThread
  participant PluginConfiguration
  PythonCaller->>clear_async: await clear_async()
  clear_async->>NativeBinding: await clear_plugin_configuration_async()
  NativeBinding->>TeardownThread: start or join cleanup
  TeardownThread->>PluginConfiguration: clear configuration
  PluginConfiguration-->>TeardownThread: cleanup result
  TeardownThread-->>NativeBinding: completion or mapped error
  NativeBinding-->>clear_async: awaitable result
  clear_async-->>PythonCaller: cleanup completed
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title follows Conventional Commits format, uses an allowed lowercase type, stays under 72 characters, and clearly describes the change.
Description check ✅ Passed The description includes all required sections, explains the implementation and validation, identifies review starting points, and references RELAY-599.
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

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

@github-actions

Copy link
Copy Markdown

@willkill07 willkill07 self-assigned this Jul 31, 2026
Signed-off-by: Will Killian <wkillian@nvidia.com>
Comment thread crates/python/src/py_plugin.rs
@willkill07 willkill07 added this to the 0.7 milestone Jul 31, 2026
Signed-off-by: Will Killian <wkillian@nvidia.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/python/src/py_plugin.rs (1)

1042-1044: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Route synchronous clearing through PluginConfigurationClearState.

clear_plugin_configuration_py bypasses the shared state. The core lease prevents concurrent teardown, but a synchronous call during clear_async() returns a conflict instead of waiting. Start or join the shared clear and block for its completion with the GIL detached. Add a cross-thread test.

🤖 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 `@crates/python/src/py_plugin.rs` around lines 1042 - 1044, Update
clear_plugin_configuration_py to route synchronous clearing through
PluginConfigurationClearState by starting or joining the shared clear operation,
waiting for completion while the GIL is detached, and preserving conflict-free
behavior when clear_async() is in progress. Add a cross-thread test covering a
synchronous clear overlapping an asynchronous clear.
🤖 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.

Outside diff comments:
In `@crates/python/src/py_plugin.rs`:
- Around line 1042-1044: Update clear_plugin_configuration_py to route
synchronous clearing through PluginConfigurationClearState by starting or
joining the shared clear operation, waiting for completion while the GIL is
detached, and preserving conflict-free behavior when clear_async() is in
progress. Add a cross-thread test covering a synchronous clear overlapping an
asynchronous clear.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Enterprise

Run ID: a95095d6-a729-4e37-937e-3f5bdedc0b59

📥 Commits

Reviewing files that changed from the base of the PR and between 8982208 and 85d182f.

📒 Files selected for processing (2)
  • crates/python/src/py_plugin.rs
  • python/tests/test_event_sanitizers.py
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: Check / Run
  • GitHub Check: Preview docs
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{rs,py}

📄 CodeRabbit inference engine (AGENTS.md)

Follow binding naming conventions in Rust and Python: use snake_case.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
**/*.{rs,py,js,mjs,cjs,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{rs,py,js,mjs,cjs,ts,tsx}: Use Json = serde_json::Value in Rust-facing runtime APIs where the existing code expects JSON payloads.
Use Result<T> with FlowError in core runtime paths, and keep errors explicit and binding-appropriate at the wrapper layer.
Keep async behavior on the existing tokio-based model; bindings should preserve callback and future lifetimes rather than blocking or hiding async work unexpectedly.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
**/*.py

📄 CodeRabbit inference engine (CONTRIBUTING.md)

**/*.py: When changing the Python wrapper package, tests, or docs tooling, lint with Ruff (E, F, W, I), format with Ruff formatter (120-character lines, double quotes), and pass ty type checking.
Add the SPDX license header to all Python source files using the # comment form.

Files:

  • python/tests/test_event_sanitizers.py
**/*.{rs,py,go,js,ts,c,h}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Use language-appropriate naming conventions: Rust snake_case, C FFI exports prefixed nemo_relay_, Go PascalCase, Node.js camelCase, and Python snake_case.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
{crates/**/src/**/*.rs,python/**/*.py}

📄 CodeRabbit inference engine (.agents/skills/maintain-dynamic-plugins/SKILL.md)

Do not add tests under src; Rust tests belong in crate tests/ trees, and Python SDK tests belong under python/tests.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
python/tests/**/*.py

📄 CodeRabbit inference engine (.agents/skills/test-python-binding/SKILL.md)

python/tests/**/*.py: Pytest is used to run tests.
Do not add @pytest.mark.asyncio to any test; async tests are automatically detected and run by the async runner.
Do not add a -> None return type annotation to test functions.
When mocking a class, do not define a new class; use unittest.mock.MagicMock or unittest.mock.AsyncMock, with the spec constructor argument when necessary.
Name mocked classes with the mock prefix, not fake.
Prefer pytest fixtures over helper methods.
Do not repeat fixtures; if a fixture is needed in multiple test files, place it in a conftest.py file.
When creating a fixture, use @pytest.fixture(name="<fixture_name>"[, scope="<scope>"]) and define the fixture function as def <fixture_name>_fixture() -> <return_type>:; only specify scope when it is not function.
Prefer pytest.mark.parametrize over creating individual tests for different input types.

Files:

  • python/tests/test_event_sanitizers.py
**/*

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

**/*: Format changed files with the language-native formatter before the final lint/test pass.
If dynamic plugin behavior changed, use maintain-dynamic-plugins and include the native SDK, worker protocol, Python SDK, docs, packaging, and Codecov surfaces in the validation plan.
If code changes alter APIs, bindings, commands, paths, packaging behavior, observability/adaptive semantics, or documented best practices, update any dependent maintainer or consumer skills in the same branch.
During iteration, prefer uv run pre-commit run --files <changed files...>.
Before review or handoff, run uv run pre-commit run --all-files.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
**/*.{rs,py,go,js,ts}

📄 CodeRabbit inference engine (.agents/skills/validate-change/SKILL.md)

If a language surface changed, always run that language's test target even when Rust core did not change.

**/*.{rs,py,go,js,ts}: When observability configuration or lifecycle is exposed, keep FFI and Python, Go, and Node.js binding-native config objects and subscriber/exporter methods aligned in logical knobs and semantics.
Require every OpenTelemetry endpoint to have a type and nonblank destination; resolve header_env values at activation and reject missing, blank, or duplicate headers.
Concatenate layered ATOF sink, ATIF storage, and OpenTelemetry endpoint lists with higher-precedence entries first.
Preserve correct handling of mark events, start/end events, orphan cases, and span or trajectory fields derived from intended event data.
Run affected Rust tests and just test-rust when event fields change; run just test-python, just test-go, and just test-node when binding-native configuration or lifecycle changes.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
**/*.{rs,py,js,ts,tsx,go,java,kt,swift}

📄 CodeRabbit inference engine (.agents/skills/add-middleware/SKILL.md)

Add tests covering registration and duplicate names, deregistration and missing names, priority ordering, callback failure policy, scope-local inheritance and cleanup, event payload semantics, immutable mark and scope fields, and parity across affected bindings.

Files:

  • python/tests/test_event_sanitizers.py
  • crates/python/src/py_plugin.rs
**/*.{md,mdx,py,go,js,ts}

📄 CodeRabbit inference engine (.agents/skills/maintain-observability/SKILL.md)

Examples and documentation must use each exporter's documented flush/deregister order before shutdown.

Files:

  • python/tests/test_event_sanitizers.py
{crates/**/tests/**,python/tests/**,go/nemo_relay/**/*_test.go}

⚙️ CodeRabbit configuration file

{crates/**/tests/**,python/tests/**,go/nemo_relay/**/*_test.go}: Tests should cover the behavior promised by the changed API surface, including error paths and cross-request isolation where relevant.
Prefer assertions on lifecycle events, scope stacks, middleware ordering, and binding parity over shallow smoke tests.

Files:

  • python/tests/test_event_sanitizers.py
**/*.rs

📄 CodeRabbit inference engine (.agents/skills/prepare-pr/SKILL.md)

**/*.rs: Any Rust change must run just test-rust
Any Rust change must run cargo fmt --all
Any Rust change must run cargo clippy --workspace --all-targets -- -D warnings

**/*.rs: Run cargo fmt --all for all FFI work since it is Rust work
Run just test-rust to validate FFI changes
Run cargo clippy --workspace --all-targets -- -D warnings to enforce strict linting on FFI work

When Rust files changed as part of Go work, also run cargo fmt --all, just test-rust, and cargo clippy --workspace --all-targets -- -D warnings

**/*.rs: Run cargo fmt --all when Rust files are changed as part of Node work
Run cargo clippy --workspace --all-targets -- -D warnings when Rust files are changed as part of Node work
Run just test-rust when Rust files are changed as part of Node work

When changing the core Rust runtime or Rust-facing API surface, format Rust code with cargo fmt (rustfmt defaults), keep cargo clippy -- -D warnings clean, and satisfy cargo deny check per deny.toml.

**/*.rs: If any Rust code changed, always run just test-rust.
If any Rust code changed, also run cargo fmt --all.
If any Rust code changed, also run cargo clippy --workspace --all-targets -- -D warnings.
For Rust changes headed for review, run cargo fmt --all and cargo clippy --workspace --all-targets -- -D warnings even if relying on pre-commit.

Files:

  • crates/python/src/py_plugin.rs
**/*.{rs,go,js,ts}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Add the SPDX license header to all Rust, Go, JavaScript, and TypeScript source files using the corresponding // comment form.

Files:

  • crates/python/src/py_plugin.rs
crates/{python,ffi,node}/**/*

⚙️ CodeRabbit configuration file

crates/{python,ffi,node}/**/*: Treat binding changes as public API changes. Check for parity with the other language bindings, FFI ownership/lifetime safety,
callback error propagation, stable type conversion, and consistent async/stream semantics.
Flag changes that update one binding without corresponding tests or documentation for the same surface elsewhere.

Files:

  • crates/python/src/py_plugin.rs
🔇 Additional comments (6)
python/tests/test_event_sanitizers.py (3)

511-515: No diff content is shown for this range beyond the change summary ("replaced synchronous plugin cleanup with awaited plugin.clear_async()"). This matches the new API and the sync clear() RuntimeError-inside-a-running-loop change described elsewhere, so no concern to raise without the actual code.


549-549: No diff content is shown for this range beyond the change summary ("await plugin.clear_async() instead of calling synchronous plugin.clear()" in failure-rollback cleanup). Consistent with the new API; no concern to raise without the actual code.


8-10: LGTM!

Also applies to: 34-116

crates/python/src/py_plugin.rs (3)

6-10: LGTM!

Also applies to: 760-788, 795-798, 969-999, 1002-1004


1048-1057: 🩺 Stability & Availability

Verify whether Node.js binding needs equivalent non-blocking teardown.

This adds a Python-specific clear_plugin_configuration_async_py to avoid blocking a running asyncio event loop during native teardown. Node.js also runs a single-threaded event loop and could hit the same deadlock class if its plugin binding still exposes only a blocking clear(). The current stack outline scopes this cohort to Python files only. Confirm whether the Node.js binding already handles this, or whether a follow-up is needed for parity.

As per path instructions, "Flag changes that update one binding without corresponding tests or documentation for the same surface elsewhere."

Source: Path instructions


885-966: 🩺 Stability & Availability

No duplicate native teardown occurs across these paths.

PLUGIN_MUTATION_OWNER prevents clear_plugin_configuration() from starting while a dynamic host owns the configuration, and the host retains its lease until clear_inner() completes. Initialization also requires the same ownership state. The reset cannot replace an active clear state through the described sequence.

			> Likely an incorrect or invalid review comment.

@willkill07

Copy link
Copy Markdown
Member Author

/merge

@rapids-bot
rapids-bot Bot merged commit 2dbc539 into NVIDIA:release/0.7 Jul 31, 2026
42 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug issue describes bug; PR fixes bug lang:python PR changes/introduces Python code lang:rust PR changes/introduces Rust code size:M PR is medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants