Skip to content

fix(metadata): discover ES fields after sparse table chunks - #16949

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
chuenchen309:fix/table-metadata-sparse-first-chunk
Jul 16, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
chuenchen309:fix/table-metadata-sparse-first-chunk

Conversation

@chuenchen309

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

When a table dataset's field_map is missing or stale, aggregate_table_doc_metadata falls back to probing chunk dictionaries for each column's Elasticsearch field key. It currently performs that probe only once, against the first dictionary chunk, and caches (None, "none") if the field is absent there.

Sparse table rows commonly omit empty columns. If the first row has no notes field but a later row contains notes_raw, the cached miss causes every later row to be skipped and the document-level notes metadata is silently lost. The result depends only on row order:

chunks = [{}, {"notes_raw": "Handle with care"}]
aggregate_table_doc_metadata(chunks, task)           # before: {}
aggregate_table_doc_metadata(list(reversed(chunks)), task)
# before: {"notes": ["Handle with care"]}

This was also identified in CodeRabbit's review of the merged table-metadata implementation in #15780, but remained unfixed after that PR merged: #15780 (review)

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

Fix

When the initial lookup found no key for a column, retry the existing _resolve_es_chunk_field_key against the current chunk. Cache the first successful resolution so subsequent rows retain the existing fast path. Field-map-backed columns and columns found in the first chunk are unchanged.

Testing

  • Added test_aggregate_auto_mode_probes_later_sparse_chunks with an empty first row and a populated second row.
  • Confirmed red→green: before the fix the assertion received {}; after the fix it receives {"notes": ["Handle with care"]}.
  • Full existing test_table_metadata_aggregation.py: 15 passed.
  • ruff check and ruff format --check: clean.
  • compileall for both changed files: clean.

The local test environment did not contain the repository's full service dependency set and had a corrupt pre-existing NLTK wordnet.zip. The test module does not use those services or corpora, so the run stubbed only common.settings engine flags, json_repair, and the global conftest's NLTK resource lookup; the production module and aggregation tests themselves ran unchanged.

Duplicate-work check

Checked all currently open PRs (including changed file paths) and found none touching rag/utils/table_es_metadata.py or its aggregation test. The earlier #15780 review is historical context, not active competing work.

Disclosure

AI-assisted (Codex): the candidate came from an AI-assisted review queue. I independently reproduced the order-dependent data loss against the real module, checked the historical review and all open PR file paths, and ran the regression plus full existing test file before submitting.

When field_map is missing or stale, table metadata aggregation resolves each column from only the first dictionary chunk. If that row is sparse, a valid field in later chunks is never discovered and the document metadata is silently omitted.

Retry the existing field-key resolver on later chunks only when the initial lookup found no key, then cache the first successful result. Add a regression test with an empty first row and a populated second row.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: chuenchen309 <[email protected]>
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 15, 2026
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

aggregate_table_doc_metadata now retries missing ES field-key resolution per chunk, allowing metadata extraction from later populated chunks. A regression test covers auto-mode aggregation when the first chunk is sparse.

Changes

Metadata aggregation

Layer / File(s) Summary
Chunk-aware key resolution and regression coverage
rag/utils/table_es_metadata.py, test/unit_test/rag/svr/test_table_metadata_aggregation.py
Missing ES typed keys are re-resolved against each chunk, and auto-mode aggregation is tested with metadata appearing only in a later chunk.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

I’m a rabbit hopping through each chunk,
Finding notes where fields once sunk.
Sparse first pages no longer stall,
Later keys now answer the call.
Carrots and metadata—harvested all!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the sparse-chunk Elasticsearch field discovery fix.
Description check ✅ Passed The description provides clear problem context, fix details, testing, and extra validation, covering the intent despite using a different heading than the template.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@yingfeng
yingfeng requested a review from yuzhichang July 15, 2026 15:49
@yingfeng yingfeng added the ci Continue Integration label Jul 15, 2026
@yingfeng
yingfeng marked this pull request as draft July 15, 2026 15:49
@yingfeng
yingfeng marked this pull request as ready for review July 15, 2026 15:49

@yuzhichang yuzhichang left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jul 16, 2026
@yingfeng
yingfeng marked this pull request as draft July 16, 2026 03:08
@yingfeng
yingfeng marked this pull request as ready for review July 16, 2026 03:08
@chuenchen309

Copy link
Copy Markdown
Contributor Author

Thanks for the review and approval! Heads-up on the red ragflow_tests_elasticsearch check: the only failure is a teardown ReadTimeout (host.docker.internal:10923, read timeout=30s) on test_documents_parse_chunks_and_scaled_bulk_contract — a heavy doc-parsing integration test unrelated to this change. The run reports 498 passed / 1 error, and all metadata tests (which this PR touches) pass. Looks like a flaky infra timeout during teardown; a CI re-run should clear it. Happy to rebase if you'd prefer a fresh run.

@codecov

codecov Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (5cf95d2) to head (63fbbaf).
⚠️ Report is 44 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16949      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang
yuzhichang merged commit 99a77a5 into infiniflow:main Jul 16, 2026
28 of 35 checks passed
yuzhichang pushed a commit that referenced this pull request Jul 16, 2026
…tate across dict entries (#16956)

## What

`meta_filter()`'s in-memory `filter_out()` helper has two related bugs
in how it coerces `input`/`value` for comparison operators (`=`, `≠`,
`>`, `<`, `≥`, `≤`):

**1. Asymmetric commit on partial `literal_eval` failure.** The original
code:
```python
input = ast.literal_eval(input)
value = ast.literal_eval(value)
```
runs as two separate statements inside one `try`. If the first succeeds
and the second raises, the first assignment already committed — `input`
and `value` end up as different types, and the subsequent `.lower()`
case-folding silently no-ops for whichever side didn't get lowered as a
string. Concretely: metadata cell `"None"` is a valid Python literal
(`ast.literal_eval("None")` → `None`), but a query value `"none"`
(lowercase) is not — so `status = "none"` never matches a cell whose
value is `"None"`, even though the intended semantics are
case-insensitive.

**2. `value` mutated in place, reused across dict entries.**
`filter_out(v2docs, operator, value)` loops over every `(input, docids)`
pair in `v2docs` and coerces `value` inside the loop body without
resetting it — so once one entry's `literal_eval(value)` succeeds and
rebinds `value` to a non-string, every later entry in the same call
compares against that already-coerced leftover instead of the original
filter value.

## Fix

- Commit both `literal_eval` results together via tuple assignment
(`input, value = ast.literal_eval(input), ast.literal_eval(value)`), so
a failure on either side leaves both operands in their pre-coercion form
instead of a mismatched mix.
- Save the original `value` before the loop and reset it at the top of
each iteration, so per-entry coercion never leaks into the next entry.

## Testing

Added 3 tests to
`test/unit_test/common/test_metadata_filter_operators.py` covering both
symptoms (case-insensitive match against a metadata cell that's a Python
keyword literal, both `=` and `≠`; a numeric `>` comparison unaffected
by an earlier dict entry having coerced the query value). Confirmed red
on `common/metadata_utils.py` at HEAD (`git stash` the fix, tests fail
with the exact symptom described above), green after. Full existing
`test_metadata_filter_operators.py` suite (22/22, including the 3 new
tests) passes. `ruff check` and `ruff format --check` clean on both
touched files.

Sandbox note: this environment has no network access to install
`pytest`/`pytest-asyncio`, so tests were run by importing the test
module and invoking each `test_*` function directly (same approach as
prior PRs from this account against this repo, e.g. #16949).
`test_apply_semi_auto_meta_data_filter.py` (the other file exercising
`meta_filter` indirectly through `apply_meta_data_filter`) needs
`pytest-asyncio` + heavier mocking and wasn't run, but it exercises
`apply_meta_data_filter`'s async/LLM-filter-generation path, not
`filter_out`'s coercion logic touched here.

Cross-referenced open PR #16833 (also touches
`common/metadata_utils.py`) — confirmed via `gh pr diff` it only touches
`convert_conditions`/operator-alias normalization and
`apply_meta_data_filter`'s `None`-vs-`["-999"]` sentinel logic, not
`filter_out`'s comparison-coercion code path. No overlap.

---
This PR was drafted with AI assistance (Claude); I reviewed the change,
independently reproduced both symptoms, and take responsibility for it.

Signed-off-by: chuenchen309 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration lgtm This PR has been approved by a maintainer size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants