Skip to content

Fix: handle null document_metadata in kb_prompt to prevent citation crash (#14651) - #14666

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
Lobster-0429:fix/14651-kb-prompt-null-document-metadata
May 8, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
Lobster-0429:fix/14651-kb-prompt-null-document-metadata

Conversation

@Lobster-0429

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Fixes #14651.

kb_prompt() in rag/prompts/generator.py crashes with AttributeError: 'NoneType' object has no attribute 'items' during agent citation generation when a retrieved chunk carries document_metadata: null.

Root cause. The crash happens at rag/prompts/generator.py:132-133:

meta = ck.get("document_metadata", {})
for k, v in meta.items():

dict.get(key, default) only returns the default when the key is missing. When the key is present with an explicit None value, .get() returns None, and .items() crashes.

How the chunk gets None. It's a round-trip inside RAGFlow itself, not bad input from retrieval:

  1. The agent stores retrieved chunks via agent/canvas.py:814, which routes them through chunks_format().
  2. rag/prompts/generator.py:61 canonicalizes the field with chunk.get("document_metadata") (no default), so chunks without metadata become {"document_metadata": None, ...}.
  3. agent/component/agent_with_tools.py:314 feeds those canonicalized chunks back into kb_prompt() for citation generation, and .get("document_metadata", {}) no longer protects us.

Fix. One-line change at rag/prompts/generator.py:132: use ck.get("document_metadata") or {} so an explicit None is also coerced to {}.

The line-61 None is intentionally part of the API/UI contract — the frontend handles it via optional chaining (web/src/components/markdown-content/index.tsx:184, web/src/pages/next-search/search-view.tsx:217) — so the fix belongs at the consumer, not the producer.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels May 8, 2026
@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3c6b176b-c40e-495d-97d7-18911e9c1bef

📥 Commits

Reviewing files that changed from the base of the PR and between d988cbe and 8eb8503.

📒 Files selected for processing (1)
  • test/unit_test/rag/prompts/test_kb_prompt_metadata.py

📝 Walkthrough

Walkthrough

The PR fixes a null-safety bug in prompt knowledge generation by treating document_metadata: null as an empty dict (ck.get("document_metadata") or {}), and adds pytest coverage for None, missing, and populated metadata cases.

Changes

Metadata Null-Safety Fix

Layer / File(s) Summary
Metadata Defaulting Logic
rag/prompts/generator.py
Changed ck.get("document_metadata", {}) to ck.get("document_metadata") or {} to safely handle chunks where document_metadata is explicitly null. Prevents AttributeError when calling .items() on a None value.
Tests: imports & fixtures
test/unit_test/rag/prompts/test_kb_prompt_metadata.py
Add pytest imports and reference to kb_prompt.
Tests: class
test/unit_test/rag/prompts/test_kb_prompt_metadata.py
Add TestKbPromptDocumentMetadata test class documenting regression scenarios.
Tests: None metadata case
test/unit_test/rag/prompts/test_kb_prompt_metadata.py
Verify document_metadata=None does not raise and rendered output contains chunk content and docnm_kwd.
Tests: missing metadata key
test/unit_test/rag/prompts/test_kb_prompt_metadata.py
Verify missing document_metadata key does not raise.
Tests: populated metadata rendering
test/unit_test/rag/prompts/test_kb_prompt_metadata.py
Verify provided metadata dict entries (e.g., author, year) appear in rendered output.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

A chunk came with metadata void,
The prompt formatter quite annoyed,
But now with or {} in place,
Null values won't cause disgrace,
Citations flow without void noise! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the fix: handling null document_metadata in kb_prompt to prevent a citation crash, with the issue reference.
Description check ✅ Passed The description comprehensively covers the problem statement, root cause analysis, the fix rationale, and includes proper type of change checkbox selection.
Linked Issues check ✅ Passed The code changes directly address all objectives from #14651: the one-line fix coerces null metadata to empty dict, preventing the AttributeError crash during citation generation, and comprehensive unit tests validate the fix against null, missing, and populated metadata cases.
Out of Scope Changes check ✅ Passed Both file changes are directly in scope: the one-line fix in generator.py addresses the root cause, and the new test module provides regression coverage for the exact bug described in #14651.

✏️ 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.

❤️ Share

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

Adds unit tests covering the three input shapes for `document_metadata` on
chunks passed to `kb_prompt`: explicit null, missing key, and populated dict.
The null-case test was confirmed to fail without the prior fix, raising the
exact `AttributeError: 'NoneType' object has no attribute 'items'` reported
in the issue.
@wangq8 wangq8 added the ci Continue Integration label May 8, 2026
@wangq8
wangq8 marked this pull request as draft May 8, 2026 06:39
@wangq8
wangq8 marked this pull request as ready for review May 8, 2026 06:39
@wangq8
wangq8 self-requested a review May 8, 2026 06:41
@wangq8
wangq8 marked this pull request as draft May 8, 2026 06:43
@wangq8
wangq8 marked this pull request as ready for review May 8, 2026 06:43
@codecov

codecov Bot commented May 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (a82ae4a) to head (8eb8503).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14666   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 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.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Thanks for your time, @wangq8 ,
All tests are successfully passed.

@wangq8
wangq8 merged commit a32ebf3 into infiniflow:main May 8, 2026
2 of 3 checks passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
…rash (infiniflow#14651) (infiniflow#14666)

### What problem does this PR solve?

Fixes infiniflow#14651.

`kb_prompt()` in `rag/prompts/generator.py` crashes with
`AttributeError: 'NoneType' object has no attribute 'items'` during
agent citation generation when a retrieved chunk carries
`document_metadata: null`.

**Root cause.** The crash happens at `rag/prompts/generator.py:132-133`:

```python
meta = ck.get("document_metadata", {})
for k, v in meta.items():
```

`dict.get(key, default)` only returns the default when the key is
*missing*. When the key is present with an explicit `None` value,
`.get()` returns `None`, and `.items()` crashes.

**How the chunk gets `None`.** It's a round-trip inside RAGFlow itself,
not bad input from retrieval:

1. The agent stores retrieved chunks via `agent/canvas.py:814`, which
routes them through `chunks_format()`.
2. `rag/prompts/generator.py:61` canonicalizes the field with
`chunk.get("document_metadata")` (no default), so chunks without
metadata become `{"document_metadata": None, ...}`.
3. `agent/component/agent_with_tools.py:314` feeds those canonicalized
chunks back into `kb_prompt()` for citation generation, and
`.get("document_metadata", {})` no longer protects us.

**Fix.** One-line change at `rag/prompts/generator.py:132`: use
`ck.get("document_metadata") or {}` so an explicit `None` is also
coerced to `{}`.

The line-61 `None` is intentionally part of the API/UI contract — the
frontend handles it via optional chaining
(`web/src/components/markdown-content/index.tsx:184`,
`web/src/pages/next-search/search-view.tsx:217`) — so the fix belongs at
the consumer, not the producer.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
…rash (infiniflow#14651) (infiniflow#14666)

### What problem does this PR solve?

Fixes infiniflow#14651.

`kb_prompt()` in `rag/prompts/generator.py` crashes with
`AttributeError: 'NoneType' object has no attribute 'items'` during
agent citation generation when a retrieved chunk carries
`document_metadata: null`.

**Root cause.** The crash happens at `rag/prompts/generator.py:132-133`:

```python
meta = ck.get("document_metadata", {})
for k, v in meta.items():
```

`dict.get(key, default)` only returns the default when the key is
*missing*. When the key is present with an explicit `None` value,
`.get()` returns `None`, and `.items()` crashes.

**How the chunk gets `None`.** It's a round-trip inside RAGFlow itself,
not bad input from retrieval:

1. The agent stores retrieved chunks via `agent/canvas.py:814`, which
routes them through `chunks_format()`.
2. `rag/prompts/generator.py:61` canonicalizes the field with
`chunk.get("document_metadata")` (no default), so chunks without
metadata become `{"document_metadata": None, ...}`.
3. `agent/component/agent_with_tools.py:314` feeds those canonicalized
chunks back into `kb_prompt()` for citation generation, and
`.get("document_metadata", {})` no longer protects us.

**Fix.** One-line change at `rag/prompts/generator.py:132`: use
`ck.get("document_metadata") or {}` so an explicit `None` is also
coerced to `{}`.

The line-61 `None` is intentionally part of the API/UI contract — the
frontend handles it via optional chaining
(`web/src/components/markdown-content/index.tsx:184`,
`web/src/pages/next-search/search-view.tsx:217`) — so the fix belongs at
the consumer, not the producer.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
- [ ] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [ ] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):
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 size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Agent-with-tools citation generation crashes when retrieved chunk has document_metadata: null

2 participants