Repository navigation
Test(chunker): add golden parity harness, fixtures, and live Go<->Python tool - #17735
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds a Python–Go chunker parity framework. It introduces shared cases, deterministic golden baselines, Go comparison tests, known-difference tracking, and manual live parity tools. ChangesChunker parity validation
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant CaptureGolden
participant PythonChunker
participant GoldenFiles
participant GoParityTest
participant GoChunker
CaptureGolden->>PythonChunker: execute parity case
PythonChunker-->>CaptureGolden: return serialized chunks
CaptureGolden->>GoldenFiles: write deterministic golden output
GoParityTest->>GoChunker: invoke registered chunker
GoChunker-->>GoParityTest: return Go chunks
GoParityTest->>GoldenFiles: compare normalized results
Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (14)
internal/ingestion/component/chunker/token.go (1)
400-405: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove migration-history detail from Go comments.
Keep comments focused on the current Python-parity contract. Do not retain descriptions of the replaced joined-string behavior.
internal/ingestion/component/chunker/token.go#L400-L405: replace the old-versus-new algorithm narrative with the current running-sum invariant.internal/ingestion/component/chunker/split_oversized_test.go#L19-L29: retain the oracle purpose and remove the historical Go behavior description.As per coding guidelines, keep Go comments aligned with the current runtime path rather than migration history; remove stale superseded comments and documentation.
🤖 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 `@internal/ingestion/component/chunker/token.go` around lines 400 - 405, Update the comment at internal/ingestion/component/chunker/token.go lines 400-405 to state only the current running-sum invariant and flush condition, removing the replaced joined-string behavior and migration history. Update internal/ingestion/component/chunker/split_oversized_test.go lines 19-29 to preserve the oracle’s purpose while removing historical descriptions of the former Go behavior.Source: Coding guidelines
internal/ingestion/component/chunker/testdata/parity/README.md (1)
10-17: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument the committed Go snapshots.
The parity stack adds
testdata/parity/go_snapshot/*.json, but the layout table omits that directory. Add its purpose and generation or validation path, or remove the files if they are not part of the supported parity contract.Based on the PR stack context, committed Go snapshots are part of this parity cohort.
🤖 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 `@internal/ingestion/component/chunker/testdata/parity/README.md` around lines 10 - 17, Update the Layout table in the parity README to document testdata/parity/go_snapshot/*.json as committed Go snapshots, including their purpose and how they are generated or validated. Keep the snapshots as part of the supported parity contract.internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json (1)
2-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the duplicate parity case or make the inputs distinct.
Both files define the same case data under different IDs. The harness runs each file independently, so the duplicate increases runtime without adding coverage.
internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json#L2-L15: keep this case for default-delimiter divergence, or change its input if it should cover another behavior.internal/ingestion/component/chunker/testdata/parity/cases/token__text_token_liveness.json#L2-L15: delete the duplicate, or replace itsparam,input, andnoteswith a tokenizer-liveness-specific case.As per coding guidelines, collapse duplicate test paths. Based on
internal/ingestion/component/chunker/golden_parity_test.goLines 147-178, each JSON case is a separate subtest.🤖 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 `@internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json` around lines 2 - 15, Remove the duplicate parity coverage or make the cases distinct: retain internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json lines 2-15 for default-delimiter divergence, and update internal/ingestion/component/chunker/testdata/parity/cases/token__text_token_liveness.json lines 2-15 with tokenizer-liveness-specific param, input, and notes or delete it. Ensure each case provides unique coverage for the subtests driven by goldenParityTest.Source: Coding guidelines
internal/ingestion/component/chunker/golden_parity_test.go (8)
180-180: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the
pathidentifiers so they do not shadow the importedpathpackage.The file imports
pathand callspath.MatchinmatchesandpatternMatchesAny.loadCasetakes a parameter namedpath, andloadGoldendeclares a local variable namedpath. The code compiles today. Any later use ofpath.Matchinside these two functions fails with a confusing error. Rename them tocasePathandgoldenPath.Also applies to: 195-195
🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` at line 180, Rename the loadCase parameter from path to casePath and the loadGolden local variable from path to goldenPath, updating all references within those functions. Preserve the imported path package name so path.Match remains available in matches and patternMatchesAny.
369-373: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winInclude the snapshot diff in the drift failure message.
The failure reports only the snapshot path. The reader must re-run with
-updateand inspectgit diffto see what changed. The file already importscmp. Print the diff directly.🛠️ Proposed fix
if gotSnap := serializeChunks(caseID, got, strip); gotSnap != string(wantSnap) { t.Fatalf("Go output drifted from snapshot %s.\n"+ "Either a Go-side change altered this known-diff behaviour (investigate), "+ - "or run `go test -update` to accept the new snapshot.", snapPath) + "or run `go test -update` to accept the new snapshot.\n(-snapshot +go):\n%s", + snapPath, cmp.Diff(string(wantSnap), gotSnap)) }🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 369 - 373, Update the snapshot mismatch failure in serializeChunks to include the cmp diff between the expected snapshot and generated output, while retaining the snapshot path and existing guidance in the fatal message. Reuse the existing cmp import rather than introducing another comparison mechanism.
230-235: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFail explicitly when
chunksis not[]map[string]any.The type assertion drops its
okresult. If the component output shape changes to[]any,chunksbecomes nil and the test reportsgo=0chunks. That message points at the chunker logic instead of the real cause, which is the output contract.🛠️ Proposed fix
- chunks, _ := out["chunks"].([]map[string]any) - return chunks + raw, present := out["chunks"] + if !present { + t.Fatalf("%s output has no \"chunks\" key: %v", tc.Component, sortedKeys(out)) + } + chunks, ok := raw.([]map[string]any) + if !ok { + t.Fatalf("%s output \"chunks\" has unexpected type %T", tc.Component, raw) + } + return chunks🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 230 - 235, Update the helper around the chunks extraction to retain and validate the type assertion for out["chunks"] as []map[string]any. Fail the test immediately with a clear output-contract error when the assertion fails, while preserving the existing _ERROR handling and returning the asserted chunks on success.
378-389: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe strip set is global, but the allow-list is per case.
extraFieldsToStripmerges thefieldsof everyextra_fieldsrule.allowedExtraFieldsresolves the same rules per case. A field declared only for case A is therefore also stripped from case B's snapshot, which removes it from the ratchet. Pass the case ID and reuseallowedExtraFieldsso both paths agree.🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 378 - 389, The extra-field stripping currently aggregates rules across all cases, while allow-list resolution is case-specific. Update extraFieldsToStrip to accept the case ID, derive the strip set through allowedExtraFields for that case, and update its callers so each snapshot strips only fields allowed for the active case.
304-316: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider rejecting overlapping ratchet rules.
matchedRatchetRulereturns the first matching rule and ignores the rest. If twochunk_countorchunk_textrules match one case, the second rule is never enforced and never reported as dead.TestKnownDiffRegistryWellFormeddoes not detect this. Add a check there that no case ID matches more than one ratchet rule.🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 304 - 316, Update TestKnownDiffRegistryWellFormed to detect overlapping ratchet rules: for each case ID, count matching rules limited to kindChunkCount and kindChunkText, and reject any case matching more than one rule. Keep matchedRatchetRule unchanged, while ensuring overlapping rules are reported rather than silently allowing the first match.
123-130: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider asserting the registry
version.
Versionis decoded and then discarded. If the registry format changes, the harness silently reads the new file with the old rules. Add a supported-version check inTestKnownDiffRegistryWellFormedso a format bump fails loudly.🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 123 - 130, Update TestKnownDiffRegistryWellFormed after unmarshalling the registry to validate registry.Version against the supported format version, and fail the test with a clear message when it differs. Keep returning registry.Rules only after the version check succeeds.
147-178: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider detecting orphan golden and snapshot files.
The harness iterates cases only. If a case file is deleted, its
golden/andgo_snapshot/files stay on disk and no test fails.TestKnownDiffRegistryWellFormedalready guards rules against the same rot. Add the equivalent check for the two fixture directories.🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 147 - 178, Update TestChunkerGoldenParity to track case IDs while iterating parityCasesDir, then validate that golden and go_snapshot contain no files without a corresponding case. Fail the test for orphan fixtures, matching the existing well-formedness validation used by TestKnownDiffRegistryWellFormed.
154-161: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThree copies of the parity case enumeration. The same directory walk appears three times: skip directories, keep
.jsonfiles, trim the suffix, and derive the case ID. The shared root cause is the absence of one helper that both harnesses call.listCaseIDsalready implements the logic and can own it.
internal/ingestion/component/chunker/golden_parity_test.go#L154-L161: replace the inline walk with a call to a shared helper that returns case IDs and their file paths.internal/ingestion/component/chunker/golden_parity_test.go#L470-L484: extendlistCaseIDsto return the path alongside the ID, then reuse it as the single source.internal/ingestion/component/chunker/live_parity_test.go#L128-L135: replace the inline walk with the same helper; the file already sharesloadCase,loadKnownDiffs, andchunkDiffswith the golden harness.🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 154 - 161, Consolidate parity-case enumeration through listCaseIDs: in internal/ingestion/component/chunker/golden_parity_test.go:154-161 and internal/ingestion/component/chunker/live_parity_test.go:128-135, replace the inline directory walks with the shared helper and use its returned case IDs and file paths; in internal/ingestion/component/chunker/golden_parity_test.go:470-484, extend listCaseIDs to return each JSON case path alongside its trimmed ID while preserving the existing filtering.internal/ingestion/component/chunker/tool-py/capture_golden.py (2)
229-254: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd logging to this new capture flow.
The capture loop reports progress and drift with
loggingmodule for the progress and drift messages, and keepstdoutfor the tool's primary output.Based on coding guidelines: "
**/*.py: Add logging for new flows".🤖 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 `@internal/ingestion/component/chunker/tool-py/capture_golden.py` around lines 229 - 254, Update the capture loop around cases, drift reporting, and abort handling to use the logging module for progress, drift, and failure messages instead of print or direct stderr output. Configure or reuse the module’s logger and preserve stdout exclusively for the tool’s primary output, including the existing successful check summary and written-file output as appropriate.Source: Coding guidelines
108-113: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winReject unknown param keys before
setattr.
setattrcreates a new attribute for any key. A typo in a case file'sparamblock therefore produces a silent no-op: Python ignores the unknown attribute, and the GoUpdatemethod ignores the unknown key. Both sides agree, the parity test passes, and the case never exercises the setting its author intended. Validate the key against the param object first.🛠️ Proposed fix
for key, value in param.items(): + if not hasattr(p, key): + raise ValueError(f"{component}: unknown param key {key!r}") setattr(p, key, value)🤖 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 `@internal/ingestion/component/chunker/tool-py/capture_golden.py` around lines 108 - 113, Validate each key in param against the parameter object before calling setattr in the surrounding capture setup, rejecting unknown keys rather than creating dynamic attributes. Preserve the existing p.check() validation for known parameters, and ensure invalid case-file keys fail before they can be included in the golden baseline.internal/ingestion/component/chunker/live_parity_test.go (1)
89-105: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winAdd a timeout to the Python subprocess.
exec.Commandhas no deadline. If the interpreter hangs, for example on a partially built.venv, the subtest blocks until the whole test binary times out. The test runs one subprocess per case, so the failure mode is slow and hard to attribute. Useexec.CommandContextwith a per-case timeout.Two smaller points in the same function:
findRepoRootruns twice per call, becausevenvPythoncalls it again; anderr.(*exec.ExitError)should beerrors.Asso a wrapped error still yields stderr.🛠️ Proposed fix
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() - cmd := exec.Command(py, script, caseID) + cmd := exec.CommandContext(ctx, py, script, caseID) cmd.Dir = root cmd.Env = append(os.Environ(), "PYTHONPATH="+root, "PYTHONUNBUFFERED=1") out, err := cmd.Output() if err != nil { - if ee, ok := err.(*exec.ExitError); ok { + var ee *exec.ExitError + if errors.As(err, &ee) { t.Fatalf("python chunker failed for %s: %v\nstderr:\n%s", caseID, err, string(ee.Stderr)) } t.Fatalf("python chunker failed for %s: %v", caseID, err) }Add
context,errors, andtimeto the import block.🤖 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 `@internal/ingestion/component/chunker/live_parity_test.go` around lines 89 - 105, Update pythonChunksLive to create a per-case context timeout and use exec.CommandContext instead of exec.Command, ensuring hung Python subprocesses terminate with an identifiable timeout failure. Reuse the root discovered by findRepoRoot when resolving the virtualenv Python rather than invoking findRepoRoot again through venvPython. Replace the direct *exec.ExitError assertion with errors.As so wrapped execution errors still expose stderr.
🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go`:
- Around line 546-549: Update the text truncation logic in the golden parity
test to limit the string to 40 Unicode runes rather than 40 bytes, preserving
valid UTF-8 for multilingual content; append the existing ellipsis only when
truncation occurs.
In `@internal/ingestion/component/chunker/live_parity_test.go`:
- Around line 142-152: The resolved known-diff branch in the live parity test
currently logs only through t.Logf, so stale rules are hidden during normal test
runs. In the matchedRatchetRule handling, replace the logging for len(diffs) ==
0 with t.Errorf while preserving the existing divergence logging and return
behavior.
In `@internal/ingestion/component/chunker/split_oversized_test.go`:
- Around line 35-40: Make TestSplitOversizedUnitMatchesPython self-contained by
removing its dependency on loadCase and the later parity fixture
token__b1_count_sensitive.json. Inline the required input text and
chunk_token_size values directly in the test while preserving the existing
splitOversizedUnitWith call and regression coverage.
In
`@internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json`:
- Line 15: The token__text_default_delim parity case lacks the required snapshot
expectation for its chunk output. Update the parity expectations, such as
known_diffs.json, with a narrow chunk_count/chunk_text rule documenting the
intended divergence, or intentionally remove the token__text_default_delim
fixture so strict compareChunks does not run without coverage.
In
`@internal/ingestion/component/chunker/testdata/parity/cases/token__text_overlap.json`:
- Around line 4-10: Fix the overlap-prefix handling used by the
token-text-overlap-split path so overlapped text remains byte-identical between
consecutive chunks, then remove the chunk_text ratchet entry from the
token__text_overlap parity fixture. If byte-identical overlap is not intended,
update or remove the fixture instead of retaining the ratchet.
In `@internal/ingestion/component/chunker/testdata/parity/known_diffs.json`:
- Line 28: Replace the TODO placeholder tracking values with the filed issue
links for all five entries in
internal/ingestion/component/chunker/testdata/parity/known_diffs.json: lines 28,
37, 46, 55, and 64, covering cross-item JSON merging, custom-delimiter text
behavior, JSON delimiter trimming, oversized single JSON items, and
overlap-prefix behavior. Remove any “move later” notes rather than retaining
them.
In `@internal/ingestion/component/chunker/testdata/parity/README.md`:
- Around line 82-92: Update the known_diffs.json schema documentation in the
table around kind and fields to list all supported difference kinds: field,
chunk-count, and chunk_text. Describe which fields each kind compares, while
preserving the existing extra_fields guidance and ensuring the table matches the
ratchet contract.
- Around line 50-56: Update the documented Go command in the parity README to
use ./build.sh --test -run TestChunkerGoldenParity
./internal/ingestion/component/chunker/... instead of raw go test, preserving
the Python baseline command. If the parity test requires CGO_ENABLED=0, document
that requirement explicitly rather than using the default build script
invocation.
In `@internal/ingestion/component/chunker/tool-py/capture_golden.py`:
- Around line 180-185: Update the write flow in main and write_manifest so a
--case ID run does not rewrite corpus-level provenance, or instead records only
the captured case ID(s) in the manifest. Preserve the existing full-corpus
manifest behavior for write runs without --case.
In `@internal/ingestion/component/chunker/tool-py/live_chunk.py`:
- Around line 55-62: Validate the loaded case’s id against the JSON filename
stem in the live_chunk.py case-loading flow before calling
_assert_tokenizer_alive() or run_case(case). Reject mismatches with the same
failure behavior and clear diagnostic used by load_cases, golden_parity_test.go,
and live_parity_test.go, while preserving processing for matching fixtures.
---
Nitpick comments:
In `@internal/ingestion/component/chunker/golden_parity_test.go`:
- Line 180: Rename the loadCase parameter from path to casePath and the
loadGolden local variable from path to goldenPath, updating all references
within those functions. Preserve the imported path package name so path.Match
remains available in matches and patternMatchesAny.
- Around line 369-373: Update the snapshot mismatch failure in serializeChunks
to include the cmp diff between the expected snapshot and generated output,
while retaining the snapshot path and existing guidance in the fatal message.
Reuse the existing cmp import rather than introducing another comparison
mechanism.
- Around line 230-235: Update the helper around the chunks extraction to retain
and validate the type assertion for out["chunks"] as []map[string]any. Fail the
test immediately with a clear output-contract error when the assertion fails,
while preserving the existing _ERROR handling and returning the asserted chunks
on success.
- Around line 378-389: The extra-field stripping currently aggregates rules
across all cases, while allow-list resolution is case-specific. Update
extraFieldsToStrip to accept the case ID, derive the strip set through
allowedExtraFields for that case, and update its callers so each snapshot strips
only fields allowed for the active case.
- Around line 304-316: Update TestKnownDiffRegistryWellFormed to detect
overlapping ratchet rules: for each case ID, count matching rules limited to
kindChunkCount and kindChunkText, and reject any case matching more than one
rule. Keep matchedRatchetRule unchanged, while ensuring overlapping rules are
reported rather than silently allowing the first match.
- Around line 123-130: Update TestKnownDiffRegistryWellFormed after
unmarshalling the registry to validate registry.Version against the supported
format version, and fail the test with a clear message when it differs. Keep
returning registry.Rules only after the version check succeeds.
- Around line 147-178: Update TestChunkerGoldenParity to track case IDs while
iterating parityCasesDir, then validate that golden and go_snapshot contain no
files without a corresponding case. Fail the test for orphan fixtures, matching
the existing well-formedness validation used by TestKnownDiffRegistryWellFormed.
- Around line 154-161: Consolidate parity-case enumeration through listCaseIDs:
in internal/ingestion/component/chunker/golden_parity_test.go:154-161 and
internal/ingestion/component/chunker/live_parity_test.go:128-135, replace the
inline directory walks with the shared helper and use its returned case IDs and
file paths; in
internal/ingestion/component/chunker/golden_parity_test.go:470-484, extend
listCaseIDs to return each JSON case path alongside its trimmed ID while
preserving the existing filtering.
In `@internal/ingestion/component/chunker/live_parity_test.go`:
- Around line 89-105: Update pythonChunksLive to create a per-case context
timeout and use exec.CommandContext instead of exec.Command, ensuring hung
Python subprocesses terminate with an identifiable timeout failure. Reuse the
root discovered by findRepoRoot when resolving the virtualenv Python rather than
invoking findRepoRoot again through venvPython. Replace the direct
*exec.ExitError assertion with errors.As so wrapped execution errors still
expose stderr.
In
`@internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json`:
- Around line 2-15: Remove the duplicate parity coverage or make the cases
distinct: retain
internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json
lines 2-15 for default-delimiter divergence, and update
internal/ingestion/component/chunker/testdata/parity/cases/token__text_token_liveness.json
lines 2-15 with tokenizer-liveness-specific param, input, and notes or delete
it. Ensure each case provides unique coverage for the subtests driven by
goldenParityTest.
In `@internal/ingestion/component/chunker/testdata/parity/README.md`:
- Around line 10-17: Update the Layout table in the parity README to document
testdata/parity/go_snapshot/*.json as committed Go snapshots, including their
purpose and how they are generated or validated. Keep the snapshots as part of
the supported parity contract.
In `@internal/ingestion/component/chunker/token.go`:
- Around line 400-405: Update the comment at
internal/ingestion/component/chunker/token.go lines 400-405 to state only the
current running-sum invariant and flush condition, removing the replaced
joined-string behavior and migration history. Update
internal/ingestion/component/chunker/split_oversized_test.go lines 19-29 to
preserve the oracle’s purpose while removing historical descriptions of the
former Go behavior.
In `@internal/ingestion/component/chunker/tool-py/capture_golden.py`:
- Around line 229-254: Update the capture loop around cases, drift reporting,
and abort handling to use the logging module for progress, drift, and failure
messages instead of print or direct stderr output. Configure or reuse the
module’s logger and preserve stdout exclusively for the tool’s primary output,
including the existing successful check summary and written-file output as
appropriate.
- Around line 108-113: Validate each key in param against the parameter object
before calling setattr in the surrounding capture setup, rejecting unknown keys
rather than creating dynamic attributes. Preserve the existing p.check()
validation for known parameters, and ensure invalid case-file keys fail before
they can be included in the golden baseline.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fd90e10c-4c67-4b7a-93fa-1a5d5075a751
📒 Files selected for processing (71)
go.modinternal/ingestion/component/chunker/golden_parity_test.gointernal/ingestion/component/chunker/live_parity_test.gointernal/ingestion/component/chunker/split_oversized_test.gointernal/ingestion/component/chunker/testdata/parity/README.mdinternal/ingestion/component/chunker/testdata/parity/_manifest.jsoninternal/ingestion/component/chunker/testdata/parity/cases/title__group_simple.jsoninternal/ingestion/component/chunker/testdata/parity/cases/title__hierarchy_2level.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__empty_input.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__html_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__html_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__html_long.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_children_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_img_id.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_multi_item_40.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_single.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_single_long.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_table_context.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_two_item.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__markdown_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__markdown_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__markdown_long.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_long_paragraph.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_token_liveness.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__html_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__html_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__json_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__json_multi_item_40.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__json_single_long.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__json_two_item.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__markdown_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__markdown_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__text_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__text_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__text_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__text_token_liveness.jsoninternal/ingestion/component/chunker/testdata/parity/golden/title__group_simple.jsoninternal/ingestion/component/chunker/testdata/parity/golden/title__hierarchy_2level.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__b1_count_sensitive.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__empty_input.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__html_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__html_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__html_long.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_children_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_img_id.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_multi_item_40.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_single.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_single_long.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_table_context.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_two_item.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__markdown_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__markdown_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__markdown_long.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_long_paragraph.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_token_liveness.jsoninternal/ingestion/component/chunker/testdata/parity/known_diffs.jsoninternal/ingestion/component/chunker/token.gointernal/ingestion/component/chunker/token_strict_cap_test.gointernal/ingestion/component/chunker/tool-py/capture_golden.pyinternal/ingestion/component/chunker/tool-py/live_chunk.py
| text, _ := ck["text"].(string) | ||
| if len(text) > 40 { | ||
| text = text[:40] + "..." | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Truncate by runes, not bytes.
text[:40] cuts the string at a byte offset. For multi-byte UTF-8 content the cut can split a rune and emit invalid UTF-8 into the failure message. The corpus covers many languages, so this is reachable.
🛠️ Proposed fix
text, _ := ck["text"].(string)
- if len(text) > 40 {
- text = text[:40] + "..."
+ if r := []rune(text); len(r) > 40 {
+ text = string(r[:40]) + "..."
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| text, _ := ck["text"].(string) | |
| if len(text) > 40 { | |
| text = text[:40] + "..." | |
| } | |
| text, _ := ck["text"].(string) | |
| if r := []rune(text); len(r) > 40 { | |
| text = string(r[:40]) + "..." | |
| } |
🤖 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 `@internal/ingestion/component/chunker/golden_parity_test.go` around lines 546
- 549, Update the text truncation logic in the golden parity test to limit the
string to 40 Unicode runes rather than 40 bytes, preserving valid UTF-8 for
multilingual content; append the existing ellipsis only when truncation occurs.
| if rule := matchedRatchetRule(rules, tc.ID); rule != nil { | ||
| // Documented divergence: Python is the truth and Go diverges by | ||
| // design (a known go_bug). A live mismatch is expected; a live | ||
| // match means the bug was fixed and the rule should be dropped. | ||
| if diffs := chunkDiffs(want, got, allowedExtra); len(diffs) == 0 { | ||
| t.Logf("known-diff %s RESOLVED live — remove rule from known_diffs.json", rule.ID) | ||
| } else { | ||
| t.Logf("known-diff %s still diverges live (expected): %d diff(s)", rule.ID, len(diffs)) | ||
| } | ||
| return | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
A resolved known diff is invisible by default.
Both branches call t.Logf and return, so the subtest always passes. go test suppresses logs for passing tests unless -v is set. The "RESOLVED live" message is the one actionable outcome of this harness, and a maintainer running the manual test without -v never sees it. golden_parity_test.go treats the same condition as a failure at line 334. Use t.Errorf here so the stale rule surfaces.
🛠️ Proposed fix
if diffs := chunkDiffs(want, got, allowedExtra); len(diffs) == 0 {
- t.Logf("known-diff %s RESOLVED live — remove rule from known_diffs.json", rule.ID)
+ t.Errorf("known-diff %s RESOLVED live — remove rule %q from known_diffs.json", rule.ID, rule.ID)
} else {
t.Logf("known-diff %s still diverges live (expected): %d diff(s)", rule.ID, len(diffs))
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if rule := matchedRatchetRule(rules, tc.ID); rule != nil { | |
| // Documented divergence: Python is the truth and Go diverges by | |
| // design (a known go_bug). A live mismatch is expected; a live | |
| // match means the bug was fixed and the rule should be dropped. | |
| if diffs := chunkDiffs(want, got, allowedExtra); len(diffs) == 0 { | |
| t.Logf("known-diff %s RESOLVED live — remove rule from known_diffs.json", rule.ID) | |
| } else { | |
| t.Logf("known-diff %s still diverges live (expected): %d diff(s)", rule.ID, len(diffs)) | |
| } | |
| return | |
| } | |
| if rule := matchedRatchetRule(rules, tc.ID); rule != nil { | |
| // Documented divergence: Python is the truth and Go diverges by | |
| // design (a known go_bug). A live mismatch is expected; a live | |
| // match means the bug was fixed and the rule should be dropped. | |
| if diffs := chunkDiffs(want, got, allowedExtra); len(diffs) == 0 { | |
| t.Errorf("known-diff %s RESOLVED live — remove rule %q from known_diffs.json", rule.ID, rule.ID) | |
| } else { | |
| t.Logf("known-diff %s still diverges live (expected): %d diff(s)", rule.ID, len(diffs)) | |
| } | |
| return | |
| } |
🤖 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 `@internal/ingestion/component/chunker/live_parity_test.go` around lines 142 -
152, The resolved known-diff branch in the live parity test currently logs only
through t.Logf, so stale rules are hidden during normal test runs. In the
matchedRatchetRule handling, replace the logging for len(diffs) == 0 with
t.Errorf while preserving the existing divergence logging and return behavior.
| func TestSplitOversizedUnitMatchesPython(t *testing.T) { | ||
| tc := loadCase(t, "testdata/parity/cases/token__b1_count_sensitive.json") | ||
| text, _ := tc.Input["text"].(string) | ||
| budget := int(tc.Param["chunk_token_size"].(float64)) | ||
|
|
||
| got := splitOversizedUnitWith(text, budget, tokenizeStr) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Keep this regression test self-contained in this layer.
Line 36 loads token__b1_count_sensitive.json, but the supplied stack adds that fixture in the later parity-corpus layer. This test will fail when this oversized-packing layer runs without the later fixture. Inline the case data here, or move this test with the fixture-owning layer.
🤖 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 `@internal/ingestion/component/chunker/split_oversized_test.go` around lines 35
- 40, Make TestSplitOversizedUnitMatchesPython self-contained by removing its
dependency on loadCase and the later parity fixture
token__b1_count_sensitive.json. Inline the required input text and
chunk_token_size values directly in the test while preserving the existing
splitOversizedUnitWith call and regression coverage.
| "output_format": "text", | ||
| "text": "RAGFlow is an open-source retrieval-augmented generation engine.\nIt ingests documents of many types and splits them into chunks.\nEach chunk is embedded and stored in a vector database for retrieval.\nThe chunker honours document structure such as headings and tables.\nLong paragraphs are divided so each chunk fits a token budget.\nOverlap between chunks preserves context across boundaries.\nRetrieval returns the most relevant chunks for a user question.\nThe generator then composes an answer from those chunks.\nEvaluation measures faithfulness and answer relevance.\nUsers tune chunk size to balance recall and precision.\nSmaller chunks improve recall but increase storage cost.\nLarger chunks keep more context but may dilute relevance.\nThe system supports many languages and encodings.\nDeep parsing extracts text from PDF images and scans.\nTables are recognised and preserved as structured chunks.\nImages can be described and attached to neighbouring text.\nThe API exposes dataset, document, and chat endpoints.\nA web UI lets users manage knowledge bases visually.\nBatch ingestion processes large corpora efficiently.\nConcurrency limits protect the embedding service.\nCaching avoids re-embedding unchanged content.\nLogging records ingestion progress and errors.\nMetrics help operators spot slow components.\nConfiguration controls parsers and chunking strategies.\nTemplates encode common ingestion pipelines.\nThe engine scales horizontally behind a load balancer.\nSecurity isolates tenant data by document id.\nAuditing tracks who accessed which knowledge base.\nPlugins extend parsing for proprietary formats." | ||
| }, | ||
| "notes": "Default delimiter ['\\n'] -> Python naive_merge('') -> 1 chunk (PY-BUG). Corpus has many '\\n' boundaries so Go segments and merges by token size into many chunks. Also a tokenizer-liveness guard: a dead tokenizer (0 tokens) collapses all segments into 1 chunk." |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rules="internal/ingestion/component/chunker/testdata/parity/known_diffs.json"
rg -n -C 6 'token__text_default_delim|chunk_count|chunk_text|applies_to' "$rules"Repository: infiniflow/ragflow
Length of output: 6638
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the parity harness around matchedRatchetRule and compareChunks.
rg -n -C 8 'matchedRatchetRule|compareChunks|known_diffs|knownDiffs|chunk_count|chunk_text|ratchet' internal/ingestion/component/chunker/testdata/parity internal/ingestion/component/chunker -g '*.go' -g '*.json'
# Show the exact fixture.
sed -n '1,80p' internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.jsonRepository: infiniflow/ragflow
Length of output: 50374
Add a narrow snapshot ratchet for token__text_default_delim.
known_diffs.json has no matching chunk_count/chunk_text rule, and token__* only covers extra_fields. The harness will use strict compareChunks for this case, so either add the documented chunk-count divergence or remove the fixture intentionally.
🤖 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
`@internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json`
at line 15, The token__text_default_delim parity case lacks the required
snapshot expectation for its chunk output. Update the parity expectations, such
as known_diffs.json, with a narrow chunk_count/chunk_text rule documenting the
intended divergence, or intentionally remove the token__text_default_delim
fixture so strict compareChunks does not run without coverage.
| "notes": "overlapped_percent on the text path: locks that the overlap carried into each following chunk is byte-identical on both sides.", | ||
| "param": { | ||
| "chunk_token_size": 64, | ||
| "delimiters": [ | ||
| "\n" | ||
| ], | ||
| "overlapped_percent": 0.1 |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rules="internal/ingestion/component/chunker/testdata/parity/known_diffs.json"
rg -n -C 8 'token-text-overlap-split|token__text_overlap|chunk_text' "$rules"Repository: infiniflow/ragflow
Length of output: 5223
Narrow the chunk_text ratchet or fix the invariant.
token-text-overlap-split applies to token__text_overlap, so the parity test can now skip text-output mismatches. Fix the overlap-prefix handling and remove this chunk_text ratchet entry, or remove/update this fixture if byte-identical overlap is not enforced.
🤖 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
`@internal/ingestion/component/chunker/testdata/parity/cases/token__text_overlap.json`
around lines 4 - 10, Fix the overlap-prefix handling used by the
token-text-overlap-split path so overlapped text remains byte-identical between
consecutive chunks, then remove the chunk_text ratchet entry from the
token__text_overlap parity fixture. If byte-identical overlap is not intended,
update or remove the fixture instead of retaining the ratchet.
| "kind": "chunk_count", | ||
| "applies_to": ["token__json_multi_item_40", "token__json_two_item"], | ||
| "owner_fix_side": "go", | ||
| "tracking": "TODO: file issue — TokenChunker json path merges per item (one chunk per item) instead of globally like Python _merge_text_chunks_by_token_size", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Replace placeholder tracking values with filed issue links.
These non-permanent go_bug rules ratchet known production divergences. The registry accepts each placeholder because it only checks for a non-empty string. The golden harness then accepts the divergence. File the remediation issues and replace each TODO: file issue value before merge.
internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L28-L28: add the issue link for cross-item JSON merging.internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L37-L37: add the issue link for custom-delimiter text behavior.internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L46-L46: add the issue link for JSON delimiter trimming.internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L55-L55: add the issue link for oversized single JSON items.internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L64-L64: add the issue link for overlap-prefix behavior.
As per coding guidelines, remove “move later” notes instead of preserving them.
📍 Affects 1 file
internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L28-L28(this comment)internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L37-L37internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L46-L46internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L55-L55internal/ingestion/component/chunker/testdata/parity/known_diffs.json#L64-L64
🤖 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 `@internal/ingestion/component/chunker/testdata/parity/known_diffs.json` at
line 28, Replace the TODO placeholder tracking values with the filed issue links
for all five entries in
internal/ingestion/component/chunker/testdata/parity/known_diffs.json: lines 28,
37, 46, 55, and 64, covering cross-item JSON merging, custom-delimiter text
behavior, JSON delimiter trimming, oversized single JSON items, and
overlap-prefix behavior. Remove any “move later” notes rather than retaining
them.
Source: Coding guidelines
| 2. Capture the Python baseline and run the Go side: | ||
|
|
||
| ```bash | ||
| source .venv/bin/activate && export PYTHONPATH=$(pwd) | ||
| python internal/ingestion/component/chunker/tool-py/capture_golden.py --case <id> | ||
| CGO_ENABLED=0 go test -count=1 ./internal/ingestion/component/chunker/ -run TestChunkerGoldenParity | ||
| ``` |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
while IFS= read -r script; do
printf '%s\n' "== $script =="
rg -n -C 4 'go test|chunker|CGO_ENABLED' "$script"
done < <(fd -t f '^build\.sh$' .)Repository: infiniflow/ragflow
Length of output: 208
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== build.sh files =="
fd -a '^build\.sh$' . | sed 's#^\./##'
echo
echo "== target file context =="
sed -n '1,90p' internal/ingestion/component/chunker/testdata/parity/README.md
echo
echo "== go test / chunker / CGO references in build.sh files =="
while IFS= read -r script; do
printf '%s\n' "== $script =="
rg -n -C 5 'go test|chunker|CGO_ENABLED' "$script" || true
done < <(fd -a '^build\.sh$' .)Repository: infiniflow/ragflow
Length of output: 3676
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== root build.sh =="
cat -n build.sh
echo
echo "== all build.sh files =="
fd -a '^build\.sh$' . | sort | sed 's#^\./##'
echo
echo "== build.sh contents via file list output parsing =="
fd -a '^build\.sh$' . | sort | while IFS= read -r script; do
echo "== $script =="
rg -n -C 5 'go test|chunker|CGO_ENABLED|go_build_flags|cgo|go test' "$script" || true
doneRepository: infiniflow/ragflow
Length of output: 31906
Use build.sh for the documented Go test command.
Line 55 runs raw go test, but this repository uses /build.sh --test to set up the CGO environment and native static libraries. Replace it with:
./build.sh --test -run TestChunkerGoldenParity ./internal/ingestion/component/chunker/...If this parity test intentionally requires CGO_ENABLED=0, document that constraint instead of using the default CGO-enabled test command.
🤖 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 `@internal/ingestion/component/chunker/testdata/parity/README.md` around lines
50 - 56, Update the documented Go command in the parity README to use ./build.sh
--test -run TestChunkerGoldenParity ./internal/ingestion/component/chunker/...
instead of raw go test, preserving the Python baseline command. If the parity
test requires CGO_ENABLED=0, document that requirement explicitly rather than
using the default build script invocation.
Source: Coding guidelines
| | Field | Meaning | | ||
| |---|---| | ||
| | `id` | Stable rule name. | | ||
| | `tag` | `python_bug`, `go_bug`, `go_intentional`, or `unresolved`. | | ||
| | `kind` | Currently `extra_fields`. | | ||
| | `applies_to` | Case-id patterns (`path.Match` globs, e.g. `token__*`, `*`). | | ||
| | `fields` | For `extra_fields`: the Go-only chunk keys this rule permits. | | ||
| | `reason` | Why the difference exists, with file:line references. | | ||
| | `permanent` | `true` if the difference is by design and will not be fixed. | | ||
| | `owner_fix_side` | Which side should change: `python`, `go`, or `tbd`. | | ||
| | `tracking` | Issue link. Required unless `permanent` is true. | |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Update the known_diffs.json schema table.
Line 86 says that kind is currently only extra_fields. The PR adds accepted chunk-count and chunk_text differences, so this table does not describe the current ratchet contract. Document each supported kind and the fields that each kind compares. Stale schema guidance can cause invalid rules or overly broad exceptions.
Based on the PR objectives, the ratchet now tracks field, chunk-count, and text differences.
🤖 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 `@internal/ingestion/component/chunker/testdata/parity/README.md` around lines
82 - 92, Update the known_diffs.json schema documentation in the table around
kind and fields to list all supported difference kinds: field, chunk-count, and
chunk_text. Describe which fields each kind compares, while preserving the
existing extra_fields guidance and ensuring the table matches the ratchet
contract.
| def write_manifest() -> None: | ||
| """Record provenance in one shared file. | ||
|
|
||
| Kept out of the per-case golden files so a re-capture does not touch every | ||
| fixture's diff with a new timestamp. | ||
| """ |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
--case rewrites the whole-corpus manifest.
main calls write_manifest() after any write run. With --case ID, only one golden file is refreshed, but the manifest records a new captured_at and commit for the entire corpus. The provenance then overstates what was captured. Either skip the manifest write for --case, or record the captured case IDs in the manifest.
Also applies to: 256-256
🤖 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 `@internal/ingestion/component/chunker/tool-py/capture_golden.py` around lines
180 - 185, Update the write flow in main and write_manifest so a --case ID run
does not rewrite corpus-level provenance, or instead records only the captured
case ID(s) in the manifest. Preserve the existing full-corpus manifest behavior
for write runs without --case.
| path = CASES_DIR / f"{case_id}.json" | ||
| if not path.exists(): | ||
| sys.stderr.write(f"no case file {path}\n") | ||
| return 2 | ||
|
|
||
| case = json.loads(path.read_text(encoding="utf-8")) | ||
| _assert_tokenizer_alive() | ||
| result = run_case(case) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Validate the case id against the filename stem.
load_cases in capture_golden.py rejects a case whose id does not match its filename stem. golden_parity_test.go and live_parity_test.go apply the same check. This script skips it. A mismatched fixture therefore runs under one identity in Python and another in Go, and the live comparison silently pairs the wrong outputs.
🛠️ Proposed fix
case = json.loads(path.read_text(encoding="utf-8"))
+ if case["id"] != path.stem:
+ sys.stderr.write(f"{path}: case id {case['id']!r} does not match filename stem {path.stem!r}\n")
+ return 2
_assert_tokenizer_alive()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| path = CASES_DIR / f"{case_id}.json" | |
| if not path.exists(): | |
| sys.stderr.write(f"no case file {path}\n") | |
| return 2 | |
| case = json.loads(path.read_text(encoding="utf-8")) | |
| _assert_tokenizer_alive() | |
| result = run_case(case) | |
| path = CASES_DIR / f"{case_id}.json" | |
| if not path.exists(): | |
| sys.stderr.write(f"no case file {path}\n") | |
| return 2 | |
| case = json.loads(path.read_text(encoding="utf-8")) | |
| if case["id"] != path.stem: | |
| sys.stderr.write(f"{path}: case id {case['id']!r} does not match filename stem {path.stem!r}\n") | |
| return 2 | |
| _assert_tokenizer_alive() | |
| result = run_case(case) |
🧰 Tools
🪛 ast-grep (0.45.0)
[info] 62-62: use jsonify instead of json.dumps for JSON output
Context: json.dumps(result, ensure_ascii=False, sort_keys=True, indent=1)
Note: [CWE-116] Improper Encoding or Escaping of Output.
(use-jsonify)
🤖 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 `@internal/ingestion/component/chunker/tool-py/live_chunk.py` around lines 55 -
62, Validate the loaded case’s id against the JSON filename stem in the
live_chunk.py case-loading flow before calling _assert_tokenizer_alive() or
run_case(case). Reject mismatches with the same failure behavior and clear
diagnostic used by load_cases, golden_parity_test.go, and live_parity_test.go,
while preserving processing for matching fixtures.
…ush (#17729) ## Summary Align Go `splitOversizedUnitWith` with Python `rag/nlp._split_oversized_unit` so the whitespace-atom sub-split produces byte-identical chunk boundaries. ### Root cause of the divergence cl100k token counting is **not additive across whitespace joins** (`token(a)+token(b) != token(a+b)`). Go previously used the exact joined-string fit check `countFn(current+atom) > budget`, while Python accumulates a running sum `current_tokens + a_tokens > budget`. The two formulas disagree by one atom at the boundary, so Go and Python emitted the same chunk *count* but shifted *text*. ### Changes - `splitOversizedUnitWith` (`token.go`): replace the exact joined-string fit check with the running-sum check (mirroring Python's `current_tokens` accumulator), and after a flush keep the overflow whitespace atom (`current += atom`) instead of dropping it. - `token_strict_cap_test.go`: relax `TestMergeByTokenSizeFromJSON_OversizedUnitIsSubSplit` to allow the same cl100k non-additive +1 overshoot Python exhibits (the invariant — an oversized unit is sub-split, not collapsed — is preserved). ### Test plan `bash build.sh --test ./internal/ingestion/component/chunker/...` — green. ## Note Test infrastructure for this change (golden parity harness, `split_oversized_test.go`, `testdata/parity/**`, `known_diffs.json`, `capture_golden.py`/`live_chunk.py`, and the `go-cmp` dependency promotion) is split into a separate, stacked PR #17735 so this PR stays minimal (production code only). This PR is **independent of #17712** (the offline BPE loader). It is based on `upstream/main` and contains only this change; no BPE-loader code is included. Co-authored-by: CodeBuddy <[email protected]>
…m flush (#17740) ## Summary Adds a self-contained regression guard for `splitOversizedUnitWith` after PR #17729 aligned it with Python's `rag/nlp._split_oversized_unit` running-sum flush. #17729 shipped a `slack=1` relaxation in `token_strict_cap_test.go` (the oversized unit is now sub-split with the same running-sum flush Python uses, which can leave a piece one token over the nominal budget due to cl100k non-additivity). This PR adds the missing positive proof that the sub-split boundaries are correct, so the relaxed assertion is no longer unguarded. ## Changes - `split_oversized_guard_test.go` (new, self-contained — no harness loader, no `testdata`; the Python oracle is inlined): - `TestSplitOversizedUnitRunningSumMatchesPython`: asserts the exact piece boundaries (live tokenizer) match Python's `_split_oversized_unit`, compensating the `slack=1` relaxation from #17729. - `TestSplitOversizedUnitDeadTokenizerCollapses`: asserts a zero-counting tokenizer collapses the B1 paragraph into exactly one chunk, catching a silently dead encoder that a non-empty-result check would miss. ## Notes - Test function names are deliberately distinct from PR #17735's `TestSplitOversizedUnitMatchesPython`, so the two PRs verify independently and do not conflict at merge time. - PR #17735 (golden parity harness) is intentionally left unchanged per the split plan. ## Test plan `bash build.sh --test ./internal/ingestion/component/chunker/` — green, including both new tests. Co-authored-by: CodeBuddy <[email protected]>
…gistry Introduce the chunker golden-parity test infrastructure, kept separate from the splitOversizedUnitWith bug fix so the fix PR stays minimal: - golden_parity_test.go: harness that runs the Go chunker over the parity case set and diffs it against committed golden JSON, honoring a known_diffs.json ratchet (extra_fields / chunk_count / chunk_text) so accepted divergences are tracked rather than silently widening. - split_oversized_test.go: focused regression test pinning the splitOversizedUnitWith running-sum boundary against an embedded Python oracle (token__b1_count_sensitive case). - testdata/parity/: case inputs (cases/), captured golden outputs (golden/), Go snapshot ratchet (go_snapshot/), the known_diffs.json registry, and a README. The B1 case also acts as a CI guard that catches a silently dead tokenizer (a dead tokenizer collapses the long paragraph to one chunk). - tool-py/capture_golden.py: regenerates the golden from the live Python chunker. - go.mod: promote github.com/google/go-cmp to a direct dependency (used by the harness). Co-Authored-By: CodeBuddy <[email protected]>
…solete known-diff rule Python PR infiniflow#17721 now forwards configured delimiters to naive_merge, so the golden for the default-delim / token-liveness cases must be re-captured: Go already splits on the configured '\n' delimiter, and Python now matches it. The token-text-delimiters-dropped rule is therefore obsolete and removed. token-text-overlap-split is reclassified from chunk_count to chunk_text: the chunk-count divergence (Python 2 vs Go 3) was also resolved by infiniflow#17721, leaving only a residual overlap-prefix-length content divergence on the text path. Co-Authored-By: CodeBuddy <[email protected]>
TestChunkerLiveParity invokes the real Python chunker (.venv/bin/python) at test time and compares its chunks against Go's invokeChunker output, so the comparison can never go stale against a committed golden. Known-diff ratchet rules are still honored: a rule whose cases now match live Python is logged as RESOLVED, while still-diverging rules are logged instead of failing. Tagged //go:build manual: requires the ragflow .venv + cl100k table, so it is opt-in locally and never runs in CI. Co-Authored-By: CodeBuddy <[email protected]>
…finiflow#17723/infiniflow#17808) Python reference changed via infiniflow#17723 (custom-delimiter rewrite) and infiniflow#17808 (OVER_CAP default + delimiter boundary). Re-capture all golden fixtures so the parity oracle reflects current Python before the Go-side alignment work. Co-authored-by: xugangqiang <>
…itWith helper splitOversizedUnitWith / splitAtomByTokenBudget were removed from the chunker by contract infiniflow#17799 (parser-layer logic misplaced in the chunker). The running-sum / OVER_CAP behaviour is now covered by token_merge_*.go, token_batch1_test.go, token_strict_cap_test.go in main, and the b1 case is already pinned end-to-end by golden_parity_test.go (token__b1_count_sensitive). Keeping this test would break compilation of the parity package.
After rebasing onto upstream/main (which merged infiniflow#17739/infiniflow#17835/infiniflow#17854/infiniflow#17868): - Remove 4 go_bug rules now resolved by merged fixes: token-json-per-item-merge, token-json-custom-delim-drops-newline, token-json-single-item-oversize, token-text-overlap-split. - Delete their go_snapshot files; also drop 4 orphaned tokenizer go_snapshot files that the harness never reads (strict-compare path). - Refresh the 3 remaining ratcheted snapshots for token-custom-delim-newline-and-field (html/markdown/text_backtick), whose Go output shifted under the merged delimiter/children-split fixes but the divergence itself persists. The 4 tokenizer-count cases (text/html/markdown_default_delim, text_token_liveness) now match the Python golden strict-compare with no rule, i.e. the tokenizer count mismatch is resolved. Harness is green under both plain and -update runs.
80f0591 to
cc7eb0f
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/ingestion/component/chunker/testdata/parity/known_diffs.json (1)
23-29: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winSeparate the
doc_type_kwddivergence from the text divergence.This rule declares
kind: "chunk_text", but its reason also documents a Go-onlydoc_type_kwdfield. The registry usesfieldsto declare allowed extra fields, and this rule declares none. Split the text difference and field difference into separate rules, or verify that the harness intentionally ratchets both under one rule. This lets the text rule be retired independently when the delimiter behavior is fixed.🤖 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 `@internal/ingestion/component/chunker/testdata/parity/known_diffs.json` around lines 23 - 29, Separate the custom-delimiter text mismatch from the extra doc_type_kwd field mismatch in the parity registry. Update the existing token-custom-delim-newline-and-field rule to cover only retained-delimiter text behavior, and add a distinct rule with the appropriate fields declaration for the doc_type_kwd difference so the text rule can be retired independently.
🤖 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
`@internal/ingestion/component/chunker/testdata/parity/golden/token__b1_count_sensitive.json`:
- Around line 3-7: Regenerate the golden baseline for token__b1_count_sensitive
using valid token counting so the 1,140-character paragraph with
chunk_token_size=50 produces the expected multiple chunks. Ensure the updated
chunks reflect the Python reference implementation; remove this case only if it
is not intended to represent that baseline.
In `@internal/ingestion/component/chunker/tool-py/capture_golden.py`:
- Around line 224-257: Add stderr logging in capture_golden.py around the main
case-processing flow to report the selected case count, capture mode,
write/check result, and drift count without logging chunk contents; update
live_chunk.py to log the requested case ID and completion status to stderr while
preserving stdout as JSON-only output. Apply the capture changes at
internal/ingestion/component/chunker/tool-py/capture_golden.py:224-257 and the
live command changes at
internal/ingestion/component/chunker/tool-py/live_chunk.py:50-64.
- Around line 187-193: Update the git revision lookup in the subprocess.run call
to resolve the executable via shutil.which("git") before invocation, and handle
a missing path explicitly before constructing the command. Pass the resolved
absolute path as the executable while preserving the existing rev-parse HEAD
behavior.
---
Nitpick comments:
In `@internal/ingestion/component/chunker/testdata/parity/known_diffs.json`:
- Around line 23-29: Separate the custom-delimiter text mismatch from the extra
doc_type_kwd field mismatch in the parity registry. Update the existing
token-custom-delim-newline-and-field rule to cover only retained-delimiter text
behavior, and add a distinct rule with the appropriate fields declaration for
the doc_type_kwd difference so the text rule can be retired independently.
🪄 Autofix
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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4af5d78d-b170-42f0-bb18-029ef9cb11be
📒 Files selected for processing (59)
go.modinternal/ingestion/component/chunker/golden_parity_test.gointernal/ingestion/component/chunker/live_parity_test.gointernal/ingestion/component/chunker/testdata/parity/README.mdinternal/ingestion/component/chunker/testdata/parity/_manifest.jsoninternal/ingestion/component/chunker/testdata/parity/cases/title__group_simple.jsoninternal/ingestion/component/chunker/testdata/parity/cases/title__hierarchy_2level.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__empty_input.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__html_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__html_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__html_long.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_children_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_img_id.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_multi_item_40.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_single.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_single_long.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_table_context.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__json_two_item.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__markdown_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__markdown_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__markdown_long.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_long_paragraph.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/cases/token__text_token_liveness.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__html_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__markdown_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/go_snapshot/token__text_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/title__group_simple.jsoninternal/ingestion/component/chunker/testdata/parity/golden/title__hierarchy_2level.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__b1_count_sensitive.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__empty_input.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__html_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__html_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__html_long.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_children_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_img_id.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_multi_item_40.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_single.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_single_long.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_table_context.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__json_two_item.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__markdown_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__markdown_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__markdown_long.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_backtick.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_default_delim.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_long_paragraph.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_overlap.jsoninternal/ingestion/component/chunker/testdata/parity/golden/token__text_token_liveness.jsoninternal/ingestion/component/chunker/testdata/parity/known_diffs.jsoninternal/ingestion/component/chunker/tool-py/capture_golden.pyinternal/ingestion/component/chunker/tool-py/live_chunk.py
🚧 Files skipped from review as they are similar to previous changes (51)
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_multi_item_40.json
- internal/ingestion/component/chunker/testdata/parity/go_snapshot/token__text_backtick.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__markdown_long.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__markdown_default_delim.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__empty_input.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__text_default_delim.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__text_overlap.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_single_long.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__html_backtick.json
- go.mod
- internal/ingestion/component/chunker/testdata/parity/cases/token__text_long_paragraph.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_table_context.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_single.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_overlap.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_img_id.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_single_long.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_single.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__html_backtick.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_backtick.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_two_item.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_children_delim.json
- internal/ingestion/component/chunker/testdata/parity/cases/title__hierarchy_2level.json
- internal/ingestion/component/chunker/testdata/parity/_manifest.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__text_backtick.json
- internal/ingestion/component/chunker/testdata/parity/cases/title__group_simple.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__text_token_liveness.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_table_context.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_overlap.json
- internal/ingestion/component/chunker/testdata/parity/golden/title__group_simple.json
- internal/ingestion/component/chunker/testdata/parity/go_snapshot/token__html_backtick.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__markdown_backtick.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_two_item.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__html_long.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__empty_input.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__text_backtick.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__markdown_backtick.json
- internal/ingestion/component/chunker/testdata/parity/golden/title__hierarchy_2level.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__html_default_delim.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__markdown_default_delim.json
- internal/ingestion/component/chunker/testdata/parity/go_snapshot/token__markdown_backtick.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_multi_item_40.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__html_default_delim.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__json_img_id.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__text_token_liveness.json
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_children_delim.json
- internal/ingestion/component/chunker/testdata/parity/README.md
- internal/ingestion/component/chunker/testdata/parity/cases/token__json_backtick.json
- internal/ingestion/component/chunker/testdata/parity/golden/token__text_default_delim.json
- internal/ingestion/component/chunker/golden_parity_test.go
- internal/ingestion/component/chunker/live_parity_test.go
| "chunks": [ | ||
| { | ||
| "text": "RAGFlow is a retrieval augmented generation engine that ingests heterogeneous documents and slices them into retrievable passages. The chunker must respect a token budget so that each passage fits the context window of the downstream language model without truncation. Token counting is the linchpin of this budget because every merge decision reads the per segment token length. When the encoder is missing the chunker silently reports zero tokens for every string and the budget is never exceeded so an entire document collapses into one oversized chunk. That degenerate behaviour is invisible to a test that only checks for a non empty result because zero is a number like any other. The only way to notice is to compare the actual chunk count against a reference implementation that counts tokens correctly. This case pins that comparison with a long single paragraph and a deliberately small budget so the correct count yields many chunks and a dead encoder yields exactly one. Retrieval quality depends on passages being coherent and appropriately sized so the guard is not merely cosmetic but protects the core promise of the system." | ||
| } | ||
| ] |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate files =="
git ls-files | rg 'internal/ingestion/component/chunker/(testdata/golden|.*golden.*parity.*test\.go|.*chunker.*test.*\.go)' || true
echo
echo "== target fixture =="
TARGET="internal/ingestion/component/sharder/testdata/parity/golden/token__b1_count_sensitive.json"
if [ -f "$TARGET" ]; then
cat -n "$TARGET"
fi
TARGET2="internal/ingestion/component/chunker/testdata/parity/golden/token__b1_count_sensitive.json"
echo
if [ -f "$TARGET2" ]; then
cat -n "$TARGET2"
fi
echo
echo "== search token__b1_count_sensitive =="
rg -n --hidden --glob '!**/.git/**' 'token__b1_count_sensitive|count_sensitive|b1' internal 2>/dev/null || true
echo
echo "== outline golden parity tests =="
for f in $(git ls-files | rg 'golden_parity_test\.go|chunker.*test\.go|ingestion/component/chunker' | head -100); do
echo "--- $f"
wc -l "$f"
doneRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate relevant code snippets =="
for f in $(git ls-files | rg 'golden_parity_test\.go|chunker.*parity.*\.go|chunker.*test.*\.go' | head -80); do
echo "--- $f"
rg -n -C 4 'chunks|want|case_id|count_sensitive|TestChunkerGoldenParity|golden|Python|baseline' "$f" || true
done
echo
echo "== all chunker golden directories =="
find internal/ingestion/component/chunker -type d | sort | head -80
find internal/ingestion/component/chunker -path '*/golden/*' -type f | sort | head -200Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate relevant code snippets =="
for f in $(git ls-files | rg 'golden_parity_test\.go|chunker.*parity.*\.go|chunker.*test.*\.go' | head -80); do
echo "--- $f"
rg -n -C 4 'chunks|want|case_id|count_sensitive|TestChunkerGoldenParity|golden|Python|baseline' "$f" || true
done
echo
echo "== all chunker golden directories =="
find internal/ingestion/component/chunker -type d |.sort | head -80
find internal/ingestion/component/chunker -path '*/golden/*' -type $f | sort | head -200Repository: infiniflow/ragflow
Length of output: 50377
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== token__b1_count_sensitive case =="
CASE="internal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.json"
if [ -f "$CASE" ]; then
cat -n "$CASE"
fi
echo
echo "== relevant parity harness implementation slices =="
sed -n '76,90p;147,174p;193,210p;220,236p;265,270p' internal/ingestion/component/chunker/golden_parity_test.go | cat -n
echo
echo "== token__b1_count_sensitive text length =="
python3 - <<'PY'
import json, pathlib
path = pathlib.Path("internal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.json")
data = json.loads(path.read_text()) if path.exists() else {}
input_text = ""
if "input" in data:
if "text" in data["input"]:
input_text = data["input"]["text"]
elif "markdown" in data["input"]:
input_text = data["input"]["markdown"]
print(data.get("id"))
print(data.get("component"))
print(data.get("param", {}).get("chunk_token_size"))
print("input_type", tuple(k for k in data.get("input",{}).keys()))
print("input_len", len(input_text))
print("input_lines", input_text.count("\n")+1 if input_text else 0)
PYRepository: infiniflow/ragflow
Length of output: 5755
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== token__b1_count_sensitive case =="
CASE="internal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.json"
if [ -f "$CASE" ]; then
cat -n "$CASE"
fi
echo
echo "== relevant parity harness implementation slices =="
sed -n '76,90p;147,174p;193,210p;220,236p;265,270p' internal/ingestion/component/chunker/golden_parity_test.go | cat -n
echo
echo "== token__b1_count_sensitive text length =="
python3 - <<'PY'
import json, pathlib
path = pathlib.Path("internal/ingestion/component/chunker/testdata/parity/cases/token__b1_count_sensitive.json")
data = json.loads(path.read_text()) if path.exists() else {}
input_text = ""
if "input" in data:
if "text" in data["input"]:
input_text = data["input"]["text"]
elif "markdown" in data["input"]:
input_text = data["input"].markdown"]
print(data.get("id"))
print(data.get("component"))
print(data.get("param", {}).get("chunk_token_size"))
print("input_type", tuple(k for k in data.get("input",{}).keys()))
print("input_len", len(input_text))
print("input_lines", input_text.count("\n")+1 if input_text else 0)
PYRepository: infiniflow/ragflow
Length of output: 5796
Regenerate this golden baseline.
token__b1_count_sensitive uses chunk_token_size=50 on a 1,140-character single paragraph, and the case notes say the correct Python baseline should split it into many chunks. The golden value has one chunk, so this lets a zero-token Go split pass and does not exercise the token-count guard. Regenerate the baseline with valid token counting, or remove the case if it is not the intended Python baseline.
🤖 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
`@internal/ingestion/component/chunker/testdata/parity/golden/token__b1_count_sensitive.json`
around lines 3 - 7, Regenerate the golden baseline for token__b1_count_sensitive
using valid token counting so the 1,140-character paragraph with
chunk_token_size=50 produces the expected multiple chunks. Ensure the updated
chunks reflect the Python reference implementation; remove this case only if it
is not intended to represent that baseline.
| commit = subprocess.run( | ||
| ["git", "rev-parse", "HEAD"], | ||
| cwd=REPO_ROOT, | ||
| capture_output=True, | ||
| text=True, | ||
| check=True, | ||
| ).stdout.strip() |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Resolve git to an absolute executable path.
Line 188 starts git by its partial path. Ruff reports S607 for this call. Resolve the executable with shutil.which() and handle a missing result before calling subprocess.run().
Proposed fix
+import shutil
+
def write_manifest() -> None:
+ git = shutil.which("git")
+ if git is None:
+ commit = "unknown"
+ else:
try:
commit = subprocess.run(
- ["git", "rev-parse", "HEAD"],
+ [git, "rev-parse", "HEAD"],🧰 Tools
🪛 Ruff (0.16.1)
[error] 188-188: Starting a process with a partial executable path
(S607)
🤖 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 `@internal/ingestion/component/chunker/tool-py/capture_golden.py` around lines
187 - 193, Update the git revision lookup in the subprocess.run call to resolve
the executable via shutil.which("git") before invocation, and handle a missing
path explicitly before constructing the command. Pass the resolved absolute path
as the executable while preserving the existing rev-parse HEAD behavior.
Source: Linters/SAST tools
| _assert_tokenizer_alive() | ||
|
|
||
| GOLDEN_DIR.mkdir(parents=True, exist_ok=True) | ||
| cases = load_cases(args.case) | ||
|
|
||
| drifted: list[str] = [] | ||
| for case in cases: | ||
| first = serialize(run_case(case)) | ||
| # Determinism guard: a chunker that is not reproducible would otherwise | ||
| # bake its nondeterminism into the baseline, and every later parity | ||
| # failure would be unexplainable. | ||
| second = serialize(run_case(case)) | ||
| if first != second: | ||
| sys.exit(f"{case['id']}: non-deterministic output across two runs; refusing to write a golden file") | ||
|
|
||
| target = GOLDEN_DIR / f"{case['id']}.json" | ||
| if args.check: | ||
| existing = target.read_text(encoding="utf-8") if target.exists() else None | ||
| if existing != first: | ||
| drifted.append(case["id"]) | ||
| print(f"DRIFT {case['id']}", file=sys.stderr) | ||
| continue | ||
| target.write_text(first, encoding="utf-8") | ||
| print(f"wrote {target.relative_to(REPO_ROOT)}") | ||
|
|
||
| if args.check: | ||
| if drifted: | ||
| print(f"\n{len(drifted)} golden file(s) stale; re-run: {CAPTURE_CMD}", file=sys.stderr) | ||
| return 1 | ||
| print(f"{len(cases)} golden file(s) up to date") | ||
| return 0 | ||
|
|
||
| write_manifest() | ||
| return 0 |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Add stderr logging for the new command flows.
internal/ingestion/component/chunker/tool-py/capture_golden.py#L224-L257: Log the selected case count, mode, write/check result, and drift count. Do not log chunk text.internal/ingestion/component/chunker/tool-py/live_chunk.py#L50-L64: Log the requested case ID and completion status to stderr. Preserve stdout as JSON-only output.
As per coding guidelines, “Add logging for new flows.”
📍 Affects 2 files
internal/ingestion/component/chunker/tool-py/capture_golden.py#L224-L257(this comment)internal/ingestion/component/chunker/tool-py/live_chunk.py#L50-L64
🤖 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 `@internal/ingestion/component/chunker/tool-py/capture_golden.py` around lines
224 - 257, Add stderr logging in capture_golden.py around the main
case-processing flow to report the selected case count, capture mode,
write/check result, and drift count without logging chunk contents; update
live_chunk.py to log the requested case ID and completion status to stderr while
preserving stdout as JSON-only output. Apply the capture changes at
internal/ingestion/component/chunker/tool-py/capture_golden.py:224-257 and the
live command changes at
internal/ingestion/component/chunker/tool-py/live_chunk.py:50-64.
Source: Coding guidelines
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17735 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The case is now compared strictly (3 chunks on both sides, no ratchet rule), so the old 'PY-BUG -> 1 chunk' description was misleading.
…wline-and-field The rule reason described pre-infiniflow#17868 behaviour: Go kept the backtick delimiter via splitKeepingDelim. Since infiniflow#17868 Go uses splitDroppingDelim on both the text/markdown/html and JSON paths, so chunk text now matches Python exactly. The only remaining divergence is the extra doc_type_kwd:'text' field Go emits on this path, which Python's text-path output never includes. Update the reason and tracking note to reflect the single Go-only field.
Summary
Golden-parity test infrastructure for the Go
TokenChunker↔ Python alignment.It runs the Go chunker over a committed case set (
testdata/parity/cases/) and diffseach output against a captured Python golden (
testdata/parity/golden/), honoring aknown_diffs.jsonratchet (extra_fields/chunk_count/chunk_text) so accepteddivergences are tracked rather than silently widening.
The alignment itself landed in separate fix PRs (all merged): #17729, #17739, #17740,
#17835, #17854, #17868 (chunker) and #17712, #17928 (tokenizer). This PR carries
test infrastructure only — no production code.
golden_parity_test.go(default unit tier, gates CI): the harness above.live_parity_test.go(//go:build manual, opt-in):TestChunkerLiveParitycomparesGo vs live Python at test time, backed by
tool-py/live_chunk.py.tool-py/capture_golden.py+tool-py/live_chunk.py: regenerate the golden from live Python.testdata/parity/: cases, Python golden, Go snapshot ratchet (3 files for still-divergentcases),
known_diffs.jsonregistry, README.go.mod: promotegithub.com/google/go-cmpto a direct dependency (used by the harness).Current ratchet state
known_diffs.jsonholds 3 design-level rules (no chunk-count regressions):go-only-chunk-id/go-only-token-metadata— Go-onlyextra_fieldsPython strips at finalize.token-custom-delim-newline-and-field— on the backtick-delimiter text/markdown/html pathGo keeps the delimiter and emits
doc_type_kwd:'text', which Python does not.All previously tracked chunk-count / chunk-text divergences are resolved by the merged fix
PRs, so the harness is green. The 4 tokenizer-count cases (
token__*_default_delim,token__text_token_liveness) now match the Python golden under strict compare (tokenizercount alignment via #17712 / #17928), so they need no rule.
Note on
split_oversized_test.goAn earlier revision pinned
splitOversizedUnitWithagainst a Python oracle. That helper wasremoved by contract #17799 (parser-layer logic misplaced in the chunker); the running-sum /
OVER_CAP behaviour is now covered by
token_merge_*.goin main and end-to-end by thetoken__b1_count_sensitiveparity case, so the file was dropped.🤖 Generated with CodeBuddy