Repository navigation
Add spacy based ner and relationship extractor for both python and Go version with equivalent outputs - #16456
Conversation
…version with equivalent outputs
|
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:
📝 WalkthroughWalkthroughAdds C++ ThincNER and ThincParser runtimes plus C APIs, Go cgo extraction and relation modules, and Python spaCy-based NER and relation classes with shared extraction types and package exports. ChangesCross-language NER and relation extraction
Sequence Diagram(s)sequenceDiagram
participant Client
participant Extractor as Go Extractor
participant ThincNER as ThincNER C API
participant ThincParser as ThincParser C API
participant DepRelationExtractor as DepRelationExtractor
Client->>Extractor: Extract(text, extractRelations)
Extractor->>ThincNER: ThincNER_Tokenize(text, lang)
ThincNER-->>Extractor: token JSON
Extractor->>ThincNER: ThincNER_Predict(handle, tokens_json)
ThincNER-->>Extractor: entity JSON
Extractor->>ThincParser: ParseTokensWithParser(tokens)
ThincParser-->>Extractor: []DepTokenC
Extractor->>DepRelationExtractor: DepExtractRelations(text, tokens, entities, lang, maxDistance)
DepRelationExtractor-->>Extractor: []Relation
Extractor-->>Client: ExtractionResult
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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: 16
🧹 Nitpick comments (2)
rag/graphrag/ner/extractor.py (1)
61-81: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd entrypoint logging for the new orchestration flow.
This is the public NER/RE API, but it doesn’t log the selected path or the entity/relation counts returned. That will make fallback and parity debugging much harder in production. As per 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 `@rag/graphrag/ner/extractor.py` around lines 61 - 81, The public NER/RE entrypoints in Extractor.extract and Extractor.extract_batch currently return results without logging the chosen flow or output sizes. Add logging at these entrypoints to record whether relations were extracted and the resulting entity/relation counts, using the existing Extractor methods and language context so fallback and parity issues are easier to debug in production.Source: Coding guidelines
rag/graphrag/ner/spacy_ner.py (1)
98-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd logs for the new extraction flow.
Right now the only signal is the model-load warning. We still need debug/info logs for which path ran and how many entities were emitted so fallback/parity issues are diagnosable. As per 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 `@rag/graphrag/ner/spacy_ner.py` around lines 98 - 123, The extraction flow in spaCyNer currently only logs model-load failures, so add logging in the main paths to make runtime behavior observable. Update spacy_ner.py’s _ensure_model, extract, and extract_batch methods to emit debug/info logs indicating whether spaCy or fallback regex was used and how many entities were returned for each call. Keep the logs lightweight and tied to the existing symbols _ensure_model, extract, _extract_with_spacy, and _extract_fallback so the new flow is easy to trace.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.
Inline comments:
In `@internal/cpp/thinc_ner.cpp`:
- Around line 408-418: The JSON token/result handling is manually parsing and
emitting raw quoted strings, so tokens containing quotes or backslashes break
both input and output. Update the token-array parsing in the token handling code
and the response builders in ThincNER_Predict and ThincNER_Tokenize to use
proper JSON escaping/serialization instead of scanning for quote delimiters, so
the contract stays valid for arbitrary token text.
- Around line 194-201: The inference path is still using synthetic defaults
instead of the saved spaCy model state. Update HashEmbed and the extractor setup
to load and use the learned tok2vec tables from model_vocab_dir, and replace the
hard-coded English label list with the checkpoint’s actual label mapping. Make
sure the inference flow in thinc_ner.cpp uses the loaded artifacts consistently
so the C++ extractor matches the Python spaCy model output.
- Around line 28-92: `load_thinc_model` currently cannot rebuild a real spaCy
checkpoint because `SimpleJSON::parse` only supports flat objects and
`model.bin` slicing depends on unordered iteration. Update `SimpleJSON` in
`thinc_ner.cpp` to handle nested checkpoint structures used by `model.ckpt`
(including fields like `shape` and `dtype`), and change the `load_thinc_model` /
`ThincNER_Create` loading path to preserve the original parameter order instead
of iterating `ckpt.strs` directly. Ensure parameter names are read in a
deterministic sequence so the correct float ranges are assigned to each tensor.
- Around line 331-352: The tokenization logic in basic_tokenize and
ThincNER_Tokenize is a heuristic character splitter rather than the spaCy
tokenizer expected by the Python/Go parity contract. Replace this custom
tokenization path with a spaCy-compatible tokenization flow for both the English
and Chinese branches, and ensure the tokens exactly match the corresponding
model tokenizer output instead of splitting abbreviations like U.S. or emitting
one UTF-8 codepoint per token.
- Around line 421-440: The temporary embedding scratch buffer in the Tok2Vec
path is hard-coded to 96, but the model dimension comes from hidden_dim via D,
so it can overflow for other checkpoints. Update the buffer sizing in the
thinc_ner.cpp tok2vec loop so the storage used by HashEmbed::forward is
allocated from D instead of a fixed width, and make the later sum over j < D
read from that same safely sized storage. Keep the change localized to the token
embedding aggregation logic around extract_features, state->embed->forward, and
the tok2vec accumulation.
In `@internal/cpp/thinc_ner.h`:
- Around line 42-44: The ThincNER_SetModelPath API is declared in
ThincNER_SetModelPath without a matching implementation or shared C API export,
so it should not be exposed yet. Either add the implementation in thinc_ner.cpp
and wire it through rag_analyzer_c_api.h consistently, or remove the declaration
from thinc_ner.h until the feature is fully available. Keep the exported symbols
aligned across the internal C++ header and the shared C API so callers cannot
compile against an unresolved function.
In `@internal/ingestion/compilation/extractor/ner_test.go`:
- Around line 140-152: The test bridge between the Python subprocess and Go
entities is missing offset fields, so the fallback behavior in ExtractRelations
is not actually exercised. Update the pyResult/pyEntity parity helpers and the
related test cases to carry StartChar/EndChar through the JSON response, then
use those offsets when rebuilding Go entities instead of defaulting to zero.
Make sure the ExtractRelations comparison path still checks the fallback branch
behavior rather than skipping related_to or masking mismatches.
- Around line 217-220: The parity checks in ner_test.go are skipping on any
Python/spaCy setup error, which lets the suite pass without validating the
cross-language contract. Update the test flow around runPythonExtractor and the
tc-driven cases to fail when the expected parity environment is missing, instead
of calling t.Skip in the test loop; use the affected test helpers/blocks in
TestNERExtractor parity cases to explicitly gate or assert the setup so the
assertions always run when the environment should be present.
In `@internal/ingestion/compilation/extractor/ner.go`:
- Around line 235-263: DetectLanguage currently can return "ja" even though the
extractor only supports English and Chinese paths, so align the return values
with what NewExtractor and the language wiring in ner.go actually handle. Update
DetectLanguage to map Japanese text to the supported fallback language or add a
real Japanese branch in the extractor setup, and make sure any caller using
DetectLanguage(text) receives only a value that NewExtractor can route
correctly.
- Around line 193-230: Model discovery in Extractor.findModelDir is effectively
broken because dirExists and getenv are stubbed to always fail. Replace those
placeholders with real filesystem and environment checks so findModelDir can
return installed spaCy paths or SPACY_MODEL_DIR when present, while still
falling back to ./models/<model> only if nothing exists.
In `@rag/graphrag/ner/relation_extractor.py`:
- Around line 41-50: The relation extractor is storing confidence_threshold in
Extractor.__init__ but never applying it, so low-confidence co-occurrence
relations still pass through. Update the relation filtering path in the
Extractor class (especially the method that builds or returns relations) to
compare each relation’s confidence against self.confidence_threshold and skip
anything below the configured threshold. Make sure the threshold is enforced
before returning results from the relation extraction flow, not just set during
initialization.
- Around line 138-162: The _extract_cooccurrence fallback in RelationExtractor
is not actually sentence-bounded and can create false positives across adjacent
sentences. Update the logic in _extract_cooccurrence to derive sentence spans
and only emit Relation objects when both entities fall within the same sentence,
rather than relying only on character distance in max_distance. Keep the
existing confidence/context behavior, but use the sentence boundary check as the
primary gate before appending related_to relations.
In `@rag/graphrag/ner/spacy_ner.py`:
- Around line 62-73: The fallback NER patterns in spacy_ner.py only cover
English, but Extractor can route Chinese requests through this path when
zh_core_web_sm is unavailable, so update the fallback behavior for the zh path
as well. In the Extractor/spacy NER loading flow, detect the requested language
before using _FALLBACK_NER_PATTERNS and either provide a Chinese-aware fallback
or fail fast with a clear error instead of returning English-biased entities.
Keep the fix localized around the fallback selection and entity extraction logic
so the zh_core_web_sm path no longer silently degrades.
- Around line 51-56: The spaCy model loading in spacy_ner.py currently
auto-downloads via spacy.cli.download() inside the extraction path, which should
be removed. Update the model initialization around _nlp = spacy.load(model_name)
so it only uses an already-installed model and, on OSError, falls back to the
existing regex-based path or a no-NER fallback without network access. Make sure
the behavior is localized to the NER loading logic and does not introduce
first-use installation side effects.
In `@rag/graphrag/ner/types.py`:
- Around line 78-83: The relation entity capture regexes in _REL_ENTITY and
_REL_ENTITY2 are too restrictive because they only accept names starting with
uppercase letters, so mixed/lowercase entities like eBay or iPhone are missed.
Relax the character class used in these patterns in rag/graphrag/ner/types.py so
typed relation extraction can match such entities while still preserving the
existing multi-word and overcapture limits.
- Around line 88-89: The founded_by regex variants in the NER pattern list need
consistent subject/object ordering because Relation.subject is always taken from
capture group 1 and Relation.obj from group 2 in relation_extractor.py. Update
the affected patterns in the pattern table so both passive and active forms
normalize to the same logical direction, using the existing _REL_ENTITY and
_REL_ENTITY2 symbols as the anchor points, and ensure any related variants at
the referenced entries follow the same capture-group ordering.
---
Nitpick comments:
In `@rag/graphrag/ner/extractor.py`:
- Around line 61-81: The public NER/RE entrypoints in Extractor.extract and
Extractor.extract_batch currently return results without logging the chosen flow
or output sizes. Add logging at these entrypoints to record whether relations
were extracted and the resulting entity/relation counts, using the existing
Extractor methods and language context so fallback and parity issues are easier
to debug in production.
In `@rag/graphrag/ner/spacy_ner.py`:
- Around line 98-123: The extraction flow in spaCyNer currently only logs
model-load failures, so add logging in the main paths to make runtime behavior
observable. Update spacy_ner.py’s _ensure_model, extract, and extract_batch
methods to emit debug/info logs indicating whether spaCy or fallback regex was
used and how many entities were returned for each call. Keep the logs
lightweight and tied to the existing symbols _ensure_model, extract,
_extract_with_spacy, and _extract_fallback so the new flow is easy to trace.
🪄 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
Run ID: 957696cb-9c56-49dc-8a77-59f02e4799a7
📒 Files selected for processing (13)
internal/cpp/CMakeLists.txtinternal/cpp/rag_analyzer_c_api.hinternal/cpp/thinc_ner.cppinternal/cpp/thinc_ner.hinternal/ingestion/compilation/extractor/ner.gointernal/ingestion/compilation/extractor/ner_extractor.gointernal/ingestion/compilation/extractor/ner_relation.gointernal/ingestion/compilation/extractor/ner_test.gorag/graphrag/ner/__init__.pyrag/graphrag/ner/extractor.pyrag/graphrag/ner/relation_extractor.pyrag/graphrag/ner/spacy_ner.pyrag/graphrag/ner/types.py
|
@CodeRabbit review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/compilation/extractor/ner.go (1)
220-227: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winCheck the
ner/component before returning a spaCy package root.ExtractEntities()passesmodelDir+"/ner"toThincNER_Create(), and that loader requiresmodel.ckptandmodel.binin that subdirectory. A package root can exist whilener/is missing or incomplete, so this can pick an unusable path and skip a validSPACY_MODEL_DIR. Prefer validatingfilepath.Join(c, "ner")(or returning thener/directory directly).🤖 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/compilation/extractor/ner.go` around lines 220 - 227, The spaCy model path lookup in the `findModelDir` logic can return a package root that lacks a usable `ner/` subdirectory, which later breaks `ExtractEntities()` when it passes `modelDir+"/ner"` to `ThincNER_Create()`. Update the candidate selection to validate `filepath.Join(c, "ner")` (or return that `ner/` path directly) before accepting a model directory, and apply the same check to the `SPACY_MODEL_DIR` fallback so incomplete roots are skipped in favor of a valid `ner/` directory.
🤖 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/cpp/thinc_ner.cpp`:
- Around line 231-253: The feature extraction in extract_features is treating
tokens as bytes, which breaks non-ASCII/UTF-8 input. Update the norm, prefix,
suffix, and shape logic to operate on Unicode codepoints or validated UTF-8
sequences instead of raw char iteration, so multilingual tokens (especially
Chinese) produce stable feature strings and hashes that match the model.
- Around line 398-477: The C API entity decoding in decode_biluo is rebuilding
ent_text from tokens with added spaces, which loses the original text span and
breaks parity with the Python spaCy output. Update decode_biluo (and the related
flush logic it feeds) to preserve the exact entity substring and character
offsets instead of concatenating tokens, using the original input text and token
offsets when constructing NERResult. Keep the token index fields if needed, but
ensure the returned entity text matches the source span exactly for punctuation
and non-space-delimited languages.
- Around line 637-681: Several layer loaders in thinc_ner.cpp enable a block
after only one parameter is present, which can leave required tensors empty and
later dereferenced in functions like maxout_linear and related layer uses.
Update the loading logic around post embeddings, post layernorm, residual
blocks, hidden projection, precomputable affine, and classifier so each layer is
marked active only when its full parameter group is successfully loaded; if any
required tensor is missing, leave the corresponding has_* flag false and do not
increment counts like n_res. Use the existing symbols post_W, post_b, post_ln_G,
post_ln_b, res_blocks, hidden_W, hidden_b, pre_W, pre_b, W, and b to locate and
tighten the checks.
- Around line 603-619: The HashEmbed load path in thinc_ner.cpp is hardcoding
runtime layout assumptions, so `HashEmbed::embed` can write a checkpoint’s
actual width into a buffer sized by the default `state->hidden_dim`. Update the
checkpoint-loading logic in the `embed_0_E` loop to derive and store the
embedding dimension from the loaded tensor shape (`nO`) and use that runtime
value consistently wherever the embedding output buffer is allocated or
consumed. Make the same adjustment in the corresponding load/restore path
referenced by the review so `state->embeds` and the downstream embedding code
agree on the actual per-table width.
- Around line 721-728: The ThincNER_Create loader currently falls back to 74 "O"
labels when load_labels_json fails, which hides a broken model setup and
produces silent empty entity results. Update ThincNER_Create to treat a missing
or malformed labels.json as a hard load failure: after load_ckpt_bin succeeds,
if load_labels_json returns false, clean up the ThincNERState and return nullptr
instead of resizing action_labels. Keep the failure path consistent with the
existing error handling in ThincNER_Create so Go callers receive an error from
the load attempt.
- Around line 574-583: In `load`/the `bin_file` parsing block, validate that
`bin_size` is a multiple of `sizeof(float)` before allocating `bin_data` and
reading from `model.bin`, and fail early if it is not. Also harden the `slice`
lambda by rejecting negative `offset` or `count` values and checking both bounds
before constructing iterators, so invalid checkpoint values cannot produce
out-of-range access. Keep the checks close to `bin_file`, `bin_data`, and
`slice` so the read and slicing logic stays safe.
- Around line 878-939: The current NER inference path in thinc_ner.cpp is
treating spaCy NER as independent token classification, which is incompatible
with transition-based checkpoints. Update the logic around the Step 6/7/8/9
flow, especially the best_actions, action_labels, and decode_biluo path, to use
the model’s parser-state action sequence instead of per-token argmax labels.
Make the export/runtime code follow the actual transition-based parser behavior
for classifying and applying actions, and only use BILUO decoding if the
exported model is truly token-level.
In `@internal/ingestion/compilation/extractor/ner.go`:
- Around line 263-267: The language selection in extractor logic is still
allowing Japanese text with any Kanji dominance to fall through to zh. Update
the decision in the NER extractor path so that the presence of any Hiragana or
Katakana in the script counts as the unsupported Japanese case and returns en
before the han-heavy branch, keeping the behavior aligned with the tests and the
no-ja-extractor fallback.
---
Outside diff comments:
In `@internal/ingestion/compilation/extractor/ner.go`:
- Around line 220-227: The spaCy model path lookup in the `findModelDir` logic
can return a package root that lacks a usable `ner/` subdirectory, which later
breaks `ExtractEntities()` when it passes `modelDir+"/ner"` to
`ThincNER_Create()`. Update the candidate selection to validate
`filepath.Join(c, "ner")` (or return that `ner/` path directly) before accepting
a model directory, and apply the same check to the `SPACY_MODEL_DIR` fallback so
incomplete roots are skipped in favor of a valid `ner/` directory.
🪄 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
Run ID: 9f866444-f535-43da-95c0-ab7f0608389d
📒 Files selected for processing (8)
internal/cpp/thinc_ner.cppinternal/cpp/thinc_ner.hinternal/ingestion/compilation/extractor/ner.gointernal/ingestion/compilation/extractor/ner_relation.gointernal/ingestion/compilation/extractor/ner_test.gorag/graphrag/ner/relation_extractor.pyrag/graphrag/ner/spacy_ner.pyrag/graphrag/ner/types.py
💤 Files with no reviewable changes (1)
- internal/cpp/thinc_ner.h
🚧 Files skipped from review as they are similar to previous changes (4)
- rag/graphrag/ner/relation_extractor.py
- rag/graphrag/ner/types.py
- rag/graphrag/ner/spacy_ner.py
- internal/ingestion/compilation/extractor/ner_test.go
| static std::vector<NERResult> decode_biluo( | ||
| const std::vector<std::string>& tokens, | ||
| const std::vector<std::string>& token_labels | ||
| ) { | ||
| std::vector<NERResult> entities; | ||
| int n = static_cast<int>(tokens.size()); | ||
| int ent_start = -1; | ||
| std::string ent_type; | ||
| std::string ent_text; | ||
|
|
||
| for (int i = 0; i < n; i++) { | ||
| const std::string& lbl = token_labels[i]; | ||
|
|
||
| if (lbl.empty() || lbl == "O") { | ||
| // End current entity | ||
| if (ent_start >= 0) { | ||
| entities.push_back({ent_text, ent_type, ent_start, i - 1, 0.85f}); | ||
| ent_start = -1; | ||
| ent_type.clear(); | ||
| ent_text.clear(); | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| if (lbl.size() < 3 || lbl[1] != '-') { | ||
| if (ent_start >= 0) { | ||
| entities.push_back({ent_text, ent_type, ent_start, i - 1, 0.85f}); | ||
| ent_start = -1; | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| char action = lbl[0]; | ||
| std::string type = lbl.substr(2); | ||
|
|
||
| if (action == 'U') { | ||
| // Unit entity (single token) | ||
| if (ent_start >= 0) { | ||
| entities.push_back({ent_text, ent_type, ent_start, i - 1, 0.85f}); | ||
| ent_start = -1; | ||
| } | ||
| entities.push_back({tokens[i], type, i, i, 0.85f}); | ||
| } else if (action == 'B') { | ||
| // Begin multi-token entity | ||
| if (ent_start >= 0) { | ||
| entities.push_back({ent_text, ent_type, ent_start, i - 1, 0.85f}); | ||
| } | ||
| ent_start = i; | ||
| ent_type = type; | ||
| ent_text = tokens[i]; | ||
| } else if (action == 'I') { | ||
| // Inside multi-token entity | ||
| if (ent_start >= 0 && ent_type == type) { | ||
| ent_text += " " + tokens[i]; | ||
| } else { | ||
| // Orphan I-: start new entity | ||
| if (ent_start >= 0) { | ||
| entities.push_back({ent_text, ent_type, ent_start, i - 1, 0.85f}); | ||
| } | ||
| ent_start = i; | ||
| ent_type = type; | ||
| ent_text = tokens[i]; | ||
| } | ||
| } else if (action == 'L') { | ||
| // Last token of multi-token entity | ||
| if (ent_start >= 0 && ent_type == type) { | ||
| ent_text += " " + tokens[i]; | ||
| entities.push_back({ent_text, ent_type, ent_start, i, 0.85f}); | ||
| } else { | ||
| entities.push_back({tokens[i], type, i, i, 0.85f}); | ||
| } | ||
| ent_start = -1; | ||
| ent_type.clear(); | ||
| ent_text.clear(); | ||
| } | ||
| } | ||
|
|
||
| // Flush remaining entity | ||
| if (ent_start >= 0) { | ||
| entities.push_back({ent_text, ent_type, ent_start, n - 1, 0.85f}); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Preserve original text spans in the C API output.
start/end are token indexes and ent_text is rebuilt with inserted spaces, while the Python spaCy path returns exact entity text plus character offsets. This breaks parity for punctuation and Chinese entities.
Also applies to: 941-949
🤖 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/cpp/thinc_ner.cpp` around lines 398 - 477, The C API entity decoding
in decode_biluo is rebuilding ent_text from tokens with added spaces, which
loses the original text span and breaks parity with the Python spaCy output.
Update decode_biluo (and the related flush logic it feeds) to preserve the exact
entity substring and character offsets instead of concatenating tokens, using
the original input text and token offsets when constructing NERResult. Keep the
token index fields if needed, but ensure the returned entity text matches the
source span exactly for punctuation and non-space-delimited languages.
| std::ifstream bin_file(bin_path, std::ios::binary | std::ios::ate); | ||
| if (!bin_file) { std::cerr << "Cannot open " << bin_path << "\n"; return false; } | ||
| size_t bin_size = static_cast<size_t>(bin_file.tellg()); | ||
| bin_file.seekg(0); | ||
| std::vector<float> bin_data(bin_size / sizeof(float)); | ||
| bin_file.read(reinterpret_cast<char*>(bin_data.data()), bin_size); | ||
|
|
||
| auto slice = [&](int64_t offset, int64_t count) -> std::vector<float> { | ||
| if (offset + count > static_cast<int64_t>(bin_data.size())) return {}; | ||
| return std::vector<float>(bin_data.begin() + offset, bin_data.begin() + offset + count); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Validate model.bin size and slice bounds before reading.
If bin_size is not divisible by sizeof(float), Line 579 reads more bytes than the vector owns. Negative offset/count values from the checkpoint can also create invalid iterators in slice.
Suggested fix
- size_t bin_size = static_cast<size_t>(bin_file.tellg());
+ auto bin_pos = bin_file.tellg();
+ if (bin_pos < 0 || static_cast<size_t>(bin_pos) % sizeof(float) != 0) {
+ std::cerr << "Invalid " << bin_path << " size\n";
+ return false;
+ }
+ size_t bin_size = static_cast<size_t>(bin_pos);
bin_file.seekg(0);
std::vector<float> bin_data(bin_size / sizeof(float));
- bin_file.read(reinterpret_cast<char*>(bin_data.data()), bin_size);
+ if (!bin_file.read(reinterpret_cast<char*>(bin_data.data()), static_cast<std::streamsize>(bin_size))) {
+ std::cerr << "Failed to read " << bin_path << "\n";
+ return false;
+ }
auto slice = [&](int64_t offset, int64_t count) -> std::vector<float> {
- if (offset + count > static_cast<int64_t>(bin_data.size())) return {};
+ if (offset < 0 || count < 0 ||
+ offset > static_cast<int64_t>(bin_data.size()) ||
+ count > static_cast<int64_t>(bin_data.size()) - offset) return {};
return std::vector<float>(bin_data.begin() + offset, bin_data.begin() + offset + count);
};📝 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.
| std::ifstream bin_file(bin_path, std::ios::binary | std::ios::ate); | |
| if (!bin_file) { std::cerr << "Cannot open " << bin_path << "\n"; return false; } | |
| size_t bin_size = static_cast<size_t>(bin_file.tellg()); | |
| bin_file.seekg(0); | |
| std::vector<float> bin_data(bin_size / sizeof(float)); | |
| bin_file.read(reinterpret_cast<char*>(bin_data.data()), bin_size); | |
| auto slice = [&](int64_t offset, int64_t count) -> std::vector<float> { | |
| if (offset + count > static_cast<int64_t>(bin_data.size())) return {}; | |
| return std::vector<float>(bin_data.begin() + offset, bin_data.begin() + offset + count); | |
| std::ifstream bin_file(bin_path, std::ios::binary | std::ios::ate); | |
| if (!bin_file) { std::cerr << "Cannot open " << bin_path << "\n"; return false; } | |
| auto bin_pos = bin_file.tellg(); | |
| if (bin_pos < 0 || static_cast<size_t>(bin_pos) % sizeof(float) != 0) { | |
| std::cerr << "Invalid " << bin_path << " size\n"; | |
| return false; | |
| } | |
| size_t bin_size = static_cast<size_t>(bin_pos); | |
| bin_file.seekg(0); | |
| std::vector<float> bin_data(bin_size / sizeof(float)); | |
| if (!bin_file.read(reinterpret_cast<char*>(bin_data.data()), static_cast<std::streamsize>(bin_size))) { | |
| std::cerr << "Failed to read " << bin_path << "\n"; | |
| return false; | |
| } | |
| auto slice = [&](int64_t offset, int64_t count) -> std::vector<float> { | |
| if (offset < 0 || count < 0 || | |
| offset > static_cast<int64_t>(bin_data.size()) || | |
| count > static_cast<int64_t>(bin_data.size()) - offset) return {}; | |
| return std::vector<float>(bin_data.begin() + offset, bin_data.begin() + offset + count); |
🤖 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/cpp/thinc_ner.cpp` around lines 574 - 583, In `load`/the `bin_file`
parsing block, validate that `bin_size` is a multiple of `sizeof(float)` before
allocating `bin_data` and reading from `model.bin`, and fail early if it is not.
Also harden the `slice` lambda by rejecting negative `offset` or `count` values
and checking both bounds before constructing iterators, so invalid checkpoint
values cannot produce out-of-range access. Keep the checks close to `bin_file`,
`bin_data`, and `slice` so the read and slicing logic stays safe.
| ThincNERHandle ThincNER_Create(const char* model_ner_dir, const char* model_vocab_dir) { | ||
| (void)model_vocab_dir; | ||
| auto state = new ThincNERState(); | ||
| if (!load_ckpt_bin(model_ner_dir, state)) { delete state; return nullptr; } | ||
| if (!load_labels_json(model_ner_dir, state)) { | ||
| std::cerr << "Warning: labels.json not found\n"; | ||
| state->action_labels.resize(74, "O"); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Fail creation when labels are missing.
Falling back to 74 "O" labels makes the model load successfully but guarantees empty entity output. Treat a missing or malformed labels.json as a load failure so Go callers receive an error instead of silent false negatives.
Suggested fix
if (!load_ckpt_bin(model_ner_dir, state)) { delete state; return nullptr; }
if (!load_labels_json(model_ner_dir, state)) {
- std::cerr << "Warning: labels.json not found\n";
- state->action_labels.resize(74, "O");
+ std::cerr << "Cannot load labels.json\n";
+ delete state;
+ return nullptr;
}📝 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.
| ThincNERHandle ThincNER_Create(const char* model_ner_dir, const char* model_vocab_dir) { | |
| (void)model_vocab_dir; | |
| auto state = new ThincNERState(); | |
| if (!load_ckpt_bin(model_ner_dir, state)) { delete state; return nullptr; } | |
| if (!load_labels_json(model_ner_dir, state)) { | |
| std::cerr << "Warning: labels.json not found\n"; | |
| state->action_labels.resize(74, "O"); | |
| } | |
| ThincNERHandle ThincNER_Create(const char* model_ner_dir, const char* model_vocab_dir) { | |
| (void)model_vocab_dir; | |
| auto state = new ThincNERState(); | |
| if (!load_ckpt_bin(model_ner_dir, state)) { delete state; return nullptr; } | |
| if (!load_labels_json(model_ner_dir, state)) { | |
| std::cerr << "Cannot load labels.json\n"; | |
| delete state; | |
| return nullptr; | |
| } |
🤖 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/cpp/thinc_ner.cpp` around lines 721 - 728, The ThincNER_Create
loader currently falls back to 74 "O" labels when load_labels_json fails, which
hides a broken model setup and produces silent empty entity results. Update
ThincNER_Create to treat a missing or malformed labels.json as a hard load
failure: after load_ckpt_bin succeeds, if load_labels_json returns false, clean
up the ThincNERState and return nullptr instead of resizing action_labels. Keep
the failure path consistent with the existing error handling in ThincNER_Create
so Go callers receive an error from the load attempt.
|
@CodeRabbit review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/cpp/thinc_ner.cpp`:
- Around line 117-123: `HashEmbed::load()` is only checking that the sliced
embedding vector is non-empty before copying, which can still allow a `count <
rows * nO` mismatch and read past the source buffer. Update the loader path
around `HashEmbed::load()` (and the analogous code in the other affected block)
to validate that the tensor/vector shape exactly matches the expected `r * o`
element count before calling `table.assign`, and fail early if the checkpoint
data is too short or otherwise inconsistent.
- Around line 329-334: ThincNER_Predict currently guards a null handle but still
constructs std::string from tj unconditionally, so a null tokens_json input can
crash. Update ThincNER_Predict to defensively check tj before creating the
std::string, matching the existing null-handling style used for the State* s
check, and return the same empty result fallback when tj is null.
- Around line 313-315: The label-loading logic in `load_labels()` currently
calls `std::stoi` on keys from `am->obj`, which can throw on malformed
`labels.json` and escape through the C API boundary in `ThincNER_Create`. Update
the loop that computes `mx` and fills `s->actLbl` to validate/parse each key
safely, catch any conversion failure, and return false from `load_labels()`
instead of letting an exception propagate. Keep the fix localized around the
`std::stoi(k)` usage and the `s->actLbl.resize` / label assignment block.
- Around line 32-42: The JSON parser in JParser::parse/pn is currently allowed
to throw or read past the input on malformed checkpoint data, which can crash
ThincNER_Create instead of failing cleanly. Harden the parsing path by making
JParser::pn, pv, po, pa, ps, and pb tolerate end-of-input/invalid tokens without
throwing, and wrap calls to JParser().parse inside load() and load_labels() so
they catch parse errors and return false. Ensure the caller path from
ThincNER_Create propagates this failure by returning nullptr.
🪄 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
Run ID: 783cb7b7-6749-4977-8d14-0bd472b50638
📒 Files selected for processing (3)
internal/cpp/thinc_ner.cppinternal/ingestion/compilation/extractor/ner_relation.gointernal/ingestion/compilation/extractor/ner_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/ingestion/compilation/extractor/ner_relation.go
- internal/ingestion/compilation/extractor/ner_test.go
|
@CodeRabbit review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/ingestion/compilation/extractor/ner_test.go (1)
347-357: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winChinese ground-truth expectations are never asserted.
zhTestsdefineswantEntities/wantRels, butTestZhFullTripleIdentityonly checks Go-vs-Python parity. If both implementations regress the same way, this suite still passes without validating the expectedzh_core_web_smoutput that this PR adds.Please add direct assertions against
tc.wantEntitiesandtc.wantRelsfor the Chinese cases, similar to the English entity/relation checks, before doing the parity comparison.Also applies to: 419-465
🤖 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/compilation/extractor/ner_test.go` around lines 347 - 357, The Chinese test cases in zhTests define expected entities and relations, but TestZhFullTripleIdentity only compares Go and Python output, so regressions can slip through if both match incorrectly. Update the Chinese branch in TestZhFullTripleIdentity to assert tc.wantEntities and tc.wantRels directly for each zhTests case, mirroring the English checks, and keep the existing parity comparison afterward. Use the zhTests slice and the tc.wantEntities/tc.wantRels fields to locate the assertions.
🤖 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/ingestion/compilation/extractor/ner_test.go`:
- Around line 347-357: The Chinese test cases in zhTests define expected
entities and relations, but TestZhFullTripleIdentity only compares Go and Python
output, so regressions can slip through if both match incorrectly. Update the
Chinese branch in TestZhFullTripleIdentity to assert tc.wantEntities and
tc.wantRels directly for each zhTests case, mirroring the English checks, and
keep the existing parity comparison afterward. Use the zhTests slice and the
tc.wantEntities/tc.wantRels fields to locate the assertions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 11eacd61-77e5-4600-b684-81493c7f08cd
📒 Files selected for processing (3)
internal/cpp/thinc_ner.cppinternal/ingestion/compilation/extractor/ner.gointernal/ingestion/compilation/extractor/ner_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/ingestion/compilation/extractor/ner.go
- internal/cpp/thinc_ner.cpp
There was a problem hiding this comment.
♻️ Duplicate comments (1)
internal/ingestion/compilation/extractor/ner.go (1)
289-296: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRoute any kana-bearing text to Japanese before the Han-heavy branch.
Japanese text with more Kanji than kana still falls through to
"zh"here, soNewExtractor(DetectLanguage(text))can load the Chinese model for valid Japanese input. Since kana is not used in Chinese andjais now supported, treathira+kata > 0as Japanese.🐛 Proposed fix
if float64(han+hira+kata)/float64(total) > 0.3 { - if hira+kata > han { + if hira+kata > 0 { return "ja" // Japanese-heavy }Consider adding a Kanji-heavy Japanese case to
internal/ingestion/compilation/extractor/ner_test.go:{"東京大学に行く", "ja"},🤖 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/compilation/extractor/ner.go` around lines 289 - 296, Route any kana-bearing text to Japanese before the Han-heavy branch in DetectLanguage within ner.go: the current CJK majority logic can still return "zh" for valid Japanese when Kanji outnumber kana. Update the branching in the language detection path so that any input with hira+kata > 0 is classified as "ja" before checking han-heavy cases, and keep the Han-heavy fallback for kana-free Chinese text. Add or extend a test in ner_test.go covering a Kanji-heavy Japanese string such as "東京大学に行く" to verify DetectLanguage returns "ja".
🤖 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.
Duplicate comments:
In `@internal/ingestion/compilation/extractor/ner.go`:
- Around line 289-296: Route any kana-bearing text to Japanese before the
Han-heavy branch in DetectLanguage within ner.go: the current CJK majority logic
can still return "zh" for valid Japanese when Kanji outnumber kana. Update the
branching in the language detection path so that any input with hira+kata > 0 is
classified as "ja" before checking han-heavy cases, and keep the Han-heavy
fallback for kana-free Chinese text. Add or extend a test in ner_test.go
covering a Kanji-heavy Japanese string such as "東京大学に行く" to verify
DetectLanguage returns "ja".
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b6418351-bd49-4fec-94be-060511220df7
📒 Files selected for processing (5)
internal/cpp/thinc_ner.cppinternal/ingestion/compilation/extractor/ner.gointernal/ingestion/compilation/extractor/ner_test.gorag/graphrag/ner/extractor.pyrag/graphrag/ner/relation_extractor.py
🚧 Files skipped from review as they are similar to previous changes (4)
- rag/graphrag/ner/extractor.py
- rag/graphrag/ner/relation_extractor.py
- internal/cpp/thinc_ner.cpp
- internal/ingestion/compilation/extractor/ner_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16456 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
@CodeRabbit review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 16
♻️ Duplicate comments (1)
internal/ingestion/compilation/extractor/ner_test.go (1)
38-90: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy liftWire these cases into actual extraction assertions.
enTestsnow records the expected NER/relation contract, but no test in the provided file consumes it, so CI can pass without exercising the new extractor pipeline. Add a table-driven test for entity and typed relation outputs, or remove the unused fixture until it is asserted.🤖 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/compilation/extractor/ner_test.go` around lines 38 - 90, The enTests fixture in ner_test.go is currently unused, so the expected NER and relation cases are not being validated by any test. Add a table-driven test that iterates over EnTestSpec and asserts the extractor output for entities and typed relations, using the existing enTests and related helpers in the test file; if this fixture is not meant to be exercised yet, remove it instead of թող leaving dead test data.
🧹 Nitpick comments (6)
rag/graphrag/ner/dep_relation_extractor.py (2)
536-538: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMove
import reto module scope.
import re as _reinside_extract_cooccurrenceruns on every call. Hoist it to the top-level imports for clarity and to avoid repeated import lookups in a hot path.🤖 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 `@rag/graphrag/ner/dep_relation_extractor.py` around lines 536 - 538, Move the regular-expression import out of the hot path by hoisting `import re as _re` from `_extract_cooccurrence` in `dep_relation_extractor.py` to the module-level imports. Update `_extract_cooccurrence` to use the module-scoped alias for the `finditer` call so the function no longer performs an import on every invocation.
448-475: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused private helpers in
rag/graphrag/ner/dep_relation_extractor.py
_already_has,_find_best_entity,_get_child_entity,_get_agent_pobj, and_get_prep_objsare only defined here and never called. Drop them unless they're intended for a follow-up change.🤖 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 `@rag/graphrag/ner/dep_relation_extractor.py` around lines 448 - 475, Remove the unused private helper methods from DepRelationExtractor in dep_relation_extractor.py: _already_has, _find_best_entity, _get_child_entity, _get_agent_pobj, and _get_prep_objs. Check the class for any remaining references before deleting them, and if a helper is meant for future use, keep it only if it is actually wired into the current extraction flow.rag/graphrag/ner/ner_extractor.py (3)
49-50: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
SKIP_SPACY_LABELSfromtypes.pyinstead of redefining.
_SKIP_LABELS = {"ORDINAL", "CARDINAL"}duplicatesSKIP_SPACY_LABELSalready exported from.types. Two copies will drift apart.♻️ Proposed change
-from .types import Entity, ExtractionResult +from .types import Entity, ExtractionResult, SKIP_SPACY_LABELS-# SpaCy labels to skip from NER output -_SKIP_LABELS = {"ORDINAL", "CARDINAL"} +# SpaCy labels to skip from NER output (see types.SKIP_SPACY_LABELS) +_SKIP_LABELS = SKIP_SPACY_LABELS🤖 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 `@rag/graphrag/ner/ner_extractor.py` around lines 49 - 50, The NER label skip set is duplicated in ner_extractor.py, which can drift from the shared constant. Update the NER extractor to import and use SKIP_SPACY_LABELS from .types instead of defining _SKIP_LABELS locally, and make sure the existing NER extraction logic in the relevant function/class references that shared symbol consistently.
242-244: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the stale trailing comment.
# Patch ExtractionResult to support metadatadescribes a no-op —ExtractionResult.metadatais already a declared dataclass field intypes.py. The dangling comment and trailing blank lines are leftover artifacts.🤖 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 `@rag/graphrag/ner/ner_extractor.py` around lines 242 - 244, Remove the stale trailing comment and any leftover blank lines in the NER extractor code path; the note about patching ExtractionResult is outdated because metadata is already part of the ExtractionResult dataclass in types.py. Update the relevant cleanup near ner_extractor.py so only the actual implementation remains and no no-op comment is left behind.
110-120: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd logging for these new extraction flows.
extract/extract_batchare the primary new entry points and currently log nothing (only_ensure_modellogs on failure). A debug/info log of model, language, and entity/relation counts would aid observability.As per coding guidelines: "Add logging for new flows" (
**/*.py).🤖 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 `@rag/graphrag/ner/ner_extractor.py` around lines 110 - 120, The new extraction entry points in NERExtractor currently do not emit any observability logs, so add debug/info logging in extract and extract_batch to record the active model/language and the number of entities/relations produced. Use the existing NERExtractor methods and __init__-set fields (such as the model/language configuration and ExtractionResult output) to place the logs after successful extraction, and keep _ensure_model unchanged except for its existing failure logging.Source: Coding guidelines
internal/ingestion/compilation/extractor/parser_go.go (1)
34-38: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftCache parser/tagger handles like the NER predictor.
These calls load and destroy native model handles per request path. Relation extraction can call this for every document, so repeated model initialization will dominate runtime; cache per
(nerDir, parserDir/taggerDir)with a safe destroy/clear lifecycle.Also applies to: 60-64
🤖 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/compilation/extractor/parser_go.go` around lines 34 - 38, The ThincParser handle is being created and destroyed on every call in the parser/tagger path, which adds heavy native model initialization overhead. Update the parsing flow around ThincParser_Create and ThincParser_Destroy to cache reusable handles keyed by the (nerDir, parserDir/taggerDir) inputs, similar to the NER predictor cache, and add a safe clear/destroy lifecycle so cached handles are released when no longer needed.
🤖 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/cpp/thinc_parser.cpp`:
- Line 31: The JSON string handling in ps() is only copying the next character
after a backslash, so escaped content like \uXXXX, quotes, backslashes, and
control characters can be corrupted; update ps() to properly decode JSON escapes
(or switch to the project’s allowed JSON utility) and then apply matching
escaping when building the JSON output in the tagger paths that concatenate raw
strings, especially the code around the tagger output assembly and token
serialization helpers.
- Around line 251-254: `parse()` currently loads `move_names` from meta.json and
later prediction logic indexes it for every classifier action, so add validation
that the vector size matches the number of actions derived from `pW_cls` before
returning success. Update the `parse()` flow in `thinc_parser.cpp` to fail fast
when `meta.json` is missing or `move_names` is shorter than the classifier rows,
and ensure the action-to-name lookup path only runs when `move_names` is
guaranteed to cover all actions.
- Around line 182-185: The parser/tagger loading path in thinc_parser.cpp is
treating several tensor loads as optional even though they are required for a
valid model state. Update the creation/loading logic around the parser state and
tagger state (including the blocks that populate poB, layernorm weights/biases,
pad_pre, pb_cls, and tb) to fail creation immediately when any required load is
missing or has the wrong shape, instead of allowing loaded=true to be set. Use
the existing load helpers and the parser/tagger state setup paths to add
explicit required-load and shape validation before returning the handle.
- Around line 155-156: The model.bin loading logic in the thinc parser reads raw
bytes into float vectors without validating that the file size is a multiple of
sizeof(float), which can overflow the allocated storage. Update the model
loading paths around the binary file reads in the parser code to check the file
size before allocating/reading, and reject or fail early when the size is not
float-aligned. Apply the same safeguard consistently in each model.bin read site
referenced by the parser load routines so the behavior is uniform across all
loaders.
- Around line 29-31: The JSON parser helpers in thinc_parser.cpp can loop
forever on malformed input because po() and pa() keep iterating when the closing
delimiter is missing and pv()/pk() may stop advancing at EOF. Update the parsing
flow in po, pa, and any called helpers like pv/ps to detect end-of-input or
missing closing tokens, then fail fast by returning an error/invalid JVal
instead of continuing to loop. Make sure the fix preserves progress checks so
tokens_json cannot hang prediction on malformed JSON.
- Around line 276-280: The preaffine projection in thinc_parser.cpp is using the
wrong weight lookup inside the nested loops, so the inner dimension is not
indexed correctly. Update the pW_pre access in the logic around the
W[p][o][w][d] computation so the offset includes the current d value, and verify
the accumulation in the loop over hidden uses the corresponding per-d weight
rather than reusing a single scalar. Keep the fix localized to the preaffine
path in the loop that computes out from hidden.
- Around line 133-136: The lowercase normalization in thinc_parser.cpp is using
raw ::tolower on a std::string, which is unsafe for bytes with the high bit set.
Update the logic in the feature-building block around the lo/t transform so each
character is cast to unsigned char before lowercasing, and consider replacing
the ASCII-only transform with a Unicode-aware casefold if non-ASCII tokens must
match spaCy’s behavior. Keep the change localized near the ids.push_back feature
extraction path so fn, fp, fs, and fsh continue to receive aligned token
features.
In `@internal/cpp/thinc_parser.h`:
- Line 19: The ThincParser_Create parameter contract is out of sync with the
implementation and Go wrapper, causing callers to pass the model directories in
the wrong order. Update the ThincParser_Create declaration and its related
documentation/comments to match the actual argument order used by the
implementation (tok2vec/NER directory first, parser directory second), and make
sure any caller-facing symbols such as ThincParser_Create and the Go wrapper
stay consistent.
In `@internal/ingestion/compilation/extractor/dep_relation.go`:
- Around line 241-251: The copula trigger list in beVerbs is incomplete for the
languages already covered by copulaDeps and langRolesMap, so copula extraction
can never start for es/pt/zh/ja. Update isBeVerb’s backing set in
dep_relation.go to include the common copula forms for those supported languages
(for example Spanish and Portuguese verb forms plus the applicable CJK copula
markers), or explicitly narrow copulaDeps/langRolesMap and document that copula
extraction only applies to en/de/fr. Use the existing beVerbs map and isBeVerb
helper as the main places to align.
- Around line 314-315: The dependency extraction path ignores the configured
distance because DepExtractRelations always appends co-occurrence relations
using a hardcoded 100. Update DepExtractRelations to take and pass through the
caller’s configured MaxDistance, and use that value in the extractCooccurrence
call so dependency extraction and the regex fallback both honor the same
distance setting.
- Around line 609-624: The dependency check in the subtree scan is effectively
disabled because the condition in the inner loop always evaluates true. In the
logic inside the function that walks `childrenOf` and uses `containsDep`, remove
the `|| true` fallback so only valid object dependencies are accepted for
`gc.Dep`. Keep the entity lookup and assignment to `prepObj`/`titleLemma`
unchanged, but make the object selection depend on the existing `cd.objDeps`
rules to avoid false positives.
In `@internal/ingestion/compilation/extractor/ner.go`:
- Around line 236-263: The getPredictor function is caching a failing NER
predictor when ThincNER_Create returns nil, which causes modelCache to keep a
permanently broken closure for that modelDir. Update getPredictor so it checks
the handle immediately after ThincNER_Create, returns an error or otherwise
avoids storing the predictor when the handle is nil, and only writes to
modelCache after a valid handle has been created. Keep the fix localized to
getPredictor, modelCache, and the predictor closure setup.
- Around line 300-310: The dedup key in NER extraction is using a rune
conversion for the entity start offset, which can corrupt large values and cause
distinct entities to collide. Update the key construction in NERExtractor’s
dedup logic to use a decimal string representation of re.Start instead of a
character conversion, and keep the rest of the seen-map dedup behavior
unchanged.
- Around line 207-229: Dependency extraction is using the fallback language
instead of the real input language, so language-specific rules in
DepExtractRelations are bypassed. Keep the langFallback mapping only for the
regex-based extractRelationsWithOpts path, and pass e.Lang directly into
DepExtractRelations in ner.go so de/fr/es/pt/ja relations use their correct role
maps.
In `@rag/graphrag/ner/dep_relation_extractor.py`:
- Around line 391-397: The prep-object selection in dep_relation_extractor.py is
bypassing its own dependency filter because `or True` makes the `gc.dep_ in
pobj_deps` check meaningless. Update the child loop in the relation extraction
logic to either enforce the intended `pobj_deps` whitelist by removing the
unconditional condition, or explicitly simplify the code if any child should be
accepted. Use the `pobj_deps`, `gc.dep_`, and `_entity_from_subtree` path to
confirm the fix preserves the intended object extraction behavior.
In `@rag/graphrag/ner/ner_extractor.py`:
- Around line 174-181: `extract_batch` is building `ExtractionResult.metadata`
differently from `extract`, so make the batch path use the same metadata shape
as the single-document path. In `NERExtractor.extract_batch`, populate
`metadata` on every result with the same core fields set by `extract` (`model`,
`n_tokens`, `n_entities`, `n_relations`) and add `tokens` only when
`include_tokens` is true, using the existing `ExtractionResult` construction and
`result.metadata` assignment pattern as the reference.
---
Duplicate comments:
In `@internal/ingestion/compilation/extractor/ner_test.go`:
- Around line 38-90: The enTests fixture in ner_test.go is currently unused, so
the expected NER and relation cases are not being validated by any test. Add a
table-driven test that iterates over EnTestSpec and asserts the extractor output
for entities and typed relations, using the existing enTests and related helpers
in the test file; if this fixture is not meant to be exercised yet, remove it
instead of թող leaving dead test data.
---
Nitpick comments:
In `@internal/ingestion/compilation/extractor/parser_go.go`:
- Around line 34-38: The ThincParser handle is being created and destroyed on
every call in the parser/tagger path, which adds heavy native model
initialization overhead. Update the parsing flow around ThincParser_Create and
ThincParser_Destroy to cache reusable handles keyed by the (nerDir,
parserDir/taggerDir) inputs, similar to the NER predictor cache, and add a safe
clear/destroy lifecycle so cached handles are released when no longer needed.
In `@rag/graphrag/ner/dep_relation_extractor.py`:
- Around line 536-538: Move the regular-expression import out of the hot path by
hoisting `import re as _re` from `_extract_cooccurrence` in
`dep_relation_extractor.py` to the module-level imports. Update
`_extract_cooccurrence` to use the module-scoped alias for the `finditer` call
so the function no longer performs an import on every invocation.
- Around line 448-475: Remove the unused private helper methods from
DepRelationExtractor in dep_relation_extractor.py: _already_has,
_find_best_entity, _get_child_entity, _get_agent_pobj, and _get_prep_objs. Check
the class for any remaining references before deleting them, and if a helper is
meant for future use, keep it only if it is actually wired into the current
extraction flow.
In `@rag/graphrag/ner/ner_extractor.py`:
- Around line 49-50: The NER label skip set is duplicated in ner_extractor.py,
which can drift from the shared constant. Update the NER extractor to import and
use SKIP_SPACY_LABELS from .types instead of defining _SKIP_LABELS locally, and
make sure the existing NER extraction logic in the relevant function/class
references that shared symbol consistently.
- Around line 242-244: Remove the stale trailing comment and any leftover blank
lines in the NER extractor code path; the note about patching ExtractionResult
is outdated because metadata is already part of the ExtractionResult dataclass
in types.py. Update the relevant cleanup near ner_extractor.py so only the
actual implementation remains and no no-op comment is left behind.
- Around line 110-120: The new extraction entry points in NERExtractor currently
do not emit any observability logs, so add debug/info logging in extract and
extract_batch to record the active model/language and the number of
entities/relations produced. Use the existing NERExtractor methods and
__init__-set fields (such as the model/language configuration and
ExtractionResult output) to place the logs after successful extraction, and keep
_ensure_model unchanged except for its existing failure logging.
🪄 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
Run ID: 2ed90665-af4a-4b41-b01c-3bbe90995a10
📒 Files selected for processing (13)
internal/cpp/CMakeLists.txtinternal/cpp/thinc_ner.cppinternal/cpp/thinc_parser.cppinternal/cpp/thinc_parser.hinternal/ingestion/compilation/extractor/dep_relation.gointernal/ingestion/compilation/extractor/ner.gointernal/ingestion/compilation/extractor/ner_relation.gointernal/ingestion/compilation/extractor/ner_test.gointernal/ingestion/compilation/extractor/parser_go.gorag/graphrag/ner/__init__.pyrag/graphrag/ner/dep_relation_extractor.pyrag/graphrag/ner/ner_extractor.pyrag/graphrag/ner/types.py
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/cpp/CMakeLists.txt
- internal/ingestion/compilation/extractor/ner_relation.go
- internal/cpp/thinc_ner.cpp
| auto fsh=[&](const std::string& t2){std::string sh;for(unsigned char c:t2){if(c>0x7F)sh+='x';else if(std::isupper(c))sh+='X';else if(std::islower(c))sh+='x';else if(std::isdigit(c))sh+='d';else sh+=c;}return hash_feat(sh);}; | ||
| std::vector<uint64_t> ids; | ||
| std::string lo=t;std::transform(lo.begin(),lo.end(),lo.begin(),::tolower); | ||
| ids.push_back(fn(lo));ids.push_back(fp(t));ids.push_back(fs(t));ids.push_back(fsh(t)); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify all ctype/tolower call sites cast to unsigned char before classification.
rg -n -C2 '::tolower|std::tolower|std::isupper|std::islower|std::isdigit' internal/cpp/thinc_parser.cppRepository: infiniflow/ragflow
Length of output: 863
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the surrounding function and any UTF-8 helpers used nearby.
sed -n '100,180p' internal/cpp/thinc_parser.cpp
printf '\n---\n'
rg -n 'u8_first|u8_last|u8_len|tolower|casefold|lower' internal/cpp/thinc_parser.cpp internal/cpp -g '!**/build/**'Repository: infiniflow/ragflow
Length of output: 14016
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Look for documentation or tests that describe the expected normalization behavior.
rg -n -i 'spaCy|spacy|multilingual|Unicode lower|casefold|UTF-8 aware|feature hashing|lowercase' README* docs internal/cpp tests .Repository: infiniflow/ragflow
Length of output: 50376
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Check the parser API/docs to see whether this path is intended for English-only or multilingual use.
sed -n '1,120p' internal/cpp/thinc_parser.h
printf '\n---\n'
sed -n '1,120p' internal/cpp/thinc_ner.hRepository: infiniflow/ragflow
Length of output: 3324
Make the lowercasing UTF-8 safe. ::tolower on raw char is undefined for bytes with the high bit set; cast to unsigned char first. If non-ASCII tokens are expected here, replace this with a Unicode-aware casefold so feature hashes stay aligned with spaCy.
🤖 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/cpp/thinc_parser.cpp` around lines 133 - 136, The lowercase
normalization in thinc_parser.cpp is using raw ::tolower on a std::string, which
is unsafe for bytes with the high bit set. Update the logic in the
feature-building block around the lo/t transform so each character is cast to
unsigned char before lowercasing, and consider replacing the ASCII-only
transform with a Unicode-aware casefold if non-ASCII tokens must match spaCy’s
behavior. Keep the change localized near the ids.push_back feature extraction
path so fn, fp, fs, and fsh continue to receive aligned token features.
| for gc in cc.children: | ||
| pobj_deps = {"pobj", "nk", "obl"} | ||
| if gc.dep_ in pobj_deps or True: # accept any child as object | ||
| prep_obj = self._entity_from_subtree(gc, entity_map) | ||
| if prep_obj: | ||
| title_lemma = c.lemma_.lower() | ||
| break |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
or True defeats the pobj_deps filter.
if gc.dep_ in pobj_deps or True: is unconditionally true, so pobj_deps is dead and the first child of the prep node is accepted regardless of its dependency label. If accepting any child is intentional, drop pobj_deps; otherwise remove or True so the filter actually applies.
♻️ Option A — enforce the filter
for gc in cc.children:
pobj_deps = {"pobj", "nk", "obl"}
- if gc.dep_ in pobj_deps or True: # accept any child as object
- prep_obj = self._entity_from_subtree(gc, entity_map)
- if prep_obj:
- title_lemma = c.lemma_.lower()
- break
+ if gc.dep_ in pobj_deps:
+ prep_obj = self._entity_from_subtree(gc, entity_map)
+ if prep_obj:
+ title_lemma = c.lemma_.lower()
+ break📝 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.
| for gc in cc.children: | |
| pobj_deps = {"pobj", "nk", "obl"} | |
| if gc.dep_ in pobj_deps or True: # accept any child as object | |
| prep_obj = self._entity_from_subtree(gc, entity_map) | |
| if prep_obj: | |
| title_lemma = c.lemma_.lower() | |
| break | |
| for gc in cc.children: | |
| pobj_deps = {"pobj", "nk", "obl"} | |
| if gc.dep_ in pobj_deps: | |
| prep_obj = self._entity_from_subtree(gc, entity_map) | |
| if prep_obj: | |
| title_lemma = c.lemma_.lower() | |
| break |
🤖 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 `@rag/graphrag/ner/dep_relation_extractor.py` around lines 391 - 397, The
prep-object selection in dep_relation_extractor.py is bypassing its own
dependency filter because `or True` makes the `gc.dep_ in pobj_deps` check
meaningless. Update the child loop in the relation extraction logic to either
enforce the intended `pobj_deps` whitelist by removing the unconditional
condition, or explicitly simplify the code if any child should be accepted. Use
the `pobj_deps`, `gc.dep_`, and `_entity_from_subtree` path to confirm the fix
preserves the intended object extraction behavior.
| result = ExtractionResult( | ||
| entities=entities, | ||
| relations=relations, | ||
| language=self.language, | ||
| ) | ||
| if include_tokens: | ||
| result.metadata = {"tokens": tokens} | ||
| results.append(result) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
extract_batch populates metadata inconsistently with extract.
extract() always sets model, n_tokens, n_entities, n_relations (and optionally tokens), but extract_batch() sets metadata only when include_tokens=True — and even then drops the counts/model. Callers consuming result.metadata get different shapes depending on the entry point.
♻️ Align batch metadata with single-doc path
result = ExtractionResult(
entities=entities,
relations=relations,
language=self.language,
)
- if include_tokens:
- result.metadata = {"tokens": tokens}
+ result.metadata = {
+ "model": self.model_name,
+ "n_tokens": len(doc),
+ "n_entities": len(entities),
+ "n_relations": len([r for r in relations if r.predicate != "related_to"]),
+ }
+ if include_tokens:
+ result.metadata["tokens"] = tokens
results.append(result)📝 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.
| result = ExtractionResult( | |
| entities=entities, | |
| relations=relations, | |
| language=self.language, | |
| ) | |
| if include_tokens: | |
| result.metadata = {"tokens": tokens} | |
| results.append(result) | |
| result = ExtractionResult( | |
| entities=entities, | |
| relations=relations, | |
| language=self.language, | |
| ) | |
| result.metadata = { | |
| "model": self.model_name, | |
| "n_tokens": len(doc), | |
| "n_entities": len(entities), | |
| "n_relations": len([r for r in relations if r.predicate != "related_to"]), | |
| } | |
| if include_tokens: | |
| result.metadata["tokens"] = tokens | |
| results.append(result) |
🤖 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 `@rag/graphrag/ner/ner_extractor.py` around lines 174 - 181, `extract_batch` is
building `ExtractionResult.metadata` differently from `extract`, so make the
batch path use the same metadata shape as the single-document path. In
`NERExtractor.extract_batch`, populate `metadata` on every result with the same
core fields set by `extract` (`model`, `n_tokens`, `n_entities`, `n_relations`)
and add `tokens` only when `include_tokens` is true, using the existing
`ExtractionResult` construction and `result.metadata` assignment pattern as the
reference.
|
@CodeRabbit review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
internal/cpp/thinc_ner.cpp (3)
431-436: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winDerive
Dfrom loaded embedding tensors.The prediction path still assumes
96-wide embeddings, butHashEmbed::embed()writesnOfloats from the checkpoint. A model with a different width can overflow or misalign the concatenated embedding buffer. This duplicates the earlier runtime-dimension concern.🤖 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/cpp/thinc_ner.cpp` around lines 431 - 436, The prediction path in the embedding concat logic still hardcodes the per-embedding width through D, while HashEmbed::embed() uses the loaded tensor width, so make D come from the loaded embedding tensors in the model rather than assuming 96. Update the Step 1 loop in thinc_ner.cpp around the s->embeds[e].embed() call and any related buffer sizing so the concatenation matches the actual embedding dimension and cannot overflow or misalign when checkpoint widths differ.
527-547: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftVerify this against spaCy’s actual transition-state decoder.
This is still greedy per-token BILUO selection constrained only by the previous label. If the exported checkpoint is spaCy’s transition-based NER, parity requires applying parser-state actions, not just local BILUO constraints.
#!/bin/bash # Verify whether the exported NER artifacts are token-level BILUO labels or spaCy transition-parser actions. rg -n -C4 'TransitionBasedParser|ParserStepModel|action_to_label|BILUO|moves|pW_full|predict_states' .🤖 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/cpp/thinc_ner.cpp` around lines 527 - 547, The constrained greedy decoding in thinc_ner.cpp still operates as local per-token BILUO filtering, which does not match spaCy’s transition-based NER decoder. Update the logic around the constrained greedy decoding block to use the actual transition-state action sequence from the spaCy parser model (for example via the TransitionBasedParser/ParserStepModel path) rather than selecting the highest-scoring token label with only previous-label constraints. Verify the checkpoint/exported artifacts to confirm whether the model exposes parser actions or token labels, and wire the decode path in line with that representation.
381-390: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winOnly enable PrecomputableAffine after validating W, bias, and hidden dimensions.
has_preis set frompW_fullalone, but prediction always readspB_full[o*nP+p]andh[d]. A missing/short bias orp_nD != s->hOcan read past the loaded buffers. This is the same class of incomplete-parameter activation flagged earlier.Proposed hardening
- size_t total = (size_t)nP * nO * nI * nD; + if(nP<=0 || nO<=0 || nI<=0 || nD<=0 || nD!=s->hO) return false; + size_t total = (size_t)nP * nO * nI * nD; s->pW_full = sl(ov->as_i64(), cv->as_i64()); - s->has_pre = s->pW_full.size() >= total; + bool has_pW = s->pW_full.size() == total; + s->has_pre = has_pW && s->pB_full.size() == (size_t)nO * nI;- s->pB_full = sl(pb_ov->as_i64(), pb_cv->as_i64()); + s->pB_full = sl(pb_ov->as_i64(), pb_cv->as_i64()); + s->has_pre = s->pW_full.size() == (size_t)s->p_nP * s->p_nO * s->p_nI * s->p_nD + && s->pB_full.size() == (size_t)s->p_nO * s->p_nI + && s->p_nD == s->hO;- const float* h = hid.data() + (size_t)i * nO; + const float* h = hid.data() + (size_t)i * s->hO;Also applies to: 489-510
🤖 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/cpp/thinc_ner.cpp` around lines 381 - 390, The PrecomputableAffine path is being enabled too early in thinc_ner.cpp: `has_pre` is currently derived from `pW_full` alone, but `predict` later depends on `pB_full` and the hidden-size match (`p_nD` vs `hO`). Update the initialization/validation logic around the `pW_full` and `pB_full` loading blocks (and the corresponding prediction setup later in the file) so `has_pre` is only set when weight, bias, and hidden-dimension requirements are all satisfied and buffer lengths are sufficient; otherwise leave precomputation disabled.
🤖 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/cpp/thinc_ner.cpp`:
- Around line 203-205: The 5-embedding feature order in thinc_ner.cpp is wrong
for zh models: in the `ids` construction inside the `n_embed >= 5` block, the
value currently placed for the `SPACY` feature ends up at position `#4` when
`n_embed == 5`, but the contract expects `IS_SPACE` there. Update the feature
push order in the `ids` assembly logic so the `IS_SPACE`-related entry is
emitted at feature slot `#4` for the 5-table path, keeping the surrounding
`n_embed` handling and the rest of the feature indices unchanged.
---
Duplicate comments:
In `@internal/cpp/thinc_ner.cpp`:
- Around line 431-436: The prediction path in the embedding concat logic still
hardcodes the per-embedding width through D, while HashEmbed::embed() uses the
loaded tensor width, so make D come from the loaded embedding tensors in the
model rather than assuming 96. Update the Step 1 loop in thinc_ner.cpp around
the s->embeds[e].embed() call and any related buffer sizing so the concatenation
matches the actual embedding dimension and cannot overflow or misalign when
checkpoint widths differ.
- Around line 527-547: The constrained greedy decoding in thinc_ner.cpp still
operates as local per-token BILUO filtering, which does not match spaCy’s
transition-based NER decoder. Update the logic around the constrained greedy
decoding block to use the actual transition-state action sequence from the spaCy
parser model (for example via the TransitionBasedParser/ParserStepModel path)
rather than selecting the highest-scoring token label with only previous-label
constraints. Verify the checkpoint/exported artifacts to confirm whether the
model exposes parser actions or token labels, and wire the decode path in line
with that representation.
- Around line 381-390: The PrecomputableAffine path is being enabled too early
in thinc_ner.cpp: `has_pre` is currently derived from `pW_full` alone, but
`predict` later depends on `pB_full` and the hidden-size match (`p_nD` vs `hO`).
Update the initialization/validation logic around the `pW_full` and `pB_full`
loading blocks (and the corresponding prediction setup later in the file) so
`has_pre` is only set when weight, bias, and hidden-dimension requirements are
all satisfied and buffer lengths are sufficient; otherwise leave precomputation
disabled.
🪄 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
Run ID: 60f4fc28-beea-4c25-8f93-3570a090a4c9
📒 Files selected for processing (5)
internal/cpp/thinc_ner.cppinternal/cpp/thinc_parser.cppinternal/cpp/thinc_parser.hinternal/ingestion/compilation/extractor/dep_relation.gointernal/ingestion/compilation/extractor/ner.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/ingestion/compilation/extractor/dep_relation.go
- internal/cpp/thinc_parser.cpp
- internal/ingestion/compilation/extractor/ner.go
… version with equivalent outputs (infiniflow#16456) As title
As title