Skip to content

Track LangChain Runnable callbacks - #2100

Merged
rapids-bot[bot] merged 1 commit into
NVIDIA:developfrom
WilliamK112:codex/langchain-chain-callback-1787
Jul 8, 2026
Merged

Track LangChain Runnable callbacks#2100
rapids-bot[bot] merged 1 commit into
NVIDIA:developfrom
WilliamK112:codex/langchain-chain-callback-1787

Conversation

@WilliamK112

@WilliamK112 WilliamK112 commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add LangChain on_chain_start / on_chain_end handling in LangchainProfilerHandler
  • emit paired FUNCTION_START / FUNCTION_END intermediate steps for base Runnable/chain invocations
  • preserve run id, runnable name, tags, inputs, outputs, and span timing metadata
  • clear per-run chain state on normal completion and chain errors
  • add regression coverage for paired chain callback events, default metadata/tags, and cleanup behavior

Closes #1787

Validation

  • PYTHONUTF8=1 uv run --extra langchain --extra test --group dev pytest packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py -q (11 passed)
  • PYTHONUTF8=1 uv run --extra langchain --extra test --group dev pytest packages/nvidia_nat_langchain/tests -q (684 passed, 13 skipped)
  • PYTHONUTF8=1 uv run --extra langchain --extra test --group dev yapf --diff --style ./pyproject.toml packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
  • PYTHONUTF8=1 uv run --extra langchain --extra test --group dev ruff check packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
  • PYTHONUTF8=1 uv run --extra langchain --extra test --group dev pre-commit run --files packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
  • git diff --check origin/develop..HEAD

Summary by CodeRabbit

  • New Features

    • Enhanced LangChain callback tracking to emit dedicated chain lifecycle events for start and end, including consistent run identifiers, names, tags, and attached input/output details.
    • Added improved chain naming derived from available serialized fields with sensible fallbacks.
  • Bug Fixes

    • Ensure chain-specific internal state is cleared after both successful completion and error paths to prevent stale data.
  • Tests

    • Expanded the LangChain callback handler test suite with new coverage for event order, payload/metadata propagation, timestamp consistency, and state cleanup on error.

@WilliamK112
WilliamK112 requested a review from a team as a code owner July 2, 2026 04:53
@copy-pr-bot

copy-pr-bot Bot commented Jul 2, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: c411e066-4f9a-469e-b2f3-b3c8502de3cd

📥 Commits

Reviewing files that changed from the base of the PR and between 7897eec and 97a44de.

📒 Files selected for processing (2)
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py
  • packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py

Walkthrough

Adds chain callback handling for LangChain Runnable invocations, including run-name extraction, per-run input/name tracking, start/end event emission, and cleanup on end or error. Adds async tests for success and error paths.

Changes

Chain callback tracking

Layer / File(s) Summary
Run name extraction and state initialization
packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py
Adds _extract_run_name and initializes per-run maps for chain inputs and derived chain names.
Chain start/end callback implementations
packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py
Adds on_chain_start, on_chain_end, a shared state-clear helper, and error cleanup for runnable callbacks.
Test coverage for chain callback events
packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
Adds async tests covering event order, payload mapping, timestamps, and cleanup after end and error.

Estimated code review effort: 2 (Simple) | ~15 minutes

Related issues: #1787
Suggested labels: enhancement, langchain
Suggested reviewers: willkill07, mdemoret-nv

🚥 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 is concise, imperative, and accurately summarizes the new LangChain Runnable callback tracking.
Linked Issues check ✅ Passed The PR implements on_chain_start/on_chain_end support for Runnable instrumentation and state cleanup as requested in #1787.
Out of Scope Changes check ✅ Passed The code and tests stay focused on Runnable callback tracking, metadata propagation, and cleanup without unrelated changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@WilliamK112
WilliamK112 force-pushed the codex/langchain-chain-callback-1787 branch from a551d13 to c520adb Compare July 2, 2026 04:56
@WilliamK112
WilliamK112 requested a review from a team as a code owner July 2, 2026 04:56
@WilliamK112
WilliamK112 changed the base branch from main to develop July 2, 2026 04:56
@WilliamK112
WilliamK112 force-pushed the codex/langchain-chain-callback-1787 branch from c520adb to bf26bd5 Compare July 2, 2026 04:57
@WilliamK112

WilliamK112 commented Jul 2, 2026

Copy link
Copy Markdown
Contributor Author

Label Checker is failing because I cannot add labels from the fork. For this PR, I believe the appropriate labels are feature request and non-breaking: it implements the requested LangChain Runnable callback tracking from #1787 and preserves existing callback behavior.

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

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py`:
- Around line 370-428: The chain event tracking maps are only populated in
on_chain_start and never cleaned up, causing per-run state to grow unbounded.
Update callback_handler.py in on_chain_end to remove the run_id_str entries from
_run_id_to_chain_input, _run_id_to_chain_name, and _run_id_to_start_time after
building the IntermediateStepPayload. If there is an error/abort path in the
LangChain callbacks (for example a chain error handler), apply the same cleanup
there using the same run_id_str keys.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: dd5cb25f-e465-4114-8fa4-f8dfe961b09b

📥 Commits

Reviewing files that changed from the base of the PR and between 201f3dc and c520adb.

📒 Files selected for processing (2)
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py
  • packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py

@WilliamK112
WilliamK112 force-pushed the codex/langchain-chain-callback-1787 branch from bf26bd5 to b971b1b Compare July 2, 2026 05:02

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

🧹 Nitpick comments (2)
packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py (2)

96-99: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Docstring first line must end with a period.

The docstring's first line ends with a colon instead of a period, which will trip the Vale doc check.

As per coding guidelines, "The first line of docstrings must be a concise description ending with a period (Vale checks this)."

📝 Proposed fix
     """
-    Test that LangChain Runnable/chain callbacks produce paired function stats:
+    Test that LangChain Runnable/chain callbacks produce paired function stats.
+
       - on_chain_start -> usage stat with event_type=FUNCTION_START
       - on_chain_end -> usage stat with event_type=FUNCTION_END
     """
🤖 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 `@packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py`
around lines 96 - 99, The docstring in the LangChain callback handler test
currently ends the summary line with a colon instead of a period, which violates
the doc style check. Update the first line of the docstring in
test_langchain_callback_handler.py so the summary is a concise sentence ending
with a period, keeping the rest of the test description unchanged.

Source: Coding guidelines


105-140: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding coverage for the default tags/metadata path.

This test only exercises on_chain_start with tags and metadata explicitly supplied. A follow-up test invoking with defaults (tags=None, metadata=None) would cover the branch that other tests, like test_langchain_handler_clears_chain_state_on_error, only partially exercise for on_chain_start.

🤖 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 `@packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py`
around lines 105 - 140, Add a follow-up test for
`LangChainCallbackHandler.on_chain_start` that omits both `tags` and `metadata`
so the default path is covered. Use the existing `handler`/`all_stats`
assertions pattern from this test, but call `on_chain_start` with `tags=None`
and `metadata=None`, then verify the emitted start/end stats still populate
correctly and that the handler state maps are cleared.
🤖 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 `@packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py`:
- Around line 96-99: The docstring in the LangChain callback handler test
currently ends the summary line with a colon instead of a period, which violates
the doc style check. Update the first line of the docstring in
test_langchain_callback_handler.py so the summary is a concise sentence ending
with a period, keeping the rest of the test description unchanged.
- Around line 105-140: Add a follow-up test for
`LangChainCallbackHandler.on_chain_start` that omits both `tags` and `metadata`
so the default path is covered. Use the existing `handler`/`all_stats`
assertions pattern from this test, but call `on_chain_start` with `tags=None`
and `metadata=None`, then verify the emitted start/end stats still populate
correctly and that the handler state maps are cleared.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: cd942f18-7fae-43bd-9b71-183ab2ef286e

📥 Commits

Reviewing files that changed from the base of the PR and between bf26bd5 and b971b1b.

📒 Files selected for processing (2)
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py
  • packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py

@WilliamK112
WilliamK112 force-pushed the codex/langchain-chain-callback-1787 branch from b971b1b to 7897eec Compare July 2, 2026 05:08

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

🧹 Nitpick comments (1)
packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py (1)

102-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract repeated test setup into a fixture.

The all_stats = [] / handler = LangchainProfilerHandler() / reactive_stream.subscribe(...) boilerplate is duplicated identically across all three tests.

♻️ Suggested fixture extraction
+@pytest.fixture(name="chain_handler_fixture")
+def chain_handler_fixture(reactive_stream: Subject):
+    all_stats = []
+    handler = LangchainProfilerHandler()
+    _ = reactive_stream.subscribe(all_stats.append)
+    return handler, all_stats
+
+
-async def test_langchain_handler_tracks_chain_runnable_events(reactive_stream: Subject):
+async def test_langchain_handler_tracks_chain_runnable_events(chain_handler_fixture):
     ...
-    all_stats = []
-    handler = LangchainProfilerHandler()
-    _ = reactive_stream.subscribe(all_stats.append)
+    handler, all_stats = chain_handler_fixture

As per coding guidelines, "Extract frequently repeated test code into pytest fixtures with the fixture_ prefix or _fixture suffix using snake_case, and define the name argument in @pytest.fixture(name="...")".

Also applies to: 147-149, 183-185

🤖 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 `@packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py`
around lines 102 - 104, The test setup that creates all_stats, instantiates
LangchainProfilerHandler, and subscribes to reactive_stream is repeated across
multiple test cases in test_langchain_callback_handler.py. Extract that
boilerplate into a pytest fixture using the required fixture naming convention
(fixture_ prefix or _fixture suffix in snake_case) and register it with
`@pytest.fixture`(name="..."), then update the tests to use the shared fixture
instead of repeating the setup in each test.

Source: Coding guidelines

🤖 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 `@packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py`:
- Around line 102-104: The test setup that creates all_stats, instantiates
LangchainProfilerHandler, and subscribes to reactive_stream is repeated across
multiple test cases in test_langchain_callback_handler.py. Extract that
boilerplate into a pytest fixture using the required fixture naming convention
(fixture_ prefix or _fixture suffix in snake_case) and register it with
`@pytest.fixture`(name="..."), then update the tests to use the shared fixture
instead of repeating the setup in each test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e61393fb-f6db-4d21-ac2e-e3ad3c62ef95

📥 Commits

Reviewing files that changed from the base of the PR and between b971b1b and 7897eec.

📒 Files selected for processing (2)
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py
  • packages/nvidia_nat_langchain/tests/test_langchain_callback_handler.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nvidia_nat_langchain/src/nat/plugins/langchain/callback_handler.py

Signed-off-by: WilliamK112 <164879897+WilliamK112@users.noreply.github.com>
@WilliamK112
WilliamK112 force-pushed the codex/langchain-chain-callback-1787 branch from 7897eec to 97a44de Compare July 2, 2026 05:16
@willkill07 willkill07 added feature request New feature or request non-breaking Non-breaking change labels Jul 8, 2026
@willkill07

Copy link
Copy Markdown
Member

/ok to test 97a44de

@willkill07

Copy link
Copy Markdown
Member

/merge

@rapids-bot
rapids-bot Bot merged commit 3c4e59b into NVIDIA:develop Jul 8, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature request New feature or request non-breaking Non-breaking change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for tracking base LangChain Runnables in callback handler

2 participants