langroid icon indicating copy to clipboard operation
langroid copied to clipboard

CodeParser shares chunk metadata, causing duplicate IDs and lost chunks

Open CSXizhang opened this issue 2 months ago • 2 comments

Describe the bug CodeParser.split() gives sibling chunks the same metadata object as their source document. Parser.add_window_ids() then overwrites the IDs and neighbor windows of sibling chunks and mutates the source document. Vector-store upserts using those repeated IDs can silently discard chunks.

To Reproduce Run this against commit 324631cde99522e779bfbed94d05ab4f3c7b3040:

from langroid.mytypes import DocMetaData, Document
from langroid.parsing.code_parser import CodeParser, CodeParsingConfig
from langroid.parsing.parser import Parser, ParsingConfig

sources = [
    Document(
        content="\n".join(f"value_{i} = {i}" for i in range(10)),
        metadata=DocMetaData(source="first.py", language="py"),
    ),
    Document(
        content="\n".join(f"echo value_{i}" for i in range(10)),
        metadata=DocMetaData(source="second.sh", language="sh"),
    ),
]
original = [doc.model_dump() for doc in sources]
chunks = CodeParser(CodeParsingConfig(chunk_size=10)).split(sources)

print("Independent metadata:", len({id(c.metadata) for c in chunks}) == len(chunks))
Parser(ParsingConfig(n_neighbor_ids=1)).add_window_ids(chunks)
print("Distinct chunk IDs:", len({c.id() for c in chunks}) == len(chunks))
print("Sources unchanged:", [doc.model_dump() for doc in sources] == original)

All three checks are false before the fix. The regression tests cover the same metadata identity, ID uniqueness, and source-preservation failures, plus source-local neighbor windows.

Expected behavior All three checks should be true. Each chunk should have independent top-level metadata, receive a distinct ID, and retain the appropriate neighbor window without changing its source document. Initial source-group IDs and shallow-copy semantics should be preserved.

Screenshots Not applicable; this is a Python API issue.

Desktop (please complete the following information):

  • OS: Windows
  • Python: 3.12
  • Langroid: source checkout at 324631cde99522e779bfbed94d05ab4f3c7b3040
  • Browser: not applicable

Additional context A separate local DocChatAgent / embedded-Qdrant ingestion check retained only 2 of 12 chunks before the fix and all 12 afterward, using mock/local models. PR #1170 changes chunk construction to use metadata.model_copy() and adds four regression cases that fail before the fix and pass afterward.

CSXizhang avatar Oct 03 '26 09:10 CSXizhang

Confirmed, and #1170 is the right fix for the sharing part — verified independently: with one shared DocMetaData per source doc, Parser.add_window_ids (parsing/parser.py:203-205) writes id/window_ids/is_chunk into that single object repeatedly, so 12 chunks collapsed to 2 distinct metadata objects and 2 distinct IDs, and the caller's original Document was mutated as well. model_copy() is also the correct choice over a deep copy or a fresh ID, since add_window_ids groups chunks by shared metadata.id.

One thing to settle before this is closed, though: the fix removes the sharing, but it does not by itself make chunk IDs distinct, so the second half of this issue's title survives. model_copy() copies id, and CodeParser.split neither sets is_chunk=True nor calls add_window_ids — unlike Parser.split_simple/split_para_sentence/split_chunk_tokens, which do both internally. Measured after the fix, with no add_window_ids call: 7 chunks, 1 distinct metadata.id, every is_chunk == False, and chunks[0].id() == src[0].id(). Since Qdrant keys points on d.id() and maybe_add_ids only fills missing IDs, vecdb.add_documents(CodeParser(...).split(docs)) still has chunks overwriting each other. The tests in #1170 pass because they call add_window_ids explicitly.

@pchalasani — the decision this needs: should CodeParser.split mirror Parser.split_simple (fresh per-chunk IDs, is_chunk=True, and an internal add_window_ids call), or should the "caller must call add_window_ids" contract stay and just be documented? Mirroring it changes the documented contract and conflicts with the ID-based grouping that #1170's tests rely on, and CodeParser has no n_neighbor_ids config of its own — which is why I did not extend the scope here. Note CodeParser has no in-repo callers, so this is latent public-API behavior, not a live regression.

Practically: #1170 is good to merge on its own, but its Fixes #1171 line would auto-close this while the duplicate-ID symptom remains, so that line is worth dropping (or this issue reopening).

pchalasani avatar Oct 04 '26 08:10 pchalasani

Decision: CodeParser.split should mirror Parser.split_simple — assign fresh per-chunk IDs and is_chunk=True itself, and call add_window_ids internally.

Reasoning: every other splitter in Parser already does this, CodeParser.split's docstring never told callers to call add_window_ids, and nothing inside langroid calls CodeParser.split, so the "caller's responsibility" contract is one almost no user knows about. The consequence of leaving it is duplicate chunk IDs and chunks silently dropped on vector-store upsert, which is worse than any churn from fixing it.

One thing the fix must also handle: add_window_ids is not idempotent. It groups chunks by their shared metadata.id, so calling it a second time sees already-distinct IDs, treats each chunk as its own group, and collapses every window_ids to a singleton. Any user who was calling it after CodeParser.split would silently lose their neighbor windows. So it needs a guard that makes it a no-op (or correct) on input that is already chunked.

Scope:

  1. CodeParser.split: metadata.model_copy(update=dict(is_chunk=True)) per chunk, then self.add_window_ids(chunks) — matching split_simple.
  2. Parser.add_window_ids: safe on already-chunked input.
  3. Tests: distinct chunk IDs, source-local neighbor windows, the original document unmutated, and a double-call case proving the windows survive.

PR #1170 already fixes the metadata-sharing half and is being merged; this is the remaining half.

pchalasani avatar Oct 04 '26 13:10 pchalasani