Repository navigation
feat: Auto-adjust chunk recall weights based on user feedback - #12689
Conversation
When users upvote or downvote responses, the system now automatically adjusts the pagerank_fea field of referenced chunks to improve future retrieval quality. - Add ChunkFeedbackService for weight management - Integrate with thumbup endpoint - Add unit tests - Fix: Handle chunks_format() field transformations (id/dataset_id) Closes #12670
|
Appreciations! |
- Disable feature by default (CHUNK_FEEDBACK_ENABLED env var) - Reduce weight increments from 1 to 0.1 to prevent outsized impact - Add test for disabled feature flag - Update docstrings to document the safeguards This addresses concerns about pagerank sensitivity and sparse feedback data.
|
@KevinHuSh Thanks for your feedback! You raise valid concerns about pagerank sensitivity. I've added safeguards to address this:
This way, deployments with sparse feedback won't see unintended side effects, while those with dense user activity can opt in and benefit from the learning signal. Happy to adjust the increment further or add additional safeguards (like requiring N votes before applying, or time-based decay) if you think it's needed. |
|
@ZhenhangTung could you please let your members review the PR? |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #12689 +/- ##
==========================================
- Coverage 98.11% 96.52% -1.60%
==========================================
Files 10 10
Lines 690 690
Branches 108 108
==========================================
- Hits 677 666 -11
- Misses 4 8 +4
- Partials 9 16 +7 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Thanks, please fix the CI error: |
|
@yingfeng please review the changes. |
qinling0210
left a comment
There was a problem hiding this comment.
CI passed, but web test in CI only covers test in test_api_app.
Your new test in test_web_api/test_chunk_feedback is not ran.
You can either test test_web_api/test_chunk_feedback locally
or add test/testcases/test_chunk_feedback to tests.yml temporarily to make ci covers your new test.
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughIntroduces a ChunkFeedbackService that converts thumb feedback into per-chunk pagerank adjustments, integrates feedback propagation into the chat feedback endpoint, adds atomic pagerank adjust methods across document-store connectors, extends tests for chunk-feedback, and updates CI to run the new test suite. (49 words) Changes
Sequence DiagramsequenceDiagram
participant Client
participant ChatAPI as Chat API
participant CFS as ChunkFeedbackService
participant DocStore as DocumentStore
Client->>ChatAPI: PATCH /message/feedback (thumbup)
ChatAPI->>ChatAPI: validate thumbup (bool)\ndetect assistant message & message_index
alt thumb value changed
ChatAPI->>CFS: apply_feedback(reference, is_positive)
CFS->>CFS: extract chunks\ncompute signed budget\nallocate deltas (uniform/relevance)
loop per chunk
CFS->>DocStore: adjust_chunk_pagerank_fea(chunk_id, delta, min,max[, row_id])
DocStore-->>CFS: success / failure
end
CFS-->>ChatAPI: return success_count, fail_count, chunk_ids
end
ChatAPI->>ChatAPI: persist conversation dict
ChatAPI-->>Client: return updated conversation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 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. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/utils/es_conn.py (1)
333-352:⚠️ Potential issue | 🟠 MajorKeep dict-based
removeupdates working in the single-doc branch.This path now only treats
removeas special when it's a string. Existing callers such asapi/db/services/document_service.pyalso send{"remove": {"source_id": ...}}; here that dict stays indoc_partand gets sent as a normal document update instead of removing the value from the array, which breaks graph cleanup.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/utils/es_conn.py` around lines 333 - 352, The branch currently only treats a string remove specially, so dict-based removes (doc_part.get("remove") being a dict) are left in doc_part and sent as a normal update; fix by detecting when doc_part.get("remove") is a dict, pop it (like remove_field) and for each key,value in that dict call self.es.update(index=index_name, id=chunk_id, script=...) to remove the matching element(s) from the document (use a Painless script that matches the value and removes array entries), then proceed to update doc_part (without the removed key) and return True as before; keep the existing string-handling path and reuse symbols remove_field, doc_part, self.es.update, index_name, chunk_id, condition and logger.exception for locating and logging the operations.
🧹 Nitpick comments (2)
test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py (1)
354-362: Turn the stub into a spy and assert the new route behavior.This only fixes imports. It still doesn't verify that
update_message_feedback()callsChunkFeedbackService.apply_feedback()on the first thumb change, or skips it on idempotent repeats.Based on learnings: "Applies to tests/**/*.py : Add/adjust tests for behavior changes"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py` around lines 354 - 362, The test currently injects a static stub for api.db.services.chunk_feedback_service but doesn't assert call behavior; replace the stub with a spy that records calls (e.g., add an attribute or list on _StubChunkFeedbackService to capture args and increment a call_count) and monkeypatch that into sys.modules as before; then exercise the route via the same client calls used in the test to trigger update_message_feedback() and add assertions that ChunkFeedbackService.apply_feedback was called exactly once on the first thumb change (inspect spy.call_count and last args) and that it was not called again for an idempotent repeat (call_count unchanged), ensuring you reference ChunkFeedbackService.apply_feedback and the update_message_feedback route in your assertions.test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py (1)
87-89: Add pytest priority markers to categorize test levels.As per coding guidelines, Python tests should use pytest with priority markers (p1/p2/p3). Consider adding markers to indicate test criticality, e.g.,
@pytest.mark.p1for core functionality tests.Example marker usage
`@pytest.mark.p1` class TestFeedbackRowsFromReference: """Chunk id + kb resolution via _feedback_rows_from_reference (single pass).""" ... `@pytest.mark.p1` class TestUpdateChunkWeight: """Tests for update_chunk_weight method.""" ... `@pytest.mark.p1` class TestApplyFeedback: """Tests for apply_feedback method.""" ...🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py` around lines 87 - 89, Add pytest priority markers to categorize tests by criticality: import pytest if not already present and add `@pytest.mark.p1` above the TestFeedbackRowsFromReference class declaration; likewise add `@pytest.mark.p1` to related test classes like TestUpdateChunkWeight and TestApplyFeedback in this file to mark them as core tests. Locate class definitions (e.g., TestFeedbackRowsFromReference, TestUpdateChunkWeight, TestApplyFeedback) and place the decorator immediately above each class line, ensuring the pytest import exists at the top of the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@rag/utils/opensearch_conn.py`:
- Around line 356-368: The code only treats remove as a string so dict-typed
remove payloads are left in doc_part and sent as fields; change the logic around
doc_part and remove handling (variables: doc_part, remove_field, self.os.update,
indexName, chunkId) to pop "remove" regardless of type, then handle both cases:
if remove is a string call update with a simple script that removes that field,
and if remove is a dict build a script + params that iterates the dict entries
(for each key/value emit a guarded remove like "if (ctx._source['key'] ==
params.key_val) { ctx._source.remove('key'); }" using params) and call
self.os.update with that script; ensure doc_part no longer contains the remove
key before sending the {"doc": doc_part} update so existing callers with dict
remove work as before.
- Around line 471-479: The retry loop in OSConnection.adjust_chunk_pagerank_fea
exits on the first exception (it calls logger.exception then break) which
differs from update() and search() that retry on transient network/timeouts;
change the error handling in adjust_chunk_pagerank_fea so it follows the same
pattern as update()/search(): log the exception with logger.exception, detect
transient errors (e.g., timeout/connection/transport-related exceptions) and
continue the retry loop instead of breaking, only stop and return False after
reaching the retry limit or for non-transient errors; reference
OSConnection.adjust_chunk_pagerank_fea and mirror the exception-handling/retry
logic used in update() and search().
---
Outside diff comments:
In `@rag/utils/es_conn.py`:
- Around line 333-352: The branch currently only treats a string remove
specially, so dict-based removes (doc_part.get("remove") being a dict) are left
in doc_part and sent as a normal update; fix by detecting when
doc_part.get("remove") is a dict, pop it (like remove_field) and for each
key,value in that dict call self.es.update(index=index_name, id=chunk_id,
script=...) to remove the matching element(s) from the document (use a Painless
script that matches the value and removes array entries), then proceed to update
doc_part (without the removed key) and return True as before; keep the existing
string-handling path and reuse symbols remove_field, doc_part, self.es.update,
index_name, chunk_id, condition and logger.exception for locating and logging
the operations.
---
Nitpick comments:
In
`@test/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.py`:
- Around line 354-362: The test currently injects a static stub for
api.db.services.chunk_feedback_service but doesn't assert call behavior; replace
the stub with a spy that records calls (e.g., add an attribute or list on
_StubChunkFeedbackService to capture args and increment a call_count) and
monkeypatch that into sys.modules as before; then exercise the route via the
same client calls used in the test to trigger update_message_feedback() and add
assertions that ChunkFeedbackService.apply_feedback was called exactly once on
the first thumb change (inspect spy.call_count and last args) and that it was
not called again for an idempotent repeat (call_count unchanged), ensuring you
reference ChunkFeedbackService.apply_feedback and the update_message_feedback
route in your assertions.
In
`@test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py`:
- Around line 87-89: Add pytest priority markers to categorize tests by
criticality: import pytest if not already present and add `@pytest.mark.p1` above
the TestFeedbackRowsFromReference class declaration; likewise add
`@pytest.mark.p1` to related test classes like TestUpdateChunkWeight and
TestApplyFeedback in this file to mark them as core tests. Locate class
definitions (e.g., TestFeedbackRowsFromReference, TestUpdateChunkWeight,
TestApplyFeedback) and place the decorator immediately above each class line,
ensuring the pytest import exists at the top of the file.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 710b3045-dbb2-451b-a356-cb5911812c22
📒 Files selected for processing (11)
.github/workflows/tests.ymlapi/apps/restful_apis/chat_api.pyapi/db/services/chunk_feedback_service.pyrag/prompts/generator.pyrag/utils/es_conn.pyrag/utils/infinity_conn.pyrag/utils/ob_conn.pyrag/utils/opensearch_conn.pytest/testcases/test_http_api/test_chat_assistant_management/test_chat_sdk_routes_unit.pytest/testcases/test_web_api/test_chunk_feedback/__init__.pytest/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py
…le-doc update; retry on transient errors - chat_api: when toggling thumbup↔thumbdown, undo the prior vote before applying the new one so pagerank moves to the correct state instead of just cancelling. - es_conn/opensearch_conn: always pop 'remove' from doc_part regardless of type; handle dict-typed remove in the single-doc update path (matching the existing multi-doc path logic). - es_conn/opensearch_conn: retry adjust_chunk_pagerank_fea on transient timeout/connection errors, matching other methods in the class. - Add TestThumbFlipFeedback tests.
|
@qinling0210 please check the changes |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (3)
test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py (1)
229-275: Coverrow_idforwarding on the ES/OpenSearch branches too.The new
row_idregression only proves the default Infinity path. A small parametrized case forelasticsearchandopensearchwould catch connector signature drift in the sharedupdate_chunk_weight()flow before it reaches production.Based on learnings, Applies to tests/**/*.py : Add/adjust tests for behavior changes
Also applies to: 448-465
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py` around lines 229 - 275, The Elasticsearch/OpenSearch tests don't assert that row_id is forwarded to the doc store; update the two tests test_update_weight_elasticsearch_uses_atomic_adjust and test_update_weight_opensearch_uses_atomic_adjust (and the similar block at 448-465) to pass a row_id to ChunkFeedbackService.update_chunk_weight and assert mock_doc_store.adjust_chunk_pagerank_fea was called with that row_id in its positional/keyword signature (alongside "chunk1", "idx-tenant1", "kb1", delta, MIN_PAGERANK_WEIGHT, MAX_PAGERANK_WEIGHT) so the connector signature includes row_id on those branches.rag/utils/es_conn.py (1)
442-450: Keep the adjust API compatible with genericrow_idforwarding.
ChunkFeedbackServicenow forwardsrow_idwhenever the reference chunk has one. Acceptingrow_id: int | None = Nonehere keeps the doc-store interface aligned with the Infinity implementation and avoids a brittle backend-specificTypeErrorif that shared path ever hits Elasticsearch.Suggested fix
def adjust_chunk_pagerank_fea( self, chunk_id: str, index_name: str, knowledgebase_id: str, delta: int, min_w: int = 0, max_w: int = 100, + row_id: int | None = None, ) -> bool: """Atomically adjust pagerank_fea on one chunk (painless script).""" + _ = row_id for _ in range(ATTEMPT_TIME):🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/utils/es_conn.py` around lines 442 - 450, The adjust_chunk_pagerank_fea signature must accept an optional generic row identifier to stay compatible with ChunkFeedbackService forwarding; update the method definition for adjust_chunk_pagerank_fea to include a parameter like row_id: int | None = None and ensure any internal calls or parameter forwarding in that function (and callers if necessary) pass row_id through unchanged so the doc-store interface remains aligned with the Infinity implementation and avoids backend-specific TypeError when row_id is present.rag/utils/opensearch_conn.py (1)
456-464: Keep the adjust API compatible with genericrow_idforwarding.The shared feedback service conditionally forwards
row_idwhen the reference carries it. Accepting an unusedrow_id: int | None = Nonehere keeps this backend aligned with Infinity and avoids surprising kwarg mismatches in the common call path.Suggested fix
def adjust_chunk_pagerank_fea( self, chunk_id: str, indexName: str, knowledgebaseId: str, delta: int, min_w: int = 0, max_w: int = 100, + row_id: int | None = None, ) -> bool: """Atomically adjust pagerank_fea on one chunk (painless script).""" + _ = row_id for _ in range(ATTEMPT_TIME):🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/utils/opensearch_conn.py` around lines 456 - 464, The adjust_chunk_pagerank_fea method currently lacks an optional row_id parameter which causes kwarg mismatches when callers forward row_id; update the method signature of adjust_chunk_pagerank_fea to accept row_id: int | None = None (or Optional[int] depending on project typing) and ensure it is simply accepted (unused) so the backend remains compatible with generic row_id forwarding; keep the parameter optional and do not change internal logic, only add the parameter to the signature for compatibility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@rag/utils/es_conn.py`:
- Around line 452-479: The update call in adjust_chunk_pagerank_fea is dropping
concurrent adjustments due to version conflicts; modify the self.es.update(...)
invocation to include Elasticsearch's retry_on_conflict parameter (e.g.,
retry_on_conflict=3) so the ES client will retry on version conflicts during
concurrent updates; keep the existing ATTEMPT_TIME loop and error handling but
add retry_on_conflict to the parameters passed to self.es.update alongside
index, id, script and params (referencing _PAGERANK_FEA_ADJUST_SCRIPT,
PAGERANK_FLD, delta/min_w/max_w) so conflicting updates are retried
automatically.
- Around line 351-362: The removal script built from remove_dict can throw if
the field is missing or the value isn't found; update the script generation in
the block that builds scripts/params for remove_dict so each per-field Painless
snippet guards with containsKey and null checks and only calls remove when
indexOf(...) >= 0 (e.g. check ctx._source.containsKey('<field>') &&
ctx._source.<field> != null and assign idx =
ctx._source.<field>.indexOf(params.p_<field>); if (idx >= 0)
ctx._source.<field>.remove(idx)). Keep using the same params map and call
self.es.update(index=index_name, id=chunk_id, script=...) as before, and after a
successful update invocation emit a log entry indicating which field(s) were
removed for chunk_id (use your existing logger). Ensure you reference
remove_dict, scripts, params, self.es.update, index_name, and chunk_id when
making the change.
In `@rag/utils/opensearch_conn.py`:
- Around line 367-378: The generated Painless script built in the remove_dict
handling (variables: remove_dict, scripts, params) must guard against missing
fields and failed index lookups; update the script snippets passed into
self.os.update (for indexName and chunkId) to first check
ctx._source.containsKey('<field>') && ctx._source['<field>'] != null, then
compute int i = ctx._source['<field>'].indexOf(params.p_<field>) and only call
remove(i) if i >= 0. Ensure you build the script using safe property access
(ctx._source['field'] form) and include these conditional checks for each kk
when creating scripts and params so updates never throw NullPointerException or
IndexOutOfBoundsException.
In
`@test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py`:
- Around line 29-31: The module currently defines _REPO_ROOT but lacks a pytest
priority marker; add a module-level pytestmark using pytest.mark.p2 (or the
correct p1/p2/p3 per the suite) so the test selection rules apply. Specifically,
declare pytestmark = pytest.mark.p2 near the top of the file (after the existing
import pytest) and ensure the symbol pytestmark is used at module scope so
pytest will pick up the priority for the entire file.
---
Nitpick comments:
In `@rag/utils/es_conn.py`:
- Around line 442-450: The adjust_chunk_pagerank_fea signature must accept an
optional generic row identifier to stay compatible with ChunkFeedbackService
forwarding; update the method definition for adjust_chunk_pagerank_fea to
include a parameter like row_id: int | None = None and ensure any internal calls
or parameter forwarding in that function (and callers if necessary) pass row_id
through unchanged so the doc-store interface remains aligned with the Infinity
implementation and avoids backend-specific TypeError when row_id is present.
In `@rag/utils/opensearch_conn.py`:
- Around line 456-464: The adjust_chunk_pagerank_fea method currently lacks an
optional row_id parameter which causes kwarg mismatches when callers forward
row_id; update the method signature of adjust_chunk_pagerank_fea to accept
row_id: int | None = None (or Optional[int] depending on project typing) and
ensure it is simply accepted (unused) so the backend remains compatible with
generic row_id forwarding; keep the parameter optional and do not change
internal logic, only add the parameter to the signature for compatibility.
In
`@test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py`:
- Around line 229-275: The Elasticsearch/OpenSearch tests don't assert that
row_id is forwarded to the doc store; update the two tests
test_update_weight_elasticsearch_uses_atomic_adjust and
test_update_weight_opensearch_uses_atomic_adjust (and the similar block at
448-465) to pass a row_id to ChunkFeedbackService.update_chunk_weight and assert
mock_doc_store.adjust_chunk_pagerank_fea was called with that row_id in its
positional/keyword signature (alongside "chunk1", "idx-tenant1", "kb1", delta,
MIN_PAGERANK_WEIGHT, MAX_PAGERANK_WEIGHT) so the connector signature includes
row_id on those branches.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 069b10dc-f4a9-472b-a6bc-13349d9525bd
📒 Files selected for processing (4)
api/apps/restful_apis/chat_api.pyrag/utils/es_conn.pyrag/utils/opensearch_conn.pytest/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/apps/restful_apis/chat_api.py
…ES/OS - es_conn/opensearch_conn: guard dict-based remove scripts with containsKey + null check + i >= 0 to prevent NullPointerException and IndexOutOfBoundsException in Painless. - es_conn/opensearch_conn: add retry_on_conflict=3 to adjust_chunk_pagerank_fea to handle version conflicts on concurrent updates. - es_conn/opensearch_conn: accept row_id: int | None = None in adjust_chunk_pagerank_fea signature to stay compatible with ChunkFeedbackService forwarding (prevents TypeError). - tests: add pytestmark = pytest.mark.p2 for test selection rules. - tests: add row_id forwarding coverage for ES and OpenSearch branches.
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
rag/utils/opensearch_conn.py (1)
460-502: Add a trace log for the new feedback-adjustment flow.This method only logs exceptions, so successful feedback writes are invisible when debugging ranking changes. A debug log with
indexName,chunk_id,delta, and the clamp bounds would make the new flow traceable.💡 Proposed trace logging
for _ in range(ATTEMPT_TIME): try: + logger.debug( + "OSConnection.adjust_chunk_pagerank_fea(index=%s, id=%s, delta=%s, min_w=%s, max_w=%s)", + indexName, + chunk_id, + delta, + min_w, + max_w, + ) self.os.update( index=indexName, id=chunk_id, retry_on_conflict=3, body={ @@ } }, ) + logger.debug( + "OSConnection.adjust_chunk_pagerank_fea(index=%s, id=%s) succeeded", + indexName, + chunk_id, + ) return TrueAs per coding guidelines,
**/*.py: Add logging for new flows`.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rag/utils/opensearch_conn.py` around lines 460 - 502, The adjust_chunk_pagerank_fea function currently only logs on exceptions so successful adjustments are not visible; add a debug/trace log right after a successful update in adjust_chunk_pagerank_fea that records indexName, chunk_id, delta, min_w and max_w (and optionally row_id) to make feedback adjustments traceable; use the existing logger and ensure the message is at debug/trace level and concise so it won’t clutter normal logs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@rag/utils/es_conn.py`:
- Around line 34-58: The script and service code cast pagerank/fedback weights
to int, which drops fractional updates like 0.1; update
_PAGERANK_FEA_ADJUST_SCRIPT to use double (or float) arithmetic instead of int:
parse stored value with ((Number)v).doubleValue() or
Double.parseDouble(v.toString()), make cur and nw doubles, use
params.delta/min_w/max_w as doubles, and remove integer-only checks (use nw ==
0.0 for deletion or better Math.abs(nw) < EPS if needed); likewise in
chunk_feedback_service.py replace all int() casts and integer conversions for
feedback weights with float/double equivalents (e.g., use float()/float parsing
or Decimal if desired) in the functions handling feedback (the blocks around the
former int casts at the cited ranges) so fractional increments like 0.1 are
preserved end-to-end.
- Around line 460-475: Add a debug log on the success path right after the
Elasticsearch update call in the feedback-adjustment flow so operators can trace
changes; specifically, in the method that calls self.es.update(...) (the block
using index=index_name, id=chunk_id, script with _PAGERANK_FEA_ADJUST_SCRIPT and
params including "delta", "min_w", "max_w", and PAGERANK_FLD), insert a
processLogger.debug (or the module logger) that logs the index_name, chunk_id,
delta, min_w, max_w and a short success message indicating the pagerank/weight
adjustment succeeded for that chunk.
- Around line 458-485: The retry loop in ESConnection.adjust_chunk_pagerank_fea
only logs transport/timeouts and retries using the same broken client; fix it by
invoking the existing ES reconnect/repair routine before retrying (e.g. call the
same helper used by search()/insert()/update() such as
self._repair_es_connection() or the client reinitialiser like
self._create_es_client()/self._init_es()) when
re.search(r"(timeout|connection)", str(e).lower()) is true, so the code replaces
the wedged self.es client before the next attempt and then continues the loop.
In `@rag/utils/opensearch_conn.py`:
- Around line 472-500: The loop is retrying a non-idempotent scripted increment
(cur + delta) on ambiguous network errors, which can double-apply if the server
succeeded but the client lost the response; change adjust_chunk_pagerank_fea so
it does not blindly retry on timeout/connection errors: either remove the
client-side retry loop around the call and rely on retry_on_conflict, or make
the update idempotent (e.g., use a script that sets an absolute value or records
an idempotency key / cumulative-applied-delta on the document) or perform a
post-write verification read after the update to confirm the change before
retrying; update references to ATTEMPT_TIME, PAGERANK_FEA_ADJUST_SCRIPT, delta,
and the method OSConnection.adjust_chunk_pagerank_fea accordingly.
- Around line 356-386: The current logic performs multiple self.os.update()
calls (using remove_field/remove_dict and then doc_part) causing non-atomic
partial updates; instead, build a single script combining removals and
assignments and call self.os.update(index=indexName, id=chunkId, body={"script":
{"source": full_script, "params": params}}) once. Concretely, gather
remove_field, remove_dict and doc_part into a single script: append a removal
statement for remove_field (ctx._source.remove('...')), for each remove_dict
entry add the containsKey/index/remove logic, and for each key in doc_part add
an assignment statement (ctx._source.key = params.p_key or ctx._source.key =
params.p_key if setting scalars or handling nested/array types as before);
populate a single params dict (with unique names like p_<key>) and execute one
update; return True if any of remove_field/remove_dict/doc_part existed.
Reference symbols: remove_field, remove_dict, doc_part, indexName, chunkId,
self.os.update.
- Around line 37-59: The Painless script and associated params are using integer
math so a per-vote 0.1 change is rounded to 0; update the
_PAGERANK_FEA_ADJUST_SCRIPT and the param declarations/usages so all math is
floating-point (use double/Double types) instead of int: treat cur as a double
(use ((Number)v).doubleValue() or Double.parseDouble for parsing), make nw a
double, accept params.delta/min_w/max_w as doubles, and adjust the zero-check to
consider double zero (or a tiny epsilon) before removing the field; change any
int(delta) casts to double conversions so the 0.1 step is applied.
---
Nitpick comments:
In `@rag/utils/opensearch_conn.py`:
- Around line 460-502: The adjust_chunk_pagerank_fea function currently only
logs on exceptions so successful adjustments are not visible; add a debug/trace
log right after a successful update in adjust_chunk_pagerank_fea that records
indexName, chunk_id, delta, min_w and max_w (and optionally row_id) to make
feedback adjustments traceable; use the existing logger and ensure the message
is at debug/trace level and concise so it won’t clutter normal logs.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 241f437a-f563-4fdb-811c-2177a162f935
📒 Files selected for processing (3)
rag/utils/es_conn.pyrag/utils/opensearch_conn.pytest/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
- test/testcases/test_web_api/test_chunk_feedback/test_chunk_feedback_service.py
…emove non-idempotent OS retry - es_conn/opensearch_conn: switch Painless script from int to double arithmetic so fractional deltas (e.g. 0.1) are not truncated to 0. Use doubleValue()/Double.parseDouble, double nw, and nw <= 0.0 guard. - es_conn/opensearch_conn: change delta/min_w/max_w params from int() to float() casts end-to-end. - chunk_feedback_service: use float(delta) and float weights throughout so fractional increments are preserved on all backends. - es_conn: call self._connect() before retry on ConnectionTimeout and connection errors, matching the pattern used by search/insert/update. - opensearch_conn: remove the non-idempotent client-side retry on ambiguous timeout/connection errors; retry_on_conflict=3 already handles version conflicts; blind retry of cur+delta can double-apply. - es_conn/opensearch_conn: add debug log on success path for traceability.
qinling0210
left a comment
There was a problem hiding this comment.
Looks good for me about using row_id
…flow#12689) ### What problem does this PR solve? Implements automatic adjustment of knowledge base chunk recall weights based on user feedback (upvotes/downvotes). When users upvote or downvote a response, the system locates the corresponding knowledge snippets and adjusts their recall weight to improve future retrieval quality. **Closes infiniflow#12670** **How it works:** 1. User upvotes/downvotes a response via `POST /thumbup` 2. System extracts chunk IDs from the conversation reference 3. For each referenced chunk: - Reads current `pagerank_fea` value from document store - Increments (+1) for upvote or decrements (-1) for downvote - Clamps weight to [0, 100] range - Updates chunk in ES/Infinity/OceanBase 4. Future retrievals score these chunks higher/lower based on accumulated feedback **Files changed:** - `api/db/services/chunk_feedback_service.py` - New service for updating chunk pagerank weights - `api/apps/conversation_app.py` - Integrated feedback service into thumbup endpoint - `test/testcases/test_web_api/test_chunk_feedback/` - Unit tests ### Type of change - [x] New Feature (non-breaking change which adds functionality) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Chat message feedback now updates per-chunk relevance weights (feature-flag gated), with configurable weighting and atomic updates across storage backends. * **Bug Fixes** * Stricter validation for message feedback inputs and more robust handling of feedback transitions. * **Tests** * Expanded test coverage for chunk-feedback behavior, weighting strategies, storage backends, and thumb-flip scenarios. * **Chores** * CI workflow extended to run the new chunk-feedback web API tests. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mkdev11 <[email protected]> Co-authored-by: mkdev11 <[email protected]>
…flow#12689) Implements automatic adjustment of knowledge base chunk recall weights based on user feedback (upvotes/downvotes). When users upvote or downvote a response, the system locates the corresponding knowledge snippets and adjusts their recall weight to improve future retrieval quality. **Closes infiniflow#12670** **How it works:** 1. User upvotes/downvotes a response via `POST /thumbup` 2. System extracts chunk IDs from the conversation reference 3. For each referenced chunk: - Reads current `pagerank_fea` value from document store - Increments (+1) for upvote or decrements (-1) for downvote - Clamps weight to [0, 100] range - Updates chunk in ES/Infinity/OceanBase 4. Future retrievals score these chunks higher/lower based on accumulated feedback **Files changed:** - `api/db/services/chunk_feedback_service.py` - New service for updating chunk pagerank weights - `api/apps/conversation_app.py` - Integrated feedback service into thumbup endpoint - `test/testcases/test_web_api/test_chunk_feedback/` - Unit tests - [x] New Feature (non-breaking change which adds functionality) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> * **New Features** * Chat message feedback now updates per-chunk relevance weights (feature-flag gated), with configurable weighting and atomic updates across storage backends. * **Bug Fixes** * Stricter validation for message feedback inputs and more robust handling of feedback transitions. * **Tests** * Expanded test coverage for chunk-feedback behavior, weighting strategies, storage backends, and thumb-flip scenarios. * **Chores** * CI workflow extended to run the new chunk-feedback web API tests. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mkdev11 <[email protected]> Co-authored-by: mkdev11 <[email protected]>
…flow#12689) ### What problem does this PR solve? Implements automatic adjustment of knowledge base chunk recall weights based on user feedback (upvotes/downvotes). When users upvote or downvote a response, the system locates the corresponding knowledge snippets and adjusts their recall weight to improve future retrieval quality. **Closes infiniflow#12670** **How it works:** 1. User upvotes/downvotes a response via `POST /thumbup` 2. System extracts chunk IDs from the conversation reference 3. For each referenced chunk: - Reads current `pagerank_fea` value from document store - Increments (+1) for upvote or decrements (-1) for downvote - Clamps weight to [0, 100] range - Updates chunk in ES/Infinity/OceanBase 4. Future retrievals score these chunks higher/lower based on accumulated feedback **Files changed:** - `api/db/services/chunk_feedback_service.py` - New service for updating chunk pagerank weights - `api/apps/conversation_app.py` - Integrated feedback service into thumbup endpoint - `test/testcases/test_web_api/test_chunk_feedback/` - Unit tests ### Type of change - [x] New Feature (non-breaking change which adds functionality) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Chat message feedback now updates per-chunk relevance weights (feature-flag gated), with configurable weighting and atomic updates across storage backends. * **Bug Fixes** * Stricter validation for message feedback inputs and more robust handling of feedback transitions. * **Tests** * Expanded test coverage for chunk-feedback behavior, weighting strategies, storage backends, and thumb-flip scenarios. * **Chores** * CI workflow extended to run the new chunk-feedback web API tests. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: mkdev11 <[email protected]> Co-authored-by: mkdev11 <[email protected]>
chat-internals port (route-independent; fork keeps /chats contract + parallel gather + cache + infiniflow#12689). Replaced fork's think-stream helper block (_ThinkStreamState / _next_think_delta / _stream_with_think_delta) with upstream v0.26's final version, which folds in: - infiniflow#15745 refine think stream parsing (big refactor; min_tokens 1->16) - infiniflow#15891 remove think text buffering (real-time reasoning) - infiniflow#15651 prevent duplicated post-think text - infiniflow#15582 think stream tail handling - infiniflow#14271 normalize think tags in final answer (adds _extract_visible_answer; removes _next_think_delta) Plus applied infiniflow#14271's 2 consumer wraps: async_chat + async_ask now call decorate_answer(_extract_visible_answer(...)). SKIPPED infiniflow#13917 (remove final["answer"]=""): conflicts with fork's deliberate answer-clearing — async_chat explicitly caches the full answer then blanks it for the streaming client ('preserve full answer for caching before clearing'). Touching it risks fork's cache/stream contract. Verified: call convention unchanged (3 consumers); _next_think_delta fully removed (0 refs); _extract_visible_answer logic correct (5 cases); fork customs intact (parallel gather x8, cache x5); py_compile. Live SSE smoke -> batch F.
Re-applied fork's a49da39 onto v0.26 dialog_service: cross_languages, keyword_extraction, meta_data_filter now run concurrently via asyncio.gather (independent ops on the refined question) instead of sequentially. meta_filter adapted to v0.26's pushdown apply_meta_data_filter signature (kb_ids + lazy metas_loader) — same reconciliation proven in the prior sync. keyword applied as v0.26 does (comma-join). Per-task exception isolation kept. infiniflow#12689 (chunk recall weights by feedback) NOT re-applied — already native in v0.26 (chunk_feedback_service present, chat_api has 18 feedback refs). Free. Langfuse-async-init micro-opt deferred (fiddly vs v0.26 langfuse structure). Verified: asyncio imported; py_compile.
What problem does this PR solve?
Implements automatic adjustment of knowledge base chunk recall weights based on user feedback (upvotes/downvotes). When users upvote or downvote a response, the system locates the corresponding knowledge snippets and adjusts their recall weight to improve future retrieval quality.
Closes #12670
How it works:
POST /thumbuppagerank_feavalue from document storeFiles changed:
api/db/services/chunk_feedback_service.py- New service for updating chunk pagerank weightsapi/apps/conversation_app.py- Integrated feedback service into thumbup endpointtest/testcases/test_web_api/test_chunk_feedback/- Unit testsType of change
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores