Repository navigation
fix: support auto mode in table parser document metadata aggregation - #15780
Conversation
### What problem does this PR solve? Table parser metadata aggregation previously only ran when table_column_mode was set to 'manual'. In auto mode (default), all columns default to 'both' role, meaning they should also be aggregated into document-level metadata for UI/chat filters. Additionally, the task snapshot could be stale - table_column_names are written to KB parser_config during chunk() but the task may have been created before that. This PR: - Renames aggregate_table_manual_doc_metadata to aggregate_table_doc_metadata - Supports both 'manual' and 'auto' table_column_mode (defaults to 'auto') - Reloads table_column_names from KB DB when missing from task snapshot - Removes the manual-only guard in task_executor and refactored post_processor - Updates all tests with new function name and adds auto mode test cases ### Type of change - [x] New Feature (non-breaking change which adds functionality) - [ ] Bug Fix (non-breaking change which fixes an issue) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe):
📝 WalkthroughWalkthroughThis PR refactors the task executor and table metadata aggregation to unify manual/auto processing modes, switches control flow for dry-run vs refactored execution based on ChangesTable metadata aggregation unification
Task executor control flow and recording context
RAPTOR and document chunking optimizations
Chunk insertion, embedding, and dataflow
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
rag/utils/table_es_metadata.py (1)
216-249:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon’t bind ES key resolution to only the first chunk.
When
field_mapis missing, resolving keys from justsample_ckcan leavetk=Noneeven if later chunks contain valid<col>_raw/<col>_tksfields, causing false-empty aggregation.Suggested fix
else: for col in meta_cols: tk, _src = es_col_keys.get(col, (None, "none")) if not tk: - if i == 0: - logging.debug(f"[TABLE_META_DEBUG] no resolved ES key for column '{col}'") - continue + probed = _probe_es_typed_key_for_column(col, ck) + if probed: + tk = probed + es_col_keys[col] = (tk, "probe_runtime") + else: + if i == 0: + logging.debug(f"[TABLE_META_DEBUG] no resolved ES key for column '{col}'") + continue🤖 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/utils/table_es_metadata.py` around lines 216 - 249, The ES key lookup is only done once using sample_ck which can leave es_col_keys[col] = (None, ...) even though later chunks contain valid fields; modify the loop that iterates chunks in the function (uses variables chunks, sample_ck, es_col_keys, meta_cols and calls _value_to_meta_string) so that when tk is None for a given col you attempt to resolve the ES key again for the current chunk by calling _resolve_es_chunk_field_key(col, fm, ck) (or similar) and update es_col_keys[col] before skipping; this ensures tk is discovered from later chunks and prevents false-empty aggregation.rag/svr/task_executor_refactor/post_processor.py (1)
72-85:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPrevent destructive metadata updates when
table_column_modeis unsupported.If mode is invalid,
aggregate_table_doc_metadatareturns{}, but this method still strips table keys and persists the merged metadata. That can unintentionally wipe existing table metadata.Suggested fix
eff_pc = merge_table_parser_config_from_kb(ctx.raw_task) - logging.debug(f"[TABLE_META_DEBUG] table post-index: table_column_mode={eff_pc.get('table_column_mode')!r}") + mode = str(eff_pc.get("table_column_mode") or "auto").lower() + logging.debug(f"[TABLE_META_DEBUG] table post-index: table_column_mode={mode!r}") + if mode not in ("manual", "auto"): + logging.warning( + "[TABLE_META_DEBUG] skip table metadata update due to unsupported table_column_mode=%r", + mode, + ) + return🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/svr/task_executor_refactor/post_processor.py` around lines 72 - 85, If aggregate_table_doc_metadata returns an empty dict because table_column_mode is unsupported, avoid stripping and persisting metadata; modify the post-processing flow in merge_table_parser_config_from_kb / aggregate_table_doc_metadata usage so you first inspect agg and eff_pc.get('table_column_mode') and only proceed with table_parser_strip_doc_metadata_keys, retrieving existing metadata (DocMetadataService.get_document_metadata) and calling update_metadata_to when agg is non-empty (or when mode is explicitly supported). In practice, add a guard after computing agg: if not agg and eff_pc.get('table_column_mode') is falsy/unsupported, skip the preserved/merged calculation and the update call (do not call table_parser_strip_doc_metadata_keys or update_metadata_to).test/unit_test/rag/svr/test_table_metadata_aggregation.py (1)
53-265:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd pytest priority markers (
p1/p2/p3) for these tests.As per coding guidelines: “
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python testing”.🤖 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 `@test/unit_test/rag/svr/test_table_metadata_aggregation.py` around lines 53 - 265, Add pytest priority markers to the tests by importing pytest and decorating the relevant test functions or classes with `@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3 as required; specifically, add markers to the TestAggregateTableManualDocMetadata test methods (e.g., test_aggregate_manual_mode_happy_path, test_aggregate_auto_mode_returns_data, etc.) and to TestMergeTableParserConfigFromKbExtra.test_merge_preserves_parser_config_when_parser_not_table, or decorate the whole classes (TestAggregateTableManualDocMetadata and TestMergeTableParserConfigFromKbExtra) if the same priority applies to all contained tests, ensuring an import pytest is present at the top of the file so the decorators resolve.Source: Coding guidelines
test/unit_test/rag/svr/task_executor_refactor/test_post_processor.py (2)
35-181:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAdd pytest priority markers to this test module.
These tests use
pytestbut none are marked with@pytest.mark.p1/@p2/@p3as required.As per coding guidelines: “
test/**/*.py: Use pytest with priority markers (p1/p2/p3) for Python testing”.🤖 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 `@test/unit_test/rag/svr/task_executor_refactor/test_post_processor.py` around lines 35 - 181, The test module lacks required pytest priority markers; add the appropriate `@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3 decorators to each test coroutine so they comply with the project's priority convention — apply them to the test methods inside classes TestPostProcessorProcessTableParserMetadata (test_skips_non_table_parser, test_skips_when_not_manual_column_mode, test_processes_table_parser_manual_mode, test_processes_table_parser_with_write_interceptor) and TestPostProcessorInsertTocChunk (test_returns_false_for_none_chunk, test_checks_cancellation, test_inserts_toc_chunk_successfully, test_handles_insert_failure), choosing the correct priority per test importance. Ensure each async test function retains its existing pytest.mark.asyncio decorator and simply has the priority marker added above the function.Source: Coding guidelines
50-62:⚠️ Potential issue | 🟠 Major | ⚡ Quick winUpdate the obsolete “skip non-manual mode” test contract.
The production path now processes both
manualandauto, so this test is validating removed behavior and can also hit real metadata service calls without patching.🤖 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 `@test/unit_test/rag/svr/task_executor_refactor/test_post_processor.py` around lines 50 - 62, The test test_skips_when_not_manual_column_mode is outdated because PostProcessor.process_table_parser_metadata now processes both "manual" and "auto"; update the test to reflect the new contract by removing the "skip" expectation and instead assert that merge_table_parser_config_from_kb is called and that process_table_parser_metadata continues without error for {"table_column_mode":"auto"} (or rename the test to e.g. test_processes_auto_column_mode). Ensure you patch/mock rag.svr.task_executor_refactor.post_processor.merge_table_parser_config_from_kb to avoid hitting real metadata services and keep asserting mock_merge.assert_called_once() and any subsequent side-effect expectations from PostProcessor.process_table_parser_metadata.
🧹 Nitpick comments (1)
test/unit_test/rag/svr/test_table_metadata_aggregation.py (1)
208-235: ⚡ Quick winAdd a dedicated test for stale-snapshot
table_column_namesreload.This file covers
field_mapreload, but the PR also introduces DB reload for missingtable_column_names; please add an explicit case to lock that behavior.Based on learnings: “Applies to tests/**/*.py : Add/adjust tests for behavior changes”.
🤖 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 `@test/unit_test/rag/svr/test_table_metadata_aggregation.py` around lines 208 - 235, Add a new unit test (e.g., test_aggregate_kb_reload_table_column_names) that exercises aggregate_table_doc_metadata when the task lacks table_column_names so it triggers the DB reload path: monkeypatch rag.utils.table_es_metadata._knowledgebase_service_cls to a MockKBS whose get_by_id returns (True, kb) where kb.parser_config includes the expected "table_column_names" (and optionally a field_map), construct a task where parser_config does not contain table_column_names but kb_parser_config indicates manual mode, provide chunks with the raw column key used in the KB parser_config, call aggregate_table_doc_metadata(chunks, task) and assert the returned metadata uses the reloaded table_column_names; reference aggregate_table_doc_metadata and _knowledgebase_service_cls to locate the code to exercise.Source: Learnings
🤖 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.
Outside diff comments:
In `@rag/svr/task_executor_refactor/post_processor.py`:
- Around line 72-85: If aggregate_table_doc_metadata returns an empty dict
because table_column_mode is unsupported, avoid stripping and persisting
metadata; modify the post-processing flow in merge_table_parser_config_from_kb /
aggregate_table_doc_metadata usage so you first inspect agg and
eff_pc.get('table_column_mode') and only proceed with
table_parser_strip_doc_metadata_keys, retrieving existing metadata
(DocMetadataService.get_document_metadata) and calling update_metadata_to when
agg is non-empty (or when mode is explicitly supported). In practice, add a
guard after computing agg: if not agg and eff_pc.get('table_column_mode') is
falsy/unsupported, skip the preserved/merged calculation and the update call (do
not call table_parser_strip_doc_metadata_keys or update_metadata_to).
In `@rag/utils/table_es_metadata.py`:
- Around line 216-249: The ES key lookup is only done once using sample_ck which
can leave es_col_keys[col] = (None, ...) even though later chunks contain valid
fields; modify the loop that iterates chunks in the function (uses variables
chunks, sample_ck, es_col_keys, meta_cols and calls _value_to_meta_string) so
that when tk is None for a given col you attempt to resolve the ES key again for
the current chunk by calling _resolve_es_chunk_field_key(col, fm, ck) (or
similar) and update es_col_keys[col] before skipping; this ensures tk is
discovered from later chunks and prevents false-empty aggregation.
In `@test/unit_test/rag/svr/task_executor_refactor/test_post_processor.py`:
- Around line 35-181: The test module lacks required pytest priority markers;
add the appropriate `@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3 decorators
to each test coroutine so they comply with the project's priority convention —
apply them to the test methods inside classes
TestPostProcessorProcessTableParserMetadata (test_skips_non_table_parser,
test_skips_when_not_manual_column_mode, test_processes_table_parser_manual_mode,
test_processes_table_parser_with_write_interceptor) and
TestPostProcessorInsertTocChunk (test_returns_false_for_none_chunk,
test_checks_cancellation, test_inserts_toc_chunk_successfully,
test_handles_insert_failure), choosing the correct priority per test importance.
Ensure each async test function retains its existing pytest.mark.asyncio
decorator and simply has the priority marker added above the function.
- Around line 50-62: The test test_skips_when_not_manual_column_mode is outdated
because PostProcessor.process_table_parser_metadata now processes both "manual"
and "auto"; update the test to reflect the new contract by removing the "skip"
expectation and instead assert that merge_table_parser_config_from_kb is called
and that process_table_parser_metadata continues without error for
{"table_column_mode":"auto"} (or rename the test to e.g.
test_processes_auto_column_mode). Ensure you patch/mock
rag.svr.task_executor_refactor.post_processor.merge_table_parser_config_from_kb
to avoid hitting real metadata services and keep asserting
mock_merge.assert_called_once() and any subsequent side-effect expectations from
PostProcessor.process_table_parser_metadata.
In `@test/unit_test/rag/svr/test_table_metadata_aggregation.py`:
- Around line 53-265: Add pytest priority markers to the tests by importing
pytest and decorating the relevant test functions or classes with
`@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3 as required; specifically, add
markers to the TestAggregateTableManualDocMetadata test methods (e.g.,
test_aggregate_manual_mode_happy_path, test_aggregate_auto_mode_returns_data,
etc.) and to
TestMergeTableParserConfigFromKbExtra.test_merge_preserves_parser_config_when_parser_not_table,
or decorate the whole classes (TestAggregateTableManualDocMetadata and
TestMergeTableParserConfigFromKbExtra) if the same priority applies to all
contained tests, ensuring an import pytest is present at the top of the file so
the decorators resolve.
---
Nitpick comments:
In `@test/unit_test/rag/svr/test_table_metadata_aggregation.py`:
- Around line 208-235: Add a new unit test (e.g.,
test_aggregate_kb_reload_table_column_names) that exercises
aggregate_table_doc_metadata when the task lacks table_column_names so it
triggers the DB reload path: monkeypatch
rag.utils.table_es_metadata._knowledgebase_service_cls to a MockKBS whose
get_by_id returns (True, kb) where kb.parser_config includes the expected
"table_column_names" (and optionally a field_map), construct a task where
parser_config does not contain table_column_names but kb_parser_config indicates
manual mode, provide chunks with the raw column key used in the KB
parser_config, call aggregate_table_doc_metadata(chunks, task) and assert the
returned metadata uses the reloaded table_column_names; reference
aggregate_table_doc_metadata and _knowledgebase_service_cls to locate the code
to exercise.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d28e3b7c-c0e9-41be-86ee-2bb55e0471b1
📒 Files selected for processing (5)
rag/svr/task_executor.pyrag/svr/task_executor_refactor/post_processor.pyrag/utils/table_es_metadata.pytest/unit_test/rag/svr/task_executor_refactor/test_post_processor.pytest/unit_test/rag/svr/test_table_metadata_aggregation.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15780 +/- ##
=======================================
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:
|
### 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:
```python
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
- [x] 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.
Signed-off-by: chuenchen309 <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
What problem does this PR solve?
Table parser metadata aggregation previously only ran when
table_column_modewas set tomanual. In auto mode (default), all columns default to"both"role, meaning they should also be aggregated into document-level metadata for UI/chat filters. Additionally, the task snapshot could be stale —table_column_namesare written to KBparser_configduringchunk()but the task may have been created before that.Changes:
aggregate_table_manual_doc_metadata→aggregate_table_doc_metadata"manual"and"auto"table_column_mode(defaults to"auto")table_column_namesfrom KB DB when missing from task snapshottask_executorand refactoredpost_processorType of change