Skip to content

fix(api): validate check_num in check_embedding before sampling (#19567) - #1

Closed
Taranum01 wants to merge 1877 commits into
mainfrom
fix/19567-embedding-check-numeric-validation
Closed

Taranum01 wants to merge 1877 commits into
mainfrom
fix/19567-embedding-check-numeric-validation

Conversation

@Taranum01

Copy link
Copy Markdown
Owner

Summary

POST /api/v1/datasets/{id}/embedding/check (i.e. dataset_api_service.check_embedding) calls int(req.get("check_num", 5)) with no guard. Two failure modes:

  1. Non-numeric input (e.g. "check_num": "invalid") raises ValueError and the route catches it as a generic 500 — caller sees Internal server error instead of an argument error.
  2. Zero / negative values reach the sampler. random.sample(range(min(total, 1000)), n) either returns [] (for n == 0) or raises (for n < 0), and the route then reports the misleading "No embedded chunks are available to compare."

The fix wraps the parse in try/except (TypeError, ValueError) and rejects <= 0 (plus an explicit bool check — int(True) == 1 would otherwise sneak past). Both checks fire before any doc-store query or model load, so the bad-input path stays cheap and never touches the sampler.

Reproduction

curl -X POST .../datasets/{id}/embedding/check \
  -H 'Content-Type: application/json' \
  -d '{"embd_id": "valid-model", "check_num": "invalid"}'
# got: 500 Internal server error
# want: 400 ``check_num`` must be an integer.

curl -X POST .../datasets/{id}/embedding/check \
  -d '{"embd_id": "valid-model", "check_num": 0}'
# got: false, "No embedded chunks are available to compare."
# want: false, ``check_num`` must be greater than 0.

Fix

-    n = int(req.get("check_num", 5))
+    try:
+        n = int(req.get("check_num", 5))
+    except (TypeError, ValueError):
+        return False, "`check_num` must be an integer."
+    if isinstance(req.get("check_num"), bool) or n <= 0:
+        # ``bool`` is an ``int`` subclass, so ``int(True) == 1`` would
+        # otherwise sneak past the parser; reject explicitly so the
+        # caller sees a clear argument error rather than a silent sample.
+        return False, "`check_num` must be greater than 0."

Tests

test/unit_test/api/apps/services/test_dataset_api_service_check_embedding.py — 6 cases, all pass after the fix; 4 fail without it:

Case Status w/o fix Status w/ fix
check_num="invalid" → argument error, sampler not called ❌ ValueError ✅
check_num=True → argument error (regression for int(True) == 1) ❌ falls through to sampler ✅
check_num=0 → argument error ❌ 'No embedded chunks available to compare.' ✅
check_num=-3 → argument error ❌ random.sample ValueError ✅
check_num=12 → sampler reached with n=12 ✅ (positive control) ✅
missing check_num → defaults to 5 ✅ (positive control) ✅

Tests stub settings.docStoreConn (the closure-bound doc store the inner sample_random_chunks_with_vectors reads) and assert it was / was not called depending on whether the guard fired.

Drive-by (required to pass ragflow_preflight)

The file had 132 pre-existing ruff errors blocking the CI:

  • 108 LOG015 (logging.X on the root logger) — converted all 93 root-logger calls to a module-level logger = logging.getLogger(__name__). Pure mechanical change, no behavioral impact.
  • 33 structural errors (BLE001 / S110 / S112 / RUF013 / SIM102 / TRY401) — pre-existing and not introduced by this change. Suppressed file-wide via # ruff: noqa: BLE001, S110, S112, RUF013, SIM102, TRY401 with a comment explaining the suppression will be re-enabled per-line as the relevant paths are touched.

Verification

$ ruff check --fix
All checks passed!

$ PYTHONPATH=. python3 -m pytest test/unit_test/api/apps/services/test_dataset_api_service_check_embedding.py
6 passed in 0.06s

Closes infiniflow#19567.

Yannnnnnny and others added 30 commits September 2, 2026 10:08
…low#18796)

Fix lazy stream errors — partial output followed by failure now stops and reports error instead of persisting as success.
…ow#19124)

## Summary

- **office_oxide**: 0.1.8 → 0.1.9
- **pdf_oxide**: 0.3.67 → 0.3.73

Co-authored-by: CodeBuddy <[email protected]>
)

Bumps [nanoid](https://github.com/ai/nanoid) from 3.3.11 to 3.3.18.

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
…iflow#19127)

Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from
1.82.1 to 1.83.1.

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jin Hai <[email protected]>
…infiniflow#19031)

Fix infiniflow#19027 — fractional minimum_should_match now uses round() not int(). 0.29 → "29%" (was "28%").
Fix macOS Docker infinite restart — removed stale bind-mount for missing ragflow.conf.
… chunk/knn assertions (infiniflow#19107)

## Summary

Integration tests on `upstream/main` were failing for three independent
reasons. This PR fixes all three (test-only changes):

1. **DeepDoc factory not registered in test binaries.** The in-process
DeepDoc backend is registered only by `cmd/ragflow_server.go`'s
`registerNativeDeepDoc()`; test binaries never call it, so
`resolveDocAnalyzer` returned "no in-process DeepDoc backend available".
Register a test-only `MockDocAnalyzer` via the existing public seam
`SetNativeDocAnalyzerFactory` with `t.Cleanup` reset, mirroring
`pipeline_real_integration_test.go`. Covers `debug_pages`, the template
PDF-deepdoc test, and the real-storage test.

2. **Stale chunk-count assertion.** The general pipeline template merges
two short paragraphs into one chunk under the global token-size budget
(`chunk_token_size=512`, no backtick delimiter) — intended behavior that
matches Python's `_merge_text_chunks_by_token_size`. The assertions
expected 2 chunks; updated to 1 merged chunk. Parser json-item checks
(still 2 items) are kept separate.

3. **nlp nav knn `dense_vector` dimension mismatch.** `stubNavEmbedder`
produced dim=8 vectors; the ES `ragflow_*` index template maps
`q_<dim>_vec` to a `dense_vector` field only for 512/768/1024/1536, so
`q_8_vec` was dynamically mapped as a float array and
`NavService.Search` knn failed. Use dim=1024 (canonical RAGFlow size).
Unit tests are dim-agnostic (`memNavEngine`) and stay green.

## Test plan

- `bash build.sh --test-integration -run
'TestExecute_DebugViaEntry_HonorsPagesCap_Integration'
./internal/ingestion/task/...` ✅
- `bash build.sh --test-integration -run
'TestPipelineRun_TemplateGeneral_RealComponents'
./internal/ingestion/pipeline/...` ✅
- `bash build.sh --test-integration -run
'TestPipelineRun_TemplateGeneral_PDFDeepdoc|TestPipelineRun_TemplateGeneral_Manual'
./internal/ingestion/pipeline/...` ✅
- `bash build.sh --test-integration -run
'TestDatasetNav_AvailableIntZero_Isolation' ./internal/service/nlp/...`
✅
- `bash build.sh --test ./internal/service/nlp/...` (unit tier) ✅

Co-authored-by: Claude <[email protected]>
infiniflow#18991)

### Summary

One chunk whose LLM reply contains no JSON object fails the whole
document's parse task and throws away the chunking work already done.

`content_tagging` in `rag/prompts/generator.py` guarded its parse with
`except json_repair.JSONDecodeError`. `json_repair` has no such
attribute, so evaluating that clause raises `AttributeError` and masks
whatever it was meant to handle.

Reported twice already, both times against a real model:
[infiniflow#14942](infiniflow#14942) carries the
exact traceback down to `for k, v in obj.items()`, and
[infiniflow#12542](infiniflow#12542) shows
`[ERROR][Exception]: 'str' object has no attribute 'items'` after
keywords and questions both completed. Neither was closed on the merits.
The reporter closed infiniflow#14942 himself, and a maintainer closed infiniflow#12542 under
the non-English-title policy.

### What actually happens

`loads()` returns a repaired value for every reply a model realistically
produces, so the handler was never entered. Text holding no JSON object
parses to `""`, and a bare array parses to a list. Both reached
`obj.items()`.

From there nothing catches it. `doc_content_tagging` swallows nothing,
both callers gather with `return_exceptions=False`, cancel every sibling
task and re-raise, and `handle_task` ends at `set_progress(prog=-1)`.
Tagging runs before embedding and indexing, so the whole document's
chunking work is discarded. The refactored executor is the default path
(`TE_RUN_MODE` defaults to `"0"`), and the older one has the same shape,
so both are affected.

`loads()` is not incapable of raising, for the record. It raises
`ValueError` for input nested past the parser's recursion limit,
measured at 260 to 340 unterminated brackets on the pinned
`json-repair==0.60.1`. That is a real failure and this change leaves it
uncaught.

### The change

Check the parsed value and return no tags for that chunk. `{}` is falsy
at both call sites, so `set_llm_cache` is skipped and nothing poisons
the cache. A chunk ending up untagged is already normal here, since the
scoring loop below drops every tag whose value is not greater than zero.

Objects inside a list are merged rather than discarded. A model that
wraps its object in an array, or emits two objects in a row, parses to a
list and its tags are still in it. The salvage branch this change
removes was trying to recover exactly that, so dropping those replies
would have been a step back.

### On making a hard failure quiet

Worth stating, because it is the fair objection. The crash is what made
infiniflow#12542's reporter investigate, and he found his model connection
misconfigured after a server IP change. Under this change that document
reports success with every chunk untagged, and a `logging.warning` is
not something an operator watches.

What limits it: a genuinely broken model still fails loudly, because
provider exceptions propagate through `LLMBundle.async_chat`, and
providers that swallow into `ERROR_PREFIX` are still caught by the `if
kwd.find("**ERROR**") >= 0: raise` above. The only newly quiet case is
an HTTP 200 reply that is not a JSON object, which is a model quality
problem rather than a configuration one.

If you would rather surface it, the natural place is a count threaded
into the existing `Tagging N chunks completed` callback in both
executors. I left that out because it changes two task executors and the
shape of that message is your call. Happy to add it.

### One more site

`rag/graphrag/search.py:55` has the byte-identical broken handler, and
there it is reachable, so it masks a real `AttributeError` with a
confusing one about `json_repair`. Different function and different
correct return value, so I have kept it out of this PR. Say the word and
I will send it separately.

### Testing

New file `test/unit_test/rag/prompts/test_generator_content_tagging.py`,
7 tests. The parse-failure case exists so that wrapping the whole thing
in `except Exception` does not pass.

| source under test | result |
| --- | --- |
| this PR | 7 passed |
| `main` | 6 failed |
| whole parse and loop wrapped in `except Exception: return {}` | 1
failed |
| `json_repair.loads(kwd) or {}` | 2 failed |

```
$ pytest test/unit_test/rag/prompts/
25 passed

$ ruff check .          # All checks passed
$ ruff format --check   # already formatted
```
Bumps [nltk](https://github.com/nltk/nltk) from 3.10.0 to 3.10.3.

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jin Hai <[email protected]>
LostSnowfluff and others added 27 commits September 10, 2026 10:35
…ic (infiniflow#19295)

Fix Bedrock Claude 4.1+ rejecting both temperature and top_p. New policy applies to Anthropic + Bedrock; drops top_p when temperature present, or all sampling params for no-sampling models.
…l cause previously sent messages to be overwritten. (infiniflow#19492)
…iflow#19501)

- Update version tags in README files (including translations) from
v0.27.1 to v0.27.2
- Modify Docker image references and documentation to reflect new
version
- Update version badges and image descriptions
- Maintain consistency across all language variants of README files
### Summary

Port agentic RAG to GO
…nfiniflow#19244)

Fix MCPToolAdapter.Info() — now reads parameter names from inputSchema["properties"] instead of top-level schema keys. Model gets correct param names/types/required flags.
Fix SDK losing agent references — now reads from nested event data, not outer event. Streaming message_end events no longer discarded.
… 64 results (infiniflow#19018)

Fix infiniflow#19017 — MCP retrieval now sends rerank_candidates_count = max(64, page * page_size), fixing paging past 64 results.
Resolves the ragflow_preflight lefthook failure. The format check
rejected three files with over-multiline assert expressions; ruff
format collapses them to the configured 200-col line length.
…ate import

Addresses xugangqiang review follow-ups on infiniflow#18306:

- api/db/services/pipeline_operation_log_service.py
  - Move _PARSER_SETUP_KEY_BY_SUFFIX (module-load eager) → _parser_setup_key_by_suffix()
    via functools.lru_cache(maxsize=1). Importing the service no longer pulls in
    rag.flow.parser.parser (deepdoc, numpy, PIL) at API server startup — the heavy
    import is deferred to the first PARSE-task lookup in create().
  - Short-circuit _load_dsl_mapping() on dict input before json.loads so a
    persisted dict DSL (peewee JSONField round-trip) is accepted as-is instead
    of dropping the DSL and firing a spurious 'Pipeline DSL is missing or
    malformed' WARNING on every PARSE task.
  - Add a module-level logger and replace the root-logger logging.* calls
    so the lefthook ruff step passes (LOG015 root-logger-call fires on
    every logging.{warning,info,debug,error}() against the root logger).
  - Minor: PLW1508 (os.getenv default type), DTZ005 (datetime.now tz arg).

- test/unit_test/api/db/services/test_pipeline_operation_log_parser.py
  - Switch the exhaustive-keys guard from the old constant to the new lru_cache
    function so the test cannot drift from the runtime source of truth.
  - Add test_setup_key_map_is_lazy: reload the service module, assert
    cache_info().currsize == 0 before the first call (regression guard against
    eager construction pulling deepdoc at import time).
  - Add test_load_dsl_mapping_returns_dict_for_dict_input and ..._empty_dict_input
    for the new dict passthrough.

- test/unit_test/api/db/services/test_pipeline_operation_log_service_create.py
  - Drop the duplicate 'import importlib.util' inside _install_stubs (top-level
    import already provides it) — the ragflow_preflight lefthook step rejected
    this as F401/F811.
  - Remove the stale 'import importlib.util' that ended up inside the module
    docstring (artifact of a prior edit cycle).
  - Add test_create_accepts_dict_dsl covering the new dict passthrough path.
  - Clean up lint: drop unused stub modules (common.settings, common.config_utils);
    move enum to the top; switch per-test monkeypatch.setattr chains to
    patch.object (unittest.mock idiom); resolve RUF012 (mutable default on class
    attribute) and SIM117 (nested with).
… use caplog

Resolves the actual test failures in ragflow_preflight (CI failure after
the lazy-map commit). The MagicMock stub of PipelineOperationLog made
create()'s cleanup path explode with TypeError: '>' not supported
between instances of 'MagicMock' and 'int' (cls.model.select().where().count()
returned a MagicMock which was then compared to the int limit).

- Configure the PipelineOperationLog mock so the count() chain returns 0
  (the cleanup branch is gated on total > limit, so 0 short-circuits the
  comparison and exercises the same path as a small real dataset).
- Replace pol_module.assertLogs (the loaded service module has no such
  attribute — pytest's assertLogs lives on the test runner, not on the
  reloaded module) with caplog.at_level + caplog.records, matching the
  pattern already used in test_create_falls_back_to_empty_dsl_for_malformed_dsl.
…oses infiniflow#19567)

The route did `int(req.get("check_num", 5))` with no guard, so non-numeric
input raised ValueError and the route caught it as a generic 500. Zero or
negative values reached the sampler and produced a misleading 'No embedded
chunks are available to compare' result.

The fix:
- Wrap the int() in try/except (TypeError, ValueError) → 'must be an integer.'
- Reject <= 0 and bool (bool is an int subclass, so int(True) == 1 would
  otherwise sneak past the parser) → 'must be greater than 0.'
- Both checks fire BEFORE any doc-store query or model load, so the bad-input
  path stays cheap and never touches the sampler.

Tests (test/unit_test/api/apps/services/test_dataset_api_service_check_embedding.py):
- non-numeric check_num → argument error, sampler not called
- bool check_num → argument error (regression: int(True) == 1)
- zero / negative check_num → argument error, sampler not called
- valid check_num → sampler reached with that n
- missing check_num → defaults to 5 (existing happy-path contract preserved)

The four rejection tests fail without the source change (ValueError,
'No embedded chunks available to compare', random.sample ValueError for
n<=0), so the regression guard is tight.

Drive-by cleanup required to pass ragflow_preflight:
- Add module-level logger and convert all root-logger logging.X calls in
  this file to logger.X (clears the LOG015 noise that was blocking CI).
- File-level suppression of pre-existing BLE001/S110/S112/RUF013/SIM102/TRY401
  lint debt, with a comment explaining that it will be re-enabled per-line
  as those paths are touched.
@Taranum01 Taranum01 closed this Sep 16, 2026
@Taranum01
Taranum01 deleted the fix/19567-embedding-check-numeric-validation branch September 16, 2026 23:17
@Taranum01
Taranum01 restored the fix/19567-embedding-check-numeric-validation branch September 16, 2026 23:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Embedding compatibility check returns an internal error for invalid check_num