Repository navigation
fix(tokenizer): load cl100k BPE table from disk instead of failing silently offline - #17712
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe tokenizer now loads tiktoken BPE tables from local cache, working-directory, installation, and ancestor paths. It parses and validates candidate files, reports detailed errors, avoids network access, and adds coverage for discovery, precedence, malformed files, read errors, token counts, and CI test selection. ChangesOffline BPE loading
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Tiktoken
participant localBpeLoader
participant Filesystem
Tiktoken->>localBpeLoader: request BPE table
localBpeLoader->>Filesystem: search local candidate paths
Filesystem-->>localBpeLoader: return candidate file
localBpeLoader->>localBpeLoader: parse and validate BPE ranks
localBpeLoader-->>Tiktoken: return table or loading error
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: 5
🤖 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/tokenizer/bpe_loader_test.go`:
- Around line 186-204: Move TestNumTokensFromString_MatchesPythonAnchors into a
separate test file guarded by the appropriate manual or integration build tag
before the package declaration, since it relies on an externally discoverable
cl100k_base table. Leave the isolate(t)-based tests in the current file untagged
so the tokenizer package can run in CI without this environment-dependent test.
In `@internal/tokenizer/bpe_loader.go`:
- Around line 19-45: Trim the documentation comment above localBpeLoader to
describe only its current behavior: local-only table loading and the rationale
for its path-priority order. Remove migration history, stock HTTP-loader
details, sync.Once failure behavior, and Python-versus-Go comparisons; keep the
comment concise and aligned with the current runtime path.
- Around line 76-79: Update the candidate-reading logic around os.ReadFile in
the BPE loader to continue searching only when the error indicates the candidate
does not exist. For other read failures, return or report a distinct actionable
error that includes the affected candidate path, rather than folding it into the
generic “no local BPE table” result.
- Around line 178-202: Update parseBpeTable to remove a trailing carriage return
from each line before splitting and parsing the token and rank fields, while
preserving existing validation and error behavior for all other input.
- Around line 73-96: Update LoadTiktokenBpe to verify each successfully read
candidate’s raw contents against the expected SHA-256 hash for the
cl100k_base.tiktoken URL before calling parseBpeTable. Reject mismatched files
and continue searching other candidates, while preserving the existing
malformed-file error handling for hash-matching content and the final not-found
error when no valid table is found.
🪄 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: 29ab26d0-1181-418e-ab77-80bc7499ad0d
📒 Files selected for processing (2)
internal/tokenizer/bpe_loader.gointernal/tokenizer/bpe_loader_test.go
| func TestNumTokensFromString_MatchesPythonAnchors(t *testing.T) { | ||
| anchors := []struct { | ||
| in string | ||
| want int | ||
| }{ | ||
| {"", 0}, | ||
| {"hello", 1}, | ||
| {"hello world", 2}, | ||
| {"hello, world!", 4}, | ||
| {"世界", 3}, | ||
| {"Hello 世界 🌍", 8}, | ||
| {"RAGFlow", 3}, | ||
| } | ||
| for _, tc := range anchors { | ||
| if got := NumTokensFromString(tc.in); got != tc.want { | ||
| t.Errorf("NumTokensFromString(%q) = %d, want %d", tc.in, got, tc.want) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Split the environment-dependent test out with a build tag instead of excluding the whole package from CI.
TestNumTokensFromString_MatchesPythonAnchors does not call isolate(t), so it depends on a real cl100k_base table being discoverable on disk (via TIKTOKEN_CACHE_DIR, ragflow_deps/, etc.). Per the PR objectives, this is why the entire tokenizer package is currently excluded from the CI test workflow. All the other tests in this file (TestLocalBpeLoader_ReadsTiktokenCacheDir, ReadsDataGymCacheDir, ReadsSha1FileFromWorkingDirectory, ReadsBundledVocabFromAncestor, CacheDirWinsOverBundledVocab, MissingTableReportsCandidatesInsteadOfDownloading, RejectsMalformedTable) are fully self-contained through isolate(t) and t.TempDir() and have no such dependency.
As per coding guidelines, "unit tests have no tier tag, while integration, e2e, and manual tests use their corresponding tags before the package clause" and "manual tests must never be wired into CI or automated pipelines" — the fix is to move TestNumTokensFromString_MatchesPythonAnchors into its own file with a manual (or integration) build tag, so the rest of this file's genuinely isolated unit tests can run in CI instead of the whole package being skipped.
🤖 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/tokenizer/bpe_loader_test.go` around lines 186 - 204, Move
TestNumTokensFromString_MatchesPythonAnchors into a separate test file guarded
by the appropriate manual or integration build tag before the package
declaration, since it relies on an externally discoverable cl100k_base table.
Leave the isolate(t)-based tests in the current file untagged so the tokenizer
package can run in CI without this environment-dependent test.
Source: Coding guidelines
| func (localBpeLoader) LoadTiktokenBpe(bpeURL string) (map[string]int, error) { | ||
| candidates := bpeCandidatePaths(bpeURL) | ||
| for _, candidate := range candidates { | ||
| contents, err := os.ReadFile(candidate) | ||
| if err != nil { | ||
| continue | ||
| } | ||
| ranks, err := parseBpeTable(contents) | ||
| if err != nil { | ||
| // A file that exists but does not parse is a corrupt download or a | ||
| // name collision. Continuing to the next candidate would mask it. | ||
| return nil, fmt.Errorf("BPE table %s is malformed: %w", candidate, err) | ||
| } | ||
| return ranks, nil | ||
| } | ||
|
|
||
| err := fmt.Errorf( | ||
| "no local BPE table for %s; run `uv run ragflow_deps/download_deps.py` or set TIKTOKEN_CACHE_DIR to the directory holding the table; tried: %s", | ||
| bpeURL, strings.Join(candidates, ", ")) | ||
| // Logged as well as returned: tiktoken-go propagates this to GetEncoding, | ||
| // whose error NumTokensFromString discards to keep returning 0. | ||
| common.Error("cl100k BPE table not found; every token count will be 0", err) | ||
| return nil, err | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
What SHA-256 hash does openai/tiktoken verify for the cl100k_base.tiktoken encoding file?
💡 Result:
The openai/tiktoken library verifies the cl100k_base.tiktoken encoding file against the SHA-256 hash 223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7 [1][2][3]. This hash is defined within the tiktoken_ext/openai_public.py file to ensure the integrity of the downloaded encoding data during the loading process [1][4].
Citations:
- 1: https://github.com/openai/tiktoken/blob/main/tiktoken_ext/openai_public.py
- 2: https://github.com/openai/tiktoken/blob/dcb39287/tiktoken_ext/openai_public.py
- 3: https://github.com/openai/tiktoken/blob/97e49cba/tiktoken_ext/openai_public.py
- 4: Add support for checking hash of downloaded files before use. openai/tiktoken#230
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Find bpe_loader.go:"
fd -a 'bpe_loader\.go$' .
echo
echo "File outline:"
ast-grep outline internal/tokenizer/bpe_loader.go || true
echo
echo "Relevant source:"
sed -n '1,180p' internal/tokenizer/bpe_loader.go
echo
echo "Search for cl100k/tiktoken hash references:"
rg -n "cl100|tiktoken|223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7|bpeCandidatePaths|searchRoots|LoadTiktokenBpe|download_deps" -S .Repository: infiniflow/ragflow
Length of output: 24297
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Search for parser implementation and callers:"
rg -n "func parseBpeTable|parseBpeTable|LoadTiktokenBpe|LoadBpeFrom|tiktoken-go|OpenEncoding|GetEncoding" internal -S
echo
echo "Go module dependency versions:"
rg -n 'pkoukk/tiktoken-go|tiktoken-go|tiktoken' go.mod go.sum || true
echo
echo "Files mentioning TIKTOKEN_CACHE_DIR:"
rg -n "TIKTOKEN_CACHE_DIR|tiktoken" -S internal . --glob '!**/.git/**' | head -200Repository: infiniflow/ragflow
Length of output: 17812
🌐 Web query:
pkoukk tiktoken-go v0.1.8 cl100k_base.tiktoken hash verify LoadBpeFrom source
💡 Result:
In the pkoukk/tiktoken-go library (including version 0.1.8), the cl100k_base encoding is initialized using the cl100k_base() function [1][2]. This function loads the BPE (Byte Pair Encoding) data by fetching the cl100k_base.tiktoken file from the official OpenAI public storage URL: https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken [1][2]. The library does not perform an internal cryptographic hash verification of the downloaded .tiktoken file against a hardcoded constant in the source code [3][2]. Instead, the loadTiktokenBpe function reads the file content, processes the base64-encoded tokens, and parses the rank values directly [3]. Key implementation details: - Loading Mechanism: The library uses a BpeLoader interface [3]. The default implementation (defaultBpeLoader) fetches the file from the remote URL [3][2]. - Customization: Users can override this behavior by calling tiktoken.SetBpeLoader() with a custom implementation, such as an offline loader, to avoid runtime network requests [4][5][6]. - Verification: Because the library relies on the official OpenAI-hosted file, it does not include a mechanism for verifying the file's hash against a local value [3][2]. Any integrity check or hash verification must be implemented manually by the user within a custom BpeLoader if required [3][5].
Citations:
- 1: https://github.com/pkoukk/tiktoken-go/blob/b2e1d31d115a40b6548743fb1cfd3c3801403607/enconding.go
- 2: https://github.com/pkoukk/tiktoken-go/blob/14f687710f5398e16cb3206cc8813183828c2cfb/encoding.go
- 3: https://github.com/pkoukk/tiktoken-go/blob/caab340cf008be05d764bfd54d367587a4c55ca2/load.go
- 4: https://github.com/pkoukk/tiktoken-go
- 5: https://pkg.go.dev/github.com/weaviate/tiktoken-go
- 6: https://pkg.go.dev/github.com/localit-io/tiktoken-go
🌐 Web query:
openai tiktoken source cl100k_base SHA256 223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7
💡 Result:
The SHA256 hash "223921b76ee99bde995b7ff738513eef100fb51d18c93597a113bcffe865b2a7" is the official expected hash for the "cl100k_base.tiktoken" vocabulary file as defined in the OpenAI "tiktoken" library [1][2][3]. This hash is used by the library to verify the integrity of the BPE (Byte Pair Encoding) vocabulary file when it is downloaded from OpenAI's public Azure blob storage [1][4]. It is hardcoded within the library's tiktoken_ext/openai_public.py file to ensure that the loaded encoding data has not been corrupted or altered [1][4]. If the hash of a downloaded file does not match this expected value, the library will raise an error [4].
Citations:
- 1: https://github.com/openai/tiktoken/blob/main/tiktoken_ext/openai_public.py
- 2: https://github.com/openai/tiktoken/blob/3591ff175d6a80efbe4fcc7f0e219ddd4b8c52f1/tiktoken_ext/openai_public.py
- 3: https://github.com/openai/tiktoken/blob/dcb39287/tiktoken_ext/openai_public.py
- 4: https://github.com/openai/tiktoken/blob/main/tiktoken/load.py
Add a cl100k_base.tiktoken content hash check before accepting local BPE tables.
LoadTiktokenBpe only rejects files that fail to parse, so any <base64> <rank> file at a discovered path is accepted as the cl100k_base encoding. Since bpeCandidatePaths() scans config directories plus the working/executable tree and their ancestors, a colliding table can silently change token counts and bypass budget splitting. Compare the loaded bytes against the expected SHA-256 hash for https://openaipublic.blob.core.windows.net/encodings/cl100k_base.tiktoken before parsing.
🤖 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/tokenizer/bpe_loader.go` around lines 73 - 96, Update
LoadTiktokenBpe to verify each successfully read candidate’s raw contents
against the expected SHA-256 hash for the cl100k_base.tiktoken URL before
calling parseBpeTable. Reject mismatched files and continue searching other
candidates, while preserving the existing malformed-file error handling for
hash-matching content and the final not-found error when no valid table is
found.
…lently offline tiktoken-go's stock loader fetches the encoding table over HTTP and caches it under TIKTOKEN_CACHE_DIR. Neither works for RAGFlow: that variable is only exported inside the Python process (common/token_utils.py), and docker/entrypoint.sh launches the Go binary from a shell, so the Go process never inherits it. The Dockerfile does ship the table (under its sha1 name in the working directory) but nothing told the Go side to look there. The failure was silent: NumTokensFromString returns 0 when the encoder fails to build, and a sync.Once memoises that error for the process lifetime. Every token count became 0, so chunk merging never crossed its token budget and an entire document collapsed into one chunk. Python has no such failure mode because its encoder is built at import time. Register a local-only BpeLoader (via tiktoken.SetBpeLoader) that resolves the table from disk only, in priority order: TIKTOKEN_CACHE_DIR / DATA_GYM_CACHE_DIR, then the working directory, the executable's directory and their ancestors (matching the Dockerfile layout and a download_deps.py checkout under ragflow_deps/). It never touches the network. When nothing is found it reports every path tried, so a genuinely missing table fails loudly instead of degrading to zero. Co-Authored-By: CodeBuddy <[email protected]>
- Distinguish os.IsNotExist from other read errors so a present-but-unreadable candidate surfaces as a read error instead of being skipped as missing. - Strip trailing CR in parseBpeTable to handle CRLF table files. - Trim the file-level doc comment to the current runtime path per AGENTS.md. - Add TestLocalBpeLoader_ReadErrorIsReported covering the read-error path. Co-Authored-By: CodeBuddy <[email protected]>
The offline BPE loader must reproduce Python's exact token counts, not just return a non-zero value. The original seven anchors only covered a handful of shapes, so a structurally valid-but-wrong table or a subtle tiktoken-go drift on whitespace/Unicode boundaries could slip through. Recompute the expected counts against tiktoken's cl100k encoder and widen the corpus to 26 entries spanning ASCII, digits, punctuation, multiple spaces, newlines, CJK, emoji, mixed-language, accented Latin, and code-like strings. All 26 now match tiktoken-go, pinning both the loader and the encoding port against the Python oracle. Co-Authored-By: CodeBuddy <[email protected]>
e01bca3 to
746422e
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/tokenizer/bpe_loader_test.go (2)
199-210: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove migration-history wording from the test comment.
“was later expanded” describes change history, not the current test contract. Keep the current source and purpose of the anchor corpus only. As per coding guidelines, remove stale documentation and keep Go doc comments aligned with the current runtime path rather than migration history.
🤖 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/tokenizer/bpe_loader_test.go` around lines 199 - 210, Update the comment above TestNumTokensFromString_MatchesPythonAnchors to remove migration-history wording such as “was later expanded,” while retaining only the current corpus scope, exact-count purpose, and explanation that pinned values detect loader failures or incorrect tables.Source: Coding guidelines
164-175: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPin the malformed-candidate contract.
This test accepts any error. It also passes if the loader skips the malformed file and later reports “not found.” Add a valid lower-priority table and assert that the error identifies the malformed candidate. This verifies that a corrupt existing file cannot fall through to another table.
Proposed test update
func TestLocalBpeLoader_RejectsMalformedTable(t *testing.T) { dir := isolate(t) path := filepath.Join(dir, cacheFileName(testBpeURL)) if err := os.WriteFile(path, []byte("not base64 at all\n"), 0o644); err != nil { t.Fatalf("write: %v", err) } + writeBpeTable(t, filepath.Join(dir, "ragflow_deps", "cl100k_base.tiktoken"), 10) _, err := localBpeLoader{}.LoadTiktokenBpe(testBpeURL) if err == nil { t.Fatal("expected an error for a malformed table, got nil") } + if !strings.Contains(err.Error(), "malformed") { + t.Errorf("malformed table was not reported: %v", err) + } }🤖 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/tokenizer/bpe_loader_test.go` around lines 164 - 175, Update TestLocalBpeLoader_RejectsMalformedTable to create a valid lower-priority fallback table alongside the malformed candidate, then assert the returned error identifies the malformed file or candidate rather than accepting any error. Preserve the test’s existing setup and ensure the loader does not silently skip the corrupt table and fall through to the valid one.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/tokenizer/bpe_loader_test.go`:
- Around line 199-210: Update the comment above
TestNumTokensFromString_MatchesPythonAnchors to remove migration-history wording
such as “was later expanded,” while retaining only the current corpus scope,
exact-count purpose, and explanation that pinned values detect loader failures
or incorrect tables.
- Around line 164-175: Update TestLocalBpeLoader_RejectsMalformedTable to create
a valid lower-priority fallback table alongside the malformed candidate, then
assert the returned error identifies the malformed file or candidate rather than
accepting any error. Preserve the test’s existing setup and ensure the loader
does not silently skip the corrupt table and fall through to the valid one.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f0a31218-9192-409f-8a1d-a101283e0254
📒 Files selected for processing (2)
internal/tokenizer/bpe_loader.gointernal/tokenizer/bpe_loader_test.go
…izer-liveness guard Align Go splitOversizedUnitWith with Python rag/nlp._split_oversized_unit: - Replace the exact joined-string fit check countFn(current+atom) > budget with a running-sum check currentTokens + aTokens > budget, mirroring Python's current_tokens accumulation. cl100k is not additive across whitespace joins (token(a)+token(b) != token(a+b)), so the exact check drifted Go's boundaries one atom off Python's, producing the same chunk count but shifted text (known_diff token-text-oversize-atom-boundary). - After a flush, keep the overflow whitespace atom (current += atom) instead of dropping it, matching Python's trailing-whitespace handling. Add B1 count-sensitive parity case (token__b1_count_sensitive): a long single paragraph under a deliberately small token budget. With a live tokenizer it yields many chunks; a dead tokenizer (returns 0) collapses it to exactly one — so this case is a CI guard that catches silent tokenizer regression, which the old empty-result check could not. Remove the now-resolved known_diff rule token-text-oversize-atom-boundary (3 cases now match Python cleanly). Relax TestMergeByTokenSizeFromJSON_OversizedUnitIsSubSplit's strict-cap assertion to allow the same cl100k non-additive +1 overshoot Python exhibits. Add the chunker golden parity harness (golden_parity_test.go), its testdata fixtures, and the capture_golden.py regeneration tool. Promote github.com/google/go-cmp to a direct dependency (used by the harness). This change is independent of PR infiniflow#17712 (the offline BPE loader) — that commit series is reverted on this branch.
…ts run - bpe_loader.go: verify the on-disk cl100k table against the SHA-1 of its *contents* and refuse to load a corrupt/tampered file (mismatch returns an error, consistent with the malformed-table path). The pinned digest is the file-content SHA-1 (6494e42d...), not the tiktoken cache filename (223921b76... = sha1(bpeURL)), which previously would have rejected the genuine table. - bpe_loader_test.go: writeBpeTable registers the synthetic table's SHA-1 so the gate accepts it while still exercising the verification path. - Split CI tiers: tag the C++-binding / dict-dependent tests (tokenizer_test.go, tokenizer_concurrent_test.go) and the on-disk anchor test (bpe_loader_anchors_test.go) with `//go:build manual` so they only run under the docker builder's /usr/share/infinity/resource. Remove the `internal/tokenizer` exclusion from tests.yml and sep-tests.yml so the pure-Go BPE loader tests (bpe_loader_test.go) run in the default tier. Co-Authored-By: CodeBuddy Code <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/tokenizer/bpe_loader.go (1)
48-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCorrect the cache-file hash documentation.
SHA-1 produces 20 bytes, so a lowercase hexadecimal digest has 40 characters. The 64-character value on Line 55 cannot be
sha1(bpeURL). Remove that value or label it with its actual algorithm. (pkg.go.dev)As per coding guidelines,
**/*.gocomments must stay aligned with the current runtime path rather than migration history.🤖 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/tokenizer/bpe_loader.go` around lines 48 - 58, Correct the cache filename documentation in the comment above expectedBpeHashes: remove the 64-character value currently labeled as sha1(bpeURL), or relabel it with its verified algorithm, and keep the comment describing only the current runtime cache-path behavior rather than migration history.Source: Coding guidelines
internal/tokenizer/bpe_loader_anchors_test.go (1)
23-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winKeep the test comment limited to current behavior.
Remove “was later expanded” and the historical offline-breakage narrative. Keep the required table location, the
manualtag rationale, and the exact-count purpose.As per coding guidelines,
**/*.gocomments must stay aligned with the current runtime path rather than migration history.🤖 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/tokenizer/bpe_loader_anchors_test.go` around lines 23 - 39, Update the comment above TestNumTokensFromString_MatchesPythonAnchors to describe only current behavior: retain the exact-count purpose, required cl100k_base table locations, and manual-tag execution rationale, while removing the expansion history and offline-breakage narrative.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/tokenizer/bpe_loader_anchors_test.go`:
- Around line 23-39: Update the comment above
TestNumTokensFromString_MatchesPythonAnchors to describe only current behavior:
retain the exact-count purpose, required cl100k_base table locations, and
manual-tag execution rationale, while removing the expansion history and
offline-breakage narrative.
In `@internal/tokenizer/bpe_loader.go`:
- Around line 48-58: Correct the cache filename documentation in the comment
above expectedBpeHashes: remove the 64-character value currently labeled as
sha1(bpeURL), or relabel it with its verified algorithm, and keep the comment
describing only the current runtime cache-path behavior rather than migration
history.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8993947f-7a96-442a-8e5c-bd561beedfee
📒 Files selected for processing (7)
.github/workflows/sep-tests.yml.github/workflows/tests.ymlinternal/tokenizer/bpe_loader.gointernal/tokenizer/bpe_loader_anchors_test.gointernal/tokenizer/bpe_loader_test.gointernal/tokenizer/tokenizer_concurrent_test.gointernal/tokenizer/tokenizer_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17712 +/- ##
=======================================
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:
|
Extract cl100k_base.tiktoken from the infiniflow/ragflow_deps image via `docker cp` into ragflow_deps/ before running `go test`, so the offline localBpeLoader can find the table on disk. This avoids fetching from openaipublic.blob.core.windows.net (unreliable / GFW-blocked) and keeps the loader's fail-loud semantics intact. The copy is best-effort: if the image is unavailable the loader still errors loudly instead of degrading to 0. Co-Authored-By: CodeBuddy Code <[email protected]>
The docker-cp-only block pulled the huge infiniflow/ragflow_deps image, which is first fetched at the later "Build ragflow:nightly" step — so the pull timed out before the Go unit-test step and the table was never provisioned, leaving the loader to fail loudly and return 0 tokens. Switch to curl-first against the upstream blob (small ~1.6MB, reachable from the CI runner — pre-PR stock loader fetched it on the fly), with a cached local image copy as a secondary fallback (no pull). If neither works the loader still fails loudly. Co-Authored-By: CodeBuddy <[email protected]>
The provisioning block was silent, so a passing run gave no way to tell whether the table came from the direct curl download or the cached infiniflow/ragflow_deps image copy. Print which path succeeded (and the byte size), or explicitly report when neither worked so the loader fails loudly. Purely additive logging; behavior unchanged. Co-Authored-By: CodeBuddy <[email protected]>
…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]>
|
LGTM |
Summary
RAGFlow's Go tokenizer silently returned 0 tokens for every string whenever the
cl100k_baseBPE table could not be loaded — which is the normal case for an offline/air-gapped Go server. This PR makes the loader resolve the table from disk (where RAGFlow actually ships it) and fail loudly when it is genuinely missing.Root cause
tiktoken-go's stock loader downloads the encoding table over HTTP and caches it underTIKTOKEN_CACHE_DIR. That does not work for RAGFlow:TIKTOKEN_CACHE_DIRis exported only inside the Python process (common/token_utils.py).docker/entrypoint.shlaunches the Go binary (bin/ragflow_server) from a shell, so the Go process never inherits the variable.openaipublic.blob.core.windows.netat runtime is not an option for air-gapped installs, and is unreliable where that host is blocked.The failure was silent:
NumTokensFromStringreturns0when the encoder fails to build, and async.Oncememoizes that error for the process lifetime. Every token count became0, so chunk merging never crossed its token budget and an entire document collapsed into a single chunk. Python has no such failure mode because its encoder is built at import time (a missing table aborts startup instead of degrading).Fix
Register a local-only
BpeLoaderviatiktoken.SetBpeLoader(internal/tokenizer/bpe_loader.go) that resolves the table from disk only, in priority order:TIKTOKEN_CACHE_DIR/DATA_GYM_CACHE_DIR(honored so operators who already configured one keep working).ragflow_deps/<basename>checkout produced byragflow_deps/download_deps.py.It never performs network I/O. When nothing is found it returns an error listing every path it tried (pointing at
download_deps.pyorTIKTOKEN_CACHE_DIR), so a genuinely missing table fails loudly instead of degrading to zero.Test plan
internal/tokenizer/bpe_loader_test.go(unit tier, runs underbash build.sh --test ./internal/tokenizer/...):TIKTOKEN_CACHE_DIR,DATA_GYM_CACHE_DIR, the sha1-named file in the working dir, and the bundledragflow_deps/name.NumTokensFromStringmatches Python-derived anchors (""→0,"hello"→1,"hello world"→2,"hello, world!"→4,"世界"→3,"Hello 世界 🌍"→8,"RAGFlow"→3).Notes
.github/workflows/tests.ymlcurrently excludesinternal/tokenizerfromgo test, so these tests do not run in CI. The tokenizer fix is exercised in CI indirectly via the chunker package once a token-count-sensitive parity case lands (tracked separately). Consider includinginternal/tokenizerin CI as a follow-up.download_deps.py→ragflow_deps/cl100k_base.tiktoken; Dockerfile →<sha1>in cwd), so noENVchange is required for the fix to take effect. SettingENV TIKTOKEN_CACHE_DIRin the Dockerfile remains a cheap belt-and-suspenders hardening that can be done separately.🤖 Generated with CodeBuddy Code