Skip to content

Fix LangChainChunker import for langchain_text_splitters and copy chunk metadata - #41625

Open
arijeetmukherjee3108-droid wants to merge 3 commits into
apache:masterfrom
arijeetmukherjee3108-droid:fix-langchain-chunker
Open

arijeetmukherjee3108-droid wants to merge 3 commits into
apache:masterfrom
arijeetmukherjee3108-droid:fix-langchain-chunker

Conversation

@arijeetmukherjee3108-droid

@arijeetmukherjee3108-droid arijeetmukherjee3108-droid commented Nov 24, 2026 •

Copy link
Copy Markdown

fixes #41623

LangChainChunker currently only imports TextSplitter from langchain.text_splitter, which raises an ImportError when using standalone langchain-text-splitters and silently skips langchain_test.py. _LangChainTextSplitter.process also passes the same metadata dict reference to every Chunk yielded from a document, so mutating chunk.metadata downstream affects all sibling chunks.

  • Import TextSplitter (and test splitters) from langchain_text_splitters first, falling back to langchain.text_splitter.
  • Pass copy.deepcopy(metadata) for each yielded Chunk and add a test verifying metadata independence in langchain_test.py.

Tested locally with pytest sdks/python/apache_beam/ml/rag/chunking/langchain_test.py -v.

@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 updates LangChainChunker and its tests to support importing TextSplitter from the standalone langchain_text_splitters package (with a fallback to langchain.text_splitter), and ensures each yielded Chunk gets a shallow copy of the document metadata dictionary. The changes are clean, backward-compatible, and well-tested.

🔍 General Feedback

  • The fallback import structure properly handles both modern (langchain-text-splitters) and legacy (langchain) installations.
  • Copying the metadata dictionary per chunk prevents unintended cross-chunk state mutation in downstream transforms or custom chunk_id_fn callbacks.

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

@github-actions github-actions Bot added python size/s S: 10-49 lines changed labels Nov 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @damccorm for label python.
Backup reviewer: tvalentyn (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).


try:
from langchain.text_splitter import TextSplitter
from langchain_text_splitters import TextSplitter

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.

Right now sdks/python/setup.py (ml_base_core) only lists 'langchain', which resolves to langchain 1.x in PreCommit Python ML and doesn't include langchain-text-splitters or langchain.text_splitter — so all tests in langchain_test.py are still getting silently skipped in CI. Could you also replace 'langchain' with 'langchain-text-splitters' (or add it alongside) in sdks/python/setup.py so these tests actually run?

@arijeetmukherjee3108-droid arijeetmukherjee3108-droid Nov 24, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch, thank you. I grepped sdks/python/ and confirmed no other modules import langchain, so I replaced 'langchain' with 'langchain-text-splitters' in ml_base_core in sdks/python/setup.py so langchain_test.py runs in PreCommit Python ML.

def check_independent_metadata(chunks):
if len(chunks) < 2:
raise BeamAssertException(
f"Expected at least 2 chunks, got {len(chunks)}")

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.

Since check_independent_metadata runs inside assert_that (after a GroupByKey / coder serialization round-trip), each Chunk has already been deserialized into a separate object by the time we mutate chunks[0].metadata — so this test would pass even without copy.deepcopy(metadata).

To actually catch the shared-reference bug, could we either call _LangChainTextSplitter(...).process(doc) directly (list(dofn.process(doc))) or mutate chunk.metadata inside a chunk_id_fn / downstream beam.Map before assert_that (e.g., mutating when chunk.index == 0 and asserting later chunks aren't affected)?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Great catch—I hadn't accounted for the GroupByKey/coder round-trip inside assert_that deserializing separate Chunk objects. I updated test_chunks_have_independent_metadata to call list(_LangChainTextSplitter(...).process(doc)) directly and verify that mutating both top-level and nested metadata does not affect sibling chunks or the input doc.

@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.73%. Comparing base (9c564f9) to head (bbcafa7).
⚠️ Report is 9 commits behind head on master.

Files with missing lines Patch % Lines
...ks/python/apache_beam/ml/rag/chunking/langchain.py 0.00% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##             master   #41625   +/-   ##
=========================================
  Coverage     58.72%   58.73%           
  Complexity     2315     2315           
=========================================
  Files          1135     1135           
  Lines        170465   170488   +23     
  Branches       1499     1499           
=========================================
+ Hits         100113   100135   +22     
- Misses        67806    67807    +1     
  Partials       2546     2546           
Flag Coverage Δ
python 80.67% <0.00%> (+<0.01%) ⬆️

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.

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.

[Bug]: LangChainChunker fails with langchain-text-splitters and shares mutable metadata dict across chunks

2 participants